From 2d7ce10ea0d176140adcd6e5644ea79fb4edab2b Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 16 Nov 2026 11:41:17 -0800 Subject: [PATCH] :new: Add the VT_MESSAGE op and the arm64e kext's VideoToolbox service An arm64 guest's VideoToolbox runs its codecs in a guest only where it finds an AppleVideoToolboxParavirtualizationDriver service: it then sends the host side `vtpv` messages, and lists and runs the host's decoders as hardware ones. This is the first slice of that route (design.md, "Decided", 17). The device gains feature bit 52, VT_MESSAGES: ring 0's VT_MESSAGE carries a message in guest RAM runs to the host, and the control completion ring's VT_STATUS answers it and VT_MESSAGE brings the host's messages back. The arm64e kext publishes the service under display 0's framebuffer where the guest took the bit and the host's caps list a decoder, with the user client of Apple's kext's five selectors, read from its 15.0.0 build. The host's side is reims_vgpu_video::paravirt: it answers the decoder list and each codec's capabilities from the decoders the caps list, an empty encoder and motion estimation list, and refuses session creates for now. No host offers the bit yet: the host's caps code turns it on with decode sessions, the next slice, so guests see nothing new. The x86 kext is unchanged, and the option ROM's bytes too; its record takes the new header. --- crates/reims-vgpu-graphics/cbindgen.toml | 3 + .../include/reims_graphics_wire.h | 90 ++ crates/reims-vgpu-graphics/src/control.rs | 23 +- crates/reims-vgpu-graphics/src/device.rs | 21 +- .../reims-vgpu-graphics/src/device/backlog.rs | 6 +- .../reims-vgpu-graphics/src/device/tests.rs | 1 + .../src/device/tests/peer.rs | 4 +- .../src/device/tests/vt.rs | 129 +++ crates/reims-vgpu-graphics/src/device/vt.rs | 303 ++++++ crates/reims-vgpu-graphics/src/lib.rs | 2 +- crates/reims-vgpu-graphics/src/wire.rs | 95 ++ crates/reims-vgpu-graphics/tests/header.rs | 9 + crates/reims-vgpu-video/src/lib.rs | 3 + crates/reims-vgpu-video/src/paravirt.rs | 53 + crates/reims-vgpu-video/src/paravirt/atom.rs | 227 +++++ crates/reims-vgpu-video/src/paravirt/host.rs | 408 ++++++++ crates/reims-vgpu-video/src/paravirt/lists.rs | 215 ++++ .../reims-vgpu-video/src/paravirt/message.rs | 950 ++++++++++++++++++ crates/reims-vgpu-video/src/paravirt/names.rs | 72 ++ crates/reims-vgpu-video/src/paravirt/plist.rs | 255 +++++ .../reims-vgpu-video/src/paravirt/status.rs | 28 + crates/reims-vgpu/src/graphics.rs | 102 +- crates/reims-vgpu/src/graphics/decode/mod.rs | 30 + crates/reims-vgpu/src/graphics/tests.rs | 75 ++ docs/graphics-kext/design.md | 70 ++ guest/kext/Makefile | 11 +- guest/kext/src/ReimsGraphics.cpp | 21 + guest/kext/src/ReimsGraphics.hpp | 14 + guest/kext/src/RgfxFeatures.hpp | 9 +- guest/kext/src/RgfxVtRoutes.hpp | 202 ++++ guest/kext/src/RgfxVtService.cpp | 617 ++++++++++++ guest/kext/src/RgfxVtService.hpp | 138 +++ guest/kext/tests/features_test.cpp | 27 +- guest/kext/tests/vt_routes_test.cpp | 138 +++ 34 files changed, 4323 insertions(+), 28 deletions(-) create mode 100644 crates/reims-vgpu-graphics/src/device/tests/vt.rs create mode 100644 crates/reims-vgpu-graphics/src/device/vt.rs create mode 100644 crates/reims-vgpu-video/src/paravirt.rs create mode 100644 crates/reims-vgpu-video/src/paravirt/atom.rs create mode 100644 crates/reims-vgpu-video/src/paravirt/host.rs create mode 100644 crates/reims-vgpu-video/src/paravirt/lists.rs create mode 100644 crates/reims-vgpu-video/src/paravirt/message.rs create mode 100644 crates/reims-vgpu-video/src/paravirt/names.rs create mode 100644 crates/reims-vgpu-video/src/paravirt/plist.rs create mode 100644 crates/reims-vgpu-video/src/paravirt/status.rs create mode 100644 guest/kext/src/RgfxVtRoutes.hpp create mode 100644 guest/kext/src/RgfxVtService.cpp create mode 100644 guest/kext/src/RgfxVtService.hpp create mode 100644 guest/kext/tests/vt_routes_test.cpp diff --git a/crates/reims-vgpu-graphics/cbindgen.toml b/crates/reims-vgpu-graphics/cbindgen.toml index 0b11297e7..b6511e665 100644 --- a/crates/reims-vgpu-graphics/cbindgen.toml +++ b/crates/reims-vgpu-graphics/cbindgen.toml @@ -353,6 +353,9 @@ include = [ "RgfxVideoSessionCreate", "RgfxViewMapping", "RgfxViewportElem", + "RgfxVtHostMessage", + "RgfxVtMessage", + "RgfxVtStatus", ] [struct] diff --git a/crates/reims-vgpu-graphics/include/reims_graphics_wire.h b/crates/reims-vgpu-graphics/include/reims_graphics_wire.h index 4eded6d4f..1d06c6c87 100644 --- a/crates/reims-vgpu-graphics/include/reims_graphics_wire.h +++ b/crates/reims-vgpu-graphics/include/reims_graphics_wire.h @@ -1523,6 +1523,14 @@ // Ambrosia's module) publishes no device and is never sent it. #define RGFX_FEATURE_POINTER_MOTION 2251799813685248 +// `FEATURES_HI` bit 20, feature bit 52, `VT_MESSAGES`: ring 0 carries +// [`RGFX_CMD_VT_MESSAGE`], a message of the guest's VideoToolbox to its host side, which the host +// answers [`RGFX_EVT_VT_STATUS`], and the control completion ring carries +// [`RGFX_EVT_VT_MESSAGE`], a message of the host's side to the guest's VideoToolbox +// (docs/graphics-kext/design.md, "Decided", 17). The arm64e kext takes it where it publishes the +// paravirtual VideoToolbox service; the device sends `VT_MESSAGE` only to a guest that took it. +#define RGFX_FEATURE_VT_MESSAGES 4503599627370496 + // `STATUS`, RW: writing [`RGFX_STATUS_RESET`] resets the device; the guest writes // [`RGFX_STATUS_DRIVER_READY`] once it has read the rings' headers. #define RGFX_REG_STATUS 16 @@ -2279,6 +2287,36 @@ // since it was last copied either way, or the block has no cache. #define RGFX_CMD_SURFACE_DOWNLOAD 759 +// `VT_MESSAGE` ([`RgfxVtMessage`], then its `run_count` [`RgfxPageRun`]s at +// [`RGFX_VT_MESSAGE_RUNS_OFFSET`]), on ring 0 from the arm64e kext, where the guest took +// [`RGFX_FEATURE_VT_MESSAGES`]: one message of the guest's VideoToolbox to its host side, a `vtpv` +// message as VideoToolbox writes it (docs/graphics-kext/design.md, "Decided", 17), its `length` +// bytes in the guest RAM the runs name, in order, from the first run's first byte. The surfaces +// the message lends are named by their IOSurface IDs, in `surfaces`, the used ones first and the +// rest 0. No command buffer waits for it, and it waits for none. Answered [`RGFX_EVT_VT_STATUS`] with +// its `seqno`: the status VideoToolbox's host side returns for the message, or +// [`RGFX_VT_STATUS_MALFORMED`] where the runs do not hold `length` bytes of guest RAM, or +// `length` is under the 48 bytes of a `vtpv` header or over [`RGFX_VT_MESSAGE_MAX`]. +#define RGFX_CMD_VT_MESSAGE 762 + +// Where a `VT_MESSAGE`'s runs start: right after its [`RgfxVtMessage`]. +#define RGFX_VT_MESSAGE_RUNS_OFFSET 72 + +// The most surfaces a `VT_MESSAGE` lends: VideoToolbox's five. +#define RGFX_VT_MESSAGE_SURFACES 5 + +// The longest message a `VT_MESSAGE` carries: 10 MiB, the most the kext's message buffer holds, +// as Apple's kext of the service sizes its own. +#define RGFX_VT_MESSAGE_MAX 10485760 + +// The longest message a [`RGFX_EVT_VT_MESSAGE`] carries: 16 KiB, the buffer VideoToolbox's +// guest side takes each host message into. +#define RGFX_VT_HOST_MESSAGE_MAX 16384 + +// [`RgfxVtStatus::status`] for a `VT_MESSAGE` the device could not read: VideoToolbox's +// `kVTParameterErr`, as the guest's support framework answers a message it cannot send. +#define RGFX_VT_STATUS_MALFORMED -12902 + // Command `COMMAND_BUFFER` (a per-queue submission ring): one command buffer, // its `obj_id` followed by the encoder-op byte stream. Struct and op stream in // a later increment. @@ -2384,6 +2422,20 @@ // ring): a `FUNCTION_HANDLE_CREATE`'s or `FUNCTION_TABLE_CREATE`'s answer. #define RGFX_EVT_FUNCTION_POINTER_STATE 1036 +// Event `VT_STATUS` ([`RgfxVtStatus`], on the control completion ring): a `VT_MESSAGE`'s +// answer, with its `seqno`. +#define RGFX_EVT_VT_STATUS 1037 + +// Event `VT_MESSAGE` ([`RgfxVtHostMessage`], then its `length` bytes at +// [`RGFX_VT_HOST_MESSAGE_BYTES_OFFSET`], on the control completion ring), `seqno` 0, sent only to +// a guest that took [`RGFX_FEATURE_VT_MESSAGES`]: one message of VideoToolbox's host side to the +// guest's, of at most [`RGFX_VT_HOST_MESSAGE_MAX`] bytes, a `vtpv` message or a `rels` box. The +// message's `size` is rounded up to a multiple of 8 after its bytes. +#define RGFX_EVT_VT_MESSAGE 1038 + +// Where a `VT_MESSAGE` event's bytes start: right after its [`RgfxVtHostMessage`]. +#define RGFX_VT_HOST_MESSAGE_BYTES_OFFSET 24 + // A command buffer's status in [`RgfxCbComplete`]: finished with no error. #define RGFX_CB_OK 0 @@ -8034,4 +8086,42 @@ typedef struct { uint64_t zfar_bits; } RgfxViewportElem; +// The `VT_MESSAGE` event: one message of VideoToolbox's host side, its `length` bytes after +// this struct. +typedef struct { + // [`RGFX_EVT_VT_MESSAGE`], `seqno` 0. + RgfxMsgHeader header; + // The message's bytes, at most [`RGFX_VT_HOST_MESSAGE_MAX`]. + uint32_t length; + // Pads the bytes to a multiple of 8; 0. + uint32_t reserved_14; +} RgfxVtHostMessage; + +// `VT_MESSAGE`: one message of the guest's VideoToolbox, `length` bytes in the guest RAM of the +// `run_count` [`RgfxPageRun`]s that follow, lending the IOSurfaces of the IDs in `surfaces`. +typedef struct { + // [`RGFX_CMD_VT_MESSAGE`]. + RgfxMsgHeader header; + // The message's bytes. + uint64_t length; + // How many runs follow, at [`RGFX_VT_MESSAGE_RUNS_OFFSET`]. + uint32_t run_count; + // How many of `surfaces` are used, from the first. + uint32_t surface_count; + // The IDs of the IOSurfaces the message lends, each one its sender's process looks up, the + // used ones first, the rest 0. + uint64_t surfaces[RGFX_VT_MESSAGE_SURFACES]; +} RgfxVtMessage; + +// `VT_STATUS`: a `VT_MESSAGE`'s answer. +typedef struct { + // [`RGFX_EVT_VT_STATUS`], with the message's `seqno`. + RgfxMsgHeader header; + // The status VideoToolbox's host side returns for the message (an `OSStatus`: 0 for one it + // took), or [`RGFX_VT_STATUS_MALFORMED`]. + int32_t status; + // Pads the message to a multiple of 8; 0. + uint32_t reserved_14; +} RgfxVtStatus; + #endif /* REIMS_GRAPHICS_WIRE_H */ diff --git a/crates/reims-vgpu-graphics/src/control.rs b/crates/reims-vgpu-graphics/src/control.rs index 1025a1588..12c3d7616 100644 --- a/crates/reims-vgpu-graphics/src/control.rs +++ b/crates/reims-vgpu-graphics/src/control.rs @@ -97,7 +97,9 @@ pub(crate) fn unheld(shared: &Shared, message: &Message, epoch: u64) -> Option Option> { let seqno = message.header.seqno; match message.header.r#type { @@ -157,6 +159,25 @@ fn lifecycle(shared: &Shared, message: &Message, epoch: u64) -> Option> }; status.map(|status| complete(seqno, status)) } + RGFX_CMD_VT_MESSAGE => { + // A guest that took no VT_MESSAGES sends none; one it sends anyway is answered as + // one the device could not read, as is one whose runs or length do not hold. + let read = shared + .driver_took(RGFX_FEATURE_VT_MESSAGES) + .then(|| crate::device::vt_read(message)) + .flatten(); + match read { + Some(vt) => { + shared.host.vt_message( + vt, + shared.vt_answer(seqno, epoch), + shared.vt_link(epoch), + ); + None + } + None => Some(crate::device::vt_status(seqno, RGFX_VT_STATUS_MALFORMED)), + } + } RGFX_CMD_SURFACE_DOWNLOAD => match read::(message) { Some(download) => { shared diff --git a/crates/reims-vgpu-graphics/src/device.rs b/crates/reims-vgpu-graphics/src/device.rs index a07df46fb..eb4b1a240 100644 --- a/crates/reims-vgpu-graphics/src/device.rs +++ b/crates/reims-vgpu-graphics/src/device.rs @@ -242,6 +242,10 @@ mod desktop; mod gate; mod guest_times; mod lanes; +mod vt; + +pub use vt::{VtAnswer, VtLink, VtMessage}; +pub(crate) use vt::{read_message as vt_read, vt_status}; /// How many of ring 0's messages a doorbell's take reads ([`Backlog::read`]) before it leaves the /// buffer to its queue's thread. @@ -380,7 +384,8 @@ const KNOWN_FEATURES: u64 = (RGFX_FEATURE_SURFACE_PAGES | RGFX_FEATURE_MULTI_DISPLAY | RGFX_FEATURE_POINTER_OVER | RGFX_FEATURE_DISPLAY_BOUNDS - | RGFX_FEATURE_POINTER_MOTION; + | RGFX_FEATURE_POINTER_MOTION + | RGFX_FEATURE_VT_MESSAGES; /// The `RGFX_QUEUE_*` flags the host carries out, each with the feature the guest's driver must /// take for a `QUEUE_CREATE` to ask for it: [`RGFX_QUEUE_UNSHARED`] alone, so a create that asks @@ -603,6 +608,20 @@ pub trait Host: Send + Sync + 'static { let _ = (completion, message); } + /// A `VT_MESSAGE` of the guest's VideoToolbox ([`RGFX_FEATURE_VT_MESSAGES`]), its runs and + /// length checked ([`VtMessage`]): the host reads its bytes from guest RAM, hands them to its + /// side of VideoToolbox's paravirtual protocol, and gives `answer` the status that side + /// returns, from any thread; `link` sends that side's messages to the guest, from any thread, + /// while no reset has come since. Called on the control thread with no lock of the device's + /// held, so the host carries the message out on a thread of its own where it waits for + /// anything, the guest's own messages among them. The default answers + /// [`RGFX_VT_STATUS_MALFORMED`], for a host with no such side, which offers no + /// `VT_MESSAGES`. + fn vt_message(&self, message: VtMessage, answer: VtAnswer, link: VtLink) { + let _ = (message, link); + answer.answer(RGFX_VT_STATUS_MALFORMED); + } + /// A `QUEUE_CREATE` made the command queue `completion` posts for: its rings and its service /// thread are the device's. Called on the context's lane with no lock held, before the create /// is answered, so before the guest's processes know the queue, whose buffers a buffer of diff --git a/crates/reims-vgpu-graphics/src/device/backlog.rs b/crates/reims-vgpu-graphics/src/device/backlog.rs index e05af915a..56a3d58e2 100644 --- a/crates/reims-vgpu-graphics/src/device/backlog.rs +++ b/crates/reims-vgpu-graphics/src/device/backlog.rs @@ -70,7 +70,8 @@ pub(super) fn whose(r#type: u32, field: Option) -> Whose { ( RGFX_CMD_GET_DISPLAYS..=RGFX_CMD_SET_DISPLAY_POWER | RGFX_CMD_SURFACE_DOWNLOAD - | RGFX_CMD_PIPELINE_ANSWERS, + | RGFX_CMD_PIPELINE_ANSWERS + | RGFX_CMD_VT_MESSAGE, _, ) => Whose::NoOne, (RGFX_CMD_QUEUE_CREATE..RGFX_CMD_CONTEXT_CLOSE, Some(obj_id)) => { @@ -248,12 +249,13 @@ mod tests { RGFX_CMD_SET_DISPLAY_POWER, RGFX_CMD_SURFACE_DOWNLOAD, RGFX_CMD_PIPELINE_ANSWERS, + RGFX_CMD_VT_MESSAGE, ] { assert_eq!(whose(r#type, field), Whose::NoOne); } assert_eq!(whose(RGFX_CMD_BUFFER_CREATE, None), Whose::Every); assert_eq!(whose(RGFX_CMD_SET_DISPLAY_POWER + 1, obj(5)), Whose::Every); - assert_eq!(whose(RGFX_CMD_PIPELINE_ANSWERS + 1, obj(5)), Whose::Every); + assert_eq!(whose(RGFX_CMD_VT_MESSAGE + 1, obj(5)), Whose::Every); assert_eq!(whose(RGFX_CMD_COMMAND_BUFFER, obj(5)), Whose::Every); } } diff --git a/crates/reims-vgpu-graphics/src/device/tests.rs b/crates/reims-vgpu-graphics/src/device/tests.rs index 39d60f523..2fb603a40 100644 --- a/crates/reims-vgpu-graphics/src/device/tests.rs +++ b/crates/reims-vgpu-graphics/src/device/tests.rs @@ -14,6 +14,7 @@ use crate::display::CursorImage; mod displays; mod motion; mod posting; +mod vt; /// How many times [`eventually`] polls, a millisecond's sleep apart, for a state the device's own /// threads reach: a minute at least, as a loaded host starves those threads for seconds. A test diff --git a/crates/reims-vgpu-graphics/src/device/tests/peer.rs b/crates/reims-vgpu-graphics/src/device/tests/peer.rs index 43899caaf..a625702da 100644 --- a/crates/reims-vgpu-graphics/src/device/tests/peer.rs +++ b/crates/reims-vgpu-graphics/src/device/tests/peer.rs @@ -801,13 +801,13 @@ fn a_producer_waiting_for_room_gets_a_record_after_the_host_s_take() { /// its own, and a later write before the driver is ready replaces what an earlier one took. #[test] fn driver_features_take_what_is_written_offered_and_known() { - // Bits 3 and 5 of the new ones, bit 45 of the high half, bit 9 (reserved) and bit 52, which + // Bits 3 and 5 of the new ones, bit 45 of the high half, bit 9 (reserved) and bit 53, which // the host does not know. let offered = PEER_FEATURES | u64::from(RGFX_FEATURE_QUIET_SCHEDULED | RGFX_FEATURE_QUEUE_BARRIER) | RGFX_FEATURE_READ_ONLY_PAGES | (1 << 9) - | (1 << 52); + | (1 << 53); let mut guest = FakeGuest::offered(offered); assert_eq!(guest.driver_features(), 0, "unwritten, it reads 0"); guest.write(RGFX_REG_STATUS, RGFX_STATUS_RESET); diff --git a/crates/reims-vgpu-graphics/src/device/tests/vt.rs b/crates/reims-vgpu-graphics/src/device/tests/vt.rs new file mode 100644 index 000000000..d13742272 --- /dev/null +++ b/crates/reims-vgpu-graphics/src/device/tests/vt.rs @@ -0,0 +1,129 @@ +//! VideoToolbox's paravirtual messages (docs/graphics-kext/design.md, "Decided", 17): a +//! `VT_MESSAGE` reaches the host checked, and is answered `VT_STATUS`; the host's own messages +//! reach a guest that took `VT_MESSAGES` as `VT_MESSAGE` events, and no other. + +use super::*; + +/// What [`VtHost`] was handed: each message, and the link it came with. +type Handed = Arc>>; + +/// A host that offers `VT_MESSAGES`, sends one message of its own for each `VT_MESSAGE`, then +/// answers it with the message's length, negated. +struct VtHost(Handed); + +impl Host for VtHost { + fn raise_interrupt(&self, _vector: u32) {} + fn features(&self) -> u64 { + RGFX_FEATURE_VT_MESSAGES + } + fn vt_message(&self, message: VtMessage, answer: VtAnswer, link: VtLink) { + let length = message.message.length; + link.send(b"vtpv-reply"); + self.0.lock().push((message, link)); + answer.answer(-(length as i32)); + } +} + +fn vt_rig() -> (Rig, Handed) { + let handed = Handed::default(); + ( + Rig::with_host(Box::new(VtHost(Arc::clone(&handed)))), + handed, + ) +} + +/// The guest's driver takes the bits `bits` of `FEATURES_HI` and starts the device. +fn take_and_start(rig: &Rig, bits: u64) { + rig.device + .mmio_write(RGFX_REG_DRIVER_FEATURES_HI.into(), (bits >> 32) as u32); + rig.start(); +} + +/// A `VT_MESSAGE` of `length` bytes in `runs`, lending the mappings `surfaces`. +fn vt_message(length: u64, runs: &[(u64, u64)], surfaces: &[u64]) -> Vec { + let mut command = RgfxVtMessage { + header: RgfxMsgHeader { + r#type: RGFX_CMD_VT_MESSAGE, + ..Default::default() + }, + length, + run_count: runs.len() as u32, + surface_count: surfaces.len() as u32, + ..RgfxVtMessage::default() + }; + command.surfaces[..surfaces.len()].copy_from_slice(surfaces); + let mut bytes = command.as_bytes().to_vec(); + for &(address, length) in runs { + bytes.extend_from_slice(RgfxPageRun { address, length }.as_bytes()); + } + bytes +} + +/// The next event, as a `VT_STATUS`: its `seqno` and status. +fn status(rig: &mut Rig) -> (u64, i32) { + let s = RgfxVtStatus::read_from_bytes(&rig.event().expect("a VT_STATUS")).unwrap(); + assert_eq!((s.header.r#type, s.header.size), (RGFX_EVT_VT_STATUS, 24)); + (s.header.seqno, s.status) +} + +/// `VT_MESSAGES` (`FEATURES_HI` bit 20) is offered where the host offers it, and only there can +/// the guest take it. +#[test] +fn vt_messages_are_offered_where_the_host_offers_them() { + let (rig, _) = vt_rig(); + let hi = rig.device.mmio_read(RGFX_REG_FEATURES_HI.into()); + assert_eq!(hi, (RGFX_FEATURE_VT_MESSAGES >> 32) as u32); + let plain = Rig::new(); + assert_eq!(plain.device.mmio_read(RGFX_REG_FEATURES_HI.into()), 0); +} + +/// A `VT_MESSAGE` reaches the host with its runs and surfaces, and the host's messages and its +/// answer reach the guest in the order the host gave them. +#[test] +fn a_vt_message_reaches_the_host_and_is_answered_in_order() { + let (mut rig, handed) = vt_rig(); + take_and_start(&rig, RGFX_FEATURE_VT_MESSAGES); + let seqno = rig.send(vt_message(100, &[(0x4000, 64), (0x8000, 0x4000)], &[3, 4])); + let reply = rig.event().expect("the host's VT_MESSAGE"); + let (h, rest) = RgfxVtHostMessage::read_from_prefix(&reply).unwrap(); + assert_eq!((h.header.r#type, h.header.seqno), (RGFX_EVT_VT_MESSAGE, 0)); + assert_eq!(&rest[..h.length as usize], b"vtpv-reply"); + assert_eq!(status(&mut rig), (seqno, -100)); + let handed = handed.lock(); + let (message, _) = &handed[0]; + assert_eq!(message.runs, vec![(0x4000, 64), (0x8000, 0x4000)]); + assert_eq!(message.surfaces(), &[3, 4]); +} + +/// A `VT_MESSAGE` from a guest that did not take `VT_MESSAGES`, or one whose runs do not hold its +/// length, is answered as one the device could not read, and never reaches the host. +#[test] +fn an_unreadable_vt_message_is_answered_malformed() { + let (mut rig, handed) = vt_rig(); + rig.start(); + let seqno = rig.send(vt_message(64, &[(0x4000, 0x4000)], &[])); + assert_eq!(status(&mut rig), (seqno, RGFX_VT_STATUS_MALFORMED)); + let (mut taken, taken_handed) = vt_rig(); + take_and_start(&taken, RGFX_FEATURE_VT_MESSAGES); + let seqno = taken.send(vt_message(0x4001, &[(0x4000, 0x4000)], &[])); + assert_eq!(status(&mut taken), (seqno, RGFX_VT_STATUS_MALFORMED)); + assert!(handed.lock().is_empty() && taken_handed.lock().is_empty()); +} + +/// A host message is dropped for a guest that did not take `VT_MESSAGES` and once the device is +/// reset, and a link made before the reset says it is stale. +#[test] +fn a_host_message_reaches_only_a_guest_that_took_vt_messages() { + let (mut rig, handed) = vt_rig(); + take_and_start(&rig, RGFX_FEATURE_VT_MESSAGES); + let seqno = rig.send(vt_message(48, &[(0x4000, 48)], &[])); + rig.event().expect("the host's VT_MESSAGE"); + assert_eq!(status(&mut rig).0, seqno); + let link = handed.lock()[0].1.clone(); + assert!(!link.stale()); + assert!(link.send(b"again")); + rig.event().expect("the second VT_MESSAGE"); + rig.device.reset(); + assert!(link.stale()); + assert!(!link.send(b"after the reset")); +} diff --git a/crates/reims-vgpu-graphics/src/device/vt.rs b/crates/reims-vgpu-graphics/src/device/vt.rs new file mode 100644 index 000000000..ad94240b0 --- /dev/null +++ b/crates/reims-vgpu-graphics/src/device/vt.rs @@ -0,0 +1,303 @@ +//! VideoToolbox's paravirtual messages ([`RGFX_FEATURE_VT_MESSAGES`]): a `VT_MESSAGE` the guest's +//! VideoToolbox sends its host side, which the host reads from guest RAM and answers with a +//! [`VtAnswer`], and the messages of the host's side to the guest's, which it sends through a +//! [`VtLink`] (docs/graphics-kext/design.md, "Decided", 17). The device reads neither message: it +//! checks a `VT_MESSAGE`'s runs and length, and frames the host's messages. + +use std::sync::Weak; +use std::sync::atomic::Ordering; + +use zerocopy::{FromBytes, IntoBytes}; + +use super::Shared; +use crate::ring::Message; +use crate::wire::*; + +/// The `VT_STATUS` a `VT_MESSAGE` owes, which the host gives from any thread once its side took +/// the message ([`super::Host::vt_message`]). It holds a weak reference to the device; an answer +/// after the device has ended, or for a message taken before a reset, is dropped, and so is one +/// never given. +pub struct VtAnswer { + /// The device's shared state, weakly. + shared: Weak, + /// The message's `seqno`. + seqno: u64, + /// The reset count the message was taken at. + epoch: u64, +} + +impl std::fmt::Debug for VtAnswer { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("VtAnswer") + .field("seqno", &self.seqno) + .finish_non_exhaustive() + } +} + +impl VtAnswer { + /// Posts the `VT_STATUS` with `status` onto the control completion ring, waiting for nothing, + /// as a [`super::CompleteAnswer`] posts its `COMPLETE`. + pub fn answer(self, status: i32) { + if let Some(shared) = self.shared.upgrade() { + shared.post_unwaiting(&vt_status(self.seqno, status), self.epoch); + } + } +} + +/// A handle that sends the guest's VideoToolbox the messages of its host side, from any thread +/// ([`Self::send`]). It holds the device weakly, so it keeps it alive no longer, and sends for the +/// reset count it was made at: once the device is reset, what it sends is dropped. +#[derive(Clone)] +pub struct VtLink { + /// The device's shared state, weakly. + shared: Weak, + /// The reset count of the `VT_MESSAGE` it came with. + epoch: u64, +} + +impl std::fmt::Debug for VtLink { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("VtLink") + .field("epoch", &self.epoch) + .finish_non_exhaustive() + } +} + +impl VtLink { + /// Sends `message`, a `vtpv` message or a `rels` box of at most [`RGFX_VT_HOST_MESSAGE_MAX`] + /// bytes, as a `VT_MESSAGE` event, in the order sent, waiting for nothing: posted here where + /// the ring has room and nothing is handed over before it, else handed to the control thread. + /// False, with nothing sent, for a longer message, a guest that did not take + /// [`RGFX_FEATURE_VT_MESSAGES`], a device that has ended or is not started, or a reset since + /// the link was made. + pub fn send(&self, message: &[u8]) -> bool { + let Some(shared) = self.shared.upgrade() else { + return false; + }; + let Some(event) = host_message(message) else { + return false; + }; + if !shared.driver_took(RGFX_FEATURE_VT_MESSAGES) + || !shared.started() + || self.stale_in(&shared) + { + return false; + } + shared.post_unwaiting(&event, self.epoch); + true + } + + /// Whether the device was reset since the link was made, or has ended: nothing it sends + /// reaches the guest. + pub fn stale(&self) -> bool { + self.shared + .upgrade() + .is_none_or(|shared| self.stale_in(&shared)) + } + + fn stale_in(&self, shared: &Shared) -> bool { + shared.epoch.load(Ordering::Acquire) != self.epoch + } +} + +/// A `VT_MESSAGE`'s answer: `VT_STATUS` with `status`. +pub(crate) fn vt_status(seqno: u64, status: i32) -> Vec { + RgfxVtStatus { + header: RgfxMsgHeader { + r#type: RGFX_EVT_VT_STATUS, + size: size_of::() as u32, + seqno, + }, + status, + reserved_14: 0, + } + .as_bytes() + .to_vec() +} + +/// The `VT_MESSAGE` event of `message`, its size rounded up to a multiple of 8; `None` for a +/// message longer than [`RGFX_VT_HOST_MESSAGE_MAX`]. +pub(crate) fn host_message(message: &[u8]) -> Option> { + let length = u32::try_from(message.len()) + .ok() + .filter(|&l| l <= RGFX_VT_HOST_MESSAGE_MAX)?; + let bytes = RGFX_VT_HOST_MESSAGE_BYTES_OFFSET + length; + let size = bytes.next_multiple_of(8); + let mut event = Vec::with_capacity(size as usize); + event.extend_from_slice( + RgfxVtHostMessage { + header: RgfxMsgHeader { + r#type: RGFX_EVT_VT_MESSAGE, + size, + seqno: 0, + }, + length, + reserved_14: 0, + } + .as_bytes(), + ); + event.extend_from_slice(message); + event.resize(size as usize, 0); + Some(event) +} + +/// A `VT_MESSAGE`, checked: its struct, and its runs. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct VtMessage { + /// The message as the guest posted it. + pub message: RgfxVtMessage, + /// Its runs of guest RAM, `(address, length)`, in order, which hold its `length` bytes from + /// the first run's first byte. + pub runs: Vec<(u64, u64)>, +} + +impl VtMessage { + /// The IDs of the IOSurfaces the message lends, in order. + pub fn surfaces(&self) -> &[u64] { + let count = (self.message.surface_count as usize).min(RGFX_VT_MESSAGE_SURFACES); + &self.message.surfaces[..count] + } +} + +/// `message` as a `VT_MESSAGE`, checked: `None` where it is shorter than its struct and runs, +/// names more surfaces than it holds, or its `length` is under a `vtpv` header's 48 bytes, over +/// [`RGFX_VT_MESSAGE_MAX`] or more than its runs hold. +pub(crate) fn read_message(message: &Message) -> Option { + let (command, rest) = RgfxVtMessage::read_from_prefix(&message.bytes).ok()?; + let length = command.length; + if !(48..=RGFX_VT_MESSAGE_MAX).contains(&length) + || command.surface_count as usize > RGFX_VT_MESSAGE_SURFACES + { + return None; + } + let count = command.run_count as usize; + let runs = rest.get(..count.checked_mul(size_of::())?)?; + let runs: Vec<(u64, u64)> = runs + .as_chunks::<{ size_of::() }>() + .0 + .iter() + .filter_map(|r| RgfxPageRun::read_from_bytes(r).ok()) + .map(|r| (r.address, r.length)) + .collect(); + let held = runs + .iter() + .try_fold(0u64, |sum, &(_, l)| sum.checked_add(l))?; + (held >= length).then_some(VtMessage { + message: command, + runs, + }) +} + +impl Shared { + /// The answer `VT_MESSAGE` `seqno`, taken at reset count `epoch`, owes ([`VtAnswer`]). + pub(crate) fn vt_answer(&self, seqno: u64, epoch: u64) -> VtAnswer { + VtAnswer { + shared: self.weak_self.get().cloned().unwrap_or_else(Weak::new), + seqno, + epoch, + } + } + + /// A link that sends the guest's VideoToolbox host messages at reset count `epoch` + /// ([`VtLink`]). + pub(crate) fn vt_link(&self, epoch: u64) -> VtLink { + VtLink { + shared: self.weak_self.get().cloned().unwrap_or_else(Weak::new), + epoch, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ring::Message; + + fn message(command: RgfxVtMessage, runs: &[RgfxPageRun]) -> Message { + let mut bytes = command.as_bytes().to_vec(); + for run in runs { + bytes.extend_from_slice(run.as_bytes()); + } + Message { + header: command.header, + bytes, + } + } + + fn command(length: u64, run_count: u32) -> RgfxVtMessage { + RgfxVtMessage { + header: RgfxMsgHeader { + r#type: RGFX_CMD_VT_MESSAGE, + size: RGFX_VT_MESSAGE_RUNS_OFFSET + 16 * run_count, + seqno: 7, + }, + length, + run_count, + ..RgfxVtMessage::default() + } + } + + #[test] + fn a_message_its_runs_hold_is_read_with_them() { + let runs = [ + RgfxPageRun { + address: 0x4000, + length: 0x4000, + }, + RgfxPageRun { + address: 0x10000, + length: 0x4000, + }, + ]; + let mut c = command(0x5000, 2); + c.surface_count = 1; + c.surfaces[0] = 9; + let read = read_message(&message(c, &runs)).unwrap(); + assert_eq!(read.runs, vec![(0x4000, 0x4000), (0x10000, 0x4000)]); + assert_eq!(read.surfaces(), &[9]); + } + + #[test] + fn a_message_is_refused_where_its_runs_or_length_do_not_hold() { + let run = [RgfxPageRun { + address: 0x4000, + length: 0x4000, + }]; + // More bytes than the runs hold. + assert!(read_message(&message(command(0x4001, 1), &run)).is_none()); + // Under a `vtpv` header. + assert!(read_message(&message(command(47, 1), &run)).is_none()); + // Over the most a message buffer holds. + assert!(read_message(&message(command(RGFX_VT_MESSAGE_MAX + 1, 1), &run)).is_none()); + // Runs past the message's end. + assert!(read_message(&message(command(64, 2), &run)).is_none()); + // More surfaces than a message lends. + let mut c = command(64, 1); + c.surface_count = 6; + assert!(read_message(&message(c, &run)).is_none()); + } + + #[test] + fn a_host_message_is_framed_and_padded_to_8() { + let event = host_message(&[1, 2, 3]).unwrap(); + assert_eq!(event.len(), 32); + let (h, rest) = RgfxVtHostMessage::read_from_prefix(&event).unwrap(); + assert_eq!(h.header.r#type, RGFX_EVT_VT_MESSAGE); + assert_eq!(h.header.size, 32); + assert_eq!(h.header.seqno, 0); + assert_eq!(h.length, 3); + assert_eq!(rest, &[1, 2, 3, 0, 0, 0, 0, 0]); + let longest = vec![0u8; RGFX_VT_HOST_MESSAGE_MAX as usize]; + assert!(host_message(&longest).is_some()); + assert!(host_message(&[0u8; RGFX_VT_HOST_MESSAGE_MAX as usize + 1]).is_none()); + } + + #[test] + fn a_status_answers_its_message() { + let bytes = vt_status(7, -12909); + let (s, _) = RgfxVtStatus::read_from_prefix(&bytes).unwrap(); + assert_eq!(s.header.r#type, RGFX_EVT_VT_STATUS); + assert_eq!(s.header.seqno, 7); + assert_eq!(s.status, -12909); + } +} diff --git a/crates/reims-vgpu-graphics/src/lib.rs b/crates/reims-vgpu-graphics/src/lib.rs index d32d9945f..983e25f8c 100644 --- a/crates/reims-vgpu-graphics/src/lib.rs +++ b/crates/reims-vgpu-graphics/src/lib.rs @@ -33,7 +33,7 @@ pub mod wire; pub use device::{ CompleteAnswer, CompletionPoster, Device, DoorbellAt, Host, PointerLink, PresentAnswer, - QueueClaim, REGION_SIZE, RingDegradation, Spot, Then, + QueueClaim, REGION_SIZE, RingDegradation, Spot, Then, VtAnswer, VtLink, VtMessage, }; pub use display::{CursorImage, FixedScreen, Mode, Scanout, Screen}; pub use wake::RawDoorbell; diff --git a/crates/reims-vgpu-graphics/src/wire.rs b/crates/reims-vgpu-graphics/src/wire.rs index de6d50f1b..c0fcacf21 100644 --- a/crates/reims-vgpu-graphics/src/wire.rs +++ b/crates/reims-vgpu-graphics/src/wire.rs @@ -473,6 +473,13 @@ pub const RGFX_FEATURE_DISPLAY_BOUNDS: u64 = 0x4_0000_0000_0000; /// pointer for games"): a guest that did not take it (a kext built before this bit, the option ROM, /// Ambrosia's module) publishes no device and is never sent it. pub const RGFX_FEATURE_POINTER_MOTION: u64 = 0x8_0000_0000_0000; +/// `FEATURES_HI` bit 20, feature bit 52, `VT_MESSAGES`: ring 0 carries +/// [`RGFX_CMD_VT_MESSAGE`], a message of the guest's VideoToolbox to its host side, which the host +/// answers [`RGFX_EVT_VT_STATUS`], and the control completion ring carries +/// [`RGFX_EVT_VT_MESSAGE`], a message of the host's side to the guest's VideoToolbox +/// (docs/graphics-kext/design.md, "Decided", 17). The arm64e kext takes it where it publishes the +/// paravirtual VideoToolbox service; the device sends `VT_MESSAGE` only to a guest that took it. +pub const RGFX_FEATURE_VT_MESSAGES: u64 = 0x10_0000_0000_0000; /// `STATUS`, RW: writing [`RGFX_STATUS_RESET`] resets the device; the guest writes /// [`RGFX_STATUS_DRIVER_READY`] once it has read the rings' headers. pub const RGFX_REG_STATUS: u32 = 0x010; @@ -1175,6 +1182,30 @@ pub const RGFX_CMD_SURFACE_PAGES: u32 = 0x2f6; /// [`RGFX_STATUS_OK`] once the pages hold it: at once where no command buffer wrote the cache /// since it was last copied either way, or the block has no cache. pub const RGFX_CMD_SURFACE_DOWNLOAD: u32 = 0x2f7; +/// `VT_MESSAGE` ([`RgfxVtMessage`], then its `run_count` [`RgfxPageRun`]s at +/// [`RGFX_VT_MESSAGE_RUNS_OFFSET`]), on ring 0 from the arm64e kext, where the guest took +/// [`RGFX_FEATURE_VT_MESSAGES`]: one message of the guest's VideoToolbox to its host side, a `vtpv` +/// message as VideoToolbox writes it (docs/graphics-kext/design.md, "Decided", 17), its `length` +/// bytes in the guest RAM the runs name, in order, from the first run's first byte. The surfaces +/// the message lends are named by their IOSurface IDs, in `surfaces`, the used ones first and the +/// rest 0. No command buffer waits for it, and it waits for none. Answered [`RGFX_EVT_VT_STATUS`] with +/// its `seqno`: the status VideoToolbox's host side returns for the message, or +/// [`RGFX_VT_STATUS_MALFORMED`] where the runs do not hold `length` bytes of guest RAM, or +/// `length` is under the 48 bytes of a `vtpv` header or over [`RGFX_VT_MESSAGE_MAX`]. +pub const RGFX_CMD_VT_MESSAGE: u32 = 0x2fa; +/// Where a `VT_MESSAGE`'s runs start: right after its [`RgfxVtMessage`]. +pub const RGFX_VT_MESSAGE_RUNS_OFFSET: u32 = 72; +/// The most surfaces a `VT_MESSAGE` lends: VideoToolbox's five. +pub const RGFX_VT_MESSAGE_SURFACES: usize = 5; +/// The longest message a `VT_MESSAGE` carries: 10 MiB, the most the kext's message buffer holds, +/// as Apple's kext of the service sizes its own. +pub const RGFX_VT_MESSAGE_MAX: u64 = 0xa0_0000; +/// The longest message a [`RGFX_EVT_VT_MESSAGE`] carries: 16 KiB, the buffer VideoToolbox's +/// guest side takes each host message into. +pub const RGFX_VT_HOST_MESSAGE_MAX: u32 = 0x4000; +/// [`RgfxVtStatus::status`] for a `VT_MESSAGE` the device could not read: VideoToolbox's +/// `kVTParameterErr`, as the guest's support framework answers a message it cannot send. +pub const RGFX_VT_STATUS_MALFORMED: i32 = -12902; /// Command `COMMAND_BUFFER` (a per-queue submission ring): one command buffer, /// its `obj_id` followed by the encoder-op byte stream. Struct and op stream in @@ -1264,6 +1295,17 @@ pub const RGFX_EVT_RATE_MAP_ANSWER: u32 = 0x40b; /// Event `FUNCTION_POINTER_STATE` ([`RgfxFunctionPointerState`], on the control completion /// ring): a `FUNCTION_HANDLE_CREATE`'s or `FUNCTION_TABLE_CREATE`'s answer. pub const RGFX_EVT_FUNCTION_POINTER_STATE: u32 = 0x40c; +/// Event `VT_STATUS` ([`RgfxVtStatus`], on the control completion ring): a `VT_MESSAGE`'s +/// answer, with its `seqno`. +pub const RGFX_EVT_VT_STATUS: u32 = 0x40d; +/// Event `VT_MESSAGE` ([`RgfxVtHostMessage`], then its `length` bytes at +/// [`RGFX_VT_HOST_MESSAGE_BYTES_OFFSET`], on the control completion ring), `seqno` 0, sent only to +/// a guest that took [`RGFX_FEATURE_VT_MESSAGES`]: one message of VideoToolbox's host side to the +/// guest's, of at most [`RGFX_VT_HOST_MESSAGE_MAX`] bytes, a `vtpv` message or a `rels` box. The +/// message's `size` is rounded up to a multiple of 8 after its bytes. +pub const RGFX_EVT_VT_MESSAGE: u32 = 0x40e; +/// Where a `VT_MESSAGE` event's bytes start: right after its [`RgfxVtHostMessage`]. +pub const RGFX_VT_HOST_MESSAGE_BYTES_OFFSET: u32 = 24; /// A command buffer's status in [`RgfxCbComplete`]: finished with no error. pub const RGFX_CB_OK: u32 = 0; @@ -1735,6 +1777,9 @@ const _: () = { assert!(offset_of!(RgfxRingHeader, guest_clock_bound_ns) == 0x20); assert!(offset_of!(RgfxRingHeader, raise_all) == 0xc4); assert!(size_of::() == 16); + assert!(size_of::() == RGFX_VT_MESSAGE_RUNS_OFFSET as usize); + assert!(size_of::() == 24); + assert!(size_of::() == RGFX_VT_HOST_MESSAGE_BYTES_OFFSET as usize); assert!(size_of::() == 16); assert!(size_of::() == 40); assert!(size_of::() == 48); @@ -2327,6 +2372,56 @@ pub struct RgfxSurfaceDownload { pub block_offset: u64, } +/// `VT_MESSAGE`: one message of the guest's VideoToolbox, `length` bytes in the guest RAM of the +/// `run_count` [`RgfxPageRun`]s that follow, lending the IOSurfaces of the IDs in `surfaces`. +#[repr(C)] +#[derive( + Clone, Copy, Debug, Default, PartialEq, Eq, FromBytes, IntoBytes, Immutable, KnownLayout, +)] +pub struct RgfxVtMessage { + /// [`RGFX_CMD_VT_MESSAGE`]. + pub header: RgfxMsgHeader, + /// The message's bytes. + pub length: u64, + /// How many runs follow, at [`RGFX_VT_MESSAGE_RUNS_OFFSET`]. + pub run_count: u32, + /// How many of `surfaces` are used, from the first. + pub surface_count: u32, + /// The IDs of the IOSurfaces the message lends, each one its sender's process looks up, the + /// used ones first, the rest 0. + pub surfaces: [u64; RGFX_VT_MESSAGE_SURFACES], +} + +/// `VT_STATUS`: a `VT_MESSAGE`'s answer. +#[repr(C)] +#[derive( + Clone, Copy, Debug, Default, PartialEq, Eq, FromBytes, IntoBytes, Immutable, KnownLayout, +)] +pub struct RgfxVtStatus { + /// [`RGFX_EVT_VT_STATUS`], with the message's `seqno`. + pub header: RgfxMsgHeader, + /// The status VideoToolbox's host side returns for the message (an `OSStatus`: 0 for one it + /// took), or [`RGFX_VT_STATUS_MALFORMED`]. + pub status: i32, + /// Pads the message to a multiple of 8; 0. + pub reserved_14: u32, +} + +/// The `VT_MESSAGE` event: one message of VideoToolbox's host side, its `length` bytes after +/// this struct. +#[repr(C)] +#[derive( + Clone, Copy, Debug, Default, PartialEq, Eq, FromBytes, IntoBytes, Immutable, KnownLayout, +)] +pub struct RgfxVtHostMessage { + /// [`RGFX_EVT_VT_MESSAGE`], `seqno` 0. + pub header: RgfxMsgHeader, + /// The message's bytes, at most [`RGFX_VT_HOST_MESSAGE_MAX`]. + pub length: u32, + /// Pads the bytes to a multiple of 8; 0. + pub reserved_14: u32, +} + /// `BUFFER_OVER_SURFACE_PAGES`: a Shared buffer of `length` bytes over the IOSurface pages the /// shared block of `block_size` bytes at `block_offset` names. #[repr(C)] diff --git a/crates/reims-vgpu-graphics/tests/header.rs b/crates/reims-vgpu-graphics/tests/header.rs index 513345e44..1347035b1 100644 --- a/crates/reims-vgpu-graphics/tests/header.rs +++ b/crates/reims-vgpu-graphics/tests/header.rs @@ -53,6 +53,15 @@ CHECK(offsetof(RgfxPointerMotion, wheel) == 24); CHECK(offsetof(RgfxPointerMotion, buttons) == 28); CHECK(RGFX_EVT_POINTER_MOTION == 0x105); CHECK(RGFX_FEATURE_POINTER_MOTION == (1ULL << 51)); +CHECK(RGFX_FEATURE_VT_MESSAGES == (1ULL << 52)); +CHECK(RGFX_CMD_VT_MESSAGE == 0x2fa); +CHECK(sizeof(RgfxVtMessage) == RGFX_VT_MESSAGE_RUNS_OFFSET); +CHECK(offsetof(RgfxVtMessage, surfaces) == 32); +CHECK(RGFX_EVT_VT_STATUS == 0x40d && sizeof(RgfxVtStatus) == 24); +CHECK(offsetof(RgfxVtStatus, status) == 16); +CHECK(RGFX_EVT_VT_MESSAGE == 0x40e); +CHECK(sizeof(RgfxVtHostMessage) == RGFX_VT_HOST_MESSAGE_BYTES_OFFSET); +CHECK(RGFX_VT_HOST_MESSAGE_MAX == 0x4000 && RGFX_VT_MESSAGE_MAX == 0xa00000); CHECK(RGFX_POINTER_BUTTON_LEFT == 1 && RGFX_POINTER_BUTTON_EXTRA == 16); CHECK(sizeof(RgfxDisplayBounds) == 40); CHECK(offsetof(RgfxDisplayBounds, min_x) == 20); diff --git a/crates/reims-vgpu-video/src/lib.rs b/crates/reims-vgpu-video/src/lib.rs index c26ec5bac..15579cd0e 100644 --- a/crates/reims-vgpu-video/src/lib.rs +++ b/crates/reims-vgpu-video/src/lib.rs @@ -5,6 +5,8 @@ //! guest surface's memory as a device reaches it, and its bounded waits on the hardware. //! - [`codec`] is H.264's and HEVC's syntax and decoding processes above the slice data, and the //! encoders' portable half, in plain Rust. +//! - [`paravirt`] is VideoToolbox's paravirtual protocol, the host's side: the messages an arm64 +//! guest's VideoToolbox sends, and the host's answers. //! - `vaapi` is VA-API through libva, and `nvidia` NVDEC and NVENC over the CUDA driver API, each //! with its libraries loaded at run time: Linux's alone. @@ -12,6 +14,7 @@ pub mod codec; pub mod core; #[cfg(target_os = "linux")] pub mod nvidia; +pub mod paravirt; #[cfg(all(test, target_os = "linux"))] mod probes; #[cfg(target_os = "linux")] diff --git a/crates/reims-vgpu-video/src/paravirt.rs b/crates/reims-vgpu-video/src/paravirt.rs new file mode 100644 index 000000000..20272dd98 --- /dev/null +++ b/crates/reims-vgpu-video/src/paravirt.rs @@ -0,0 +1,53 @@ +//! VideoToolbox's paravirtual protocol, the host's side (docs/graphics-kext/design.md, "Decided", +//! 17): the `vtpv` messages an arm64 guest's VideoToolbox sends its host, which the arm64e kext +//! carries to the device as `VT_MESSAGE`s, and the host's answers. +//! +//! - [`atom`] and [`message`] read and write the messages, and [`plist`] writes the property +//! lists they carry. +//! - [`Host`] answers them: the decoder list (`decs`) and a decoder's capabilities (`dcap`) from +//! the decoders the host's video arm runs ([`Decoder`]), no encoder (`encs`) and no +//! motion-estimation processor (`meps`), a create of any session refused, as for a codec the +//! host lacks, and its close taken. +//! - [`status`] is the statuses the guest sees. + +// The library's lint set, as `core`'s: no unsafe code, no indexing that can panic, and no silent +// `as` conversion outside tests. +#![deny( + unsafe_code, + clippy::indexing_slicing, + clippy::unwrap_used, + clippy::expect_used, + clippy::panic, + clippy::unreachable, + clippy::disallowed_types, + clippy::disallowed_methods, + clippy::mod_module_files +)] + +pub mod atom; +mod host; +mod lists; +pub mod message; +mod names; +pub mod plist; +pub mod status; + +pub use host::{Answer, Codec, Decoder, Host}; + +/// Why guest bytes could not be read. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum WireError { + /// The bytes do not follow the format: an atom's size, a parameter's length or type, a + /// missing header. + #[error("malformed: {0}")] + Malformed(&'static str), +} + +impl WireError { + /// The status the guest sees for this failure. + pub fn status(&self) -> status::OsStatus { + match self { + Self::Malformed(_) => status::MALFORMED_MESSAGE, + } + } +} diff --git a/crates/reims-vgpu-video/src/paravirt/atom.rs b/crates/reims-vgpu-video/src/paravirt/atom.rs new file mode 100644 index 000000000..50f7b5a25 --- /dev/null +++ b/crates/reims-vgpu-video/src/paravirt/atom.rs @@ -0,0 +1,227 @@ +//! QuickTime-style atoms: a big-endian u32 size that counts the 8-byte +//! header, a big-endian type, then the payload. Messages, parameters, +//! sample buffer serializations and image description extensions are all +//! built from them. + +use crate::core::fourcc::FourCc; +use crate::paravirt::WireError; + +/// The size of an atom's header: its size and its type. +pub const ATOM_HEADER_SIZE: usize = 8; + +/// One atom found in a byte range. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Atom<'a> { + /// The atom's type. + pub kind: FourCc, + /// Where the atom starts, relative to the range it was found in. + pub offset: usize, + /// The whole atom, header included. + pub bytes: &'a [u8], +} + +impl<'a> Atom<'a> { + /// What follows the header. + pub fn payload(&self) -> &'a [u8] { + self.bytes.get(ATOM_HEADER_SIZE..).unwrap_or_default() + } +} + +/// The atoms that follow each other in `bytes`, each read as a sibling. +/// +/// A size under 8 or past the end ends the walk with an error, as +/// FigAtomStream's walk does; a tail shorter than a header ends it quietly. +pub fn siblings(bytes: &[u8]) -> Siblings<'_> { + Siblings { + bytes, + offset: 0, + failed: false, + } +} + +/// The iterator [`siblings`] returns. +#[derive(Clone, Debug)] +pub struct Siblings<'a> { + bytes: &'a [u8], + offset: usize, + failed: bool, +} + +impl<'a> Iterator for Siblings<'a> { + type Item = Result, WireError>; + + fn next(&mut self) -> Option { + if self.failed { + return None; + } + let rest = self.bytes.get(self.offset..)?; + if rest.len() < ATOM_HEADER_SIZE { + return None; + } + let size = usize::try_from(read_u32(rest, 0)?).ok()?; + if size < ATOM_HEADER_SIZE || size > rest.len() { + self.failed = true; + return Some(Err(WireError::Malformed("atom size"))); + } + let atom = Atom { + kind: FourCc(read_u32(rest, 4)?), + offset: self.offset, + bytes: rest.get(..size)?, + }; + self.offset += size; + Some(Ok(atom)) + } +} + +/// The big-endian u32 at `offset`, if the bytes reach that far. +pub fn read_u32(bytes: &[u8], offset: usize) -> Option { + let field = bytes.get(offset..offset.checked_add(4)?)?; + Some(u32::from_be_bytes(field.try_into().ok()?)) +} + +/// The big-endian u64 at `offset`, if the bytes reach that far. +pub fn read_u64(bytes: &[u8], offset: usize) -> Option { + let field = bytes.get(offset..offset.checked_add(8)?)?; + Some(u64::from_be_bytes(field.try_into().ok()?)) +} + +/// The big-endian u16 at `offset`, if the bytes reach that far. +pub fn read_u16(bytes: &[u8], offset: usize) -> Option { + let field = bytes.get(offset..offset.checked_add(2)?)?; + Some(u16::from_be_bytes(field.try_into().ok()?)) +} + +/// Writes atoms into a growing buffer, nesting as FigAtomWriter does: each +/// atom's size is filled in when it ends. +#[derive(Debug, Default)] +pub struct AtomWriter { + bytes: Vec, + open: Vec, +} + +impl AtomWriter { + /// An empty writer. + pub fn new() -> Self { + Self::default() + } + + /// A writer that appends to `bytes`. + pub fn with_bytes(bytes: Vec) -> Self { + Self { + bytes, + open: Vec::new(), + } + } + + /// Starts an atom of type `kind`; its payload is what is written until + /// the matching [`end`](Self::end). + pub fn begin(&mut self, kind: FourCc) -> &mut Self { + self.open.push(self.bytes.len()); + self.bytes.extend_from_slice(&[0; 4]); + self.bytes.extend_from_slice(&kind.to_be_bytes()); + self + } + + /// Appends payload bytes to the open atom. + pub fn append(&mut self, payload: &[u8]) -> &mut Self { + self.bytes.extend_from_slice(payload); + self + } + + /// Ends the innermost open atom, writing its size. + /// + /// An atom larger than 4 GiB cannot be written; it is truncated to the + /// u32 the header has room for, which no message here comes near (the + /// guest's buffers are 0xa00000 bytes at most). + pub fn end(&mut self) -> &mut Self { + if let Some(start) = self.open.pop() { + let size = u32::try_from(self.bytes.len() - start).unwrap_or(u32::MAX); + if let Some(field) = self.bytes.get_mut(start..start + 4) { + field.copy_from_slice(&size.to_be_bytes()); + } + } + self + } + + /// A whole atom: `kind`, then `payload`. + pub fn atom(&mut self, kind: FourCc, payload: &[u8]) -> &mut Self { + self.begin(kind).append(payload).end() + } + + /// The bytes so far, to patch a field already written. + pub fn bytes_mut(&mut self) -> &mut [u8] { + &mut self.bytes + } + + /// The bytes so far. + pub fn len(&self) -> usize { + self.bytes.len() + } + + /// Whether nothing is written yet. + pub fn is_empty(&self) -> bool { + self.bytes.is_empty() + } + + /// The bytes, with every atom still open ended. + pub fn finish(mut self) -> Vec { + while !self.open.is_empty() { + self.end(); + } + self.bytes + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn nested_atoms_get_their_sizes() { + let mut writer = AtomWriter::new(); + writer.begin(FourCc::new(*b"outr")); + writer.atom(FourCc::new(*b"innr"), &[1, 2, 3]); + writer.end(); + let bytes = writer.finish(); + assert_eq!( + bytes, + [ + 0, 0, 0, 19, b'o', b'u', b't', b'r', 0, 0, 0, 11, b'i', b'n', b'n', b'r', 1, 2, 3 + ] + ); + let outer: Vec<_> = siblings(&bytes).collect(); + assert_eq!(outer.len(), 1); + let Some(Ok(outer)) = outer.first().cloned() else { + panic!("one atom"); + }; + let inner: Vec<_> = siblings(outer.payload()).collect(); + assert_eq!( + inner, + [Ok(Atom { + kind: FourCc::new(*b"innr"), + offset: 0, + bytes: &bytes[8..19], + })] + ); + } + + #[test] + fn an_atom_past_the_end_is_malformed() { + let bytes = [0, 0, 0, 12, b'a', b'b', b'c', b'd', 0, 0]; + let found: Vec<_> = siblings(&bytes).collect(); + assert_eq!(found, [Err(WireError::Malformed("atom size"))]); + } + + #[test] + fn an_atom_smaller_than_its_header_is_malformed() { + let bytes = [0, 0, 0, 4, b'a', b'b', b'c', b'd']; + let found: Vec<_> = siblings(&bytes).collect(); + assert_eq!(found, [Err(WireError::Malformed("atom size"))]); + } + + #[test] + fn a_short_tail_ends_the_walk() { + let bytes = [0, 0, 0, 8, b'a', b'b', b'c', b'd', 0, 0, 0]; + assert_eq!(siblings(&bytes).count(), 1); + } +} diff --git a/crates/reims-vgpu-video/src/paravirt/host.rs b/crates/reims-vgpu-video/src/paravirt/host.rs new file mode 100644 index 000000000..1f9b6215f --- /dev/null +++ b/crates/reims-vgpu-video/src/paravirt/host.rs @@ -0,0 +1,408 @@ +//! The host's side of the guest's messages: what each is answered with, and what the host sends +//! the guest for it. + +use crate::core::fourcc::FourCc; +use crate::paravirt::lists::{self, MotionEstimationAnswer}; +use crate::paravirt::message::{Message, read_header}; +use crate::paravirt::names::{self, HostMessage}; +use crate::paravirt::status::{self, OsStatus}; + +/// A codec the host's decoders decode. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Codec { + /// H.264, `avc1`. + H264, + /// HEVC, `hvc1`. + Hevc, +} + +impl Codec { + /// The CoreMedia codec type the guest names it by. + pub const fn fourcc(self) -> FourCc { + FourCc::new(match self { + Self::H264 => *b"avc1", + Self::Hevc => *b"hvc1", + }) + } +} + +/// A decoder the host's video arm runs, as the decoder list names it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Decoder { + /// Its codec. + pub codec: Codec, + /// The profiles it decodes, as VideoToolbox numbers them (H.264's `profile_idc`, HEVC's + /// `general_profile_idc`), in ascending order. + pub profiles: Vec, + /// The highest level it decodes, as the codec numbers it (H.264's `level_idc`, HEVC's + /// `general_level_idc`). + pub max_level: u32, +} + +/// What a guest message is answered with: the status the guest's send returns, and the messages +/// the host sends the guest for it, in order, each at most the guest's 16 KiB dequeue buffer. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Answer { + /// The status. + pub status: OsStatus, + /// The messages to the guest. + pub replies: Vec>, +} + +impl Answer { + fn status(status: OsStatus) -> Self { + Self { + status, + replies: Vec::new(), + } + } + + fn reply(reply: Vec) -> Self { + Self { + status: status::NO_ERROR, + replies: vec![reply], + } + } +} + +/// The host's side: the decoders the host's video arm runs, and the answers the module doc of +/// [`crate::paravirt`] lists. It keeps no session. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Host { + decoders: Vec, +} + +impl Host { + /// A host whose decoder list holds `decoders`. + pub fn new(decoders: Vec) -> Self { + Self { decoders } + } + + /// The decoders the list holds. + pub fn decoders(&self) -> &[Decoder] { + &self.decoders + } + + /// Answers the guest's message `bytes`, as the kext took it from its client: a message that + /// does not read is malformed, and one for a session is answered as for a UUID with none. + pub fn deliver(&self, bytes: &[u8]) -> Answer { + if let Err(error) = read_header(bytes, 0) { + return Answer::status(error.status()); + } + let message = match Message::parse(bytes) { + Ok(message) => message, + Err(error) => return Answer::status(error.status()), + }; + let header = message.header(); + let Some(kind) = HostMessage::from_fourcc(header.message_type) else { + return Answer::status(status::SESSION_NOT_FOUND); + }; + let replied = |reply: Result, crate::paravirt::WireError>| match reply { + Ok(reply) => Answer::reply(reply), + Err(error) => Answer::status(error.status()), + }; + match kind { + HostMessage::DecoderList => replied(lists::decoder_list(&message, &self.decoders)), + HostMessage::DecoderCapabilities => { + replied(lists::decoder_capabilities(&message, &self.decoders)) + } + HostMessage::EncoderList => replied(lists::encoder_list(&message)), + HostMessage::MotionEstimationList => match lists::motion_estimation_list(&message) { + Ok(MotionEstimationAnswer::Reply(reply)) => Answer::reply(reply), + Ok(MotionEstimationAnswer::Refused(status)) => Answer::status(status), + Err(error) => Answer::status(error.status()), + }, + HostMessage::CreateDecoder | HostMessage::CreateEncoder => { + // A decoder or encoder create needs a nonzero `,cod` and reads `,ver`, as + // Apple's create reads them. + match (message.s32(names::CODEC), message.u32(names::VERSION)) { + (Ok(Some(codec)), Ok(_)) if codec != 0 => { + let refused = if kind == HostMessage::CreateDecoder { + status::COULD_NOT_FIND_VIDEO_DECODER + } else { + status::COULD_NOT_FIND_VIDEO_ENCODER + }; + Answer::reply(lists::create_reply(&message, refused)) + } + (Err(error), _) | (_, Err(error)) => Answer::status(error.status()), + _ => Answer::status(status::MALFORMED_MESSAGE), + } + } + HostMessage::CreateMotionEstimation => match message.u32(names::VERSION) { + Ok(_) => Answer::reply(lists::create_reply( + &message, + status::MOTION_ESTIMATION_PROCESSOR_NOT_FOUND, + )), + Err(error) => Answer::status(error.status()), + }, + // The host keeps no session, so a close finds none to end. + HostMessage::Destroy => Answer::status(status::NO_ERROR), + HostMessage::Jpeg => { + Answer::reply(lists::jpeg_reply(&message, status::NO_JPEG_HARDWARE)) + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::paravirt::message::{GuestUuid, MessageFlags, MessageWriter}; + use crate::paravirt::plist::{Value, encode}; + + fn decoders() -> Vec { + vec![ + Decoder { + codec: Codec::H264, + profiles: vec![66, 77, 100], + max_level: 52, + }, + Decoder { + codec: Codec::Hevc, + profiles: vec![1, 2, 3], + max_level: 153, + }, + ] + } + + fn request(kind: &[u8; 4]) -> MessageWriter { + MessageWriter::new( + FourCc::new(*kind), + MessageFlags::GUEST_EXPECTS_REPLY, + Some(GuestUuid([0x5a; 16])), + 9, + ) + } + + /// The one reply `answer` holds, checked as the reply to a request of `kind`, and its status. + fn one_reply(answer: &Answer, kind: &[u8; 4]) -> Vec { + assert_eq!(answer.status, 0); + let [reply] = answer.replies.as_slice() else { + panic!("one reply, not {}", answer.replies.len()) + }; + let header = Message::parse(reply).unwrap().header(); + assert_eq!(header.message_type, FourCc::new(*kind)); + assert_eq!(header.flags, MessageFlags::REPLY_TO_GUEST); + assert_eq!(header.guest_uuid, GuestUuid([0x5a; 16])); + assert_eq!(header.reply_id, 9); + reply.clone() + } + + fn levels(level: i64, keys: &[&str]) -> Value { + Value::Dictionary( + keys.iter() + .map(|k| ((*k).to_owned(), Value::Integer(level))) + .collect(), + ) + } + + fn integers(values: &[i64]) -> Value { + Value::Array(values.iter().map(|&v| Value::Integer(v)).collect()) + } + + /// `decs` lists each decoder, its profiles and its level, as the module doc of `lists` says. + #[test] + fn the_decoder_list_names_each_decoder_with_its_profiles_and_level() { + let mut decs = request(b"decs"); + decs.u32(names::VERSION, 6); + let reply = one_reply(&Host::new(decoders()).deliver(&decs.finish()), b"decs"); + let message = Message::parse(&reply).unwrap(); + assert_eq!(message.u32(names::VERSION).unwrap(), Some(6)); + let entry = |id: &str, name: &str, codec: &str, profiles: &[i64], level: i64| { + let details = profiles + .iter() + .map(|p| (p.to_string(), levels(level, &["VTMaxDecodeLevel"]))) + .collect(); + Value::dictionary([ + ("CMClassImplementationID", Value::string(id)), + ("CMClassImplementationName", Value::string(name)), + ("IsPreferredInternalPlugin", Value::Boolean(false)), + ("VTCodecType", Value::Array(vec![Value::string(codec)])), + ("VTRating", Value::Integer(400)), + ( + "VTDecoderCapabilities", + Value::dictionary([ + ("VTPerProfileDetails", Value::Dictionary(details)), + ("VTSupportedProfileArray", integers(profiles)), + ]), + ), + ]) + }; + let expected = Value::Array(vec![ + entry( + "reims-vgpu-video.videodecoder.avc", + "reims-vgpu-video Decoder - AVC", + "avc1", + &[66, 77, 100], + 52, + ), + entry( + "reims-vgpu-video.videodecoder.hevc", + "reims-vgpu-video Decoder - HEVC", + "hvc1", + &[1, 2, 3], + 153, + ), + ]); + assert_eq!( + message.property_list_bytes(names::DECODERS).unwrap(), + Some(encode(&expected).as_slice()) + ); + } + + /// A host with no decoder lists none. + #[test] + fn a_host_with_no_decoder_lists_none() { + let mut decs = request(b"decs"); + decs.u32(names::VERSION, 6); + let reply = one_reply(&Host::default().deliver(&decs.finish()), b"decs"); + let message = Message::parse(&reply).unwrap(); + assert_eq!( + message.property_list_bytes(names::DECODERS).unwrap(), + Some(encode(&Value::Array(Vec::new())).as_slice()) + ); + } + + /// `dcap` answers the capabilities of a codec the host decodes, and NULL for any other. + #[test] + fn a_decoders_capabilities_are_its_profiles_and_level() { + let host = Host::new(decoders()); + let mut dcap = request(b"dcap"); + dcap.s32(names::CODEC, FourCc::new(*b"hvc1").0.cast_signed()); + let reply = one_reply(&host.deliver(&dcap.finish()), b"dcap"); + let message = Message::parse(&reply).unwrap(); + let support = |p: &str| { + ( + p.to_owned(), + Value::dictionary([ + ("VTIsHardwareAccelerated", Value::Boolean(true)), + ("VTMaxDecodeLevel", Value::Integer(153)), + ("VTMaxPlaybackLevel", Value::Integer(153)), + ]), + ) + }; + let expected = Value::dictionary([ + ("VTIsHDRAllowedOnDevice", Value::Boolean(true)), + ( + "VTPerProfileSupport", + Value::Dictionary(vec![support("1"), support("2"), support("3")]), + ), + ("VTSupportedProfiles", integers(&[1, 2, 3])), + ]); + assert_eq!( + message + .property_list_bytes(names::DECODER_CAPABILITIES) + .unwrap(), + Some(encode(&expected).as_slice()) + ); + assert_eq!(message.u32(names::VERSION).unwrap(), Some(6)); + let mut vp9 = request(b"dcap"); + vp9.s32(names::CODEC, FourCc::new(*b"vp09").0.cast_signed()); + let reply = one_reply(&host.deliver(&vp9.finish()), b"dcap"); + let message = Message::parse(&reply).unwrap(); + assert_eq!( + message + .property_list_bytes(names::DECODER_CAPABILITIES) + .unwrap(), + Some(&[][..]) + ); + } + + /// `encs` and `meps` list nothing; `meps` from a guest older than protocol 6 is refused with + /// no reply. + #[test] + fn no_encoder_and_no_motion_estimation_are_listed() { + let host = Host::new(decoders()); + let mut encs = request(b"encs"); + encs.u32(names::VERSION, 6); + let reply = one_reply(&host.deliver(&encs.finish()), b"encs"); + let message = Message::parse(&reply).unwrap(); + let empty = encode(&Value::Array(Vec::new())); + assert_eq!( + message.property_list_bytes(names::ENCODERS).unwrap(), + Some(empty.as_slice()) + ); + let mut meps = request(b"meps"); + meps.u32(names::VERSION, 6); + let reply = one_reply(&host.deliver(&meps.finish()), b"meps"); + let message = Message::parse(&reply).unwrap(); + assert_eq!( + message + .property_list_bytes(names::MOTION_ESTIMATORS) + .unwrap(), + Some(empty.as_slice()) + ); + let mut old = request(b"meps"); + old.u32(names::VERSION, 5); + assert_eq!( + host.deliver(&old.finish()), + Answer::status(status::UNSUPPORTED_GUEST) + ); + } + + /// A create is refused in its reply's `,err`, as for a codec the host lacks, and its close + /// taken; a create with no codec type is malformed, with no reply. + #[test] + fn a_create_is_refused_in_its_reply_and_its_close_taken() { + let host = Host::new(decoders()); + for (kind, refused) in [ + (b"+dec", status::COULD_NOT_FIND_VIDEO_DECODER), + (b"+enc", status::COULD_NOT_FIND_VIDEO_ENCODER), + ] { + let mut create = request(kind); + create.s32(names::CODEC, FourCc::new(*b"avc1").0.cast_signed()); + create.u32(names::VERSION, 6); + let reply = one_reply(&host.deliver(&create.finish()), kind); + let message = Message::parse(&reply).unwrap(); + assert_eq!(message.s32(names::ERROR).unwrap(), Some(refused)); + assert_eq!(message.u32(names::VERSION).unwrap(), Some(6)); + assert!( + message + .property_list_bytes(names::HOST_INFO) + .unwrap() + .is_some() + ); + let mut bare = request(kind); + bare.u32(names::VERSION, 6); + assert_eq!( + host.deliver(&bare.finish()), + Answer::status(status::MALFORMED_MESSAGE) + ); + } + let mut mep = request(b"+mep"); + mep.u32(names::VERSION, 6); + let reply = one_reply(&host.deliver(&mep.finish()), b"+mep"); + let message = Message::parse(&reply).unwrap(); + assert_eq!( + message.s32(names::ERROR).unwrap(), + Some(status::MOTION_ESTIMATION_PROCESSOR_NOT_FOUND) + ); + for kind in [b"-dec", b"-enc", b"-mep", b"-uui", b"-all"] { + assert_eq!( + host.deliver(&request(kind).finish()), + Answer::status(status::NO_ERROR) + ); + } + } + + /// A JPEG request is answered with no JPEG hardware; a session's message, as for a UUID with + /// none; bytes with no message header, as malformed. + #[test] + fn jpeg_session_and_unreadable_messages() { + let host = Host::new(decoders()); + let reply = one_reply(&host.deliver(&request(b"jcap").finish()), b"jcap"); + let message = Message::parse(&reply).unwrap(); + assert_eq!( + message.s32(names::ERROR).unwrap(), + Some(status::NO_JPEG_HARDWARE) + ); + assert_eq!( + host.deliver(&request(b"dfrm").finish()), + Answer::status(status::SESSION_NOT_FOUND) + ); + assert_eq!( + host.deliver(&[0; 48]), + Answer::status(status::MALFORMED_MESSAGE) + ); + } +} diff --git a/crates/reims-vgpu-video/src/paravirt/lists.rs b/crates/reims-vgpu-video/src/paravirt/lists.rs new file mode 100644 index 000000000..3c81ecb6c --- /dev/null +++ b/crates/reims-vgpu-video/src/paravirt/lists.rs @@ -0,0 +1,215 @@ +//! The host's own answers: the codec lists (`decs`, `encs`, `meps`), a decoder's capabilities +//! (`dcap`) and a create's reply. +//! +//! The lists say what the guest may ask for. The decoder list holds one decoder for each codec the +//! host's video arm decodes, with the profiles and the level the arm answers: the guest's +//! VideoToolbox registers each as `paravirtualized:`, hardware-accelerated. The encoder and +//! motion-estimation lists hold none, as Apple's host answers where it has none. + +use crate::paravirt::message::{Message, MessageFlags, MessageWriter}; +use crate::paravirt::names; +use crate::paravirt::plist::Value; +use crate::paravirt::status::OsStatus; +use crate::paravirt::{Codec, Decoder, WireError}; + +/// The protocol version each list and create reply carries: 6, for the decoders, the encoders +/// (`kVTVESHostProtocolVersion`), motion estimation and the capabilities +/// (`kVTVDCapabilitesHostProtocolVersion`) alike. +pub(crate) const PROTOCOL_VERSION: u32 = 6; + +/// The rating each listed decoder carries. Apple's hardware decoders carry 400 (measured on macOS +/// 27, 26A434, 2026-10-24: `decs` lists `com.apple.videotoolbox.videodecoder.avd.avc` with +/// VTRating 400); the guest prefers the higher-rated of two decoders for a codec. +const DECODER_RATING: i64 = 400; + +/// What `,hin`'s `VTHostBuildVersion` says of this host. Apple's says the host's macOS build; the +/// guest only logs it. The value is ours. +const HOST_BUILD_VERSION: &str = concat!("reims-vgpu-video ", env!("CARGO_PKG_VERSION")); + +/// The reply to `request`: its type, UUID and reply identifier, flagged as a reply to the guest. +pub(crate) fn reply(request: &Message<'_>) -> MessageWriter { + MessageWriter::reply_to(&request.header(), MessageFlags::REPLY_TO_GUEST) +} + +/// The `CMClassImplementationID` of this host's decoder for `codec`, which the guest registers as +/// `paravirtualized:` and sends back as `,cid` when it opens one. The IDs and names are ours. +fn decoder_id(codec: Codec) -> &'static str { + match codec { + Codec::H264 => "reims-vgpu-video.videodecoder.avc", + Codec::Hevc => "reims-vgpu-video.videodecoder.hevc", + } +} + +fn decoder_name(codec: Codec) -> &'static str { + match codec { + Codec::H264 => "reims-vgpu-video Decoder - AVC", + Codec::Hevc => "reims-vgpu-video Decoder - HEVC", + } +} + +fn fourcc_string(codec: Codec) -> Value { + Value::String(String::from_utf8_lossy(&codec.fourcc().to_be_bytes()).into_owned()) +} + +fn profiles(decoder: &Decoder) -> Value { + Value::Array( + decoder + .profiles + .iter() + .map(|&p| Value::Integer(i64::from(p))) + .collect(), + ) +} + +/// One entry of the decoder list, in the keys and shapes Apple's hardware decoders' entries have +/// (measured on macOS 27, 26A434, 2026-10-24: VTCodecType an array of FourCC strings, +/// VTPerProfileDetails keyed by the profile as a decimal string, under VTDecoderCapabilities). +fn decoder_entry(decoder: &Decoder) -> Value { + let details = decoder + .profiles + .iter() + .map(|p| { + let detail = Value::dictionary([( + "VTMaxDecodeLevel", + Value::Integer(i64::from(decoder.max_level)), + )]); + (p.to_string(), detail) + }) + .collect(); + Value::dictionary([ + ( + "CMClassImplementationID", + Value::string(decoder_id(decoder.codec)), + ), + ( + "CMClassImplementationName", + Value::string(decoder_name(decoder.codec)), + ), + ("IsPreferredInternalPlugin", Value::Boolean(false)), + ( + "VTCodecType", + Value::Array(vec![fourcc_string(decoder.codec)]), + ), + ("VTRating", Value::Integer(DECODER_RATING)), + ( + "VTDecoderCapabilities", + Value::dictionary([ + ("VTPerProfileDetails", Value::Dictionary(details)), + ("VTSupportedProfileArray", profiles(decoder)), + ]), + ), + ]) +} + +/// `decs`: the decoders, then the version. The request's `,ver` is read but not checked. +pub(crate) fn decoder_list( + request: &Message<'_>, + decoders: &[Decoder], +) -> Result, WireError> { + request.u32(names::VERSION)?; + let entries = decoders.iter().map(decoder_entry).collect(); + let mut reply = reply(request); + reply.property_list(names::DECODERS, Some(&Value::Array(entries))); + reply.u32(names::VERSION, PROTOCOL_VERSION); + Ok(reply.finish()) +} + +/// A decoder's capabilities as `dcap` answers them, in the shape Apple's host answers for `avc1` +/// (measured on macOS 27, 26A434, 2026-10-24): per profile, that it is hardware-accelerated and +/// its highest decode and playback level, then the profiles. VTIsHDRAllowedOnDevice is true, as +/// Apple's host answers on a device that allows HDR: the arm decodes an HDR stream as any other, +/// and the profiles say which it takes. +fn capabilities(decoder: &Decoder) -> Value { + let level = Value::Integer(i64::from(decoder.max_level)); + let per_profile = decoder + .profiles + .iter() + .map(|p| { + let support = Value::dictionary([ + ("VTIsHardwareAccelerated", Value::Boolean(true)), + ("VTMaxDecodeLevel", level.clone()), + ("VTMaxPlaybackLevel", level.clone()), + ]); + (p.to_string(), support) + }) + .collect(); + Value::dictionary([ + ("VTIsHDRAllowedOnDevice", Value::Boolean(true)), + ("VTPerProfileSupport", Value::Dictionary(per_profile)), + ("VTSupportedProfiles", profiles(decoder)), + ]) +} + +/// `dcap`: the capabilities of the codec `,cod` (`=s32`) names, NULL for one the host does not +/// decode, then the version. +pub(crate) fn decoder_capabilities( + request: &Message<'_>, + decoders: &[Decoder], +) -> Result, WireError> { + let codec = request.s32(names::CODEC)?.unwrap_or(0).cast_unsigned(); + let found = decoders.iter().find(|d| d.codec.fourcc().0 == codec); + let mut reply = reply(request); + reply.property_list( + names::DECODER_CAPABILITIES, + found.map(capabilities).as_ref(), + ); + reply.u32(names::VERSION, PROTOCOL_VERSION); + Ok(reply.finish()) +} + +/// `encs`: no encoder, then the version. The request's `,ver` is read but not checked. +pub(crate) fn encoder_list(request: &Message<'_>) -> Result, WireError> { + request.u32(names::VERSION)?; + let mut reply = reply(request); + reply.property_list(names::ENCODERS, Some(&Value::Array(Vec::new()))); + reply.u32(names::VERSION, PROTOCOL_VERSION); + Ok(reply.finish()) +} + +/// What `meps` answers: a reply, or a status and no reply. +pub(crate) enum MotionEstimationAnswer { + /// The reply to send. + Reply(Vec), + /// The status to answer, with nothing sent. + Refused(OsStatus), +} + +/// `meps`: a guest older than protocol 6 is refused with no reply, any other told of no +/// processor, then the version. +pub(crate) fn motion_estimation_list( + request: &Message<'_>, +) -> Result { + let version = request.u32(names::VERSION)?.unwrap_or(0); + if version < PROTOCOL_VERSION { + return Ok(MotionEstimationAnswer::Refused( + crate::paravirt::status::UNSUPPORTED_GUEST, + )); + } + let mut reply = reply(request); + reply.property_list(names::MOTION_ESTIMATORS, Some(&Value::Array(Vec::new()))); + reply.u32(names::VERSION, PROTOCOL_VERSION); + Ok(MotionEstimationAnswer::Reply(reply.finish())) +} + +/// A create's reply, with `status` in its `,err`, then the version and the host's info, as Apple's +/// host answers a create it makes no codec for: the guest fails its create on the `,err`. +pub(crate) fn create_reply(request: &Message<'_>, status: OsStatus) -> Vec { + let mut reply = reply(request); + reply.s32(names::ERROR, status); + reply.u32(names::VERSION, PROTOCOL_VERSION); + reply.property_list( + names::HOST_INFO, + Some(&Value::dictionary([( + "VTHostBuildVersion", + Value::string(HOST_BUILD_VERSION), + )])), + ); + reply.finish() +} + +/// A JPEG request's reply: `,err` alone, as the host has no JPEG engine. +pub(crate) fn jpeg_reply(request: &Message<'_>, status: OsStatus) -> Vec { + let mut reply = reply(request); + reply.s32(names::ERROR, status); + reply.finish() +} diff --git a/crates/reims-vgpu-video/src/paravirt/message.rs b/crates/reims-vgpu-video/src/paravirt/message.rs new file mode 100644 index 000000000..0266ff058 --- /dev/null +++ b/crates/reims-vgpu-video/src/paravirt/message.rs @@ -0,0 +1,950 @@ +//! `vtpv` messages: the 48-byte header atom and the `para` parameter atoms +//! that follow it as its siblings. +//! +//! A message may start with other atoms, which the scanners skip. A +//! fragmented message is several messages one after another, each but the +//! last flagged [`MessageFlags::MORE_FRAGMENTS`]; the fragment-aware +//! readers ([`Message::data`], [`Message::sample_buffer`]) walk them. + +use crate::core::fourcc::FourCc; +use crate::paravirt::WireError; +use crate::paravirt::atom::{AtomWriter, read_u32, read_u64}; +use crate::paravirt::plist; + +/// The header atom's type. +pub const MESSAGE_ATOM: FourCc = FourCc::new(*b"vtpv"); +/// A parameter atom's type. +pub const PARAMETER_ATOM: FourCc = FourCc::new(*b"para"); +/// The header atom's size: its own header, type, flags, UUID, reply +/// identifier and 8 reserved bytes. +pub const HEADER_SIZE: usize = 48; +/// A parameter atom's header: atom header, key and value type. +pub const PARAMETER_HEADER_SIZE: usize = 16; + +/// A message's flags (the constant names here are ours, by direction). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)] +pub struct MessageFlags(pub u32); + +impl MessageFlags { + /// No flags: a notification either way. + pub const NONE: Self = Self(0); + /// A guest request that waits for the host's reply. + pub const GUEST_EXPECTS_REPLY: Self = Self(0x1); + /// A host request that waits for the guest's reply. + pub const HOST_EXPECTS_REPLY: Self = Self(0x2); + /// The host's reply to a guest request. + pub const REPLY_TO_GUEST: Self = Self(0x4); + /// The guest's reply to a host request. + pub const REPLY_TO_HOST: Self = Self(0x8); + /// Another fragment of the same message follows. + pub const MORE_FRAGMENTS: Self = Self(0x10); + + /// Whether every bit of `other` is set. + pub const fn contains(self, other: Self) -> bool { + self.0 & other.0 == other.0 + } + + /// These flags with the bits of `mask` replaced by those of `flags`, as + /// VTParavirtualizationMessageChangeMessageFlags computes them. + pub const fn changed(self, flags: Self, mask: Self) -> Self { + Self((self.0 & !mask.0) | (flags.0 & mask.0)) + } +} + +/// The UUID that names a guest session, as its 16 bytes. The host's own +/// list requests (`decs`, `dcap`, ...) carry the zero UUID. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default, PartialOrd, Ord)] +pub struct GuestUuid(pub [u8; 16]); + +impl GuestUuid { + /// The zero UUID, which a NULL UUID is written as. + pub const ZERO: Self = Self([0; 16]); +} + +/// A `CMTime` as the wire carries it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct MediaTime { + /// The numerator. + pub value: i64, + /// The denominator; a valid time has a positive one. + pub timescale: i32, + /// `kCMTimeFlags_*`: bit 0 is valid. + pub flags: u32, + /// The epoch. + pub epoch: i64, +} + +impl MediaTime { + /// `kCMTimeInvalid`: all zero. + pub const INVALID: Self = Self { + value: 0, + timescale: 0, + flags: 0, + epoch: 0, + }; + /// `kCMTimeFlags_Valid`. + pub const FLAG_VALID: u32 = 1; + + /// Whether the valid flag is set. + pub const fn is_valid(self) -> bool { + self.flags & Self::FLAG_VALID != 0 + } + + /// The time from its native (little-endian, guest x86_64) 24-byte form, + /// as sample buffer serializations write it. + pub fn from_native(bytes: &[u8]) -> Option { + Some(Self { + value: i64::from_le_bytes(bytes.get(0..8)?.try_into().ok()?), + timescale: i32::from_le_bytes(bytes.get(8..12)?.try_into().ok()?), + flags: u32::from_le_bytes(bytes.get(12..16)?.try_into().ok()?), + epoch: i64::from_le_bytes(bytes.get(16..24)?.try_into().ok()?), + }) + } + + /// The native 24-byte form. + pub fn to_native(self) -> [u8; 24] { + let mut bytes = [0; 24]; + bytes[0..8].copy_from_slice(&self.value.to_le_bytes()); + bytes[8..12].copy_from_slice(&self.timescale.to_le_bytes()); + bytes[12..16].copy_from_slice(&self.flags.to_le_bytes()); + bytes[16..24].copy_from_slice(&self.epoch.to_le_bytes()); + bytes + } +} + +/// A parameter's value type, the FourCC after its key +/// (each appender). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum ValueType { + /// `=u32`: a big-endian u32. + U32, + /// `=s32`: a big-endian i32. + S32, + /// `=s64`: a big-endian i64. + S64, + /// `=tim`: a big-endian CMTime. + Time, + /// `=wxh`: CMVideoDimensions, two big-endian i32. + Dimensions, + /// `=32p`: VTInt32Point, two big-endian i32. + Point, + /// `=32s`: VTInt32Size, two big-endian i32. + Size, + /// `=dat`: raw bytes, fragmented across messages when large. + Data, + /// `=pls`: a property list; empty means NULL. + PropertyList, + /// `=uui`: a UUID's 16 bytes. + Uuid, + /// `=ui+`: UUIDs, 16 bytes each. + UuidArray, + /// `=tc+`: FigTagCollections. + TagCollections, + /// `=fds`: a big-endian QuickTime ImageDescription. + FormatDescription, + /// `=sbf`: a sample buffer serialization, fragmented across messages + /// when large. + SampleBuffer, +} + +impl ValueType { + /// The FourCC the wire spells it as. + pub const fn fourcc(self) -> FourCc { + FourCc::new(match self { + Self::U32 => *b"=u32", + Self::S32 => *b"=s32", + Self::S64 => *b"=s64", + Self::Time => *b"=tim", + Self::Dimensions => *b"=wxh", + Self::Point => *b"=32p", + Self::Size => *b"=32s", + Self::Data => *b"=dat", + Self::PropertyList => *b"=pls", + Self::Uuid => *b"=uui", + Self::UuidArray => *b"=ui+", + Self::TagCollections => *b"=tc+", + Self::FormatDescription => *b"=fds", + Self::SampleBuffer => *b"=sbf", + }) + } +} + +/// The parsed header of a message. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct MessageHeader { + /// The message type. + pub message_type: FourCc, + /// The flags. + pub flags: MessageFlags, + /// The session the message belongs to. + pub guest_uuid: GuestUuid, + /// The reply identifier: the requester's for a request that expects a + /// reply and for its reply, 0 otherwise. + pub reply_id: u64, +} + +/// Finds the first `vtpv` atom at or after `start`, as +/// `vtpvScanForTopLevelBoxWithType` does: a size under 8 or past the end is +/// malformed, a `vtpv` atom under 48 bytes is malformed, and no `vtpv` atom +/// at all is malformed. +/// +/// Returns the atom's offset in `bytes`. +pub fn find_header(bytes: &[u8], start: usize) -> Result { + let region = bytes + .get(start..) + .ok_or(WireError::Malformed("no message header"))?; + let mut offset = 0usize; + while offset + 8 <= region.len() { + let size = atom_size(region, offset)?; + let kind = read_u32(region, offset + 4).ok_or(WireError::Malformed("atom type"))?; + if FourCc(kind) == MESSAGE_ATOM { + if size < HEADER_SIZE { + return Err(WireError::Malformed("short message header")); + } + return Ok(start + offset); + } + offset += size; + } + Err(WireError::Malformed("no message header")) +} + +/// The size of the atom at `offset` in `region`, checked as both scanners +/// check it. +fn atom_size(region: &[u8], offset: usize) -> Result { + let size = read_u32(region, offset).ok_or(WireError::Malformed("atom size"))?; + let size = usize::try_from(size).map_err(|_| WireError::Malformed("atom size"))?; + if size < 8 { + return Err(WireError::Malformed("atom size")); + } + if region.len() - offset < size { + return Err(WireError::Malformed("atom past the end")); + } + Ok(size) +} + +/// Reads the header of the first `vtpv` atom at or after `start`. +pub fn read_header(bytes: &[u8], start: usize) -> Result { + let at = find_header(bytes, start)?; + let field = |offset: usize| read_u32(bytes, at + offset); + let message_type = field(8).ok_or(WireError::Malformed("message type"))?; + let flags = field(12).ok_or(WireError::Malformed("message flags"))?; + let uuid = bytes + .get(at + 16..at + 32) + .and_then(|uuid| <[u8; 16]>::try_from(uuid).ok()) + .ok_or(WireError::Malformed("message UUID"))?; + let reply_id = read_u64(bytes, at + 32).ok_or(WireError::Malformed("reply identifier"))?; + Ok(MessageHeader { + message_type: FourCc(message_type), + flags: MessageFlags(flags), + guest_uuid: GuestUuid(uuid), + reply_id, + }) +} + +/// A message read from guest bytes: its header and its parameters. +/// +/// The getters follow Apple's: a parameter that is absent reads as `None` +/// (Apple's default: 0, NULL or `kCMTimeInvalid`), one whose key matches +/// but whose value type differs is malformed, and one whose length does +/// not fit its type is malformed. +#[derive(Clone, Copy, Debug)] +pub struct Message<'a> { + bytes: &'a [u8], + header: MessageHeader, +} + +impl<'a> Message<'a> { + /// Reads the header; the parameters are read on demand. + pub fn parse(bytes: &'a [u8]) -> Result { + let header = read_header(bytes, 0)?; + Ok(Self { bytes, header }) + } + + /// The header. + pub fn header(&self) -> MessageHeader { + self.header + } + + /// The whole message, every fragment included. + pub fn bytes(&self) -> &'a [u8] { + self.bytes + } + + /// The first parameter atom with `key`, from `start` on, as + /// `vtpvScanForParameterBoxWithType` finds it. Returns the atom's + /// offset in the message and its bytes. + fn find( + &self, + start: usize, + key: FourCc, + value_type: ValueType, + ) -> Result, WireError> { + let Some(region) = self.bytes.get(start..) else { + return Ok(None); + }; + let mut offset = 0usize; + while offset + PARAMETER_HEADER_SIZE <= region.len() { + let size = atom_size(region, offset)?; + let kind = read_u32(region, offset + 4).ok_or(WireError::Malformed("atom type"))?; + if FourCc(kind) == PARAMETER_ATOM + && read_u32(region, offset + 8).map(FourCc) == Some(key) + { + // The key and type are read from the next 8 bytes whatever + // the atom's size, so a short atom is caught by the + // getter's length check, as in Apple's. + if read_u32(region, offset + 12).map(FourCc) != Some(value_type.fourcc()) { + return Err(WireError::Malformed("parameter value type")); + } + let atom = region + .get(offset..offset + size) + .ok_or(WireError::Malformed("atom past the end"))?; + return Ok(Some((start + offset, atom))); + } + offset += size; + } + Ok(None) + } + + /// The payload of the parameter `key` of type `value_type`, which must + /// be `length` bytes when present. + fn fixed( + &self, + key: FourCc, + value_type: ValueType, + length: usize, + ) -> Result, WireError> { + match self.find(0, key, value_type)? { + None => Ok(None), + Some((_, atom)) if atom.len() == PARAMETER_HEADER_SIZE + length => { + Ok(atom.get(PARAMETER_HEADER_SIZE..)) + } + Some(_) => Err(WireError::Malformed("parameter length")), + } + } + + /// Whether the message has the parameter, with a payload + /// (`VTParavirtualizationMessageContainsParameter`). + pub fn contains(&self, key: FourCc, value_type: ValueType) -> bool { + matches!(self.find(0, key, value_type), Ok(Some(_))) + } + + /// A `=u32` parameter. + pub fn u32(&self, key: FourCc) -> Result, WireError> { + Ok(self + .fixed(key, ValueType::U32, 4)? + .and_then(|payload| read_u32(payload, 0))) + } + + /// A `=s32` parameter. + pub fn s32(&self, key: FourCc) -> Result, WireError> { + Ok(self + .fixed(key, ValueType::S32, 4)? + .and_then(|payload| read_u32(payload, 0)) + .map(u32::cast_signed)) + } + + /// A `=s64` parameter. + pub fn s64(&self, key: FourCc) -> Result, WireError> { + Ok(self + .fixed(key, ValueType::S64, 8)? + .and_then(|payload| read_u64(payload, 0)) + .map(u64::cast_signed)) + } + + /// A `=tim` parameter. + pub fn time(&self, key: FourCc) -> Result, WireError> { + Ok(self.fixed(key, ValueType::Time, 24)?.and_then(|payload| { + Some(MediaTime { + value: read_u64(payload, 0)?.cast_signed(), + timescale: read_u32(payload, 8)?.cast_signed(), + flags: read_u32(payload, 12)?, + epoch: read_u64(payload, 16)?.cast_signed(), + }) + })) + } + + /// A pair of big-endian i32: `=wxh`, `=32p` or `=32s`. + pub fn i32_pair( + &self, + key: FourCc, + value_type: ValueType, + ) -> Result, WireError> { + Ok(self.fixed(key, value_type, 8)?.and_then(|payload| { + Some(( + read_u32(payload, 0)?.cast_signed(), + read_u32(payload, 4)?.cast_signed(), + )) + })) + } + + /// A `=uui` parameter. + pub fn uuid(&self, key: FourCc) -> Result, WireError> { + Ok(self + .fixed(key, ValueType::Uuid, 16)? + .and_then(|payload| <[u8; 16]>::try_from(payload).ok()) + .map(GuestUuid)) + } + + /// A `=ui+` parameter: whole 16-byte UUIDs, none left over. + pub fn uuid_array(&self, key: FourCc) -> Result>, WireError> { + let Some((_, atom)) = self.find(0, key, ValueType::UuidArray)? else { + return Ok(None); + }; + let payload = atom + .get(PARAMETER_HEADER_SIZE..) + .ok_or(WireError::Malformed("UUID array length"))?; + if payload.len() % 16 != 0 { + return Err(WireError::Malformed("UUID array length")); + } + Ok(Some( + payload + .as_chunks::<16>() + .0 + .iter() + .map(|uuid| GuestUuid(*uuid)) + .collect(), + )) + } + + /// A `=pls` parameter's bytes as written, a binary property list or + /// none for NULL. + pub fn property_list_bytes(&self, key: FourCc) -> Result, WireError> { + Ok(self + .find(0, key, ValueType::PropertyList)? + .and_then(|(_, atom)| atom.get(PARAMETER_HEADER_SIZE..))) + } + + /// A `=fds` parameter's ImageDescription bytes, at least the 86-byte + /// header. + pub fn image_description(&self, key: FourCc) -> Result, WireError> { + let Some((_, atom)) = self.find(0, key, ValueType::FormatDescription)? else { + return Ok(None); + }; + atom.get(PARAMETER_HEADER_SIZE..) + .filter(|payload| payload.len() >= 86) + .map(Some) + .ok_or(WireError::Malformed("short image description")) + } + + /// A `=dat` parameter, gathered from every fragment. + pub fn data(&self, key: FourCc) -> Result>, WireError> { + self.fragmented(key, ValueType::Data) + } + + /// A `=sbf` parameter's serialization, gathered from every fragment. + pub fn sample_buffer(&self, key: FourCc) -> Result>, WireError> { + self.fragmented(key, ValueType::SampleBuffer) + } + + /// Walks the fragments: each fragment's flags come from the first + /// header at or after where the walk stands, its piece is the first + /// parameter with `key` from there on, and the walk goes on past that + /// parameter while the flags say more fragments follow. A fragment + /// without the parameter makes the whole value NULL; an empty piece is + /// malformed. + /// + /// The header found for one fragment is still the first at or after + /// the walk's place until the walk passes it, so it is looked for again + /// only then: each header search starts past the last header found, + /// and the walk stays linear in the message. Looking from each place + /// again, as Apple's reader does, is quadratic in the fragments a + /// message holds before its next header. + fn fragmented(&self, key: FourCc, value_type: ValueType) -> Result>, WireError> { + let mut value = Vec::new(); + let mut start = 0usize; + let mut header: Option<(usize, MessageFlags)> = None; + loop { + let flags = match header { + Some((at, flags)) if at >= start => flags, + _ => { + let at = find_header(self.bytes, start)?; + let flags = read_header(self.bytes, at)?.flags; + header = Some((at, flags)); + flags + } + }; + let Some((offset, atom)) = self.find(start, key, value_type)? else { + return Ok(None); + }; + let piece = atom + .get(PARAMETER_HEADER_SIZE..) + .filter(|piece| !piece.is_empty()) + .ok_or(WireError::Malformed("empty fragment"))?; + value.extend_from_slice(piece); + start = offset + atom.len(); + if !flags.contains(MessageFlags::MORE_FRAGMENTS) { + return Ok(Some(value)); + } + } + } +} + +/// Builds a message: the header atom, then parameters in the order they +/// are appended. +#[derive(Debug)] +pub struct MessageWriter { + writer: AtomWriter, +} + +impl MessageWriter { + /// A message with this header; `None` writes the zero UUID. + pub fn new( + message_type: FourCc, + flags: MessageFlags, + guest_uuid: Option, + reply_id: u64, + ) -> Self { + let mut writer = AtomWriter::new(); + writer + .begin(MESSAGE_ATOM) + .append(&message_type.to_be_bytes()) + .append(&flags.0.to_be_bytes()) + .append(&guest_uuid.unwrap_or(GuestUuid::ZERO).0) + .append(&reply_id.to_be_bytes()) + .append(&[0; 8]) + .end(); + Self { writer } + } + + /// The reply to `request`: its type, UUID and reply identifier with + /// `flags`. + pub fn reply_to(request: &MessageHeader, flags: MessageFlags) -> Self { + Self::new( + request.message_type, + flags, + Some(request.guest_uuid), + request.reply_id, + ) + } + + /// The bytes written so far. + pub fn len(&self) -> usize { + self.writer.len() + } + + /// Never true: the header is always there. + pub fn is_empty(&self) -> bool { + self.writer.is_empty() + } + + fn parameter(&mut self, key: FourCc, value_type: ValueType, payload: &[u8]) -> &mut Self { + self.writer + .begin(PARAMETER_ATOM) + .append(&key.to_be_bytes()) + .append(&value_type.fourcc().to_be_bytes()) + .append(payload) + .end(); + self + } + + /// Appends a `=u32` parameter. + pub fn u32(&mut self, key: FourCc, value: u32) -> &mut Self { + self.parameter(key, ValueType::U32, &value.to_be_bytes()) + } + + /// Appends a `=s32` parameter. + pub fn s32(&mut self, key: FourCc, value: i32) -> &mut Self { + self.parameter(key, ValueType::S32, &value.to_be_bytes()) + } + + /// Appends a `=s64` parameter. + pub fn s64(&mut self, key: FourCc, value: i64) -> &mut Self { + self.parameter(key, ValueType::S64, &value.to_be_bytes()) + } + + /// Appends a `=tim` parameter. + pub fn time(&mut self, key: FourCc, time: MediaTime) -> &mut Self { + let mut payload = [0; 24]; + payload[0..8].copy_from_slice(&time.value.to_be_bytes()); + payload[8..12].copy_from_slice(&time.timescale.to_be_bytes()); + payload[12..16].copy_from_slice(&time.flags.to_be_bytes()); + payload[16..24].copy_from_slice(&time.epoch.to_be_bytes()); + self.parameter(key, ValueType::Time, &payload) + } + + /// Appends a pair of big-endian i32: `=wxh`, `=32p` or `=32s`. + pub fn i32_pair(&mut self, key: FourCc, value_type: ValueType, pair: (i32, i32)) -> &mut Self { + let mut payload = [0; 8]; + payload[0..4].copy_from_slice(&pair.0.to_be_bytes()); + payload[4..8].copy_from_slice(&pair.1.to_be_bytes()); + self.parameter(key, value_type, &payload) + } + + /// Appends a `=uui` parameter. + pub fn uuid(&mut self, key: FourCc, uuid: GuestUuid) -> &mut Self { + self.parameter(key, ValueType::Uuid, &uuid.0) + } + + /// Appends a `=ui+` parameter. + pub fn uuid_array(&mut self, key: FourCc, uuids: &[GuestUuid]) -> &mut Self { + let payload: Vec = uuids.iter().flat_map(|uuid| uuid.0).collect(); + self.parameter(key, ValueType::UuidArray, &payload) + } + + /// Appends a `=pls` parameter, a binary property list ([`plist`]): `None` writes NULL, an + /// empty payload. + pub fn property_list(&mut self, key: FourCc, value: Option<&plist::Value>) -> &mut Self { + let payload = value.map(plist::encode).unwrap_or_default(); + self.parameter(key, ValueType::PropertyList, &payload) + } + + /// Appends a `=dat` parameter whole. + pub fn data(&mut self, key: FourCc, data: &[u8]) -> &mut Self { + self.parameter(key, ValueType::Data, data) + } + + /// Appends a `=fds` parameter from ImageDescription bytes. + pub fn image_description(&mut self, key: FourCc, description: &[u8]) -> &mut Self { + self.parameter(key, ValueType::FormatDescription, description) + } + + /// Appends as much of `serialization` as fits a message of `limit` + /// bytes as a `=sbf` parameter, and returns the rest, as + /// `…AppendCMSampleBufferRemainderDataWithLimitAndCopyRemainingData` + /// does: nothing is appended when fewer than 17 bytes are left. + pub fn sample_buffer_with_limit<'s>( + &mut self, + key: FourCc, + limit: usize, + serialization: &'s [u8], + ) -> &'s [u8] { + let current = self.len(); + if current + 17 > limit { + return serialization; + } + let room = limit - current - PARAMETER_HEADER_SIZE; + let chunk = room.min(serialization.len()); + let (piece, rest) = serialization.split_at(chunk); + self.parameter(key, ValueType::SampleBuffer, piece); + rest + } + + /// Replaces the header's flags under `mask`. + pub fn change_flags(&mut self, flags: MessageFlags, mask: MessageFlags) -> &mut Self { + if let Some(field) = self.writer.bytes_mut().get_mut(12..16) + && let Ok(current) = <[u8; 4]>::try_from(&*field) + { + let changed = MessageFlags(u32::from_be_bytes(current)).changed(flags, mask); + field.copy_from_slice(&changed.0.to_be_bytes()); + } + self + } + + /// Replaces the header's reply identifier. + pub fn set_reply_id(&mut self, reply_id: u64) -> &mut Self { + if let Some(field) = self.writer.bytes_mut().get_mut(32..40) { + field.copy_from_slice(&reply_id.to_be_bytes()); + } + self + } + + /// The message's bytes. + pub fn finish(self) -> Vec { + self.writer.finish() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const KEY: FourCc = FourCc::new(*b",key"); + + /// A message written by hand: `+dec`, flags 1, UUID 0x11.., reply 7, + /// then `,cod` as `=s32` 'avc1' and `,ver` as `=u32` 6. + fn hand_written_create() -> Vec { + let mut bytes = vec![0, 0, 0, 48]; + bytes.extend_from_slice(b"vtpv+dec"); + bytes.extend_from_slice(&[0, 0, 0, 1]); + bytes.extend_from_slice(&[0x11; 16]); + bytes.extend_from_slice(&[0, 0, 0, 0, 0, 0, 0, 7]); + bytes.extend_from_slice(&[0; 8]); + bytes.extend_from_slice(&[0, 0, 0, 20]); + bytes.extend_from_slice(b"para,cod=s32avc1"); + bytes.extend_from_slice(&[0, 0, 0, 20]); + bytes.extend_from_slice(b"para,ver=u32"); + bytes.extend_from_slice(&[0, 0, 0, 6]); + bytes + } + + #[test] + fn a_hand_written_message_reads_back() -> Result<(), WireError> { + let bytes = hand_written_create(); + let message = Message::parse(&bytes)?; + assert_eq!( + message.header(), + MessageHeader { + message_type: FourCc::new(*b"+dec"), + flags: MessageFlags::GUEST_EXPECTS_REPLY, + guest_uuid: GuestUuid([0x11; 16]), + reply_id: 7, + } + ); + assert_eq!( + message.s32(FourCc::new(*b",cod"))?, + Some(i32::from_be_bytes(*b"avc1")) + ); + assert_eq!(message.u32(FourCc::new(*b",ver"))?, Some(6)); + assert_eq!(message.u32(FourCc::new(*b",gin"))?, None); + Ok(()) + } + + #[test] + fn the_writer_writes_the_hand_written_bytes() { + let mut writer = MessageWriter::new( + FourCc::new(*b"+dec"), + MessageFlags::GUEST_EXPECTS_REPLY, + Some(GuestUuid([0x11; 16])), + 7, + ); + writer + .s32(FourCc::new(*b",cod"), i32::from_be_bytes(*b"avc1")) + .u32(FourCc::new(*b",ver"), 6); + assert_eq!(writer.finish(), hand_written_create()); + } + + #[test] + fn a_key_with_another_value_type_is_malformed() -> Result<(), WireError> { + // Measured on the M3 Max (macOS 27, 26A434): `dcap` with `,cod` as `=u32` + // answers -19093 and no reply; the host reads it as `=s32`. + let bytes = hand_written_create(); + let message = Message::parse(&bytes)?; + assert_eq!( + message.u32(FourCc::new(*b",cod")), + Err(WireError::Malformed("parameter value type")) + ); + Ok(()) + } + + #[test] + fn a_parameter_of_the_wrong_length_is_malformed() -> Result<(), WireError> { + let mut writer = MessageWriter::new(FourCc::new(*b"test"), MessageFlags::NONE, None, 0); + writer.parameter(KEY, ValueType::U32, &[0, 0, 0, 0, 0]); + let bytes = writer.finish(); + let message = Message::parse(&bytes)?; + assert_eq!( + message.u32(KEY), + Err(WireError::Malformed("parameter length")) + ); + Ok(()) + } + + #[test] + fn leading_atoms_are_skipped() -> Result<(), WireError> { + let mut bytes = vec![0, 0, 0, 0x30]; + bytes.extend_from_slice(b"subs"); + bytes.extend_from_slice(&[0; 40]); + bytes.extend_from_slice(&hand_written_create()); + let message = Message::parse(&bytes)?; + assert_eq!(message.header().message_type, FourCc::new(*b"+dec")); + assert_eq!(message.u32(FourCc::new(*b",ver"))?, Some(6)); + Ok(()) + } + + #[test] + fn a_short_header_atom_is_malformed() { + let mut bytes = vec![0, 0, 0, 40]; + bytes.extend_from_slice(b"vtpv"); + bytes.extend_from_slice(&[0; 32]); + assert_eq!( + Message::parse(&bytes).err(), + Some(WireError::Malformed("short message header")) + ); + } + + #[test] + fn bytes_without_a_header_are_malformed() { + assert_eq!( + Message::parse(&[0, 0, 0, 8, b'a', b'b', b'c', b'd']).err(), + Some(WireError::Malformed("no message header")) + ); + assert_eq!( + Message::parse(&[]).err(), + Some(WireError::Malformed("no message header")) + ); + } + + #[test] + fn every_scalar_type_round_trips() -> Result<(), WireError> { + let time = MediaTime { + value: -3, + timescale: 600, + flags: MediaTime::FLAG_VALID, + epoch: 9, + }; + let uuid = GuestUuid([7; 16]); + let mut writer = MessageWriter::new(FourCc::new(*b"test"), MessageFlags::NONE, None, 0); + writer + .s64(FourCc::new(*b",s64"), -5) + .time(FourCc::new(*b",tim"), time) + .i32_pair(FourCc::new(*b",wxh"), ValueType::Dimensions, (1920, 1080)) + .uuid(FourCc::new(*b",uui"), uuid) + .uuid_array(FourCc::new(*b",ui+"), &[uuid, GuestUuid::ZERO]); + let bytes = writer.finish(); + let message = Message::parse(&bytes)?; + assert_eq!(message.s64(FourCc::new(*b",s64"))?, Some(-5)); + assert_eq!(message.time(FourCc::new(*b",tim"))?, Some(time)); + assert_eq!( + message.i32_pair(FourCc::new(*b",wxh"), ValueType::Dimensions)?, + Some((1920, 1080)) + ); + assert_eq!(message.uuid(FourCc::new(*b",uui"))?, Some(uuid)); + assert_eq!( + message.uuid_array(FourCc::new(*b",ui+"))?, + Some(vec![uuid, GuestUuid::ZERO]) + ); + Ok(()) + } + + #[test] + fn a_time_is_big_endian_on_the_wire() { + let mut writer = MessageWriter::new(FourCc::new(*b"test"), MessageFlags::NONE, None, 0); + writer.time( + KEY, + MediaTime { + value: 1, + timescale: 2, + flags: 3, + epoch: 4, + }, + ); + let bytes = writer.finish(); + assert_eq!( + &bytes[HEADER_SIZE + 16..], + &[ + 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4 + ] + ); + } + + #[test] + fn a_uuid_array_with_a_partial_uuid_is_malformed() -> Result<(), WireError> { + let mut writer = MessageWriter::new(FourCc::new(*b"test"), MessageFlags::NONE, None, 0); + writer.parameter(KEY, ValueType::UuidArray, &[0; 17]); + let bytes = writer.finish(); + let message = Message::parse(&bytes)?; + assert_eq!( + message.uuid_array(KEY), + Err(WireError::Malformed("UUID array length")) + ); + Ok(()) + } + + #[test] + fn a_reply_carries_its_requests_identity() { + let request = MessageHeader { + message_type: FourCc::new(*b"dfrm"), + flags: MessageFlags::GUEST_EXPECTS_REPLY, + guest_uuid: GuestUuid([3; 16]), + reply_id: 0x0102_0304_0506_0708, + }; + let bytes = MessageWriter::reply_to(&request, MessageFlags::REPLY_TO_GUEST).finish(); + assert_eq!( + read_header(&bytes, 0), + Ok(MessageHeader { + flags: MessageFlags::REPLY_TO_GUEST, + ..request + }) + ); + } + + /// Splits `serialization` into fragments as the guest decoder does: the + /// first message carries `,frm` and then as much as fits, each full one + /// is re-flagged "more fragments" with "expects reply" cleared, and the + /// last keeps "expects reply". + fn fragment(serialization: &[u8], limit: usize) -> Vec { + let header = || { + MessageWriter::new( + FourCc::new(*b"dfrm"), + MessageFlags::GUEST_EXPECTS_REPLY, + Some(GuestUuid([1; 16])), + 0, + ) + }; + let mut message = header(); + message.s64(FourCc::new(*b",frm"), 9); + let mut rest = message.sample_buffer_with_limit(KEY, limit, serialization); + let mut bytes = Vec::new(); + while !rest.is_empty() { + message.change_flags( + MessageFlags::MORE_FRAGMENTS, + MessageFlags(MessageFlags::MORE_FRAGMENTS.0 | MessageFlags::GUEST_EXPECTS_REPLY.0), + ); + bytes.extend_from_slice(&std::mem::replace(&mut message, header()).finish()); + rest = message.sample_buffer_with_limit(KEY, limit, rest); + } + bytes.extend_from_slice(&message.finish()); + bytes + } + + #[test] + fn fragments_reassemble_in_order() -> Result<(), WireError> { + let serialization: Vec = (0..=255).cycle().take(1000).collect(); + let bytes = fragment(&serialization, 200); + let headers = [0, 200, 400, 600, 800, 1000] + .iter() + .filter_map(|start| read_header(&bytes, *start).ok()) + .count(); + assert!(headers > 4, "split into several fragments"); + let message = Message::parse(&bytes)?; + assert_eq!(message.sample_buffer(KEY)?, Some(serialization)); + assert_eq!(message.s64(FourCc::new(*b",frm"))?, Some(9)); + Ok(()) + } + + #[test] + fn nothing_is_appended_when_17_bytes_do_not_fit() { + let mut message = MessageWriter::new(FourCc::new(*b"dfrm"), MessageFlags::NONE, None, 0); + let rest = message.sample_buffer_with_limit(KEY, HEADER_SIZE + 16, &[1, 2, 3]); + assert_eq!(rest, &[1, 2, 3]); + assert_eq!(message.len(), HEADER_SIZE); + } + + #[test] + fn an_empty_fragment_is_malformed() -> Result<(), WireError> { + let mut writer = MessageWriter::new(FourCc::new(*b"test"), MessageFlags::NONE, None, 0); + writer.data(KEY, &[]); + let bytes = writer.finish(); + let message = Message::parse(&bytes)?; + assert_eq!( + message.data(KEY), + Err(WireError::Malformed("empty fragment")) + ); + Ok(()) + } + + #[test] + fn changing_flags_keeps_the_bits_outside_the_mask() { + let flags = MessageFlags(0x1 | 0x8); + assert_eq!( + flags.changed(MessageFlags(0x10), MessageFlags(0x11)), + MessageFlags(0x18) + ); + } + + /// A reply identifier set after the parameters is the header's, and + /// leaves the rest as it was. + #[test] + fn a_reply_identifier_set_later_is_the_headers() -> Result<(), WireError> { + let uuid = GuestUuid([0x11; 16]); + let mut message = MessageWriter::new( + FourCc::new(*b"Dbuf"), + MessageFlags::HOST_EXPECTS_REPLY, + Some(uuid), + 0, + ); + message.s64(KEY, 7); + let mut expected = MessageWriter::new( + FourCc::new(*b"Dbuf"), + MessageFlags::HOST_EXPECTS_REPLY, + Some(uuid), + 0x0102_0304_0506_0708, + ); + expected.s64(KEY, 7); + message.set_reply_id(0x0102_0304_0506_0708); + let bytes = message.finish(); + assert_eq!(bytes, expected.finish()); + assert_eq!(read_header(&bytes, 0)?.reply_id, 0x0102_0304_0506_0708); + Ok(()) + } +} diff --git a/crates/reims-vgpu-video/src/paravirt/names.rs b/crates/reims-vgpu-video/src/paravirt/names.rs new file mode 100644 index 000000000..a338b5033 --- /dev/null +++ b/crates/reims-vgpu-video/src/paravirt/names.rs @@ -0,0 +1,72 @@ +//! The message types and parameter keys the host reads and writes, as the wire spells them. Each +//! is Apple's, as the appender or getter that uses it spells it; the Rust names are ours. + +use crate::core::fourcc::FourCc; + +/// A message the host answers itself, before any session's. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum HostMessage { + /// `decs`: list the host's decoders. + DecoderList, + /// `dcap`: a decoder's capabilities. + DecoderCapabilities, + /// `encs`: list the host's encoders. + EncoderList, + /// `meps`: list the host's motion-estimation processors. + MotionEstimationList, + /// `+dec`: open a decoder session. + CreateDecoder, + /// `+enc`: open an encoder session. + CreateEncoder, + /// `+mep`: open a motion-estimation session. + CreateMotionEstimation, + /// `-all`, `-dec`, `-enc`, `-mep`, `-uui`: close sessions. + Destroy, + /// `jcap`, `jdec`, `jenc`: the JPEG engine's. + Jpeg, +} + +impl HostMessage { + const ALL: [(Self, [u8; 4]); 15] = [ + (Self::DecoderList, *b"decs"), + (Self::DecoderCapabilities, *b"dcap"), + (Self::EncoderList, *b"encs"), + (Self::MotionEstimationList, *b"meps"), + (Self::CreateDecoder, *b"+dec"), + (Self::CreateEncoder, *b"+enc"), + (Self::CreateMotionEstimation, *b"+mep"), + (Self::Destroy, *b"-all"), + (Self::Destroy, *b"-dec"), + (Self::Destroy, *b"-enc"), + (Self::Destroy, *b"-mep"), + (Self::Destroy, *b"-uui"), + (Self::Jpeg, *b"jcap"), + (Self::Jpeg, *b"jdec"), + (Self::Jpeg, *b"jenc"), + ]; + + /// The message `message_type` names, if the host answers it itself. + pub(crate) fn from_fourcc(message_type: FourCc) -> Option { + Self::ALL + .iter() + .find(|(_, code)| FourCc::new(*code) == message_type) + .map(|(message, _)| *message) + } +} + +/// `,ver`: a protocol version, `=u32`. +pub(crate) const VERSION: FourCc = FourCc::new(*b",ver"); +/// `,err`: a status, `=s32`. +pub(crate) const ERROR: FourCc = FourCc::new(*b",err"); +/// `,cod`: a codec type, `=s32`. +pub(crate) const CODEC: FourCc = FourCc::new(*b",cod"); +/// `,dec`: the decoder list, `=pls`. +pub(crate) const DECODERS: FourCc = FourCc::new(*b",dec"); +/// `,enc`: the encoder list, `=pls`. +pub(crate) const ENCODERS: FourCc = FourCc::new(*b",enc"); +/// `,mep`: the motion-estimation processor list, `=pls`. +pub(crate) const MOTION_ESTIMATORS: FourCc = FourCc::new(*b",mep"); +/// `,dca`: a decoder's capabilities, `=pls`. +pub(crate) const DECODER_CAPABILITIES: FourCc = FourCc::new(*b",dca"); +/// `,hin`: the host's info, `=pls`. +pub(crate) const HOST_INFO: FourCc = FourCc::new(*b",hin"); diff --git a/crates/reims-vgpu-video/src/paravirt/plist.rs b/crates/reims-vgpu-video/src/paravirt/plist.rs new file mode 100644 index 000000000..eb201b5a5 --- /dev/null +++ b/crates/reims-vgpu-video/src/paravirt/plist.rs @@ -0,0 +1,255 @@ +//! The property lists the host's answers carry, as `=pls` parameters: binary property lists +//! (`bplist00`), which CoreMedia's `FigCreateCFPropertyListFromData` reads as +//! `CFPropertyListCreateWithData` does, and which the guest's VideoToolbox writes its own in. +//! +//! The writer makes one object for each value, no two shared, numbered in the order a walk from +//! the top value meets them, a container before what it holds: the format's readers take any +//! order and need no object shared. Integers take the fewest bytes the format reads back as the +//! same value: 1, 2 or 4 unsigned bytes for a value below 2^32, 8 bytes, signed, for any other. +//! A string all of whose characters are ASCII is written as ASCII, any other as UTF-16. + +/// A property list value: the kinds the host's answers hold. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Value { + /// A boolean. + Boolean(bool), + /// An integer. + Integer(i64), + /// A string. + String(String), + /// An array. + Array(Vec), + /// A dictionary, its keys in the order given, each once. + Dictionary(Vec<(String, Value)>), +} + +impl Value { + /// A string value. + pub fn string(value: &str) -> Self { + Self::String(value.to_owned()) + } + + /// A dictionary of `entries`. + pub fn dictionary(entries: [(&str, Value); N]) -> Self { + Self::Dictionary( + entries + .into_iter() + .map(|(key, value)| (key.to_owned(), value)) + .collect(), + ) + } +} + +/// One object of the list, its children by number. +enum Object<'a> { + Boolean(bool), + Integer(i64), + String(&'a str), + Array(Vec), + Dictionary(Vec, Vec), +} + +/// Numbers `value` and everything it holds as objects from `objects.len()`, in the order of the +/// module doc, and returns its number. +fn flatten<'a>(value: &'a Value, objects: &mut Vec>) -> u64 { + let number = objects.len() as u64; + match value { + Value::Boolean(b) => objects.push(Object::Boolean(*b)), + Value::Integer(i) => objects.push(Object::Integer(*i)), + Value::String(s) => objects.push(Object::String(s)), + Value::Array(values) => { + objects.push(Object::Array(Vec::new())); + let children = values.iter().map(|v| flatten(v, objects)).collect(); + if let Some(Object::Array(slot)) = objects.get_mut(number as usize) { + *slot = children; + } + } + Value::Dictionary(entries) => { + objects.push(Object::Dictionary(Vec::new(), Vec::new())); + let keys: Vec = entries + .iter() + .map(|(key, _)| { + let n = objects.len() as u64; + objects.push(Object::String(key)); + n + }) + .collect(); + let values = entries.iter().map(|(_, v)| flatten(v, objects)).collect(); + if let Some(Object::Dictionary(k, v)) = objects.get_mut(number as usize) { + *k = keys; + *v = values; + } + } + } + number +} + +/// The fewest bytes, of 1, 2, 4 and 8, that hold `value` unsigned. +fn width(value: u64) -> u8 { + match value { + 0..=0xff => 1, + 0x100..=0xffff => 2, + 0x1_0000..=0xffff_ffff => 4, + _ => 8, + } +} + +/// Appends `value`'s low `bytes` bytes, big-endian. +fn put(out: &mut Vec, value: u64, bytes: u8) { + let all = value.to_be_bytes(); + out.extend_from_slice(all.get(8 - usize::from(bytes)..).unwrap_or(&all)); +} + +/// Appends an integer object. +fn put_integer(out: &mut Vec, value: i64) { + if value < 0 { + out.push(0x13); + out.extend_from_slice(&value.to_be_bytes()); + return; + } + let value = value.unsigned_abs(); + let bytes = width(value); + out.push(0x10 | bytes.trailing_zeros() as u8); + put(out, value, bytes); +} + +/// Appends a marker of kind `kind` (its high nibble) for `count` items: in the marker where under +/// 15, else after it as an integer object. +fn put_count(out: &mut Vec, kind: u8, count: usize) { + if count < 15 { + out.push(kind | count as u8); + } else { + out.push(kind | 0xf); + put_integer(out, count as i64); + } +} + +/// `value` as a binary property list. +pub fn encode(value: &Value) -> Vec { + let mut objects = Vec::new(); + flatten(value, &mut objects); + let count = objects.len() as u64; + let reference = width(count.saturating_sub(1)); + let mut out = b"bplist00".to_vec(); + let mut offsets = Vec::with_capacity(objects.len()); + for object in &objects { + offsets.push(out.len() as u64); + match object { + Object::Boolean(b) => out.push(if *b { 0x09 } else { 0x08 }), + Object::Integer(i) => put_integer(&mut out, *i), + Object::String(s) if s.is_ascii() => { + put_count(&mut out, 0x50, s.len()); + out.extend_from_slice(s.as_bytes()); + } + Object::String(s) => { + let units: Vec = s.encode_utf16().collect(); + put_count(&mut out, 0x60, units.len()); + for unit in units { + out.extend_from_slice(&unit.to_be_bytes()); + } + } + Object::Array(children) => { + put_count(&mut out, 0xa0, children.len()); + for &child in children { + put(&mut out, child, reference); + } + } + Object::Dictionary(keys, values) => { + put_count(&mut out, 0xd0, keys.len()); + for &child in keys.iter().chain(values) { + put(&mut out, child, reference); + } + } + } + } + let table = out.len() as u64; + let offset = width(table); + for &at in &offsets { + put(&mut out, at, offset); + } + // The trailer: 6 bytes unused, the offsets' and references' widths, the object count, the + // top object's number and the offset table's offset. + out.extend_from_slice(&[0; 6]); + out.push(offset); + out.push(reference); + out.extend_from_slice(&count.to_be_bytes()); + out.extend_from_slice(&0u64.to_be_bytes()); + out.extend_from_slice(&table.to_be_bytes()); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A dictionary of every kind, as the writer lays it out: read back by Python's `plistlib` + /// and checked by `plutil -lint` on macOS 27.0.1 (2026-11-16), which read it as written. + #[test] + fn a_dictionary_of_every_kind_is_laid_out_as_read_back() { + let value = Value::dictionary([ + ("a", Value::Boolean(true)), + ("n", Value::Integer(400)), + ( + "l", + Value::Array(vec![Value::Integer(-1), Value::string("x")]), + ), + ]); + let bytes = encode(&value); + let mut expected = b"bplist00".to_vec(); + // 0: the dictionary, keys 1 to 3, values 4, 5, 6. + expected.extend_from_slice(&[0xd3, 1, 2, 3, 4, 5, 6]); + expected.extend_from_slice(b"\x51a\x51n\x51l"); + expected.extend_from_slice(&[0x09, 0x11, 0x01, 0x90]); + // 6: the array of 7 and 8. + expected.extend_from_slice(&[0xa2, 7, 8]); + expected.push(0x13); + expected.extend_from_slice(&(-1i64).to_be_bytes()); + expected.extend_from_slice(b"\x51x"); + let table = expected.len() as u8; + expected.extend_from_slice(&[8, 15, 17, 19, 21, 22, 25, 28, 37]); + expected.extend_from_slice(&[0, 0, 0, 0, 0, 0, 1, 1]); + expected.extend_from_slice(&9u64.to_be_bytes()); + expected.extend_from_slice(&0u64.to_be_bytes()); + expected.extend_from_slice(&u64::from(table).to_be_bytes()); + assert_eq!(bytes, expected); + } + + #[test] + fn integers_take_the_fewest_bytes_that_read_back_the_same() { + let one = |i| { + let mut out = Vec::new(); + put_integer(&mut out, i); + out + }; + assert_eq!(one(0), [0x10, 0]); + assert_eq!(one(0xff), [0x10, 0xff]); + assert_eq!(one(0x100), [0x11, 1, 0]); + assert_eq!(one(0x1_0000), [0x12, 0, 1, 0, 0]); + assert_eq!(one(0x1_0000_0000), [0x13, 0, 0, 0, 1, 0, 0, 0, 0]); + assert_eq!( + one(-2), + [0x13, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe] + ); + } + + #[test] + fn long_strings_and_arrays_count_after_their_marker() { + let long = "abcdefghijklmnop"; + let bytes = encode(&Value::string(long)); + assert_eq!(&bytes[8..11], &[0x5f, 0x10, 16]); + assert_eq!(&bytes[11..27], long.as_bytes()); + let wide = encode(&Value::string("é")); + assert_eq!(&wide[8..11], &[0x61, 0x00, 0xe9]); + } + + #[test] + fn many_objects_take_wider_references() { + let values = (0..300).map(Value::Integer).collect(); + let bytes = encode(&Value::Array(values)); + // The array's marker, its count as a 2-byte integer, then 2-byte references. + assert_eq!(&bytes[8..14], &[0xaf, 0x11, 0x01, 0x2c, 0x00, 0x01]); + let trailer = &bytes[bytes.len() - 32..]; + assert_eq!(trailer[7], 2); + assert_eq!(u64::from_be_bytes(trailer[8..16].try_into().unwrap()), 301); + } +} diff --git a/crates/reims-vgpu-video/src/paravirt/status.rs b/crates/reims-vgpu-video/src/paravirt/status.rs new file mode 100644 index 000000000..662f5fb97 --- /dev/null +++ b/crates/reims-vgpu-video/src/paravirt/status.rs @@ -0,0 +1,28 @@ +//! The statuses the guest sees: the `OSStatus` the host answers each message with, and the `,err` +//! of its replies. Each value is Apple's: the VideoToolbox ones are public (`VTErrors.h` in the +//! macOS SDK), the paravirtual protocol's are its host's and guest's own. The names are ours, from +//! Apple's constant names where it has one. + +/// The status of an operation: 0 is success, anything else an `OSStatus` error. +pub type OsStatus = i32; + +/// Success. +pub const NO_ERROR: OsStatus = 0; +/// `kVTParameterErr`. +pub const PARAMETER: OsStatus = -12902; +/// `kVTCouldNotFindVideoDecoderErr`: a decoder create for a codec the host has no decoder of. +pub const COULD_NOT_FIND_VIDEO_DECODER: OsStatus = -12906; +/// `kVTCouldNotFindVideoEncoderErr`: likewise, an encoder create. +pub const COULD_NOT_FIND_VIDEO_ENCODER: OsStatus = -12908; +/// A message that does not parse, or that the receiver cannot take (kVTPVMalformedMessageErr). +pub const MALFORMED_MESSAGE: OsStatus = -19093; +/// A message for a UUID with no session. +pub const SESSION_NOT_FOUND: OsStatus = -19094; +/// No motion-estimation processor matches (kVTMESProcessorNotFoundErr). +pub const MOTION_ESTIMATION_PROCESSOR_NOT_FOUND: OsStatus = -19350; +/// A motion-estimation list request from a guest older than protocol 6 +/// (kVTMESUnsupportedGuestErr). +pub const UNSUPPORTED_GUEST: OsStatus = -19960; +/// CMPhoto's status where it has no JPEG hardware, which a JPEG request is answered with. The +/// name is ours. +pub const NO_JPEG_HARDWARE: OsStatus = -16994; diff --git a/crates/reims-vgpu/src/graphics.rs b/crates/reims-vgpu/src/graphics.rs index 146521830..ceb522ab6 100644 --- a/crates/reims-vgpu/src/graphics.rs +++ b/crates/reims-vgpu/src/graphics.rs @@ -86,16 +86,20 @@ use reims_vgpu_graphics::wire::{ RGFX_FEATURE_UNSHARED_QUEUES, RGFX_RESOURCE_ID_CHUNK, RGFX_RESOURCE_ID_CHUNKS, RGFX_STATUS_INVALID_ARGUMENT, RGFX_STATUS_NOT_FOUND, RGFX_STATUS_OK, RGFX_STATUS_REFUSED, RGFX_VIDEO_CAPS_CODECS, RGFX_VIDEO_CAPS_OFFSET, RGFX_VIDEO_CAPS_OUTPUT_CACHED, - RGFX_VIDEO_CAPS_VERSION, RgfxBlockGrant, RgfxBlockRelease, RgfxBufferOverPages, RgfxCbComplete, - RgfxCbScheduled, RgfxCbSubmitted, RgfxColorEntry, RgfxDisplayColor, RgfxEventSignalled, - RgfxFunctionPointerState, RgfxHeapOverPages, RgfxIcbState, RgfxLibraryLookup, RgfxMsgHeader, - RgfxPageRun, RgfxPipelineAnswersQuery, RgfxRateMapAnswer, RgfxRateMapState, RgfxSamplerState, - RgfxScheduledAsk, RgfxSharedEventName, RgfxSurfacePages, RgfxSurfacePagesLayout, RgfxVideoCaps, + RGFX_VIDEO_CAPS_VERSION, RGFX_VIDEO_CODEC_H264, RGFX_VIDEO_CODEC_HEVC, RGFX_VIDEO_DECODE, + RGFX_VIDEO_H264_BASELINE, RGFX_VIDEO_H264_HIGH, RGFX_VIDEO_H264_MAIN, RGFX_VIDEO_HEVC_MAIN, + RGFX_VIDEO_HEVC_MAIN_10, RGFX_VT_STATUS_MALFORMED, RgfxBlockGrant, RgfxBlockRelease, + RgfxBufferOverPages, RgfxCbComplete, RgfxCbScheduled, RgfxCbSubmitted, RgfxColorEntry, + RgfxDisplayColor, RgfxEventSignalled, RgfxFunctionPointerState, RgfxHeapOverPages, + RgfxIcbState, RgfxLibraryLookup, RgfxMsgHeader, RgfxPageRun, RgfxPipelineAnswersQuery, + RgfxRateMapAnswer, RgfxRateMapState, RgfxSamplerState, RgfxScheduledAsk, RgfxSharedEventName, + RgfxSurfacePages, RgfxSurfacePagesLayout, RgfxVideoCaps, }; use reims_vgpu_graphics::{ CompleteAnswer, CompletionPoster, CursorImage, DoorbellAt, Host, Mode, PresentAnswer, - QueueClaim, RawDoorbell, RingDegradation, Scanout, Screen, + QueueClaim, RawDoorbell, RingDegradation, Scanout, Screen, VtAnswer, VtLink, VtMessage, }; +use reims_vgpu_video::paravirt; use reims_vgpu_vulkan::core::host::HostQueue; use reims_vgpu_vulkan::core::memory::map::MemoryMap as CoreMemoryMap; use reims_vgpu_vulkan::core::num::ToU64; @@ -640,13 +644,16 @@ impl GraphicsDevice

