metal2vulkan-rt: command queues, command buffers and events on the submit and completion threads
Step (c) of the new runtime's compute core.
What:
- CommandQueue (newCommandQueueWithMaxCommandBufferCount:, its bound on uncompleted command
buffers), CommandBuffer (enqueue, commit, handlers, waits, status, error), Event and
SharedEvent (signaled_value, set_signaled_value, wait_until_signaled_value,
notify_listener).
- A command buffer records at once into segments split at event waits and signals. The submit
thread holds a segment whose waits are not met, and its queue behind it, while the segments
before it run (reims F1). A wait the host's value meets submits no semaphore wait; a GPU
signal not above the highest value submitted or set is left out, so the semaphore only rises.
- The completion thread retires by a progress semaphore, follows submitted event signals (a
listener runs at a mid-buffer signal, reims F2), runs handlers with no lock held, and is
woken through a host-signalled timeline semaphore only when a wait needs it.
- A command buffer keeps each block it uses until it retires. A zeroed Private buffer's fill is
an upload submitted ahead of every later commit, whose segments start with a barrier; each
segment ends with a barrier to the host.
- Device::quiesce(timeout) (F9), with every wait bounded, no join of a thread still running, no
thread-local that exit() tears down, idempotent, freeing nothing; unmap runs on the caller for
every block handed out, once (a handed set replaces the per-idle flag).
- The last handle dropped in a handler: the completion thread finishes the teardown itself (F8).
- CommandQueue::abandon (F14); a loss ends held work, in-flight work once the device is idle,
host waits on pending signals, and later commits, with DeviceLost { in_flight } (F13).
- Refusals Committed, OtherDevice, NoCommandBuffers with their basis; Error::Quiesced;
docs/REFUSALS.md and the API signature table regenerated; the README's contract.
Verified: cargo fmt; refusal_surface --check. The compile and device jobs follow.
This commit is contained in:
1 parent
4e8784ad14
commit
077c9722e3
20 files changed
+3545
-143
No files matched your search
@@ -3,8 +3,9 @@
|
||||
The Metal API on Vulkan, with one path for every device. It replaces `metal2vulkan-runtime` and
|
||||
takes its name when it does; until then it is unpublished.
|
||||
|
||||
Its public API so far: the instance and the device, memory blocks and the buffers in them, the
|
||||
device's counters, and `floor`, the check of a Vulkan device against the floor below.
|
||||
Its public API so far: the instance and the device, memory blocks and the buffers in them, command
|
||||
queues, command buffers and events, the device's counters, and `floor`, the check of a Vulkan
|
||||
device against the floor below.
|
||||
|
||||
## Instance and device
|
||||
|
||||
@@ -29,13 +30,19 @@ device's counters, and `floor`, the check of a Vulkan device against the floor b
|
||||
|
||||
### Teardown
|
||||
|
||||
A device is torn down when its last handle, and the last handle of every object made from it, is
|
||||
dropped. Blocks the consumer holds do not keep it alive. Teardown joins the block-maker thread
|
||||
and waits until the GPU is idle; then, on the dropping thread, it frees every block, calling
|
||||
`BlockMappings::unmap` first for each block the consumer was handed, and destroys the `VkDevice`.
|
||||
A physical device and a device each hold their instance. No thread of the runtime outlives its
|
||||
device and nothing relies on a static destructor or an `atexit` handler, so the consumer drops
|
||||
every handle before the process exits: a driver may unmap device memory inside `exit()`.
|
||||
The runtime runs three threads per device: the block-maker, the submit thread and the completion
|
||||
thread. A device is torn down when its last handle, and the last handle of every object made from
|
||||
it, is dropped; a committed command buffer and the blocks the consumer holds do not keep it alive.
|
||||
Teardown stops the submit thread, which submits what is ready and ends what it holds with
|
||||
`CommandBufferError::NotRun`; the completion thread retires the rest as the GPU completes it and
|
||||
runs the handlers; the threads are joined and the GPU goes idle. Then every block is freed,
|
||||
`BlockMappings::unmap` first for each block the consumer was handed, and the `VkDevice` is
|
||||
destroyed. Teardown runs on the thread that drops the last handle, or, where that is a handler or
|
||||
a listener, on the completion thread once the handler returns. A physical device and a device
|
||||
each hold their instance. No thread of the runtime outlives its device, and nothing relies on a
|
||||
static destructor or an `atexit` handler: the consumer drops every handle, or calls
|
||||
`Device::quiesce`, before the process exits, since a driver may unmap device memory inside
|
||||
`exit()`.
|
||||
|
||||
### Counters
|
||||
|
||||
@@ -68,22 +75,85 @@ in its memory.
|
||||
- `Device::new_buffer(block, offset, length, zeroed)` makes a `Buffer`: a view of the range, with
|
||||
no Vulkan object of its own. Its `gpu_address` is the block's address plus the offset, and its
|
||||
`contents` the block's mapping plus the offset, or `None` in a Private block. `zeroed` zeroes the
|
||||
range before the call returns, as `newBufferWithLength:options:` does: through the mapping for
|
||||
Shared, by a GPU fill submitted and waited for in Private, which writes exactly the range. A
|
||||
buffer placed in a heap passes false, since Metal does not zero heap memory. A length of 0 and a
|
||||
range past the block are refused, as Metal answers nil for both.
|
||||
range, as `newBufferWithLength:options:` does: through the mapping for Shared, before the call
|
||||
returns; in Private by a GPU fill of exactly the range, recorded into the upload, which goes
|
||||
ahead of every command buffer committed after the call (each command buffer's commands start
|
||||
with a barrier after every earlier submission) and holds the block until it completes. A buffer
|
||||
placed in a heap passes false, since Metal does not zero heap memory. A length of 0 and a range
|
||||
past the block are refused, as Metal answers nil for both.
|
||||
|
||||
The consumer's ranges follow Metal's retention: it reuses a range only once the work that named
|
||||
the buffer there before has completed.
|
||||
the buffer there before has completed. A command buffer keeps each block it uses until it retires,
|
||||
so a block released meanwhile goes back to the pool only then.
|
||||
|
||||
### The consumer's mappings
|
||||
|
||||
A consumer that maps blocks itself, into a guest for instance, passes `DeviceOptions::block_mappings`.
|
||||
Before the runtime frees a block it handed out, it calls `BlockMappings::unmap(block)`, which
|
||||
returns once every mapping the consumer made of it is gone and none of its threads touches the
|
||||
block. The memory stays mapped and valid until then. It runs on the block-maker thread, or at
|
||||
teardown on the dropping thread after the runtime's threads are joined, and it never calls into the
|
||||
runtime. Blocks the consumer never took are freed without it.
|
||||
block. The memory stays mapped and valid until then. It runs once per block: on the block-maker
|
||||
thread; in `Device::quiesce`, on the calling thread, for every block still handed out; or at
|
||||
teardown, on the thread that ends it, after the runtime's other threads are joined. It never calls
|
||||
into the runtime. Blocks the consumer never took are freed without it, and so is every block freed
|
||||
after a quiesce.
|
||||
|
||||
## Queues, command buffers and events
|
||||
|
||||
- `Device::new_command_queue(max)` is `newCommandQueueWithMaxCommandBufferCount:`
|
||||
(`newCommandQueue` is 64). Every queue submits to the device's one `VkQueue`.
|
||||
`CommandQueue::command_buffer` waits, as Metal does, while `max` of the queue's command buffers
|
||||
are made and not yet completed.
|
||||
- A `CommandBuffer` records at once, with no replay log. Event waits and signals split it into
|
||||
segments, one `VkCommandBuffer` each where it has commands; their commands start with a barrier
|
||||
after every earlier submission and end with a barrier that makes their writes visible to the
|
||||
host. `enqueue` takes the command buffer's place in its queue; `commit` hands it to the submit
|
||||
thread and returns. A committed command buffer holds no device handle.
|
||||
- The submit thread passes whatever is ready to one `vkQueueSubmit2`, in the device's commit
|
||||
order, ahead of it the upload of zero fills, and the last submit info signals the progress
|
||||
semaphore. It holds a segment whose event waits are not met, and its queue's later command
|
||||
buffers behind it, while the segments before it run, so the host can see a signal the command
|
||||
buffer makes before its wait. Other queues go on. `Scheduled` means the last segment has passed
|
||||
`vkQueueSubmit2`.
|
||||
- The completion thread retires command buffers as the progress semaphore reaches them: the
|
||||
status, the blocks they kept, their recorders and their place in the queue, then the handlers.
|
||||
Scheduled and completed handlers run on it, every device's in turn, so no handler waits for a
|
||||
command buffer.
|
||||
- `Event` and `SharedEvent` are timeline semaphores whose values are Metal's values. A host set
|
||||
(`SharedEvent::set_signaled_value`) raises a floor and never signals the semaphore; a wait the
|
||||
floor meets is submitted with no semaphore wait, and a GPU signal not above the highest value
|
||||
submitted or set is left out, so the semaphore only rises and never races a host set.
|
||||
`signaled_value` is the higher of the semaphore and the floor. `notify_listener` runs its
|
||||
listener on the completion thread when the value is reached, at a signal in the middle of a
|
||||
command buffer as well as at its end; `wait_until_signaled_value` wakes then too.
|
||||
- `CommandQueue::abandon` ends every command buffer of the queue that is held or not yet submitted
|
||||
with `NotRun` and runs its handlers, as a Mac drops a dead process's held work. Segments already
|
||||
submitted still complete; the queue stays usable.
|
||||
- At a loss of the device (or a failed submission, which the runtime takes as one), the submit
|
||||
thread ends what it holds, the completion thread ends what is in flight once the device is idle
|
||||
(at once on a lost device), host waits for pending signals end false, and every later commit
|
||||
ends at once. `CommandBufferError::DeviceLost { in_flight }` tells the command buffers that had
|
||||
passed `vkQueueSubmit2` from the rest. Teardown then completes, and a new device can be made on
|
||||
the same instance.
|
||||
|
||||
### Quiesce and exit
|
||||
|
||||
`Device::quiesce(timeout)` is for a process that exits with the device alive. With every wait
|
||||
bounded by the timeout, it stops the submit thread (ready work is submitted, held work ends
|
||||
`NotRun`) and the block-maker, waits for the GPU to complete what was submitted, lets the
|
||||
completion thread retire it and end, and then runs `BlockMappings::unmap` on the calling thread for
|
||||
every block still handed out. It frees nothing: every block's memory and mapping stays valid until
|
||||
the process ends. After it, no runtime thread touches a block; later calls that need a thread
|
||||
return `Error::Quiesced`. It answers true once the GPU went idle and every thread ended in time. A
|
||||
second call returns at once.
|
||||
|
||||
It is safe in an `atexit` handler on whichever thread calls `exit()`: it joins a thread only once
|
||||
that thread has ended, reads no thread-local that `exit()` tears down, and takes no lock a
|
||||
consumer's thread can hold. The consumer parks its own threads that touch blocks first.
|
||||
|
||||
### Known gaps
|
||||
|
||||
- `GPUStartTime` and `GPUEndTime` are not built yet.
|
||||
- Presenting (the binary semaphore a command buffer signals for a present) comes with presenting.
|
||||
|
||||
## One path for every device
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use crate::counters::Gauge;
|
||||
use crate::device::Device;
|
||||
use crate::error::{Error, Refusal};
|
||||
use crate::memory::{self, Block, BlockId, Mapping};
|
||||
use crate::memory::{Block, BlockId, Mapping};
|
||||
use std::ptr::NonNull;
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -36,13 +36,16 @@ impl Device {
|
||||
/// holds. The consumer chooses the range; it reuses a range only once the work that named the
|
||||
/// buffer there before has completed, as Metal frees a buffer's memory only then.
|
||||
///
|
||||
/// `zeroed` zeroes the range before the call returns, as `newBufferWithLength:options:` does
|
||||
/// in Metal: through the mapping in a Shared block, by a GPU fill submitted and waited for in a
|
||||
/// Private one. A buffer placed in a heap passes false: Metal does not zero heap memory.
|
||||
/// `zeroed` zeroes the range, as `newBufferWithLength:options:` does in Metal: in a Shared
|
||||
/// block through the mapping, before the call returns; in a Private block by a GPU fill in the
|
||||
/// upload, which is submitted ahead of every command buffer committed after this call and
|
||||
/// holds the block until it completes. A buffer placed in a heap passes false: Metal does not
|
||||
/// zero heap memory.
|
||||
///
|
||||
/// Err: [`Refusal::EmptyBuffer`] for a length of 0 and [`Refusal::BufferPastBlock`] for a
|
||||
/// range that leaves the block, where Metal answers nil; [`Error::NoSuchBlock`] for a block the
|
||||
/// consumer does not hold; [`Error::Vulkan`] where a Private fill fails.
|
||||
/// consumer does not hold; for a zeroed Private buffer, [`Error::Quiesced`], and
|
||||
/// [`Error::Vulkan`] where the upload's command buffer cannot be made.
|
||||
pub fn new_buffer(
|
||||
&self,
|
||||
block: BlockId,
|
||||
@@ -63,13 +66,19 @@ impl Device {
|
||||
length,
|
||||
block_len,
|
||||
}))?;
|
||||
if zeroed {
|
||||
memory::zero(self.core(), &block.memory, offset, end)?;
|
||||
}
|
||||
let contents = block.memory.mapping.map(|mapping| {
|
||||
// SAFETY: `offset` is inside the block.
|
||||
Mapping::new(unsafe { mapping.at(offset) })
|
||||
});
|
||||
if zeroed {
|
||||
match contents {
|
||||
// SAFETY: `offset..end` lies in the block, and the range is the new buffer's.
|
||||
Some(contents) => unsafe {
|
||||
contents.get().as_ptr().write_bytes(0, length as usize)
|
||||
},
|
||||
None => self.core().work.zero(self.core(), &block, offset, end)?,
|
||||
}
|
||||
}
|
||||
self.core().counters.rise(Gauge::Buffers);
|
||||
Ok(Buffer {
|
||||
inner: Arc::new(Inner {
|
||||
@@ -109,4 +118,10 @@ impl Buffer {
|
||||
pub fn offset(&self) -> u64 {
|
||||
self.inner.offset
|
||||
}
|
||||
|
||||
/// For the device tests: the block, for a command buffer to keep.
|
||||
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
|
||||
pub(crate) fn block_for_test(&self) -> &Arc<Block> {
|
||||
&self.inner.block
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,523 @@
|
||||
//! Command buffers: recorded at once into segments that event waits and signals split, and their
|
||||
//! states from creation to retirement.
|
||||
|
||||
use crate::device::{lock, Core, Device};
|
||||
use crate::error::{Error, Refusal};
|
||||
use crate::event::{Event, EventInner};
|
||||
use crate::memory::Block;
|
||||
use crate::queue::QueueInner;
|
||||
use crate::record::{self, Recorder};
|
||||
use ash::vk;
|
||||
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
|
||||
|
||||
/// `MTLCommandBuffer`.
|
||||
///
|
||||
/// Each call records at once; there is no replay log. Event waits and signals split it into
|
||||
/// segments, one `VkCommandBuffer` each where it records commands, submitted with the semaphore
|
||||
/// operations between them. The submit thread holds a segment whose waits are not yet met, and its
|
||||
/// queue's later command buffers behind it, while the segments before it run: an event the held
|
||||
/// part waits for can be signalled by the part before it. Each segment's commands start with a
|
||||
/// barrier after every earlier submission, and end with a barrier that makes their writes visible
|
||||
/// to the host.
|
||||
///
|
||||
/// A cheap handle: clones share one command buffer. It holds the device until it is committed and
|
||||
/// nothing of it after, so a command buffer held forever on an event does not keep the device
|
||||
/// alive: teardown ends it with [`CommandBufferError::NotRun`].
|
||||
#[derive(Clone)]
|
||||
pub struct CommandBuffer {
|
||||
inner: Arc<CbInner>,
|
||||
}
|
||||
|
||||
/// `MTLCommandBufferStatus`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum CommandBufferStatus {
|
||||
/// `MTLCommandBufferStatusNotEnqueued`.
|
||||
NotEnqueued,
|
||||
/// `MTLCommandBufferStatusEnqueued`.
|
||||
Enqueued,
|
||||
/// `MTLCommandBufferStatusCommitted`: also while the submit thread holds a later segment.
|
||||
Committed,
|
||||
/// `MTLCommandBufferStatusScheduled`: the last segment has passed `vkQueueSubmit2`.
|
||||
Scheduled,
|
||||
/// `MTLCommandBufferStatusCompleted`.
|
||||
Completed,
|
||||
/// `MTLCommandBufferStatusError`, with [`CommandBuffer::error`].
|
||||
Error,
|
||||
}
|
||||
|
||||
/// `MTLCommandBufferError`, the part this runtime reports.
|
||||
#[non_exhaustive]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum CommandBufferError {
|
||||
/// The `VkDevice` was lost, or a submission failed, which the runtime takes as a loss. With
|
||||
/// one device, a fault anywhere ends every queue's work. `in_flight`: some of the command
|
||||
/// buffer had passed `vkQueueSubmit2` (Metal's hang or victim); false for one held or not yet
|
||||
/// submitted, and for every commit after the loss.
|
||||
DeviceLost {
|
||||
/// Whether part of the command buffer had been submitted.
|
||||
in_flight: bool,
|
||||
},
|
||||
/// Ended without its held part running: by [`CommandQueue::abandon`](crate::CommandQueue::abandon),
|
||||
/// by [`Device::quiesce`], or at teardown. Segments before the held one may have run.
|
||||
NotRun,
|
||||
}
|
||||
|
||||
/// A scheduled or completed handler.
|
||||
pub(crate) type Handler = Box<dyn FnOnce(&CommandBuffer) + Send>;
|
||||
|
||||
/// The command buffer itself: what its handles, its queue's FIFO and the completion thread hold.
|
||||
pub(crate) struct CbInner {
|
||||
pub(crate) queue: Arc<QueueInner>,
|
||||
state: Mutex<CbState>,
|
||||
/// Signalled at each status change and once the handlers have run.
|
||||
changed: Condvar,
|
||||
}
|
||||
|
||||
struct CbState {
|
||||
status: CommandBufferStatus,
|
||||
error: Option<CommandBufferError>,
|
||||
/// The handlers have run: waits for completion return.
|
||||
finished: bool,
|
||||
/// Until commit: what is recorded, and the device.
|
||||
building: Option<Building>,
|
||||
/// Ended while enqueued and not yet committed (an abandon, a loss or a quiesce): the commit
|
||||
/// ends it with this error at once.
|
||||
ended: Option<CommandBufferError>,
|
||||
}
|
||||
|
||||
struct Building {
|
||||
device: Device,
|
||||
gpu: Gpu,
|
||||
handlers: Handlers,
|
||||
}
|
||||
|
||||
/// What the GPU uses: the recorder, the segments, and the blocks kept until retirement.
|
||||
pub(crate) struct Gpu {
|
||||
pub(crate) recorder: Option<Recorder>,
|
||||
pub(crate) segments: Vec<Segment>,
|
||||
/// Each block the commands use, once: a block released meanwhile is reused only after the
|
||||
/// command buffer retires.
|
||||
pub(crate) blocks: Vec<Arc<Block>>,
|
||||
}
|
||||
|
||||
/// One submission's part of a command buffer: its waits, its commands and its signals.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Segment {
|
||||
pub(crate) waits: Vec<(Arc<EventInner>, u64)>,
|
||||
pub(crate) command: Option<vk::CommandBuffer>,
|
||||
/// At most one per event, the highest value.
|
||||
pub(crate) signals: Vec<(Arc<EventInner>, u64)>,
|
||||
}
|
||||
|
||||
pub(crate) struct Handlers {
|
||||
pub(crate) scheduled: Vec<Handler>,
|
||||
pub(crate) completed: Vec<Handler>,
|
||||
}
|
||||
|
||||
/// A committed command buffer on its way through the submit thread.
|
||||
pub(crate) struct Pending {
|
||||
/// Its place in the device's commit order.
|
||||
pub(crate) seq: u64,
|
||||
/// The first segment not yet submitted.
|
||||
pub(crate) next: usize,
|
||||
/// The progress value of the last submission with a segment of it; 0 before the first.
|
||||
pub(crate) value: u64,
|
||||
pub(crate) gpu: Gpu,
|
||||
pub(crate) handlers: Handlers,
|
||||
}
|
||||
|
||||
impl CommandBuffer {
|
||||
/// A new command buffer of `queue`, which has counted it.
|
||||
pub(crate) fn new(queue: Arc<QueueInner>, device: Device) -> CommandBuffer {
|
||||
CommandBuffer {
|
||||
inner: Arc::new(CbInner {
|
||||
queue,
|
||||
state: Mutex::new(CbState {
|
||||
status: CommandBufferStatus::NotEnqueued,
|
||||
error: None,
|
||||
finished: false,
|
||||
building: Some(Building {
|
||||
device,
|
||||
gpu: Gpu {
|
||||
recorder: None,
|
||||
segments: vec![Segment::default()],
|
||||
blocks: Vec::new(),
|
||||
},
|
||||
handlers: Handlers {
|
||||
scheduled: Vec::new(),
|
||||
completed: Vec::new(),
|
||||
},
|
||||
}),
|
||||
ended: None,
|
||||
}),
|
||||
changed: Condvar::new(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn state(&self) -> MutexGuard<'_, CbState> {
|
||||
lock(&self.inner.state)
|
||||
}
|
||||
|
||||
/// Runs `f` on what is being recorded. Err: [`Refusal::Committed`].
|
||||
fn building<R>(&self, f: impl FnOnce(&mut Building) -> Result<R, Error>) -> Result<R, Error> {
|
||||
let mut state = self.state();
|
||||
let building = state
|
||||
.building
|
||||
.as_mut()
|
||||
.ok_or(Error::Refused(Refusal::Committed))?;
|
||||
f(building)
|
||||
}
|
||||
|
||||
/// The device, while the command buffer is not committed. Err: [`Refusal::Committed`].
|
||||
fn device(&self) -> Result<Device, Error> {
|
||||
self.building(|building| Ok(building.device.clone()))
|
||||
}
|
||||
|
||||
/// `encodeSignalEvent:value:`: the event takes `value` once the commands before it complete,
|
||||
/// unless a value at least as high is already submitted or set.
|
||||
///
|
||||
/// Err: [`Refusal::Committed`]; [`Refusal::OtherDevice`] for another device's event.
|
||||
pub fn encode_signal_event(&self, event: &Event, value: u64) -> Result<(), Error> {
|
||||
self.building(|building| {
|
||||
building.check(event)?;
|
||||
building.signal(event.inner(), value);
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// `encodeWaitForEvent:value:`: the commands after it run once the event reaches `value`.
|
||||
///
|
||||
/// The submit thread holds this segment, and its queue behind it, until the host's value
|
||||
/// reaches `value` (then no semaphore wait is submitted) or a signal of at least `value` is
|
||||
/// submitted (then the segment waits on the semaphore). Other queues go on.
|
||||
///
|
||||
/// Err: [`Refusal::Committed`]; [`Refusal::OtherDevice`] for another device's event;
|
||||
/// [`Error::Vulkan`] where ending the segment's commands fails.
|
||||
pub fn encode_wait_for_event(&self, event: &Event, value: u64) -> Result<(), Error> {
|
||||
self.building(|building| {
|
||||
building.check(event)?;
|
||||
building.wait(event.inner(), value)
|
||||
})
|
||||
}
|
||||
|
||||
/// `addScheduledHandler:`: runs on the completion thread once the last segment has passed
|
||||
/// `vkQueueSubmit2`, or at once there for a command buffer that ends without running.
|
||||
///
|
||||
/// Err: [`Refusal::Committed`].
|
||||
pub fn add_scheduled_handler(
|
||||
&self,
|
||||
handler: impl FnOnce(&CommandBuffer) + Send + 'static,
|
||||
) -> Result<(), Error> {
|
||||
self.building(|building| {
|
||||
building.handlers.scheduled.push(Box::new(handler));
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// `addCompletedHandler:`: runs on the completion thread once the command buffer has
|
||||
/// completed or ended, after its scheduled handlers. One thread runs every device's handlers
|
||||
/// in turn, so a handler waits for no command buffer.
|
||||
///
|
||||
/// Err: [`Refusal::Committed`].
|
||||
pub fn add_completed_handler(
|
||||
&self,
|
||||
handler: impl FnOnce(&CommandBuffer) + Send + 'static,
|
||||
) -> Result<(), Error> {
|
||||
self.building(|building| {
|
||||
building.handlers.completed.push(Box::new(handler));
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// `enqueue`: takes the command buffer's place in its queue now; the queue's later command
|
||||
/// buffers wait behind it until it is committed. A second call changes nothing.
|
||||
///
|
||||
/// Err: [`Refusal::Committed`]; [`Error::Quiesced`].
|
||||
pub fn enqueue(&self) -> Result<(), Error> {
|
||||
let device = self.device()?;
|
||||
let core = device.core();
|
||||
let mut work = core.work.lock();
|
||||
if work.closed() {
|
||||
return Err(Error::Quiesced);
|
||||
}
|
||||
let mut state = self.state();
|
||||
if state.building.is_none() {
|
||||
return Err(Error::Refused(Refusal::Committed));
|
||||
}
|
||||
if state.status == CommandBufferStatus::NotEnqueued {
|
||||
work.enqueue(&self.inner);
|
||||
state.status = CommandBufferStatus::Enqueued;
|
||||
self.inner.changed.notify_all();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `commit`: hands the command buffer to the submit thread and returns. Where nothing is held,
|
||||
/// submission follows the device's commit order, and whatever is ready goes in one
|
||||
/// `vkQueueSubmit2`. A commit after a loss ends at once with
|
||||
/// [`CommandBufferError::DeviceLost`].
|
||||
///
|
||||
/// Err: [`Refusal::Committed`]; [`Error::Quiesced`]; [`Error::Vulkan`] where ending the last
|
||||
/// segment's commands fails.
|
||||
pub fn commit(&self) -> Result<(), Error> {
|
||||
// The handle keeps the device alive through the call; it is dropped once no lock is held.
|
||||
let device = self.device()?;
|
||||
let core = device.core();
|
||||
let mut work = core.work.lock();
|
||||
if work.closed() {
|
||||
return Err(Error::Quiesced);
|
||||
}
|
||||
let mut state = self.state();
|
||||
let Some(mut building) = state.building.take() else {
|
||||
return Err(Error::Refused(Refusal::Committed));
|
||||
};
|
||||
if let Err(error) = building.close() {
|
||||
state.building = Some(building);
|
||||
return Err(error);
|
||||
}
|
||||
let Building { gpu, handlers, .. } = building;
|
||||
let pending = Pending {
|
||||
seq: work.seq(),
|
||||
next: 0,
|
||||
value: 0,
|
||||
gpu,
|
||||
handlers,
|
||||
};
|
||||
state.status = CommandBufferStatus::Committed;
|
||||
self.inner.changed.notify_all();
|
||||
let ended = state.ended.or(work
|
||||
.lost()
|
||||
.then_some(CommandBufferError::DeviceLost { in_flight: false }));
|
||||
drop(state);
|
||||
match ended {
|
||||
Some(error) => {
|
||||
drop(work);
|
||||
core.done
|
||||
.end_all(core, vec![(Arc::clone(&self.inner), pending, error)]);
|
||||
}
|
||||
None => {
|
||||
work.commit(&self.inner, pending);
|
||||
drop(work);
|
||||
core.work.wake();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `waitUntilScheduled`: returns once the command buffer is scheduled, or has completed or
|
||||
/// ended.
|
||||
pub fn wait_until_scheduled(&self) {
|
||||
let mut state = self.state();
|
||||
while !matches!(
|
||||
state.status,
|
||||
CommandBufferStatus::Scheduled
|
||||
| CommandBufferStatus::Completed
|
||||
| CommandBufferStatus::Error
|
||||
) {
|
||||
state = self.wait(state);
|
||||
}
|
||||
}
|
||||
|
||||
/// `waitUntilCompleted`: returns once the command buffer has completed or ended and its
|
||||
/// handlers have run.
|
||||
pub fn wait_until_completed(&self) {
|
||||
let mut state = self.state();
|
||||
while !state.finished {
|
||||
state = self.wait(state);
|
||||
}
|
||||
}
|
||||
|
||||
fn wait<'a>(&self, state: MutexGuard<'a, CbState>) -> MutexGuard<'a, CbState> {
|
||||
self.inner
|
||||
.changed
|
||||
.wait(state)
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// `status`.
|
||||
pub fn status(&self) -> CommandBufferStatus {
|
||||
self.state().status
|
||||
}
|
||||
|
||||
/// `error`: set when [`status`](Self::status) is [`CommandBufferStatus::Error`].
|
||||
pub fn error(&self) -> Option<CommandBufferError> {
|
||||
self.state().error
|
||||
}
|
||||
|
||||
/// For the device tests: records commands into the current segment with `f`, and keeps each
|
||||
/// buffer's block until the command buffer retires.
|
||||
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
|
||||
pub(crate) fn record_for_test(
|
||||
&self,
|
||||
buffers: &[&crate::Buffer],
|
||||
f: impl FnOnce(&ash::Device, vk::CommandBuffer),
|
||||
) -> Result<(), Error> {
|
||||
self.building(|building| {
|
||||
let command = building.command()?;
|
||||
f(&building.device.core().device, command);
|
||||
for buffer in buffers {
|
||||
building.keep(buffer.block_for_test());
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Building {
|
||||
/// Err: [`Refusal::OtherDevice`] for another device's event.
|
||||
fn check(&self, event: &Event) -> Result<(), Error> {
|
||||
if event.inner().is_of(self.device.core()) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::Refused(Refusal::OtherDevice))
|
||||
}
|
||||
}
|
||||
|
||||
fn last(&mut self) -> &mut Segment {
|
||||
let segments = &mut self.gpu.segments;
|
||||
let last = segments.len() - 1;
|
||||
&mut segments[last]
|
||||
}
|
||||
|
||||
/// Ends the last segment's commands, if it has any.
|
||||
fn close(&mut self) -> Result<(), Error> {
|
||||
let core = Arc::clone(self.device.core());
|
||||
match self.last().command {
|
||||
Some(command) => record::end(&core.device, command, &core.counters),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts a new segment after the last one.
|
||||
fn split(&mut self) -> Result<(), Error> {
|
||||
self.close()?;
|
||||
self.gpu.segments.push(Segment::default());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn wait(&mut self, event: &Arc<EventInner>, value: u64) -> Result<(), Error> {
|
||||
let last = self.last();
|
||||
if last.command.is_some() || !last.signals.is_empty() {
|
||||
self.split()?;
|
||||
}
|
||||
self.last().waits.push((Arc::clone(event), value));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn signal(&mut self, event: &Arc<EventInner>, value: u64) {
|
||||
let signals = &mut self.last().signals;
|
||||
match signals
|
||||
.iter_mut()
|
||||
.find(|(signalled, _)| Arc::ptr_eq(signalled, event))
|
||||
{
|
||||
Some((_, highest)) => *highest = (*highest).max(value),
|
||||
None => signals.push((Arc::clone(event), value)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The current segment's command buffer, begun with its barrier. Commands after a signal go
|
||||
/// in a new segment.
|
||||
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
|
||||
fn command(&mut self) -> Result<vk::CommandBuffer, Error> {
|
||||
if !self.last().signals.is_empty() {
|
||||
self.split()?;
|
||||
}
|
||||
if let Some(command) = self.last().command {
|
||||
return Ok(command);
|
||||
}
|
||||
let core = Arc::clone(self.device.core());
|
||||
let recorder = match self.gpu.recorder.take() {
|
||||
Some(recorder) => recorder,
|
||||
None => core.recorders.take(&core.device)?,
|
||||
};
|
||||
let recorder = self.gpu.recorder.insert(recorder);
|
||||
let command = recorder.next(&core.device)?;
|
||||
record::begin_barrier(&core.device, command, &core.counters);
|
||||
self.last().command = Some(command);
|
||||
Ok(command)
|
||||
}
|
||||
|
||||
/// Keeps `block` until the command buffer retires.
|
||||
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
|
||||
fn keep(&mut self, block: &Arc<Block>) {
|
||||
if !self.gpu.blocks.iter().any(|kept| Arc::ptr_eq(kept, block)) {
|
||||
self.gpu.blocks.push(Arc::clone(block));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CbInner {
|
||||
/// The submit thread passed the last segment to `vkQueueSubmit2`.
|
||||
pub(crate) fn scheduled(&self) {
|
||||
let mut state = lock(&self.state);
|
||||
state.status = CommandBufferStatus::Scheduled;
|
||||
self.changed.notify_all();
|
||||
}
|
||||
|
||||
/// Ended while enqueued and not committed: the commit ends it with `error`.
|
||||
pub(crate) fn end_uncommitted(&self, error: CommandBufferError) {
|
||||
lock(&self.state).ended = Some(error);
|
||||
}
|
||||
}
|
||||
|
||||
/// On the completion thread: runs the scheduled handlers of a command buffer just submitted.
|
||||
pub(crate) fn run_scheduled(inner: Arc<CbInner>, handlers: Vec<Handler>) {
|
||||
let handle = CommandBuffer { inner };
|
||||
for handler in handlers {
|
||||
handler(&handle);
|
||||
}
|
||||
}
|
||||
|
||||
/// On the completion thread: retires a command buffer that completed (`error` None) or ended,
|
||||
/// recycling its recorder and giving up its blocks and its place in the queue, then runs its
|
||||
/// handlers.
|
||||
pub(crate) fn retire(
|
||||
core: &Core,
|
||||
inner: Arc<CbInner>,
|
||||
gpu: Gpu,
|
||||
handlers: Handlers,
|
||||
error: Option<CommandBufferError>,
|
||||
) {
|
||||
{
|
||||
let mut state = lock(&inner.state);
|
||||
state.status = match error {
|
||||
Some(_) => CommandBufferStatus::Error,
|
||||
None => CommandBufferStatus::Completed,
|
||||
};
|
||||
state.error = error;
|
||||
inner.changed.notify_all();
|
||||
}
|
||||
let Gpu {
|
||||
recorder,
|
||||
segments,
|
||||
blocks,
|
||||
} = gpu;
|
||||
if let Some(recorder) = recorder {
|
||||
core.recorders.give_back(&core.device, recorder);
|
||||
}
|
||||
drop((segments, blocks));
|
||||
inner.queue.release();
|
||||
let handle = CommandBuffer { inner };
|
||||
for handler in handlers.scheduled.into_iter().chain(handlers.completed) {
|
||||
handler(&handle);
|
||||
}
|
||||
let mut state = lock(&handle.inner.state);
|
||||
state.finished = true;
|
||||
handle.inner.changed.notify_all();
|
||||
}
|
||||
|
||||
impl Drop for CbInner {
|
||||
fn drop(&mut self) {
|
||||
let state = self.state.get_mut().unwrap_or_else(PoisonError::into_inner);
|
||||
// A command buffer never committed gives back its recorder and its place in the queue; a
|
||||
// committed one did so when it retired.
|
||||
if let Some(Building { device, gpu, .. }) = state.building.take() {
|
||||
if let Some(recorder) = gpu.recorder {
|
||||
let core = device.core();
|
||||
core.recorders.give_back(&core.device, recorder);
|
||||
}
|
||||
self.queue.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,450 @@
|
||||
//! The completion thread: it retires command buffers and uploads as the GPU completes them, runs
|
||||
//! the handlers, follows the event signals it submitted and runs listeners, and ends the work in
|
||||
//! flight at a loss.
|
||||
|
||||
use crate::command::{self, CbInner, CommandBufferError, Gpu, Handler, Handlers, Pending};
|
||||
use crate::device::{lock, Core};
|
||||
use crate::error::Error;
|
||||
use crate::event::{self, EventInner, Listener};
|
||||
use crate::submit::{Ended, Upload};
|
||||
use ash::vk;
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// The completion side: what the completion thread has to do, and its two timeline semaphores.
|
||||
pub(crate) struct Done {
|
||||
state: Mutex<DoneState>,
|
||||
/// Wakes the completion thread while it waits on the host.
|
||||
changed: Condvar,
|
||||
/// Each batch signals its value when it completes.
|
||||
pub(crate) progress: vk::Semaphore,
|
||||
/// The host signals it to wake the completion thread from a GPU wait.
|
||||
wake: vk::Semaphore,
|
||||
}
|
||||
|
||||
struct DoneState {
|
||||
/// Command buffers just submitted, with their scheduled handlers.
|
||||
scheduled: Vec<(Arc<CbInner>, Vec<Handler>)>,
|
||||
/// Work submitted, by progress value: each retires once the progress semaphore reaches it.
|
||||
flight: VecDeque<Retiree>,
|
||||
/// Command buffers that ended without anything in flight: they retire at once.
|
||||
ended: Vec<Retiree>,
|
||||
/// Events with submitted signals the completion thread has not yet seen.
|
||||
watched: Vec<Arc<EventInner>>,
|
||||
/// Events whose listeners a host value may reach.
|
||||
fire: Vec<Arc<EventInner>>,
|
||||
waiting: Waiting,
|
||||
/// The wake semaphore's last value.
|
||||
woken: u64,
|
||||
stop: bool,
|
||||
/// With `stop`: when the thread ends whatever is still in flight.
|
||||
deadline: Option<Instant>,
|
||||
lost: bool,
|
||||
/// The thread ended with nothing in flight.
|
||||
drained: bool,
|
||||
}
|
||||
|
||||
/// Where the completion thread waits.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Waiting {
|
||||
/// It does not: it reads the state before it next waits.
|
||||
Not,
|
||||
/// On the host, for a change of the state.
|
||||
Host,
|
||||
/// On the GPU; `progress` where it waits for the progress semaphore too, so that more work in
|
||||
/// flight needs no wake.
|
||||
Gpu { progress: bool },
|
||||
}
|
||||
|
||||
struct Retiree {
|
||||
value: u64,
|
||||
item: Item,
|
||||
}
|
||||
|
||||
enum Item {
|
||||
Command {
|
||||
cb: Arc<CbInner>,
|
||||
gpu: Gpu,
|
||||
handlers: Handlers,
|
||||
error: Option<CommandBufferError>,
|
||||
},
|
||||
Upload(Upload),
|
||||
}
|
||||
|
||||
impl Done {
|
||||
/// Makes the two semaphores.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// `device` is live.
|
||||
pub(crate) unsafe fn new(device: &ash::Device) -> Result<Done, Error> {
|
||||
let progress = event::timeline(device)?;
|
||||
let wake = event::timeline(device).inspect_err(|_| {
|
||||
// SAFETY: the semaphore is unused.
|
||||
unsafe { device.destroy_semaphore(progress, None) };
|
||||
})?;
|
||||
Ok(Done {
|
||||
state: Mutex::new(DoneState {
|
||||
scheduled: Vec::new(),
|
||||
flight: VecDeque::new(),
|
||||
ended: Vec::new(),
|
||||
watched: Vec::new(),
|
||||
fire: Vec::new(),
|
||||
waiting: Waiting::Not,
|
||||
woken: 0,
|
||||
stop: false,
|
||||
deadline: None,
|
||||
lost: false,
|
||||
drained: false,
|
||||
}),
|
||||
changed: Condvar::new(),
|
||||
progress,
|
||||
wake,
|
||||
})
|
||||
}
|
||||
|
||||
/// Destroys the semaphores.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// No pending work names them.
|
||||
pub(crate) unsafe fn destroy(&mut self, device: &ash::Device) {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe {
|
||||
device.destroy_semaphore(self.progress, None);
|
||||
device.destroy_semaphore(self.wake, None);
|
||||
}
|
||||
}
|
||||
|
||||
fn lock(&self) -> MutexGuard<'_, DoneState> {
|
||||
lock(&self.state)
|
||||
}
|
||||
|
||||
/// Wakes the completion thread where it waits. With `flight_only` (the change is only more
|
||||
/// work in flight), a thread that already waits for the progress semaphore is left to wait.
|
||||
fn wake(&self, state: &mut DoneState, device: &ash::Device, flight_only: bool) {
|
||||
match state.waiting {
|
||||
Waiting::Not => return,
|
||||
Waiting::Gpu { progress: true } if flight_only => return,
|
||||
Waiting::Host => self.changed.notify_one(),
|
||||
Waiting::Gpu { .. } => {
|
||||
state.woken += 1;
|
||||
let signal = vk::SemaphoreSignalInfo::default()
|
||||
.semaphore(self.wake)
|
||||
.value(state.woken);
|
||||
// SAFETY: only the host signals the semaphore, under this lock, each time higher.
|
||||
// A failure is a loss, which the thread's wait then reports.
|
||||
let _ = unsafe { device.signal_semaphore(&signal) };
|
||||
}
|
||||
}
|
||||
state.waiting = Waiting::Not;
|
||||
}
|
||||
|
||||
/// From the submit thread: a batch passed to `vkQueueSubmit2` with progress `value`.
|
||||
pub(crate) fn submitted(
|
||||
&self,
|
||||
core: &Core,
|
||||
value: u64,
|
||||
upload: Option<Upload>,
|
||||
finished: Vec<(Arc<CbInner>, Pending)>,
|
||||
watch: Vec<Arc<EventInner>>,
|
||||
) {
|
||||
let mut state = self.lock();
|
||||
let mut flight_only = watch.is_empty();
|
||||
if let Some(upload) = upload {
|
||||
state.flight.push_back(Retiree {
|
||||
value,
|
||||
item: Item::Upload(upload),
|
||||
});
|
||||
}
|
||||
for (cb, pending) in finished {
|
||||
let Pending {
|
||||
gpu,
|
||||
handlers:
|
||||
Handlers {
|
||||
scheduled,
|
||||
completed,
|
||||
},
|
||||
..
|
||||
} = pending;
|
||||
if !scheduled.is_empty() {
|
||||
flight_only = false;
|
||||
state.scheduled.push((Arc::clone(&cb), scheduled));
|
||||
}
|
||||
state.flight.push_back(Retiree {
|
||||
value,
|
||||
item: Item::Command {
|
||||
cb,
|
||||
gpu,
|
||||
handlers: Handlers {
|
||||
scheduled: Vec::new(),
|
||||
completed,
|
||||
},
|
||||
error: None,
|
||||
},
|
||||
});
|
||||
}
|
||||
state.watched.extend(watch);
|
||||
self.wake(&mut state, &core.device, flight_only);
|
||||
}
|
||||
|
||||
/// Command buffers that ended: each retires with its error once what it had in flight
|
||||
/// completes, at once where it had nothing in flight.
|
||||
pub(crate) fn end_all(&self, core: &Core, ended: Vec<Ended>) {
|
||||
if ended.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut state = self.lock();
|
||||
for (cb, pending, error) in ended {
|
||||
let Pending {
|
||||
value,
|
||||
gpu,
|
||||
handlers,
|
||||
..
|
||||
} = pending;
|
||||
let retiree = Retiree {
|
||||
value,
|
||||
item: Item::Command {
|
||||
cb,
|
||||
gpu,
|
||||
handlers,
|
||||
error: Some(error),
|
||||
},
|
||||
};
|
||||
if value == 0 {
|
||||
state.ended.push(retiree);
|
||||
} else {
|
||||
let at = state.flight.partition_point(|other| other.value <= value);
|
||||
state.flight.insert(at, retiree);
|
||||
}
|
||||
}
|
||||
self.wake(&mut state, &core.device, false);
|
||||
}
|
||||
|
||||
/// A host value of `event` may reach some of its listeners.
|
||||
pub(crate) fn fire(&self, core: &Core, event: Arc<EventInner>) {
|
||||
let mut state = self.lock();
|
||||
state.fire.push(event);
|
||||
self.wake(&mut state, &core.device, false);
|
||||
}
|
||||
|
||||
/// Tells the completion thread to end once nothing is in flight, or at `deadline`.
|
||||
pub(crate) fn stop(&self, core: &Core, deadline: Option<Instant>) {
|
||||
let mut state = self.lock();
|
||||
state.stop = true;
|
||||
state.deadline = deadline;
|
||||
self.wake(&mut state, &core.device, false);
|
||||
}
|
||||
|
||||
/// Whether the completion thread ended with nothing in flight.
|
||||
pub(crate) fn drained(&self) -> bool {
|
||||
self.lock().drained
|
||||
}
|
||||
}
|
||||
|
||||
/// The device is lost, or a submission failed: the submit thread ends what it holds and every
|
||||
/// later commit, and the completion thread ends what is in flight once the device is idle,
|
||||
/// without waiting on the GPU again.
|
||||
pub(crate) fn lose(core: &Core) {
|
||||
core.work.lose();
|
||||
let mut state = core.done.lock();
|
||||
state.lost = true;
|
||||
core.done.wake(&mut state, &core.device, false);
|
||||
}
|
||||
|
||||
impl Retiree {
|
||||
fn retire(self, core: &Core) {
|
||||
match self.item {
|
||||
Item::Command {
|
||||
cb,
|
||||
gpu,
|
||||
handlers,
|
||||
error,
|
||||
} => command::retire(core, cb, gpu, handlers, error),
|
||||
Item::Upload(upload) => upload.retire(core),
|
||||
}
|
||||
}
|
||||
|
||||
/// In flight at a loss.
|
||||
fn lost(mut self) -> Retiree {
|
||||
if let Item::Command { error, .. } = &mut self.item {
|
||||
error.get_or_insert(CommandBufferError::DeviceLost { in_flight: true });
|
||||
}
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// The completion thread, until it is stopped.
|
||||
pub(crate) fn run(core: Arc<Core>) {
|
||||
let done = &core.done;
|
||||
let device = &core.device;
|
||||
let mut state = done.lock();
|
||||
loop {
|
||||
let scheduled: Vec<_> = state.scheduled.drain(..).collect();
|
||||
let mut retire: Vec<Retiree> = state.ended.drain(..).collect();
|
||||
let fired: Vec<Arc<EventInner>> = state.fire.drain(..).collect();
|
||||
let mut fire: Vec<(Listener, u64)> = Vec::new();
|
||||
let mut newly_lost = false;
|
||||
if state.lost {
|
||||
// The signals pending never come: the host waits for them end first.
|
||||
for event in state.watched.drain(..) {
|
||||
event.lose();
|
||||
}
|
||||
if !state.flight.is_empty() {
|
||||
// Nothing is pending once the device is idle, which a lost device reaches at once.
|
||||
state.waiting = Waiting::Not;
|
||||
drop(state);
|
||||
core.wait_idle();
|
||||
state = done.lock();
|
||||
retire.extend(state.flight.drain(..).map(Retiree::lost));
|
||||
}
|
||||
} else {
|
||||
if !state.flight.is_empty() {
|
||||
// SAFETY: the progress semaphore is the device's.
|
||||
match unsafe { device.get_semaphore_counter_value(done.progress) } {
|
||||
Ok(reached) => {
|
||||
while state
|
||||
.flight
|
||||
.front()
|
||||
.is_some_and(|retiree| retiree.value <= reached)
|
||||
{
|
||||
retire.extend(state.flight.pop_front());
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
state.lost = true;
|
||||
newly_lost = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut index = 0;
|
||||
while index < state.watched.len() {
|
||||
let event = &state.watched[index];
|
||||
if event.observe(event.counter().ok(), &mut fire) {
|
||||
index += 1;
|
||||
} else {
|
||||
state.watched.swap_remove(index);
|
||||
}
|
||||
}
|
||||
}
|
||||
for event in &fired {
|
||||
event.observe(None, &mut fire);
|
||||
}
|
||||
if newly_lost || !scheduled.is_empty() || !retire.is_empty() || !fire.is_empty() {
|
||||
state.waiting = Waiting::Not;
|
||||
drop(state);
|
||||
if newly_lost {
|
||||
core.work.lose();
|
||||
}
|
||||
// Handlers and listeners run with no lock held.
|
||||
for (cb, handlers) in scheduled {
|
||||
command::run_scheduled(cb, handlers);
|
||||
}
|
||||
for retiree in retire {
|
||||
retiree.retire(&core);
|
||||
}
|
||||
for (listener, value) in fire {
|
||||
listener(value);
|
||||
}
|
||||
drop(fired);
|
||||
state = done.lock();
|
||||
continue;
|
||||
}
|
||||
drop(fired);
|
||||
if state.stop {
|
||||
if state.flight.is_empty() {
|
||||
state.drained = true;
|
||||
break;
|
||||
}
|
||||
if state
|
||||
.deadline
|
||||
.is_some_and(|deadline| Instant::now() >= deadline)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
let timeout = state
|
||||
.deadline
|
||||
.filter(|_| state.stop)
|
||||
.map(|deadline| deadline.saturating_duration_since(Instant::now()));
|
||||
if state.lost || (state.flight.is_empty() && state.watched.is_empty()) {
|
||||
state.waiting = Waiting::Host;
|
||||
state = match timeout {
|
||||
None => done
|
||||
.changed
|
||||
.wait(state)
|
||||
.unwrap_or_else(PoisonError::into_inner),
|
||||
Some(timeout) => {
|
||||
done.changed
|
||||
.wait_timeout(state, timeout)
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.0
|
||||
}
|
||||
};
|
||||
state.waiting = Waiting::Not;
|
||||
continue;
|
||||
}
|
||||
let mut semaphores = Vec::new();
|
||||
let mut values = Vec::new();
|
||||
let target = state.flight.front().map(|retiree| retiree.value);
|
||||
if let Some(value) = target {
|
||||
semaphores.push(done.progress);
|
||||
values.push(value);
|
||||
}
|
||||
for event in &state.watched {
|
||||
if let Some(value) = event.next_pending() {
|
||||
semaphores.push(event.semaphore);
|
||||
values.push(value);
|
||||
}
|
||||
}
|
||||
semaphores.push(done.wake);
|
||||
values.push(state.woken + 1);
|
||||
state.waiting = Waiting::Gpu {
|
||||
progress: target.is_some(),
|
||||
};
|
||||
drop(state);
|
||||
let wait = vk::SemaphoreWaitInfo::default()
|
||||
.flags(vk::SemaphoreWaitFlags::ANY)
|
||||
.semaphores(&semaphores)
|
||||
.values(&values);
|
||||
let nanos = timeout.map_or(u64::MAX, nanos);
|
||||
// SAFETY: every semaphore is a timeline semaphore of the device, live while the state
|
||||
// holds its event or the core lives.
|
||||
let result = unsafe { device.wait_semaphores(&wait, nanos) };
|
||||
state = done.lock();
|
||||
state.waiting = Waiting::Not;
|
||||
if result.is_err_and(|result| result != vk::Result::TIMEOUT) {
|
||||
state.lost = true;
|
||||
drop(state);
|
||||
core.work.lose();
|
||||
state = done.lock();
|
||||
}
|
||||
}
|
||||
let watched: Vec<_> = state.watched.drain(..).collect();
|
||||
let fired: Vec<_> = state.fire.drain(..).collect();
|
||||
drop(state);
|
||||
drop((watched, fired));
|
||||
}
|
||||
|
||||
fn nanos(duration: Duration) -> u64 {
|
||||
u64::try_from(duration.as_nanos()).unwrap_or(u64::MAX)
|
||||
}
|
||||
|
||||
impl Core {
|
||||
/// Waits, up to `deadline`, for the batch of progress `value` and every one before it. True
|
||||
/// once they completed, or the device is lost and runs nothing more; false at the deadline.
|
||||
pub(crate) fn wait_progress(&self, value: u64, deadline: Option<Instant>) -> bool {
|
||||
let semaphores = [self.done.progress];
|
||||
let values = [value];
|
||||
let wait = vk::SemaphoreWaitInfo::default()
|
||||
.semaphores(&semaphores)
|
||||
.values(&values);
|
||||
let nanos = deadline.map_or(u64::MAX, |deadline| {
|
||||
nanos(deadline.saturating_duration_since(Instant::now()))
|
||||
});
|
||||
// SAFETY: the progress semaphore is the device's.
|
||||
let result = unsafe { self.device.wait_semaphores(&wait, nanos) };
|
||||
result != Err(vk::Result::TIMEOUT)
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,8 @@ use std::sync::Arc;
|
||||
pub(crate) enum Metric {
|
||||
/// [`Metrics::submissions`].
|
||||
Submissions,
|
||||
/// [`Metrics::barriers`].
|
||||
Barriers,
|
||||
/// [`Metrics::blocks_made`].
|
||||
BlocksMade,
|
||||
}
|
||||
@@ -20,6 +22,10 @@ pub(crate) enum Gauge {
|
||||
Buffers,
|
||||
/// [`Gauges::blocks`].
|
||||
Blocks,
|
||||
/// [`Gauges::command_buffers`].
|
||||
CommandBuffers,
|
||||
/// [`Gauges::events`].
|
||||
Events,
|
||||
}
|
||||
|
||||
/// No Metal counterpart: a device's counters ([`Device::counters`](crate::Device::counters)).
|
||||
@@ -63,6 +69,7 @@ impl Counters {
|
||||
let a = &self.atomics;
|
||||
let atomic = match metric {
|
||||
Metric::Submissions => &a.submissions,
|
||||
Metric::Barriers => &a.barriers,
|
||||
Metric::BlocksMade => &a.blocks_made,
|
||||
};
|
||||
atomic.fetch_add(1, Relaxed);
|
||||
@@ -83,6 +90,8 @@ impl Counters {
|
||||
match gauge {
|
||||
Gauge::Buffers => &a.buffers,
|
||||
Gauge::Blocks => &a.blocks,
|
||||
Gauge::CommandBuffers => &a.command_buffers,
|
||||
Gauge::Events => &a.events,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! The device: one `VkDevice` for every command queue, every guest process and the compositor;
|
||||
//! its queues, its memory blocks and its teardown.
|
||||
//! its queues, its memory blocks, its threads, quiesce and teardown.
|
||||
|
||||
use crate::complete::{self, Done};
|
||||
use crate::counters::Counters;
|
||||
use crate::error::Error;
|
||||
use crate::extension::{self, DeviceExtension};
|
||||
@@ -8,22 +9,34 @@ use crate::fill::Filler;
|
||||
use crate::floor;
|
||||
use crate::instance::{Instance, PhysicalDevice};
|
||||
use crate::memory::{self, Block, BlockId, BlockInfo, BlockMappings, MemoryClass, Pool, BLOCK_LEN};
|
||||
use crate::record::Recorders;
|
||||
use crate::submit::{self, Work};
|
||||
use ash::vk;
|
||||
use std::cell::Cell;
|
||||
use std::collections::HashMap;
|
||||
use std::ffi::{c_char, CString};
|
||||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
|
||||
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
|
||||
use std::thread::{self, JoinHandle};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// `MTLDevice`, over one `VkDevice` that every command queue, every guest process and the
|
||||
/// compositor share.
|
||||
///
|
||||
/// A cheap handle: clones share one device, and every object made from it holds a clone. Blocks
|
||||
/// the consumer holds do not. The device is torn down when the last handle is dropped: the
|
||||
/// block-maker thread is joined and the GPU goes idle; then, on the dropping thread, every block
|
||||
/// is freed, after [`BlockMappings::unmap`] for each the consumer was handed, and the `VkDevice`
|
||||
/// is destroyed, with every gauge at zero. No thread of the runtime outlives it,
|
||||
/// and nothing relies on a static destructor or an `atexit` handler, so the consumer drops every
|
||||
/// handle before the process exits (a driver may unmap device memory inside `exit()`).
|
||||
/// A cheap handle: clones share one device, and every object made from it holds a clone, except
|
||||
/// a committed command buffer. Blocks the consumer holds do not.
|
||||
///
|
||||
/// The runtime runs three threads: the block-maker, the submit thread and the completion thread,
|
||||
/// which runs every handler and listener. The device is torn down when the last handle is
|
||||
/// dropped: the submit thread submits what is ready and ends what it holds with
|
||||
/// [`CommandBufferError::NotRun`](crate::CommandBufferError::NotRun); the completion thread
|
||||
/// retires the rest as the GPU completes it; the threads are joined; then every block is freed,
|
||||
/// after [`BlockMappings::unmap`] for each the consumer was handed, and the `VkDevice` is
|
||||
/// destroyed, with every gauge at zero. Where the last handle drops in a handler or a listener,
|
||||
/// the completion thread finishes the teardown itself once the handler returns. No thread of the
|
||||
/// runtime outlives the teardown, and nothing relies on a static destructor or an `atexit`
|
||||
/// handler: the consumer drops every handle, or calls [`quiesce`](Device::quiesce), before the
|
||||
/// process exits (a driver may unmap device memory inside `exit()`).
|
||||
#[derive(Clone)]
|
||||
pub struct Device {
|
||||
shared: Arc<Shared>,
|
||||
@@ -34,7 +47,44 @@ pub struct Device {
|
||||
struct Shared {
|
||||
core: Arc<Core>,
|
||||
claims: Mutex<HashMap<BlockId, Arc<Block>>>,
|
||||
threads: Vec<JoinHandle<()>>,
|
||||
threads: Mutex<Threads>,
|
||||
}
|
||||
|
||||
/// The runtime's threads, each until it is stopped.
|
||||
#[derive(Default)]
|
||||
struct Threads {
|
||||
blocks: Option<Runner>,
|
||||
submit: Option<Runner>,
|
||||
complete: Option<Runner>,
|
||||
}
|
||||
|
||||
struct Runner {
|
||||
handle: JoinHandle<()>,
|
||||
ended: Arc<Ended>,
|
||||
}
|
||||
|
||||
/// Set as a runtime thread ends, so a stop can wait for it with a deadline.
|
||||
#[derive(Default)]
|
||||
struct Ended {
|
||||
flag: Mutex<bool>,
|
||||
changed: Condvar,
|
||||
}
|
||||
|
||||
/// Marks its thread ended when dropped, after the thread's body, panics included.
|
||||
struct Ending(Arc<Ended>);
|
||||
|
||||
impl Drop for Ending {
|
||||
fn drop(&mut self) {
|
||||
*lock(&self.0.flag) = true;
|
||||
self.0.changed.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// The core a runtime thread serves, by address; 0 on every other thread. Constant and without
|
||||
/// a destructor, so it reads the same while the thread's other thread-locals are torn down
|
||||
/// (in `exit()`).
|
||||
static SERVES: Cell<usize> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The device itself: what the runtime's threads and every block hold.
|
||||
@@ -53,8 +103,24 @@ pub(crate) struct Core {
|
||||
max_block_len: u64,
|
||||
pub(crate) pool: Pool,
|
||||
pub(crate) filler: Filler,
|
||||
pub(crate) recorders: Recorders,
|
||||
pub(crate) work: Work,
|
||||
pub(crate) done: Done,
|
||||
/// Quiesced or torn down: calls that need a thread are refused.
|
||||
closed: AtomicBool,
|
||||
/// [`RUNNING`], [`HALTING`], or the answer of the stop that ran.
|
||||
halt: AtomicU8,
|
||||
}
|
||||
|
||||
/// No stop has begun.
|
||||
const RUNNING: u8 = 0;
|
||||
/// A stop is running.
|
||||
const HALTING: u8 = 1;
|
||||
/// A stop ended with the GPU idle and every thread joined.
|
||||
const HALTED_IDLE: u8 = 2;
|
||||
/// A stop ended at its deadline.
|
||||
const HALTED_LATE: u8 = 3;
|
||||
|
||||
/// The device's queues, each behind the lock that Vulkan's external synchronization of a queue
|
||||
/// needs. Where the family has a second queue, presenting has it to itself; where it has one, the
|
||||
/// presenting queue is the runtime's own queue and its lock.
|
||||
@@ -90,7 +156,8 @@ impl Device {
|
||||
/// the consumer needs, and chooses its memory types on it ([`floor::memory_types`]). It takes one queue of the floor's queue
|
||||
/// family for the runtime and, where that family has a second queue, a queue for presenting;
|
||||
/// where it has one, presenting shares the runtime's queue and its lock. It starts the
|
||||
/// block-maker thread, which makes one block of each memory class ready.
|
||||
/// block-maker thread, which makes one block of each memory class ready, the submit thread and
|
||||
/// the completion thread.
|
||||
///
|
||||
/// Err: [`Error::BelowFloor`] with every item the device lacks; [`Error::Vulkan`] where a
|
||||
/// Vulkan call fails; [`Error::Thread`].
|
||||
@@ -155,9 +222,9 @@ impl Device {
|
||||
let counters = Counters::new();
|
||||
// SAFETY: the device was made from `raw` with `capabilities.features`, and the family is
|
||||
// its queues' family.
|
||||
let memory = unsafe { memory_types_and_filler(&device, &capabilities, family, &counters) };
|
||||
let (memory_types, filler) = match memory {
|
||||
Ok(memory) => memory,
|
||||
let made = unsafe { objects(&device, &capabilities, family, &counters) };
|
||||
let (memory_types, filler, done) = match made {
|
||||
Ok(made) => made,
|
||||
Err(error) => {
|
||||
// SAFETY: nothing made from the device is left.
|
||||
unsafe { device.destroy_device(None) };
|
||||
@@ -201,19 +268,28 @@ impl Device {
|
||||
max_block_len,
|
||||
pool: Pool::new(options.block_mappings),
|
||||
filler,
|
||||
recorders: Recorders::new(family),
|
||||
work: Work::new(),
|
||||
done,
|
||||
closed: AtomicBool::new(false),
|
||||
halt: AtomicU8::new(RUNNING),
|
||||
});
|
||||
let maker = Arc::clone(&core);
|
||||
let blocks = thread::Builder::new()
|
||||
.name("m2v-blocks".to_string())
|
||||
.spawn(move || memory::run(maker))
|
||||
.map_err(Error::Thread)?;
|
||||
Ok(Device {
|
||||
let device = Device {
|
||||
shared: Arc::new(Shared {
|
||||
core,
|
||||
claims: Mutex::new(HashMap::new()),
|
||||
threads: vec![blocks],
|
||||
threads: Mutex::new(Threads::default()),
|
||||
}),
|
||||
})
|
||||
};
|
||||
// A thread that does not start drops the device, which stops those that did.
|
||||
let core = &device.shared.core;
|
||||
let blocks = spawn("m2v-blocks", core, memory::run)?;
|
||||
lock(&device.shared.threads).blocks = Some(blocks);
|
||||
let submit = spawn("m2v-submit", core, submit::run)?;
|
||||
lock(&device.shared.threads).submit = Some(submit);
|
||||
let complete = spawn("m2v-complete", core, complete::run)?;
|
||||
lock(&device.shared.threads).complete = Some(complete);
|
||||
Ok(device)
|
||||
}
|
||||
|
||||
/// `hasUnifiedMemory`: true where Vulkan's device type is integrated or CPU, false for a
|
||||
@@ -281,9 +357,12 @@ impl Device {
|
||||
///
|
||||
/// Err: [`Limit::BlockLen`](crate::Limit::BlockLen) past the device's largest allocation or
|
||||
/// buffer; [`Limit::BlockIds`](crate::Limit::BlockIds); [`Error::Vulkan`] where the device is
|
||||
/// out of memory or lost.
|
||||
/// out of memory or lost; [`Error::Quiesced`].
|
||||
pub fn take_block(&self, class: MemoryClass, len: u64) -> Result<BlockInfo, Error> {
|
||||
let core = &self.shared.core;
|
||||
if core.closed() {
|
||||
return Err(Error::Quiesced);
|
||||
}
|
||||
let memory = if len <= BLOCK_LEN {
|
||||
core.pool.take(class)?
|
||||
} else {
|
||||
@@ -291,14 +370,41 @@ impl Device {
|
||||
memory::make(core, class, len, core.pool.number()?, false)?
|
||||
};
|
||||
let info = memory.info();
|
||||
core.pool.hand(memory.id);
|
||||
lock(&self.shared.claims).insert(memory.id, Arc::new(Block::new(memory, Arc::clone(core))));
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
/// No Metal counterpart: stops the runtime's threads and its GPU work, for a process about to
|
||||
/// exit with the device still alive. True once the GPU went idle and every thread ended
|
||||
/// within `timeout`; false where the timeout passed first, or the call ran in a handler or a
|
||||
/// listener (the completion thread cannot wait for itself).
|
||||
///
|
||||
/// In order, each wait bounded by `timeout`: the submit thread submits what is ready, ends
|
||||
/// every command buffer it holds or has not yet submitted with
|
||||
/// [`CommandBufferError::NotRun`](crate::CommandBufferError::NotRun), and ends; the
|
||||
/// block-maker thread ends; the GPU completes everything submitted; the completion thread
|
||||
/// retires it, runs the handlers, and ends; then [`BlockMappings::unmap`] runs on this thread
|
||||
/// for every block still handed out. After it, no runtime thread touches a block, unless the
|
||||
/// call answered false.
|
||||
///
|
||||
/// It frees nothing: every block's memory and mapping stays valid until the process ends, or
|
||||
/// until the device's last handle drops, which then frees it without the hook. Later calls
|
||||
/// that need a runtime thread return [`Error::Quiesced`]: taking a block, a command buffer,
|
||||
/// an enqueue or commit, a zeroed Private buffer, and a listener.
|
||||
///
|
||||
/// Safe in an `atexit` handler on whichever thread calls `exit()`: it joins a thread only once
|
||||
/// that thread has ended, reads no thread-local that `exit()` tears down, and takes no lock a
|
||||
/// consumer's thread can hold. A second call returns at once, with the first call's answer,
|
||||
/// or false while the first is still running.
|
||||
pub fn quiesce(&self, timeout: Duration) -> bool {
|
||||
self.shared.halt(Instant::now().checked_add(timeout), true)
|
||||
}
|
||||
|
||||
/// No Metal counterpart: gives a block back.
|
||||
///
|
||||
/// It takes effect once no [`Buffer`](crate::Buffer) of the block remains. A pooled block is
|
||||
/// then zeroed and kept ready, with the same number, address and mapping, while its class has
|
||||
/// It takes effect once no [`Buffer`](crate::Buffer) of the block remains and every command
|
||||
/// buffer that used it has retired. A pooled block is then zeroed and kept ready, with the same number, address and mapping, while its class has
|
||||
/// fewer than two idle; otherwise the block-maker thread frees it, after
|
||||
/// [`BlockMappings::unmap`]. A dedicated block is always freed that way.
|
||||
///
|
||||
@@ -329,26 +435,141 @@ impl Device {
|
||||
pub(crate) fn with_runtime_queue<R>(&self, f: impl FnOnce(vk::Queue) -> R) -> R {
|
||||
f(*lock(&self.shared.core.queues.runtime))
|
||||
}
|
||||
|
||||
/// For the device tests: the runtime acts as at a loss of the device.
|
||||
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
|
||||
pub(crate) fn lose_for_test(&self) {
|
||||
complete::lose(&self.shared.core);
|
||||
}
|
||||
}
|
||||
|
||||
/// The memory types the floor chooses on a new device, and the zero fill's objects.
|
||||
/// Starts a runtime thread that serves `core`.
|
||||
fn spawn(name: &str, core: &Arc<Core>, body: fn(Arc<Core>)) -> Result<Runner, Error> {
|
||||
let ended = Arc::new(Ended::default());
|
||||
let ending = Ending(Arc::clone(&ended));
|
||||
let core = Arc::clone(core);
|
||||
let handle = thread::Builder::new()
|
||||
.name(name.to_string())
|
||||
.spawn(move || {
|
||||
let _ending = ending;
|
||||
SERVES.set(Arc::as_ptr(&core) as usize);
|
||||
body(core);
|
||||
})
|
||||
.map_err(Error::Thread)?;
|
||||
Ok(Runner { handle, ended })
|
||||
}
|
||||
|
||||
impl Ended {
|
||||
/// Waits for the thread to end, up to `deadline`. True once it has.
|
||||
fn wait(&self, deadline: Option<Instant>) -> bool {
|
||||
let mut flag = lock(&self.flag);
|
||||
while !*flag {
|
||||
flag = match deadline {
|
||||
None => self
|
||||
.changed
|
||||
.wait(flag)
|
||||
.unwrap_or_else(PoisonError::into_inner),
|
||||
Some(deadline) => {
|
||||
let Some(left) = deadline.checked_duration_since(Instant::now()) else {
|
||||
return false;
|
||||
};
|
||||
self.changed
|
||||
.wait_timeout(flag, left)
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.0
|
||||
}
|
||||
};
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
/// Stops the runtime's threads and its GPU work: for [`Device::quiesce`] (`quiesce`, with its
|
||||
/// deadline) and for teardown. Only the first call stops anything; a later one answers at
|
||||
/// once. True once the GPU went idle and every thread ended by `deadline`.
|
||||
fn halt(&self, deadline: Option<Instant>, quiesce: bool) -> bool {
|
||||
let core = &self.core;
|
||||
match core
|
||||
.halt
|
||||
.compare_exchange(RUNNING, HALTING, Ordering::AcqRel, Ordering::Acquire)
|
||||
{
|
||||
Ok(_) => {}
|
||||
Err(halt) => return halt == HALTED_IDLE,
|
||||
}
|
||||
core.closed.store(true, Ordering::Release);
|
||||
let (blocks, submit, complete) = {
|
||||
let mut threads = lock(&self.threads);
|
||||
(
|
||||
threads.blocks.take(),
|
||||
threads.submit.take(),
|
||||
threads.complete.take(),
|
||||
)
|
||||
};
|
||||
// Submission stops: what is ready goes, and what is held ends.
|
||||
core.work.stop();
|
||||
let mut idle = finish(submit, deadline);
|
||||
core.pool.stop();
|
||||
idle &= finish(blocks, deadline);
|
||||
if quiesce {
|
||||
idle &= core.wait_progress(core.work.progress(), deadline);
|
||||
}
|
||||
core.done.stop(core, deadline);
|
||||
// Only the completion thread runs the consumer's code among the runtime's threads. Where
|
||||
// this call runs on it (a handler or listener dropped the last handle, or quiesced), it
|
||||
// ends itself once the call returns, and is not waited for.
|
||||
let on_completion = SERVES.get() == Arc::as_ptr(core) as usize;
|
||||
idle &= !on_completion && finish(complete, deadline) && core.done.drained();
|
||||
if quiesce {
|
||||
core.pool.unmap_all();
|
||||
}
|
||||
let answer = if idle { HALTED_IDLE } else { HALTED_LATE };
|
||||
core.halt.store(answer, Ordering::Release);
|
||||
idle
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits for a thread to end, up to `deadline`, and joins it once it has; a thread past the
|
||||
/// deadline is left to end alone. True once it ended.
|
||||
fn finish(runner: Option<Runner>, deadline: Option<Instant>) -> bool {
|
||||
let Some(Runner { handle, ended }) = runner else {
|
||||
return true;
|
||||
};
|
||||
let done = ended.wait(deadline);
|
||||
if done {
|
||||
// A thread that panicked has ended all the same.
|
||||
let _ = handle.join();
|
||||
}
|
||||
done
|
||||
}
|
||||
|
||||
/// The memory types the floor chooses on a new device, the zero fill's objects, and the
|
||||
/// completion thread's semaphores.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// `device` was made with `capabilities.features`, and `family` is its queues' family.
|
||||
unsafe fn memory_types_and_filler(
|
||||
unsafe fn objects(
|
||||
device: &ash::Device,
|
||||
capabilities: &floor::Capabilities,
|
||||
family: u32,
|
||||
counters: &Counters,
|
||||
) -> Result<(floor::MemoryTypes, Filler), Error> {
|
||||
) -> Result<(floor::MemoryTypes, Filler, Done), Error> {
|
||||
// SAFETY: the caller's contract.
|
||||
let memory_types =
|
||||
unsafe { floor::memory_types(device, capabilities) }.map_err(Error::BelowFloor)?;
|
||||
// SAFETY: the caller's contract; the Shared type is host-visible and host-coherent, and the
|
||||
// floor chose it for buffers of every usage.
|
||||
let filler = unsafe { Filler::new(device, family, memory_types.shared, counters) }?;
|
||||
Ok((memory_types, filler))
|
||||
let mut filler = unsafe { Filler::new(device, family, memory_types.shared, counters) }?;
|
||||
// SAFETY: the device is live.
|
||||
match unsafe { Done::new(device) } {
|
||||
Ok(done) => Ok((memory_types, filler, done)),
|
||||
Err(error) => {
|
||||
// SAFETY: the fill's objects are unused.
|
||||
unsafe { filler.destroy(device, counters) };
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Core {
|
||||
@@ -359,6 +580,21 @@ impl Core {
|
||||
MemoryClass::Shared => self.memory_types.shared,
|
||||
}
|
||||
}
|
||||
|
||||
/// Quiesced or torn down.
|
||||
pub(crate) fn closed(&self) -> bool {
|
||||
self.closed.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
/// Waits for the device to go idle. A lost device does so at once.
|
||||
pub(crate) fn wait_idle(&self) {
|
||||
// `vkDeviceWaitIdle` needs every queue of the device externally synchronized.
|
||||
let _runtime = lock(&self.queues.runtime);
|
||||
let _present = (!Arc::ptr_eq(&self.queues.runtime, &self.queues.present))
|
||||
.then(|| lock(&self.queues.present));
|
||||
// SAFETY: every queue is held. A lost device fails the wait, and then nothing is pending.
|
||||
let _ = unsafe { self.device.device_wait_idle() };
|
||||
}
|
||||
}
|
||||
|
||||
/// No Metal counterpart: a device's Vulkan handles ([`Device::raw`]).
|
||||
@@ -376,11 +612,7 @@ pub struct RawDevice<'a> {
|
||||
|
||||
impl Drop for Shared {
|
||||
fn drop(&mut self) {
|
||||
self.core.pool.stop();
|
||||
for thread in self.threads.drain(..) {
|
||||
// A thread that panicked has stopped all the same.
|
||||
let _ = thread.join();
|
||||
}
|
||||
self.halt(None, false);
|
||||
// The blocks the consumer still holds go back to the pool, for the core to free. No
|
||||
// buffer of them is left: each holds a handle of the device.
|
||||
self.claims
|
||||
@@ -392,20 +624,16 @@ impl Drop for Shared {
|
||||
|
||||
impl Drop for Core {
|
||||
fn drop(&mut self) {
|
||||
{
|
||||
// `vkDeviceWaitIdle` needs every queue of the device externally synchronized.
|
||||
let _runtime = lock(&self.queues.runtime);
|
||||
let _present = (!Arc::ptr_eq(&self.queues.runtime, &self.queues.present))
|
||||
.then(|| lock(&self.queues.present));
|
||||
// SAFETY: every queue is held. A lost device fails the wait; teardown goes on.
|
||||
let _ = unsafe { self.device.device_wait_idle() };
|
||||
self.wait_idle();
|
||||
// The runtime's threads have ended: the core is dropped only once none holds it, and with
|
||||
// it every command buffer and upload, each of which held what it used.
|
||||
for memory in self.pool.remaining() {
|
||||
memory::free(self, memory);
|
||||
}
|
||||
// The runtime's threads are joined: the core is dropped only once none holds it.
|
||||
for (memory, handed) in self.pool.remaining() {
|
||||
memory::free(self, memory, handed);
|
||||
}
|
||||
// SAFETY: the device is idle, and nothing made from it is left but the fill's objects.
|
||||
self.recorders.destroy_all(&self.device);
|
||||
// SAFETY: the device is idle, and nothing made from it is left but these objects.
|
||||
unsafe {
|
||||
self.done.destroy(&self.device);
|
||||
self.filler.destroy(&self.device, &self.counters);
|
||||
self.device.destroy_device(None);
|
||||
}
|
||||
|
||||
@@ -36,6 +36,9 @@ pub enum Error {
|
||||
NoSuchBlock(BlockId),
|
||||
/// The runtime could not start one of its threads. Metal has no counterpart.
|
||||
Thread(io::Error),
|
||||
/// A call that needs one of the runtime's threads, after
|
||||
/// [`Device::quiesce`](crate::Device::quiesce) stopped them. Metal has no counterpart.
|
||||
Quiesced,
|
||||
}
|
||||
|
||||
/// A call Metal refuses, with what it was asked.
|
||||
@@ -60,6 +63,24 @@ pub enum Refusal {
|
||||
/// The block's length.
|
||||
block_len: u64,
|
||||
},
|
||||
/// A call on a command buffer already committed: encoding, adding a handler, enqueueing or
|
||||
/// committing again.
|
||||
///
|
||||
/// Basis: metal-documented (Metal's validation asserts "commit an already committed command
|
||||
/// buffer", "Completed handler provided after commit call" and "Scheduled handler provided
|
||||
/// after commit call").
|
||||
Committed,
|
||||
/// An event of another device in an encode call
|
||||
/// ([`CommandBuffer::encode_wait_for_event`](crate::CommandBuffer::encode_wait_for_event) or
|
||||
/// [`CommandBuffer::encode_signal_event`](crate::CommandBuffer::encode_signal_event)).
|
||||
///
|
||||
/// Basis: ours (an event's semaphore belongs to the `VkDevice` that made it).
|
||||
OtherDevice,
|
||||
/// A queue that may hold no command buffer
|
||||
/// ([`Device::new_command_queue`](crate::Device::new_command_queue) with a count of 0).
|
||||
///
|
||||
/// Basis: ours (its first `commandBuffer` call would wait forever).
|
||||
NoCommandBuffers,
|
||||
}
|
||||
|
||||
/// A limit a call ran into, with what it was asked.
|
||||
@@ -104,6 +125,7 @@ impl fmt::Display for Error {
|
||||
write!(f, "block {} is not one the consumer holds", block.get())
|
||||
}
|
||||
Error::Thread(error) => write!(f, "a runtime thread did not start: {error}"),
|
||||
Error::Quiesced => f.write_str("the device is quiesced"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -120,6 +142,11 @@ impl fmt::Display for Refusal {
|
||||
f,
|
||||
"a buffer of {length} bytes at offset {offset} leaves its block of {block_len} bytes"
|
||||
),
|
||||
Refusal::Committed => f.write_str("the command buffer is already committed"),
|
||||
Refusal::OtherDevice => f.write_str("the event is another device's"),
|
||||
Refusal::NoCommandBuffers => {
|
||||
f.write_str("a command queue must hold at least one command buffer")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -143,7 +170,7 @@ impl std::error::Error for Error {
|
||||
Error::BelowFloor(below) => Some(below),
|
||||
Error::Vulkan { result, .. } => Some(result),
|
||||
Error::Thread(error) => Some(error),
|
||||
Error::Refused(_) | Error::Limit(_) | Error::NoSuchBlock(_) => None,
|
||||
Error::Refused(_) | Error::Limit(_) | Error::NoSuchBlock(_) | Error::Quiesced => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
//! Events: Metal's event values carried by timeline semaphores, and the host floor of a shared
|
||||
//! event.
|
||||
|
||||
use crate::counters::Gauge;
|
||||
use crate::device::{lock, Core, Device};
|
||||
use crate::error::Error;
|
||||
use ash::vk;
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::{Arc, Condvar, Mutex, PoisonError};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// `MTLEvent`: a timeline semaphore whose values are Metal's values.
|
||||
///
|
||||
/// Metal's values only rise, so a signal not above the highest value already submitted or set
|
||||
/// changes nothing: the submit thread leaves it out, and the semaphore only rises. A cheap handle:
|
||||
/// clones share one event. It holds the device.
|
||||
#[derive(Clone)]
|
||||
pub struct Event {
|
||||
inner: Arc<EventInner>,
|
||||
device: Device,
|
||||
}
|
||||
|
||||
/// `MTLSharedEvent`: an [`Event`] the host also reads, sets and waits on.
|
||||
///
|
||||
/// A host set raises a floor and never signals the semaphore, so it never conflicts with a GPU
|
||||
/// signal already submitted. `newSharedEventHandle` has no counterpart: one device serves every
|
||||
/// guest process.
|
||||
#[derive(Clone)]
|
||||
pub struct SharedEvent {
|
||||
event: Event,
|
||||
}
|
||||
|
||||
/// What a listener of a shared event runs: the event's value when it fires.
|
||||
pub(crate) type Listener = Box<dyn FnOnce(u64) + Send>;
|
||||
|
||||
/// The event itself: what command buffers and the completion thread hold.
|
||||
pub(crate) struct EventInner {
|
||||
pub(crate) semaphore: vk::Semaphore,
|
||||
core: Arc<Core>,
|
||||
pub(crate) state: Mutex<EventState>,
|
||||
/// Signalled whenever the value the host sees rises, and at a loss.
|
||||
changed: Condvar,
|
||||
}
|
||||
|
||||
pub(crate) struct EventState {
|
||||
/// The highest value of a signal handed to `vkQueueSubmit2`.
|
||||
pub(crate) submitted: u64,
|
||||
/// The highest value the host set.
|
||||
pub(crate) floor: u64,
|
||||
/// The highest semaphore value the completion thread has seen.
|
||||
observed: u64,
|
||||
/// Values of submitted signals the completion thread has not yet seen, lowest first.
|
||||
pub(crate) pending: VecDeque<u64>,
|
||||
/// In the completion thread's watch list: while signals are pending.
|
||||
pub(crate) watched: bool,
|
||||
listeners: Vec<(u64, Listener)>,
|
||||
/// The device was lost while signals were pending: they never come.
|
||||
lost: bool,
|
||||
}
|
||||
|
||||
impl Device {
|
||||
/// `newEvent`.
|
||||
///
|
||||
/// Err: [`Error::Vulkan`] where the semaphore cannot be made.
|
||||
pub fn new_event(&self) -> Result<Event, Error> {
|
||||
let core = self.core();
|
||||
let semaphore = timeline(&core.device)?;
|
||||
core.counters.rise(Gauge::Events);
|
||||
Ok(Event {
|
||||
inner: Arc::new(EventInner {
|
||||
semaphore,
|
||||
core: Arc::clone(core),
|
||||
state: Mutex::new(EventState {
|
||||
submitted: 0,
|
||||
floor: 0,
|
||||
observed: 0,
|
||||
pending: VecDeque::new(),
|
||||
watched: false,
|
||||
listeners: Vec::new(),
|
||||
lost: false,
|
||||
}),
|
||||
changed: Condvar::new(),
|
||||
}),
|
||||
device: self.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// `newSharedEvent`.
|
||||
///
|
||||
/// Err: [`Error::Vulkan`] where the semaphore cannot be made.
|
||||
pub fn new_shared_event(&self) -> Result<SharedEvent, Error> {
|
||||
Ok(SharedEvent {
|
||||
event: self.new_event()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A new timeline semaphore at 0.
|
||||
pub(crate) fn timeline(device: &ash::Device) -> Result<vk::Semaphore, Error> {
|
||||
let mut kind = vk::SemaphoreTypeCreateInfo::default()
|
||||
.semaphore_type(vk::SemaphoreType::TIMELINE)
|
||||
.initial_value(0);
|
||||
let info = vk::SemaphoreCreateInfo::default().push_next(&mut kind);
|
||||
// SAFETY: the device is live, and timeline semaphores are in the floor.
|
||||
unsafe { device.create_semaphore(&info, None) }.map_err(Error::vulkan("vkCreateSemaphore"))
|
||||
}
|
||||
|
||||
impl Event {
|
||||
/// The event, for the command buffers that wait on it and signal it.
|
||||
pub(crate) fn inner(&self) -> &Arc<EventInner> {
|
||||
&self.inner
|
||||
}
|
||||
|
||||
/// No Metal counterpart: the device the event was made on.
|
||||
pub fn device(&self) -> &Device {
|
||||
&self.device
|
||||
}
|
||||
}
|
||||
|
||||
impl SharedEvent {
|
||||
/// `signaledValue`: the higher of the semaphore's value and the host's floor.
|
||||
pub fn signaled_value(&self) -> u64 {
|
||||
let inner = &self.event.inner;
|
||||
let state = lock(&inner.state);
|
||||
let floor = state.observed.max(state.floor);
|
||||
// A lost device answers with what was seen before the loss.
|
||||
inner.counter().map_or(floor, |counter| counter.max(floor))
|
||||
}
|
||||
|
||||
/// `setSignaledValue:`: raises the host's floor to `value`; a value not above it changes
|
||||
/// nothing. The semaphore is never signalled from the host. Held command buffers and host
|
||||
/// waits that the new value meets go on, and listeners it reaches run.
|
||||
pub fn set_signaled_value(&self, value: u64) {
|
||||
let inner = &self.event.inner;
|
||||
let reached = {
|
||||
let mut state = lock(&inner.state);
|
||||
if value <= state.floor {
|
||||
return;
|
||||
}
|
||||
state.floor = value;
|
||||
inner.changed.notify_all();
|
||||
state.listeners.iter().any(|(at, _)| *at <= value)
|
||||
};
|
||||
let core = &inner.core;
|
||||
core.work.poke();
|
||||
if reached {
|
||||
core.done.fire(core, Arc::clone(inner));
|
||||
}
|
||||
}
|
||||
|
||||
/// `waitUntilSignaledValue:timeoutMS:`: true once [`signaled_value`](Self::signaled_value)
|
||||
/// reaches `value`, false when `timeout` passes first.
|
||||
///
|
||||
/// Also false once the device is lost while the signals the wait needs are pending. A wait
|
||||
/// that no submitted signal can meet is met only by the host.
|
||||
pub fn wait_until_signaled_value(&self, value: u64, timeout: Duration) -> bool {
|
||||
let inner = &self.event.inner;
|
||||
let deadline = Instant::now().checked_add(timeout);
|
||||
let mut state = lock(&inner.state);
|
||||
loop {
|
||||
if state.floor.max(state.observed) >= value
|
||||
|| inner.counter().is_ok_and(|counter| counter >= value)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if state.lost {
|
||||
return false;
|
||||
}
|
||||
state = match deadline {
|
||||
None => inner
|
||||
.changed
|
||||
.wait(state)
|
||||
.unwrap_or_else(PoisonError::into_inner),
|
||||
Some(deadline) => {
|
||||
let Some(left) = deadline.checked_duration_since(Instant::now()) else {
|
||||
return false;
|
||||
};
|
||||
inner
|
||||
.changed
|
||||
.wait_timeout(state, left)
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.0
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// `notifyListener:atValue:block:`: runs `listener` on the completion thread once
|
||||
/// [`signaled_value`](Self::signaled_value) reaches `value`, at once where it already has, with
|
||||
/// the event's value then. Metal's block also receives the event; a listener captures what it
|
||||
/// needs. A signal the GPU reaches in the middle of a command buffer runs it then, not at the
|
||||
/// command buffer's end.
|
||||
///
|
||||
/// Err: [`Error::Quiesced`] after [`Device::quiesce`], when no listener runs again.
|
||||
pub fn notify_listener(
|
||||
&self,
|
||||
value: u64,
|
||||
listener: impl FnOnce(u64) + Send + 'static,
|
||||
) -> Result<(), Error> {
|
||||
let inner = &self.event.inner;
|
||||
let core = &inner.core;
|
||||
if core.closed() {
|
||||
return Err(Error::Quiesced);
|
||||
}
|
||||
let reached = {
|
||||
let mut state = lock(&inner.state);
|
||||
state.listeners.push((value, Box::new(listener)));
|
||||
value <= state.observed.max(state.floor)
|
||||
};
|
||||
if reached {
|
||||
core.done.fire(core, Arc::clone(inner));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `MTLSharedEvent` as an `MTLEvent`, for the encode calls.
|
||||
pub fn as_event(&self) -> &Event {
|
||||
&self.event
|
||||
}
|
||||
|
||||
/// For the device tests: records a GPU signal of `value` as submitted, so a wait for it waits
|
||||
/// on the semaphore, which the test then signals from the host.
|
||||
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
|
||||
pub(crate) fn pretend_submitted_for_test(&self, value: u64) {
|
||||
let mut state = lock(&self.event.inner.state);
|
||||
state.submitted = state.submitted.max(value);
|
||||
}
|
||||
}
|
||||
|
||||
impl EventInner {
|
||||
/// Whether the event is `core`'s.
|
||||
pub(crate) fn is_of(&self, core: &Arc<Core>) -> bool {
|
||||
Arc::ptr_eq(&self.core, core)
|
||||
}
|
||||
|
||||
/// The semaphore's value now.
|
||||
pub(crate) fn counter(&self) -> Result<u64, Error> {
|
||||
// SAFETY: the semaphore is a timeline semaphore of the device, live while `self` is.
|
||||
unsafe { self.core.device.get_semaphore_counter_value(self.semaphore) }
|
||||
.map_err(Error::vulkan("vkGetSemaphoreCounterValue"))
|
||||
}
|
||||
|
||||
/// On the completion thread: takes in the semaphore's value (`counter`, where read), wakes the
|
||||
/// host waits it meets, and takes out the listeners the event's value now reaches, with that
|
||||
/// value. Returns whether signals are still pending.
|
||||
pub(crate) fn observe(&self, counter: Option<u64>, fire: &mut Vec<(Listener, u64)>) -> bool {
|
||||
let mut state = lock(&self.state);
|
||||
if let Some(counter) = counter.filter(|&counter| counter > state.observed) {
|
||||
state.observed = counter;
|
||||
while state.pending.front().is_some_and(|&value| value <= counter) {
|
||||
state.pending.pop_front();
|
||||
}
|
||||
self.changed.notify_all();
|
||||
}
|
||||
let value = state.observed.max(state.floor);
|
||||
fire.extend(
|
||||
state
|
||||
.listeners
|
||||
.extract_if(.., |(at, _)| *at <= value)
|
||||
.map(|(_, listener)| (listener, value)),
|
||||
);
|
||||
if state.pending.is_empty() {
|
||||
state.watched = false;
|
||||
}
|
||||
state.watched
|
||||
}
|
||||
|
||||
/// At a loss: the pending signals never come, so the host waits for them end.
|
||||
pub(crate) fn lose(&self) {
|
||||
let mut state = lock(&self.state);
|
||||
state.lost = true;
|
||||
state.pending.clear();
|
||||
state.watched = false;
|
||||
self.changed.notify_all();
|
||||
}
|
||||
|
||||
/// The value the completion thread waits for next: the lowest pending signal.
|
||||
pub(crate) fn next_pending(&self) -> Option<u64> {
|
||||
lock(&self.state).pending.front().copied()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for EventInner {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: no pending GPU work names the semaphore: every command buffer that waits on it
|
||||
// or signals it holds the event until it retires, and the completion thread holds it
|
||||
// while its signals are pending.
|
||||
unsafe { self.core.device.destroy_semaphore(self.semaphore, None) };
|
||||
self.core.counters.fall(Gauge::Events);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Zero fills of memory the host does not map: one command buffer of fill and copy commands,
|
||||
//! submitted on the runtime's queue and waited for.
|
||||
//! Zero fills of memory the host does not map: fill and copy commands, recorded into the
|
||||
//! upload that goes ahead of later commits, or into a command buffer of the fill's own, submitted
|
||||
//! on the runtime's queue and waited for.
|
||||
|
||||
use crate::counters::{Counters, Gauge, Metric};
|
||||
use crate::device::{lock, Core};
|
||||
@@ -42,8 +43,46 @@ pub(crate) fn plan(offset: u64, end: u64) -> Plan {
|
||||
}
|
||||
}
|
||||
|
||||
/// The objects one zero fill uses, behind a lock: fills run one at a time.
|
||||
/// Records the commands that zero `offset..end` of `buffer` into `command`.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// `command` is recording; `zeros` is the zero source; `buffer` has transfer-destination usage and
|
||||
/// `offset..end` lies in it.
|
||||
pub(crate) unsafe fn record(
|
||||
device: &ash::Device,
|
||||
command: vk::CommandBuffer,
|
||||
zeros: vk::Buffer,
|
||||
buffer: vk::Buffer,
|
||||
offset: u64,
|
||||
end: u64,
|
||||
) {
|
||||
let plan = plan(offset, end);
|
||||
let copies: Vec<vk::BufferCopy> = plan
|
||||
.copies
|
||||
.iter()
|
||||
.map(|&(start, end)| vk::BufferCopy {
|
||||
src_offset: 0,
|
||||
dst_offset: start,
|
||||
size: end - start,
|
||||
})
|
||||
.collect();
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe {
|
||||
if let Some((start, end)) = plan.fill {
|
||||
device.cmd_fill_buffer(command, buffer, start, end - start, 0);
|
||||
}
|
||||
if !copies.is_empty() {
|
||||
device.cmd_copy_buffer(command, zeros, buffer, &copies);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The zero source, and the objects of a fill submitted and waited for, behind a lock: such fills
|
||||
/// run one at a time.
|
||||
pub(crate) struct Filler {
|
||||
/// The zero source, [`ZEROS`] bytes that read zero; `state` owns it.
|
||||
zeros: vk::Buffer,
|
||||
state: Mutex<Objects>,
|
||||
}
|
||||
|
||||
@@ -74,6 +113,7 @@ impl Filler {
|
||||
// SAFETY: the caller's contract.
|
||||
match unsafe { objects.make(device, family, host_type, counters) } {
|
||||
Ok(()) => Ok(Filler {
|
||||
zeros: objects.zeros,
|
||||
state: Mutex::new(objects),
|
||||
}),
|
||||
Err(error) => {
|
||||
@@ -84,6 +124,11 @@ impl Filler {
|
||||
}
|
||||
}
|
||||
|
||||
/// The zero source, for [`record`].
|
||||
pub(crate) fn zeros(&self) -> vk::Buffer {
|
||||
self.zeros
|
||||
}
|
||||
|
||||
/// Zeroes `offset..end` of `buffer` and waits for it.
|
||||
pub(crate) fn zero(
|
||||
&self,
|
||||
@@ -92,21 +137,11 @@ impl Filler {
|
||||
offset: u64,
|
||||
end: u64,
|
||||
) -> Result<(), Error> {
|
||||
let plan = plan(offset, end);
|
||||
let objects = lock(&self.state);
|
||||
let device = &core.device;
|
||||
let command = objects.command;
|
||||
let begin = vk::CommandBufferBeginInfo::default()
|
||||
.flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT);
|
||||
let copies: Vec<vk::BufferCopy> = plan
|
||||
.copies
|
||||
.iter()
|
||||
.map(|&(start, end)| vk::BufferCopy {
|
||||
src_offset: 0,
|
||||
dst_offset: start,
|
||||
size: end - start,
|
||||
})
|
||||
.collect();
|
||||
let commands = [vk::CommandBufferSubmitInfo::default().command_buffer(command)];
|
||||
let submit = vk::SubmitInfo2::default().command_buffer_infos(&commands);
|
||||
// SAFETY: the lock gives this call the pool, command buffer and fence, and the previous
|
||||
@@ -119,12 +154,7 @@ impl Filler {
|
||||
device
|
||||
.begin_command_buffer(command, &begin)
|
||||
.map_err(Error::vulkan("vkBeginCommandBuffer"))?;
|
||||
if let Some((start, end)) = plan.fill {
|
||||
device.cmd_fill_buffer(command, buffer, start, end - start, 0);
|
||||
}
|
||||
if !copies.is_empty() {
|
||||
device.cmd_copy_buffer(command, objects.zeros, buffer, &copies);
|
||||
}
|
||||
record(device, command, objects.zeros, buffer, offset, end);
|
||||
device
|
||||
.end_command_buffer(command)
|
||||
.map_err(Error::vulkan("vkEndCommandBuffer"))?;
|
||||
|
||||
@@ -9,21 +9,30 @@
|
||||
#![warn(missing_docs)]
|
||||
|
||||
mod buffer;
|
||||
mod command;
|
||||
mod complete;
|
||||
mod counters;
|
||||
mod device;
|
||||
mod error;
|
||||
mod event;
|
||||
mod extension;
|
||||
mod fill;
|
||||
pub mod floor;
|
||||
mod instance;
|
||||
mod memory;
|
||||
mod queue;
|
||||
mod record;
|
||||
mod submit;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
pub use buffer::Buffer;
|
||||
pub use command::{CommandBuffer, CommandBufferError, CommandBufferStatus};
|
||||
pub use counters::{Counters, Gauges, Metrics};
|
||||
pub use device::{Device, DeviceOptions, RawDevice};
|
||||
pub use error::{Error, Limit, Refusal};
|
||||
pub use event::{Event, SharedEvent};
|
||||
pub use extension::DeviceExtension;
|
||||
pub use instance::{Instance, PhysicalDevice};
|
||||
pub use memory::{BlockId, BlockInfo, BlockMappings, MemoryClass, BLOCK_LEN};
|
||||
pub use queue::CommandQueue;
|
||||
@@ -6,6 +6,7 @@ use crate::device::{lock, Core};
|
||||
use crate::error::{Error, Limit};
|
||||
use crate::floor;
|
||||
use ash::vk;
|
||||
use std::collections::HashSet;
|
||||
use std::ptr::NonNull;
|
||||
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
|
||||
|
||||
@@ -97,9 +98,10 @@ pub trait BlockMappings: Send + Sync {
|
||||
/// Returns only once every mapping of `block` the consumer made is gone and none of its
|
||||
/// threads touches the block's memory. The memory stays mapped and valid until it returns.
|
||||
///
|
||||
/// It runs on the block-maker thread, or at teardown on the thread that drops the device's
|
||||
/// last handle, after the runtime's threads are joined. It makes no call into the runtime and
|
||||
/// drops no runtime handle.
|
||||
/// It runs once per block: on the block-maker thread; in
|
||||
/// [`Device::quiesce`](crate::Device::quiesce), on the thread that calls it, for every block
|
||||
/// still handed out; or at teardown, on the thread that ends it, once the runtime's other
|
||||
/// threads are joined. It makes no call into the runtime and drops no runtime handle.
|
||||
fn unmap(&self, block: BlockId);
|
||||
}
|
||||
|
||||
@@ -161,8 +163,9 @@ impl Mapping {
|
||||
}
|
||||
}
|
||||
|
||||
/// A block that has been handed out. The consumer's hold on it and each buffer of it is one
|
||||
/// reference; the last one dropped gives it back to the pool.
|
||||
/// A block that has been handed out. The consumer's hold on it, each buffer of it, and each
|
||||
/// command buffer and upload that uses it until it retires are one reference each; the last one
|
||||
/// dropped gives it back to the pool.
|
||||
pub(crate) struct Block {
|
||||
pub(crate) memory: Memory,
|
||||
core: Arc<Core>,
|
||||
@@ -192,7 +195,7 @@ pub(crate) struct Pool {
|
||||
|
||||
struct State {
|
||||
/// Per class, zeroed blocks no one holds, the latest last.
|
||||
idle: [Vec<Idle>; 2],
|
||||
idle: [Vec<Memory>; 2],
|
||||
/// Blocks given back, for the block-maker thread.
|
||||
returned: Vec<Memory>,
|
||||
/// Per class, why the block-maker thread could not make the last block it tried, for the
|
||||
@@ -200,12 +203,10 @@ struct State {
|
||||
failed: [Option<Error>; 2],
|
||||
stop: bool,
|
||||
next_id: u32,
|
||||
}
|
||||
|
||||
struct Idle {
|
||||
memory: Memory,
|
||||
/// Whether the consumer has held it, so that freeing it calls the hook.
|
||||
handed: bool,
|
||||
/// The blocks `take_block` returned that are not yet freed: freeing one calls the hook.
|
||||
handed: HashSet<BlockId>,
|
||||
/// The hook has run for every block handed out ([`Pool::unmap_all`]); it never runs again.
|
||||
unmapped: bool,
|
||||
}
|
||||
|
||||
impl Pool {
|
||||
@@ -217,6 +218,8 @@ impl Pool {
|
||||
failed: [None, None],
|
||||
stop: false,
|
||||
next_id: 1,
|
||||
handed: HashSet::new(),
|
||||
unmapped: false,
|
||||
}),
|
||||
changed: Condvar::new(),
|
||||
mappings,
|
||||
@@ -239,14 +242,17 @@ impl Pool {
|
||||
}
|
||||
|
||||
/// Takes a ready block of `class`, waiting for the block-maker thread where none is ready.
|
||||
/// Err: why the block-maker thread could not make one.
|
||||
/// Err: why the block-maker thread could not make one; [`Error::Quiesced`] once it is stopped.
|
||||
pub(crate) fn take(&self, class: MemoryClass) -> Result<Memory, Error> {
|
||||
let index = class.index();
|
||||
let mut state = self.lock();
|
||||
loop {
|
||||
if let Some(idle) = state.idle[index].pop() {
|
||||
if state.stop {
|
||||
return Err(Error::Quiesced);
|
||||
}
|
||||
if let Some(memory) = state.idle[index].pop() {
|
||||
self.changed.notify_all();
|
||||
return Ok(idle.memory);
|
||||
return Ok(memory);
|
||||
}
|
||||
if let Some(error) = state.failed[index].take() {
|
||||
self.changed.notify_all();
|
||||
@@ -256,6 +262,31 @@ impl Pool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Records a block as handed to the consumer, so that freeing it calls the hook.
|
||||
pub(crate) fn hand(&self, block: BlockId) {
|
||||
let mut state = self.lock();
|
||||
if !state.unmapped {
|
||||
state.handed.insert(block);
|
||||
}
|
||||
}
|
||||
|
||||
/// In [`Device::quiesce`](crate::Device::quiesce), once the block-maker thread is stopped:
|
||||
/// calls the hook for every block handed out and not yet freed, on this thread. No block's
|
||||
/// hook runs again: a block freed later is freed without it.
|
||||
pub(crate) fn unmap_all(&self) {
|
||||
let mut handed: Vec<BlockId> = {
|
||||
let mut state = self.lock();
|
||||
state.unmapped = true;
|
||||
state.handed.drain().collect()
|
||||
};
|
||||
handed.sort_unstable();
|
||||
if let Some(mappings) = &self.mappings {
|
||||
for block in handed {
|
||||
mappings.unmap(block);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn give_back(&self, memory: Memory) {
|
||||
self.lock().returned.push(memory);
|
||||
self.changed.notify_all();
|
||||
@@ -267,19 +298,25 @@ impl Pool {
|
||||
self.changed.notify_all();
|
||||
}
|
||||
|
||||
/// At teardown, after the block-maker thread is joined: every block the pool still has, and
|
||||
/// whether the consumer held it.
|
||||
pub(crate) fn remaining(&mut self) -> Vec<(Memory, bool)> {
|
||||
/// At teardown, after the block-maker thread is joined: every block the pool still has.
|
||||
pub(crate) fn remaining(&mut self) -> Vec<Memory> {
|
||||
let state = self.state.get_mut().unwrap_or_else(PoisonError::into_inner);
|
||||
let mut remaining: Vec<(Memory, bool)> = state
|
||||
.idle
|
||||
.iter_mut()
|
||||
.flat_map(|idle| idle.drain(..))
|
||||
.map(|idle| (idle.memory, idle.handed))
|
||||
.collect();
|
||||
remaining.extend(state.returned.drain(..).map(|memory| (memory, true)));
|
||||
let mut remaining: Vec<Memory> = state.idle.iter().flatten().copied().collect();
|
||||
remaining.extend(state.returned.iter().copied());
|
||||
remaining
|
||||
}
|
||||
|
||||
/// For the device tests: whether the pool has the block back, idle or still to be zeroed.
|
||||
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
|
||||
pub(crate) fn holds(&self, block: BlockId) -> bool {
|
||||
let state = self.lock();
|
||||
state
|
||||
.idle
|
||||
.iter()
|
||||
.flatten()
|
||||
.chain(&state.returned)
|
||||
.any(|memory| memory.id == block)
|
||||
}
|
||||
}
|
||||
|
||||
fn number(state: &mut State) -> Result<BlockId, Error> {
|
||||
@@ -306,14 +343,11 @@ pub(crate) fn run(core: Arc<Core>) {
|
||||
// block that cannot be zeroed is freed.
|
||||
let kept = room && zero(&core, &memory, 0, memory.len).is_ok();
|
||||
if !kept {
|
||||
free(&core, memory, true);
|
||||
free(&core, memory);
|
||||
}
|
||||
state = pool.lock();
|
||||
if kept {
|
||||
state.idle[memory.class.index()].push(Idle {
|
||||
memory,
|
||||
handed: true,
|
||||
});
|
||||
state.idle[memory.class.index()].push(memory);
|
||||
pool.changed.notify_all();
|
||||
}
|
||||
continue;
|
||||
@@ -327,10 +361,7 @@ pub(crate) fn run(core: Arc<Core>) {
|
||||
let made = id.and_then(|id| make(&core, class, BLOCK_LEN, id, true));
|
||||
state = pool.lock();
|
||||
match made {
|
||||
Ok(memory) => state.idle[class.index()].push(Idle {
|
||||
memory,
|
||||
handed: false,
|
||||
}),
|
||||
Ok(memory) => state.idle[class.index()].push(memory),
|
||||
Err(error) => state.failed[class.index()] = Some(error),
|
||||
}
|
||||
pool.changed.notify_all();
|
||||
@@ -406,7 +437,7 @@ pub(crate) fn make(
|
||||
match finish(core, &mut block) {
|
||||
Ok(()) => Ok(block),
|
||||
Err(error) => {
|
||||
free(core, block, false);
|
||||
free(core, block);
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
@@ -434,7 +465,7 @@ fn finish(core: &Core, block: &mut Memory) -> Result<(), Error> {
|
||||
|
||||
/// Zeroes `offset..end` of a block: through the mapping for Shared, by a GPU fill for Private.
|
||||
/// The bytes belong to no one else: a block no one holds, or the range of a buffer being made.
|
||||
pub(crate) fn zero(core: &Core, memory: &Memory, offset: u64, end: u64) -> Result<(), Error> {
|
||||
fn zero(core: &Core, memory: &Memory, offset: u64, end: u64) -> Result<(), Error> {
|
||||
match memory.mapping {
|
||||
Some(mapping) => {
|
||||
// SAFETY: `offset..end` lies in the block, which the mapping spans.
|
||||
@@ -450,17 +481,19 @@ pub(crate) fn zero(core: &Core, memory: &Memory, offset: u64, end: u64) -> Resul
|
||||
}
|
||||
}
|
||||
|
||||
/// Frees a block, calling the consumer's hook first where it held the block. Freeing the memory
|
||||
/// also unmaps it.
|
||||
pub(crate) fn free(core: &Core, memory: Memory, handed: bool) {
|
||||
/// Frees a block, calling the consumer's hook first where it was handed out and the hook has not
|
||||
/// run for it. Freeing the memory also unmaps it.
|
||||
pub(crate) fn free(core: &Core, memory: Memory) {
|
||||
let handed = core.pool.lock().handed.remove(&memory.id);
|
||||
if handed {
|
||||
if let Some(mappings) = &core.pool.mappings {
|
||||
mappings.unmap(memory.id);
|
||||
}
|
||||
}
|
||||
let device = &core.device;
|
||||
// SAFETY: no GPU work that uses the block is pending: the only GPU work on a block is its
|
||||
// zero fills, each waited for. The consumer's mappings are gone.
|
||||
// SAFETY: no GPU work that uses the block is pending: a command buffer or upload that uses it
|
||||
// holds it until it retires, and the fills of the block-maker thread are waited for. The
|
||||
// consumer's mappings are gone.
|
||||
unsafe {
|
||||
device.destroy_buffer(memory.buffer, None);
|
||||
device.free_memory(memory.memory, None);
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
//! Command queues: Metal's bound on a queue's uncompleted command buffers, and abandoning a queue.
|
||||
|
||||
use crate::command::CommandBuffer;
|
||||
use crate::counters::{Counters, Gauge};
|
||||
use crate::device::{lock, Device};
|
||||
use crate::error::{Error, Refusal};
|
||||
use std::sync::{Arc, Condvar, Mutex, PoisonError};
|
||||
|
||||
/// `MTLCommandQueue`: one FIFO on the submit thread. Every queue submits to the device's one
|
||||
/// `VkQueue`.
|
||||
///
|
||||
/// A cheap handle: clones share one queue. It holds the device.
|
||||
#[derive(Clone)]
|
||||
pub struct CommandQueue {
|
||||
inner: Arc<QueueInner>,
|
||||
device: Device,
|
||||
}
|
||||
|
||||
/// The queue itself: what its command buffers and the submit thread hold.
|
||||
pub(crate) struct QueueInner {
|
||||
max: u32,
|
||||
/// Command buffers made and not yet retired.
|
||||
count: Mutex<u32>,
|
||||
/// Signalled when one retires.
|
||||
room: Condvar,
|
||||
counters: Counters,
|
||||
}
|
||||
|
||||
impl Device {
|
||||
/// `newCommandQueueWithMaxCommandBufferCount:`; `newCommandQueue` is this call with 64.
|
||||
///
|
||||
/// Err: [`Refusal::NoCommandBuffers`] for a count of 0.
|
||||
pub fn new_command_queue(&self, max_command_buffer_count: u32) -> Result<CommandQueue, Error> {
|
||||
if max_command_buffer_count == 0 {
|
||||
return Err(Error::Refused(Refusal::NoCommandBuffers));
|
||||
}
|
||||
Ok(CommandQueue {
|
||||
inner: Arc::new(QueueInner {
|
||||
max: max_command_buffer_count,
|
||||
count: Mutex::new(0),
|
||||
room: Condvar::new(),
|
||||
counters: self.counters(),
|
||||
}),
|
||||
device: self.clone(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl CommandQueue {
|
||||
/// `commandBuffer`: waits, as Metal does, while the queue's maximum count of its command
|
||||
/// buffers are made and not yet completed. `commandBufferWithUnretainedReferences` is the same
|
||||
/// call: what a command buffer keeps is one reference per block it uses.
|
||||
///
|
||||
/// Err: [`Error::Quiesced`].
|
||||
pub fn command_buffer(&self) -> Result<CommandBuffer, Error> {
|
||||
let core = self.device.core();
|
||||
let mut count = lock(&self.inner.count);
|
||||
loop {
|
||||
if core.closed() {
|
||||
return Err(Error::Quiesced);
|
||||
}
|
||||
if *count < self.inner.max {
|
||||
break;
|
||||
}
|
||||
count = self
|
||||
.inner
|
||||
.room
|
||||
.wait(count)
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
}
|
||||
*count += 1;
|
||||
drop(count);
|
||||
self.inner.counters.rise(Gauge::CommandBuffers);
|
||||
Ok(CommandBuffer::new(
|
||||
Arc::clone(&self.inner),
|
||||
self.device.clone(),
|
||||
))
|
||||
}
|
||||
|
||||
/// No Metal counterpart: ends every command buffer of the queue the submit thread holds or has
|
||||
/// not yet submitted with [`CommandBufferError::NotRun`](crate::CommandBufferError::NotRun),
|
||||
/// and runs their handlers, as a Mac drops a dead process's held command buffers. One enqueued
|
||||
/// and not yet committed ends so at its commit. Segments already submitted still complete.
|
||||
/// The queue stays usable.
|
||||
pub fn abandon(&self) {
|
||||
let core = self.device.core();
|
||||
core.work.abandon(core, &self.inner);
|
||||
}
|
||||
|
||||
/// No Metal counterpart: the device the queue was made on.
|
||||
pub fn device(&self) -> &Device {
|
||||
&self.device
|
||||
}
|
||||
}
|
||||
|
||||
impl QueueInner {
|
||||
/// Whether `queue` is this queue.
|
||||
pub(crate) fn is(&self, queue: &QueueInner) -> bool {
|
||||
std::ptr::eq(self, queue)
|
||||
}
|
||||
|
||||
/// One of the queue's command buffers retired, or was dropped uncommitted.
|
||||
pub(crate) fn release(&self) {
|
||||
*lock(&self.count) -= 1;
|
||||
self.room.notify_one();
|
||||
self.counters.fall(Gauge::CommandBuffers);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
//! Recording: a command pool and the command buffers allocated from it, recycled from one Metal
|
||||
//! command buffer (or upload) to the next once its work has completed.
|
||||
|
||||
use crate::counters::{Counters, Metric};
|
||||
use crate::device::lock;
|
||||
use crate::error::Error;
|
||||
use ash::vk;
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// The most idle pools the device keeps; one given back past them is destroyed.
|
||||
const IDLE_MAX: usize = 64;
|
||||
|
||||
/// A command pool and the command buffers allocated from it so far, the first `used` of them
|
||||
/// recording or recorded.
|
||||
pub(crate) struct Recorder {
|
||||
pool: vk::CommandPool,
|
||||
buffers: Vec<vk::CommandBuffer>,
|
||||
used: usize,
|
||||
}
|
||||
|
||||
impl Recorder {
|
||||
/// The next command buffer, begun for one submission.
|
||||
pub(crate) fn next(&mut self, device: &ash::Device) -> Result<vk::CommandBuffer, Error> {
|
||||
if self.used == self.buffers.len() {
|
||||
let info = vk::CommandBufferAllocateInfo::default()
|
||||
.command_pool(self.pool)
|
||||
.level(vk::CommandBufferLevel::PRIMARY)
|
||||
.command_buffer_count(1);
|
||||
// SAFETY: the pool is this recorder's, used by one thread at a time.
|
||||
let buffer = unsafe { device.allocate_command_buffers(&info) }
|
||||
.map_err(Error::vulkan("vkAllocateCommandBuffers"))?[0];
|
||||
self.buffers.push(buffer);
|
||||
}
|
||||
let buffer = self.buffers[self.used];
|
||||
let begin = vk::CommandBufferBeginInfo::default()
|
||||
.flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT);
|
||||
// SAFETY: the buffer is in its initial state: allocated now or reset with its pool.
|
||||
unsafe { device.begin_command_buffer(buffer, &begin) }
|
||||
.map_err(Error::vulkan("vkBeginCommandBuffer"))?;
|
||||
self.used += 1;
|
||||
Ok(buffer)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
|
||||
/// Records the barrier every segment of a Metal command buffer begins with: every write earlier in
|
||||
/// submission order (earlier command buffers, earlier segments, zero fills) is made visible to
|
||||
/// every command after it.
|
||||
pub(crate) fn begin_barrier(device: &ash::Device, buffer: vk::CommandBuffer, counters: &Counters) {
|
||||
let barrier = [vk::MemoryBarrier2::default()
|
||||
.src_stage_mask(vk::PipelineStageFlags2::ALL_COMMANDS)
|
||||
.src_access_mask(vk::AccessFlags2::MEMORY_WRITE)
|
||||
.dst_stage_mask(vk::PipelineStageFlags2::ALL_COMMANDS)
|
||||
.dst_access_mask(vk::AccessFlags2::MEMORY_READ | vk::AccessFlags2::MEMORY_WRITE)];
|
||||
let dependency = vk::DependencyInfo::default().memory_barriers(&barrier);
|
||||
// SAFETY: the buffer is recording.
|
||||
unsafe { device.cmd_pipeline_barrier2(buffer, &dependency) };
|
||||
counters.count(Metric::Barriers);
|
||||
}
|
||||
|
||||
/// Ends a segment's command buffer, after the barrier that makes its writes visible to the host:
|
||||
/// Shared memory reads the GPU's writes once the command buffer completes or the host sees an
|
||||
/// event it signals.
|
||||
pub(crate) fn end(
|
||||
device: &ash::Device,
|
||||
buffer: vk::CommandBuffer,
|
||||
counters: &Counters,
|
||||
) -> Result<(), Error> {
|
||||
let barrier = [vk::MemoryBarrier2::default()
|
||||
.src_stage_mask(vk::PipelineStageFlags2::ALL_COMMANDS)
|
||||
.src_access_mask(vk::AccessFlags2::MEMORY_WRITE)
|
||||
.dst_stage_mask(vk::PipelineStageFlags2::HOST)
|
||||
.dst_access_mask(vk::AccessFlags2::HOST_READ)];
|
||||
let dependency = vk::DependencyInfo::default().memory_barriers(&barrier);
|
||||
// SAFETY: the buffer is recording.
|
||||
unsafe { device.cmd_pipeline_barrier2(buffer, &dependency) };
|
||||
counters.count(Metric::Barriers);
|
||||
// SAFETY: as above.
|
||||
unsafe { device.end_command_buffer(buffer) }.map_err(Error::vulkan("vkEndCommandBuffer"))
|
||||
}
|
||||
|
||||
/// The device's idle recorders.
|
||||
pub(crate) struct Recorders {
|
||||
family: u32,
|
||||
idle: Mutex<Vec<Recorder>>,
|
||||
}
|
||||
|
||||
impl Recorders {
|
||||
pub(crate) fn new(family: u32) -> Recorders {
|
||||
Recorders {
|
||||
family,
|
||||
idle: Mutex::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// An idle recorder, or a new one.
|
||||
pub(crate) fn take(&self, device: &ash::Device) -> Result<Recorder, Error> {
|
||||
if let Some(recorder) = lock(&self.idle).pop() {
|
||||
return Ok(recorder);
|
||||
}
|
||||
let info = vk::CommandPoolCreateInfo::default()
|
||||
.flags(vk::CommandPoolCreateFlags::TRANSIENT)
|
||||
.queue_family_index(self.family);
|
||||
// SAFETY: the device is live.
|
||||
let pool = unsafe { device.create_command_pool(&info, None) }
|
||||
.map_err(Error::vulkan("vkCreateCommandPool"))?;
|
||||
Ok(Recorder {
|
||||
pool,
|
||||
buffers: Vec::new(),
|
||||
used: 0,
|
||||
})
|
||||
}
|
||||
|
||||
/// Takes back a recorder whose work has completed, or that never submitted: its pool is reset
|
||||
/// for the next one, or destroyed past [`IDLE_MAX`].
|
||||
pub(crate) fn give_back(&self, device: &ash::Device, mut recorder: Recorder) {
|
||||
// SAFETY: no command buffer of the pool is pending. A failed reset (a lost device) leaves
|
||||
// the pool to be destroyed.
|
||||
let reset =
|
||||
unsafe { device.reset_command_pool(recorder.pool, vk::CommandPoolResetFlags::empty()) };
|
||||
let mut idle = lock(&self.idle);
|
||||
if reset.is_ok() && idle.len() < IDLE_MAX {
|
||||
recorder.used = 0;
|
||||
idle.push(recorder);
|
||||
} else {
|
||||
drop(idle);
|
||||
destroy(device, recorder);
|
||||
}
|
||||
}
|
||||
|
||||
/// At teardown: destroys every idle recorder.
|
||||
pub(crate) fn destroy_all(&mut self, device: &ash::Device) {
|
||||
let idle = self
|
||||
.idle
|
||||
.get_mut()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
for recorder in idle.drain(..) {
|
||||
destroy(device, recorder);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Destroys a recorder's pool, which frees its command buffers.
|
||||
pub(crate) fn destroy(device: &ash::Device, recorder: Recorder) {
|
||||
// SAFETY: no command buffer of the pool is pending: the device is idle, or the recorder's work
|
||||
// completed.
|
||||
unsafe { device.destroy_command_pool(recorder.pool, None) };
|
||||
}
|
||||
@@ -0,0 +1,524 @@
|
||||
//! The submit thread: each queue's FIFO of command buffers, the holds at event waits, the upload
|
||||
//! that goes ahead of later commits, and the batches it passes to `vkQueueSubmit2`.
|
||||
|
||||
use crate::command::{CbInner, CommandBufferError, Pending, Segment};
|
||||
use crate::complete;
|
||||
use crate::counters::Metric;
|
||||
use crate::device::{lock, Core};
|
||||
use crate::error::Error;
|
||||
use crate::event::EventInner;
|
||||
use crate::fill;
|
||||
use crate::memory::Block;
|
||||
use crate::queue::QueueInner;
|
||||
use crate::record::Recorder;
|
||||
use ash::vk;
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
|
||||
|
||||
/// The submit side: the FIFOs and the upload, and the submit thread's wake-up.
|
||||
pub(crate) struct Work {
|
||||
state: Mutex<WorkState>,
|
||||
changed: Condvar,
|
||||
}
|
||||
|
||||
pub(crate) struct WorkState {
|
||||
/// The queues with command buffers enqueued or committed and not yet fully submitted.
|
||||
fifos: Vec<Fifo>,
|
||||
/// The next command buffer's place in the commit order.
|
||||
next_seq: u64,
|
||||
/// The progress value of the last batch.
|
||||
progress: u64,
|
||||
/// Zero fills recorded and not yet submitted.
|
||||
upload: Option<Upload>,
|
||||
/// Something changed that may let a held segment go.
|
||||
dirty: bool,
|
||||
/// The submit thread is to end: it submits what is ready, then ends what is held.
|
||||
stop: bool,
|
||||
/// Quiesced or torn down: commits and uploads are refused.
|
||||
closed: bool,
|
||||
lost: bool,
|
||||
}
|
||||
|
||||
struct Fifo {
|
||||
queue: Arc<QueueInner>,
|
||||
entries: VecDeque<Entry>,
|
||||
}
|
||||
|
||||
struct Entry {
|
||||
cb: Arc<CbInner>,
|
||||
/// None while enqueued and not committed.
|
||||
pending: Option<Pending>,
|
||||
}
|
||||
|
||||
/// Zero fills recorded into one command buffer, submitted ahead of everything in the next batch,
|
||||
/// which holds every block they fill until it retires.
|
||||
pub(crate) struct Upload {
|
||||
pub(crate) recorder: Recorder,
|
||||
command: vk::CommandBuffer,
|
||||
pub(crate) blocks: Vec<Arc<Block>>,
|
||||
}
|
||||
|
||||
/// What one `vkQueueSubmit2` submits.
|
||||
struct Batch {
|
||||
value: u64,
|
||||
upload: Option<Upload>,
|
||||
segments: Vec<Staged>,
|
||||
/// Command buffers whose last segment is in the batch.
|
||||
finished: Vec<(Arc<CbInner>, Pending)>,
|
||||
/// Events the batch signals that the completion thread is not yet watching.
|
||||
watch: Vec<Arc<EventInner>>,
|
||||
}
|
||||
|
||||
/// One segment's submit info.
|
||||
#[derive(Default)]
|
||||
struct Staged {
|
||||
waits: Vec<vk::SemaphoreSubmitInfo<'static>>,
|
||||
command: Option<vk::CommandBufferSubmitInfo<'static>>,
|
||||
signals: Vec<vk::SemaphoreSubmitInfo<'static>>,
|
||||
}
|
||||
|
||||
/// An ended command buffer, with how it ended.
|
||||
pub(crate) type Ended = (Arc<CbInner>, Pending, CommandBufferError);
|
||||
|
||||
impl Work {
|
||||
pub(crate) fn new() -> Work {
|
||||
Work {
|
||||
state: Mutex::new(WorkState {
|
||||
fifos: Vec::new(),
|
||||
next_seq: 0,
|
||||
progress: 0,
|
||||
upload: None,
|
||||
dirty: false,
|
||||
stop: false,
|
||||
closed: false,
|
||||
lost: false,
|
||||
}),
|
||||
changed: Condvar::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn lock(&self) -> MutexGuard<'_, WorkState> {
|
||||
lock(&self.state)
|
||||
}
|
||||
|
||||
/// Wakes the submit thread after a change [`WorkState`] recorded.
|
||||
pub(crate) fn wake(&self) {
|
||||
self.changed.notify_one();
|
||||
}
|
||||
|
||||
/// A host value rose: held segments may go.
|
||||
pub(crate) fn poke(&self) {
|
||||
self.lock().dirty = true;
|
||||
self.wake();
|
||||
}
|
||||
|
||||
/// Records the zero fill of `offset..end` of `block` into the upload, which goes ahead of
|
||||
/// every later commit.
|
||||
///
|
||||
/// Err: [`Error::Quiesced`]; [`Error::Vulkan`] where a command pool or buffer cannot be made.
|
||||
pub(crate) fn zero(
|
||||
&self,
|
||||
core: &Core,
|
||||
block: &Arc<Block>,
|
||||
offset: u64,
|
||||
end: u64,
|
||||
) -> Result<(), Error> {
|
||||
let mut state = self.lock();
|
||||
if state.closed {
|
||||
return Err(Error::Quiesced);
|
||||
}
|
||||
let device = &core.device;
|
||||
let upload = match state.upload.take() {
|
||||
Some(upload) => upload,
|
||||
None => {
|
||||
let mut recorder = core.recorders.take(device)?;
|
||||
match recorder.next(device) {
|
||||
Ok(command) => Upload {
|
||||
recorder,
|
||||
command,
|
||||
blocks: Vec::new(),
|
||||
},
|
||||
Err(error) => {
|
||||
core.recorders.give_back(device, recorder);
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
let upload = state.upload.insert(upload);
|
||||
// SAFETY: the upload's command buffer is recording, under the lock; the block's buffer has
|
||||
// every usage, and `offset..end` lies in it.
|
||||
unsafe {
|
||||
fill::record(
|
||||
device,
|
||||
upload.command,
|
||||
core.filler.zeros(),
|
||||
block.memory.buffer,
|
||||
offset,
|
||||
end,
|
||||
)
|
||||
};
|
||||
if !upload.blocks.iter().any(|held| Arc::ptr_eq(held, block)) {
|
||||
upload.blocks.push(Arc::clone(block));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Ends `queue`'s held and unsubmitted command buffers with `NotRun`.
|
||||
pub(crate) fn abandon(&self, core: &Core, queue: &QueueInner) {
|
||||
let ended = {
|
||||
let mut state = self.lock();
|
||||
match state.fifos.iter().position(|fifo| fifo.queue.is(queue)) {
|
||||
Some(index) => {
|
||||
let fifo = state.fifos.swap_remove(index);
|
||||
end(fifo.entries, |_| CommandBufferError::NotRun)
|
||||
}
|
||||
None => Vec::new(),
|
||||
}
|
||||
};
|
||||
core.done.end_all(core, ended);
|
||||
}
|
||||
|
||||
/// Closes the device to commits and uploads, and tells the submit thread to end.
|
||||
pub(crate) fn stop(&self) {
|
||||
let mut state = self.lock();
|
||||
state.closed = true;
|
||||
state.stop = true;
|
||||
state.dirty = true;
|
||||
self.wake();
|
||||
}
|
||||
|
||||
/// At a loss: the submit thread ends everything it holds.
|
||||
pub(crate) fn lose(&self) {
|
||||
let mut state = self.lock();
|
||||
state.lost = true;
|
||||
state.dirty = true;
|
||||
self.wake();
|
||||
}
|
||||
|
||||
/// The progress value of the last batch.
|
||||
pub(crate) fn progress(&self) -> u64 {
|
||||
self.lock().progress
|
||||
}
|
||||
}
|
||||
|
||||
impl WorkState {
|
||||
pub(crate) fn closed(&self) -> bool {
|
||||
self.closed
|
||||
}
|
||||
|
||||
pub(crate) fn lost(&self) -> bool {
|
||||
self.lost
|
||||
}
|
||||
|
||||
/// The next place in the commit order.
|
||||
pub(crate) fn seq(&mut self) -> u64 {
|
||||
self.next_seq += 1;
|
||||
self.next_seq
|
||||
}
|
||||
|
||||
fn fifo(&mut self, queue: &Arc<QueueInner>) -> &mut Fifo {
|
||||
let index = match self.fifos.iter().position(|fifo| fifo.queue.is(queue)) {
|
||||
Some(index) => index,
|
||||
None => {
|
||||
self.fifos.push(Fifo {
|
||||
queue: Arc::clone(queue),
|
||||
entries: VecDeque::new(),
|
||||
});
|
||||
self.fifos.len() - 1
|
||||
}
|
||||
};
|
||||
&mut self.fifos[index]
|
||||
}
|
||||
|
||||
/// Takes `cb`'s place in its queue's FIFO.
|
||||
pub(crate) fn enqueue(&mut self, cb: &Arc<CbInner>) {
|
||||
self.fifo(&cb.queue).entries.push_back(Entry {
|
||||
cb: Arc::clone(cb),
|
||||
pending: None,
|
||||
});
|
||||
}
|
||||
|
||||
/// Hands `cb` to the submit thread: at its place where it was enqueued, else at its queue's
|
||||
/// end.
|
||||
pub(crate) fn commit(&mut self, cb: &Arc<CbInner>, pending: Pending) {
|
||||
self.dirty = true;
|
||||
let fifo = self.fifo(&cb.queue);
|
||||
match fifo
|
||||
.entries
|
||||
.iter_mut()
|
||||
.find(|entry| Arc::ptr_eq(&entry.cb, cb))
|
||||
{
|
||||
Some(entry) => entry.pending = Some(pending),
|
||||
None => fifo.entries.push_back(Entry {
|
||||
cb: Arc::clone(cb),
|
||||
pending: Some(pending),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// The FIFO whose head goes next: of the committed heads whose next segment is ready, the
|
||||
/// earliest committed.
|
||||
fn next_ready(&self) -> Option<usize> {
|
||||
let mut best: Option<(usize, u64)> = None;
|
||||
for (index, fifo) in self.fifos.iter().enumerate() {
|
||||
let Some(Entry {
|
||||
pending: Some(pending),
|
||||
..
|
||||
}) = fifo.entries.front()
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if best.is_some_and(|(_, seq)| seq < pending.seq) {
|
||||
continue;
|
||||
}
|
||||
if ready(&pending.gpu.segments[pending.next]) {
|
||||
best = Some((index, pending.seq));
|
||||
}
|
||||
}
|
||||
best.map(|(index, _)| index)
|
||||
}
|
||||
|
||||
/// Takes every ready segment, in commit order, into one batch; None where none is ready.
|
||||
fn stage(&mut self) -> Option<Batch> {
|
||||
let value = self.progress + 1;
|
||||
let mut segments = Vec::new();
|
||||
let mut finished = Vec::new();
|
||||
let mut watch = Vec::new();
|
||||
while let Some(index) = self.next_ready() {
|
||||
let fifo = &mut self.fifos[index];
|
||||
let Some(Entry {
|
||||
pending: Some(pending),
|
||||
..
|
||||
}) = fifo.entries.front_mut()
|
||||
else {
|
||||
break;
|
||||
};
|
||||
segments.push(stage(&pending.gpu.segments[pending.next], &mut watch));
|
||||
pending.next += 1;
|
||||
pending.value = value;
|
||||
if pending.next == pending.gpu.segments.len() {
|
||||
if let Some(Entry {
|
||||
cb,
|
||||
pending: Some(pending),
|
||||
}) = fifo.entries.pop_front()
|
||||
{
|
||||
finished.push((cb, pending));
|
||||
}
|
||||
if fifo.entries.is_empty() {
|
||||
self.fifos.swap_remove(index);
|
||||
}
|
||||
}
|
||||
}
|
||||
if segments.is_empty() {
|
||||
return None;
|
||||
}
|
||||
self.progress = value;
|
||||
Some(Batch {
|
||||
value,
|
||||
upload: self.upload.take(),
|
||||
segments,
|
||||
finished,
|
||||
watch,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether every wait of `segment` is met by the host's value or by a submitted signal.
|
||||
fn ready(segment: &Segment) -> bool {
|
||||
segment.waits.iter().all(|(event, value)| {
|
||||
let state = lock(&event.state);
|
||||
state.floor >= *value || state.submitted >= *value
|
||||
})
|
||||
}
|
||||
|
||||
/// A ready segment's submit info. A wait the host's value meets submits no semaphore wait; a
|
||||
/// signal not above the highest value submitted or set is left out, so the semaphore only rises.
|
||||
fn stage(segment: &Segment, watch: &mut Vec<Arc<EventInner>>) -> Staged {
|
||||
let mut staged = Staged {
|
||||
command: segment
|
||||
.command
|
||||
.map(|command| vk::CommandBufferSubmitInfo::default().command_buffer(command)),
|
||||
..Staged::default()
|
||||
};
|
||||
for (event, value) in &segment.waits {
|
||||
if lock(&event.state).floor >= *value {
|
||||
continue;
|
||||
}
|
||||
staged.waits.push(
|
||||
vk::SemaphoreSubmitInfo::default()
|
||||
.semaphore(event.semaphore)
|
||||
.value(*value)
|
||||
.stage_mask(vk::PipelineStageFlags2::ALL_COMMANDS),
|
||||
);
|
||||
}
|
||||
for (event, value) in &segment.signals {
|
||||
let mut state = lock(&event.state);
|
||||
if *value <= state.submitted.max(state.floor) {
|
||||
continue;
|
||||
}
|
||||
state.submitted = *value;
|
||||
state.pending.push_back(*value);
|
||||
if !state.watched {
|
||||
state.watched = true;
|
||||
watch.push(Arc::clone(event));
|
||||
}
|
||||
staged.signals.push(
|
||||
vk::SemaphoreSubmitInfo::default()
|
||||
.semaphore(event.semaphore)
|
||||
.value(*value)
|
||||
.stage_mask(vk::PipelineStageFlags2::ALL_COMMANDS),
|
||||
);
|
||||
}
|
||||
staged
|
||||
}
|
||||
|
||||
/// Ends FIFO entries: a committed one now, one not yet committed at its commit; `error` answers
|
||||
/// for each, with its pending part where it is committed.
|
||||
fn end(
|
||||
entries: VecDeque<Entry>,
|
||||
error: impl Fn(Option<&Pending>) -> CommandBufferError,
|
||||
) -> Vec<Ended> {
|
||||
let mut ended = Vec::new();
|
||||
for Entry { cb, pending } in entries {
|
||||
match pending {
|
||||
Some(pending) => {
|
||||
let error = error(Some(&pending));
|
||||
ended.push((cb, pending, error));
|
||||
}
|
||||
None => cb.end_uncommitted(error(None)),
|
||||
}
|
||||
}
|
||||
ended
|
||||
}
|
||||
|
||||
/// The submit thread, until it is stopped.
|
||||
pub(crate) fn run(core: Arc<Core>) {
|
||||
let work = &core.work;
|
||||
let mut state = work.lock();
|
||||
loop {
|
||||
if state.lost {
|
||||
let ended = drain(&mut state, |pending| CommandBufferError::DeviceLost {
|
||||
in_flight: pending.is_some_and(|pending| pending.value > 0),
|
||||
});
|
||||
let upload = state.upload.take();
|
||||
drop(state);
|
||||
if let Some(upload) = upload {
|
||||
upload.retire(&core);
|
||||
}
|
||||
core.done.end_all(&core, ended);
|
||||
state = work.lock();
|
||||
} else if let Some(batch) = state.stage() {
|
||||
drop(state);
|
||||
submit(&core, batch);
|
||||
state = work.lock();
|
||||
continue;
|
||||
}
|
||||
if state.stop {
|
||||
let ended = drain(&mut state, |_| CommandBufferError::NotRun);
|
||||
let upload = state.upload.take();
|
||||
drop(state);
|
||||
if let Some(upload) = upload {
|
||||
upload.retire(&core);
|
||||
}
|
||||
core.done.end_all(&core, ended);
|
||||
return;
|
||||
}
|
||||
while !state.dirty {
|
||||
state = work
|
||||
.changed
|
||||
.wait(state)
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
}
|
||||
state.dirty = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends every FIFO's entries.
|
||||
fn drain(
|
||||
state: &mut WorkState,
|
||||
error: impl Fn(Option<&Pending>) -> CommandBufferError,
|
||||
) -> Vec<Ended> {
|
||||
state
|
||||
.fifos
|
||||
.drain(..)
|
||||
.flat_map(|fifo| end(fifo.entries, &error))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Submits a batch: the upload first, then each segment in order, the last signalling the
|
||||
/// progress value. Whatever was passed to `vkQueueSubmit2` goes to the completion thread as in
|
||||
/// flight; a failed submission is taken as a loss.
|
||||
fn submit(core: &Core, batch: Batch) {
|
||||
let Batch {
|
||||
value,
|
||||
upload,
|
||||
mut segments,
|
||||
finished,
|
||||
watch,
|
||||
} = batch;
|
||||
let device = &core.device;
|
||||
// SAFETY: the upload's command buffer was recording under the work lock, which `stage` took
|
||||
// it out under.
|
||||
let mut ok = upload
|
||||
.as_ref()
|
||||
.is_none_or(|upload| unsafe { device.end_command_buffer(upload.command) }.is_ok());
|
||||
if let Some(upload) = &upload {
|
||||
segments.insert(
|
||||
0,
|
||||
Staged {
|
||||
command: Some(
|
||||
vk::CommandBufferSubmitInfo::default().command_buffer(upload.command),
|
||||
),
|
||||
..Staged::default()
|
||||
},
|
||||
);
|
||||
}
|
||||
segments.retain(|staged| {
|
||||
staged.command.is_some() || !staged.waits.is_empty() || !staged.signals.is_empty()
|
||||
});
|
||||
let progress = vk::SemaphoreSubmitInfo::default()
|
||||
.semaphore(core.done.progress)
|
||||
.value(value)
|
||||
.stage_mask(vk::PipelineStageFlags2::ALL_COMMANDS);
|
||||
match segments.last_mut() {
|
||||
Some(last) => last.signals.push(progress),
|
||||
None => segments.push(Staged {
|
||||
signals: vec![progress],
|
||||
..Staged::default()
|
||||
}),
|
||||
}
|
||||
let infos: Vec<vk::SubmitInfo2<'_>> = segments
|
||||
.iter()
|
||||
.map(|staged| {
|
||||
vk::SubmitInfo2::default()
|
||||
.wait_semaphore_infos(&staged.waits)
|
||||
.command_buffer_infos(staged.command.as_slice())
|
||||
.signal_semaphore_infos(&staged.signals)
|
||||
})
|
||||
.collect();
|
||||
if ok {
|
||||
let queue = lock(&core.queues.runtime);
|
||||
// SAFETY: every command buffer is executable and in no other pending submission; every
|
||||
// wait is on a signal submitted earlier, and every signal raises its semaphore; the queue
|
||||
// is held.
|
||||
ok = unsafe { device.queue_submit2(*queue, &infos, vk::Fence::null()) }.is_ok();
|
||||
drop(queue);
|
||||
core.counters.count(Metric::Submissions);
|
||||
}
|
||||
if !ok {
|
||||
complete::lose(core);
|
||||
}
|
||||
for (cb, _) in &finished {
|
||||
cb.scheduled();
|
||||
}
|
||||
core.done.submitted(core, value, upload, finished, watch);
|
||||
}
|
||||
|
||||
impl Upload {
|
||||
/// Recycles the upload's recorder and gives up its blocks: once its submission completed, or
|
||||
/// where it never went.
|
||||
pub(crate) fn retire(self, core: &Core) {
|
||||
core.recorders.give_back(&core.device, self.recorder);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,866 @@
|
||||
//! Command queues, command buffers and events, under a device cfg on every device of the cfg's
|
||||
//! kind: states, handlers and refusals; holds per segment; the host floor; host values racing GPU
|
||||
//! signals; listeners; abandon; quiesce, also in an `exit()` handler; teardown from a handler; a
|
||||
//! loss; and a released block kept until its last command buffer retires.
|
||||
|
||||
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
|
||||
mod on_device {
|
||||
use crate::device::lock;
|
||||
use crate::tests::devices_of_the_cfgs_kind;
|
||||
use crate::{
|
||||
BlockId, BlockMappings, Buffer, CommandBuffer, CommandBufferError, CommandBufferStatus,
|
||||
CommandQueue, Device, DeviceOptions, Error, Gauges, Instance, MemoryClass, Refusal,
|
||||
SharedEvent, BLOCK_LEN,
|
||||
};
|
||||
use ash::vk;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc;
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
use std::thread::{self, JoinHandle};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// How long a test waits for what must happen.
|
||||
const PATIENCE: Duration = Duration::from_secs(60);
|
||||
|
||||
fn within(what: &str, mut done: impl FnMut() -> bool) {
|
||||
let deadline = Instant::now() + PATIENCE;
|
||||
while !done() {
|
||||
assert!(Instant::now() < deadline, "timed out waiting for {what}");
|
||||
thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
}
|
||||
|
||||
/// The matrix's leak records: each kind's live count once the device is gone.
|
||||
fn print_gauges_at_drop(test: &str, gauges: Gauges) {
|
||||
for (kind, value) in [
|
||||
("buffers", gauges.buffers),
|
||||
("blocks", gauges.blocks),
|
||||
("command_buffers", gauges.command_buffers),
|
||||
("events", gauges.events),
|
||||
] {
|
||||
println!("M2V-MATRIX gauge {test}/{kind}@drop {value}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens each device of the cfg's kind with `options`, runs `body`, which drops the device,
|
||||
/// and checks that every gauge reaches zero.
|
||||
fn each_device(test: &str, mut body: impl FnMut(&str, &Instance, Device)) {
|
||||
let instance = Instance::new(&[]).expect("an instance at the floor");
|
||||
let devices = devices_of_the_cfgs_kind(&instance);
|
||||
assert!(!devices.is_empty(), "no device of this cfg's kind");
|
||||
for (name, physical) in &devices {
|
||||
let device = Device::new(physical, DeviceOptions::default())
|
||||
.unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
let counters = device.counters();
|
||||
body(name, &instance, device);
|
||||
within("the teardown", || counters.gauges() == Gauges::default());
|
||||
print_gauges_at_drop(test, counters.gauges());
|
||||
}
|
||||
}
|
||||
|
||||
/// Buffers of 256 bytes in one Shared block, each zeroed.
|
||||
struct Arena {
|
||||
device: Device,
|
||||
block: BlockId,
|
||||
next: u64,
|
||||
}
|
||||
|
||||
impl Arena {
|
||||
fn new(device: &Device) -> Arena {
|
||||
let block = device
|
||||
.take_block(MemoryClass::Shared, 1)
|
||||
.expect("a Shared block");
|
||||
Arena {
|
||||
device: device.clone(),
|
||||
block: block.id,
|
||||
next: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn buffer(&mut self) -> Buffer {
|
||||
let buffer = self
|
||||
.device
|
||||
.new_buffer(self.block, self.next, 256, true)
|
||||
.expect("a buffer");
|
||||
self.next += 256;
|
||||
buffer
|
||||
}
|
||||
}
|
||||
|
||||
/// Records a fill of `buffer` with `word`, keeping its block.
|
||||
fn fill(command_buffer: &CommandBuffer, buffer: &Buffer, word: u32) {
|
||||
let target = buffer.block_for_test().memory.buffer;
|
||||
let (offset, size) = (buffer.offset(), buffer.length());
|
||||
command_buffer
|
||||
.record_for_test(&[buffer], |device, command| {
|
||||
// SAFETY: the command buffer is recording; the range is the buffer's, in whole
|
||||
// words.
|
||||
unsafe { device.cmd_fill_buffer(command, target, offset, size, word) };
|
||||
})
|
||||
.expect("a fill");
|
||||
}
|
||||
|
||||
/// A buffer's first word, as the host reads it.
|
||||
fn word(buffer: &Buffer) -> u32 {
|
||||
let contents = buffer.contents().expect("a Shared buffer");
|
||||
// SAFETY: the buffer is alive and at least 4 bytes long.
|
||||
unsafe { contents.cast::<u32>().as_ptr().read_volatile() }
|
||||
}
|
||||
|
||||
/// Waits for a command buffer to complete or end, and for its handlers.
|
||||
fn finished(name: &str, command_buffer: &CommandBuffer) {
|
||||
within(name, || {
|
||||
matches!(
|
||||
command_buffer.status(),
|
||||
CommandBufferStatus::Completed | CommandBufferStatus::Error
|
||||
)
|
||||
});
|
||||
command_buffer.wait_until_completed();
|
||||
}
|
||||
|
||||
/// A log the handlers write to.
|
||||
#[derive(Clone, Default)]
|
||||
struct Log(Arc<Mutex<Vec<String>>>);
|
||||
|
||||
impl Log {
|
||||
fn push(&self, line: impl Into<String>) {
|
||||
lock(&self.0).push(line.into());
|
||||
}
|
||||
|
||||
fn lines(&self) -> Vec<String> {
|
||||
lock(&self.0).clone()
|
||||
}
|
||||
|
||||
/// Adds handlers that log `label`'s scheduling and completion, with the status each sees.
|
||||
fn handlers(&self, label: &str, command_buffer: &CommandBuffer) {
|
||||
let (log, scheduled) = (self.clone(), format!("{label} scheduled"));
|
||||
command_buffer
|
||||
.add_scheduled_handler(move |cb| log.push(format!("{scheduled} {:?}", cb.status())))
|
||||
.expect("a scheduled handler");
|
||||
let (log, completed) = (self.clone(), format!("{label} completed"));
|
||||
command_buffer
|
||||
.add_completed_handler(move |cb| {
|
||||
log.push(format!("{completed} {:?} {:?}", cb.status(), cb.error()))
|
||||
})
|
||||
.expect("a completed handler");
|
||||
}
|
||||
}
|
||||
|
||||
/// A command buffer goes through Metal's states, runs its handlers in order on the completion
|
||||
/// thread, and runs its commands; a queue keeps enqueue order and bounds its command buffers;
|
||||
/// Metal's refusals.
|
||||
#[test]
|
||||
fn every_device_runs_command_buffers_through_their_states_and_handlers() {
|
||||
each_device("command_states", |name, instance, device| {
|
||||
let mut arena = Arena::new(&device);
|
||||
let (a, b) = (arena.buffer(), arena.buffer());
|
||||
let queue = device.new_command_queue(64).expect("a queue");
|
||||
let log = Log::default();
|
||||
let before = device.counters().metrics();
|
||||
|
||||
let first = queue.command_buffer().expect("a command buffer");
|
||||
assert_eq!(first.status(), CommandBufferStatus::NotEnqueued);
|
||||
fill(&first, &a, 0x11);
|
||||
log.handlers("first", &first);
|
||||
first.enqueue().expect("an enqueue");
|
||||
first.enqueue().expect("a second enqueue changes nothing");
|
||||
assert_eq!(first.status(), CommandBufferStatus::Enqueued);
|
||||
// Committed first, the second waits behind the first, enqueued before it.
|
||||
let second = queue.command_buffer().expect("a command buffer");
|
||||
fill(&second, &b, 0x22);
|
||||
log.handlers("second", &second);
|
||||
second.commit().expect("a commit");
|
||||
thread::sleep(Duration::from_millis(50));
|
||||
assert_eq!(second.status(), CommandBufferStatus::Committed, "{name}");
|
||||
first.commit().expect("a commit");
|
||||
finished(name, &second);
|
||||
assert_eq!(first.status(), CommandBufferStatus::Completed, "{name}");
|
||||
assert_eq!(
|
||||
(second.status(), second.error()),
|
||||
(CommandBufferStatus::Completed, None)
|
||||
);
|
||||
assert_eq!((word(&a), word(&b)), (0x11, 0x22), "{name}");
|
||||
let lines = log.lines();
|
||||
let at = |line: &str| {
|
||||
lines
|
||||
.iter()
|
||||
.position(|logged| logged == line)
|
||||
.unwrap_or_else(|| panic!("{name}: no {line:?} in {lines:?}"))
|
||||
};
|
||||
assert_eq!(lines.len(), 4, "{name}: {lines:?}");
|
||||
assert!(at("first scheduled Scheduled") < at("first completed Completed None"));
|
||||
assert!(at("second scheduled Scheduled") < at("second completed Completed None"));
|
||||
assert!(at("first completed Completed None") < at("second completed Completed None"));
|
||||
let after = device.counters().metrics();
|
||||
// Each segment with commands has two barriers: one at its start, one at its end.
|
||||
assert_eq!(after.barriers - before.barriers, 4, "{name}");
|
||||
assert!(after.submissions > before.submissions, "{name}");
|
||||
|
||||
// After commit, Metal refuses.
|
||||
let refused = |result: Result<(), Error>| {
|
||||
matches!(result, Err(Error::Refused(Refusal::Committed)))
|
||||
};
|
||||
let event = device.new_event().expect("an event");
|
||||
assert!(refused(first.commit()), "{name}");
|
||||
assert!(refused(first.enqueue()), "{name}");
|
||||
assert!(refused(first.add_completed_handler(|_| {})), "{name}");
|
||||
assert!(refused(first.add_scheduled_handler(|_| {})), "{name}");
|
||||
assert!(refused(first.encode_signal_event(&event, 1)), "{name}");
|
||||
assert!(refused(first.encode_wait_for_event(&event, 1)), "{name}");
|
||||
assert!(matches!(
|
||||
device.new_command_queue(0),
|
||||
Err(Error::Refused(Refusal::NoCommandBuffers))
|
||||
));
|
||||
|
||||
// A queue of one: the next command buffer waits until the first retires.
|
||||
let single = device.new_command_queue(1).expect("a queue");
|
||||
let held = single.command_buffer().expect("a command buffer");
|
||||
let (sent, received) = mpsc::channel();
|
||||
let waiter = {
|
||||
let single = single.clone();
|
||||
thread::spawn(move || {
|
||||
let next = single.command_buffer().expect("a command buffer");
|
||||
sent.send(()).expect("a send");
|
||||
next
|
||||
})
|
||||
};
|
||||
assert!(received.recv_timeout(Duration::from_millis(50)).is_err());
|
||||
held.commit().expect("a commit");
|
||||
received.recv_timeout(PATIENCE).expect("room in the queue");
|
||||
drop(waiter.join().expect("the waiter"));
|
||||
|
||||
// Another device's event is refused.
|
||||
let other = Device::new(&physical_of(instance, &device), DeviceOptions::default())
|
||||
.expect("a second device");
|
||||
let foreign = other.new_event().expect("an event");
|
||||
let local = queue.command_buffer().expect("a command buffer");
|
||||
for result in [
|
||||
local.encode_signal_event(&foreign, 1),
|
||||
local.encode_wait_for_event(&foreign, 1),
|
||||
] {
|
||||
assert!(matches!(result, Err(Error::Refused(Refusal::OtherDevice))));
|
||||
}
|
||||
drop((local, foreign, other));
|
||||
drop((a, b, arena, queue, single, event, device));
|
||||
});
|
||||
}
|
||||
|
||||
/// The physical device a device was opened on, for a second device.
|
||||
fn physical_of(instance: &Instance, device: &Device) -> crate::PhysicalDevice {
|
||||
let raw = device.raw().physical_device;
|
||||
instance
|
||||
.physical_devices()
|
||||
.expect("the physical devices")
|
||||
.into_iter()
|
||||
.find(|physical| physical.raw() == raw)
|
||||
.expect("the device's physical device")
|
||||
}
|
||||
|
||||
/// A command buffer that signals E, waits for F and works on: the host sees E and the work
|
||||
/// before it while the rest is held, and sets F, and then the rest runs. Another queue goes
|
||||
/// on meanwhile; the same queue waits behind it.
|
||||
#[test]
|
||||
fn every_device_holds_a_command_buffer_from_its_waiting_segment_on() {
|
||||
each_device("command_holds", |name, _, device| {
|
||||
let mut arena = Arena::new(&device);
|
||||
let (a, b, c, d) = (
|
||||
arena.buffer(),
|
||||
arena.buffer(),
|
||||
arena.buffer(),
|
||||
arena.buffer(),
|
||||
);
|
||||
let (e, f) = (shared_event(&device), shared_event(&device));
|
||||
let (queue, other) = (queue(&device), queue(&device));
|
||||
|
||||
let held = queue.command_buffer().expect("a command buffer");
|
||||
fill(&held, &a, 1);
|
||||
held.encode_signal_event(e.as_event(), 1).expect("a signal");
|
||||
held.encode_wait_for_event(f.as_event(), 1).expect("a wait");
|
||||
fill(&held, &b, 2);
|
||||
held.commit().expect("a commit");
|
||||
let behind = queue.command_buffer().expect("a command buffer");
|
||||
fill(&behind, &d, 4);
|
||||
behind.commit().expect("a commit");
|
||||
|
||||
assert!(
|
||||
e.wait_until_signaled_value(1, PATIENCE),
|
||||
"{name}: E reached"
|
||||
);
|
||||
assert_eq!(e.signaled_value(), 1);
|
||||
assert_eq!(word(&a), 1, "{name}: the work before the signal");
|
||||
let beside = other.command_buffer().expect("a command buffer");
|
||||
fill(&beside, &c, 3);
|
||||
beside.commit().expect("a commit");
|
||||
finished(name, &beside);
|
||||
assert_eq!(word(&c), 3, "{name}: another queue goes on");
|
||||
assert_eq!(held.status(), CommandBufferStatus::Committed, "{name}");
|
||||
assert_eq!(behind.status(), CommandBufferStatus::Committed, "{name}");
|
||||
assert_eq!((word(&b), word(&d)), (0, 0), "{name}: held");
|
||||
|
||||
f.set_signaled_value(1);
|
||||
finished(name, &held);
|
||||
finished(name, &behind);
|
||||
assert_eq!(
|
||||
(held.status(), behind.status()),
|
||||
(
|
||||
CommandBufferStatus::Completed,
|
||||
CommandBufferStatus::Completed
|
||||
)
|
||||
);
|
||||
assert_eq!((word(&b), word(&d)), (2, 4), "{name}");
|
||||
drop((a, b, c, d, arena, e, f, queue, other, device));
|
||||
});
|
||||
}
|
||||
|
||||
fn shared_event(device: &Device) -> SharedEvent {
|
||||
device.new_shared_event().expect("a shared event")
|
||||
}
|
||||
|
||||
fn queue(device: &Device) -> CommandQueue {
|
||||
device.new_command_queue(64).expect("a queue")
|
||||
}
|
||||
|
||||
/// A wait the host's value meets is submitted with no semaphore wait (the semaphore never
|
||||
/// reaches it, so one would hang), and a GPU signal not above the host's value is left out.
|
||||
#[test]
|
||||
fn every_device_meets_a_wait_by_the_host_value_without_a_semaphore_wait() {
|
||||
each_device("command_floor", |name, _, device| {
|
||||
let (f, e) = (shared_event(&device), shared_event(&device));
|
||||
let queue = queue(&device);
|
||||
|
||||
let waiting = queue.command_buffer().expect("a command buffer");
|
||||
waiting
|
||||
.encode_wait_for_event(f.as_event(), 5)
|
||||
.expect("a wait");
|
||||
waiting.commit().expect("a commit");
|
||||
thread::sleep(Duration::from_millis(20));
|
||||
assert_eq!(waiting.status(), CommandBufferStatus::Committed, "{name}");
|
||||
f.set_signaled_value(5);
|
||||
f.set_signaled_value(3);
|
||||
assert_eq!(f.signaled_value(), 5, "{name}: the host value only rises");
|
||||
finished(name, &waiting);
|
||||
assert_eq!(waiting.status(), CommandBufferStatus::Completed, "{name}");
|
||||
|
||||
e.set_signaled_value(5);
|
||||
let low = queue.command_buffer().expect("a command buffer");
|
||||
low.encode_signal_event(e.as_event(), 3).expect("a signal");
|
||||
low.encode_wait_for_event(e.as_event(), 4).expect("a wait");
|
||||
low.encode_signal_event(e.as_event(), 7).expect("a signal");
|
||||
low.commit().expect("a commit");
|
||||
finished(name, &low);
|
||||
assert_eq!(low.status(), CommandBufferStatus::Completed, "{name}");
|
||||
assert_eq!(e.signaled_value(), 7, "{name}");
|
||||
drop((f, e, queue, device));
|
||||
});
|
||||
}
|
||||
|
||||
/// Host sets race GPU signals of the same values, with GPU waits on them from another queue:
|
||||
/// every command buffer completes, and the semaphore only rises (the validation layer checks
|
||||
/// each signal).
|
||||
#[test]
|
||||
fn every_device_takes_host_values_racing_gpu_signals() {
|
||||
each_device("event_race", |name, _, device| {
|
||||
let e = shared_event(&device);
|
||||
let (signals, waits) = (queue(&device), queue(&device));
|
||||
for value in 1..=200 {
|
||||
let waiter = waits.command_buffer().expect("a command buffer");
|
||||
waiter
|
||||
.encode_wait_for_event(e.as_event(), value)
|
||||
.expect("a wait");
|
||||
waiter.commit().expect("a commit");
|
||||
let signaller = signals.command_buffer().expect("a command buffer");
|
||||
signaller
|
||||
.encode_signal_event(e.as_event(), value)
|
||||
.expect("a signal");
|
||||
thread::scope(|scope| {
|
||||
scope.spawn(|| signaller.commit().expect("a commit"));
|
||||
scope.spawn(|| e.set_signaled_value(value));
|
||||
});
|
||||
finished(name, &signaller);
|
||||
finished(name, &waiter);
|
||||
assert_eq!(waiter.status(), CommandBufferStatus::Completed, "{name}");
|
||||
if value % 100 == 0 {
|
||||
let gauges = device.counters().gauges();
|
||||
println!(
|
||||
"M2V-MATRIX gauge event_race/command_buffers@{value} {}",
|
||||
gauges.command_buffers
|
||||
);
|
||||
println!(
|
||||
"M2V-MATRIX gauge event_race/events@{value} {}",
|
||||
gauges.events
|
||||
);
|
||||
}
|
||||
}
|
||||
assert_eq!(e.signaled_value(), 200, "{name}");
|
||||
drop((e, signals, waits, device));
|
||||
});
|
||||
}
|
||||
|
||||
/// A listener runs when the GPU reaches its value in the middle of a command buffer, at once
|
||||
/// for a value already reached, and for a host value.
|
||||
#[test]
|
||||
fn every_device_runs_a_listener_when_the_gpu_reaches_its_value_mid_buffer() {
|
||||
each_device("event_listeners", |name, _, device| {
|
||||
let (e, f) = (shared_event(&device), shared_event(&device));
|
||||
let queue = queue(&device);
|
||||
let (sent, received) = mpsc::channel::<(u32, u64)>();
|
||||
let listen = |at: u64, label: u32| {
|
||||
let sent = sent.clone();
|
||||
e.notify_listener(at, move |value| sent.send((label, value)).expect("a send"))
|
||||
.expect("a listener");
|
||||
};
|
||||
listen(1, 1);
|
||||
let held = queue.command_buffer().expect("a command buffer");
|
||||
held.encode_signal_event(e.as_event(), 1).expect("a signal");
|
||||
held.encode_wait_for_event(f.as_event(), 1).expect("a wait");
|
||||
held.commit().expect("a commit");
|
||||
assert_eq!(received.recv_timeout(PATIENCE), Ok((1, 1)), "{name}");
|
||||
assert_eq!(
|
||||
held.status(),
|
||||
CommandBufferStatus::Committed,
|
||||
"{name}: still held"
|
||||
);
|
||||
listen(1, 2);
|
||||
assert_eq!(
|
||||
received.recv_timeout(PATIENCE),
|
||||
Ok((2, 1)),
|
||||
"{name}: already reached"
|
||||
);
|
||||
listen(3, 3);
|
||||
f.set_signaled_value(1);
|
||||
finished(name, &held);
|
||||
assert!(received.try_recv().is_err(), "{name}: 3 is not reached");
|
||||
e.set_signaled_value(3);
|
||||
assert_eq!(
|
||||
received.recv_timeout(PATIENCE),
|
||||
Ok((3, 3)),
|
||||
"{name}: a host value"
|
||||
);
|
||||
drop((e, f, queue, device));
|
||||
});
|
||||
}
|
||||
|
||||
/// Abandon ends the queue's held and unsubmitted command buffers with NotRun and runs their
|
||||
/// handlers; the part already submitted ran, the rest never does, and the queue goes on.
|
||||
#[test]
|
||||
fn every_device_abandons_a_queues_held_and_unsubmitted_command_buffers() {
|
||||
each_device("command_abandon", |name, _, device| {
|
||||
let mut arena = Arena::new(&device);
|
||||
let (a, b, c, d) = (
|
||||
arena.buffer(),
|
||||
arena.buffer(),
|
||||
arena.buffer(),
|
||||
arena.buffer(),
|
||||
);
|
||||
let f = shared_event(&device);
|
||||
let queue = queue(&device);
|
||||
let log = Log::default();
|
||||
|
||||
let held = queue.command_buffer().expect("a command buffer");
|
||||
fill(&held, &a, 1);
|
||||
held.encode_wait_for_event(f.as_event(), 1).expect("a wait");
|
||||
fill(&held, &b, 2);
|
||||
log.handlers("held", &held);
|
||||
held.commit().expect("a commit");
|
||||
let behind = queue.command_buffer().expect("a command buffer");
|
||||
fill(&behind, &c, 3);
|
||||
log.handlers("behind", &behind);
|
||||
behind.commit().expect("a commit");
|
||||
let enqueued = queue.command_buffer().expect("a command buffer");
|
||||
log.handlers("enqueued", &enqueued);
|
||||
enqueued.enqueue().expect("an enqueue");
|
||||
within("the part before the wait", || word(&a) == 1);
|
||||
|
||||
queue.abandon();
|
||||
finished(name, &held);
|
||||
finished(name, &behind);
|
||||
for command_buffer in [&held, &behind] {
|
||||
assert_eq!(
|
||||
(command_buffer.status(), command_buffer.error()),
|
||||
(CommandBufferStatus::Error, Some(CommandBufferError::NotRun)),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
enqueued.commit().expect("a commit");
|
||||
finished(name, &enqueued);
|
||||
assert_eq!(enqueued.error(), Some(CommandBufferError::NotRun), "{name}");
|
||||
let mut lines = log.lines();
|
||||
lines.sort();
|
||||
assert_eq!(
|
||||
lines,
|
||||
[
|
||||
"behind completed Error Some(NotRun)",
|
||||
"behind scheduled Error",
|
||||
"enqueued completed Error Some(NotRun)",
|
||||
"enqueued scheduled Error",
|
||||
"held completed Error Some(NotRun)",
|
||||
"held scheduled Error",
|
||||
],
|
||||
"{name}"
|
||||
);
|
||||
|
||||
f.set_signaled_value(1);
|
||||
let after = queue.command_buffer().expect("a command buffer");
|
||||
fill(&after, &d, 4);
|
||||
after.commit().expect("a commit");
|
||||
finished(name, &after);
|
||||
assert_eq!(after.status(), CommandBufferStatus::Completed, "{name}");
|
||||
assert_eq!(
|
||||
(word(&b), word(&c), word(&d)),
|
||||
(0, 0, 4),
|
||||
"{name}: never ran"
|
||||
);
|
||||
drop((a, b, c, d, arena, f, queue, device));
|
||||
});
|
||||
}
|
||||
|
||||
/// The consumer's hook as these tests see it: each block unmapped, and the thread it ran on.
|
||||
#[derive(Default)]
|
||||
struct Hook(Mutex<Vec<(BlockId, Option<String>)>>);
|
||||
|
||||
impl BlockMappings for Hook {
|
||||
fn unmap(&self, block: BlockId) {
|
||||
let thread = thread::current().name().map(str::to_string);
|
||||
lock(&self.0).push((block, thread));
|
||||
}
|
||||
}
|
||||
|
||||
/// Quiesce, from a thread other than the one that made the device, with handles alive: held
|
||||
/// work ends NotRun with its handlers run, every handed block is unmapped once on that
|
||||
/// thread, calls that need a thread are refused, memory stays mapped, and a second call
|
||||
/// answers at once. The last drop then frees everything without the hook.
|
||||
#[test]
|
||||
fn every_device_quiesces_with_handles_alive() {
|
||||
let instance = Instance::new(&[]).expect("an instance at the floor");
|
||||
let devices = devices_of_the_cfgs_kind(&instance);
|
||||
assert!(!devices.is_empty(), "no device of this cfg's kind");
|
||||
for (name, physical) in &devices {
|
||||
let hook = Arc::new(Hook::default());
|
||||
let options = DeviceOptions {
|
||||
block_mappings: Some(hook.clone() as Arc<dyn BlockMappings>),
|
||||
..DeviceOptions::default()
|
||||
};
|
||||
let device = Device::new(physical, options).expect("a device");
|
||||
let counters = device.counters();
|
||||
let mut arena = Arena::new(&device);
|
||||
let a = arena.buffer();
|
||||
let private = device
|
||||
.take_block(MemoryClass::Private, 1)
|
||||
.expect("a Private block");
|
||||
let (f, e) = (shared_event(&device), shared_event(&device));
|
||||
let queue = queue(&device);
|
||||
let held = queue.command_buffer().expect("a command buffer");
|
||||
fill(&held, &a, 7);
|
||||
held.encode_wait_for_event(f.as_event(), 1).expect("a wait");
|
||||
held.commit().expect("a commit");
|
||||
let open = queue.command_buffer().expect("a command buffer");
|
||||
within("the part before the wait", || word(&a) == 7);
|
||||
|
||||
let quiesced = thread::scope(|scope| {
|
||||
scope
|
||||
.spawn(|| device.quiesce(PATIENCE))
|
||||
.join()
|
||||
.expect("the quiescing thread")
|
||||
});
|
||||
assert!(quiesced, "{name}: idle within the timeout");
|
||||
let started = Instant::now();
|
||||
assert!(device.quiesce(PATIENCE), "{name}: the first call's answer");
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_secs(1),
|
||||
"{name}: at once"
|
||||
);
|
||||
assert_eq!(held.error(), Some(CommandBufferError::NotRun), "{name}");
|
||||
held.wait_until_completed();
|
||||
|
||||
let mut unmapped = lock(&hook.0).clone();
|
||||
unmapped.sort();
|
||||
let mut handed = vec![(arena.block, None), (private.id, None)];
|
||||
handed.sort();
|
||||
assert_eq!(
|
||||
unmapped, handed,
|
||||
"{name}: each handed block once, on the quiescing thread"
|
||||
);
|
||||
assert_eq!(word(&a), 7, "{name}: memory stays mapped");
|
||||
assert!(matches!(queue.command_buffer(), Err(Error::Quiesced)));
|
||||
assert!(matches!(
|
||||
device.take_block(MemoryClass::Shared, 1),
|
||||
Err(Error::Quiesced)
|
||||
));
|
||||
assert!(matches!(
|
||||
device.new_buffer(private.id, 0, 64, true),
|
||||
Err(Error::Quiesced)
|
||||
));
|
||||
assert!(matches!(open.enqueue(), Err(Error::Quiesced)));
|
||||
assert!(matches!(open.commit(), Err(Error::Quiesced)));
|
||||
assert!(matches!(e.notify_listener(1, |_| {}), Err(Error::Quiesced)));
|
||||
|
||||
drop((a, arena, f, e, queue, held, open, device));
|
||||
within("the teardown", || counters.gauges() == Gauges::default());
|
||||
print_gauges_at_drop("quiesce", counters.gauges());
|
||||
assert_eq!(lock(&hook.0).len(), 2, "{name}: no unmap after quiesce");
|
||||
}
|
||||
}
|
||||
|
||||
/// The last handle dropped in a completed handler: the completion thread finishes the
|
||||
/// teardown itself once the handler returns.
|
||||
#[test]
|
||||
fn every_device_tears_down_from_a_completed_handler() {
|
||||
each_device("handler_teardown", |name, _, device| {
|
||||
let queue = queue(&device);
|
||||
let command_buffer = queue.command_buffer().expect("a command buffer");
|
||||
drop(queue);
|
||||
command_buffer
|
||||
.add_completed_handler(move |_| drop(device))
|
||||
.expect("a handler");
|
||||
command_buffer.commit().expect("a commit");
|
||||
finished(name, &command_buffer);
|
||||
});
|
||||
}
|
||||
|
||||
/// At a loss: a host wait for a pending signal ends false; the command buffer in flight ends
|
||||
/// DeviceLost in flight, the held one and every later commit DeviceLost not in flight; the
|
||||
/// device tears down, and a new device opens and runs work.
|
||||
#[test]
|
||||
fn every_device_ends_its_work_at_a_loss_and_a_new_device_opens() {
|
||||
each_device("device_loss", |name, instance, device| {
|
||||
let (e, f, g) = (
|
||||
shared_event(&device),
|
||||
shared_event(&device),
|
||||
shared_event(&device),
|
||||
);
|
||||
let queue = queue(&device);
|
||||
let other = self::queue(&device);
|
||||
// In flight: its wait is on a signal the test makes as if submitted, then gives from
|
||||
// the host.
|
||||
e.pretend_submitted_for_test(1);
|
||||
let in_flight = queue.command_buffer().expect("a command buffer");
|
||||
in_flight
|
||||
.encode_wait_for_event(e.as_event(), 1)
|
||||
.expect("a wait");
|
||||
in_flight
|
||||
.encode_signal_event(g.as_event(), 1)
|
||||
.expect("a signal");
|
||||
in_flight.commit().expect("a commit");
|
||||
let held = other.command_buffer().expect("a command buffer");
|
||||
held.encode_wait_for_event(f.as_event(), 1).expect("a wait");
|
||||
held.commit().expect("a commit");
|
||||
within("the scheduling", || {
|
||||
in_flight.status() == CommandBufferStatus::Scheduled
|
||||
});
|
||||
let waiting = thread::scope(|scope| {
|
||||
let waiter = scope.spawn(|| g.wait_until_signaled_value(1, PATIENCE));
|
||||
thread::sleep(Duration::from_millis(20));
|
||||
device.lose_for_test();
|
||||
waiter.join().expect("the waiter")
|
||||
});
|
||||
assert!(
|
||||
!waiting,
|
||||
"{name}: a wait for a pending signal ends at the loss"
|
||||
);
|
||||
|
||||
let raw = device.raw();
|
||||
let signal = vk::SemaphoreSignalInfo::default()
|
||||
.semaphore(e.as_event().inner().semaphore)
|
||||
.value(1);
|
||||
// SAFETY: the semaphore is the device's, and 1 is above its value.
|
||||
unsafe { raw.device.signal_semaphore(&signal) }.expect("a host signal");
|
||||
finished(name, &in_flight);
|
||||
finished(name, &held);
|
||||
let late = queue.command_buffer().expect("a command buffer");
|
||||
late.commit().expect("a commit");
|
||||
finished(name, &late);
|
||||
for (command_buffer, in_flight) in [(&in_flight, true), (&held, false), (&late, false)]
|
||||
{
|
||||
assert_eq!(
|
||||
command_buffer.error(),
|
||||
Some(CommandBufferError::DeviceLost { in_flight }),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
let physical = physical_of(instance, &device);
|
||||
drop((e, f, g, queue, other, device));
|
||||
|
||||
let device = Device::new(&physical, DeviceOptions::default()).expect("a new device");
|
||||
let counters = device.counters();
|
||||
let mut arena = Arena::new(&device);
|
||||
let a = arena.buffer();
|
||||
let queue = self::queue(&device);
|
||||
let after = queue.command_buffer().expect("a command buffer");
|
||||
fill(&after, &a, 9);
|
||||
after.commit().expect("a commit");
|
||||
finished(name, &after);
|
||||
assert_eq!(
|
||||
(after.status(), word(&a)),
|
||||
(CommandBufferStatus::Completed, 9)
|
||||
);
|
||||
drop((a, arena, queue, device));
|
||||
within("the new device's teardown", || {
|
||||
counters.gauges() == Gauges::default()
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// A block released while a command buffer that uses it is held stays out of the pool until
|
||||
/// that command buffer retires.
|
||||
#[test]
|
||||
fn every_device_keeps_a_released_block_until_its_last_command_buffer_retires() {
|
||||
each_device("block_retention", |name, _, device| {
|
||||
let block = device
|
||||
.take_block(MemoryClass::Private, 1)
|
||||
.expect("a Private block");
|
||||
let buffer = device
|
||||
.new_buffer(block.id, 0, 4096, false)
|
||||
.expect("a buffer");
|
||||
let f = shared_event(&device);
|
||||
let queue = queue(&device);
|
||||
let held = queue.command_buffer().expect("a command buffer");
|
||||
fill(&held, &buffer, 5);
|
||||
held.encode_wait_for_event(f.as_event(), 1).expect("a wait");
|
||||
held.commit().expect("a commit");
|
||||
drop(buffer);
|
||||
device.release_block(block.id).expect("a release");
|
||||
thread::sleep(Duration::from_millis(50));
|
||||
let pool = &device.core().pool;
|
||||
assert!(!pool.holds(block.id), "{name}: back while in use");
|
||||
f.set_signaled_value(1);
|
||||
finished(name, &held);
|
||||
within("the block's return", || pool.holds(block.id));
|
||||
drop((f, queue, device));
|
||||
});
|
||||
}
|
||||
|
||||
/// The child's device, its reader thread and whether it reads, for the exit handler.
|
||||
static EXIT_DEVICE: OnceLock<Device> = OnceLock::new();
|
||||
static READER: Mutex<Option<JoinHandle<()>>> = Mutex::new(None);
|
||||
static READING: AtomicBool = AtomicBool::new(true);
|
||||
|
||||
unsafe extern "C" {
|
||||
fn atexit(handler: extern "C" fn()) -> std::ffi::c_int;
|
||||
fn exit(code: std::ffi::c_int) -> !;
|
||||
}
|
||||
|
||||
/// The consumer's exit handler: it parks its own reader, then quiesces twice.
|
||||
extern "C" fn quiesce_at_exit() {
|
||||
READING.store(false, Ordering::Release);
|
||||
if let Some(reader) = lock(&READER).take() {
|
||||
let _ = reader.join();
|
||||
}
|
||||
if let Some(device) = EXIT_DEVICE.get() {
|
||||
let first = device.quiesce(Duration::from_secs(10));
|
||||
let second = device.quiesce(Duration::from_secs(10));
|
||||
println!("M2V exit: quiesced {first} {second}");
|
||||
}
|
||||
}
|
||||
|
||||
fn register_exit_handler() {
|
||||
// SAFETY: the handler is a plain function that lives as long as the process.
|
||||
assert_eq!(unsafe { atexit(quiesce_at_exit) }, 0, "atexit");
|
||||
}
|
||||
|
||||
/// The child of `every_device_quiesces_in_an_exit_handler`, run in a process of its own:
|
||||
/// without its variable, it does nothing.
|
||||
#[test]
|
||||
fn exit_child() {
|
||||
let Ok(mode) = std::env::var("M2V_EXIT_CHILD") else {
|
||||
return;
|
||||
};
|
||||
if mode == "before-instance" {
|
||||
register_exit_handler();
|
||||
}
|
||||
let instance = Instance::new(&[]).expect("an instance at the floor");
|
||||
let (_, physical) = devices_of_the_cfgs_kind(&instance)
|
||||
.into_iter()
|
||||
.next()
|
||||
.expect("a device of this cfg's kind");
|
||||
let device = Device::new(&physical, DeviceOptions::default()).expect("a device");
|
||||
if mode == "after-device" {
|
||||
register_exit_handler();
|
||||
}
|
||||
// Blocks stay taken; a reader thread reads one; the block-maker zeroes released ones; a
|
||||
// command buffer is held.
|
||||
let block = device
|
||||
.take_block(MemoryClass::Shared, BLOCK_LEN)
|
||||
.expect("a Shared block");
|
||||
let released: Vec<_> = (0..3)
|
||||
.map(|_| device.take_block(MemoryClass::Shared, 1).expect("a block"))
|
||||
.collect();
|
||||
let address = block.contents.expect("contents").as_ptr() as usize;
|
||||
*lock(&READER) = Some(thread::spawn(move || {
|
||||
while READING.load(Ordering::Acquire) {
|
||||
for offset in (0..BLOCK_LEN as usize).step_by(4096) {
|
||||
// SAFETY: the block stays taken and mapped until the process ends.
|
||||
unsafe { ((address + offset) as *const u8).read_volatile() };
|
||||
}
|
||||
}
|
||||
}));
|
||||
let event = device.new_shared_event().expect("an event");
|
||||
let queue = device.new_command_queue(64).expect("a queue");
|
||||
let held = queue.command_buffer().expect("a command buffer");
|
||||
held.encode_wait_for_event(event.as_event(), 1)
|
||||
.expect("a wait");
|
||||
held.commit().expect("a commit");
|
||||
for block in &released {
|
||||
device.release_block(block.id).expect("a release");
|
||||
}
|
||||
std::mem::forget((event, queue, held));
|
||||
assert!(EXIT_DEVICE.set(device).is_ok());
|
||||
// `exit()` from a thread other than the one that made the device, with nothing released.
|
||||
let exiting = thread::spawn(|| {
|
||||
// SAFETY: the C library's exit, which runs the handlers registered with `atexit`.
|
||||
unsafe { exit(0) }
|
||||
});
|
||||
let _ = exiting.join();
|
||||
}
|
||||
|
||||
/// In a process of its own, a consumer's `atexit` handler quiesces a live device with blocks
|
||||
/// taken, a reader thread on one, the block-maker busy and a command buffer held, then the
|
||||
/// process exits through `exit()` with no release: exit code 0 and no validation error. The
|
||||
/// handler is registered after `Device::new` (`M2V_EXIT_MODES` adds `before-instance`), once
|
||||
/// per mode (`M2V_EXIT_RUNS` runs each more often).
|
||||
#[test]
|
||||
fn every_device_quiesces_in_an_exit_handler() {
|
||||
let modes = std::env::var("M2V_EXIT_MODES").unwrap_or_else(|_| "after-device".into());
|
||||
let runs: u32 = std::env::var("M2V_EXIT_RUNS")
|
||||
.ok()
|
||||
.and_then(|runs| runs.parse().ok())
|
||||
.unwrap_or(1);
|
||||
let executable = std::env::current_exe().expect("the test executable");
|
||||
let mut failed = Vec::new();
|
||||
for mode in modes.split_whitespace() {
|
||||
let mut held = 0;
|
||||
for run in 0..runs {
|
||||
let output = std::process::Command::new(&executable)
|
||||
.args([
|
||||
"--exact",
|
||||
"tests::command::on_device::exit_child",
|
||||
"--nocapture",
|
||||
"--test-threads=1",
|
||||
])
|
||||
.env("M2V_EXIT_CHILD", mode)
|
||||
.output()
|
||||
.expect("the child");
|
||||
let text = format!(
|
||||
"{}{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let clean = output.status.success()
|
||||
&& text.contains("M2V exit: quiesced true true")
|
||||
&& !text.contains("Validation Error");
|
||||
if clean {
|
||||
held += 1;
|
||||
} else {
|
||||
println!("M2V exit {mode} run {run}: {:?}\n{text}", output.status);
|
||||
}
|
||||
}
|
||||
println!("M2V exit {mode}: {held} of {runs} runs clean");
|
||||
if held != runs {
|
||||
failed.push(mode.to_string());
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
failed.is_empty(),
|
||||
"exit modes with a failed run: {failed:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,9 @@
|
||||
//! down with its gauges at zero, and enables the consumer's extensions it offers.
|
||||
|
||||
use crate::{
|
||||
BlockId, BlockInfo, BlockMappings, Buffer, Counters, Device, DeviceExtension, DeviceOptions,
|
||||
Gauges, Instance, Metrics, PhysicalDevice,
|
||||
BlockId, BlockInfo, BlockMappings, Buffer, CommandBuffer, CommandBufferError,
|
||||
CommandBufferStatus, CommandQueue, Counters, Device, DeviceExtension, DeviceOptions, Event,
|
||||
Gauges, Instance, Metrics, PhysicalDevice, SharedEvent,
|
||||
};
|
||||
|
||||
#[test]
|
||||
@@ -20,6 +21,12 @@ fn the_handles_cross_threads() {
|
||||
send_sync::<BlockInfo>();
|
||||
send_sync::<Buffer>();
|
||||
send_sync::<std::sync::Arc<dyn BlockMappings>>();
|
||||
send_sync::<CommandQueue>();
|
||||
send_sync::<CommandBuffer>();
|
||||
send_sync::<CommandBufferStatus>();
|
||||
send_sync::<CommandBufferError>();
|
||||
send_sync::<Event>();
|
||||
send_sync::<SharedEvent>();
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -68,8 +68,8 @@ mod on_device {
|
||||
use crate::device::lock;
|
||||
use crate::tests::devices_of_the_cfgs_kind;
|
||||
use crate::{
|
||||
BlockId, BlockInfo, BlockMappings, Buffer, Device, DeviceOptions, Error, Gauges, Instance,
|
||||
Limit, MemoryClass, Refusal, BLOCK_LEN,
|
||||
BlockId, BlockInfo, BlockMappings, Buffer, CommandBufferStatus, Device, DeviceOptions,
|
||||
Error, Gauges, Instance, Limit, MemoryClass, Refusal, BLOCK_LEN,
|
||||
};
|
||||
use ash::vk;
|
||||
use std::collections::HashMap;
|
||||
@@ -383,17 +383,33 @@ mod on_device {
|
||||
);
|
||||
}
|
||||
drop(zeroed);
|
||||
// A zeroed Private range is filled ahead of the next command buffer committed, whose
|
||||
// commands see the fill.
|
||||
let queue = device.new_command_queue(1).expect("a queue");
|
||||
for (offset, length) in [(4097, 13), (8001, 2), (4096, 64), (4099, 1), (1, 8000)] {
|
||||
gpu.fill(vk_buffer(&device, private.id), 0, 8192, u32::MAX);
|
||||
let zeroed = device
|
||||
.new_buffer(private.id, offset, length, true)
|
||||
.expect("a zeroed Private buffer");
|
||||
gpu.copy(
|
||||
let (from, to) = (
|
||||
vk_buffer(&device, private.id),
|
||||
vk_buffer(&device, shared.id),
|
||||
0,
|
||||
8192,
|
||||
);
|
||||
let copy = queue.command_buffer().expect("a command buffer");
|
||||
copy.record_for_test(&[], |device, command| {
|
||||
let region = [vk::BufferCopy {
|
||||
src_offset: 0,
|
||||
dst_offset: 0,
|
||||
size: 8192,
|
||||
}];
|
||||
// SAFETY: the command buffer is recording; both blocks are held and span the
|
||||
// region.
|
||||
unsafe { device.cmd_copy_buffer(command, from, to, ®ion) };
|
||||
})
|
||||
.expect("a copy");
|
||||
copy.commit().expect("a commit");
|
||||
copy.wait_until_completed();
|
||||
assert_eq!(copy.status(), CommandBufferStatus::Completed, "{name}");
|
||||
let range = offset as usize..(offset + length) as usize;
|
||||
for (index, &byte) in host[..8192].iter().enumerate() {
|
||||
let expected = if range.contains(&index) { 0 } else { 0xFF };
|
||||
@@ -474,7 +490,7 @@ mod on_device {
|
||||
);
|
||||
|
||||
// Teardown unmaps the rest on this thread, and frees every block.
|
||||
drop((view, whole, gpu));
|
||||
drop((view, whole, gpu, queue));
|
||||
drop(device);
|
||||
let gauges = counters.gauges();
|
||||
print_gauges_at_drop("blocks_teardown", gauges);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
mod command;
|
||||
mod device;
|
||||
mod floor;
|
||||
mod memory;
|
||||
|
||||
@@ -1382,6 +1382,8 @@ enum metal2vulkan-air::tensor_ops::Mode #[derive(Clone, Copy, Debug, PartialEq,
|
||||
enum metal2vulkan-air::tensor_ops::OperandForm #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum OperandForm
|
||||
enum metal2vulkan-air::tensor_ops::OperandIndex #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum OperandIndex
|
||||
enum metal2vulkan-air::tensor_ops::TensorSpace #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum TensorSpace
|
||||
enum metal2vulkan-rt::CommandBufferError #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum CommandBufferError
|
||||
enum metal2vulkan-rt::CommandBufferStatus #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum CommandBufferStatus
|
||||
enum metal2vulkan-rt::Error #[derive(Debug)] #[non_exhaustive] pub enum Error
|
||||
enum metal2vulkan-rt::Limit #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum Limit
|
||||
enum metal2vulkan-rt::MemoryClass #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum MemoryClass
|
||||
@@ -8709,6 +8711,19 @@ method metal2vulkan-rt::Buffer::contents pub fn contents(&self) -> Option<NonNul
|
||||
method metal2vulkan-rt::Buffer::gpu_address pub fn gpu_address(&self) -> u64
|
||||
method metal2vulkan-rt::Buffer::length pub fn length(&self) -> u64
|
||||
method metal2vulkan-rt::Buffer::offset pub fn offset(&self) -> u64
|
||||
method metal2vulkan-rt::CommandBuffer::add_completed_handler pub fn add_completed_handler(&self, handler: impl FnOnce(&CommandBuffer) + Send + 'static) -> Result<(), Error>
|
||||
method metal2vulkan-rt::CommandBuffer::add_scheduled_handler pub fn add_scheduled_handler(&self, handler: impl FnOnce(&CommandBuffer) + Send + 'static) -> Result<(), Error>
|
||||
method metal2vulkan-rt::CommandBuffer::commit pub fn commit(&self) -> Result<(), Error>
|
||||
method metal2vulkan-rt::CommandBuffer::encode_signal_event pub fn encode_signal_event(&self, event: &Event, value: u64) -> Result<(), Error>
|
||||
method metal2vulkan-rt::CommandBuffer::encode_wait_for_event pub fn encode_wait_for_event(&self, event: &Event, value: u64) -> Result<(), Error>
|
||||
method metal2vulkan-rt::CommandBuffer::enqueue pub fn enqueue(&self) -> Result<(), Error>
|
||||
method metal2vulkan-rt::CommandBuffer::error pub fn error(&self) -> Option<CommandBufferError>
|
||||
method metal2vulkan-rt::CommandBuffer::status pub fn status(&self) -> CommandBufferStatus
|
||||
method metal2vulkan-rt::CommandBuffer::wait_until_completed pub fn wait_until_completed(&self)
|
||||
method metal2vulkan-rt::CommandBuffer::wait_until_scheduled pub fn wait_until_scheduled(&self)
|
||||
method metal2vulkan-rt::CommandQueue::abandon pub fn abandon(&self)
|
||||
method metal2vulkan-rt::CommandQueue::command_buffer pub fn command_buffer(&self) -> Result<CommandBuffer, Error>
|
||||
method metal2vulkan-rt::CommandQueue::device pub fn device(&self) -> &Device
|
||||
method metal2vulkan-rt::Counters::gauges pub fn gauges(&self) -> Gauges
|
||||
method metal2vulkan-rt::Counters::metrics pub fn metrics(&self) -> Metrics
|
||||
method metal2vulkan-rt::Device::counters pub fn counters(&self) -> Counters
|
||||
@@ -8717,6 +8732,10 @@ method metal2vulkan-rt::Device::has_unified_memory pub fn has_unified_memory(&se
|
||||
method metal2vulkan-rt::Device::memory_types pub fn memory_types(&self) -> floor::MemoryTypes
|
||||
method metal2vulkan-rt::Device::new pub fn new(physical: &PhysicalDevice, options: DeviceOptions) -> Result<Device, Error>
|
||||
method metal2vulkan-rt::Device::new_buffer pub fn new_buffer(&self, block: BlockId, offset: u64, length: u64, zeroed: bool) -> Result<Buffer, Error>
|
||||
method metal2vulkan-rt::Device::new_command_queue pub fn new_command_queue(&self, max_command_buffer_count: u32) -> Result<CommandQueue, Error>
|
||||
method metal2vulkan-rt::Device::new_event pub fn new_event(&self) -> Result<Event, Error>
|
||||
method metal2vulkan-rt::Device::new_shared_event pub fn new_shared_event(&self) -> Result<SharedEvent, Error>
|
||||
method metal2vulkan-rt::Device::quiesce pub fn quiesce(&self, timeout: Duration) -> bool
|
||||
method metal2vulkan-rt::Device::raw pub fn raw(&self) -> RawDevice<'_>
|
||||
method metal2vulkan-rt::Device::release_block pub fn release_block(&self, block: BlockId) -> Result<(), Error>
|
||||
method metal2vulkan-rt::Device::take_block pub fn take_block(&self, class: MemoryClass, len: u64) -> Result<BlockInfo, Error>
|
||||
@@ -8724,11 +8743,17 @@ method metal2vulkan-rt::Device::with_present_queue pub fn with_present_queue<R>(
|
||||
method metal2vulkan-rt::DeviceExtension::name pub fn name(&self) -> &CStr
|
||||
method metal2vulkan-rt::DeviceExtension::new pub fn new(name: &CStr) -> DeviceExtension
|
||||
method metal2vulkan-rt::DeviceExtension::with_features pub fn with_features<T>(name: &CStr, wanted: T, needs: fn(&T) -> bool) -> DeviceExtension where T: vk::ExtendsPhysicalDeviceFeatures2 + vk::ExtendsDeviceCreateInfo + Copy + Default + Send + Sync + 'static,
|
||||
method metal2vulkan-rt::Event::device pub fn device(&self) -> &Device
|
||||
method metal2vulkan-rt::Instance::extensions pub fn extensions(&self) -> &[CString]
|
||||
method metal2vulkan-rt::Instance::new pub fn new(extensions: &[&CStr]) -> Result<Instance, Error>
|
||||
method metal2vulkan-rt::Instance::physical_devices pub fn physical_devices(&self) -> Result<Vec<PhysicalDevice>, Error>
|
||||
method metal2vulkan-rt::Instance::raw pub fn raw(&self) -> (&ash::Entry, &ash::Instance)
|
||||
method metal2vulkan-rt::PhysicalDevice::raw pub fn raw(&self) -> vk::PhysicalDevice
|
||||
method metal2vulkan-rt::SharedEvent::as_event pub fn as_event(&self) -> &Event
|
||||
method metal2vulkan-rt::SharedEvent::notify_listener pub fn notify_listener(&self, value: u64, listener: impl FnOnce(u64) + Send + 'static) -> Result<(), Error>
|
||||
method metal2vulkan-rt::SharedEvent::set_signaled_value pub fn set_signaled_value(&self, value: u64)
|
||||
method metal2vulkan-rt::SharedEvent::signaled_value pub fn signaled_value(&self) -> u64
|
||||
method metal2vulkan-rt::SharedEvent::wait_until_signaled_value pub fn wait_until_signaled_value(&self, value: u64, timeout: Duration) -> bool
|
||||
method metal2vulkan-runtime::AddressModeMap::constexpr_mode pub fn constexpr_mode(&self, from: SamplerAddressMode) -> Option<SamplerAddressMode>
|
||||
method metal2vulkan-runtime::AddressModeMap::is_identity pub fn is_identity(&self) -> bool
|
||||
method metal2vulkan-runtime::AddressModeMap::mode pub fn mode(&self, from: SamplerAddressMode) -> SamplerAddressMode
|
||||
@@ -10744,15 +10769,19 @@ struct metal2vulkan-air::tensor_ops::RunForm #[derive(Clone, Copy, Debug, Partia
|
||||
struct metal2vulkan-rt::BlockId #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct BlockId(u32)
|
||||
struct metal2vulkan-rt::BlockInfo #[derive(Clone, Copy, Debug)] #[non_exhaustive] pub struct BlockInfo
|
||||
struct metal2vulkan-rt::Buffer #[derive(Clone)] pub struct Buffer
|
||||
struct metal2vulkan-rt::CommandBuffer #[derive(Clone)] pub struct CommandBuffer
|
||||
struct metal2vulkan-rt::CommandQueue #[derive(Clone)] pub struct CommandQueue
|
||||
struct metal2vulkan-rt::Counters #[derive(Clone)] pub struct Counters
|
||||
struct metal2vulkan-rt::Device #[derive(Clone)] pub struct Device
|
||||
struct metal2vulkan-rt::DeviceExtension #[derive(Clone)] pub struct DeviceExtension
|
||||
struct metal2vulkan-rt::DeviceOptions #[derive(Clone, Default)] #[non_exhaustive] pub struct DeviceOptions
|
||||
struct metal2vulkan-rt::Event #[derive(Clone)] pub struct Event
|
||||
struct metal2vulkan-rt::Gauges #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[non_exhaustive] pub struct Gauges
|
||||
struct metal2vulkan-rt::Instance #[derive(Clone)] pub struct Instance
|
||||
struct metal2vulkan-rt::Metrics #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[non_exhaustive] pub struct Metrics
|
||||
struct metal2vulkan-rt::PhysicalDevice #[derive(Clone)] pub struct PhysicalDevice
|
||||
struct metal2vulkan-rt::RawDevice #[non_exhaustive] pub struct RawDevice<'a>
|
||||
struct metal2vulkan-rt::SharedEvent #[derive(Clone)] pub struct SharedEvent
|
||||
struct metal2vulkan-rt::floor::BelowFloor #[derive(Clone, Debug, PartialEq, Eq)] pub struct BelowFloor
|
||||
struct metal2vulkan-rt::floor::Capabilities pub struct Capabilities
|
||||
struct metal2vulkan-rt::floor::Features #[derive(Clone, Copy, Default)] pub struct Features
|
||||
@@ -12605,10 +12634,19 @@ variant metal2vulkan-air::tensor_ops::OperandIndex::Right Right
|
||||
variant metal2vulkan-air::tensor_ops::TensorSpace::Device Device
|
||||
variant metal2vulkan-air::tensor_ops::TensorSpace::Thread Thread
|
||||
variant metal2vulkan-air::tensor_ops::TensorSpace::Threadgroup Threadgroup
|
||||
variant metal2vulkan-rt::CommandBufferError::DeviceLost DeviceLost { in_flight: bool }
|
||||
variant metal2vulkan-rt::CommandBufferError::NotRun NotRun
|
||||
variant metal2vulkan-rt::CommandBufferStatus::Committed Committed
|
||||
variant metal2vulkan-rt::CommandBufferStatus::Completed Completed
|
||||
variant metal2vulkan-rt::CommandBufferStatus::Enqueued Enqueued
|
||||
variant metal2vulkan-rt::CommandBufferStatus::Error Error
|
||||
variant metal2vulkan-rt::CommandBufferStatus::NotEnqueued NotEnqueued
|
||||
variant metal2vulkan-rt::CommandBufferStatus::Scheduled Scheduled
|
||||
variant metal2vulkan-rt::Error::BelowFloor BelowFloor(BelowFloor)
|
||||
variant metal2vulkan-rt::Error::Limit Limit(Limit)
|
||||
variant metal2vulkan-rt::Error::Loader Loader(ash::LoadingError)
|
||||
variant metal2vulkan-rt::Error::NoSuchBlock NoSuchBlock(BlockId)
|
||||
variant metal2vulkan-rt::Error::Quiesced Quiesced
|
||||
variant metal2vulkan-rt::Error::Refused Refused(Refusal)
|
||||
variant metal2vulkan-rt::Error::Thread Thread(io::Error)
|
||||
variant metal2vulkan-rt::Error::Vulkan Vulkan { call: &'static str, result: vk::Result }
|
||||
@@ -12617,7 +12655,10 @@ variant metal2vulkan-rt::Limit::BlockLen BlockLen { len: u64, max: u64 }
|
||||
variant metal2vulkan-rt::MemoryClass::Private Private
|
||||
variant metal2vulkan-rt::MemoryClass::Shared Shared
|
||||
variant metal2vulkan-rt::Refusal::BufferPastBlock BufferPastBlock { offset: u64, length: u64, block_len: u64 }
|
||||
variant metal2vulkan-rt::Refusal::Committed Committed
|
||||
variant metal2vulkan-rt::Refusal::EmptyBuffer EmptyBuffer
|
||||
variant metal2vulkan-rt::Refusal::NoCommandBuffers NoCommandBuffers
|
||||
variant metal2vulkan-rt::Refusal::OtherDevice OtherDevice
|
||||
variant metal2vulkan-rt::floor::Missing::Extension Extension(&'static CStr)
|
||||
variant metal2vulkan-rt::floor::Missing::Feature Feature { structure: &'static str, member: String }
|
||||
variant metal2vulkan-rt::floor::Missing::Limit Limit { name: &'static str, device: u32, needed: u32 }
|
||||
|
||||
|
Can't render this file because it is too large.
|
+8
-2
@@ -37,7 +37,7 @@ Columns:
|
||||
| What a call did wrong | 73 | 73 | 0 | 0 | 0 | 0 | 0 |
|
||||
| What a call did wrong, in detail | 174 | 157 | 0 | 0 | 0 | 0 | 0 |
|
||||
| Devices below the new runtime's floor | 6 | 6 | 0 | 0 | 0 | 0 | 0 |
|
||||
| The new runtime's `Refusal` | 2 | 2 | 0 | 0 | 0 | 0 | 0 |
|
||||
| The new runtime's `Refusal` | 5 | 5 | 0 | 0 | 0 | 0 | 0 |
|
||||
| The new runtime's `Limit` | 2 | 2 | 0 | 0 | 0 | 0 | 0 |
|
||||
|
||||
## Totals by basis
|
||||
@@ -54,7 +54,7 @@ Columns:
|
||||
| What a call did wrong | 22 | 3 | 5 | 0 | 18 | 8 | 17 | 0 |
|
||||
| What a call did wrong, in detail | 60 | 26 | 23 | 0 | 39 | 26 | 0 | 0 |
|
||||
| Devices below the new runtime's floor | 0 | 0 | 0 | 6 | 0 | 0 | 0 | 0 |
|
||||
| The new runtime's `Refusal` | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| The new runtime's `Refusal` | 2 | 1 | 0 | 0 | 2 | 0 | 0 | 0 |
|
||||
| The new runtime's `Limit` | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 |
|
||||
|
||||
## 1. Translator and front-end refusals (`Unsupported`: a `Feature` and its `Needs`)
|
||||
@@ -611,6 +611,9 @@ Columns:
|
||||
|---|---|---|---|---|---|
|
||||
| `EmptyBuffer` | A buffer of no bytes (`Device::new_buffer` with a length of 0) | every device (a public call's own check of its arguments) | `metal-measured`: an Apple M3 Max: newBufferWithLength:0 answers nil | 1: `crates/metal2vulkan-rt/src/buffer.rs (new_buffer)` | `-` |
|
||||
| `BufferPastBlock` | A buffer whose range leaves its block (`Device::new_buffer`) | every device (a public call's own check of its arguments) | `metal-measured`: an Apple M3 Max, macOS 27.0.1: a placement heap of 1 MiB answers nil for a 4096-byte buffer at offset 1,047,552 | 1: `crates/metal2vulkan-rt/src/buffer.rs (new_buffer)` | `-` |
|
||||
| `Committed` | A call on a command buffer already committed | every device (a public call's own check of its arguments) | `metal-documented`: Metal's validation asserts "commit an already committed command buffer", "Completed handler provided after commit call" and "Scheduled handler provided after commit call" | 3: `crates/metal2vulkan-rt/src/command.rs (building)`, `crates/metal2vulkan-rt/src/command.rs (commit)` (+1) | `-` |
|
||||
| `OtherDevice` | An event of another device in an encode call (`CommandBuffer::encode_wait_for_event` or `CommandBuffer::encode_signal_event`) | every device (a public call's own check of its arguments) | `ours`: an event's semaphore belongs to the `VkDevice` that made it | 1: `crates/metal2vulkan-rt/src/command.rs (check)` | `-` |
|
||||
| `NoCommandBuffers` | A queue that may hold no command buffer (`Device::new_command_queue` with a count of 0) | every device (a public call's own check of its arguments) | `ours`: its first `commandBuffer` call would wait forever | 1: `crates/metal2vulkan-rt/src/queue.rs (new_command_queue)` | `-` |
|
||||
|
||||
## 12. The new runtime's `Limit` (`Error::Limit(Limit)`)
|
||||
|
||||
@@ -1106,6 +1109,9 @@ Each refusal's sites, with the function that builds it.
|
||||
- `floor::MemoryType`: `crates/metal2vulkan-rt/src/floor.rs (choose)`
|
||||
- `rt:Refusal::EmptyBuffer`: `crates/metal2vulkan-rt/src/buffer.rs (new_buffer)`
|
||||
- `rt:Refusal::BufferPastBlock`: `crates/metal2vulkan-rt/src/buffer.rs (new_buffer)`
|
||||
- `rt:Refusal::Committed`: `crates/metal2vulkan-rt/src/command.rs (building)`; `crates/metal2vulkan-rt/src/command.rs (commit)`; `crates/metal2vulkan-rt/src/command.rs (enqueue)`
|
||||
- `rt:Refusal::OtherDevice`: `crates/metal2vulkan-rt/src/command.rs (check)`
|
||||
- `rt:Refusal::NoCommandBuffers`: `crates/metal2vulkan-rt/src/queue.rs (new_command_queue)`
|
||||
- `rt:Limit::BlockLen`: `crates/metal2vulkan-rt/src/memory.rs (dedicated_len)`
|
||||
- `rt:Limit::BlockIds`: `crates/metal2vulkan-rt/src/memory.rs (number)`
|
||||
|
||||
Reference in new issue
Block a user