Files
metal2vulkan/crates/metal2vulkan-runtime/src/kernel_map.rs
T
Anees Iqbal 7a1da6cb22 rt: a draw through buffers bound at a multiple of 4 below their alignment draws the state's word-bound content
Row L97 (the draw residual). A dispatch of a function's kernel whose buffer
argument of 8 or 16 is bound at a multiple of 4 below that alignment runs a
variant of its kernel that holds the slot to 4 (8 where a 64-bit atomic may
reach it). A draw refused such a bind (Refusal::BufferOffsetAlignment). It
now draws the same way.

- RenderPipelineState::for_words(device, words) makes the state's content
  with LoweringInputs::word_bound_buffers set for its vertex function (bits
  0..31) and fragment function (bits 32..63). The device's map of contents
  keeps it under the state's key with that mask (KernelKey.words widens to
  u64). Like a pass's 2D-array content, it has no cache record of its own.
  Its samplers are numbered at the state's indices; a mismatch is
  Gap::KernelInput (ConstexprSampler).
- RenderCommandEncoder keeps the state set (`base`) apart from the state it
  draws through (`pipeline`). Where a draw's facts are not held (a bind or
  the state changed), bind_words reads the base's buffer address fields. A
  slot of mask 7 or 15 whose bound address is a multiple of 4 but not of
  its alignment sets its bit. The mask is ANDed with the slots the state
  lowers from AIR (word_slots: a function the consumer compiled has none,
  and its bind stays refused). A new mask switches `pipeline` to that
  content, or back to `base`. An execution of an indirect command buffer
  draws through `base`.
- The draw's own checks then hold each slot to the content's alignment: an
  address off a multiple of 4 is still refused, as is one off 8 that a
  64-bit atomic may reach.

Cost: a draw bound aligned keeps the state it was set with, and the scan of
its address fields runs only where the draw's facts are found again
(expected from the code, not measured). The first draw of a new mask lowers
both functions again and makes the content's VkPipeline (a first-use wait),
as the compute variant does. A later draw of that mask finds the content.