{ } region.write(RGFX_DEVICE_INFO_OFFSET, info.as_bytes()); // The host's hardware video, whose codecs the video caps after the device info list - // for the guest's video driver. + // for the guest's video driver, and whose decoders VideoToolbox's paravirtual path + // lists for an arm64 guest's. + let mut vt = paravirt::Host::default(); let video_runtime = crate::video::runtime::PlatformRuntime::of(&platform); if let Some(video) = platform.graphics_video(&gpu_device, video_runtime) { let caps = video_caps(features, &*video); let cached = caps.flags & RGFX_VIDEO_CAPS_OUTPUT_CACHED != 0; debug_assert!(caps.codec_count as usize <= RGFX_VIDEO_CAPS_CODECS); region.write(RGFX_VIDEO_CAPS_OFFSET, caps.as_bytes()); + vt = paravirt::Host::new(vt_decoders(&caps)); if cached && video.imports_device_caches() { decoder.set_exportable_caches(); } else if cached && video.decodes_into_device_caches() { @@ -699,6 +706,7 @@ impl GraphicsDevice

{ features_16k, deferred_budget, control: Arc::clone(&control), + vt, }); // Display 0's window, then those of displays 1 and up, or none. let window_configs: Vec> = match config.window { @@ -3026,6 +3034,9 @@ struct CallbackHost { deferred_budget: u64, /// The stage-3 decoder, fed the stage-3 messages of ring 0 and of the queues' rings. control: Arc>, + /// The host's side of VideoToolbox's paravirtual messages ([`paravirt`]), over the decoders + /// of the host's hardware video. + vt: paravirt::Host, } impl Host for CallbackHost

