34 Commits
Author SHA1 Message Date
Anees IqbalandClaude 3043b90d69 🔥 The udmabuf exporter is gone: guest pages reach the GPU through the RAMBlock span, on every host
Component: `vendor/qemu/hw/display` — both device shims and the build wiring.
Only `hw/display/reims-vgpu-*` is touched; upstream QEMU's own dma-buf users
(virtio-gpu, ui/, vfio) are unrelated and out of scope.

Deletes `reims-vgpu-dmabuf.{c,h}` — the `/dev/udmabuf` handle, the
`UDMABUF_CREATE_LIST` call and the run coalescer — the PCI shim's
`dmabuf_for_pages` forwarder and its HostOps entry, and the meson translation
unit.

ABI v17's `guest_ram_regions` replaced the mechanism outright rather than
alongside it: guest pages now reach the host GPU by importing the mapping QEMU
already holds over a RAMBlock, which works on Linux, Windows and macOS, where
udmabuf is a Linux kernel object with no equivalent on either of the other two.
Removed rather than left in place, because a half-retired rail with two
spellings is the divergence class AGENTS.md warns about and a caller that can
still ask for an fd eventually will.

Two comments corrected rather than deleted, both about `map_pages_stable`: it
was documented as the flag the GPU rail read, and the GPU rail no longer exists
on that path. It is a claim about a CPU-side view only. The MMIO shim's copy
also now says why the import does not re-open the device-lifetime retention
that `reims-vgpu-mmio.c:208` records dropping — an import is over the span,
never over a packed `mach_vm_remap` view.

Verified: `ninja qemu-system-x86_64` builds and links clean against the v18
staticlib; all three reims TUs compile under QEMU's `-Werror` set. Not
verified: no live boot, and the MMIO shim was compiled on Linux but not built
into an Apple-host binary.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-07 14:43:10 +03:00
Anees IqbalandClaude 5f0ee545db ✨ ABI v17: the shim says where guest RAM lives, once, instead of building a view of the pages somebody wants
Component: `vendor/qemu/hw/display` — the shared shim plus both device shims.
No behavior change on either pathway: nothing calls the new entry point yet.

`guest_ram_regions` enumerates guest RAM as stable (gpa_base, host_va, len)
spans that hold for the VM's lifetime. Guest pages are about to reach the host
GPU by importing the mapping QEMU already holds over a RAMBlock, once, after
which a resource is an (offset, len) inside that import rather than a page
list somebody has to export.

It is deliberately not `map_pages` with a different return type. `map_pages`
answers "give me a view of these specific pages" and on the sysbus shim builds
a packed `mach_vm_remap` view the caller must release; this never allocates,
never releases, and never changes its answer. That is also why it does not
re-open the device-lifetime retention `reims-vgpu-mmio.c:208` records dropping
— an import is over the span, never over a remap view, and a fragmented
surface becomes several offsets inside one span.

One implementation in `reims-vgpu-shim.c`, which both shims point their table
entry straight at. It walks the system address space's flat view, skips ROM,
ROMD and ram_device ranges (RAM-backed, but the guest either cannot store into
them or does not own them), and coalesces adjacent ranges only when they
continue in *both* address spaces — two blocks that abut in GPA but not in
host VA stay separate, because merging those would make an offset inside the
span name the wrong host bytes.

The shim exports the spans and nothing else: not whether this host can import
them, not which primitive the backend would use, not how the ranges coalesced.
A shim holding those three can rebuild the rule, and per AGENTS.md it will.

Truncation is reported rather than silent: the call returns its true total
even when that exceeds the caller's array, so a short array is a fact the
caller learns instead of a part of guest RAM the GPU silently cannot reach.

Verified: `ninja qemu-system-x86_64` builds and links clean with the v17
staticlib. Both device shims and the shared shim compile with QEMU's `-Werror`
set. Not verified: no live boot, and the MMIO shim was compiled on Linux but
not built into an Apple-host binary.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-07 14:12:20 +03:00
Anees IqbalandClaude 4847b5f73f 🐛 The x86 shim's early-console arm fell through to the product re-push when its paint failed
`hw/display/reims-vgpu-pci.c`, x86 PCI pathway.

`fb_update` asks Rust who owns the host console and branches on the kind it
names. The `_FIRMWARE` arm returns either way and says why: a failed copy must
not fall through to the re-push at the bottom of the function, whose pending
frame is a *product* one, and pushing that while Rust says the firmware console
owns the screen is the pre-boundary steal the feed exists to prevent.

The `_EARLY` arm right above it returned only when its paint succeeded. A failed
early paint fell through and pushed the product frame — the same steal, with the
same reasoning against it written eight lines below, unapplied. The arm64 shim
returns either way on this arm, so the two shims disagreed and each host builds
only one of them.

Now returns unconditionally. No console update added beside it: unlike the arm64
shim's, this `paint_scanout` already calls `qemu_console_update_full` and clears
`new_frame_ready` itself on the path that returns true, so calling it here would
be the second call.

Verified: QEMU builds; both device shims present. The Rust-side gate is
`a_console_feed_arm_never_falls_through_to_the_product_re_push` in
`crates/reims-vgpu/tests/qemu_shims_agree.rs`, which fails on this file with the
old arm restored and passes with it fixed.

Not verified: arm64, whose shim already had the behavior this brings x86 to.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-05 09:15:13 +03:00
Anees Iqbal d53c32fcdb ♻️ The arm64 shim's page-size constant was spelled as if it were every guest's
`reims-vgpu-mmio.c` sized its `mach_vm_remap` view, its host-VA alignment mask
and its packed-contiguity stride from `REIMS_VGPU_GUEST_PAGE_SIZE`, eight uses in
`map_pages`. That name has no architecture in it and the value is 16384 — arm64e's
page, not "the guest's".

Its three siblings in the same block of the shared header are all arch-qualified
(`..._SHIFT_ARM64E`, `..._SHIFT_X86_64`, `..._SIZE_X86_64`), and the Rust side
adopted exactly this prohibition after being bitten by it: `model::regs` carries
a comment saying there is no bare `PAGE_SIZE` / `PAGE_SHIFT` because those names
"defaulted to arm16K and caused x86 wild writes (stamp slots)". The rule was
never carried across the boundary, where the header is the only copy and nothing
compares the two.

Renamed to `REIMS_VGPU_GUEST_PAGE_SIZE_ARM64E`, so the four constants read alike
and a use of the arm64e page on an x86 path has to say so. No live bug: all eight
uses are in the arm64 shim, where 16 KiB is the right number. This is the spelling
that makes the next one visible.

Not verified by compilation on this host: every one of the eight sits inside
`#if defined(CONFIG_DARWIN)` and is preprocessed away on Linux. `qemu-build.sh`
succeeds and both devices register, which proves the file parses and the header
change is consistent, not that the Darwin arm compiles. It is a textual rename of
one `#define` and all of its uses, and a grep confirms no unqualified spelling
survives anywhere in the tree.

The parent repo adds `the_abi_header_is_pinned_to_the_rust_page_geometry`, which
fails if any of the four drifts from `contract::gva`.
2026-08-05 08:22:18 +03:00
Anees IqbalandClaude 636a83b04c 🐛 The arm64 shim read a failed console-feed as "not early", and painted early frames at the surface's size instead of the one Rust named
QEMU shims, both pathways. `device_console_feed` is the single owner of
host-console ownership; its doc records that the shims used to assemble the
three-way themselves and that neither may re-derive it. The PCI shim had been
brought onto that contract. The MMIO shim had not, and `gfx_update` held three
copies of a rule that is not C's to hold:

- It called `reims_vgpu_qemu_console_feed` raw and tested
  `rc == OK && kind == EARLY`, so a failed call fell through to the
  post-boundary re-push. That is the shim inventing a policy for "no answer",
  which `device_console_feed`'s own doc names as the thing being removed. The
  PCI shim already read a failed call as _FIRMWARE — fail closed, because the
  firmware console owns the screen until Rust says otherwise.

- On _EARLY it bailed whenever the surface size differed from the geometry
  Rust named ("never resize from the refresh path"), and otherwise overwrote
  that geometry with `surface_width`/`surface_height` before copying. So an
  early front at a new size repainted nothing on arm64, forever, while x86
  resized and painted it. `device_console_feed` states that _EARLY guarantees a
  paintable target and that the shims therefore do not re-test the geometry.

- It had no _FIRMWARE arm at all: that kind fell into the re-push, which is the
  pre-boundary steal the PCI shim's comment names. The `may_paint` gate on
  `apply_scanout` means no product frame can be pending pre-boundary today, so
  this arm is a closed door rather than a live loss — but it is the door.

Changes:

- `reims-vgpu-shim.{c,h}` gains `reims_vgpu_shim_console_feed`, which forwards
  the kind and answers _FIRMWARE for a device with no handle or no answer. Both
  shims call it; the PCI-private copy is deleted.
- `reims-vgpu-mmio.c` gains `paint_scanout`, factored out of `apply_scanout`
  and now also used by `gfx_update`'s _EARLY arm, so both paint at the geometry
  they were handed. It deliberately does *not* push the console the way the PCI
  twin does: that shim's immediate push and this one's coalescing are each a
  measurement of their own pathway, recorded next to each, and unifying them
  would generalize one host's finding onto the other.
- Comments naming an "archive" implementation that no longer exists are gone.

Verification: x86_64 QEMU builds warning-free with all three shim files forced
to recompile. Driven boot, `window-drag-probe --seconds 25 --app Safari`:
desktop up at 1921x1079 / 138742 colors, window moved (320,180) -> (724,222),
fail-channel classes unchanged from baseline (gva_zero_pfn,
buffer_import_bind_offset_alignment, mem_qemu_read_gpa_callback_failed,
llvm_vector_alloc_stride) with no new reason.

Not verified: the arm64 MMIO pathway cannot be booted from this host, so the
three fixes above are argued from `device_console_feed`'s stated contract and
from the PCI shim that already honours it, not from a boot. The Darwin-only
arms of reims-vgpu-mmio.c are untouched and were not compiled.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-05 06:18:15 +03:00
Anees Iqbal 22faaef548 ♻️ Two shims each carried a private copy of the geometry Rust refuses a paint against
`hw/display/reims-vgpu-{mmio,pci}.c`, both pathways.

Three constants that cross the Rust/C boundary existed as three copies each with
nothing comparing them:

- the EFI pre-boot mode, `1920u`/`1080u`, once per shim and once in Rust as
  `model::regs::EFI_BOOT_{WIDTH,HEIGHT}`;
- the gfx MMIO window size, `0x4000`, as `REIMS_VGPU_MMIO_GFX_MMIO_SIZE`, as
  `REIMS_VGPU_PCI_BAR_SIZE`, and in Rust as `model::regs::GFX_MMIO_SIZE`.

Both now come from `include/reims_vgpu_qemu_abi.h`, which is the file the
project's rule already names for anything crossing the boundary, and the local
defines are gone.

The EFI pair is the one that bites. The shim sizes the `DisplaySurface` the
pre-boot console is painted into, and `scanout::paint_efi_console` refuses a
paint whose width is not the mode this device advertised to the firmware. A
drift does not degrade — it makes the refusal fire on every early console paint,
into a surface the shim itself just created at the other size, with the two
numbers living in different files and different languages. The window size is
the same shape one level down: a region larger than the bound Rust indexes is
guest-addressable space whose accesses reach a register store with no slot for
them.

Kept local on purpose: `REIMS_VGPU_MMIO_IOSFC_MMIO_SIZE`, because Rust keeps no
per-offset state for that rail and a mirror would be a source of truth nothing
checks; and `REIMS_VGPU_PCI_EFI_BPP`, which describes this shim's own BAR1 GOP
layout rather than anything Rust reads — Rust reaches those bytes only through
`efi_console_copy`'s explicit stride argument.

No ABI version bump: these are compile-time constants, not a change to the
`HostOps` table or any struct layout the version guards.

Verification: `scripts/qemu-build/qemu-build.sh` — both shim objects rebuild and
`qemu-system-x86_64` links, with both devices present. The Rust side of this
change carries the two drift tests.
2026-08-05 05:40:17 +03:00
Anees IqbalandClaude 0111a8f970 ♻️ A table that can only fail by dropping a range should grow instead
`hw/display/reims-vgpu-dirty.c` — the guest-write witness, shared by both shims
and every pathway.

The flat view walk that replaced the monotone hull recorded guest-RAM ranges
into a fixed 64-entry array and stopped when it filled. That bound is not a
budget. A range it dropped is a range no tracked page can resolve into, and an
unresolvable page reads as written — for every page in the range, on every
harvest, for the life of the VM, with no counter naming it. That is the same
latch the hull produced, reached by a smaller door, and nothing about it is
recoverable or observable from the guest side. So the table now grows to
whatever the flat view reports and the bound is gone with the magic number that
carried it.

Measured before changing it, because a table should be banded before it is
widened: 5 ranges on x86 q35 with this device, unchanged across a driven boot
including the load phase. 64 therefore had ample headroom and was never close to
binding — this removes a failure mode, not a live fault, and the comment now
says so rather than implying the reach was under pressure.

Two smaller things fall out. The per-range `logged`/`needs_log` state moves from
parallel stack arrays into the slice itself, which is where the page loop reads
it. And the logging pass now lets `g_hash_table_add` decide, rather than the
flag: one MemoryRegion can supply several ranges — on q35 guest RAM is one
region aliased below and above the PCI hole — so a region whose ranges both
asked for logging took `memory_region_ref` twice against a single table entry,
and the extra reference was never dropped.

Verified: builds warning-free. A driven boot on this binary
(vibrancy-latch-probe, 150 s load) reads `gw_refused_guest_store` 165 and
`deferred_flush_clobber` 0 — inside the clean band of 145-186 and 0, against a
degraded cluster of 20122-34772 and 29-69 — with `t11rung_resident_refused` 30
against 27780 latched, and the two controls `t11_gw_armed` (75283) and
`gw_vouched` (43484) at their usual magnitudes, so the witness is still armed
and answering rather than silenced. The temporary probe that produced the range
count was removed before this build.

Not verified: the pane gate refused a verdict on that boot rather than scoring
it — its control region moved, so the two shots are not the same scene. The
mechanism counters above are the reading. arm64/MMIO is the same file and was
not booted; it presents guest RAM as one range, so it exercised neither the old
bound nor the aliasing that double-referenced.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-05 02:38:36 +03:00
Anees Iqbal 5100aa997b 🐛 A set armed on a harvest whose sync predated its own region being recorded
Follow-up to the FlatView slice cut in the previous commit. Enabling region
logging moved to the tail of the harvest, because `memory_region_set_log`
rebuilds the flat view the slice table describes — but the arming push that
protects a set from that harvest still ran where it always had, which is now
*after* the generation update it was meant to gate. A set created one harvest
earlier therefore reached `s->gen = 1` on a harvest whose sync was taken before
its region started recording, and its first readable generation rested on an
absence of reports that was never evidence.

Wrong direction to leave open even though it cannot produce the latch this
series is about: it reports a written surface as clean, not a clean one as
written.

Make the wait per set rather than global. A set that met an unrecorded region
while reading its own pages pushes its own `arm_at`, in the same locked pass that
found it and before the generation moves. That is strictly narrower than the
global push it replaces — a set whose pages all sat in recorded regions no longer
waits for one that did not — and it keeps the documented window exactly: two
harvests for the first surface of a boot, one for every surface after it.

The test stays `s->gen == 0`. An already armed set must not be sent back through
its startup window; its pages read as written for that harvest, which is the
conservative answer and needs no help.

Verified: builds warning-free. Boot sweep pending, same as the previous commit.
2026-08-05 01:53:14 +03:00
Anees Iqbal f2057c633d 🐛 The first non-RAM byte in the tracked window swallowed every guest page above it
The guest-write witness (`hw/display/reims-vgpu-dirty.c`, both shims, every
pathway) cut its tracked window by walking a monotone hull of every GPA ever
tracked with `address_space_translate`. That walk cannot be made correct.
`address_space_translate_internal` clamps `plen` to the section **only when the
section is RAM** (`system/physmem.c`); for anything else it hands back the whole
requested length. So the first non-RAM byte in the hull produced one `mr == NULL`
slice covering every guest page above it, and the walk stopped there.

On x86 q35 low RAM ends below the PCI hole and high RAM begins at 4 GiB, with 37
device ranges in between. One tracked page landing in low RAM while others sat
above the hole was enough: every page in high RAM then resolved to that slice.
`reims_vgpu_dirty_harvest` reads a page it cannot resolve as written — the
conservative answer, and the right one for a page that is genuinely gone — so
every tracked surface reported itself permanently overwritten by the guest. The
hull never shrank and the clear pass skipped unresolved pages, so nothing could
undo it for the life of the VM.

Downstream that is a guest-visible latch rather than a slow path. Every
host-side copy of a surface is declared stale, the type-11 sampled rung refuses
its resident and merges guest pages that never held the composite, and deferred
render windows report `deferred_flush_clobber`. It reads as vibrancy backdrops
going transparent and popover geometry breaking, and it does not recover.

Ask the FlatView for the guest-RAM ranges instead of reconstructing them.
`flatview_for_each_range` reports every range with exact bounds; guest RAM is a
handful of them, so the slice bound now describes RAM regions rather than a hull
that crosses MMIO, and no reachable input makes it lie. The hull is deleted with
the walk that needed it.

