What: the ring's idle rule (Ring::due), run on the block-maker thread beside the pool's: a block past the first goes once every chunk of it has been free for the idle age (250 ms), where the ring, at its fewest free chunks since the block fell idle, kept more than a block's chunks free without it, so neither a take in that time nor the next would have asked for a block. The fewest is set at the give-back that made the block idle, from the chunks the ring has free once that give-back is done, and falls with each take. The first block stays, and so does a block holding the nil buffer, the zero range or the whole range. A take now takes a chunk of the oldest block with one free, so the newest blocks fall idle first; each block keeps its own free chunks. A block past the first that falls idle wakes the block-maker thread (Pool::nudge); the thread frees it as memory of its own (Loose::RingBlock: its fault span noted freed, the buffer destroyed, the memory freed, the blocks gauge falling). A block that does not meet the rule now cannot meet it in the same idle time, so the thread sets no wake for it. Why: the planner's cache ruling (1). The ring kept every block it made for the device's life, so a burst of parameter writes left its peak of 2 MiB blocks of the ring type (device-local and host-visible, small without resizable BAR) until the device went. Freed at idle alone, a ring in steady use would free its second block and make it again each idle age. A second condition, no take for the idle age, which took an idle ring down to its first block, was dropped by the planner's ruling: whether a take waited for a block it then made again could not be read on a recorded play, so an idle ring keeps its first block and the one ahead of it. Docs: the ring module doc, Ring::due, Pool::nudge, memory::run, the runtime README's internals paragraph. Verified: red on the RX 7900 XTX (RADV 26.2.6) with the parent's runtime and this branch's tests, m3-max-79046: the burst test timed out waiting for the ring back to its first block and the one ahead; the steady-use test passed (nothing is freed). Green in the same job at this code: the ring, ahead and memory modules, 33 passed, "6 blocks after the burst, 2 once idle; the next take made none". At this tree (f882510ace, the same tree): clippy -D warnings plain, under m2v_cpu_icd and under m2v_gpu, rustdoc -D warnings, and the workspace's rustdoc of private items, all exit 0; the runtime's suite on lavapipe 904 passed, 3 skipped, with the same line (m3-max-79050). The cost line, one job on the Radeon 780M (RADV PHOENIX, Mesa 26.2.6), the release replay player on stream glbench-780m-r2 with a fresh pipeline cache each play, arms a (the parent's runtime) and b (this one) alternated a b a b (m3-max-79045): 792 frames each; blocks made a 300 and 299, b 300 and 299, 37.88 and 37.75 per 100 frames in each arm, with block bytes made equal pair by pair (the one-block difference between the pairs is a pool allocation, 33.5 MB, in both arms). This play makes no ring block more than the parent.
647 lines
27 KiB
Rust
647 lines
27 KiB
Rust
//! The parameter ring: memory of the floor's ring type (device-local, host-visible, coherent) that
|
|
//! the host writes and the GPU reads by address. It holds parameter blocks longer than the push
|
|
//! range and the bytes of `set_bytes`, which a draw's vertex input also reads through the block's
|
|
//! buffer.
|
|
//!
|
|
//! The ring is made of 2 MiB blocks, each split into chunks of 64 KiB, each chunk at a multiple of
|
|
//! the ring's alignment (at least 16) in the device address space: 32 where Vulkan places the
|
|
//! block's address at a multiple of that alignment, and 31 where it places it off it
|
|
//! ([`chunk_starts`]). A command buffer takes
|
|
//! chunks as it records, writes each byte once, and gives them back when it retires, so the GPU
|
|
//! never reads a chunk the host is writing. A take takes a chunk of the first block, in the order
|
|
//! the blocks were made, that has one free, so the later blocks are the first to fall idle. The
|
|
//! block-maker thread makes them, off every caller's thread (`crate::memory::Internal`): the
|
|
//! first as its first work once the device's making starts it, and the next each time a take
|
|
//! leaves fewer chunks free than a block holds, so a block's chunks are free ahead of the takes
|
|
//! and the ring holds at most one block more than the most chunks in use at once need. It makes
|
|
//! one block at a time, without the ring's lock: a take or a give-back never waits for the
|
|
//! driver's allocation. It takes an ask up before it makes the block, so a take that asks again
|
|
//! once the ring has that block, before the thread is done with it, asks anew, and the thread
|
|
//! makes the next block after it: no ask goes unanswered. A take that finds no chunk free while
|
|
//! the block-maker thread makes the next waits for it, or for a chunk given back, counted in
|
|
//! [`Metrics::maker_waits`](crate::Metrics::maker_waits). Where it made none (its make failed, or
|
|
//! it had stopped), a take that finds no chunk free makes the block on its own thread, without
|
|
//! the ring's lock, counted in
|
|
//! [`Metrics::ring_block_allocations`](crate::Metrics::ring_block_allocations), and takes that
|
|
//! meet it then wait for it. The runtime never reads the ring back.
|
|
//!
|
|
//! The idle rule ([`Ring::due`]) frees a block past the first on the block-maker thread once every
|
|
//! chunk of it has been free for the idle age (`crate::memory::IDLE_AGE_NANOS`, 250 ms), where the
|
|
//! ring, at its fewest free chunks since the block fell idle, kept more than a block's chunks free
|
|
//! without it, so neither a take in that time nor the next would have asked for a block. The first
|
|
//! block is kept for the device's life, and so is a block that holds a chunk kept for it (below).
|
|
//! So the blocks a burst made go once the takes fall back, down to what the takes since need and
|
|
//! a block's chunks ahead of them; an idle ring keeps its first block and the one ahead of it, and
|
|
//! a ring in steady use frees no block it would make again.
|
|
//!
|
|
//! One chunk, taken at the first ask and kept for the device's life, is the nil buffer
|
|
//! ([`Ring::nil`]): 64 KiB of zeros, at a multiple of 16 like every chunk, so it meets any buffer
|
|
//! argument's alignment. A buffer argument nothing is bound to reads it, as Metal's nil buffer
|
|
//! reads zeros. A read past its 64 KiB, and a write through it, are not covered.
|
|
//!
|
|
//! Another, taken the same way, is the zero range ([`Ring::zero`]): zeros that no command and no
|
|
//! buffer argument reaches, which a checked load of a buffer argument outside its buffer reads
|
|
//! (the translator's `PushField::ZeroAddress`), so it reads zero.
|
|
//!
|
|
//! A third is the whole execution range ([`Ring::whole`]): Metal's
|
|
//! `MTLIndirectCommandBufferExecutionRange` of every command, location 0 and length `u32::MAX`,
|
|
//! which a direct draw of a state made for indirect command buffers, and an execution over a range
|
|
//! the CPU gives, point the vertex function's range at (the translator's
|
|
//! `PushField::IndirectRange`). Nothing writes it after its first ask.
|
|
|
|
use crate::counters::{Gauge, Metric, Site};
|
|
use crate::device::{lock, Core};
|
|
use crate::error::Error;
|
|
use crate::fault::RangeKind;
|
|
use crate::floor;
|
|
use crate::memory::{self, Internal, Mapping};
|
|
use ash::vk;
|
|
use std::ptr::NonNull;
|
|
use std::sync::{Condvar, Mutex, OnceLock, PoisonError};
|
|
|
|
/// A chunk's length: the most one write takes.
|
|
pub(crate) const CHUNK: u64 = 64 * 1024;
|
|
/// A ring block's length.
|
|
pub(crate) const BLOCK: u64 = 32 * CHUNK;
|
|
/// The chunks of a block: a take that leaves fewer free asks the block-maker thread for the
|
|
/// next block.
|
|
pub(crate) const SPARE: usize = (BLOCK / CHUNK) as usize;
|
|
/// The least alignment of every write: a parameter block's, and Metal's for `setBytes` data.
|
|
const ALIGN: u64 = 16;
|
|
|
|
/// The device's ring.
|
|
pub(crate) struct Ring {
|
|
state: Mutex<State>,
|
|
/// The alignment of every write in the device address space: [`ALIGN`], or the translator's
|
|
/// buffer base alignment where that is larger (`DeviceProfile::buffer_base_alignment`). A
|
|
/// chunk starts at a multiple of it ([`chunk_starts`]) and a write at a multiple of it in its
|
|
/// chunk, so a write's offset in its block's buffer is a multiple of the device's
|
|
/// `minStorageBufferOffsetAlignment`: a `set_bytes` copy a kernel reaches through a storage
|
|
/// buffer of set 0 (`crate::bound`) starts its descriptor at its own first byte.
|
|
align: u64,
|
|
/// The nil buffer's address, once asked ([`Ring::nil`]), read with no lock.
|
|
nil: OnceLock<u64>,
|
|
/// The zero range's address, once asked ([`Ring::zero`]), read with no lock.
|
|
zero: OnceLock<u64>,
|
|
/// The whole execution range's address, once asked ([`Ring::whole`]), read with no lock.
|
|
whole: OnceLock<u64>,
|
|
/// A block made, or chunks given back, while a block was being made.
|
|
changed: Condvar,
|
|
/// For the device tests: where set, the making of a block, the block-maker thread's or a
|
|
/// take's, meets the test at the barrier twice before it allocates, once parked and once
|
|
/// released; so does the block-maker thread's answer that it makes none
|
|
/// (`crate::memory::MakerTest::Fail`), once the ring has it.
|
|
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
|
|
pub(crate) park: Mutex<Option<std::sync::Arc<std::sync::Barrier>>>,
|
|
}
|
|
|
|
struct State {
|
|
/// The blocks in the order they were made: a take takes a chunk of the first with one free.
|
|
blocks: Vec<RingBlock>,
|
|
/// The free chunks of every block.
|
|
free: usize,
|
|
/// Who makes the next block.
|
|
next: Next,
|
|
}
|
|
|
|
/// Who makes the ring's next block.
|
|
#[derive(Clone, Copy, PartialEq, Eq)]
|
|
enum Next {
|
|
/// No one: a block's chunks are free, or the block-maker thread made none.
|
|
Unasked,
|
|
/// The block-maker thread, asked for it ([`Internal::RingBlock`]).
|
|
Maker,
|
|
/// A take, on its own thread, where the block-maker thread made none.
|
|
Take,
|
|
}
|
|
|
|
struct RingBlock {
|
|
buffer: vk::Buffer,
|
|
memory: vk::DeviceMemory,
|
|
/// Its free chunks.
|
|
free: Vec<Chunk>,
|
|
/// Its chunks ([`chunk_starts`]).
|
|
chunks: usize,
|
|
/// Where every chunk of it is free: since when, and the fewest chunks the ring had free since
|
|
/// then.
|
|
idle: Option<Idle>,
|
|
}
|
|
|
|
/// A block's idle time ([`RingBlock::idle`]).
|
|
#[derive(Clone, Copy)]
|
|
struct Idle {
|
|
since: u64,
|
|
low: usize,
|
|
}
|
|
|
|
/// A block made ([`make`]), before the ring keeps it.
|
|
struct Made {
|
|
buffer: vk::Buffer,
|
|
memory: vk::DeviceMemory,
|
|
}
|
|
|
|
/// A chunk: its device address, its host address, and its block's buffer with its offset there.
|
|
#[derive(Clone, Copy)]
|
|
pub(crate) struct Chunk {
|
|
address: u64,
|
|
host: Mapping,
|
|
buffer: vk::Buffer,
|
|
offset: u64,
|
|
}
|
|
|
|
/// Where a write into the ring lies: its device address, and its block's buffer with its offset
|
|
/// there.
|
|
#[derive(Clone, Copy)]
|
|
pub(crate) struct Placed {
|
|
pub(crate) address: u64,
|
|
pub(crate) buffer: vk::Buffer,
|
|
pub(crate) offset: u64,
|
|
}
|
|
|
|
impl Ring {
|
|
/// The ring of a new device whose writes lie at multiples of `align` (at least [`ALIGN`]),
|
|
/// whose first block the block-maker thread makes as its first work (`crate::memory::run`).
|
|
pub(crate) fn new(align: u64) -> Ring {
|
|
Ring {
|
|
align: align.max(ALIGN),
|
|
state: Mutex::new(State {
|
|
blocks: Vec::new(),
|
|
free: 0,
|
|
next: Next::Maker,
|
|
}),
|
|
nil: OnceLock::new(),
|
|
zero: OnceLock::new(),
|
|
whole: OnceLock::new(),
|
|
changed: Condvar::new(),
|
|
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
|
|
park: Mutex::new(None),
|
|
}
|
|
}
|
|
|
|
/// A free chunk. A take that leaves fewer than [`SPARE`] free, with no block being made, asks
|
|
/// the block-maker thread for the next. Where none is free, the take waits while the
|
|
/// block-maker thread or another take makes a block (a wait for the block-maker thread is
|
|
/// counted), and makes one itself where neither does.
|
|
fn take(&self, core: &Core) -> Result<Chunk, Error> {
|
|
let mut state = lock(&self.state);
|
|
// When this take began to wait for the block-maker thread's block.
|
|
let mut since = None;
|
|
loop {
|
|
if let Some(chunk) = state.take() {
|
|
let ask = state.next == Next::Unasked && state.free < SPARE;
|
|
if ask {
|
|
state.next = Next::Maker;
|
|
}
|
|
drop(state);
|
|
waited(core, since);
|
|
if ask && !core.pool.ask(Internal::RingBlock) {
|
|
self.unasked();
|
|
}
|
|
return Ok(chunk);
|
|
}
|
|
match state.next {
|
|
Next::Unasked => break,
|
|
Next::Maker => {
|
|
since.get_or_insert_with(crate::host_time);
|
|
}
|
|
Next::Take => {}
|
|
}
|
|
state = self
|
|
.changed
|
|
.wait(state)
|
|
.unwrap_or_else(PoisonError::into_inner);
|
|
}
|
|
waited(core, since);
|
|
state.next = Next::Take;
|
|
drop(state);
|
|
let made = make(core);
|
|
let mut state = lock(&self.state);
|
|
state.next = Next::Unasked;
|
|
self.changed.notify_all();
|
|
let (block, address, host) = made?;
|
|
let chunk = state.add(block, address, host, self.align);
|
|
state.taken();
|
|
Ok(chunk)
|
|
}
|
|
|
|
/// On the block-maker thread: makes the block asked of it ([`Internal::RingBlock`]) and hands
|
|
/// its chunks to the takes. Err where the make failed: a take that finds no chunk free then
|
|
/// makes the next block.
|
|
pub(crate) fn make_ahead(&self, core: &Core) -> Result<(), Error> {
|
|
let made = make(core);
|
|
let mut state = lock(&self.state);
|
|
state.next = Next::Unasked;
|
|
self.changed.notify_all();
|
|
let (block, address, host) = made?;
|
|
let first = state.add(block, address, host, self.align);
|
|
state.give(vec![first], crate::host_time());
|
|
Ok(())
|
|
}
|
|
|
|
/// The block-maker thread makes no block asked of it: it has stopped, or (in the device
|
|
/// tests) its make fails at once. A take that finds no chunk free makes the block.
|
|
pub(crate) fn unasked(&self) {
|
|
let mut state = lock(&self.state);
|
|
if state.next == Next::Maker {
|
|
state.next = Next::Unasked;
|
|
self.changed.notify_all();
|
|
}
|
|
}
|
|
|
|
/// The alignment of every write's device address in the ring: the translator's buffer base
|
|
/// alignment (`DeviceProfile::buffer_base_alignment`), at least 16.
|
|
pub(crate) fn align(&self) -> u64 {
|
|
self.align
|
|
}
|
|
|
|
/// The nil buffer's address (the module docs): a chunk of zeros, taken and zeroed at the
|
|
/// first ask and never given back, so no command buffer writes it.
|
|
pub(crate) fn nil(&self, core: &Core) -> Result<u64, Error> {
|
|
self.kept(core, &self.nil, &[])
|
|
}
|
|
|
|
/// The zero range's address (the module docs): a chunk of zeros taken as the nil buffer's
|
|
/// is, which nothing is bound to, so nothing writes it. A multiple of 16.
|
|
pub(crate) fn zero(&self, core: &Core) -> Result<u64, Error> {
|
|
self.kept(core, &self.zero, &[])
|
|
}
|
|
|
|
/// The whole execution range's address (the module docs): a chunk taken as the nil buffer's
|
|
/// is, its first 8 bytes location 0 and length `u32::MAX`, the rest zeros.
|
|
pub(crate) fn whole(&self, core: &Core) -> Result<u64, Error> {
|
|
self.kept(core, &self.whole, &[0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff])
|
|
}
|
|
|
|
/// The address of the chunk `which` holds, taken at its first ask, its bytes `head` and zeros
|
|
/// after them, and never given back. Every later ask reads it with no lock and no locked
|
|
/// instruction: a draw or a dispatch whose bindings changed asks again (the lock budget,
|
|
/// `crate::tests::locks`).
|
|
fn kept(&self, core: &Core, which: &OnceLock<u64>, head: &[u8]) -> Result<u64, Error> {
|
|
if let Some(&address) = which.get() {
|
|
return Ok(address);
|
|
}
|
|
let chunk = self.take(core)?;
|
|
// SAFETY: the chunk is out of every command buffer's hands and no pending work reads it:
|
|
// the host alone writes it, once; `head` is shorter than a chunk.
|
|
unsafe {
|
|
let at = chunk.host.at(0).as_ptr();
|
|
std::ptr::write_bytes(at, 0, CHUNK as usize);
|
|
std::ptr::copy_nonoverlapping(head.as_ptr(), at, head.len());
|
|
}
|
|
let address = *which.get_or_init(|| chunk.address);
|
|
if address != chunk.address {
|
|
// Another thread's ask made it first: the chunk goes back.
|
|
self.give_back(core, vec![chunk]);
|
|
}
|
|
Ok(address)
|
|
}
|
|
|
|
/// Takes back a retired command buffer's chunks. Where a block past the first has every chunk
|
|
/// free then, the block-maker thread is woken to weigh it ([`due`](Self::due)).
|
|
fn give_back(&self, core: &Core, chunks: Vec<Chunk>) {
|
|
let now = crate::host_time();
|
|
let mut state = lock(&self.state);
|
|
let idle = state.give(chunks, now);
|
|
if state.next != Next::Unasked {
|
|
self.changed.notify_all();
|
|
}
|
|
drop(state);
|
|
if idle {
|
|
core.pool.nudge();
|
|
}
|
|
}
|
|
|
|
/// On the block-maker thread, the idle rule (the module docs): the last block past the first
|
|
/// whose chunks have all been free for the idle age ([`memory::IDLE_AGE_NANOS`]) at `now`,
|
|
/// where the ring at its fewest free chunks since kept more than a block's chunks free without
|
|
/// it, taken out of the ring to free; else the host time when one such block will be due where
|
|
/// nothing changes (`Err`). `None` where no block past the first meets it, or a block is being
|
|
/// made. A block that does not meet it now meets it in this idle time no more: the ring's
|
|
/// fewest free chunks since only fall.
|
|
pub(crate) fn due(&self, now: u64) -> Option<Result<memory::Loose, u64>> {
|
|
let mut state = lock(&self.state);
|
|
if state.next != Next::Unasked {
|
|
return None;
|
|
}
|
|
let mut wake: Option<u64> = None;
|
|
let mut gone = None;
|
|
for (index, block) in state.blocks.iter().enumerate().skip(1).rev() {
|
|
let Some(idle) = block.idle.filter(|idle| idle.low > block.chunks + SPARE) else {
|
|
continue;
|
|
};
|
|
match memory::idle_due(idle.since, now) {
|
|
None => {
|
|
gone = Some(index);
|
|
break;
|
|
}
|
|
Some(at) => wake = Some(wake.map_or(at, |wake| wake.min(at))),
|
|
}
|
|
}
|
|
match gone {
|
|
Some(index) => Some(Ok(state.remove(index))),
|
|
None => wake.map(Err),
|
|
}
|
|
}
|
|
|
|
/// For the device tests: the ring's blocks and free chunks where its lock is free now, else
|
|
/// None.
|
|
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
|
|
pub(crate) fn chunks(&self) -> Option<(usize, usize)> {
|
|
(self.state.try_lock().ok()).map(|state| (state.blocks.len(), state.free))
|
|
}
|
|
|
|
/// For the device tests: whether the ring's next block waits on an ask of the block-maker
|
|
/// thread.
|
|
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
|
|
pub(crate) fn asked(&self) -> bool {
|
|
lock(&self.state).next == Next::Maker
|
|
}
|
|
|
|
/// For the device tests: meets the test at [`park`](Self::park) twice where it is set.
|
|
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
|
|
pub(crate) fn meet_park(&self) {
|
|
let park = lock(&self.park).clone();
|
|
if let Some(park) = park {
|
|
park.wait();
|
|
park.wait();
|
|
}
|
|
}
|
|
|
|
/// Frees every block, returning how many it freed.
|
|
///
|
|
/// # Safety
|
|
///
|
|
/// No pending work reads the ring.
|
|
pub(crate) unsafe fn destroy(&mut self, device: &ash::Device) -> usize {
|
|
let state = self
|
|
.state
|
|
.get_mut()
|
|
.unwrap_or_else(|error| error.into_inner());
|
|
let freed = state.blocks.len();
|
|
for block in state.blocks.drain(..) {
|
|
// SAFETY: by the caller; freeing the memory unmaps it.
|
|
unsafe {
|
|
device.destroy_buffer(block.buffer, None);
|
|
device.free_memory(block.memory, None);
|
|
}
|
|
}
|
|
state.free = 0;
|
|
self.nil.take();
|
|
self.zero.take();
|
|
freed
|
|
}
|
|
}
|
|
|
|
impl State {
|
|
/// Keeps a block made at `address`, mapped at `host`, whose writes lie at multiples of
|
|
/// `align`: its chunks but the first are free, and the first is the caller's
|
|
/// ([`chunk_starts`]).
|
|
fn add(&mut self, made: Made, address: u64, host: Mapping, align: u64) -> Chunk {
|
|
let buffer = made.buffer;
|
|
let (skew, chunks) = chunk_starts(address, align);
|
|
let chunk = |index: u64| {
|
|
let offset = skew + index * CHUNK;
|
|
Chunk {
|
|
address: address + offset,
|
|
// SAFETY: the chunk lies in the block's mapping.
|
|
host: Mapping::new(unsafe { host.at(offset) }),
|
|
buffer,
|
|
offset,
|
|
}
|
|
};
|
|
let free: Vec<Chunk> = (1..chunks).rev().map(chunk).collect();
|
|
self.free += free.len();
|
|
self.blocks.push(RingBlock {
|
|
buffer,
|
|
memory: made.memory,
|
|
free,
|
|
chunks: chunks as usize,
|
|
idle: None,
|
|
});
|
|
chunk(0)
|
|
}
|
|
|
|
/// A free chunk of the first block that has one, taken.
|
|
fn take(&mut self) -> Option<Chunk> {
|
|
let block = self
|
|
.blocks
|
|
.iter_mut()
|
|
.find(|block| !block.free.is_empty())?;
|
|
let chunk = block.free.pop()?;
|
|
block.idle = None;
|
|
self.free -= 1;
|
|
self.taken();
|
|
Some(chunk)
|
|
}
|
|
|
|
/// A take, which leaves the ring the chunks it has free: the low of every idle block.
|
|
fn taken(&mut self) {
|
|
let free = self.free;
|
|
for idle in self
|
|
.blocks
|
|
.iter_mut()
|
|
.filter_map(|block| block.idle.as_mut())
|
|
{
|
|
idle.low = idle.low.min(free);
|
|
}
|
|
}
|
|
|
|
/// Takes back `chunks` at `now`, one give-back: each block that then has every chunk free is
|
|
/// idle from `now`, with the chunks the ring has free once all are back. True where such a
|
|
/// block is past the first.
|
|
fn give(&mut self, chunks: Vec<Chunk>, now: u64) -> bool {
|
|
let mut idle = Vec::new();
|
|
for chunk in chunks {
|
|
let Some(index) = (self.blocks.iter()).position(|block| block.buffer == chunk.buffer)
|
|
else {
|
|
continue;
|
|
};
|
|
self.free += 1;
|
|
let block = &mut self.blocks[index];
|
|
block.free.push(chunk);
|
|
if block.free.len() == block.chunks {
|
|
idle.push(index);
|
|
}
|
|
}
|
|
let free = self.free;
|
|
for &index in &idle {
|
|
self.blocks[index].idle = Some(Idle {
|
|
since: now,
|
|
low: free,
|
|
});
|
|
}
|
|
idle.iter().any(|&index| index > 0)
|
|
}
|
|
|
|
/// Takes the block at `index` out, every chunk of it free, for the block-maker thread to free:
|
|
/// the ring has its chunks free no longer, so neither has any idle block's low.
|
|
fn remove(&mut self, index: usize) -> memory::Loose {
|
|
let block = self.blocks.remove(index);
|
|
self.free -= block.chunks;
|
|
for idle in self
|
|
.blocks
|
|
.iter_mut()
|
|
.filter_map(|block| block.idle.as_mut())
|
|
{
|
|
idle.low = idle.low.saturating_sub(block.chunks);
|
|
}
|
|
memory::Loose::RingBlock {
|
|
buffer: block.buffer,
|
|
memory: block.memory,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Where the chunks of a block at device address `address` lie, for writes at multiples of
|
|
/// `align` (a power of two, at most 256): the first at the block's first byte whose address is a
|
|
/// multiple of `align` (its offset in the block, the skew), each next [`CHUNK`] past it, and as
|
|
/// many as the block holds whole. Vulkan places a buffer's address at a multiple of the largest
|
|
/// of its memory requirements' alignment and the offset alignments of its usages
|
|
/// (`vkGetBufferDeviceAddress`), which may be less than 16: a block placed at a multiple of
|
|
/// `align` has a skew of 0 and [`SPARE`] chunks, and any other one fewer. The skew is a multiple
|
|
/// of the block's own placement, so a chunk's offset in the block's buffer is a multiple of the
|
|
/// device's `minStorageBufferOffsetAlignment`, which that placement holds.
|
|
pub(crate) fn chunk_starts(address: u64, align: u64) -> (u64, u64) {
|
|
let skew = address.next_multiple_of(align) - address;
|
|
(skew, (BLOCK - skew) / CHUNK)
|
|
}
|
|
|
|
/// Counts a take's wait for the block-maker thread's block, begun at `since` where it waited.
|
|
fn waited(core: &Core, since: Option<u64>) {
|
|
if let Some(since) = since {
|
|
(core.counters).maker_wait(crate::host_time().saturating_sub(since));
|
|
}
|
|
}
|
|
|
|
/// Makes a ring block: a buffer with every buffer usage on an allocation of the ring type with a
|
|
/// device address, mapped. Returns it with its device and host addresses. Its allocation is
|
|
/// counted at [`Site::RingBlock`] on a consumer's thread.
|
|
fn make(core: &Core) -> Result<(Made, u64, Mapping), Error> {
|
|
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
|
|
core.ring.meet_park();
|
|
let device = &core.device;
|
|
let info = vk::BufferCreateInfo::default()
|
|
.size(BLOCK)
|
|
.usage(floor::BUFFER_USAGE)
|
|
.sharing_mode(vk::SharingMode::EXCLUSIVE);
|
|
// SAFETY: the device is live.
|
|
let buffer =
|
|
unsafe { device.create_buffer(&info, None) }.map_err(Error::vulkan("vkCreateBuffer"))?;
|
|
// SAFETY: `buffer` is the device's.
|
|
let requirements = unsafe { device.get_buffer_memory_requirements(buffer) };
|
|
let mut flags =
|
|
vk::MemoryAllocateFlagsInfo::default().flags(vk::MemoryAllocateFlags::DEVICE_ADDRESS);
|
|
let allocate = vk::MemoryAllocateInfo::default()
|
|
.allocation_size(requirements.size)
|
|
.memory_type_index(core.memory_types.ring)
|
|
.push_next(&mut flags);
|
|
// SAFETY: the floor chose the ring type for buffers of this usage, and `bufferDeviceAddress`
|
|
// is enabled.
|
|
let allocated = unsafe {
|
|
memory::allocate(
|
|
device,
|
|
&core.counters,
|
|
core.max_allocations,
|
|
&allocate,
|
|
Some(Site::RingBlock),
|
|
)
|
|
};
|
|
let memory = match allocated {
|
|
Ok(memory) => memory,
|
|
Err(error) => {
|
|
// SAFETY: `buffer` is unused.
|
|
unsafe { device.destroy_buffer(buffer, None) };
|
|
return Err(error);
|
|
}
|
|
};
|
|
core.counters.count(Metric::BlocksMade);
|
|
let block = Made { buffer, memory };
|
|
match finish(device, &block) {
|
|
Ok((address, host)) => {
|
|
// Noted; freed by the idle rule (`Ring::due`) or at the teardown.
|
|
(core.spans).made(block.buffer, address, BLOCK, RangeKind::RingBlock);
|
|
Ok((block, address, host))
|
|
}
|
|
Err(error) => {
|
|
// SAFETY: nothing uses the block.
|
|
unsafe {
|
|
device.destroy_buffer(block.buffer, None);
|
|
memory::free(device, block.memory);
|
|
}
|
|
core.counters.fall(Gauge::Blocks);
|
|
Err(error)
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Binds a ring block's memory, reads its address and maps it.
|
|
fn finish(device: &ash::Device, block: &Made) -> Result<(u64, Mapping), Error> {
|
|
// SAFETY: the allocation is the buffer's size and of a type its requirements allow.
|
|
unsafe { device.bind_buffer_memory(block.buffer, block.memory, 0) }
|
|
.map_err(Error::vulkan("vkBindBufferMemory"))?;
|
|
let info = vk::BufferDeviceAddressInfo::default().buffer(block.buffer);
|
|
// SAFETY: the buffer has device-address usage and is bound.
|
|
let address = unsafe { device.get_buffer_device_address(&info) };
|
|
// SAFETY: the ring type is host-visible, and the memory is not mapped.
|
|
let pointer =
|
|
unsafe { device.map_memory(block.memory, 0, vk::WHOLE_SIZE, vk::MemoryMapFlags::empty()) }
|
|
.map_err(Error::vulkan("vkMapMemory"))?;
|
|
let host = NonNull::new(pointer.cast::<u8>()).ok_or(Error::Vulkan {
|
|
call: "vkMapMemory",
|
|
result: vk::Result::ERROR_MEMORY_MAP_FAILED,
|
|
})?;
|
|
Ok((address, Mapping::new(host)))
|
|
}
|
|
|
|
/// A command buffer's part of the ring: the chunks it took, the last one being written.
|
|
#[derive(Default)]
|
|
pub(crate) struct Writes {
|
|
chunks: Vec<Chunk>,
|
|
/// Bytes used of the last chunk.
|
|
used: u64,
|
|
}
|
|
|
|
impl Writes {
|
|
/// Copies `bytes`, at most a chunk, into the ring at a device address that is a multiple of
|
|
/// the ring's alignment (at least 16 bytes, `Ring::align`), and returns where it lies.
|
|
pub(crate) fn write(&mut self, core: &Core, bytes: &[u8]) -> Result<Placed, Error> {
|
|
let len = bytes.len() as u64;
|
|
debug_assert!(len <= CHUNK);
|
|
let start = self.used.next_multiple_of(core.ring.align);
|
|
let chunk = match self.chunks.last() {
|
|
Some(chunk) if start + len <= CHUNK => {
|
|
self.used = start + len;
|
|
(*chunk, start)
|
|
}
|
|
_ => {
|
|
let chunk = core.ring.take(core)?;
|
|
self.chunks.push(chunk);
|
|
self.used = len;
|
|
(chunk, 0)
|
|
}
|
|
};
|
|
let (chunk, offset) = chunk;
|
|
// SAFETY: `offset..offset + len` lies in the chunk, which this command buffer alone writes
|
|
// until it retires, and which no pending work reads: its last command buffer retired.
|
|
unsafe {
|
|
std::ptr::copy_nonoverlapping(
|
|
bytes.as_ptr(),
|
|
chunk.host.at(offset).as_ptr(),
|
|
bytes.len(),
|
|
)
|
|
};
|
|
Ok(Placed {
|
|
address: chunk.address + offset,
|
|
buffer: chunk.buffer,
|
|
offset: chunk.offset + offset,
|
|
})
|
|
}
|
|
|
|
/// Gives the chunks back once the command buffer retired or never ran.
|
|
pub(crate) fn give_back(self, core: &Core) {
|
|
if !self.chunks.is_empty() {
|
|
core.ring.give_back(core, self.chunks);
|
|
}
|
|
}
|
|
}
|