Batch native I/O submissions and dispatch completions from the owning AioContext using a ring event and userspace polling. Fall back to the existing IOCP waiter when IORING is unavailable or disabled.
Rebased onto intel-vm-suspend after #8 (maintainer): the bounce cache
keeps #8's size, #8's zero-copy scatter/gather stays on the IOCP path
only (its completions need the IOCP waiter, which IORING mode does not
run), and util/aio-win32.c gains aio_poll_disabled(), which the IORING
submit reads and which only aio-posix.c defined.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Mirror eligible software virtio-blk queue routes under a transport mutex. Preserve masked notifications in the MSI-X PBA across route changes, device stop, and VM state save. Retain software notifiers for config changes and delivery fallback.
Queue IDs reach 65535, so the doorbell offset of a queue above 8191,
(qid << 3) plus the CQ's 4, overflows a uint16_t and registers the
ioeventfd at the wrong address; hold it in a uint32_t. A guest that sends
Doorbell Buffer Config again re-initialised the notifiers of queues that
already had them; skip queues whose ioeventfd is enabled.
Taken from "whpx: accelerate MMIO ioeventfd writes with doorbells" in
reims-go/qemu-reims-vgpu#2, whose WHPX doorbells #8 has since provided.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Windows readlink can use the extended path prefix for the same target. Keep checking that the entry is a symlink and compare the resolved target, including entries built after configure.
Keep the Windows suspend, mapped RAM, and Winsock changes. Use the upstream WHPX timer probe and graphics RAM-device mapping while keeping pool pieces outside migration.
A VM with a vfio-pci device beside reims-graphics-pci ended as the guest's
graphics driver started: "vfio_container_dma_map(..., 0xcc0000000, 0x1000000,
...) = -14 (Bad address)", then "vfio: DMA mapping failed, unable to
continue" (steelbrain/reims-vgpu#213, a Linux host with an RX 6700 XT and a
USB controller passed through). 0xcc0000000 is the guest's Shared pool's
first piece, a 16 MiB block of the GPU's memory that the library has QEMU map
into the guest. The host's mapping of that memory is a dma-buf's, which the
IOMMU refused to map. vfio's listener maps every RAM section for the passed-
through device's DMA, and at run time a refused map is a hardware error for
plain RAM and a warning, once, for a RAM device (hw/vfio/listener.c).
Each pool piece is now a RAM device (memory_region_init_ram_device_ptr), with
no property or option. In this QEMU a RAM device is otherwise RAM: KVM's and
WHPX's slot maps, HVF's, TCG's softmmu and a device's DMA
(memory_access_is_direct, which reads memory_region_is_ram alone) take it as
before. What changes besides vfio: vhost-vdpa skips it, a guest memory dump
leaves it out, and `info mtree` names it ramd. The guest's RAM and BAR 2, the
device's region, stay plain RAM: vfio maps them as before.
(cherry picked from commit 325206b3c747feaa6675fcc9562680c21bf8cfe9)
The test runs the script in each case's own build directory, so a relative
SCRIPT, as meson test never gives it but a run from the source tree does,
named no file there and every case failed.
Configuring QEMU on a Windows host without Developer Mode or an
administrator's rights stopped at symlink-install-tree.py: os.symlink fails
there with WinError 1314, a required privilege not held, and the script
raised on every error but EEXIST, after a line asking for Developer Mode.
qemu-bundle only serves a run from the build tree; `ninja install`, which
installs from the build, never reads it.
Where os.symlink is refused, for any error but EEXIST, the script now copies
the entry instead: a file with its metadata, a directory whole. An entry
built after the configure step (the executables, built firmware, generated
files) does not exist yet and is left out, which only a run from the build
tree misses; one line says how many entries were copied and left out.
tests/symlink-install-tree runs the script over a fake MESONINTROSPECT's
install list in a scratch build directory: with os.symlink refused under
three errnos, the bundle holds copies of the file and the directory, leaves
out the entry not built yet, and configures again over its copies; and
where the host makes links, it makes them, as before, and keeps them on a
second run. meson test runs it in the suite scripts.
The device gave QEMU's input layer the window's pixel, at most size - 1,
and QEMU scales [0, size] over the tablet's range, so the last pixel never
reached the tablet's maximum, and no position put a macOS guest's cursor in
a display's last column or row. Measured with capture off on macOS 26
guests: the last column of a display 2016 pixels across went as 0x7fee and
put an x86-64 26.7.2 guest's cursor at 2014.92, and the last row of 1260 as
0x7fe4, at 1258.94, over KWin's Wayland and SDL's X11 (potluck jobs
m3-max-84927, m3-max-85009); on a Windows host at 1439.45 of 1440 and
809.47 of 810 (m3-max-85087); and an arm64 guest's at 1007.43 of 1008
points across, at 2x (m3-max-84982).
The last pixel of each axis now goes as size, the tablet's maximum
(reims_pointer_axis, hw/display/reims-pointer.h), on every display: at
the maximum the cursor was at 2015.98 and 1259.98, and at 1007.98 on arm64
(m3-max-84928, m3-max-84980, m3-max-84983). A display of the guest's placed beside it does not take the
maximum, as the guest scales the tablet over the display its cursor is on:
with display 1 right of display 0, the maximum on display 0 left the cursor
at 2015.98 of display 0 (m3-max-84980).
tablet-right-edge-head, which gave the maximum to the x of one display, as
an opt-in property, goes with its page in docs/system/devices; reims-ctl
never set it. tests/unit/test-reims-pointer.c checks the values QEMU's
scaling then gives.
dock-pressure moved a second USB mouse, usb-mouse with motion-only=on
(relative Y, no buttons), down 18 counts 32 times, 80 ms apart, once the
window's pointer reached a display's bottom row, for macOS to show a Dock
hidden there. Measured with capture off, without the property and then
with it, on macOS 26 guests:
- An x86-64 26.7.2 guest's tablet alone shows its hidden Dock at the
bottom, right and left edges, over KWin's Wayland and SDL's X11 on Linux
and on a Windows host (potluck jobs m3-max-84927, m3-max-85009,
m3-max-85087). With the property the Dock showed the same; the pulses
moved the cursor from 1258.94 to 1259.98 of 1260 (m3-max-84928), the last
row, which the next commit gives the tablet itself.
- An arm64 guest under TCG shows its hidden Dock at the right and left, and
not at the bottom: not with the tablet at the bottom row (629.45 of 630
points) nor at the tablet's maximum (629.98; m3-max-84982), and not after
the pulses either, which took the cursor to 629.98 (m3-max-84983).
The pulses showed no Dock the tablet did not, so they go with the second
mouse, and reims-ctl's command stays as it is: hw/input/hid.c's and
hw/usb/dev-hid.c's motion-only mode and its case in
tests/qtest/usb-hcd-xhci-test.c, the device's timer with its reset and
finalize, and reims_pointer_bottom with its unit test.
Replace environment switches with explicit opt-in device properties, share pointer arithmetic with unit tests and cancel pressure timers at reset. An xHCI regression reads actual USB reports: ordinary mice retain buttons, motion-only mice deliver relative Y without buttons beside a tablet.
Validated before the host reboot: full x86 QEMU build, two pointer unit tests, 16 existing xHCI cases, the new report regression and PCI syntax checking with warnings denied. AI-assisted downstream contribution; no DCO certification is asserted.
usb-kbd converts guest keyboard events through linux -> qnum -> hid_usage_keys[].
The legacy hid_usage_keys[] slots did not match QEMU's keycodemapdb QNUM values
for KEY_F13..KEY_F24:
- F13..F15 (qnum 0x5d..0x5f) mapped to F17..F19 (0x6c..0x6e)
- F20 (qnum 0x5a) mapped to F14 (0x69)
- F16..F19, F21..F24 (qnum 0x55, 0x83, 0xf7, 0x84, 0x74, 0xf9, 0x6d, 0x6f) mapped to 0x00 and were silently dropped
None of these 12 QNUM indices collide with any other entry in
input-keymap-linux-to-qnum.c.inc. Update hid_usage_keys[] so F13-F24
round-trip losslessly to USB HID usages 0x68-0x73 (needed for macOS
modifier-key remapping carriers F20/F21/F22/F24 and extended F-keys).
QEMU's memory array has only the devices RAM fills, as DIMMs: on current
machines one, so a macOS guest's System Information lists a single slot,
where the Mac it presents may have four SO-DIMM slots.
slots= makes the array that many devices, those past the ones RAM fills
empty (size 0, type and speed unknown, only their locators named), and
type 16's Number of Memory Devices counts them all; form_factor= sets every
device's Form Factor (9, DIMM, by default). Without them the tables are as
before. bios-tables-test's smbios-memory-slots checks both cases.
The resolution property gave every display the same size: each window's
first size, or each display's mode without a window. A VM of several
displays on screens of different sizes could not open each window at its
screen's size. The property now also takes a comma-separated list of one
size per display, in the displays' order (on QEMU's command line each comma
is written ",,": resolution=2560x1440,,1920x1080): each window opens at its
own, and without a window each display offers its own as its mode, through
the library's headless_modes. Another count of sizes than displays is
refused at realize, saying so. One size is every display's, as before, and
the device then gives the library the config it gave before.
QEMU wrote 0x06, multi-bit ECC, as the memory array's Memory Error
Correction on every machine, and OpenCore copies it into an x86-64 macOS
guest's SMBIOS, so System Information shows the memory as "ECC: Enabled" on
an iMac20,1, whose RAM has none. The new error_correction option sets the
field, 1 to 7 as SMBIOS numbers them (3 is none); without it the field
stays 6.
bios-tables-test: smbios-error-correction reads type 16's field without the
option (6) and with error_correction=3 (3). Red before this commit
(m3-max-80517): QEMU refused -smbios type=16 ("Don't know how to build
fields for SMBIOS type 16").
With kernel-irqchip=off the guest's xAPIC is QEMU's, and its TPR is
mirrored in the vCPU's CR8. whpx_set_registers set vcpu->tpr, the TPR CR8
is taken to hold, from the APIC at every level, but wrote CR8 only above
WHPX_LEVEL_FAST_RUNTIME_STATE, the level an emulated instruction's
registers go back at. So a TPR the instruction changed (a read-modify-write
of the xAPIC's TPR at 0xfee00080, or an x2APIC WRMSR) matched vcpu->tpr
without reaching CR8: whpx_vcpu_pre_run saw nothing to write, and at the
next exit whpx_vcpu_post_run put CR8's old TPR back into the APIC, undoing
the guest's write. vcpu->tpr now changes only where CR8 is written, so
pre_run writes the new TPR to CR8.
Measured on an i7-8700B under Windows 11's WHPX with a guest of our own
that ORs 0x50 into the TPR and reads it back: kernel-irqchip=off read 0x00
in 3 of 3 runs, kernel-irqchip=on 0x50 in 3 of 3 (QEMU a86885f8, the same
lines as 21e66365; potluck job m3-max-80368).
1e223049 stops the VM through blk_error_action() where a flash write finds
the host disk full, and the stop records the error in the drive's I/O
status, which asserts that the status is enabled: QEMU aborted instead of
pausing (qtest pflash-cfi01/enospc-pauses, potluck job m3-max-80263). A
writable flash drive now enables it at realize, as IDE and virtio-blk do,
so the VM pauses and query-block answers the drive's io-status nospace,
which reims-ctl reads to name the file whose disk is full.
pflash_cfi01, the firmware's flash (an x86-64 guest's OVMF variables),
wrote each program and erase to its drive and, where the write failed,
logged "Could not update PFLASH" and went on: its memory kept the new bytes,
so the guest read them, but the file never got them, and the change was
gone at the VM's next start. On a full host disk that is any variable the
firmware or the guest's boot loader writes. The disks' devices pause the
VM instead, under -drive's default werror=enospc.
Now a write whose drive's error action is stop marks its bytes to write
again, and pauses the VM with io-error as the disks' devices do; as the VM
resumes, the flash writes them again from its memory, and pauses again
where that fails too. The drive's action is -drive's (if=pflash takes no
werror, so ENOSPC stops), and a drive's other errors still only log the
line, as before.
What the guest sees: on a full host disk the VM pauses at the flash write,
and after space is freed and the VM resumes, the variable is in the file.
The qtest pflash-cfi01-test: enospc-pauses (red before this: the VM ran on
and the file kept 0xff), and eio-runs, which held before and still holds.
A VM whose disk is on QEMU's nvme device went on running when the host's
disk filled: the device completed the failed write to the guest with Write
Fault, which macOS's file system takes as a failed disk. AHCI and
virtio-blk pause the VM instead, under -drive's default werror=enospc, and
QEMU runs the writes again once the VM resumes, so the guest never sees
them fail and carries on once space is freed.
nvme and nvme-ns forced report/report on their drive, having no rerror and
werror properties (a zeroed BlockConf reads as report), and no completion
path asked the drive's error action. Now both devices take the properties,
AUTO by default as virtio-blk's are, so a -drive's werror and rerror apply;
a failed Read, Write, Write Zeroes, Flush or Dataset Management on an I/O
queue of a namespace that is not zoned follows the drive's action. Under
stop the command is held on its SQ with no completion, QEMU pauses the VM
with io-error and query-block gives the drive's io-status (nospace), and
the VM's resume runs the command again from its fetched copy. Under ignore
it completes as done, and under report with its error, as before, now with
QMP's BLOCK_IO_ERROR as the other devices send it. Other commands (Copy,
Compare, Verify, zone commands, admin commands) and cancels keep reporting.
A reset while the VM is paused drops the held commands with the queues,
and a migration with one held is refused, where it would have asserted.
What the guest sees: on a full host disk the VM pauses with no I/O error,
and after space is freed and the VM resumes, the write completes. An I/O
error other than ENOSPC still reaches the guest as before.
The qtests: enospc-pauses (red before this: the write completed with
status 0x280 and the VM ran on), enospc-reset, and eio-reports, which held
before and still holds.
At QEMU's quit, vm_shutdown stops the VM, and the device's VM state handler
tears it down: the library's release of its last device lets go of the GPU
device before the process exits. A VM that was not running at the quit hears
no such stop: one paused (by QMP's stop, or by a full disk), one never started
past -S, or one paused by a shutdown whose action pauses (-no-shutdown). Its
device stayed to the exit, the library's quiesce at the end of QEMU's cleanup
answered that it still held a GPU device, and QEMU ended with _exit.
The cleanup notifier now first tears down each device no teardown ran for
(its VM state handler still set), BAR 2 out of the guest's address space
first, as at a stop. The release then lets go of the GPU device, the quiesce
answers true, and QEMU ends with exit(), running its exit handlers. Only a
device a display's read kept (the GPU stopped answering) still ends QEMU with
_exit.
What changes for the host: QEMU quits such a VM by exit() instead of _exit;
the guest sees nothing, as it no longer runs.
With REIMS_VGPU_WINDOW=0, or another display of QEMU's, the device passed
the library no window config, and the resolution property went nowhere:
every display offered the guest 1920x1080 whatever the VM's setting. The
library's config now carries a headless mode (headless_mode_width and
_height, read only where window is NULL), and the device gives it the
resolution there, so a VM started headless gets the mode its settings
name, at 60 Hz.
reims-vgpu's reset now waits, before it returns, until the GPU work the
guest committed before it has completed and run its completed handlers, at
most 30 s, so none of it writes the guest's memory after the reset. A STATUS
write of 0 runs that reset on the vCPU, which calls the library with no BQL.
The settle waits for nothing of QEMU's: the completed handlers' raise is
the irqfd's write, msi_lock, which waits for nothing else, or a bottom
half. So the register accesses still need no BQL, and the comment above
them says what a STATUS write of 0 waits for.
A dsound playback voice placed its write position 60 ms past DirectSound's
write cursor and kept that reserve for the stream's life. An x86-64 macOS
guest's posts come down to their least margin past the write cursor once a
turn of their 41.67 ms grid, so most of the reserve was latency: a period's
first frame waited 107 ms at the median to play (p99 129) where the guest's
players are told 2 ms. And the host's device plays to its own clock: one
that runs fast eats the reserve until the audio runs out before the write
cursor, a gap of silence each time (forced 227 ppm fast, one every 260 s;
at 100 ppm about one every 10 minutes); one that runs slow grows the fill
and the latency.
Now the voice trims the rate its guest's audio is resampled to. In 2 s
buckets of its reads with audio flowing it takes the margin's least. The
level is the least of the last five buckets, and the drift the slope of the
buckets' least margins, with what the trim itself played out added back, by
least squares over the last 30 once 15 are in. The voice plays at its rate
less the drift and 1 Hz more for each millisecond the level stands past the
15 ms it keeps, within 1000 ppm (44 Hz at 44.1 kHz, 1.7 cents of pitch). A
gap keeps 10 ms more, up to 45, and starts the buckets again; the drift
stays. A stream still starts 60 ms past the write cursor, which its first
posts need whatever their phase on the grid, and trims from there. The
trace event dsound_trim records each bucket.
The rate moves through the mixing engine's resampler: st_rate_set_out_mhz()
sets a rate converter's output rate with its interpolation going on from
where it stands, and audio_pcm_hw_trim_out() sets it for a voice's soft
voices. A converter once trimmed interpolates from then on, even where its
rates come out equal: going back to copying would drop the frame the
interpolation holds. DirectSound's own frequency was tried first and
clicked: on a Windows 11 host each IDirectSoundBuffer_SetFrequency, of any
size, moved the audio by 4 to 19 us some 35 ms later, 10.8 clicks a minute
at rest.
What the guest hears on a Windows host: its sound about 35 ms sooner at the
median, and no gap from the device's drift, at a pitch within 1.7 cents of
its own. Other hosts: nothing changes, since no other backend trims.
Measured on our Windows 11 test host (UHD 630): a 26.7.2 x86-64
guest played a two-tone sine, captured by WASAPI loopback, 200 s at rest,
200 s busy, then 840 s with a scratch hook (never landed) setting the
buffer's DirectSound frequency 10 Hz (227 ppm) fast at the stream's start.
Base da50fbf9 with the hook (m3-max-78857) against this with it
(m3-max-79145):
- clicks a minute at rest 0 and 0, busy 0.93 and 0, in the drift phase
0.58 and 0;
- a period's first frame's wait from 60 s in, median / p99: at rest
106.7 / 129.3 ms and 71.7 / 96.4, busy 104.6 / 127.3 and 72.7 / 97.0;
- gaps in 834 s at +227 ppm: 3 (260 s apart) and 0, the margin's least
11.8 ms, the drift taken as 10.2 Hz.
test-dsound-ring holds the trim's arithmetic: on the functions without the
trim its five trim tests fail. test-audio-rate holds the resampler: the
output stays on the input's curve while the rate moves, at 48 to 44.1 kHz
and at equal rates, where a converter that went back to copying stepped by
a whole frame (0.14 of the amplitude).
Convert file-win32 and win32-aio from legacy BlockAIOCB + BH completion
callbacks to native coroutine block driver hooks (.bdrv_co_preadv,
.bdrv_co_pwritev, and .bdrv_co_flush_to_disk), matching file-posix and
linux-aio:
- Stack-allocate Win32AioCoReq across qemu_coroutine_yield() and wake
waiting coroutines directly via aio_co_schedule() from the IOCP
waiter thread, returning synchronously without yielding or scheduling
a BH whenever FILE_SKIP_COMPLETION_PORT_ON_SUCCESS completes inline.
- Add a per-QEMUWin32AIOState mutex-protected 3-bucket page-aligned
bounce-buffer slab pool (64 KiB x16, 256 KiB x8, 1 MiB x8) to
eliminate per-request _aligned_malloc/_aligned_free churn on
multi-iov and unaligned direct I/O writes while safely falling back
to qemu_try_blockalign() for oversized or stricter-alignment requests.
- Convert the thread-pool fallback (paio_co_submit) to
thread_pool_submit_co() for both bdrv_file and bdrv_host_device.
(cherry picked from commit e60f01ecb6)
reims-vgpu's take of PR 22, whole, as benched (planner's verdict 12-02).
reims-ctl runs every Windows disk with aio=threads and cache=writeback,
through the file driver. On that path this PR fixes reads that failed and
came back as zeros with success, a leaked request on a failed flush, and a
truncate that could set the wrong end of file. Both silent-corruption
defects reproduced on the base and are clean here. The coroutine hooks
need this commit's win32-aio.c, so the PR is carried whole. aio=native is
not turned on by this.
A change the PR does not name: buffered files get request alignment 1
where it was the volume's sector size. That is what the POSIX side does
for buffered files. No 4096-byte-sector volume was available to run it on.
Bench on the Windows mini, venue C:, its system disk, a USB NVMe (the
only disk online). qemu-img bench, qcow2 over 4 GiB, -t writeback -i
threads. Seconds a1/a2/b1/b2 (A = the fork before, B = this PR), then
the a and b spreads:
1M seq write QD16 8.13/7.57/7.39/7.43 7.4% 0.5%
1M overwrite 6.05/3.83/5.02/3.24 57.7% 55.0%
1M seq read 7.01/7.10/6.78/6.94 1.2% 2.4%
4K seq write QD16 3.74/3.82/3.79/3.84 2.1% 1.2%
4K seq read QD16 24.23/24.15/23.56/22.75 0.3% 3.5%
4K rand write QD16 1.39/1.51/1.41/1.33 9.2% 5.8%
4K rand read QD16 19.25/19.61/19.45/16.41 1.9% 18.5%
4K rand write QD1 0.57/0.60/0.61/0.71 6.0% 16.9%
4K rand read QD1 4.41/4.24/4.19/3.89 4.1% 7.8%
1M rand write QD16 1.97/1.44/2.38/1.71 36.9% 39.2%
1M rand read QD16 8.35/8.09/7.99/6.76 3.2% 18.2%
4K, a flush per write 9.04/9.39/9.09/7.99 3.9% 13.7%
64K QD16, flush per 16 1.17/1.18/1.32/1.02 1.5% 29.6%
No row is slower beyond 3% and beyond both spreads. qemu-img check and
compare: every arm identical to a1. A byte-range lock held by another
process: the base reads zeros with success ("Pattern verification failed
at offset 0"); this PR answers "Input/output error". 400 truncates under
writes: the base lost the tail (offset 66060288); this PR is clean at
464 MiB.
Fix multiple correctness, concurrency, and performance bugs in QEMU's Windows
raw file and native IOCP AIO backends that prevented iothread + aio=native
and cache=none (FILE_FLAG_NO_BUFFERING) from working reliably on Windows
WHPX hosts:
1. Wire .bdrv_detach_aio_context and .bdrv_attach_aio_context on bdrv_file
(previously only registered on bdrv_host_device), fixing the immediate I/O
stall when virtio-blk-pci,iothread=io0 moves a file node to an iothread.
2. Replace the racy shared manual-reset OVERLAPPED.hEvent wakeup in
block/win32-aio.c with a dedicated joinable blocking IOCP waiter thread
posting completions back to req_ctx via BH, eliminating lost wakeups and
handling GetQueuedCompletionStatus returning FALSE with non-NULL ov
(failed I/O and async ERROR_HANDLE_EOF) instead of dropping packets.
3. Fix short-read bounce-buffer data corruption in win32-aio.c (copy only
actually transferred bytes before zero-padding the tail) and error-path
aio_context_unref / bounce-buffer leaks.
4. Enable FILE_SKIP_COMPLETION_PORT_ON_SUCCESS | FILE_SKIP_SET_EVENT_ON_HANDLE
via SetFileCompletionNotificationModes (consistent across reopen) so
synchronous completions bypass IOCP and waiter-thread wakeup hops.
5. Fix FILE_FLAG_NO_BUFFERING (cache=none) alignment and error handling in
block/file-win32.c: probe logical/physical sector and buffer alignment on
open/reopen (FileStorageInfo / FileAlignmentInfo, falling back to
IOCTL_STORAGE_QUERY_PROPERTY and NtQueryVolumeInformationFile
FileFsSizeInformation), bounce-buffer unaligned direct I/O in both native
and thread-pool paths, stop turning ReadFile failures into silent zero
reads, fix FlushFileBuffers failure cleanup leak, and switch
raw_co_truncate to SetFileInformationByHandle(FileEndOfFileInfo).
(cherry picked from commit edfe3ebd86)
The comment on reims_graphics_kvm_pool_host_memory (5d0e52bd) counted a
kernel older than KVM_CAP_ARM_CACHEABLE_PFNMAP_SUPPORTED among the hosts that
answer none. Linux 6.18's headers define the capability (243), and the
device's realize refuses a Linux host below 7.2 (458f4b7b) before it asks, so
no host the device runs on is such a kernel: the clause is dropped, and the
comment says the floor's kernels all know the capability.
The comment at the check's call in the realize is wrapped at 80 columns.
Nothing the device does changes.
The warning that nested virtualization could not be turned on (73977854)
was one line of 122 columns, indented as though inside a block it is not
in, and the guest-error log of an MMIO write the fast path dispatched
(0c429b2a) ran to 87. Both are wrapped, and the warning's block indented as
its if.
The warning now reads "WHPX: Failed to enable nested virtualization,
hr=...: going on without it"; nothing else changes.
qemu_coroutine_new's and qemu_coroutine_self's checks of the fiber they make
(6059c36f) wrote their failure with fprintf, where QEMU's code reports
through error_report, which gives the line QEMU's prefix and timestamp and
sends it to the monitor where one is current; one line was also past 80
columns. The comment on CreateFiberEx now says what the call does and why.
Nothing changes but the failure's line: "CreateFiberEx of a 1048576-byte
stack, 65536 bytes committed, failed: error N", or "ConvertThreadToFiber
failed: error N", before the abort as before.
The probe of whether Hyper-V refuses the TSC deadline timer's register runs
on a partition of its own (81437f75), which got a processor count of one and
the local APIC's emulation and nothing else of the guest's partition: Hyper-V
gave it its default processor features, not the feature banks the guest's
partition was set to, so it could answer for another processor than the
guest's.
The probe's partition now takes what whpx_accel_init gave the guest's: the
processor feature banks where the host is not legacy Windows, and nested
virtualization where the local APIC is Hyper-V's and the banks offer it.
Where a step of the probe fails, QEMU now warns, naming the step and its
HRESULT, where it went on silently; the guest is offered the timer then, as
before. The comment says why the probe has a partition of its own.
What hosts see: the refusal line, and the guest's TSC deadline timer, follow
the guest's own processor; a probe that fails is named in QEMU's log.
whpx-mmio.h's decoder (whpx_decode_mov_store32), effective address
(whpx_mov_store32_ea) and address check (whpx_mmio_write32_address_valid)
are built only into whpx-all.c, which only a Windows host builds, so nothing
held them on the hosts our checks run on. A wrong answer there writes a
guest's store to another register or with another value, or moves RIP past
the wrong number of bytes, with no emulator to catch it.
tests/unit/test-whpx-mmio.c holds them on any host:
- the stores the fast path takes, MOV r/m32, r32 and MOV r/m32, imm32 with
and without REX.R, REX.X and REX.B, through a base, a SIB with and without
an index, RIP and a SIB's disp32 alone, with each field the decoder gives;
- what it leaves to the emulator: REX.W, register destinations, C7 /1, other
opcodes, every legacy prefix, bytes short of the instruction, more than 16
bytes and an exit length other than the decoded one;
- the effective address, the displacement sign-extended, RIP-relative from
the next instruction;
- the address check, which takes only the exit's guest virtual address,
4-aligned and at the guest physical address's place in its page.
What a Windows host runs does not change.
Linux's KVM on arm64 takes a cacheable VM_PFNMAP mapping as a memory slot
only where the CPU has stage-2 forced write-back and CACHE_DIC, and the VM
says so as KVM_CAP_ARM_CACHEABLE_PFNMAP_SUPPORTED. Every host mapping of a
Honeykrisp allocation is VM_PFNMAP, so on an M1 Pro under Fedora Asahi Remix
45 the reims-graphics device's first Shared pool piece failed
KVM_SET_USER_MEMORY_REGION2 with EINVAL, and QEMU exited
(steelbrain/reims-vgpu#174).
The device now sets the library's pool_host_memory where it runs under KVM on
an arm64 host and the VM does not answer the capability, which a kernel older
than it does not either: the pool's blocks are then memfds of the library's
that the GPU imports, which KVM maps as guest memory, cached, as it maps the
guest's RAM. The check is in reims-graphics-pci-kvm.c, which only targets
with KVM link, with its stub beside the others; it asks the VM through
kvm_vm_ioctl, since kvm_vm_check_extension is declared for per-target builds
alone.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 0d6ff26282)
On Windows, the default Winsock FD_SETSIZE is 64. In util/main-loop.c,
os_host_main_loop_wait() populated fixed stack-allocated fd_set buffers
with FD_SET(), silently dropping any sockets past the first 64 entries in
gpollfds. Under libslirp user NAT, background guest traffic (for example
macOS Tahoe right after boot) routinely exceeds 64 active sockets, causing
newly created UDP/ICMP sockets to starve until older UDP flows expire.
Introduce a Win64-safe dynamically allocated QemuWin32FdSet helper
(include/qemu/win32-fdset.h) with compile-time fd_set ABI layout
assertions and deduplication, allocate read/write/exception sets for
gpollfds->len in util/main-loop.c, and add a Windows-only unit test
(tests/unit/test-win32-fdset.c) covering empty/duplicate handling and
63/64/65/128/1024 simultaneously ready Winsock sockets.
Convert file-win32 and win32-aio from legacy BlockAIOCB + BH completion
callbacks to native coroutine block driver hooks (.bdrv_co_preadv,
.bdrv_co_pwritev, and .bdrv_co_flush_to_disk), matching file-posix and
linux-aio:
- Stack-allocate Win32AioCoReq across qemu_coroutine_yield() and wake
waiting coroutines directly via aio_co_schedule() from the IOCP
waiter thread, returning synchronously without yielding or scheduling
a BH whenever FILE_SKIP_COMPLETION_PORT_ON_SUCCESS completes inline.
- Add a per-QEMUWin32AIOState mutex-protected 3-bucket page-aligned
bounce-buffer slab pool (64 KiB x16, 256 KiB x8, 1 MiB x8) to
eliminate per-request _aligned_malloc/_aligned_free churn on
multi-iov and unaligned direct I/O writes while safely falling back
to qemu_try_blockalign() for oversized or stricter-alignment requests.
- Convert the thread-pool fallback (paio_co_submit) to
thread_pool_submit_co() for both bdrv_file and bdrv_host_device.
Fix multiple correctness, concurrency, and performance bugs in QEMU's Windows
raw file and native IOCP AIO backends that prevented iothread + aio=native
and cache=none (FILE_FLAG_NO_BUFFERING) from working reliably on Windows
WHPX hosts:
1. Wire .bdrv_detach_aio_context and .bdrv_attach_aio_context on bdrv_file
(previously only registered on bdrv_host_device), fixing the immediate I/O
stall when virtio-blk-pci,iothread=io0 moves a file node to an iothread.
2. Replace the racy shared manual-reset OVERLAPPED.hEvent wakeup in
block/win32-aio.c with a dedicated joinable blocking IOCP waiter thread
posting completions back to req_ctx via BH, eliminating lost wakeups and
handling GetQueuedCompletionStatus returning FALSE with non-NULL ov
(failed I/O and async ERROR_HANDLE_EOF) instead of dropping packets.
3. Fix short-read bounce-buffer data corruption in win32-aio.c (copy only
actually transferred bytes before zero-padding the tail) and error-path
aio_context_unref / bounce-buffer leaks.
4. Enable FILE_SKIP_COMPLETION_PORT_ON_SUCCESS | FILE_SKIP_SET_EVENT_ON_HANDLE
via SetFileCompletionNotificationModes (consistent across reopen) so
synchronous completions bypass IOCP and waiter-thread wakeup hops.
5. Fix FILE_FLAG_NO_BUFFERING (cache=none) alignment and error handling in
block/file-win32.c: probe logical/physical sector and buffer alignment on
open/reopen (FileStorageInfo / FileAlignmentInfo, falling back to
IOCTL_STORAGE_QUERY_PROPERTY and NtQueryVolumeInformationFile
FileFsSizeInformation), bounce-buffer unaligned direct I/O in both native
and thread-pool paths, stop turning ReadFile failures into silent zero
reads, fix FlushFileBuffers failure cleanup leak, and switch
raw_co_truncate to SetFileInformationByHandle(FileEndOfFileInfo).
- Keep normal and zero page offsets in ascending order in
multifd_send_zero_page_detect() instead of swapping from the tail,
so contiguous guest RAM runs are not fragmented into out-of-order 4 KiB
writes.
- On Win32, coalesce a contiguous multifd packet's non-zero pages to
64 KiB NTFS sparse compression-unit boundaries within the packet's
exclusive [pkt_min, pkt_max) range without changing the mapped-ram
file format or file_bmap.
- Enable the existing direct-io migration parameter on Win32 via
CreateFileW(..., FILE_FLAG_NO_BUFFERING) for mapped-ram secondary
multifd channels.
CreateFiber(1 MiB, ...) commits the full 1 MiB stack upfront per coroutine, which can exhaust Windows commit charge during burst disk I/O + GPU workloads and return NULL (later crashing inside SwitchToFiber(NULL)). Use CreateFiberEx(64 KiB, stack_size, 0, ...), reuse existing fibers via IsThreadAFiber(), and abort with GetLastError() on NULL.
Some Windows 11 hosts report NestedVirtSupport via WHvGetCapability yet fail WHvSetPartitionProperty(WHvPartitionPropertyCodeNestedVirtualization) with hr=0x80370302 (WHV_E_UNKNOWN_PROPERTY). Log a warning and clear Bank1.NestedVirtSupport instead of aborting VM startup so kernel-irqchip=on remains usable.
Fixes two crashes on Windows 10 22H2 (Build 19045) WHPX hosts:
1. whpx_tsc_deadline_refused() previously created and deleted vCPU 0 on the real partition, causing whpx_init_vcpu() to fail with E_INVALIDARG (0x80070057) when recreating vCPU 0. Probe on a throwaway partition instead.
2. Guard whp_dispatch.WHvResetPartition before calling it in whpx_set_registers(), as this function pointer is NULL on Windows 10.
vmapple turns x-ascending-capabilities on for virtio-net-pci (4a39ef8d)
and virtio-sound-pci (5c42f3fc), since macOS 27's virtio PCI transport
revisits PCI_CFG and NOTIFY forever on a list whose links go down in
address: without it a macOS 27 guest never starts the device. Only an
arm64 macOS 27 boot that listens for sound saw the sound half.
tests/qtest/virtio-pci-caps-test.c reads each device's capability list
from PCI config space under qtest on a PC machine, with the property on
and off, and holds that with it on the list links the same capabilities
at the same offsets, in address order. With virtio-sound-pci's
reordering taken out of its realize, /virtio-pci-caps/sound/ascending
fails. vmapple's own setting of the property is not held.
dsoundaudio.c builds only on Windows, so nothing held the arithmetic
0c0ac356 and 4d205af8 gave its playback voice: the reserve past
DirectSound's write cursor (60 ms of whole frames, as far as the play
cursor at most), the cursors rounded to whole frames, and the bytes left
to play once the play cursor has moved. A change to any of them would
bring the clicks back on a Windows host unseen.
The three move unchanged into static inline functions of
audio/dsound-ring.h, a header of their own that includes nothing of
Windows, with the reserve's comment and DSOUND_RESERVE_US; dsoundaudio.c
calls them where it computed them, with the same operands. What a Windows
host plays does not change.
tests/unit/test-dsound-ring.c holds each on any host: the reserve at 44100
and 48000 Hz and against a short buffer, the cursors' rounding and the
write cursor's wrap, and the bytes left after a move, a move past them all
and a stall of three quarters of a turn. With the reserve at half the
buffer, as before 4d205af8, or the cursors unrounded, as before 0c0ac356,
it fails.
Linux's KVM on arm64 takes a cacheable VM_PFNMAP mapping as a memory slot
only where the CPU has stage-2 forced write-back and CACHE_DIC, and the VM
says so as KVM_CAP_ARM_CACHEABLE_PFNMAP_SUPPORTED. Every host mapping of a
Honeykrisp allocation is VM_PFNMAP, so on an M1 Pro under Fedora Asahi Remix
45 the reims-graphics device's first Shared pool piece failed
KVM_SET_USER_MEMORY_REGION2 with EINVAL, and QEMU exited
(steelbrain/reims-vgpu#174).
The device now sets the library's pool_host_memory where it runs under KVM on
an arm64 host and the VM does not answer the capability, which a kernel older
than it does not either: the pool's blocks are then memfds of the library's
that the GPU imports, which KVM maps as guest memory, cached, as it maps the
guest's RAM. The check is in reims-graphics-pci-kvm.c, which only targets
with KVM link, with its stub beside the others; it asks the VM through
kvm_vm_ioctl, since kvm_vm_check_extension is declared for per-target builds
alone.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The library writes its counts line only at a device reset and at the
exit, so a log read while the guest runs, as reims-ctl's report zips it,
has none. A set of the device's new x-write-counts property to true calls
rvg_write_counts, which writes them on stderr, QEMU's log, before QMP
answers.
The device now needs Linux 7.2 or later on a Linux host: its realize fails
below it, naming the running release and "Linux 7.2 or later". Before 7.2 a
udmabuf over large pages is malformed (an entry per base page naming a large
folio's head page and an offset past the page), and amdgpu's import binds the
wrong pages (reims-vgpu issue 185); 7.2 builds the table from the pages
themselves (upstream 5bf888673e0d).
The floor takes the place of the below-7.2 form: ram_block_add advises every
block MADV_HUGEPAGE again, the device maps its region and pool pieces with no
advice of its own, and the backend collapses preallocated shared RAM with no
4 KiB line. qemu_guest_ram_huge_pages and qemu_linux_release_at_least become
qemu_linux_release_meets_floor, the floor's one check, whose test holds its
table: 7.1 refused, 7.2 passes, a release that does not parse refused.
What hosts see: below 7.2 the device's realize fails, where 51382c20 and
1a35b9fb kept guest RAM and the device's library RAM on 4 KiB pages; on 7.2
and later nothing changes.
51382c20 and 1a35b9fb kept a shared file's guest RAM, and the reims-graphics
device's region and pool pieces, off transparent huge pages on every Linux
host, for the udmabuf scatterlists of Linux 6.11 to 7.1 (reims-vgpu issue
185). Linux 7.2 builds a udmabuf's scatterlist from its pages themselves
(upstream 5bf888673e0d), so there the pages can be huge again.
One fact decides it, read once: qemu_guest_ram_huge_pages(), whether the
running kernel's release (uname) is 7.2 or later by its leading
"MAJOR.MINOR" (qemu_linux_release_at_least; a release that does not parse
counts as older). tests/unit/test-cutils.c holds its table.
What users see:
- Linux 7.2 and later: as before the revert, QEMU advises guest RAM and the
device's library RAM MADV_HUGEPAGE, and collapses a preallocated shared
backend's RAM into huge pages once its prealloc has run, 53e76630's
host_memory_backend_collapse restored as it was, with its line saying how
much of the RAM is on huge pages.
- below 7.2: guest RAM and the device's library RAM are advised
MADV_NOHUGEPAGE and not collapsed, so they stay on 4 KiB pages at every
shmem_enabled, and the backend logs one line saying so, naming the
kernel's release and "before 7.2".
The device maps the library's memory into the guest as RAM from a pointer:
the region (BAR 2) and each piece of the Shared pool. ram_block_add advises
such a block MADV_HUGEPAGE, which takes back the library's MADV_NOHUGEPAGE on
those mappings; they are shared mappings of the library's memfds, which it
hands GPUs as udmabuf dma-bufs, and Linux 6.11 to 7.1 build a udmabuf's
scatterlist for a large folio's pages with entries that amdgpu's import binds
to the wrong pages (reims-vgpu issue 185; 51382c20 keeps guest RAM off huge
pages for the same reason). With shmem_enabled at advise, the region of a
macOS 26.7.2 guest on a Radeon 780M held 70 MiB of 2 MiB folios after its
boot (VmFlags hg, ShmemPmdMapped 71680 kB).
Advise each such block MADV_NOHUGEPAGE as the device makes it, before the
guest can touch it: reims_graphics_library_ram.
ram_block_add advised every RAM block MADV_HUGEPAGE. For a shared file of
base pages, memory-backend-memfd's shmem among it, that let the kernel back
guest RAM with 2 MiB folios at shmem_enabled advise (and always or
within_size without the advice), and the guest's pages reach host GPUs as
udmabuf dma-bufs of that memfd.
Linux 6.11 to 7.1 build a udmabuf's scatterlist with sg_set_folio(), an
entry per 4 KiB page that names its folio's head page and the page's offset
in the folio, up to 2 MiB less a page (upstream 0c8b91ef5100; fixed in 7.2
by 5bf888673e0d). An importer that walks the mapped table by DMA page counts
such an entry as offset plus length, so amdgpu's dma-buf import
(drm_prime_sg_to_dma_addr_array, under dma-direct, as an AMD integrated GPU
runs by default) binds the buffer's pages to the wrong host pages: other
guest pages, and past the folio's end for pages in its upper half. A user's
macOS guest on a Radeon 890M with Linux 6.18.59 had its kernel memory
overwritten 80 to 154 s into each of five boots with guest RAM on huge
pages (reims-vgpu issue 185).
Advise such a block MADV_NOHUGEPAGE in place of MADV_HUGEPAGE, before any
prealloc touches the file, on every Linux host: no fault through the RAM's
mapping and no khugepaged pass over it then makes a large folio of it. RAM
of other kinds (anonymous, private, hugetlbfs) keeps the huge page advice.
This reverts commit 53e766304f on every host:
QEMU no longer collapses a backend's RAM into huge pages once its prealloc
has run, and no longer logs the line that said how much of it the collapse
put on them.
With the collapse, a user's x86-64 macOS 26.7.2 guest on the reims-graphics
device panicked 80 to 154 s into each of 5 boots, its kernel's memory
overwritten (reims-vgpu issue 185; a Radeon 890M on RADV, Mesa 26.1.8,
Linux 6.18.59). The reporter's bisect put it on this commit: the device with
the collapse panicked; the prealloc with the collapse skipped ran clean for
20 minutes; the collapse with plain VGA in place of the device ran clean.
The collapse had been measured with one boot to the desktop, which a fault
minutes into use does not show.
Guest RAM is preallocated as before. A fault backs a shared file's RAM, a
memfd's shmem among it, with a huge page only where the host's
/sys/kernel/mm/transparent_hugepage/shmem_enabled gives one: advise with
QEMU's MADV_HUGEPAGE, always or within_size.
On a Radeon 890M host (RADV, Mesa 26.1.8, Linux 6.18.59), a macOS 26.7.2
guest on reims-graphics-pci over collapsed RAM panicked 80 to 154 s into
every boot, its kernel's memory overwritten: pmap's pv lists, an rw lock,
a ledger, IOKit matching. With the same memfd preallocated and the
collapse skipped, it ran clean for 11 minutes, then 9 more at 8 vCPUs
and 12 GiB, with apps opening throughout. With plain VGA in the device's
place, collapsed RAM ran clean too: the panics need both.
Skip the collapse unless QEMU_HOSTMEM_COLLAPSE=1, until where it goes wrong
(the import of udmabufs over large shmem folios, or KVM's 2 MiB maps beside
it) is found. reims-vgpu#185 has the bisect.
A playback voice placed its write position half its buffer past
DirectSound's write cursor: 92.88 ms at the default 185.76 ms buffer. That
covered an x86-64 macOS guest's posts, spread over 43 to 53 ms about their
pace on its 41.67 ms grid, plus the audio timer's wait for them, up to a
30 ms gap between its runs, plus DirectSound's 10 ms cursor steps. Each
period then waited 134 ms at the median from its write to its play.
With virtio-snd's TX handler running the backend as each period comes, the
timer's wait is gone, and the reserve covers the guest's spread and the
cursor's step: 60 ms. On a Windows host (2026-11-24, the guest at rest and
busy, 200 s each) the smallest reserve a gap-free run needed at its worst
start phase was 51.3 ms at rest and 56.5 ms busy; at 56 ms the median wait
from a period's write to its play was 97.3 ms at rest and 101.3 ms busy.
The buffer stays 185.76 ms, room for the reserve and the periods past it.
A guest's playback reached the host's device only at the audio timer's
next run, every 10 ms on the main loop, so each period waited for it: on a
Windows host, 5.5 ms at the median and 13 ms at most at rest, with the
timer's runs up to 30 ms apart with the guest busy. A backend that keeps a
reserve ahead of the device, as dsound does, had to cover that wait on top
of the guest's own jitter.
Now virtio-snd's TX handler runs the backend's voices after it queues the
guest's messages, through audio_be_kick: a mixing-engine backend runs
audio_run there, as its timer does, and the timer keeps its period. On the
Windows host the wait from a post to its write fell to 1.0 ms at the median
and 3.6 ms at most, with the guest busy.
A playback voice wrote wherever its write position had fallen, and took
the free space up to the play cursor. DirectSound has already mixed the
bytes from the play cursor to the write cursor. Audio written there was
never heard, and the buffer's audio from one turn earlier played in its
place: a click.
A guest that sends its audio in periods hit this every few seconds. On a
Windows host, an x86-64 macOS guest sends 85.33 ms periods. They arrive
83.3 ms apart, or 125 ms apart about once in 21. Within 20 s the posts
drift by 42 ms at rest and 54 ms with the guest busy, and the audio timer's
runs come up to 30 ms apart. That left the buffer with under ~31 ms of audio
ahead of the play cursor often enough to make 111 clicks a minute at rest,
and 172 busy.
Now the voice keeps a reserve past the write cursor. It places the write
position half the buffer past the write cursor, with silence before it,
when the voice starts and again whenever the audio written runs out before
the write cursor. It counts its fill from the play cursor's advance, and
never writes over audio not yet played. It clears what the play cursor has
passed, so a gap plays silence and not stale audio. The output buffer's
default doubles to 185.76 ms, so the 92.88 ms reserve covers the 54 ms
drift and a 30 ms late timer run with some margin. A stream's audio now
plays the write cursor's lead plus the reserve after it is written. The
trace events dsound_place_out and dsound_buffer_get_free record the
placements, the gaps and the fill.
QEMU wrote 0x07, "RAM", as every memory device's type, and macOS's About
This Mac shows that word as the memory's kind: "16 GB 2666 MHz RAM", where
a real Mac shows "DDR4". The new memory_type option sets the field, 1 to
255 as SMBIOS numbers them (26 is DDR4); without it the field stays 7.
usb-host resets the host device (libusb_reset_device) whenever it lets go
of it: when the device is removed or its host device closed, when QEMU
exits, and when an open fails. An iPhone given to a macOS guest is left in
a state from which the next guest loses it. macOS asks a new iPhone to
switch its USB mode (vendor request 0xc052), after which it re-enumerates
once; after the reset QEMU made as a VM stopped, the next VM's guest asked
the switch again, and the iPhone left the bus 1 s later and did not come
back until it was plugged in again.
usb-host gains reset-on-close, on by default. Off, QEMU releases the
device's interfaces and gives them back to the host's drivers without
resetting it, so it stays in the configuration and mode the guest left.
Across a guest reboot, where QEMU let go of nothing, a macOS 27.2.1 guest
under KVM found the iPhone in its switched mode, asked no switch, set its
configuration and drove it: usbmuxd took its multiplexor interface and
AppleUSBNCM11 its two network interfaces.
Not for upstream: written with an AI assistant, which QEMU's policy on
AI-generated content (docs/devel/code-provenance.rst) declines.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
macOS 27's virtio PCI transport never starts a device whose capability
list runs from high offsets to low, as QEMU links it (MSI-X at 0x98, then
0x84, 0x70 and on down): 4a39ef8d54 relinked vmapple-virtio-blk-pci's and,
through x-ascending-capabilities, virtio-net-pci's, but not
virtio-sound-pci's. On a macOS 27.2.1 (26B131) guest under KVM, each
virtio-sound-pci device's IOConfigThread spun in AppleVirtIO, reading the
PCI_CFG capability at 0x84 and the notify capability at 0x70 byte by byte
through IOPCIFamily, forever ("triggered fail-safe by spinning for at
least 1000000us at fixed priority"): its transport never registered, its
status stayed 0, and kernel_task took two of four vCPUs. In some boots the
spin stopped the boot before the root disk's driver started.
virtio-sound-pci gains x-ascending-capabilities, which relinks its list
in ascending address order after its realize, keeping each capability's
offset and contents, as virtio-net-pci's does; off by default, and on for
the vmapple machine.
With it, a 27.2.1 guest's two virtio-sound-pci devices (an output stream
alone and an input stream alone, on one pipewire audiodev) reach
DRIVER_OK, Core Audio lists two "Apple Virtual Sound Device"s, the
default output and the default input, and afplay's sound reaches the
host's speakers through PipeWire.
Not for upstream: written with an AI assistant, which QEMU's policy on
AI-generated content (docs/devel/code-provenance.rst) declines.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
At a fault the kernel backs shmem, a memfd's RAM among it, with a transparent
huge page only where /sys/kernel/mm/transparent_hugepage/shmem_enabled lets
it: advise with QEMU's MADV_HUGEPAGE, always or within_size, and then only
where a free 2 MiB page is found. At never, upstream's default and most
distributions', a guest on memory-backend-memfd runs on 4 KiB pages alone, and
KVM maps it 4 KiB at a time.
Once a shared file-backed backend's prealloc has run, and before any device is
realized and can pin guest pages, collapse it with MADV_COLLAPSE (Linux 6.1),
2 MiB at a time. For shmem the kernel takes MADV_COLLAPSE at every
shmem_enabled but deny (shmem_huge_force in shmem_allowable_huge_orders, read
in Linux 6.13 and 7.3), and leaves a range already on a huge page as it is. A
range it cannot collapse stays on its pages, and one line says how much of the
RAM is on huge pages, the time taken and the first failure: EINVAL where the
kernel has no MADV_COLLAPSE or shmem_enabled is deny.
x-avx512-xstate=on lists opmask, ZMM_Hi256 and Hi16_ZMM in CPUID leaf 0xD
while leaf 7's AVX-512 bits stay as the CPU model sets them, so a guest may
turn those components on in XCR0 while its feature bits say no AVX-512. The
accelerator's filter still drops them where the host lacks them. A Zen 4
core runs a thread's code from its decoders, not its op cache, while the
thread's XCR0 leaves these components off; reims-ctl sets the property for
macOS guests whose kexts turn the components on. Off by default.
An exit() that skips QEMU's cleanup (a later device's refused realize, a
failed incoming migration) reached the device's exit handler, which
quiesced reims-vgpu there and let the exit go on where the quiesce answered
true. The library's runtime supports no quiesce inside an exit handler, and
no exit with its device live, and on that path no release let go of the
device. So the handler now runs no quiesce: where the cleanup's quiesce did
not answer true, it runs QEMU's own exit work and ends with
_exit(EXIT_FAILURE) at once. After the cleanup's true answer it does nothing,
as before.
A new trace event, reims_graphics_end, names each end through _exit, the
cleanup's and the exit handler's, with its status.
rvg_quiesce_for_exit now answers whether QEMU may call exit(): false where
the library still holds a GPU device at the exit, quiesced or not, since its
runtime supports exit() with a device live on no driver (on an RTX 3090, 3 of
9 power-offs that exited after a quiesce that stopped everything in time
ended in SIGSEGV inside the NVIDIA driver's exit handler). The device is
held at the exit where its release did not run first: a quit of a stopped VM,
a shutdown action that pauses, a read of a display that kept the device, and
a let-go the library could not finish.
On false the device's cleanup notifier, and its exit handler for an exit()
that skips the cleanup, now run what exit() would run of QEMU's own, then
_exit: the exit notifiers (usb-host's return of host devices to their
drivers, a tap's down script, the pidfile's removal), the restore of the
terminal a stdio chardev took, and the flush of the C library's streams. To
call them, qemu_run_exit_notifiers is no longer static, and char-stdio gives
its term_exit as qemu_chr_stdio_term_exit. The warning on false is gone: the
library warns where a wait outlasted its bound, and the trace event says
what the answer was.
Where the reims-graphics device stays to the exit (a shutdown action that
pauses, a quit of a stopped VM, a display read past its 5 s), the library's
GPU device and the threads of metal2vulkan-rt's runtime under it live on as
exit() runs the driver's exit handlers: on NVIDIA's driver an exit with a
thread inside it can end in SIGSEGV in the driver's handler.
QEMU's exit notifiers cannot stop them in time: they run from an atexit
handler registered at QEMU's start (system/runstate.c, qemu_init_subsystems),
so after the driver's own, registered as it loaded. So qemu_cleanup() gets a
notifier list of its own, run at its end, before exit() runs any handler,
and the device calls rvg_quiesce_for_exit there with a bound of 5 s, the
release's own, with the BQL let go as around the release. On a false answer
a thread may still be in the driver, and QEMU ends with _exit and the
cleanup's status. An exit() that skips the cleanup (a later device's refused
realize, a failed incoming migration) reaches an atexit handler registered
as the device is made, after the driver loaded, which does the same with
EXIT_FAILURE. A trace event, reims_graphics_quiesce, times each call.
The populate maps a whole pool piece into the second-level tables, so
KVM's delete of the piece's slot now zaps all of it. Under the BQL that
delete took 3.0-8.3 ms for a 256 MiB piece (the address space 0 ioctl,
measured on an RX 780M host and an RTX 3090 host), and the removal's BQL
hold went from 0.8-1.4 ms p50 before the populate to 3.9-5.4 ms p50 and
4.5-8.4 ms max: every vCPU exit that needs the BQL waited for it.
kvm_unmap_before_del deletes the piece's slots in each address space on
the library's thread, before the removal is queued, as WHPX already
unmaps a removed piece there (whpx_unmap_before_del). The listener's
removal then finds no slot and deletes nothing, so the BQL hold is the
flat view's render and the listener's bookkeeping. The delete pauses the
populate, so it waits for no KVM_PRE_FAULT_MEMORY call, and holds the
slots lock, which a memory transaction under the BQL takes, only for its
own ioctls. A slot with a dirty log or a guest_memfd is left to the
removal.
Between the delete and the removal a guest access to the piece exits
and QEMU carries it out on the piece's memory; the library removes only
pieces the guest holds no mapping of.
reims-graphics-pci-prefault.c takes its lock with WITH_QEMU_LOCK_GUARD,
which qemu/lockable.h defines. On POSIX hosts qemu/thread.h brings it in
through qemu/thread-posix.h, so the Linux build compiled; on Windows
qemu/thread-win32.h does not, and the CLANG64 build failed with an
undeclared WITH_QEMU_LOCK_GUARD. The device's own file includes the
header itself, and now so does the populate's. The Linux build's
preprocessed source is unchanged (the header is guarded).
A guest's first touch of a 548 MiB pool piece takes 140,288 nested page
faults on WHPX, 1,274-1,312 ms on the Windows mini's UHD 630, where a
WHvAdviseGpaRange populate of the mapped range (WHvAdviseGpaRangeCodePopulate,
for writes) takes 52-56 ms and leaves the first read and write with none
(measured 11-18, Windows 10.0.26300). The populate thread now issues it on
WHPX, as it issues KVM_PRE_FAULT_MEMORY on KVM: one partition call a 2 MiB
slice, which needs no vCPU (whpx_populate, accel/whpx/whpx-common.c).
The partition's maps and unmaps wait for a populate call in flight.
Measured with a 64 MiB map and unmap of another range looped beside a 548
MiB populate, the map waited 55 ms (p50) beside one call for the whole
range, and 1.25 / 1.64 / 3.94 ms (p50 / p90 / max) beside 2 MiB slices,
against 1.60 / 1.76 / 2.25 ms with no populate; in slices the populate took
218 ms. The device's pool maps and unmaps run ahead, outside the BQL
(whpx_map_ahead, whpx_unmap_before_del), so WHPX's populate takes no pause
around a pool transaction: its ops have no kick, and a pause and its resume
then do nothing. WHvAdviseGpaRange is loaded as an optional function; where
the hypervisor lacks it the device warns once and populates nothing.
KVM_PRE_FAULT_MEMORY retries a page with no reload of its vCPU's MMU for as
long as the fault is stale, until a signal (arch/x86/kvm/mmu/mmu.c:
5063-5072, 4817-4843 in Linux 7.3.3), and a fault is stale while the VM's
TDP root is obsolete. Roots go obsolete at a slot's delete where KVM zaps
every slot (KVM_X86_QUIRK_SLOT_ZAP_ALL on, KVM's default, which the device
turns off where KVM has the quirk; mmu.c:7629-7650), at an MMIO generation
wrap after many slot changes (mmu.c:7653-7678), or when nx_huge_pages is
switched (mmu.c:7755-7766). Any of these can come from a slot change that is
no pool add or removal, which does not pause the populate: the call then
spins holding KVM's SRCU, and the slot change waits for it under the BQL
(virt/kvm/kvm_main.c:1651) with nothing to end it.
The populate thread now arms a one-shot CLOCK_MONOTONIC timer for 20 ms
around each call, which signals the thread with SIG_IPI (SIGEV_THREAD_ID)
and so ends the call with its progress (kvm_main.c:4411-4415). The next
call reloads its MMU first, which frees the obsolete root (mmu.c:5114,
arch/x86/kvm/mmu.h:195-198), and goes on. A slice takes 0.3-0.6 ms, so the
timer fires only on a stuck call; three calls in a row cut with nothing done
leave the rest of the piece to the guest's first touch. A pool add or
removal still ends the call in flight itself, by its pause, and never waits
on the timer. The region and totals trace events count the timer's cuts.
KVM's master clock, which a guest's kvmclock reads as stable, needs every
online vCPU of the VM in one TSC generation (arch/x86/kvm/x86.c:1088-1101,
1587-1588 in Linux 7.3.3). The populate's helper is an online vCPU of the
VM whose TSC nothing wrote after its creation. A guest reboot writes TSC 1
on each guest vCPU (target/i386/cpu.c:9486-9496): the first write starts a
new generation, the others join it, and the helper stayed in the old one,
so the master clock went off for the guest's kvmclock until QEMU exits.
Generations also match only at one TSC frequency, which the helper did not
take where the guest's differs from KVM's default.
The helper now takes vCPU 0's TSC frequency when it is made, and writes its
TSC to 0 as the host then and after each put of a guest vCPU's TSC
(kvm_arch_put_registers at KVM_PUT_RESET_STATE or above, through a notifier
list in target/i386/kvm/kvm.c that runs on the vCPU's thread). KVM takes a
host write of 0 as synchronizing (MSR_IA32_TSC, arch/x86/kvm/msrs.c:
1630-1632; x86.c:1314-1319), so the helper joins the generation the last
put left with no change to the guest vCPUs' offsets (x86.c:1351-1361), and
a write to a helper already in it changes nothing (x86.c:1280-1288). The
master clock is recomputed when the vCPU that started the generation, which
KVM's request names (x86.c:1108-1110), next enters the guest, after every
put of the reset and its rejoin. The tsc_rejoin trace event records each
write.
A pool piece's first touch by the guest takes one stage-2 fault a 4 KiB
page: 140,289 of them, about 180-260 ms, for a 548 MiB piece on KVM. Once a
piece is in the guest and its add answered, one thread of the VM's now fills
the second-level tables for it ahead of the guest's touch, lowest address
first, in 2 MiB slices, one call a slice. The add's answer never waits for
it, and a call that fails leaves the rest of its piece to the guest's first
touch, as before. Only pool pieces are populated.
The call is KVM_PRE_FAULT_MEMORY, a vCPU ioctl, on a vCPU of the thread's
own, the helper, which never runs. A guest vCPU cannot take the calls: each
holds its vCPU's mutex, which KVM_RUN holds while the guest runs. A vCPU
picks its TDP root by its role, which takes CPUID's MAXPHYADDR, SMM and
guest mode and nothing else of the vCPU (arch/x86/kvm/mmu/mmu.c:5963-6010
in Linux 7.3.3; SMEP there is the VM's, tdp_has_smep), and a mapping's
memory type takes no vCPU state (arch/x86/kvm/vmx/vmx.c:7791-7805): with
vCPU 0's CPUID, outside SMM and guest mode, the helper fills the tables the
guest's vCPUs use. Its id is one past every APIC id the machine can give,
which the previous commit leaves room for.
A call holds KVM's SRCU throughout (virt/kvm/kvm_main.c:4392-4433), and a
slot change waits for it under the BQL (kvm_swap_active_memslots,
kvm_main.c:1651). A pool add or removal therefore pauses the populate before
its transaction: it signals the thread with SIG_IPI, which ends the call in
flight with its progress (kvm_main.c:4411-4415), waits for the call to end,
and resumes the thread once its slot change is done. A removal stops its
piece between slices and drops what is queued of it.
Targets other than x86-64 KVM, and kernels without KVM_PRE_FAULT_MEMORY,
take no populate.
QEMU sets KVM_CAP_MAX_VCPU_ID to the machine's apic_id_limit
(hw/i386/x86-common.c:107, and target/i386/kvm/kvm.c's vmfd change), one
past the highest APIC id a guest CPU can have, and KVM refuses
KVM_CREATE_VCPU for any id at or past it (arch/x86/kvm/x86.c:9334-9338 in
Linux 7.3.3). reims-graphics-pci's pre-fault helper is a vCPU that never
runs and that the guest is never told of; it takes the id apic_id_limit,
so the cap is one higher.
Nothing the guest sees changes: FW_CFG_MAX_CPUS, the MADT and CPUID are
built from apic_id_limit and QEMU's CPU list (hw/i386/fw_cfg.c:147), which
stay as they were. KVM reads the cap only to refuse ids and to size the
AVIC physical id table (arch/x86/kvm/svm/avic.c:166) and VMX's IPI
virtualisation PID table (arch/x86/kvm/vmx/vmx.c:4856, 4928), each one
entry longer.
reims-graphics-pci gave the library a pool range only on a PC machine,
from the host bridge's pci-hole64-end, and none on aarch64, so an arm64
guest's device had no pool. vmapple places nothing past RAM and its
firmware tells macOS of RAM alone, so the machine now answers the room
from the end of RAM, rounded up to 1 GiB, to the end of the guest's
physical addresses: the CPU's PARange, at most 40 bits, and under KVM at
most KVM's maximum IPA, which the VM gets. It gives the room as read-only
machine properties, x-pool-room-base and x-pool-room-size, which the
device reads where the PC path answers nothing; the device's reservation
then sets no fw_cfg file where there is none.
On the M3 under HVF (40 bits) a 4 GiB guest's room is 0x200000000 up
to 1 TiB. The guest is told of no piece yet: pieces appear at addresses
its firmware never listed, as on x86 before the kext uses them. A PC
machine's pool is unchanged.
vmapple had no get_physical_address_range, so HVF created its VMs at 36
bits of IPA, HVF's default: 64 GiB, of which RAM from 4 GiB takes the
first part. The reims-graphics device's Shared pool needs room past RAM
for as much host memory as the host GPU's heaps hold, which on a Mac with
much memory is more than what 64 GiB leaves.
Ask for 40 bits, or the most the host gives where that is fewer. macOS's
kernel maps physical addresses of up to 40 bits (TCR_EL1.IPS is a
constant 40 bits in xnu's osfmk/arm64/proc_reg.h, read from code), so 40
is all of what the guest reaches. RAM ending past the bits the host gives
fails at once, as virt's does, where the map of RAM failed before.
What the guest sees changes under HVF: on a host whose maximum is 40 bits
or more (the M3 Max's is 40), its ID_AA64MMFR0_EL1.PARange, which HVF
clamps to the VM's IPA size, reads 40 bits in place of 36, and stage 2
covers 1 TiB. Under KVM (KVM's maximum IPA, unchanged) and TCG nothing
changes.
Under KVM and WHPX a guest physical address past the host's physical
address width cannot be mapped: KVM refuses a memory slot that ends past the
host's MAXPHYADDR, and WHPX its map, and QEMU then aborts. The pool's room
ran to three quarters of the guest's physical address space alone, and a
guest may have more bits than its host, with QEMU's warning: reims-ctl's
guests have the CPU model's default 40, and a Coffee Lake host has 39. A
piece placed past the host's width would then end the VM.
The room now also ends at the host's width under KVM and WHPX: CPUID leaf
0x80000008's EAX[7:0], or 36 without that leaf, as QEMU's
host_cpu_phys_bits answers. The device is built once for every target and
only the x86 targets link host_cpu_phys_bits, so it reads CPUID itself, on
hosts with <cpuid.h>. TCG maps nothing in hardware and keeps the guest's
bound. The warning for a room with nothing in it names whose bits bound it.
The library's pool now takes a piece out of the guest before it gives its
block back to its block source, on its pool thread, rather than inside the
source's unmap hook when the source frees the block. The callback's code is
unchanged; its comment named the old thread.
The library now sizes the guest's Shared pool's range from the sum of the
host GPU's memory heaps, every heap, not from the heap of its host-cached
memory type alone: a heap's size is how the driver accounts for memory, not
the most it allocates. The device's code is unchanged; its comments named the
old source.
The pool's pieces were in the order they were added, and an add's overlap
check and a removal's find scanned all of them: 6.1 us of an add and
2.6 us of a removal with 2,000 pieces in (q35 under KVM, paused, on a
Ryzen 7 7840HS: a probe device doing the same lookups, the median of 3
runs' p50 over 50 asks each).
The pieces are now kept sorted by address, and a binary search finds the
first piece at an address or above it. The pieces are disjoint, so only
that piece and the one before it can overlap a new range; a removal's
piece is the one found, if its address matches. Both answer as before. At
N=2,000 the add's lookup takes 0.1 us and the removal's 0.1 us.
ram_block_add kept ram_list.blocks sorted from the largest block to the
smallest by walking it from the head to the first smaller block, linear in
the blocks. With 2,000 16 MiB RAM regions of reims-graphics-pci's pool in,
the walk was most of the 36 us an add spent making its region (q35 under
KVM, paused, on a Ryzen 7 7840HS: a probe device doing the add's calls, the
median of 3 runs' p50 over 50 adds each).
The list's runs of one size are now also kept in an array, largest first,
each with its last block, which ram_block_add and qemu_ram_free update with
the list under the ramlist lock. A binary search finds the run of the new
block's size, or the run before where it would go, and the block goes
after that run's last block, or first where no block is larger: where the
walk put it, after every block of its size or larger. A removal moves its
run's last block back to the one before it, or drops the run. The list's
order is unchanged: the probe compared it with the walk's order after each
add and removal, 4,398 times, all equal.
The region's making at N=2,000 fell from 36.4 us to 6.5 us, and at N=500
from 11.7 us to 5.2 us.
render_memory_region inserted each range into the view's array by moving
every range after it, after a scan from the array's start for its place.
Both are linear in the ranges, so rendering a container of N subregions
was quadratic: with 2,000 16 MiB RAM regions of reims-graphics-pci's pool
in system memory, a commit's three renders took 2.3 ms of a 2.66 ms add
(q35 under KVM, paused, on a Ryzen 7 7840HS: a probe device doing the
add's calls, the median of 3 runs' p50 over 50 adds each).
While the render builds it, the view's array now keeps its unused slots as
a gap at the last insert, and a binary search finds where a region starts.
An insert moves only the ranges between the gap and its place, so a
container's disjoint subregions, which render in their list's order, newest
first, insert with almost nothing moved when they were added in address
order, either way; the gap is closed before the view is simplified.
Only memory.c changes, and in it only how the render finds a range's place
and makes room for it. The search starts the loop at the first range that
ends past the region's start, where the old loop's first pass not skipped
by its continue was, and each insert puts the same range at the same place
in the view's order. Which ranges a region renders, their offsets, flags
and order, flatview_simplify, the dispatch (physmem.c is untouched) and
what listeners see are the same. The probe checked it: it rendered 20,162
views both ways, in address order and scattered, and compared them field
by field, all equal.
The add at N=2,000 fell from 2.66 ms to 0.75 ms and the removal from
2.61 ms to 0.73 ms (N=0: 73 us and 82 us); with the adds in no address
order, 1.25 ms and 1.16 ms. What is left grows with N because every commit
still renders each flat view whole, its dispatch included: about 0.1 us a
region a view.
Each pool ask committed a memory transaction of its own, and each commit
renders every flat view, which with many pieces in is most of the ask's
cost: 2.3 ms of a 2.66 ms add with 2,000 16 MiB pieces in (q35 under KVM,
paused, on a Ryzen 7 7840HS: a probe device doing the asks' calls, the
median of 3 runs' p50 over 50 asks each).
The bh now takes the asks at the head of its queue that are of one kind,
adds or removals, and carries them out in one transaction. The order of the
asks and of their answers is kept: each add of a run is answered once the
run has committed, so the guest's address space has the piece before the
library hears of it, and an ask of the other kind waits for the next run.
The trace gives each ask the run's length and the run's BQL time.
With runs of 8, an ask at N=2,000 costs 365 us of BQL (add) and 345 us
(removal), against 2.66 ms and 2.61 ms one at a time; at N=0, 26 us and
34 us against 84 us and 89 us. An ask that comes alone still pays a whole
commit.
find_ram_offset compared each RAM block with every other to find the gap
after it, which is quadratic in the number of blocks. A device that maps
many blocks of its own pays it on each add: with 2,000 16 MiB pool pieces
of reims-graphics-pci in, the placement took 16.1 ms of an 18.6 ms add
(q35 under KVM, paused, on a Ryzen 7 7840HS: a probe device doing the
add's calls, the median of 3 runs' p50 over 50 adds each). QEMU 11.1.90,
this tree's base, has the same search.
The blocks' ranges are now also kept in an array sorted by offset, which
ram_block_add and qemu_ram_free update with the block list under the
ramlist lock, and find_ram_offset reads it in one pass: the block that
follows a gap is the next one in the array. The smallest gap that fits
still wins; between gaps of one size the lowest now wins, where the list's
order (largest block first) chose before. Offsets are this process's own:
the dirty bitmaps index them, and migration names a block by its idstr
and gives offsets within it.
The placement at N=2,000 fell from 16.1 ms to 2.2 us, and at N=500 from
1.10 ms to 0.6 us; the add at N=2,000 from 18.6 ms to 2.66 ms, nearly all
of it the commit's render. The pass and the array's insert are still
linear, about 1 ns a block. A logarithmic search would need an ordered map
with a lower-bound lookup, which neither GLib 2.66, QEMU's minimum, nor
util/qtree has.
memory_region_set_unmergeable commits a transaction of its own when the
region is enabled, which a new region is, even while it is in no address
space yet. Each pool add therefore committed twice and rendered every flat
view twice: with 2,000 pieces in, that second commit cost 2.34 ms of a
20.7 ms add (q35 under KVM, paused, on a Ryzen 7 7840HS: a probe device
doing the add's calls, the median of 3 runs' p50 over 50 adds each).
The flag is now set inside the add's transaction, before the piece goes in,
so the add commits once with the same result. The add at N=0 fell from
131 us to 81 us, and at N=2,000 from 20.7 ms to 18.6 ms; the rest of it is
the RAMBlock's placement and the commit's render.
The device reserved x-pool-size bytes, 64 GiB by default, for the guest's
Shared pool whatever the host GPU: more address space than a 24 GiB GPU's
Shared heap can ever fill, and on a GPU with a larger heap a pool that stops
short of it. The library now sizes the range from the Shared memory heap of
the GPU device it opens, so realize offers it the room the machine has (from
pci-hole64-end, in whole GiB, below three quarters of the guest's physical
addresses), and after the create reserves the range it took
(rvg_graphics_device_pool_range): fw_cfg etc/reserved-memory-end goes past it,
rounded up to 1 GiB, and KVM's slot-zap-all quirk goes off as before. The
x-pool-size property goes: no host needs an override, and a GPU with no
host-cached memory still gives no pool.
What the guest sees changes: the firmware's reserved-memory-end follows the
host GPU's Shared heap instead of a fixed 64 GiB.
reims-graphics-pci.c is in system_ss, built once for every target, and its
pool's KVM_X86_QUIRK_SLOT_ZAP_ALL block called kvm_check_extension and
kvm_vm_ioctl wherever the host's headers define the quirk, which is every
x86-64 Linux host. qemu-system-aarch64 there has no KVM, and its link failed
on both: no Linux host could build the arm64 guests' QEMU since the pool.
The calls move to reims-graphics-pci-kvm.c, which only the targets with
CONFIG_KVM link, and the other targets link reims-graphics-pci-kvm-stub.c,
as hw/vfio does with kvm-helpers.c. Both are added on Linux hosts alone,
where the device file calls them; on macOS and Windows the device's code is
unchanged. Under KVM the quirk is turned off as before, with the same
warning where KVM refuses.
Under WHPX a piece's removal held the BQL for the hypervisor's unmap: 46 ms
for a 1 GiB piece, which a vCPU exiting meanwhile waited 34.6 ms of. The
library's pool_remove now unmaps the piece on its own thread first
(whpx_unmap_before_del), as pool_add maps it ahead; the removal on the main
loop then takes the region out with no unmap. The trace says whether it was
unmapped ahead and how long that took.
WHvUnmapGpaRange took 45 ms for 1 GiB on the Mac mini 2018's Hyper-V
(measured 11-17). The listener calls it inside the memory transaction's
commit, under the BQL, so a removal held the BQL 46 ms, and a vCPU that
exited to a device meanwhile waited 34.6 ms.
whpx_unmap_before_del unmaps a range on the caller's thread, without the BQL,
and records it; the listener's removal of a section of exactly that range
then unmaps nothing. Until the removal a guest access there exits, and the
MMIO path carries it out on the region's memory. A range whose map ahead is
still to be added is left to the listener.
The library's new runtime allocates the GPU memory the guest's Shared
buffers live in, and the device maps those blocks into the guest. This adds
the host side of that pool.
At realize the device reserves a range of guest physical addresses with
nothing under it: the first 1 GiB past the RAM and the PCI host bridge's
default 64-bit window (pci-hole64-end before any BAR is placed), 64 GiB by
default (x-pool-size, an internal property), below the top quarter of the
guest's physical address bits where OVMF puts its own 64-bit window when it
sizes it from them. It raises fw_cfg etc/reserved-memory-end past the range,
so that OVMF's 64-bit window goes above it, as above memory hotplug's area,
and gives the range to the library (RvgGraphicsDeviceConfig, v5). Under KVM
it turns KVM_X86_QUIRK_SLOT_ZAP_ALL off where the kernel offers it, so a
piece's removal zaps only its own slot.
The library asks to map and unmap pieces on its threads (pool_add,
pool_remove). The asks are queued and carried out on the main loop under the
BQL, in order. Each piece is a RAM region of its own over the block,
unmergeable, owned by an object of its own: an add is a pure add, which
touches no other KVM slot or WHPX mapping. Under WHPX the hypervisor's map runs
on the asking thread first, outside the BQL (whpx_map_ahead). Once it is added
the device tells the library (rvg_graphics_device_pool_added). A removal takes
the region out of the guest's address space. The piece's end, once its last
holder lets go (an older flat view past its RCU grace period, a device's DMA
map), tells the library its memory may go (rvg_graphics_device_pool_removed).
The teardown takes every piece out before the release and waits for their ends
(drain_call_rcu), so the library frees the blocks inside the release, before
the process exits.
x-pool-grow asks the library for more pool, as the guest's own ask will; it
drives the host side's checks and measurements until the guest's side exists.
Trace events time each add: from the ask, the map ahead, and the part under
the BQL.
WHvMapGpaRange takes about 26 ms a GiB on the Mac mini 2018's Hyper-V (8.2 ms
for 256 MiB, 26.2 ms for 1 GiB, measured 11-17). The listener calls it inside
the memory transaction's commit, under the BQL, so a vCPU that exits to a
device under the BQL meanwhile waits for the whole map: 21 ms during a 1 GiB
add. The rest of that commit held the BQL for 0.5-0.6 ms.
whpx_map_ahead maps a range on the caller's thread, without the BQL, and
records it; the listener's add of a RAM section of exactly that range and
memory then maps nothing. The call is partition-wide, as the vCPUs' runs are,
which already go on beside the main thread's maps. whpx_unmap_ahead undoes a
map whose region was never added. Removal is unchanged: the listener unmaps.
The comment on whpx_sysenter_msr (40257041) said QEMU keeps the MSRs' 64 bits
as Intel's CPU does. It keeps them in the CPU's state, but they answer only
a guest read that faults as well: a read Hyper-V answers itself gives the
low 32 bits, all Hyper-V holds, and the vCPU's next full register read
(whpx_get_registers at WHPX_LEVEL_FULL_STATE, which cpu_synchronize_state,
a system reset, a snapshot and a debug exit make) takes Hyper-V's 32 bits
into the state. Read from the code; the comment now says so, without the
comparison with KVM. No code changes.
Hyper-V on a Ryzen 5 5600G (Windows 11 Pro 26200) refuses
WHvX64RegisterTscDeadline (hr=c0350005, logged by the reset of every vCPU)
while its CPUID output offers the TSC deadline timer, so QEMU's filter kept
the CPU model's tsc-deadline. A macOS guest's kernel arms that timer where
CPUID offers it, and waited at boot for interrupts that never came; with
-tsc-deadline among the VM's CPU flags it took the local APIC's timer and
booted (measured on that host by pull request #15's author, 2026-11-16). The
VM's owner had to add the flag by hand.
At its init WHPX now asks Hyper-V: it makes vCPU 0 before any other, sets
its TSC deadline register to 0 as each vCPU's reset does, and deletes it.
Where the set is refused, whpx_get_supported_cpuid's leaf 1 offers no TSC
deadline timer, so x86_cpu_filter_features drops the model's tsc-deadline as
any feature the host lacks ("check" warns of it), the guest arms the local
APIC's timer, and the reset no longer sets the register. It is decided by
Hyper-V's answer, not the host's vendor, as KVM offers the timer only where
KVM_CAP_TSC_DEADLINE_TIMER says it has one (kvm_arch_get_supported_cpuid).
A host whose Hyper-V takes the register is as before: the Mac mini 2018's
(i7-8700B, UHD 630) took it, its reset logging no refusal of 00002095, and
its guests keep the timer. The refusal and the guest's boot on an AMD host
are read from this code and the author's report, not run here: no AMD host
with Windows is at hand.
Joins the three commits this branch had not pushed (243971f2, 0fdbf381,
500d30fb: WHPX's interrupts and doorbells off the BQL, screendumps encoded
off it) with pull request #15, 40257041, which keeps an Intel guest's MSRs
that Hyper-V refuses on an AMD host. target/i386/whpx/whpx-all.c merged
without conflicts.
A macOS guest on reims-ctl's Skylake model, under WHPX on a Ryzen 5 5600G,
stopped at the Apple logo with no progress bar: the kernel took a general
protection fault before its console was up, and debug=0x100 kept the panic
on the stack. Hyper-V on an AMD host answers with #GP the guest's write of
a 64-bit address to IA32_SYSENTER_EIP (wrmsr 0x176, which macOS makes at
boot: AMD's SYSENTER MSRs hold 32 bits), and its read of IA32_MISC_ENABLE
(rdmsr 0x1a0 in commpage_post_ucode_update), an MSR of Intel's alone.
intercept-msr-gp now defaults to on where the host is not Intel's, so such
a #GP reaches QEMU's MSR emulation, which keeps SYSENTER_ESP and _EIP's 64
bits for the guest and gives Hyper-V their low 32, as KVM on AMD does for an
Intel guest, and answers MISC_ENABLE, FEATURE_CONTROL and PLATFORM_INFO from
the CPU's state. The full register sync gives Hyper-V the SYSENTER MSRs' low
32 bits there too. intercept-msr-gp=on or off as given is kept, and an
Intel host is as before.
With it the guest boots macOS Tahoe's recovery (Darwin 25.6.0), installs
26 and reaches Setup Assistant on that host. Its kernel picks the TSC
deadline timer, which Hyper-V gives an AMD host's guest no register for
(WHvX64RegisterTscDeadline, hr=c0350005): the VM's CPU flags drop it
(-tsc-deadline), outside this change.
qmp_screendump encoded and wrote its PNG or PPM on the main thread, in the
coroutine, with the BQL held, so for the whole encode no vCPU could touch a
device the BQL guards and the main loop ran nothing. A PNG of a 2880x1620
display takes about 120 ms on a Mac mini 2018, a busy desktop's up to 1.7 s.
Under WHPX a macOS guest's full-screen present loop (present_probe, a PNG
screendump at +6 s) still lost 108-142 ms at the screendump in 4 of 5 runs,
runs 2 to 6, with the two commits before this, which take the device's
interrupts and doorbells off the BQL (measured 11-16; their messages quote 2
runs that dodged it). A build that logged every BQL wait over 20 ms, with
the waiting vCPU's last exit, found the waits in prepare_mmio_access: a vCPU
wrote at 0x806492b4 and waited 127 ms for the BQL while a probe screendump's
PNG was encoded, and the present loop stalled 133-283 ms meanwhile; at a
desktop screendump two vCPUs waited 1.66 s and 1.64 s, at 0x806492b0 and
0x80403004. Neither region is the device's: they are other devices' MMIO,
which takes the BQL. The vCPU then stalls the guest's work that waits for it.
The runs without a gap had no such wait during their screendump.
The coroutine now copies the console's surface under the BQL, as the update
left it (pixman_image_composite into an image of the surface's format; 18.7
MB at 2880x1620), and runs the encode and the write of the copy on a thread
of the current AioContext's pool (thread_pool_submit_co). It waits for them
with the BQL let go and the main loop running, then removes the file on an
error as before. The dump's pixels are the update's frame, as before: the old
code encoded the surface itself, which no update could change while it held
the BQL; the copy keeps that now that the encode does not hold it. The QMP
and HMP commands answer when the file is written, as before.
whpx_vcpu_pre_run took the BQL before every WHvRunVirtualProcessor, so a
vCPU waited for the BQL's holder after any exit, including an MMIO write to
a lockless region such as reims-graphics-pci's doorbell. A QMP screendump in
PNG holds the BQL in png_save for about 120 ms at 2880x1620 on a Mac mini 2018
(UHD 630). For that long the guest's submitting vCPU stood still, and an
on-screen Metal app's nextDrawable blocked 116-133 ms in every run, whether
or not the device's interrupts went off the main loop (the commit before
this). Measured 11-16 with present_probe and a PNG screendump at +6 s, runs 2
on: before both commits, gap max 128-148 ms; with the commit before this
alone, 116.6-133.7 ms. Under a build that logged pre_run's waits, the vCPUs
waited 111-123 ms for the BQL at each screendump, each after a
MemoryAccess exit to the device's BARs, while 8191 of 8192 interrupts went
out directly. With this skip on top: 33.7-34.0 ms, 60.0 fps, 0 dropped, and
no wait over 20 ms, the same as KVM's on ms01's Iris Xe (33.3-33.7 ms).
kvm_arch_pre_run takes the BQL only to inject a pending NMI or SMI, and,
when the PIC is not in the kernel, for the userspace PIC and TPR; with KVM's
in-kernel irqchip and nothing pending it takes none. This matches that: with
the hypervisor's APIC (kernel-irqchip) and no NMI, SMI, INIT, TPR or HARD
request pending, the locked section has nothing to do, so it is skipped and
only ready_for_pic_interrupt is reset. Its TPR sync and PIC injection are
kernel-irqchip=off's or wait for CPU_INTERRUPT_HARD. kernel-irqchip=off, and
any pending request, take the BQL as before.
The kick-after-check window: a request raised after the check goes through
cpu_interrupt (generic_handle_interrupt), which kicks the vCPU through
qemu_cpu_kick, whpx_kick_vcpu_thread and whpx_vcpu_kick, that is
WHvCancelRunVirtualProcessor. That brings the vCPU back to pre_run, where
the next check sees the request. A request raised between the old
bql_unlock and the run already had this window, and the loop's own
exit_request kick before WHvRunVirtualProcessor relies on the same cancel.
Microsoft's reference for WHvCancelRunVirtualProcessor does not say whether
a cancel made before the run returns it at once (read).
Without irqfds (WHPX, HVF, TCG) the device raised every interrupt through a
BH, so the interrupt waited for QEMU's main loop. On WHPX that let any hold of
the main loop hold back every completion the guest's GPU work waited for. A
QMP screendump in PNG of the 2880x1620 display spends about 120 ms in
png_save under the BQL. During that time the guest took no completion, and an
on-screen Metal app's nextDrawable blocked 117-133 ms, a 7-refresh gap. This
held in 6 of 6 present_probe runs on a Mac mini 2018 (UHD 630), measured
11-15. Under KVM, where the irqfd injects the interrupt, the same screendump
cost no frame: ms01's Iris Xe, 6 of 6 runs, gap max 33.3-33.7 ms, measured
11-16.
Where the accelerator is WHPX and its APIC is the hypervisor's
(kernel-irqchip), the raising thread now asks the hypervisor for the
vector's MSI itself: whpx_send_msi_direct, the request whpx_apic_mem_write
makes, with no BQL. The message comes from the MSI-X vector notifiers, as
the irqfd's route does, kept under a lock of the device's that mask and
unmask take. So no interrupt is requested once the guest's mask of the
vector has returned. A full barrier orders the library's writes of what
the interrupt reports before the request. A masked vector, disabled MSI-X,
vector 0, a refused request, and WHPX without the in-hypervisor APIC still
go through the BH, where msix_notify sets the pending bit, drops the
interrupt or says why it is lost, as before. whpx-apic.c now makes every
MSI request under one lock of its own, so requests reach the partition one
at a time as the BQL kept them before.
That WHvRequestInterrupt may be called off the vCPU threads while they run
was read, not measured. Microsoft's reference page (learn.microsoft.com,
virtualization/api/hypervisor-platform/funcs/whvrequestinterrupt) takes only
the partition handle and states no thread restriction. QEMU already calls it
from the main loop's thread (the BH's msix_notify) while vCPUs run in
WHvRunVirtualProcessor. With kernel-irqchip a halted vCPU stays in the
hypervisor (whpx-all.c: the X64Halt exit is kernel-irqchip=off's), so the
request wakes it as one from an MMIO exit does.
The dsound backend made its DirectSoundCapture object at realize and failed
the whole audiodev where Windows has no recording device, a PC with no
microphone among them: "Could not initialize DirectSoundCapture: No sound
driver is available for use", and QEMU exited. Capture is now optional:
without it the backend logs why and plays as before, and an input voice
fails to initialize, as dsound_init_in already does without the object.
qemu_console_lookup_by_device asked every console for its "device" and
"head" properties with &error_abort, but only a graphic console has them.
A lookup that matched no graphic console reached the first text console
and ended QEMU. QMP's screendump naming reims-graphics-pci with a head
past its displays did so under -display none, where the default parallel
port's vc:80Cx24C makes a fixed text console: "Property
'qemu-fixed-text-console.device' not found", then an abort.
The lookup now passes over every console that is not a graphic one, so
such a screendump answers that the device's head is not bound to a
console, and QEMU goes on. display-screendump-test checks it beside two
text consoles, then a screendump of the head the device has.
reims-vgpu's graphics device can have up to four displays
(RvgGraphicsDeviceConfig's display_count). The new displays property sets
how many, 1 to RVG_GRAPHICS_DISPLAYS_MAX, 1 by default; realize refuses
anything else. Display i is head i of QEMU's UI and gets its own console.
The console is filled by its own reads of that display
(rvg_graphics_device_read_display_at), each with its own late bound, so
QMP's screendump of head i saves display i. Each console also shows its
display's guest cursor: display 0's comes through cursor_glyph, cursor_show
and cursor_move as before, and the other displays' come through the _at
callbacks, which name the display.
Under -display none the library opens a window per display, each at the
resolution property's size. A window's pointer, scroll and keys reach the
guest through its own display's console. All windows share the one
tablet's button state. Teardown waits for every display's read. At
displays=1 the device makes the same console, window, reads and callbacks
as before.
reims-vgpu's library runs on Windows too, so meson looks for it there, through
pkg-config and linked statically as on Linux and macOS; without it the device
is left out, as before.
The memory walk passes each range of RAM that is a view of a section
(memory-backend-ram,share=on) with the section's handle and the range's offset
in it, the Windows form of RvgMemoryRangeFile, and leaves other RAM out, as
Linux leaves out RAM with no shared file. The library maps views of the
section's pages, which share the pages WHPX maps into the guest. The control
ring's doorbell is the EventNotifier's event (rvg_graphics_device_set_doorbell
takes a void * on Windows), which QEMU's memory core sets in userspace under
WHPX as it does under HVF. A route's notifier is cleaned up without an fd
where there are none; no route is taken there, as route_doorbell needs
eventfds. Linux and macOS compile the same code as before.
memory-backend-ram,share=on, like every RAM_SHARED block, ignored share on
Windows: its RAM came from VirtualAlloc, private to the process, so no second
mapping could share its pages. On Windows a shared block is now a view of a
section the paging file backs (CreateFileMapping with SEC_COMMIT, then
MapViewOfFile), committed whole as VirtualAlloc's memory is. The RAMBlock
keeps the section's handle (qemu_ram_get_section, beside qemu_ram_get_fd),
and the block is freed with UnmapViewOfFile and CloseHandle. A device's
library maps views of the section's pages again (MapViewOfFile3), and those
share the pages WHPX maps into the guest, both ways.
qemu_win32_map_alloc now passes the size's high 32 bits to CreateFileMapping,
which RAM of 4 GiB or more needs; its display surfaces are smaller and map as
before. RAM_NORESERVE keeps qemu_anon_ram_alloc's path, which refuses it, and
POSIX hosts are unchanged.
whpx_accel_init's cpuidExitList had no leaf 4, so Hyper-V answered it with no
cache levels and the CPU model's own leaf 4 never reached the guest. macOS
counts the CPUs sharing the last-level cache from it, gets 0, and panics 1.3 s
into boot (osfmk/i386/cpu_threads.c:198, zero divisor:
topoParms.nCoresSharingLLC), with -cpu host and kernel-irqchip=off alike.
With leaf 4 in the list, Sequoia's recovery boots to its UI under WHPX on an
i7-8700B (Windows 11 26H2) in 2 minutes.
The short-packet test pressed usb-kbd's key before it queued its TDs. A
key wakes the keyboard's interrupt endpoint, and the controller kicks it
then: typed isoch, the endpoint's ring was still empty, and its Ring
Overrun event came first, ahead of the TD's two events. The TDs are now
queued and NAKed by the idle keyboard first, as test_xhci_bei does, and
the key completes them.
xhci_xfer_report posted one Transfer Event per TD at most: the first TRB
that asked for one took it, and every later TRB of the TD stayed silent.
A Short Packet met on a TRB with ISP that is not the TD's last therefore
posted its event, and the TD's last TRB, with IOC, posted none. xHCI
4.10.1.1.2 asks for both: the short TRB's event with Short Packet and its
residue, then one for the last TRB with Short Packet and the same
residue, and software takes the TD as complete only at the event that
points at its last TRB.
macOS queues an isoch IN TD that crosses a page as an Isoch TRB with ISP
and Chain, then a Normal TRB with ISP and IOC. A UVC camera's frames end
in short packets, so the first TRB's event came and the second never did:
AppleUSBXHCIIsochronousRequest logged "mismatched event TRB" for each
later event of the endpoint, its requests never completed, the camera's
stream stopped within 44 to 115 ms of starting, and no frame reached the
guest (a black viewfinder with the camera's light on).
Each TRB now posts the events 4.10.1.1 gives it, within its TD: without
a Short Packet, each TRB with IOC posts Success; the TRB a Short Packet
is met on posts Short Packet with its residue where it has ISP or IOC,
once; each later Transfer TRB of the TD with IOC posts Short Packet with
that residue (with the TRB's own residue where the short TRB posted
nothing, as before); and an Event Data TRB after the Short Packet is
parsed only if no event completed the TD, and then only the first, as
PAE is 0. A TRB with IOC before the short one no longer silences the
short one's event either. BEI is kept per TRB, and an error still posts
one event and ends the report. The code is the same for isoch, bulk,
interrupt and control rings; a control transfer's Setup and Status
Stages stay TDs of their own.
tests/qtest/usb-hcd-xhci-test.c runs usb-kbd's 8-byte report into
two-TRB TDs on its interrupt endpoint, and into macOS's Isoch-and-Normal
TD on the endpoint typed isoch.
pa had no enable_in: a capture voice's record stream was connected as the
voice was made (a virtio-snd stream's PREPARE) and disconnected as it was
freed (its RELEASE), whether the guest captured or not. All that time the
host's sound server listed QEMU as a client recording from its source.
A capture voice now keeps the sample spec and buffer attributes it was
made with, connects its record stream as the voice is enabled (the guest's
capture starts, or the VM runs again with it on) and disconnects it as the
voice is disabled, so the server lists the client only while the guest
captures. Each new stream gives what the source captures from then on, and
until it is ready a read finds nothing, without an error line. The guest's
last volume and mute for the voice are kept with it and given to each
stream as it becomes ready. A channel count pa has no map for is still
refused as the voice is made.
A process rang its queues through a kext call, about 1.5 us of a 5.4 us
commit on a 780M host: the Mach trap and IOUserClient's dispatch to the
kext's DOORBELL write. The library now has doorbell pages: the kext binds
one to each process it opens and maps it into the process, which writes
its rings' ids there itself.
BAR 4 is that page array, 32-bit and not prefetchable,
RVG_GRAPHICS_DOORBELLS_SIZE bytes, a lockless region whose writes go to
rvg_graphics_device_doorbell_write on the vCPU and whose reads answer 0,
and the config says so (doorbell_pages), so the library offers the wire's
DOORBELL_PAGES. A queue of a process with a page is routed at the page's
doorbell (route_doorbell_page), an ioeventfd matching the ring's id there
as on DOORBELL; a route replaces another of the same ring at the same
address only.
e9e0fa81 moved libusb_set_interface_alt_setting to a worker, but Linux's
usbfs takes the device's lock for each ioctl, and SETINTERFACE holds it for
the whole call. The main loop still made the device's other ioctls: it
reaped completed URBs in libusb's event handling (REAPURBNDELAY), submitted
URBs for the guest's packets and resubmitted iso transfers (SUBMITURB), and
canceled them (DISCARDURB). Each waited out the call with the BQL held: a
macOS guest stopping a USB audio device's output while its input still
streamed stalled QMP for 5.5 to 11.3 ms, the length of the worker's call.
While a device's SET_INTERFACE call runs, the main loop now makes no usbfs
call on it:
- libusb's fds leave the main loop, and it handles no libusb events,
until the last SET_INTERFACE call in flight returns. libusb reaps every
device with URBs to reap from one context, so it cannot leave one device
out: the other usb-host devices' completions wait for the call, as they
did when the main loop made it itself. Their submits do not wait.
- The device's submits and cancels wait, in their order, in a queue of
its own, and are made when its own call returns, before the events
resume, and whatever rc the call had. So usbfs gets them in the order it
got them before, where they waited for the lock in the main loop, and
each endpoint's URBs complete in the order they did. A submit that fails
then completes its transfer through its callback once, with nothing
transferred: NO_DEVICE for a device that is gone, which schedules the
device's close as a failed submit did, and an error otherwise. A cancel
of it that waited behind it is dropped. A cancel of a transfer whose
submit still waits takes both out and completes the transfer as
canceled, so it never reaches the kernel.
- Sync calls on the device wait for its call and its queue first: control
requests, a reset, closing it and QEMU's exit did already, and stream
allocation and release now do. So a device closed, unplugged or reset
meanwhile has every queued submit made, or completed with its error,
before its close aborts the transfers, and no URB after the close.
- Closing another device handles libusb events to drain its transfers,
so it first waits for every device's call and queue.
- A request started from a completion libusb reaps keeps the rest of that
pass of libusb's: a transfer it reaps after the request started may have
a cancel waiting, which is dropped as the transfer is freed.
A command for a slot that names no enabled slot completed with Slot ID 0:
xhci_get_slot returned 0 for it, and that was the Slot ID the completion
took. xHCI 6.4.2.2 has the Slot ID of a command's completion reflect the
slot the command is for, and the commands that name a slot (4.6.4 to
4.6.10) set the completion's Slot ID to the command's before they check
the slot. Their Slot Not Enabled Error and TRB Error completions now hold
the command's Slot ID. A driver that looks its device up by the
completion's Slot ID finds the device it sent the command for; one that
matches the Command TRB pointer sees no change.
The test's Stop Endpoint for a slot that is not enabled now expects that
slot's ID in its completion.
xhci_process_commands kept one event and one slot id for every command a
doorbell fetched, and each case set only what it changed. So a No Op, Get
Port Bandwidth, an NEC firmware revision on qemu-xhci, an unsupported
command's TRB Error and an Enable Slot that found no slot completed with
the previous command's Slot ID; an NEC firmware revision reply kept the
previous command's completion code; and every command after an NEC reply
completed with the reply's TRB type (48), Command Completion Parameter and,
after a challenge response, its Slot ID and VF ID fields.
Each command now starts from an empty Command Completion Event (xHCI
6.4.2.2): the Slot ID is 0 for No Op, Set LTV, Get Port Bandwidth, a
command the xHC does not support and an Enable Slot with no free slot, and
the completion code, the parameter, the VF ID and the type are the
command's own.
The test queues commands for a slot and commands that are not for one at a
single doorbell, on qemu-xhci and on nec-usb-xhci, and checks each
completion's fields.
The teardown deleted event_bh after the library's release and set it to
NULL, but a callback can still run past the release, and each of them
queues an event and schedules event_bh: qemu_bh_schedule(NULL) ends QEMU
with SIGSEGV at its quit. The callbacks that can run then:
- the window's pointer, scroll, key and close, one already running on the
window's thread as the release closes the window, which waits for no
callback under way;
- cursor_glyph, cursor_show and cursor_move, on a device thread the
release's 5 s bound left running (the library then keeps the GPU device
to the exit).
event_bh now stays to the exit, and the instance's finalize, which comes
only after a realize that failed, deletes it with what is queued. Once the
teardown closed the console the BH drops each event it finds, so nothing a
late callback queued reaches QEMU's input layer, the console or the
cursor the teardown let go. Before the teardown nothing changes: the main
loop, which runs the BH, starts after realize made the console.
The device's other BHs and files a late callback reaches keep to the same
rule already: raise_interrupt schedules a one-shot BH of its own, which
finds MSI-X uninitialised and notifies nothing, or writes the irqfd, which
the teardown leaves open; route_doorbell finds the routes closed; the read
done BH and the read's bound check what the teardown freed. The control
doorbell's notifier the teardown cleans up is no callback's: the library
holds its own copy.
route_doorbell, on one of the library's ring-0 or control threads as a
command queue is made or ends, takes the BQL to apply its change. At
QEMU's quit the teardown held the BQL across rvg_graphics_device_release,
which waits up to 5 s for the library's threads: a route call waiting for
the BQL at that moment held the release, and the quit, for the whole 5 s,
and the library then kept the GPU device to the exit. At quit the release,
and nothing else, now runs with the BQL let go, as pause_all_vcpus in the
same vm_shutdown lets it go while it waits. The route call takes it, finds
the routes closed and returns.
What can take the BQL, or run, inside that window, and what it finds:
- route_doorbell: routes_closed, set under the BQL by
reims_graphics_routes_close earlier in the teardown, so an add closes
its copy of the bell and is refused, and a drop finds the emptied table
and changes nothing. It adds or drops no ioeventfd and touches no memory
region; the table lives until finalize. Routes still change only under
the BQL, and a route's add or drop still comes before its queue's create
or destroy is answered.
- raise_interrupt: takes no lock. irqfd_on is false (the irqfd was
disabled earlier), so it schedules a oneshot BH; the BH runs on the main
loop's thread after the release, where MSI-X is uninitialised and it
notifies nothing. The irqfd stays open, as before.
- cursor_glyph, cursor_show, cursor_move (the display thread) and the
window's pointer, scroll, key and close: take event_lock, queue an
event and schedule event_bh, which live until the teardown deletes them
after the release, under the event_lock.
- destroy: QEMU gives none.
- No BH of ours runs inside the window: the main loop's thread, the only
one that runs the main context's BHs, is in the release.
- No PCI access: vm_shutdown paused the vCPUs, BAR 2 left the address
space, MSI-X is uninitialised, and s->device is NULL before the release
begins.
- Other threads that take the BQL there, the RCU thread's callbacks and a
paused vCPU's thread, touch nothing of the device's.
What the teardown freed before the window (the pool, the read's pixels and
bound, each route, the control doorbell) no callback reaches: the pool and
bound serve only the closed console, and a route is reached only through
the emptied table.
A realize that fails ran no guest, and the device is not hotpluggable, so
no unrealize comes while a guest runs: there the release stays under the
BQL.
A screendump waits for the console's read of the display, which waits for
its draw on the GPU, and QMP runs one command at a time on every monitor:
a GPU that never answered the read (NVIDIA's Xid 109, measured on the RTX
2080 and RTX 3090) left every QMP monitor without an answer until the
quit, with no query-status, system_powerdown or other screendump. A read
still under way 3 s after its start is now late: a timer on the realtime
clock answers the updates waiting for it, and every update until the read
ends is answered at once, starting no other read. The read goes on in the
pool, and its end updates the console as before.
A late screendump gets what the console shows: the frame of the last read
that ended (the display as that read found it), or QEMU's placeholder,
"Guest has not initialized the display (yet).", where no read has ended.
A read that ends within 3 s is waited for as before, so a screendump stays
exact on a GPU that answers. The 3 s leave reims-ctl's viewer, which waits
5 s for a QMP answer, 2 s of margin; a read on a GPU that answers takes
milliseconds. The teardown's own wait for the read stays 5 s.
The routes wrap each queue's doorbell file in an EventNotifier with
event_notifier_init_fd, which util/event_notifier-posix.c defines only
under CONFIG_EVENTFD, so the macOS build (HVF or TCG) failed to link.
The library offers routed doorbells only to a Linux host that gives
route_doorbell, so a build without eventfds gives no route_doorbell and
compiles none of the route code but its teardown. Linux builds, where
CONFIG_EVENTFD is set, compile the same code as before.
A write of a command queue's doorbell went to the library on the vCPU,
an exit to QEMU on every commit: 13.4 us of the guest's time on the
Radeon 780M host, against 8.9 us for the control ring's doorbell, which an
ioeventfd takes. Where the guest took DOORBELL_ASKS, the library now hands
over each queue's eventfd with its ring's id (route_doorbell), and the
device adds it as an ioeventfd on DOORBELL matching that id exactly, so
KVM signals the queue's thread in the kernel and the vCPU goes back to the
guest. A write the guest asks to be answered at the doorbell carries bit 0
and so matches no route: it reaches the library as before.
The change is applied under the BQL before the callback returns, taken
where the calling thread does not hold it: once a route is dropped no
write reaches its file, so a queue made again over the same ring gets
every write of its own. At most RVG_GRAPHICS_DOORBELL_ROUTES routes are
held, since KVM's MMIO bus holds 1000 devices and QEMU ends the VM where
KVM refuses an ioeventfd; a route of a ring another holds replaces it, and
the teardown drops them all.
PCM_INFO's channels_max is the most channels a stream supports (virtio
1.2, the sound device's PCM information), and the driver must set no more
in PCM_SET_PARAMS.
virtio_snd_pcm_open set it to the channel count of the stream it opened,
so once a stream was prepared, PCM_INFO answered with that stream's
channels: after a mono stream, a driver asking again was told one channel
at most. channels_max now stays 2, as realize sets it.
macOS's AppleVirtIOSound sets 2 channels on every stream (traced by
virtio_snd_pcm_params on 11.7.11), so a macOS guest saw 2 either way.
The device MUST NOT complete an input stream's I/O message until its buffer
is full, the stream's end excepted (virtio 1.2, 5.14.6.8, Input Stream).
virtio_snd_pcm_in_cb completed one once period_bytes were recorded into it,
so a buffer larger than a period came back partly filled, and read no more
than a period at a time. It now fills each buffer to its size, and a
smaller one completes when full, as before. A stop or release still
completes the messages pending as they are.
A driver that posts period_bytes buffers sees no change: macOS's
AppleVirtIOSound posts 65536-byte buffers with period_bytes 65536 (11.7.11,
traced by virtio_snd_pcm_queued and virtio_snd_pcm_params), and Linux's
driver posts period-sized ones.
An input stream's I/O message is its header, then a device-writable buffer,
then the status part (virtio 1.2, 5.14.6.8). return_rx_buffer wrote the
status at the offset the recorded frames ended at, which is the status
part only where the buffer was filled. A message completed partly filled,
as at the stream's stop or release, or empty, had its status written over
the start of its unfilled frames, and the status part kept what it held
before: a driver that reads it there, as Linux's does from a descriptor of
its own, read a stale status.
The status is now written at the end of the message, after the buffer,
whatever was recorded. The frames still go from the buffer's start, and the
used length stays the status' size plus the frames recorded, as the spec
defines it. A filled message's status is where it was. For macOS's
AppleVirtIOSound, which posts period_bytes buffers and completes each I/O
with result 0 whatever the status and used length say, only the messages
completed at a stop or release change: their status part now holds OK and
a latency of 0, not what the guest's memory held.
What a stream's I/O messages did showed only at the queue level: a tx or
rx queue callback ran. Each stream now traces the parameters the driver
set, each I/O message as it is queued and as it completes (its size, the
bytes played or recorded of it, the latency reported, how many stay
pending), and how many are pending at each start, stop and release, so a
driver's stream lifecycle can be read against the device's completions.
A device's stream directions were fixed, the first half playback and the
second half capture, so no device captured alone. macOS's AppleVirtIOSound
makes one CoreAudio device of each virtio-snd device and starts all of its
streams when a client starts it. It posts an input stream's receive buffers
at the stream's start and again at each one's completion while its ring has
room, so on a device started for playback alone the input ring fills unread
and the posting ends, and a recording that joins while the playback runs
gets no input until both stop. A capture-only device beside a playback-only
one lets the guest start its input for a recording alone.
input-streams counts the streams that capture, the last ones; by default
half of them, rounded down, as before. streams=1,input-streams=1 makes a
capture-only device.
An input stream's voice ran from VIRTIO_SND_R_PCM_START to its STOP, read
or not. macOS's AppleVirtIOSound starts its input stream with each output
stream and posts receive buffers for its first 0.73 s only, so while any
guest output played QEMU kept the host's capture running (a PipeWire cycle
every 5.3 ms on the host's default source, a microphone) with nothing to
put the audio in, and the backend's buffers filled with audio the guest
would get, late, if it read again.
A started input stream's voice now runs while the driver has buffers posted
for it: posting one starts it, and audio that comes with none posted stops
it. The guest's buffers are filled as before while it keeps them posted;
its first buffer after a time with none takes what the source captures
from then on. This holds for every backend whose capture voices stop
(pa's record stream runs from prepare to release either way).
A capture stream that stopped and starts again (the guest's input voice
enabled once more, or the VM resumed) gave its reader what the ring still
held from before it stopped first.
Drop what the ring holds as the stream starts, so its reader gets what the
source captures from then on, as alsa's snd_pcm_drop and snd_pcm_start do.
A stream that starts once and runs sees no change.
A capture ring that fills keeps its oldest 4 MiB: capture_on_process drops
what does not fit. A guest that reads its input stream again after the ring
filled (about 24 s of 16-bit stereo at 44.1 kHz with nothing read) got that
much stale audio first, and kept that delay for the rest of the stream.
When qpw_read finds the ring full, it skips to the newest audio it is asked
for, in whole frames, and the skipped bytes are said with the overrun count
as the stream closes. A guest that reads in time never fills the ring, and
sees no change.
A capture stream whose guest reads none of its input fills its 4 MiB ring
(about 24 s at the 176 kB/s one such stream ran at), and from then on each
PipeWire cycle found it full and wrote an "overrun write" line: about 190
lines a second at a 256-frame quantum, 169,695 in one 17-minute boot of a
macOS 26.7.2 guest whose host's default source is an analog input. A host
with no source runs no cycles, and writes no lines.
The overrun is what a stream nobody reads does, so say it once per stream
when the ring first fills, count the cycles that found it full and the
bytes they dropped, and say the count as the stream closes, at QEMU's quit
among others. A stream that is read never fills its ring, and runs as
before.
With the teardown's wait for a display read bounded, QEMU's quit after
NVIDIA's Xid 109 (a GPU that stopped answering) went on past the device
and then hung in monitor_cleanup, which waits for the QMP dispatcher
coroutine to finish: a screendump held it, waiting in the console's
dump_queue for the update the stuck read was for. Closing the console
wakes no such waiter, and a read that ends after the close updates no
console, so the screendump never returned. The same held, on any GPU, for
a screendump whose read had not ended when the quit began.
Mark the console's update done before closing it: a waiting screendump is
answered with what the console shows, the last read's frame, and the
dispatcher can stop.
The teardown at QEMU's quit freed the console's thread pool first, as a
read of the display under way uses the device, and thread_pool_free waits
for the read with no bound, under the BQL. A read waits for its draw on
the GPU, and a GPU that stopped answering never finishes it: after NVIDIA's
Xid 109 (a context switch timeout) in Apple's Modern Rendering sample on an
RTX 2080 and an RTX 3090, a screendump's read waited for good, and QMP's and
HMP's quit left QEMU in qemu_cleanup -> vm_state_notify ->
reims_graphics_pci_teardown -> thread_pool_free until SIGKILL.
Wait for the read at most 5 s, the bound the library's release of its last
device waits for its own threads. Past it, say so and leave the device, its
pool and the rest to the process's exit, as a VM whose shutdown pauses it
keeps them: releasing the device while the read uses it is not allowed. A
read that ends within the bound changes nothing.
IMODI resets to 4000. An event posted within IMODI of the last interrupt
waits for IMODC to reach 0, an event posted after the count ran out
asserts the interrupt at once, and with IMODI at 0 every event does.
qemu-xhci stored the Interrupter Moderation register and did nothing
with it: an interrupter asserted its interrupt for each non-blocking
event the guest's event handler was not already busy with, and again
whenever the handler cleared Event Handler Busy with events left on the
ring.
Interrupters now follow the specification's moderation (4.17.2): the
interrupt asserts when a non-blocking event awaits (the Interrupt
Pending Enable flag, 4.17.5), the moderation counter is at 0 and the
event handler is not busy. Asserting it loads IMODC with IMODI, which
then counts down in 250 ns steps; an event posted meanwhile waits for
the count. IPE clears when the ring is initialized or the guest's ERDP
reaches the enqueue pointer, so blocking events left on a ring no
longer assert the interrupt by themselves. IMODI resets to 4000 (1 ms),
IMODC reads back the time left and the guest may set it. IP and EINT
are set when the interrupt asserts, and no longer for each event posted
while the handler is busy.
macOS reads offset 0x1c of the capability registers, HCCPARAMS2 in xHCI
1.1 and later and reserved in 1.0, which qemu-xhci reports. It read as
0 already, traced as an unimplemented read. It now reads as 0 on its
own: none of HCCPARAMS2's capabilities.
qemu-xhci on q35's PCI Express bus sets LTC and completes Set LTV with
Success; on the pc machine's conventional PCI it leaves LTC clear and
refuses the command with TRB Error.
macOS issues the Set Latency Tolerance Value command at each start and
stop of a USB audio stream whatever HCCPARAMS1 says, and logs
"setLatencyTolerance: completed with result code 5" each time qemu-xhci
refuses it with TRB Error. The refusal is the xHCI specification's
answer for an xHC without the Latency Tolerance Messaging Capability
(LTC, 4.6.14), and qemu-xhci left LTC clear.
An xHC sets LTC where its host interconnect has an LTR mechanism
(4.13.1), as PCI Express does. On a PCI Express bus qemu-xhci now sets
LTC, has LTR in Device Capabilities 2, its enable in Device Control 2
and the LTR Extended Capability, and completes Set LTV with Success,
recording the BELT it carries. On conventional PCI LTC stays clear and
the command keeps failing with TRB Error. No LTR message carries the
BELT on, as nothing in QEMU would receive one.
libusb_set_interface_alt_setting() is synchronous. Under Linux the kernel
holds the device while it kills the interface's transfers, sends
SET_INTERFACE and reconfigures the host controller's endpoints, and
usb-host made the call from the guest's control transfer, holding the
BQL. QEMU's main loop and every vCPU waited out the call: up to 26 ms a
call at each start and stop of an audio stream in a macOS guest, with a
USB/IP audio device.
A worker thread from the thread pool now makes the call, and the guest's
SET_INTERFACE completes asynchronously when it returns, with the alt
setting and the endpoints updated as before. Control requests still
reach the device in the guest's order: one that arrives while a
SET_INTERFACE runs (only after the guest canceled it) waits for it, as
do a guest reset, closing the device and QEMU's exit. A canceled request
still applies its result, which is the device's state.
Both devices' resets clear what raises their interrupts (PL011's
int_level and int_enabled, PL061's istate and im) and leave the lines at
the level they had. An in-kernel GIC (HVF's, KVM's) keeps a level line's
input across its own reset, so an interrupt raised in the last boot is
pending again in the next, with nothing in the device to answer it.
vmapple has both devices: the PL011 as macOS's serial port, the PL061
for the power button.
Each reset now sets its lines from the state it cleared, which lowers
them.
The engine's reset cleared its status, interrupt status and enable and
its watermark, and kept the rest: the FIFO and its index, the flag info,
both key contexts, the IVs, the direction and the block mode, and the
interrupt line's level.
A guest that panics in the middle of a command leaves words of it in
the FIFO. Kept, they become the head of the next boot's first command,
whose misparsed words fifo_process() fails as an invalid command
(REG_IRQ_STATUS_INVALID_CMD, which only its default case sets), and
macOS panics on that: "AppleS8000AESAccelerator::AES Error: IntStatus
0x4" @AppleS8000AES.cpp:1209, in 225 of 378 boots of a macOS 27.2.1
restore OS's panic loop, the first at boot 27, and in 60 of 71 of a
27.0.1 guest's. A first boot never met it.
The reset now clears everything the guest sets, as at power-on, and
lowers the interrupt: the line keeps its level across a reset
otherwise, and an in-kernel GIC (HVF's, KVM's) raises its interrupt
again in the next boot.
HVF's distributor loops (for_each_dist_irq_reg) start at the first SPI,
as the 32 internal IRQs' distributor bits are RAZ/WI under affinity
routing, but they read and wrote from each register group's first
register: GICD_IGROUPR0, ISENABLER0, ISPENDR0, ISACTIVER0, ICFGR0 and
IPRIORITYR0. Each SPI's enable, pending, active and group bits and its
trigger went to the register of the IRQ 32 below it, and the priority
loop paired its fields with the right registers but stopped 32 IRQs
short. The clear half of each set/clear pair was written 0, which
clears nothing.
So a put, which the GIC's reset makes on every guest reboot, left the
last boot's SPI enables, pendings and actives in the GIC. A macOS guest
that panics leaves MSIs pending (its kernel takes no more interrupts),
and the next boot takes each one as soon as it enables its CPU
interface, on whatever its SPI belongs to then. AppleVirtIO took them on
queues it had not set up yet: data aborts reading the used ring's index
through a null ring (far 0x2, AppleVirtIOQueue::handleEvent+0x18), 6 of
378 boots of a macOS 27.2.1 restore OS's panic loop, the first at boot
13, and on 15.6.1 and 27.0.1 guests in theirs.
The loops now skip the internal IRQs' registers and fields, as the KVM
GIC's (kvm_dist_putbmp and its siblings) do, and the clear registers get
all ones, as KVM's get.
A TD one frame late just after the 2048-frame window wraps, and one 100
frames late, run at once; they used to wait 2048 frames. TDs 100 frames
ahead, and 98 frames ahead across the wrap, wait for their frames.
An isoch TD without SIA names its frame by the frame's low 11 bits, a
window of 2048 frames. The controller put the frame in the current window
and moved it one window ahead if that left it more than 32 frames in the
past. So a TD more than 32 frames late, or one frame late just after the
window wrapped, waited 2048 frames, 2.048 s. A guest that queues its TDs a
few frames ahead hits the wrap every 2.048 s once its TDs run late. macOS
schedules each 8 ms block of a high speed audio stream with a Frame ID; the
block after such a TD came 2 s late, macOS reported a 2023 ms delay on the
stream ("safeguardAgainstDelays timeDiff 2023") and restarted it.
A TD is scheduled at most 895 ms ahead (xHCI 4.11.2.5). A frame in the half
of the window behind the current frame is now late, and its TD runs at
once, as a TD up to 32 frames late did; a frame in the half ahead is waited
for.
usb-host held only an IN stream's first packet for its data. After that,
an IN packet that found no completed transfer completed with no data.
That happens whenever the guest's packets catch up with the device:
QEMU's main loop was busy for a few milliseconds and then ran the late
TDs back to back, or a TD's timer ran before the libusb completions that
were already waiting. A device sends a packet at each service interval,
so on hardware the guest never gets these empty packets. macOS counted
one to three of them in many of its 8 ms input blocks, and got empty
packets on an explicit feedback endpoint.
On a controller with iso_nak_retry the packet is now NAKed, and the
transfer's completion wakes the endpoint: the TD completes then, with the
device's data. The guest sees its packets late by as long as QEMU was,
and no longer empty.
A key going down on usb-kbd completes a TD with BEI set: its Transfer
Event is written and IMAN.IP stays clear. The key coming up completes the
next TD, without BEI, which sets IMAN.IP. IMAN.IP used to be set by both.
A key pressed on usb-kbd after Stop Endpoint wakes its interrupt
endpoint. The endpoint stays stopped, and the TD queued on it does not
run, until the guest rings the doorbell; the endpoint used to be running
again and complete the TD.
A device's wakeup kicked its endpoint whatever state the endpoint was in,
and a kick moves the endpoint to Running. usb-host wakes an isochronous IN
endpoint each time one of its transfers completes, so an endpoint the guest
had just stopped with Stop Endpoint was running again before the guest read
its context. macOS reads the endpoint context once the command completes.
Finding the endpoint running, it logs "endpoint did not stop", fails the
pipe's abort with kIOReturnNotReady (0xe00002d8) and the change to
alternate setting 0 with it, and fails the Stop Endpoint commands that
follow ("hardware is unavailable").
Only a doorbell moves a stopped endpoint back to Running (xHCI 4.6.9). A
wakeup, and the kick timer, now kick an endpoint only while it runs.
QEMU raised an interrupt for every Transfer Event, BEI or not. macOS
sets BEI on seven of each eight isochronous TDs of a high speed audio
stream, one per microframe, asking for one interrupt a millisecond. It
got one per TD: 8000 a second for each stream. Each interrupt makes the
guest write the dequeue pointer of every interrupter, a VM exit apiece.
A Transfer Event that a Normal, Isoch or Event Data TRB with BEI set
generates for a completion (Success or Short Packet) is now written
without asserting the interrupt (xHCI 4.17.5). The interrupter's next
interrupt brings the guest to it. Errors still interrupt. A guest that
sets BEI gets the interrupts it asked for. Its events are the same.
Three doorbells rung on an empty isochronous OUT ring give one Ring
Underrun event, where each used to give one. A TD that runs makes the
next empty ring a new condition, reported once again, and a doorbell
after that adds nothing.
When every buffer of an isochronous OUT ring was on its way to the
device, usb-host dropped the guest's next packet and completed it with
nothing sent. On xHCI the guest then saw its OUT TD finish as a short
packet with 0 bytes transferred, which a real controller never reports
for OUT. A high speed audio stream on a USB/IP device lost 384 packets
this way in one run.
On a controller that retries a NAKed isochronous packet
(USBBus.iso_nak_retry), usb-host now answers USB_RET_NAK and keeps the
packet. When the next transfer completes and frees its buffer, it wakes
the endpoint. The guest's TD completes once its data is in a transfer,
paced by the device. On other controllers the packet is still dropped.
A passed-through device sends a packet at each service interval from
the first one, but usb-host gets those packets only as each host
transfer completes. Until then it completed the guest's IN packets with
no data. A real device never sends these empty packets: macOS counted
44 of them on a high speed audio input, where it allows 16, and
restarted the device's streams.
usb-host now answers the stream's first packet USB_RET_NAK until two
transfers have completed. It does this only on a controller that sets
the new USBBus.iso_nak_retry, which says the controller keeps a NAKed
isochronous packet and retries it when the endpoint is woken. xHCI does:
the TD waits in epctx->retry, and each completed IN transfer already
wakes the endpoint. The stream then starts with one transfer of data
already buffered ahead of the guest. On xHCI the guest's first IN TD
completes about two milliseconds later, with the device's data. Every
TD after it completes on its schedule, from that point on. Other
controllers complete NAKed iso packets empty or with an error, so for
them nothing changes. Once the stream has started, an empty ring still
gives an empty packet, so the stream follows the guest's schedule.
An endpoint's isochronous ring had isobufs transfers of isobsize packets
whatever the endpoint's interval and speed, a FIXME assuming one packet
a frame. On a high speed endpoint serviced every microframe a transfer
was 4 ms of the bus, and on one serviced every millisecond, as an
audio device's explicit feedback endpoint is, 32 ms. An IN stream
delivers nothing until its first transfer completes, so the guest's
first packets came back empty for that long: macOS restarted a high
speed USB audio device's streams on "excessive zero length packets",
and its feedback stream read nothing for its first 34 ms.
Size each transfer by the endpoint's bInterval and the device's speed
to one millisecond of the bus, at most isobsize packets, and keep the
ring's isobufs * isobsize packets in as many transfers as that takes.
The ring holds as many packets as before, and an OUT stream still waits
for half of them before it starts; data now moves to and from the
device a millisecond at a time.
Every kick of an isochronous endpoint that found its ring empty posted a
Ring Underrun (OUT) or Ring Overrun (IN) event, a doorbell's kick
included. macOS rings the endpoint's doorbell again on that event, so
once its audio driver stopped queueing TDs, the two fed each other:
13 to 30 events a millisecond on interrupter 0, until its event ring
filled (Event Ring Full) and dropped what came next, command completions
included. A USB audio device on usb-host restarted its streams every
300 to 400 ms, each stop waiting on those events.
Report the empty ring once, when it runs out of TDs, and again only
after TDs were queued and ran out (xHCI 4.10.3.1). A doorbell on a ring
already reported empty posts nothing. A guest sees one event where it
saw one per doorbell.
QEMU never unrealizes the device at its exit, so the library's GPU device
lived to the process's end. On NVIDIA's proprietary driver an exit with a
runtime device live can end with SIGSEGV inside the driver's own exit
handler, which tears its SPIR-V compiler down while a worker thread of the
driver's still runs in it: 6 of 80 exits on an RTX 3090 right after the
device's check of textures over host pages, none with the device dropped
first.
Tear the device down from a VM change state handler once the VM stopped
for good (RUN_STATE_SHUTDOWN from vm_shutdown, after the main loop), with
BAR 2 disabled first, as the library's region goes with the device. The
library's release of its last device then waits, at most 5 s, for the
device's threads and lets go of its GPU devices before the process exits.
None of the device's callbacks takes the BQL, which the handler holds, so
the wait is not held up. A shutdown whose action pauses the VM keeps the
device, which the guest uses again after a reset; its later quit, like a
quit of a VM stopped before it, notifies no handler, and the device stays
to the exit as before. A second teardown, at unrealize, finds nothing left
to undo.
The guest masks the device's MSI-X vector whenever its driver chooses,
and a failure to remove the irqfd notifier there would repeat at each
mask, a line every time. Say it once a process with error_report_once,
as the library says each kind of failure once (docs/conventions.md).
KVM passes a data abort with no instruction syndrome (ISV=0) to QEMU
as KVM_EXIT_ARM_NISV, and QEMU has injected an external abort for
each one. Under HVF, QEMU emulates such accesses. A guest that works
under HVF can therefore fault under KVM.
reims-vgpu's firmware graphics driver for Ambrosia does: its BarSize()
reads a BAR from ECAM with "ldr w9, [x8, #16]!", a writeback form.
Under KVM on an Apple M2 Pro (Linux 6.19.14-400.asahi.fc42), Ambrosia
stopped the boot with
exception 4: ESR 0x96000010 ELR 0x140020a9c FAR 0x40028010
the external abort QEMU injected.
Try arm_emulate_isv0_mmio() in strict mode first. Where the access
reached a device QEMU emulates, the instruction is emulated as under
HVF. Where QEMU has no device at the address, such as KVM's in-kernel
interrupt controller, the access fails, no register changes, and the
guest takes the external abort as before.
Tested: the same boot now finds the device ("reims-graphics at
00:05.0: 1920x1080, framebuffer 0x80400000, registers 0x50000000"),
starts the early console and enters the kernel.
hvf_emulate_isv0_mmio() decodes and performs the loads and stores
that take a data abort with no instruction syndrome (pair, writeback
and SIMD&FP accesses), which macOS guests and their firmware make to
device memory. Nothing in it is HVF's: it synchronizes the vCPU, reads
the instruction with cpu_memory_rw_debug() and accesses QEMU's address
space. KVM needs the same, so move it to target/arm/isv0-mmio.c as
arm_emulate_isv0_mmio().
Add a strict mode for callers whose accelerator emulates devices of
its own. With it, every access is made before any register changes,
and the function returns false, changing no register, if one fails,
as an access to an address with no device in QEMU does. Without it, a
failed access is ignored as before. HVF calls it without strict mode,
so nothing changes for HVF.
macOS on vmapple makes paravirtualized calls for its pointer
authentication keys, SMCCC 0xC1000000 to 0xC10000FF: SET_INITIAL_STATE
when a CPU starts, GET_DEFAULT_KEYS, SET_B_KEYS on context switches,
and the EL0 diversifier calls. None is implemented anywhere. HVF and
TCG answer each with NOT_SUPPORTED in x0 and change no other register.
KVM answers with NOT_SUPPORTED too, but through smccc_set_retval(),
which also writes zero to x1, x2 and x3.
macOS keeps x1 to x3 of some of these calls whatever x0 says; XNU
records x3 of GET_DEFAULT_KEYS as its default JOP PID, for one. Under
KVM it gets zero where HVF and TCG leave the caller's value, and user
space then fails pointer authentication: a macOS 27.2.1 guest on an
Apple M2 Pro (Linux 6.19.14-400.asahi.fc42, FEAT_FPAC) killed launchd
right after dyld mapped the shared cache's authenticated GOTs, with
EXC_ARM_PAC_FAIL (ESR class 0x1C, an FPAC trap from EL0):
[launchd:1] FATAL exception: type=0x1 reason=0x1c code=0x105
panic(...): initproc failed to start -- exit reason namespace 28
subcode 0x105
The guest's APCTL_EL1 on that host has AppleMode clear (0xc, read
through APCTL_EL12 on every core), so Apple's key diversification is
not involved.
Have KVM pass the whole range to QEMU and answer as HVF and TCG do:
NOT_SUPPORTED in x0, every other register as the caller left it.
These calls come on every context switch, so the handler sets x0
alone, with KVM_SET_ONE_REG, without taking the BQL or synchronizing
the vCPU's state.
Tested with that guest under KVM with -smp 4: launchd runs ("System
Integrity Protection is engaged") and user space continues to boot.
For an SMCCC call it does not implement, KVM answers NOT_SUPPORTED
through smccc_set_retval(), which also writes zero to x1, x2 and x3.
TCG's PSCI code and HVF write x0 only. A guest that keeps x1 to x3 of
such a call behaves differently under KVM.
Add kvm_arm_forward_smccc_range(), which has KVM pass a range of
function IDs to QEMU (KVM_SMCCC_FILTER_FWD_TO_USER). The hypercall
exit handler answers any call other than PSCI CPU_ON with
NOT_SUPPORTED in x0 and leaves every other register as the caller left
it. Such calls may come often, on every context switch for the one
user, so it writes x0 alone with KVM_SET_ONE_REG, or into env when
QEMU holds the vCPU's state, without taking the BQL.
No board calls it yet, so nothing changes.
A vCPU thread started at the default QoS, the class a build, or any other
CPU-bound process the user starts on the host, runs at. A vCPU running the
guest's work is then one CPU-bound thread among the build's and gets its
share like each of them, so a guest beside a build runs on a fraction of a
core. On an M3 Max (16 cores), an arm64 macOS 27.0.1 guest on Ambrosia beside
64 spinning processes had its own timers fire up to 1.9 s late, and a
full-screen Metal app in it presented 22 frames a second where it presents
60 alone; a sleeping host thread on a 60 Hz grid kept its ticks throughout,
so the loss was the vCPUs' share alone.
Each vCPU thread now asks for the user-initiated QoS as it starts: above
the default QoS, so the guest keeps its CPU beside the host's builds, and
below the user-interactive QoS of the host's own interface, so a busy guest,
or several, cannot take the CPU from the host's desktop. HVF is built only
on macOS, so no other host changes.
Two CPU properties that a macOS guest on vmapple needs under KVM had
to be given on the command line, as -cpu host,pmu=off,
kvm-psci-version=1.1. Set them on vmapple's CPUs instead.
vmapple does not initialize KVM's PMU, and KVM refuses to run a vCPU
that has the PMUv3 feature without it: with -cpu host the first
KVM_RUN fails with "kvm run failed Invalid argument" at the firmware's
entry. macOS's ApplePSCI driver accepts PSCI 1.1, which HVF reports,
and rejects the 1.3 that current kernels give by default ("ApplePSCI -
[ERROR] unsupported PSCI version 1.3"), leaving the secondary CPUs
unstarted.
This replaces a user's own pmu or kvm-psci-version setting on vmapple,
as no other value boots macOS there.
vmapple sets cpu-on-copies-pauth-keys so that every CPU the guest
starts runs on the boot CPU's pointer authentication keys, which the
boot firmware sets on the boot CPU only. Under KVM, PSCI CPU_ON is the
host kernel's, the copy never happens, and each secondary starts on
the keys KVM resets it to.
A macOS 27.0.1 guest on vmapple under KVM (Apple M2 Pro, Linux
6.19.14-400.asahi.fc42, -smp 4) then fails as c9126183 describes for
HVF. CPU 3 held APIAKEYLO/APIBKEYLO/APDAKEYLO_EL1 0x1de7ec7edbadc0de,
KVM's reset value, while CPU 0 held the firmware's keys. CPU 3
returned through a PAC-corrupted LR (0xe481fe00234aca10), took an EL1
data abort (ESR 0x96000047) and halted, with the other CPUs spinning
behind it.
With -smp 2 or more under KVM, have KVM pass CPU_ON to QEMU, so that
the CPUs start through arm_set_cpu_on() and take the boot CPU's keys.
A host kernel without the SMCCC filter is an error then, since the
guest's secondaries would fail.
Tested with a macOS 27.2.1 guest under KVM with -smp 4: all four CPUs
hold the same APIA, APIB, APDA and APGA keys (read through the
gdbstub), and the guest roots, grafts its cryptexes and starts
launchd. With -smp 1 no filter is installed.
Under KVM, PSCI is served by the host kernel, and a CPU it powers on
starts from KVM's reset state. arm_set_cpu_on() never runs, so CPU
properties that act there, such as cpu-on-copies-pauth-keys, have no
effect under KVM.
Add kvm_arm_forward_psci_cpu_on(), which installs a VM-wide SMCCC
filter (KVM_ARM_VM_SMCCC_FILTER, Linux 6.4) with the action
KVM_SMCCC_FILTER_FWD_TO_USER for the two CPU_ON function IDs, SMC32
and SMC64. KVM then exits to QEMU with KVM_EXIT_HYPERCALL for those
calls only, and keeps serving every other PSCI call itself.
The exit handler reads the arguments from the caller's registers (arm
KVM does not fill kvm_run.hypercall.args), starts the target through
arm_set_cpu_on() as TCG and HVF do, and returns the PSCI result in x0.
KVM has already moved the PC past the HVC or SMC.
arm_set_cpu_on() resets the target and gives it its entry state in
env, which KVM has not seen. A second piece of work, queued behind it
while the BQL is held, hands KVM the whole state with
cpu_synchronize_post_reset(), which also makes the vCPU's KVM_MP_STATE
runnable. Because KVM still serves CPU_OFF, a target that QEMU last
saw on is synchronized first, so that its power state is current
before arm_set_cpu_on() checks it.
The probe asks KVM_HAS_DEVICE_ATTR on the VM directly rather than
through kvm_vm_check_attr(): arm64 KVM answers it without reporting
KVM_CAP_VM_ATTRIBUTES, which kvm_vm_check_attr() requires. On Linux
6.19.14-400.asahi.fc42, KVM_CHECK_EXTENSION(KVM_CAP_VM_ATTRIBUTES)
returns 0 while KVM_HAS_DEVICE_ATTR for the filter succeeds.
No board calls it yet, so nothing changes.
The library's config now carries the guest's architecture (guest_arch,
RVG_GUEST_ARCH_X86_64 or RVG_GUEST_ARCH_ARM64), which decides the device's
isFramebufferReadSupported answer: the host GPU's for an arm64 guest, as an
Apple silicon Mac answers, and no for an x86-64 guest, as an AMD Mac
answers. CoreAnimation in an arm64 guest blends its generic shader against
a destination it reads by framebuffer fetch, which it compiles in by that
answer, so with no it drew the menu bar black.
The device is target-independent code, so it asks the target at run time:
target_aarch64() names an arm64 guest, and every other target an x86-64
one, as before.
On macOS the device passed the library no RAM map: HVF's guest RAM is the
process's private anonymous memory, with no file behind it, and the device
gave only ranges with a shared file. So the GPU copied every IOSurface of
an arm64 guest on a Mac, and WindowServer spent most of its updates
merging no-copy buffers' shadows.
The library makes its views on macOS by mach_vm_remap of the process's own
mapping, which needs no file, and a view so made shares the pages HVF maps
into the guest, both ways (measured on the M3 Max: a guest write is seen
through the view, and a write through the view by the guest). On macOS
give it every RAM range in pages of the host's size, with an fd of -1.
Linux is unchanged: only ranges with a shared file go in.
The library uses a surface in place on a host of 16 KiB pages only where
the guest lays its pages out in whole 16 KiB pages (its PAGES_16K feature,
which the arm64e kext takes), so an x86-64 guest on a Mac goes on copying.
The device gave the library the guest's RAM map only when every RAM range
of the machine's address space had a shared file behind it, and otherwise
passed no map, so the GPU copied every IOSurface. The vmapple machine has
two small RAM regions with no file (the 1 MiB firmware and the 64 KiB
config, each made by memory_region_init_ram, with no command-line option to
back them), so even with the guest's main RAM a shared memfd the device fell
back to copying every surface.
Give the library only the ranges that have a shared file in pages of the
host's size, and leave out those that do not. The library views a surface
whose pages lie in a mapped range in place and copies one whose pages fall
outside the map, as it copies every surface without a map; it already
resolves such a partial map (an address in no range is a copy). IOSurfaces
live only in the guest's main RAM, which a shared memfd backs, so in
practice every surface is used in place. A machine whose RAM is all
file-backed (q35 with -object memory-backend-memfd,share=on) is unchanged:
every range has a file, so the whole of RAM is mapped as before.
This keeps QEMU's own machines untouched and covers any machine with a small
unbacked RAM region, vmapple among them.
On vmapple the guest has no GPU driver without our arm64e kexts, so it makes
no IOSurface and the device makes no view there yet; arm64 in-place views
wait for the arm64e kext build.
The guide said the firmware adds a /filesystems node with DoNotUseSEP for
macOS 15 and later. Ambrosia stopped adding it: on the device tree it
writes, APFS mounts each volume unencrypted without the node on every
tested build. The firmware now makes one change before entering the
kernel, the PAC nop pass.
The comments on VMAppleCfg put scratch at 0x180 and the strings from 0x380,
but cpu_ids is 0x200 bytes from 0x100, so scratch starts at 0x300 and the
strings at 0x500: serial at 0x500, model at 0x540 and soc_name at 0x584,
which is where the guest firmware reads them. Comments only.
The comment on the SME default said HVF's max CPU has no "sme" property.
It does: HVF adds it as the vCPU starts, and on an M3 it reads false. That
happens after the machine's defaults apply, so the optional default skips
it, and HVF's CPU keeps whatever SME the host gives, on an M4 too. Say so.
Comment only.
Under TCG the machine's max CPU offers SME, with streaming vectors of up to
2048 bits. As a macOS 14.6.1 kernel starts, it creates the zone for each
thread's SME state, sized from the longest vector at (SVL + 34) * SVL + 88
bytes. With 256-byte vectors that is 74328 bytes, more than a zone's element
may be, and the kernel panics with "zone_create: element size too large:
74328" right after "mig_table_max_displ". macOS 15.6.1, 26.6.2 and 27.0.1
boot with SME on. With -cpu max,sme=off, 14.6.1 boots under TCG and
answers SSH.
Make SME off the default for the max CPU on this machine, as an M1 to M3
under HVF has none. The default is optional, since under HVF the max CPU
has no "sme" property, and -cpu max,sme=on still turns SME on.
On every boot of a macOS guest on this machine, timed logs "Could not get
mib for kern.monotoniclock_offset_usecs" and "Current RTC offset is zero.
RTC reset likely.", then sets the clock back to the last write to the
guest's disk, by minutes or hours, until it reaches a time server. Without
a network the clock stays wrong. macOS's PL031 driver keeps no offset to
calendar time. Virtualization.framework's machine has a second clock at
0x30240000, avp-rtc in the guest's device tree, which macOS 14 and later
drive with AppleVirtualPlatformRTC. That driver reads a 64-bit counter of
microseconds, keeps the offset from it to calendar time in NVRAM
(com.apple.System.rtc-offset), and gives the offset to timed. The offsets
Virtualization.framework's guests stored are tens of milliseconds, so its
counter counts calendar time.
Add the device, vmapple-rtc. Its counter counts microseconds of the rtc
clock from the Unix epoch, as the PL031 counts seconds, so -rtc applies to
both. Its control and interrupt-enable registers read back what was
written, and its interrupt status reads zero. Its ID register reads 0xf001,
the value on which Virtualization.framework's iBoot keeps avp-rtc in the
device tree and drops the PL031. Nothing on the machine raises the driver's
interrupts, so the device has no interrupt line. The PL031 stays, and the
firmware picks which clock the guest gets.
With a firmware whose device tree gives the guest avp-rtc in place of
pl031-rtc, and an offset in NVRAM, 14.6.1, 15.6.1, 26.6.2 and 27.0.1 guests
under HVF have the offset sysctl and log no "RTC reset". Booted twice with
a network and once without, each came up within 0.32 s of the host, and
timed stepped its clock by at most 1.9 s. The exception was a 14.6.1 guest
whose timed had saved a time 214 s off in earlier boots and applied it on
each boot until a time server answered. With that state gone, it stepped by
0.9 s and, without a network, came up within 0.05 s of the host. With -rtc
base= a day ahead and no network, the guests came up a day ahead, less up
to 5.2 s of drift that timed had estimated. 12.6 and 13.6 have no driver
for the device and boot as before. A traced boot of 27.0.1 makes only the
accesses the driver's code does: 64-bit reads of the counter, CTRL set to
1, the interrupt enables set to 0 and then 6, and every interrupt cleared.
The library no longer asks whether the guest wrote its scanout: its window
draws the scanout again at each of the display's refreshes while it shows
no presented surface, and a presented surface is drawn by the guest's
presents alone. The scanout shows only at boot and in recovery, where its
full cost buys a simpler device.
BAR 2 is now one RAM region over the library's mapping, with no dirty
logging, in place of two (the rings and the allocations) split only so
that the log covered the allocations; the scanout_written callback, which
took the BQL to snapshot and clear that log, is gone with the C API's
field.
About one boot in four to six of a macOS 27.0.1 or 26.6.2 guest never comes
up on the network. In each, configd logs "en0: clearing IPv6 state on first
launch" and nothing more: DHCP never starts, and the TX queue's used index
stays 0. The control queue shows that QEMU took the guest's first control
command and signalled its completion (used_idx 1, signalled_used 1,
last_avail_idx 1), and the guest never woke for it. QEMU completes a control
command inside the guest's queue-notify MMIO exit, so the interrupt likely
comes before macOS's driver waits for it, and the driver misses the wakeup.
With -global virtio-net-pci.ctrl_vq=off, none of 20 boots of 27.0.1 under
HVF hung, against 4 in about 40 without it.
Make the machine's virtio-net devices offer no control queue, nor the
features that need one, so that a plain -device virtio-net-pci gets this.
macOS doesn't need the queue: without it, the device stays promiscuous, as
it resets, and passes the guest every frame QEMU's user network delivers.
With this commit and no flag, all of 20 boots of a 27.0.1 guest on Ambrosia
under HVF came up and answered SSH, 8 to 12 s after QEMU started.
As its platform expert starts, macOS's AppleVirtualPlatform driver reads
configuration register 1 by DMA: it writes the physical address of a request
to 0x004ffff8, an address its code holds rather than one the device tree
gives, and goes on without the register when the request comes back
unanswered. Virtualization.framework's machine answers it; this machine has
no device there. Under HVF the write is dropped, since hvf.c does not inject
the error. Under TCG it is a synchronous external abort (ESR 0x96000050),
and a 27.0.1 kernel panics on it: its handler for an implementation-specific
error reads Apple's error status registers, which TCG does not model, and
the panic reads "Undefined kernel instruction ... instr=d53ef008".
Map an unimplemented device over the doorbell, so that the write is ignored
under both accelerators and -d unimp logs it. Under HVF the guest sees no
change. With it, and a firmware whose device tree has no avp-ctrr node, a
27.0.1 guest boots under TCG to SSH with System Integrity Protection
enabled, and from power-on to shutdown makes no other access to an address
with no device.
The machine needed HVF only for the kernel-entry hook, which is gone: the
guest's firmware makes macOS's kernel-entry changes itself. Without HVF the
machine can run under TCG on hosts that are not Apple silicon, such as
x86-64 Linux. Three things kept it from that:
- Kconfig made VMAPPLE depend on HVF. It now depends on AARCH64 and on TCG
or HVF, and is built by default.
- The default CPU type was host, which TCG does not have. It is now max,
which is the host CPU under HVF, so nothing changes there.
- TCG's generic timer counts at 1 GHz. macOS's device tree gives every CPU
a timebase-frequency of 24 MHz, the frequency of Apple silicon's system
counter, which HVF passes through. Under TCG the machine now sets each
CPU's cntfrq to 24 MHz, so the guest's clock keeps the host's time.
Under TCG, macOS's pointer authentication calls (SMCCC 0xC1000000 to
0xC10000FF over HVC) reach QEMU's PSCI code, which answers them as not
supported, as Hypervisor.framework does under HVF. A 27.0.1 guest makes
SET_INITIAL_STATE (0xC1000000) on each CPU, GET_DEFAULT_KEYS (0xC1000001)
and PAC_NOP (0xC10000F0) as it starts, then 0xC1000003 and 0xC1000005 by
the hundred thousand as it runs. So the guest needs the same firmware under
both, and the comment on cpu-on-copies-pauth-keys and the docs say so.
macOS places every PCI BAR below 4 GiB, 64-bit prefetchable ones included:
its PCI configurator clears the flag that lets a 64-bit BAR go higher
before it assigns any. A BAR is aligned to its size, and with RAM at
0x70000000 no 1 GiB-aligned gigabyte below 4 GiB was free, so a device
with a 1 GiB BAR, such as a GPU's VRAM aperture, got no address. A second
window above RAM does not help: on a macOS 26.6.2 guest, a 1 GiB 64-bit
prefetchable BAR stays unassigned with a window at 0x800000000 offered.
RAM now starts at 4 GiB, and the PCIe MMIO window runs from 0x50000000 up
to it. With a firmware that gives the guest this window and RAM base,
Ambrosia, the same guest boots with the 1 GiB BAR at 0x80000000 and the
rest of the bus, its boot disk included, where it was.
AVPBooter no longer boots on this layout: it keeps its stack at 0x70053ff0
and faults on its first store there. This breaks no product path: since
2026-11-07 the project's tools and boots no longer start arm64 guests with
AVPBooter, and Ambrosia is the firmware for this layout. The docs now say
that the machine needs such a firmware, and what it does for macOS.
This reverts the kernel-entry hook of "hw/vmapple: boot macOS 14 and
later guests" (e1c37ea4): RAM that is not executable from reset, the
hvf_arm_exec_fault hook that catches iBoot's jump into the kernel, and the
two changes made there, the PAC-spin nops and /filesystems/DoNotUseSEP.
A firmware that enters the kernel itself, as Ambrosia does in place of
AVPBooter and iBoot, makes both changes before the jump, so the machine
needs no hook at kernel entry and can run under any accelerator. On this
commit, a 27.0.1 guest boots on Ambrosia to launchd with SIP engaged.
AVPBooter now boots only macOS 12 and 13 guests, as the docs say.
apple-gfx is gone from this tree, and with it the machine's display,
apple-gfx-mmio, so vmapple has not been built since: its Kconfig depends on
MAC_PVG, which nothing sets now, and configs/devices/aarch64-softmmu leaves
it out. A guest does not need the display to boot. macOS runs without one,
on its serial console, and its firmware need not drive one.
Take the display out of the machine: create_gfx, its two MMIO regions at
0x30200000 and 0x30210000 and their two interrupts, and the machine's
dependency on MAC_PVG and MAC_PVG_MMIO. Nothing else uses those two
symbols, so drop them too. Build vmapple by default again wherever HVF is,
as before apple-gfx went.
The docs drop apple-gfx's display section and the build prerequisite it
needed, and name the one the machine still has: a crypto library, whose
AES ciphers the AES engine runs on.
reims-vgpu drops Apple's paravirtualized graphics: the guest's GPU is the
reims-graphics device alone, which its own kexts drive. Remove the devices
that served Apple's guest drivers, and what only they used:
- apple-gfx (apple-gfx.c/.h, apple-gfx-pci.c, apple-gfx-mmio.c and the App
Nap hold, apple-gfx-activity.m and its stub), with the IOSurface device,
apple-gfx-iosurface-pci, which apple-gfx-pci.c held;
- apple-videotoolbox-pci and apple-m2scaler-pci, the paravirtual
VideoToolbox and M2 scaler devices;
- their trace events, their Kconfig symbols (MAC_PVG_PCI, MAC_PVG_VIDEO_PCI,
MAC_PVG_SCALER_PCI), the Foundation dependency and the install of
apple-gfx-pci's option ROM (ReimsVgpu.rom), and apple-gfx's MAINTAINERS
entry;
- the KVM dirty source apple-gfx gave the library: kvm_dirty_log_for_each_slot,
CPUState.kvm_run_seq and physical_memory_take_dirty. reims-graphics-pci
logs its allocations through the memory API, as before.
The meson option that finds reims-vgpu is now reims_vgpu
(--enable-reims-vgpu), not pvg, upstream's name for Apple's framework.
reims-graphics-pci is built as before wherever the library is found, and
behaves as before; only two of its comments that cited apple-gfx change.
vmapple stays in the tree but is not built: its display was apple-gfx-mmio,
and its Kconfig depends on MAC_PVG, which nothing sets now.
configs/devices/aarch64-softmmu/default.mak leaves it out again
(CONFIG_VMAPPLE=n, as upstream has it), and MAC_PVG and MAC_PVG_MMIO stay
defined for its Kconfig. docs/system/arm/vmapple.rst says so.
The device's window opened at 1920x1080, then kept the size the person gave
it. The library opens it at the size its window config's mode names, which
the device left 0x0. The resolution property, "<width>x<height>", now names
that size; without it, the window opens at 1920x1080 as before.
Anees Iqbal
hello@aneesiqbal.ai
The library now gives the region as a shared mapping of a memfd of its own
on Linux, which RADV imports through dma-bufs, and as private anonymous
memory on macOS. The device's comment said private anonymous memory on
every host. A comment only.
ppm_save wrote each row with the stride of its PIXMAN_BE_r8g8b8 line
buffer, which pixman rounds up to 4 bytes. A display whose width is not a
multiple of 4 so gave rows of width * 3 bytes and 1 to 3 bytes of padding,
where a PPM's rows are width * 3 bytes: each row started 1 to 3 bytes
after the one before, and the image read back sheared, by 2/3 of a pixel a
row at a width of 3662, its colour channels rotating from row to row and
the padding showing as a dark diagonal seam.
It now writes width * 3 bytes a row, as png_save does. The new qtest
dumps bochs-display at widths of 64, 66 and 67 pixels and checks the PPM's
length and every pixel.
The console had the display's pixels, read back from the library, but
never a cursor: the device called neither qemu_console_set_cursor nor
qemu_console_set_mouse. QEMU's own displays (SPICE, VNC, GTK, D-Bus) so
drew no cursor for a macOS guest on the device, whose kext gives
WindowServer a hardware cursor and draws none into the frame, though the
pointer still moved the guest's cursor.
The library now tells the device the guest's cursor on its display thread
(cursor_glyph, cursor_show, cursor_move of RvgGraphicsCallbacks), and each
is queued, as the window's input is, for the BH. It makes a QEMUCursor of
each glyph, with its hot spot, and sets the console's cursor place and
whether it shows. The library gives the hot spot's place
(rvg_graphics_device_cursor_position); the console takes the image's
top-left corner, as virtio-gpu gives it, so the hot spot is taken off.
Under -display none the console has no display, and the window shows the
cursor as the host's pointer, as before.
macOS lays every 64-bit prefetchable BAR out below 4 GiB, and BAR 2's
1 GiB needs that window to start at or below 1 GiB, so the device needs
-machine max-ram-below-4g=1G on a PC machine. Without it q35 keeps 2 GiB
of RAM below 4 GiB, the guest gives the BAR no address, and the kext finds
no region: the guest boots on the firmware's framebuffer with nothing said
on the host.
Realize now warns, naming the option, where a PC machine (one with the
max-ram-below-4g property) has RAM at 1 GiB. It warns rather than fails:
the device itself works, and only macOS's layout leaves the BAR out.
The console carried the window's input only, with empty GraphicHwOps, so
QEMU's own displays showed nothing of the device and QMP's screendump was
always the console's empty 640x480 placeholder, whatever the guest showed.
Boot checks of the guest's screen had to read the scanout out of QEMU's
memory, which stops showing the screen once WindowServer presents
IOSurfaces.
gfx_update now reads what the display shows back from the library
(rvg_graphics_device_read_display): the scanout or the presented IOSurface,
through the display's colour, at the display's mode. The read runs on a
thread of the device's pool, never under the BQL, since it waits for its
draw on the GPU; a BH copies the pixels into the console's surface, made
again when the mode's size changes, and says the update is done. One read
runs at a time, and an update that comes while one is under way is done
with it, as apple-gfx's renders are. The teardown ends the pool, so a
read under way finishes before the device is released.
BAR 0's writes go to rvg_graphics_device_mmio_write_taking again. It
writes every register as rvg_graphics_device_mmio_write does. For a
DOORBELL write of a command queue's ring, the library may answer the
queue's next command buffer on the writing vCPU, where nothing need be
waited for. It posts the buffer's CB_SUBMITTED and raises its interrupt
there, before the write returns. The buffer stays on the ring, and the
queue's thread takes, walks and commits it, as before. Where anything must
be waited for, the write only wakes the queue's thread.
This differs from the take that 67cc08ad reverted. The vCPU now only
tries locks, copies the message onto its stack and allocates nothing,
where each take cost 15 us at the median and some purged pages, up to
340 us. It also no longer takes the buffer off the ring.
The raise on the vCPU writes the vector's irqfd or schedules a BH. Neither
waits for a lock, and the BAR 0 region is lockless, so no BQL is held
across the call. The library raises after it writes the completion ring,
on the same thread, so the guest still takes the interrupt after it sees
the event.
This reverts f2c7e2a5: BAR 0's writes go to rvg_graphics_device_mmio_write
again, and a DOORBELL write of a command queue's ring only wakes the
queue's thread. The vCPU no longer takes the queue's next command buffer.
Measured on msi under KVM at the reims-vgpu effort tip, in same-run A/B
boots (the take switched on and off every 20 s):
- WindowServer's frame commits (every commit inside its compositing) all
ride one queue, and 86% of their doorbells could not be taken: a
control-ring message published before them was not carried out yet;
- the frames' composite time did not move at its median (442 against
435 us), and its mean moved either way from run to run;
- each take cost the vCPU 15 us at the median, and the library's
allocator purged pages (madvise) inside some of them, up to 340 us.
The commits of WindowServer's other queue did gain (to 115 from 205 us at
the median), but they are not on the frame's path.
The comment on the library's callbacks now says what the library's API
promises: they run with no lock held that a call of ours waits for, and
scanout_written with none of the library's.
BAR 0's writes now go to rvg_graphics_device_mmio_write_taking. It writes
every register as rvg_graphics_device_mmio_write does. For a DOORBELL write
of a command queue's ring, the library may take the queue's next command
buffer on the writing vCPU, where nothing need be waited for. Its
CB_SUBMITTED is then posted and its interrupt raised there, before the
write returns, with no wait for the queue's thread to wake. That thread
still walks and commits the buffer. Where the take must wait for anything,
the write wakes the queue's thread as before.
The raise on the vCPU writes the vector's irqfd or schedules a BH. Neither
waits for a lock, and the BAR 0 region is lockless, so no BQL is held
across the call. The library raises after it writes the completion ring, on
the same thread, so the guest still takes the interrupt after it sees the
event.
This changes only which thread posts a buffer's CB_SUBMITTED and when, a
change the contract leaves free: the events of each queue keep its order.
Where the accelerator injects MSI-X through an irqfd (KVM's in-kernel
irqchip), the library's raise now writes the vector's irqfd, and KVM injects
the interrupt from the raising thread. Elsewhere (HVF, TCG) it still
schedules a BH, whose msix_notify waits for the main loop. Under KVM that
wait was 36 us on average, and 115 to 165 us at p95, in every round trip of
a command buffer's CB_SUBMITTED.
The irqfd is set up while MSI-X is enabled, as ivshmem's is, and the guest
sees what msix_notify gives it: a raise while the vector is masked becomes
its pending bit, and one while MSI-X is disabled is dropped.
This changes only which thread injects the interrupt, a change the contract
leaves free. The irqfd's write follows the library's write of the completion
ring on the same thread, so the guest still takes the interrupt after it
sees that write, as it did through the BH: the order of interrupts relative
to guest-visible writes is unchanged.
This reverts commit 2243023e05.
The library no longer takes a dirty source for the graphics device: with it,
resolving the guest pages behind each IOSurface's import cost the device's
thread about 5 ms a command buffer, and WindowServer's composites fell from
42 to 28 a second on a discrete GPU. The graphics device's config is at its
second version again, which this file passes.
Under KVM, with the guest RAM map, give the graphics device the dirty source
apple-gfx gives: the VM's fd and the same four callbacks. The library's
Vulkan runtime keeps a render target over an IOSurface's guest pages as a
shadow, copied in before each use; with the source it copies again only the
pages the guest wrote, where it copied the whole surface at every composite.
The device's migration blocker keeps migration from clearing the log.
The library maps an IOSurface's own guest pages for the GPU in place when it
has the guest's RAM map and the memfd behind each range, as apple-gfx-pci
gives it. Without them (RAM that is not a shared memfd in pages of the
host's size) each surface's GPU view stays a copy, with a warning.
The GPU device of reims-vgpu's own guest driver for x86-64 macOS guests, PCI
1234:5247, class 0x0380, a device Apple's paravirtualized graphics kext never
matches. Its host side is the library's graphics device
(rvg_graphics_device_*); this is its transport:
- BAR 0, 4 KiB: the library's 32-bit registers, with the MSI-X table and
PBA from 0x800 and one vector. A write of the control ring's id to
DOORBELL is taken by an ioeventfd, whose file the library's control
thread polls, so ringing never runs the library on the vCPU.
- BAR 2, 64-bit and prefetchable: the library's region, private anonymous
memory of QEMU's process, as two RAM regions over the one mapping, the
control rings and the guest's allocations. Only the allocations are
dirty-logged: the scanout lies there, and the rings' constant writes
would otherwise be logged too.
- The library's callbacks run on its threads with none of its locks held:
an interrupt is raised by a BH, and scanout_written takes the BQL to read
and clear the allocations' dirty log, so the window presents the scanout
only when the guest wrote it.
Under -display none the library opens a window for the display, unless
REIMS_VGPU_WINDOW is "0", as apple-gfx does; its input reaches the guest
through the device's console, queued for a BH as apple-gfx's is. The device
has no default option ROM.
CONFIG_REIMS_GRAPHICS is set for every target when the library is found,
not only the HVF and KVM ones MAC_PVG is limited to: the region is plain
memory the guest maps, so an x86-64 guest under TCG on a Mac may have it.
QEMU maps anonymous guest RAM at QEMU_VMALLOC_ALIGN (2 MiB on Linux
x86-64 and arm64) so transparent huge pages can back it, and KVM can
map it 2 MiB at a time. RAM from a file of base pages, such as
memory-backend-memfd's shmem, got only the base page's alignment, and
the kernel puts a huge page only where the mapping's address keeps the
file's offset in one: with shmem_enabled at advise, as CachyOS ships it,
and QEMU's MADV_HUGEPAGE, a memfd-backed guest still ran on 4 KiB pages
alone.
Align such RAM to QEMU_VMALLOC_ALIGN too. Measured with a 16 GiB macOS
guest on an RTX 5080 laptop: KVM maps about 10 GiB of it at 2 MiB (none
before), and the vCPUs' time a frame falls by 6-7% in two workloads at
the same frame rate.
On a discrete GPU, and on an iGPU whose driver cannot reference the guest's
RAM, reims-vgpu's runtime copies the guest's resources into GPU memory, and
without a dirty source it copies each one whole at each use. Under KVM the
library now reads the dirty log of the guest's RAM itself, on the VM's fd,
from a thread of its own, and copies again only the pages written since its
last copy. apple-gfx gives it the VM's fd and four callbacks, none of which
takes the BQL, which MMIO handlers that wait on the library hold:
- start logs the machine's RAM for DIRTY_MEMORY_VGA, in a BH, at the
library's first harvest: KVM maps a logged slot 4 KiB at a time, so a
guest whose library never asks keeps its huge pages;
- flush_vcpus kicks each vCPU inside KVM_RUN once and waits until it has
left it, which drains Intel's page-modification log: KVM_GET_DIRTY_LOG
kicks the vCPUs in guest mode but does not wait for them, so a write made
before the read could reach the bitmap after it. CPUState.kvm_run_seq is
odd while the vCPU thread is inside KVM_RUN;
- for_each_slot passes each slot that logs dirty pages, in every address
space, to the library's rvg_dirty_slot, under the slots' lock
(kvm_dirty_log_for_each_slot), so no slot changes while the library runs
KVM_GET_DIRTY_LOG and KVM_CLEAR_DIRTY_LOG on it;
- take_host_writes hands over QEMU's own DMA into the RAM, such as the M2
scaler's output, which KVM's log never sees, from the DIRTY_MEMORY_VGA
bitmap a word at a time (physical_memory_take_dirty), leaving KVM's log
to the library.
The library's thread is unknown to QEMU's RCU, so the callbacks that read
RCU-protected state register it once per call. The device blocks
migration, so nothing else clears the RAM's log. Without KVM's initially-set
manual protection, with the dirty ring, under global dirty tracking, or with
pages other than 4 KiB, the device gives no source and the library copies
whole, as before.
The AES engine runs the guest's DATA commands on QEMU's ciphers. Since
crypto/cipher.c fell back to cipher-stub.c.inc, a build that finds no
crypto library (gnutls, nettle or libgcrypt) has no AES: qcrypto_cipher_new
fails, the DATA command fails and stays at the head of the FIFO, and so does
every command after it. Nothing tells the guest.
A macOS 26 guest sends one as it mounts its root volume: builtin key 3,
AES-256-CBC, 16 bytes, after about 760 reads of the root disk. It then
waits for that command forever. iBoot's serial output ends at "End of
iBootStage2", every vCPU idles in WFI with its timer still firing, and
the display never gets a mode. With -d guest_errors, QEMU logs "cmd_data:
Failed to create cipher object". Measured on an M2 Pro on macOS 27.2 with a
QEMU built against a Homebrew that had none of the three libraries. The
same guest boots on an M3 Max whose QEMU links gnutls.
Check at realize that AES-128, -192 and -256 work in ECB and CBC mode, the
key lengths and modes the engine's KEY command can select. Without them,
fail to realize with an error that says what the build lacks, so QEMU
exits at start instead of the guest hanging.
A macOS guest hands its VideoToolbox sessions and its IOSurfaceAccelerator's
scaling and conversion to the host through two virtio-PCI devices, 106b:1a03
and 106b:1a0b, as Virtualization.framework gives them. These are their
transports, on reims-vgpu's video device (rvg_video_device_*) and scaler
device (rvg_scaler_device_*), beside apple-gfx.
apple-videotoolbox-pci:
- modern virtio only, no device features and no device configuration,
MSI-X with a vector per queue and one for the configuration, and the
capabilities linked in ascending address order, as vmapple-virtio-blk-pci
links them;
- queue 0 carries the guest's messages, 1024 descriptors deep so that an
x86_64 guest's largest message, 0x200000 bytes on 4 KiB pages, fits: each
element's readable part, gathered across its descriptors, goes to the
library, and the status it answers is scattered into the writable part,
little-endian; a writable part under 4 bytes gets none;
- a readable part over RVG_VIDEO_MAX_MESSAGE_SIZE (16 MiB) is answered
RVG_VIDEO_ALLOCATION_FAILED from its descriptors' sizes, before anything
is allocated or copied, as rvg_video_device_deliver answers such a
message: a guest's 1024 descriptors, each up to 4 GiB, can add up to many
times the host's memory;
- queue 1 carries the host's: the library's messages, which come on its own
threads, wait in a ring and fill the guest's buffers as it posts them; a
message longer than the buffer ends QEMU, as Apple's host ends the VM;
- DRIVER_OK starts the library's host session, and a reset ends it.
apple-m2scaler-pci:
- the same transport with one queue; each element's readable part, up to
64 KiB, is copied into one buffer, which the library answers in place;
a larger element, or a refusal, sets DEVICE_NEEDS_RESET with no reply,
and an abort of Apple's host ends QEMU;
- the guest memory a request names is reached through the device's DMA
address space, and only where it is RAM, through MemoryRegionCaches, so
what is checked as RAM is what is copied;
- DRIVER_OK makes the library's accelerator, a needs-reset where it cannot,
and a reset drops it;
- it realizes on every host. Where the library's device does not scale
(rvg_scaler_device_scales), validate_features refuses the guest's
features with -ENOTSUP, traced as apple_m2scaler_features_refused, so
FEATURES_OK does not stay set: the guest's driver reads its status back,
gives its start up before DRIVER_OK, and the guest does without the
device, as in a VM without it.
Both answer each element on a worker thread of the device's, as Apple's
host answers on the device's own queue, so the main loop never waits out a
decode or a transform; the status comes back through a bottom half, which
returns the element and only then pops the next, in the guest's order. A
reset and the unrealize wait for the worker's element and discard its
answer; the worker never takes the BQL.
Neither device has a property of its own, so a user sets nothing on either:
the library picks what both decode, encode and transform with, from the GPU
apple-gfx-pci's device runs on, and logs its choice and why. Both find the
IOSurfaces a request names through the process's latest IOSurface device,
so neither needs a link.
Not for upstream: written with an AI assistant, which QEMU's policy on
AI-generated content (docs/devel/code-provenance.rst) declines.
An x86-64 macOS guest that runs Apple's arm64 paravirtualized GPU driver
(AppleParavirtGPUIOGPUFamily, ported) needs the IOSurface device, which
maps the guest's IOSurfaces: the driver's start waits for the mapper
driver's service with no timeout, and every texture over an IOSurface is
a mapper texture. vmapple has the device as apple-gfx-mmio's second
region, and apple-gfx-pci had none. The mapper driver uses memory index 0
and interrupt index 0, which the GPU's own function, with its one MSI
vector, cannot give it as well, so the device is a PCI device of its own.
Add apple-gfx-iosurface-pci, vendor 0x106b, device 0xeeef (ours: no
Apple device has it). BAR 0 is 64 KiB of 32-bit memory with the IOSurface
device's registers at 0x1000 to 0x1030, as in vmapple's region, and one
MSI vector is notified once per completed command, from a BH the
library's worker schedules. 8-byte accesses pass whole, where
apple-gfx-mmio truncates them to 32 bits: the ring's and the descriptor
table's bases are guest physical addresses, which may lie above 4 GiB. A
4-byte access acts as on apple-gfx-mmio. Its gpu link names the
apple-gfx-pci whose IOSurfaces it maps; unset, it takes the machine's only
apple-gfx-pci, made before it, and realize refuses when there is none or
more than one, and for a second instance, since a device maps through the
process's latest IOSurface device. Like apple-gfx-mmio, it makes the
IOSurface device from the guest's RAM as the system memory's flat view
has it, after the GPU's device: on Linux the library reaches those pages
through the files the GPU's device names. Its reset writes 0 to its
registers through the library's MMIO writes, as a guest would; the
library ignores a ring size of 0, so that register keeps its size, which
maps nothing until a base and a size are written again.
apple-gfx-pci always maps the guest's IOSurfaces through the IOSurface
device and passes the library process_isolation with
process_isolation_follows_guest; it always gives the library a memory
map, which isolation needs. The library then isolates a task other than
task 0 only while the IOSurface device has a descriptor table, and
answers argument buffers in device info by the same rule. Apple's x86-64
AppleParavirtGPU, stock (binary version 6) or under reims-util's
ReimsVgpu.kext (245), never touches the device and references IOSurfaces
through ref textures whose backing is in task 0, which an isolated task
does not serve: its tasks run in process. The ported arm64 driver's
mapper writes the descriptor table base at its start, before its GPU
driver makes a task, so its tasks run isolated, which its info replies
need: in process each one ends QEMU. A VM with no apple-gfx-iosurface-pci
runs every task in process and is told no argument buffers, as before.
macOS 27's virtio PCI transport never starts a device whose capabilities
are linked from high offsets to low (the previous commit), and
virtio-net-pci links them by address only with x-ascending-capabilities
on. Turn it on in the vmapple machine's defaults, so a VM's network card
starts without the option on its command line.
Measured with reims-ctl's command for each VM, unchanged: a macOS 27.0.1
(26A434) guest's three virtio devices reach DRIVER_OK and it reaches its
login window; a macOS 26 guest's do too, and it reaches its desktop with
its menu bar and Dock.
Not for upstream: written with an AI assistant, which QEMU's policy on
AI-generated content (docs/devel/code-provenance.rst) declines.
macOS 27's virtio PCI transport never starts a device whose capability
list runs from high offsets to low, as QEMU links it (MSI-X at 0x98,
then 0x84, 0x70 and on down): its cached and its fallback capability
lookups disagree on such a list. Each virtio device of a macOS 27.0.1
(26A434) guest read the PCI_CFG capability at 0x84, then the notify
capability at 0x70 and BAR 4's type, then started over, about 100,000
config reads a second. No device's status left 0, the root disk saw no
I/O, and the kernel never reached its GPU driver: a black screen. macOS
26 walks the same list once and goes on.
Relink the capabilities in ascending address order, keeping each one's
offset and contents: always on vmapple-virtio-blk-pci, and on
virtio-net-pci when x-ascending-capabilities is on (off by default).
vmapple-virtio-blk-pci also states subsystem ID 0x1100, the value it
already had, and gains Apple's vendor capability: virtio cfg_type 9,
vendor 0x106b, 14 bytes, with its transport encryption disabled flag
set. The patch's author found a non-FileVault root disk needs it; that
was not isolated from the reordering.
With both, a macOS 27.0.1 guest mounts its root volume, its virtio
devices reach DRIVER_OK, and it reaches Setup Assistant.
Not for upstream: written with an AI assistant, which QEMU's policy on
AI-generated content (docs/devel/code-provenance.rst) declines.
Co-authored-by: Jesus Martínez <jesse_m@naver.com>
macOS 15.4 and later list the SMC's keys at boot: PerfPowerServices'
PLSMCMetricsAgent asks GET_KEY_BY_INDEX (0x12) for index after index
until the SMC answers 0xb8, index out of range. isa-applesmc took READ
(0x10) alone and answered any other command 0x82, bad command, so the
walk never ended. An x86-64 macOS 26.6.1 guest asked about 22,000 times a
second from 30 s after boot on: PerfPowerServices ran a vCPU at 100%,
almost all of it in AppleSMC's port I/O, and QEMU took 119% of a host
core with the desktop idle.
The device now takes GET_KEY_BY_INDEX: a big-endian index of 4 bytes,
with no length byte after it, answered with a key's name the way READ
answers a value. macOS sends no length byte; waiting for one left
AppleSMC polling the status port until it timed out. The keys are listed
in the order of their names, MSSD, MSSP, NATJ and REV, without OSK0 and
OSK1, which a Mac finds by name only, and index 4 and past get 0xb8.
GET_KEY_TYPE (0x13) and WRITE (0x11) stay refused with 0x82: macOS sends
the first about 60 times a boot and the second a few times, and gives
each refusal up at once.
Measured on the same guest under KVM: each boot walks the index once or
twice, 5 commands a walk ending at 0xb8, and the SMC sees no I/O once the
guest is idle; PerfPowerServices used under 1 s of CPU in its first 3
minutes. The guest reached its desktop, rebooted and shut down.
Not for upstream: written with an AI assistant, which QEMU's policy on
AI-generated content (docs/devel/code-provenance.rst) declines.
macOS installers and recovery images (x86-64 macOS 26) ship no driver of
the device's own, so IOGraphics' IONDRVFramebuffer is the only driver
that binds it, and it takes the EFI boot framebuffer over only when that
lies inside one of the device's memory BARs. The option ROM's
framebuffer is guest RAM, and the device had one register BAR, so the
installer's WindowServer found no usable display, aborted and started
again, the screen frozen on the Apple logo.
Add BAR 2, a 64 MiB 32-bit prefetchable window (the efi-framebuffer-bar
property, on by default), which holds one alias of the machine's RAM,
made at realize and left disabled. After the library takes a guest write
to 0x1210, the device reads the framebuffer's start back from the
library under the BQL, in the library's page unit (APV_PAGE_SHIFT: 4 KiB
on x86-64 hosts, 16 KiB otherwise), and looks it up in the system
memory's flat view. When that is the machine's RAM, BAR 2 shows the run
of RAM there, up to 64 MiB, at its offset 0; a start of 0 or anything
else disables the alias. Offset, size and enable change in one
transaction before the access returns, so the option ROM's read-back
right after its writes sees them. A reset disables the alias again.
The start is read back rather than taken from the write because the MMIO
region is lockless under KVM: two vCPUs' hooks can take the BQL in
another order than the library took their writes. The hook runs after
rvg_device_mmio_write returns, never inside it. A repeated start changes
nothing: the alias's setters return early on equal values.
The window ends where the guest's own RAM range ends: on q35, SMRAM
(TSEG) is part of the machine's RAM, hidden only in the flat view. Only
0x1210 writes and a reset change BAR 2, so after EFI goes off a guest
kernel's draws to its boot framebuffer (progress bar, verbose console,
panic screen) still land in RAM rather than trapping one access at a
time. BAR 2 is left out where the machine's RAM is a guest_memfd's, as
KVM refuses a second memory slot onto it; under NUMA, or without a
machine RAM region, the alias never turns on, and the ROM keeps its
framebuffer in RAM.
The library, its memory map (built at realize) and the registers it
reads are unchanged: the ROM still writes the RAM page, and BAR 2 is
only another guest-physical address of the same RAM. What the guest
sees: one more memory BAR, which shows the EFI framebuffer from the
ROM's 0x1210 write until the next one or a reset.
App Nap: hold a user-initiated activity while an apple-gfx device is
realized (NSActivityUserInitiatedAllowingIdleSystemSleep, which leaves
the host's idle sleep to its own settings). With QEMU's window behind
another application's, macOS napped QEMU 30 to 50 s after it lost the
focus, every QEMU thread ran at priority 4, and a macOS 26.6.2 guest
reached its desktop at 215 s rather than 53 s; with the activity it
never napped. The activity is apple-gfx-activity.m's; other hosts build
apple-gfx-activity-stub.c, whose two functions do nothing.
MMIO: make accesses on the vCPU thread, calling the library directly,
rather than on the pool with an AIO_WAIT_WHILE under the BQL, where a
lost aio_wait_kick hung a vmapple guest. An access waits only on the
library's threads, which never wait on QEMU. Mark the region lockless
and drop the per-device reentrancy guard, so that under KVM vCPUs make
accesses without the BQL, and at once; HVF and TCG still take the BQL
for them. The guest sees the same values and interrupts.
Linux hosts: find the reims-vgpu package and install its option ROM on
Linux as on macOS, and enable MAC_PVG for KVM's targets as well as
HVF's; meson's summary says whether it found the library on both. Give
each range of the memory map its own host address (its offset in its
region added: q35's RAM above 4 GiB is an alias), pass the file behind
each range in RvgDeviceConfig.memory_files (the library maps guest pages
from it on Linux, and a realize there without shared file-backed RAM
fails, naming -object memory-backend-memfd,share=on), and trace each
range.
Display: read each frame's pixels on the pool thread into the job's own
buffer, so that a slow read (1.7 s for 1080p on a Linux host) no longer
holds the main loop and starves the guest's other devices. Render the
surface only while a display change listener has asked for it within the
last 6 s, else on demand from gfx_update, so that a headless run reads
back no frame that nothing shows. The library sees the same calls, in
the same order, only fewer of them.
With no functional change: comments brought up to date (what a present
waits for, which thread runs the window's callbacks and raise_interrupt,
the resolution property's form), a render's size kept in its job alone,
the window's dead wheel callback dropped, QEMU's coding style followed,
and the long lines of apple-gfx's meson rules and of hvf's ISV=0
emulation wrapped.
An exit notifier that released the device at the process's exit came and
went: it blocked QEMU's exit on FIFO work the stopped vCPUs never
completed.
The guest saw each of apple-gfx's displays named "QEMU display", in its
display settings. Name them "Reims vGPU", as the library's windows for
them are titled.
macOS 14 and later guests stop in their kernel's first instructions:
the kernel spins with "hvc #0; cbnz x0, ." on each of its pointer
authentication hypercalls, which the public Hypervisor.framework API
fails without an exit. macOS 15 and later also panic when APFS mounts
their unencrypted data volume ("unencrypted data volume is not
allowed"), unless the device tree has /filesystems/DoNotUseSEP, and
reset in a loop.
Make two changes to the guest when iBoot enters the kernel:
- Replace every "cbnz x0, ." that follows an "hvc #0" in the kernel's
memory, from the boot arguments' physBase to their topOfKernelData,
with a nop, so the kernel runs on the firmware's keys, as macOS 13's
does. 14.6.1, 15.6.1 and 26.6.2 have 19 such sites; 13.6 has none.
- If the device tree has no /filesystems node, append one that has
DoNotUseSEP as the root's last child, in the zeroes that pad the tree
to its last 16 KiB page, and cover it with the tree's length in the
boot arguments. 13.6's tree has the node, and is left as it is.
To catch the kernel's entry, RAM is not executable from reset. Each page
iBoot runs becomes executable on its first fetch, until a fetch lands in
the kernel's memory with x0 at the boot arguments; only the boot CPU
runs then. HVF reports these faults through a new hook,
hvf_arm_exec_fault, which a machine can set to handle a stage 2 fault
on an instruction fetch itself.
With this, 13.6, 14.6.1, 15.6.1 and 26.6.2 guests reach their desktops.
The page says only macOS 12 guests are supported. macOS 13 guests boot
too, and macOS 14, 15 and 26 guests stop in their kernel's first
instructions, which the page should explain.
A vmapple kernel asks the hypervisor to manage its pointer
authentication keys through the HVC64 calls 0xC1000000 to 0xC10000FF.
The public Hypervisor.framework API answers them itself as not
supported (x0 = 0xffffffff), without an exit to QEMU. macOS 13's kernel
ignores the result. From macOS 14 on, every call site is followed by
"cbnz x0, .", so the boot CPU spins right after iBoot hands over, with
nothing on the serial console after iBootStage2's banner. 14.6.1's
kernelcache has 19 such sites (SET_INITIAL_STATE in the start code of
every CPU, GET_DEFAULT_KEYS, and SET_B_KEYS and the EL0 diversifier
calls on context switches), none behind a condition the machine could
set.
Hypervisor.framework implements the calls only for a VM created with a
private ISA setting (_hv_vm_config_set_isa), which hv_vm_create()
refuses with HV_DENIED under com.apple.security.hypervisor. With EL2
enabled, HVF still answers these calls from EL1 itself.
With its queue full, the device merged a new report into the last one
queued: the new pointer and buttons, the sum of the scrolling, the new
phases. Where one of the two was a scroll report and the other a pointer
report, the merged report broke both rules the device keeps for macOS,
which ignores the pointer and buttons of a report it takes as a scroll: a
scroll report repeats the pointer and buttons of the report before it, and
a report that returns the scroll fields to 0 comes before a pointer report.
A button released while the guest was not reading the device, its queue
ending in a scroll report, reached the guest only in a scroll report.
Drop reports while the queue is full, and once the guest has read it
empty, report what it missed by those rules: the phases of the last
scrolling dropped, so that a gesture whose end was dropped ends, then the
pointer and buttons as they are. The scrolling dropped is lost, rather
than replayed late. A subsection migrates the dropped state, when there is
some.
input-send-event takes a scroll event's distance as any 64-bit value. The
device summed the distances unchecked and multiplied them into wheel units
and lines, which wrapped: one event of 2^62 reported the wheel turned up
and the smooth scrolling fields going down.
Hold the sum of a synchronization's distances to 32 bits, which is more
than a report carries, so that what follows cannot overflow.
A synchronization whose events both scroll and move the pointer or press
a button made a scroll report first, which repeats the pointer and buttons
the guest had, and the pointer report after it. VNC sends a wheel button
with the pointer's new position in one synchronization, so a macOS guest
scrolled the view under the pointer's old position, then moved it.
Report the pointer first: the scroll report then repeats the new pointer
and buttons, and the guest scrolls where the pointer is.
The machine realizes the device its tablet property names with
usb_create_simple(), which takes a failure as a bug: &error_abort. The
property takes any USB device, and some need properties of their own, so
-M vmapple,tablet=usb-storage aborted QEMU with "Unexpected error in
usb_msd_storage_realize()" and SIGABRT.
Realize the tablet with &error_fatal, so that QEMU exits with the device's
error, as it does for a -device that fails to realize.
realize registers the input handler, then binds it to the display
property's console. When that console does not exist, realize fails, and
QEMU frees a device that fails to realize without unrealizing it, so the
handler stayed in the input layer's list with a pointer to freed memory.
device_add usb-vmapple-tablet,display=nosuch followed by a scroll event
from input-send-event crashed QEMU.
Unregister the handler when the bind fails.
vmapple.rst says a macOS guest reads the width it is told in whole
centimetres, rounded up, and that 2560x1600@148 reads as 44 cm. That mode
is told 440.39 mm, which rounded up to whole centimetres is 45 cm, 144.5
ppi, a 1x desktop; the guest reads 44 because it first rounds to whole
millimetres, to nearest, as apple_gfx_guest_centimeters does. Say so.
The display's settings page holds the width the guest is told in whole
millimetres in 16 bits, so a width of more than 65535 mm is not what the
page holds: 2575x1600@1 is told 65560 mm, which 16 bits hold as 24, 3 cm.
apple_gfx_guest_scale_unknown read it as 6556 cm, about 1 ppi, and let it
through as 1x, but what the guest reads there was never measured. Refuse
it with the other densities whose scale is unknown. Of the densities the
property takes, it refuses 2575 to 3811 pixels wide at 1 ppi, which were
let through before; wider modes at 1 ppi, or narrower ones, are refused
already or are not told that wide.
A density whose guest scale is unknown is refused with "where the scale
it runs was never measured", and vmapple.rst and the comments say the
same. Some of what it refuses was measured: 1280x800@220 ran 1x, and
5832x3645@148 and @130 ran HiDPI. It is the density that does not tell
the scale there, not the boots that are missing, so say "is not known from
the density", which holds for every input refused.
Also say that only the chosen mode is checked: the smaller modes offered
with it are told the same size in millimetres, and may fall where the
chosen mode would be refused (2560x1600@227, measured HiDPI across 29 cm,
offers 1680x1050, which reads 147.1 ppi there).
resolution=WxH@PPI tells the guest a density for the window display's
mode, and reims-vgpu sizes the window by the scale it expects the guest to
run there. Measured on a macOS 13.6 guest, the guest reads the width it is
told rounded to whole millimetres and then up to whole centimetres, and runs
HiDPI from 2021 pixels across 35 cm (146.667 ppi) and 1x at up to 3811
across 66 (146.666 ppi). That holds for modes 1920 to 3811 pixels wide:
5832x3645 ran HiDPI at 128.8 ppi, and 1280x800 ran 1x at 216.7 ppi across
15 cm, where the narrowest and smallest measured HiDPI were 1920 pixels and
29 cm. The docs said "more than about 148 ppi", where 2560x1600@148 reads
as 44 cm, 147.8 ppi, and runs HiDPI.
Where the guest's scale was never measured, the window may show a 1x
desktop at half size or a HiDPI one scaled up: between the two densities,
below them for a mode wider than 3811 pixels, and above them for one
narrower than 1920 pixels or 29 cm. Refuse those densities at realize,
naming the centimetres the guest would read, and state the measured rule
in vmapple.rst.
The window display paragraph said a HiDPI guest at a chosen density is
shown one guest pixel per screen pixel, as if always. A windowed window is
sized a guest point per host point, so that holds on a Retina screen with
room for half the mode; a 1x screen halves the frames, a mode too big for
the screen is shrunk, and a borderless window fits the image to its screen.
Say so, move resolution=host ahead of the density, and rewrap the
paragraph, one of whose lines ran to 90 columns.
A display's window sent the guest wheel notches: reims-vgpu counts a
trackpad's movement as one notch per 40 points, which a macOS guest
scrolls in jumps with no momentum, and QEMU's usb-tablet has no
horizontal wheel.
Give the window reims-vgpu's scroll callback, which has each scroll event
as its distance in 1/256 point with the phases of its gesture and of the
momentum after it, and as the notches the wheel callback would have had.
Where the device that takes the console's wheel takes smooth scroll events
(qemu_input_scrolls_smoothly(): vmapple's usb-vmapple-tablet), send the
distance and phases as them; elsewhere, send the notches as wheel buttons,
as before. The library then calls the wheel callback no more.
This needs a reims-vgpu whose RvgWindowCallbacks has scroll.
The vmapple machine gave its macOS guest usb-tablet, which the guest
scrolls by whole, accelerated wheel notches, vertically only. Give it
usb-vmapple-tablet, the USB pointing device Virtualization.framework gives
the same guests, which macOS scrolls as it does a trackpad from smooth
scroll events.
Keep the choice: the machine's tablet property names the USB pointing
device, usb-vmapple-tablet by default. tablet=usb-tablet gives the guest
the device it had before, for a guest or a user interface that
usb-vmapple-tablet does not suit, and to compare the two. A name that is
not a USB device is refused when the property is set.
Describe the machine's input devices and the choice in vmapple.rst.
A macOS guest scrolls usb-tablet's wheel by whole notches, which it
accelerates: a trackpad swipe reaches it as a few jumps of up to 35 pixels,
about 50 ms apart, with no momentum, and there is no horizontal wheel. The
USB pointing device Virtualization.framework gives its macOS guests also
carries smooth scrolling: the distance, with the phases of the gesture and
of the momentum scrolling after it. macOS binds its own driver,
AppleVirtualPlatformHIDEventDriver, to that device's vendor and product
IDs (05ac:8106), and scrolls it as it does a trackpad.
usb-vmapple-tablet is that device: the same IDs and report descriptor, an
absolute pointer with three buttons, a wheel, a horizontal wheel, and the
smooth scrolling fields, which it fills from the input layer's scroll
events. Wheel buttons scroll a fixed 20 pixels a notch. Other guests see
a HID mouse with two wheels, which honour the resolution multiplier.
macOS takes a report as a scroll, ignoring its pointer and buttons, when a
scroll field in it is new, and so is every field of the first report it
reads. So the device sends a report of nothing after a reset, repeats the
pointer and buttons in scroll reports, and returns the scroll fields to 0
before a pointer report; without these, the first move after the guest
starts and a click right after a scroll were lost.
With a macOS 13.6 guest, a swipe of 30 events of 6 pixels and 40 momentum
events at 120 Hz arrives as 73 scroll events with their phases, and moves
a text view 57 times, a median 6 pixels every 8.4 ms.
User interfaces send scrolling to the guest as wheel buttons, one press
and release per notch. A host's trackpad scrolls by points, and has the
guest follow the fingers only when the guest gets the distance, and the
phases of the gesture and of the momentum scrolling after it, which is
what a trackpad or Virtualization.framework's pointing device gives a
macOS guest.
Add an input event kind for that: InputScrollEvent carries a distance in
1/256 pixel on one axis, in the direction of the wheel buttons (up and
left above 0), with the gesture's phase and the momentum's. The events up
to a synchronization make one report. qemu_input_queue_scroll() queues one,
QMP's input-send-event and replay carry them, and the input_event_scroll
trace shows them. qemu_input_scrolls_smoothly() tells a user interface
whether the device that takes a console's wheel takes them too, as
qemu_input_is_absolute() tells it about the pointer; where it does not, the
interface keeps sending wheel buttons.
The resolution property picks the mode a window display offers the guest
first, which reims-vgpu offers at a 1x density (110 ppi) and the window
scales up on the GPU. A 1x desktop scaled up looks soft on a Retina screen,
where a guest told a higher density runs a HiDPI desktop at the mode's
pixels, as Virtualization.framework's guests do (macosvm's 2560x1600 at
200 ppi).
Accept "<width>x<height>@<ppi>", 1 to 65535 pixels per inch, and pass the
density in RvgWindowConfig's mode_pixels_per_inch. Without "@" nothing
changes: the density is 0, which the library takes as 1x. The
resolution=host and display-modes paths are unchanged.
A macOS guest on vmapple under HVF brings up only its boot CPU. With
-smp N, every secondary faults on its first return from
machine_load_context(), panics, and spins in its panic handler with
interrupts masked: N-1 host cores at 100%, and a guest on one CPU.
macOS does not program its pointer authentication keys on vmapple. It
asks the hypervisor to, through the HVC64 fast calls 0xC1000000 to
0xC1000006 (XNU's doc/vmapple_pac.md): SET_INITIAL_STATE when a CPU
starts, then SET_B_KEYS and the EL0 diversifier calls on context
switches. Virtualization.framework implements them, in a private
Hypervisor.framework mode. The public Hypervisor.framework API answers
the whole range 0xC1000000 to 0xC10000FF itself: hv_vcpu_run() does
not return for these calls, the PAC calls return 0xffffffff and change
no register but x0, and PAC_NOP (0xC10000F0) returns 0. QEMU never
sees them and cannot implement them, and the guest runs on whatever
keys each vCPU holds.
The vmapple boot firmware (AVPBooter) writes all ten AP*Key registers
on the boot CPU, and iBoot and XNU keep them. A secondary comes out of
reset with QEMU's zero keys, and the first pointer it authenticates was
signed on CPU 0: the continuation machine_stack_attach() signs with
APIAKey. On a macOS 13.6 guest, CPU 1's retaa on LR 0xb7acfe002679a770
branched to 0xe687fe002679a770 (FEAT_PAuth2 corrupts the pointer; the
host has no FEAT_FPACCOMBINE, so there is no PAC fail exception) and
took a translation fault there.
Set cpu-on-copies-pauth-keys on vmapple's CPUs, so that every CPU the
guest powers on starts with the keys of the CPU that powers it on. All
CPUs then share the firmware's keys, as the guest expects. After a
reset the firmware sets the boot CPU's keys again, and the secondaries
take them when the guest starts them.
This belongs to the machine rather than to HVF. It is vmapple's
contract that the platform, not the guest, provides the keys; guests
on other machines, Linux among them, program their own, and HVF guests
there keep the keys a CPU resets to. It would serve vmapple under TCG
as well.
The calls themselves stay unimplemented, as with -smp 1 before. The
per-process B keys (SET_B_KEYS) and the EL0 diversifier, which gives
user space keys of its own, have no effect, so the kernel and every
process share one set of keys. Hypervisor.framework intercepts the
calls, so only its private mode can provide them.
Tested with a macOS 13.6 guest on an M3 Max running macOS 26.7, with
-smp 8 and kernel-irqchip=on: the guest reaches the desktop and reports
hw.ncpu and hw.activecpu 8, eight busy loops in it keep all eight vCPU
threads at 100%, and an idle guest's vCPU threads use 2% or less where
seven sat at 100% before. HMP system_reset and a restart from the guest
both bring every CPU back up, and -smp 1 boots as before.
The pointer authentication keys are UNKNOWN after reset, and QEMU
resets them to zero, which suits guests that program their own keys.
Some platforms leave the keys to their hypervisor instead, which gives
every CPU the keys the boot CPU runs with, and a guest written for such
a platform expects a pointer signed on one CPU to authenticate on all
of them.
Add a "cpu-on-copies-pauth-keys" CPU property, off by default, for
boards to set. When a CPU that has it is powered on through
arm_set_cpu_on(), as PSCI CPU_ON does under TCG and HVF, it starts with
the pointer authentication keys of the CPU making the call instead of
the reset value. The keys are taken when the call is made, after
synchronizing the caller's state so that an accelerator's copy of them
is current, and given to the new CPU after its reset.
No board sets the property yet, so nothing changes.
e181197cc2 (the RFC v7 vmapple series) marked the machine with
.interfaces = aarch64_machine_interfaces from hw/arm/machines-qom.h.
Upstream removed those interfaces from every Arm machine (ad4320478e) and
then the header (108485a709), so after the merge of upstream master
vmapple.c no longer compiled. Drop both lines as upstream did for the other
machines; vmapple_machine_info is upstream's again.
This reverts commit cbb749d421.
Upstream fixed the same assertion in bf6530630e ("target/arm/hvf: seed
NO_RAW ID registers from isar.idregs[] on vCPU init"), which this branch
has had since the merge of upstream master in 49873ce25e. It lists
ID_AA64ISAR0_EL1 among the NO_RAW registers the sync loop skips and seeds
the vCPU's copy at init, so the assertion holds again and any other NO_RAW
register in the sync list still stops QEMU at start rather than going
unsynced. hvf_arch_init_vcpu() is now upstream's.
In window mode, each display offered the modes of the host screen its
window opens on: on a Retina screen, 3456x2160 at HiDPI, a desktop the
guest runs much slower than 1920x1080.
A new string property, resolution, picks the mode a window display offers
first, which reims-vgpu offers at 1x with the standard sizes within it, at
the host screen's refresh rate, and which the window scales to its size on
the GPU (RvgWindowConfig's mode_width and mode_height, with
RVG_WINDOW_MATCH_HOST_SCREEN):
- unset: 1920x1080;
- "<width>x<height>": that mode, each side 1 to 65535 pixels;
- "host": no mode, so the library offers the host screen's own modes at
its density, as before.
A malformed value fails realize. The display-modes property, where given,
still sets the modes and passes no flag; headless runs are unchanged.
vmapple.rst describes the property.
Under -display none on macOS, QEMU shows no display and leaves the main
thread in CFRunLoopRun. reims-vgpu can open an AppKit window of its own for
a display there (RvgDisplayConfig's window), drawing each guest frame into
it on the GPU, with no copy to the CPU and no QEMU UI in between, and
sending the window's pointer, wheel, keys and close back to the host.
Window mode is on when query-display-options says the display type is none
and the environment's REIMS_VGPU_WINDOW is not "0"; QEMU says so once, and
how to turn it off. Each display then passes an RvgWindowConfig:
- Its modes match the host screen the window opens on
(RVG_WINDOW_MATCH_HOST_SCREEN), and the default modes are not set. With
the display-modes property, the flag is off and those modes are set.
- A guest frame is no longer rendered and copied into the surface. The
surface is drawn only when QEMU's display system asks (gfx_update: a
screendump, or a listener such as VNC), by one render whose completion
always signals the update done: also when the encode is refused or the
size changed. With no mode or frame target yet, gfx_update is done at
once, so a screendump never waits for a frame that will not come.
- The window callbacks come on the process's main thread, without the BQL,
and must not block. They queue their events on the device's FIFO, which
its BH runs under the BQL in order, with the display's console as the
source: the pointer as absolute X and Y clamped to the mode, and button
changes (left, right, middle, side, extra), then a sync; each wheel notch
as a WHEEL_UP/DOWN or WHEEL_LEFT/RIGHT press and release, then a sync;
each key's USB HID usage through qemu_input_map_usb_to_linux, sent at
once as QEMU's local displays send keys; and a close as a host-UI
shutdown request with the power-off action, as QEMU's own windows do.
REIMS_VGPU_WINDOW=0, or any display type but none, keeps apple-gfx as it
was. vmapple.rst describes the displays property and window mode.
reims-vgpu drives up to RVG_MAX_DISPLAY_PORTS displays on one device, and
apple-gfx made only one. A new uint32 property, displays (1 to 8, default
1), sets the device's display_port_count, and realize makes one display a
port, each with the next serial number, the same name, size and modes, and
one graphic console a display, head i for port i. A value out of range
fails realize.
The display state (the reims-vgpu display, console, surface, frame target,
cursor and frame bookkeeping) moves from AppleGFXState into an array of
AppleGFXDisplay, each pointing back at its device, and each display's
callbacks and console get its own.
The cursor callbacks' work now runs in the order the callbacks came. Each
scheduled a one-shot BH, and one-shot BHs scheduled together run in the
reverse order (aio_bh_enqueue inserts at the head, aio_bh_poll takes from
the head), so a cursor glyph could be replaced by the one set before it.
The glyph, show and move callbacks now queue their work on a mutex-guarded
FIFO, drained in order by one BH per device. The show callback's value
travels with its work instead of being stored at once, so each cursor
update sees the state as of its own callback.
With displays=1, the library is called as before: the same device config,
one display on port 0 with the next serial number and the same modes, and
the new-frame and mode-change paths are unchanged.
The reims-vgpu package no longer carries Apple's EFI option ROM: its
optionrom variable names ReimsVgpu.rom, the package's own EFI driver for
the device, which paravirt-decompile builds from its firmware/ directory.
The file QEMU installs and the device's class romfile take that name, so
nothing calls the package's ROM Apple's.
- meson installs the file optionrom names into qemu_datadir as
ReimsVgpu.rom, and configure's symlink-install-tree links it into the
build tree's qemu-bundle as before.
- apple-gfx-pci's class romfile is ReimsVgpu.rom; romfile= still overrides
it and romfile="" drops it.
Measured with a fresh build on the package from paravirt-decompile's
dist tree: the qemu-bundle link points at the dist tree's
share/reims-vgpu/ReimsVgpu.rom (5632 bytes). A paused virt machine with
-device apple-gfx-pci and no romfile= realizes with romfile
"ReimsVgpu.rom", romsize 8192 and BAR 6.
A guest's EFI firmware drives the PCI device only through its option ROM,
Apple's EFI driver for 106b:eeee. The framework's API named its path; the
new C API has no such function (paravirt-decompile's plan, Q12), so the
device had no default ROM and every -device apple-gfx-pci needed romfile=.
The reims-vgpu package now carries the ROM and names it in its .pc file's
optionrom variable, and QEMU installs it with its other firmware.
- meson installs the file optionrom names into qemu_datadir, as
AppleParavirtEFI.rom. Configure's symlink-install-tree links it into
the build tree's qemu-bundle as well, where qemu_find_file finds it for
a QEMU run from the build tree. A package that names no existing ROM
gets a warning, not a failure: romfile= still works then.
- apple-gfx-pci's class romfile is AppleParavirtEFI.rom, as virtio-net-pci's
is efi-virtio.rom, so romfile= overrides it and romfile="" drops it.
Measured with the build from the previous commit, rebuilt: the qemu-bundle
link points at the dist tree's share/reims-vgpu/AppleParavirtEFI.rom (16896
bytes). A paused virt machine with -device apple-gfx-pci and no romfile=
realizes with romfile "AppleParavirtEFI.rom", romsize 32768 and BAR 6. As
for the other devices with a class romfile, -device apple-gfx-pci,help
shows romfile without a default.
paravirt-decompile now builds reims-vgpu as a plain library, which a host
links the way it links its other dependencies (its plan, Q5 and phase 7):
`cargo xtask dist` writes libreims_vgpu.a and .dylib, reims_vgpu.h and
reims-vgpu.pc into its target/dist. apple-gfx takes it the way QEMU
takes rutabaga_gfx_ffi, and the framework and its directory option go.
- pvg is dependency('reims-vgpu', method: 'pkg-config'), with
static: true, so the library is linked into the binary: no install
name or rpath of it is recorded. Its Libs.private names the system
frameworks and libraries it needs.
- pvg_framework goes, with its checks of a framework's binary, header
and @rpath install name, and the -F, -framework and rpath arguments.
pvg=auto without the package builds no apple-gfx, and --enable-pvg
without it stops configure, both as meson's dependency() does.
- apple-gfx.h includes <reims_vgpu.h>, which the package's Cflags find.
- The configure summary says reims-vgpu support, with its version.
- scripts/meson-buildoptions.sh is regenerated with the bundled meson
(1.11.1), keeping its --prefix and --localstatedir defaults as
committed, and vmapple.rst says how to build.
Measured on macOS 26.7 (25G229) with Xcode 26.6's clang, configured with
aarch64-softmmu, --enable-hvf, --enable-pvg and --disable-docs, and
PKG_CONFIG_PATH at a dist tree built from paravirt-decompile's
steelbrain/native-dist: meson finds reims-vgpu 0.1.0, and stores the path
as its pkg_config_path. It warns that -lSystem, -liconv and -lobjc have
no static archive; those stay dynamic, as the system's. otool -L lists
neither ReimsVGPU.framework nor libreims_vgpu.dylib and no LC_RPATH to
the tree, and the rvg_ functions are defined in the binary. ld warns
that two C objects of the archive were built for macOS 26.5, newer than
QEMU's deployment target, 26.0.
reims-vgpu replaced its C API, which projected ParavirtualizedGraphics'
SDK one call per method with Objective-C types, by an API of its own
(paravirt-decompile's docs/api.md; its header reims_vgpu.h). Each object
is made from one config struct with a callback table, refusals are an
RvgStatus, the library picks its Metal device and makes its own frame
targets, and callbacks come on the library's threads with no queues or
blocks. apple-gfx then needs nothing Objective-C, so apple-gfx.m,
apple-gfx-mmio.m and apple-gfx-pci.m become .c files: no Metal,
IOSurface, dispatch, blocks or autorelease pools. The marshalling onto
the BQL stays QEMU's, where it was.
- Realize fills an RvgDeviceConfig: the bus variant gives
raise_interrupt, and the MMIO one use_iosurface_mapper and
process_isolation; common realize gives display port count 1, the
system's default Metal device (metal_registry_id 0, the device
copy_suitable_metal_device picked on arm64) and the memory map, walked
from the flat view into a GArray freed after the create, since the
library copies it. The display gets port 0, the next serial number,
"QEMU display", 400 x 300 mm and a callback table, then the modes.
A refused create fails the realize with rvg_status_message's text,
where the old code went on with a NULL device. apple-gfx-mmio makes the
IOSurface device after the device, from a second walk, as before, and
fails the realize if it is refused; releasing an IOSurface device
that did not exist yet goes.
- Frames: set_mode makes an RvgFrameTarget of the surface's size in
BGRA8, the byte order of pixman's x8r8g8b8, in place of the Metal
texture. A render retains the target, and a pool job encodes the
display's frame into it, commits, waits, and schedules the completion
BH, which copies the target into the surface with
rvg_frame_target_read_pixels at the surface's stride, if the size is
unchanged. The copy reads the target the frame drew into, where the old
BH read s->texture, which a mode change there and back could replace.
A refused encode is logged and skips the copy, now through the same
BH rather than by taking the BQL on the background thread.
- The display's callbacks come on the library's display thread, one at
a time in the guest's order, as they came on the main queue:
mode_change takes the BQL and sets the mode synchronously, the others
schedule the same BHs as before. The cursor glyph arrives as pixels and
a hot spot, copied into the BH's job. The show callback takes the
guest's byte and stores show != 0, where the block's bool parameter
took the byte as it came.
- MMIO: each AppleGFXState owns a ThreadPool. The MMIO reads and writes
of both regions, and the renders, go to it with
thread_pool_submit_immediate, which starts a thread when none is free,
in place of dispatch_async_f onto the global queue; the vCPU still
waits in AIO_WAIT_WHILE. The IOSurface registers are still read and
written as 32 bits.
- Gone with the paths below macOS 15.4, dead at the deployment target
26.0: the PGTask task list and its callbacks, the read_memory BH, the
IOSurface map and unmap callbacks, and their trace events. QEMU gives
the device raise_interrupt and a memory map only.
- Gone: the Metal device and command queue (the library makes the
process's frame queue when the device is created), the managed-storage
blit, the descriptor probe for the MMIO size (RVG_DEVICE_MMIO_SIZE),
and the option ROM lookup. apple-gfx-pci has no default romfile until
the ROM ships as a data file; romfile= still sets one. The PCI IDs, BAR
and MSI count come from the header.
- meson builds the three .c files and no longer adds Metal to pvg.
Measured on macOS 26.7 (25G229) with Xcode 26.6's clang, configured with
aarch64-softmmu, --enable-hvf, --enable-pvg and --disable-docs, and a
pvg_framework whose Headers hold the API's draft header (paravirt-
decompile's docs/api/reims_vgpu.h at a8228da1): the three objects compile
as C without a warning, and checkpatch finds nothing. Their undefined
symbols name 20 of the header's 35 functions, and no Objective-C,
Metal, dispatch or Mach VM symbol.
Then linked against the ReimsVGPU.framework that paravirt-decompile's
cargo xtask bundle builds at 2182cf83, whose reims_vgpu.h declares
exactly the draft's items, in cbindgen's order. No source change was
needed, and the link gives no warning. otool -L lists only
@rpath/ReimsVGPU.framework/Versions/A/ReimsVGPU of the two frameworks,
with an LC_RPATH at that Frameworks directory, and the binary binds the
20 functions and no rvg_legacy_ one. Not booted. Smoke-tested paused
(-S), with no guest code run, beside the previous QEMU (53c555c179's reims
backend, on the framework built before the new API):
- -device help lists apple-gfx-pci, and both variants list their
properties;
- vmapple with blank aux and root images, and virt with apple-gfx-pci
and a display-modes property, realize. The machine resets, HMP xp reads
0x30200000, 0x30201010 (4 words each) and the IOSurface registers
0x30211000 and 0x30211008 through the ThreadPool hop, system_reset
resets again, and QMP quit exits 0. Both QEMUs read the same values,
all 0, and write the same apple_gfx* trace, line for line.
paravirt-decompile makes reims-vgpu the only library apple-gfx drives
(its plan, Q6): nothing in this tree is to link the system's
ParavirtualizedGraphics.framework any more. The next commit rewrites
apple-gfx on reims-vgpu's own API; this one only takes the pg backend
away, so that the rewrite reads on its own.
- The apple_gfx_backend option goes, and with it
APPLE_GFX_BACKEND_REIMS. configure --apple-gfx-backend is now an
unknown option.
- apple-gfx*.m keep what the reims backend compiled: every
#ifdef APPLE_GFX_BACKEND_REIMS is resolved with unifdef, which drops
the Objective-C branches, PGCopyOptionROMURL and the private
IOSurface declarations. The header's comment no longer names the
option.
- pvg_framework names a ReimsVGPU.framework, under the same checks as
before: an absolute path, a binary and Headers/reims_vgpu.h, and an
@rpath/ install name. pvg=auto without it builds no apple-gfx, and
--enable-pvg without it stops configure. Metal stays a dependency,
since the three .m files still import it.
- The configure summary says ReimsVGPU support and framework.
- scripts/meson-buildoptions.sh is regenerated with the bundled meson
(1.11.1), keeping its --prefix and --localstatedir defaults as
committed, and vmapple.rst says how to build with the one backend.
Measured on macOS 26.7 (25G229) with Xcode 26.6's clang, configured
with aarch64-softmmu, --enable-hvf and --disable-docs:
- with --enable-pvg and a pvg_framework holding a framework whose
header is reims-vgpu's current reims_vgpu.h, the three objects
compile without a warning. Their preprocessed source equals that of
the previous commit's files preprocessed with
-DAPPLE_GFX_BACKEND_REIMS, but for the file names and line numbers
that __FILE__ and __LINE__ put in assertions;
- --apple-gfx-backend=reims: "unknown option";
- --enable-pvg alone: fails with the pvg_framework error;
- no options: the message, and ReimsVGPU support NO.
paravirt-decompile's native rewrite (its plan, step T6) deleted the
Objective-C++ ParavirtualizedGraphics.framework that the pg backend
linked from source. Its product is now reims-vgpu, which the reims
backend drives, so reims becomes the default. pg goes back to linking
the system framework, as upstream does, which gives paravirt-decompile
a VM control that runs Apple's framework with no DYLD_FRAMEWORK_PATH.
- apple_gfx_backend defaults to reims: reims-vgpu's C API, in a
ReimsVGPU.framework built from source, which pvg_framework names as
before. Choosing reims no longer counts as asking for apple-gfx,
because every configure now chooses it. So pvg=auto without
pvg_framework builds no apple-gfx, as pg did at 7e2d0fa93e, and a
message says why. --enable-pvg without one stops configure, as
before. The warning that reims had no effect under --disable-pvg goes,
since every such configure would now print it.
- pg with no pvg_framework links dependency('appleframeworks', modules:
['ParavirtualizedGraphics', 'Metal']), upstream's line. QEMU then
records the framework's /System/Library/Frameworks install name, and
dyld loads the system's copy. With pvg_framework, pg still links a
ParavirtualizedGraphics.framework built from source (paravirt-
decompile's skin), under the same checks as before.
- Naming a pvg_framework asks for apple-gfx under either backend, so
Metal is required with it. The branch for Metal not found goes, since
it can no longer be taken.
- The builder hints name what paravirt-decompile builds now: `cargo
xtask bundle` into target/Frameworks for reims, and the skin (`cargo
xtask bundle --all`, into target/skin/Frameworks) for pg. make
qemu-framework and rust/target are gone.
- The summary gives /System/Library/Frameworks as the framework that pg
links when no pvg_framework is given.
scripts/meson-buildoptions.sh was regenerated with the bundled meson
(1.11.1). Its --prefix and --localstatedir defaults were kept as
committed: this host's meson reports Homebrew's. vmapple.rst now says
how to build with each backend.
Measured on macOS 26.7 (25G229) with Xcode 26.6's clang. The
configure line was aarch64-softmmu, --enable-hvf and --disable-docs,
plus the options given below.
- pg with --enable-pvg and no pvg_framework (paravirt-decompile's make
qemu-system): the summary says ParavirtualizedGraphics support YES,
framework /System/Library/Frameworks. otool -L lists
/System/Library/Frameworks/ParavirtualizedGraphics.framework/
Versions/A/ParavirtualizedGraphics, and there is no LC_RPATH to a
framework directory. The depfiles of apple-gfx.m, apple-gfx-pci.m and
apple-gfx-mmio.m take every ParavirtualizedGraphics header from the
SDK. The binary is signed ad hoc with the hypervisor entitlement.
- reims with --enable-pvg and pvg_framework at paravirt-decompile's
target/Frameworks (its make qemu): otool -L lists
@rpath/ReimsVGPU.framework/Versions/A/ReimsVGPU, with an LC_RPATH at
that directory.
- configure only, one run per branch:
- no options: reims, with the message, and ReimsVGPU support NO;
- --enable-pvg alone: fails with the pvg_framework error;
- --disable-pvg: ReimsVGPU support NO, with no warning;
- --apple-gfx-backend=pg: ParavirtualizedGraphics support YES,
through appleframeworks (ParavirtualizedGraphics, Metal);
- pg with pvg_framework at paravirt-decompile's skin: YES, with that
directory;
- a relative pvg_framework, or an empty directory under either
backend: fails, with the error naming the right builder;
- --disable-pvg with a pvg_framework: NO.
Nothing is pushed. 7e2d0fa93e, the commit paravirt-decompile's tag
rust-port-parity records, is tagged rust-port-parity here, locally.
The apple_gfx_backend meson option (default pg) builds apple-gfx against
ReimsVGPU.framework's C API (reims_vgpu.h) instead of
ParavirtualizedGraphics. Each framework call keeps its Objective-C form
under the pg backend, so the two read side by side; blocks become
static functions with the same bodies, called on the same queues.
apple-gfx linked the system's ParavirtualizedGraphics.framework through
dependency('appleframeworks'): the SDK's headers and .tbd, and a binary
that records /System/Library/Frameworks/ParavirtualizedGraphics.framework/
Versions/A/ParavirtualizedGraphics, so dyld loads the shared cache's copy.
This fork runs vmapple on the framework paravirt-decompile builds from its
decompiled source, and until now that took DYLD_FRAMEWORK_PATH at run
time.
Add a pvg_framework option (configure --pvg-framework=DIR), the absolute
path of a directory holding a ParavirtualizedGraphics.framework built from
source. The pvg dependency compiles apple-gfx*.m with -F<dir>, so their
#import <ParavirtualizedGraphics/...> find that bundle's Headers, and links
with -F<dir> -framework ParavirtualizedGraphics and an rpath to <dir>.
Metal stays a system framework. The framework's install name must start
with @rpath/: a binary records the install name of each dylib it links, so
one that kept the system's would load the system's copy at run time.
configure checks that with otool -D. It stops, naming paravirt-decompile's
make qemu-framework, when pvg is enabled without a directory, or when the
directory is relative, holds no framework binary and Headers, or holds one
that is not a dylib or whose install name is not @rpath/. pvg=auto without
a directory builds without apple-gfx, and pvg=disabled ignores the option.
scripts/meson-buildoptions.sh is regenerated with the bundled meson, and
vmapple.rst says how to build.
Measured on a macOS 26.6.2 host (25G83) with paravirt-decompile's make
qemu: aarch64-softmmu, --enable-hvf --enable-pvg, and --pvg-framework at
its build/qemu-framework, whose install name is @rpath/.
- otool -L on qemu-system-aarch64 lists @rpath/ParavirtualizedGraphics
.framework/Versions/A/ParavirtualizedGraphics. The string
/System/Library/Frameworks/ParavirtualizedGraphics occurs nowhere in the
binary. otool -l shows an LC_RPATH at the directory.
- The depfiles of apple-gfx.m, apple-gfx-pci.m and apple-gfx-mmio.m take
every ParavirtualizedGraphics header from the directory, none from the
SDK.
- Run with no DYLD variable, dyld loads the framework from the directory
(DYLD_PRINT_LIBRARIES, vmmap), and launchd runs the GPU task XPC service
from inside that bundle. A macOS 13.6 vmapple guest boots to the desktop
and draws Maps and Photos.
- The binary is still signed ad hoc with the hvf entitlements.
- Each configure error above was run, and so were pvg=auto without a
directory and pvg=disabled, which configure with pvg NO.
ld warns that the framework's minos, 26.6 (its image's), is newer than
QEMU's deployment target, 26.0.
e181197cc2 turned vmapple on for aarch64 by setting CONFIG_VMAPPLE=y in
configs/devices/aarch64-softmmu/default.mak. VMAPPLE selects MAC_PVG_MMIO,
which depends on MAC_PVG, and meson sets MAC_PVG only when the pvg
dependency is found. With CONFIG_VMAPPLE forced on, every configure
without pvg (--disable-pvg, or pvg=auto finding no framework) fails in
minikconf:
KconfigDataError: contradiction between clauses when setting MAC_PVG_MMIO
Nobody saw it because pvg=auto always found the system
ParavirtualizedGraphics.framework on macOS. The next commit stops linking
the system framework, so auto finds none unless it is given a framework
built from source, and the machine has to follow pvg.
Make VMAPPLE depend on MAC_PVG and let its "default y if ARM" turn it on,
in place of the forced assignment. The assignment stays in the file,
commented out, beside the other boards it lists as ones to keep out.
Measured with minikconf on this host's aarch64-softmmu configuration.
Without CONFIG_MAC_PVG it now succeeds and leaves VMAPPLE and MAC_PVG_*
out. With CONFIG_MAC_PVG=y it sets VMAPPLE, VMAPPLE_AES, _BDIF, _CFG,
_VIRTIO_BLK, MAC_PVG_MMIO and MAC_PVG_PCI, as before. configure with
--disable-pvg, and with pvg=auto and no framework, now completes, and a
pvg build still offers -M vmapple.
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.
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.
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.
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-11-15 01:56:31 -08:00
170 changed files with 16405 additions and 2510 deletions
The Virtio sound device can be configured with the following properties:
* ``jacks`` number of physical jacks (Unimplemented).
* ``streams`` number of PCM streams. At the moment, no stream configuration is supported: the first one will always be a playback stream, an optional second will always be a capture stream. Adding more will cycle stream directions from playback to capture.
* ``streams`` number of PCM streams: the playback streams first, then the capture streams.
* ``input-streams`` how many of the streams capture; by default the second half of them (none of
one stream, one of two). ``streams=1,input-streams=1`` makes a capture-only device.
* ``chmaps`` number of channel maps (Unimplemented).
All streams are stereo and have the default channel positions ``Front left, right``.
reims_graphics_pool_reserved(uint64_t gpa, uint64_t size, uint64_t end) "the pool's range at 0x%"PRIx64", 0x%"PRIx64" bytes, reserved to 0x%"PRIx64
reims_graphics_pool_add(uint64_t gpa, uint64_t size, bool ahead, int64_t ask_ns, int64_t map_ahead_ns, unsigned run, int64_t held_ns) "piece at 0x%"PRIx64", 0x%"PRIx64" bytes, mapped ahead %d: %"PRId64" ns from the ask, map ahead %"PRId64" ns, BQL part of its run of %u %"PRId64" ns"
reims_graphics_pool_remove(uint64_t gpa, uint64_t size, bool ahead, int64_t unmap_ahead_ns, unsigned run, int64_t held_ns) "piece at 0x%"PRIx64", 0x%"PRIx64" bytes taken out, unmapped ahead %d: unmap ahead %"PRId64" ns, BQL part of its run of %u %"PRId64" ns"
reims_graphics_pool_removed(uint64_t gpa) "piece at 0x%"PRIx64" ended"
reims_graphics_quiesce(const char *where, bool may_exit, int64_t ns) "at the %s: answered %d in %"PRId64" ns"
reims_graphics_end(const char *where, int status) "at the %s: ends with _exit(%d)"
reims_graphics_prefault_helper(unsigned long id, unsigned cpuid_entries, int tsc_khz) "the populate's vCPU %lu made, with vCPU 0's %u CPUID entries and TSC kHz %d"
reims_graphics_prefault_tsc_rejoin(int cpu_index, int ret) "after vCPU %d's TSC put, the populate's vCPU's TSC write answered %d"
reims_graphics_prefault_region(uint64_t gpa, uint64_t size, uint64_t done, unsigned slices, unsigned cuts, unsigned kicks, int err, bool stopped) "piece at 0x%"PRIx64", 0x%"PRIx64" bytes: 0x%"PRIx64" populated in %u slices, %u cut by the timer, %u by a pause; errno %d, stopped %d"
Loaded 100 of 170 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.