Logging is now enabled for the regions a tracked page actually resolved into,
discovered in the read pass and applied after the clear pass, because
`memory_region_set_log` rebuilds the flat view the slice table describes. A
region not yet logged reads as written for that harvest, which is what a region
with no recorded history has to say, and the arming push that follows keeps the
documented one-harvest/two-harvest window exactly as it was.

Measured: `gw_refused_guest_store` separates clean from degraded boots with no
overlap over twelve recorded boots on two binaries — 155-186 on the seven clean
ones, 20 122-34 772 on the five degraded ones — and steps between the two inside
a single second, never returning. That counter is the gate for this change.

Not verified: this commit is the build and the reasoning; the post-fix boot
sweep that scores it has not run yet. arm64/MMIO is the same code but was not
booted.
2026-08-05 01:49:38 +03:00
Anees IqbalandClaude e3ce4e5983 🐛 The backend a build was configured for survives ninja regenerating it
Component: `hw/display/meson.build`, `meson_options.txt`.

`reims_vgpu_backend_kind` was read from `REIMS_VGPU_BACKEND` in the environment.
That is correct exactly once, at configure. Meson also re-runs its build files
whenever ninja finds them out of date, and *that* run inherits ninja's
environment — which for any plain `ninja`, any IDE, and any script that did not
export the variable is an environment where it is unset. The default is `metal`,
so a tree configured for Vulkan quietly became a Metal one the first time
anything under `hw/display` changed.

On a Linux host the result is not subtle — `backend-metal` is Apple-only and the
staticlib fails with twenty-odd Rust errors — but it arrives at the next *boot*
rather than at the change, and the caller's own stamp still says `vulkan`,
because the script wrote what it intended rather than what meson resolved.

The backend is now a meson option, which is stored in the build directory and
survives regeneration. `env` stays the default so a caller that has not been
taught the option keeps its old behaviour, and it is read only on a real
configure.

Verified: reconfigured x86_64/vulkan from scratch, then `touch
hw/display/meson.build` and `env -u REIMS_VGPU_BACKEND ninja` — build.ninja
still names `--no-default-features --features backend-vulkan,host-window` and
nothing names `backend-metal`. Before this change that sequence rewrote the rule
to `--features backend-metal`.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-04 18:53:36 +03:00
Anees Iqbal 68e93d2220 ✨ Export a run of guest pages as a Linux dma-buf
Component: Reims VGPU QEMU shim, x86 PCI attach.

`reims_vgpu_dmabuf_for_pages` turns page-aligned guest GPAs into one dma-buf fd
via `UDMABUF_CREATE_LIST`, so the host GPU can read and write those pages in
place instead of the device staging every byte through the CPU in both
directions.

The shim answers with the fd or with a named `REIMS_VGPU_DMABUF_ERR_*` code from
the shared ABI header. It exports no inputs: whether this host has
`/dev/udmabuf`, whether guest RAM is fd-backed, and whether the run list fits
the kernel's bound are questions only QEMU can answer, and a caller holding all
three would reconstruct the rule.

Two things that are derived rather than guessed:

- The run offset is `qemu_ram_get_fd_offset(rb) + offset`. A RAMBlock may sit at
  a non-zero offset inside its backing file, and dropping the block's own offset
  builds a dma-buf over the wrong bytes of the right file — corruption, not a
  failure. QEMU's own `virtio-gpu-udmabuf.c` omits this term.
- `REIMS_VGPU_DMABUF_MAX_RUNS` is the udmabuf driver's `list_limit` default.
  Adjacent pages coalesce first, so it bounds runs and not pages: a contiguous
  surface of any size is one run, and a scattered one is refused by name rather
  than as an opaque ioctl error.

`/dev/udmabuf` is opened once. Opening it is a permission check as much as an
acquisition and the answer cannot change while the process runs, so a host
without the node does not retry the open per resource.

The non-Linux arm answers `UNSUPPORTED` in C rather than being absent, so the
Rust side sees one named refusal instead of a link error. The sysbus/MMIO attach
leaves the callback NULL, which reads the same way.

Verified: `ninja libsystem.a.p/hw_display_reims-vgpu-dmabuf.c.o
libsystem.a.p/hw_display_reims-vgpu-pci.c.o` compiles clean, and `nm` shows
`reims_vgpu_dmabuf_for_pages` as a defined text symbol.

Not verified: no live boot — nothing has called this against real guest pages,
and the full QEMU link was not run (this build directory's staticlib target is
configured for `backend-metal`, which does not build on a Linux host).
2026-08-04 18:07:40 +03:00
Anees Iqbal 684d2e814d 🔧 Ignore coverage artifacts an instrumented QEMU run drops here
QEMU built against a -C instrument-coverage staticlib writes default_*.profraw
into its working directory when LLVM_PROFILE_FILE is unset. scripts/runtime-dead
sets it, but a hand-run does not. These are build artifacts, never tracked.
2026-08-03 17:24:40 +03:00
Anees Iqbal 3538e649ec ✨ Let QEMU link the profile runtime so the staticlib can be measured
vendor/qemu, x86 Vulkan link path. Opt-in and off by default.

Building crates/reims-vgpu with -C instrument-coverage produces __llvm_prf_*
sections and nothing that writes them. rustc bundles profiler_builtins into a
final artifact; this staticlib is not one, QEMU links it. So the profile runtime
has to be named at the QEMU link instead, and named --whole-archive: no
instrumented object references it, so the linker drops every member otherwise.

REIMS_VGPU_COVERAGE carries the path to libclang_rt.profile-<arch>.a. Unset —
the default, and every build that is not scripts/runtime-dead — changes nothing:
verified by rebuilding with the variable clear and confirming the binary carries
no __llvm_prf_cnts section.

This exists for scripts/runtime-dead, which measures which decoded paths the
guest protocol never takes. AGENTS.md names that as the one reduction lever
scripts/dead-state cannot see.
2026-08-03 17:23:02 +03:00
Anees Iqbal 118ad5d527 🐛 One shim gated the console on ownership and the other painted regardless
vendor/qemu thin shim, both pathways (reims-vgpu-pci, reims-vgpu-mmio).

v14 moved the console-ownership *kind* into Rust but went on exporting it as
an input, and the two shims did with it what shims do:

  - reims-vgpu-pci rebuilt the paint verdict itself, out of console_feed's
    out_kind and out_mapping_id:
        kind == FIRMWARE || (kind == EARLY && mid != mapping_id)
  - reims-vgpu-mmio rebuilt nothing and painted every present it was handed.

So a pre-boundary present naming a mapping other than the latched early front
was refused on x86 as a steal of the firmware console, and painted on arm64.
One rule, one pathway holding it — the same shape as the GPA-attrs drift, on
the question of who owns the screen.

The verdict is now exported whole as reims_vgpu_qemu_scanout_may_paint (ABI
v15) and forwarded by reims_vgpu_shim_scanout_may_paint, which both shims call.
The kind stays exported because fb_update genuinely dispatches on it — it picks
between three QEMU-side mechanisms — but no shim assembles the paint rule now.

x86 behaviour is unchanged by construction: the two branches the shim lost
(rust_handle == 0, and a console_feed that errors) both already collapsed to
FIRMWARE and therefore to "do not paint", which is what the forwarder returns
for both. arm64 changes: it gains the gate it never had.

Verified: x86 boot (vm/boot-x86.sh --device reims-vgpu-pci --testing,
REIMS_VGPU_WINDOW=0 so gfx_update and apply_scanout actually run) reaches the
macOS 13.7.8 desktop with WindowServer alive; fail-log record set unchanged
from the pre-change boot (same seven classes, no new ones).

NOT verified: the arm64 MMIO pathway. It needs an Apple host, and it is the
pathway whose behaviour this changes.
2026-08-03 17:07:12 +03:00
Anees IqbalandClaude fdf614f1b9 🐛 One shim had RAM-only GPA attrs and the other did not
Component: QEMU device shims, both pathways (`reims-vgpu-pci` x86,
`reims-vgpu-mmio` arm64) plus the shared `reims-vgpu-shim`.

`read_gpa`/`write_gpa` were written twice, and the two copies had drifted on the
one thing that matters. The PCI shim passed `MemTxAttrs{ .memory = 1 }`; the MMIO
shim passed `MEMTXATTRS_UNSPECIFIED`.

That attribute is not cosmetic. Every GPA reaching these two functions came from
a guest-supplied page-entry list. With `.memory` set, an entry that resolves to a
device instead of RAM is rejected with MEMTX_ACCESS_ERROR; without it, the access
is performed — so a bad PFN pointing at one of our own BARs re-entered this
device's MMIO handler from inside a Rust call that already held the device lock.
The x86 shim carried a comment naming that hazard. The arm64 shim had the same
hazard and no defence.

`reims-vgpu-shim.h` states the rule this violated: a duplicated predicate is a
predicate that can drift, and a drift between the two shims is a bug the guest
sees on exactly one pathway. Both functions ignore the HostOps `ctx` entirely,
which is that header's own test for belonging in the shared file, so they move
there with the attrs and their basis recorded once.

Net -4 lines of C; the point is the drift, not the count.

Verified: x86_64 build clean, all four shim objects recompiled warning-free
(pci, mmio, dirty, shim). One driven `vm/boot-x86.sh --device reims-vgpu-pci
--testing` boot reached the guest desktop and presented guest frames through the
engine-resident zero-copy rail; against the stashed baseline log the memory-
callback failure census is identical (one pre-existing EFI-framebuffer read at
0x80000000, present on both arms) and `window_publish` reads 416 against 415.

NOT verified: the arm64/MMIO pathway, which is where the behaviour actually
changes. That needs an Apple host. The change there is strictly narrowing — RAM
accesses are unaffected; only device-targeted GPAs, which previously re-entered
MMIO, now fail closed and surface as a visible decline.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-03 16:11:10 +03:00
Anees Iqbal c8d70b766e 🔥 The shims decided who owns the console; that is not a shim's decision
hw/display/reims-vgpu-pci.c and hw/display/reims-vgpu-mmio.c. Needs the
matching parent commit — this is ABI v14 and will not link against v13.

Both shims called `present_boundary_seen` and `early_scanout_target` and
recombined the pair into a three-way: firmware console, early latched front, or
product present. That branch is the host-console ownership rule. It is protocol
policy, AGENTS.md says C is a thin shim, and the rule already existed a third
time in Rust — at `host_console_uses_bar1`, whose doc said in as many words
"shipped C mirrors this". Three copies of one display-ownership rule is three
chances for a pathway to disagree about who owns the screen.

Both queries are replaced by `reims_vgpu_qemu_console_feed`, which returns the
answer. `reims_vgpu_pci_present_boundary` and
`reims_vgpu_pci_early_scanout_latched` are gone; `apply_scanout` and `fb_update`
switch on the kind. The geometry validity test the shims each did on the early
target (`mid == 0 || w == 0 || h == 0`) is gone with them — that is a decode
rule, and `_EARLY` now guarantees a paintable target.

Every branch is a semantic identity with what it replaced:

  boundary                       -> _PRODUCT   paint
  !boundary, no early latch      -> _FIRMWARE  do not paint
  !boundary, latched, mid != id  -> _EARLY     do not paint
  !boundary, latched, mid == id  -> _EARLY     paint
  rust_handle == 0               -> _FIRMWARE  do not paint

`fb_update`'s `_FIRMWARE` arm returns unconditionally, including when the
firmware copy fails, exactly as the old code did. Falling through to the
pending-frame re-push there would push a product frame while Rust says the
firmware console owns the screen, which is the pre-boundary steal this feed
exists to prevent.

Verified by A/B on a live x86 guest, both boots `REIMS_VGPU_WINDOW=0` so QEMU
owns the console with `-display gtk` and `fb_update` actually ticks (the default
host-window config uses `-display none` and never calls it, so it does not
exercise this code at all):

  - this commit, and the same boot with both repos stashed to baseline
  - screenshots at the same boot stage are **byte-identical**, 4174 bytes each,
    ImageMagick RMSE 0 (0)

That console renders black on both arms. It is black at baseline, so this change
did not cause it; the boot script and AGENTS.md both record the QEMU display
path as deprecated for product work, kept for archaeology and A/B. The supported
host-window path booted to a full macOS desktop on this staticlib.

Also verified: both shim objects deleted and recompiled explicitly, no
diagnostics; `qemu-system-x86_64` links.

Not verified: the Darwin arm of `reims-vgpu-mmio.c` (`#if defined(CONFIG_DARWIN)`)
is not covered by a Linux compile, and arm64 was not booted. The mmio change is
outside that guard.
2026-08-03 15:54:09 +03:00
Anees Iqbal 2017e1d82d 🔧 Both shims carried their own copy of the scanout ceiling
hw/display/reims-vgpu-pci.c and hw/display/reims-vgpu-mmio.c.

`REIMS_VGPU_PCI_MAX_DIM` and `REIMS_VGPU_MMIO_MAX_DIM` were each `8192u`, each
declared in its own shim, each with no stated basis, and each used for exactly
one thing: the geometry guard in that shim's `set_mode`. That is two copies of a
product policy bound sitting in the thin C layer, which is the shape
`reims-vgpu-shim.h` already warns about in its own header comment — a duplicated
table is a table that can drift, and a drift between the two shims is a bug the
guest sees on exactly one pathway. Here it would be a geometry that one attach
accepts and the other silently drops.

Both now use `REIMS_VGPU_MAX_SCANOUT_DIM` from the shared ABI header, which both
files already include. The bound's owner is Rust `model::MAX_SCANOUT_DIM`, where
the basis is now recorded: it is derived from the allocation it bounds, not from
a device capability — tightly packed BGRA8 at 8192 squared is a 256 MiB single
surface, the figure `surface_cache`'s GVA cache cap is reasoned against, and the
16-bit wire fields would otherwise admit a 16 GiB surface from one corrupt guest
word.

No behaviour change: same value, same guard, same two call sites.

Verified: `scripts/qemu-build/qemu-build.sh --backend vulkan --target x86_64`
links `qemu-system-x86_64` clean, and both shim objects were deleted and
recompiled explicitly so this is not a stale-object pass —
`hw_display_reims-vgpu-mmio.c.o` and `hw_display_reims-vgpu-pci.c.o` both build
with no diagnostics.

Not verified: no guest was booted, and the Darwin arm of `mmio.c` is guarded by
`#if defined(CONFIG_DARWIN)`, so the Linux compile above does not cover it. The
lines changed here are outside that guard.
2026-08-03 15:31:20 +03:00
Anees Iqbal 161b53c3d6 🔥 The EFI console copy filled two out-params its only caller throws away
Component: QEMU x86 PCI shim (`reims-vgpu-pci.c`), the `efi_console_copy` half
of the pre-boundary host-console feed.

`reims_vgpu_pci_copy_early_console` declared `gpa` and `fb_stride`, passed
their addresses to `reims_vgpu_qemu_efi_console_copy`, and then read neither.
The call's only decision is `rc == REIMS_VGPU_QEMU_OK`. Both locals are gone
and the call now passes the five arguments it actually uses.

The staticlib side drops the matching outs in the same changeset, so the ABI
header, the `extern "C"` shim and this caller move together.

Verified: `scripts/qemu-build/qemu-build.sh --backend vulkan --target x86_64`
builds clean from a fresh configure (the pre-existing build dir was stale — its
stamp read `x86_64:vulkan` while `build.ninja` still baked `backend-metal`, so
it was removed and reconfigured). `qemu-system-x86_64` reports both devices
present with the vulkan-linked staticlib.

Not verified: no live x86 guest boot. This removes only discarded out-params;
the copy path and its OK/EMPTY contract are unchanged.
2026-08-03 14:36:55 +03:00
Anees Iqbal 171c485d12 ♻️ Seven shim services were written twice, so the button table could drift
Component: QEMU C shim (hw/display), both pathways -- reims-vgpu-pci
(x86 PCI) and reims-vgpu-mmio (arm64 sysbus).

reims-vgpu-pci.c and reims-vgpu-mmio.c each carried their own copy of
seven functions whose bodies were byte-identical once the pci_/mmio_
name prefix was normalised away:

  mono_ns, is_ram_gpa, read_kva   -- ignore the HostOps ctx entirely
  button                          -- a 27-line REIMS_VGPU_BUTTON_* table
  input_key, input_pointer_move, input_button -- read only s->con

None of them read anything from the device state, so neither copy was
earning its bus-specific home. The cost was not the 222 duplicated
lines; it was that a change to the button table or the is_ram_gpa
predicate had to be made twice, and a miss would produce a bug visible
on exactly one of the two pathways. That is the failure mode the split
invites and nothing prevented it.

They now live in reims-vgpu-shim.{c,h}, following the precedent
reims-vgpu-dirty.{c,h} already set as code "shared by both shims". The
three with HostOps-compatible signatures are pointed at directly from
both host_ops tables; the three input helpers take a QemuConsole* so the
caller supplies the one field they needed. `button` is now static inside
the shared file, since it has no caller outside it. Every comment that
explained a removed body was carried across -- notably the read_kva
"never fall back to first_cpu" AB-BA deadlock note, which had existed
only in the mmio copy even though both copies had the hazard.

Dropping the bodies left includes with no remaining user: ui/input.h,
system/hw_accel.h, exec/cpu-common.h, hw/core/cpu.h and qemu/timer.h in
the PCI shim, and ui/input.h plus exec/cpu-common.h in the MMIO shim.
Removed, and the surviving uses re-checked by rebuild rather than by
grep, since QEMU headers include each other freely.

C shim total 3,206 -> 3,170 lines. The net is small because the shared
file carries the contract comments; the duplication itself went from 222
lines to 116.

