🆕 Map the guest's Shared pool's blocks into a range the host reserves
metal2vulkan's new runtime allocates the GPU memory the guest's Shared buffers live in, and the device maps those blocks into the guest (plan D2, route 1). This is the host side of that pool: the guest's side, and the wire it reads the range and its pieces from, come with the D2 guest work. The library: a pool per device (crates/reims-vgpu/src/pool.rs) over the range the host reserved. Its thread takes Shared blocks from a block source and asks the host to map each at the lowest free 2 MiB-aligned address (pool_add); the host says when the guest's address space has it (rvg_graphics_device_pool_added). The source's unmap hook takes a piece out of the lookups, waits for every hold on it, asks the host to unmap it (pool_remove) and returns once the host says it is gone (rvg_graphics_device_pool_removed); only then may the source free the block. The pool keeps one empty piece as headroom, asks for a block more when the guest uses the last empty one, and gives back a piece that stayed empty for 5 s above the lowest empty one. The source's calls and hook have metal2vulkan-rt's shape (take_block, release_block, BlockMappings::unmap, BlockInfo); until the device runs on that runtime the source is the process's own memory (HostBlocks), so only the source changes then. The C API: RvgGraphicsDeviceConfig and RvgGraphicsCallbacks go to their fifth version (pool_physical_address and _length; pool_add and pool_remove), with rvg_graphics_device_pool_added, _pool_removed and _pool_grow (the host's ask for more pool now, which QEMU's x-pool-grow property drives). QEMU (vendor/qemu): the device reserves 64 GiB past the RAM and the host bridge's default 64-bit window, raises etc/reserved-memory-end past it so OVMF's 64-bit window goes above it, turns KVM's zap-every-slot quirk off, maps each piece as a RAM region of its own (a pure add) on its main loop, and under WHPX runs the hypervisor's map outside the BQL. Its teardown takes every piece out before the release, which frees the blocks before the process exits. For the guest: the firmware's 64-bit PCI window starts past the reserved range, 32 GiB or more higher than before; nothing else changes until the guest's side maps the pool.
This commit is contained in:
1 parent
b8aa508721
commit
426724ff52
11 files changed
+1705
-8
No files matched your search
@@ -304,6 +304,40 @@ typedef bool (*RvgGraphicsRouteDoorbellPageFn)(void *ctx,
|
||||
uint32_t ring_id,
|
||||
int32_t bell);
|
||||
|
||||
// `pool_add(ctx, physical_address, host_address, length)`: map `length` bytes of host memory
|
||||
// from `host_address` into the guest at `physical_address`, a piece of the guest's Shared pool
|
||||
// (RvgGraphicsDeviceConfig's `pool_physical_address` and `pool_physical_length`, which hold the
|
||||
// piece), and call rvg_graphics_device_pool_added with `physical_address` once the guest's
|
||||
// address space has it (QEMU: a RAM region over the memory, added on its main loop, unmergeable
|
||||
// with its neighbours). The memory stays mapped, and the device asks no other piece over its
|
||||
// addresses, until the host has said the piece is removed (rvg_graphics_device_pool_removed).
|
||||
// `physical_address`, `host_address` and `length` are multiples of 2 MiB, 4 KiB and 2 MiB.
|
||||
//
|
||||
// Thread: the device's pool thread (`reims-vgpu.graphics-pool`), never inside a call of the
|
||||
// host's, with no lock of the library's held. It must not wait for a lock the host holds while
|
||||
// it calls the device (QEMU's BQL): QEMU queues the add for its main loop. One piece at a time,
|
||||
// in the order the device places them, each before its pool_remove. May call: nothing of the
|
||||
// library's. Needed with a pool.
|
||||
typedef void (*RvgGraphicsPoolAddFn)(void *ctx,
|
||||
uint64_t physical_address,
|
||||
void *host_address,
|
||||
uint64_t length);
|
||||
|
||||
// `pool_remove(ctx, physical_address, length)`: unmap the piece of the pool at
|
||||
// `physical_address` that pool_add mapped, and call rvg_graphics_device_pool_removed with
|
||||
// `physical_address` once it is out of the guest's address space and no thread of the host's
|
||||
// touches its memory (QEMU: once its region's last reference goes, past its RCU grace period).
|
||||
// The device frees the memory only after that. A remove of a piece whose add the host has not
|
||||
// carried out yet follows that add: the host carries out the add, then the remove.
|
||||
//
|
||||
// Thread: the one that frees the piece's block (the device's pool thread, or the block source's
|
||||
// own), never inside a call of the host's, with no lock of the library's held. It must not wait
|
||||
// for a lock the host holds while it calls the device (QEMU queues the remove for its main
|
||||
// loop). Once a piece, after its pool_add. Not called once rvg_graphics_device_release has
|
||||
// begun: the host removes every piece it added before it releases the device. May call: nothing
|
||||
// of the library's. Needed with a pool.
|
||||
typedef void (*RvgGraphicsPoolRemoveFn)(void *ctx, uint64_t physical_address, uint64_t length);
|
||||
|
||||
// `cursor_glyph_at(ctx, display, glyph)`: the guest set the cursor's image of display `display`,
|
||||
// 1 or above, or its colour chain (display 0's is cursor_glyph).
|
||||
//
|
||||
@@ -366,6 +400,11 @@ typedef struct {
|
||||
// cursor_move of display 1 and up: rvg_graphics_device_cursor_position_at reads where. A
|
||||
// host built before it gives none.
|
||||
RvgCursorMoveAtFn cursor_move_at;
|
||||
// Maps a piece of the guest's Shared pool. A host built before it, whose `struct_size` ends
|
||||
// before it, gives none, and has no pool.
|
||||
RvgGraphicsPoolAddFn pool_add;
|
||||
// Unmaps a piece of the guest's Shared pool. A host built before it gives none.
|
||||
RvgGraphicsPoolRemoveFn pool_remove;
|
||||
} RvgGraphicsCallbacks;
|
||||
|
||||
// `pointer(ctx, x, y, width, height, buttons)`: the pointer is at (`x`, `y`) in the guest's
|
||||
@@ -600,6 +639,16 @@ typedef struct {
|
||||
// display, missing where `window` is given and it has several, or a NULL entry. A host built
|
||||
// before this field gives none.
|
||||
const RvgWindowConfig *const *display_windows;
|
||||
// The first guest physical address of the range the host reserved for the guest's Shared
|
||||
// pool, with no RAM or device under it, which the device fills with blocks of host memory as
|
||||
// the pool grows (pool_add). 0, with `pool_physical_length` 0, for none, as a host built
|
||||
// before this field, whose `struct_size` ends before it, has. Refused
|
||||
// (RVG_ERR_INVALID_ARGUMENT): a range not in whole multiples of 2 MiB, one past the address
|
||||
// space, one a range of `memory_map` overlaps, and one given without both pool_add and
|
||||
// pool_remove.
|
||||
uint64_t pool_physical_address;
|
||||
// The range's length in bytes: 0 for none.
|
||||
uint64_t pool_physical_length;
|
||||
} RvgGraphicsDeviceConfig;
|
||||
|
||||
#ifdef __cplusplus
|
||||
@@ -623,6 +672,36 @@ const char *rvg_status_message(RvgStatus status);
|
||||
RvgStatus rvg_graphics_device_create(const RvgGraphicsDeviceConfig *config,
|
||||
RvgGraphicsDevice **device);
|
||||
|
||||
// The host mapped the pool's piece at `physical_address` that pool_add asked for: the guest's
|
||||
// address space has it from now on. RVG_ERR_INVALID_ARGUMENT for a device without a pool, an
|
||||
// address the device asked no add at, or one the host said it added already. On any thread, the
|
||||
// host's lock (QEMU's BQL) held or not: waits for nothing. Calls back: never.
|
||||
//
|
||||
// # Safety
|
||||
// `device` is a live graphics device handle.
|
||||
RvgStatus rvg_graphics_device_pool_added(RvgGraphicsDevice *device, uint64_t physical_address);
|
||||
|
||||
// The host took the pool's piece at `physical_address` out of the guest's address space, and no
|
||||
// thread of its own touches its memory: asked to by pool_remove, or of its own, as it does with
|
||||
// every piece it added before it releases the device. The device may free the piece's memory
|
||||
// from now on. RVG_ERR_INVALID_ARGUMENT for a device without a pool, or an address the device
|
||||
// asked no add at. On any thread, the host's lock (QEMU's BQL) held or not: waits for nothing.
|
||||
// Calls back: never.
|
||||
//
|
||||
// # Safety
|
||||
// `device` is a live graphics device handle.
|
||||
RvgStatus rvg_graphics_device_pool_removed(RvgGraphicsDevice *device, uint64_t physical_address);
|
||||
|
||||
// Asks for at least `length` more bytes of the guest's Shared pool now, ahead of the guest's own
|
||||
// ask, as that ask does: the device's pool thread takes a block (256 MiB, or `length` rounded up
|
||||
// to 2 MiB past that) and asks the host to map it (pool_add). QEMU calls it for its device's
|
||||
// `x-pool-grow` property. RVG_ERR_INVALID_ARGUMENT for a device without a pool or a `length` of
|
||||
// 0. On any thread: waits for nothing. Calls back: never.
|
||||
//
|
||||
// # Safety
|
||||
// `device` is a live graphics device handle.
|
||||
RvgStatus rvg_graphics_device_pool_grow(RvgGraphicsDevice *device, uint64_t length);
|
||||
|
||||
// Drops the host's reference; the last one closes the window, waiting for nothing, and ends the
|
||||
// device's threads without waiting for them: the callbacks' destroy runs once both have ended,
|
||||
// possibly after this returns, and the region stays mapped until then and until the window's
|
||||
|
||||
@@ -111,6 +111,8 @@ fn a_panic_in_a_callback_of_the_first_export_ends_in_the_hook() {
|
||||
cursor_glyph_at: None,
|
||||
cursor_show_at: None,
|
||||
cursor_move_at: None,
|
||||
pool_add: None,
|
||||
pool_remove: None,
|
||||
};
|
||||
let config = crate::graphics::RvgGraphicsDeviceConfig {
|
||||
struct_size: crate::sized::size_u32::<crate::graphics::RvgGraphicsDeviceConfig>(),
|
||||
@@ -122,6 +124,8 @@ fn a_panic_in_a_callback_of_the_first_export_ends_in_the_hook() {
|
||||
doorbell_pages: 0,
|
||||
display_count: 0,
|
||||
display_windows: std::ptr::null(),
|
||||
pool_physical_address: 0,
|
||||
pool_physical_length: 0,
|
||||
};
|
||||
// SAFETY: a live config; a NULL out-pointer, which the create refuses.
|
||||
let _ =
|
||||
|
||||
@@ -11,7 +11,8 @@ use std::ffi::c_void;
|
||||
use std::sync::Arc;
|
||||
|
||||
use reims_vgpu::{
|
||||
GraphicsCallbacks, GraphicsConfig, GraphicsDevice, GraphicsRaiseFn, GuestArch, RawDoorbell,
|
||||
GraphicsCallbacks, GraphicsConfig, GraphicsDevice, GraphicsRaiseFn, GuestArch, PoolAddFn,
|
||||
PoolConfig, PoolRemoveFn, RawDoorbell,
|
||||
};
|
||||
#[cfg(not(windows))]
|
||||
use reims_vgpu::{GraphicsRouteDoorbellFn, GraphicsRouteDoorbellPageFn};
|
||||
@@ -196,6 +197,46 @@ pub type RvgGraphicsRouteDoorbellPageFn = Option<
|
||||
) -> bool,
|
||||
>;
|
||||
|
||||
/// `pool_add(ctx, physical_address, host_address, length)`: map `length` bytes of host memory
|
||||
/// from `host_address` into the guest at `physical_address`, a piece of the guest's Shared pool
|
||||
/// (RvgGraphicsDeviceConfig's `pool_physical_address` and `pool_physical_length`, which hold the
|
||||
/// piece), and call rvg_graphics_device_pool_added with `physical_address` once the guest's
|
||||
/// address space has it (QEMU: a RAM region over the memory, added on its main loop, unmergeable
|
||||
/// with its neighbours). The memory stays mapped, and the device asks no other piece over its
|
||||
/// addresses, until the host has said the piece is removed (rvg_graphics_device_pool_removed).
|
||||
/// `physical_address`, `host_address` and `length` are multiples of 2 MiB, 4 KiB and 2 MiB.
|
||||
///
|
||||
/// Thread: the device's pool thread (`reims-vgpu.graphics-pool`), never inside a call of the
|
||||
/// host's, with no lock of the library's held. It must not wait for a lock the host holds while
|
||||
/// it calls the device (QEMU's BQL): QEMU queues the add for its main loop. One piece at a time,
|
||||
/// in the order the device places them, each before its pool_remove. May call: nothing of the
|
||||
/// library's. Needed with a pool.
|
||||
pub type RvgGraphicsPoolAddFn = Option<
|
||||
unsafe extern "C-unwind" fn(
|
||||
ctx: *mut c_void,
|
||||
physical_address: u64,
|
||||
host_address: *mut c_void,
|
||||
length: u64,
|
||||
),
|
||||
>;
|
||||
|
||||
/// `pool_remove(ctx, physical_address, length)`: unmap the piece of the pool at
|
||||
/// `physical_address` that pool_add mapped, and call rvg_graphics_device_pool_removed with
|
||||
/// `physical_address` once it is out of the guest's address space and no thread of the host's
|
||||
/// touches its memory (QEMU: once its region's last reference goes, past its RCU grace period).
|
||||
/// The device frees the memory only after that. A remove of a piece whose add the host has not
|
||||
/// carried out yet follows that add: the host carries out the add, then the remove.
|
||||
///
|
||||
/// Thread: the one that frees the piece's block (the device's pool thread, or the block source's
|
||||
/// own), never inside a call of the host's, with no lock of the library's held. It must not wait
|
||||
/// for a lock the host holds while it calls the device (QEMU queues the remove for its main
|
||||
/// loop). Once a piece, after its pool_add. Not called once rvg_graphics_device_release has
|
||||
/// begun: the host removes every piece it added before it releases the device. May call: nothing
|
||||
/// of the library's. Needed with a pool.
|
||||
pub type RvgGraphicsPoolRemoveFn = Option<
|
||||
unsafe extern "C-unwind" fn(ctx: *mut c_void, physical_address: u64, length: u64),
|
||||
>;
|
||||
|
||||
/// The graphics device's callbacks.
|
||||
///
|
||||
/// The cursor's three tell the host the guest's cursor on the device's display, for a host that
|
||||
@@ -246,6 +287,11 @@ pub struct RvgGraphicsCallbacks {
|
||||
/// cursor_move of display 1 and up: rvg_graphics_device_cursor_position_at reads where. A
|
||||
/// host built before it gives none.
|
||||
pub cursor_move_at: RvgCursorMoveAtFn,
|
||||
/// Maps a piece of the guest's Shared pool. A host built before it, whose `struct_size` ends
|
||||
/// before it, gives none, and has no pool.
|
||||
pub pool_add: RvgGraphicsPoolAddFn,
|
||||
/// Unmaps a piece of the guest's Shared pool. A host built before it gives none.
|
||||
pub pool_remove: RvgGraphicsPoolRemoveFn,
|
||||
}
|
||||
|
||||
// SAFETY: repr(C), a u32 first; a pointer and optional function pointers.
|
||||
@@ -341,6 +387,16 @@ pub struct RvgGraphicsDeviceConfig {
|
||||
/// display, missing where `window` is given and it has several, or a NULL entry. A host built
|
||||
/// before this field gives none.
|
||||
pub display_windows: *const *const RvgWindowConfig,
|
||||
/// The first guest physical address of the range the host reserved for the guest's Shared
|
||||
/// pool, with no RAM or device under it, which the device fills with blocks of host memory as
|
||||
/// the pool grows (pool_add). 0, with `pool_physical_length` 0, for none, as a host built
|
||||
/// before this field, whose `struct_size` ends before it, has. Refused
|
||||
/// (RVG_ERR_INVALID_ARGUMENT): a range not in whole multiples of 2 MiB, one past the address
|
||||
/// space, one a range of `memory_map` overlaps, and one given without both pool_add and
|
||||
/// pool_remove.
|
||||
pub pool_physical_address: u64,
|
||||
/// The range's length in bytes: 0 for none.
|
||||
pub pool_physical_length: u64,
|
||||
}
|
||||
|
||||
// SAFETY: repr(C), a u32 first; pointers and u32s.
|
||||
@@ -494,6 +550,13 @@ unsafe fn create(
|
||||
Ok(m) => m,
|
||||
Err(s) => return refuse(s),
|
||||
};
|
||||
let pool = match (c.pool_physical_address, c.pool_physical_length) {
|
||||
(0, 0) => None,
|
||||
(physical_address, physical_length) => Some(PoolConfig {
|
||||
physical_address,
|
||||
physical_length,
|
||||
}),
|
||||
};
|
||||
let raise_interrupt = callbacks.raise_interrupt.map(|f| {
|
||||
let t = table.clone();
|
||||
let raise: GraphicsRaiseFn = Arc::new(move |vector| {
|
||||
@@ -540,6 +603,8 @@ unsafe fn create(
|
||||
cursor_move_at: cursor_move_at(&table, callbacks.cursor_move_at),
|
||||
route_doorbell,
|
||||
route_doorbell_page,
|
||||
pool_add: pool_add(&table, callbacks.pool_add),
|
||||
pool_remove: pool_remove(&table, callbacks.pool_remove),
|
||||
},
|
||||
window: (window.iter().zip(&window_tables))
|
||||
.map(|((w, wc), t)| w.to_config(window_callbacks(t, wc)))
|
||||
@@ -552,6 +617,7 @@ unsafe fn create(
|
||||
memory_map,
|
||||
guest_arch,
|
||||
doorbell_pages,
|
||||
pool,
|
||||
};
|
||||
match GraphicsDevice::with_platform(<Plat as reims_vgpu::ApiPlatform>::process(), config) {
|
||||
Ok(d) => {
|
||||
@@ -567,6 +633,107 @@ unsafe fn create(
|
||||
}
|
||||
}
|
||||
|
||||
/// The host's pool_add, called with the table's ctx.
|
||||
fn pool_add(table: &Arc<Table>, f: RvgGraphicsPoolAddFn) -> Option<PoolAddFn> {
|
||||
let f = f?;
|
||||
let t = table.clone();
|
||||
let add: PoolAddFn = Arc::new(move |physical_address, host, length| {
|
||||
// SAFETY: the host's function over its ctx.
|
||||
ffi::host_call("pool_add", || unsafe {
|
||||
f(t.ctx(), physical_address, host.cast(), length)
|
||||
});
|
||||
});
|
||||
Some(add)
|
||||
}
|
||||
|
||||
/// The host's pool_remove, called with the table's ctx.
|
||||
fn pool_remove(table: &Arc<Table>, f: RvgGraphicsPoolRemoveFn) -> Option<PoolRemoveFn> {
|
||||
let f = f?;
|
||||
let t = table.clone();
|
||||
let remove: PoolRemoveFn = Arc::new(move |physical_address, length| {
|
||||
// SAFETY: the host's function over its ctx.
|
||||
ffi::host_call("pool_remove", || unsafe {
|
||||
f(t.ctx(), physical_address, length)
|
||||
});
|
||||
});
|
||||
Some(remove)
|
||||
}
|
||||
|
||||
/// The host mapped the pool's piece at `physical_address` that pool_add asked for: the guest's
|
||||
/// address space has it from now on. RVG_ERR_INVALID_ARGUMENT for a device without a pool, an
|
||||
/// address the device asked no add at, or one the host said it added already. On any thread, the
|
||||
/// host's lock (QEMU's BQL) held or not: waits for nothing. Calls back: never.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is a live graphics device handle.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_graphics_device_pool_added(
|
||||
device: *mut RvgGraphicsDevice,
|
||||
physical_address: u64,
|
||||
) -> RvgStatus {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { pool_call(device, "rvg_graphics_device_pool_added", |d| d.pool_added(physical_address)) }
|
||||
})
|
||||
}
|
||||
|
||||
/// The host took the pool's piece at `physical_address` out of the guest's address space, and no
|
||||
/// thread of its own touches its memory: asked to by pool_remove, or of its own, as it does with
|
||||
/// every piece it added before it releases the device. The device may free the piece's memory
|
||||
/// from now on. RVG_ERR_INVALID_ARGUMENT for a device without a pool, or an address the device
|
||||
/// asked no add at. On any thread, the host's lock (QEMU's BQL) held or not: waits for nothing.
|
||||
/// Calls back: never.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is a live graphics device handle.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_graphics_device_pool_removed(
|
||||
device: *mut RvgGraphicsDevice,
|
||||
physical_address: u64,
|
||||
) -> RvgStatus {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { pool_call(device, "rvg_graphics_device_pool_removed", |d| d.pool_removed(physical_address)) }
|
||||
})
|
||||
}
|
||||
|
||||
/// Asks for at least `length` more bytes of the guest's Shared pool now, ahead of the guest's own
|
||||
/// ask, as that ask does: the device's pool thread takes a block (256 MiB, or `length` rounded up
|
||||
/// to 2 MiB past that) and asks the host to map it (pool_add). QEMU calls it for its device's
|
||||
/// `x-pool-grow` property. RVG_ERR_INVALID_ARGUMENT for a device without a pool or a `length` of
|
||||
/// 0. On any thread: waits for nothing. Calls back: never.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is a live graphics device handle.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_graphics_device_pool_grow(
|
||||
device: *mut RvgGraphicsDevice,
|
||||
length: u64,
|
||||
) -> RvgStatus {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { pool_call(device, "rvg_graphics_device_pool_grow", |d| d.pool_grow(length)) }
|
||||
})
|
||||
}
|
||||
|
||||
/// The body of the pool's functions inside their `ffi::export`: `call` on the device, its answer
|
||||
/// as a status.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is a live graphics device handle.
|
||||
unsafe fn pool_call(
|
||||
device: *mut RvgGraphicsDevice,
|
||||
name: &'static str,
|
||||
call: impl FnOnce(&GraphicsDevice<Plat>) -> Result<(), reims_vgpu::Error>,
|
||||
) -> RvgStatus {
|
||||
// SAFETY: the caller's contract.
|
||||
let d = unsafe { live(device, name) };
|
||||
match call(&d.device) {
|
||||
Ok(()) => RVG_OK,
|
||||
Err(e) => status(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops the host's reference; the last one closes the window, waiting for nothing, and ends the
|
||||
/// device's threads without waiting for them: the callbacks' destroy runs once both have ended,
|
||||
/// possibly after this returns, and the region stays mapped until then and until the window's
|
||||
|
||||
@@ -25,6 +25,8 @@ fn callbacks() -> RvgGraphicsCallbacks {
|
||||
cursor_glyph_at: None,
|
||||
cursor_show_at: None,
|
||||
cursor_move_at: None,
|
||||
pool_add: None,
|
||||
pool_remove: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,6 +41,8 @@ fn config(callbacks: &RvgGraphicsCallbacks) -> RvgGraphicsDeviceConfig {
|
||||
doorbell_pages: 0,
|
||||
display_count: 0,
|
||||
display_windows: std::ptr::null(),
|
||||
pool_physical_address: 0,
|
||||
pool_physical_length: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -542,3 +546,115 @@ fn command_buffer_copy_cost() {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// What the pool's host callbacks were asked, for [`a_pool_s_pieces_reach_the_host_and_back`].
|
||||
static POOL_ASKS: std::sync::Mutex<Vec<(bool, u64, u64)>> = std::sync::Mutex::new(Vec::new());
|
||||
|
||||
unsafe extern "C-unwind" fn pool_add(
|
||||
_ctx: *mut c_void,
|
||||
physical_address: u64,
|
||||
host_address: *mut c_void,
|
||||
length: u64,
|
||||
) {
|
||||
assert!(!host_address.is_null());
|
||||
POOL_ASKS
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push((true, physical_address, length));
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn pool_remove(_ctx: *mut c_void, physical_address: u64, length: u64) {
|
||||
POOL_ASKS
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push((false, physical_address, length));
|
||||
}
|
||||
|
||||
/// A pool needs both of its callbacks and a range of whole 2 MiB; a device without one refuses
|
||||
/// the pool's calls; a device with one grows on the host's ask, on its pool thread, takes the
|
||||
/// host's word that it added the piece once, and its removal; a config of the fourth version,
|
||||
/// whose `struct_size` ends before the pool's fields, has no pool whatever lies past its size
|
||||
#[test]
|
||||
fn a_pool_s_pieces_reach_the_host_and_back() {
|
||||
const BASE: u64 = 52 << 30;
|
||||
let plain = RvgGraphicsCallbacks {
|
||||
destroy: None,
|
||||
..callbacks()
|
||||
};
|
||||
let with_pool = RvgGraphicsCallbacks {
|
||||
pool_add: Some(pool_add),
|
||||
pool_remove: Some(pool_remove),
|
||||
..plain
|
||||
};
|
||||
let mut device = std::ptr::null_mut();
|
||||
// SAFETY: live configs and out-pointers; then live devices, released.
|
||||
unsafe {
|
||||
for (cb, address, length) in [
|
||||
(&plain, BASE, 64 << 30),
|
||||
(&with_pool, BASE + 4096, 64 << 30),
|
||||
(&with_pool, BASE, (64 << 30) + 4096),
|
||||
(&with_pool, BASE, 0),
|
||||
] {
|
||||
let c = RvgGraphicsDeviceConfig {
|
||||
pool_physical_address: address,
|
||||
pool_physical_length: length,
|
||||
..config(cb)
|
||||
};
|
||||
assert_eq!(
|
||||
rvg_graphics_device_create(&c, &mut device),
|
||||
RVG_ERR_INVALID_ARGUMENT,
|
||||
"{address:#x} {length:#x}"
|
||||
);
|
||||
}
|
||||
// The fourth version: no pool, whatever its fields hold.
|
||||
let c = RvgGraphicsDeviceConfig {
|
||||
struct_size: std::mem::offset_of!(RvgGraphicsDeviceConfig, pool_physical_address)
|
||||
as u32,
|
||||
pool_physical_address: BASE,
|
||||
pool_physical_length: 64 << 30,
|
||||
..config(&plain)
|
||||
};
|
||||
assert_eq!(rvg_graphics_device_create(&c, &mut device), RVG_OK);
|
||||
assert_eq!(
|
||||
rvg_graphics_device_pool_grow(device, 1),
|
||||
RVG_ERR_INVALID_ARGUMENT
|
||||
);
|
||||
assert_eq!(
|
||||
rvg_graphics_device_pool_added(device, BASE),
|
||||
RVG_ERR_INVALID_ARGUMENT
|
||||
);
|
||||
rvg_graphics_device_release(device);
|
||||
|
||||
let c = RvgGraphicsDeviceConfig {
|
||||
pool_physical_address: BASE,
|
||||
pool_physical_length: 64 << 30,
|
||||
..config(&with_pool)
|
||||
};
|
||||
assert_eq!(rvg_graphics_device_create(&c, &mut device), RVG_OK);
|
||||
assert_eq!(
|
||||
rvg_graphics_device_pool_grow(device, 0),
|
||||
RVG_ERR_INVALID_ARGUMENT
|
||||
);
|
||||
assert_eq!(rvg_graphics_device_pool_grow(device, 1), RVG_OK);
|
||||
for _ in 0..10_000 {
|
||||
if !POOL_ASKS.lock().unwrap().is_empty() {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(1));
|
||||
}
|
||||
assert_eq!(*POOL_ASKS.lock().unwrap(), [(true, BASE, 256 << 20)]);
|
||||
assert_eq!(rvg_graphics_device_pool_added(device, BASE), RVG_OK);
|
||||
assert_eq!(
|
||||
rvg_graphics_device_pool_added(device, BASE),
|
||||
RVG_ERR_INVALID_ARGUMENT
|
||||
);
|
||||
assert_eq!(
|
||||
rvg_graphics_device_pool_removed(device, BASE + (256 << 20)),
|
||||
RVG_ERR_INVALID_ARGUMENT
|
||||
);
|
||||
// The host removes its pieces before the release, and the release asks it nothing.
|
||||
assert_eq!(rvg_graphics_device_pool_removed(device, BASE), RVG_OK);
|
||||
rvg_graphics_device_release(device);
|
||||
}
|
||||
assert_eq!(POOL_ASKS.lock().unwrap().len(), 1);
|
||||
}
|
||||
@@ -125,6 +125,7 @@ use crate::cursor::{
|
||||
use crate::entry;
|
||||
use crate::entry::no_catch;
|
||||
use crate::error::Error;
|
||||
use crate::pool::{HostBlocks, Pool, PoolAddFn, PoolConfig, PoolHost, PoolRemoveFn};
|
||||
use crate::graphics::answers::PipelineAnswers;
|
||||
use crate::graphics::color::{ColorChange, ColorStaging, DisplayColor};
|
||||
use crate::graphics::compile::{CompileKind, CompileOf, CompilePool, Pending};
|
||||
@@ -265,6 +266,11 @@ pub struct GraphicsCallbacks {
|
||||
/// bell, at the page, or drops the route. Without it such a queue is not routed, and its
|
||||
/// writes come through [`GraphicsDevice::doorbell_write`].
|
||||
pub route_doorbell_page: Option<GraphicsRouteDoorbellPageFn>,
|
||||
/// Maps a piece of the guest's Shared pool into the guest ([`PoolAddFn`]); needed with
|
||||
/// [`GraphicsConfig::pool`], on the pool's thread.
|
||||
pub pool_add: Option<PoolAddFn>,
|
||||
/// Unmaps a piece of the pool ([`PoolRemoveFn`]); needed with [`GraphicsConfig::pool`].
|
||||
pub pool_remove: Option<PoolRemoveFn>,
|
||||
}
|
||||
|
||||
/// A graphics device's config.
|
||||
@@ -303,6 +309,12 @@ pub struct GraphicsConfig {
|
||||
/// `RGFX_FEATURE_DOORBELL_PAGES`, on which the kext maps each process's own page, which it
|
||||
/// rings its queues' doorbells on with no call into the kext.
|
||||
pub doorbell_pages: bool,
|
||||
/// The guest physical range the host reserved for the guest's Shared pool, with no RAM under
|
||||
/// it, which the device fills with blocks as the pool grows (`crate::pool`); `None` is no pool.
|
||||
/// Given, it needs [`GraphicsCallbacks::pool_add`] and `pool_remove`, a range
|
||||
/// [`PoolConfig::is_valid`] takes, and none of [`Self::memory_map`]'s ranges overlapping it:
|
||||
/// otherwise [`Error::InvalidArgument`].
|
||||
pub pool: Option<PoolConfig>,
|
||||
}
|
||||
|
||||
/// The architecture of the macOS guest a graphics device serves ([`GraphicsConfig::guest_arch`]).
|
||||
@@ -388,6 +400,28 @@ fn display_count(config: &GraphicsConfig) -> Result<usize, Error> {
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
/// The pool `config` gives, with the host's side of it: `None` without one;
|
||||
/// [`Error::InvalidArgument`] for a range [`PoolConfig::is_valid`] refuses, one a range of the
|
||||
/// memory map overlaps, or one without both of the host's pool callbacks.
|
||||
fn pool_host(config: &GraphicsConfig) -> Result<Option<(PoolConfig, PoolHost)>, Error> {
|
||||
let Some(range) = config.pool else {
|
||||
return Ok(None);
|
||||
};
|
||||
let (Some(add), Some(remove)) = (&config.callbacks.pool_add, &config.callbacks.pool_remove)
|
||||
else {
|
||||
return Err(Error::InvalidArgument);
|
||||
};
|
||||
let mut ram = (config.memory_map.iter()).flat_map(|m| m.ranges());
|
||||
if !range.is_valid() || ram.any(|r| range.overlaps(r.physical_address, r.physical_length)) {
|
||||
return Err(Error::InvalidArgument);
|
||||
}
|
||||
let host = PoolHost {
|
||||
add: Arc::clone(add),
|
||||
remove: Arc::clone(remove),
|
||||
};
|
||||
Ok(Some((range, host)))
|
||||
}
|
||||
|
||||
/// The reims-graphics device.
|
||||
pub struct GraphicsDevice<P: ApiPlatform = DefaultPlatform> {
|
||||
/// The displays' windows, display `i`'s at index `i`, none without them, which close when
|
||||
@@ -410,6 +444,8 @@ pub struct GraphicsDevice<P: ApiPlatform = DefaultPlatform> {
|
||||
/// The stage-3 decoder's state while it lives: once the device ended, what holds the GPU
|
||||
/// device until its threads, its objects and their GPU work let go ([`ENDING`]).
|
||||
ending: Weak<GraphicsControl<P>>,
|
||||
/// The guest's Shared pool, where the host reserved one.
|
||||
pool: Option<Pool>,
|
||||
/// The platform the decoder runs on.
|
||||
platform: PhantomData<fn() -> P>,
|
||||
}
|
||||
@@ -449,6 +485,7 @@ impl<P: ApiPlatform> GraphicsDevice<P> {
|
||||
pub fn with_platform(platform: Arc<P>, config: GraphicsConfig) -> Result<Self, Error> {
|
||||
entry::run(|_| {
|
||||
let count = display_count(&config)?;
|
||||
let pool_host = pool_host(&config)?;
|
||||
let size = usize::try_from(reims_vgpu_graphics::REGION_SIZE)
|
||||
.map_err(|_| Error::HostResources)?;
|
||||
let region = platform
|
||||
@@ -833,6 +870,14 @@ impl<P: ApiPlatform> GraphicsDevice<P> {
|
||||
let shown = first_shown.filter(|_| !windows.is_empty());
|
||||
#[cfg(not(test))]
|
||||
drop(first_shown);
|
||||
// The guest's Shared pool, its blocks the process's own memory until the device runs
|
||||
// on metal2vulkan-rt, whose blocks then fill it through the same calls.
|
||||
let pool = match pool_host {
|
||||
Some((range, host)) => Some(Pool::new(range, host, |mappings| {
|
||||
Arc::new(HostBlocks::new(mappings))
|
||||
})?),
|
||||
None => None,
|
||||
};
|
||||
let device = reims_vgpu_graphics::Device::with_screens(region, host, screens)
|
||||
.ok_or(Error::HostResources)?;
|
||||
desktop.set_windows(by_display);
|
||||
@@ -848,11 +893,47 @@ impl<P: ApiPlatform> GraphicsDevice<P> {
|
||||
#[cfg(test)]
|
||||
shown,
|
||||
reads,
|
||||
pool,
|
||||
platform: PhantomData,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// The host mapped the pool's piece at `physical_address` it was asked to add
|
||||
/// ([`GraphicsCallbacks::pool_add`]): the guest's address space has it from now on. Any
|
||||
/// thread, the host's lock held or not; waits for nothing and calls back never.
|
||||
/// [`Error::InvalidArgument`] without a pool, or for an address the device asked no add at,
|
||||
/// or one the host said it added already.
|
||||
pub fn pool_added(&self, physical_address: u64) -> Result<(), Error> {
|
||||
(self.pool.as_ref())
|
||||
.ok_or(Error::InvalidArgument)?
|
||||
.added(physical_address)
|
||||
}
|
||||
|
||||
/// The host took the pool's piece at `physical_address` out of the guest's address space,
|
||||
/// and no thread of its own touches it: asked to ([`GraphicsCallbacks::pool_remove`]), or of
|
||||
/// its own, as it does with every piece before the device's release. Any thread, the host's
|
||||
/// lock held or not; waits for nothing and calls back never. [`Error::InvalidArgument`]
|
||||
/// without a pool, or for an address the device asked no add at.
|
||||
pub fn pool_removed(&self, physical_address: u64) -> Result<(), Error> {
|
||||
(self.pool.as_ref())
|
||||
.ok_or(Error::InvalidArgument)?
|
||||
.removed(physical_address)
|
||||
}
|
||||
|
||||
/// Asks for at least `length` more bytes of the guest's Shared pool now, as the guest's own
|
||||
/// ask does: the pool's thread takes a block and asks the host to map it
|
||||
/// ([`GraphicsCallbacks::pool_add`]). Waits for nothing and calls back never.
|
||||
/// [`Error::InvalidArgument`] without a pool, or for a `length` of 0.
|
||||
pub fn pool_grow(&self, length: u64) -> Result<(), Error> {
|
||||
let pool = self.pool.as_ref().ok_or(Error::InvalidArgument)?;
|
||||
if length == 0 {
|
||||
return Err(Error::InvalidArgument);
|
||||
}
|
||||
pool.grow(length);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The region's first byte: BAR 2's memory, which the host maps into the guest, write-back.
|
||||
/// It stays mapped until the device and its window's GPU work have ended.
|
||||
pub fn region_base(&self) -> *mut u8 {
|
||||
@@ -1013,6 +1094,9 @@ impl<P: ApiPlatform> Drop for GraphicsDevice<P> {
|
||||
entry::run(|_| {
|
||||
drop(std::mem::take(&mut self.windows));
|
||||
});
|
||||
// The host removed every piece of the pool before the release: the pool's thread ends
|
||||
// and its source goes, unmapping each block it handed out before it frees it.
|
||||
drop(self.pool.take());
|
||||
let ending: Weak<dyn std::any::Any + Send + Sync> = self.ending.clone();
|
||||
let mut ended = ENDING.lock();
|
||||
ended.retain(|state| state.strong_count() > 0);
|
||||
|
||||
@@ -31,6 +31,7 @@ mod faults;
|
||||
mod graphics;
|
||||
mod memory;
|
||||
pub mod platform;
|
||||
mod pool;
|
||||
pub mod singleton;
|
||||
mod video;
|
||||
mod window;
|
||||
@@ -47,6 +48,7 @@ pub use graphics::{
|
||||
};
|
||||
pub use memory::{HostFile, MemoryFile, MemoryMap};
|
||||
pub use platform::ApiPlatform;
|
||||
pub use pool::{BLOCK_LEN, PIECE_ALIGN, PoolAddFn, PoolConfig, PoolRemoveFn, RELEASE_DELAY};
|
||||
pub use reims_vgpu_graphics::RawDoorbell;
|
||||
pub use reims_vgpu_vulkan::VulkanPlatform;
|
||||
|
||||
|
||||
@@ -0,0 +1,673 @@
|
||||
//! The guest's Shared pool: a range of guest physical addresses the host reserved with no RAM
|
||||
//! under it ([`PoolConfig`]), which the device fills with the block source's host-visible blocks
|
||||
//! as it grows, one piece a block, and gives back as the guest empties them.
|
||||
//!
|
||||
//! # Growth
|
||||
//!
|
||||
//! An ask for more pool ([`Pool::grow`]: the host's `rvg_graphics_device_pool_grow`, and the
|
||||
//! headroom rule below) wakes the pool's thread, `reims-vgpu.graphics-pool`. It takes a Shared
|
||||
//! block from the source ([`BlockSource::take_block`], which waits only when no block is ready),
|
||||
//! places it at the lowest free address of the range that holds it, 2 MiB aligned, so pieces go
|
||||
//! out in ascending addresses, and asks the host to map it there ([`PoolHost::add`]) with no lock
|
||||
//! of the pool's held. The host maps it (QEMU: a RAM region of its own over the block, added on
|
||||
//! its main loop) and says so ([`Pool::added`], the C API's "range added"); only then does
|
||||
//! [`Pool::find`] find it. A block the source hands out again after the pool gave it back keeps
|
||||
//! its id, so its piece keeps its address and mapping, and the host is asked nothing.
|
||||
//!
|
||||
//! # Headroom and giving blocks back
|
||||
//!
|
||||
//! A new piece is empty: nothing of the guest's lies in it. The guest says when it puts something
|
||||
//! in a piece ([`Pool::piece_used`]) and when it has emptied one ([`Pool::piece_empty`]). The pool
|
||||
//! keeps one empty piece as headroom: when the guest uses the last empty one, the pool asks for a
|
||||
//! block more. A piece that stays empty for [`RELEASE_DELAY`] while a lower one is empty too goes
|
||||
//! back to the source ([`BlockSource::release_block`]), which keeps it ready, mapped, or frees it
|
||||
//! through the unmap below; the lowest empty piece stays as the headroom. The delay rides out
|
||||
//! churn, where a guest empties and fills a piece again within seconds.
|
||||
//!
|
||||
//! # Release
|
||||
//!
|
||||
//! The source calls [`BlockMappings::unmap`] before it frees any block it handed out, teardown
|
||||
//! included. For a block of the pool's, unmap takes the piece out of the lookups, waits for every
|
||||
//! hold on it ([`PieceHold`]) to go, asks the host to unmap it ([`PoolHost::remove`]), and returns
|
||||
//! once the host says it is out of the guest's address space and no host thread of its own touches
|
||||
//! it ([`Pool::removed`]). So no guest access, no thread of the host's and no thread of the
|
||||
//! library's touches a block once the source frees it.
|
||||
//!
|
||||
//! At the device's release the host has removed every piece it added (QEMU does so as it tears
|
||||
//! the device down, before the release): from then on ([`Pool::close`]) an unmap waits only for
|
||||
//! the holds, and asks the host nothing.
|
||||
//!
|
||||
//! # The block source
|
||||
//!
|
||||
//! [`BlockSource`] and [`BlockMappings`] are metal2vulkan-rt's block calls and hook as its API
|
||||
//! names them (`Device::take_block`, `release_block`, `BlockMappings::unmap`, [`BlockInfo`]).
|
||||
//! Until the device runs on that runtime, the source is [`HostBlocks`], blocks of the process's
|
||||
//! own memory, which hands blocks out, keeps them ready and frees them as the runtime does.
|
||||
|
||||
// Guest addresses flow through here: arithmetic is spelt out.
|
||||
#![cfg_attr(not(test), deny(clippy::arithmetic_side_effects))]
|
||||
|
||||
mod host_blocks;
|
||||
|
||||
use std::collections::{BTreeMap, HashMap, VecDeque};
|
||||
use std::ptr::NonNull;
|
||||
use std::sync::{Arc, Weak};
|
||||
use std::thread::JoinHandle;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use parking_lot::{Condvar, Mutex};
|
||||
|
||||
pub(crate) use host_blocks::HostBlocks;
|
||||
|
||||
use crate::Error;
|
||||
|
||||
/// A pooled block's length, metal2vulkan-rt's `BLOCK_LEN`: 256 MiB.
|
||||
pub const BLOCK_LEN: u64 = 256 << 20;
|
||||
|
||||
/// The alignment of a piece's guest physical address and of a pool's range: 2 MiB, a large page
|
||||
/// of the guest's and of the hypervisors' second-level tables.
|
||||
pub const PIECE_ALIGN: u64 = 2 << 20;
|
||||
|
||||
/// How long a piece stays empty, with a lower piece empty too, before its block goes back to the
|
||||
/// source (the module doc's "Headroom and giving blocks back").
|
||||
pub const RELEASE_DELAY: Duration = Duration::from_secs(5);
|
||||
|
||||
/// A block's storage mode as the guest's buffers in it see it (metal2vulkan-rt's `MemoryClass`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum MemoryClass {
|
||||
/// Device-local, never mapped, no host pointer.
|
||||
Private,
|
||||
/// Host-visible, host-coherent and host-cached: the only class mapped into the guest.
|
||||
Shared,
|
||||
}
|
||||
|
||||
/// A block's number, never reused while its source lives (metal2vulkan-rt's `BlockId`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub struct BlockId(pub u32);
|
||||
|
||||
impl BlockId {
|
||||
/// The number.
|
||||
pub fn get(self) -> u32 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// A block a source handed out (metal2vulkan-rt's `BlockInfo`): plain data.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct BlockInfo {
|
||||
/// Its number.
|
||||
pub id: BlockId,
|
||||
/// Its class.
|
||||
pub class: MemoryClass,
|
||||
/// Its length: [`BLOCK_LEN`] for a pooled block, more for a dedicated one.
|
||||
pub len: u64,
|
||||
/// The GPU address of its first byte; 0 from a source with no GPU ([`HostBlocks`]).
|
||||
pub gpu_address: u64,
|
||||
/// Its host mapping, for a Shared block; `None` for a Private one.
|
||||
pub contents: Option<NonNull<u8>>,
|
||||
}
|
||||
|
||||
// SAFETY: plain data; `contents` is an address, and dereferencing it is the holder's unsafe.
|
||||
unsafe impl Send for BlockInfo {}
|
||||
// SAFETY: as Send.
|
||||
unsafe impl Sync for BlockInfo {}
|
||||
|
||||
/// A source refused a block.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum BlockError {
|
||||
/// A length past what the source allocates in one block.
|
||||
Length,
|
||||
/// The host or the device has no memory for it.
|
||||
OutOfMemory,
|
||||
/// A block the caller does not hold.
|
||||
NotHeld,
|
||||
}
|
||||
|
||||
/// Where the pool's blocks come from (metal2vulkan-rt's `Device::take_block` and
|
||||
/// `release_block`).
|
||||
pub trait BlockSource: Send + Sync {
|
||||
/// A block of `class` at least `len` long: a pooled one up to [`BLOCK_LEN`], a dedicated one
|
||||
/// past it. Waits only when no block is ready.
|
||||
fn take_block(&self, class: MemoryClass, len: u64) -> Result<BlockInfo, BlockError>;
|
||||
/// Gives a block back: it goes back to the ready set, with its id, address and mapping, or is
|
||||
/// freed after [`BlockMappings::unmap`].
|
||||
fn release_block(&self, block: BlockId) -> Result<(), BlockError>;
|
||||
}
|
||||
|
||||
/// The hook a source calls before it frees any block it handed out, teardown included
|
||||
/// (metal2vulkan-rt's `BlockMappings`).
|
||||
pub trait BlockMappings: Send + Sync {
|
||||
/// Returns once every mapping of `block` made of it is gone and no thread touches it. Calls
|
||||
/// nothing of the source's.
|
||||
fn unmap(&self, block: BlockId);
|
||||
}
|
||||
|
||||
/// The guest physical range the host reserved for the pool, with no RAM under it.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct PoolConfig {
|
||||
/// Its first guest physical address, a multiple of [`PIECE_ALIGN`].
|
||||
pub physical_address: u64,
|
||||
/// Its length, a multiple of [`PIECE_ALIGN`].
|
||||
pub physical_length: u64,
|
||||
}
|
||||
|
||||
impl PoolConfig {
|
||||
/// Whether a pool takes the range: not empty, both ends multiples of [`PIECE_ALIGN`], and not
|
||||
/// past the address space.
|
||||
pub fn is_valid(self) -> bool {
|
||||
self.physical_length != 0
|
||||
&& self.physical_address % PIECE_ALIGN == 0
|
||||
&& self.physical_length % PIECE_ALIGN == 0
|
||||
&& self
|
||||
.physical_address
|
||||
.checked_add(self.physical_length)
|
||||
.is_some()
|
||||
}
|
||||
|
||||
/// Whether the range overlaps `length` bytes from `address`.
|
||||
pub fn overlaps(self, address: u64, length: u64) -> bool {
|
||||
let end = self.physical_address.saturating_add(self.physical_length);
|
||||
address < end && self.physical_address < address.saturating_add(length)
|
||||
}
|
||||
}
|
||||
|
||||
/// `(physical_address, host_address, length)`: map `length` bytes of host memory at
|
||||
/// `host_address` into the guest at `physical_address`, then say so ([`Pool::added`]). Called on
|
||||
/// the pool's thread with no lock of the device's held; it must not wait for a lock the host holds
|
||||
/// while it calls the device.
|
||||
pub type PoolAddFn = Arc<dyn Fn(u64, *mut u8, u64) + Send + Sync>;
|
||||
|
||||
/// `(physical_address, length)`: unmap the piece at `physical_address`, then say so once no
|
||||
/// thread of the host's touches it ([`Pool::removed`]). Called inside [`BlockMappings::unmap`],
|
||||
/// on the source's thread, with no lock of the device's held; it must not wait for a lock the host
|
||||
/// holds while it calls the device.
|
||||
pub type PoolRemoveFn = Arc<dyn Fn(u64, u64) + Send + Sync>;
|
||||
|
||||
/// The host's side of the pool.
|
||||
#[derive(Clone)]
|
||||
pub struct PoolHost {
|
||||
/// Maps a piece.
|
||||
pub add: PoolAddFn,
|
||||
/// Unmaps a piece.
|
||||
pub remove: PoolRemoveFn,
|
||||
}
|
||||
|
||||
/// Where a piece's mapping is.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Mapped {
|
||||
/// Asked of the host, not yet added.
|
||||
Adding,
|
||||
/// In the guest's address space.
|
||||
Live,
|
||||
/// Being unmapped, out of the lookups; `asked` once the host was asked to remove it.
|
||||
Removing { asked: bool },
|
||||
/// Out of the guest's address space, and no thread of the host's touches it.
|
||||
Removed,
|
||||
}
|
||||
|
||||
/// One block in the range.
|
||||
#[derive(Debug)]
|
||||
struct Piece {
|
||||
block: BlockInfo,
|
||||
mapped: Mapped,
|
||||
/// The pool holds the block: taken, not given back. A piece given back stays mapped until the
|
||||
/// source unmaps it, and nothing finds it.
|
||||
held: bool,
|
||||
/// Since when nothing of the guest's lies in it; `None` while something does.
|
||||
empty_since: Option<Instant>,
|
||||
/// Holds on it ([`PieceHold`]).
|
||||
holds: u64,
|
||||
}
|
||||
|
||||
impl Piece {
|
||||
/// Whether the guest may put something in it: held and not being unmapped.
|
||||
fn usable(&self) -> bool {
|
||||
self.held && matches!(self.mapped, Mapped::Adding | Mapped::Live)
|
||||
}
|
||||
}
|
||||
|
||||
/// What the pool's lock holds.
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
/// By guest physical address.
|
||||
pieces: BTreeMap<u64, Piece>,
|
||||
/// Each piece's address, by its block.
|
||||
by_block: HashMap<BlockId, u64>,
|
||||
/// Asks for more pool, in bytes, oldest first.
|
||||
asks: VecDeque<u64>,
|
||||
/// The device was released: the host removed every piece it added.
|
||||
closed: bool,
|
||||
/// The pool's thread logged the range's being full once.
|
||||
full_logged: bool,
|
||||
}
|
||||
|
||||
/// The pool's shared part: what the thread, the device and the source's hook hold.
|
||||
struct Shared {
|
||||
range: PoolConfig,
|
||||
host: PoolHost,
|
||||
/// [`RELEASE_DELAY`], shorter in the tests.
|
||||
release_delay: Duration,
|
||||
state: Mutex<State>,
|
||||
changed: Condvar,
|
||||
}
|
||||
|
||||
/// A hold on a live piece: while it lives, an unmap of its block waits.
|
||||
pub struct PieceHold {
|
||||
shared: Arc<Shared>,
|
||||
physical_address: u64,
|
||||
/// The block.
|
||||
pub block: BlockId,
|
||||
/// The byte the lookup named, in the block.
|
||||
pub offset: u64,
|
||||
/// That byte's host address.
|
||||
pub host: NonNull<u8>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for PieceHold {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("PieceHold")
|
||||
.field("block", &self.block)
|
||||
.field("offset", &self.offset)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for PieceHold {
|
||||
fn drop(&mut self) {
|
||||
let mut st = self.shared.state.lock();
|
||||
if let Some(p) = st.pieces.get_mut(&self.physical_address) {
|
||||
p.holds = p.holds.saturating_sub(1);
|
||||
}
|
||||
drop(st);
|
||||
self.shared.changed.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
/// The pool's [`BlockMappings`], which the source holds: weak, so the source, which the pool
|
||||
/// holds, makes no cycle.
|
||||
struct Mappings(Weak<Shared>);
|
||||
|
||||
impl BlockMappings for Mappings {
|
||||
fn unmap(&self, block: BlockId) {
|
||||
if let Some(shared) = self.0.upgrade() {
|
||||
shared.unmap(block);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The guest's Shared pool of one device.
|
||||
pub struct Pool {
|
||||
shared: Arc<Shared>,
|
||||
/// The source. Dropped after the thread that takes from it ends ([`Pool::close`]); it frees
|
||||
/// its blocks once nothing else holds it, after unmapping each.
|
||||
source: Option<Arc<dyn BlockSource>>,
|
||||
thread: Option<JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Pool {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Pool")
|
||||
.field("range", &self.shared.range)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl Pool {
|
||||
/// A pool over `range`, its blocks from what `source` makes with the pool's hook, and its
|
||||
/// thread started. [`Error::InvalidArgument`] for a range [`PoolConfig::is_valid`] refuses,
|
||||
/// [`Error::HostResources`] where the thread is refused.
|
||||
pub(crate) fn new(
|
||||
range: PoolConfig,
|
||||
host: PoolHost,
|
||||
source: impl FnOnce(Arc<dyn BlockMappings>) -> Arc<dyn BlockSource>,
|
||||
) -> Result<Pool, Error> {
|
||||
Pool::with_delay(range, host, RELEASE_DELAY, source)
|
||||
}
|
||||
|
||||
/// [`Pool::new`], its pieces given back after `release_delay`.
|
||||
fn with_delay(
|
||||
range: PoolConfig,
|
||||
host: PoolHost,
|
||||
release_delay: Duration,
|
||||
source: impl FnOnce(Arc<dyn BlockMappings>) -> Arc<dyn BlockSource>,
|
||||
) -> Result<Pool, Error> {
|
||||
if !range.is_valid() {
|
||||
return Err(Error::InvalidArgument);
|
||||
}
|
||||
let shared = Arc::new(Shared {
|
||||
range,
|
||||
host,
|
||||
release_delay,
|
||||
state: Mutex::new(State::default()),
|
||||
changed: Condvar::new(),
|
||||
});
|
||||
let source = source(Arc::new(Mappings(Arc::downgrade(&shared))));
|
||||
let thread = {
|
||||
let shared = Arc::clone(&shared);
|
||||
let source = Arc::clone(&source);
|
||||
std::thread::Builder::new()
|
||||
.name("reims-vgpu.graphics-pool".into())
|
||||
.spawn(move || shared.serve(source.as_ref()))
|
||||
.map_err(|_| Error::HostResources)?
|
||||
};
|
||||
Ok(Pool {
|
||||
shared,
|
||||
source: Some(source),
|
||||
thread: Some(thread),
|
||||
})
|
||||
}
|
||||
|
||||
/// Asks for at least `length` more bytes of pool: the pool's thread takes a block and has the
|
||||
/// host map it. Waits for nothing.
|
||||
pub fn grow(&self, length: u64) {
|
||||
self.shared.state.lock().asks.push_back(length);
|
||||
self.shared.changed.notify_all();
|
||||
}
|
||||
|
||||
/// The host mapped the piece at `physical_address` it was asked to add: lookups find it from
|
||||
/// now on. [`Error::InvalidArgument`] for an address the pool asked no add at, or one the host
|
||||
/// said it added already.
|
||||
pub fn added(&self, physical_address: u64) -> Result<(), Error> {
|
||||
let mut st = self.shared.state.lock();
|
||||
let p = (st.pieces.get_mut(&physical_address)).ok_or(Error::InvalidArgument)?;
|
||||
match p.mapped {
|
||||
Mapped::Adding => p.mapped = Mapped::Live,
|
||||
// An unmap came first: the host's remove follows its add.
|
||||
Mapped::Removing { .. } => {}
|
||||
Mapped::Live | Mapped::Removed => return Err(Error::InvalidArgument),
|
||||
}
|
||||
log::info!(
|
||||
"pool: {} MiB at {physical_address:#x} mapped into the guest",
|
||||
p.block.len >> 20
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The host took the piece at `physical_address` out of the guest's address space, and no
|
||||
/// thread of its own touches it: asked to ([`PoolHost::remove`]), or of its own, as it does
|
||||
/// before it releases the device. [`Error::InvalidArgument`] for an address the pool asked
|
||||
/// no add at.
|
||||
pub fn removed(&self, physical_address: u64) -> Result<(), Error> {
|
||||
let mut st = self.shared.state.lock();
|
||||
let p = (st.pieces.get_mut(&physical_address)).ok_or(Error::InvalidArgument)?;
|
||||
p.mapped = Mapped::Removed;
|
||||
drop(st);
|
||||
self.shared.changed.notify_all();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The guest put something in the piece at `physical_address`. Where no other piece is
|
||||
/// empty, the pool asks for a block more, so one stays as headroom.
|
||||
/// [`Error::InvalidArgument`] for an address where no piece the guest may use starts.
|
||||
pub fn piece_used(&self, physical_address: u64) -> Result<(), Error> {
|
||||
let mut st = self.shared.state.lock();
|
||||
let p = (st.pieces.get_mut(&physical_address)).ok_or(Error::InvalidArgument)?;
|
||||
if !p.usable() {
|
||||
return Err(Error::InvalidArgument);
|
||||
}
|
||||
p.empty_since = None;
|
||||
let headroom = (st.pieces.values()).any(|p| p.usable() && p.empty_since.is_some());
|
||||
if !headroom && st.asks.is_empty() {
|
||||
st.asks.push_back(BLOCK_LEN);
|
||||
}
|
||||
drop(st);
|
||||
self.shared.changed.notify_all();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The guest emptied the piece at `physical_address`: no guest mapping of it is left (the
|
||||
/// kext unmapped every process's mapping into it and holds none of its own), and nothing of
|
||||
/// the guest's lies in it. From now on the guest puts nothing there until it says
|
||||
/// [`Pool::piece_used`]: [`RELEASE_DELAY`] later, if it is still empty and a lower piece is
|
||||
/// empty too, its block goes back to the source, and the guest may not use it again until the
|
||||
/// device hands it out anew. [`Error::InvalidArgument`] for an address where no piece the
|
||||
/// guest may use starts.
|
||||
pub fn piece_empty(&self, physical_address: u64) -> Result<(), Error> {
|
||||
let mut st = self.shared.state.lock();
|
||||
let p = (st.pieces.get_mut(&physical_address)).ok_or(Error::InvalidArgument)?;
|
||||
if !p.usable() {
|
||||
return Err(Error::InvalidArgument);
|
||||
}
|
||||
if p.empty_since.is_none() {
|
||||
p.empty_since = Some(Instant::now());
|
||||
}
|
||||
drop(st);
|
||||
self.shared.changed.notify_all();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The live piece the guest may use that holds `length` bytes from `physical_address`, held
|
||||
/// until the answer drops; `None` where none holds all of them.
|
||||
pub fn find(&self, physical_address: u64, length: u64) -> Option<PieceHold> {
|
||||
let mut st = self.shared.state.lock();
|
||||
let (&start, p) = st.pieces.range_mut(..=physical_address).next_back()?;
|
||||
let offset = physical_address.checked_sub(start)?;
|
||||
let end = offset.checked_add(length)?;
|
||||
if p.mapped != Mapped::Live || !p.held || end > p.block.len {
|
||||
return None;
|
||||
}
|
||||
let contents = p.block.contents?;
|
||||
p.holds = p.holds.checked_add(1)?;
|
||||
let block = p.block.id;
|
||||
drop(st);
|
||||
let offset_bytes = usize::try_from(offset).ok()?;
|
||||
// SAFETY: `offset` is inside the block's mapping, checked above.
|
||||
let host = unsafe { NonNull::new_unchecked(contents.as_ptr().add(offset_bytes)) };
|
||||
Some(PieceHold {
|
||||
shared: Arc::clone(&self.shared),
|
||||
physical_address: start,
|
||||
block,
|
||||
offset,
|
||||
host,
|
||||
})
|
||||
}
|
||||
|
||||
/// The pieces the guest may use and the host mapped, by address: `(physical_address,
|
||||
/// length)`.
|
||||
pub fn live(&self) -> Vec<(u64, u64)> {
|
||||
let st = self.shared.state.lock();
|
||||
(st.pieces.iter())
|
||||
.filter(|(_, p)| p.mapped == Mapped::Live && p.held)
|
||||
.map(|(&a, p)| (a, p.block.len))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The device's release: the host removed every piece it added. Ends the pool's thread, then
|
||||
/// lets go of the source; from now on an unmap waits only for the holds on its piece.
|
||||
pub(crate) fn close(&mut self) {
|
||||
self.shared.state.lock().closed = true;
|
||||
self.shared.changed.notify_all();
|
||||
if let Some(t) = self.thread.take() {
|
||||
let _ = t.join();
|
||||
}
|
||||
self.source = None;
|
||||
}
|
||||
|
||||
/// The block source, for the tests.
|
||||
#[cfg(test)]
|
||||
fn source(&self) -> Option<&Arc<dyn BlockSource>> {
|
||||
self.source.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Pool {
|
||||
fn drop(&mut self) {
|
||||
self.close();
|
||||
}
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
/// The pool's thread: takes a block for each ask and has the host map it, and gives back the
|
||||
/// pieces that stayed empty past their delay, until the pool closes.
|
||||
fn serve(&self, source: &dyn BlockSource) {
|
||||
loop {
|
||||
let mut st = self.state.lock();
|
||||
if st.closed {
|
||||
return;
|
||||
}
|
||||
if let Some(length) = st.asks.pop_front() {
|
||||
drop(st);
|
||||
match source.take_block(MemoryClass::Shared, length) {
|
||||
Ok(block) => self.place(source, block),
|
||||
Err(e) => log::warn!(kind:? = e; "pool: no block of {length} bytes: {e:?}"),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let now = Instant::now();
|
||||
let (due, next) = self.due(&st, now);
|
||||
if let Some((at, block)) = due {
|
||||
if let Some(p) = st.pieces.get_mut(&at) {
|
||||
p.held = false;
|
||||
p.empty_since = None;
|
||||
}
|
||||
drop(st);
|
||||
log::info!("pool: the empty piece at {at:#x} goes back to the source");
|
||||
if let Err(e) = source.release_block(block) {
|
||||
log::warn!(kind:? = e; "pool: the source refused a block back: {e:?}");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match next {
|
||||
Some(when) => {
|
||||
let _ = self.changed.wait_until(&mut st, when);
|
||||
}
|
||||
None => self.changed.wait(&mut st),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The piece whose block goes back now, if any, and when the next may: of the empty pieces
|
||||
/// the guest may use, every one but the lowest, once empty for the delay.
|
||||
fn due(&self, st: &State, now: Instant) -> (Option<(u64, BlockId)>, Option<Instant>) {
|
||||
let mut empty = (st.pieces.iter()).filter_map(|(&at, p)| {
|
||||
let since = p.empty_since.filter(|_| p.usable())?;
|
||||
Some((at, p.block.id, since.checked_add(self.release_delay)?))
|
||||
});
|
||||
// The lowest empty piece is the headroom.
|
||||
let _ = empty.next();
|
||||
let mut next: Option<Instant> = None;
|
||||
for (at, block, when) in empty {
|
||||
if when <= now {
|
||||
return (Some((at, block)), None);
|
||||
}
|
||||
next = Some(next.map_or(when, |n| n.min(when)));
|
||||
}
|
||||
(None, next)
|
||||
}
|
||||
|
||||
/// Places `block` at the lowest free address that holds it and asks the host to map it; a
|
||||
/// block the pool placed before (given back, then taken again) keeps its piece, mapped.
|
||||
fn place(&self, source: &dyn BlockSource, block: BlockInfo) {
|
||||
let mut st = self.state.lock();
|
||||
if let Some(&at) = st.by_block.get(&block.id) {
|
||||
if let Some(p) = st.pieces.get_mut(&at) {
|
||||
p.held = true;
|
||||
p.empty_since = Some(Instant::now());
|
||||
}
|
||||
return;
|
||||
}
|
||||
let Some(contents) = block.contents else {
|
||||
drop(st);
|
||||
let _ = source.release_block(block.id);
|
||||
return;
|
||||
};
|
||||
let Some(at) = first_fit(self.range, &st.pieces, block.len) else {
|
||||
if !std::mem::replace(&mut st.full_logged, true) {
|
||||
log::warn!(
|
||||
"pool: the range at {:#x} of {} MiB holds no {} MiB more: the block goes back",
|
||||
self.range.physical_address,
|
||||
self.range.physical_length >> 20,
|
||||
block.len >> 20
|
||||
);
|
||||
}
|
||||
drop(st);
|
||||
let _ = source.release_block(block.id);
|
||||
return;
|
||||
};
|
||||
st.pieces.insert(
|
||||
at,
|
||||
Piece {
|
||||
block,
|
||||
mapped: Mapped::Adding,
|
||||
held: true,
|
||||
empty_since: Some(Instant::now()),
|
||||
holds: 0,
|
||||
},
|
||||
);
|
||||
st.by_block.insert(block.id, at);
|
||||
drop(st);
|
||||
(self.host.add)(at, contents.as_ptr(), block.len);
|
||||
}
|
||||
|
||||
/// [`BlockMappings::unmap`] of the pool's: the module doc's "Release".
|
||||
fn unmap(&self, block: BlockId) {
|
||||
let mut st = self.state.lock();
|
||||
if !st.by_block.contains_key(&block) {
|
||||
return;
|
||||
}
|
||||
let mut warned = false;
|
||||
let started = Instant::now();
|
||||
loop {
|
||||
let closed = st.closed;
|
||||
let Some(&at) = st.by_block.get(&block) else {
|
||||
return;
|
||||
};
|
||||
let Some(p) = st.pieces.get_mut(&at) else {
|
||||
return;
|
||||
};
|
||||
match p.mapped {
|
||||
Mapped::Adding | Mapped::Live => {
|
||||
p.mapped = Mapped::Removing { asked: false };
|
||||
p.held = false;
|
||||
}
|
||||
Mapped::Removing { asked: false } if p.holds == 0 && !closed => {
|
||||
p.mapped = Mapped::Removing { asked: true };
|
||||
let len = p.block.len;
|
||||
drop(st);
|
||||
(self.host.remove)(at, len);
|
||||
st = self.state.lock();
|
||||
}
|
||||
Mapped::Removing { .. } if p.holds == 0 && closed => p.mapped = Mapped::Removed,
|
||||
Mapped::Removed if p.holds == 0 => {
|
||||
st.pieces.remove(&at);
|
||||
st.by_block.remove(&block);
|
||||
return;
|
||||
}
|
||||
_ => {
|
||||
if !warned && started.elapsed() > Duration::from_secs(1) {
|
||||
warned = true;
|
||||
log::warn!(
|
||||
"pool: the unmap of the piece at {at:#x} still waits after 1 s: {}",
|
||||
if p.holds > 0 {
|
||||
"a thread of the device's holds it"
|
||||
} else {
|
||||
"the host has not removed it"
|
||||
}
|
||||
);
|
||||
}
|
||||
let _ = self
|
||||
.changed
|
||||
.wait_for(&mut st, Duration::from_millis(250));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The lowest address in `range`, a multiple of [`PIECE_ALIGN`], where `length` bytes overlap no
|
||||
/// piece of `pieces`; `None` where none is left.
|
||||
fn first_fit(range: PoolConfig, pieces: &BTreeMap<u64, Piece>, length: u64) -> Option<u64> {
|
||||
let end = range.physical_address.checked_add(range.physical_length)?;
|
||||
let mut at = range.physical_address;
|
||||
for (&start, p) in pieces {
|
||||
if at.checked_add(length)? <= start {
|
||||
break;
|
||||
}
|
||||
let past = start.checked_add(p.block.len)?;
|
||||
at = at.max(past.checked_next_multiple_of(PIECE_ALIGN)?);
|
||||
}
|
||||
(at.checked_add(length)? <= end).then_some(at)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,162 @@
|
||||
//! [`HostBlocks`]: a [`BlockSource`] of the process's own memory, which hands blocks out, keeps
|
||||
//! them ready and frees them as metal2vulkan-rt's device does, until the pool takes its blocks from
|
||||
//! that runtime: then only the source changes.
|
||||
//!
|
||||
//! Each block is zeroed memory of the process's, aligned to 2 MiB and touched a byte a page before
|
||||
//! it goes out, as the runtime touches a Shared block. A block given back goes to the ready set
|
||||
//! with its id and mapping; past two ready blocks, the oldest is freed after the pool's
|
||||
//! [`BlockMappings::unmap`], on the thread that gave the block back. At the source's end, once
|
||||
//! nothing holds it, every block it handed out or keeps ready is unmapped, then freed. Its blocks
|
||||
//! have no GPU: `gpu_address` is 0.
|
||||
|
||||
use std::alloc::Layout;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::ptr::NonNull;
|
||||
use std::sync::Arc;
|
||||
|
||||
use parking_lot::Mutex;
|
||||
|
||||
use super::{BLOCK_LEN, BlockError, BlockId, BlockInfo, BlockMappings, BlockSource, MemoryClass};
|
||||
|
||||
/// The alignment of a block's memory: 2 MiB, a large page.
|
||||
const ALIGN: usize = 2 << 20;
|
||||
|
||||
/// How many blocks given back stay ready: past them the oldest is freed.
|
||||
const READY_MAX: usize = 2;
|
||||
|
||||
/// One block of the process's memory.
|
||||
struct Block {
|
||||
info: BlockInfo,
|
||||
layout: Layout,
|
||||
}
|
||||
|
||||
impl Block {
|
||||
/// A zeroed block of `len` bytes, every page touched; `None` where the host refuses it.
|
||||
fn new(id: BlockId, len: u64) -> Option<Block> {
|
||||
let layout = Layout::from_size_align(usize::try_from(len).ok()?, ALIGN).ok()?;
|
||||
// SAFETY: `layout` has a non-zero size: `len` is at least a page.
|
||||
let ptr = NonNull::new(unsafe { std::alloc::alloc_zeroed(layout) })?;
|
||||
// The first CPU write to a fresh mapping is the slow one: done here, off the guest's path.
|
||||
for page in (0..layout.size()).step_by(4096) {
|
||||
// SAFETY: inside the allocation.
|
||||
unsafe { ptr.as_ptr().add(page).write_volatile(0) };
|
||||
}
|
||||
Some(Block {
|
||||
info: BlockInfo {
|
||||
id,
|
||||
class: MemoryClass::Shared,
|
||||
len,
|
||||
gpu_address: 0,
|
||||
contents: Some(ptr),
|
||||
},
|
||||
layout,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Block {
|
||||
fn drop(&mut self) {
|
||||
if let Some(ptr) = self.info.contents {
|
||||
// SAFETY: allocated with this layout in `Block::new`.
|
||||
unsafe { std::alloc::dealloc(ptr.as_ptr(), self.layout) };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the source's lock holds.
|
||||
#[derive(Default)]
|
||||
struct Blocks {
|
||||
/// The blocks handed out, by id.
|
||||
out: HashMap<BlockId, Block>,
|
||||
/// The pooled blocks given back, oldest first.
|
||||
ready: VecDeque<Block>,
|
||||
/// The id the next new block takes.
|
||||
next: u32,
|
||||
}
|
||||
|
||||
/// Blocks of the process's own memory ([module doc](self)).
|
||||
pub(crate) struct HostBlocks {
|
||||
mappings: Arc<dyn BlockMappings>,
|
||||
blocks: Mutex<Blocks>,
|
||||
}
|
||||
|
||||
impl HostBlocks {
|
||||
/// A source whose blocks are unmapped through `mappings` before they are freed.
|
||||
pub(crate) fn new(mappings: Arc<dyn BlockMappings>) -> HostBlocks {
|
||||
HostBlocks {
|
||||
mappings,
|
||||
blocks: Mutex::new(Blocks {
|
||||
next: 1,
|
||||
..Blocks::default()
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// How many blocks it has, handed out and ready: for the tests.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn counts(&self) -> (usize, usize) {
|
||||
let b = self.blocks.lock();
|
||||
(b.out.len(), b.ready.len())
|
||||
}
|
||||
}
|
||||
|
||||
impl BlockSource for HostBlocks {
|
||||
fn take_block(&self, class: MemoryClass, len: u64) -> Result<BlockInfo, BlockError> {
|
||||
if class != MemoryClass::Shared {
|
||||
return Err(BlockError::Length);
|
||||
}
|
||||
let mut b = self.blocks.lock();
|
||||
if len <= BLOCK_LEN
|
||||
&& let Some(block) = b.ready.pop_front()
|
||||
{
|
||||
let info = block.info;
|
||||
b.out.insert(info.id, block);
|
||||
return Ok(info);
|
||||
}
|
||||
let id = BlockId(b.next);
|
||||
b.next = b.next.checked_add(1).ok_or(BlockError::OutOfMemory)?;
|
||||
drop(b);
|
||||
let len = if len <= BLOCK_LEN {
|
||||
BLOCK_LEN
|
||||
} else {
|
||||
len.checked_next_multiple_of(ALIGN as u64)
|
||||
.ok_or(BlockError::Length)?
|
||||
};
|
||||
let block = Block::new(id, len).ok_or(BlockError::OutOfMemory)?;
|
||||
let info = block.info;
|
||||
self.blocks.lock().out.insert(id, block);
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
fn release_block(&self, block: BlockId) -> Result<(), BlockError> {
|
||||
let mut b = self.blocks.lock();
|
||||
let given = b.out.remove(&block).ok_or(BlockError::NotHeld)?;
|
||||
if given.info.len > BLOCK_LEN {
|
||||
drop(b);
|
||||
self.mappings.unmap(block);
|
||||
drop(given);
|
||||
return Ok(());
|
||||
}
|
||||
b.ready.push_back(given);
|
||||
let surplus = (b.ready.len() > READY_MAX)
|
||||
.then(|| b.ready.pop_front())
|
||||
.flatten();
|
||||
drop(b);
|
||||
if let Some(old) = surplus {
|
||||
self.mappings.unmap(old.info.id);
|
||||
drop(old);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for HostBlocks {
|
||||
/// Every block, handed out or ready, is unmapped, then freed.
|
||||
fn drop(&mut self) {
|
||||
let b = std::mem::take(&mut *self.blocks.lock());
|
||||
for block in b.out.into_values().chain(b.ready) {
|
||||
self.mappings.unmap(block.info.id);
|
||||
drop(block);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,388 @@
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use parking_lot::{Condvar, Mutex};
|
||||
|
||||
use super::*;
|
||||
|
||||
const BASE: u64 = 52 << 30;
|
||||
const MIB: u64 = 1 << 20;
|
||||
|
||||
/// What the pool asked of the host, in order.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Call {
|
||||
Add(u64, u64),
|
||||
Remove(u64, u64),
|
||||
}
|
||||
|
||||
/// A host that records the pool's asks and answers none by itself.
|
||||
#[derive(Default)]
|
||||
struct Host {
|
||||
calls: Mutex<Vec<Call>>,
|
||||
changed: Condvar,
|
||||
}
|
||||
|
||||
impl Host {
|
||||
fn pool_host(self: &Arc<Self>) -> PoolHost {
|
||||
let add = Arc::clone(self);
|
||||
let remove = Arc::clone(self);
|
||||
PoolHost {
|
||||
add: Arc::new(move |at, _host, len| add.record(Call::Add(at, len))),
|
||||
remove: Arc::new(move |at, len| remove.record(Call::Remove(at, len))),
|
||||
}
|
||||
}
|
||||
|
||||
fn record(&self, call: Call) {
|
||||
self.calls.lock().push(call);
|
||||
self.changed.notify_all();
|
||||
}
|
||||
|
||||
/// The calls once there are at least `n`, or the test fails after 10 s.
|
||||
fn wait_for(&self, n: usize) -> Vec<Call> {
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
let mut calls = self.calls.lock();
|
||||
while calls.len() < n {
|
||||
assert!(
|
||||
!self.changed.wait_until(&mut calls, deadline).timed_out(),
|
||||
"the pool asked {:?}, not {n} calls",
|
||||
*calls
|
||||
);
|
||||
}
|
||||
calls.clone()
|
||||
}
|
||||
|
||||
fn calls(&self) -> Vec<Call> {
|
||||
self.calls.lock().clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// The host blocks the pool takes from, kept for the tests' counts.
|
||||
fn pool(range: PoolConfig, host: &Arc<Host>, delay: Duration) -> (Pool, Arc<HostBlocks>) {
|
||||
let kept: Arc<Mutex<Option<Arc<HostBlocks>>>> = Arc::default();
|
||||
let k = Arc::clone(&kept);
|
||||
let pool = Pool::with_delay(range, host.pool_host(), delay, move |m| {
|
||||
let blocks = Arc::new(HostBlocks::new(m));
|
||||
*k.lock() = Some(Arc::clone(&blocks));
|
||||
let source: Arc<dyn BlockSource> = blocks;
|
||||
source
|
||||
})
|
||||
.unwrap();
|
||||
let blocks = kept.lock().take().unwrap();
|
||||
(pool, blocks)
|
||||
}
|
||||
|
||||
fn range(gib: u64) -> PoolConfig {
|
||||
PoolConfig {
|
||||
physical_address: BASE,
|
||||
physical_length: gib << 30,
|
||||
}
|
||||
}
|
||||
|
||||
const LONG: Duration = Duration::from_secs(3600);
|
||||
|
||||
#[test]
|
||||
fn a_range_must_be_whole_large_pages_and_not_empty() {
|
||||
assert!(range(64).is_valid());
|
||||
for bad in [
|
||||
PoolConfig::default(),
|
||||
PoolConfig {
|
||||
physical_address: BASE + 4096,
|
||||
physical_length: 1 << 30,
|
||||
},
|
||||
PoolConfig {
|
||||
physical_address: BASE,
|
||||
physical_length: (1 << 30) + 4096,
|
||||
},
|
||||
PoolConfig {
|
||||
physical_address: u64::MAX - (2 << 20) + 1,
|
||||
physical_length: 4 << 20,
|
||||
},
|
||||
] {
|
||||
assert!(!bad.is_valid(), "{bad:?}");
|
||||
}
|
||||
let host = Arc::new(Host::default());
|
||||
assert_eq!(
|
||||
Pool::new(PoolConfig::default(), host.pool_host(), |m| Arc::new(
|
||||
HostBlocks::new(m)
|
||||
))
|
||||
.err(),
|
||||
Some(Error::InvalidArgument)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pieces_go_out_at_ascending_addresses_from_the_range_start() {
|
||||
let host = Arc::new(Host::default());
|
||||
let (pool, _blocks) = pool(range(64), &host, LONG);
|
||||
pool.grow(BLOCK_LEN);
|
||||
pool.grow(1);
|
||||
pool.grow(BLOCK_LEN + 1);
|
||||
assert_eq!(
|
||||
host.wait_for(3),
|
||||
[
|
||||
Call::Add(BASE, BLOCK_LEN),
|
||||
Call::Add(BASE + BLOCK_LEN, BLOCK_LEN),
|
||||
// A dedicated block, rounded up to 2 MiB.
|
||||
Call::Add(BASE + 2 * BLOCK_LEN, BLOCK_LEN + 2 * MIB),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_piece_is_found_only_once_the_host_added_it() {
|
||||
let host = Arc::new(Host::default());
|
||||
let (pool, _blocks) = pool(range(64), &host, LONG);
|
||||
pool.grow(BLOCK_LEN);
|
||||
host.wait_for(1);
|
||||
assert!(pool.find(BASE, 4096).is_none());
|
||||
assert!(pool.live().is_empty());
|
||||
pool.added(BASE).unwrap();
|
||||
let hold = pool.find(BASE + 8192, 4096).unwrap();
|
||||
assert_eq!(hold.offset, 8192);
|
||||
assert_eq!(pool.live(), [(BASE, BLOCK_LEN)]);
|
||||
// Past the piece's end, and below the range: nothing.
|
||||
assert!(pool.find(BASE + BLOCK_LEN - 4096, 8192).is_none());
|
||||
assert!(pool.find(BASE - 4096, 4096).is_none());
|
||||
// The host says it once, and only where the pool asked.
|
||||
assert_eq!(pool.added(BASE), Err(Error::InvalidArgument));
|
||||
assert_eq!(pool.added(BASE + BLOCK_LEN), Err(Error::InvalidArgument));
|
||||
assert_eq!(pool.removed(BASE + 2 * MIB), Err(Error::InvalidArgument));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_piece_holds_the_blocks_memory_the_host_maps() {
|
||||
let host = Arc::new(Host::default());
|
||||
let (pool, _blocks) = pool(range(64), &host, LONG);
|
||||
pool.grow(BLOCK_LEN);
|
||||
host.wait_for(1);
|
||||
pool.added(BASE).unwrap();
|
||||
let a = pool.find(BASE + 4096, 8).unwrap();
|
||||
// SAFETY: inside the block, which the hold keeps.
|
||||
unsafe { a.host.as_ptr().cast::<u64>().write(0x1234_5678) };
|
||||
let b = pool.find(BASE + 4096, 8).unwrap();
|
||||
// SAFETY: as above.
|
||||
assert_eq!(unsafe { b.host.as_ptr().cast::<u64>().read() }, 0x1234_5678);
|
||||
}
|
||||
|
||||
/// Gives every block back through the pool's hook, as the source does when it frees surplus
|
||||
/// blocks, and returns the thread doing it.
|
||||
fn unmap_in_background(pool: &Pool, block: BlockId) -> std::thread::JoinHandle<()> {
|
||||
let mappings = Mappings(Arc::downgrade(&pool.shared));
|
||||
std::thread::spawn(move || mappings.unmap(block))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unmap_returns_only_once_the_host_removed_the_piece() {
|
||||
let host = Arc::new(Host::default());
|
||||
let (pool, _blocks) = pool(range(64), &host, LONG);
|
||||
pool.grow(BLOCK_LEN);
|
||||
host.wait_for(1);
|
||||
pool.added(BASE).unwrap();
|
||||
let id = pool.find(BASE, 1).unwrap().block;
|
||||
let unmap = unmap_in_background(&pool, id);
|
||||
assert_eq!(host.wait_for(2)[1], Call::Remove(BASE, BLOCK_LEN));
|
||||
// Out of the lookups as soon as the unmap began.
|
||||
assert!(pool.find(BASE, 1).is_none());
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
assert!(!unmap.is_finished());
|
||||
pool.removed(BASE).unwrap();
|
||||
unmap.join().unwrap();
|
||||
// The address is free again: the next block goes there.
|
||||
pool.grow(BLOCK_LEN);
|
||||
assert_eq!(host.wait_for(3)[2], Call::Add(BASE, BLOCK_LEN));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unmap_asks_the_host_only_once_no_hold_is_left() {
|
||||
let host = Arc::new(Host::default());
|
||||
let (pool, _blocks) = pool(range(64), &host, LONG);
|
||||
pool.grow(BLOCK_LEN);
|
||||
host.wait_for(1);
|
||||
pool.added(BASE).unwrap();
|
||||
let hold = pool.find(BASE, 1).unwrap();
|
||||
let unmap = unmap_in_background(&pool, hold.block);
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
assert_eq!(host.calls().len(), 1, "no remove while a hold lives");
|
||||
drop(hold);
|
||||
assert_eq!(host.wait_for(2)[1], Call::Remove(BASE, BLOCK_LEN));
|
||||
pool.removed(BASE).unwrap();
|
||||
unmap.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unmap_before_the_hosts_add_answers_still_waits_for_the_remove() {
|
||||
let host = Arc::new(Host::default());
|
||||
let (pool, blocks) = pool(range(64), &host, LONG);
|
||||
pool.grow(BLOCK_LEN);
|
||||
host.wait_for(1);
|
||||
let id = BlockId(1);
|
||||
assert_eq!(blocks.counts(), (1, 0));
|
||||
let unmap = unmap_in_background(&pool, id);
|
||||
assert_eq!(host.wait_for(2)[1], Call::Remove(BASE, BLOCK_LEN));
|
||||
// The host's add, which it queued first, then its remove.
|
||||
pool.added(BASE).unwrap();
|
||||
assert!(pool.find(BASE, 1).is_none());
|
||||
pool.removed(BASE).unwrap();
|
||||
unmap.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_the_release_the_sources_unmaps_ask_the_host_nothing() {
|
||||
let host = Arc::new(Host::default());
|
||||
let (mut pool, blocks) = pool(range(64), &host, LONG);
|
||||
pool.grow(BLOCK_LEN);
|
||||
pool.grow(BLOCK_LEN);
|
||||
host.wait_for(2);
|
||||
pool.added(BASE).unwrap();
|
||||
// The host removed both pieces before the release: it says so of the live one, as QEMU's
|
||||
// pieces' ends do; of the other it says nothing, and the release stands for it.
|
||||
pool.removed(BASE).unwrap();
|
||||
pool.close();
|
||||
drop(blocks);
|
||||
assert_eq!(host.calls().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_range_gives_the_block_back() {
|
||||
let host = Arc::new(Host::default());
|
||||
let (pool, blocks) = pool(
|
||||
PoolConfig {
|
||||
physical_address: BASE,
|
||||
physical_length: BLOCK_LEN + 2 * MIB,
|
||||
},
|
||||
&host,
|
||||
LONG,
|
||||
);
|
||||
pool.grow(BLOCK_LEN);
|
||||
host.wait_for(1);
|
||||
pool.grow(BLOCK_LEN);
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while blocks.counts() != (1, 1) {
|
||||
assert!(Instant::now() < deadline, "{:?}", blocks.counts());
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
assert_eq!(host.calls().len(), 1);
|
||||
}
|
||||
|
||||
/// Waits until the source holds `out` blocks handed out and `ready` ready.
|
||||
fn wait_counts(blocks: &HostBlocks, out: usize, ready: usize) {
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while blocks.counts() != (out, ready) {
|
||||
assert!(Instant::now() < deadline, "{:?}", blocks.counts());
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_piece_above_the_headroom_goes_back_after_the_delay() {
|
||||
let delay = Duration::from_millis(300);
|
||||
let host = Arc::new(Host::default());
|
||||
let (pool, blocks) = pool(range(64), &host, delay);
|
||||
let start = Instant::now();
|
||||
pool.grow(BLOCK_LEN);
|
||||
pool.grow(BLOCK_LEN);
|
||||
host.wait_for(2);
|
||||
pool.added(BASE).unwrap();
|
||||
pool.added(BASE + BLOCK_LEN).unwrap();
|
||||
wait_counts(&blocks, 1, 1);
|
||||
assert!(start.elapsed() >= delay, "{:?}", start.elapsed());
|
||||
// The higher one went; it stays mapped until the source frees it, and nothing finds it.
|
||||
assert_eq!(pool.live(), [(BASE, BLOCK_LEN)]);
|
||||
assert!(pool.find(BASE + BLOCK_LEN, 1).is_none());
|
||||
assert_eq!(
|
||||
pool.piece_used(BASE + BLOCK_LEN),
|
||||
Err(Error::InvalidArgument)
|
||||
);
|
||||
assert_eq!(host.calls().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_lowest_empty_piece_stays_as_headroom() {
|
||||
let delay = Duration::from_millis(50);
|
||||
let host = Arc::new(Host::default());
|
||||
let (pool, blocks) = pool(range(64), &host, delay);
|
||||
pool.grow(BLOCK_LEN);
|
||||
host.wait_for(1);
|
||||
pool.added(BASE).unwrap();
|
||||
std::thread::sleep(delay * 6);
|
||||
assert_eq!(blocks.counts(), (1, 0));
|
||||
assert_eq!(pool.live(), [(BASE, BLOCK_LEN)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_piece_used_again_within_the_delay_is_kept() {
|
||||
let delay = Duration::from_millis(400);
|
||||
let host = Arc::new(Host::default());
|
||||
let (pool, blocks) = pool(range(64), &host, delay);
|
||||
pool.grow(BLOCK_LEN);
|
||||
pool.grow(BLOCK_LEN);
|
||||
host.wait_for(2);
|
||||
pool.added(BASE).unwrap();
|
||||
pool.added(BASE + BLOCK_LEN).unwrap();
|
||||
pool.piece_used(BASE).unwrap();
|
||||
pool.piece_used(BASE + BLOCK_LEN).unwrap();
|
||||
// Using the last empty piece asked for a block more: the headroom.
|
||||
assert_eq!(host.wait_for(3)[2], Call::Add(BASE + 2 * BLOCK_LEN, BLOCK_LEN));
|
||||
pool.added(BASE + 2 * BLOCK_LEN).unwrap();
|
||||
// Emptied, then used again within the delay: kept.
|
||||
pool.piece_empty(BASE + BLOCK_LEN).unwrap();
|
||||
std::thread::sleep(delay / 4);
|
||||
pool.piece_used(BASE + BLOCK_LEN).unwrap();
|
||||
std::thread::sleep(delay * 2);
|
||||
assert_eq!(blocks.counts(), (3, 0));
|
||||
// Emptied for good: the lowest empty piece, now this one, stays as the headroom, and the
|
||||
// one above it, empty past the delay, goes.
|
||||
pool.piece_empty(BASE + BLOCK_LEN).unwrap();
|
||||
wait_counts(&blocks, 2, 1);
|
||||
assert_eq!(pool.live(), [(BASE, BLOCK_LEN), (BASE + BLOCK_LEN, BLOCK_LEN)]);
|
||||
assert_eq!(host.calls().len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_taken_again_keeps_its_address_and_asks_the_host_nothing() {
|
||||
let delay = Duration::from_millis(50);
|
||||
let host = Arc::new(Host::default());
|
||||
let (pool, blocks) = pool(range(64), &host, delay);
|
||||
pool.grow(BLOCK_LEN);
|
||||
pool.grow(BLOCK_LEN);
|
||||
host.wait_for(2);
|
||||
pool.added(BASE).unwrap();
|
||||
pool.added(BASE + BLOCK_LEN).unwrap();
|
||||
wait_counts(&blocks, 1, 1);
|
||||
// The headroom piece is used: the pool asks for a block more, and the source hands the ready
|
||||
// one out again.
|
||||
pool.piece_used(BASE).unwrap();
|
||||
wait_counts(&blocks, 2, 0);
|
||||
assert_eq!(
|
||||
pool.live(),
|
||||
[(BASE, BLOCK_LEN), (BASE + BLOCK_LEN, BLOCK_LEN)]
|
||||
);
|
||||
assert_eq!(host.calls().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ready_blocks_past_two_are_unmapped_before_they_are_freed() {
|
||||
let delay = Duration::from_millis(30);
|
||||
let host = Arc::new(Host::default());
|
||||
let (pool, blocks) = pool(range(64), &host, delay);
|
||||
for _ in 0..4 {
|
||||
pool.grow(BLOCK_LEN);
|
||||
}
|
||||
host.wait_for(4);
|
||||
for i in 0..4 {
|
||||
pool.added(BASE + i * BLOCK_LEN).unwrap();
|
||||
}
|
||||
// Three go back above the headroom; the source keeps two ready and frees the oldest, whose
|
||||
// unmap waits for the host.
|
||||
let calls = host.wait_for(5);
|
||||
let Call::Remove(at, len) = calls[4] else {
|
||||
panic!("{calls:?}");
|
||||
};
|
||||
assert_eq!(len, BLOCK_LEN);
|
||||
assert_eq!(blocks.counts(), (1, 2));
|
||||
pool.removed(at).unwrap();
|
||||
wait_counts(&blocks, 1, 2);
|
||||
std::thread::sleep(delay * 4);
|
||||
assert_eq!(host.calls().len(), 5);
|
||||
assert!(pool.source().is_some());
|
||||
}
|
||||
+28
-6
@@ -56,14 +56,16 @@ Every struct the host fills in, and every struct the library hands out, starts w
|
||||
zero, and is `RVG_ERR_UNSUPPORTED` otherwise. A host built against a newer header then works
|
||||
with an older library as long as it leaves the new fields at zero.
|
||||
- `RvgWindowConfig` and `RvgWindowCallbacks` are at their first version.
|
||||
`RvgGraphicsDeviceConfig` is at its fourth: the second added `guest_arch`, and a host built
|
||||
`RvgGraphicsDeviceConfig` is at its fifth: the second added `guest_arch`, and a host built
|
||||
before it, whose `struct_size` ends before that field, serves an x86-64 guest; the third added
|
||||
`doorbell_pages`, and a host built before it maps no doorbell pages; the fourth added
|
||||
`display_count` and `display_windows`, and a host built before it makes a device of one
|
||||
display. `RvgGraphicsCallbacks` is at its fourth: the second added `route_doorbell`, and a host
|
||||
built before it routes no doorbell; the third added `route_doorbell_page`, and a host built
|
||||
before it routes none on a doorbell page; the fourth added `cursor_glyph_at`, `cursor_show_at`
|
||||
and `cursor_move_at`, and a host built before it is told the cursor of display 0 alone. A
|
||||
display; the fifth added `pool_physical_address` and `pool_physical_length`, and a host built
|
||||
before it has no pool. `RvgGraphicsCallbacks` is at its fifth: the second added
|
||||
`route_doorbell`, and a host built before it routes no doorbell; the third added
|
||||
`route_doorbell_page`, and a host built before it routes none on a doorbell page; the fourth
|
||||
added `cursor_glyph_at`, `cursor_show_at` and `cursor_move_at`, and a host built before it is
|
||||
told the cursor of display 0 alone; the fifth added `pool_add` and `pool_remove`. A
|
||||
struct that
|
||||
grows keeps its first version's size as the least it accepts, and reads the later fields of a
|
||||
host built before them as zero.
|
||||
@@ -82,7 +84,7 @@ unknown status as a failure.
|
||||
| value | name | when |
|
||||
|---|---|---|
|
||||
| 0 | `RVG_OK` | |
|
||||
| 1 | `RVG_ERR_INVALID_ARGUMENT` | a NULL handle, config or out-pointer where one is needed; a `struct_size` too small; a refused memory file; a `guest_arch` that is none of `RVG_GUEST_ARCH_*`; a `doorbell_pages` other than 0 or 1; a `display_count` past `RVG_GRAPHICS_DISPLAYS_MAX`, or `display_windows` not given exactly where `window` is (one for each display from 1), or holding NULL; a doorbell that is not open, or a second one; `read_display`'s destination missing or too short; `read_display_at`'s display at or past the device's count |
|
||||
| 1 | `RVG_ERR_INVALID_ARGUMENT` | a NULL handle, config or out-pointer where one is needed; a `struct_size` too small; a refused memory file; a `guest_arch` that is none of `RVG_GUEST_ARCH_*`; a `doorbell_pages` other than 0 or 1; a `display_count` past `RVG_GRAPHICS_DISPLAYS_MAX`, or `display_windows` not given exactly where `window` is (one for each display from 1), or holding NULL; a pool range not in whole 2 MiB, past the address space, overlapping the memory map, or given without `pool_add` and `pool_remove`; a doorbell that is not open, or a second one; `read_display`'s destination missing or too short; `read_display_at`'s display at or past the device's count; a pool call on a device without a pool, an address the device asked no add at, a second `pool_added` of one piece, or a `pool_grow` of 0 bytes |
|
||||
| 2 | `RVG_ERR_UNSUPPORTED` | a larger `struct_size` with non-zero bytes the library does not know |
|
||||
| 3 | `RVG_ERR_METAL` | the platform refused the display's texture or its draw (`rvg_graphics_device_read_display`) |
|
||||
| 4 | `RVG_ERR_GPU` | the call's GPU work ended with an error |
|
||||
@@ -171,6 +173,21 @@ starts again. QEMU releases its device as it quits, once the VM stopped for good
|
||||
pauses it keeps its device to the exit, and so does a quit while a read of its display
|
||||
(`rvg_graphics_device_read_display`) still waits for its draw on the GPU 5 s into the teardown.
|
||||
|
||||
### The guest's Shared pool
|
||||
|
||||
A host that reserves a range of guest physical addresses for the guest's Shared pool
|
||||
(`pool_physical_address`, `pool_physical_length`) maps the device's blocks there as the pool grows
|
||||
(`pool_add`, answered by `rvg_graphics_device_pool_added`) and unmaps them as the device frees them
|
||||
(`pool_remove`, answered by `rvg_graphics_device_pool_removed`). The device frees a block only once
|
||||
the host said its piece is out of the guest's address space and no thread of the host's touches it,
|
||||
and once no thread of its own holds it. Before the release the host takes out every piece it added
|
||||
and says so for each, as QEMU's teardown does; the release then frees every block before it
|
||||
returns, so none is freed by a driver's exit handler (on NVIDIA's driver, which unmaps its memory
|
||||
inside `exit()`, a thread still reading a block then faults). QEMU reserves the range at realize past
|
||||
the RAM and the PCI host bridge's default 64-bit window, raises fw_cfg `etc/reserved-memory-end`
|
||||
past it so OVMF's 64-bit window goes above it, maps each piece as a RAM region of its own (an add is
|
||||
a pure add), and under WHPX runs the hypervisor's map outside its BQL (`whpx_map_ahead`).
|
||||
|
||||
## 2. The C header
|
||||
|
||||
The header has the twelve functions, every type, callback typedef and constant, with the thread and
|
||||
@@ -283,6 +300,9 @@ returns. The library logs through the `log` crate; a Rust host installs its own
|
||||
| `rvg_graphics_device_cursor_position` | never | nothing |
|
||||
| `rvg_graphics_device_read_display_at` | never | its draw on the GPU |
|
||||
| `rvg_graphics_device_cursor_position_at` | never | nothing |
|
||||
| `rvg_graphics_device_pool_added` | never | nothing |
|
||||
| `rvg_graphics_device_pool_removed` | never | nothing |
|
||||
| `rvg_graphics_device_pool_grow` | never | nothing |
|
||||
|
||||
## 5. Callbacks and threads
|
||||
|
||||
@@ -293,6 +313,8 @@ returns. The library logs through the `log` crate; a Rust host installs its own
|
||||
| `raise_interrupt` | the thread that posts the event it raises for: the device's control thread, `reims-vgpu.graphics-control`; one of ring 0's threads, `reims-vgpu.graphics-ring0-<i>`, which carry out a guest process's control messages, its presents and a block's pages and downloads, each on its lane; a display's refresh thread, `reims-vgpu.graphics-refresh` (display 0's) and, on a device of several displays, `reims-vgpu.graphics-refresh-<i>`; a command queue's service thread, `reims-vgpu.graphics-queue-<id>`, or one of its lane's threads, which walk and commit its command buffers, `reims-vgpu.graphics-lane-<id>`; a pipeline compile's thread, `reims-vgpu.graphics-compile-<n>`; a thread that makes IOSurfaces' and pages blocks' views, `reims-vgpu.graphics-surfaces-<i>`; a thread that makes indirect command buffers, `reims-vgpu.icb-create-<i>`; a thread that lets go of a closed process's objects and answers its close, `reims-vgpu.graphics-closes-<i>`; or the platform's thread that runs a command buffer's scheduled or completed handler; or the host's own, inside `rvg_graphics_device_mmio_write_taking` or `rvg_graphics_device_doorbell_write`. Never inside another call of the host's | nothing: they may call at once | each after the completion ring's message it raises for is published |
|
||||
| `route_doorbell`, `route_doorbell_page` (the route of a queue whose process has a doorbell page, at that page's doorbell in BAR 4) | one of ring 0's threads, `reims-vgpu.graphics-ring0-<i>`, or the control thread, `reims-vgpu.graphics-control`, as a command queue is made, destroyed or its process closed, with no lock of the library's held, where it may wait for a lock the host holds while it calls the device (QEMU's BQL), since no function the host calls under it waits for a thread inside the callback but the release of the process's last device, at most 5 s; dropping a route, also the host's own inside `rvg_graphics_device_mmio_write_taking` (a STATUS write of 0, or a `DOORBELL_PAGE_BIND` write that binds a page to another context) or `rvg_graphics_device_reset`, where it must not wait for a lock the host holds around that call | nothing: they may call at once | a queue's route before its create is answered, and its drop once its queue has ended and before its destroy, its process's close or the reset is answered; a dropped route takes no write once the call returns |
|
||||
| `cursor_glyph`, `cursor_show`, `cursor_move` (display 0's), and `cursor_glyph_at`, `cursor_show_at`, `cursor_move_at` (each display's from 1, named) | the display thread: one serial worker for the whole process (after 5 s idle it exits, and the next callback starts a new one) | every display callback of the process: one at a time | the order the device's control thread took the guest's cursor and display power commands, of every display, and its resets |
|
||||
| `pool_add` | the device's pool thread, `reims-vgpu.graphics-pool`, with no lock of the library's held; never inside a call of the host's; it must not wait for a lock the host holds while it calls the device (QEMU queues the add for its main loop) | one at a time | the order the device places the pieces, each before its `pool_remove`; the host answers each with `rvg_graphics_device_pool_added` once the guest's address space has it |
|
||||
| `pool_remove` | the thread that frees the piece's block: the pool thread, or the block source's own (metal2vulkan-rt's block-maker thread), inside its unmap hook, with no lock of the library's held; never inside a call of the host's; it must not wait for a lock the host holds while it calls the device | nothing | once a piece, after its `pool_add`, never once the release has begun; the host answers with `rvg_graphics_device_pool_removed` once the piece is out of the guest's address space and no thread of its own touches it, and the device frees the block only then |
|
||||
| a window's `pointer`, `wheel`, `key`, `close`, `scroll` | on macOS the process's main thread, where AppKit runs; on Linux and Windows the library's thread `reims-vgpu.ui`; never inside a call of the host's | every window callback of the process: one at a time | the order the events arrived |
|
||||
| `destroy` (each table) | the device's: once its threads have ended, after their last callback, possibly on one of them after the release has returned; the window's: once the release has closed the window, on the releasing thread or, while a window callback runs, the window's thread once it returns; either, on the caller's thread, in a refused create | nothing | once, after every call of its table |
|
||||
|
||||
|
||||
Vendored
+1
-1
Submodule vendor/qemu updated: f56d36ff50...0b8a0702eb.
Reference in new issue
Block a user