feat(display): the display's GPU composes each offered swap into the shared hidden buffer, which flips once the composition completes and is composed over by a newer frame before then, with the CPU compose as the fallback reported once per reason and GPU and CPU counts in DCP PACING

This commit is contained in:
Tyler Smith committed 2026-11-19 17:37:02 -05:00
1 parent 00dc25c504
commit 0ae834ade0
10 files changed
+540 -10

No files matched your search

+4
View File
@@ -405,6 +405,10 @@ impl Scanout for MirroredScanout {
self.scanout.try_present_gpu(layers, damage, physical)
}
fn take_gpu_stats(&mut self) -> stela_soc::scanout::GpuStats {
self.scanout.take_gpu_stats()
}
fn set_refresh(&mut self, millihertz: u32) -> Result<()> {
self.scanout.set_refresh(millihertz)
}
+41 -3
View File
@@ -32,6 +32,9 @@ use core::{cell::UnsafeCell, ffi::c_int, ffi::c_void, ptr::NonNull};
use stela_contracts::refuse;
use stela_drivers::gpu::metal::kms::{self, Display, Drm, Error as DisplayError, Watched};
use stela_soc::machine::{MonitorId, Scanout, ScanoutFormat, ScanoutMode};
use stela_soc::scanout::{GpuPresent, GpuStats, Layer};
mod composition;
/// A GPU's primary node, the DRM master.
struct Node(c_int);
@@ -101,6 +104,8 @@ struct KmsScanout {
/// The counter at the display's last vertical blank as the last look
/// read it, when it could ([`Display::last_vblank_ns`]).
vblank_tsc: Option<u64>,
/// The display's frames its GPU composes.
composition: composition::Composition,
}
impl Scanout for KmsScanout {
@@ -122,12 +127,13 @@ impl Scanout for KmsScanout {
fn present(&mut self, rows: &[u8]) -> Result<()> {
self.presented = true;
let Some((_, display)) = &mut self.display else {
let Some((name, display)) = &mut self.display else {
// Shown nowhere: a display taken later asks every row of the
// next frame, its buffers holding none.
self.look();
return Ok(());
};
self.composition.settle(name, self.tsc_hz);
console::release();
let presented = display.present(rows);
self.blank &= presented.is_err();
@@ -142,10 +148,11 @@ impl Scanout for KmsScanout {
fill: &mut dyn FnMut(usize, &mut [u8]) -> Result<()>,
) -> Result<bool> {
self.presented = true;
let Some((_, display)) = &mut self.display else {
let Some((name, display)) = &mut self.display else {
self.look();
return Ok(true);
};
self.composition.settle(name, self.tsc_hz);
let prepared = display.prepare_rows(damage, fill)?;
console::release();
let presented = prepared.present();
@@ -154,6 +161,34 @@ impl Scanout for KmsScanout {
Ok(true)
}
/// The display's GPU composes the frame into the hidden buffer, which
/// flips once the composition completed ([`composition`]).
fn try_present_gpu(
&mut self,
layers: &[Layer],
damage: Option<Range<usize>>,
physical: &dyn Fn(u64) -> Option<u64>,
) -> Result<GpuPresent> {
let Some((name, display)) = &mut self.display else {
return Ok(GpuPresent::Declined(
"no GPU display shows the guest's frames",
));
};
let offered = self
.composition
.offer(name, display, layers, damage, physical, self.tsc_hz);
if offered == GpuPresent::Taken {
self.presented = true;
self.blank = false;
console::release();
}
Ok(offered)
}
fn take_gpu_stats(&mut self) -> GpuStats {
self.composition.take_stats()
}
fn refresh_rates(&self) -> Vec<u32> {
match &self.display {
Some((_, display)) => display.refresh_rates(),
@@ -194,10 +229,12 @@ impl Scanout for KmsScanout {
.display
.as_ref()
.is_some_and(|(_, display)| display.queued())
|| self.composition.pending()
}
fn flush(&mut self) -> Result<()> {
if let Some((_, display)) = &mut self.display {
if let Some((name, display)) = &mut self.display {
self.composition.flush(name, display, self.tsc_hz);
let flushed = display.flush();
finish_present(display, flushed)?;
}
@@ -248,6 +285,7 @@ impl KmsScanout {
tsc_hz,
reported: false,
vblank_tsc: None,
composition: composition::Composition::default(),
}
}
@@ -0,0 +1,317 @@
//! The display's frames composed by its GPU.
//!
//! Where the display's GPU serves Metal, the boot CPU shares the display's
//! three scanout buffers with that service once, and each composed swap
//! the DCP model offers ([`Scanout::try_present_gpu`]) is committed as a
//! composition of its damaged rows into the hidden buffer, from its
//! layers' guest pages. The hidden buffer's flip waits for the
//! composition: the next present or a flush on the boot CPU queues it once
//! the service shows it complete. A newer frame before then is composed
//! over it, the GPU running both in order, so the older one is replaced,
//! never torn. A frame the CPU draws first waits for the composition, for
//! [`SETTLE_MS`] at most.
//!
//! [`Scanout::try_present_gpu`]: stela_soc::machine::Scanout::try_present_gpu
use super::{super::gate, Node};
use crate::{engine::host, output};
use alloc::{sync::Arc, vec::Vec};
use core::ops::Range;
use stela_contracts::gate::MemoryRange;
use stela_drivers::gpu::metal::{
binding::ComposeFormat,
device::display::{DisplayFrame, DisplayLayer, DisplayPlane},
error::Error,
kms::Display,
service::DisplayTarget,
};
use stela_soc::scanout::{GpuPresent, GpuStats, Layer, PixelFormat};
/// The longest a frame the CPU draws waits for the composition before it.
pub(super) const SETTLE_MS: u64 = 50;
/// The GPU's composition of the display's frames.
#[derive(Default)]
pub(super) struct Composition {
/// The display's buffers shared with its GPU's service, once shared.
shared: Option<Shared>,
/// The frame composed into the hidden buffer, whose flip waits for its
/// composition: its serial and the counter at its commit.
pending: Option<(u64, u64)>,
/// Why the GPU composes none of the display's frames.
refused: Option<&'static str>,
/// The first refusal's details were reported, and a composition that
/// outlasted [`SETTLE_MS`].
reported: bool,
outlasted: bool,
stats: GpuStats,
}
struct Shared {
service: &'static Arc<gate::Shared>,
target: DisplayTarget,
/// Each shared buffer's framebuffer and bytes per row.
buffers: [(u32, u32); 3],
}
impl Composition {
/// Composes `layers` into `display`'s hidden buffer on the GPU of
/// `name`, or declines, which leaves the CPU to compose them.
pub(super) fn offer(
&mut self,
name: &str,
display: &mut Display<Node>,
layers: &[Layer],
damage: Option<Range<usize>>,
physical: &dyn Fn(u64) -> Option<u64>,
tsc_hz: u64,
) -> GpuPresent {
if let Some(reason) = self.refused {
return GpuPresent::Declined(reason);
}
let frame_layers = match display_layers(layers, physical) {
Ok(frame_layers) => frame_layers,
Err(reason) => return GpuPresent::Declined(reason),
};
if let Err(reason) = self.share(name, display) {
return GpuPresent::Declined(reason);
}
// The frame before goes to the screen once composed; one still
// being composed is composed over.
let replaced = match self.composed() {
Some(true) => {
self.flipped(display, tsc_hz);
false
}
Some(false) => true,
None => {
// Its device was lost: its buffers are shared again.
self.pending = None;
self.shared = None;
return GpuPresent::Declined("the display's GPU device was lost");
}
};
let Some(shared) = &self.shared else {
return GpuPresent::Declined("the display's buffers are not shared");
};
let (framebuffer, rows) = display.draw_rows(damage);
let Some(index) = shared
.buffers
.iter()
.position(|&(buffer, _)| buffer == framebuffer)
else {
return GpuPresent::Declined("the display's hidden buffer was not shared");
};
let frame = DisplayFrame {
pitch: shared.buffers[index].1,
width: display.size().0,
rows: rows.start as u32..rows.end as u32,
layers: frame_layers,
};
match shared
.service
.compose_display(&shared.target, index, &frame)
{
Ok(serial) => {
if let Some((_, committed)) = self.pending.replace((serial, host::rdtsc())) {
self.note(committed, tsc_hz, replaced);
}
GpuPresent::Taken
}
Err(Error::DeviceLost) => {
self.shared = None;
self.pending = None;
GpuPresent::Declined("the display's GPU device was lost")
}
Err(Error::Unsupported(_)) => {
GpuPresent::Declined("the GPU service was busy past its wait bound")
}
Err(error) => {
self.report(name, "refused a display composition", error);
GpuPresent::Declined("the display's GPU refused a composition")
}
}
}
/// Whether a composition waits for its flip.
pub(super) fn pending(&self) -> bool {
self.pending.is_some()
}
/// Queues the flip of the hidden buffer's composed frame once its
/// composition completed. On the boot CPU, the display's buffers are
/// shared first, so presents on any processor may compose.
pub(super) fn flush(&mut self, name: &str, display: &mut Display<Node>, tsc_hz: u64) {
if self.refused.is_none() {
let _ = self.share(name, display);
}
match self.composed() {
Some(true) => self.flipped(display, tsc_hz),
Some(false) => {}
None => {
self.pending = None;
self.shared = None;
}
}
}
/// Before the CPU draws into the hidden buffer: waits for the
/// composition there, for [`SETTLE_MS`] at most, and forgets it, as
/// the CPU's frame replaces it.
pub(super) fn settle(&mut self, name: &str, tsc_hz: u64) {
let Some((_, committed)) = self.pending else {
return;
};
let deadline = committed.saturating_add(tsc_hz / 1000 * SETTLE_MS);
while self.composed() == Some(false) {
if host::rdtsc() >= deadline {
if !core::mem::replace(&mut self.outlasted, true) {
output::arguments(format_args!(
"GPU {name}: a display composition outlasted {SETTLE_MS} ms; the CPU \
draws over it\n"
));
}
break;
}
core::hint::spin_loop();
}
self.pending = None;
self.note(committed, tsc_hz, true);
}
pub(super) fn take_stats(&mut self) -> GpuStats {
core::mem::take(&mut self.stats)
}
/// Whether the pending composition completed: true with none, `None`
/// once its device was lost or replaced.
fn composed(&self) -> Option<bool> {
let Some((serial, _)) = self.pending else {
return Some(true);
};
let shared = self.shared.as_ref()?;
shared.service.display_composed(&shared.target, serial)
}
/// The pending composition completed: its flip is queued.
fn flipped(&mut self, display: &mut Display<Node>, tsc_hz: u64) {
let Some((_, committed)) = self.pending.take() else {
return;
};
self.note(committed, tsc_hz, false);
// A refused flip is the display's to report at its next flush.
let _ = display.present_drawn();
}
fn note(&mut self, committed: u64, tsc_hz: u64, replaced: bool) {
let ticks = host::rdtsc().saturating_sub(committed);
let ns = u64::try_from(u128::from(ticks) * 1_000_000_000 / u128::from(tsc_hz.max(1)))
.unwrap_or(u64::MAX);
let stats = &mut self.stats;
if replaced {
stats.replaced += 1;
} else {
stats.flipped += 1;
}
stats.total_ns = stats.total_ns.saturating_add(ns);
stats.longest_ns = stats.longest_ns.max(ns);
}
/// Shares `display`'s buffers with the service of its GPU `name`, on
/// the boot CPU, where a DRM request completes at once.
fn share(&mut self, name: &str, display: &mut Display<Node>) -> Result<(), &'static str> {
if self.shared.is_some() {
return Ok(());
}
let service = gate::service_of(name).ok_or("no Metal service runs on the display's GPU")?;
let buffers = match display.share_buffers() {
None => return Err("the display's buffers are shared from the boot CPU first"),
Some(Err(error)) => {
self.report(name, "shares no scanout buffer", error);
return Err(self.refuse("the display's driver shares no scanout buffer"));
}
Some(Ok(buffers)) => buffers,
};
let descriptors: Vec<_> = buffers
.iter()
.map(|buffer| (buffer.fd, buffer.bytes as u64))
.collect();
match service.share_scanouts(&descriptors) {
Ok(target) => {
self.shared = Some(Shared {
service,
target,
buffers: buffers.map(|buffer| (buffer.framebuffer, buffer.pitch as u32)),
});
output::arguments(format_args!(
"GPU {name}: composes the display's frames into its shared scanout buffers\n"
));
Ok(())
}
Err(error) => {
// The descriptors stay open: the driver may have taken some.
self.report(name, "imports no scanout buffer", error);
Err(self.refuse("the display's GPU imports no scanout buffer"))
}
}
}
fn refuse(&mut self, reason: &'static str) -> &'static str {
self.refused = Some(reason);
reason
}
fn report(&mut self, name: &str, what: &str, error: impl core::fmt::Debug) {
if !core::mem::replace(&mut self.reported, true) {
output::arguments(format_args!(
"GPU {name}: the display's GPU {what}: {error:?}\n"
));
}
}
}
/// `layers` as the compose kernel reads them: their planes' guest pages
/// by `physical`, or why the kernel cannot read them.
fn display_layers(
layers: &[Layer],
physical: &dyn Fn(u64) -> Option<u64>,
) -> Result<Vec<DisplayLayer>, &'static str> {
if layers.len() > 4 {
return Err("the GPU composes four layers at most");
}
let rect = |rect: stela_soc::scanout::Rect| [rect.x, rect.y, rect.width, rect.height];
layers
.iter()
.map(|layer| {
let mut planes = layer
.planes(physical)
.ok_or("a layer's pages did not resolve")?
.into_iter()
.map(|plane| DisplayPlane {
ranges: plane
.runs
.into_iter()
.map(|(address, bytes)| MemoryRange { address, bytes })
.collect(),
origin: plane.origin,
});
let color = planes.next().ok_or("a layer has its colour plane")?;
let surface = layer.surface;
let (format, alpha_stride) = match surface.format {
PixelFormat::Bgra8888 => (ComposeFormat::Bgra8, 0),
PixelFormat::Rgba8888 => (ComposeFormat::Rgba8, 0),
PixelFormat::Argb2101010 => (ComposeFormat::Argb2101010, 0),
PixelFormat::Xr10A8 { alpha_stride, .. } => (ComposeFormat::Xr10A8, alpha_stride),
};
Ok(DisplayLayer {
color,
alpha: planes.next(),
stride: surface.stride,
alpha_stride,
format,
premultiplied: layer.premultiplied,
source: rect(layer.source),
destination: rect(layer.destination),
})
})
.collect()
}
+16 -1
View File
@@ -45,7 +45,7 @@ use stela_linux::{
};
use stela_loader::{apple_device_tree::DeviceTree, stela_gpu};
type Shared = SharedService<NativeBackend, AirCompiler>;
pub(super) type Shared = SharedService<NativeBackend, AirCompiler>;
/// A process's main stack, as big as the deepest compile LLVM bounds.
pub(super) const STACK_BYTES: usize = 16 << 20;
@@ -61,6 +61,8 @@ static SERVICES: AtomicPtr<Vec<Arc<Shared>>> = AtomicPtr::new(ptr::null_mut());
/// The bound GPU, by its index (its DRM minor), of each service, in the
/// services' order.
static SERVED: AtomicPtr<Vec<usize>> = AtomicPtr::new(ptr::null_mut());
/// The name of each service's GPU, in the same order.
static SERVICE_GPUS: AtomicPtr<Vec<String>> = AtomicPtr::new(ptr::null_mut());
/// The compile stacks ([`open_gpu`]), whose jobs [`run`] runs with the
/// shootdown vector open; a GPU past these runs its jobs masked.
@@ -1287,8 +1289,13 @@ pub(in crate::engine) fn open_service() {
));
}
}
let names: Vec<String> = opened
.iter()
.map(|&(index, _)| bound[index].name.clone())
.collect();
let (served, services): (Vec<_>, Vec<_>) = opened.into_iter().unzip();
SERVED.store(Box::into_raw(Box::new(served)), Ordering::Release);
SERVICE_GPUS.store(Box::into_raw(Box::new(names)), Ordering::Release);
SERVICES.store(Box::into_raw(Box::new(services)), Ordering::Release);
}
@@ -1498,6 +1505,14 @@ pub(in crate::engine) fn profile_passes() {
pass_times::set_pass_profile(true);
}
/// The service of the GPU named `name`, once the services are open.
pub(super) fn service_of(name: &str) -> Option<&'static Arc<Shared>> {
// SAFETY: the names are published before the services and leaked.
let names = unsafe { SERVICE_GPUS.load(Ordering::Acquire).as_ref() }?;
let index = names.iter().position(|gpu| gpu == name)?;
shared().get(index)
}
pub(super) fn shared() -> &'static [Arc<Shared>] {
// SAFETY: the published services are leaked, so they live for the boot.
unsafe { SERVICES.load(Ordering::Acquire).as_ref() }.map_or(&[], Vec::as_slice)
+3 -1
View File
@@ -2320,8 +2320,10 @@ impl<D: Drm> Display<D> {
/// The buffer the next frame fills, by its framebuffer, and the rows of
/// it the GPU must compose: `damage` (`None`: every row) and the rows it
/// lacks of the newest frame. Until [`Self::present_drawn`] the CPU
/// fills no rows.
/// fills no rows, and a frame the buffer held waits for no flip: the
/// GPU draws the newer frame over it, the rows it showed included.
pub fn draw_rows(&mut self, damage: Option<Range<usize>>) -> (u32, Range<usize>) {
self.queued = false;
let height = self.height as usize;
let damage = damage.map_or(0..height, |rows| {
rows.start.min(height)..rows.end.min(height)
@@ -240,7 +240,17 @@ fn the_gpu_composes_into_the_shared_hidden_buffer_and_its_frame_flips() {
display.present_drawn().unwrap();
let (_, rows) = display.draw_rows(Some(3..4));
assert_eq!(rows, 3..4);
// Where a request must wait, nothing is shared.
// Where a request must wait, nothing is shared, and a frame drawn
// waits for its flip until a newer frame drawn over it replaces it.
display.drm.immediate = false;
assert!(display.share_buffers().is_none());
display.present_drawn().unwrap();
assert!(display.queued());
let (_, rows) = display.draw_rows(Some(0..1));
assert_eq!(rows, 0..1, "it holds the frame it replaces whole");
assert!(!display.queued(), "no flip while the GPU draws");
let flips = display.drm.flips.len();
display.drm.immediate = true;
display.flush().unwrap();
assert_eq!(display.drm.flips.len(), flips);
}
+1 -1
View File
@@ -107,7 +107,7 @@ pub(crate) struct Missed;
/// The I/O address ranges `layer`'s source rows occupy in each of its
/// surface's planes: from its first row's first pixel to its last row's
/// last; `None` on overflow.
fn layer_spans(layer: &Layer) -> Option<Vec<Range<u64>>> {
pub(crate) fn layer_spans(layer: &Layer) -> Option<Vec<Range<u64>>> {
let source = layer.source;
if source.width == 0 || source.height == 0 {
return Some(Vec::new());
+25 -2
View File
@@ -98,7 +98,7 @@
//! (`plane.c`), which marks premultiplied only its formats without alpha
//! (XRGB, XBGR, XBGR2101010) and straight its ARGB ones: premultiplied over
//! black, an X byte of any value shows the colour unchanged.
use super::super::scanout::{self, Mode, Scanout};
use super::super::scanout::{self, GpuStats, Mode, Scanout};
use super::Log;
use super::abi::{self, Fields, IO_RETURN_SUCCESS, Interface, LINK_UNSUPPORTED, Method, Packed};
use super::avipc::DisplayState;
@@ -325,6 +325,11 @@ pub struct Pacing {
/// completed.
pub overlapped: u32,
pub most_unanswered: usize,
/// Swaps composed on the GPU and on the CPU, and what became of the
/// GPU's frames ([`Scanout::take_gpu_stats`]).
pub gpu_composed: u32,
pub cpu_composed: u32,
pub gpu: GpuStats,
/// The first [`SAMPLED_SWAPS`] swaps submitted in the window, each with
/// its own times: what decides when the AP starts its next frame, which
/// the window's averages cannot tell apart.
@@ -562,6 +567,17 @@ impl core::fmt::Display for Pacing {
self.overlapped,
self.most_unanswered,
)?;
let gpu = self.gpu;
write!(
f,
" composed=gpu:{}/cpu:{} gpu_frames=flipped:{}/replaced:{} gpu_ms={:.2}/{:.2}",
self.gpu_composed,
self.cpu_composed,
gpu.flipped,
gpu.replaced,
gpu.total_ns as f64 / 1e6 / f64::from(gpu.flipped + gpu.replaced).max(1.0),
gpu.longest_ns as f64 / 1e6,
)?;
let Some(first) = self.swaps.first() else {
return Ok(());
};
@@ -1327,7 +1343,11 @@ impl Methods {
if ticks < PACING_WINDOW {
return;
}
let pacing = core::mem::take(&mut self.pacing);
let mut pacing = core::mem::take(&mut self.pacing);
// A scanout composing now keeps its count for the next window.
if let Some(scanout) = &mut self.scanout {
pacing.gpu = scanout.take_gpu_stats();
}
if pacing.presented != 0 || pacing.submitted != 0 {
self.record_log(Log::Pacing(Box::new(Pacing {
ticks,
@@ -1513,6 +1533,7 @@ impl Methods {
else {
return Ok(false);
};
let on_gpu = declined.is_none() && result.is_ok();
if let Some(reason) = declined
&& self.cpu_composes.insert(reason)
{
@@ -1530,6 +1551,8 @@ impl Methods {
return self.repainted(result).map(|()| false);
}
result?;
self.pacing.gpu_composed += u32::from(on_gpu);
self.pacing.cpu_composed += u32::from(!on_gpu);
self.presented(batch);
Ok(true)
}
+14 -1
View File
@@ -1678,7 +1678,10 @@ fn pacing_reports_rate_gaps_stalls_lateness_and_queue_depth() {
assert!(
line.contains(&format!(" gaps=1:{}/2:0/3:1/4-7:0/8+:0 ", pacing.gaps - 1))
&& line.contains(" burst_fps=")
&& line.ends_with(" overlapped=1/1"),
&& line.contains(" overlapped=1/1 ")
&& line.ends_with(
" composed=gpu:0/cpu:0 gpu_frames=flipped:0/replaced:0 gpu_ms=0.00/0.00"
),
"{line}"
);
// A window in which nothing was submitted or shown is not reported.
@@ -3288,6 +3291,16 @@ fn a_composed_present_goes_to_the_gpu_and_falls_back_to_the_cpu_reported_once()
);
// Every swap completes either way; only the fallback composes rows.
assert_eq!(completed, submits.len());
let composed = (methods.pacing.gpu_composed, methods.pacing.cpu_composed);
let swaps = submits.len() as u32;
assert_eq!(
composed,
if declines.is_some() {
(0, swaps)
} else {
(swaps, 0)
}
);
let reports: Vec<_> = methods
.take_unmodeled()
.into_iter()
+108
View File
@@ -293,6 +293,12 @@ pub trait Scanout {
))
}
/// What became of the frames [`Self::try_present_gpu`] took since the
/// last call.
fn take_gpu_stats(&mut self) -> GpuStats {
GpuStats::default()
}
/// Whether an earlier present left work only [`Self::flush`] finishes,
/// such as a page flip whose request must wait for another processor.
fn queued(&self) -> bool {
@@ -393,6 +399,18 @@ pub enum GpuPresent {
Declined(&'static str),
}
/// What became of frames the GPU composed ([`Scanout::take_gpu_stats`]):
/// those flipped, those a newer frame replaced before their composition
/// completed, and the total and longest nanoseconds from a composition's
/// commit until it was seen complete.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct GpuStats {
pub flipped: u32,
pub replaced: u32,
pub total_ns: u64,
pub longest_ns: u64,
}
/// One surface plane the model reads pixels from: its format, size and the
/// DART I/O address (DVA) of its top-left pixel. Built from the driver's
/// `SurfaceContents` (`IOMFB::DCP::SurfaceContents::from`).
@@ -444,6 +462,17 @@ impl Rect {
/// stay bounded by the screen whatever the layer's ratio.
const SPAN_PER_SHOWN: usize = 4;
/// The page size of the guest RAM runs [`Layer::planes`] answers: the
/// host's, which every IOMMU page of the display holds whole.
pub const HOST_PAGE: u64 = 0x1000;
/// A plane of a layer in guest RAM ([`Layer::planes`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PlanePages {
pub runs: Vec<(u64, u64)>,
pub origin: i64,
}
/// One layer of a composed frame: a source rectangle of a surface shown in
/// a destination rectangle of the screen, its colour premultiplied by its
/// alpha or not.
@@ -481,6 +510,43 @@ impl Layer {
})
}
/// The planes of the layer's surface its source rows occupy, the
/// colour plane first: for each, the runs of guest RAM under its pages
/// in I/O address order, as `(physical address, bytes)` in whole
/// [`HOST_PAGE`]s, and the offset from the first run's first byte to
/// the plane's first pixel, negative when the rows start past the
/// plane's first page. `physical` resolves an I/O address; `None` when
/// a page does not resolve or an address overflows.
pub fn planes(&self, physical: &dyn Fn(u64) -> Option<u64>) -> Option<Vec<PlanePages>> {
let surface = self.surface;
let mut bases = alloc::vec![surface.iova];
if let PixelFormat::Xr10A8 { alpha, .. } = surface.format {
bases.push(alpha);
}
let spans = crate::dcp::compose::layer_spans(self)?;
let mut planes = Vec::new();
for (span, base) in spans.into_iter().zip(bases) {
let first = span.start & !(HOST_PAGE - 1);
let end = span
.end
.max(span.start + 1)
.checked_next_multiple_of(HOST_PAGE)?;
let mut runs: Vec<(u64, u64)> = Vec::new();
for page in (first..end).step_by(HOST_PAGE as usize) {
let address = physical(page)?;
match runs.last_mut() {
Some((start, bytes)) if *start + *bytes == address => *bytes += HOST_PAGE,
_ => runs.push((address, HOST_PAGE)),
}
}
planes.push(PlanePages {
runs,
origin: base.wrapping_sub(first) as i64,
});
}
Some(planes)
}
/// Whether the source is shown at its own size.
fn unscaled(&self) -> bool {
(self.source.width, self.source.height) == (self.destination.width, self.destination.height)
@@ -2764,4 +2830,46 @@ mod tests {
}
}
}
#[test]
fn a_layers_planes_are_the_runs_of_pages_under_its_rows() {
// Rows of 0x1000 bytes from I/O address 0x1_0800: the source's
// rows 1 and 2 span 0x1_1800..0x1_2840, the pages 0x1_1000 to
// 0x1_2000. Those pages lie at 0x50_0000 and 0x50_1000, then the
// alpha plane's page apart at 0x90_0000.
let mut surface = surface(0x400, 4, 0x1000, 0x1_0800);
surface.format = PixelFormat::Xr10A8 {
alpha: 0x2_0000,
alpha_stride: 0x400,
};
let source = Rect {
x: 0,
y: 1,
width: 0x10,
height: 2,
};
let layer = Layer::new(surface, source, Rect::whole(0x10, 2), false).unwrap();
let physical = |iova: u64| match iova {
0x1_1000 => Some(0x50_0000),
0x1_2000 => Some(0x50_1000),
0x2_0000 => Some(0x90_0000),
_ => None,
};
let planes = layer.planes(&physical).unwrap();
assert_eq!(
planes,
[
PlanePages {
runs: alloc::vec![(0x50_0000, 0x2000)],
origin: -0x800,
},
PlanePages {
runs: alloc::vec![(0x90_0000, 0x1000)],
origin: 0,
},
]
);
let unresolved = |iova: u64| (iova != 0x1_2000).then_some(0x50_0000);
assert_eq!(layer.planes(&unresolved), None);
}
}