Verified: all three objects compile warning-free on Linux/x86_64 via
`ninja libsystem.a.p/hw_display_reims-vgpu-{pci,mmio,shim}.c.o`, and no
reference to any removed symbol remains.

Not verified: no live VM boot on either pathway, and the Apple-host
build of these files was not exercised -- the code is bus-independent
and host-independent, but the arm64/HVF compile was not run here.
2026-08-03 13:40:24 +03:00
Anees IqbalandClaude f61c19b83e 🔥 The GOP console proxy was a probe that outlived the question it asked
Component: QEMU C shim, hw/display/reims-vgpu-pci.c (x86 PCI pathway).

Deletes `reims_vgpu_pci_gop_console_proxy()` and the
`reims_vgpu_pci_bar1_fingerprint()` it drove, the seven `gop_proxy_*` fields
of device state they carried, their reset block, and the three call sites in
`reims_vgpu_pci_fb_update()`.

What it was: on every display refresh tick it FNV-1a'd a 1/64 sample of the
1920x1080 BAR1 framebuffer, compared the digest against the previous tick, and
`fopen`/`fprintf`/`fclose`'d a line into a hardcoded `/tmp/reims-vgpu-gop-console.log`
on change or every 250 ms.

Why it goes:

- Its own comment declares it a probe, not a feature: "Freeze class under test",
  "Correlate this log with serial milestones", "do NOT use content as product
  cutover". AGENTS.md says temporary probes are fine to collect evidence and
  must be removed before claiming the fix. The freeze it was built to chase is
  not referenced by any remaining code, script, or doc.
- It costs a strided read of ~32k framebuffer pixels plus an open/write/close
  syscall trio on the display refresh path, per tick, always on. That is real
  per-frame work for a diagnostic no one reads.
- The hardcoded `/tmp` path is not a product artifact. The device already has an
  always-on fail log with a real sink behind it; a second, separate, unbuffered
  log file bypasses it.

`reims_vgpu_pci_copy_gop_fb()` is untouched — that is the product early-boot
GOP framebuffer copy, not the probe. The console-ownership contract in
`fb_update()` (boundary, early latch, product present) is unchanged; only the
proxy calls sitting beside it are gone. `REIMS_VGPU_PCI_EFI_W/H/BPP` remain in
use by the real copy paths.

Verified: `ninja libsystem.a.p/hw_display_reims-vgpu-pci.c.o` in the existing
build tree compiles clean.
Not verified: no live x86 VM boot in this change — the removal deletes an
observer with no control edge into `fb_update`'s return value or the surface.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-03 12:57:49 +03:00
Anees Iqbal c7b0c1e075 🔒 The write witness waited two harvests for something that had already happened
Component: hw/display/reims-vgpu-dirty.{c,h}. Paired with the parent repo's
d7f151b, which carried the Rust-side counter and the corrected docs and left
this half uncommitted in a detached submodule.

`reims_vgpu_dirty_track` pinned a new set's generation at 0 for two harvests,
reasoning that the first harvest after the call may still be turning dirty
logging on for the pages' regions, so writes older than it were never recorded.
That reason is right and it is a reason about the *first* set to name a region.
Guest RAM is one MemoryRegion, so after the first tracked surface of a boot no
harvest enables anything and the second harvest waited for an event that could
no longer occur.

Waiting is not free. An unarmed set reads back generation 0, the Rust side's
`guest_write_gen` maps that to "cannot tell", the type-11 LOAD elision refuses
with `t11_gw_ref_no_stamp`, and the draw pays a whole-frame seed read out of
guest pages plus a whole-frame staging upload. The window is counted in harvests
and harvests are driven by guest doorbells, so it lasts as long as the guest
stays quiet — which is exactly when a draw arriving into it is a visible hitch.

`arm_at` is now `harvests + 1`, and `reims_vgpu_dirty_harvest` pushes every
never-armed set to the next harvest when that harvest had to enable logging, so
a set created before its region was logged arms exactly as late as before. The
push tests `s->gen == 0` rather than `d->harvests < s->arm_at`: a set created at
harvest H carries `arm_at = H + 1` and `d->harvests` is already H + 1 at that
point, so the arithmetic test is false for precisely the set that needs pushing.

Soundness: with logging already on, every guest write to the pages since the
last sync is already in KVM's bitmap, so the first sync after `track` reports
all of them. A write predating `track` is also reported, which refuses an
elision that could have been taken — conservative in the safe direction. A page
reported unwritten was genuinely unwritten, because logging was on for the whole
interval.

Measured, two boots running the same sequence, normalised: unarmed stamps
99/7577 = 1.31 % before against 162/14257 = 1.14 % after, and full-frame seed
uploads 1.56 % against 1.40 %. Real, small, and not the hitch fix — most sets
were already arming within about one Store either way.

Verified: QEMU rebuilt and booted (x86/PCI, reims-vgpu-pci), guest reached the
desktop and Safari probes returned; parent-repo tests and clippy in d7f151b. Not
verified: `FakeHost` does not model the arming window, so there is no unit test
for this and the proxy is the live counter pair above; the arm64/MMIO pathway
shares this file and was not booted.
2026-08-02 10:52:23 +03:00
Anees Iqbal b249677d64 🔒 The dirty bitmap knew which pages moved and only ever said whether any did
Component: vendor/qemu thin shim (x86 PCI + arm MMIO), guest-write tracking.

reims_vgpu_dirty_harvest already reads the hypervisor bitmap one guest page at
a time. It folded that into a per-set boolean and threw the rest away, so the
only question the device could ask was "did anything in this surface move".

That is the right question for a reader deciding whether to reuse a host-side
copy: one moved page makes the copy wrong. It is the wrong question for a
writer. A deferred writeback holds a frame the device rendered and lands it in
the guest's pages later; if the guest wrote some of those pages in between,
writing the whole frame loses the guest's stores and dropping the frame loses
the device's. Neither is correct and the difference between them is exactly
the per-page list this discards.

Adds reims_vgpu_dirty_written_since: the page-aligned GPAs of a token's set
whose last observed write is newer than a generation the caller previously
recorded. Backed by a page_gen array parallel to pages, stamped in the harvest
that already computes the answer -- so this costs one u64 per tracked page and
no extra bitmap work.

Stamped after the generation update rather than during the page walk, because
the value to stamp with is the generation this harvest produces, and that is
not known until every page has been read. Not stamped at all while the set is
inside its two-harvest startup window: a page stamped there would carry a
generation no reader can have recorded and would read as written forever.

Returns -1 -- "assume the whole set was written" -- for an unknown token, an
unreadable generation, a since_gen of 0, and a set with more written pages
than the caller's buffer. It refuses rather than truncating: a short list says
"these pages and no others", which is the one answer that turns a
conservative caller into a wrong one.

Also plumbs guest_written_pages through both shims' HostOps tables. Pages that
this harvest could not cut a slice for, or that are not RAM, are recorded as
written per page as well as for the set, so the per-page reader is never less
conservative than the generation.

Verified: qemu-system-x86_64 builds and links clean with the reims-vgpu
vulkan staticlib. Not verified: the arm MMIO shim is compiled but not booted
from this host.
2026-07-31 07:48:41 +03:00
Anees IqbalandClaude 6495b4fc10 🔒 The arm shim has two guest register windows, and only one was harvesting
`reims-vgpu-mmio` exposes both a gfx and an iosfc MMIO region, and either can
carry the write that hands the device work. The harvest sat on the gfx path
only, so on whichever rail the arm64 guest actually uses for a submission the
guest-write witness could be a whole submission stale — the elision would
answer with a generation harvested before the guest's last store instead of
after it.

Both paths now harvest. Neither is a new cost: the harvest returns immediately
unless a generation has been read since the last one, so covering the second
window costs a predicate rather than a sync. `reims-vgpu-pci` has no second
window and is unchanged.

Verified: `ninja libsystem.a.p/hw_display_reims-vgpu-mmio.c.o` warning-free on
Linux.
Not verified: no arm64 host available here, so the ordering this restores has
not been exercised on the pathway it exists for.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-07-31 04:18:50 +03:00
Anees IqbalandClaude 2a19c608ff ✨ QEMU answers what the device cannot see: which guest pages were written
Implements the reims-vgpu ABI v12 guest-write tracking triple in both shims
over the hypervisor's dirty bitmap.

A paravirtual surface's storage is plain guest RAM. The guest CPU stores into
it with no device operation at all, so nothing the Rust device counts can
witness such a store, and every host-side copy of those pages (an engine
resident, a cache entry) is stale from that instant with nothing to say so.
The hypervisor's dirty bitmap is the only witness; this is the adapter.

New `hw/display/reims-vgpu-dirty.{c,h}`, shared by both shims:

- `track` registers a mapping incarnation's page list, `gen` reads a monotonic
  count of harvests that saw some page of it written, `untrack` releases it.
  `gen` is safe from any thread; `harvest` is BQL-only.
- The harvest runs in `gfx_write`, **before** the register write reaches Rust.
  That is the guest handing the device work, so every guest store ordered
  before the handoff is observed before the work that could reuse a host-side
  copy of those pages runs. It is also the only place it can run: the
  accelerator's dirty-log sync needs the BQL, which a vCPU MMIO write holds and
  the drain thread must never take — taking it there inverts against
  `gfx_write`, which already calls into Rust with the BQL held.
- Read and clear are separate passes. Reads are pure
  (`physical_memory_get_dirty_flag`), so every set holding a page sees the same
  answer; a snapshot-and-clear per set would let the first set harvested
  consume the reports of every set sharing its region — and its bitmap-long
  rounding would take up to 63 neighbouring pages with it.
- Only pages that came back written are cleared. Clearing re-protects, so
  clearing the whole tracked window would make every page the guest has mapped
  refault after every harvest; this costs one refault per page the guest
  writes again. Exactly-adjacent pages merge into one hypervisor round trip and
  no range is widened past a page that was written.
- A set's generation reads back 0 ("cannot tell") for its first two harvests,
  because writes older than the harvest that turned logging on for its regions
  were never recorded, and their absence would otherwise look like the guest
  not having written.
- A window that will not cut, a page outside it, or a page that is not RAM all
  read as written — the conservative answer, which costs a reuse and never a
  wrong frame.
- Region logging goes on once and stays on for the device life (refcounted via
  `memory_region_set_log`, released in `reims_vgpu_dirty_free`): toggling per
  surface re-protects the whole region each time.
- A harvest nothing has consumed since the previous one is skipped, so a burst
  of register writes costs one sync.
- `page_size` below the target page is refused rather than answered at a
  granularity the bitmap does not have. Both pathways are the other way round
  (4 KiB x86 == target, 16 KiB arm64e > target, checked per target page).

Both shims gain the three callbacks, a `ReimsVgpuDirty *` created at realize
and freed after the Rust device is destroyed, and the harvest call in
`gfx_write`.

Verified: all three objects compile warning-free
(`ninja libsystem.a.p/hw_display_reims-vgpu-{dirty,pci,mmio}.c.o`), including
the MMIO shim built on Linux.
Not verified: no live VM boot yet. Nothing in Rust consumes the generation
yet, so no set is ever tracked and the harvest returns immediately.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-07-31 03:56:16 +03:00
Anees Iqbal 999c6d7919 🐛 Guest page views are released when the caller is done with them
Component: QEMU shims (hw/display/reims-vgpu-mmio.c, hw/display/reims-vgpu-pci.c).

`map_pages` on the MMIO shim returns a direct RAMBlock HVA for a host-contiguous
run and a packed `mach_vm_remap` view for a fragmented one. `unmap_pages` was
`(void)ptr; (void)len;` and the views were held in `stable_aliases` until device
teardown, so every fragmented map leaked a VA reservation for the VM's lifetime.

That retention existed for one reason: Rust cached `VK_EXT_external_memory_host`
imports over those views and could re-read the pages at any later point, so the
address had to stay valid forever. Nothing imports guest pages any more, so the
retention buys nothing and the leak is pure cost.

`unmap_pages` now releases. The array survives as `page_views` but its job is
inverted — it is a *lookup*, not a retention list. It has to exist: a view and a
direct RAMBlock HVA are indistinguishable as bare pointers, and
`mach_vm_deallocate` on the latter would unmap the guest's own memory. A pointer
not found in it is guest RAM and is left alone. The recorded allocation length
is used rather than the caller's `len`, because a run entered at a page offset
asks to release fewer bytes than its view spans.

`reims_vgpu_mmio_free_page_views` stays as a teardown backstop but now logs
anything still mapped. A silent reclaim there is exactly what hid this leak.

`map_pages_stable` splits, and the split is the honest reading:

- MMIO -> 0. It can hand out a view whose lifetime the caller owns, and the flag
  cannot be conditioned on whether a particular run turned out contiguous.
- PCI -> 1, unchanged, with the claim narrowed in its comment. That shim never
  allocates: it refuses any list that is not a packed host-contiguous run and
  otherwise returns `memory_region_get_ram_ptr() + xlat`, which is guest RAM
  itself. No release is owed and none is possible to get wrong.

The flag used to mean "you may retain this inside a cached host-pointer import".
It now means only "no release is owed", which is why the two shims can disagree.

Not verified: QEMU is not configured or built on this host — the edits are
brace/paren balanced and `qemu/log.h` is already included for the new
`qemu_log_mask`, but nothing compiled them and no VM was booted.
2026-07-29 15:00:56 +03:00
Anees Iqbal 64b7545a8f 🔥 The console surface is one path again, with no imported backing
Component: QEMU MMIO shim (hw/display/reims-vgpu-mmio.c).

`reims_vgpu_mmio_set_gpu_mode` allocated a display buffer at an alignment it
negotiated with Rust, attached it as the DisplaySurface backing, and handed it
to `reims_vgpu_qemu_scanout_gpu_copy` so the engine could DMA a finished present
into it — no framebuffer bytes across the CPU.

The alignment came from `VK_EXT_external_memory_host` and the buffers had to be
retained in `scanout_buffers` until teardown, because the engine cached their
imports. That extension is no longer requested, so the alignment query now fails
and the branch is dead. Removed the function, `surface_gpu_direct`,
`surface_buffer_len`, and the whole `scanout_buffers` retention array, leaving
`reims_vgpu_mmio_set_mode` and the CPU `scanout_copy` as the single path — which
is what every frame already took whenever the direct arm declined.

Not verified: QEMU is not built on this host and no VM was booted. The
corresponding Rust ABI exports and header declarations go in the same
superproject commit, so a build sees both sides or neither.
2026-07-29 14:51:05 +03:00
Anees IqbalandClaude debb769cce 🔥 Drop the deprecated GL/dmabuf scanout bridge
`reims_vgpu_pci_scanout_gl` imported an exported present dmabuf into QEMU's
console GL context. Its own comment named it "Deprecated pre-host-window
GL/dmabuf bridge" and said "The supported product path is the Rust host
window/direct-present route; keep this shim thin and do not extend it for fps
work unless explicitly doing historical investigation."

The Rust side only ever enqueued this action behind `REIMS_VGPU_SCANOUT_GL=1`, so it
was dead on every normal boot, and it is a second display path competing with
the real one. Removed there in the same change; this drops the handler and its
`REIMS_VGPU_HOST_ACTION_SCANOUT_GL` dispatch arm.

Wire value 7 is retired rather than reused: the surrounding action numbers are
unchanged (6 then 8), so nothing else on the ABI moves.

Not built — QEMU was not compiled for this change; verified by grep that no
reference to the removed symbols remains under hw/display/.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-07-29 05:48:44 +03:00
Anees Iqbal 1a41502fdc Point Reims vGPU build at crate workspace
Component: QEMU display build integration.

Update the Reims vGPU Meson integration for the repository layout where QEMU lives under vendor/qemu and the Rust host crate lives under crates/reims-vgpu. The C shim still links the same staticlib and includes the same C ABI header; only the source-root-relative paths change.

Verification: ran git diff --check in the QEMU submodule before committing.
2026-07-26 14:40:58 +03:00
Anees Iqbal 9b3625cca1 Add Reims vGPU QEMU shims
Component: QEMU display/vmapple integration.

Add thin sysbus MMIO and PCI Reims vGPU devices that hand device behavior to the host Rust backend through the C ABI. Wire the devices into hw/display build configuration, trace events, and vmapple's gfx-device selection while keeping protocol and backend logic outside QEMU.

Verification: reconstructed from base b83371668192a705b878e909c5ae9c1233cbd5fb; applied host/qemu-patches/0001-0005 with git am --3way; staged the exact tree from current host/qemu tip ab8fc79abf9a366e6b6effc258c9c53b188f6753; final tree compared against that tip before push.
2026-07-26 14:24:35 +03:00
Anees Iqbal 33dc61d2cf vmapple: gfx-device property for apple-gfx-mmio Reims VGPU slots
Select the paravirt GPU backing REIMS_VGPU_GFX/REIMS_VGPU_IOSFC via a machine property
(default apple-gfx-mmio). Product-device alternatives were removed; only
Apple's ParavirtualizedGraphics path remains valid.
2026-07-26 14:23:54 +03:00
Anees Iqbal 4a2e2b3967 hvf: place the in-kernel vGIC at the machine's GIC bases
hvf_arch_vm_create() hardcoded the hv_gic distributor/redistributor GPAs
to hw/arm/virt.c's base_memmap (0x08000000/0x080A0000). On any machine
whose GICv3 lives elsewhere — vmapple puts it at 0x10000000/0x10010000 —
kernel-irqchip=on placed the in-kernel vGIC at addresses the guest never
touches, while the guest's dist/redist accesses landed on the GIC
device's ops-less MemoryRegions (reads-as-zero, writes ignored). A
vmapple macOS guest wedges in iBootStage2 that way (no timer PPI ever
enabled, one vCPU spins at 100%).

