diff --git a/Cargo.lock b/Cargo.lock index dc8675936..a7941b0c9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -588,6 +588,7 @@ dependencies = [ "objc2-io-surface", "objc2-metal", "objc2-quartz-core", + "reims-graphics", "reims-vgpu-core", "reims-vgpu-metal", "reims-vgpu-video-conformance", diff --git a/crates/reims-vgpu/Cargo.toml b/crates/reims-vgpu/Cargo.toml index d029534e2..ac815e220 100644 --- a/crates/reims-vgpu/Cargo.toml +++ b/crates/reims-vgpu/Cargo.toml @@ -26,6 +26,8 @@ reims-vgpu-window.workspace = true reims-vgpu-vulkan = { workspace = true, optional = true } # The video device's host session (`video`). reims-vgpu-video-core.workspace = true +# The reims-graphics device's host side (`graphics`). +reims-graphics.workspace = true # A window frame that fails, or a window that gets no sink (`window::vulkan`). log.workspace = true # KVM's dirty-log ioctls, in a host's dirty source's harvest (`dirty`); on Linux, the guest's RAM diff --git a/crates/reims-vgpu/src/error.rs b/crates/reims-vgpu/src/error.rs index 36de871cc..1650b6e32 100644 --- a/crates/reims-vgpu/src/error.rs +++ b/crates/reims-vgpu/src/error.rs @@ -39,6 +39,9 @@ pub enum Error { Gpu, /// A frame committed twice, or waited on before its commit. FrameState, + /// The host refused the memory, a pipe or a thread a device needs: the graphics device's + /// region, or its threads. + HostResources, } impl std::fmt::Display for Error { @@ -59,6 +62,7 @@ impl std::fmt::Display for Error { Error::Resume(_) => "the resume state was refused", Error::Gpu => "the frame's GPU work failed", Error::FrameState => "the frame is not in a state for this call", + Error::HostResources => "the host refused memory, a pipe or a thread", }) } } diff --git a/crates/reims-vgpu/src/graphics.rs b/crates/reims-vgpu/src/graphics.rs new file mode 100644 index 000000000..de3c02abe --- /dev/null +++ b/crates/reims-vgpu/src/graphics.rs @@ -0,0 +1,367 @@ +//! [`GraphicsDevice`]: the reims-graphics device (PCI 1234:5247), `reims-graphics`'s host side +//! with its display shown in a window of the library's, made from a [`GraphicsConfig`]. +//! +//! The device's region (BAR 2) is made here and shared: the device takes the guest's commands +//! from its rings, and the window's sink imports it once as a no-copy buffer on the platform +//! (Metal on macOS, the Vulkan platform's runtime with the `vulkan` feature) and blits the +//! scanout out of it into each drawable, on the GPU, with no copy on the CPU (`sink`). The +//! buffer's deallocator holds the region, so it stays mapped until the GPU has let the buffer +//! go, after the device and the window. +//! +//! **The window** ([`WindowScreen`]) is a display window of `reims-vgpu-window` that keeps its +//! size (`WindowConfig::keeps_its_size`): the guest follows it. It opens sized for the config's +//! mode, else 1920 × 1080, and the display then offers the guest one mode, the window's size in +//! pixels as its render thread last drew into it, at the refresh rate of the host screen it +//! opened on; when that size changes (the person resized the window) the device tells the +//! guest (`DISPLAY_CHANGED`). The guest's scanout shows in the window at once and then whenever +//! the host's dirty log says the guest wrote it, at the screen's rate; the window draws it at +//! the screen's pace. The guest's cursor image is the host's cursor over the image, shown while +//! the guest shows its cursor; the guest's cursor position moves nothing, since the host's +//! pointer moves the guest's (the window never draws the cursor into the image itself). +//! +//! **Without a window** the display offers 1920 × 1080 at 60 Hz and shows nothing. +//! +//! Every public method runs as an entry ([`crate::entry`]). + +use std::marker::PhantomData; +use std::os::fd::RawFd; +use std::sync::Arc; + +use reims_graphics::region::Region; +use reims_graphics::{CursorImage, FixedScreen, Host, Mode, Scanout, Screen}; +use reims_vgpu_core::sync::Mutex; +use reims_vgpu_window::{FrameSink, Window, WindowConfig}; + +use crate::DefaultPlatform; +use crate::entry; +use crate::error::Error; +use crate::platform::ApiPlatform; +use crate::window::WindowLink; + +#[cfg(target_os = "macos")] +mod metal; +mod sink; +#[cfg(feature = "vulkan")] +mod vulkan; + +/// Raises MSI-X vector `vector`: the device's interrupt. +pub type GraphicsRaiseFn = Arc; +/// Whether the guest wrote any of the `length` bytes at `offset` in the region since the last +/// ask: the host's dirty log over the scanout, taken and cleared. +pub type ScanoutWrittenFn = Arc bool + Send + Sync>; + +/// A graphics device's callbacks. Each is called on one of the device's two threads +/// (`reims-vgpu.graphics-control`, `reims-vgpu.graphics-refresh`), never inside a call of the +/// host's into the device, with no lock of the library's held; the two may call at once. +#[derive(Clone, Default)] +pub struct GraphicsCallbacks { + /// Raises the device's interrupt. Without it the guest gets no interrupt. + pub raise_interrupt: Option, + /// The host's dirty log over the scanout, on the refresh thread. Without it the guest's + /// scanout is taken as written at every refresh. + pub scanout_written: Option, +} + +/// A graphics device's config. +#[derive(Clone, Default)] +pub struct GraphicsConfig { + /// Its callbacks. + pub callbacks: GraphicsCallbacks, + /// The display's window: its input callbacks and the mode it opens sized for; `None` is no + /// window. The window keeps its size whatever this says (the module doc). + pub window: Option, +} + +/// The mode a display offers before its window has a size, and without a window. +const FALLBACK_MODE: Mode = Mode { + width: 1920, + height: 1080, + refresh_mhz: 60_000, +}; + +/// The reims-graphics device. +pub struct GraphicsDevice { + /// The window, which closes when the link drops: before the device. + window: Option, + /// The device. + device: reims_graphics::Device, + /// The platform the window's sink draws on. + _platform: PhantomData

, +} + +impl std::fmt::Debug for GraphicsDevice

{ + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("GraphicsDevice") + .field("device", &self.device) + .field("window", &self.window.is_some()) + .finish() + } +} + +impl GraphicsDevice { + /// A device on the process's platform. + pub fn new(config: GraphicsConfig) -> Result { + GraphicsDevice::with_platform(DefaultPlatform::process(), config) + } +} + +impl GraphicsDevice

{ + /// A device whose window draws on `platform`. [`Error::HostResources`] where the host + /// refuses the region's memory, a pipe or a thread. + pub fn with_platform(platform: Arc

, config: GraphicsConfig) -> Result { + entry::run(|_| { + let size = + usize::try_from(reims_graphics::REGION_SIZE).map_err(|_| Error::HostResources)?; + let region = Arc::new(Region::new(size).ok_or(Error::HostResources)?); + let host = Box::new(CallbackHost(config.callbacks)); + let (window, screen): (Option, Box) = match config.window { + Some(window_config) => { + let (link, screen) = WindowScreen::open(&platform, ®ion, window_config); + (Some(link), Box::new(screen)) + } + None => (None, Box::new(FixedScreen(FALLBACK_MODE))), + }; + let device = + reims_graphics::Device::new(region, host, screen).ok_or(Error::HostResources)?; + Ok(GraphicsDevice { + window, + device, + _platform: PhantomData, + }) + }) + } + + /// The region's first byte: BAR 2's memory, which the host maps into the guest, write-back. + /// It stays mapped until the device and its window's GPU work have ended. + pub fn region_base(&self) -> *mut u8 { + self.device.region_base() + } + + /// The region's size: BAR 2's, a power of two. + pub fn region_size(&self) -> u64 { + self.device.region_size() + } + + /// A 32-bit read of BAR 0 at `offset`. + pub fn mmio_read(&self, offset: u64) -> u32 { + entry::run(|_| self.device.mmio_read(offset)) + } + + /// A 32-bit write of BAR 0 at `offset`. A reset (`STATUS` 0) waits for the command the + /// device is taking, which waits for nothing of the host's. + pub fn mmio_write(&self, offset: u64, value: u32) { + entry::run(|_| self.device.mmio_write(offset, value)); + } + + /// Takes a copy of `fd`, the host's `ioeventfd` for `DOORBELL` with ring 0. False where `fd` + /// is not open or the device has one already. + pub fn set_doorbell(&self, fd: RawFd) -> bool { + entry::run(|_| self.device.set_doorbell(fd)) + } + + /// The host's reset of the device (the guest's bus reset). + pub fn reset(&self) { + entry::run(|_| self.device.reset()); + } +} + +impl Drop for GraphicsDevice

{ + /// The window closes, then the device ends; neither waits (`reims-graphics`'s `device`). + fn drop(&mut self) { + entry::run(|_| { + drop(self.window.take()); + }); + } +} + +/// The host's callbacks as the device's [`Host`]. +struct CallbackHost(GraphicsCallbacks); + +impl Host for CallbackHost { + fn raise_interrupt(&self, vector: u32) { + if let Some(f) = &self.0.raise_interrupt { + f(vector); + } + } + + fn scanout_written(&self, offset: u64, length: u64) -> bool { + self.0 + .scanout_written + .as_ref() + .is_none_or(|f| f(offset, length)) + } +} + +/// What the window and its sink share: the scanout the guest set, and the size of the drawable +/// the window's render thread last drew into, its size in pixels. +#[derive(Debug, Default)] +pub(crate) struct Shown { + /// The guest's scanout; `None` shows black. + pub(crate) scanout: Mutex>, + /// The window's size in pixels, once drawn into. + pub(crate) drawable: Mutex>, +} + +/// The display's window as the device's [`Screen`] (the module doc). +pub(crate) struct WindowScreen { + /// The window. + window: Arc, + /// What it shows. + shown: Arc, + /// The refresh rate of the host screen it opened on, in thousandths of a hertz. + refresh_mhz: u32, + /// The guest's cursor, as last told. + cursor: Mutex, +} + +/// The guest's cursor, as the window shows it: over the image while the guest has an image and +/// shows it. +#[derive(Debug)] +struct CursorState { + /// The guest has an image. + image: bool, + /// The guest shows its cursor: until it says otherwise, it does. + visible: bool, + /// What the window was last told, once told. + shown: Option, +} + +impl CursorState { + /// Tells `window` whether the cursor shows, where that changed. + fn update(&mut self, window: &Window) { + let show = self.image && self.visible; + if self.shown != Some(show) { + self.shown = Some(show); + window.cursor_show(show); + } + } +} + +impl WindowScreen { + /// The window of a display over `region`, opened with its sink on `platform` where the + /// platform draws one (no sink: the window never opens), and the screen over it. + fn open( + platform: &Arc

, + region: &Arc, + mut config: WindowConfig, + ) -> (WindowLink, WindowScreen) { + config.keeps_its_size = true; + let first = config.mode.unwrap_or((1920, 1080)); + let window = Window::new(config, 0, reims_vgpu_window::handle::title(0)); + window.offered_mode(first.0, first.1); + let refresh_mhz = reims_vgpu_window::screens::screen_for_port(0) + .map_or(FALLBACK_MODE.refresh_mhz, |s| hz_to_mhz(s.refresh_hz)); + let shown = Arc::new(Shown::default()); + if let Some(sink) = scanout_sink(platform, region, &shown) { + window.attach(sink); + } + let screen = WindowScreen { + window: Arc::clone(&window), + shown, + refresh_mhz, + cursor: Mutex::new(CursorState { + image: false, + visible: true, + shown: None, + }), + }; + (WindowLink::new(window), screen) + } +} + +/// `hz` in thousandths of a hertz: 60 Hz where it is not a positive rate. +fn hz_to_mhz(hz: f64) -> u32 { + if !(hz.is_finite() && hz > 0.0) { + return FALLBACK_MODE.refresh_mhz; + } + #[expect( + clippy::as_conversions, + reason = "a rate up to 1000 Hz, rounded to nearest" + )] + let mhz = (hz * 1000.0).round() as u32; + mhz +} + +impl Screen for WindowScreen { + /// The window's size in pixels as last drawn into, else the mode it opened for, at its host + /// screen's rate. + fn mode(&self) -> Mode { + let drawn = *self.shown.drawable.lock(); + let (width, height) = drawn.unwrap_or_else(|| { + let (w, h) = self.window.offered().unwrap_or((1920, 1080)); + (u64::from(w), u64::from(h)) + }); + let clamp = |v: u64| u32::try_from(v.max(1)).unwrap_or(u32::MAX); + Mode { + width: clamp(width), + height: clamp(height), + refresh_mhz: self.refresh_mhz, + } + } + + /// The window takes the scanout's size as the guest's mode, and draws it. + fn scanout(&self, scanout: Option) { + *self.shown.scanout.lock() = scanout; + if let Some(s) = scanout { + let mode = |v: u32| u16::try_from(v).unwrap_or(u16::MAX); + self.window.guest_mode(mode(s.width), mode(s.height)); + } + self.window.new_frame(); + } + + fn present(&self) { + self.window.new_frame(); + } + + /// The host's cursor over the image takes the guest's image; with none, nothing shows + /// there. + fn cursor_image(&self, image: Option) { + let mut cursor = self.cursor.lock(); + cursor.image = image.is_some(); + if let Some(image) = image { + let hot = |v: u32| u16::try_from(v).unwrap_or(u16::MAX); + self.window.cursor_glyph( + image.width, + image.height, + (hot(image.hot_spot.0), hot(image.hot_spot.1)), + &image.rgba, + ); + } + cursor.update(&self.window); + } + + /// The window shows or hides the guest's cursor as the guest does; the position is the + /// host's pointer's (the module doc). + fn cursor_moved(&self, _x: i32, _y: i32, visible: bool) { + let mut cursor = self.cursor.lock(); + cursor.visible = visible; + cursor.update(&self.window); + } +} + +/// The window's sink over `region` on `platform` ([`sink::ScanoutDraw`]): Metal's on macOS's +/// product platform, the Vulkan platform's swapchain presenter with the `vulkan` feature; +/// `None` on any other platform (the testkit's), or where the platform refuses the region's +/// import or a command queue. +fn scanout_sink( + platform: &Arc