{ @@ -3189,6 +3200,83 @@ impl Host for CallbackHost

{ fn scheduled_ask(&self, completion: &CompletionPoster, message: &[u8]) { stepped(|| self.control.scheduled_ask(completion, message)); } + + fn vt_message(&self, message: VtMessage, answer: VtAnswer, link: VtLink) { + let length = message.message.length; + let Some(bytes) = self.control.decoder().guest_bytes(&message.runs, length) else { + log::warn!( + target: "reims_vgpu::graphics", + "a VT_MESSAGE of {length} bytes: its runs lie outside the guest RAM the host maps" + ); + answer.answer(RGFX_VT_STATUS_MALFORMED); + return; + }; + let answered = self.vt.deliver(&bytes); + for reply in &answered.replies { + if !link.send(reply) { + log::warn!( + target: "reims_vgpu::graphics", + "a {}-byte VideoToolbox message to the guest was not sent", + reply.len() + ); + } + } + answer.answer(answered.status); + } +} + +/// The decoders VideoToolbox's paravirtual path lists ([`paravirt::Host`]): one for each decode +/// entry of `caps` of H.264 or HEVC with a profile, its profiles as VideoToolbox numbers them +/// (H.264's `profile_idc`; HEVC's `general_profile_idc`, Main Still Picture where Main is, whose +/// decoder takes its streams) and its level the caps'. +fn vt_decoders(caps: &RgfxVideoCaps) -> Vec { + let count = usize::try_from(caps.codec_count) + .unwrap_or(usize::MAX) + .min(RGFX_VIDEO_CAPS_CODECS); + let numbered = |bits: u32, numbers: &[(u32, u32)]| -> Vec { + numbers + .iter() + .filter(|&&(bit, _)| bits & bit != 0) + .map(|&(_, number)| number) + .collect() + }; + caps.codecs + .iter() + .take(count) + .filter(|c| c.direction == RGFX_VIDEO_DECODE) + .filter_map(|c| { + let (codec, profiles) = match c.codec { + RGFX_VIDEO_CODEC_H264 => ( + paravirt::Codec::H264, + numbered( + c.profiles, + &[ + (RGFX_VIDEO_H264_BASELINE, 66), + (RGFX_VIDEO_H264_MAIN, 77), + (RGFX_VIDEO_H264_HIGH, 100), + ], + ), + ), + RGFX_VIDEO_CODEC_HEVC => ( + paravirt::Codec::Hevc, + numbered( + c.profiles, + &[ + (RGFX_VIDEO_HEVC_MAIN, 1), + (RGFX_VIDEO_HEVC_MAIN_10, 2), + (RGFX_VIDEO_HEVC_MAIN, 3), + ], + ), + ), + _ => return None, + }; + (!profiles.is_empty()).then_some(paravirt::Decoder { + codec, + profiles, + max_level: c.max_level, + }) + }) + .collect() } /// Runs `f`, a callback of the device's that may call the GPU's driver, as a step of the exit diff --git a/crates/reims-vgpu/src/graphics/decode/mod.rs b/crates/reims-vgpu/src/graphics/decode/mod.rs index 9203e18d8..65158edb7 100644 --- a/crates/reims-vgpu/src/graphics/decode/mod.rs +++ b/crates/reims-vgpu/src/graphics/decode/mod.rs @@ -2723,6 +2723,36 @@ impl GraphicsDecoder

{ .map(|present| present.texture) } + /// The first `length` bytes the guest RAM runs `runs` hold, `(address, length)` in order, as + /// the host's mapping of the guest's RAM reads them now: a `VT_MESSAGE`'s message. `None` + /// where the host has no mapping of the guest's RAM, a byte of them lies outside it, or the + /// runs hold fewer bytes. + pub(crate) fn guest_bytes(&self, runs: &[(u64, u64)], length: u64) -> Option> { + let runs: Vec = runs + .iter() + .map(|&(address, length)| RgfxPageRun { address, length }) + .collect(); + use reims_vgpu_vulkan::core::num::{ToU64 as _, ToUsize as _}; + let pages = self + .shared + .surface_views + .lock() + .host_pages_in_order(&runs)?; + let mut bytes = Vec::with_capacity(length.to_usize()); + for (host, n) in pages { + let left = length.to_usize().saturating_sub(bytes.len()); + if left == 0 { + break; + } + let n = n.to_usize().min(left); + // SAFETY: `n` bytes of the host's mapping of the guest's RAM, which the memory map's + // lease keeps mapped for the device's life; the guest may write them as they are + // read, which gives it back garbage, as a write of its own message would. + bytes.extend_from_slice(unsafe { std::slice::from_raw_parts(host.as_ptr::(), n) }); + } + (bytes.len().to_u64() == length).then_some(bytes) + } + /// The textures IOSurface `iosurface_id` is named by, oldest first: those over its plane 0, /// the newest of which a present of it shows ([`Self::surface_present`]). pub(crate) fn surface_textures(&self, iosurface_id: u32) -> Vec { diff --git a/crates/reims-vgpu/src/graphics/tests.rs b/crates/reims-vgpu/src/graphics/tests.rs index 1061b899f..63d8ae390 100644 --- a/crates/reims-vgpu/src/graphics/tests.rs +++ b/crates/reims-vgpu/src/graphics/tests.rs @@ -13248,3 +13248,78 @@ fn a_group_closes_at_its_limits() { ); } } + +/// VideoToolbox's paravirtual path lists a decoder for each decode entry of the caps of H.264 or +/// HEVC with a profile, its profiles as VideoToolbox numbers them and its level the caps': no +/// encode entry, no entry with no profile, and no codec past the caps' count. +#[test] +fn vt_decoders_are_the_caps_decode_entries() { + let entry = |codec, direction, profiles, max_level| RgfxVideoCodecCaps { + codec, + direction, + profiles, + max_level, + ..RgfxVideoCodecCaps::default() + }; + let mut caps = RgfxVideoCaps { + version: RGFX_VIDEO_CAPS_VERSION, + codec_count: 4, + ..RgfxVideoCaps::default() + }; + caps.codecs[0] = entry( + RGFX_VIDEO_CODEC_H264, + RGFX_VIDEO_DECODE, + RGFX_VIDEO_H264_BASELINE | RGFX_VIDEO_H264_MAIN | RGFX_VIDEO_H264_HIGH, + 52, + ); + caps.codecs[1] = entry( + RGFX_VIDEO_CODEC_H264, + RGFX_VIDEO_ENCODE, + RGFX_VIDEO_H264_HIGH, + 51, + ); + caps.codecs[2] = entry( + RGFX_VIDEO_CODEC_HEVC, + RGFX_VIDEO_DECODE, + RGFX_VIDEO_HEVC_MAIN | RGFX_VIDEO_HEVC_MAIN_10, + 153, + ); + caps.codecs[3] = entry(RGFX_VIDEO_CODEC_HEVC, RGFX_VIDEO_DECODE, 0, 153); + // Past the count: not listed. + caps.codecs[4] = entry( + RGFX_VIDEO_CODEC_H264, + RGFX_VIDEO_DECODE, + RGFX_VIDEO_H264_MAIN, + 40, + ); + assert_eq!( + vt_decoders(&caps), + vec![ + paravirt::Decoder { + codec: paravirt::Codec::H264, + profiles: vec![66, 77, 100], + max_level: 52, + }, + paravirt::Decoder { + codec: paravirt::Codec::Hevc, + profiles: vec![1, 2, 3], + max_level: 153, + }, + ] + ); + let main10 = RgfxVideoCaps { + codec_count: 1, + codecs: { + let mut codecs = [RgfxVideoCodecCaps::default(); RGFX_VIDEO_CAPS_CODECS]; + codecs[0] = entry( + RGFX_VIDEO_CODEC_HEVC, + RGFX_VIDEO_DECODE, + RGFX_VIDEO_HEVC_MAIN_10, + 120, + ); + codecs + }, + ..caps + }; + assert_eq!(vt_decoders(&main10)[0].profiles, vec![2]); +} diff --git a/docs/graphics-kext/design.md b/docs/graphics-kext/design.md index 514c7810a..427a125ba 100644 --- a/docs/graphics-kext/design.md +++ b/docs/graphics-kext/design.md @@ -1599,6 +1599,64 @@ Stages: of decodes alone; a CPU lock downloads it in 1 to 5 ms. Where the GPU shares the CPU's memory, the copy writes the surface's pages, on the decode queue. +17. **An arm64 guest's hardware video is VideoToolbox's paravirtual path, + over the arm64e kext.** AppleGVA's vendor-driver route is x86-64's + (item 16). An arm64 guest's VideoToolbox has the path Apple's VMs use + instead: where VideoToolboxParavirtualizationSupport finds a service of + class `AppleVideoToolboxParavirtualizationDriver` and opens it, the + guest's VideoToolbox counts itself as running in a guest, asks the host + for its decoders and encoders, and registers each one the host lists as + `paravirtualized:`, hardware-accelerated; its own + `ParavirtualizedVideoDecoder` and `ParavirtualizedVideoEncoder` then run + each session as messages to the host (read from VideoToolbox and the + support framework, macOS 27.0.1 arm64e; [the old protocol's + doc](../video/devices.md) at tag `arm64-last-capable` lists the messages, + which Apple's VMs carry over a virtio device of their own). + - **The guest's side is the arm64e kext's.** Where the guest took + `RGFX_FEATURE_VT_MESSAGES` and the caps list a decoder, display 0's + framebuffer publishes a service of that class (`RgfxVtService.hpp`), + whose user client answers + the framework's five selectors as Apple's kext of that class does + (read from `AppleVideoToolboxParavirtualization.kext` 15.0.0, the + macOS 27.2.1 arm64e VM kernel collection): 0 sizes the message buffer + (at most 10 MiB) and answers its capacity and the user addresses of + the buffer and of the host-message queue, an IOSharedDataQueue the + kext maps into the process; 1 and 2 register and deregister a 16-byte + session UUID for the client; 3 sends the buffer's first `length` + bytes, with up to five IOSurface IDs, and answers the host's status + for it, as its output and as its return (the kext answers a message + that names a surface `kVTParameterErr` for now: nothing the host + answers yet takes one); 4 moves the host messages kept while the + queue was full into it. The notification port is type + 0. Apple's kext of that class binds only to Apple's VM device + (106b:1a03), which no VM of ours has, so it never loads beside ours. + - **The wire:** `VT_MESSAGE` on ring 0 carries one message: its length, + the guest RAM runs of the client's message buffer that hold it, and + the IDs of the IOSurfaces it lends. It waits for no + command buffer and no buffer waits for it. The host reads the message + from guest RAM, hands it to its session layer, and answers + `VT_STATUS` with the status VideoToolbox's host side would return. A + message from the host (a reply, a request, an emitted frame; 16 KiB + at most, the framework's dequeue buffer) comes as `VT_MESSAGE` on the + control completion ring, its bytes inline; the kext gives it to every + client that registered its UUID, and a `Bye!` to every client with + each UUID written in, as Apple's kext does. A deregistration of a + UUID the client registered sends the host `-uui` for it, and so does + a client's close for each UUID it holds, as Apple's kext does. + - **The answers are the host's arms'.** `decs` lists one decoder for + each codec the caps decode, `dcap` its profiles and level from the + caps' entry; a codec the host lacks is not listed, so VideoToolbox + decodes it in software as on a Mac without it. `encs` lists no + encoder and `meps` no processor, and every create is answered with a + refusal in its reply's `,err`, as for a codec the host lacks + (`reims_vgpu_video::paravirt`). A host with no arm offers no caps and + the kext publishes no service: the guest's VideoToolbox is then not a + guest's. + - **No host offers `VT_MESSAGES` yet.** A guest's VideoToolbox would + list our decoders as hardware while no session of one can run, so + the host offers the bit once its decode sessions do; until then the + arm64e kext publishes no service, and the guest answers no hardware + decoder for any codec, as before the bit. ## What metal2vulkan adds in stage 3 @@ -2125,6 +2183,18 @@ only where no negotiation can carry it. games", below). The device offers it where the host made it with a window, on a device of one display as of several, and sends the event only to a guest that took it. Both kexts take it; the firmware drivers do not. +- Bit 52, `FEATURES_HI`'s bit 20, is `VT_MESSAGES`: ring 0 carries the arm64e + kext's `VT_MESSAGE` (0x2fa, `RgfxVtMessage`, then its runs: one message of + the guest's VideoToolbox to its host side), which the host answers + `VT_STATUS` (0x40d, `RgfxVtStatus`: the status VideoToolbox's host side + returns for it), and the control completion ring carries the host's side's + messages to the guest's as the event `VT_MESSAGE` (0x40e, + `RgfxVtHostMessage`, its bytes inline, `seqno` 0), sent only to a guest that + took the bit (item 17 of "Decided", above). The device refuses a + `VT_MESSAGE` of a guest that did not take it as one it could not read + (`RGFX_VT_STATUS_MALFORMED`). The arm64e kext takes it, and publishes the + service only where the caps list a decoder; the x86-64 kext and the firmware + drivers do not. No host offers it yet (item 17). **BAR2: the region.** A 64-bit prefetchable BAR over host memory (1 GiB), mapped write-back by the guest. The device places the control rings at fixed diff --git a/guest/kext/Makefile b/guest/kext/Makefile index 91e1bb1e4..668a19ddc 100644 --- a/guest/kext/Makefile +++ b/guest/kext/Makefile @@ -83,11 +83,12 @@ HEADERS = $(wildcard src/*.hpp src/shim/*/*.h src/shim/*/*/*.h) # The Stage-2 framebuffer (ReimsGraphics), the Stage-3 Metal accelerator # (RgfxAccelerator) and its region-map + doorbell user client, the guest's own mouse for # POINTER_MOTION (RgfxPointerDevice), the pointer's moves (ReimsGraphicsPointer), on x86-64 the -# device control (RgfxDeviceControl) and on arm64e the front end (ReimsGraphicsMobile), all one -# kext: the objects both architectures build, with each architecture's own (OBJECTS_x86_64, -# OBJECTS_arm64e) third in the link. +# device control (RgfxDeviceControl) and on arm64e the front end (ReimsGraphicsMobile) and the +# VideoToolbox service (RgfxVtService), all one kext: the objects both architectures build, with +# each architecture's own (OBJECTS_x86_64, OBJECTS_arm64e) third in the link. OBJECTS_x86_64 = $(BUILD)/obj/RgfxDeviceControl.o $(BUILD)/obj/ReimsGraphicsPointer.o -OBJECTS_arm64e = $(BUILD)/obj/ReimsGraphicsMobile.o $(BUILD)/obj/ReimsGraphicsPointer.o +OBJECTS_arm64e = $(BUILD)/obj/ReimsGraphicsMobile.o $(BUILD)/obj/ReimsGraphicsPointer.o \ + $(BUILD)/obj/RgfxVtService.o OBJECTS = $(BUILD)/obj/ReimsGraphics.o \ $(BUILD)/obj/RgfxAccelerator.o \ $(OBJECTS_$(ARCH_NAME)) \ @@ -163,7 +164,7 @@ TESTS = $(BUILD)/tests/spans_test $(BUILD)/tests/blocks_test $(BUILD)/tests/surf $(BUILD)/tests/queue_publish_test $(BUILD)/tests/doorbell_pages_test $(BUILD)/tests/top_down_test \ $(BUILD)/tests/display_table_test $(BUILD)/tests/agdc_displays_test \ $(BUILD)/tests/pointer_over_test $(BUILD)/tests/display_bounds_test $(BUILD)/tests/display_places_test \ - $(BUILD)/tests/pointer_motion_test $(BUILD)/tests/register_hold_test + $(BUILD)/tests/pointer_motion_test $(BUILD)/tests/register_hold_test $(BUILD)/tests/vt_routes_test $(BUILD)/tests/%: tests/%.cpp $(HEADERS) ../../crates/reims-vgpu-graphics/include/reims_graphics_wire.h Makefile @mkdir -p $(@D) diff --git a/guest/kext/src/ReimsGraphics.cpp b/guest/kext/src/ReimsGraphics.cpp index 00a6fc561..61ddd1b46 100644 --- a/guest/kext/src/ReimsGraphics.cpp +++ b/guest/kext/src/ReimsGraphics.cpp @@ -1151,6 +1151,16 @@ void ReimsGraphics::handleEvent(UInt32 type, UInt64 seqno, const volatile UInt8 // The host's pointer drives the guest's own mouse (RgfxPointerDevice.hpp). pointerMotion(payload, size); return; +#if defined(__arm64e__) + case RGFX_EVT_VT_STATUS: + // A VT_MESSAGE's answer, for the thread that sent it (RgfxVtService.hpp). + answerLifecycle(type, seqno, payload, size); + return; + case RGFX_EVT_VT_MESSAGE: + // The host's side's message, for the guest's VideoToolbox (RgfxVtService.hpp). + vtMessage(payload, size); + return; +#endif case RGFX_EVT_POINTER_OVER: // The host's pointer is over another display: the cursor goes there // (ReimsGraphicsPointer.cpp). @@ -1652,6 +1662,10 @@ bool ReimsGraphics::start(IOService *provider) pipelineAnswersTaken = false; multiDisplayTaken = false; pointerMotionTaken = false; +#if defined(__arm64e__) + vtMessagesTaken = false; + vtService = nullptr; +#endif displayBoundsTaken = false; boundsTold = {}; displayCount = 0; @@ -1828,6 +1842,9 @@ bool ReimsGraphics::start(IOService *provider) (RGFX_FEATURE_PIPELINE_KEYS | RGFX_FEATURE_PIPELINE_ANSWERS); multiDisplayTaken = (took & RGFX_FEATURE_MULTI_DISPLAY) != 0; pointerMotionTaken = (took & RGFX_FEATURE_POINTER_MOTION) != 0; +#if defined(__arm64e__) + vtMessagesTaken = (took & RGFX_FEATURE_VT_MESSAGES) != 0; +#endif constexpr uint64_t kCarriesPast = RGFX_FEATURE_MULTI_DISPLAY | RGFX_FEATURE_POINTER_OVER | RGFX_FEATURE_DISPLAY_BOUNDS; displayBoundsTaken = (took & kCarriesPast) == kCarriesPast; @@ -1904,6 +1921,9 @@ bool ReimsGraphics::start(IOService *provider) releaseRegistrations(); #endif startPointerDevice(); +#if defined(__arm64e__) + startVtService(); +#endif return true; } fail: @@ -1946,6 +1966,7 @@ void ReimsGraphics::stop(IOService *provider) quiesce(); stopPointerDevice(); #if defined(__arm64e__) + stopVtService(); freeMobileChanges(); #endif freePointer(); diff --git a/guest/kext/src/ReimsGraphics.hpp b/guest/kext/src/ReimsGraphics.hpp index 873e39eee..bb33ca376 100644 --- a/guest/kext/src/ReimsGraphics.hpp +++ b/guest/kext/src/ReimsGraphics.hpp @@ -73,6 +73,7 @@ typedef graft_iomfb_word RgfxIOMFBWord; class RgfxAccelerator; class RgfxPointerDevice; +class AppleVideoToolboxParavirtualizationDriver; // The display front end each architecture's WindowServer drives: an IOFramebuffer on x86-64, and // on arm64, where WindowServer opens no IOFramebuffer, an IOMobileFramebuffer, the subclass of @@ -739,6 +740,19 @@ private: void startPointerDevice(); void stopPointerDevice(); void pointerMotion(const volatile UInt8 *payload, UInt32 size); +#if defined(__arm64e__) + // The arm64e kext's VideoToolbox service (RgfxVtService.hpp), display 0's alone: whether the + // host took VT_MESSAGES, set at the start's features; the service, published once the + // framebuffer has started where it took it and the caps list a decoder (startVtService), and + // stopped in the stop once the work loop hands it nothing more (stopVtService); and + // handleEvent's VT_MESSAGE, which hands it the host's message on the work loop. The service + // is stored and read atomically, as the mouse is. + bool vtMessagesTaken; + AppleVideoToolboxParavirtualizationDriver *vtService; + void startVtService(); + void stopVtService(); + void vtMessage(const volatile UInt8 *payload, UInt32 size); +#endif // The boot screen the scanout holds until clearBootScreen: the boot framebuffer the OS had at // the start (publishBootConsole); the largest span a mode's scanout has had (setScanout, under diff --git a/guest/kext/src/RgfxFeatures.hpp b/guest/kext/src/RgfxFeatures.hpp index f26a2f5c6..36ca99d60 100644 --- a/guest/kext/src/RgfxFeatures.hpp +++ b/guest/kext/src/RgfxFeatures.hpp @@ -165,7 +165,11 @@ // bundle; // - POINTER_MOTION (bit 51), both kexts: the framebuffer publishes the guest's own mouse // (RgfxPointerDevice.hpp) and hands it each POINTER_MOTION's reports -// (RgfxPointerMotion.hpp), which needs nothing of the bundle. +// (RgfxPointerMotion.hpp), which needs nothing of the bundle; +// - VT_MESSAGES (bit 52), the arm64e kext alone: the framebuffer publishes the VideoToolbox +// service where the host's caps list a decoder, carries its clients' messages to the host as +// VT_MESSAGEs and hands them the host's VT_MESSAGE events (RgfxVtService.hpp), which needs +// nothing of the bundle; an x86-64 guest's hardware video is AppleGVA's (RgfxVideoCodecs.hpp). // // The accelerator answers the bundle's Features call with the feature word (rgfxFeatureWord), and // grants a queue's flags (kRgfxAccelMethodQueueCreate's seventh input) only where their feature @@ -208,7 +212,8 @@ constexpr uint64_t kRgfxCarriedFeatures = RGFX_FEATURE_READ_ONLY_PAGES | RGFX_FEATURE_DOORBELL_PAGES | RGFX_FEATURE_PIPELINE_ANSWERS | RGFX_FEATURE_POINTER_MOTION | RGFX_FEATURE_MULTI_DISPLAY | RGFX_FEATURE_POINTER_OVER | RGFX_FEATURE_DISPLAY_BOUNDS | - (RGFX_GUEST_ARM64 ? RGFX_FEATURE_PAGES_16K : RGFX_FEATURE_DISPLAY_POWER); + (RGFX_GUEST_ARM64 ? RGFX_FEATURE_PAGES_16K | RGFX_FEATURE_VT_MESSAGES + : RGFX_FEATURE_DISPLAY_POWER); // What the framebuffer writes to DRIVER_FEATURES, given the host's offer and, on arm64, the // displays whose node the firmware placed under /arm-io, counted from display 0 (`mobileNodes`): diff --git a/guest/kext/src/RgfxVtRoutes.hpp b/guest/kext/src/RgfxVtRoutes.hpp new file mode 100644 index 000000000..cd50d51b6 --- /dev/null +++ b/guest/kext/src/RgfxVtRoutes.hpp @@ -0,0 +1,202 @@ +/* + * RgfxVtRoutes.hpp — the rules of the arm64e kext's VideoToolbox service (RgfxVtService.hpp, + * design.md, "Decided", 17): which of its clients each message of the host goes to, the message + * the kext sends the host as a client lets go of a session UUID, the runs of a client's message + * buffer a message lies in, and whether the host's caps list a decoder for the service to serve. + * + * Apple's kext of the service, AppleVideoToolboxParavirtualization.kext 15.0.0 (read from the + * macOS 27.2.1 arm64e VM kernel collection), routes as this does: a host message goes to every + * client that registered the UUID its `vtpv` header names, once each, and a `Bye!` to every + * client once for each UUID it registered, that UUID written in; each deregistration of a UUID the + * client registered, and each UUID a closing client holds, sends the host a `-uui` of it. + * + * Header-only and free of kernel types, so tests/vt_routes_test.cpp checks it on the Mac. + */ + +#ifndef RGFX_VT_ROUTES_HPP_ +#define RGFX_VT_ROUTES_HPP_ + +#include +#include + +#include "reims_graphics_wire.h" + +// A session UUID's bytes, and a `vtpv` header's. +constexpr uint32_t kRgfxVtUuidBytes = 16; +constexpr uint32_t kRgfxVtHeaderBytes = 48; +// The capacity of a client's host-message queue, an IOSharedDataQueue: Apple's kext's. +constexpr uint32_t kRgfxVtQueueBytes = 0x8014; +// The (UUID, client) pairs the service routes at once, and the host messages a client keeps while +// its queue is full: ours, past anything a process's sessions hold. +constexpr uint32_t kRgfxVtRoutesMax = 256; +constexpr uint32_t kRgfxVtPendingMax = 256; + +// Where a `vtpv` header keeps its message type and its UUID. +constexpr uint32_t kRgfxVtTypeAt = 8; +constexpr uint32_t kRgfxVtUuidAt = 16; + +static inline uint32_t rgfxVtBe32(const uint8_t *p) +{ + return static_cast(p[0]) << 24 | static_cast(p[1]) << 16 | + static_cast(p[2]) << 8 | p[3]; +} + +// The four bytes of a FourCC, as the wire spells it, as one big-endian u32. +constexpr uint32_t rgfxVtFourCc(const char (&s)[5]) +{ + return static_cast(static_cast(s[0])) << 24 | + static_cast(static_cast(s[1])) << 16 | + static_cast(static_cast(s[2])) << 8 | + static_cast(static_cast(s[3])); +} + +// What a host message is, for its routing. +enum RgfxVtHostKind : uint8_t { + // A `vtpv` message for the clients of its UUID. + kRgfxVtForUuid, + // A `Bye!`: for every client, once for each UUID it registered. + kRgfxVtByeAll, + // A `rels` box: the host lets go of surfaces the guest lent it, which the kext lends none of. + kRgfxVtReleases, + // Neither: too short, or not a `vtpv` atom. + kRgfxVtUnreadable, +}; + +// What the `length` bytes of the host's `message` are, and its UUID, in `uuid`, for one for a +// UUID. +static inline RgfxVtHostKind rgfxVtHostMessage(const uint8_t *message, uint32_t length, + uint8_t uuid[kRgfxVtUuidBytes]) +{ + if (length >= 8 && rgfxVtBe32(message + 4) == rgfxVtFourCc("rels")) + return kRgfxVtReleases; + if (length < kRgfxVtHeaderBytes || rgfxVtBe32(message) < kRgfxVtHeaderBytes || + rgfxVtBe32(message + 4) != rgfxVtFourCc("vtpv")) + return kRgfxVtUnreadable; + if (rgfxVtBe32(message + kRgfxVtTypeAt) == rgfxVtFourCc("Bye!")) + return kRgfxVtByeAll; + memcpy(uuid, message + kRgfxVtUuidAt, kRgfxVtUuidBytes); + return kRgfxVtForUuid; +} + +// The `-uui` the kext sends the host as a client lets go of `uuid`, as Apple's kext writes it: +// a bare 48-byte `vtpv` header with no flags, the UUID, and no reply. +static inline void rgfxVtForgetMessage(uint8_t out[kRgfxVtHeaderBytes], + const uint8_t uuid[kRgfxVtUuidBytes]) +{ + static const uint8_t head[16] = {0, 0, 0, 48, 'v', 't', 'p', 'v', '-', 'u', 'u', 'i'}; + memset(out, 0, kRgfxVtHeaderBytes); + memcpy(out, head, sizeof(head)); + memcpy(out + kRgfxVtUuidAt, uuid, kRgfxVtUuidBytes); +} + +// The service's routes: each UUID a client registered, with the client, in the order registered. +// A client is any pointer; the table never follows one. +struct RgfxVtRoutes { + struct Route { + uint8_t uuid[kRgfxVtUuidBytes]; + const void *client; + }; + Route routes[kRgfxVtRoutesMax]; + uint32_t count; + + // Registers `uuid` for `client`, again where it holds it already, as Apple's kext does; false + // where the table is full. + bool add(const uint8_t uuid[kRgfxVtUuidBytes], const void *client) + { + if (count == kRgfxVtRoutesMax) + return false; + memcpy(routes[count].uuid, uuid, kRgfxVtUuidBytes); + routes[count].client = client; + count++; + return true; + } + + // Deregisters every registration of `uuid` for `client`: whether it held one, for the kext to + // send the host `-uui`. + bool remove(const uint8_t uuid[kRgfxVtUuidBytes], const void *client) + { + uint32_t kept = 0; + bool removed = false; + for (uint32_t i = 0; i < count; i++) { + if (routes[i].client == client && !memcmp(routes[i].uuid, uuid, kRgfxVtUuidBytes)) { + removed = true; + continue; + } + routes[kept++] = routes[i]; + } + count = kept; + return removed; + } + + // Deregisters each UUID `client` registered, and writes them, each once, in the order + // registered, into `out`, at most `max`: how many it wrote. + uint32_t removeClient(const void *client, uint8_t (*out)[kRgfxVtUuidBytes], uint32_t max) + { + uint32_t kept = 0, written = 0; + for (uint32_t i = 0; i < count; i++) { + if (routes[i].client != client) { + routes[kept++] = routes[i]; + continue; + } + bool seen = false; + for (uint32_t w = 0; w < written && !seen; w++) + seen = !memcmp(out[w], routes[i].uuid, kRgfxVtUuidBytes); + if (!seen && written < max) + memcpy(out[written++], routes[i].uuid, kRgfxVtUuidBytes); + } + count = kept; + return written; + } + + // The clients that registered `uuid`, each once, into `out`, at most `max`: how many. + uint32_t clientsOf(const uint8_t uuid[kRgfxVtUuidBytes], const void **out, uint32_t max) const + { + uint32_t n = 0; + for (uint32_t i = 0; i < count && n < max; i++) { + if (memcmp(routes[i].uuid, uuid, kRgfxVtUuidBytes)) + continue; + bool seen = false; + for (uint32_t c = 0; c < n && !seen; c++) + seen = out[c] == routes[i].client; + if (!seen) + out[n++] = routes[i].client; + } + return n; + } +}; + +// The runs of the first `length` bytes of a buffer whose runs are `runs` (`count` of them), into +// `out`, at most `max`: how many, 0 where they do not hold `length` bytes or do not fit. +static inline uint32_t rgfxVtMessageRuns(const RgfxPageRun *runs, uint32_t count, uint64_t length, + RgfxPageRun *out, uint32_t max) +{ + uint32_t n = 0; + for (uint32_t i = 0; i < count && length; i++) { + if (n == max) + return 0; + const uint64_t take = runs[i].length < length ? runs[i].length : length; + out[n++] = {runs[i].address, take}; + length -= take; + } + return length ? 0 : n; +} + +// Whether `caps` lists a decoder for the service to serve: a decode entry of H.264 or HEVC with a +// profile, in caps of the version the kext reads. False for an older host's caps and for a host +// with no video arm, which writes none. +static inline bool rgfxVtServesDecoders(const RgfxVideoCaps &caps) +{ + if (caps.version < RGFX_VIDEO_CAPS_VERSION) + return false; + const uint32_t n = caps.codec_count < RGFX_VIDEO_CAPS_CODECS ? caps.codec_count + : RGFX_VIDEO_CAPS_CODECS; + for (uint32_t i = 0; i < n; i++) { + const RgfxVideoCodecCaps &c = caps.codecs[i]; + if (c.direction == RGFX_VIDEO_DECODE && c.profiles != 0 && + (c.codec == RGFX_VIDEO_CODEC_H264 || c.codec == RGFX_VIDEO_CODEC_HEVC)) + return true; + } + return false; +} + +#endif // RGFX_VT_ROUTES_HPP_ diff --git a/guest/kext/src/RgfxVtService.cpp b/guest/kext/src/RgfxVtService.cpp new file mode 100644 index 000000000..8e8f1cfb7 --- /dev/null +++ b/guest/kext/src/RgfxVtService.cpp @@ -0,0 +1,617 @@ +/* + * RgfxVtService: see RgfxVtService.hpp. The arm64e kext's VideoToolbox service, its user client, + * and display 0's framebuffer's side of it: the service's start and stop, and the VT_MESSAGE + * events it routes. + */ + +#include "RgfxVtService.hpp" + +#include "ReimsGraphics.hpp" +#include "RgfxSurfaceBlocks.hpp" +#include "RgfxTrace.hpp" + +#include + +namespace { +// How long a send waits for its VT_STATUS: the host answers once its side took the message. +constexpr UInt32 kRgfxVtAnswerMs = 10000; +// The status the framework's guest side answers a message it cannot send, kVTParameterErr. +constexpr int32_t kRgfxVtParameterErr = -12902; +// The selectors (RgfxVtService.hpp). +enum : uint32_t { + kVtSizeBuffer = 0, + kVtRegisterUuid = 1, + kVtDeregisterUuid = 2, + kVtSend = 3, + kVtReadyForMessages = 4, +}; +// The most scalars a send takes: its length and five IOSurface IDs. +constexpr uint32_t kVtSendScalarsMax = 1 + RGFX_VT_MESSAGE_SURFACES; +} // namespace + +// MARK: - The service + +#define super IOService +OSDefineMetaClassAndStructors(AppleVideoToolboxParavirtualizationDriver, IOService); + +AppleVideoToolboxParavirtualizationDriver * +AppleVideoToolboxParavirtualizationDriver::withFramebuffer(ReimsGraphics *fb) +{ + AppleVideoToolboxParavirtualizationDriver *service = + OSTypeAlloc(AppleVideoToolboxParavirtualizationDriver); + if (!service) + return nullptr; + service->fb = nullptr; + service->lock = nullptr; + service->routes = nullptr; + service->forgetBuffer = nullptr; + service->forgetRun = {}; + service->forgetLock = nullptr; + service->delivered = nullptr; + if (!service->init(nullptr) || !service->attach(fb)) { + service->release(); + return nullptr; + } + if (!service->start(fb)) { + service->detach(fb); + service->release(); + return nullptr; + } + service->registerService(); + return service; +} + +bool AppleVideoToolboxParavirtualizationDriver::start(IOService *provider) +{ + ReimsGraphics *owner = OSDynamicCast(ReimsGraphics, provider); + if (!owner || !super::start(provider)) + return false; + owner->retain(); + fb = owner; + lock = IOLockAlloc(); + forgetLock = IOLockAlloc(); + routes = static_cast(IOMalloc(sizeof(RgfxVtRoutes))); + if (routes) + bzero(routes, sizeof(RgfxVtRoutes)); + delivered = static_cast(IOMalloc(RGFX_VT_HOST_MESSAGE_MAX)); + // The page of the kext's own `-uui`s, in one run of guest RAM. + forgetBuffer = IOBufferMemoryDescriptor::withOptions( + kIODirectionInOut | kIOMemoryPhysicallyContiguous, PAGE_SIZE, PAGE_SIZE); + if (forgetBuffer && forgetBuffer->prepare() == kIOReturnSuccess) { + IOByteCount segment = 0; + forgetRun = {forgetBuffer->getPhysicalSegment(0, &segment, kIOMemoryMapperNone), + kRgfxVtHeaderBytes}; + } else { + OSSafeReleaseNULL(forgetBuffer); + } + if (!lock || !forgetLock || !routes || !delivered || !forgetBuffer || !forgetRun.address) { + IOLog("RgfxVtService: no memory for the VideoToolbox service\n"); + super::stop(provider); + return false; + } + IOLog("RgfxVtService: the guest's VideoToolbox finds the host's decoders here\n"); + return true; +} + +void AppleVideoToolboxParavirtualizationDriver::stop(IOService *provider) +{ + super::stop(provider); +} + +void AppleVideoToolboxParavirtualizationDriver::free() +{ + if (forgetBuffer) { + forgetBuffer->complete(); + forgetBuffer->release(); + forgetBuffer = nullptr; + } + if (routes) + IOFree(routes, sizeof(RgfxVtRoutes)); + routes = nullptr; + if (delivered) + IOFree(delivered, RGFX_VT_HOST_MESSAGE_MAX); + delivered = nullptr; + if (lock) + IOLockFree(lock); + lock = nullptr; + if (forgetLock) + IOLockFree(forgetLock); + forgetLock = nullptr; + OSSafeReleaseNULL(fb); + super::free(); +} + +IOReturn AppleVideoToolboxParavirtualizationDriver::newUserClient(task_t owningTask, + void *securityID, UInt32 type, + OSDictionary *properties, + IOUserClient **handler) +{ + if (type != 0 || !handler) + return kIOReturnBadArgument; + RgfxVtUserClient *client = OSTypeAlloc(RgfxVtUserClient); + if (!client) + return kIOReturnNoMemory; + if (!client->initWithTask(owningTask, securityID, type, properties)) { + client->release(); + return kIOReturnNoMemory; + } + if (!client->attach(this)) { + client->release(); + return kIOReturnInternalError; + } + if (!client->start(this)) { + client->detach(this); + client->release(); + return kIOReturnInternalError; + } + *handler = client; + return kIOReturnSuccess; +} + +bool AppleVideoToolboxParavirtualizationDriver::registerUuid(const RgfxVtUserClient *client, + const uint8_t *uuid) +{ + IOLockLock(lock); + const bool added = routes->add(uuid, client); + IOLockUnlock(lock); + return added; +} + +void AppleVideoToolboxParavirtualizationDriver::deregisterUuid(const RgfxVtUserClient *client, + const uint8_t *uuid) +{ + IOLockLock(lock); + const bool removed = routes->remove(uuid, client); + IOLockUnlock(lock); + if (removed) + sendForget(uuid); +} + +void AppleVideoToolboxParavirtualizationDriver::deregisterAll(const RgfxVtUserClient *client) +{ + uint8_t(*held)[kRgfxVtUuidBytes] = static_cast( + IOMalloc(kRgfxVtRoutesMax * kRgfxVtUuidBytes)); + if (!held) + return; + IOLockLock(lock); + const uint32_t n = routes->removeClient(client, held, kRgfxVtRoutesMax); + IOLockUnlock(lock); + for (uint32_t i = 0; i < n; i++) + sendForget(held[i]); + IOFree(held, kRgfxVtRoutesMax * kRgfxVtUuidBytes); +} + +void AppleVideoToolboxParavirtualizationDriver::sendForget(const uint8_t *uuid) +{ + IOLockLock(forgetLock); + rgfxVtForgetMessage(static_cast(forgetBuffer->getBytesNoCopy()), uuid); + int32_t status = 0; + const IOReturn r = send(&forgetRun, 1, kRgfxVtHeaderBytes, &status); + IOLockUnlock(forgetLock); + static char unsent; + if ((r != kIOReturnSuccess || status != 0) && rgfxFirstCalls(&unsent, 0, 1)) + IOLog("RgfxVtService: a session's -uui: 0x%x, status %d\n", r, status); +} + +IOReturn AppleVideoToolboxParavirtualizationDriver::send(const RgfxPageRun *runs, uint32_t count, + uint64_t length, int32_t *status) +{ + *status = kRgfxVtParameterErr; + const uint32_t size = RGFX_VT_MESSAGE_RUNS_OFFSET + count * sizeof(RgfxPageRun); + if (count == 0 || size > ReimsGraphics::kLifecycleMessageMax) + return kIOReturnNoSpace; + uint8_t *message = static_cast(IOMalloc(size)); + if (!message) + return kIOReturnNoMemory; + bzero(message, size); + RgfxVtMessage head = {}; + head.length = length; + head.run_count = count; + memcpy(message, &head, sizeof(head)); + memcpy(message + RGFX_VT_MESSAGE_RUNS_OFFSET, runs, count * sizeof(RgfxPageRun)); + UInt8 reply[ReimsGraphics::kLifecycleReplyMax]; + UInt32 replied = 0; + IOReturn r = fb->postLifecycle(RGFX_CMD_VT_MESSAGE, message, size, RGFX_EVT_VT_STATUS, reply, + sizeof(reply), &replied, nullptr, kRgfxVtAnswerMs); + IOFree(message, size); + if (r == kIOReturnSuccess && replied >= sizeof(RgfxVtStatus)) { + RgfxVtStatus answer; + memcpy(&answer, reply, sizeof(answer)); + *status = answer.status; + } else if (r == kIOReturnSuccess) { + r = kIOReturnUnderrun; + } + return r; +} + +void AppleVideoToolboxParavirtualizationDriver::deliver(const volatile uint8_t *message, + uint32_t length) +{ + if (length > RGFX_VT_HOST_MESSAGE_MAX) + return; + for (uint32_t i = 0; i < length; i++) + delivered[i] = message[i]; + uint8_t uuid[kRgfxVtUuidBytes]; + const RgfxVtHostKind kind = rgfxVtHostMessage(delivered, length, uuid); + if (kind == kRgfxVtReleases || kind == kRgfxVtUnreadable) { + static char dropped; + if (rgfxFirstCalls(&dropped, kind, 1)) + IOLog("RgfxVtService: a host message of %u bytes goes to no client (%s)\n", length, + kind == kRgfxVtReleases ? "rels" : "unreadable"); + return; + } + if (kind == kRgfxVtForUuid) { + const void *clients[kRgfxVtRoutesMax]; + IOLockLock(lock); + const uint32_t n = routes->clientsOf(uuid, clients, kRgfxVtRoutesMax); + for (uint32_t i = 0; i < n; i++) + static_cast(clients[i])->retain(); + IOLockUnlock(lock); + for (uint32_t i = 0; i < n; i++) { + RgfxVtUserClient *client = + const_cast(static_cast(clients[i])); + client->deliver(delivered, length); + client->release(); + } + return; + } + // A `Bye!`: to each client once for each UUID it registered, that UUID written in. + RgfxVtRoutes::Route *all = static_cast( + IOMalloc(sizeof(RgfxVtRoutes::Route) * kRgfxVtRoutesMax)); + if (!all) + return; + IOLockLock(lock); + const uint32_t n = routes->count; + memcpy(all, routes->routes, sizeof(RgfxVtRoutes::Route) * n); + for (uint32_t i = 0; i < n; i++) + static_cast(all[i].client)->retain(); + IOLockUnlock(lock); + for (uint32_t i = 0; i < n; i++) { + RgfxVtUserClient *client = + const_cast(static_cast(all[i].client)); + memcpy(delivered + kRgfxVtUuidAt, all[i].uuid, kRgfxVtUuidBytes); + client->deliver(delivered, length); + client->release(); + } + IOFree(all, sizeof(RgfxVtRoutes::Route) * kRgfxVtRoutesMax); +} + +#undef super + +// MARK: - The user client + +#define super IOUserClient +OSDefineMetaClassAndStructors(RgfxVtUserClient, IOUserClient); + +bool RgfxVtUserClient::initWithTask(task_t owningTask, void *securityID, UInt32 type, + OSDictionary *properties) +{ + task = owningTask; + service = nullptr; + buffer = nullptr; + bufferMap = nullptr; + capacity = 0; + runs = nullptr; + runCount = 0; + runCapacity = 0; + queue = nullptr; + queueMap = nullptr; + portSet = false; + kept = nullptr; + gone = false; + lock = nullptr; + sendLock = nullptr; + if (!super::initWithTask(owningTask, securityID, type, properties)) + return false; + lock = IOLockAlloc(); + sendLock = IOLockAlloc(); + kept = OSArray::withCapacity(4); + queue = IOSharedDataQueue::withCapacity(kRgfxVtQueueBytes); + if (!lock || !sendLock || !kept || !queue) + return false; + // The queue's memory, mapped into the process, which dequeues from it. + IOMemoryDescriptor *memory = queue->getMemoryDescriptor(); + if (memory) { + queueMap = memory->createMappingInTask(owningTask, 0, kIOMapAnywhere); + memory->release(); + } + return queueMap != nullptr; +} + +bool RgfxVtUserClient::start(IOService *provider) +{ + AppleVideoToolboxParavirtualizationDriver *owner = + OSDynamicCast(AppleVideoToolboxParavirtualizationDriver, provider); + if (!owner || !super::start(provider)) + return false; + owner->retain(); + service = owner; + return true; +} + +void RgfxVtUserClient::letGo() +{ + IOLockLock(lock); + const bool first = !gone; + gone = true; + IOLockUnlock(lock); + if (first && service) + service->deregisterAll(this); +} + +IOReturn RgfxVtUserClient::clientClose() +{ + letGo(); + if (!isInactive()) + terminate(); + return kIOReturnSuccess; +} + +IOReturn RgfxVtUserClient::clientDied() +{ + return clientClose(); +} + +void RgfxVtUserClient::free() +{ + if (lock) + letGo(); + OSSafeReleaseNULL(queueMap); + OSSafeReleaseNULL(queue); + OSSafeReleaseNULL(bufferMap); + if (buffer) { + buffer->complete(); + buffer->release(); + buffer = nullptr; + } + if (runs) + IOFree(runs, runCapacity * sizeof(RgfxPageRun)); + runs = nullptr; + OSSafeReleaseNULL(kept); + OSSafeReleaseNULL(service); + if (lock) + IOLockFree(lock); + lock = nullptr; + if (sendLock) + IOLockFree(sendLock); + sendLock = nullptr; + super::free(); +} + +IOReturn RgfxVtUserClient::registerNotificationPort(mach_port_t port, UInt32 type, + io_user_reference_t refCon) +{ + if (type != 0) + return kIOReturnUnsupported; + IOLockLock(lock); + const bool set = portSet; + if (!set) { + portSet = true; + queue->setNotificationPort(port); + } + IOLockUnlock(lock); + return set ? kIOReturnBadArgument : kIOReturnSuccess; +} + +IOReturn RgfxVtUserClient::externalMethod(uint32_t selector, IOExternalMethodArguments *a, + IOExternalMethodDispatch *dispatch, OSObject *target, + void *reference) +{ + if (!a || !service) + return kIOReturnBadArgument; + switch (selector) { + case kVtSizeBuffer: + if (a->scalarInputCount != 1 || a->scalarOutputCount < 3) + return kIOReturnBadArgument; + return sizeBuffer(a); + case kVtRegisterUuid: + case kVtDeregisterUuid: { + if (a->structureInputSize != kRgfxVtUuidBytes || !a->structureInput) + return kIOReturnBadArgument; + const uint8_t *uuid = static_cast(a->structureInput); + if (selector == kVtDeregisterUuid) { + service->deregisterUuid(this, uuid); + return kIOReturnSuccess; + } + return service->registerUuid(this, uuid) ? kIOReturnSuccess : kIOReturnNoResources; + } + case kVtSend: + if (a->scalarInputCount < 1 || a->scalarInputCount > kVtSendScalarsMax || + a->scalarOutputCount < 1) + return kIOReturnBadArgument; + return sendMessage(a); + case kVtReadyForMessages: + IOLockLock(lock); + deliverKept(); + IOLockUnlock(lock); + return kIOReturnSuccess; + default: + return kIOReturnBadArgument; + } +} + +// Selector 0: the message buffer, of at least the size asked, wired and shared with the process, +// and its runs of guest RAM, which a send's VT_MESSAGE names. +IOReturn RgfxVtUserClient::sizeBuffer(IOExternalMethodArguments *a) +{ + const uint64_t asked = a->scalarInput[0]; + if (asked > RGFX_VT_MESSAGE_MAX) { + IOLog("RgfxVtService: a message buffer of %llu bytes is more than the %u it holds\n", + asked, static_cast(RGFX_VT_MESSAGE_MAX)); + return kIOReturnBadArgument; + } + IOLockLock(sendLock); + IOReturn r = kIOReturnSuccess; + if (asked > capacity || !buffer) { + const uint64_t bytes = (asked + PAGE_SIZE - 1) & ~static_cast(PAGE_SIZE - 1); + IOBufferMemoryDescriptor *made = IOBufferMemoryDescriptor::inTaskWithOptions( + kernel_task, kIODirectionInOut | kIOMemoryKernelUserShared, bytes ? bytes : PAGE_SIZE, + PAGE_SIZE); + IOMemoryMap *mapped = nullptr; + const uint32_t most = static_cast((bytes ? bytes : PAGE_SIZE) / PAGE_SIZE); + RgfxPageRun *walked = static_cast(IOMalloc(most * sizeof(RgfxPageRun))); + uint32_t n = 0; + bool ok = made && walked && made->prepare() == kIOReturnSuccess; + const bool prepared = ok; + if (ok) + mapped = made->createMappingInTask(task, 0, kIOMapAnywhere); + ok = ok && mapped; + for (uint64_t at = 0; ok && at < made->getLength();) { + IOByteCount segment = 0; + const addr64_t phys = made->getPhysicalSegment(at, &segment, kIOMemoryMapperNone); + ok = phys && segment && rgfxSurfaceAppendRun(walked, &n, most, phys, segment); + at += segment; + } + if (!ok) { + OSSafeReleaseNULL(mapped); + if (made && prepared) + made->complete(); + OSSafeReleaseNULL(made); + if (walked) + IOFree(walked, most * sizeof(RgfxPageRun)); + r = kIOReturnNoMemory; + } else { + OSSafeReleaseNULL(bufferMap); + if (buffer) { + buffer->complete(); + buffer->release(); + } + if (runs) + IOFree(runs, runCapacity * sizeof(RgfxPageRun)); + buffer = made; + bufferMap = mapped; + runs = walked; + runCount = n; + runCapacity = most; + capacity = asked; + } + } + if (r == kIOReturnSuccess) { + a->scalarOutput[0] = capacity; + a->scalarOutput[1] = bufferMap->getAddress(); + a->scalarOutput[2] = queueMap->getAddress(); + a->scalarOutputCount = 3; + } + IOLockUnlock(sendLock); + return r; +} + +// Selector 3: the buffer's first `length` bytes to the host, and its status back. +IOReturn RgfxVtUserClient::sendMessage(IOExternalMethodArguments *a) +{ + const uint64_t length = a->scalarInput[0]; + int32_t status = kRgfxVtParameterErr; + IOReturn r = kIOReturnSuccess; + bool surfaces = false; + for (uint32_t i = 1; i < a->scalarInputCount; i++) + surfaces = surfaces || a->scalarInput[i] != 0; + if (surfaces) { + static char lent; + if (rgfxFirstCalls(&lent, 0, 1)) + IOLog("RgfxVtService: a message that lends a surface is not sent: the host takes " + "none yet\n"); + } else { + IOLockLock(sendLock); + if (!buffer || length > capacity) { + r = kIOReturnBadArgument; + } else { + RgfxPageRun *message = + static_cast(IOMalloc(runCapacity * sizeof(RgfxPageRun))); + const uint32_t n = + message ? rgfxVtMessageRuns(runs, runCount, length, message, runCapacity) : 0; + r = n ? service->send(message, n, length, &status) : kIOReturnNoMemory; + if (message) + IOFree(message, runCapacity * sizeof(RgfxPageRun)); + } + IOLockUnlock(sendLock); + } + a->scalarOutput[0] = static_cast(static_cast(status)); + a->scalarOutputCount = 1; + return r != kIOReturnSuccess ? r : static_cast(status); +} + +void RgfxVtUserClient::deliver(const uint8_t *message, uint32_t length) +{ + IOLockLock(lock); + if (!gone) { + const bool queued = kept->getCount() == 0 && + queue->enqueue(const_cast(message), length); + if (!queued && kept->getCount() < kRgfxVtPendingMax) { + if (OSData *copy = OSData::withBytes(message, length)) { + kept->setObject(copy); + copy->release(); + } + } else if (!queued) { + static char full; + if (rgfxFirstCalls(&full, 0, 1)) + IOLog("RgfxVtService: a client keeps %u host messages already: one dropped\n", + kRgfxVtPendingMax); + } + } + IOLockUnlock(lock); +} + +void RgfxVtUserClient::deliverKept() +{ + while (kept->getCount()) { + OSData *first = OSDynamicCast(OSData, kept->getObject(0)); + if (first && !queue->enqueue(const_cast(first->getBytesNoCopy()), + first->getLength())) + break; + kept->removeObject(0); + } +} + +#undef super + +// MARK: - Display 0's framebuffer's side + +void ReimsGraphics::startVtService() +{ + if (!vtMessagesTaken || __atomic_load_n(&vtService, __ATOMIC_ACQUIRE)) + return; + RgfxVideoCaps caps; + volatile const UInt8 *at = ring(RGFX_VIDEO_CAPS_OFFSET); + UInt8 *to = reinterpret_cast(&caps); + for (UInt32 i = 0; i < sizeof(caps); i++) + to[i] = at[i]; + if (!rgfxVtServesDecoders(caps)) { + IOLog("ReimsGraphics: the host decodes no video: no VideoToolbox service\n"); + return; + } + AppleVideoToolboxParavirtualizationDriver *made = + AppleVideoToolboxParavirtualizationDriver::withFramebuffer(this); + if (!made) { + IOLog("ReimsGraphics: the VideoToolbox service did not start\n"); + return; + } + __atomic_store_n(&vtService, made, __ATOMIC_RELEASE); +} + +void ReimsGraphics::stopVtService() +{ + AppleVideoToolboxParavirtualizationDriver *service = + __atomic_exchange_n(&vtService, nullptr, __ATOMIC_ACQ_REL); + if (!service) + return; + service->terminate(); + service->release(); +} + +void ReimsGraphics::vtMessage(const volatile UInt8 *payload, UInt32 size) +{ + // The event's length and its padding word, then its bytes. + constexpr UInt32 kBytesAt = RGFX_VT_HOST_MESSAGE_BYTES_OFFSET - sizeof(RgfxMsgHeader); + AppleVideoToolboxParavirtualizationDriver *service = + __atomic_load_n(&vtService, __ATOMIC_ACQUIRE); + const UInt32 length = size >= kBytesAt ? *reinterpret_cast(payload) + : 0; + if (!service || size < kBytesAt || length > size - kBytesAt) { + static char unread; + if (rgfxFirstCalls(&unread, size, 1)) + IOLog("ReimsGraphics: a VT_MESSAGE of %u bytes goes nowhere%s\n", size, + service ? "" : " (no VideoToolbox service is up)"); + return; + } + service->deliver(payload + kBytesAt, length); +} diff --git a/guest/kext/src/RgfxVtService.hpp b/guest/kext/src/RgfxVtService.hpp new file mode 100644 index 000000000..8b9b20e2d --- /dev/null +++ b/guest/kext/src/RgfxVtService.hpp @@ -0,0 +1,138 @@ +/* + * RgfxVtService: the arm64e kext's VideoToolbox service (design.md, "Decided", 17), of the class + * an arm64 guest's VideoToolboxParavirtualizationSupport looks for, + * AppleVideoToolboxParavirtualizationDriver: where it finds one and opens it, the guest's + * VideoToolbox counts itself as running in a guest and sends its host side `vtpv` messages, which + * the service carries to the device as VT_MESSAGEs. It is a child of display 0's framebuffer, + * published by it where the guest took VT_MESSAGES and the host's caps list a decoder, and + * stopped with it. + * + * Its user client, RgfxVtUserClient, answers the framework's five selectors as Apple's kext of + * the class does (AppleVideoToolboxParavirtualization.kext 15.0.0, read from the macOS 27.2.1 + * arm64e VM kernel collection; RgfxVtRoutes.hpp): + * - 0, one scalar in, three out: sizes the client's message buffer to at least the size asked, + * at most RGFX_VT_MESSAGE_MAX, and answers its capacity and the process's addresses of the + * buffer and of its host-message queue, an IOSharedDataQueue of kRgfxVtQueueBytes; + * - 1 and 2, a 16-byte structure in: register and deregister a session UUID for the client; + * - 3, the message's length and up to five IOSurface IDs in, one scalar out: sends the buffer's + * first `length` bytes, and answers the host's status for it, as its output and its return. A + * message that names a surface is answered kVTParameterErr, posting nothing: nothing the host + * answers yet takes one; + * - 4: moves the host messages kept while the queue was full into it. + * Its notification port, type 0, is the queue's. Apple's kext of the class binds only to Apple's + * VM device (106b:1a03), which no VM of ours has, so the two never load together. + * + * Our own code; it names only SDK-public IOKit classes. + */ + +#ifndef RGFX_VT_SERVICE_HPP_ +#define RGFX_VT_SERVICE_HPP_ + +#include +#include +#include +#include +#include + +#include "RgfxVtRoutes.hpp" + +class ReimsGraphics; +class RgfxVtUserClient; + +class AppleVideoToolboxParavirtualizationDriver : public IOService { + OSDeclareDefaultStructors(AppleVideoToolboxParavirtualizationDriver); + +public: + // The service of display 0's framebuffer `fb`, started and registered; nullptr where it did + // not start. + static AppleVideoToolboxParavirtualizationDriver *withFramebuffer(ReimsGraphics *fb); + + bool start(IOService *provider) override; + void stop(IOService *provider) override; + void free() override; + IOReturn newUserClient(task_t owningTask, void *securityID, UInt32 type, + OSDictionary *properties, IOUserClient **handler) override; + + // Selector 1: `uuid` registered for `client`; false where the routes are full. + bool registerUuid(const RgfxVtUserClient *client, const uint8_t *uuid); + // Selector 2: every registration of `uuid` for `client` let go of, and the host sent `-uui` + // of it where there was one. + void deregisterUuid(const RgfxVtUserClient *client, const uint8_t *uuid); + // A client's close: each UUID it registered let go of, and the host sent `-uui` of each. + void deregisterAll(const RgfxVtUserClient *client); + // Sends the message of `length` bytes in the guest RAM runs `runs` (`count` of them) as a + // VT_MESSAGE, and waits for its VT_STATUS, its status into *status. Thread context only. + IOReturn send(const RgfxPageRun *runs, uint32_t count, uint64_t length, int32_t *status); + // handleEvent's VT_MESSAGE, on the device's work loop: the `length` bytes of the host's + // message, to the clients RgfxVtRoutes.hpp routes it to. + void deliver(const volatile uint8_t *message, uint32_t length); + +private: + // Sends the host `-uui` of `uuid`, from forgetBuffer. + void sendForget(const uint8_t *uuid); + + // The framebuffer, retained from start until free. + ReimsGraphics *fb; + // Under lock: the routes, IOMalloc'd. + IOLock *lock; + RgfxVtRoutes *routes; + // The page the kext writes its own `-uui`s in, wired, and its run; under forgetLock. + IOBufferMemoryDescriptor *forgetBuffer; + RgfxPageRun forgetRun; + IOLock *forgetLock; + // The work loop's copy of the host message it routes, RGFX_VT_HOST_MESSAGE_MAX bytes. + uint8_t *delivered; +}; + +class RgfxVtUserClient : public IOUserClient { + OSDeclareDefaultStructors(RgfxVtUserClient); + +public: + bool initWithTask(task_t owningTask, void *securityID, UInt32 type, + OSDictionary *properties) override; + bool start(IOService *provider) override; + IOReturn clientClose() override; + IOReturn clientDied() override; + void free() override; + // The queue's port: the 64-bit reference's, which a 64-bit process's + // IOConnectSetNotificationPort reaches, and the 32-bit one's IOUserClient's own. + using IOUserClient::registerNotificationPort; + IOReturn registerNotificationPort(mach_port_t port, UInt32 type, io_user_reference_t refCon) + override; + IOReturn externalMethod(uint32_t selector, IOExternalMethodArguments *arguments, + IOExternalMethodDispatch *dispatch, OSObject *target, + void *reference) override; + // A host message for this client, on the work loop: into its queue, or kept while the queue + // is full or holds kept ones. + void deliver(const uint8_t *message, uint32_t length); + +private: + IOReturn sizeBuffer(IOExternalMethodArguments *a); + IOReturn sendMessage(IOExternalMethodArguments *a); + // Moves the kept messages into the queue while it has room. Under lock. + void deliverKept(); + // Lets go of the service's routes, once. + void letGo(); + + task_t task; + // The service, retained from start until free. + AppleVideoToolboxParavirtualizationDriver *service; + // Under lock: the message buffer, its capacity, its process mapping and its runs; the queue, + // its process mapping and its port; the kept messages; and whether the client let go. + IOLock *lock; + IOBufferMemoryDescriptor *buffer; + IOMemoryMap *bufferMap; + uint64_t capacity; + RgfxPageRun *runs; + uint32_t runCount; + uint32_t runCapacity; + IOSharedDataQueue *queue; + IOMemoryMap *queueMap; + bool portSet; + OSArray *kept; + bool gone; + // Serializes the client's sends, which share its buffer. + IOLock *sendLock; +}; + +#endif // RGFX_VT_SERVICE_HPP_ diff --git a/guest/kext/tests/features_test.cpp b/guest/kext/tests/features_test.cpp index 16d7a38b3..aaa6daf8c 100644 --- a/guest/kext/tests/features_test.cpp +++ b/guest/kext/tests/features_test.cpp @@ -92,6 +92,12 @@ constexpr uint64_t kDisplayBounds = RGFX_FEATURE_DISPLAY_BOUNDS; constexpr uint64_t kDisplayBoundsCarried = kDisplayBounds; // POINTER_MOTION, which both kexts carry, publishing the guest's own mouse for it. constexpr uint64_t kPointerMotion = RGFX_FEATURE_POINTER_MOTION; +// VT_MESSAGES, which the arm64e kext carries, publishing the VideoToolbox service for it, and +// the x86-64 kext does not. +constexpr uint64_t kVtMessages = RGFX_FEATURE_VT_MESSAGES; +constexpr uint64_t kVtMessagesCarried = RGFX_GUEST_ARM64 ? kVtMessages : 0; +// A bit the wire does not name. +constexpr uint64_t kUnnamed = 1ull << 53; // Every bit the wire names from bit 3 that the kext does not carry out yet. constexpr uint64_t kNotCarried = RGFX_FEATURE_QUIET_SCHEDULED | RGFX_FEATURE_CONSUMED_DOORBELL | RGFX_FEATURE_QUEUE_BARRIER | RGFX_FEATURE_CB_PARTS | @@ -99,7 +105,8 @@ constexpr uint64_t kNotCarried = RGFX_FEATURE_QUIET_SCHEDULED | RGFX_FEATURE_CON (kDisplayPower & ~kDisplayPowerCarried) | (kMultiDisplay & ~kMultiDisplayCarried) | (kPointerOver & ~kPointerOverCarried) | - (kDisplayBounds & ~kDisplayBoundsCarried); + (kDisplayBounds & ~kDisplayBoundsCarried) | + (kVtMessages & ~kVtMessagesCarried); // The ones it does: the bundle lays no-copy buffers over pages blocks the kext makes, orders its // command buffers over IOSurfaces and places its Managed buffers' CPU copies in its heaps, neither // of which needs anything of the kext, makes indirect command buffers, whose creates and writes, @@ -174,7 +181,7 @@ constexpr uint64_t kCarried = kPages | kOrder | kIcb | kUnshared | kManaged | kH kSlotsInPages | kDoorbellAsks | kGuestTimes | kReadOnlyPages | kDoorbellPages | kPipelineAnswers | kDisplayPowerCarried | kMultiDisplayCarried | kPointerOverCarried | kDisplayBoundsCarried | - kPointerMotion | k16KCarried; + kPointerMotion | k16KCarried | kVtMessagesCarried; // Every bit the wire names from bit 3. constexpr uint64_t kNew = kNotCarried | kCarried; } // namespace @@ -190,7 +197,8 @@ int main() // TEXTURE_DID_MODIFY_DATA, RATE_MAPS, FUNCTION_POINTERS, DYNAMIC_LIBRARIES, PIPELINE_KEYS, // ICB_SLOTS_IN_PAGES, DOORBELL_ASKS, GUEST_TIMES, READ_ONLY_PAGES, DOORBELL_PAGES, // PIPELINE_ANSWERS, POINTER_MOTION, MULTI_DISPLAY, POINTER_OVER, DISPLAY_BOUNDS and, the x86-64 - // kext, DISPLAY_POWER, and writes each only where offered. + // kext, DISPLAY_POWER, or, the arm64e kext, PAGES_16K and VT_MESSAGES, and writes each only + // where offered. check(kRgfxCarriedFeatures == kCarried, "the kext takes PAGES_BUFFERS, SURFACE_ORDER, ICBs, UNSHARED_QUEUES, MANAGED_AT_OFFSET, " "HEAP_OVER_PAGES, SUBMIT_ROOM, ICB slots, COMMIT_ORDER, SURFACE_DEFERRED, HOST_TIME, " @@ -200,7 +208,8 @@ int main() "DISPLAY_SCALE, TEXTURE_DID_MODIFY_DATA, RATE_MAPS, FUNCTION_POINTERS, DYNAMIC_LIBRARIES, " "PIPELINE_KEYS, ICB_SLOTS_IN_PAGES, DOORBELL_ASKS, GUEST_TIMES, READ_ONLY_PAGES, " "DOORBELL_PAGES, PIPELINE_ANSWERS, POINTER_MOTION, MULTI_DISPLAY, POINTER_OVER, " - "DISPLAY_BOUNDS and, on x86-64, DISPLAY_POWER from bit 3"); + "DISPLAY_BOUNDS and, on x86-64, DISPLAY_POWER, on arm64e PAGES_16K and VT_MESSAGES, " + "from bit 3"); check(RGFX_FEATURE_PAGES_BUFFERS == (1u << 7), "PAGES_BUFFERS is bit 7"); check(RGFX_FEATURE_SURFACE_ORDER == (1u << 11), "SURFACE_ORDER is bit 11"); check(RGFX_FEATURE_INDIRECT_COMMAND_BUFFERS == (1u << 12), "INDIRECT_COMMAND_BUFFERS is bit 12"); @@ -445,6 +454,10 @@ int main() check(rgfxDriverFeatures(kRgfxOfferedFeatures | kScheduledAsk, 2) == kScheduledAsk, "none of them offered (a device of one display): the word as before"); } + check(RGFX_FEATURE_VT_MESSAGES == (1ull << 52), "VT_MESSAGES is bit 52"); + check(rgfxDriverFeatures(kRgfxOfferedFeatures | kNotCarried | kVtMessages) == + kVtMessagesCarried, + "VT_MESSAGES offered, written by the arm64e kext alone"); // PAGES_16K: the arm64e kext writes it first where offered, and then with the rest; the // x86-64 kext never writes it, and writes nothing first. check(rgfxDriverFeaturesFirst(~0ull) == k16KCarried, "PAGES_16K first where carried"); @@ -455,9 +468,9 @@ int main() check(rgfxFeatureWord(kRgfxOfferedFeatures | k16K, k16K) == (kRgfxOfferedFeatures | k16KCarried), "PAGES_16K taken is in the word where carried"); check(rgfxDriverFeatures(0) == 0, "nothing offered, nothing written"); - check(rgfxDriverFeatures(kRgfxOfferedFeatures | kNotCarried | (1ull << 52)) == 0, + check(rgfxDriverFeatures(kRgfxOfferedFeatures | kNotCarried | kUnnamed) == 0, "every other bit offered, none written"); - check(rgfxDriverFeatures(kRgfxOfferedFeatures | kNew | (1ull << 52)) == kCarried, + check(rgfxDriverFeatures(kRgfxOfferedFeatures | kNew | kUnnamed) == kCarried, "every bit offered, the carried bits written"); check(rgfxDriverFeatures(kRgfxOfferedFeatures | kNotCarried | kPages) == kPages, "PAGES_BUFFERS offered, written"); @@ -498,7 +511,7 @@ int main() "SUBMIT_ROOM offered but not taken is not"); // A read-back of bits the kext never wrote, or of bits 0 to 2 the host does not offer, adds // nothing. - check(rgfxFeatureWord(kRgfxOfferedFeatures, kNotCarried | (1ull << 52)) == + check(rgfxFeatureWord(kRgfxOfferedFeatures, kNotCarried | kUnnamed) == kRgfxOfferedFeatures, "taken bits the kext does not carry out are dropped"); check(rgfxFeatureWord(kRgfxOfferedFeatures | kNew, kNew) == (kRgfxOfferedFeatures | kCarried), diff --git a/guest/kext/tests/vt_routes_test.cpp b/guest/kext/tests/vt_routes_test.cpp new file mode 100644 index 000000000..a3a5514bc --- /dev/null +++ b/guest/kext/tests/vt_routes_test.cpp @@ -0,0 +1,138 @@ +// The native test of RgfxVtRoutes.hpp: which clients a host message goes to, the `-uui` the kext +// sends as a client lets go of a UUID, the runs a message of a client's buffer lies in, and +// whether the caps list a decoder for the VideoToolbox service to serve. +#include "RgfxVtRoutes.hpp" + +#include +#include +#include + +namespace { +int checks = 0; + +void check(bool ok, const char *what) +{ + checks++; + if (!ok) { + std::fprintf(stderr, "vt_routes_test: FAILED: %s\n", what); + std::exit(1); + } +} + +// A `vtpv` header of `type` for `uuid`. +void header(uint8_t out[kRgfxVtHeaderBytes], const char (&type)[5], uint8_t uuid) +{ + std::memset(out, 0, kRgfxVtHeaderBytes); + const uint8_t head[8] = {0, 0, 0, 48, 'v', 't', 'p', 'v'}; + std::memcpy(out, head, sizeof(head)); + std::memcpy(out + 8, type, 4); + std::memset(out + 16, uuid, kRgfxVtUuidBytes); +} +} // namespace + +int main() +{ + static_assert(RGFX_FEATURE_VT_MESSAGES == (1ull << 52), "VT_MESSAGES is bit 52"); + static_assert(RGFX_CMD_VT_MESSAGE == 0x2fa, "VT_MESSAGE is 0x2fa"); + static_assert(RGFX_EVT_VT_STATUS == 0x40d && RGFX_EVT_VT_MESSAGE == 0x40e, + "VT_STATUS and VT_MESSAGE are 0x40d and 0x40e"); + static_assert(sizeof(RgfxVtMessage) == RGFX_VT_MESSAGE_RUNS_OFFSET, "runs follow the struct"); + static_assert(sizeof(RgfxVtHostMessage) == RGFX_VT_HOST_MESSAGE_BYTES_OFFSET, + "bytes follow the struct"); + + // What a host message is: for its UUID, a `Bye!` for all, a `rels` box, or unreadable. + { + uint8_t m[kRgfxVtHeaderBytes]; + uint8_t uuid[kRgfxVtUuidBytes] = {}; + header(m, "decs", 0x5a); + check(rgfxVtHostMessage(m, sizeof(m), uuid) == kRgfxVtForUuid && uuid[0] == 0x5a && + uuid[15] == 0x5a, + "a vtpv message goes to its UUID's clients"); + header(m, "Bye!", 0); + check(rgfxVtHostMessage(m, sizeof(m), uuid) == kRgfxVtByeAll, "a Bye! goes to all"); + check(rgfxVtHostMessage(m, 47, uuid) == kRgfxVtUnreadable, "47 bytes are no header"); + m[3] = 40; + check(rgfxVtHostMessage(m, sizeof(m), uuid) == kRgfxVtUnreadable, + "a header atom under 48 bytes is unreadable"); + const uint8_t rels[16] = {0, 0, 0, 16, 'r', 'e', 'l', 's'}; + check(rgfxVtHostMessage(rels, sizeof(rels), uuid) == kRgfxVtReleases, "a rels box"); + } + + // The `-uui`: Apple's kext's 48 bytes. + { + uint8_t uuid[kRgfxVtUuidBytes]; + std::memset(uuid, 0x11, sizeof(uuid)); + uint8_t m[kRgfxVtHeaderBytes]; + std::memset(m, 0xee, sizeof(m)); + rgfxVtForgetMessage(m, uuid); + uint8_t expected[kRgfxVtHeaderBytes] = {0, 0, 0, 48, 'v', 't', 'p', 'v', '-', 'u', 'u', 'i'}; + std::memset(expected + 16, 0x11, kRgfxVtUuidBytes); + check(!std::memcmp(m, expected, sizeof(m)), "the -uui is a bare header of the UUID"); + } + + // Routes: each UUID's clients once each, a deregistration of a held UUID says so, and a + // client's close lets go of each UUID it held, each once. + { + static RgfxVtRoutes routes; + routes.count = 0; + int a = 0, b = 0; + uint8_t u1[kRgfxVtUuidBytes], u2[kRgfxVtUuidBytes]; + std::memset(u1, 1, sizeof(u1)); + std::memset(u2, 2, sizeof(u2)); + check(routes.add(u1, &a) && routes.add(u1, &a) && routes.add(u1, &b) && routes.add(u2, &a), + "registrations are taken, a repeat too"); + const void *clients[4]; + check(routes.clientsOf(u1, clients, 4) == 2 && clients[0] == &a && clients[1] == &b, + "a UUID's clients, each once, in order"); + check(routes.clientsOf(u2, clients, 4) == 1 && clients[0] == &a, "the other UUID's"); + check(routes.remove(u1, &b) && !routes.remove(u1, &b), + "a held UUID's deregistration says so, an unheld one's does not"); + check(routes.clientsOf(u1, clients, 4) == 1, "the UUID's other client stays"); + uint8_t held[4][kRgfxVtUuidBytes]; + check(routes.removeClient(&a, held, 4) == 2 && held[0][0] == 1 && held[1][0] == 2, + "a close lets go of each UUID once, in order"); + check(routes.count == 0, "no route is left"); + for (uint32_t i = 0; i < kRgfxVtRoutesMax; i++) + routes.add(u1, &a); + check(!routes.add(u1, &b), "a full table takes no more"); + } + + // The runs of a message: the first `length` bytes of the buffer's runs. + { + const RgfxPageRun buffer[2] = {{0x10000, 0x4000}, {0x40000, 0x8000}}; + RgfxPageRun out[2]; + check(rgfxVtMessageRuns(buffer, 2, 48, out, 2) == 1 && out[0].address == 0x10000 && + out[0].length == 48, + "a short message in the first run"); + check(rgfxVtMessageRuns(buffer, 2, 0x5000, out, 2) == 2 && out[1].address == 0x40000 && + out[1].length == 0x1000, + "a longer one into the second"); + check(rgfxVtMessageRuns(buffer, 2, 0xc001, out, 2) == 0, "more than the runs hold"); + check(rgfxVtMessageRuns(buffer, 2, 0x5000, out, 1) == 0, "more runs than fit"); + } + + // The service serves a host whose caps list a decode entry of H.264 or HEVC with a profile. + { + RgfxVideoCaps caps = {}; + check(!rgfxVtServesDecoders(caps), "an older host's caps serve nothing"); + caps.version = RGFX_VIDEO_CAPS_VERSION; + caps.codec_count = 1; + caps.codecs[0].codec = RGFX_VIDEO_CODEC_H264; + caps.codecs[0].direction = RGFX_VIDEO_ENCODE; + caps.codecs[0].profiles = RGFX_VIDEO_H264_HIGH; + check(!rgfxVtServesDecoders(caps), "an encoder alone serves nothing"); + caps.codecs[0].direction = RGFX_VIDEO_DECODE; + check(rgfxVtServesDecoders(caps), "an H.264 decoder is served"); + caps.codecs[0].profiles = 0; + check(!rgfxVtServesDecoders(caps), "a decoder of no profile is not"); + caps.codecs[1] = caps.codecs[0]; + caps.codecs[1].codec = RGFX_VIDEO_CODEC_HEVC; + caps.codecs[1].profiles = RGFX_VIDEO_HEVC_MAIN; + check(!rgfxVtServesDecoders(caps), "an entry past the count is not read"); + caps.codec_count = 2; + check(rgfxVtServesDecoders(caps), "an HEVC decoder is served"); + } + + std::printf("vt_routes_test: %d checks passed\n", checks); + return 0; +}