Add a MachineClass::get_vgic_bases hook (mirroring
get_kernel_irqchip_default), implement it for vmapple from its memmap,
and fall back to the virt values when a board does not provide it.

With this, vmapple boots macOS to the desktop under kernel-irqchip=on:
render oracle clean (1440x1080 screendump, desktop content), ssh up,
in-guest top idle. Verified on macOS 26.5 host, Monterey vmapple guest.
2026-07-26 14:23:54 +03:00
Anees Iqbal 663b9b9c0b hvf: emulate ISV=0 data aborts (LDP/STP, SIMD&FP, indexed LDR/STR)
macOS 13+ guest kernels access MMIO with instructions the CPU reports with
ISV=0 (no instruction syndrome) during early boot — load/store pair, SIMD&FP
single-register, and pre/post-indexed GPR loads/stores. macOS 12 did not, so
the vmapple bring-up never hit this. QEMU's hvf arm data-abort handler had a
bare assert(isv), so any such access aborted QEMU (observed:
insn=0xb8080d09 'str w9,[x8,#128]!' at ipa=0x10020080).

Decode the faulting instruction from guest memory and perform the access at
the already-translated fault IPA, covering exactly the A64 classes that report
ISV=0 and can target MMIO. Refuse SP-based writeback and anything unrecognized
(abort with pc/insn/va/ipa context) rather than silently mis-emulating.
2026-07-26 14:23:54 +03:00
Anees Iqbal cbb749d421 hvf: skip NO_RAW cpregs in hvf_arch_init_vcpu (macOS 26 host)
hvf_arch_init_vcpu() asserts !(ri->type & ARM_CP_NO_RAW) while building the
cpreg sync list. Some ID registers (e.g. ID_AA64ISAR0_EL1) became
ARM_CP_NO_RAW in system emulation because a field is computed at read time
via a readfn (RNDR depends on SCR_EL3.TRNDR under FEAT_RNG_TRAP). Such regs
have no raw backing store to sync with HVF and must not be added to the sync
list. Without this, the assert aborts on a macOS 26 host and no aarch64 HVF
guest (incl. vmapple) can start. Verified live: the vmapple guest gets past
HVF vCPU init to iBootStage2 with this change.
2026-07-26 14:23:54 +03:00
Anees Iqbal e181197cc2 vmapple: enable arm macOS guest boot on a macOS 26 host (RFC v7 patches 1-6)
Applies the QEMU-devel RFC v7 series "vmapple: make it work on the latest
macOS release" (Mohamed Mediouni), patches 1-6, rebased onto this base:

  1. apple-gfx: use the macOS 15.4+ PGMemoryMapDescriptor interface
     (+ argument buffers / process isolation)
  2. hw/vmapple/aes: convert MAX_LEN to a #define
  3. vmapple: declare it AArch64-compatible (visible to -M vmapple)
  4. build the VMapple machine by default (CONFIG_VMAPPLE=y)
  5. vmapple: add the arm-gicv2m MSI controller
  6. vmapple, gicv2m: macOS compat quirk (V2M_MSI_TYPER bit 31)

Patch 7 (private ISA / Tahoe) is deliberately excluded: it requires SIP
disabled + AMFI bypass, which this project does not do. This boots an arm
macOS Monterey guest under -M vmapple with HVF on a macOS 26 host.
2026-07-26 14:23:54 +03:00
21 changed files with 4036 additions and 26 deletions

No files matched your search