, + region: &Arc, + shown: &Arc, +) -> Option> { + let any: Arc = Arc::clone(platform) as _; + #[cfg(target_os = "macos")] + let any = match any.downcast::() { + Ok(metal) => return metal::sink(metal, region, shown), + Err(other) => other, + }; + #[cfg(feature = "vulkan")] + let any = match any.downcast::() { + Ok(vulkan) => return vulkan::sink(vulkan, region, shown), + Err(other) => other, + }; + let _ = (any, region, shown); + None +} + +#[cfg(test)] +mod tests; diff --git a/crates/reims-vgpu/src/graphics/metal.rs b/crates/reims-vgpu/src/graphics/metal.rs new file mode 100644 index 000000000..9d732b52b --- /dev/null +++ b/crates/reims-vgpu/src/graphics/metal.rs @@ -0,0 +1,76 @@ +//! A graphics display's window sink on the product's platform: [`MetalScanoutSink`] blits the +//! scanout straight into each drawable the window's render thread takes of its layer, and +//! presents it in the same command buffer. + +use std::sync::Arc; + +use objc2::rc::Retained; +use objc2::runtime::ProtocolObject; +use objc2_metal::{MTLCommandBuffer as _, MTLDevice, MTLDrawable}; +use objc2_quartz_core::CAMetalDrawable; +use reims_graphics::region::Region; +use reims_vgpu_core::platform::Platform; +use reims_vgpu_core::platform::command::CommandBuffer as _; +use reims_vgpu_core::platform::resource::Texture as _; +use reims_vgpu_core::raise::OnFault; +use reims_vgpu_metal::{MetalPlatform, Obj, msg}; +use reims_vgpu_window::{DrawnCursor, FrameSink, PixelRect}; + +use super::Shown; +use super::sink::ScanoutDraw; +use crate::display::no_catch; +use crate::entry; + +/// The sink of a graphics display on Metal, over `region`; `None` where Metal refuses a queue +/// or the region's import. +pub(super) fn sink( + platform: Arc, + region: &Arc, + shown: &Arc, +) -> Option> { + let draw = ScanoutDraw::new(platform, region, shown)?; + Some(Arc::new(MetalScanoutSink { draw })) +} + +/// What blits a graphics display's scanout into its window's drawables on Metal. +struct MetalScanoutSink { + /// The region's buffer, the queue and the scanout. + draw: ScanoutDraw, +} + +impl FrameSink for MetalScanoutSink { + /// The default Metal device, which the queue and the buffer are on. + fn device(&self) -> Option>> { + Some(self.draw.device.as_retained().clone()) + } + + /// The scanout blitted into `drawable`'s texture, presented in the same command buffer; + /// false, the drawable dropped, where the guest has no scanout. The window's cursor is the + /// host's, so `cursor` is never given (`graphics`'s module doc). + fn draw( + &self, + drawable: &ProtocolObject, + region: PixelRect, + _cursor: Option<&DrawnCursor>, + ) -> bool { + entry::run(|_| { + let texture: ::Texture = + Obj::from_retained(msg::get("texture", || drawable.texture())); + self.draw.drawn((texture.width(), texture.height())); + let Some(command_buffer) = self.draw.encode(&texture, region) else { + return false; + }; + let drawable: &ProtocolObject = ProtocolObject::from_ref(drawable); + msg::get("presentDrawable:", || { + command_buffer.get().presentDrawable(drawable); + }); + no_catch(command_buffer.commit(OnFault::Die)); + true + }) + } + + /// False: the scanout is blitted into the drawables, which must take copies. + fn render_target_only(&self) -> bool { + false + } +} diff --git a/crates/reims-vgpu/src/graphics/sink.rs b/crates/reims-vgpu/src/graphics/sink.rs new file mode 100644 index 000000000..caec8b55a --- /dev/null +++ b/crates/reims-vgpu/src/graphics/sink.rs @@ -0,0 +1,169 @@ +//! [`ScanoutDraw`]: what a graphics display's window sink draws with, on any platform: the +//! device's region, imported once as a no-copy buffer, and a command queue of its own on the +//! platform's default device. Each draw blits the guest's scanout out of the buffer into the +//! drawable's texture, at the image's place, in one command buffer: the GPU reads the guest's +//! pixels in place, and the CPU copies nothing. +//! +//! **Sizes.** The guest sets a scanout of the size the display offers, the window's size in +//! pixels, so the image is the whole drawable and the blit covers it. While the two differ (the +//! window resized, the guest not yet following), the blit copies what fits of the scanout at the +//! image's top left, clipped to the drawable, after a clear of the drawable to black: a blit +//! cannot scale, and the guest's next mode makes the sizes equal again. +//! +//! **The import.** The buffer covers the whole region, so its deallocator, which holds the +//! region, is what keeps the region mapped while a command buffer still reads it: Metal (or the +//! runtime) runs it once the buffer has gone, after the sink and every command buffer that used +//! it. + +use std::sync::Arc; + +use reims_graphics::region::Region; +use reims_vgpu_core::host::HostPtr; +use reims_vgpu_core::platform::blit::{BlitCmd, BlitEncoder as _}; +use reims_vgpu_core::platform::command::{CommandBuffer as _, CommandQueue as _}; +use reims_vgpu_core::platform::descriptor::RenderPassDescriptor as _; +use reims_vgpu_core::platform::device::GpuDevice as _; +use reims_vgpu_core::platform::render::{RenderCmd, RenderEncoder as _}; +use reims_vgpu_core::platform::resource::Texture as _; +use reims_vgpu_core::platform::types::{ClearColor, MtlOrigin, MtlSize}; +use reims_vgpu_core::platform::values::ColorAttachmentSet; +use reims_vgpu_core::platform::{HostRange, Platform}; +use reims_vgpu_core::raise::OnFault; +use reims_vgpu_window::PixelRect; + +use super::Shown; +use crate::display::no_catch; +use crate::platform::ApiPlatform; + +/// `MTLLoadActionClear`. +const LOAD_ACTION_CLEAR: u64 = 2; +/// `MTLStoreActionStore`. +const STORE_ACTION_STORE: u64 = 1; + +/// What a graphics display's window sink draws with (the module doc). +pub(crate) struct ScanoutDraw { + /// The platform, whose render pass descriptors clear the drawable. + platform: Arc

, + /// The device the queue and the buffer are on: the platform's default. Only the Metal sink, + /// on macOS, reads it. + #[cfg_attr(not(target_os = "macos"), allow(dead_code))] + pub(crate) device: P::Device, + /// The sink's command queue. + pub(crate) queue: P::CommandQueue, + /// The region, as a no-copy buffer. + buffer: P::Buffer, + /// What the window shows. + shown: Arc, +} + +impl ScanoutDraw

{ + /// The draw over `region` on `platform`'s default device, sharing `shown` with the window's + /// screen; `None` where the platform has no device, or refuses a queue or the import. + pub(crate) fn new( + platform: Arc

, + region: &Arc, + shown: &Arc, + ) -> Option> { + let device = platform.metal_device(None)?; + let queue = device.new_command_queue()?; + let keep = Arc::clone(region); + // SAFETY: the region is mapped from its making until its last reference goes, and the + // deallocator holds one until the platform runs it, once the buffer has gone. + let bytes = unsafe { HostRange::new(HostPtr::from_ptr(region.base()), region.size()) }; + let buffer = no_catch(device.new_buffer_over_host_memory( + OnFault::Die, + bytes, + 0, + Some(Box::new(move || drop(keep))), + )); + let Some(buffer) = buffer else { + log::warn!( + target: "reims_vgpu::graphics", + "the platform refused the region's import: the window stays empty" + ); + return None; + }; + Some(ScanoutDraw { + platform, + device, + queue, + buffer, + shown: Arc::clone(shown), + }) + } + + /// The window's render thread draws into a drawable of `size` pixels: the window's size, + /// which the display offers the guest. + pub(crate) fn drawn(&self, size: (u64, u64)) { + *self.shown.drawable.lock() = Some(size); + } + + /// A command buffer of the sink's queue with the scanout blitted into `texture` at `region` + /// (the module doc), not committed; `None`, with nothing encoded, where the guest has no + /// scanout or the queue gives no command buffer. + pub(crate) fn encode( + &self, + texture: &P::Texture, + region: PixelRect, + ) -> Option { + let scanout = (*self.shown.scanout.lock())?; + let command_buffer = no_catch(self.queue.command_buffer(OnFault::Die))?; + let (texture_width, texture_height) = (texture.width(), texture.height()); + let x = region.x.min(texture_width); + let y = region.y.min(texture_height); + let width = u64::from(scanout.width) + .min(region.width) + .min(texture_width - x); + let height = u64::from(scanout.height) + .min(region.height) + .min(texture_height - y); + if (x, y, width, height) != (0, 0, texture_width, texture_height) { + self.clear(&command_buffer, texture); + } + if width > 0 && height > 0 { + let blit = no_catch(command_buffer.blit_encoder(OnFault::Die))?; + let stride = u64::from(scanout.stride); + no_catch(blit.encode( + OnFault::Die, + BlitCmd::CopyBufferToTexture { + source_buffer: &self.buffer, + source_offset: scanout.offset, + source_bytes_per_row: stride, + source_bytes_per_image: stride * height, + source_size: MtlSize::new(width, height, 1), + destination_texture: texture, + destination_slice: 0, + destination_level: 0, + destination_origin: MtlOrigin::new(x, y, 0), + }, + )); + no_catch(blit.encode(OnFault::Die, BlitCmd::EndEncoding)); + } + Some(command_buffer) + } + + /// Clears all of `texture` to opaque black, in a render pass of `command_buffer` with no + /// draw. + fn clear(&self, command_buffer: &P::CommandBuffer, texture: &P::Texture) { + let pass = self.platform.render_pass_descriptor(); + no_catch(pass.set_color_attachment( + OnFault::Die, + 0, + &ColorAttachmentSet { + texture: Some(Some(texture)), + load_action: Some(LOAD_ACTION_CLEAR), + store_action: Some(STORE_ACTION_STORE), + clear_color: Some(ClearColor { + red: 0.0, + green: 0.0, + blue: 0.0, + alpha: 1.0, + }), + ..ColorAttachmentSet::default() + }, + )); + if let Some(encoder) = no_catch(command_buffer.render_encoder(OnFault::Die, &pass)) { + no_catch(encoder.encode(OnFault::Die, RenderCmd::EndEncoding)); + } + } +} diff --git a/crates/reims-vgpu/src/graphics/tests.rs b/crates/reims-vgpu/src/graphics/tests.rs new file mode 100644 index 000000000..f606fbcde --- /dev/null +++ b/crates/reims-vgpu/src/graphics/tests.rs @@ -0,0 +1,110 @@ +use std::sync::atomic::{AtomicU32, Ordering}; + +use reims_graphics::wire::*; +use reims_vgpu_core::testkit::FakePlatform; + +use super::*; + +/// A graphics device on the testkit's platform, with no window, raising through `raised`. +fn headless(raised: &Arc) -> GraphicsDevice { + let raised = Arc::clone(raised); + let config = GraphicsConfig { + callbacks: GraphicsCallbacks { + raise_interrupt: Some(Arc::new(move |vector| { + assert_eq!(vector, 0); + raised.fetch_add(1, Ordering::SeqCst); + })), + scanout_written: None, + }, + window: None, + }; + GraphicsDevice::with_platform(Arc::new(FakePlatform::new()), config).unwrap() +} + +/// A headless device's region is the device's, its registers read as the wire says, and the +/// guest's armed completion reaches the host's interrupt callback; its display offers 1920 × +/// 1080 at 60 Hz +#[test] +fn a_headless_device_answers_its_guest() { + let raised = Arc::new(AtomicU32::new(0)); + let device = headless(&raised); + assert_eq!(device.region_size(), reims_graphics::REGION_SIZE); + assert!(!device.region_base().is_null()); + assert_eq!(device.mmio_read(RGFX_REG_MAGIC.into()), RGFX_MAGIC); + assert_eq!( + device.mmio_read(RGFX_REG_REGION_SIZE_LO.into()), + (reims_graphics::REGION_SIZE & 0xffff_ffff) as u32 + ); + device.mmio_write(RGFX_REG_STATUS.into(), RGFX_STATUS_DRIVER_READY); + // SAFETY: the region is the device's, mapped while it lives, and the rings' fields are at + // their offsets; nothing else writes the guest's side. + unsafe { + let base = device.region_base(); + let ring = base.add(RGFX_CONTROL_SUBMIT_OFFSET as usize + 256); + let header = RgfxMsgHeader { + r#type: RGFX_CMD_GET_DISPLAYS, + size: 16, + seqno: 1, + }; + std::ptr::copy_nonoverlapping( + std::ptr::from_ref(&header).cast::(), + ring, + size_of::(), + ); + let armed = base.add(RGFX_CONTROL_COMPLETE_OFFSET as usize + 0xc0); + std::sync::atomic::AtomicU32::from_ptr(armed.cast()).store(1, Ordering::SeqCst); + let producer = base.add(RGFX_CONTROL_SUBMIT_OFFSET as usize); + std::sync::atomic::AtomicU64::from_ptr(producer.cast()).store(16, Ordering::SeqCst); + } + device.mmio_write(RGFX_REG_DOORBELL.into(), RGFX_CONTROL_RING_ID); + for _ in 0..2000 { + if raised.load(Ordering::SeqCst) > 0 { + break; + } + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert_eq!(raised.load(Ordering::SeqCst), 1); + // The answer: DISPLAYS, its one mode 1920 × 1080 at 60 Hz. + // SAFETY: as above; the device published the answer before it raised. + let mode = unsafe { + let answer = device + .region_base() + .add(RGFX_CONTROL_COMPLETE_OFFSET as usize + 256 + 36); + std::slice::from_raw_parts(answer, 12).to_vec() + }; + let words: Vec = mode + .chunks(4) + .map(|c| u32::from_le_bytes(c.try_into().unwrap())) + .collect(); + assert_eq!(words, [1920, 1080, 60_000]); +} + +/// The host screen's rate in thousandths of a hertz, rounded; 60 Hz for a rate that is none +#[test] +fn a_screen_s_rate_is_kept_in_millihertz() { + assert_eq!(hz_to_mhz(120.0), 120_000); + assert_eq!(hz_to_mhz(59.94), 59_940); + assert_eq!(hz_to_mhz(0.0), 60_000); + assert_eq!(hz_to_mhz(f64::NAN), 60_000); +} + +/// The window shows the guest's cursor once it has an image and while the guest shows it, +/// telling the window only of a change +#[test] +fn the_cursor_shows_with_an_image_while_the_guest_shows_it() { + let window = Window::new(WindowConfig::default(), 0, "test".to_owned()); + let mut cursor = CursorState { + image: false, + visible: true, + shown: None, + }; + cursor.update(&window); + assert_eq!(cursor.shown, Some(false)); + cursor.image = true; + cursor.update(&window); + assert_eq!(cursor.shown, Some(true)); + cursor.visible = false; + cursor.update(&window); + assert_eq!(cursor.shown, Some(false)); + window.close(); +} diff --git a/crates/reims-vgpu/src/graphics/vulkan.rs b/crates/reims-vgpu/src/graphics/vulkan.rs new file mode 100644 index 000000000..8e9bd6d3a --- /dev/null +++ b/crates/reims-vgpu/src/graphics/vulkan.rs @@ -0,0 +1,110 @@ +//! A graphics display's window sink on the Vulkan platform, on either OS: [`VulkanScanoutSink`] +//! makes a presenter over a swapchain of the window's surface, as the Vulkan platform's display +//! sink does (`crate::window`'s `vulkan`), and each draw blits the scanout into the swapchain's +//! next image (its usage takes transfers) and presents it. What each OS's window asks of the +//! sink is its own (`linux.rs`, `macos.rs`). + +use std::sync::Arc; + +use reims_graphics::region::Region; +use reims_vgpu_core::platform::command::CommandBuffer as _; +use reims_vgpu_core::raise::OnFault; +use reims_vgpu_vulkan::VulkanPlatform; +use reims_vgpu_vulkan::swapchain::{Acquired, Swapchain}; +use reims_vgpu_window::{Drawn, DrawnCursor, FrameSink, PixelRect, Presenter, VulkanTarget}; + +use super::Shown; +use super::sink::ScanoutDraw; +use crate::display::no_catch; +use crate::entry; + +#[cfg(target_os = "linux")] +mod linux; +#[cfg(target_os = "macos")] +mod macos; + +/// The sink of a graphics display on the Vulkan platform, over `region`; `None` where the +/// runtime refuses a queue or the region's import. +pub(super) fn sink( + platform: Arc, + region: &Arc, + shown: &Arc, +) -> Option> { + let draw = ScanoutDraw::new(platform, region, shown)?; + Some(Arc::new(VulkanScanoutSink { + draw: Arc::new(draw), + })) +} + +/// What presents a graphics display's scanout in its window on the Vulkan platform. +pub(super) struct VulkanScanoutSink { + /// The region's buffer, the queue and the scanout; shared with the presenters. + draw: Arc>, +} + +impl VulkanScanoutSink { + /// The window's surface on the runtime's instance and a swapchain over it, on the sink's + /// queue's device; none where either is refused, which is logged. + fn make_presenter(&self, target: &dyn VulkanTarget) -> Option> { + // SAFETY: the target makes the surface on the instance it is given, and hands it over. + let made = entry::run(|_| unsafe { + Swapchain::over(&self.draw.queue, |get_instance_proc_addr, instance| { + target.create_surface(get_instance_proc_addr, instance) + }) + }); + match made { + Ok(swapchain) => Some(Box::new(ScanoutPresenter { + draw: Arc::clone(&self.draw), + swapchain, + })), + Err(refused) => { + log::warn!( + target: "reims_vgpu::graphics", + "no swapchain for the graphics display's window ({refused}): it stays empty" + ); + None + } + } + } +} + +/// A graphics window's presenter: the scanout's draw and the window's swapchain, on its render +/// thread. +struct ScanoutPresenter { + /// The region's buffer, the queue and the scanout. + draw: Arc>, + /// The swapchain. + swapchain: Swapchain, +} + +impl Presenter for ScanoutPresenter { + /// The next image, the scanout blitted into it, and its present once the runtime has + /// scheduled the blit. `cursor` is never given (`graphics`'s module doc). + fn draw( + &mut self, + drawable: (u64, u64), + region: PixelRect, + _cursor: Option<&DrawnCursor>, + ) -> Drawn { + entry::run(|_| { + self.draw.drawn(drawable); + let frame = match self.swapchain.acquire(drawable) { + Acquired::Image(frame) => frame, + Acquired::Retry => return Drawn::Retry, + Acquired::Failed => return Drawn::Ended, + }; + let Some(texture) = self.swapchain.texture(frame) else { + return Drawn::Nothing; + }; + let Some(command_buffer) = self.draw.encode(texture, region) else { + return Drawn::Nothing; + }; + if !self.swapchain.encode_ready(frame, &command_buffer) { + return Drawn::Nothing; + } + no_catch(command_buffer.commit(OnFault::Die)); + self.swapchain.present(frame, command_buffer); + Drawn::Presented + }) + } +} diff --git a/crates/reims-vgpu/src/graphics/vulkan/linux.rs b/crates/reims-vgpu/src/graphics/vulkan/linux.rs new file mode 100644 index 000000000..1683c00fc --- /dev/null +++ b/crates/reims-vgpu/src/graphics/vulkan/linux.rs @@ -0,0 +1,13 @@ +//! What Linux's window asks of the graphics display's Vulkan sink ([`FrameSink`]): a presenter +//! over the window's swapchain, which SDL's window makes its surface for. + +use reims_vgpu_window::{FrameSink, Presenter, VulkanTarget}; + +use super::VulkanScanoutSink; + +impl FrameSink for VulkanScanoutSink { + /// The presenter ([`VulkanScanoutSink::make_presenter`]). + fn presenter(&self, target: &dyn VulkanTarget) -> Option> { + self.make_presenter(target) + } +} diff --git a/crates/reims-vgpu/src/graphics/vulkan/macos.rs b/crates/reims-vgpu/src/graphics/vulkan/macos.rs new file mode 100644 index 000000000..df528493a --- /dev/null +++ b/crates/reims-vgpu/src/graphics/vulkan/macos.rs @@ -0,0 +1,43 @@ +//! What macOS's window asks of the graphics display's Vulkan sink ([`FrameSink`]): it presents +//! itself, through a presenter over a swapchain of the window's `CAMetalLayer`, as the Vulkan +//! platform's display sink does (`crate::window`'s `vulkan/macos.rs`). + +use objc2::rc::Retained; +use objc2::runtime::ProtocolObject; +use objc2_metal::MTLDevice; +use objc2_quartz_core::CAMetalDrawable; +use reims_vgpu_window::{DrawnCursor, FrameSink, PixelRect, Presenter, VulkanTarget}; + +use super::VulkanScanoutSink; + +impl FrameSink for VulkanScanoutSink { + /// None: the swapchain sets the layer's device. + fn device(&self) -> Option>> { + None + } + + /// Nothing: the sink presents itself, and is given no drawable. + fn draw( + &self, + _drawable: &ProtocolObject, + _region: PixelRect, + _cursor: Option<&DrawnCursor>, + ) -> bool { + false + } + + /// False: the swapchain's images take transfers. + fn render_target_only(&self) -> bool { + false + } + + /// True: the sink presents through [`FrameSink::presenter`]. + fn presents(&self) -> bool { + true + } + + /// The presenter ([`VulkanScanoutSink::make_presenter`]). + fn presenter(&self, target: &dyn VulkanTarget) -> Option> { + self.make_presenter(target) + } +} diff --git a/crates/reims-vgpu/src/lib.rs b/crates/reims-vgpu/src/lib.rs index a88d015fd..27eb051c1 100644 --- a/crates/reims-vgpu/src/lib.rs +++ b/crates/reims-vgpu/src/lib.rs @@ -38,6 +38,7 @@ mod display; mod entry; mod error; mod frame; +mod graphics; mod iosurface; pub mod platform; mod retained; @@ -55,6 +56,9 @@ pub use display::{ }; pub use error::{Error, ResumeError}; pub use frame::{Frame, FrameTarget, MAX_FRAME_TARGET_SIZE, PixelFormat, Region}; +pub use graphics::{ + GraphicsCallbacks, GraphicsConfig, GraphicsDevice, GraphicsRaiseFn, ScanoutWrittenFn, +}; pub use iosurface::{IoSurfaceDevice, IoSurfaceDeviceConfig}; pub use platform::ApiPlatform; pub use reims_vgpu_core::host::{