Docs: the runtime README (Render encoders: the draw bullet; Compute
encoders: the variant's paragraph); error.rs's BufferOffsetAlignment;
docs/API.md section 1 and its accepted differences. REFUSALS.md unchanged
(refusal_surface --check 0); api signatures --check 0.

Verified:
- Green on lavapipe, m3-max-79015 (at this commit's tree before its rebase
  onto 8dd00ec58c). Over tests::draw, render_offsets and indirect: 67 of 67
  passed, 838 skipped. The new test draws every case through the content,
  and the second draw of a bind finds it.
- The two draw-alignment tests on a card per vendor, 2 of 2 passed on each:
  - Radeon 780M (RADV PHOENIX, Mesa 26.2.6), m3-max-79076, at this commit;
  - RTX 3090 (NVIDIA 620.70.06), m3-max-79043, and Iris Xe (ANV, Mesa
    26.2.6), m3-max-79051, both before the rebase.
- m3-max-79086, at this commit: workspace clippy (all targets, all
  features, -D warnings) EXIT=0 in all three configurations (plain,
  --cfg m2v_cpu_icd, --cfg m2v_gpu); Rustdoc EXIT=0; the runtime's private
  Rustdoc EXIT=0. The runtime suite on lavapipe: 903 tests run, 903 passed,
  3 skipped.
2026-12-02 09:30:59 -08:00

213 lines
8.0 KiB
Rust

//! The device's compiled pipelines by their content ([`KernelKey`]), compute and render alike in
//! one map: every pipeline state of one content shares one translation, its shader modules and
//! their `VkPipeline`s, and a state of a content the map holds costs a lookup. The map holds at
//! most [`KERNEL_ENTRIES`], forgetting the least recently used past it. It bounds what it holds,
//! not what lives: a state keeps the content it took, which goes once its last state and the map
//! have let it go. The translator's keys name their kind (`compute` or `render`), so a key of
//! one kind never meets a content of the other.
use crate::counters::{Counters, Gauge, Metric};
use crate::device::lock;
use crate::pipeline::Compiled;
use crate::render::RenderCompiled;
use metal2vulkan::cache::PipelineKey;
use std::collections::HashMap;
use std::hash::Hash;
use std::sync::{Arc, Mutex};
/// The entries the map holds at most.
pub(crate) const KERNEL_ENTRIES: usize = 1024;
/// What a pipeline state compiles: the translator's key of its descriptor
/// (`Device::compute_pipeline_key`: the kernel's AIR and entry, its constant values, linked
/// functions and dynamic libraries, its lowering inputs, the descriptor's fields that change the
/// compile, the device's profile and the translator's semantics version; or
/// `Device::queried_render_descriptor_key`, every field of a render pipeline descriptor with its
/// functions keyed as a kernel is; neither key decodes a function), and a compute descriptor's
/// `requiredThreadsPerThreadgroup`, which the state answers as its `maxTotalThreadsPerThreadgroup`
/// and the translator's key leaves out (`None` for a render pipeline); for a compute state's
/// variant, its texture slots that hold an 8-bit sRGB texture's UNORM twin and its buffer slots
/// bound at a multiple of 4 below their argument's alignment, bit `i` slot `i` in each
/// (`PipelineInner::variant`); for a render state's content for a pass, the colours its
/// fragment function fetches through an element holding a 2D array view, bit `i` colour `i`
/// (`RenderPipelineState::for_pass`); and for a render state's content for its draws' buffers,
/// the buffer slots bound at a multiple of 4 below their argument's alignment, bit `i` the vertex
/// function's slot `i` and bit `32 + i` the fragment function's
/// (`RenderPipelineState::for_words`). Each is 0 for every other content.
#[derive(Clone, PartialEq, Eq, Hash)]
pub(crate) struct KernelKey {
pub(crate) pipeline: PipelineKey,
pub(crate) required: Option<[u32; 3]>,
pub(crate) srgb: u128,
pub(crate) words: u64,
pub(crate) arrays: u8,
}
/// What one content compiles to.
#[derive(Clone)]
pub(crate) enum Content {
Kernel(Arc<Compiled>),
Render(Arc<RenderCompiled>),
}
impl Content {
/// The address of what it holds, which names it.
fn at(&self) -> *const () {
match self {
Content::Kernel(compiled) => Arc::as_ptr(compiled).cast(),
Content::Render(compiled) => Arc::as_ptr(compiled).cast(),
}
}
}
/// The device's map of compiled contents.
pub(crate) struct KernelMap {
map: Mutex<Lru<KernelKey, Content>>,
}
impl KernelMap {
/// An empty map of [`KERNEL_ENTRIES`] entries.
pub(crate) fn new() -> KernelMap {
KernelMap {
map: Mutex::new(Lru::new(KERNEL_ENTRIES)),
}
}
/// The compiled kernel of `key`, where the map holds it.
pub(crate) fn find(&self, key: &KernelKey) -> Option<Arc<Compiled>> {
match lock(&self.map).get(key)? {
Content::Kernel(compiled) => Some(compiled),
Content::Render(_) => None,
}
}
/// The compiled render pipeline of `key`, where the map holds it.
pub(crate) fn find_render(&self, key: &KernelKey) -> Option<Arc<RenderCompiled>> {
match lock(&self.map).get(key)? {
Content::Render(compiled) => Some(compiled),
Content::Kernel(_) => None,
}
}
/// The kernel the map holds under `key`: the one it holds already (another thread compiled
/// the content first), or `compiled`, kept now. Past the cap, the least recently used entry
/// is forgotten, and goes once no state holds it.
pub(crate) fn keep(
&self,
key: KernelKey,
compiled: Arc<Compiled>,
counters: &Counters,
) -> Arc<Compiled> {
match self.keep_content(key, Content::Kernel(Arc::clone(&compiled)), counters) {
Content::Kernel(kept) => kept,
Content::Render(_) => compiled,
}
}
/// The render pipeline the map holds under `key`, as [`keep`](Self::keep) keeps a kernel.
pub(crate) fn keep_render(
&self,
key: KernelKey,
compiled: Arc<RenderCompiled>,
counters: &Counters,
) -> Arc<RenderCompiled> {
match self.keep_content(key, Content::Render(Arc::clone(&compiled)), counters) {
Content::Render(kept) => kept,
Content::Kernel(_) => compiled,
}
}
fn keep_content(&self, key: KernelKey, content: Content, counters: &Counters) -> Content {
// What the map lets go is dropped after its lock, as a content's end gives the reaper
// work.
let ours = content.at();
let (kept, gone) = lock(&self.map).keep(key, content);
if kept.at() != ours {
counters.count(Metric::KernelMakesDropped);
}
// A new entry beside the others is one more; one in place of the oldest, or the entry
// held already, leaves as many.
if gone.is_none() {
counters.rise(Gauge::KernelEntries);
}
drop(gone);
kept
}
/// Forgets every entry, at the device's end.
pub(crate) fn clear(&self, counters: &Counters) {
let held = lock(&self.map).clear();
for _ in &held {
counters.fall(Gauge::KernelEntries);
}
drop(held);
}
/// For the tests: a map of `cap` entries in place of [`KERNEL_ENTRIES`], set before any state.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) fn set_cap(&self, cap: usize) {
lock(&self.map).cap = cap;
}
}
/// A map of at most `cap` entries, the least recently used forgotten first.
pub(crate) struct Lru<K, V> {
cap: usize,
clock: u64,
entries: HashMap<K, (V, u64)>,
}
impl<K: Eq + Hash + Clone, V: Clone> Lru<K, V> {
/// An empty map of at most `cap` entries.
pub(crate) fn new(cap: usize) -> Lru<K, V> {
Lru {
cap,
clock: 0,
entries: HashMap::new(),
}
}
/// The value of `key`, now the most recently used.
pub(crate) fn get(&mut self, key: &K) -> Option<V> {
self.clock += 1;
let clock = self.clock;
let (value, used) = self.entries.get_mut(key)?;
*used = clock;
Some(value.clone())
}
/// The value held under `key`, now the most recently used: the one held already, or `value`,
/// kept now; and what that let go: `value` where `key` held one already, the least recently
/// used entry's where keeping `value` passed the cap, else nothing.
pub(crate) fn keep(&mut self, key: K, value: V) -> (V, Option<V>) {
self.clock += 1;
let clock = self.clock;
if let Some((held, used)) = self.entries.get_mut(&key) {
*used = clock;
return (held.clone(), Some(value));
}
let mut forgotten = None;
if self.entries.len() >= self.cap.max(1) {
let oldest = (self.entries.iter())
.min_by_key(|(_, (_, used))| *used)
.map(|(key, _)| key.clone());
if let Some((value, _)) = oldest.and_then(|oldest| self.entries.remove(&oldest)) {
forgotten = Some(value);
}
}
self.entries.insert(key, (value.clone(), clock));
(value, forgotten)
}
/// Every value, the map left empty.
pub(crate) fn clear(&mut self) -> Vec<V> {
self.entries.drain().map(|(_, (value, _))| value).collect()
}
/// The entries held.
#[cfg(test)]
pub(crate) fn len(&self) -> usize {
self.entries.len()
}
}