+4
View File
@@ -20,3 +20,7 @@ GTAGS
*.swp
*.patch
*.gcov
# LLVM coverage artifacts (see scripts/runtime-dead in the parent repo).
*.profraw
*.profdata
+1 -1
View File
@@ -9,4 +9,4 @@ include ../arm-softmmu/default.mak
# CONFIG_XLNX_VERSAL=n
# CONFIG_SBSA_REF=n
# CONFIG_NPCM8XX=n
CONFIG_VMAPPLE=n
CONFIG_VMAPPLE=y
+11
View File
@@ -153,3 +153,14 @@ config MAC_PVG_PCI
bool
depends on MAC_PVG && PCI
default y if PCI_DEVICES
# Product paravirt GPU: thin QEMU C → host/reims-vgpu Rust staticlib.
# Sibling of MAC_PVG_MMIO (Apple's ParavirtualizedGraphics.framework path).
# Builds both:
# reims-vgpu-mmio — sysbus (vmapple / arm)
# reims-vgpu-pci — PCI (x86 Tahoe; vendor 0x106B / device 0xEEEE)
# No arch dependency: Linux/x86 builds link the Metal host stubs / Vulkan so the
# device + Rust staticlib stay in the link graph while real encode is filled in.
config REIMS_VGPU
bool
default y
+42 -11
View File
@@ -19,6 +19,7 @@
#include "hw/core/irq.h"
#include "apple-gfx.h"
#include "trace.h"
#include "system/address-spaces.h"
#import <ParavirtualizedGraphics/ParavirtualizedGraphics.h>
@@ -36,12 +37,19 @@ typedef bool(^IOSFCMapMemory)(uint64_t phys, uint64_t len, bool ro, void **va,
@interface PGDeviceDescriptor (IOSurfaceMapper)
@property (readwrite, nonatomic) bool usingIOSurfaceMapper;
@property (readwrite, nonatomic) bool enableArgumentBuffers;
@property (readwrite, nonatomic) bool enableProcessIsolation;
@property (readwrite, nonatomic) bool enableProtectedContent;
@property (readwrite, nonatomic, copy, nullable) PGMemoryMapDescriptor* memoryMapDescriptor;
@end
@interface PGIOSurfaceHostDeviceDescriptor : NSObject
-(PGIOSurfaceHostDeviceDescriptor *)init;
@property (readwrite, nonatomic, copy, nullable) IOSFCMapMemory mapMemory;
@property (readwrite, nonatomic, copy, nullable) IOSFCUnmapMemory unmapMemory;
@property (readwrite, nonatomic, copy, nullable) PGMemoryMapDescriptor* memoryMapDescriptor;
@property (readwrite, nonatomic) unsigned long long mmioLength;
@property (readwrite, nonatomic, copy, nullable) IOSFCRaiseInterrupt raiseInterrupt;
@end
@@ -183,19 +191,32 @@ static PGIOSurfaceHostDevice *apple_gfx_prepare_iosurface_host_device(
[PGIOSurfaceHostDeviceDescriptor new];
PGIOSurfaceHostDevice *iosfc_host_dev;
iosfc_desc.mapMemory =
^bool(uint64_t phys, uint64_t len, bool ro, void **va, void *e, void *f) {
*va = apple_gfx_mmio_map_surface_memory(phys, len, ro);
/*
* The legacy memory management API is no longer present
* for the IOSurface mapper as of macOS 15.4.
*/
if (@available(macOS 15.4, *)) {
PGMemoryMapDescriptor *memory_map_descriptor = [PGMemoryMapDescriptor new];
FlatView* fv = address_space_to_flatview(&address_space_memory);
flatview_for_each_range(fv, apple_gfx_register_memory_cb, memory_map_descriptor);
/* the device model defines this as a single-page MMIO region, hence 16KB */
iosfc_desc.mmioLength = 0x10000;
iosfc_desc.memoryMapDescriptor = memory_map_descriptor;
} else {
iosfc_desc.mapMemory =
^bool(uint64_t phys, uint64_t len, bool ro, void **va, void *e, void *f) {
*va = apple_gfx_mmio_map_surface_memory(phys, len, ro);
trace_apple_gfx_iosfc_map_memory(phys, len, ro, va, e, f, *va);
trace_apple_gfx_iosfc_map_memory(phys, len, ro, va, e, f, *va);
return *va != NULL;
};
return *va != NULL;
};
iosfc_desc.unmapMemory =
^bool(void *va, void *b, void *c, void *d, void *e, void *f) {
return apple_gfx_mmio_unmap_surface_memory(va);
};
iosfc_desc.unmapMemory =
^bool(void *va, void *b, void *c, void *d, void *e, void *f) {
return apple_gfx_mmio_unmap_surface_memory(va);
};
}
iosfc_desc.raiseInterrupt = ^bool(uint32_t vector) {
trace_apple_gfx_iosfc_raise_irq(vector);
@@ -223,13 +244,23 @@ static void apple_gfx_mmio_realize(DeviceState *dev, Error **errp)
};
desc.usingIOSurfaceMapper = true;
s->pgiosfc = apple_gfx_prepare_iosurface_host_device(s);
desc.enableArgumentBuffers = true;
/*
* Process isolation needs PGMemoryMapDescriptor instead of
* the legacy memory management interface present in releases
* older than macOS 15.4.
*/
if (@available(macOS 15.4, *)) {
desc.enableProcessIsolation = true;
}
if (!apple_gfx_common_realize(&s->common, dev, desc, errp)) {
[s->pgiosfc release];
s->pgiosfc = nil;
}
s->pgiosfc = apple_gfx_prepare_iosurface_host_device(s);
[desc release];
desc = nil;
}
+16
View File
@@ -12,6 +12,7 @@
#include "system/memory.h"
#include "hw/core/qdev-properties.h"
#include "ui/surface.h"
#include "objc/NSObject.h"
#define TYPE_APPLE_GFX_MMIO "apple-gfx-mmio"
#define TYPE_APPLE_GFX_PCI "apple-gfx-pci"
@@ -23,6 +24,17 @@
@protocol MTLTexture;
@protocol MTLCommandQueue;
typedef struct PGGuestPhysicalRange_s
{
uint64_t physicalAddress;
uint64_t physicalLength;
void *hostAddress;
} PGGuestPhysicalRange_t;
@interface PGMemoryMapDescriptor : NSObject
-(void)addRange:(PGGuestPhysicalRange_t) range;
@end
typedef QTAILQ_HEAD(, PGTask_s) PGTaskList;
typedef struct AppleGFXDisplayMode {
@@ -68,6 +80,10 @@ void *apple_gfx_host_ptr_for_gpa_range(uint64_t guest_physical,
uint64_t length, bool read_only,
MemoryRegion **mapping_in_region);
bool apple_gfx_register_memory_cb(Int128 start, Int128 len,
const MemoryRegion *mr,
hwaddr offset_in_region, void *opaque);
extern const PropertyInfo qdev_prop_apple_gfx_display_mode;
#endif
+40 -1
View File
@@ -21,6 +21,7 @@
#include "system/address-spaces.h"
#include "system/dma.h"
#include "migration/blocker.h"
#include "system/memory.h"
#include "ui/console.h"
#include "apple-gfx.h"
#include "trace.h"
@@ -596,6 +597,35 @@ void apple_gfx_common_init(Object *obj, AppleGFXState *s, const char* obj_name)
/* TODO: PVG framework supports serialising device state: integrate it! */
}
@interface PGDeviceDescriptor (IOSurfaceMapper)
@property (readwrite, nonatomic, copy, nullable) PGMemoryMapDescriptor* memoryMapDescriptor;
@end
bool apple_gfx_register_memory_cb(Int128 start, Int128 len,
const MemoryRegion *mr,
hwaddr offset_in_region, void *opaque) {
PGGuestPhysicalRange_t range;
PGMemoryMapDescriptor *memory_map_descriptor = opaque;
if (memory_access_is_direct(mr, true, MEMTXATTRS_UNSPECIFIED)) {
range.physicalAddress = start;
range.physicalLength = len;
range.hostAddress = memory_region_get_ram_ptr(mr);
[memory_map_descriptor addRange:range];
}
return false;
}
static void apple_gfx_register_memory(AppleGFXState *s,
PGDeviceDescriptor *desc)
{
PGMemoryMapDescriptor* memoryMapDescriptor = [PGMemoryMapDescriptor new];
FlatView* fv = address_space_to_flatview(&address_space_memory);
flatview_for_each_range(fv, apple_gfx_register_memory_cb, memoryMapDescriptor);
desc.memoryMapDescriptor = memoryMapDescriptor;
}
static void apple_gfx_register_task_mapping_handlers(AppleGFXState *s,
PGDeviceDescriptor *desc)
{
@@ -763,7 +793,16 @@ bool apple_gfx_common_realize(AppleGFXState *s, DeviceState *dev,
desc.device = s->mtl;
apple_gfx_register_task_mapping_handlers(s, desc);
/*
* The legacy memory management interface doesn't allow for
* vGPU sandboxing. As such, always use the new interface
* on macOS 15.4 onwards.
*/
if (@available(macOS 15.4, *)) {
apple_gfx_register_memory(s, desc);
} else {
apple_gfx_register_task_mapping_handlers(s, desc);
}
s->cursor_show = true;
+108
View File
@@ -65,6 +65,114 @@ system_ss.add(when: 'CONFIG_ATI_VGA', if_true: [files('ati.c', 'ati_2d.c', 'ati_
system_ss.add(when: [pvg, 'CONFIG_MAC_PVG_PCI'], if_true: [files('apple-gfx.m', 'apple-gfx-pci.m')])
system_ss.add(when: [pvg, 'CONFIG_MAC_PVG_MMIO'], if_true: [files('apple-gfx.m', 'apple-gfx-mmio.m')])
if config_all_devices.has_key('CONFIG_REIMS_VGPU')
# Thin QEMU C device links crates/reims-vgpu (Cargo staticlib). Backend is a
# configure-time choice baked into the binary — one backend per boot, never a
# runtime env sniff.
# Sources live in the parent repo, two directories above this vendored submodule.
reims_vgpu_repo_dir = meson.global_source_root() / '..' / '..'
reims_vgpu_abi_header_dir = reims_vgpu_repo_dir / 'crates' / 'reims-vgpu' / 'include'
# A meson option and not the environment, because meson re-runs this file
# whenever ninja decides the build is out of date — and that regeneration
# inherits ninja's environment, not the one the configure ran under. A build
# configured for Vulkan therefore silently became a Metal one the first time
# any meson.build changed under a plain `ninja`, and on Linux that build fails
# with twenty Rust errors from an Apple-only arm. An option is stored in the
# build directory and survives regeneration, which is the property this needs.
#
# `env` keeps `REIMS_VGPU_BACKEND` working for a caller that has not been
# taught the option yet, and it is only ever read on a real configure —
# `scripts/qemu-build` passes the option, so the fallback is not on the path
# any boot takes.
reims_vgpu_backend_kind = get_option('reims_vgpu_backend')
if reims_vgpu_backend_kind == 'env'
reims_vgpu_backend_kind = run_command(find_program('sh'), '-c',
'printf %s "${REIMS_VGPU_BACKEND:-metal}"', check: true).stdout().strip()
endif
cargo = find_program('cargo')
# Rust staticlib always needs these on Unix; Apple frameworks only on Darwin.
reims_vgpu_rust_sys_libs = ['-lm', '-ldl', '-lpthread']
if host_os == 'darwin'
reims_vgpu_rust_sys_libs += ['-liconv']
endif
if reims_vgpu_backend_kind == 'metal'
reims_vgpu_cargo_features = '--features backend-metal'
if host_os == 'darwin'
reims_vgpu_link_args = [
'-framework', 'Metal',
'-framework', 'Foundation',
'-framework', 'QuartzCore',
'-framework', 'CoreGraphics',
'-lobjc',
] + reims_vgpu_rust_sys_libs
else
# Host metal stubs: no Apple frameworks.
reims_vgpu_link_args = reims_vgpu_rust_sys_libs
endif
elif reims_vgpu_backend_kind == 'vulkan'
# host-window adds the Rust-owned winit + VkSurfaceKHR presentation window
# (kb host-window), opt-in at runtime behind REIMS_VGPU_WINDOW. Always built into
# the vulkan binary; reims_vgpu_qemu_window_start returns ERR_STATE if unused.
reims_vgpu_cargo_features = '--no-default-features --features backend-vulkan,host-window'
# ash loads the Vulkan loader at runtime; no link-time Vulkan dep.
if host_os == 'darwin'
# winit/raw-window-metal link against the native macOS windowing stack even
# when REIMS_VGPU_WINDOW is off at runtime. Keep the Rust staticlib dependency
# self-contained so a Darwin Vulkan QEMU link does not depend on Cocoa
# already being enabled elsewhere in QEMU.
reims_vgpu_link_args = [
'-framework', 'AppKit',
'-framework', 'ApplicationServices',
'-framework', 'Carbon',
'-framework', 'CoreFoundation',
'-framework', 'CoreGraphics',
'-framework', 'CoreVideo',
'-framework', 'Foundation',
'-framework', 'Metal',
'-framework', 'QuartzCore',
'-lobjc',
] + reims_vgpu_rust_sys_libs
else
# Linux window backends are loaded by winit/ash-window at runtime.
reims_vgpu_link_args = reims_vgpu_rust_sys_libs
# Runtime-dead measurement (scripts/runtime-dead). When the staticlib is
# built with -C instrument-coverage, its objects carry __llvm_prf_* but
# nothing that writes them: rustc bundles the profiler runtime into a
# final artifact, and this staticlib is not one — it is linked by QEMU.
# So the profile runtime is named here instead, whole-archive because no
# instrumented object references it and the linker would drop every
# member. REIMS_VGPU_COVERAGE holds the path to
# libclang_rt.profile-<arch>.a; unset (the default) changes nothing.
reims_vgpu_coverage_rt = run_command('sh', '-c',
'printf %s "$REIMS_VGPU_COVERAGE"', check: false).stdout().strip()
if reims_vgpu_coverage_rt != ''
reims_vgpu_link_args += ['-Wl,--whole-archive', reims_vgpu_coverage_rt,
'-Wl,--no-whole-archive']
endif
endif
else
error('unknown REIMS_VGPU_BACKEND: ' + reims_vgpu_backend_kind + ' (metal | vulkan)')
endif
reims_vgpu_built = reims_vgpu_repo_dir / 'target' / 'release' / 'libreims_vgpu.a'
reims_vgpu_a = custom_target('reims-vgpu-staticlib',
output: 'libreims_vgpu.a',
console: true,
build_always_stale: true,
command: [find_program('sh'), '-c',
'"' + cargo.full_path() + '" build --release --manifest-path "' +
reims_vgpu_repo_dir + '/Cargo.toml" -p reims-vgpu ' + reims_vgpu_cargo_features +
' && ( cmp -s "' + reims_vgpu_built + '" "@OUTPUT@" || cp "' +
reims_vgpu_built + '" "@OUTPUT@" )'])
# Header lives outside the qemu submodule tree; use compile_args -I.
reims_vgpu_dep = declare_dependency(
link_with: reims_vgpu_a,
link_args: reims_vgpu_link_args,
compile_args: ['-I' + reims_vgpu_abi_header_dir])
system_ss.add(when: 'CONFIG_REIMS_VGPU',
if_true: [files('reims-vgpu-mmio.c', 'reims-vgpu-pci.c', 'reims-vgpu-dirty.c',
'reims-vgpu-shim.c'), reims_vgpu_dep])
endif
if config_all_devices.has_key('CONFIG_VIRTIO_GPU')
virtio_gpu_ss = ss.source_set()
virtio_gpu_ss.add(when: 'CONFIG_VIRTIO_GPU',
+639
View File
@@ -0,0 +1,639 @@
/*
* reims-vgpu: guest-write tracking over the hypervisor dirty bitmap.
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "qemu/osdep.h"
#include "qemu/thread.h"
#include "qemu/rcu.h"
#include "exec/target_page.h"
#include "system/address-spaces.h"
#include "system/memory.h"
#include "system/physmem.h"
#include "system/ram_addr.h"
#include "reims-vgpu-dirty.h"
/*
* One guest-RAM range of the system address space. A tracked page is resolved
* against this table by address, so one entry serves every page that lands in
* it — the same reason reims_vgpu_*_map_pages walks maximal runs.
*/
typedef struct ReimsVgpuDirtySlice {
MemoryRegion *mr;
uint64_t gpa; /* first GPA covered */
uint64_t len; /* bytes covered */
ram_addr_t ram_addr; /* ram_addr_t of `gpa` */
hwaddr offset; /* offset of `gpa` within mr */
/* Whether this device was already recording writes to the range when this
* harvest's sync ran, and whether a tracked page asked it to start. Held
* per slice rather than in parallel arrays because they are read in the
* page loop, which is the harvest's inner loop. */
bool logged;
bool needs_log;
} ReimsVgpuDirtySlice;
/* A tracked page set: one mapping incarnation's guest storage. */
typedef struct ReimsVgpuDirtySet {
uint64_t *pages; /* sorted, deduplicated, page-aligned */
/*
* Parallel to `pages`: the value `gen` took at the harvest that last saw
* this page written, or 0 for a page never seen written. A set-level
* generation can only say "something in here moved", which forces a reader
* holding a whole-surface copy to discard all of it; this is what lets it
* discard exactly the pages that moved.
*/
uint64_t *page_gen;
size_t count;
uint64_t page_size;
uint64_t gen; /* 0 until armed */
uint64_t arm_at; /* harvest count at which gen may leave 0 */
} ReimsVgpuDirtySet;
struct ReimsVgpuDirty {
QemuMutex lock;
GHashTable *sets; /* token -> ReimsVgpuDirtySet* */
uint64_t next_token;
/*
* Regions this device turned DIRTY_MEMORY_VGA logging on for, referenced
* so the pointers stay valid until we turn it back off. Logging stays on
* for the device's life: toggling it per surface re-protects the whole
* region each time, and the guest's entire working set would refault for a
* saving this device never collects.
*/
GHashTable *logged; /* MemoryRegion* -> itself */
/*
* The guest-RAM ranges of the system address space, rebuilt at the top of
* each harvest and owned across harvests only so the steady state does not
* allocate. Grown to whatever the flat view reports and never bounded: a
* range this table dropped would read as written for every page in it, for
* the life of the VM, with nothing to say so — which is precisely the
* failure the flat view walk replaced.
*
* Measured at 5 ranges on x86 q35 with this device, unchanged across a
* driven boot including the load phase. So this is not a table under
* pressure, and the growth is not there to serve a reach anyone has seen.
* It is here because the alternative to growing is dropping, and dropping
* is unobservable from the guest side and permanent.
*/
ReimsVgpuDirtySlice *slices;
int slices_cap;
uint64_t harvests;
/*
* Generation reads since the last harvest. A harvest nothing has consumed
* since the previous one cannot tell any reader something it does not
* already know, so it is skipped — which collapses a burst of doorbell
* writes into one sync.
*/
uint64_t reads_since_harvest;
};
static void reims_vgpu_dirty_set_free(gpointer p)
{
ReimsVgpuDirtySet *s = p;
g_free(s->pages);
g_free(s->page_gen);
g_free(s);
}
ReimsVgpuDirty *reims_vgpu_dirty_new(void)
{
ReimsVgpuDirty *d = g_new0(ReimsVgpuDirty, 1);
qemu_mutex_init(&d->lock);
d->sets = g_hash_table_new_full(g_int64_hash, g_int64_equal, g_free,
reims_vgpu_dirty_set_free);
d->logged = g_hash_table_new(NULL, NULL);
return d;
}
void reims_vgpu_dirty_free(ReimsVgpuDirty *d)
{
GHashTableIter it;
gpointer key, val;
if (!d) {
return;
}
/* BQL: memory_region_set_log is a MemoryRegion transaction. */
g_hash_table_iter_init(&it, d->logged);
while (g_hash_table_iter_next(&it, &key, &val)) {
MemoryRegion *mr = key;
memory_region_set_log(mr, false, DIRTY_MEMORY_VGA);
memory_region_unref(mr);
}
g_hash_table_destroy(d->logged);
g_hash_table_destroy(d->sets);
g_free(d->slices);
qemu_mutex_destroy(&d->lock);
g_free(d);
}
static int reims_vgpu_dirty_cmp_u64(const void *a, const void *b)
{
uint64_t x = *(const uint64_t *)a;
uint64_t y = *(const uint64_t *)b;
return x < y ? -1 : (x > y ? 1 : 0);
}
/*
* One guest page a harvest found written, with the geometry it was tracked at.
* The size travels with the page because the clear must cover the whole guest
* page and the two pathways do not share a page shift.
*/
typedef struct ReimsVgpuDirtyWritten {
uint64_t gpa;
uint64_t page_size;
} ReimsVgpuDirtyWritten;
static int reims_vgpu_dirty_cmp_written(gconstpointer a, gconstpointer b)
{
const ReimsVgpuDirtyWritten *x = a;
const ReimsVgpuDirtyWritten *y = b;
if (x->gpa != y->gpa) {
return x->gpa < y->gpa ? -1 : 1;
}
/* Larger page first, so a duplicate of the same base collapses into the
* run the wider page opens rather than truncating it. */
return x->page_size > y->page_size ? -1 : (x->page_size < y->page_size);
}
uint64_t reims_vgpu_dirty_track(ReimsVgpuDirty *d, const uint64_t *gpas,
size_t count, size_t page_size)
{
ReimsVgpuDirtySet *s;
uint64_t *pages;
uint64_t token;
size_t i, n;
if (!d || !gpas || count == 0 || page_size == 0 ||
(page_size & (page_size - 1)) != 0) {
return 0;
}
/*
* The dirty bitmap is indexed in target pages, so a guest page smaller
* than one cannot be asked about. Both product pathways are the other way
* round (4 KiB x86 == target, 16 KiB arm64e > target), and answering for a
* granularity the bitmap does not have would be a guess.
*/
if (page_size < qemu_target_page_size()) {
return 0;
}
pages = g_new(uint64_t, count);
for (i = 0; i < count; i++) {
pages[i] = gpas[i] & ~((uint64_t)page_size - 1);
}
qsort(pages, count, sizeof(*pages), reims_vgpu_dirty_cmp_u64);
n = 0;
for (i = 0; i < count; i++) {
if (n == 0 || pages[n - 1] != pages[i]) {
pages[n++] = pages[i];
}
}
s = g_new0(ReimsVgpuDirtySet, 1);
s->pages = pages;
s->page_gen = g_new0(uint64_t, n);
s->count = n;
s->page_size = page_size;
qemu_mutex_lock(&d->lock);
/*
* One harvest, and a second only if that harvest has to turn logging on.
*
* This used to be an unconditional two, because "the first harvest after
* this call is the one that may still be turning logging on for these
* pages, so writes older than it were never recorded". That reason is
* right, and it is a reason about the *first* set to name a region — not
* about every set. Guest RAM is one MemoryRegion, so once any surface has
* been tracked, logging is already on for every later one, no harvest ever
* enables anything, and the second harvest was waiting for something that
* had already happened.
*
* It is not free to wait. While the set is unarmed its generation reads
* back 0, `HostOps::guest_write_gen` maps that to "cannot tell", the
* type-11 LOAD elision refuses with `t11_gw_ref_no_stamp`, and every draw
* onto that surface pays a whole-frame seed read out of guest pages plus a
* whole-frame staging upload. The window is counted in harvests and
* harvests are driven by guest doorbells, so on a quiet desktop it lasts as
* long as the guest stays quiet — which is exactly when a draw arriving
* into it is a visible hitch (measured at 12-65 ms per draw, against
* 0.2 ms driven).
*
* The second harvest is still taken when it is owed: `reims_vgpu_dirty_harvest`
* pushes every set still waiting when it had to enable logging, so a set
* created before the region was logged arms exactly as late as it used to.
*/
s->arm_at = d->harvests + 1;
d->next_token++;
token = d->next_token;
g_hash_table_insert(d->sets, g_memdup2(&token, sizeof(token)), s);
qemu_mutex_unlock(&d->lock);
return token;
}
void reims_vgpu_dirty_untrack(ReimsVgpuDirty *d, uint64_t token)
{
if (!d || token == 0) {
return;
}
qemu_mutex_lock(&d->lock);
g_hash_table_remove(d->sets, &token);
qemu_mutex_unlock(&d->lock);
}
uint64_t reims_vgpu_dirty_gen(ReimsVgpuDirty *d, uint64_t token)
{
ReimsVgpuDirtySet *s;
uint64_t gen = 0;
if (!d || token == 0) {
return 0;
}
qemu_mutex_lock(&d->lock);
s = g_hash_table_lookup(d->sets, &token);
if (s) {
gen = s->gen;
}
d->reads_since_harvest++;
qemu_mutex_unlock(&d->lock);
return gen;
}
int64_t reims_vgpu_dirty_written_since(ReimsVgpuDirty *d, uint64_t token,
uint64_t since_gen, uint64_t *out,
size_t max)
{
ReimsVgpuDirtySet *s;
int64_t found = 0;
size_t p;
if (!d || token == 0 || out == NULL) {
return -1;
}
qemu_mutex_lock(&d->lock);
s = g_hash_table_lookup(d->sets, &token);
/*
* `since_gen == 0` is a caller that never recorded a readable observation,
* and `s->gen == 0` is a set still inside its startup window. Neither can
* be compared against a page stamp, and both mean the same thing to the
* caller as an unknown token does.
*/
if (!s || s->gen == 0 || since_gen == 0) {
qemu_mutex_unlock(&d->lock);
return -1;
}
for (p = 0; p < s->count; p++) {
if (s->page_gen[p] <= since_gen) {
continue;
}
if ((size_t)found == max) {
/* Truncation would read as "these pages and no others". */
qemu_mutex_unlock(&d->lock);
return -1;
}
out[found++] = s->pages[p];
}
/*
* Counted like reims_vgpu_dirty_gen(): a caller asking this question is a
* consumer of the report, so the next harvest has something to tell it and
* must not be skipped.
*/
d->reads_since_harvest++;
qemu_mutex_unlock(&d->lock);
return found;
}
typedef struct ReimsVgpuDirtyRamScan {
ReimsVgpuDirty *d;
int n;
} ReimsVgpuDirtyRamScan;
static bool reims_vgpu_dirty_ram_range(Int128 start, Int128 len,
const MemoryRegion *mr,
hwaddr offset_in_region, void *opaque)
{
ReimsVgpuDirtyRamScan *scan = opaque;
ReimsVgpuDirty *d = scan->d;
ReimsVgpuDirtySlice *sl;
if (!mr->ram || !int128_nz(len)) {
return false;
}
if (scan->n == d->slices_cap) {
d->slices_cap = d->slices_cap ? d->slices_cap * 2 : 16;
d->slices = g_renew(ReimsVgpuDirtySlice, d->slices, d->slices_cap);
}
sl = &d->slices[scan->n++];
sl->logged = false;
sl->needs_log = false;
/*
* Dropping const: the FlatView hands out a const view of a region this
* harvest goes on to read a dirty bitmap for, turn logging on for, and
* clear bits in, all of which are non-const operations on a region the
* caller holds the BQL over.
*/
sl->mr = (MemoryRegion *)mr;
sl->gpa = int128_get64(start);
sl->len = int128_get64(len);
sl->offset = offset_in_region;
sl->ram_addr = memory_region_get_ram_addr(sl->mr) + offset_in_region;
return false;
}
/*
* The guest-RAM ranges of the system address space. Returns how many were
* recorded.
*
* This asks the FlatView rather than reconstructing it, and the difference is
* not a simplification. It used to cut a monotone hull of every GPA ever
* tracked into slices by walking it with address_space_translate(), and that
* walk could not be made correct: address_space_translate_internal() clamps
* `plen` to the section *only when the section is RAM* (system/physmem.c). The
* first non-RAM byte in the hull therefore returned the whole remaining length,
* and the walk recorded one "not RAM" slice covering every guest page above it.
*
* On x86 q35 low RAM ends below the PCI hole and high RAM begins at 4 GiB, so
* one tracked page landing in low RAM while others sat above the hole put every
* page in high RAM into that slice. The harvest reads a page it cannot resolve
* as written — the conservative answer, and the right one for a page that is
* genuinely gone — so every tracked surface then reported itself permanently
* overwritten by the guest. The hull never shrank and the clear pass skipped
* unresolved pages, so nothing could undo it for the life of the VM.
*
* Downstream that is a guest-visible latch, not a slow path: every host-side
* copy of a surface is declared stale, the type-11 sampled rung refuses its
* resident and merges guest pages that never held the composite, and deferred
* render windows report `deferred_flush_clobber`. It reads as backdrops going
* transparent and popover geometry breaking, until the guest is rebooted.
*
* A range is kept whenever it is `ram`, including device BARs and flash. A
* tracked page that lands in one is a page this device must answer for rather
* than skip, and nothing turns logging on for a region until a tracked page
* resolves into it.
*
* Every such range is recorded; the table grows to fit rather than stopping at
* a bound. A bound here is not a budget that costs latency when it binds — a
* dropped range makes every page in it read as written for the life of the VM,
* which is the same latch by a smaller door, and one no counter would name.
* Growth is amortized and the steady state reallocates nothing, because the
* table is owned across harvests and the flat view's shape does not churn.
*/
static int reims_vgpu_dirty_ram_slices(ReimsVgpuDirty *d)
{
ReimsVgpuDirtyRamScan scan = { d, 0 };
RCU_READ_LOCK_GUARD();
flatview_for_each_range(address_space_to_flatview(&address_space_memory),
reims_vgpu_dirty_ram_range, &scan);
return scan.n;
}
/* Which slice holds `gpa`, or -1. Slices are few and ordered, so a linear
* scan beats any structure these counts would justify. */
static int reims_vgpu_dirty_slice_of(const ReimsVgpuDirtySlice *slices, int n,
uint64_t gpa)
{
int i;
for (i = 0; i < n; i++) {
if (gpa >= slices[i].gpa && gpa - slices[i].gpa < slices[i].len) {
return i;
}
}
return -1;
}
/*
* Was any target page of the guest page at `gpa` written?
*
* A pure read of the bitmap, deliberately: the answer must be the same for
* every set holding the page, so nothing is consumed here. Clearing happens
* once, after every set has been evaluated.
*/
static bool reims_vgpu_dirty_page_written(const ReimsVgpuDirtySlice *sl,
uint64_t gpa, uint64_t page_size)
{
size_t target = qemu_target_page_size();
ram_addr_t base = sl->ram_addr + (gpa - sl->gpa);
uint64_t off;
for (off = 0; off < page_size; off += target) {
if (physical_memory_get_dirty_flag(base + off, DIRTY_MEMORY_VGA)) {
return true;
}
}
return false;
}
void reims_vgpu_dirty_harvest(ReimsVgpuDirty *d)
{
ReimsVgpuDirtySlice *slices;
g_autoptr(GArray) written = NULL;
g_autoptr(GArray) hit = NULL;
GHashTableIter it;
gpointer key, val;
int n, i;
guint w;
if (!d) {
return;
}
qemu_mutex_lock(&d->lock);
if (g_hash_table_size(d->sets) == 0 || d->reads_since_harvest == 0) {
qemu_mutex_unlock(&d->lock);
return;
}
qemu_mutex_unlock(&d->lock);
n = reims_vgpu_dirty_ram_slices(d);
slices = d->slices;
/*
* Whether this device was already recording writes to each range when the
* sync below ran. Answered once per range rather than per page: the page
* loop runs over every page of every tracked set, and a hash lookup there
* is the harvest's inner loop.
*
* A range that is not logged yet is one whose bits mean nothing, so its
* pages read as written below and it is queued for logging afterwards.
* Enabling is deferred past the clear pass because memory_region_set_log()
* is a MemoryRegion transaction that rebuilds the flat view, which would
* leave this slice table describing a view that no longer exists.
*/
for (i = 0; i < n; i++) {
slices[i].logged = g_hash_table_contains(d->logged, slices[i].mr);
}
/* One sync for every logged region, then only reads. */
memory_global_dirty_log_sync(false);
written = g_array_new(FALSE, FALSE, sizeof(ReimsVgpuDirtyWritten));
/*
* Indices of the current set's written pages. Held across the generation
* update because the value to stamp them with is the generation this
* harvest produces, which is not known until every page has been read.
* Reused between sets so the harvest allocates once, not once per mapping.
*/
hit = g_array_new(FALSE, FALSE, sizeof(size_t));
qemu_mutex_lock(&d->lock);
d->harvests++;
d->reads_since_harvest = 0;
g_hash_table_iter_init(&it, d->sets);
while (g_hash_table_iter_next(&it, &key, &val)) {
ReimsVgpuDirtySet *s = val;
bool any = false;
bool unlogged = false;
size_t p;
g_array_set_size(hit, 0);
for (p = 0; p < s->count; p++) {
uint64_t gpa = s->pages[p];
int si = reims_vgpu_dirty_slice_of(slices, n, gpa);
/*
* Not guest RAM this device can read a bitmap for, or RAM whose
* writes this device was not yet recording when the sync ran.
* Both mean the host cannot say the page is unwritten, and that
* reads as written — per page as well as for the set, so a
* per-page reader is no less conservative than the generation is.
*/
if (si < 0) {
any = true;
g_array_append_val(hit, p);
continue;
}
if (!slices[si].logged) {
slices[si].needs_log = true;
unlogged = true;
any = true;
g_array_append_val(hit, p);
continue;
}
if (reims_vgpu_dirty_page_written(&slices[si], gpa, s->page_size)) {
ReimsVgpuDirtyWritten rec = { gpa, s->page_size };
any = true;
g_array_append_val(hit, p);
/* Recorded for the clear pass, which must not run until every
* set has read the bit — otherwise the first set harvested
* would consume the report of every set sharing the page. */
g_array_append_val(written, rec);
}
}
/*
* Some page of this set sits in a region whose writes this device was
* not yet recording when the sync above ran, so writes older than it
* were never recorded and their absence is not evidence. Wait for a
* harvest that covered every page.
*
* This is what lets `reims_vgpu_dirty_track` arm at +1 instead of +2.
* The +2 was paying for this case on every set; this pays for it on the
* sets it applies to, which after the first surface of a boot is none.
* The test is `s->gen == 0` — never armed — because an already armed set
* must not be sent back through its startup window: its pages read as
* written above, which is the conservative answer and needs no help.
*/
if (s->gen == 0 && unlogged) {
s->arm_at = d->harvests + 1;
}
if (d->harvests < s->arm_at) {
/* Startup window: an absence of reports says nothing about the
* guest yet, so the generation stays unreadable. */
s->gen = 0;
} else if (s->gen == 0) {
s->gen = 1;
} else if (any) {
s->gen++;
}
/*
* Stamp after the generation, and only once it is readable. A page
* stamped during the startup window would carry a generation no reader
* can have recorded, and would then read as written forever.
*/
if (s->gen != 0) {
guint h;
for (h = 0; h < hit->len; h++) {
s->page_gen[g_array_index(hit, size_t, h)] = s->gen;
}
}
}
qemu_mutex_unlock(&d->lock);
/*
* Clear only the pages that came back written. Clearing re-protects, so
* clearing the whole tracked window would make every page the guest has
* mapped refault after every harvest; clearing what was written costs
* exactly one refault per page the guest writes again, which is the work
* the report is worth.
*
* Exactly-adjacent pages merge into one call because each call is a
* hypervisor round trip. Nothing is widened: a merged range covers only
* pages that were themselves written.
*/
g_array_sort(written, reims_vgpu_dirty_cmp_written);
w = 0;
while (w < written->len) {
ReimsVgpuDirtyWritten first = g_array_index(written, ReimsVgpuDirtyWritten, w);
int si = reims_vgpu_dirty_slice_of(slices, n, first.gpa);
uint64_t end = first.gpa + first.page_size;
while (w + 1 < written->len) {
ReimsVgpuDirtyWritten next =
g_array_index(written, ReimsVgpuDirtyWritten, w + 1);
if (next.gpa + next.page_size <= end) {
/* Same page recorded by a second set, or a smaller page
* already inside the run. */
w++;
continue;
}
if (next.gpa != end ||
reims_vgpu_dirty_slice_of(slices, n, next.gpa) != si) {
break;
}
end = next.gpa + next.page_size;
w++;
}
if (si >= 0) {
memory_region_reset_dirty(
slices[si].mr, slices[si].offset + (first.gpa - slices[si].gpa),
end - first.gpa, DIRTY_MEMORY_VGA);
}
w++;
}
/*
* Start recording writes to every region a tracked page resolved into and
* that was not being recorded for the sync above. Last, because this is a
* MemoryRegion transaction: it rebuilds the flat view, and the slice table
* every pass above it describes the old one.
*
* Nothing is missed by the delay. Every page in such a region already read
* as written — which is what a region with no recorded history has to say —
* and no set whose pages were among them armed on this harvest.
*/
for (i = 0; i < n; i++) {
if (!slices[i].needs_log) {
continue;
}
/*
* One MemoryRegion can supply several ranges — on x86 q35 guest RAM is
* one region aliased below and above the PCI hole — so the insert is
* what decides, not the flag. g_hash_table_add() reports whether the
* key was new, which keeps the reference this table owns at one per
* region however many of its ranges asked.
*/
if (g_hash_table_add(d->logged, slices[i].mr)) {
memory_region_ref(slices[i].mr);
memory_region_set_log(slices[i].mr, true, DIRTY_MEMORY_VGA);
}
}
}
+91
View File
@@ -0,0 +1,91 @@
/*
* reims-vgpu: guest-write tracking over the hypervisor dirty bitmap.
*
* A paravirtual surface's storage is plain guest RAM. The guest CPU stores
* into it with no device operation, so nothing the Rust device counts can
* witness such a store, and every host-side copy of those pages (an engine
* resident, a cache entry) is stale from that instant with nothing to say so.
* The hypervisor's dirty bitmap is the only witness. This is the device-side
* adapter for it, shared by both shims.
*
* The Rust side registers a page set once per mapping incarnation and then
* reads a *generation*. A generation rather than a consume-on-read flag
* because a consumed flag is correct for exactly one reader: the first draw of
* a frame would eat the report and every later draw would be told the surface
* is clean.
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef REIMS_VGPU_DIRTY_H
#define REIMS_VGPU_DIRTY_H
#include <stdint.h>
#include <stddef.h>
typedef struct ReimsVgpuDirty ReimsVgpuDirty;
/* Create/destroy. Destroy runs with the BQL held: it turns region logging
* back off, which is a MemoryRegion transaction. */
ReimsVgpuDirty *reims_vgpu_dirty_new(void);
void reims_vgpu_dirty_free(ReimsVgpuDirty *d);
/*
* Register `count` page-aligned GPAs of `page_size` bytes as one tracked set.
* Returns a non-zero opaque token, or 0 when the set cannot be tracked.
* Safe from any thread.
*
* The token's generation reads back as 0 ("cannot tell") until one harvest has
* passed, and until two when that harvest was the one that turned dirty logging
* on for the pages' regions: writes older than the enable were never recorded
* and must not be mistaken for their absence. Guest RAM is one MemoryRegion, so
* after the first tracked surface of a boot no harvest enables anything and the
* window is one.
*/
uint64_t reims_vgpu_dirty_track(ReimsVgpuDirty *d, const uint64_t *gpas,
size_t count, size_t page_size);
/* Release a token. Safe from any thread; a stale or zero token is ignored. */
void reims_vgpu_dirty_untrack(ReimsVgpuDirty *d, uint64_t token);
/*
* Monotonic count of harvests that saw some page of the set written, or 0 for
* an unknown or not-yet-armed token. Safe from any thread, and idempotent:
* two reads returning the same value prove no harvest observed a write in
* between.
*/
uint64_t reims_vgpu_dirty_gen(ReimsVgpuDirty *d, uint64_t token);
/*
* Which pages of the set were written, not just whether any were.
*
* Fills `out` with the page-aligned GPAs of `token`'s set whose most recent
* observed write is newer than `since_gen`, and returns how many. `since_gen`
* is a value a caller previously read from reims_vgpu_dirty_gen() and recorded
* next to a host-side copy of the pages.
*
* Returns -1 for every case where the answer is not knowable and the caller must
* assume the whole set was written: an unknown token, a token whose generation
* is still unreadable, a `since_gen` of 0 (no recorded observation to compare
* against), or a set with more written pages than `max` can hold. A truncated
* list would say "these pages and no others", which is the one answer that turns
* a conservative caller into a wrong one.
*
* Safe from any thread.
*/
int64_t reims_vgpu_dirty_written_since(ReimsVgpuDirty *d, uint64_t token,
uint64_t since_gen, uint64_t *out,
size_t max);
/*
* Fold the hypervisor bitmap into every tracked set. **BQL thread only** —
* this enables MemoryRegion dirty logging and drives the accelerator's
* log_sync, neither of which is safe off the main thread.
*
* Call it where the guest hands the device work, so that every guest store
* ordered before that handoff is observed before the work runs. Cheap when
* nothing is tracked or when no generation has been read since the last call.
*/
void reims_vgpu_dirty_harvest(ReimsVgpuDirty *d);
#endif /* REIMS_VGPU_DIRTY_H */
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+308
View File
@@ -0,0 +1,308 @@
/*
* reims-vgpu: bus-independent shim services. See reims-vgpu-shim.h.
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "qemu/osdep.h"
#include "qemu/timer.h"
#include "hw/core/cpu.h"
#include "exec/cpu-common.h"
#include "system/address-spaces.h"
#include "system/hw_accel.h"
#include "system/memory.h"
#include "ui/console.h"
#include "ui/input.h"
#include "reims_vgpu_qemu_abi.h"
#include "reims-vgpu-shim.h"
uint64_t reims_vgpu_shim_mono_ns(void *ctx)
{
(void)ctx;
return (uint64_t)qemu_clock_get_ns(QEMU_CLOCK_HOST);
}
/*
* RAM-only attrs. `memory = 1` makes the address space reject a translation
* that resolves to a device rather than RAM (MEMTX_ACCESS_ERROR) instead of
* performing it. Every GPA reaching read/write_gpa came from a guest-supplied
* page-entry list, so an entry pointing at one of our own BARs would otherwise
* re-enter this device's MMIO handler from inside a Rust call that already
* holds the device lock. Failing closed turns that into a visible decline.
*/
static const MemTxAttrs reims_vgpu_shim_ram_attrs = {
.memory = true,
};
int reims_vgpu_shim_read_gpa(void *ctx, uint64_t gpa, uint8_t *buf, size_t len)
{
MemTxResult r;
(void)ctx;
if (!buf || len == 0) {
return 0;
}
r = address_space_read(&address_space_memory, gpa,
reims_vgpu_shim_ram_attrs, buf, len);
return r == MEMTX_OK ? 0 : -1;
}
int reims_vgpu_shim_write_gpa(void *ctx, uint64_t gpa, const uint8_t *buf,
size_t len)
{
MemTxResult r;
(void)ctx;
if (!buf || len == 0) {
return 0;
}
r = address_space_write(&address_space_memory, gpa,
reims_vgpu_shim_ram_attrs, buf, len);
return r == MEMTX_OK ? 0 : -1;
}
int reims_vgpu_shim_is_ram_gpa(void *ctx, uint64_t gpa)
{
hwaddr xlat, plen = 1;
MemoryRegion *mr;
int ok;
(void)ctx;
rcu_read_lock();
mr = address_space_translate(&address_space_memory, gpa, &xlat, &plen, true,
MEMTXATTRS_UNSPECIFIED);
ok = mr && memory_region_is_ram(mr) && plen >= 1;
rcu_read_unlock();
return ok ? 1 : 0;
}
/*
* Coalescing state for one guest_ram_regions walk.
*
* `found` counts every span the walk produced, including the ones past the
* caller's `max`. That is the difference between a caller that learns its array
* was short and one that imports part of the guest's RAM and never finds out.
*/
typedef struct ReimsVgpuRamScan {
ReimsVgpuGuestRamRegion *out;
size_t max;
size_t found;
bool pending;
uint64_t gpa;
uint64_t hva;
uint64_t len;
} ReimsVgpuRamScan;
static void reims_vgpu_ram_scan_flush(ReimsVgpuRamScan *scan)
{
if (!scan->pending) {
return;
}
if (scan->found < scan->max) {
scan->out[scan->found].gpa_base = scan->gpa;
scan->out[scan->found].host_va = scan->hva;
scan->out[scan->found].len = scan->len;
}
scan->found++;
scan->pending = false;
}
static bool reims_vgpu_ram_scan_range(Int128 start, Int128 len,
const MemoryRegion *mr,
hwaddr offset_in_region, void *opaque)
{
ReimsVgpuRamScan *scan = opaque;
uint64_t gpa, bytes, hva;
void *ptr;
/*
* ROM and ROMD ranges are RAM-backed but the guest cannot store into them,
* and a ram_device is somebody else's mapping (a VFIO BAR) rather than
* guest memory. Reporting any of the three would hand the GPU write access
* to bytes the guest believes are fixed, or does not own at all.
*/
if (!mr || !memory_region_is_ram(mr) || mr->readonly ||
memory_region_is_romd(mr) || memory_region_is_ram_device(mr)) {
reims_vgpu_ram_scan_flush(scan);
return false;
}
/*
* An Int128 that does not fit a uint64_t cannot be a mapping in this
* process's address space, so it is not a span anything could import.
*/
if (int128_gethi(start) != 0 || int128_gethi(len) != 0) {
reims_vgpu_ram_scan_flush(scan);
return false;
}
gpa = int128_get64(start);
bytes = int128_get64(len);
if (bytes == 0) {
return false;
}
ptr = memory_region_get_ram_ptr(mr);
if (!ptr) {
reims_vgpu_ram_scan_flush(scan);
return false;
}
hva = (uint64_t)(uintptr_t)ptr + (uint64_t)offset_in_region;
/*
* Merge only when the next range continues this one in *both* address
* spaces. A board that splits one RAMBlock across several flat ranges then
* costs one span, while two blocks that abut in GPA but not in host VA stay
* separate — merging those would make an offset inside the span name the
* wrong host bytes, which is exactly the failure importing a RAMBlock at a
* time exists to avoid.
*/
if (scan->pending && scan->gpa + scan->len == gpa &&
scan->hva + scan->len == hva && scan->len <= UINT64_MAX - bytes) {
scan->len += bytes;
return false;
}
reims_vgpu_ram_scan_flush(scan);
scan->pending = true;
scan->gpa = gpa;
scan->hva = hva;
scan->len = bytes;
return false;
}
int reims_vgpu_shim_guest_ram_regions(void *ctx, ReimsVgpuGuestRamRegion *out,
size_t max)
{
ReimsVgpuRamScan scan = { 0 };
(void)ctx;
if (!out || max == 0) {
return REIMS_VGPU_GUEST_RAM_ERR_ARGS;
}
scan.out = out;
scan.max = max;
rcu_read_lock();
flatview_for_each_range(address_space_to_flatview(&address_space_memory),
reims_vgpu_ram_scan_range, &scan);
rcu_read_unlock();
reims_vgpu_ram_scan_flush(&scan);
if (scan.found == 0) {
return REIMS_VGPU_GUEST_RAM_ERR_NO_RAM;
}
/*
* A span count that does not fit the return type is not a machine anyone
* runs. Reporting it as "no RAM" would be a lie, so it is the argument
* refusal: the caller asked for an answer this return value cannot carry.
*/
if (scan.found > (size_t)INT_MAX) {
return REIMS_VGPU_GUEST_RAM_ERR_ARGS;
}
return (int)scan.found;
}
int reims_vgpu_shim_read_kva(void *ctx, uint64_t kva, uint8_t *buf, size_t len)
{
CPUState *cs = current_cpu;
(void)ctx;
if (!buf || len == 0) {
return 0;
}
if (!cs) {
return -2;
}
cpu_synchronize_state(cs);
return cpu_memory_rw_debug(cs, kva, buf, len, false) == 0 ? 0 : -1;
}
static InputButton reims_vgpu_shim_button(uint32_t code, bool *ok)
{
*ok = true;
switch (code) {
case REIMS_VGPU_BUTTON_LEFT:
return INPUT_BUTTON_LEFT;
case REIMS_VGPU_BUTTON_MIDDLE:
return INPUT_BUTTON_MIDDLE;
case REIMS_VGPU_BUTTON_RIGHT:
return INPUT_BUTTON_RIGHT;
case REIMS_VGPU_BUTTON_WHEEL_UP:
return INPUT_BUTTON_WHEEL_UP;
case REIMS_VGPU_BUTTON_WHEEL_DOWN:
return INPUT_BUTTON_WHEEL_DOWN;
case REIMS_VGPU_BUTTON_SIDE:
return INPUT_BUTTON_SIDE;
case REIMS_VGPU_BUTTON_EXTRA:
return INPUT_BUTTON_EXTRA;
case REIMS_VGPU_BUTTON_WHEEL_LEFT:
return INPUT_BUTTON_WHEEL_LEFT;
case REIMS_VGPU_BUTTON_WHEEL_RIGHT:
return INPUT_BUTTON_WHEEL_RIGHT;
default:
*ok = false;
return INPUT_BUTTON_LEFT;
}
}
bool reims_vgpu_shim_scanout_may_paint(uint64_t rust_handle, uint32_t mapping_id)
{
uint32_t may = 0;
if (rust_handle == 0) {
return false;
}
if (reims_vgpu_qemu_scanout_may_paint(rust_handle, mapping_id, &may) !=
REIMS_VGPU_QEMU_OK) {
return false;
}
return may != 0;
}
uint32_t reims_vgpu_shim_console_feed(uint64_t rust_handle, uint32_t *out_mid,
uint32_t *out_w, uint32_t *out_h,
uint32_t *out_gen)
{
uint32_t kind = REIMS_VGPU_CONSOLE_FEED_FIRMWARE;
if (rust_handle == 0) {
return REIMS_VGPU_CONSOLE_FEED_FIRMWARE;
}
if (reims_vgpu_qemu_console_feed(rust_handle, &kind, out_mid, out_w, out_h,
out_gen) != REIMS_VGPU_QEMU_OK) {
return REIMS_VGPU_CONSOLE_FEED_FIRMWARE;
}
return kind;
}
void reims_vgpu_shim_input_key(QemuConsole *con, uint32_t evdev, bool down)
{
if (!con) {
return;
}
qemu_input_event_send_key_linux(con, evdev, down);
}
void reims_vgpu_shim_input_pointer_move(QemuConsole *con, uint32_t x,
uint32_t y, uint32_t w, uint32_t h)
{
if (!con || w == 0 || h == 0) {
return;
}
qemu_input_queue_abs(con, INPUT_AXIS_X, (int)x, 0, (int)w);
qemu_input_queue_abs(con, INPUT_AXIS_Y, (int)y, 0, (int)h);
qemu_input_event_sync();
}
void reims_vgpu_shim_input_button(QemuConsole *con, uint32_t code, bool down)
{
InputButton button;
bool ok;
if (!con) {
return;
}
button = reims_vgpu_shim_button(code, &ok);
if (!ok) {
return;
}
qemu_input_queue_btn(con, button, down);
qemu_input_event_sync();
}
+124
View File
@@ -0,0 +1,124 @@
/*
* reims-vgpu: shim services that do not depend on which bus attached the
* device, shared by reims-vgpu-pci and reims-vgpu-mmio.
*
* A service belongs here when its body reads nothing from the device state:
* either it ignores the HostOps `ctx` entirely (host clock, address-space
* queries, vCPU-relative reads) or it needs only the console, which the
* caller passes explicitly. Anything that touches the bus object, the
* per-device dirty tracker, or a bus-specific trace event stays in its shim.
*
* The point is not line count. A duplicated button table or address-space
* predicate is a table that can drift, and a drift between the two shims is
* a bug the guest sees on exactly one pathway.
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef REIMS_VGPU_SHIM_H
#define REIMS_VGPU_SHIM_H
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#include "qemu/typedefs.h"
/* ReimsVgpuGuestRamRegion, for the span enumeration below. */
#include "reims_vgpu_qemu_abi.h"
/*
* The five below match HostOps function-pointer signatures, so both shims'
* host_ops tables point at them directly; `ctx` is accepted and ignored.
*/
/* Host monotonic clock in nanoseconds. */
uint64_t reims_vgpu_shim_mono_ns(void *ctx);
/*
* Guest-physical byte access. Both use RAM-only transaction attrs, so a GPA
* that resolves to a device is rejected rather than performed — a guest page
* entry pointing at one of our own BARs must not re-enter device MMIO from
* inside a Rust call. Return 0 on success (including an empty request), -1 on
* a failed transaction.
*/
int reims_vgpu_shim_read_gpa(void *ctx, uint64_t gpa, uint8_t *buf, size_t len);
int reims_vgpu_shim_write_gpa(void *ctx, uint64_t gpa, const uint8_t *buf,
size_t len);
/* 1 = guest RAM, 0 = not (MMIO / ROM / unmapped). Mapper page-entry accept. */
int reims_vgpu_shim_is_ram_gpa(void *ctx, uint64_t gpa);
/*
* Where guest RAM lives in this process, as stable (gpa_base, host_va, len)
* spans. See the ReimsVgpuHostOps.guest_ram_regions comment in
* reims_vgpu_qemu_abi.h for the contract; this is the one implementation of it
* and both shims point their table entry straight at it.
*
* Bus-independent by construction: it reads the system address space and
* nothing from the device. Writing it once is not a line-count argument — the
* two shims run on different hosts, so a second copy is a divergence that shows
* up on exactly the pathway nobody is booting.
*/
int reims_vgpu_shim_guest_ram_regions(void *ctx, ReimsVgpuGuestRamRegion *out,
size_t max);
/*
* Guest kernel VA -> host buffer, for MappingInternal / page-table walks.
*
* MUST run on a vCPU thread with current_cpu set (typically the iosfc
* producer MMIO path). Never falls back to first_cpu: from the drain BH
* that would do_run_on_cpu while the vCPU may be blocked in MMIO waiting
* for the Rust DEVICES mutex — classic AB-BA hang (UI "not responding").
* Returns 0 on success, -2 with no current vCPU, -1 on a failed read.
*/
int reims_vgpu_shim_read_kva(void *ctx, uint64_t kva, uint8_t *buf, size_t len);
/*
* May a present naming `mapping_id` paint the host console right now?
*
* The verdict comes from Rust whole; this only forwards it, and answers false
* for a device that has no handle or cannot answer. Do NOT rebuild it from
* `reims_vgpu_shim_console_feed`'s kind and mapping id — that reconstruction is
* what the two shims had drifted on, x86 gating and arm64 painting every
* present it was handed.
*/
bool reims_vgpu_shim_scanout_may_paint(uint64_t rust_handle, uint32_t mapping_id);
/*
* Who owns the host console right now: a `REIMS_VGPU_CONSOLE_FEED_*`. The
* `out_*` are filled only for _EARLY, and are left untouched otherwise.
*
* A device that has no handle, or whose call does not return OK, is reported as
* _FIRMWARE. That is the answer, not a fallback: the pre-boundary firmware
* console is what owns the screen until Rust says otherwise, so failing closed
* is the only reading that cannot paint product pixels over it. The arm64 shim
* used to conflate "the call failed" with "not _EARLY" and fall through to its
* post-boundary re-push, which is the shim inventing a policy for "no answer" —
* `device_console_feed`'s own doc names that as the thing being removed.
*/
uint32_t reims_vgpu_shim_console_feed(uint64_t rust_handle, uint32_t *out_mid,
uint32_t *out_w, uint32_t *out_h,
uint32_t *out_gen);
/*
* Host-owned-window input: replay a neutral Rust input action through the
* QEMU input subsystem. Input routes to the guest's active handlers
* (usb-kbd / usb-tablet) independent of any display, so these work with
* -display none. All business logic (platform key -> evdev, scroll delta ->
* wheel notches, coordinate origin) lives in Rust; the shim only translates
* the neutral wire form into the QEMU input ABI, which owns the QEMU-side
* keycode and button enums. A NULL console drops the event.
*/
/* `evdev` is a Linux evdev code; QEMU drops codes it cannot map to a qcode,
* so no shim-side keycode table is needed. */
void reims_vgpu_shim_input_key(QemuConsole *con, uint32_t evdev, bool down);
/* Absolute pointer (usb-tablet): scales window pixels into the abs range. */
void reims_vgpu_shim_input_pointer_move(QemuConsole *con, uint32_t x,
uint32_t y, uint32_t w, uint32_t h);
/* `code` is a REIMS_VGPU_BUTTON_*; an unrecognised one drops the event. */
void reims_vgpu_shim_input_button(QemuConsole *con, uint32_t code, bool down);
#endif /* REIMS_VGPU_SHIM_H */
+36
View File
@@ -226,3 +226,39 @@ apple_gfx_iosfc_unmap_memory(void *a, void *b, void *c, void *d, void *e, void *
apple_gfx_iosfc_unmap_memory_region(void* mem, void *region) "unmapping @ %p from memory region %p"
apple_gfx_iosfc_raise_irq(uint32_t vector) "vector=0x%x"
# reims-vgpu-mmio.c — thin QEMU shim → host/reims-vgpu staticlib
reims_vgpu_mmio_realize(uint64_t handle, const char *backend) "handle=0x%"PRIx64" backend=%s"
reims_vgpu_mmio_gfx_read(uint64_t offset, uint64_t val) "offset=0x%"PRIx64" val=0x%"PRIx64
reims_vgpu_mmio_gfx_write(uint64_t offset, uint64_t val) "offset=0x%"PRIx64" val=0x%"PRIx64
reims_vgpu_mmio_iosfc_read(uint64_t offset, uint64_t val) "offset=0x%"PRIx64" val=0x%"PRIx64
reims_vgpu_mmio_iosfc_write(uint64_t offset, uint64_t val) "offset=0x%"PRIx64" val=0x%"PRIx64
reims_vgpu_mmio_irq_gfx(void) "pulse gfx IRQ"
reims_vgpu_mmio_irq_iosfc(void) "pulse iosfc IRQ"
reims_vgpu_mmio_scanout(uint64_t mapping_id, uint64_t width, uint64_t height) "mapping=%"PRIu64" %"PRIu64"x%"PRIu64
reims_vgpu_mmio_mode_change(uint64_t width, uint64_t height) "mode=%"PRIu64"x%"PRIu64
reims_vgpu_mmio_cursor(uint64_t x, uint64_t y, uint64_t show) "x=%"PRIu64" y=%"PRIu64" show=%"PRIu64
# reims-vgpu-pci.c — thin PCI shim (x86 Tahoe) → same staticlib
reims_vgpu_pci_realize(uint64_t handle, const char *backend) "handle=0x%"PRIx64" backend=%s"
reims_vgpu_pci_gfx_read(uint64_t offset, uint64_t val) "offset=0x%"PRIx64" val=0x%"PRIx64
reims_vgpu_pci_gfx_write(uint64_t offset, uint64_t val) "offset=0x%"PRIx64" val=0x%"PRIx64
reims_vgpu_pci_irq_gfx(void) "msi vector 0"
reims_vgpu_pci_scanout(uint64_t mapping_id, uint64_t width, uint64_t height) "mapping=%"PRIu64" %"PRIu64"x%"PRIu64
reims_vgpu_pci_mode_change(uint64_t width, uint64_t height) "mode=%"PRIu64"x%"PRIu64
# Sampled-texture resolve failure for a draw bind: reason is ReimsVgpuResourceResolveReason
# (0=none/post-resolve sample fail); fmt/w/h are 0 when resolve itself fails.
# Extra type-2 fields when sampled convert fails after geometry resolve (fmt may be 0).
# Main-loop stall instrumentation: begin/end pairs around every point where the
# device blocks the drain (or a vCPU MMIO doorbell) on in-flight backend work.
# A wedged boot's trace TAIL names the stall site: a *_begin with no matching
# *_end is the loop the device is stuck in; worker begin/end durations expose a
# slow backend job (e.g. a Vulkan-rail shader translate) directly.
# Temporary content-vs-publish oracle (scanout gap map G1/G4). reason: 1=0x3b/0x28
# boundary sample, 2=type-11 0x73 LOAD writeback with partial scissor. outside_clobber
# counts strided samples outside the job scissor union where guest-pre != job rgba
# (full-FB store would destroy those pixels). outside_seed_drift: pre != seed outside
# (another writer landed between seed and complete). unique_blocks: 32x32 mean diversity
# on boundary samples (width/height omitted — use t11_register / scanout_frame).
# Probe-only — remove after the isolation boot.
+5
View File
@@ -57,6 +57,7 @@ struct ARMGICv2mState {
uint32_t base_spi;
uint32_t num_spi;
uint32_t macos_compat;
};
static void gicv2m_set_irq(void *opaque, int irq)
@@ -81,6 +82,9 @@ static uint64_t gicv2m_read(void *opaque, hwaddr offset,
case V2M_MSI_TYPER:
val = (s->base_spi + 32) << 16;
val |= s->num_spi;
if (s->macos_compat) {
val |= BIT(31);
}
return val;
case V2M_MSI_IIDR:
/* We don't have any valid implementor so we leave that field as zero
@@ -173,6 +177,7 @@ static void gicv2m_init(Object *obj)
static const Property gicv2m_properties[] = {
DEFINE_PROP_UINT32("base-spi", ARMGICv2mState, base_spi, 0),
DEFINE_PROP_UINT32("num-spi", ARMGICv2mState, num_spi, 64),
DEFINE_PROP_UINT32("macos-compat", ARMGICv2mState, macos_compat, 0),
};
static void gicv2m_class_init(ObjectClass *klass, const void *data)
+1
View File
@@ -31,4 +31,5 @@ config VMAPPLE
select VMAPPLE_BDIF
select VMAPPLE_CFG
select MAC_PVG_MMIO
select REIMS_VGPU
select VMAPPLE_VIRTIO_BLK
+2 -1
View File
@@ -253,7 +253,7 @@ static bool cmd_iv(AESState *s)
static void dump_data(const char *desc, const void *p, size_t len)
{
static const size_t MAX_LEN = 0x1000;
#define MAX_LEN 0x1000
char hex[MAX_LEN * 2 + 1] = "";
if (len > MAX_LEN) {
@@ -262,6 +262,7 @@ static void dump_data(const char *desc, const void *p, size_t len)
qemu_hexdump_to_buffer(hex, sizeof(hex), p, len);
trace_aes_dump_data(desc, hex);
#undef MAX_LEN
}
static bool cmd_data(AESState *s)
+85 -2
View File
@@ -32,6 +32,7 @@
#include "hw/core/sysbus.h"
#include "hw/usb/usb.h"
#include "hw/arm/boot.h"
#include "hw/arm/machines-qom.h"
#include "hw/char/pl011.h"
#include "hw/intc/arm_gic.h"
#include "hw/intc/arm_gicv3_common.h"
@@ -68,6 +69,7 @@ struct VMAppleMachineState {
MemoryRegion fw_mr;
MemoryRegion ecam_alias;
uint64_t uuid;
char *gfx_device;
};
#define TYPE_VMAPPLE_MACHINE MACHINE_TYPE_NAME("vmapple")
@@ -82,6 +84,7 @@ enum {
VMAPPLE_MEM,
VMAPPLE_GIC_DIST,
VMAPPLE_GIC_REDIST,
VMAPPLE_GICV2M,
VMAPPLE_UART,
VMAPPLE_RTC,
VMAPPLE_PCIE,
@@ -103,6 +106,7 @@ static const MemMapEntry memmap[] = {
[VMAPPLE_GIC_DIST] = { 0x10000000, 0x00010000 },
[VMAPPLE_GIC_REDIST] = { 0x10010000, 0x00400000 },
[VMAPPLE_GICV2M] = { 0x1FFF0000, 0x00010000 },
[VMAPPLE_UART] = { 0x20010000, 0x00010000 },
[VMAPPLE_RTC] = { 0x20050000, 0x00001000 },
@@ -128,6 +132,7 @@ static const int irqmap[] = {
[VMAPPLE_APV_GFX] = 0x11,
[VMAPPLE_AES_1] = 0x12,
[VMAPPLE_PCIE] = 0x20,
[VMAPPLE_GICV2M] = 0x80
};
#define GPEX_NUM_IRQS 16
@@ -207,9 +212,18 @@ static void create_gfx(VMAppleMachineState *vms, MemoryRegion *mem)
{
int irq_gfx = vms->irqmap[VMAPPLE_APV_GFX];
int irq_iosfc = vms->irqmap[VMAPPLE_APV_IOSFC];
DeviceState *gfx_dev;
SysBusDevice *gfx;
gfx = SYS_BUS_DEVICE(qdev_new("apple-gfx-mmio"));
/*
* The platform's fixed REIMS_VGPU_GFX/REIMS_VGPU_IOSFC slots are backed by either
* apple-gfx-mmio (ParavirtualizedGraphics.framework host side, reference)
* or reims-vgpu-mmio (product: thin C → crates/reims-vgpu Rust staticlib).
* Sysbus layout: mmio 0/irq 0 = gfx window, mmio 1/irq 1 = IOSurface mapper.
*/
gfx_dev = qdev_new(vms->gfx_device);
gfx_dev->id = g_strdup("reims-vgpu-gfx");
gfx = SYS_BUS_DEVICE(gfx_dev);
sysbus_mmio_map(gfx, 0, vms->memmap[VMAPPLE_APV_GFX].base);
sysbus_mmio_map(gfx, 1, vms->memmap[VMAPPLE_APV_IOSFC].base);
sysbus_connect_irq(gfx, 0, qdev_get_gpio_in(vms->gic, irq_gfx));
@@ -285,6 +299,27 @@ static void create_gic(VMAppleMachineState *vms, MemoryRegion *mem)
}
}
#define NUM_GICV2M_SPIS 128
static void create_gicv2m(VMAppleMachineState *vms)
{
int i;
int irq = vms->irqmap[VMAPPLE_GICV2M];
DeviceState *dev;
dev = qdev_new("arm-gicv2m");
qdev_prop_set_uint32(dev, "base-spi", irq);
qdev_prop_set_uint32(dev, "num-spi", NUM_GICV2M_SPIS);
qdev_prop_set_uint32(dev, "macos-compat", 1);
sysbus_realize_and_unref(SYS_BUS_DEVICE(dev), &error_fatal);
sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, vms->memmap[VMAPPLE_GICV2M].base);
for (i = 0; i < NUM_GICV2M_SPIS; i++) {
sysbus_connect_irq(SYS_BUS_DEVICE(dev), i,
qdev_get_gpio_in(vms->gic, irq + i));
}
}
static void create_uart(const VMAppleMachineState *vms, int uart,
MemoryRegion *mem, Chardev *chr)
{
@@ -495,6 +530,7 @@ static void mach_vmapple_init(MachineState *machine)
machine->ram);
create_gic(vms, sysmem);
create_gicv2m(vms);
create_bdif(vms, sysmem);
create_pvpanic(vms, sysmem);
create_aes(vms, sysmem);
@@ -561,6 +597,14 @@ static const CPUArchIdList *vmapple_possible_cpu_arch_ids(MachineState *ms)
return ms->possible_cpus;
}
static bool vmapple_get_vgic_bases(const MachineState *ms,
uint64_t *dist_base, uint64_t *redist_base)
{
*dist_base = memmap[VMAPPLE_GIC_DIST].base;
*redist_base = memmap[VMAPPLE_GIC_REDIST].base;
return true;
}
static GlobalProperty vmapple_compat_defaults[] = {
{ TYPE_VIRTIO_PCI, "disable-legacy", "on" },
/*
@@ -585,6 +629,7 @@ static void vmapple_machine_class_init(ObjectClass *oc, const void *data)
mc->cpu_index_to_instance_props = vmapple_cpu_index_to_props;
mc->default_cpu_type = ARM_CPU_TYPE_NAME("host");
mc->get_default_cpu_node_id = vmapple_get_default_cpu_node_id;
mc->get_vgic_bases = vmapple_get_vgic_bases;
mc->default_ram_id = "mach-vmapple.ram";
mc->desc = "Apple aarch64 Virtual Machine";
@@ -592,15 +637,52 @@ static void vmapple_machine_class_init(ObjectClass *oc, const void *data)
G_N_ELEMENTS(vmapple_compat_defaults));
}
static char *vmapple_get_gfx_device(Object *obj, Error **errp)
{
VMAppleMachineState *vms = VMAPPLE_MACHINE(obj);
return g_strdup(vms->gfx_device);
}
static void vmapple_set_gfx_device(Object *obj, const char *value,
Error **errp)
{
VMAppleMachineState *vms = VMAPPLE_MACHINE(obj);
if (strcmp(value, "apple-gfx-mmio") != 0 &&
strcmp(value, "reims-vgpu-mmio") != 0) {
error_setg(errp,
"invalid gfx-device '%s' (valid: apple-gfx-mmio, reims-vgpu-mmio)",
value);
return;
}
g_free(vms->gfx_device);
vms->gfx_device = g_strdup(value);
}
static void vmapple_instance_init(Object *obj)
{
VMAppleMachineState *vms = VMAPPLE_MACHINE(obj);
vms->irqmap = irqmap;
vms->gfx_device = g_strdup("apple-gfx-mmio");
object_property_add_uint64_ptr(obj, "uuid", &vms->uuid,
OBJ_PROP_FLAG_READWRITE);
object_property_set_description(obj, "uuid", "Machine UUID (SDOM)");
object_property_add_str(obj, "gfx-device", vmapple_get_gfx_device,
vmapple_set_gfx_device);
object_property_set_description(obj, "gfx-device",
"Paravirt GPU device backing the Reims VGPU "
"slots (apple-gfx-mmio | reims-vgpu-mmio)");
}
static void vmapple_instance_finalize(Object *obj)
{
VMAppleMachineState *vms = VMAPPLE_MACHINE(obj);
g_free(vms->gfx_device);
}
static const TypeInfo vmapple_machine_info = {
@@ -609,6 +691,8 @@ static const TypeInfo vmapple_machine_info = {
.instance_size = sizeof(VMAppleMachineState),
.class_init = vmapple_machine_class_init,
.instance_init = vmapple_instance_init,
.instance_finalize = vmapple_instance_finalize,
.interfaces = aarch64_machine_interfaces
};
static void machvmapple_machine_init(void)
@@ -616,4 +700,3 @@ static void machvmapple_machine_init(void)
type_register_static(&vmapple_machine_info);
}
type_init(machvmapple_machine_init);
+8
View File
@@ -281,6 +281,14 @@ struct MachineClass {
int (*get_physical_address_range)(MachineState *machine,
int default_ipa_size, int max_ipa_size);
bool (*get_kernel_irqchip_default) (const MachineState *machine);
/*
* Guest physical addresses of the GICv3 distributor and (first)
* redistributor region, for accelerators (HVF) that must place an
* in-kernel vGIC before any vCPU exists. Returns false when the
* board has no GICv3.
*/
bool (*get_vgic_bases) (const MachineState *machine,
uint64_t *dist_base, uint64_t *redist_base);
BlockInterfaceType block_default_type;
int units_per_default_bus;
+3
View File
@@ -385,3 +385,6 @@ option('rust', type: 'feature', value: 'disabled',
description: 'Rust support')
option('strict_rust_lints', type: 'boolean', value: false,
description: 'Enable stricter set of Rust warnings')
option('reims_vgpu_backend', type : 'combo', choices : ['env', 'metal', 'vulkan'], value: 'env',
description: 'host GPU backend linked into the reims-vgpu staticlib')
+280 -10
View File
@@ -1353,9 +1353,26 @@ hv_return_t hvf_arch_vm_create(MachineState *ms, uint32_t pa_range)
* This must be done prior to the creation of any vCPU
* but past hv_vm_create()
*/
hv_gic_config_t cfg = hv_gic_config_create();
hv_gic_config_set_distributor_base(cfg, 0x08000000);
hv_gic_config_set_redistributor_base(cfg, 0x080A0000);
MachineClass *mc = MACHINE_GET_CLASS(ms);
/*
* Fallback matches hw/arm/virt.c's base_memmap; boards whose
* GICv3 lives elsewhere must implement get_vgic_bases or the
* in-kernel vGIC is placed at GPAs the guest never accesses.
*/
uint64_t dist_base = 0x08000000;
uint64_t redist_base = 0x080A0000;
hv_gic_config_t cfg;
if (mc->get_vgic_bases &&
!mc->get_vgic_bases(ms, &dist_base, &redist_base)) {
error_report("HVF: machine has no GICv3 for the platform vGIC");
ret = HV_UNSUPPORTED;
goto cleanup;
}
cfg = hv_gic_config_create();
hv_gic_config_set_distributor_base(cfg, dist_base);
hv_gic_config_set_redistributor_base(cfg, redist_base);
ret = hv_gic_create(cfg);
if (ret != HV_SUCCESS) {
error_report("error creating platform VGIC");
@@ -1437,8 +1454,16 @@ int hvf_arch_init_vcpu(CPUState *cpu)
continue;
}
if (ri) {
assert(!(ri->type & ARM_CP_NO_RAW));
/*
* Skip NO_RAW registers instead of asserting on them. Some ID registers
* (e.g. ID_AA64ISAR0_EL1) became ARM_CP_NO_RAW in system emulation
* because a field is computed at read time via a readfn (RNDR depends on
* SCR_EL3.TRNDR under FEAT_RNG_TRAP). Such regs have no raw backing store
* to sync with HVF, so they must not be added to the cpreg sync list.
* Without this, hvf_arch_init_vcpu() aborts on macOS hosts and no
* aarch64 HVF guest (incl. vmapple) can start.
*/
if (ri && !(ri->type & ARM_CP_NO_RAW)) {
arm_cpu->cpreg_indexes[sregs_cnt++] = kvm_id;
}
}
@@ -2326,6 +2351,238 @@ static void hvf_sync_vtimer(CPUState *cpu)
}
}
/*
* Emulate a load/store that took a data abort with ISV=0, i.e. with no
* instruction syndrome: the CPU only describes single general-purpose
* loads/stores in the ISS, so LDP/STP and SIMD&FP accesses to MMIO arrive
* undecoded. macOS 13+ guest kernels perform such accesses against device
* memory during early boot (the macOS 12 kernel does not), so vmapple needs
* this to run newer guests.
*
* Decodes the faulting instruction from guest memory and performs the access
* at the already-translated fault IPA. Covers exactly the A64 classes that
* report ISV=0 and can plausibly target MMIO:
* - load/store pair, GPR and SIMD&FP (LDP/STP/LDNP/STNP/LDPSW), all
* indexing modes
* - load/store single SIMD&FP register (LDR/STR/LDUR/STUR B/H/S/D/Q),
* immediate/register-offset/pre/post-index forms
* Anything else (exclusives, atomics, SP-based writeback, ...) returns false
* so the caller can fail loudly with full context.
*
* On success the emulated instruction is complete: registers and PC are
* updated in env (state was pulled via cpu_synchronize_state, so the handler
* tail's flush_cpu_state pushes everything back to HVF).
*/
static bool hvf_emulate_isv0_mmio(CPUState *cpu, hwaddr ipa, uint32_t *insn_out)
{
CPUARMState *env = cpu_env(cpu);
AddressSpace *as = cpu_get_address_space(cpu, ARMASIdx_NS);
uint32_t insn = 0;
cpu_synchronize_state(cpu);
if (cpu_memory_rw_debug(cpu, env->pc, &insn, sizeof(insn), false)) {
return false;
}
*insn_out = insn;
if ((insn & 0x38000000) == 0x28000000) {
/* Load/store pair (incl. no-allocate): C4.1.66 op0=x101. */
uint32_t opc = extract32(insn, 30, 2);
bool is_vector = extract32(insn, 26, 1);
uint32_t mode = extract32(insn, 23, 2); /* 0=STNP/LDNP 1=post 2=offset 3=pre */
bool is_load = extract32(insn, 22, 1);
int64_t imm7 = sextract32(insn, 15, 7);
uint32_t rt2 = extract32(insn, 10, 5);
uint32_t rn = extract32(insn, 5, 5);
uint32_t rt = extract32(insn, 0, 5);
bool wback = (mode == 1) || (mode == 3);
bool sext = false;
int esize;
if (is_vector) {
if (opc == 3) {
return false; /* unallocated */
}
esize = 4 << opc; /* S/D/Q */
} else if (opc == 0) {
esize = 4;
} else if (opc == 1 && is_load) {
esize = 4;
sext = true; /* LDPSW */
} else if (opc == 2) {
esize = 8;
} else {
return false; /* unallocated / STGP */
}
if (wback && rn == 31) {
return false; /* SP-based MMIO writeback: refuse */
}
for (int i = 0; i < 2; i++) {
uint32_t reg = i ? rt2 : rt;
hwaddr addr = ipa + (hwaddr)i * esize;
uint8_t buf[16] = { 0 };
if (is_load) {
address_space_read(as, addr, MEMTXATTRS_UNSPECIFIED, buf, esize);
if (is_vector) {
env->vfp.zregs[reg].d[0] = ldq_le_p(buf);
env->vfp.zregs[reg].d[1] = esize == 16 ? ldq_le_p(buf + 8) : 0;
} else if (reg != 31) {
uint64_t v = esize == 4 ? ldl_le_p(buf) : ldq_le_p(buf);
env->xregs[reg] = sext ? sextract64(v, 0, 32) : v;
}
} else {
if (is_vector) {
stq_le_p(buf, env->vfp.zregs[reg].d[0]);
if (esize == 16) {
stq_le_p(buf + 8, env->vfp.zregs[reg].d[1]);
}
} else if (reg != 31) {
if (esize == 4) {
stl_le_p(buf, (uint32_t)env->xregs[reg]);
} else {
stq_le_p(buf, env->xregs[reg]);
}
}
address_space_write(as, addr, MEMTXATTRS_UNSPECIFIED, buf, esize);
}
}
if (wback) {
env->xregs[rn] += imm7 * esize;
}
env->pc += 4;
return true;
}
if (extract32(insn, 24, 6) == 0x38) {
/*
* Load/store single GPR, imm9/register-offset forms: bits[29:24]=
* 111000. The pre/post-indexed (writeback) forms report ISV=0
* because the syndrome cannot describe the base update — macOS 13+
* uses e.g. "str w9, [x8, #128]!" on MMIO.
*/
uint32_t size = extract32(insn, 30, 2);
uint32_t opc = extract32(insn, 22, 2);
uint32_t rn = extract32(insn, 5, 5);
uint32_t rt = extract32(insn, 0, 5);
bool wback = false;
int esize = 1 << size;
uint8_t buf[8] = { 0 };
if (extract32(insn, 21, 1)) {
if (extract32(insn, 10, 2) != 2) {
return false; /* atomics etc., not register-offset */
}
} else {
switch (extract32(insn, 10, 2)) {
case 0: /* LDUR/STUR: no writeback */
case 2: /* LDTR/STTR: treat as plain access */
break;
case 1: /* post-index */
case 3: /* pre-index */
wback = true;
break;
}
}
if (size == 3 && opc == 2) {
return false; /* PRFUM: prefetch never aborts */
}
if (wback && rn == 31) {
return false; /* SP-based MMIO writeback: refuse */
}
if (opc == 0) { /* store */
if (rt != 31) {
stq_le_p(buf, env->xregs[rt]);
}
address_space_write(as, ipa, MEMTXATTRS_UNSPECIFIED, buf, esize);
} else { /* load: 01 zext, 10 sext→X, 11 sext→W */
uint64_t v;
address_space_read(as, ipa, MEMTXATTRS_UNSPECIFIED, buf, esize);
v = ldq_le_p(buf) & MAKE_64BIT_MASK(0, esize * 8);
if (opc == 2) {
v = sextract64(v, 0, esize * 8);
} else if (opc == 3) {
v = (uint32_t)sextract64(v, 0, esize * 8);
}
if (rt != 31) {
env->xregs[rt] = v;
}
}
if (wback) {
env->xregs[rn] += sextract32(insn, 12, 9);
}
env->pc += 4;
return true;
}
if (extract32(insn, 24, 6) == 0x3d || extract32(insn, 24, 6) == 0x3c) {
/* Load/store single SIMD&FP register: bits[29:24]=1111 0V. */
uint32_t size = extract32(insn, 30, 2);
uint32_t opc = extract32(insn, 22, 2);
bool unsigned_imm = extract32(insn, 24, 2) == 1;
bool is_load = opc & 1;
uint32_t rn = extract32(insn, 5, 5);
uint32_t rt = extract32(insn, 0, 5);
uint32_t scale = size;
bool wback = false;
int esize;
uint8_t buf[16] = { 0 };
if (opc & 2) {
if (size != 0) {
return false; /* only Q extends the size range */
}
scale = 4;
}
esize = 1 << scale;
if (!unsigned_imm) {
if (extract32(insn, 21, 1)) {
if (extract32(insn, 10, 2) != 2) {
return false; /* not a register-offset form */
}
} else {
switch (extract32(insn, 10, 2)) {
case 0: /* LDUR/STUR: no writeback */
break;
case 1: /* post-index */
case 3: /* pre-index */
wback = true;
break;
default:
return false;
}
}
}
if (wback && rn == 31) {
return false; /* SP-based MMIO writeback: refuse */
}
if (is_load) {
address_space_read(as, ipa, MEMTXATTRS_UNSPECIFIED, buf, esize);
env->vfp.zregs[rt].d[0] = ldq_le_p(buf);
env->vfp.zregs[rt].d[1] = esize == 16 ? ldq_le_p(buf + 8) : 0;
} else {
stq_le_p(buf, env->vfp.zregs[rt].d[0]);
if (esize == 16) {
stq_le_p(buf + 8, env->vfp.zregs[rt].d[1]);
}
address_space_write(as, ipa, MEMTXATTRS_UNSPECIFIED, buf, esize);
}
if (wback) {
env->xregs[rn] += sextract32(insn, 12, 9);
}
env->pc += 4;
return true;
}
return false;
}
static int hvf_handle_exception(CPUState *cpu, hv_vcpu_exit_exception_t *excp)
{
CPUARMState *env = cpu_env(cpu);
@@ -2432,11 +2689,24 @@ static int hvf_handle_exception(CPUState *cpu, hv_vcpu_exit_exception_t *excp)
*/
assert(!s1ptw);
/*
* TODO: ISV will be 0 for SIMD or SVE accesses.
* Inject the exception into the guest.
*/
assert(isv);
if (!isv) {
/*
* No instruction syndrome (LDP/STP, SIMD&FP, ...): decode and
* emulate the faulting instruction. macOS 13+ guests do such
* accesses against MMIO in early boot.
*/
uint32_t insn = 0;
if (!hvf_emulate_isv0_mmio(cpu, ipa, &insn)) {
error_report("hvf: unhandled ISV=0 data abort: pc=0x%" PRIx64
" insn=0x%08x va=0x%llx ipa=0x%llx wnr=%d",
env->pc, insn, excp->virtual_address,
excp->physical_address, iswrite);
abort();
}
/* Emulation advanced env->pc itself; flushed at handler tail. */
break;
}
/*
* Emulate MMIO.