Author SHA1 Message Date
YXC0915 51e8c2d3b5 win32: advertise the fixed native block AIO backend 2026-12-02 00:03:33 +08:00
棠渚听潮 7b5d7ee8a8 block/file-win32, win32-aio: convert to coroutine I/O and add bounce-buffer pool
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)
2026-12-02 00:02:30 +08:00
棠渚听潮 c8d42adbf6 block/file-win32, win32-aio: fix AioContext migration, IOCP completion, and direct I/O
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)
2026-12-02 00:02:30 +08:00
YXC0915 fa8e2e4b9e io: identify rejected Win32 direct writes 2026-12-01 11:55:46 +08:00
YXC0915 4c4757156a migration: coalesce Win32 mapped-ram writes and support Win32 direct-io
- 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.
2026-12-01 11:40:55 +08:00
YXC0915 c67660108a Apply qemu-intel-whpx-suspend
Reims-Go-Patch: qemu-intel-whpx-suspend.patch
2026-12-01 09:40:17 +08:00
YXC0915 5e8b305bdf Apply qemu-win32-mapped-ram-io
Reims-Go-Patch: qemu-win32-mapped-ram-io.patch
2026-12-01 09:40:17 +08:00
YXC0915 8124a9ac5a Apply qemu-win32-coroutine-fiber-commit
Reims-Go-Patch: qemu-win32-coroutine-fiber-commit.patch
2026-12-01 09:40:16 +08:00
YXC0915 d94e40608f Apply qemu-whpx-nested-virt-nonfatal
Reims-Go-Patch: qemu-whpx-nested-virt-nonfatal.patch
2026-12-01 09:40:16 +08:00
YXC0915 c9691d296d Apply qemu-whpx-win10-startup-ipis
Reims-Go-Patch: qemu-whpx-win10-startup-ipis.patch
2026-12-01 09:40:15 +08:00
YXC0915 3b2d4814be Apply qemu-whpx-win10-compat
Reims-Go-Patch: qemu-whpx-win10-compat.patch
2026-12-01 09:40:15 +08:00
Anees Iqbal 4571bc5fec ✅ Test that x-ascending-capabilities links in order
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.
2026-11-27 11:37:45 -08:00
Anees Iqbal 1600825bb0 ✅ Test dsound's playback buffer arithmetic on any host
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.
2026-11-27 11:23:08 -08:00
Anees Iqbal b057a987fe 🆕 Write reims-vgpu's degradation counts on a QOM property's set
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.
2026-11-26 12:08:41 -08:00
Anees Iqbal 458f4b7b31 🐛 Refuse a Linux host below 7.2 at reims-graphics-pci's realize
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.
2026-11-25 20:09:18 -08:00
Anees Iqbal 695ad62cce 🐎 Put guest RAM back on huge pages on Linux 7.2 and later
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".
2026-11-25 18:23:53 -08:00
Anees Iqbal 1a35b9fb47 🐛 Keep the reims-graphics device's library RAM off huge pages
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.
2026-11-25 18:18:14 -08:00
Anees Iqbal 51382c20b6 🐛 Keep shared file-backed guest RAM off transparent huge pages
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.
2026-11-25 18:06:01 -08:00
Anees Iqbal de738a4103 ⏪ Take MADV_COLLAPSE of preallocated guest RAM back out
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.
2026-11-25 17:40:43 -08:00
Anees Iqbal 4d205af8e2 🐎 Hold dsound's playback reserve at 60 ms, not half the buffer
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.
2026-11-25 10:43:59 -08:00
Anees Iqbal 207be58775 🐎 Run the audio backend as soon as a virtio-snd guest posts
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.
2026-11-25 10:43:09 -08:00
Anees Iqbal 0c0ac35698 🐛 Write dsound's playback only past DirectSound's write cursor
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.
2026-11-24 01:03:32 -08:00
Anees Iqbal 0c91b471fd 🆕 Let -smbios type=17 set the memory devices' Memory Type
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.
2026-11-24 00:05:44 -08:00
vintowareandClaude Opus 5.5 b980d0f46d 🐛 Let usb-host leave a device unreset as it lets go of it
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>
2026-11-23 21:08:57 -08:00
vintowareandClaude Opus 5.5 5c42f3fce4 🐛 Link virtio-sound-pci's capabilities in address order on vmapple
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>
2026-11-24 03:05:29 +00:00
Anees Iqbal 53e766304f 🐎 Collapse preallocated guest RAM into huge pages
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.
2026-11-23 12:02:03 -08:00
Anees Iqbal c3e4018538 🆕 List the AVX-512 XSAVE components without avx512f
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.
2026-11-21 06:32:51 -08:00
Anees Iqbal ba44746362 🐛 End an exit that skips the cleanup with _exit and no quiesce
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.
2026-11-19 07:00:52 -08:00
Anees Iqbal e8f0178b15 🐛 End with _exit where reims-vgpu still holds a GPU device
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.
2026-11-19 06:50:11 -08:00
Anees Iqbal 88337859c9 🆕 Quiesce reims-vgpu at the end of QEMU's cleanup
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.
2026-11-19 04:29:28 -08:00
Anees Iqbal 7ad9c809e7 🐎 Delete a removed pool piece's KVM slots off the BQL
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.
2026-11-18 21:09:05 -08:00
Anees Iqbal d2de4f945b 🐛 Include qemu/lockable.h in the pool's populate
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).
2026-11-18 20:10:29 -08:00
Anees Iqbal b561d79cbe 🆕 Pre-fault the reims-graphics pool's pieces on WHPX
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.
2026-11-18 19:51:03 -08:00
Anees Iqbal cfe57e555b 🐛 End a stuck pre-fault call after 20 ms
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.
2026-11-18 19:46:54 -08:00
Anees Iqbal a4dfdbf1b4 🐛 Keep the pre-fault vCPU in its VM's TSC generation
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.
2026-11-18 19:46:33 -08:00
Anees Iqbal 9c95b6775f 🆕 Pre-fault the reims-graphics pool's pieces on KVM
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.
2026-11-18 19:45:46 -08:00
Anees Iqbal dd0e0d4a4a 🆕 Leave room for one vCPU past the guest's APIC ids
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.
2026-11-18 19:41:01 -08:00
Anees Iqbal 0590cfdea8 hw/vmapple + reims-graphics-pci: give the Shared pool vmapple's room
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.
2026-11-18 18:58:38 -08:00
Anees Iqbal dc1b6821d7 hw/vmapple: ask HVF for 40 bits of guest physical address
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.
2026-11-18 18:58:38 -08:00
Anees Iqbal d4896daf67 🐛 Cap the pool's room at the host's physical address bits
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.
2026-11-18 18:16:42 -08:00
Anees Iqbal 65d741f5c7 📝 Say pool_remove comes on the library's pool thread [ci skip]
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.
2026-11-18 18:16:42 -08:00
Anees Iqbal 66475e8df2 📝 Say the pool's range is sized for the GPU's heaps, summed
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.
2026-11-18 17:54:44 -08:00
Anees Iqbal db1411fb9d hw/display/reims-graphics-pci: find a pool piece by binary search
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.
2026-11-18 17:04:03 -08:00
Anees Iqbal f6d6673b7c system/physmem: put a RAM block in the list without walking it
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.
2026-11-18 17:04:03 -08:00
Anees Iqbal 05db047e3d system/memory: render a flat view without moving every later range
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.
2026-11-18 17:04:03 -08:00
Anees Iqbal 9f2e07b017 hw/display/reims-graphics-pci: carry out a run of pool asks in one commit
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.
2026-11-18 17:04:03 -08:00
Anees Iqbal 29359d069d system/physmem: place a RAM block in one pass over the blocks by offset
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.
2026-11-18 17:03:56 -08:00
Anees Iqbal fe167f2a9b hw/display/reims-graphics-pci: set a pool piece unmergeable in its add
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.
2026-11-18 17:03:56 -08:00
Anees Iqbal 492d9db516 🆕 Reserve the pool's range the library takes for the GPU's heap
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.
2026-11-18 16:02:13 -08:00
Anees Iqbal aa1643a40d hw/display/reims-graphics-pci: link its KVM calls only where KVM is
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.
2026-11-17 11:57:24 -08:00
Anees Iqbal 3d763b51ad hw/display/reims-graphics-pci: unmap a pool piece ahead of its removal
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.
2026-11-17 06:14:07 -08:00
Anees Iqbal 5a945ca3a4 accel/whpx: let a device unmap a RAM region's memory ahead of its removal
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.
2026-11-17 06:13:45 -08:00
Anees Iqbal a6329932fe hw/display/reims-graphics-pci: name the guest's Shared pool in the file's head
The head lists what the device gives the guest: the pool's range is one of
them, and the teardown takes its pieces out before the library's release.
2026-11-17 06:08:34 -08:00
Anees Iqbal 14ed3b0da5 hw/display/reims-graphics-pci: give x-pool-grow its type info and getter slot
object_class_property_add takes the property's QAPI type info and a getter
before the setter: x-pool-grow is a uint64 with a setter alone.
2026-11-17 05:46:57 -08:00
Anees Iqbal 0b8a0702eb hw/display/reims-graphics-pci: map the guest's Shared pool's pieces
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.
2026-11-17 05:36:04 -08:00
Anees Iqbal 9d2fb7a869 accel/whpx: let a device map a RAM region's memory ahead of its add
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.
2026-11-17 05:31:45 -08:00
Anees Iqbal f56d36ff50 target/i386/whpx: say what the SYSENTER MSRs' interception keeps
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.
2026-11-16 15:25:19 -08:00
Anees Iqbal c3704402af target/i386/whpx: offer no TSC deadline timer where Hyper-V refuses it
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.
2026-11-16 15:24:46 -08:00
Anees Iqbal e8ae598e55 Merge GitHub's steelbrain/reims-vgpu-rebase-2 (pull request #15)
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.
2026-11-16 14:46:42 -08:00
Anees Iqbal 5970afb495 Merge pull request #15 from naileclevrai/whpx-amd-intel-msrs
whpx: keep an Intel guest's MSRs that Hyper-V refuses on an AMD host
2026-11-16 14:41:26 -08:00
NailecMC 4025704118 whpx: keep an Intel guest's MSRs that Hyper-V refuses on an AMD host
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.
2026-11-16 22:44:47 +01:00
Anees Iqbal 500d30fb24 ui: encode a screendump on a thread of the pool, with the BQL let go
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.
2026-11-16 13:20:04 -08:00
Anees Iqbal 0fdbf3810d target/i386/whpx: let a vCPU run on without the BQL when nothing is pending
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).
2026-11-16 12:27:58 -08:00
Anees Iqbal 243971f2cd hw/display/reims-graphics-pci: raise interrupts on WHPX without the main loop
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.
2026-11-16 11:36:47 -08:00
Anees Iqbal e435673c53 audio/dsound: play sound on a host with no recording device
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.
2026-11-16 03:27:38 -08:00
Anees Iqbal 979d171c9a ui/console: pass over text consoles in a lookup by device
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.
2026-11-15 18:25:48 -08:00
Anees Iqbal 010bf82714 hw/display/reims-graphics-pci: give each display a console and window
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.
2026-11-15 14:24:10 -08:00
Anees Iqbal a86885f804 hw/display/reims-graphics-pci: build on Windows
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.
2026-11-15 06:20:37 -08:00
Anees Iqbal 6c2cae1637 system/physmem: give shared RAM a section on Windows
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.
2026-11-15 06:14:29 -08:00
Anees Iqbal cc128f0e14 target/i386/whpx: answer CPUID leaf 4 from the CPU model
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.
2026-11-15 06:07:42 -08:00
Anees Iqbal 1890afed25 tests/qtest/usb-hcd-xhci: queue the short-packet TDs before the key
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.
2026-11-15 05:06:54 -08:00
Anees Iqbal ae97f3f533 hw/usb/hcd-xhci: post the event a TD's last TRB owes after a short packet
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.
2026-11-15 04:59:00 -08:00
Anees Iqbal 341397871f audio/paaudio: keep a record stream only while capture runs
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.
2026-11-15 01:58:57 -08:00
Anees Iqbal 83b7255ca0 hw/display/reims-graphics-pci: map the doorbell pages as BAR 4
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.
2026-11-15 01:58:57 -08:00
Anees Iqbal db125fda0c hw/usb/host-libusb: make no usbfs call on a device while it sets an alt
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.
2026-11-15 01:58:57 -08:00
Anees Iqbal 3b327429d8 hw/usb/hcd-xhci: give a failed slot command's completion its Slot ID
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.
2026-11-15 01:58:57 -08:00
Anees Iqbal 347a220481 hw/usb/hcd-xhci: complete each command with its own fields
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.
2026-11-15 01:58:57 -08:00
Anees Iqbal f819bec29a hw/display/reims-graphics-pci: keep the event BH to the exit
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.
2026-11-15 01:58:32 -08:00
Anees Iqbal 92db49c1d8 hw/display/reims-graphics-pci: release the device at quit with the BQL let go
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.
2026-11-15 01:58:32 -08:00
Anees Iqbal fa60069450 hw/display/reims-graphics-pci: answer a screendump within 3 s of its read
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.
2026-11-15 01:58:32 -08:00
Anees Iqbal d81acc1df7 hw/display/reims-graphics-pci: route doorbells only where QEMU has eventfds
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.
2026-11-15 01:58:32 -08:00
Anees Iqbal db9cb35faf hw/display/reims-graphics-pci: take routed queue doorbells as ioeventfds
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.
2026-11-15 01:58:32 -08:00
Anees Iqbal 244e098197 hw/audio/virtio-snd: keep channels_max at what the device supports
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.
2026-11-15 01:58:32 -08:00
Anees Iqbal 19b84b6ded hw/audio/virtio-snd: complete an RX message once its buffer is full
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.
2026-11-15 01:58:32 -08:00
Anees Iqbal 764f51d186 hw/audio/virtio-snd: write an RX message's status after its buffer
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.
2026-11-15 01:58:32 -08:00
Anees Iqbal 17d093ccc2 hw/audio/virtio-snd: trace each stream's parameters and I/O messages
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.
2026-11-15 01:58:32 -08:00
Anees Iqbal 7e24448ef8 hw/audio/virtio-snd: take the number of input streams as a property
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.
2026-11-15 01:58:32 -08:00
Anees Iqbal 99a42e4f2b hw/audio/virtio-snd: capture only while the driver has buffers posted
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).
2026-11-15 01:58:32 -08:00
Anees Iqbal 7df1c970f2 audio/pwaudio: start a capture again from the present
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.
2026-11-15 01:58:32 -08:00
Anees Iqbal febd8228f0 audio/pwaudio: read a full capture ring from its newest audio
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.
2026-11-15 01:58:32 -08:00
Anees Iqbal 94aa0ffd2d audio/pwaudio: say a full capture buffer once, then count
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.
2026-11-15 01:58:32 -08:00
Anees Iqbal ad84c22467 hw/display/reims-graphics-pci: answer a waiting screendump at the teardown
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.
2026-11-15 01:58:32 -08:00
Anees Iqbal 60886c1a4c hw/display/reims-graphics-pci: bound the quit's wait for a display read
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.
2026-11-15 01:58:32 -08:00
Anees Iqbal 26c1702015 tests/qtest/usb-hcd-xhci: test interrupt moderation
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.
2026-11-15 01:58:32 -08:00
Anees Iqbal 9fa8e2bc48 hw/usb/hcd-xhci: moderate interrupts with IMOD
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.
2026-11-15 01:58:32 -08:00
Anees Iqbal 5412dd0600 hw/usb/hcd-xhci: read HCCPARAMS2 as 0
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.
2026-11-15 01:58:32 -08:00
Anees Iqbal c16cb1f86b tests/qtest/usb-hcd-xhci: test Set LTV with and without LTC
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.
2026-11-15 01:58:32 -08:00
Anees Iqbal aa598d74a5 hw/usb/hcd-xhci: support Set LTV on PCI Express
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.
2026-11-15 01:58:08 -08:00
Anees Iqbal 3e24b0f569 hw/usb/host-libusb: set an interface's alt setting off the main loop
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.
2026-11-15 01:58:08 -08:00
Anees Iqbal 553e4c6035 hw/char/pl011, hw/gpio/pl061: lower the interrupt lines on reset
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.
2026-11-15 01:58:08 -08:00
Anees Iqbal 06688caa79 hw/vmapple/aes: reset the FIFO, keys and mode, and lower the interrupt
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.
2026-11-15 01:58:08 -08:00
Anees Iqbal 46184d3b44 hw/intc/arm_gicv3_hvf: put each SPI's state in its own registers
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.
2026-11-15 01:58:08 -08:00
Anees Iqbal 33297479ab tests/qtest/usb-hcd-xhci: test isoch TDs with late Frame IDs
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.
2026-11-15 01:58:08 -08:00
Anees Iqbal 668c8d0a37 hw/usb/hcd-xhci: run an isoch TD with a late Frame ID now, not 2 s later
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.
2026-11-15 01:58:08 -08:00
Anees Iqbal 574ac2594d hw/usb/host-libusb: hold every iso IN packet until its data is there
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.
2026-11-15 01:58:08 -08:00
Anees Iqbal 027dfa8fff tests/qtest/usb-hcd-xhci: test a TD's Block Event Interrupt flag
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.
2026-11-15 01:58:08 -08:00
Anees Iqbal 4202f8cc03 tests/qtest/usb-hcd-xhci: test that a woken stopped endpoint stays stopped
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.
2026-11-15 01:58:08 -08:00
Anees Iqbal 5fa19b1eb3 hw/usb/hcd-xhci: leave a stopped endpoint stopped until its doorbell
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.
2026-11-15 01:57:48 -08:00
Anees Iqbal f3405832bd hw/usb/hcd-xhci: honor a TRB's Block Event Interrupt flag
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.
2026-11-15 01:57:34 -08:00
Anees Iqbal 8e7b3a9c6d tests/qtest/usb-hcd-xhci: test that an empty isoch ring is reported once
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.
2026-11-15 01:57:34 -08:00
Anees Iqbal 44665ca5eb hw/usb/host-libusb: hold an iso OUT packet for a free buffer
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.
2026-11-15 01:57:21 -08:00
Anees Iqbal 96a9609a7c hw/usb/host-libusb: hold an iso IN stream's first packet for its data
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.
2026-11-15 01:57:21 -08:00
Anees Iqbal c5ea80906a hw/usb/host-libusb: give each iso transfer a millisecond of the bus
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.
2026-11-15 01:57:21 -08:00
Anees Iqbal 8e67cf32ac hw/usb/hcd-xhci: report an empty isochronous ring once
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.
2026-11-15 01:57:10 -08:00
Anees Iqbal 4f41fa27c4 hw/display/reims-graphics-pci: tear the device down at QEMU's quit
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.
2026-11-15 01:57:10 -08:00
Anees Iqbal 287ab36b95 hw/display/reims-graphics-pci: say a vector mask's failure once
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).
2026-11-15 01:57:10 -08:00
Anees Iqbal 4445c4805b target/arm/kvm: emulate MMIO accesses that have no syndrome
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.
2026-11-15 01:57:10 -08:00
Anees Iqbal af7af7086a target/arm: share the ISV=0 MMIO emulator between accelerators
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.
2026-11-15 01:57:10 -08:00
Anees Iqbal 2b0673635b hw/vmapple: under KVM, answer macOS's PAC calls as HVF and TCG do
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.
2026-11-15 01:57:10 -08:00
Anees Iqbal d5c89ec921 target/arm/kvm: let a board answer SMCCC calls as TCG and HVF do
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.
2026-11-15 01:57:10 -08:00
Anees Iqbal 2c3a3650c0 accel/hvf: run each vCPU at the user-initiated QoS
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.
2026-11-15 01:57:10 -08:00
Anees Iqbal 055cc6c4f3 hw/vmapple: under KVM, give the CPUs no PMU and PSCI 1.1
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.
2026-11-15 01:57:10 -08:00
Anees Iqbal 8dda3627d3 hw/vmapple: start secondary CPUs through QEMU under KVM
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.
2026-11-15 01:57:10 -08:00
Anees Iqbal 3d06c211ec target/arm/kvm: let a board take PSCI CPU_ON from KVM
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.
2026-11-15 01:57:10 -08:00
Anees Iqbal 308b5fc6f0 hw/display/reims-graphics-pci: tell the library the guest's architecture
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.
2026-11-15 01:57:10 -08:00
Anees Iqbal 02687c09c3 hw/display/reims-graphics-pci: give the library macOS's RAM with no file
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.
2026-11-15 01:57:10 -08:00
Anees Iqbal eac08533d1 hw/display/reims-graphics-pci: map only the file-backed RAM ranges
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.
2026-11-15 01:57:10 -08:00
Anees Iqbal fa4640412d docs/system/arm/vmapple: drop the DoNotUseSEP step the firmware no longer takes
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.
2026-11-15 01:57:10 -08:00
Anees Iqbal 2c9e6ed538 hw/vmapple: give the config block's string fields their real offsets
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.
2026-11-15 01:57:10 -08:00
Anees Iqbal d4489ead58 hw/vmapple: say why the SME default doesn't reach HVF's CPU
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.
2026-11-15 01:57:10 -08:00
Anees Iqbal a25cd13ac6 hw/vmapple: offer no SME under TCG
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.
2026-11-15 01:57:10 -08:00
Anees Iqbal 665035aa7b hw/vmapple: add avp-rtc, the clock macOS keeps its offset with
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 7365f20ed9 hw/display/reims-graphics-pci: drop the scanout's dirty log
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 1b3509f32f hw/vmapple: offer virtio-net without its control queue
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 42e7766d35 hw/vmapple: ignore the guest's write to its DMA config doorbell
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal c629d1471a hw/vmapple: build and run the machine without HVF
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 981994e8a0 hw/vmapple: move RAM to 4 GiB to open a PCIe window below it
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal b6821b7876 hw/vmapple: leave the guest's kernel to its firmware
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 9e4c8fa106 hw/vmapple: drop apple-gfx from the machine
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 96e1b470ea hw/display: remove apple-gfx, its video devices and the IOSurface device
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 9bf62d8490 hw/display/reims-graphics-pci: open the window at the resolution property
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
2026-11-15 01:57:09 -08:00
Anees Iqbal 03d4af6f05 hw/display/reims-graphics-pci: say what BAR 2's memory is on each host
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal e1360002ad ui: write a PPM screendump's rows without the line buffer's padding
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 00d11f7edf hw/display/reims-graphics-pci: give the console the guest's cursor
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal b7d7fdaf61 hw/display/reims-graphics-pci: warn where BAR 2 gets no address
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal aebdef13de hw/display/reims-graphics-pci: show the display in the console
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 142c8e72a0 hw/display/reims-graphics-pci: answer a command buffer on its doorbell's vCPU
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal f16ca588c2 hw/display/reims-graphics-pci: ring a queue's doorbell with the plain write
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 945a86b745 hw/display/reims-graphics-pci: take a command buffer on its doorbell's vCPU
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 967400b3f6 hw/display/reims-graphics-pci: raise the interrupt through an irqfd
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 3410aab784 Revert "hw/display/reims-graphics-pci: give the library the dirty source"
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 8c92e94307 hw/display/reims-graphics-pci: give the library the dirty source
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal e3e5ef1d37 hw/display/reims-graphics-pci: give the library the guest RAM map
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal a6795a99a5 hw/display: add reims-graphics-pci
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 5e83e90dc2 system/physmem: align file-backed RAM to 2 MiB on Linux
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 12d4802b30 hw/display/apple-gfx: give the library a KVM dirty source
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 93f9f40cdc hw/vmapple/aes: refuse to realize without AES ciphers
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 5d192e7951 hw/display: add apple-videotoolbox-pci and apple-m2scaler-pci
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal fe3f6fecb4 hw/display/apple-gfx-pci: add the IOSurface device over PCI
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal d01f28c9ed hw/vmapple: order virtio-net-pci's capabilities by address
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.
2026-11-15 01:57:09 -08:00
Anees IqbalandJesus Martínez 4a39ef8d54 hw/vmapple: boot macOS 27 guests: virtio capabilities in address order
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>
2026-11-15 01:57:09 -08:00
Anees Iqbal 83de566436 hw/misc/applesmc: answer GET_KEY_BY_INDEX
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 052e51e82d hw/display/apple-gfx-pci: show the EFI framebuffer in BAR 2
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 7d9890dfd5 🚐 Point to new repo name 2026-11-15 01:57:09 -08:00
Anees Iqbal 3821d6b992 hw/display/apple-gfx: build on Linux hosts, take MMIO off the BQL
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 567931cf56 hw/display/apple-gfx: name the guest's displays Reims vGPU
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal eae5dd4a5c hw/vmapple: boot macOS 14 and later guests
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 6a54a097bd docs/system/arm/vmapple: say which macOS guests boot, and why not 14
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 4f4e12bef8 docs/system/arm/vmapple: rewrap the input section
The paragraph on usb-vmapple-tablet kept a line of 106 columns when a
phrase was added to it. Rewrap it.
2026-11-15 01:57:09 -08:00
Anees Iqbal ffca79f534 hw/usb/dev-vmapple-tablet: resynchronize the guest after the queue fills
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 743bbba8f9 hw/usb/dev-vmapple-tablet: hold smooth scroll distances to 32 bits
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal eb67b81577 hw/usb/dev-vmapple-tablet: report a sync's pointer before its scrolling
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 29043c9b34 hw/vmapple: report a tablet that fails to realize, rather than abort
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 74d5134fb9 hw/usb/dev-vmapple-tablet: unregister the input handler when realize fails
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 3b1e7142ea docs/system/arm/vmapple: round a told width to millimetres first
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 6f4ed991a3 hw/display/apple-gfx: refuse a density told wider than 65535 mm
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 7625164acf hw/display/apple-gfx: say a refused density does not tell the scale
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).
2026-11-15 01:57:09 -08:00
Anees Iqbal 2f28b3d956 hw/display/apple-gfx: refuse a density whose guest scale is unknown
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 0ac391e4f7 docs/system/arm/vmapple: say when a window shows guest pixels 1:1
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 8bd846364e hw/display/apple-gfx: send the windows' smooth scrolling
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 3deaf0f735 hw/vmapple: give the guest usb-vmapple-tablet, with a tablet property
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 1d0776ac53 hw/usb: add usb-vmapple-tablet, Virtualization.framework's USB tablet
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 9017d7e47e ui/input: add smooth scroll events
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 1cf7e47d53 hw/display/apple-gfx: let resolution name the mode's density
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal d10ee1dd7b hw/vmapple: start secondary CPUs on the boot CPU's PAuth keys
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal ab4c3018f4 target/arm: optionally start CPU_ON targets on the caller's PAuth keys
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal d24cde8e6e hw/vmapple: drop the aarch64 machine interface upstream removed
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 478c28ff70 Revert "hvf: skip NO_RAW cpregs in hvf_arch_init_vcpu (macOS 26 host)"
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal bd66ba00cc hw/display/apple-gfx: run a window's guest at 1920x1080 by default
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 3c671094fa hw/display/apple-gfx: let reims-vgpu open a window for each display
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 40b8f64223 hw/display/apple-gfx: give a device up to 8 displays
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 55e557113a hw/display: name apple-gfx-pci's default romfile ReimsVgpu.rom
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 65d958d479 hw/display: give apple-gfx-pci Apple's option ROM as its default romfile
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 3777230b00 hw/display: find reims-vgpu through pkg-config
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal af066cdf8e hw/display: rewrite apple-gfx in C on reims-vgpu's own API
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.
2026-11-15 01:57:09 -08:00
Anees Iqbal 05c8180d63 hw/display: drop apple-gfx's pg backend
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.
2026-11-15 01:56:32 -08:00
Anees Iqbal c8acb07bdc hw/display: make reims apple-gfx's default, and pg the system's
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.
2026-11-15 01:56:32 -08:00
Anees Iqbal 94dd3a3dca hw/display: add a reims-vgpu backend for apple-gfx
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.
2026-11-15 01:56:32 -08:00
Anees Iqbal 196ef49505 hw/display: link apple-gfx against ParavirtualizedGraphics from source
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.
2026-11-15 01:56:32 -08:00
Anees Iqbal 32c0dbf71d hw/vmapple: build the machine only when apple-gfx is available
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.
2026-11-15 01:56:32 -08:00
Anees Iqbal 1161969f05 hvf: place the in-kernel vGIC at the machine's GIC bases
hvf_arch_vm_create() hardcoded the hv_gic distributor/redistributor GPAs
to hw/arm/virt.c's base_memmap (0x08000000/0x080A0000). On any machine
whose GICv3 lives elsewhere — vmapple puts it at 0x10000000/0x10010000 —
kernel-irqchip=on placed the in-kernel vGIC at addresses the guest never
touches, while the guest's dist/redist accesses landed on the GIC
device's ops-less MemoryRegions (reads-as-zero, writes ignored). A
vmapple macOS guest wedges in iBootStage2 that way (no timer PPI ever
enabled, one vCPU spins at 100%).

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

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

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

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

Patch 7 (private ISA / Tahoe) is deliberately excluded: it requires SIP
disabled + AMFI bypass, which this project does not do. This boots an arm
macOS Monterey guest under -M vmapple with HVF on a macOS 26 host.
2026-11-15 01:56:31 -08:00
136 changed files with 11436 additions and 2392 deletions

No files matched your search

+30
View File
@@ -0,0 +1,30 @@
# Configuration for Repo Lockdown - https://github.com/dessant/repo-lockdown
name: 'Repo Lockdown'
on:
pull_request_target:
types: opened
permissions:
pull-requests: write
jobs:
action:
runs-on: ubuntu-latest
steps:
- uses: dessant/repo-lockdown@v2
with:
pr-comment: |
Thank you for your interest in the QEMU project.
This repository is a read-only mirror of the project's repostories hosted
on https://gitlab.com/qemu-project/qemu.git.
The project does not process merge requests filed on GitHub.
QEMU welcomes contributions of code (either fixing bugs or adding new
functionality). However, we get a lot of patches, and so we have some
guidelines about contributing on the project website:
https://www.qemu.org/contribute/
lock-pr: true
close-pr: true
-91
View File
@@ -1,91 +0,0 @@
name: Merge upstream updates
on:
schedule:
- cron: '11 2 * * *'
workflow_dispatch:
permissions:
contents: write
concurrency:
group: merge-upstream-intel-vm-suspend
cancel-in-progress: false
jobs:
sync:
if: github.repository == 'reims-go/qemu-reims-vgpu'
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Merge upstream into the maintenance branch
shell: bash
env:
GH_TOKEN: ${{ github.token }}
TARGET_BRANCH: intel-vm-suspend
UPSTREAM_REPO: steelbrain/qemu-reims-vgpu
UPSTREAM_BRANCH: steelbrain/reims-vgpu-rebase-2
GIT_AUTHOR_NAME: YXC0915
GIT_AUTHOR_EMAIL: 62410385+yxc0915@users.noreply.github.com
GIT_COMMITTER_NAME: 'github-actions[bot]'
GIT_COMMITTER_EMAIL: '41898282+github-actions[bot]@users.noreply.github.com'
GIT_TERMINAL_PROMPT: '0'
run: |
set -euo pipefail
summary() {
printf '%s\n' "$1" | tee -a "$GITHUB_STEP_SUMMARY"
}
# Check ancestry on GitHub first so routine polls do not fetch QEMU history.
target_ref=${TARGET_BRANCH//\//%2F}
upstream_ref=${UPSTREAM_BRANCH//\//%2F}
status=$(gh api "repos/$GITHUB_REPOSITORY/compare/$target_ref...${UPSTREAM_REPO%%/*}:$upstream_ref?per_page=1" --jq .status)
case "$status" in
identical|behind)
summary "$TARGET_BRANCH already contains $UPSTREAM_REPO:$UPSTREAM_BRANCH."
exit 0
;;
ahead|diverged) ;;
*)
echo "::error::Unexpected upstream comparison status: $status"
exit 1
;;
esac
git init --bare --quiet "$RUNNER_TEMP/upstream-sync.git"
cd "$RUNNER_TEMP/upstream-sync.git"
git remote add origin "https://github.com/$GITHUB_REPOSITORY.git"
git remote add upstream "https://github.com/$UPSTREAM_REPO.git"
git fetch --no-tags --refmap= origin "refs/heads/$TARGET_BRANCH:refs/remotes/origin/target"
git fetch --no-tags --refmap= upstream "refs/heads/$UPSTREAM_BRANCH:refs/remotes/upstream/source"
target=$(git rev-parse refs/remotes/origin/target)
source=$(git rev-parse refs/remotes/upstream/source)
# Recheck ancestry using the exact commits that were fetched.
if git merge-base --is-ancestor "$source" "$target"; then
summary "$TARGET_BRANCH already contains upstream commit $source."
exit 0
fi
if git merge-base --is-ancestor "$target" "$source"; then
merged=$source
elif tree=$(git merge-tree --write-tree "$target" "$source"); then
merged=$(git commit-tree "$tree" -p "$target" -p "$source" \
-m "Merge $UPSTREAM_REPO:$UPSTREAM_BRANCH into $TARGET_BRANCH")
else
result=$?
printf '%s\n' "$tree" | sed 's/^/ /'
if [[ "$result" != 1 ]]; then
exit "$result"
fi
echo "::warning::Upstream merge has conflicts. The maintenance branch was not updated."
summary "Skipped merging $source into $TARGET_BRANCH at $target because of merge conflicts. See the job log."
exit 0
fi
# A normal push rejects a competing branch update and leaves its work intact.
auth=$(printf 'x-access-token:%s' "$GH_TOKEN" | base64 -w0)
echo "::add-mask::$auth"
git -c "http.https://github.com/.extraheader=AUTHORIZATION: basic $auth" \
push origin "$merged:refs/heads/$TARGET_BRANCH"
summary "Merged upstream commit $source into $TARGET_BRANCH at $merged."
+1 -1
View File
@@ -62,5 +62,5 @@ config HV_BALLOON_POSSIBLE
config HAVE_RUST
bool
config MAC_PVG
config REIMS_GRAPHICS
bool
+1 -5
View File
@@ -3044,11 +3044,6 @@ F: hw/display/edid*
F: include/hw/display/edid.h
F: qemu-edid.c
macOS PV Graphics (apple-gfx)
M: Phil Dennis-Jordan <phil@philjordan.eu>
S: Maintained
F: hw/display/apple-gfx*
PIIX4 South Bridge (i82371AB)
M: Hervé Poussineau <hpoussin@reactos.org>
M: Philippe Mathieu-Daudé <philmd@oss.qualcomm.com>
@@ -3218,6 +3213,7 @@ M: Phil Dennis-Jordan <phil@philjordan.eu>
S: Maintained
F: hw/vmapple/*
F: include/hw/vmapple/*
F: hw/usb/dev-vmapple-tablet.c
F: docs/system/arm/vmapple.rst
Nitro Enclaves (native)
+12
View File
@@ -59,6 +59,7 @@
#include "system/hvf.h"
#include "system/hvf_int.h"
#include <mach/mach_time.h>
#include <pthread/qos.h>
HVFState *hvf_state;
@@ -158,6 +159,17 @@ static void *hvf_cpu_thread_fn(void *arg)
assert(hvf_enabled());
/*
* The vCPU runs the guest at the user-initiated QoS, above the default
* QoS a build or any other CPU-bound process on the host runs at, and
* below the host's own user-interactive work. At the default QoS a vCPU
* running the guest's work is one CPU-bound thread among the build's,
* and loses its share to them: an arm64 macOS guest's timers then fire
* up to 1.9 s late and its display falls to 22 frames a second beside 64
* spinning processes on an M3 Max's 16 cores.
*/
pthread_set_qos_class_self_np(QOS_CLASS_USER_INITIATED, 0);
rcu_register_thread();
bql_lock();
+37
View File
@@ -1972,6 +1972,43 @@ static void kvm_region_commit(MemoryListener *listener)
kvm_slots_unlock();
}
bool kvm_unmap_before_del(uint64_t gpa, uint64_t size)
{
KVMState *s = kvm_state;
KVMMemoryListener *kml;
KVMSlot *mem;
bool done = false;
int i, err;
if (!s || size > kvm_max_slot_size) {
return false;
}
kvm_slots_lock();
for (i = 0; i < s->nr_as; i++) {
kml = s->as[i].ml;
mem = kml ? kvm_lookup_matching_slot(kml, gpa, size) : NULL;
/* A dirty log, which the removal syncs first, stays the removal's. */
if (!mem || (mem->flags & KVM_MEM_LOG_DIRTY_PAGES) ||
mem->guest_memfd >= 0) {
continue;
}
g_free(mem->dirty_bmap);
mem->dirty_bmap = NULL;
mem->memory_size = 0;
mem->flags = 0;
err = kvm_set_user_memory_region(kml, mem, false);
if (err) {
fprintf(stderr, "%s: error unregistering slot: %s\n",
__func__, strerror(-err));
abort();
}
kml->nr_slots_used--;
done = true;
}
kvm_slots_unlock();
return done;
}
static void kvm_log_sync(MemoryListener *listener,
MemoryRegionSection *section)
{
+5
View File
@@ -139,6 +139,11 @@ bool kvm_hwpoisoned_mem(void)
return false;
}
bool kvm_unmap_before_del(uint64_t gpa, uint64_t size)
{
return false;
}
int kvm_create_guest_memfd(uint64_t size, uint64_t flags, Error **errp)
{
error_setg(errp, "KVM is not enabled");
+29
View File
@@ -11,3 +11,32 @@
bool whpx_allowed;
bool whpx_irqchip_in_kernel;
bool whpx_send_msi_direct(uint64_t address, uint32_t data)
{
return false;
}
bool whpx_map_ahead(void *host, uint64_t gpa, uint64_t size)
{
return false;
}
void whpx_unmap_ahead(uint64_t gpa, uint64_t size, void *host)
{
}
bool whpx_unmap_before_del(uint64_t gpa, uint64_t size)
{
return false;
}
bool whpx_can_populate(void)
{
return false;
}
int whpx_populate(uint64_t gpa, uint64_t size)
{
return -ENOTSUP;
}
+216 -2
View File
@@ -17,6 +17,8 @@
#include "system/cpus.h"
#include "system/runstate.h"
#include "qemu/main-loop.h"
#include "qemu/queue.h"
#include "qemu/thread.h"
#include "hw/core/boards.h"
#include "hw/intc/ioapic.h"
#include "qemu/error-report.h"
@@ -48,8 +50,14 @@ struct WHPDispatch whp_dispatch;
void whpx_flush_cpu_state(CPUState *cpu)
{
if (cpu->vcpu_dirty) {
whpx_set_registers(cpu, WHPX_LEVEL_RUNTIME_STATE);
WHPXStateLevel level = (cpu->accel && cpu->accel->loadvm_pending)
? WHPX_LEVEL_FULL_STATE
: WHPX_LEVEL_RUNTIME_STATE;
whpx_set_registers(cpu, level);
cpu->vcpu_dirty = false;
if (cpu->accel) {
cpu->accel->loadvm_pending = false;
}
}
}
@@ -205,6 +213,19 @@ static void do_whpx_cpu_synchronize_pre_loadvm(CPUState *cpu,
run_on_cpu_data arg)
{
cpu->vcpu_dirty = true;
if (cpu->accel) {
cpu->accel->loadvm_pending = true;
}
}
static void do_whpx_cpu_synchronize_post_loadvm(CPUState *cpu,
run_on_cpu_data arg)
{
if (cpu->accel && cpu->accel->loadvm_pending) {
whpx_set_registers(cpu, WHPX_LEVEL_FULL_STATE);
cpu->vcpu_dirty = false;
cpu->accel->loadvm_pending = false;
}
}
/*
@@ -235,7 +256,36 @@ void whpx_cpu_synchronize_pre_loadvm(CPUState *cpu)
static void whpx_pre_resume_vm(AccelState *as, bool step_pending)
{
CPUState *cpu;
bool any_loadvm = false;
whpx_global.step_pending = step_pending;
CPU_FOREACH(cpu) {
if (cpu->accel && cpu->accel->loadvm_pending) {
any_loadvm = true;
break;
}
}
if (any_loadvm) {
uint64_t max_tsc = 0;
CPU_FOREACH(cpu) {
uint64_t t = cpu_env(cpu)->tsc;
if (t > max_tsc) {
max_tsc = t;
}
}
if (whp_dispatch.WHvSuspendPartitionTime) {
whp_dispatch.WHvSuspendPartitionTime(whpx_global.partition);
}
CPU_FOREACH(cpu) {
if (cpu->accel && cpu->accel->loadvm_pending) {
cpu_env(cpu)->tsc = max_tsc;
run_on_cpu(cpu, do_whpx_cpu_synchronize_post_loadvm,
RUN_ON_CPU_NULL);
}
}
}
}
/*
@@ -286,6 +336,161 @@ void whpx_vcpu_kick(CPUState *cpu)
* Memory support.
*/
/*
* The ranges a device mapped ahead of their RAM region's add
* (whpx_map_ahead), each until the listener meets its add; and those it
* unmapped ahead of their RAM region's removal (whpx_unmap_before_del), each
* until the listener meets the removal.
*/
typedef struct WhpxMappedAhead {
uint64_t gpa;
uint64_t size;
void *host;
QSLIST_ENTRY(WhpxMappedAhead) next;
} WhpxMappedAhead;
static QSLIST_HEAD(, WhpxMappedAhead) whpx_mapped_ahead =
QSLIST_HEAD_INITIALIZER(whpx_mapped_ahead);
static QSLIST_HEAD(, WhpxMappedAhead) whpx_unmapped_ahead =
QSLIST_HEAD_INITIALIZER(whpx_unmapped_ahead);
static QemuMutex whpx_mapped_ahead_lock;
static void __attribute__((__constructor__)) whpx_mapped_ahead_init(void)
{
qemu_mutex_init(&whpx_mapped_ahead_lock);
}
/*
* Takes the entry a device mapped ahead for exactly @gpa, @size and @host, if
* any: true where the listener's map of that section is already done.
*/
static bool whpx_take_mapped_ahead(uint64_t gpa, uint64_t size, void *host)
{
WhpxMappedAhead *m;
bool found = false;
qemu_mutex_lock(&whpx_mapped_ahead_lock);
QSLIST_FOREACH(m, &whpx_mapped_ahead, next) {
if (m->gpa == gpa && m->size == size && m->host == host) {
QSLIST_REMOVE(&whpx_mapped_ahead, m, WhpxMappedAhead, next);
g_free(m);
found = true;
break;
}
}
qemu_mutex_unlock(&whpx_mapped_ahead_lock);
return found;
}
bool whpx_map_ahead(void *host, uint64_t gpa, uint64_t size)
{
struct whpx_state *whpx = &whpx_global;
WhpxMappedAhead *m;
HRESULT hr;
hr = whp_dispatch.WHvMapGpaRange(whpx->partition, host, gpa, size,
WHvMapGpaRangeFlagRead |
WHvMapGpaRangeFlagWrite |
WHvMapGpaRangeFlagExecute);
if (FAILED(hr)) {
return false;
}
m = g_new0(WhpxMappedAhead, 1);
m->gpa = gpa;
m->size = size;
m->host = host;
qemu_mutex_lock(&whpx_mapped_ahead_lock);
QSLIST_INSERT_HEAD(&whpx_mapped_ahead, m, next);
qemu_mutex_unlock(&whpx_mapped_ahead_lock);
return true;
}
void whpx_unmap_ahead(uint64_t gpa, uint64_t size, void *host)
{
struct whpx_state *whpx = &whpx_global;
if (whpx_take_mapped_ahead(gpa, size, host)) {
whp_dispatch.WHvUnmapGpaRange(whpx->partition, gpa, size);
}
}
/*
* Takes the entry a device unmapped ahead for exactly @gpa and @size, if any:
* true where the listener's unmap of that section is already done.
*/
static bool whpx_take_unmapped_ahead(uint64_t gpa, uint64_t size)
{
WhpxMappedAhead *m;
bool found = false;
qemu_mutex_lock(&whpx_mapped_ahead_lock);
QSLIST_FOREACH(m, &whpx_unmapped_ahead, next) {
if (m->gpa == gpa && m->size == size) {
QSLIST_REMOVE(&whpx_unmapped_ahead, m, WhpxMappedAhead, next);
g_free(m);
found = true;
break;
}
}
qemu_mutex_unlock(&whpx_mapped_ahead_lock);
return found;
}
bool whpx_unmap_before_del(uint64_t gpa, uint64_t size)
{
struct whpx_state *whpx = &whpx_global;
WhpxMappedAhead *m, *a;
HRESULT hr;
m = g_new0(WhpxMappedAhead, 1);
m->gpa = gpa;
m->size = size;
qemu_mutex_lock(&whpx_mapped_ahead_lock);
QSLIST_FOREACH(a, &whpx_mapped_ahead, next) {
if (a->gpa == gpa) {
/* Its add is still to come: the listener unmaps it as usual. */
qemu_mutex_unlock(&whpx_mapped_ahead_lock);
g_free(m);
return false;
}
}
/* Recorded first: a removal the listener meets meanwhile unmaps nothing. */
QSLIST_INSERT_HEAD(&whpx_unmapped_ahead, m, next);
qemu_mutex_unlock(&whpx_mapped_ahead_lock);
hr = whp_dispatch.WHvUnmapGpaRange(whpx->partition, gpa, size);
if (FAILED(hr)) {
whpx_take_unmapped_ahead(gpa, size);
return false;
}
return true;
}
bool whpx_can_populate(void)
{
return whp_dispatch.WHvAdviseGpaRange != NULL;
}
int whpx_populate(uint64_t gpa, uint64_t size)
{
struct whpx_state *whpx = &whpx_global;
WHV_MEMORY_RANGE_ENTRY range = {
.GuestAddress = gpa,
.SizeInBytes = size,
};
WHV_ADVISE_GPA_RANGE_POPULATE populate = {
.AccessType = WHvMemoryAccessWrite,
};
HRESULT hr;
if (!whp_dispatch.WHvAdviseGpaRange) {
return -ENOTSUP;
}
hr = whp_dispatch.WHvAdviseGpaRange(whpx->partition, &range, 1,
WHvAdviseGpaRangeCodePopulate,
&populate, sizeof(populate));
return FAILED(hr) ? -EIO : 0;
}
static void whpx_set_phys_mem(MemoryRegionSection *section, bool add)
{
struct whpx_state *whpx = &whpx_global;
@@ -313,6 +518,10 @@ static void whpx_set_phys_mem(MemoryRegionSection *section, bool add)
}
if (!add) {
/* A device unmapped it ahead, outside the BQL: the unmap is done. */
if (whpx_take_unmapped_ahead(gva, size)) {
return;
}
hr = whp_dispatch.WHvUnmapGpaRange(whpx->partition,
gva, size);
if (FAILED(hr)) {
@@ -326,6 +535,11 @@ static void whpx_set_phys_mem(MemoryRegionSection *section, bool add)
| (writable ? WHvMapGpaRangeFlagWrite : 0);
mem = memory_region_get_ram_ptr(area) + section->offset_within_region;
/* A device mapped it ahead, outside the BQL: the map is done. */
if (writable && whpx_take_mapped_ahead(gva, size, mem)) {
return;
}
hr = whp_dispatch.WHvMapGpaRange(whpx->partition,
mem, gva, size, flags);
if (FAILED(hr)) {
@@ -359,7 +573,7 @@ static void whpx_log_sync(MemoryListener *listener,
{
MemoryRegion *mr = section->mr;
if (!memory_region_is_ram(mr)) {
if (!memory_region_is_ram(mr) || !runstate_is_running()) {
return;
}
+9
View File
@@ -145,6 +145,15 @@ void audio_be_set_active_out(AudioBackend *be, SWVoiceOut *sw, bool on)
return klass->set_active_out(be, sw, on);
}
void audio_be_kick(AudioBackend *be)
{
AudioBackendClass *klass = AUDIO_BACKEND_GET_CLASS(be);
if (klass->kick) {
klass->kick(be);
}
}
void audio_be_set_active_in(AudioBackend *be, SWVoiceIn *sw, bool on)
{
AudioBackendClass *klass = AUDIO_BACKEND_GET_CLASS(be);
+7
View File
@@ -1426,6 +1426,12 @@ static void audio_mixeng_backend_set_volume_out(AudioBackend *be, SWVoiceOut *sw
static void audio_mixeng_backend_set_volume_in(AudioBackend *be, SWVoiceIn *sw,
Volume *vol);
/* What the timer runs, between its runs: its period stays as it was. */
static void audio_mixeng_backend_kick(AudioBackend *be)
{
audio_run(AUDIO_MIXENG_BACKEND(be), "kick");
}
static void audio_mixeng_backend_class_init(ObjectClass *klass, const void *data)
{
AudioBackendClass *be = AUDIO_BACKEND_CLASS(klass);
@@ -1447,6 +1453,7 @@ static void audio_mixeng_backend_class_init(ObjectClass *klass, const void *data
be->get_buffer_size_out = audio_mixeng_backend_get_buffer_size_out;
be->add_capture = audio_mixeng_backend_add_capture;
be->del_capture = audio_mixeng_backend_del_capture;
be->kick = audio_mixeng_backend_kick;
}
static void audio_mixeng_backend_init(Object *obj)
+66
View File
@@ -0,0 +1,66 @@
/*
* QEMU DirectSound audio driver: its playback buffer's arithmetic
*
* Moved out of dsoundaudio.c, which builds only on Windows, unchanged, so
* that tests/unit/test-dsound-ring.c holds it on any host.
*
* SPDX-License-Identifier: MIT
*/
#ifndef AUDIO_DSOUND_RING_H
#define AUDIO_DSOUND_RING_H
#include "qemu/host-utils.h"
/*
* The reserve past the write cursor. An x86-64 macOS guest posts its periods
* on a 41.67 ms grid, their arrivals spread over 43 to 53 ms about their pace,
* and DirectSound's cursors move in 10 ms steps: 60 ms covers both, where the
* voice is written as each period comes.
*/
#define DSOUND_RESERVE_US 60000
/*
* The reserve in bytes of a voice of @freq frames a second and @bpf bytes a
* frame in a buffer of @size_emul bytes, where the write cursor leads the
* play cursor by @lead bytes: whole frames, as far as the play cursor at most.
*/
static inline size_t dsound_reserve(int freq, size_t bpf, size_t size_emul,
size_t lead)
{
size_t reserve = (size_t)muldiv64(freq, DSOUND_RESERVE_US,
1000000) * bpf;
return MIN(reserve, size_emul - lead) / bpf * bpf;
}
/* The play cursor @ppos at its frame's start. */
static inline size_t dsound_play_frame(size_t ppos, size_t bpf)
{
return ppos / bpf * bpf;
}
/* The first frame's start at or past the write cursor @wpos, in the buffer. */
static inline size_t dsound_write_frame(size_t wpos, size_t bpf,
size_t size_emul)
{
return (wpos + bpf - 1) / bpf * bpf % size_emul;
}
/*
* The bytes from the play cursor to the write position once the play cursor
* has moved @played bytes, @since_ns after its last read, of @filled before:
* none where it passed them all, or where most of a turn of the buffer
* (@buffer_ns) went by since, short of a stall of the main loop.
*/
static inline size_t dsound_filled_after(size_t filled, size_t played,
int64_t since_ns, int64_t buffer_ns)
{
if (played >= filled ||
since_ns >= buffer_ns / 4 * 3) {
return 0;
}
return filled - played;
}
#endif
+12
View File
@@ -195,7 +195,15 @@ static int dsound_init_out(HWVoiceOut *hw, struct audsettings *as)
memset (&bd, 0, sizeof (bd));
bd.dwSize = sizeof (bd);
bd.lpwfxFormat = &wfx;
#ifdef DSBTYPE_IN
bd.dwBufferBytes = audio_buffer_bytes(pdo, as, 92880);
#else
/*
* Twice the 92880 us of a capture buffer: room past the write cursor
* for dsound_place_out's reserve and the guest's periods beyond it.
*/
bd.dwBufferBytes = audio_buffer_bytes(pdo, as, 185760);
#endif
#ifdef DSBTYPE_IN
hr = IDirectSoundCapture_CreateCaptureBuffer (
s->dsound_capture,
@@ -253,6 +261,10 @@ static int dsound_init_out(HWVoiceOut *hw, struct audsettings *as)
}
hw->size_emul = bc.dwBufferBytes;
hw->samples = bc.dwBufferBytes / hw->info.bytes_per_frame;
#ifndef DSBTYPE_IN
ds->buffer_ns = muldiv64(hw->samples, NANOSECONDS_PER_SECOND,
hw->info.freq);
#endif
trace_dsound_buffer_bytes(bc.dwBufferBytes, bd.dwBufferBytes);
return 0;
+132 -13
View File
@@ -29,7 +29,9 @@
#include "qemu/osdep.h"
#include "qemu/audio.h"
#include "qemu/error-report.h"
#include "qemu/timer.h"
#include "audio_int.h"
#include "dsound-ring.h"
#include "qemu/module.h"
#include "qapi/error.h"
#include "qom/object.h"
@@ -55,10 +57,33 @@ struct AudioDsound {
struct audsettings settings;
};
/*
* A playback voice writes only past DirectSound's write cursor: the bytes
* between its play and write cursors DirectSound has mixed already, so what is
* written there is not heard, and the buffer's audio from one turn earlier
* plays in its place. The write position (hw.pos_emul) is placed
* DSOUND_RESERVE_US past the write cursor, with silence before it, when the
* voice starts, and again when the audio written runs out before the write
* cursor: a guest that hands its audio over in periods, their arrivals spread
* over some 50 ms about their pace, is played from that reserve without a
* gap, where its frontend has the voice written as each period comes
* (virtio-snd does). The reserve is latency. What the play cursor has passed
* becomes silence, so a gap plays silence.
*/
typedef struct {
HWVoiceOut hw;
LPDIRECTSOUNDBUFFER dsound_buffer;
bool first_time;
/* The bytes from the play cursor, at play_pos, to the write position. */
size_t filled;
DWORD play_pos;
/* When play_pos was read, and the buffer's length, in nanoseconds. */
int64_t play_ns;
int64_t buffer_ns;
/* Whether audio was written since the write position was placed. */
bool primed;
/* The times the audio written ran out before the write cursor. */
uint32_t gaps;
} DSoundVoiceOut;
typedef struct {
@@ -355,6 +380,8 @@ static void dsound_enable_out(HWVoiceOut *hw, bool enable)
}
dsound_clear_sample(hw, dsb, s);
/* The next read of the cursors places the write position. */
ds->first_time = true;
hr = IDirectSoundBuffer_Play(dsb, 0, 0, DSBPLAY_LOOPING);
if (FAILED(hr)) {
@@ -378,26 +405,101 @@ static void dsound_enable_out(HWVoiceOut *hw, bool enable)
}
}
/* Fill @len bytes of the buffer from @pos with silence. */
static void dsound_clear_out(HWVoiceOut *hw, DWORD pos, size_t len)
{
DSoundVoiceOut *ds = (DSoundVoiceOut *)hw;
size_t bpf = hw->info.bytes_per_frame;
LPVOID p1, p2;
DWORD blen1, blen2;
if (!len ||
dsound_lock_out(ds->dsound_buffer, &hw->info, pos, len, &p1, &p2,
&blen1, &blen2, 0, AUDIO_DSOUND(hw->s))) {
return;
}
if (p1 && blen1) {
audio_pcm_info_clear_buf(&hw->info, p1, blen1 / bpf);
}
if (p2 && blen2) {
audio_pcm_info_clear_buf(&hw->info, p2, blen2 / bpf);
}
dsound_unlock_out(ds->dsound_buffer, p1, p2, blen1, blen2);
}
/*
* Place the write position DSOUND_RESERVE_US past the write cursor @wpos, with
* silence from the write cursor to it. Where the buffer is too short for that,
* the write position goes as far as the play cursor.
*/
static void dsound_place_out(HWVoiceOut *hw, DWORD ppos, DWORD wpos)
{
DSoundVoiceOut *ds = (DSoundVoiceOut *)hw;
size_t bpf = hw->info.bytes_per_frame;
size_t lead = audio_ring_dist(wpos, ppos, hw->size_emul);
size_t reserve = dsound_reserve(hw->info.freq, bpf, hw->size_emul, lead);
if (ds->primed) {
ds->gaps++;
}
trace_dsound_place_out(hw, ppos, wpos, ds->filled, reserve, ds->primed,
ds->gaps);
dsound_clear_out(hw, wpos, reserve);
hw->pos_emul = (wpos + reserve) % hw->size_emul;
ds->filled = lead + reserve;
ds->primed = false;
}
static size_t dsound_buffer_get_free(HWVoiceOut *hw)
{
DSoundVoiceOut *ds = (DSoundVoiceOut *) hw;
LPDIRECTSOUNDBUFFER dsb = ds->dsound_buffer;
size_t bpf = hw->info.bytes_per_frame;
int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
size_t played;
HRESULT hr;
DWORD ppos, wpos;
hr = IDirectSoundBuffer_GetCurrentPosition(
dsb, &ppos, ds->first_time ? &wpos : NULL);
hr = IDirectSoundBuffer_GetCurrentPosition(dsb, &ppos, &wpos);
if (FAILED(hr)) {
dsound_logerr(hr, "Could not get playback buffer position");
return 0;
}
/* Whole frames: the play cursor's frame, and the first past the write's. */
ppos = dsound_play_frame(ppos, bpf);
wpos = dsound_write_frame(wpos, bpf, hw->size_emul);
/*
* The play cursor's advance since the last read, which reads it more
* often than once a turn of the buffer, short of a stall of the main
* loop: after one of most of a turn, the audio written counts as played.
* What it played becomes silence, which a gap then plays rather than the
* audio of a turn earlier.
*/
played = audio_ring_dist(ppos, ds->play_pos, hw->size_emul);
if (ds->first_time) {
hw->pos_emul = wpos;
ds->first_time = false;
ds->primed = false;
} else {
dsound_clear_out(hw, ds->play_pos, played);
ds->filled = dsound_filled_after(ds->filled, played,
now - ds->play_ns, ds->buffer_ns);
}
ds->play_pos = ppos;
ds->play_ns = now;
return audio_ring_dist(ppos, hw->pos_emul, hw->size_emul);
/*
* Until audio comes, the write position keeps its place past the write
* cursor; once the audio written runs out before the write cursor, it
* takes it again, a gap of silence.
*/
if (!ds->primed ||
ds->filled < audio_ring_dist(wpos, ppos, hw->size_emul)) {
dsound_place_out(hw, ppos, wpos);
}
trace_dsound_buffer_get_free(hw, ppos, wpos, ds->filled);
return hw->size_emul - ds->filled;
}
static void *dsound_get_buffer_out(HWVoiceOut *hw, size_t *size)
@@ -409,8 +511,13 @@ static void *dsound_get_buffer_out(HWVoiceOut *hw, size_t *size)
int err;
void *ret;
/* Never over audio not yet played. */
req_size = MIN(*size, hw->size_emul - hw->pos_emul);
assert(req_size > 0);
req_size = MIN(req_size, hw->size_emul - ds->filled);
if (!req_size) {
*size = 0;
return NULL;
}
err = dsound_lock_out(dsb, &hw->info, hw->pos_emul, req_size, &ret, NULL,
&act_size, NULL, false, AUDIO_DSOUND(hw->s));
@@ -435,6 +542,10 @@ static size_t dsound_put_buffer_out(HWVoiceOut *hw, void *buf, size_t len)
return 0;
}
hw->pos_emul = (hw->pos_emul + len) % hw->size_emul;
ds->filled += len;
if (len) {
ds->primed = true;
}
return len;
}
@@ -610,6 +721,11 @@ audio_dsound_realize(AudioBackend *abe, Audiodev *dev, Error **errp)
return false;
}
/*
* Capture is optional: a host with no recording device (no microphone)
* still plays sound. Without the capture object, an input voice fails to
* initialize (dsound_init_in).
*/
hr = CoCreateInstance (
&CLSID_DirectSoundCapture,
NULL,
@@ -618,14 +734,17 @@ audio_dsound_realize(AudioBackend *abe, Audiodev *dev, Error **errp)
(void **) &s->dsound_capture
);
if (FAILED (hr)) {
dserror_set(errp, hr, "Could not create DirectSoundCapture instance");
return false;
}
hr = IDirectSoundCapture_Initialize (s->dsound_capture, NULL);
if (FAILED(hr)) {
dserror_set(errp, hr, "Could not initialize DirectSoundCapture");
return false;
dsound_logerr(hr, "Could not create DirectSoundCapture instance, "
"no recording");
s->dsound_capture = NULL;
} else {
hr = IDirectSoundCapture_Initialize (s->dsound_capture, NULL);
if (FAILED(hr)) {
dsound_logerr(hr, "Could not initialize DirectSoundCapture, "
"no recording");
IDirectSoundCapture_Release (s->dsound_capture);
s->dsound_capture = NULL;
}
}
hr = IDirectSound_SetCooperativeLevel (
+164 -80
View File
@@ -40,12 +40,22 @@ typedef struct {
AudioPa *g;
} PAVoiceOut;
/*
* A capture voice has a record stream only while the voice is enabled, so
* the host's sound server lists a recording client only while the guest
* captures. What the stream opens with, and the guest's last volume for
* it, are kept with the voice.
*/
typedef struct {
HWVoiceIn hw;
pa_stream *stream;
const void *read_data;
size_t read_length;
AudioPa *g;
pa_sample_spec ss;
pa_buffer_attr ba;
bool has_volume;
Volume volume;
} PAVoiceIn;
static void qpa_conn_fini(PAConnection *c);
@@ -92,8 +102,15 @@ static void *qpa_get_buffer_in(HWVoiceIn *hw, size_t *size)
pa_threaded_mainloop_lock(c->mainloop);
if (!p->stream) {
goto unlock_empty;
}
CHECK_DEAD_GOTO(c, p->stream, unlock_and_fail,
"pa_threaded_mainloop_lock failed");
if (pa_stream_get_state(p->stream) != PA_STREAM_READY) {
/* wait for stream to become ready */
goto unlock_empty;
}
if (!p->read_length) {
r = pa_stream_peek(p->stream, &p->read_data, &p->read_length);
@@ -107,6 +124,7 @@ static void *qpa_get_buffer_in(HWVoiceIn *hw, size_t *size)
return (void *) p->read_data;
unlock_and_fail:
unlock_empty:
pa_threaded_mainloop_unlock(c->mainloop);
*size = 0;
return NULL;
@@ -120,6 +138,9 @@ static void qpa_put_buffer_in(HWVoiceIn *hw, void *buf, size_t size)
pa_threaded_mainloop_lock(c->mainloop);
if (!p->stream) {
goto unlock;
}
CHECK_DEAD_GOTO(c, p->stream, unlock,
"pa_threaded_mainloop_lock failed");
@@ -145,6 +166,9 @@ static size_t qpa_read(HWVoiceIn *hw, void *data, size_t length)
pa_threaded_mainloop_lock(c->mainloop);
if (!p->stream) {
goto unlock;
}
CHECK_DEAD_GOTO(c, p->stream, unlock_and_fail,
"pa_threaded_mainloop_lock failed");
if (pa_stream_get_state(p->stream) != PA_STREAM_READY) {
@@ -398,6 +422,54 @@ static void stream_state_cb (pa_stream *s, void * userdata)
}
}
/* The channel map of a stream of CHANNELS, false where none is known */
static bool qpa_channel_map_init(pa_channel_map *map, int channels)
{
pa_channel_map_init(map);
map->channels = channels;
/*
* TODO: This currently expects the only frontend supporting more than 2
* channels is the usb-audio. We will need some means to set channel
* order when a new frontend gains multi-channel support.
*/
switch (channels) {
case 1:
map->map[0] = PA_CHANNEL_POSITION_MONO;
break;
case 2:
map->map[0] = PA_CHANNEL_POSITION_LEFT;
map->map[1] = PA_CHANNEL_POSITION_RIGHT;
break;
case 6:
map->map[0] = PA_CHANNEL_POSITION_FRONT_LEFT;
map->map[1] = PA_CHANNEL_POSITION_FRONT_RIGHT;
map->map[2] = PA_CHANNEL_POSITION_CENTER;
map->map[3] = PA_CHANNEL_POSITION_LFE;
map->map[4] = PA_CHANNEL_POSITION_REAR_LEFT;
map->map[5] = PA_CHANNEL_POSITION_REAR_RIGHT;
break;
case 8:
map->map[0] = PA_CHANNEL_POSITION_FRONT_LEFT;
map->map[1] = PA_CHANNEL_POSITION_FRONT_RIGHT;
map->map[2] = PA_CHANNEL_POSITION_CENTER;
map->map[3] = PA_CHANNEL_POSITION_LFE;
map->map[4] = PA_CHANNEL_POSITION_REAR_LEFT;
map->map[5] = PA_CHANNEL_POSITION_REAR_RIGHT;
map->map[6] = PA_CHANNEL_POSITION_SIDE_LEFT;
map->map[7] = PA_CHANNEL_POSITION_SIDE_RIGHT;
break;
default:
error_report("pulseaudio: unsupported channel count %d", channels);
return false;
}
return true;
}
static pa_stream *qpa_simple_new (
PAConnection *c,
const char *name,
@@ -405,6 +477,8 @@ static pa_stream *qpa_simple_new (
const char *dev,
const pa_sample_spec *ss,
const pa_buffer_attr *attr,
pa_stream_notify_cb_t state_cb,
void *state_userdata,
int *rerror)
{
int r;
@@ -414,46 +488,7 @@ static pa_stream *qpa_simple_new (
pa_threaded_mainloop_lock(c->mainloop);
pa_channel_map_init(&map);
map.channels = ss->channels;
/*
* TODO: This currently expects the only frontend supporting more than 2
* channels is the usb-audio. We will need some means to set channel
* order when a new frontend gains multi-channel support.
*/
switch (ss->channels) {
case 1:
map.map[0] = PA_CHANNEL_POSITION_MONO;
break;
case 2:
map.map[0] = PA_CHANNEL_POSITION_LEFT;
map.map[1] = PA_CHANNEL_POSITION_RIGHT;
break;
case 6:
map.map[0] = PA_CHANNEL_POSITION_FRONT_LEFT;
map.map[1] = PA_CHANNEL_POSITION_FRONT_RIGHT;
map.map[2] = PA_CHANNEL_POSITION_CENTER;
map.map[3] = PA_CHANNEL_POSITION_LFE;
map.map[4] = PA_CHANNEL_POSITION_REAR_LEFT;
map.map[5] = PA_CHANNEL_POSITION_REAR_RIGHT;
break;
case 8:
map.map[0] = PA_CHANNEL_POSITION_FRONT_LEFT;
map.map[1] = PA_CHANNEL_POSITION_FRONT_RIGHT;
map.map[2] = PA_CHANNEL_POSITION_CENTER;
map.map[3] = PA_CHANNEL_POSITION_LFE;
map.map[4] = PA_CHANNEL_POSITION_REAR_LEFT;
map.map[5] = PA_CHANNEL_POSITION_REAR_RIGHT;
map.map[6] = PA_CHANNEL_POSITION_SIDE_LEFT;
map.map[7] = PA_CHANNEL_POSITION_SIDE_RIGHT;
break;
default:
error_report("pulseaudio: unsupported channel count %d", ss->channels);
if (!qpa_channel_map_init(&map, ss->channels)) {
goto fail;
}
@@ -462,7 +497,7 @@ static pa_stream *qpa_simple_new (
goto fail;
}
pa_stream_set_state_callback(stream, stream_state_cb, c);
pa_stream_set_state_callback(stream, state_cb, state_userdata);
flags = PA_STREAM_EARLY_REQUESTS;
@@ -530,6 +565,8 @@ static int qpa_init_out(HWVoiceOut *hw, struct audsettings *as)
ppdo->name,
&ss,
&ba, /* buffering attributes */
stream_state_cb,
c,
&error
);
if (!pa->stream) {
@@ -552,51 +589,37 @@ static int qpa_init_in(HWVoiceIn *hw, struct audsettings *as)
{
AudioMixengBackend *amb = hw->s;
AudioPa *apa = AUDIO_PA(amb);
int error;
pa_sample_spec ss;
pa_buffer_attr ba;
struct audsettings obt_as = *as;
PAVoiceIn *pa = (PAVoiceIn *) hw;
AudiodevPaOptions *popts = &amb->dev->u.pa;
AudiodevPaPerDirectionOptions *ppdo = popts->in;
PAConnection *c = apa->conn;
pa_channel_map map;
pa->g = apa;
ss.format = audfmt_to_pa (as->fmt, as->big_endian);
ss.channels = as->nchannels;
ss.rate = as->freq;
pa->ss.format = audfmt_to_pa (as->fmt, as->big_endian);
pa->ss.channels = as->nchannels;
pa->ss.rate = as->freq;
ba.fragsize = pa_usec_to_bytes((amb->dev->timer_period >> 1) * 3, &ss);
ba.maxlength = pa_usec_to_bytes(
MAX(ppdo->latency, amb->dev->timer_period * 3), &ss);
ba.minreq = -1;
ba.prebuf = -1;
pa->ba.fragsize = pa_usec_to_bytes((amb->dev->timer_period >> 1) * 3,
&pa->ss);
pa->ba.maxlength = pa_usec_to_bytes(
MAX(ppdo->latency, amb->dev->timer_period * 3), &pa->ss);
pa->ba.minreq = -1;
pa->ba.prebuf = -1;
obt_as.fmt = pa_to_audfmt (ss.format, &obt_as.big_endian);
pa->stream = qpa_simple_new (
c,
ppdo->stream_name ?: amb->dev->id,
PA_STREAM_RECORD,
ppdo->name,
&ss,
&ba, /* buffering attributes */
&error
);
if (!pa->stream) {
qpa_logerr(error, "pa_simple_new for capture failed");
goto fail1;
/* What the record stream would refuse, refused before it is opened */
if (!qpa_channel_map_init(&map, pa->ss.channels)) {
return -1;
}
obt_as.fmt = pa_to_audfmt (pa->ss.format, &obt_as.big_endian);
audio_pcm_init_info (&hw->info, &obt_as);
/* hw->samples counts in frames */
hw->samples = audio_buffer_frames(
qapi_AudiodevPaPerDirectionOptions_base(ppdo), &obt_as, 46440);
return 0;
fail1:
return -1;
}
static void qpa_simple_disconnect(PAConnection *c, pa_stream *stream)
@@ -632,10 +655,8 @@ static void qpa_fini_out (HWVoiceOut *hw)
}
}
static void qpa_fini_in (HWVoiceIn *hw)
static void qpa_close_in(PAVoiceIn *pa)
{
PAVoiceIn *pa = (PAVoiceIn *) hw;
if (pa->stream) {
PAConnection *c = pa->g->conn;
@@ -654,6 +675,11 @@ static void qpa_fini_in (HWVoiceIn *hw)
}
}
static void qpa_fini_in (HWVoiceIn *hw)
{
qpa_close_in((PAVoiceIn *) hw);
}
static void qpa_volume_out(HWVoiceOut *hw, Volume *vol)
{
PAVoiceOut *pa = (PAVoiceOut *) hw;
@@ -694,12 +720,12 @@ static void qpa_volume_out(HWVoiceOut *hw, Volume *vol)
pa_threaded_mainloop_unlock(c->mainloop);
}
static void qpa_volume_in(HWVoiceIn *hw, Volume *vol)
/* Give a record stream the guest's volume, with the mainloop locked */
static void qpa_set_source_output_volume(PAConnection *c, pa_stream *stream,
Volume *vol)
{
PAVoiceIn *pa = (PAVoiceIn *) hw;
pa_operation *op;
pa_cvolume v;
PAConnection *c = pa->g->conn;
int i;
pa_cvolume_init(&v);
@@ -709,10 +735,8 @@ static void qpa_volume_in(HWVoiceIn *hw, Volume *vol)
v.values[i] = ((PA_VOLUME_NORM - PA_VOLUME_MUTED) * vol->vol[i]) / 255;
}
pa_threaded_mainloop_lock(c->mainloop);
op = pa_context_set_source_output_volume(c->context,
pa_stream_get_index(pa->stream),
pa_stream_get_index(stream),
&v, NULL, NULL);
if (!op) {
qpa_logerr(pa_context_errno(c->context),
@@ -722,7 +746,7 @@ static void qpa_volume_in(HWVoiceIn *hw, Volume *vol)
}
op = pa_context_set_source_output_mute(c->context,
pa_stream_get_index(pa->stream),
pa_stream_get_index(stream),
vol->mute, NULL, NULL);
if (!op) {
qpa_logerr(pa_context_errno(c->context),
@@ -730,10 +754,69 @@ static void qpa_volume_in(HWVoiceIn *hw, Volume *vol)
} else {
pa_operation_unref(op);
}
}
static void qpa_volume_in(HWVoiceIn *hw, Volume *vol)
{
PAVoiceIn *pa = (PAVoiceIn *) hw;
PAConnection *c = pa->g->conn;
pa_threaded_mainloop_lock(c->mainloop);
pa->volume = *vol;
pa->has_volume = true;
if (pa->stream && pa_stream_get_state(pa->stream) == PA_STREAM_READY) {
qpa_set_source_output_volume(c, pa->stream, vol);
}
pa_threaded_mainloop_unlock(c->mainloop);
}
/* A record stream takes the guest's last volume as it becomes ready */
static void record_state_cb(pa_stream *s, void *userdata)
{
PAVoiceIn *pa = userdata;
if (pa_stream_get_state(s) == PA_STREAM_READY && pa->has_volume) {
qpa_set_source_output_volume(pa->g->conn, s, &pa->volume);
}
stream_state_cb(s, pa->g->conn);
}
/*
* The record stream opens as the guest's capture starts, and closes as it
* stops.
*/
static void qpa_enable_in(HWVoiceIn *hw, bool enable)
{
PAVoiceIn *pa = (PAVoiceIn *) hw;
AudioMixengBackend *amb = hw->s;
AudiodevPaPerDirectionOptions *ppdo = amb->dev->u.pa.in;
int error;
if (!enable) {
qpa_close_in(pa);
return;
}
if (pa->stream) {
return;
}
pa->stream = qpa_simple_new (
pa->g->conn,
ppdo->stream_name ?: amb->dev->id,
PA_STREAM_RECORD,
ppdo->name,
&pa->ss,
&pa->ba, /* buffering attributes */
record_state_cb,
pa,
&error
);
if (!pa->stream) {
qpa_logerr(error, "pa_simple_new for capture failed");
}
}
static void qpa_validate_per_direction_opts(Audiodev *dev,
AudiodevPaPerDirectionOptions *pdo)
{
@@ -916,6 +999,7 @@ static void audio_pa_class_init(ObjectClass *klass, const void *data)
k->read = qpa_read;
k->get_buffer_in = qpa_get_buffer_in;
k->put_buffer_in = qpa_put_buffer_in;
k->enable_in = qpa_enable_in;
k->volume_in = qpa_volume_in;
}
+76 -6
View File
@@ -60,6 +60,18 @@ typedef struct PWVoice {
pwvolume volume;
bool muted;
/*
* The capture overruns: the cycles that found the ring full, and the
* bytes they dropped. Written on PipeWire's data thread, read once the
* stream is gone.
*/
uint64_t overruns, overrun_bytes;
/*
* The bytes qpw_read skipped in a full ring to read its newest audio.
* Written by the reader, read once the stream is gone.
*/
uint64_t skipped_bytes;
} PWVoice;
typedef struct PWVoiceOut {
@@ -184,12 +196,25 @@ capture_on_process(void *data)
error_report("%p: underrun write:%u filled:%d", p, index, filled);
pw_stream_queue_buffer(v->stream, b);
return;
} else {
if ((uint32_t) filled + n_bytes > RINGBUFFER_SIZE) {
error_report("%p: overrun write:%u filled:%d + size:%u > max:%u",
p, index, filled, n_bytes, RINGBUFFER_SIZE);
n_bytes = RINGBUFFER_SIZE - (uint32_t)filled;
} else if ((uint32_t) filled + n_bytes > RINGBUFFER_SIZE) {
/*
* Nothing has read the ring for as long as it holds: the guest's
* input stream runs, and the guest takes none of it. The source runs
* on, a cycle each quantum (every 5.3 ms at 256 frames of 48 kHz),
* each finding the ring full: what does not fit is dropped, said at
* the first such cycle and counted, and the count is said as the
* stream closes.
*/
uint32_t room = RINGBUFFER_SIZE - (uint32_t)filled;
if (v->overruns++ == 0) {
warn_report("pipewire: capture stream %s: its %u-byte buffer is "
"full of audio nothing has read: captured audio is "
"dropped while it stays full, and counted",
pw_stream_get_name(v->stream), RINGBUFFER_SIZE);
}
v->overrun_bytes += n_bytes - room;
n_bytes = room;
}
spa_ringbuffer_write_data(&v->ring,
v->buffer, RINGBUFFER_SIZE,
@@ -252,6 +277,22 @@ qpw_read(HWVoiceIn *hw, void *data, size_t len)
goto done_unlock;
}
if ((uint32_t)avail >= RINGBUFFER_SIZE && (size_t)avail > len) {
/*
* A full ring holds its oldest audio: capture_on_process drops what
* does not fit. Read from its start, it would give the reader as
* much stale audio as it holds (about 24 s of 16-bit stereo at
* 44.1 kHz), and that delay for the rest of the stream. Skip to the
* newest len bytes, in whole frames, and count what is skipped. A
* reader that keeps up never finds the ring full.
*/
uint32_t skip = ((uint32_t)avail - len) / v->frame_size * v->frame_size;
index += skip;
avail -= skip;
v->skipped_bytes += skip;
}
if ((size_t)avail < len) {
len = avail;
}
@@ -630,13 +671,26 @@ qpw_init_in(HWVoiceIn *hw, struct audsettings *as)
static void
qpw_voice_fini(AudioPw *c, PWVoice *v)
{
g_autofree char *name = NULL;
if (!v->stream) {
return;
}
pw_thread_loop_lock(c->thread_loop);
name = g_strdup(pw_stream_get_name(v->stream));
pw_stream_destroy(v->stream);
v->stream = NULL;
pw_thread_loop_unlock(c->thread_loop);
if (v->overruns) {
info_report("pipewire: capture stream %s: %" PRIu64 " bytes of "
"captured audio dropped in %" PRIu64 " cycles that found "
"its buffer full", name, v->overrun_bytes, v->overruns);
}
if (v->skipped_bytes) {
info_report("pipewire: capture stream %s: %" PRIu64 " bytes of its "
"oldest audio skipped to read the newest", name,
v->skipped_bytes);
}
}
static void
@@ -668,7 +722,23 @@ qpw_enable_out(HWVoiceOut *hw, bool enable)
static void
qpw_enable_in(HWVoiceIn *hw, bool enable)
{
qpw_voice_set_enabled(AUDIO_PW(hw->s), &PW_VOICE_IN(hw)->v, enable);
AudioPw *c = AUDIO_PW(hw->s);
PWVoice *v = &PW_VOICE_IN(hw)->v;
if (enable) {
uint32_t index;
/*
* What the stream captured before it stopped is stale: a capture
* that starts again gives the reader what the source captures from
* then on, as ALSA's snd_pcm_drop and snd_pcm_start do for alsa.
*/
pw_thread_loop_lock(c->thread_loop);
spa_ringbuffer_get_write_index(&v->ring, &index);
spa_ringbuffer_read_update(&v->ring, index);
pw_thread_loop_unlock(c->thread_loop);
}
qpw_voice_set_enabled(c, v, enable);
}
static void
+2
View File
@@ -32,6 +32,8 @@ dbus_audio_read(size_t len) "len = %zu"
dsound_clear_sample(void *p1, uint32_t blen1, uint32_t len1, void *p2, uint32_t blen2, uint32_t len2) "p1=%p, blen1=%u, len1=%u, p2=%p, blen2=%u, len2=%u"
dsound_wave_format(uint16_t wFormatTag, uint16_t nChannels, uint32_t nSamplesPerSec, uint32_t nAvgBytesPerSec, uint16_t nBlockAlign, uint16_t wBitsPerSample, uint16_t cbSize) "wFormatTag=%u, nChannels=%u, nSamplesPerSec=%u, nAvgBytesPerSec=%u, nBlockAlign=%u, wBitsPerSample=%u, cbSize=%u"
dsound_buffer_bytes(uint32_t caps_bytes, uint32_t desc_bytes) "caps_bytes=%u, desc_bytes=%u"
dsound_buffer_get_free(void *voice, uint32_t play, uint32_t write, uint32_t filled) "voice=%p, play=%u, write=%u, filled=%u"
dsound_place_out(void *voice, uint32_t play, uint32_t write, uint32_t filled, uint32_t reserve, bool gap, uint32_t gaps) "voice=%p, play=%u, write=%u, filled=%u, reserve=%u, gap=%d, gaps=%u"
# jackaudio.c
jack_client_recover(void) "attempting to reconnect to server"
+55
View File
@@ -24,6 +24,8 @@
#include "qemu/mmap-alloc.h"
#include "qemu/madvise.h"
#include "qemu/cutils.h"
#include "qemu/error-report.h"
#include "qemu/units.h"
#include "hw/core/qdev.h"
#ifdef CONFIG_NUMA
@@ -332,6 +334,58 @@ size_t host_memory_backend_pagesize(HostMemoryBackend *memdev)
return pagesize;
}
/*
* Put a shared file's preallocated RAM, a memfd's shmem among it, on
* transparent huge pages, 2 MiB at a time, on Linux. At a fault the kernel
* backs shmem with a huge page only where
* /sys/kernel/mm/transparent_hugepage/shmem_enabled lets it (advise with
* QEMU_MADV_HUGEPAGE, always, within_size) and a free 2 MiB page is found;
* at never, most distributions' default, the guest runs on 4 KiB pages
* alone. MADV_COLLAPSE (Linux 6.1) copies a 2 MiB range onto one huge page
* at any shmem_enabled but deny, and leaves a range already on one as it is.
* It runs before any device is realized, so before a device pins guest
* pages, which would keep them where they are. A range it cannot collapse
* stays on its pages; one line says how much is on huge pages, and the first
* failure. An async prealloc (prealloc-context) has not run yet here: none.
*/
static void host_memory_backend_collapse(HostMemoryBackend *backend,
void *ptr, uint64_t sz,
size_t pagesize, bool async)
{
#if defined(CONFIG_LINUX) && (defined(__x86_64__) || defined(__aarch64__))
#ifndef MADV_COLLAPSE
#define MADV_COLLAPSE 25
#endif
const uintptr_t huge = 2 * MiB;
uintptr_t start = QEMU_ALIGN_UP((uintptr_t)ptr, huge);
uintptr_t end = QEMU_ALIGN_DOWN((uintptr_t)ptr + sz, huge);
g_autofree char *name = NULL;
uint64_t done = 0;
int64_t t0;
int err = 0;
/* A 2 MiB page is a huge page only over 4 KiB base pages. */
if (!backend->prealloc || !backend->share ||
(async && backend->prealloc_context) ||
memory_region_get_fd(&backend->mr) < 0 || pagesize != 4 * KiB) {
return;
}
t0 = g_get_monotonic_time();
for (uintptr_t addr = start; addr < end; addr += huge) {
if (madvise((void *)addr, huge, MADV_COLLAPSE) == 0) {
done += huge;
} else if (!err) {
err = errno;
}
}
name = host_memory_backend_get_name(backend);
info_report("memory backend '%s': %" PRIu64 " of %" PRIu64 " bytes on "
"huge pages after MADV_COLLAPSE, in %" PRId64 " ms%s%s",
name, done, sz, (g_get_monotonic_time() - t0) / 1000,
err ? "; first failure: " : "", err ? strerror(err) : "");
#endif
}
static void
host_memory_backend_memory_complete(UserCreatable *uc, Error **errp)
{
@@ -432,6 +486,7 @@ host_memory_backend_memory_complete(UserCreatable *uc, Error **errp)
async, errp)) {
return;
}
host_memory_backend_collapse(backend, ptr, sz, pagesize, async);
}
static bool
+373 -165
View File
@@ -25,6 +25,8 @@
#include "qemu/osdep.h"
#include "qapi/error.h"
#include "qemu/cutils.h"
#include "qemu/host-utils.h"
#include "qemu/memalign.h"
#include "block/block-io.h"
#include "block/block_int.h"
#include "qemu/module.h"
@@ -43,12 +45,11 @@
#define FTYPE_HARDDISK 2
typedef struct RawWin32AIOData {
BlockDriverState *bs;
HANDLE hfile;
struct iovec *aio_iov;
int aio_niov;
QEMUIOVector *qiov;
void *bounce_buf;
size_t aio_nbytes;
off64_t aio_offset;
int64_t aio_offset;
int aio_type;
} RawWin32AIOData;
@@ -57,85 +58,117 @@ typedef struct BDRVRawState {
int type;
char drive_path[16]; /* format: "d:\" */
QEMUWin32AIOState *aio;
bool needs_alignment;
uint32_t probed_req_align;
uint32_t probed_mem_align;
} BDRVRawState;
typedef struct BDRVRawReopenState {
HANDLE hfile;
bool needs_alignment;
uint32_t probed_req_align;
uint32_t probed_mem_align;
} BDRVRawReopenState;
/*
* Read/writes the data to/from a given linear buffer.
*
* Returns the number of bytes handles or -errno in case of an error. Short
* reads are only returned if the end of the file is reached.
*/
static size_t handle_aiocb_rw(RawWin32AIOData *aiocb)
static int win32_error_to_errno(DWORD err)
{
size_t offset = 0;
int i;
switch (err) {
case ERROR_DISK_FULL:
case ERROR_HANDLE_DISK_FULL:
return -ENOSPC;
case ERROR_ACCESS_DENIED:
return -EACCES;
case ERROR_INVALID_PARAMETER:
return -EINVAL;
case ERROR_OPERATION_ABORTED:
return -ECANCELED;
case ERROR_NOT_ENOUGH_MEMORY:
case ERROR_OUTOFMEMORY:
return -ENOMEM;
default:
return -EIO;
}
}
for (i = 0; i < aiocb->aio_niov; i++) {
OVERLAPPED ov;
DWORD ret, ret_count, len;
static int handle_aiocb_rw(RawWin32AIOData *aiocb, size_t *transferred)
{
QEMUIOVector *qiov = aiocb->qiov;
struct iovec bounce_iov = {
.iov_base = aiocb->bounce_buf,
.iov_len = aiocb->aio_nbytes,
};
const struct iovec *iov = aiocb->bounce_buf ? &bounce_iov : qiov->iov;
int niov = aiocb->bounce_buf ? 1 : qiov->niov;
bool is_read = (aiocb->aio_type & QEMU_AIO_TYPE_MASK) == QEMU_AIO_READ;
memset(&ov, 0, sizeof(ov));
ov.Offset = (aiocb->aio_offset + offset);
ov.OffsetHigh = (aiocb->aio_offset + offset) >> 32;
len = aiocb->aio_iov[i].iov_len;
if (aiocb->aio_type & QEMU_AIO_WRITE) {
ret = WriteFile(aiocb->hfile, aiocb->aio_iov[i].iov_base,
len, &ret_count, &ov);
*transferred = 0;
for (int i = 0; i < niov; i++) {
uint64_t offset = aiocb->aio_offset + *transferred;
OVERLAPPED ov = {
.Offset = (DWORD)offset,
.OffsetHigh = (DWORD)(offset >> 32),
};
DWORD len = (DWORD)iov[i].iov_len;
DWORD count;
BOOL ok;
if (len == 0) {
continue;
}
if (is_read) {
ok = ReadFile(aiocb->hfile, iov[i].iov_base, len, &count, &ov);
} else {
ret = ReadFile(aiocb->hfile, aiocb->aio_iov[i].iov_base,
len, &ret_count, &ov);
ok = WriteFile(aiocb->hfile, iov[i].iov_base, len, &count, &ov);
}
if (!ret) {
ret_count = 0;
if (!ok) {
DWORD err = GetLastError();
if (is_read && err == ERROR_HANDLE_EOF) {
return 0;
}
return win32_error_to_errno(err);
}
if (ret_count != len) {
offset += ret_count;
if (count > len) {
return -EIO;
}
*transferred += count;
if (count < len) {
break;
}
offset += len;
}
return offset;
return 0;
}
static int aio_worker(void *arg)
{
RawWin32AIOData *aiocb = arg;
ssize_t ret = 0;
int ret = 0;
size_t count;
QEMUIOVector *qiov = aiocb->qiov;
switch (aiocb->aio_type & QEMU_AIO_TYPE_MASK) {
case QEMU_AIO_READ:
count = handle_aiocb_rw(aiocb);
if (count < aiocb->aio_nbytes) {
/* A short read means that we have reached EOF. Pad the buffer
* with zeros for bytes after EOF. */
iov_memset(aiocb->aio_iov, aiocb->aio_niov, count,
0, aiocb->aio_nbytes - count);
count = aiocb->aio_nbytes;
ret = handle_aiocb_rw(aiocb, &count);
if (ret < 0) {
break;
}
if (count == aiocb->aio_nbytes) {
ret = 0;
} else {
ret = -EINVAL;
if (aiocb->bounce_buf && count) {
iov_from_buf(qiov->iov, qiov->niov, 0, aiocb->bounce_buf, count);
}
if (count < aiocb->aio_nbytes) {
qemu_iovec_memset(qiov, count, 0, aiocb->aio_nbytes - count);
}
break;
case QEMU_AIO_WRITE:
count = handle_aiocb_rw(aiocb);
if (count == aiocb->aio_nbytes) {
ret = 0;
} else {
ret = -EINVAL;
ret = handle_aiocb_rw(aiocb, &count);
if (ret == 0 && count < aiocb->aio_nbytes) {
ret = -EIO;
}
break;
case QEMU_AIO_FLUSH:
if (!FlushFileBuffers(aiocb->hfile)) {
return -EIO;
ret = win32_error_to_errno(GetLastError());
}
break;
default:
@@ -144,30 +177,47 @@ static int aio_worker(void *arg)
break;
}
g_free(aiocb);
return ret;
}
static BlockAIOCB *paio_submit(BlockDriverState *bs, HANDLE hfile,
int64_t offset, QEMUIOVector *qiov, int count,
BlockCompletionFunc *cb, void *opaque, int type)
static int coroutine_fn paio_co_submit(BlockDriverState *bs, HANDLE hfile,
int64_t offset, QEMUIOVector *qiov, int64_t bytes, int type)
{
RawWin32AIOData *acb = g_new(RawWin32AIOData, 1);
RawWin32AIOData acb = {
.hfile = hfile,
.aio_type = type,
.aio_offset = offset,
.qiov = qiov,
};
int ret;
acb->bs = bs;
acb->hfile = hfile;
acb->aio_type = type;
if (qiov) {
acb->aio_iov = qiov->iov;
acb->aio_niov = qiov->niov;
assert(qiov->size == count);
if (bytes < 0 || bytes > BDRV_REQUEST_MAX_BYTES ||
(qiov && qiov->size != (uint64_t)bytes)) {
return -EINVAL;
}
acb.aio_nbytes = bytes;
if (bytes && (bs->open_flags & BDRV_O_NOCACHE)) {
if (!QEMU_IS_ALIGNED(offset, bs->bl.request_alignment) ||
!QEMU_IS_ALIGNED(bytes, bs->bl.request_alignment)) {
return -EINVAL;
}
if (qiov->niov > 1 ||
!QEMU_PTR_IS_ALIGNED(qiov->iov[0].iov_base,
bdrv_min_mem_align(bs))) {
acb.bounce_buf = qemu_try_blockalign(bs, bytes);
if (!acb.bounce_buf) {
return -ENOMEM;
}
if (type & QEMU_AIO_WRITE) {
iov_to_buf(qiov->iov, qiov->niov, 0, acb.bounce_buf, bytes);
}
}
}
acb->aio_nbytes = count;
acb->aio_offset = offset;
trace_file_paio_submit(acb, opaque, offset, count, type);
return thread_pool_submit_aio(aio_worker, acb, cb, opaque);
trace_file_paio_submit(&acb, NULL, offset, (int)acb.aio_nbytes, type);
ret = thread_pool_submit_co(aio_worker, &acb);
qemu_vfree(acb.bounce_buf);
return ret;
}
static int set_sparse(int fd)
@@ -196,37 +246,184 @@ static void raw_attach_aio_context(BlockDriverState *bs,
}
}
typedef struct RawIoStatusBlock {
union {
LONG Status;
PVOID Pointer;
};
ULONG_PTR Information;
} RawIoStatusBlock;
typedef struct RawFileFsSizeInfo {
LARGE_INTEGER TotalAllocationUnits;
LARGE_INTEGER AvailableAllocationUnits;
ULONG SectorsPerAllocationUnit;
ULONG BytesPerSector;
} RawFileFsSizeInfo;
typedef LONG (NTAPI * nt_query_volume_info_file_t)(HANDLE, RawIoStatusBlock *,
PVOID, ULONG, ULONG);
static bool raw_query_fs_sector_size(HANDLE hfile, uint32_t *logical)
{
enum { RAW_FILE_FS_SIZE_INFORMATION = 3 };
HMODULE ntdll = GetModuleHandleA("ntdll.dll");
nt_query_volume_info_file_t query_vol;
RawIoStatusBlock iosb = { 0 };
RawFileFsSizeInfo info = { 0 };
LONG status;
if (!ntdll) {
return false;
}
query_vol = (nt_query_volume_info_file_t)
GetProcAddress(ntdll, "NtQueryVolumeInformationFile");
if (!query_vol) {
return false;
}
/* Called before hfile is attached to an IOCP. */
status = query_vol(hfile, &iosb, &info, sizeof(info),
RAW_FILE_FS_SIZE_INFORMATION);
if (status == (LONG)STATUS_PENDING) {
if (WaitForSingleObject(hfile, INFINITE) != WAIT_OBJECT_0) {
return false;
}
status = iosb.Status;
}
if (status < 0 || iosb.Information < sizeof(info)) {
return false;
}
*logical = info.BytesPerSector;
return true;
}
static int raw_probe_volume_alignment(HANDLE hfile, const char *filename,
uint32_t *logical, uint32_t *physical,
Error **errp)
{
DWORD path_size = GetFinalPathNameByHandleW(hfile, NULL, 0,
VOLUME_NAME_GUID);
if (path_size > 0) {
g_autofree wchar_t *path = g_new(wchar_t, path_size);
DWORD length = GetFinalPathNameByHandleW(hfile, path, path_size,
VOLUME_NAME_GUID);
wchar_t *slash = (length > 4 && length < path_size)
? wcschr(path + 4, L'\\') : NULL;
if (slash) {
HANDLE volume_handle;
*slash = L'\0';
volume_handle = CreateFileW(path, 0,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, 0, NULL);
if (volume_handle != INVALID_HANDLE_VALUE) {
STORAGE_PROPERTY_QUERY query = {
.PropertyId = StorageAccessAlignmentProperty,
.QueryType = PropertyStandardQuery,
};
STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR info;
DWORD returned;
BOOL ok = DeviceIoControl(volume_handle,
IOCTL_STORAGE_QUERY_PROPERTY,
&query, sizeof(query),
&info, sizeof(info),
&returned, NULL);
CloseHandle(volume_handle);
if (ok && returned >= sizeof(info) &&
info.Size >= sizeof(info) &&
info.BytesPerLogicalSector >= BDRV_SECTOR_SIZE &&
info.BytesPerLogicalSector <= BDRV_MAX_ALIGNMENT &&
is_power_of_2(info.BytesPerLogicalSector)) {
*logical = info.BytesPerLogicalSector;
*physical = info.BytesPerPhysicalSector;
return 0;
}
}
}
}
if (raw_query_fs_sector_size(hfile, logical)) {
*physical = 0;
return 0;
}
error_setg(errp, "Could not query sector size for '%s'", filename);
return -EINVAL;
}
static int raw_probe_direct_alignment(HANDLE hfile, const char *drive_path,
uint32_t *req_align, uint32_t *mem_align,
Error **errp)
{
FILE_STORAGE_INFO fsi;
FILE_ALIGNMENT_INFO fai;
uint32_t logical, physical;
uint64_t file_align = 0;
bool have_storage_info;
have_storage_info = GetFileInformationByHandleEx(hfile, FileStorageInfo,
&fsi, sizeof(fsi));
if (have_storage_info) {
logical = fsi.LogicalBytesPerSector;
physical = 0;
if (is_power_of_2(fsi.PhysicalBytesPerSectorForAtomicity) &&
fsi.PhysicalBytesPerSectorForAtomicity <= BDRV_MAX_ALIGNMENT) {
physical = fsi.PhysicalBytesPerSectorForAtomicity;
}
} else {
int ret = raw_probe_volume_alignment(hfile, drive_path, &logical,
&physical, errp);
if (ret < 0) {
return ret;
}
if (!is_power_of_2(physical) || physical > BDRV_MAX_ALIGNMENT) {
physical = 0;
}
}
if (GetFileInformationByHandleEx(hfile, FileAlignmentInfo,
&fai, sizeof(fai))) {
file_align = (uint64_t)fai.AlignmentRequirement + 1;
if (!is_power_of_2(file_align) || file_align > BDRV_MAX_ALIGNMENT) {
error_setg(errp, "Unsupported buffer alignment for '%s'",
drive_path);
return -EINVAL;
}
}
if (logical < BDRV_SECTOR_SIZE || logical > BDRV_MAX_ALIGNMENT ||
!is_power_of_2(logical)) {
error_setg(errp, "Unsupported logical sector size %" PRIu32
" for '%s'", logical, drive_path);
return -EINVAL;
}
if (!have_storage_info && !physical) {
if (!file_align) {
error_setg(errp, "Could not determine direct I/O buffer alignment "
"for '%s'", drive_path);
return -EINVAL;
}
physical = qemu_real_host_page_size();
}
*req_align = logical;
*mem_align = MAX(logical, MAX(physical, (uint32_t)file_align));
return 0;
}
static void raw_probe_alignment(BlockDriverState *bs, Error **errp)
{
BDRVRawState *s = bs->opaque;
DWORD sectorsPerCluster, freeClusters, totalClusters, count;
DISK_GEOMETRY_EX dg;
BOOL status;
if (s->type == FTYPE_CD) {
bs->bl.request_alignment = 2048;
return;
bs->bl.request_alignment = s->needs_alignment ? s->probed_req_align : 1;
if (s->needs_alignment) {
bs->bl.min_mem_alignment = s->probed_mem_align;
bs->bl.opt_mem_alignment = MAX(s->probed_mem_align,
qemu_real_host_page_size());
}
if (s->type == FTYPE_HARDDISK) {
status = DeviceIoControl(s->hfile, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX,
NULL, 0, &dg, sizeof(dg), &count, NULL);
if (status != 0) {
bs->bl.request_alignment = dg.Geometry.BytesPerSector;
return;
}
/* try GetDiskFreeSpace too */
}
if (s->drive_path[0]) {
GetDiskFreeSpace(s->drive_path, &sectorsPerCluster,
&dg.Geometry.BytesPerSector,
&freeClusters, &totalClusters);
bs->bl.request_alignment = dg.Geometry.BytesPerSector;
return;
}
/* XXX Does Windows support AIO on less than 512-byte alignment? */
bs->bl.request_alignment = 512;
}
static void raw_parse_flags(int flags, bool use_aio, int *access_flags,
@@ -351,17 +548,6 @@ static int raw_open(BlockDriverState *bs, QDict *options, int flags,
raw_parse_flags(flags, use_aio, &access_flags, &overlapped);
if (filename[0] && filename[1] == ':') {
snprintf(s->drive_path, sizeof(s->drive_path), "%c:\\", filename[0]);
} else if (filename[0] == '\\' && filename[1] == '\\') {
s->drive_path[0] = 0;
} else {
/* Relative path. */
char buf[MAX_PATH];
GetCurrentDirectory(MAX_PATH, buf);
snprintf(s->drive_path, sizeof(s->drive_path), "%c:\\", buf[0]);
}
s->hfile = CreateFile(filename, access_flags,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
OPEN_EXISTING, overlapped, NULL);
@@ -377,21 +563,30 @@ static int raw_open(BlockDriverState *bs, QDict *options, int flags,
goto fail;
}
s->needs_alignment = flags & BDRV_O_NOCACHE;
if (s->needs_alignment) {
ret = raw_probe_direct_alignment(s->hfile, filename,
&s->probed_req_align,
&s->probed_mem_align, errp);
if (ret < 0) {
goto fail_handle;
}
}
if (use_aio) {
s->aio = win32_aio_init();
if (s->aio == NULL) {
CloseHandle(s->hfile);
error_setg(errp, "Could not initialize AIO");
ret = -EINVAL;
goto fail;
DWORD err = GetLastError();
error_setg_win32(errp, err, "Could not initialize AIO");
ret = win32_error_to_errno(err);
goto fail_handle;
}
ret = win32_aio_attach(s->aio, s->hfile);
if (ret < 0) {
win32_aio_cleanup(s->aio);
CloseHandle(s->hfile);
error_setg_errno(errp, -ret, "Could not enable AIO");
goto fail;
error_setg_win32(errp, GetLastError(), "Could not enable AIO");
goto fail_handle;
}
win32_aio_attach_aio_context(s->aio, bdrv_get_aio_context(bs));
@@ -400,47 +595,54 @@ static int raw_open(BlockDriverState *bs, QDict *options, int flags,
/* When extending regular files, we get zeros from the OS */
bs->supported_truncate_flags = BDRV_REQ_ZERO_WRITE;
ret = 0;
qemu_opts_del(opts);
return 0;
fail_handle:
CloseHandle(s->hfile);
s->hfile = INVALID_HANDLE_VALUE;
if (s->aio) {
win32_aio_cleanup(s->aio);
s->aio = NULL;
}
fail:
qemu_opts_del(opts);
return ret;
}
static BlockAIOCB *raw_aio_preadv(BlockDriverState *bs,
int64_t offset, int64_t bytes,
QEMUIOVector *qiov, BdrvRequestFlags flags,
BlockCompletionFunc *cb, void *opaque)
static int coroutine_fn raw_co_preadv(BlockDriverState *bs,
int64_t offset, int64_t bytes,
QEMUIOVector *qiov,
BdrvRequestFlags flags)
{
BDRVRawState *s = bs->opaque;
if (s->aio) {
return win32_aio_submit(bs, s->aio, s->hfile, offset, bytes, qiov,
cb, opaque, QEMU_AIO_READ);
} else {
return paio_submit(bs, s->hfile, offset, qiov, bytes,
cb, opaque, QEMU_AIO_READ);
return win32_aio_co_submit(bs, s->aio, s->hfile, offset, bytes, qiov,
QEMU_AIO_READ);
}
return paio_co_submit(bs, s->hfile, offset, qiov, bytes, QEMU_AIO_READ);
}
static BlockAIOCB *raw_aio_pwritev(BlockDriverState *bs,
int64_t offset, int64_t bytes,
QEMUIOVector *qiov, BdrvRequestFlags flags,
BlockCompletionFunc *cb, void *opaque)
static int coroutine_fn raw_co_pwritev(BlockDriverState *bs,
int64_t offset, int64_t bytes,
QEMUIOVector *qiov,
BdrvRequestFlags flags)
{
BDRVRawState *s = bs->opaque;
if (s->aio) {
return win32_aio_submit(bs, s->aio, s->hfile, offset, bytes, qiov,
cb, opaque, QEMU_AIO_WRITE);
} else {
return paio_submit(bs, s->hfile, offset, qiov, bytes,
cb, opaque, QEMU_AIO_WRITE);
return win32_aio_co_submit(bs, s->aio, s->hfile, offset, bytes, qiov,
QEMU_AIO_WRITE);
}
return paio_co_submit(bs, s->hfile, offset, qiov, bytes, QEMU_AIO_WRITE);
}
static BlockAIOCB *raw_aio_flush(BlockDriverState *bs,
BlockCompletionFunc *cb, void *opaque)
static int coroutine_fn raw_co_flush_to_disk(BlockDriverState *bs)
{
BDRVRawState *s = bs->opaque;
return paio_submit(bs, s->hfile, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
return paio_co_submit(bs, s->hfile, 0, NULL, 0, QEMU_AIO_FLUSH);
}
static void raw_close(BlockDriverState *bs)
@@ -449,11 +651,12 @@ static void raw_close(BlockDriverState *bs)
if (s->aio) {
win32_aio_detach_aio_context(s->aio, bdrv_get_aio_context(bs));
}
CloseHandle(s->hfile);
if (s->aio) {
win32_aio_cleanup(s->aio);
s->aio = NULL;
}
CloseHandle(s->hfile);
if (bs->open_flags & BDRV_O_TEMPORARY) {
unlink(bs->filename);
}
@@ -464,8 +667,7 @@ static int coroutine_fn raw_co_truncate(BlockDriverState *bs, int64_t offset,
BdrvRequestFlags flags, Error **errp)
{
BDRVRawState *s = bs->opaque;
LONG low, high;
DWORD dwPtrLow;
FILE_END_OF_FILE_INFO info = { .EndOfFile.QuadPart = offset };
if (prealloc != PREALLOC_MODE_OFF) {
error_setg(errp, "Unsupported preallocation mode '%s'",
@@ -473,21 +675,12 @@ static int coroutine_fn raw_co_truncate(BlockDriverState *bs, int64_t offset,
return -ENOTSUP;
}
low = offset;
high = offset >> 32;
if (!SetFileInformationByHandle(s->hfile, FileEndOfFileInfo,
&info, sizeof(info))) {
DWORD err = GetLastError();
/*
* An error has occurred if the return value is INVALID_SET_FILE_POINTER
* and GetLastError doesn't return NO_ERROR.
*/
dwPtrLow = SetFilePointer(s->hfile, low, &high, FILE_BEGIN);
if (dwPtrLow == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) {
error_setg_win32(errp, GetLastError(), "SetFilePointer error");
return -EIO;
}
if (SetEndOfFile(s->hfile) == 0) {
error_setg_win32(errp, GetLastError(), "SetEndOfFile error");
return -EIO;
error_setg_win32(errp, err, "Could not set end of file");
return win32_error_to_errno(err);
}
return 0;
}
@@ -611,7 +804,7 @@ static int raw_reopen_prepare(BDRVReopenState *state,
BDRVRawReopenState *rs;
int access_flags;
DWORD overlapped;
int ret = 0;
int ret;
if (s->type != FTYPE_FILE) {
error_setg(errp, "Can only reopen files");
@@ -645,12 +838,21 @@ static int raw_reopen_prepare(BDRVReopenState *state,
goto fail;
}
rs->needs_alignment = state->flags & BDRV_O_NOCACHE;
if (rs->needs_alignment) {
ret = raw_probe_direct_alignment(rs->hfile, state->bs->filename,
&rs->probed_req_align,
&rs->probed_mem_align, errp);
if (ret < 0) {
goto fail_handle;
}
}
if (s->aio) {
ret = win32_aio_attach(s->aio, rs->hfile);
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not enable AIO");
CloseHandle(rs->hfile);
goto fail;
error_setg_win32(errp, GetLastError(), "Could not enable AIO");
goto fail_handle;
}
}
@@ -658,6 +860,8 @@ static int raw_reopen_prepare(BDRVReopenState *state,
return 0;
fail_handle:
CloseHandle(rs->hfile);
fail:
g_free(rs);
state->opaque = NULL;
@@ -674,6 +878,9 @@ static void raw_reopen_commit(BDRVReopenState *state)
CloseHandle(s->hfile);
s->hfile = rs->hfile;
s->needs_alignment = rs->needs_alignment;
s->probed_req_align = rs->probed_req_align;
s->probed_mem_align = rs->probed_mem_align;
g_free(rs);
state->opaque = NULL;
@@ -687,9 +894,7 @@ static void raw_reopen_abort(BDRVReopenState *state)
return;
}
if (rs->hfile != INVALID_HANDLE_VALUE) {
CloseHandle(rs->hfile);
}
CloseHandle(rs->hfile);
g_free(rs);
state->opaque = NULL;
@@ -724,9 +929,12 @@ BlockDriver bdrv_file = {
.bdrv_reopen_commit = raw_reopen_commit,
.bdrv_reopen_abort = raw_reopen_abort,
.bdrv_aio_preadv = raw_aio_preadv,
.bdrv_aio_pwritev = raw_aio_pwritev,
.bdrv_aio_flush = raw_aio_flush,
.bdrv_co_preadv = raw_co_preadv,
.bdrv_co_pwritev = raw_co_pwritev,
.bdrv_co_flush_to_disk = raw_co_flush_to_disk,
.bdrv_detach_aio_context = raw_detach_aio_context,
.bdrv_attach_aio_context = raw_attach_aio_context,
.bdrv_co_truncate = raw_co_truncate,
.bdrv_co_getlength = raw_co_getlength,
@@ -892,9 +1100,9 @@ static BlockDriver bdrv_host_device = {
.bdrv_close = raw_close,
.bdrv_refresh_limits = hdev_refresh_limits,
.bdrv_aio_preadv = raw_aio_preadv,
.bdrv_aio_pwritev = raw_aio_pwritev,
.bdrv_aio_flush = raw_aio_flush,
.bdrv_co_preadv = raw_co_preadv,
.bdrv_co_pwritev = raw_co_pwritev,
.bdrv_co_flush_to_disk = raw_co_flush_to_disk,
.bdrv_detach_aio_context = raw_detach_aio_context,
.bdrv_attach_aio_context = raw_attach_aio_context,
+257 -152
View File
@@ -23,214 +23,319 @@
*/
#include "qemu/osdep.h"
#include "qemu/timer.h"
#include "block/block-io.h"
#include "block/block_int.h"
#include "qemu/aio.h"
#include "block/raw-aio.h"
#include "qemu/aiocb.h"
#include "qemu/event_notifier.h"
#include "qemu/error-report.h"
#include "qemu/iov.h"
#include "qemu/lockable.h"
#include "qemu/memalign.h"
#include "qemu/thread.h"
#include "qemu/units.h"
#include <windows.h>
#include <winioctl.h>
#define FTYPE_FILE 0
#define FTYPE_CD 1
#define FTYPE_HARDDISK 2
enum {
WIN32_AIO_KEY_IO = 1,
WIN32_AIO_KEY_STOP,
};
#define WIN32_AIO_BOUNCE_MAX_CACHED 16
static const struct {
size_t size;
unsigned int capacity;
} bounce_buckets[] = {
{ 64 * KiB, WIN32_AIO_BOUNCE_MAX_CACHED },
{ 256 * KiB, 8 },
{ MiB, 8 },
};
typedef struct Win32AioBounceBucket {
void *buffers[WIN32_AIO_BOUNCE_MAX_CACHED];
unsigned int count;
} Win32AioBounceBucket;
struct QEMUWin32AIOState {
HANDLE hIOCP;
EventNotifier e;
int count;
QemuThread waiter_thread;
AioContext *aio_ctx;
bool skip_iocp_on_success;
QemuMutex pool_lock;
size_t pool_align;
Win32AioBounceBucket pool[ARRAY_SIZE(bounce_buckets)];
};
typedef struct QEMUWin32AIOCB {
BlockAIOCB common;
struct QEMUWin32AIOState *ctx;
AioContext *req_ctx;
int nbytes;
typedef struct Win32AioCoReq {
OVERLAPPED ov;
QEMUIOVector *qiov;
Coroutine *co;
AioContext *req_ctx;
DWORD win32_err;
DWORD transferred;
} Win32AioCoReq;
static int win32_error_to_errno(DWORD err)
{
switch (err) {
case ERROR_DISK_FULL:
case ERROR_HANDLE_DISK_FULL:
return -ENOSPC;
case ERROR_ACCESS_DENIED:
return -EACCES;
case ERROR_INVALID_PARAMETER:
return -EINVAL;
case ERROR_OPERATION_ABORTED:
return -ECANCELED;
case ERROR_NOT_ENOUGH_MEMORY:
case ERROR_OUTOFMEMORY:
return -ENOMEM;
default:
return -EIO;
}
}
static void *win32_aio_bounce_alloc(QEMUWin32AIOState *aio,
BlockDriverState *bs, size_t bytes,
int *bucket_out)
{
int bucket = 0;
void *buf;
bool is_read;
bool is_linear;
int ret;
} QEMUWin32AIOCB;
static void win32_aio_completion_cb_bh(void *opaque)
{
QEMUWin32AIOCB *waiocb = opaque;
while (bucket < ARRAY_SIZE(bounce_buckets) &&
bytes > bounce_buckets[bucket].size) {
bucket++;
}
if (bucket == ARRAY_SIZE(bounce_buckets) ||
bdrv_min_mem_align(bs) > aio->pool_align) {
*bucket_out = -1;
return qemu_try_blockalign(bs, bytes);
}
waiocb->common.cb(waiocb->common.opaque, waiocb->ret);
aio_context_unref(waiocb->req_ctx);
qemu_aio_unref(waiocb);
WITH_QEMU_LOCK_GUARD(&aio->pool_lock) {
Win32AioBounceBucket *pool = &aio->pool[bucket];
if (pool->count) {
*bucket_out = bucket;
return pool->buffers[--pool->count];
}
}
buf = qemu_try_memalign(aio->pool_align, bounce_buckets[bucket].size);
if (buf) {
*bucket_out = bucket;
}
return buf;
}
/*
* Completes an AIO request (calls the callback and frees the ACB).
*/
static void win32_aio_process_completion(QEMUWin32AIOState *s,
QEMUWin32AIOCB *waiocb, DWORD count)
static void win32_aio_bounce_free(QEMUWin32AIOState *aio, void *buf, int bucket)
{
s->count--;
if (!buf) {
return;
}
if (bucket >= 0) {
Win32AioBounceBucket *pool = &aio->pool[bucket];
QEMU_LOCK_GUARD(&aio->pool_lock);
if (waiocb->ov.Internal != 0) {
waiocb->ret = -EIO;
} else {
waiocb->ret = 0;
if (count < waiocb->nbytes) {
/* Short reads mean EOF, pad with zeros. */
if (waiocb->is_read) {
qemu_iovec_memset(waiocb->qiov, count, 0,
waiocb->qiov->size - count);
} else {
waiocb->ret = -EINVAL;
if (pool->count < bounce_buckets[bucket].capacity) {
pool->buffers[pool->count++] = buf;
return;
}
}
qemu_vfree(buf);
}
static void *win32_aio_waiter(void *opaque)
{
QEMUWin32AIOState *s = opaque;
for (;;) {
DWORD count = 0;
ULONG_PTR key;
OVERLAPPED *ov;
Win32AioCoReq *req;
AioContext *ctx;
Coroutine *co;
BOOL ok = GetQueuedCompletionStatus(s->hIOCP, &count, &key, &ov,
INFINITE);
DWORD err = ok ? ERROR_SUCCESS : GetLastError();
if (!ov) {
if (!ok) {
error_report("GetQueuedCompletionStatus failed: %lu", err);
abort();
}
}
}
if (!waiocb->is_linear) {
if (waiocb->ret == 0 && waiocb->is_read) {
QEMUIOVector *qiov = waiocb->qiov;
iov_from_buf(qiov->iov, qiov->niov, 0, waiocb->buf, qiov->size);
assert(key == WIN32_AIO_KEY_STOP);
break;
}
qemu_vfree(waiocb->buf);
assert(key == WIN32_AIO_KEY_IO);
req = container_of(ov, Win32AioCoReq, ov);
ctx = req->req_ctx;
co = req->co;
req->win32_err = err;
req->transferred = err == ERROR_HANDLE_EOF ? 0 : count;
aio_co_schedule(ctx, co);
}
if (waiocb->req_ctx == s->aio_ctx) {
win32_aio_completion_cb_bh(waiocb);
} else {
aio_bh_schedule_oneshot(waiocb->req_ctx, win32_aio_completion_cb_bh,
waiocb);
}
}
static void win32_aio_completion_cb(EventNotifier *e)
{
QEMUWin32AIOState *s = container_of(e, QEMUWin32AIOState, e);
DWORD count;
ULONG_PTR key;
OVERLAPPED *ov;
event_notifier_test_and_clear(&s->e);
while (GetQueuedCompletionStatus(s->hIOCP, &count, &key, &ov, 0)) {
QEMUWin32AIOCB *waiocb = container_of(ov, QEMUWin32AIOCB, ov);
win32_aio_process_completion(s, waiocb, count);
}
}
static const AIOCBInfo win32_aiocb_info = {
.aiocb_size = sizeof(QEMUWin32AIOCB),
};
BlockAIOCB *win32_aio_submit(BlockDriverState *bs,
QEMUWin32AIOState *aio, HANDLE hfile,
uint64_t offset, uint64_t bytes, QEMUIOVector *qiov,
BlockCompletionFunc *cb, void *opaque, int type)
{
struct QEMUWin32AIOCB *waiocb;
DWORD rc;
waiocb = qemu_aio_get(&win32_aiocb_info, bs, cb, opaque);
waiocb->req_ctx = qemu_get_current_aio_context();
waiocb->nbytes = bytes;
waiocb->qiov = qiov;
waiocb->is_read = (type == QEMU_AIO_READ);
aio_context_ref(waiocb->req_ctx);
if (qiov->niov > 1) {
waiocb->buf = qemu_try_blockalign(bs, qiov->size);
if (waiocb->buf == NULL) {
goto out;
}
if (type & QEMU_AIO_WRITE) {
iov_to_buf(qiov->iov, qiov->niov, 0, waiocb->buf, qiov->size);
}
waiocb->is_linear = false;
} else {
waiocb->buf = qiov->iov[0].iov_base;
waiocb->is_linear = true;
}
memset(&waiocb->ov, 0, sizeof(waiocb->ov));
waiocb->ov.Offset = (DWORD)offset;
waiocb->ov.OffsetHigh = (DWORD)(offset >> 32);
waiocb->ov.hEvent = event_notifier_get_handle(&aio->e);
aio->count++;
if (type & QEMU_AIO_READ) {
rc = ReadFile(hfile, waiocb->buf, waiocb->nbytes, NULL, &waiocb->ov);
} else {
rc = WriteFile(hfile, waiocb->buf, waiocb->nbytes, NULL, &waiocb->ov);
}
if(rc == 0 && GetLastError() != ERROR_IO_PENDING) {
goto out_dec_count;
}
return &waiocb->common;
out_dec_count:
aio->count--;
out:
qemu_aio_unref(waiocb);
return NULL;
}
int coroutine_fn win32_aio_co_submit(BlockDriverState *bs,
QEMUWin32AIOState *aio, HANDLE hfile,
uint64_t offset, uint64_t bytes, QEMUIOVector *qiov, int type)
{
Win32AioCoReq req;
void *bounce_buf = NULL;
int bucket = -1;
void *buf;
BOOL ok;
DWORD sync_transferred = 0;
DWORD transferred;
DWORD win32_err;
int ret = 0;
bool direct = bs->open_flags & BDRV_O_NOCACHE;
bool is_read = (type & QEMU_AIO_TYPE_MASK) == QEMU_AIO_READ;
assert(aio->aio_ctx);
if (bytes != qiov->size || bytes > BDRV_REQUEST_MAX_BYTES ||
bytes > UINT32_MAX) {
return -EINVAL;
}
if (bytes == 0) {
return 0;
}
if (direct && (!QEMU_IS_ALIGNED(offset, bs->bl.request_alignment) ||
!QEMU_IS_ALIGNED(bytes, bs->bl.request_alignment))) {
return -EINVAL;
}
if (qiov->niov > 1 ||
(direct && !QEMU_PTR_IS_ALIGNED(qiov->iov[0].iov_base,
bdrv_min_mem_align(bs)))) {
bounce_buf = win32_aio_bounce_alloc(aio, bs, bytes, &bucket);
if (!bounce_buf) {
return -ENOMEM;
}
if (!is_read) {
iov_to_buf(qiov->iov, qiov->niov, 0, bounce_buf, bytes);
}
}
buf = bounce_buf ? bounce_buf : qiov->iov[0].iov_base;
/* The waiter can queue the coroutine before the system call returns. */
req = (Win32AioCoReq) {
.ov = {
.Offset = (DWORD)offset,
.OffsetHigh = (DWORD)(offset >> 32),
.hEvent = NULL,
},
.co = qemu_coroutine_self(),
.req_ctx = qemu_get_current_aio_context(),
};
if (is_read) {
ok = ReadFile(hfile, buf, (DWORD)bytes,
aio->skip_iocp_on_success ? &sync_transferred : NULL,
&req.ov);
} else {
ok = WriteFile(hfile, buf, (DWORD)bytes,
aio->skip_iocp_on_success ? &sync_transferred : NULL,
&req.ov);
}
win32_err = ok ? ERROR_SUCCESS : GetLastError();
if (win32_err == ERROR_IO_PENDING || (ok && !aio->skip_iocp_on_success)) {
qemu_coroutine_yield();
win32_err = req.win32_err;
transferred = req.transferred;
} else {
transferred = ok ? sync_transferred : 0;
}
if (win32_err != ERROR_SUCCESS &&
!(is_read && win32_err == ERROR_HANDLE_EOF)) {
ret = win32_error_to_errno(win32_err);
} else if (transferred > bytes || (!is_read && transferred < bytes)) {
ret = -EIO;
} else if (is_read) {
if (bounce_buf && transferred) {
iov_from_buf(qiov->iov, qiov->niov, 0, bounce_buf, transferred);
}
if (transferred < bytes) {
qemu_iovec_memset(qiov, transferred, 0, bytes - transferred);
}
}
win32_aio_bounce_free(aio, bounce_buf, bucket);
return ret;
}
int win32_aio_attach(QEMUWin32AIOState *aio, HANDLE hfile)
{
if (CreateIoCompletionPort(hfile, aio->hIOCP, (ULONG_PTR) 0, 0) == NULL) {
return -EINVAL;
} else {
return 0;
UCHAR modes = FILE_SKIP_COMPLETION_PORT_ON_SUCCESS |
FILE_SKIP_SET_EVENT_ON_HANDLE;
if (!CreateIoCompletionPort(hfile, aio->hIOCP, WIN32_AIO_KEY_IO, 0)) {
return win32_error_to_errno(GetLastError());
}
if (!aio->aio_ctx) {
aio->skip_iocp_on_success =
SetFileCompletionNotificationModes(hfile, modes) != 0;
} else if (aio->skip_iocp_on_success) {
if (!SetFileCompletionNotificationModes(hfile, modes)) {
return win32_error_to_errno(GetLastError());
}
} else {
SetFileCompletionNotificationModes(hfile,
FILE_SKIP_SET_EVENT_ON_HANDLE);
}
return 0;
}
void win32_aio_detach_aio_context(QEMUWin32AIOState *aio,
AioContext *old_context)
{
aio_set_event_notifier(old_context, &aio->e, NULL, NULL, NULL);
assert(aio->aio_ctx == old_context);
/* Block layer drain has waited for all requests to finish. */
if (!PostQueuedCompletionStatus(aio->hIOCP, 0, WIN32_AIO_KEY_STOP, NULL)) {
error_report("PostQueuedCompletionStatus failed: %lu", GetLastError());
abort();
}
qemu_thread_join(&aio->waiter_thread);
aio->aio_ctx = NULL;
}
void win32_aio_attach_aio_context(QEMUWin32AIOState *aio,
AioContext *new_context)
{
assert(!aio->aio_ctx);
aio->aio_ctx = new_context;
aio_set_event_notifier(new_context, &aio->e, win32_aio_completion_cb,
NULL, NULL);
qemu_thread_create(&aio->waiter_thread, "win32-aio", win32_aio_waiter, aio,
QEMU_THREAD_JOINABLE);
}
QEMUWin32AIOState *win32_aio_init(void)
{
HANDLE port = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);
QEMUWin32AIOState *s;
s = g_malloc0(sizeof(*s));
if (event_notifier_init(&s->e, false) < 0) {
goto out_free_state;
if (!port) {
return NULL;
}
s->hIOCP = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);
if (s->hIOCP == NULL) {
goto out_close_efd;
}
s = g_new0(QEMUWin32AIOState, 1);
s->hIOCP = port;
qemu_mutex_init(&s->pool_lock);
s->pool_align = qemu_real_host_page_size();
return s;
out_close_efd:
event_notifier_cleanup(&s->e);
out_free_state:
g_free(s);
return NULL;
}
void win32_aio_cleanup(QEMUWin32AIOState *aio)
{
assert(!aio->aio_ctx);
for (int i = 0; i < ARRAY_SIZE(aio->pool); i++) {
Win32AioBounceBucket *pool = &aio->pool[i];
for (unsigned int j = 0; j < pool->count; j++) {
qemu_vfree(pool->buffers[j]);
}
}
qemu_mutex_destroy(&aio->pool_lock);
CloseHandle(aio->hIOCP);
event_notifier_cleanup(&aio->e);
g_free(aio);
}
+5
View File
@@ -66,6 +66,11 @@ static void term_exit(void)
}
}
void qemu_chr_stdio_term_exit(void)
{
term_exit();
}
static void stdio_chr_set_echo(Chardev *chr, bool echo)
{
struct termios tty;
+4 -1
View File
@@ -9,4 +9,7 @@ include ../arm-softmmu/default.mak
# CONFIG_XLNX_VERSAL=n
# CONFIG_SBSA_REF=n
# CONFIG_NPCM8XX=n
CONFIG_VMAPPLE=n
# Selected by default when TCG or HVF is enabled; uncomment it to keep it
# out of the build.
# CONFIG_VMAPPLE=n
+132 -10
View File
@@ -12,12 +12,17 @@ Prerequisites
To run the vmapple machine model, you need to
* Run on Apple Silicon
* Run on macOS 12.0 or above
* Have an already installed copy of a Virtualization.Framework macOS 12 virtual
machine. Note that newer versions than 12.x are currently NOT supported on
the guest side. I will assume that you installed it using the
* Run on Apple Silicon, on macOS 12.0 or above, for HVF; or on any host
under TCG (see `Under TCG`_)
* Have an already installed copy of a Virtualization.Framework macOS 12 or
later virtual machine. I will assume that you installed it using the
`macosvm <https://github.com/s-u/macosvm>`__ CLI.
* Have a firmware for the machine, such as Ambrosia.
Virtualization.framework's own, AVPBooter, does not boot on it (see
`Guest firmware`_).
* Build QEMU with a crypto library (gnutls, nettle or libgcrypt), whose AES
ciphers the machine's AES engine runs on. Without one, the engine fails to
realize and QEMU exits at start.
First, we need to extract the UUID from the virtual machine that you installed. You can do this
by running the shell script in contrib/vmapple/uuid.sh on the macosvm.json file.
@@ -37,15 +42,15 @@ Now we also need to trim the aux partition. It contains metadata that we can jus
How to run
----------
Then, we can launch QEMU with the Virtualization.Framework pre-boot environment and the readily
installed target disk images. I recommend to port forward the VM's ssh and vnc ports to the host
to get better interactive access into the target system:
Then, we can launch QEMU with the firmware and the readily installed target disk images. I
recommend to port forward the VM's ssh and vnc ports to the host to get better interactive access
into the target system:
.. code-block:: bash
:caption: Example execution command line
$ UUID="$(contrib/vmapple/uuid.sh 'macosvm.json')"
$ AVPBOOTER="/System/Library/Frameworks/Virtualization.framework/Resources/AVPBooter.vmapple2.bin"
$ FIRMWARE="ambrosia.bin"
$ AUX="aux.img.trimmed"
$ DISK="disk.img"
$ qemu-system-aarch64 \
@@ -53,7 +58,7 @@ to get better interactive access into the target system:
-m 4G \
-accel hvf \
-M vmapple,uuid="$UUID" \
-bios "$AVPBOOTER" \
-bios "$FIRMWARE" \
-drive file="$AUX",if=pflash,format=raw \
-drive file="$DISK",if=pflash,format=raw \
-drive file="$AUX",if=none,id=aux,format=raw \
@@ -63,3 +68,120 @@ to get better interactive access into the target system:
-netdev user,id=net0,ipv6=off,hostfwd=tcp::2222-:22,hostfwd=tcp::5901-:5900 \
-device virtio-net-pci,netdev=net0
The machine offers virtio-net devices without a control queue: macOS's
driver can miss the completion of its first control command, and its
interface then never comes up. Without the queue the device stays
promiscuous and passes the guest every frame its backend delivers.
Under TCG
---------
The machine also runs under TCG, on any host, with ``-accel tcg`` in place of
``-accel hvf``. Its CPU type defaults to ``max`` under both; under HVF,
``max`` is the host's CPU. Under TCG, the machine's generic timer counts at
24 MHz, the timebase frequency macOS's device tree gives every CPU, and the
frequency of Apple silicon's system counter, which HVF passes through. The
``max`` CPU has no SME by default under TCG: macOS 14 sizes each thread's
SME state from the longest streaming vector, and with TCG's 2048-bit
vectors it panics as it starts. ``-cpu max,sme=on`` turns SME back on.
The pointer authentication calls of `Guest firmware`_ reach QEMU under TCG,
whose PSCI code answers each of them as not supported, as
Hypervisor.framework does, so a guest needs the same firmware under both.
As it starts, macOS's platform driver asks Virtualization.framework's machine
for a configuration register by writing the physical address of a request to
0x004ffff8. The machine leaves the request unanswered, as HVF leaves an
access to an address with no device, and the driver goes on without the
register; ``-d unimp`` logs the write. Under TCG any other access to an
address with no device is an external abort, which the kernel does not
survive. So the firmware's device tree must not list a device that the
machine lacks and macOS probes, such as Virtualization.framework's CTRR
device at 0x30260000.
Guest firmware
--------------
The machine's RAM starts at 4 GiB, and below it the PCIe MMIO window runs
from 0x50000000 up to RAM. macOS places every PCI BAR below 4 GiB, aligned
to its size, so a device with a 1 GiB BAR needs a free, 1 GiB-aligned
gigabyte there. Virtualization.framework's machine has its RAM at
0x70000000, and its firmware, AVPBooter, keeps its stack there, so AVPBooter
does not boot on this machine. A firmware for it gives macOS this layout in
the device tree; Ambrosia is one.
Under HVF the machine asks for 40 bits of guest physical address, or for the
most the host gives where that is fewer, where HVF's default is 36 bits:
macOS's kernel maps physical addresses of up to 40 bits. HVF gives the guest
that size as its ``ID_AA64MMFR0_EL1.PARange``. RAM must end within it.
The machine places nothing past RAM. From the end of RAM, rounded up to
1 GiB, to the end of the guest's physical addresses, in whole GiB, is room
that a device may map memory into once the guest runs; the read-only machine
properties ``x-pool-room-base`` and ``x-pool-room-size`` give it, and
``reims-graphics-pci`` puts its Shared pool there. Under KVM and TCG its end
is the CPU's ``PARange``, at most 40 bits.
The firmware also makes one change that macOS needs on this machine before
it enters the kernel. The machine makes no change to the guest itself.
A vmapple guest kernel asks the hypervisor to manage its pointer
authentication keys through paravirtualized hypercalls: ``hvc #0`` with
SMCCC function IDs 0xC1000000 to 0xC10000FF. Hypervisor.framework answers
these calls itself, without an exit to QEMU, and for a VM created through
its public API it answers each of them as not supported. The macOS 12 and
13 kernels carry on with the keys the firmware set up, which all processes
then share. From macOS 14 on, the kernel checks the result of every one of
these calls and loops forever when one fails, with ``hvc #0; cbnz x0, .``.
Hypervisor.framework implements the calls only for VMs created with a
private ISA setting, which needs an entitlement that only Apple-signed
binaries can hold. QEMU does not use it. So the firmware replaces each of
those loops with a ``nop``.
Clock
-----
Beside its PL031 at 0x20050000, the machine has Virtualization.framework's
second clock at 0x30240000, which macOS's device tree lists as ``avp-rtc``.
macOS keeps the offset from it to calendar time in NVRAM, on the aux drive,
and its timed daemon reads that offset to tell whether the clock was reset.
macOS's PL031 driver keeps no offset: with the PL031 alone, timed takes the
clock for reset on every boot, and sets it back to the last write to the
guest's disk until it reaches a time server. Both clocks count QEMU's RTC
clock from the Unix epoch, so ``-rtc base=`` and ``-rtc clock=`` apply to
both. The firmware's device tree gives the guest one of the two. macOS 14
and later drive ``avp-rtc``; the device trees of earlier releases list only
the PL031.
Display
-------
The machine gives the guest no display. Virtualization.framework's
paravirtualized display, which macOS drives with a driver of its own, is not
in this tree. A guest has a display only from a PCI display device given with
``-device`` that the guest has a driver for. Without one, reach the guest
through the serial console, or through ``ssh`` on host port 2222, which the
example forwards to the guest's port 22.
Input
-----
The machine gives the guest a USB keyboard and a USB pointing device,
``usb-vmapple-tablet`` unless the machine's ``tablet`` property names another
USB device: ``-M vmapple,tablet=usb-tablet`` gives it QEMU's usual USB
tablet instead.
``usb-vmapple-tablet`` is the pointing device Virtualization.framework gives
its macOS guests: an absolute pointer with three buttons, a wheel and a
horizontal wheel, whose reports also carry smooth scrolling, that is, the
distance scrolled with the phases of the gesture it belongs to and of the
momentum scrolling after it. macOS drives it with a driver of its own
(AppleVirtualPlatformHIDEventDriver in macOS 13.6), and scrolls as it does
with a trackpad: smooth scroll events, such as a window's under ``-display
none`` or the ``scroll`` events of ``input-send-event``, scroll the guest
point by point, both ways, with the momentum the host gave the gesture. A
wheel's notch scrolls a fixed 20 pixels there. Other guests see a HID mouse
with an absolute pointer and two wheels.
With ``usb-tablet``, macOS scrolls by whole wheel notches, which it
accelerates, vertically only.
+10
View File
@@ -393,6 +393,16 @@ usb device at hand, so it's a trial-and-error game. If the default
doesn't work, try another option and see whenever the situation
improves.
QEMU also resets the device itself when it lets go of it: when the
``usb-host`` device is removed or its host device closed, when QEMU
exits, and when opening the device fails. ``reset-on-close=false``
leaves it unreset: QEMU releases its interfaces and gives them back to
the host's drivers in the configuration the guest left. An Apple iOS
device switched to another USB mode by a macOS guest needs this: the
reset leaves it in a state from which the next guest's mode switch makes
it leave the bus until it is plugged in again, while unreset it stays in
the mode the guest set, which the next guest finds and keeps.
record usb transfers
^^^^^^^^^^^^^^^^^^^^
+3 -1
View File
@@ -22,7 +22,9 @@ Device properties
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``.
+4
View File
@@ -61,3 +61,7 @@ virtio_snd_handle_event(void) "event queue callback called"
virtio_snd_pcm_stream_flush(uint32_t stream) "flushing stream %"PRIu32
virtio_snd_handle_tx_xfer(void) "tx queue callback called"
virtio_snd_handle_rx_xfer(void) "rx queue callback called"
virtio_snd_pcm_params(uint32_t stream, uint32_t buffer_bytes, uint32_t period_bytes, uint8_t channels, uint8_t format, uint8_t rate) "stream %"PRIu32": buffer_bytes=%"PRIu32" period_bytes=%"PRIu32" channels=%u format=%u rate=%u"
virtio_snd_pcm_queued(uint32_t stream, size_t size, size_t pending) "stream %"PRIu32": I/O message of %zu bytes queued, %zu pending"
virtio_snd_pcm_completed(uint32_t stream, size_t size, uint32_t latency, size_t pending) "stream %"PRIu32": I/O message completed with %zu bytes, latency_bytes=%"PRIu32", %zu pending"
virtio_snd_pcm_state(uint32_t stream, const char *command, size_t pending) "stream %"PRIu32": %s with %zu I/O messages pending"
+26
View File
@@ -12,6 +12,7 @@
#include "qom/object.h"
#include "qapi/error.h"
#include "hw/audio/model.h"
#include "hw/pci/pci.h"
#include "hw/virtio/virtio-pci.h"
#include "hw/audio/virtio-snd.h"
@@ -25,12 +26,15 @@ struct VirtIOSoundPCI {
VirtIOPCIProxy parent_obj;
VirtIOSound vdev;
bool ascending_capabilities;
};
static const Property virtio_snd_pci_properties[] = {
DEFINE_PROP_BIT("ioeventfd", VirtIOPCIProxy, flags,
VIRTIO_PCI_FLAG_USE_IOEVENTFD_BIT, true),
DEFINE_PROP_UINT32("vectors", VirtIOPCIProxy, nvectors, 2),
DEFINE_PROP_BOOL("x-ascending-capabilities", VirtIOSoundPCI,
ascending_capabilities, false),
};
static void virtio_snd_pci_realize(VirtIOPCIProxy *vpci_dev, Error **errp)
@@ -40,6 +44,28 @@ static void virtio_snd_pci_realize(VirtIOPCIProxy *vpci_dev, Error **errp)
virtio_pci_force_virtio_1(vpci_dev);
qdev_realize(vdev, BUS(&vpci_dev->bus), errp);
if (dev->ascending_capabilities && qdev_is_realized(vdev)) {
uint8_t *config = vpci_dev->pci_dev.config;
bool capabilities[PCI_CONFIG_SPACE_SIZE] = { false };
unsigned offset, previous = PCI_CAPABILITY_LIST;
/* macOS 27's virtio PCI transport revisits PCI_CFG and NOTIFY
* forever on a descending list, as virtio-net-pci's does. Keep
* capability contents and offsets; only reorder the links. */
for (offset = config[PCI_CAPABILITY_LIST]; offset;
offset = config[offset + PCI_CAP_LIST_NEXT]) {
capabilities[offset] = true;
}
for (offset = PCI_CONFIG_HEADER_SIZE; offset < PCI_CONFIG_SPACE_SIZE;
offset++) {
if (capabilities[offset]) {
config[previous] = offset;
previous = offset + PCI_CAP_LIST_NEXT;
}
}
config[previous] = 0;
}
}
static void virtio_snd_pci_class_init(ObjectClass *klass, const void *data)
+94 -10
View File
@@ -31,6 +31,8 @@
#define VIRTIO_SOUND_STREAM_DEFAULT 2
#define VIRTIO_SOUND_CHMAP_DEFAULT 0
#define VIRTIO_SOUND_HDA_FN_NID 0
/* input-streams unset: the second half of the streams take input. */
#define VIRTIO_SOUND_INPUT_STREAMS_HALF UINT32_MAX
typedef enum virtio_snd_pcm_state {
VIRTIO_SND_PCM_STATE_UNINIT = 0,
@@ -72,6 +74,13 @@ static void virtio_snd_process_cmdq(VirtIOSound *s);
static void virtio_snd_pcm_flush(VirtIOSoundPCMStream *stream);
static void virtio_snd_pcm_close(VirtIOSoundPCMStream *stream);
static void virtio_snd_pcm_in_cb(void *data, int available);
static size_t virtio_snd_pcm_get_io_msgs_count(VirtIOSoundPCMStream *stream);
/* The stream's id: its index in the device's array of streams. */
static uint32_t virtio_snd_pcm_stream_id(VirtIOSoundPCMStream *stream)
{
return stream - stream->s->streams;
}
static uint32_t supported_formats = BIT(VIRTIO_SND_PCM_FMT_S8)
| BIT(VIRTIO_SND_PCM_FMT_U8)
@@ -144,6 +153,8 @@ static const Property virtio_snd_properties[] = {
VIRTIO_SOUND_STREAM_DEFAULT),
DEFINE_PROP_UINT32("chmaps", VirtIOSound, snd_conf.chmaps,
VIRTIO_SOUND_CHMAP_DEFAULT),
DEFINE_PROP_UINT32("input-streams", VirtIOSound, input_streams,
VIRTIO_SOUND_INPUT_STREAMS_HALF),
};
static void
@@ -400,6 +411,9 @@ uint32_t virtio_snd_set_pcm_params(VirtIOSound *s,
st_params->channels = params->channels;
st_params->format = params->format;
st_params->rate = params->rate;
trace_virtio_snd_pcm_params(stream_id, st_params->buffer_bytes,
st_params->period_bytes, st_params->channels,
st_params->format, st_params->rate);
if (virtio_snd_pcm_state_prepared(stream->state)) {
/* implicit VIRTIO_SND_R_PCM_RELEASE */
@@ -520,7 +534,6 @@ static void virtio_snd_get_qemu_audsettings(audsettings *as,
static void virtio_snd_pcm_open(VirtIOSoundPCMStream *stream)
{
virtio_snd_get_qemu_audsettings(&stream->as, &stream->params);
stream->info.channels_max = stream->as.nchannels;
if (stream->info.direction == VIRTIO_SND_D_OUTPUT) {
stream->voice.out = audio_be_open_out(stream->s->audio_be,
@@ -681,6 +694,8 @@ static uint32_t virtio_snd_pcm_start_stop(VirtIOSound *s,
return cpu_to_le32(VIRTIO_SND_S_BAD_MSG);
}
trace_virtio_snd_pcm_state(stream_id, start ? "start" : "stop",
virtio_snd_pcm_get_io_msgs_count(stream));
if (start) {
switch (stream->state) {
case VIRTIO_SND_PCM_STATE_PREPARED:
@@ -710,7 +725,14 @@ static uint32_t virtio_snd_pcm_start_stop(VirtIOSound *s,
stream->state = VIRTIO_SND_PCM_STATE_STOPPED;
}
virtio_snd_pcm_set_active(stream, start);
/*
* A started input stream captures only while the driver has buffers
* posted for it: virtio_snd_handle_rx_xfer starts its voice, and
* virtio_snd_pcm_in_cb stops it.
*/
virtio_snd_pcm_set_active(stream, start &&
(stream->info.direction == VIRTIO_SND_D_OUTPUT ||
!QSIMPLEQ_EMPTY(&stream->queue)));
return cpu_to_le32(VIRTIO_SND_S_OK);
}
@@ -790,6 +812,10 @@ static void virtio_snd_handle_pcm_release(VirtIOSound *s,
stream_id = le32_to_cpu(stream_id);
trace_virtio_snd_handle_pcm_release(stream_id);
stream = virtio_snd_pcm_get_stream(s, stream_id);
if (stream) {
trace_virtio_snd_pcm_state(stream_id, "release",
virtio_snd_pcm_get_io_msgs_count(stream));
}
if (stream == NULL) {
error_report("%s already released stream %"PRIu32,
VIRTIO_DEVICE(s)->name, stream_id);
@@ -1028,6 +1054,7 @@ static void virtio_snd_handle_tx_xfer(VirtIODevice *vdev, VirtQueue *vq)
* return them after the for loop.
*/
bool must_empty_invalid_queue = false;
bool queued = false;
if (!virtio_queue_ready(vq)) {
return;
@@ -1080,6 +1107,9 @@ static void virtio_snd_handle_tx_xfer(VirtIODevice *vdev, VirtQueue *vq)
stream->latency_bytes += size;
QSIMPLEQ_INSERT_TAIL(&stream->queue, buffer, entry);
trace_virtio_snd_pcm_queued(stream_id, size,
virtio_snd_pcm_get_io_msgs_count(stream));
queued = true;
continue;
tx_err:
@@ -1093,6 +1123,15 @@ tx_err:
if (must_empty_invalid_queue) {
empty_invalid_queue(vdev, vq);
}
/*
* The guest's new audio goes to the host's device now, not at the audio
* timer's next run: a guest that hands its audio over in periods is then
* played that much sooner, and the backend's reserve need not cover the
* timer's step and lateness.
*/
if (queued) {
audio_be_kick(vsnd->audio_be);
}
}
/*
@@ -1162,6 +1201,11 @@ static void virtio_snd_handle_rx_xfer(VirtIODevice *vdev, VirtQueue *vq)
buffer->size = 0;
buffer->offset = 0;
QSIMPLEQ_INSERT_TAIL(&stream->queue, buffer, entry);
trace_virtio_snd_pcm_queued(stream_id, size,
virtio_snd_pcm_get_io_msgs_count(stream));
if (stream->state == VIRTIO_SND_PCM_STATE_STARTED) {
virtio_snd_pcm_set_active(stream, true);
}
continue;
@@ -1227,6 +1271,16 @@ static void virtio_snd_realize(DeviceState *dev, Error **errp)
return;
}
if (vsnd->input_streams == VIRTIO_SOUND_INPUT_STREAMS_HALF) {
vsnd->input_streams = vsnd->snd_conf.streams / 2;
}
if (vsnd->input_streams > vsnd->snd_conf.streams) {
error_setg(errp,
"Invalid number of input streams: %"PRIu32" of %"PRIu32,
vsnd->input_streams, vsnd->snd_conf.streams);
return;
}
if (vsnd->snd_conf.chmaps > VIRTIO_SND_CHMAP_MAX_SIZE) {
error_setg(errp,
"Invalid number of channel maps: %"PRIu32,
@@ -1254,7 +1308,7 @@ static void virtio_snd_realize(DeviceState *dev, Error **errp)
stream->info.formats = supported_formats;
stream->info.rates = supported_rates;
stream->info.direction =
i < vsnd->snd_conf.streams / 2 + (vsnd->snd_conf.streams & 1)
i < vsnd->snd_conf.streams - vsnd->input_streams
? VIRTIO_SND_D_OUTPUT : VIRTIO_SND_D_INPUT;
stream->info.channels_min = 1;
stream->info.channels_max = 2;
@@ -1303,6 +1357,9 @@ static inline void return_tx_buffer(VirtIOSoundPCMStream *stream,
buffer,
VirtIOSoundPCMBuffer,
entry);
trace_virtio_snd_pcm_completed(virtio_snd_pcm_stream_id(stream),
buffer->offset, stream->latency_bytes,
virtio_snd_pcm_get_io_msgs_count(stream));
virtio_snd_pcm_buffer_free(buffer);
}
@@ -1366,15 +1423,23 @@ static void virtio_snd_pcm_out_cb(void *data, int available)
}
/*
* Flush all buffer data from this input stream's queue into the driver's
* virtual queue.
* Complete an input stream's I/O message: the frames recorded into it, from
* the start of its buffer, then the status part, which follows the buffer
* (5.14.6.8) wherever the frames end, as a buffer completes partly filled
* at the stream's end. The used length is the status' size plus that of the
* frames recorded.
*
* @stream: VirtIOSoundPCMStream *stream
* @buffer: the I/O message's buffer
*/
static inline void return_rx_buffer(VirtIOSoundPCMStream *stream,
VirtIOSoundPCMBuffer *buffer)
{
virtio_snd_pcm_status resp = { 0 };
/* virtio_snd_handle_rx_xfer took no message shorter than the status. */
size_t status_offset = iov_size(buffer->elem->in_sg, buffer->elem->in_num)
- sizeof(virtio_snd_pcm_status);
resp.status = cpu_to_le32(VIRTIO_SND_S_OK);
resp.latency_bytes = 0;
/* Copy data -if any- to guest */
@@ -1385,7 +1450,7 @@ static inline void return_rx_buffer(VirtIOSoundPCMStream *stream,
buffer->size);
iov_from_buf(buffer->elem->in_sg,
buffer->elem->in_num,
buffer->size,
status_offset,
&resp,
sizeof(virtio_snd_pcm_status));
virtqueue_push(buffer->vq,
@@ -1398,6 +1463,9 @@ static inline void return_rx_buffer(VirtIOSoundPCMStream *stream,
buffer,
VirtIOSoundPCMBuffer,
entry);
trace_virtio_snd_pcm_completed(virtio_snd_pcm_stream_id(stream),
buffer->size, 0,
virtio_snd_pcm_get_io_msgs_count(stream));
virtio_snd_pcm_buffer_free(buffer);
}
@@ -1414,6 +1482,18 @@ static void virtio_snd_pcm_in_cb(void *data, int available)
VirtIOSoundPCMBuffer *buffer;
size_t size, max_size, to_read;
if (QSIMPLEQ_EMPTY(&stream->queue)) {
/*
* Audio came, and the driver has no buffer posted to take it: stop
* the voice until it posts one (virtio_snd_handle_rx_xfer). A driver
* that keeps its input stream started and posts no buffers for it
* (macOS's AppleVirtIOSound starts its input with each output) then
* runs no capture on the host.
*/
virtio_snd_pcm_set_active(stream, false);
return;
}
while (!QSIMPLEQ_EMPTY(&stream->queue)) {
buffer = QSIMPLEQ_FIRST(&stream->queue);
if (!virtio_queue_ready(buffer->vq)) {
@@ -1432,14 +1512,18 @@ static void virtio_snd_pcm_in_cb(void *data, int available)
}
max_size -= sizeof(virtio_snd_pcm_status);
/*
* A message completes once its buffer is full, whatever its size
* against period_bytes: the device MUST NOT complete it before, but
* at the stream's end (5.14.6.8, Input Stream), where a flush and a
* stopped stream complete it as it is.
*/
for (;;) {
if (buffer->size >= max_size) {
return_rx_buffer(stream, buffer);
break;
}
to_read = stream->params.period_bytes - buffer->size;
to_read = MIN(to_read, available);
to_read = MIN(to_read, max_size - buffer->size);
to_read = MIN(max_size - buffer->size, available);
size = audio_be_read(stream->s->audio_be,
stream->voice.in,
buffer->data + buffer->size,
@@ -1450,7 +1534,7 @@ static void virtio_snd_pcm_in_cb(void *data, int available)
}
buffer->size += size;
available -= size;
if (buffer->size >= stream->params.period_bytes) {
if (buffer->size >= max_size) {
return_rx_buffer(stream, buffer);
break;
}
+6
View File
@@ -708,6 +708,12 @@ static void pl011_reset(DeviceState *dev)
s->logged_disabled_uart = false;
pl011_reset_rx_fifo(s);
pl011_reset_tx_fifo(s);
/*
* Lower the interrupt lines the cleared state no longer raises: a line
* keeps its level across a reset otherwise, and an in-kernel GIC (HVF's,
* KVM's) raises its interrupt again once the GIC is reset.
*/
pl011_update(s);
}
static void pl011_class_init(ObjectClass *oc, const void *data)
+2 -6
View File
@@ -150,11 +150,7 @@ config XLNX_DISPLAYPORT
config DM163
bool
config MAC_PVG_MMIO
config REIMS_GRAPHICS_PCI
bool
depends on MAC_PVG && AARCH64
config MAC_PVG_PCI
bool
depends on MAC_PVG && PCI
depends on REIMS_GRAPHICS && PCI && MSI_NONBROKEN
default y if PCI_DEVICES
-285
View File
@@ -1,285 +0,0 @@
/*
* QEMU Apple ParavirtualizedGraphics.framework device, MMIO (arm64) variant
*
* Copyright © 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: GPL-2.0-or-later
*
* ParavirtualizedGraphics.framework is a set of libraries that macOS provides
* which implements 3d graphics passthrough to the host as well as a
* proprietary guest communication channel to drive it. This device model
* implements support to drive that library from within QEMU as an MMIO-based
* system device for macOS on arm64 VMs.
*/
#include "qemu/osdep.h"
#include "qemu/log.h"
#include "qemu/aio-wait.h"
#include "hw/core/sysbus.h"
#include "hw/core/irq.h"
#include "apple-gfx.h"
#include "trace.h"
#import <ParavirtualizedGraphics/ParavirtualizedGraphics.h>
OBJECT_DECLARE_SIMPLE_TYPE(AppleGFXMMIOState, APPLE_GFX_MMIO)
/*
* ParavirtualizedGraphics.Framework only ships header files for the PCI
* variant which does not include IOSFC descriptors and host devices. We add
* their definitions here so that we can also work with the ARM version.
*/
typedef bool(^IOSFCRaiseInterrupt)(uint32_t vector);
typedef bool(^IOSFCUnmapMemory)(void *, void *, void *, void *, void *, void *);
typedef bool(^IOSFCMapMemory)(uint64_t phys, uint64_t len, bool ro, void **va,
void *, void *);
@interface PGDeviceDescriptor (IOSurfaceMapper)
@property (readwrite, nonatomic) bool usingIOSurfaceMapper;
@end
@interface PGIOSurfaceHostDeviceDescriptor : NSObject
-(PGIOSurfaceHostDeviceDescriptor *)init;
@property (readwrite, nonatomic, copy, nullable) IOSFCMapMemory mapMemory;
@property (readwrite, nonatomic, copy, nullable) IOSFCUnmapMemory unmapMemory;
@property (readwrite, nonatomic, copy, nullable) IOSFCRaiseInterrupt raiseInterrupt;
@end
@interface PGIOSurfaceHostDevice : NSObject
-(instancetype)initWithDescriptor:(PGIOSurfaceHostDeviceDescriptor *)desc;
-(uint32_t)mmioReadAtOffset:(size_t)offset;
-(void)mmioWriteAtOffset:(size_t)offset value:(uint32_t)value;
@end
struct AppleGFXMapSurfaceMemoryJob;
struct AppleGFXMMIOState {
SysBusDevice parent_obj;
AppleGFXState common;
qemu_irq irq_gfx;
qemu_irq irq_iosfc;
MemoryRegion iomem_iosfc;
PGIOSurfaceHostDevice *pgiosfc;
};
typedef struct AppleGFXMMIOJob {
AppleGFXMMIOState *state;
uint64_t offset;
uint64_t value;
bool completed;
} AppleGFXMMIOJob;
static void iosfc_do_read(void *opaque)
{
AppleGFXMMIOJob *job = opaque;
job->value = [job->state->pgiosfc mmioReadAtOffset:job->offset];
qatomic_set(&job->completed, true);
aio_wait_kick();
}
static uint64_t iosfc_read(void *opaque, hwaddr offset, unsigned size)
{
AppleGFXMMIOJob job = {
.state = opaque,
.offset = offset,
.completed = false,
};
dispatch_queue_t queue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async_f(queue, &job, iosfc_do_read);
AIO_WAIT_WHILE(NULL, !qatomic_read(&job.completed));
trace_apple_gfx_mmio_iosfc_read(offset, job.value);
return job.value;
}
static void iosfc_do_write(void *opaque)
{
AppleGFXMMIOJob *job = opaque;
[job->state->pgiosfc mmioWriteAtOffset:job->offset value:job->value];
qatomic_set(&job->completed, true);
aio_wait_kick();
}
static void iosfc_write(void *opaque, hwaddr offset, uint64_t val,
unsigned size)
{
AppleGFXMMIOJob job = {
.state = opaque,
.offset = offset,
.value = val,
.completed = false,
};
dispatch_queue_t queue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async_f(queue, &job, iosfc_do_write);
AIO_WAIT_WHILE(NULL, !qatomic_read(&job.completed));
trace_apple_gfx_mmio_iosfc_write(offset, val);
}
static const MemoryRegionOps apple_iosfc_ops = {
.read = iosfc_read,
.write = iosfc_write,
.endianness = DEVICE_LITTLE_ENDIAN,
.valid = {
.min_access_size = 4,
.max_access_size = 8,
},
.impl = {
.min_access_size = 4,
.max_access_size = 8,
},
};
static void raise_irq_bh(void *opaque)
{
qemu_irq *irq = opaque;
qemu_irq_pulse(*irq);
}
static void *apple_gfx_mmio_map_surface_memory(uint64_t guest_physical_address,
uint64_t length, bool read_only)
{
void *mem;
MemoryRegion *region = NULL;
RCU_READ_LOCK_GUARD();
mem = apple_gfx_host_ptr_for_gpa_range(guest_physical_address,
length, read_only, &region);
if (mem) {
memory_region_ref(region);
}
return mem;
}
static bool apple_gfx_mmio_unmap_surface_memory(void *ptr)
{
MemoryRegion *region;
ram_addr_t offset = 0;
RCU_READ_LOCK_GUARD();
region = memory_region_from_host(ptr, &offset);
if (!region) {
qemu_log_mask(LOG_GUEST_ERROR,
"%s: memory at %p to be unmapped not found.\n",
__func__, ptr);
return false;
}
trace_apple_gfx_iosfc_unmap_memory_region(ptr, region);
memory_region_unref(region);
return true;
}
static PGIOSurfaceHostDevice *apple_gfx_prepare_iosurface_host_device(
AppleGFXMMIOState *s)
{
PGIOSurfaceHostDeviceDescriptor *iosfc_desc =
[PGIOSurfaceHostDeviceDescriptor new];
PGIOSurfaceHostDevice *iosfc_host_dev;
iosfc_desc.mapMemory =
^bool(uint64_t phys, uint64_t len, bool ro, void **va, void *e, void *f) {
*va = apple_gfx_mmio_map_surface_memory(phys, len, ro);
trace_apple_gfx_iosfc_map_memory(phys, len, ro, va, e, f, *va);
return *va != NULL;
};
iosfc_desc.unmapMemory =
^bool(void *va, void *b, void *c, void *d, void *e, void *f) {
return apple_gfx_mmio_unmap_surface_memory(va);
};
iosfc_desc.raiseInterrupt = ^bool(uint32_t vector) {
trace_apple_gfx_iosfc_raise_irq(vector);
aio_bh_schedule_oneshot(qemu_get_aio_context(),
raise_irq_bh, &s->irq_iosfc);
return true;
};
iosfc_host_dev =
[[PGIOSurfaceHostDevice alloc] initWithDescriptor:iosfc_desc];
[iosfc_desc release];
return iosfc_host_dev;
}
static void apple_gfx_mmio_realize(DeviceState *dev, Error **errp)
{
@autoreleasepool {
AppleGFXMMIOState *s = APPLE_GFX_MMIO(dev);
PGDeviceDescriptor *desc = [PGDeviceDescriptor new];
desc.raiseInterrupt = ^(uint32_t vector) {
trace_apple_gfx_raise_irq(vector);
aio_bh_schedule_oneshot(qemu_get_aio_context(),
raise_irq_bh, &s->irq_gfx);
};
desc.usingIOSurfaceMapper = true;
s->pgiosfc = apple_gfx_prepare_iosurface_host_device(s);
if (!apple_gfx_common_realize(&s->common, dev, desc, errp)) {
[s->pgiosfc release];
s->pgiosfc = nil;
}
[desc release];
desc = nil;
}
}
static void apple_gfx_mmio_init(Object *obj)
{
AppleGFXMMIOState *s = APPLE_GFX_MMIO(obj);
apple_gfx_common_init(obj, &s->common, TYPE_APPLE_GFX_MMIO);
sysbus_init_mmio(SYS_BUS_DEVICE(s), &s->common.iomem_gfx);
memory_region_init_io(&s->iomem_iosfc, obj, &apple_iosfc_ops, s,
TYPE_APPLE_GFX_MMIO, 0x10000);
sysbus_init_mmio(SYS_BUS_DEVICE(s), &s->iomem_iosfc);
sysbus_init_irq(SYS_BUS_DEVICE(s), &s->irq_gfx);
sysbus_init_irq(SYS_BUS_DEVICE(s), &s->irq_iosfc);
}
static void apple_gfx_mmio_reset(Object *obj, ResetType type)
{
AppleGFXMMIOState *s = APPLE_GFX_MMIO(obj);
[s->common.pgdev reset];
}
static const Property apple_gfx_mmio_properties[] = {
DEFINE_PROP_ARRAY("display-modes", AppleGFXMMIOState,
common.num_display_modes, common.display_modes,
qdev_prop_apple_gfx_display_mode, AppleGFXDisplayMode),
};
static void apple_gfx_mmio_class_init(ObjectClass *klass, const void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
ResettableClass *rc = RESETTABLE_CLASS(klass);
rc->phases.hold = apple_gfx_mmio_reset;
dc->hotpluggable = false;
dc->realize = apple_gfx_mmio_realize;
device_class_set_props(dc, apple_gfx_mmio_properties);
}
static const TypeInfo apple_gfx_mmio_types[] = {
{
.name = TYPE_APPLE_GFX_MMIO,
.parent = TYPE_SYS_BUS_DEVICE,
.instance_size = sizeof(AppleGFXMMIOState),
.class_init = apple_gfx_mmio_class_init,
.instance_init = apple_gfx_mmio_init,
}
};
DEFINE_TYPES(apple_gfx_mmio_types)
-157
View File
@@ -1,157 +0,0 @@
/*
* QEMU Apple ParavirtualizedGraphics.framework device, PCI variant
*
* Copyright © 2023-2024 Phil Dennis-Jordan
*
* SPDX-License-Identifier: GPL-2.0-or-later
*
* ParavirtualizedGraphics.framework is a set of libraries that macOS provides
* which implements 3d graphics passthrough to the host as well as a
* proprietary guest communication channel to drive it. This device model
* implements support to drive that library from within QEMU as a PCI device
* aimed primarily at x86-64 macOS VMs.
*/
#include "qemu/osdep.h"
#include "hw/pci/pci_device.h"
#include "hw/pci/msi.h"
#include "apple-gfx.h"
#include "trace.h"
#import <ParavirtualizedGraphics/ParavirtualizedGraphics.h>
OBJECT_DECLARE_SIMPLE_TYPE(AppleGFXPCIState, APPLE_GFX_PCI)
struct AppleGFXPCIState {
PCIDevice parent_obj;
AppleGFXState common;
};
static const char *apple_gfx_pci_option_rom_path = NULL;
static void apple_gfx_init_option_rom_path(void)
{
NSURL *option_rom_url = PGCopyOptionROMURL();
const char *option_rom_path = option_rom_url.fileSystemRepresentation;
apple_gfx_pci_option_rom_path = g_strdup(option_rom_path);
[option_rom_url release];
}
static void apple_gfx_pci_init(Object *obj)
{
AppleGFXPCIState *s = APPLE_GFX_PCI(obj);
if (!apple_gfx_pci_option_rom_path) {
/*
* The following is done on device not class init to avoid running
* ObjC code before fork() in -daemonize mode.
*/
PCIDeviceClass *pci = PCI_DEVICE_CLASS(object_get_class(obj));
apple_gfx_init_option_rom_path();
pci->romfile = apple_gfx_pci_option_rom_path;
}
apple_gfx_common_init(obj, &s->common, TYPE_APPLE_GFX_PCI);
}
typedef struct AppleGFXPCIInterruptJob {
PCIDevice *device;
uint32_t vector;
} AppleGFXPCIInterruptJob;
static void apple_gfx_pci_raise_interrupt(void *opaque)
{
AppleGFXPCIInterruptJob *job = opaque;
if (msi_enabled(job->device)) {
msi_notify(job->device, job->vector);
}
g_free(job);
}
static void apple_gfx_pci_interrupt(PCIDevice *dev, uint32_t vector)
{
AppleGFXPCIInterruptJob *job;
trace_apple_gfx_raise_irq(vector);
job = g_malloc0(sizeof(*job));
job->device = dev;
job->vector = vector;
aio_bh_schedule_oneshot(qemu_get_aio_context(),
apple_gfx_pci_raise_interrupt, job);
}
static void apple_gfx_pci_realize(PCIDevice *dev, Error **errp)
{
AppleGFXPCIState *s = APPLE_GFX_PCI(dev);
int ret;
pci_register_bar(dev, PG_PCI_BAR_MMIO,
PCI_BASE_ADDRESS_SPACE_MEMORY, &s->common.iomem_gfx);
ret = msi_init(dev, 0x0 /* config offset; 0 = find space */,
PG_PCI_MAX_MSI_VECTORS, true /* msi64bit */,
false /* msi_per_vector_mask */, errp);
if (ret != 0) {
return;
}
@autoreleasepool {
PGDeviceDescriptor *desc = [PGDeviceDescriptor new];
desc.raiseInterrupt = ^(uint32_t vector) {
apple_gfx_pci_interrupt(dev, vector);
};
apple_gfx_common_realize(&s->common, DEVICE(dev), desc, errp);
[desc release];
desc = nil;
}
}
static void apple_gfx_pci_reset(Object *obj, ResetType type)
{
AppleGFXPCIState *s = APPLE_GFX_PCI(obj);
[s->common.pgdev reset];
}
static const Property apple_gfx_pci_properties[] = {
DEFINE_PROP_ARRAY("display-modes", AppleGFXPCIState,
common.num_display_modes, common.display_modes,
qdev_prop_apple_gfx_display_mode, AppleGFXDisplayMode),
};
static void apple_gfx_pci_class_init(ObjectClass *klass, const void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
PCIDeviceClass *pci = PCI_DEVICE_CLASS(klass);
ResettableClass *rc = RESETTABLE_CLASS(klass);
rc->phases.hold = apple_gfx_pci_reset;
dc->desc = "macOS Paravirtualized Graphics PCI Display Controller";
dc->hotpluggable = false;
set_bit(DEVICE_CATEGORY_DISPLAY, dc->categories);
pci->vendor_id = PG_PCI_VENDOR_ID;
pci->device_id = PG_PCI_DEVICE_ID;
pci->class_id = PCI_CLASS_DISPLAY_OTHER;
pci->realize = apple_gfx_pci_realize;
device_class_set_props(dc, apple_gfx_pci_properties);
}
static const TypeInfo apple_gfx_pci_types[] = {
{
.name = TYPE_APPLE_GFX_PCI,
.parent = TYPE_PCI_DEVICE,
.instance_size = sizeof(AppleGFXPCIState),
.class_init = apple_gfx_pci_class_init,
.instance_init = apple_gfx_pci_init,
.interfaces = (const InterfaceInfo[]) {
{ INTERFACE_PCIE_DEVICE },
{ },
},
}
};
DEFINE_TYPES(apple_gfx_pci_types)
-74
View File
@@ -1,74 +0,0 @@
/*
* Data structures and functions shared between variants of the macOS
* ParavirtualizedGraphics.framework based apple-gfx display adapter.
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef QEMU_APPLE_GFX_H
#define QEMU_APPLE_GFX_H
#include "qemu/queue.h"
#include "system/memory.h"
#include "hw/core/qdev-properties.h"
#include "ui/surface.h"
#define TYPE_APPLE_GFX_MMIO "apple-gfx-mmio"
#define TYPE_APPLE_GFX_PCI "apple-gfx-pci"
@class PGDeviceDescriptor;
@protocol PGDevice;
@protocol PGDisplay;
@protocol MTLDevice;
@protocol MTLTexture;
@protocol MTLCommandQueue;
typedef QTAILQ_HEAD(, PGTask_s) PGTaskList;
typedef struct AppleGFXDisplayMode {
uint16_t width_px;
uint16_t height_px;
uint16_t refresh_rate_hz;
} AppleGFXDisplayMode;
typedef struct AppleGFXState {
/* Initialised on init/realize() */
MemoryRegion iomem_gfx;
id<PGDevice> pgdev;
id<PGDisplay> pgdisp;
QemuConsole *con;
id<MTLDevice> mtl;
id<MTLCommandQueue> mtl_queue;
AppleGFXDisplayMode *display_modes;
uint32_t num_display_modes;
/* List `tasks` is protected by task_mutex */
QemuMutex task_mutex;
PGTaskList tasks;
/* Mutable state (BQL protected) */
QEMUCursor *cursor;
DisplaySurface *surface;
id<MTLTexture> texture;
int8_t pending_frames; /* # guest frames in the rendering pipeline */
bool gfx_update_requested; /* QEMU display system wants a new frame */
bool new_frame_ready; /* Guest has rendered a frame, ready to be used */
bool using_managed_texture_storage;
uint32_t rendering_frame_width;
uint32_t rendering_frame_height;
/* Mutable state (atomic) */
bool cursor_show;
} AppleGFXState;
void apple_gfx_common_init(Object *obj, AppleGFXState *s, const char* obj_name);
bool apple_gfx_common_realize(AppleGFXState *s, DeviceState *dev,
PGDeviceDescriptor *desc, Error **errp);
void *apple_gfx_host_ptr_for_gpa_range(uint64_t guest_physical,
uint64_t length, bool read_only,
MemoryRegion **mapping_in_region);
extern const PropertyInfo qdev_prop_apple_gfx_display_mode;
#endif
-882
View File
@@ -1,882 +0,0 @@
/*
* QEMU Apple ParavirtualizedGraphics.framework device
*
* Copyright © 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: GPL-2.0-or-later
*
* ParavirtualizedGraphics.framework is a set of libraries that macOS provides
* which implements 3d graphics passthrough to the host as well as a
* proprietary guest communication channel to drive it. This device model
* implements support to drive that library from within QEMU.
*/
#include "qemu/osdep.h"
#include "qemu/lockable.h"
#include "qemu/cutils.h"
#include "qemu/log.h"
#include "qapi/qapi-builtin-type-infos.h"
#include "qapi/visitor.h"
#include "qapi/error.h"
#include "qemu/aio-wait.h"
#include "system/address-spaces.h"
#include "system/dma.h"
#include "migration/blocker.h"
#include "ui/console.h"
#include "apple-gfx.h"
#include "trace.h"
#include <mach/mach.h>
#include <mach/mach_vm.h>
#include <dispatch/dispatch.h>
#import <ParavirtualizedGraphics/ParavirtualizedGraphics.h>
static const AppleGFXDisplayMode apple_gfx_default_modes[] = {
{ 1920, 1080, 60 },
{ 1440, 1080, 60 },
{ 1280, 1024, 60 },
};
static Error *apple_gfx_mig_blocker;
static uint32_t next_pgdisplay_serial_num = 1;
static dispatch_queue_t get_background_queue(void)
{
return dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
}
/* ------ PGTask and task operations: new/destroy/map/unmap ------ */
/*
* This implements the type declared in <ParavirtualizedGraphics/PGDevice.h>
* which is opaque from the framework's point of view. It is used in callbacks
* in the form of its typedef PGTask_t, which also already exists in the
* framework headers.
*
* A "task" in PVG terminology represents a host-virtual contiguous address
* range which is reserved in a large chunk on task creation. The mapMemory
* callback then requests ranges of guest system memory (identified by their
* GPA) to be mapped into subranges of this reserved address space.
* This type of operation isn't well-supported by QEMU's memory subsystem,
* but it is fortunately trivial to achieve with Darwin's mach_vm_remap() call,
* which allows us to refer to the same backing memory via multiple virtual
* address ranges. The Mach VM APIs are therefore used throughout for managing
* task memory.
*/
struct PGTask_s {
QTAILQ_ENTRY(PGTask_s) node;
AppleGFXState *s;
mach_vm_address_t address;
uint64_t len;
/*
* All unique MemoryRegions for which a mapping has been created in this
* task, and on which we have thus called memory_region_ref(). There are
* usually very few regions of system RAM in total, so we expect this array
* to be very short. Therefore, no need for sorting or fancy search
* algorithms, linear search will do.
* Protected by AppleGFXState's task_mutex.
*/
GPtrArray *mapped_regions;
};
static PGTask_t *apple_gfx_new_task(AppleGFXState *s, uint64_t len)
{
mach_vm_address_t task_mem;
PGTask_t *task;
kern_return_t r;
r = mach_vm_allocate(mach_task_self(), &task_mem, len, VM_FLAGS_ANYWHERE);
if (r != KERN_SUCCESS) {
return NULL;
}
task = g_new0(PGTask_t, 1);
task->s = s;
task->address = task_mem;
task->len = len;
task->mapped_regions = g_ptr_array_sized_new(2 /* Usually enough */);
QEMU_LOCK_GUARD(&s->task_mutex);
QTAILQ_INSERT_TAIL(&s->tasks, task, node);
return task;
}
static void apple_gfx_destroy_task(AppleGFXState *s, PGTask_t *task)
{
GPtrArray *regions = task->mapped_regions;
MemoryRegion *region;
size_t i;
for (i = 0; i < regions->len; ++i) {
region = g_ptr_array_index(regions, i);
memory_region_unref(region);
}
g_ptr_array_unref(regions);
mach_vm_deallocate(mach_task_self(), task->address, task->len);
QEMU_LOCK_GUARD(&s->task_mutex);
QTAILQ_REMOVE(&s->tasks, task, node);
g_free(task);
}
void *apple_gfx_host_ptr_for_gpa_range(uint64_t guest_physical,
uint64_t length, bool read_only,
MemoryRegion **mapping_in_region)
{
MemoryRegion *ram_region;
char *host_ptr;
hwaddr ram_region_offset = 0;
hwaddr ram_region_length = length;
ram_region = address_space_translate(&address_space_memory,
guest_physical,
&ram_region_offset,
&ram_region_length, !read_only,
MEMTXATTRS_UNSPECIFIED);
if (!ram_region || ram_region_length < length ||
!memory_access_is_direct(ram_region, !read_only,
MEMTXATTRS_UNSPECIFIED)) {
return NULL;
}
host_ptr = memory_region_get_ram_ptr(ram_region);
if (!host_ptr) {
return NULL;
}
host_ptr += ram_region_offset;
*mapping_in_region = ram_region;
return host_ptr;
}
static bool apple_gfx_task_map_memory(AppleGFXState *s, PGTask_t *task,
uint64_t virtual_offset,
PGPhysicalMemoryRange_t *ranges,
uint32_t range_count, bool read_only)
{
kern_return_t r;
void *source_ptr;
mach_vm_address_t target;
vm_prot_t cur_protection, max_protection;
bool success = true;
MemoryRegion *region;
RCU_READ_LOCK_GUARD();
QEMU_LOCK_GUARD(&s->task_mutex);
trace_apple_gfx_map_memory(task, range_count, virtual_offset, read_only);
for (int i = 0; i < range_count; i++) {
PGPhysicalMemoryRange_t *range = &ranges[i];
target = task->address + virtual_offset;
virtual_offset += range->physicalLength;
trace_apple_gfx_map_memory_range(i, range->physicalAddress,
range->physicalLength);
region = NULL;
source_ptr = apple_gfx_host_ptr_for_gpa_range(range->physicalAddress,
range->physicalLength,
read_only, &region);
if (!source_ptr) {
success = false;
continue;
}
if (!g_ptr_array_find(task->mapped_regions, region, NULL)) {
g_ptr_array_add(task->mapped_regions, region);
memory_region_ref(region);
}
cur_protection = 0;
max_protection = 0;
/* Map guest RAM at range->physicalAddress into PG task memory range */
r = mach_vm_remap(mach_task_self(),
&target, range->physicalLength, vm_page_size - 1,
VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE,
mach_task_self(), (mach_vm_address_t)source_ptr,
false /* shared mapping, no copy */,
&cur_protection, &max_protection,
VM_INHERIT_COPY);
trace_apple_gfx_remap(r, source_ptr, target);
g_assert(r == KERN_SUCCESS);
}
return success;
}
static void apple_gfx_task_unmap_memory(AppleGFXState *s, PGTask_t *task,
uint64_t virtual_offset, uint64_t length)
{
kern_return_t r;
mach_vm_address_t range_address;
trace_apple_gfx_unmap_memory(task, virtual_offset, length);
/*
* Replace task memory range with fresh 0 pages, undoing the mapping
* from guest RAM.
*/
range_address = task->address + virtual_offset;
r = mach_vm_allocate(mach_task_self(), &range_address, length,
VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE);
g_assert(r == KERN_SUCCESS);
}
/* ------ Rendering and frame management ------ */
static void apple_gfx_render_frame_completed_bh(void *opaque);
static void apple_gfx_render_new_frame(AppleGFXState *s)
{
bool managed_texture = s->using_managed_texture_storage;
uint32_t width = surface_width(s->surface);
uint32_t height = surface_height(s->surface);
MTLRegion region = MTLRegionMake2D(0, 0, width, height);
id<MTLCommandBuffer> command_buffer = [s->mtl_queue commandBuffer];
id<MTLTexture> texture = s->texture;
assert(bql_locked());
[texture retain];
[command_buffer retain];
s->rendering_frame_width = width;
s->rendering_frame_height = height;
dispatch_async(get_background_queue(), ^{
/*
* This is not safe to call from the BQL/BH due to PVG-internal locks
* causing deadlocks.
*/
bool r = [s->pgdisp encodeCurrentFrameToCommandBuffer:command_buffer
texture:texture
region:region];
if (!r) {
[texture release];
[command_buffer release];
qemu_log_mask(LOG_GUEST_ERROR,
"%s: encodeCurrentFrameToCommandBuffer:texture:region: "
"failed\n", __func__);
bql_lock();
--s->pending_frames;
if (s->pending_frames > 0) {
apple_gfx_render_new_frame(s);
}
bql_unlock();
return;
}
if (managed_texture) {
/* "Managed" textures exist in both VRAM and RAM and must be synced. */
id<MTLBlitCommandEncoder> blit = [command_buffer blitCommandEncoder];
[blit synchronizeResource:texture];
[blit endEncoding];
}
[texture release];
[command_buffer addCompletedHandler:
^(id<MTLCommandBuffer> cb)
{
aio_bh_schedule_oneshot(qemu_get_aio_context(),
apple_gfx_render_frame_completed_bh, s);
}];
[command_buffer commit];
[command_buffer release];
});
}
static void copy_mtl_texture_to_surface_mem(id<MTLTexture> texture, void *vram)
{
/*
* TODO: Skip this entirely on a pure Metal or headless/guest-only
* rendering path, else use a blit command encoder? Needs careful
* (double?) buffering design.
*/
size_t width = texture.width, height = texture.height;
MTLRegion region = MTLRegionMake2D(0, 0, width, height);
[texture getBytes:vram
bytesPerRow:(width * 4)
bytesPerImage:(width * height * 4)
fromRegion:region
mipmapLevel:0
slice:0];
}
static void apple_gfx_render_frame_completed_bh(void *opaque)
{
AppleGFXState *s = opaque;
@autoreleasepool {
--s->pending_frames;
assert(s->pending_frames >= 0);
/* Only update display if mode hasn't changed since we started rendering. */
if (s->rendering_frame_width == surface_width(s->surface) &&
s->rendering_frame_height == surface_height(s->surface)) {
copy_mtl_texture_to_surface_mem(s->texture, surface_data(s->surface));
if (s->gfx_update_requested) {
s->gfx_update_requested = false;
qemu_console_update_full(s->con);
qemu_console_hw_update_done(s->con);
s->new_frame_ready = false;
} else {
s->new_frame_ready = true;
}
}
if (s->pending_frames > 0) {
apple_gfx_render_new_frame(s);
}
}
}
static bool apple_gfx_fb_update_display(void *opaque)
{
AppleGFXState *s = opaque;
bool done = true;
assert(bql_locked());
if (s->new_frame_ready) {
qemu_console_update_full(s->con);
s->new_frame_ready = false;
} else if (s->pending_frames > 0) {
s->gfx_update_requested = true;
done = false;
}
return done;
}
static const GraphicHwOps apple_gfx_fb_ops = {
.gfx_update = apple_gfx_fb_update_display,
};
/* ------ Mouse cursor and display mode setting ------ */
static void set_mode(AppleGFXState *s, uint32_t width, uint32_t height)
{
MTLTextureDescriptor *textureDescriptor;
if (s->surface &&
width == surface_width(s->surface) &&
height == surface_height(s->surface)) {
return;
}
[s->texture release];
s->surface = qemu_create_displaysurface(width, height);
@autoreleasepool {
textureDescriptor =
[MTLTextureDescriptor
texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
width:width
height:height
mipmapped:NO];
textureDescriptor.usage = s->pgdisp.minimumTextureUsage;
s->texture = [s->mtl newTextureWithDescriptor:textureDescriptor];
s->using_managed_texture_storage =
(s->texture.storageMode == MTLStorageModeManaged);
}
qemu_console_set_surface(s->con, s->surface);
}
static void update_cursor(AppleGFXState *s)
{
assert(bql_locked());
qemu_console_set_mouse(s->con, s->pgdisp.cursorPosition.x,
s->pgdisp.cursorPosition.y, qatomic_read(&s->cursor_show));
}
static void update_cursor_bh(void *opaque)
{
AppleGFXState *s = opaque;
update_cursor(s);
}
typedef struct AppleGFXSetCursorGlyphJob {
AppleGFXState *s;
NSBitmapImageRep *glyph;
PGDisplayCoord_t hotspot;
} AppleGFXSetCursorGlyphJob;
static void set_cursor_glyph(void *opaque)
{
AppleGFXSetCursorGlyphJob *job = opaque;
AppleGFXState *s = job->s;
NSBitmapImageRep *glyph = job->glyph;
uint32_t bpp = glyph.bitsPerPixel;
size_t width = glyph.pixelsWide;
size_t height = glyph.pixelsHigh;
size_t padding_bytes_per_row = glyph.bytesPerRow - width * 4;
const uint8_t* px_data = glyph.bitmapData;
trace_apple_gfx_cursor_set(bpp, width, height);
if (s->cursor) {
cursor_unref(s->cursor);
s->cursor = NULL;
}
if (bpp == 32) { /* Shouldn't be anything else, but just to be safe... */
s->cursor = cursor_alloc(width, height);
s->cursor->hot_x = job->hotspot.x;
s->cursor->hot_y = job->hotspot.y;
uint32_t *dest_px = s->cursor->data;
for (size_t y = 0; y < height; ++y) {
for (size_t x = 0; x < width; ++x) {
/*
* NSBitmapImageRep's red & blue channels are swapped
* compared to QEMUCursor's.
*/
*dest_px =
(px_data[0] << 16u) |
(px_data[1] << 8u) |
(px_data[2] << 0u) |
(px_data[3] << 24u);
++dest_px;
px_data += 4;
}
px_data += padding_bytes_per_row;
}
qemu_console_set_cursor(s->con, s->cursor);
update_cursor(s);
}
[glyph release];
g_free(job);
}
/* ------ DMA (device reading system memory) ------ */
typedef struct AppleGFXReadMemoryJob {
QemuEvent event;
hwaddr physical_address;
uint64_t length;
void *dst;
bool success;
} AppleGFXReadMemoryJob;
static void apple_gfx_do_read_memory(void *opaque)
{
AppleGFXReadMemoryJob *job = opaque;
MemTxResult r;
r = dma_memory_read(&address_space_memory, job->physical_address,
job->dst, job->length, MEMTXATTRS_UNSPECIFIED);
job->success = (r == MEMTX_OK);
qemu_event_set(&job->event);
}
static bool apple_gfx_read_memory(AppleGFXState *s, hwaddr physical_address,
uint64_t length, void *dst)
{
AppleGFXReadMemoryJob job = {
.physical_address = physical_address, .length = length, .dst = dst
};
trace_apple_gfx_read_memory(physical_address, length, dst);
/* Performing DMA requires BQL, so do it in a BH. */
qemu_event_init(&job.event, 0);
aio_bh_schedule_oneshot(qemu_get_aio_context(),
apple_gfx_do_read_memory, &job);
qemu_event_wait(&job.event);
qemu_event_destroy(&job.event);
return job.success;
}
/* ------ Memory-mapped device I/O operations ------ */
typedef struct AppleGFXIOJob {
AppleGFXState *state;
uint64_t offset;
uint64_t value;
bool completed;
} AppleGFXIOJob;
static void apple_gfx_do_read(void *opaque)
{
AppleGFXIOJob *job = opaque;
job->value = [job->state->pgdev mmioReadAtOffset:job->offset];
qatomic_set(&job->completed, true);
aio_wait_kick();
}
static uint64_t apple_gfx_read(void *opaque, hwaddr offset, unsigned size)
{
AppleGFXIOJob job = {
.state = opaque,
.offset = offset,
.completed = false,
};
dispatch_queue_t queue = get_background_queue();
dispatch_async_f(queue, &job, apple_gfx_do_read);
AIO_WAIT_WHILE(NULL, !qatomic_read(&job.completed));
trace_apple_gfx_read(offset, job.value);
return job.value;
}
static void apple_gfx_do_write(void *opaque)
{
AppleGFXIOJob *job = opaque;
[job->state->pgdev mmioWriteAtOffset:job->offset value:job->value];
qatomic_set(&job->completed, true);
aio_wait_kick();
}
static void apple_gfx_write(void *opaque, hwaddr offset, uint64_t val,
unsigned size)
{
/*
* The methods mmioReadAtOffset: and especially mmioWriteAtOffset: can
* trigger synchronous operations on other dispatch queues, which in turn
* may call back out on one or more of the callback blocks. For this reason,
* and as we are holding the BQL, we invoke the I/O methods on a pool
* thread and handle AIO tasks while we wait. Any work in the callbacks
* requiring the BQL will in turn schedule BHs which this thread will
* process while waiting.
*/
AppleGFXIOJob job = {
.state = opaque,
.offset = offset,
.value = val,
.completed = false,
};
dispatch_queue_t queue = get_background_queue();
dispatch_async_f(queue, &job, apple_gfx_do_write);
AIO_WAIT_WHILE(NULL, !qatomic_read(&job.completed));
trace_apple_gfx_write(offset, val);
}
static const MemoryRegionOps apple_gfx_ops = {
.read = apple_gfx_read,
.write = apple_gfx_write,
.endianness = DEVICE_LITTLE_ENDIAN,
.valid = {
.min_access_size = 4,
.max_access_size = 8,
},
.impl = {
.min_access_size = 4,
.max_access_size = 4,
},
};
static size_t apple_gfx_get_default_mmio_range_size(void)
{
size_t mmio_range_size;
@autoreleasepool {
PGDeviceDescriptor *desc = [PGDeviceDescriptor new];
mmio_range_size = desc.mmioLength;
[desc release];
}
return mmio_range_size;
}
/* ------ Initialisation and startup ------ */
void apple_gfx_common_init(Object *obj, AppleGFXState *s, const char* obj_name)
{
size_t mmio_range_size = apple_gfx_get_default_mmio_range_size();
trace_apple_gfx_common_init(obj_name, mmio_range_size);
memory_region_init_io(&s->iomem_gfx, obj, &apple_gfx_ops, s, obj_name,
mmio_range_size);
/* TODO: PVG framework supports serialising device state: integrate it! */
}
static void apple_gfx_register_task_mapping_handlers(AppleGFXState *s,
PGDeviceDescriptor *desc)
{
desc.createTask = ^(uint64_t vmSize, void * _Nullable * _Nonnull baseAddress) {
PGTask_t *task = apple_gfx_new_task(s, vmSize);
*baseAddress = (void *)task->address;
trace_apple_gfx_create_task(vmSize, *baseAddress);
return task;
};
desc.destroyTask = ^(PGTask_t * _Nonnull task) {
trace_apple_gfx_destroy_task(task, task->mapped_regions->len);
apple_gfx_destroy_task(s, task);
};
desc.mapMemory = ^bool(PGTask_t * _Nonnull task, uint32_t range_count,
uint64_t virtual_offset, bool read_only,
PGPhysicalMemoryRange_t * _Nonnull ranges) {
return apple_gfx_task_map_memory(s, task, virtual_offset,
ranges, range_count, read_only);
};
desc.unmapMemory = ^bool(PGTask_t * _Nonnull task, uint64_t virtual_offset,
uint64_t length) {
apple_gfx_task_unmap_memory(s, task, virtual_offset, length);
return true;
};
desc.readMemory = ^bool(uint64_t physical_address, uint64_t length,
void * _Nonnull dst) {
return apple_gfx_read_memory(s, physical_address, length, dst);
};
}
static void new_frame_handler_bh(void *opaque)
{
AppleGFXState *s = opaque;
/* Drop frames if guest gets too far ahead. */
if (s->pending_frames >= 2) {
return;
}
++s->pending_frames;
if (s->pending_frames > 1) {
return;
}
@autoreleasepool {
apple_gfx_render_new_frame(s);
}
}
static PGDisplayDescriptor *apple_gfx_prepare_display_descriptor(AppleGFXState *s)
{
PGDisplayDescriptor *disp_desc = [PGDisplayDescriptor new];
disp_desc.name = @"QEMU display";
disp_desc.sizeInMillimeters = NSMakeSize(400., 300.); /* A 20" display */
disp_desc.queue = dispatch_get_main_queue();
disp_desc.newFrameEventHandler = ^(void) {
trace_apple_gfx_new_frame();
aio_bh_schedule_oneshot(qemu_get_aio_context(), new_frame_handler_bh, s);
};
disp_desc.modeChangeHandler = ^(PGDisplayCoord_t sizeInPixels,
OSType pixelFormat) {
trace_apple_gfx_mode_change(sizeInPixels.x, sizeInPixels.y);
BQL_LOCK_GUARD();
set_mode(s, sizeInPixels.x, sizeInPixels.y);
};
disp_desc.cursorGlyphHandler = ^(NSBitmapImageRep *glyph,
PGDisplayCoord_t hotspot) {
AppleGFXSetCursorGlyphJob *job = g_malloc0(sizeof(*job));
job->s = s;
job->glyph = glyph;
job->hotspot = hotspot;
[glyph retain];
aio_bh_schedule_oneshot(qemu_get_aio_context(),
set_cursor_glyph, job);
};
disp_desc.cursorShowHandler = ^(BOOL show) {
trace_apple_gfx_cursor_show(show);
qatomic_set(&s->cursor_show, show);
aio_bh_schedule_oneshot(qemu_get_aio_context(),
update_cursor_bh, s);
};
disp_desc.cursorMoveHandler = ^(void) {
trace_apple_gfx_cursor_move();
aio_bh_schedule_oneshot(qemu_get_aio_context(),
update_cursor_bh, s);
};
return disp_desc;
}
static NSArray<PGDisplayMode *> *apple_gfx_create_display_mode_array(
const AppleGFXDisplayMode display_modes[], uint32_t display_mode_count)
{
PGDisplayMode *mode_obj;
NSMutableArray<PGDisplayMode *> *mode_array =
[[NSMutableArray alloc] initWithCapacity:display_mode_count];
for (unsigned i = 0; i < display_mode_count; i++) {
const AppleGFXDisplayMode *mode = &display_modes[i];
trace_apple_gfx_display_mode(i, mode->width_px, mode->height_px);
PGDisplayCoord_t mode_size = { mode->width_px, mode->height_px };
mode_obj =
[[PGDisplayMode alloc] initWithSizeInPixels:mode_size
refreshRateInHz:mode->refresh_rate_hz];
[mode_array addObject:mode_obj];
[mode_obj release];
}
return mode_array;
}
static id<MTLDevice> copy_suitable_metal_device(void)
{
id<MTLDevice> dev = nil;
NSArray<id<MTLDevice>> *devs = MTLCopyAllDevices();
/* Prefer a unified memory GPU. Failing that, pick a non-removable GPU. */
for (size_t i = 0; i < devs.count; ++i) {
if (devs[i].hasUnifiedMemory) {
dev = devs[i];
break;
}
if (!devs[i].removable) {
dev = devs[i];
}
}
if (dev != nil) {
[dev retain];
} else {
dev = MTLCreateSystemDefaultDevice();
}
[devs release];
return dev;
}
bool apple_gfx_common_realize(AppleGFXState *s, DeviceState *dev,
PGDeviceDescriptor *desc, Error **errp)
{
PGDisplayDescriptor *disp_desc;
const AppleGFXDisplayMode *display_modes = apple_gfx_default_modes;
uint32_t num_display_modes = ARRAY_SIZE(apple_gfx_default_modes);
NSArray<PGDisplayMode *> *mode_array;
if (apple_gfx_mig_blocker == NULL) {
error_setg(&apple_gfx_mig_blocker,
"Migration state blocked by apple-gfx display device");
if (migrate_add_blocker(&apple_gfx_mig_blocker, errp) < 0) {
return false;
}
}
qemu_mutex_init(&s->task_mutex);
QTAILQ_INIT(&s->tasks);
s->mtl = copy_suitable_metal_device();
s->mtl_queue = [s->mtl newCommandQueue];
desc.device = s->mtl;
apple_gfx_register_task_mapping_handlers(s, desc);
s->cursor_show = true;
s->pgdev = PGNewDeviceWithDescriptor(desc);
disp_desc = apple_gfx_prepare_display_descriptor(s);
/*
* Although the framework does, this integration currently does not support
* multiple virtual displays connected to a single PV graphics device.
* It is however possible to create
* more than one instance of the device, each with one display. The macOS
* guest will ignore these displays if they share the same serial number,
* so ensure each instance gets a unique one.
*/
s->pgdisp = [s->pgdev newDisplayWithDescriptor:disp_desc
port:0
serialNum:next_pgdisplay_serial_num++];
[disp_desc release];
if (s->display_modes != NULL && s->num_display_modes > 0) {
trace_apple_gfx_common_realize_modes_property(s->num_display_modes);
display_modes = s->display_modes;
num_display_modes = s->num_display_modes;
}
s->pgdisp.modeList = mode_array =
apple_gfx_create_display_mode_array(display_modes, num_display_modes);
[mode_array release];
s->con = qemu_graphic_console_create(dev, 0, &apple_gfx_fb_ops, s);
return true;
}
/* ------ Display mode list device property ------ */
static void apple_gfx_get_display_mode(Object *obj, Visitor *v,
const char *name, void *opaque,
Error **errp)
{
Property *prop = opaque;
AppleGFXDisplayMode *mode = object_field_prop_ptr(obj, prop);
/* 3 uint16s (max 5 digits) + 2 separator characters + nul. */
char buffer[5 * 3 + 2 + 1];
char *pos = buffer;
int rc = snprintf(buffer, sizeof(buffer),
"%"PRIu16"x%"PRIu16"@%"PRIu16,
mode->width_px, mode->height_px,
mode->refresh_rate_hz);
assert(rc < sizeof(buffer));
visit_type_str(v, name, &pos, errp);
}
static void apple_gfx_set_display_mode(Object *obj, Visitor *v,
const char *name, void *opaque,
Error **errp)
{
Property *prop = opaque;
AppleGFXDisplayMode *mode = object_field_prop_ptr(obj, prop);
const char *endptr;
g_autofree char *str = NULL;
int ret;
int val;
if (!visit_type_str(v, name, &str, errp)) {
return;
}
endptr = str;
ret = qemu_strtoi(endptr, &endptr, 10, &val);
if (ret || val > UINT16_MAX || val <= 0) {
error_setg(errp, "width in '%s' must be a decimal integer number"
" of pixels in the range 1..65535", name);
return;
}
mode->width_px = val;
if (*endptr != 'x') {
goto separator_error;
}
ret = qemu_strtoi(endptr + 1, &endptr, 10, &val);
if (ret || val > UINT16_MAX || val <= 0) {
error_setg(errp, "height in '%s' must be a decimal integer number"
" of pixels in the range 1..65535", name);
return;
}
mode->height_px = val;
if (*endptr != '@') {
goto separator_error;
}
ret = qemu_strtoi(endptr + 1, &endptr, 10, &val);
if (ret || val > UINT16_MAX || val <= 0) {
error_setg(errp, "refresh rate in '%s'"
" must be a positive decimal integer (Hertz)", name);
return;
}
mode->refresh_rate_hz = val;
return;
separator_error:
error_setg(errp,
"Each display mode takes the format '<width>x<height>@<rate>'");
}
const PropertyInfo qdev_prop_apple_gfx_display_mode = {
.type = "display_mode",
.qapi_type = &str_type_info,
.description =
"Display mode in pixels and Hertz, as <width>x<height>@<refresh-rate> "
"Example: 3840x2160@60",
.get = apple_gfx_get_display_mode,
.set = apple_gfx_set_display_mode,
};
+14 -2
View File
@@ -65,8 +65,20 @@ system_ss.add(when: 'CONFIG_ARTIST', if_true: files('artist.c'))
system_ss.add(when: 'CONFIG_ATI_VGA', if_true: [files('ati.c', 'ati_2d.c', 'ati_dbg.c'), pixman])
system_ss.add(when: [pvg, 'CONFIG_MAC_PVG_PCI'], if_true: [files('apple-gfx.m', 'apple-gfx-pci.m')])
system_ss.add(when: [pvg, 'CONFIG_MAC_PVG_MMIO'], if_true: [files('apple-gfx.m', 'apple-gfx-mmio.m')])
# The reims-graphics device's transport; reims-vgpu's graphics device is its
# host side.
reims_graphics_ss = ss.source_set()
reims_graphics_ss.add(files('reims-graphics-pci.c',
'reims-graphics-pci-prefault.c'))
# Its calls into KVM. system_ss builds the device once for every target, and a
# target without KVM links no KVM function, so those targets take the stub.
if host_os == 'linux'
reims_graphics_ss.add(when: 'CONFIG_KVM',
if_true: files('reims-graphics-pci-kvm.c'),
if_false: files('reims-graphics-pci-kvm-stub.c'))
endif
system_ss.add_all(when: [reims_vgpu, 'CONFIG_REIMS_GRAPHICS_PCI'],
if_true: reims_graphics_ss)
if config_all_devices.has_key('CONFIG_VIRTIO_GPU')
virtio_gpu_ss = ss.source_set()
+18
View File
@@ -0,0 +1,18 @@
/*
* QEMU reims-graphics device: its calls into KVM, for the targets without KVM
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "qemu/osdep.h"
#include "reims-graphics-pci-kvm.h"
bool reims_graphics_kvm_disable_slot_zap_all(void)
{
return true;
}
const ReimsGraphicsPrefaultOps *reims_graphics_kvm_prefault_ops(void)
{
return NULL;
}
+317
View File
@@ -0,0 +1,317 @@
/*
* QEMU reims-graphics device: its calls into KVM, for the targets with KVM
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "qemu/osdep.h"
#include <sys/ioctl.h>
#include "qapi/error.h"
#include "qemu/error-report.h"
#include "qemu/main-loop.h"
#include "qemu/notify.h"
#include "hw/core/boards.h"
#include "hw/core/cpu.h"
#include "system/kvm.h"
#include <linux/kvm.h>
#include "reims-graphics-pci-kvm.h"
#include "reims-graphics-pci-prefault.h"
#include "trace.h"
bool reims_graphics_kvm_disable_slot_zap_all(void)
{
#ifdef KVM_X86_QUIRK_SLOT_ZAP_ALL
struct kvm_enable_cap cap = {
.cap = KVM_CAP_DISABLE_QUIRKS2,
.args = { KVM_X86_QUIRK_SLOT_ZAP_ALL },
};
if (!kvm_enabled() ||
!(kvm_check_extension(kvm_state, KVM_CAP_DISABLE_QUIRKS2) &
KVM_X86_QUIRK_SLOT_ZAP_ALL)) {
return true;
}
return kvm_vm_ioctl(kvm_state, KVM_ENABLE_CAP, &cap) >= 0;
#else
return true;
#endif
}
#if defined(__x86_64__) && defined(KVM_PRE_FAULT_MEMORY)
/*
* The pool's populate on KVM: KVM_PRE_FAULT_MEMORY, a vCPU ioctl, on a vCPU
* of the populate thread's own, the helper. The guest's vCPUs are never
* used for it: each call holds its vCPU's mutex, which a guest vCPU's
* KVM_RUN holds while the guest runs.
*
* The helper is made by the populate thread (KVM_CREATE_VCPU), which issues
* every call on it, and never runs: no KVM_RUN, no state put but its CPUID,
* its TSC frequency and its TSC (below). KVM fills the VM's shared TDP
* tables, whose root a vCPU picks by its role: CPUID's MAXPHYADDR (on a
* host with 5-level paging), SMM and guest mode, and the memory type of a
* mapping takes no vCPU state (arch/x86/kvm/mmu/mmu.c:5963-6010,
* arch/x86/kvm/vmx/vmx.c:7791-7805 in Linux 7.3.3). Given 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 guest has or can be given
* (MachineClass::possible_cpu_arch_ids), so no message the guest sends to
* the CPUs it is told of names it, and its APIC stays software-disabled
* with its LVTs masked, so a fixed, lowest-priority or logical message
* never takes it. KVM_CAP_MAX_VCPU_ID is one higher for it
* (target/i386/kvm/kvm.c, kvm_set_max_apic_id). Ids past 254 make none:
* AVIC without x2AVIC inhibits itself for the whole VM at such an id.
*/
#define REIMS_GRAPHICS_KVM_HELPER_MAX_ID 254
#define REIMS_GRAPHICS_KVM_CPUID_MAX 4096
#define REIMS_GRAPHICS_KVM_MSR_IA32_TSC 0x10
/*
* The time a call runs before the thread is signalled, which ends it with
* its progress (-EINTR where it made none). A call retries a page with no
* reload of its vCPU's MMU for as long as the VM's TDP root is obsolete,
* until a signal (arch/x86/kvm/mmu/mmu.c:5063-5072, 4817-4843 in Linux
* 7.3.3), holding KVM's SRCU, which every slot change then waits for under
* the BQL. 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 it; 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). The next call frees the obsolete root
* (arch/x86/kvm/mmu.h:195-198). A slice takes 0.3-0.6 ms.
*/
#define REIMS_GRAPHICS_KVM_CALL_LIMIT_NS (20 * 1000 * 1000)
#ifndef sigev_notify_thread_id
#define sigev_notify_thread_id _sigev_un._tid
#endif
static struct {
unsigned long id; /* the helper's vCPU id */
struct kvm_cpuid2 *cpuid; /* vCPU 0's, for the helper */
int tsc_khz; /* vCPU 0's, or <= 0 where KVM did not say */
int fd; /* the helper's vCPU fd, -1 until made */
pthread_t thread; /* the populate thread */
timer_t timer; /* the populate thread's call limit */
Notifier tsc_put;
} reims_graphics_kvm_helper = { .fd = -1 };
/*
* Writes the helper's TSC as the host, to 0, which KVM always takes as
* synchronizing: the helper joins the TSC generation the VM's vCPUs are
* in, with no change to theirs (arch/x86/kvm/msrs.c:1630-1632,
* arch/x86/kvm/x86.c:1314-1319, 1351-1361), and a write to a helper
* already in it changes nothing (x86.c:1287-1288).
*/
static int reims_graphics_kvm_helper_tsc_zero(int fd)
{
struct {
struct kvm_msrs info;
struct kvm_msr_entry entries[1];
} msrs = {
.info.nmsrs = 1,
.entries[0].index = REIMS_GRAPHICS_KVM_MSR_IA32_TSC,
};
return ioctl(fd, KVM_SET_MSRS, &msrs) == 1 ? 0 : -errno;
}
/*
* After each put of a guest vCPU's TSC at a reset (a guest reboot writes
* TSC 1 on each vCPU, target/i386/cpu.c:9486-9496) or of its full state: on
* that vCPU's thread. KVM's master clock needs every vCPU, the helper
* included, in one TSC generation (x86.c:1088-1101); the first vCPU's
* write starts a new one, which the others join, and a helper nobody
* wrote would be left out, so the master clock would go off for the guest's
* kvmclock until the next reset (x86.c:1587-1594). The helper joins after
* each put, so it is in the generation the last put leaves.
*/
static void reims_graphics_kvm_tsc_put(Notifier *n, void *data)
{
CPUState *cpu = data;
int fd = qatomic_read(&reims_graphics_kvm_helper.fd);
int ret;
if (fd < 0) {
return;
}
ret = reims_graphics_kvm_helper_tsc_zero(fd);
trace_reims_graphics_prefault_tsc_rejoin(cpu->cpu_index, ret);
if (ret < 0) {
warn_report_once("reims-graphics-pci: the pre-fault helper's TSC "
"write failed (%s): KVM's master clock may stay "
"off", strerror(-ret));
}
}
/* On the populate thread: makes the helper and the call limit's timer. */
static bool reims_graphics_kvm_prefault_start(Error **errp)
{
struct sigevent sev = {
.sigev_notify = SIGEV_THREAD_ID,
.sigev_signo = SIG_IPI,
};
sigset_t set;
int fd, khz, ret;
/*
* The timer and a pause's kick signal this thread with SIG_IPI, whose
* handler (kvm_ipi_signal, accel/kvm/kvm-all.c) does nothing on a
* thread that is no vCPU's; the signal only ends the call in flight
* (virt/kvm/kvm_main.c:4411-4415, arch/x86/kvm/mmu/mmu.c:5063-5065).
*/
sigemptyset(&set);
sigaddset(&set, SIG_IPI);
pthread_sigmask(SIG_UNBLOCK, &set, NULL);
reims_graphics_kvm_helper.thread = pthread_self();
sev.sigev_notify_thread_id = qemu_get_thread_id();
if (timer_create(CLOCK_MONOTONIC, &sev,
&reims_graphics_kvm_helper.timer) < 0) {
error_setg_errno(errp, errno, "reims-graphics-pci: no pre-fault of "
"the pool: timer_create");
return false;
}
fd = kvm_vm_ioctl(kvm_state, KVM_CREATE_VCPU,
(void *)reims_graphics_kvm_helper.id);
if (fd < 0) {
error_setg_errno(errp, -fd, "reims-graphics-pci: no pre-fault of the "
"pool: KVM_CREATE_VCPU %lu",
reims_graphics_kvm_helper.id);
return false;
}
/*
* The helper's TSC frequency is the guest's vCPUs', as KVM's TSC
* generations match only at one frequency; then it joins theirs, and
* from here on rejoins it after each of their puts, whatever comes
* of the rest: the helper is in the VM for good.
*/
khz = reims_graphics_kvm_helper.tsc_khz;
if (khz > 0 && ioctl(fd, KVM_GET_TSC_KHZ) != khz &&
ioctl(fd, KVM_SET_TSC_KHZ, khz) < 0) {
error_setg_errno(errp, errno, "reims-graphics-pci: no pre-fault of "
"the pool: KVM_SET_TSC_KHZ %d on its vCPU", khz);
return false;
}
ret = reims_graphics_kvm_helper_tsc_zero(fd);
if (ret < 0) {
error_setg_errno(errp, -ret, "reims-graphics-pci: no pre-fault of "
"the pool: the TSC write on its vCPU");
return false;
}
qatomic_set(&reims_graphics_kvm_helper.fd, fd);
if (ioctl(fd, KVM_SET_CPUID2, reims_graphics_kvm_helper.cpuid) < 0) {
error_setg_errno(errp, errno, "reims-graphics-pci: no pre-fault of "
"the pool: KVM_SET_CPUID2 on its vCPU");
return false;
}
trace_reims_graphics_prefault_helper(reims_graphics_kvm_helper.id,
reims_graphics_kvm_helper.cpuid->nent,
khz);
return true;
}
static int64_t reims_graphics_kvm_prefault_populate(hwaddr gpa, uint64_t size,
bool *cut)
{
struct kvm_pre_fault_memory range = { .gpa = gpa, .size = size };
struct itimerspec limit = {
.it_value.tv_nsec = REIMS_GRAPHICS_KVM_CALL_LIMIT_NS,
};
struct itimerspec off = { 0 }, left;
int ret, err;
timer_settime(reims_graphics_kvm_helper.timer, 0, &limit, NULL);
ret = ioctl(reims_graphics_kvm_helper.fd, KVM_PRE_FAULT_MEMORY, &range);
err = errno;
timer_settime(reims_graphics_kvm_helper.timer, 0, &off, &left);
/* A one-shot timer with nothing left ran out: it signalled. */
*cut = left.it_value.tv_sec == 0 && left.it_value.tv_nsec == 0;
if (ret == 0) {
/* Progress: KVM gives the range left back. */
return range.size < size ? size - range.size : -EIO;
}
return -err;
}
static void reims_graphics_kvm_prefault_kick(void)
{
pthread_kill(reims_graphics_kvm_helper.thread, SIG_IPI);
}
static const ReimsGraphicsPrefaultOps reims_graphics_kvm_prefault = {
.start = reims_graphics_kvm_prefault_start,
.populate = reims_graphics_kvm_prefault_populate,
.kick = reims_graphics_kvm_prefault_kick,
};
/* vCPU 0's CPUID, as KVM holds it: NULL where it did not answer. */
static struct kvm_cpuid2 *reims_graphics_kvm_cpuid(CPUState *cpu)
{
struct kvm_cpuid2 *cpuid;
unsigned nent;
for (nent = 128; nent <= REIMS_GRAPHICS_KVM_CPUID_MAX; nent *= 2) {
cpuid = g_malloc0(sizeof(*cpuid) +
nent * sizeof(struct kvm_cpuid_entry2));
cpuid->nent = nent;
if (ioctl(cpu->kvm_fd, KVM_GET_CPUID2, cpuid) == 0) {
return cpuid;
}
g_free(cpuid);
if (errno != E2BIG) {
break;
}
}
return NULL;
}
const ReimsGraphicsPrefaultOps *reims_graphics_kvm_prefault_ops(void)
{
MachineState *ms = MACHINE(qdev_get_machine());
MachineClass *mc = MACHINE_GET_CLASS(ms);
const CPUArchIdList *ids;
CPUState *cpu = first_cpu;
unsigned long id = 0;
int i;
if (!kvm_enabled() || !kvm_pre_fault_memory_supported) {
return NULL;
}
if (!mc->possible_cpu_arch_ids || !cpu || cpu->kvm_fd < 0) {
warn_report("reims-graphics-pci: no pre-fault of the pool: the "
"machine names no vCPUs");
return NULL;
}
ids = mc->possible_cpu_arch_ids(ms);
for (i = 0; i < ids->len; i++) {
id = MAX(id, ids->cpus[i].arch_id + 1);
}
if (id > REIMS_GRAPHICS_KVM_HELPER_MAX_ID) {
warn_report("reims-graphics-pci: no pre-fault of the pool: its "
"vCPU's id would be %lu, past %d", id,
REIMS_GRAPHICS_KVM_HELPER_MAX_ID);
return NULL;
}
reims_graphics_kvm_helper.id = id;
reims_graphics_kvm_helper.cpuid = reims_graphics_kvm_cpuid(cpu);
if (!reims_graphics_kvm_helper.cpuid) {
warn_report("reims-graphics-pci: no pre-fault of the pool: "
"KVM_GET_CPUID2 on vCPU 0: %s", strerror(errno));
return NULL;
}
reims_graphics_kvm_helper.tsc_khz = ioctl(cpu->kvm_fd, KVM_GET_TSC_KHZ);
reims_graphics_kvm_helper.tsc_put.notify = reims_graphics_kvm_tsc_put;
kvm_tsc_put_add_notifier(&reims_graphics_kvm_helper.tsc_put);
return &reims_graphics_kvm_prefault;
}
#else
const ReimsGraphicsPrefaultOps *reims_graphics_kvm_prefault_ops(void)
{
return NULL;
}
#endif
+32
View File
@@ -0,0 +1,32 @@
/*
* QEMU reims-graphics device: its calls into KVM
*
* SPDX-License-Identifier: GPL-2.0-or-later
*
* reims-graphics-pci.c is built once for every target (system_ss), and a
* target without KVM links neither kvm_check_extension nor kvm_vm_ioctl. The
* device's calls into KVM are therefore in reims-graphics-pci-kvm.c, which
* only the targets with KVM link; the others link
* reims-graphics-pci-kvm-stub.c (hw/display/meson.build). Linux hosts alone
* build either.
*/
#ifndef HW_DISPLAY_REIMS_GRAPHICS_PCI_KVM_H
#define HW_DISPLAY_REIMS_GRAPHICS_PCI_KVM_H
#include "reims-graphics-pci-prefault.h"
/*
* Turns KVM's KVM_X86_QUIRK_SLOT_ZAP_ALL off for the VM, where KVM runs it
* and has the quirk. False only where KVM refused to turn it off.
*/
bool reims_graphics_kvm_disable_slot_zap_all(void);
/*
* The pool's populate on KVM (reims-graphics-pci-prefault.h), under the
* BQL at realize, once the VM's vCPUs are made: NULL where KVM has no
* KVM_CAP_PRE_FAULT_MEMORY or the host is not x86-64.
*/
const ReimsGraphicsPrefaultOps *reims_graphics_kvm_prefault_ops(void);
#endif
+356
View File
@@ -0,0 +1,356 @@
/*
* QEMU reims-graphics device: the pool's pre-fault
*
* SPDX-License-Identifier: GPL-2.0-or-later
*
* reims-graphics-pci-prefault.h says what it does. One thread a VM, for
* every device of the VM's: the populate's calls run on the thread, and
* the queue, under its lock, holds the pieces not yet started, sorted by
* address.
*/
#include "qemu/osdep.h"
#include "qapi/error.h"
#include "qemu/error-report.h"
#include "qemu/lockable.h"
#include "qemu/thread.h"
#include "qemu/timer.h"
#include "system/kvm.h"
#include "system/whpx.h"
#include "reims-graphics-pci-prefault.h"
#ifdef CONFIG_LINUX
#include "reims-graphics-pci-kvm.h"
#endif
#include "trace.h"
/* Calls in a row cut with nothing done, after which a piece is let go. */
#define REIMS_GRAPHICS_PREFAULT_CUTS 3
typedef struct ReimsGraphicsPrefaultRange {
hwaddr gpa;
uint64_t size;
int64_t queued; /* get_clock() at the add */
} ReimsGraphicsPrefaultRange;
struct ReimsGraphicsPrefault {
const ReimsGraphicsPrefaultOps *ops;
QemuThread thread;
QemuSemaphore started;
bool ok; /* the start's answer, once started is posted */
QemuMutex lock;
QemuCond cond;
GArray *queue; /* lock: ReimsGraphicsPrefaultRange, sorted by gpa */
bool busy; /* lock: a piece is in flight, */
hwaddr cur_gpa; /* lock: at cur_gpa, */
uint64_t cur_size; /* lock: of cur_size bytes, */
bool cur_stopped; /* lock: and its removal stopped it */
unsigned paused; /* lock: the pauses on, which no call starts under */
bool in_call; /* lock: the thread is in a call, */
bool kicked; /* lock: which a pause has signalled */
QemuCond idle; /* broadcast when a call a pause waits for ends */
/* lock: the totals */
uint64_t regions, bytes, slices, cuts, kicks, errors, stopped, dropped;
int64_t cpu_ns;
};
static bool reims_graphics_prefault_overlap(hwaddr a, uint64_t a_size,
hwaddr b, uint64_t b_size)
{
return a < b + b_size && b < a + a_size;
}
/* The calling thread's CPU time, in ns: 0 where the host does not say. */
static int64_t reims_graphics_prefault_cpu_ns(void)
{
#ifdef CLOCK_THREAD_CPUTIME_ID
struct timespec ts;
if (clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts) == 0) {
return ts.tv_sec * NANOSECONDS_PER_SECOND + ts.tv_nsec;
}
#endif
return 0;
}
/*
* Populates @r, lowest address first, a slice a call, until it is done, its
* removal stops it, or a call fails: a failed call leaves the rest of the
* piece to the guest's first touch, as without the populate.
*/
static void reims_graphics_prefault_region(ReimsGraphicsPrefault *pf,
const ReimsGraphicsPrefaultRange *r)
{
hwaddr gpa = r->gpa, end = r->gpa + r->size, next;
int64_t t0 = get_clock(), c0 = reims_graphics_prefault_cpu_ns();
int64_t s0, slice_ns, slice_max = 0, wall, cpu;
unsigned slices = 0, cuts = 0, kicks = 0, cut_run = 0;
int64_t done;
bool cut, kicked, stopped = false;
int err = 0;
while (gpa < end) {
WITH_QEMU_LOCK_GUARD(&pf->lock) {
while (pf->paused) {
qemu_cond_wait(&pf->cond, &pf->lock);
}
stopped = pf->cur_stopped;
pf->in_call = !stopped;
pf->kicked = false;
}
if (stopped) {
break;
}
next = MIN(end, QEMU_ALIGN_DOWN(gpa, REIMS_GRAPHICS_PREFAULT_SLICE) +
REIMS_GRAPHICS_PREFAULT_SLICE);
cut = false;
s0 = get_clock();
done = pf->ops->populate(gpa, next - gpa, &cut);
slice_ns = get_clock() - s0;
WITH_QEMU_LOCK_GUARD(&pf->lock) {
pf->in_call = false;
kicked = pf->kicked;
if (pf->paused) {
qemu_cond_broadcast(&pf->idle);
}
}
slice_max = MAX(slice_max, slice_ns);
slices++;
cuts += cut;
kicks += kicked;
if (done > 0) {
gpa += done;
cut_run = 0;
} else if (done == -EINTR && kicked) {
/* A pause ended it with nothing done: it starts afresh after. */
} else if (done == -EINTR &&
++cut_run < REIMS_GRAPHICS_PREFAULT_CUTS) {
/* Cut with nothing done: the next call starts afresh. */
} else {
err = -done;
break;
}
}
wall = get_clock() - t0;
cpu = reims_graphics_prefault_cpu_ns() - c0;
trace_reims_graphics_prefault_region(r->gpa, r->size, gpa - r->gpa,
slices, cuts, kicks, err, stopped);
trace_reims_graphics_prefault_region_time(r->gpa, t0 - r->queued, wall,
cpu, slice_max);
WITH_QEMU_LOCK_GUARD(&pf->lock) {
pf->regions++;
pf->bytes += gpa - r->gpa;
pf->slices += slices;
pf->cuts += cuts;
pf->kicks += kicks;
pf->errors += err != 0;
pf->stopped += stopped;
pf->cpu_ns += cpu;
}
}
/*
* The populate on WHPX: one partition call a slice, which needs no vCPU.
* Measured 11-18 on the Windows mini (UHD 630, Windows 10.0.26300), with
* a 64 MiB map and unmap of another range looped beside a 548 MiB populate:
* the populate in one call took 54 ms and the map beside it waited 55 ms
* (p50), where in 2 MiB slices it took 218 ms and a map waited 1.25 / 1.64
* / 3.94 ms (p50 / p90 / max), against 1.60 / 1.76 / 2.25 ms with no
* populate.
*/
static bool reims_graphics_whpx_prefault_start(Error **errp)
{
if (!whpx_can_populate()) {
error_setg(errp, "reims-graphics-pci: no pre-fault of the pool: "
"the hypervisor has no WHvAdviseGpaRange");
return false;
}
return true;
}
static int64_t reims_graphics_whpx_prefault_populate(hwaddr gpa,
uint64_t size, bool *cut)
{
int ret = whpx_populate(gpa, size);
return ret < 0 ? ret : size;
}
static const ReimsGraphicsPrefaultOps reims_graphics_whpx_prefault = {
.start = reims_graphics_whpx_prefault_start,
.populate = reims_graphics_whpx_prefault_populate,
};
static void *reims_graphics_prefault_thread(void *opaque)
{
ReimsGraphicsPrefault *pf = opaque;
ReimsGraphicsPrefaultRange r;
Error *err = NULL;
pf->ok = pf->ops->start(&err);
if (!pf->ok) {
warn_report_err(err);
}
qemu_sem_post(&pf->started);
if (!pf->ok) {
return NULL;
}
for (;;) {
WITH_QEMU_LOCK_GUARD(&pf->lock) {
while (pf->queue->len == 0) {
qemu_cond_wait(&pf->cond, &pf->lock);
}
r = g_array_index(pf->queue, ReimsGraphicsPrefaultRange, 0);
g_array_remove_index(pf->queue, 0);
pf->busy = true;
pf->cur_gpa = r.gpa;
pf->cur_size = r.size;
pf->cur_stopped = false;
}
reims_graphics_prefault_region(pf, &r);
WITH_QEMU_LOCK_GUARD(&pf->lock) {
pf->busy = false;
}
}
return NULL;
}
ReimsGraphicsPrefault *reims_graphics_prefault_get(void)
{
static ReimsGraphicsPrefault *made;
static bool tried;
const ReimsGraphicsPrefaultOps *ops = NULL;
ReimsGraphicsPrefault *pf;
if (tried) {
return made;
}
tried = true;
#ifdef CONFIG_LINUX
if (kvm_enabled()) {
ops = reims_graphics_kvm_prefault_ops();
}
#endif
if (whpx_enabled()) {
ops = &reims_graphics_whpx_prefault;
}
if (!ops) {
return NULL;
}
pf = g_new0(ReimsGraphicsPrefault, 1);
pf->ops = ops;
qemu_sem_init(&pf->started, 0);
qemu_mutex_init(&pf->lock);
qemu_cond_init(&pf->cond);
qemu_cond_init(&pf->idle);
pf->queue = g_array_new(false, false, sizeof(ReimsGraphicsPrefaultRange));
/* It lives to the process's exit, waiting for pieces. */
qemu_thread_create(&pf->thread, "rgfx-prefault",
reims_graphics_prefault_thread, pf,
QEMU_THREAD_DETACHED);
qemu_sem_wait(&pf->started);
if (!pf->ok) {
g_array_free(pf->queue, true);
qemu_cond_destroy(&pf->idle);
qemu_cond_destroy(&pf->cond);
qemu_mutex_destroy(&pf->lock);
qemu_sem_destroy(&pf->started);
g_free(pf);
return NULL;
}
made = pf;
return made;
}
void reims_graphics_prefault_add(ReimsGraphicsPrefault *pf, hwaddr gpa,
uint64_t size)
{
ReimsGraphicsPrefaultRange r = {
.gpa = gpa, .size = size, .queued = get_clock(),
};
guint i;
WITH_QEMU_LOCK_GUARD(&pf->lock) {
for (i = 0; i < pf->queue->len; i++) {
if (g_array_index(pf->queue, ReimsGraphicsPrefaultRange,
i).gpa > gpa) {
break;
}
}
g_array_insert_val(pf->queue, i, r);
qemu_cond_broadcast(&pf->cond);
}
}
void reims_graphics_prefault_stop(ReimsGraphicsPrefault *pf, hwaddr gpa,
uint64_t size)
{
ReimsGraphicsPrefaultRange *r;
guint i = 0;
WITH_QEMU_LOCK_GUARD(&pf->lock) {
while (i < pf->queue->len) {
r = &g_array_index(pf->queue, ReimsGraphicsPrefaultRange, i);
if (reims_graphics_prefault_overlap(r->gpa, r->size, gpa, size)) {
trace_reims_graphics_prefault_dropped(r->gpa, r->size);
pf->dropped++;
g_array_remove_index(pf->queue, i);
} else {
i++;
}
}
if (pf->busy &&
reims_graphics_prefault_overlap(pf->cur_gpa, pf->cur_size,
gpa, size)) {
pf->cur_stopped = true;
}
}
}
void reims_graphics_prefault_pause(ReimsGraphicsPrefault *pf)
{
int64_t t0 = get_clock();
unsigned kicks = 0;
bool in_call;
if (!pf->ops->kick) {
return;
}
WITH_QEMU_LOCK_GUARD(&pf->lock) {
pf->paused++;
in_call = pf->in_call;
while (pf->in_call) {
/*
* A signal that lands before the call is in the kernel ends
* nothing: each millisecond the call goes on, it is sent again.
*/
pf->kicked = true;
pf->ops->kick();
kicks++;
qemu_cond_timedwait(&pf->idle, &pf->lock, 1);
}
}
trace_reims_graphics_prefault_pause(in_call, kicks, get_clock() - t0);
}
void reims_graphics_prefault_resume(ReimsGraphicsPrefault *pf)
{
if (!pf->ops->kick) {
return;
}
WITH_QEMU_LOCK_GUARD(&pf->lock) {
assert(pf->paused > 0);
if (--pf->paused == 0) {
qemu_cond_broadcast(&pf->cond);
}
}
}
void reims_graphics_prefault_report(ReimsGraphicsPrefault *pf)
{
WITH_QEMU_LOCK_GUARD(&pf->lock) {
trace_reims_graphics_prefault_totals(pf->regions, pf->bytes,
pf->slices, pf->cuts, pf->kicks,
pf->errors, pf->stopped,
pf->dropped, pf->cpu_ns);
}
}
+95
View File
@@ -0,0 +1,95 @@
/*
* QEMU reims-graphics device: the pool's pre-fault
*
* SPDX-License-Identifier: GPL-2.0-or-later
*
* A pool piece's first touch by the guest takes one second-level fault a
* 4 KiB page: 140,289 of them for a 548 MiB piece, about 180-260 ms on KVM
* and 1.3 s on WHPX. Once the piece is in the guest and its add answered,
* one thread of the VM's fills the second-level tables for it ahead of the
* guest's touch, so the guest's first touch takes no fault: the populate.
* The answer never waits for it.
*
* The thread takes the pieces lowest address first, each in 2 MiB slices,
* one call a slice, and stops a piece between slices at its removal. Each
* call holds what a slot change waits for (KVM's SRCU, WHPX's partition
* map), so a slice bounds that wait. The accelerator's part, the call, is a
* ReimsGraphicsPrefaultOps: KVM's KVM_PRE_FAULT_MEMORY on a vCPU of the
* thread's own that never runs (reims-graphics-pci-kvm.c), or WHPX's
* WHvAdviseGpaRange populate (whpx_populate).
*
* On KVM a pool piece's add changes a slot under the BQL, and its removal
* deletes its slot on the library's thread first (kvm_unmap_before_del),
* neither of which must wait for a call: each pauses the populate first,
* which signals the call in flight to end it at once, and resumes it once
* its slot change is done. On WHPX the device maps and unmaps its pieces
* outside the BQL (whpx_map_ahead, whpx_unmap_before_del), and a map or
* unmap under the BQL waits for at most the slice in flight: the populate
* takes no pause there.
*/
#ifndef HW_DISPLAY_REIMS_GRAPHICS_PCI_PREFAULT_H
#define HW_DISPLAY_REIMS_GRAPHICS_PCI_PREFAULT_H
#include "exec/hwaddr.h"
#include "qemu/units.h"
/* The most a call populates: what a slot change waits for, at most. */
#define REIMS_GRAPHICS_PREFAULT_SLICE (2 * MiB)
typedef struct ReimsGraphicsPrefaultOps {
/*
* On the populate thread, once, before any call: false, with @errp
* set, where it cannot populate.
*/
bool (*start)(Error **errp);
/*
* On the populate thread: populates [@gpa, @gpa + @size), at most one
* slice. The bytes done from @gpa (> 0), or a negative errno where
* none were. *@cut is set where the call ran into its time limit.
*/
int64_t (*populate)(hwaddr gpa, uint64_t size, bool *cut);
/*
* Any thread: signals the populate thread, so that the call it is in
* ends with what it has done (-EINTR where it did nothing). NULL where
* a slot change under the BQL waits for at most the slice in flight: a
* pause and its resume then do nothing.
*/
void (*kick)(void);
} ReimsGraphicsPrefaultOps;
typedef struct ReimsGraphicsPrefault ReimsGraphicsPrefault;
/*
* The VM's populate thread, under the BQL: made at the first call, which
* waits for its start. NULL where the accelerator has no populate or its
* start failed (a warning says why).
*/
ReimsGraphicsPrefault *reims_graphics_prefault_get(void);
/*
* Queues [@gpa, @gpa + @size) for the populate, once the guest's address
* space has it and its add was answered. Any thread.
*/
void reims_graphics_prefault_add(ReimsGraphicsPrefault *pf, hwaddr gpa,
uint64_t size);
/*
* Drops what is queued of [@gpa, @gpa + @size), and stops the piece in
* flight there before its next slice. Any thread; it waits for no call.
*/
void reims_graphics_prefault_stop(ReimsGraphicsPrefault *pf, hwaddr gpa,
uint64_t size);
/*
* Any thread, before a slot change: no call starts until the matching
* resume, and the call in flight is ended; returns once none is. Pauses
* nest.
*/
void reims_graphics_prefault_pause(ReimsGraphicsPrefault *pf);
void reims_graphics_prefault_resume(ReimsGraphicsPrefault *pf);
/* Traces the thread's totals so far. */
void reims_graphics_prefault_report(ReimsGraphicsPrefault *pf);
#endif
File diff suppressed because it is too large. Load diff
+15 -28
View File
@@ -198,32 +198,19 @@ dm163_leds(int led, uint32_t value) "led %d: 0x%x"
dm163_channels(int channel, uint8_t value) "channel %d: 0x%x"
dm163_refresh_rate(uint32_t rr) "refresh rate %d"
# apple-gfx.m
apple_gfx_read(uint64_t offset, uint64_t res) "offset=0x%"PRIx64" res=0x%"PRIx64
apple_gfx_write(uint64_t offset, uint64_t val) "offset=0x%"PRIx64" val=0x%"PRIx64
apple_gfx_create_task(uint32_t vm_size, void *va) "vm_size=0x%x base_addr=%p"
apple_gfx_destroy_task(void *task, unsigned int num_mapped_regions) "task=%p, task->mapped_regions->len=%u"
apple_gfx_map_memory(void *task, uint32_t range_count, uint64_t virtual_offset, uint32_t read_only) "task=%p range_count=0x%x virtual_offset=0x%"PRIx64" read_only=%d"
apple_gfx_map_memory_range(uint32_t i, uint64_t phys_addr, uint64_t phys_len) "[%d] phys_addr=0x%"PRIx64" phys_len=0x%"PRIx64
apple_gfx_remap(uint64_t retval, void *source_ptr, uint64_t target) "retval=%"PRId64" source=%p target=0x%"PRIx64
apple_gfx_unmap_memory(void *task, uint64_t virtual_offset, uint64_t length) "task=%p virtual_offset=0x%"PRIx64" length=0x%"PRIx64
apple_gfx_read_memory(uint64_t phys_address, uint64_t length, void *dst) "phys_addr=0x%"PRIx64" length=0x%"PRIx64" dest=%p"
apple_gfx_raise_irq(uint32_t vector) "vector=0x%x"
apple_gfx_new_frame(void) ""
apple_gfx_mode_change(uint64_t x, uint64_t y) "x=%"PRId64" y=%"PRId64
apple_gfx_cursor_set(uint32_t bpp, uint64_t width, uint64_t height) "bpp=%d width=%"PRId64" height=0x%"PRId64
apple_gfx_cursor_show(uint32_t show) "show=%d"
apple_gfx_cursor_move(void) ""
apple_gfx_common_init(const char *device_name, size_t mmio_size) "device: %s; MMIO size: %zu bytes"
apple_gfx_common_realize_modes_property(uint32_t num_modes) "using %u modes supplied by 'display-modes' device property"
apple_gfx_display_mode(uint32_t mode_idx, uint16_t width_px, uint16_t height_px) "mode %2"PRIu32": %4"PRIu16"x%4"PRIu16
# apple-gfx-mmio.m
apple_gfx_mmio_iosfc_read(uint64_t offset, uint64_t res) "offset=0x%"PRIx64" res=0x%"PRIx64
apple_gfx_mmio_iosfc_write(uint64_t offset, uint64_t val) "offset=0x%"PRIx64" val=0x%"PRIx64
apple_gfx_iosfc_map_memory(uint64_t phys, uint64_t len, uint32_t ro, void *va, void *e, void *f, void* va_result) "phys=0x%"PRIx64" len=0x%"PRIx64" ro=%d va=%p e=%p f=%p -> *va=%p"
apple_gfx_iosfc_map_memory_new_region(size_t i, void *region, uint64_t start, uint64_t end) "index=%zu, region=%p, 0x%"PRIx64"-0x%"PRIx64
apple_gfx_iosfc_unmap_memory(void *a, void *b, void *c, void *d, void *e, void *f) "a=%p b=%p c=%p d=%p e=%p f=%p"
apple_gfx_iosfc_unmap_memory_region(void* mem, void *region) "unmapping @ %p from memory region %p"
apple_gfx_iosfc_raise_irq(uint32_t vector) "vector=0x%x"
# reims-graphics-pci.c
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-pci-prefault.c, reims-graphics-pci-kvm.c
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"
reims_graphics_prefault_region_time(uint64_t gpa, int64_t queued_ns, int64_t wall_ns, int64_t cpu_ns, int64_t slice_max_ns) "piece at 0x%"PRIx64": queued %"PRId64" ns, wall %"PRId64" ns, thread CPU %"PRId64" ns, longest slice %"PRId64" ns"
reims_graphics_prefault_dropped(uint64_t gpa, uint64_t size) "piece at 0x%"PRIx64", 0x%"PRIx64" bytes, removed before its populate started"
reims_graphics_prefault_pause(bool in_call, unsigned kicks, int64_t wait_ns) "paused for a slot change: in a call %d, %u signals, %"PRId64" ns"
reims_graphics_prefault_totals(uint64_t regions, uint64_t bytes, uint64_t slices, uint64_t cuts, uint64_t kicks, uint64_t errors, uint64_t stopped, uint64_t dropped, int64_t cpu_ns) "%"PRIu64" pieces, 0x%"PRIx64" bytes populated in %"PRIu64" slices, %"PRIu64" cut by the timer, %"PRIu64" by a pause; %"PRIu64" ended by an error, %"PRIu64" stopped, %"PRIu64" dropped; thread CPU %"PRId64" ns"
+6
View File
@@ -499,6 +499,12 @@ static void pl061_hold_reset(Object *obj, ResetType type)
qemu_set_irq(s->out[i], level);
}
s->old_out_data = pullups;
/*
* Lower the interrupt line, as the enter phase cleared what raises it:
* a line keeps its level across a reset otherwise, and an in-kernel GIC
* (HVF's, KVM's) raises its interrupt again once the GIC is reset.
*/
qemu_set_irq(s->irq, (s->istate & s->im) != 0);
}
static void pl061_set_irq(void * opaque, int irq, int level)
+5
View File
@@ -57,6 +57,7 @@ struct ARMGICv2mState {
uint32_t base_spi;
uint32_t num_spi;
uint32_t macos_compat;
};
static void gicv2m_set_irq(void *opaque, int irq)
@@ -81,6 +82,9 @@ static uint64_t gicv2m_read(void *opaque, hwaddr offset,
case V2M_MSI_TYPER:
val = (s->base_spi + 32) << 16;
val |= s->num_spi;
if (s->macos_compat) {
val |= BIT(31);
}
return val;
case V2M_MSI_IIDR:
/* We don't have any valid implementor so we leave that field as zero
@@ -173,6 +177,7 @@ static void gicv2m_init(Object *obj)
static const Property gicv2m_properties[] = {
DEFINE_PROP_UINT32("base-spi", ARMGICv2mState, base_spi, 0),
DEFINE_PROP_UINT32("num-spi", ARMGICv2mState, num_spi, 64),
DEFINE_PROP_UINT32("macos-compat", ARMGICv2mState, macos_compat, 0),
};
static void gicv2m_class_init(ObjectClass *klass, const void *data)
+21 -3
View File
@@ -90,8 +90,13 @@ static void hvf_dist_get_priority(GICv3State *s,
uint64_t reg;
uint32_t *field;
int irq;
field = (uint32_t *)(bmp);
/*
* The loop starts at the first SPI: skip the internal IRQs' fields in
* bmp and their registers, as for_each_dist_irq_reg() does.
*/
field = (uint32_t *)(bmp + GIC_INTERNAL);
offset += (GIC_INTERNAL * 8) / 8;
for_each_dist_irq_reg(irq, s->num_irq, 8) {
hv_gic_get_distributor_reg(offset, &reg);
*field = reg;
@@ -106,8 +111,10 @@ static void hvf_dist_put_priority(GICv3State *s,
{
uint32_t reg, *field;
int irq;
field = (uint32_t *)(bmp);
/* As in hvf_dist_get_priority(): the loop starts at the first SPI. */
field = (uint32_t *)(bmp + GIC_INTERNAL);
offset += (GIC_INTERNAL * 8) / 8;
for_each_dist_irq_reg(irq, s->num_irq, 8) {
reg = *field;
hv_gic_set_distributor_reg(offset, reg);
@@ -123,6 +130,8 @@ static void hvf_dist_get_edge_trigger(GICv3State *s,
uint64_t reg;
int irq;
/* The loop starts at the first SPI: skip the internal IRQs' registers. */
offset += (GIC_INTERNAL * 2) / 8;
for_each_dist_irq_reg(irq, s->num_irq, 2) {
hv_gic_get_distributor_reg(offset, &reg);
reg = half_unshuffle32(reg >> 1);
@@ -141,6 +150,8 @@ static void hvf_dist_put_edge_trigger(GICv3State *s,
uint32_t reg;
int irq;
/* The loop starts at the first SPI: skip the internal IRQs' registers. */
offset += (GIC_INTERNAL * 2) / 8;
for_each_dist_irq_reg(irq, s->num_irq, 2) {
reg = *gic_bmp_ptr32(bmp, irq);
if (irq % 32 != 0) {
@@ -161,6 +172,8 @@ static void hvf_dist_getbmp(GICv3State *s, hv_gic_distributor_reg_t offset,
uint64_t reg;
int irq;
/* The loop starts at the first SPI: skip the internal IRQs' register. */
offset += (GIC_INTERNAL * 1) / 8;
for_each_dist_irq_reg(irq, s->num_irq, 1) {
hv_gic_get_distributor_reg(offset, &reg);
*gic_bmp_ptr32(bmp, irq) = reg;
@@ -174,6 +187,11 @@ static void hvf_dist_putbmp(GICv3State *s, hv_gic_distributor_reg_t offset,
uint32_t reg;
int irq;
/* The loop starts at the first SPI: skip the internal IRQs' register. */
offset += (GIC_INTERNAL * 1) / 8;
if (clroffset != 0) {
clroffset += (GIC_INTERNAL * 1) / 8;
}
for_each_dist_irq_reg(irq, s->num_irq, 1) {
/*
* If this bitmap is a set/clear register pair, first write to the
@@ -181,7 +199,7 @@ static void hvf_dist_putbmp(GICv3State *s, hv_gic_distributor_reg_t offset,
* the 1 bits.
*/
if (clroffset != 0) {
reg = 0;
reg = ~0;
hv_gic_set_distributor_reg(clroffset, reg);
clroffset += 4;
}
+53 -1
View File
@@ -37,6 +37,7 @@
#include "qemu/error-report.h"
#include "qemu/module.h"
#include "qemu/timer.h"
#include "migration/vmstate.h"
#include "qom/object.h"
#include "hw/acpi/acpi_aml_interface.h"
@@ -108,7 +109,7 @@ struct AppleSMCState {
uint8_t status;
uint8_t status_1e;
uint8_t last_ret;
char key[4];
uint8_t key[4];
uint8_t read_pos;
uint8_t data_len;
uint8_t data_pos;
@@ -126,6 +127,7 @@ static void applesmc_io_cmd_write(void *opaque, hwaddr addr, uint64_t val,
smc_debug("CMD received: 0x%02x\n", (uint8_t)val);
switch (val) {
case APPLESMC_READ_CMD:
case APPLESMC_GET_KEY_BY_INDEX_CMD:
/* did last command run through OK? */
if (status == APPLESMC_ST_CMD_DONE || status == APPLESMC_ST_NEW_CMD) {
s->cmd = val;
@@ -162,6 +164,7 @@ static void applesmc_io_data_write(void *opaque, hwaddr addr, uint64_t val,
{
AppleSMCState *s = opaque;
const struct AppleSMCData *d;
uint32_t index;
smc_debug("DATA received: 0x%02x\n", (uint8_t)val);
switch (s->cmd) {
@@ -189,6 +192,34 @@ static void applesmc_io_data_write(void *opaque, hwaddr addr, uint64_t val,
}
s->read_pos++;
break;
case APPLESMC_GET_KEY_BY_INDEX_CMD:
/* a big-endian index of 4 bytes, with no length byte after it */
if ((s->status & 0x0f) == APPLESMC_ST_CMD_DONE || s->read_pos == 4) {
break;
}
s->key[s->read_pos++] = val;
s->status = APPLESMC_ST_ACK;
if (s->read_pos < 4) {
break;
}
/* the keys in the list's order but OSK0 and OSK1, found by name only */
index = ldl_be_p(s->key);
QLIST_FOREACH(d, &s->data_def, node) {
if (memcmp(d->key, "OSK", 3) && index-- == 0) {
break;
}
}
if (d != NULL) {
memcpy(s->data, d->key, 4);
s->data_len = 4;
s->data_pos = 0;
s->status = APPLESMC_ST_ACK | APPLESMC_ST_DATA_READY;
s->status_1e = APPLESMC_ST_CMD_DONE;
} else {
s->status = APPLESMC_ST_CMD_DONE;
s->status_1e = APPLESMC_ST_1E_BAD_INDEX;
}
break;
default:
s->status = APPLESMC_ST_CMD_DONE;
s->status_1e = APPLESMC_ST_1E_STILL_BAD_CMD;
@@ -208,6 +239,7 @@ static uint64_t applesmc_io_data_read(void *opaque, hwaddr addr, unsigned size)
switch (s->cmd) {
case APPLESMC_READ_CMD:
case APPLESMC_GET_KEY_BY_INDEX_CMD:
if (!(s->status & APPLESMC_ST_DATA_READY)) {
break;
}
@@ -330,6 +362,7 @@ static void applesmc_isa_realize(DeviceState *dev, Error **errp)
}
QLIST_INIT(&s->data_def);
/* each goes at the head: GET_KEY_BY_INDEX lists MSSD, MSSP, NATJ, REV */
applesmc_add_key(s, "REV ", 6, "\x01\x13\x0f\x00\x00\x03");
applesmc_add_key(s, "OSK0", 32, s->osk);
applesmc_add_key(s, "OSK1", 32, s->osk + 32);
@@ -375,11 +408,30 @@ static void build_applesmc_aml(AcpiDevAmlIf *adev, Aml *scope)
aml_append(scope, dev);
}
static const VMStateDescription vmstate_applesmc = {
.name = "applesmc",
.version_id = 1,
.minimum_version_id = 1,
.fields = (const VMStateField[]) {
VMSTATE_UINT8(cmd, AppleSMCState),
VMSTATE_UINT8(status, AppleSMCState),
VMSTATE_UINT8(status_1e, AppleSMCState),
VMSTATE_UINT8(last_ret, AppleSMCState),
VMSTATE_UINT8_ARRAY(key, AppleSMCState, 4),
VMSTATE_UINT8(read_pos, AppleSMCState),
VMSTATE_UINT8(data_len, AppleSMCState),
VMSTATE_UINT8(data_pos, AppleSMCState),
VMSTATE_UINT8_ARRAY(data, AppleSMCState, 255),
VMSTATE_END_OF_LIST()
}
};
static void qdev_applesmc_class_init(ObjectClass *klass, const void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
AcpiDevAmlIfClass *adevc = ACPI_DEV_AML_IF_CLASS(klass);
dc->vmsd = &vmstate_applesmc;
dc->realize = applesmc_isa_realize;
dc->unrealize = applesmc_unrealize;
device_class_set_legacy_reset(dc, qdev_applesmc_isa_reset);
+22 -3
View File
@@ -109,7 +109,10 @@ static struct {
static struct {
const char *loc_pfx, *bank, *manufacturer, *serial, *asset, *part;
uint16_t speed;
} type17;
uint8_t memory_type;
} type17 = {
.memory_type = 0x07, /* RAM */
};
static QEnumLookup type41_kind_lookup = {
.array = (const char *const[]) {
@@ -469,6 +472,10 @@ static const QemuOptDesc qemu_smbios_type17_opts[] = {
.name = "speed",
.type = QEMU_OPT_NUMBER,
.help = "maximum capable speed",
},{
.name = "memory_type",
.type = QEMU_OPT_NUMBER,
.help = "memory type (7, RAM, by default; 26 is DDR4)",
},
{ /* end of list */ }
};
@@ -897,7 +904,7 @@ static void smbios_build_type_17_table(unsigned instance, uint64_t size)
snprintf(loc_str, sizeof(loc_str), "%s %d", type17.loc_pfx, instance);
SMBIOS_TABLE_SET_STR(17, device_locator_str, loc_str);
SMBIOS_TABLE_SET_STR(17, bank_locator_str, type17.bank);
t->memory_type = 0x07; /* RAM */
t->memory_type = type17.memory_type;
t->type_detail = cpu_to_le16(0x02); /* Other */
t->speed = cpu_to_le16(type17.speed);
SMBIOS_TABLE_SET_STR(17, manufacturer_str, type17.manufacturer);
@@ -1533,7 +1540,9 @@ void smbios_entry_add(QemuOpts *opts, Error **errp)
return;
}
return;
case 17:
case 17: {
uint64_t memory_type;
if (!qemu_opts_validate(opts, qemu_smbios_type17_opts, errp)) {
return;
}
@@ -1544,7 +1553,17 @@ void smbios_entry_add(QemuOpts *opts, Error **errp)
save_opt(&type17.asset, opts, "asset");
save_opt(&type17.part, opts, "part");
type17.speed = qemu_opt_get_number(opts, "speed", 0);
memory_type = qemu_opt_get_number(opts, "memory_type",
0x07 /* RAM */);
if (memory_type == 0 || memory_type > UINT8_MAX) {
error_setg(errp, "SMBIOS memory type %" PRIu64
" is out of range (1 to %d)", memory_type,
UINT8_MAX);
return;
}
type17.memory_type = memory_type;
return;
}
case 41: {
struct type41_instance *t41_i;
Error *local_err = NULL;
+5
View File
@@ -72,6 +72,11 @@ config USB_TABLET_WACOM
default y
depends on USB
config USB_TABLET_VMAPPLE
bool
default y
depends on USB
config USB_STORAGE_CORE
bool
depends on USB
+875
View File
@@ -0,0 +1,875 @@
/*
* USB tablet of Virtualization.framework's macOS guests
*
* The USB pointing device Virtualization.framework gives a macOS guest: an
* absolute pointer whose reports also carry smooth scrolling, that is, the
* scroll distance in pixels with the phases of the gesture it belongs to
* and of the momentum scrolling after it. macOS binds its own driver,
* AppleVirtualPlatformHIDEventDriver, to the device's vendor and product
* IDs, and scrolls as it does with a trackpad. Other guests see a HID
* mouse with an absolute pointer, a wheel and a horizontal wheel.
*
* Report 1, in the input direction:
* byte 0 buttons 1 to 3
* bytes 1-4 X and Y, 0 to 0x7fff
* bytes 5-6 wheel notches, above 0 up
* bytes 7-8 horizontal wheel notches (AC Pan), above 0 right
* bytes 9-12 vertical scroll in 1/65536 line, above 0 up
* bytes 13-16 horizontal scroll in 1/65536 line, above 0 left
* bytes 17-18 phases: bits 1:0 momentum (none, began, changed, ended),
* bits 4:2 gesture (none, may begin, began, changed, ended,
* cancelled)
* Feature report 2 is the wheels' resolution multiplier: set, the wheels
* count 1/120 notch. Feature report 3 bit 0 turns on the smooth scrolling
* fields; this device fills them in either way.
*
* macOS takes a report as a scroll when one of its scroll fields is new: a
* relative field that is not 0 or was not 0 in the report before, phases
* that differ from the report before, or any field of the first report it
* reads. It then ignores the report's pointer and buttons, and it moves the
* pointer or presses a button only for a field that differs from the report
* before. So a report of nothing goes first after a reset, scroll reports
* repeat the pointer and buttons of the report before them, and a report
* that returns the scroll fields to 0 comes between a scroll report and a
* pointer report.
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "qemu/osdep.h"
#include "qapi/error.h"
#include "ui/console.h"
#include "ui/input.h"
#include "hw/usb/usb.h"
#include "hw/usb/hid.h"
#include "hw/core/qdev-properties.h"
#include "migration/vmstate.h"
#include "qemu/bswap.h"
#include "qemu/module.h"
#include "desc.h"
#include "trace.h"
#include "qom/object.h"
#define VMAPPLE_TABLET_QUEUE_LENGTH 16
/* macOS scrolls 10 pixels a line of the smooth scrolling fields. */
#define VMAPPLE_TABLET_LINE_PIXELS 10
/*
* The pixels a wheel notch stands for: what a notch of a wheel scrolls, and
* the smooth scrolling that makes a notch in the wheel fields. macOS does
* not accelerate this device's scrolling; a notch of usb-tablet's wheel
* scrolls from 5 to 40 pixels there, by how fast the wheel turns.
*/
#define VMAPPLE_TABLET_NOTCH_PIXELS 20
/* Wheel units a notch makes when the resolution multiplier is set */
#define VMAPPLE_TABLET_MULTIPLIED_NOTCH 120
enum {
VMAPPLE_TABLET_REPORT_INPUT = 1,
VMAPPLE_TABLET_REPORT_MULTIPLIER = 2,
VMAPPLE_TABLET_REPORT_SMOOTH = 3,
};
#define VMAPPLE_TABLET_REPORT_SIZE 20
typedef struct VMAppleTabletReport {
uint8_t buttons;
uint16_t x;
uint16_t y;
int16_t wheel;
int16_t pan;
int32_t scroll_y;
int32_t scroll_x;
uint16_t phases;
} VMAppleTabletReport;
struct USBVMAppleTabletState {
USBDevice dev;
USBEndpoint *intr;
QemuInputHandlerState *hs;
bool input_active;
char *display;
uint32_t head;
/* Input since the last synchronization */
uint8_t buttons;
uint16_t x;
uint16_t y;
bool pointer_changed;
int32_t notches_y;
int32_t notches_x;
int64_t scroll_y;
int64_t scroll_x;
uint16_t phases;
bool scrolled;
/*
* Smooth scrolling not yet a whole wheel unit, in 1/256 pixel times the
* units a notch makes
*/
int32_t notch_rest_y;
int32_t notch_rest_x;
VMAppleTabletReport queue[VMAPPLE_TABLET_QUEUE_LENGTH];
uint32_t queue_head;
uint32_t queue_count;
/* The last report queued, which the guest reads last */
VMAppleTabletReport last;
/* Reports were dropped, the queue being full; see vmapple_tablet_push() */
bool overflow;
/* The phases of the last scroll report dropped that had some */
uint16_t owed_phases;
uint8_t idle;
uint8_t multiplier;
uint8_t smooth;
};
#define TYPE_USB_VMAPPLE_TABLET "usb-vmapple-tablet"
OBJECT_DECLARE_SIMPLE_TYPE(USBVMAppleTabletState, USB_VMAPPLE_TABLET)
enum {
STR_MANUFACTURER = 1,
STR_PRODUCT,
STR_SERIALNUMBER,
STR_CONFIG,
};
static const USBDescStrings desc_strings = {
[STR_MANUFACTURER] = "QEMU",
[STR_PRODUCT] = "QEMU vmapple USB Tablet",
[STR_SERIALNUMBER] = "1",
[STR_CONFIG] = "HID Tablet",
};
/* The descriptor Virtualization.framework's device has. */
static const uint8_t vmapple_tablet_report_descriptor[] = {
0x05, 0x01, /* Usage Page (Generic Desktop) */
0x09, 0x02, /* Usage (Mouse) */
0xa1, 0x01, /* Collection (Application) */
0x85, 0x01, /* Report ID (1) */
0x09, 0x01, /* Usage (Pointer) */
0xa1, 0x00, /* Collection (Physical) */
0x05, 0x09, /* Usage Page (Button) */
0x19, 0x01, /* Usage Minimum (1) */
0x29, 0x03, /* Usage Maximum (3) */
0x15, 0x00, /* Logical Minimum (0) */
0x25, 0x01, /* Logical Maximum (1) */
0x95, 0x03, /* Report Count (3) */
0x75, 0x01, /* Report Size (1) */
0x81, 0x02, /* Input (Data, Variable, Absolute) */
0x95, 0x01, /* Report Count (1) */
0x75, 0x05, /* Report Size (5) */
0x81, 0x01, /* Input (Constant) */
0x05, 0x01, /* Usage Page (Generic Desktop) */
0x09, 0x30, /* Usage (X) */
0x09, 0x31, /* Usage (Y) */
0x15, 0x00, /* Logical Minimum (0) */
0x26, 0xff, 0x7f, /* Logical Maximum (0x7fff) */
0x75, 0x10, /* Report Size (16) */
0x95, 0x02, /* Report Count (2) */
0x81, 0x02, /* Input (Data, Variable, Absolute) */
0xa1, 0x02, /* Collection (Logical) */
0x85, 0x02, /* Report ID (2) */
0x09, 0x48, /* Usage (Resolution Multiplier) */
0x95, 0x01, /* Report Count (1) */
0x75, 0x08, /* Report Size (8) */
0x15, 0x00, /* Logical Minimum (0) */
0x25, 0x01, /* Logical Maximum (1) */
0x35, 0x01, /* Physical Minimum (1) */
0x45, 0x78, /* Physical Maximum (120) */
0xb1, 0x02, /* Feature (Data, Variable, Absolute) */
0x85, 0x01, /* Report ID (1) */
0x09, 0x38, /* Usage (Wheel) */
0x35, 0x00, /* Physical Minimum (0) */
0x45, 0x00, /* Physical Maximum (0) */
0x16, 0x01, 0x80, /* Logical Minimum (-0x7fff) */
0x26, 0xff, 0x7f, /* Logical Maximum (0x7fff) */
0x75, 0x10, /* Report Size (16) */
0x95, 0x01, /* Report Count (1) */
0x81, 0x06, /* Input (Data, Variable, Relative) */
0x05, 0x0c, /* Usage Page (Consumer) */
0x0a, 0x38, 0x02, /* Usage (AC Pan) */
0x81, 0x06, /* Input (Data, Variable, Relative) */
0x06, 0x61, 0xff, /* Usage Page (0xff61, vendor-defined) */
0x09, 0x02, /* Usage (2): vertical scroll */
0x09, 0x01, /* Usage (1): horizontal scroll */
0x75, 0x20, /* Report Size (32) */
0x95, 0x02, /* Report Count (2) */
0x81, 0x06, /* Input (Data, Variable, Relative) */
0x09, 0x03, /* Usage (3): phases */
0x75, 0x10, /* Report Size (16) */
0x95, 0x01, /* Report Count (1) */
0x81, 0x02, /* Input (Data, Variable, Absolute) */
0x85, 0x03, /* Report ID (3) */
0x09, 0x04, /* Usage (4): smooth scrolling on */
0x95, 0x01, /* Report Count (1) */
0x75, 0x01, /* Report Size (1) */
0xb1, 0x02, /* Feature (Data, Variable, Absolute) */
0x95, 0x01, /* Report Count (1) */
0x75, 0x07, /* Report Size (7) */
0xb1, 0x01, /* Feature (Constant) */
0xc0, /* End Collection */
0xc0, /* End Collection */
0xc0, /* End Collection */
};
static const uint8_t desc_hid_vmapple_tablet[] = {
0x09, /* u8 bLength */
USB_DT_HID, /* u8 bDescriptorType */
0x11, 0x01, /* u16 HID_class */
0x00, /* u8 country_code */
0x01, /* u8 num_descriptors */
USB_DT_REPORT, /* u8 type: Report */
sizeof(vmapple_tablet_report_descriptor), 0, /* u16 len */
};
static const USBDescIface desc_iface_vmapple_tablet_full = {
.bInterfaceNumber = 0,
.bNumEndpoints = 1,
.bInterfaceClass = USB_CLASS_HID,
.ndesc = 1,
.descs = (USBDescOther[]) {
{ .data = desc_hid_vmapple_tablet },
},
.eps = (USBDescEndpoint[]) {
{
.bEndpointAddress = USB_DIR_IN | 0x01,
.bmAttributes = USB_ENDPOINT_XFER_INT,
.wMaxPacketSize = VMAPPLE_TABLET_REPORT_SIZE,
.bInterval = 1, /* 1 ms */
},
},
};
static const USBDescIface desc_iface_vmapple_tablet = {
.bInterfaceNumber = 0,
.bNumEndpoints = 1,
.bInterfaceClass = USB_CLASS_HID,
.ndesc = 1,
.descs = (USBDescOther[]) {
{ .data = desc_hid_vmapple_tablet },
},
.eps = (USBDescEndpoint[]) {
{
.bEndpointAddress = USB_DIR_IN | 0x01,
.bmAttributes = USB_ENDPOINT_XFER_INT,
.wMaxPacketSize = VMAPPLE_TABLET_REPORT_SIZE,
.bInterval = 4, /* 2 ^ (4 - 1) * 125 usecs = 1 ms */
},
},
};
static const USBDescDevice desc_device_vmapple_tablet_full = {
.bcdUSB = 0x0110,
.bMaxPacketSize0 = 8,
.bNumConfigurations = 1,
.confs = (USBDescConfig[]) {
{
.bNumInterfaces = 1,
.bConfigurationValue = 1,
.iConfiguration = STR_CONFIG,
.bmAttributes = USB_CFG_ATT_ONE,
.bMaxPower = 50,
.nif = 1,
.ifs = &desc_iface_vmapple_tablet_full,
},
},
};
static const USBDescDevice desc_device_vmapple_tablet = {
.bcdUSB = 0x0200,
.bMaxPacketSize0 = 64,
.bNumConfigurations = 1,
.confs = (USBDescConfig[]) {
{
.bNumInterfaces = 1,
.bConfigurationValue = 1,
.iConfiguration = STR_CONFIG,
.bmAttributes = USB_CFG_ATT_ONE,
.bMaxPower = 50,
.nif = 1,
.ifs = &desc_iface_vmapple_tablet,
},
},
};
static const USBDesc desc_vmapple_tablet = {
.id = {
/* The IDs macOS binds AppleVirtualPlatformHIDEventDriver to */
.idVendor = 0x05ac,
.idProduct = 0x8106,
.bcdDevice = 0,
.iManufacturer = STR_MANUFACTURER,
.iProduct = STR_PRODUCT,
.iSerialNumber = STR_SERIALNUMBER,
},
.full = &desc_device_vmapple_tablet_full,
.high = &desc_device_vmapple_tablet,
.str = desc_strings,
};
static bool vmapple_tablet_report_scrolls(const VMAppleTabletReport *r)
{
return r->wheel || r->pan || r->scroll_y || r->scroll_x || r->phases;
}
static void vmapple_tablet_enqueue(USBVMAppleTabletState *s,
const VMAppleTabletReport *r)
{
assert(s->queue_count < VMAPPLE_TABLET_QUEUE_LENGTH);
s->queue[(s->queue_head + s->queue_count++) %
VMAPPLE_TABLET_QUEUE_LENGTH] = *r;
s->last = *r;
}
/*
* Queue @r, after a report that returns the scroll fields to 0 if needed.
*
* A full queue drops @r, and every report after it until the guest has read
* the queue empty, which then gets what the guest missed, from
* vmapple_tablet_resync(). Merging @r into the last report queued instead
* would lose it where the two differ in kind: macOS ignores the pointer and
* buttons of a scroll report, and then sees no change in a pointer report
* that repeats them, so a button released while the queue is full would
* stay held.
*/
static void vmapple_tablet_push(USBVMAppleTabletState *s,
const VMAppleTabletReport *r)
{
bool settle = vmapple_tablet_report_scrolls(&s->last) &&
!vmapple_tablet_report_scrolls(r);
trace_usb_vmapple_tablet_report(r->buttons, r->x, r->y, r->wheel, r->pan,
r->scroll_y, r->scroll_x, r->phases);
if (s->overflow ||
s->queue_count + settle >= VMAPPLE_TABLET_QUEUE_LENGTH) {
trace_usb_vmapple_tablet_queue_full();
s->overflow = true;
if (r->phases) {
s->owed_phases = r->phases;
}
return;
}
if (settle) {
VMAppleTabletReport zero = {
.buttons = s->last.buttons,
.x = s->last.x,
.y = s->last.y,
};
vmapple_tablet_enqueue(s, &zero);
}
vmapple_tablet_enqueue(s, r);
}
/*
* Once the guest has read the queue empty after reports were dropped: the
* phases of the last scrolling dropped, so that a gesture the guest missed
* the end of ends, and the pointer and buttons as they are.
*/
static void vmapple_tablet_resync(USBVMAppleTabletState *s)
{
VMAppleTabletReport scroll = {
.buttons = s->last.buttons,
.x = s->last.x,
.y = s->last.y,
.phases = s->owed_phases,
};
VMAppleTabletReport pointer = {
.buttons = s->buttons,
.x = s->x,
.y = s->y,
};
s->overflow = false;
s->owed_phases = 0;
if (scroll.phases) {
vmapple_tablet_push(s, &scroll);
}
vmapple_tablet_push(s, &pointer);
}
static uint16_t vmapple_tablet_phases(InputScrollPhase phase,
InputScrollMomentum momentum)
{
static const uint8_t gesture[INPUT_SCROLL_PHASE__MAX] = {
[INPUT_SCROLL_PHASE_NONE] = 0,
[INPUT_SCROLL_PHASE_MAY_BEGIN] = 1,
[INPUT_SCROLL_PHASE_BEGAN] = 2,
[INPUT_SCROLL_PHASE_CHANGED] = 3,
[INPUT_SCROLL_PHASE_ENDED] = 4,
[INPUT_SCROLL_PHASE_CANCELLED] = 5,
};
static const uint8_t momentum_phase[INPUT_SCROLL_MOMENTUM__MAX] = {
[INPUT_SCROLL_MOMENTUM_NONE] = 0,
[INPUT_SCROLL_MOMENTUM_BEGAN] = 1,
[INPUT_SCROLL_MOMENTUM_CHANGED] = 2,
[INPUT_SCROLL_MOMENTUM_ENDED] = 3,
};
return gesture[phase] << 2 | momentum_phase[momentum];
}
static int64_t vmapple_tablet_notch_units(USBVMAppleTabletState *s)
{
return s->multiplier ? VMAPPLE_TABLET_MULTIPLIED_NOTCH : 1;
}
/*
* @distance in 1/256 pixel as whole wheel units, keeping the rest in @rest,
* which counts afresh when the direction turns.
*/
static int64_t vmapple_tablet_wheel(USBVMAppleTabletState *s, int32_t *rest,
int64_t distance)
{
const int64_t notch = VMAPPLE_TABLET_NOTCH_PIXELS * 256;
int64_t sum = distance * vmapple_tablet_notch_units(s);
int64_t units;
if (!sum) {
return 0;
}
if ((int64_t)*rest * sum > 0) {
sum += *rest;
}
units = sum / notch;
*rest = sum - units * notch;
return units;
}
/* @distance in 1/256 pixel in 1/65536 line */
static int32_t vmapple_tablet_lines(int64_t distance)
{
int64_t lines = distance * 256 / VMAPPLE_TABLET_LINE_PIXELS;
return MIN(MAX(lines, INT32_MIN), INT32_MAX);
}
/*
* @distance plus @value, in 1/256 pixel, held to 32 bits: input-send-event
* takes any 64-bit value, which the sums after this would overflow.
*/
static int64_t vmapple_tablet_add(int64_t distance, int64_t value)
{
value = MIN(MAX(value, INT32_MIN), INT32_MAX);
return MIN(MAX(distance + value, INT32_MIN), INT32_MAX);
}
static void vmapple_tablet_input_event(DeviceState *dev, QemuConsole *src,
QemuInputEvent *evt)
{
static const uint8_t bmap[INPUT_BUTTON__MAX] = {
[INPUT_BUTTON_LEFT] = 0x01,
[INPUT_BUTTON_RIGHT] = 0x02,
[INPUT_BUTTON_MIDDLE] = 0x04,
};
USBVMAppleTabletState *s = USB_VMAPPLE_TABLET(dev);
switch (evt->type) {
case INPUT_EVENT_KIND_BTN:
switch (evt->btn.button) {
case INPUT_BUTTON_WHEEL_UP:
s->notches_y += evt->btn.down;
break;
case INPUT_BUTTON_WHEEL_DOWN:
s->notches_y -= evt->btn.down;
break;
case INPUT_BUTTON_WHEEL_LEFT:
s->notches_x += evt->btn.down;
break;
case INPUT_BUTTON_WHEEL_RIGHT:
s->notches_x -= evt->btn.down;
break;
default:
if (evt->btn.down) {
s->buttons |= bmap[evt->btn.button];
} else {
s->buttons &= ~bmap[evt->btn.button];
}
s->pointer_changed = true;
break;
}
break;
case INPUT_EVENT_KIND_ABS:
if (evt->abs.axis == INPUT_AXIS_X) {
s->x = evt->abs.value;
} else if (evt->abs.axis == INPUT_AXIS_Y) {
s->y = evt->abs.value;
}
s->pointer_changed = true;
break;
case INPUT_EVENT_KIND_SCROLL:
if (evt->scroll.axis == INPUT_AXIS_X) {
s->scroll_x = vmapple_tablet_add(s->scroll_x, evt->scroll.value);
} else if (evt->scroll.axis == INPUT_AXIS_Y) {
s->scroll_y = vmapple_tablet_add(s->scroll_y, evt->scroll.value);
}
s->phases = vmapple_tablet_phases(evt->scroll.phase,
evt->scroll.momentum);
s->scrolled = true;
break;
default:
break;
}
}
static void vmapple_tablet_input_sync(DeviceState *dev)
{
USBVMAppleTabletState *s = USB_VMAPPLE_TABLET(dev);
bool pushed = false;
/* The pointer first, so that the scrolling is where the pointer went. */
if (s->pointer_changed) {
VMAppleTabletReport r = {
.buttons = s->buttons,
.x = s->x,
.y = s->y,
};
vmapple_tablet_push(s, &r);
pushed = true;
}
if (s->scrolled || s->notches_y || s->notches_x) {
const int64_t notch = VMAPPLE_TABLET_NOTCH_PIXELS * 256;
int64_t units = vmapple_tablet_notch_units(s);
int64_t wheel = s->notches_y * units +
vmapple_tablet_wheel(s, &s->notch_rest_y, s->scroll_y);
int64_t left = s->notches_x * units +
vmapple_tablet_wheel(s, &s->notch_rest_x, s->scroll_x);
VMAppleTabletReport r = {
.buttons = s->last.buttons,
.x = s->last.x,
.y = s->last.y,
.wheel = MIN(MAX(wheel, -INT16_MAX), INT16_MAX),
/* AC Pan counts to the right, as HID has it */
.pan = MIN(MAX(-left, -INT16_MAX), INT16_MAX),
.scroll_y = vmapple_tablet_lines(s->scroll_y +
s->notches_y * notch),
.scroll_x = vmapple_tablet_lines(s->scroll_x +
s->notches_x * notch),
.phases = s->scrolled ? s->phases : 0,
};
vmapple_tablet_push(s, &r);
pushed = true;
}
s->pointer_changed = false;
s->notches_y = 0;
s->notches_x = 0;
s->scroll_y = 0;
s->scroll_x = 0;
s->scrolled = false;
if (pushed) {
usb_wakeup(s->intr, 0);
}
}
static const QemuInputHandler vmapple_tablet_handler = {
.name = "QEMU vmapple USB Tablet",
.mask = INPUT_EVENT_MASK_BTN | INPUT_EVENT_MASK_ABS |
INPUT_EVENT_MASK_SCROLL,
.event = vmapple_tablet_input_event,
.sync = vmapple_tablet_input_sync,
};
static int vmapple_tablet_write_report(const VMAppleTabletReport *r,
uint8_t *buf, int len)
{
uint8_t report[VMAPPLE_TABLET_REPORT_SIZE];
report[0] = VMAPPLE_TABLET_REPORT_INPUT;
report[1] = r->buttons;
stw_le_p(&report[2], r->x);
stw_le_p(&report[4], r->y);
stw_le_p(&report[6], r->wheel);
stw_le_p(&report[8], r->pan);
stl_le_p(&report[10], r->scroll_y);
stl_le_p(&report[14], r->scroll_x);
stw_le_p(&report[18], r->phases);
len = MIN(len, sizeof(report));
memcpy(buf, report, len);
return len;
}
static void usb_vmapple_tablet_handle_reset(USBDevice *dev)
{
USBVMAppleTabletState *s = USB_VMAPPLE_TABLET(dev);
const VMAppleTabletReport nothing = { 0 };
s->buttons = 0;
s->pointer_changed = false;
s->notches_y = 0;
s->notches_x = 0;
s->scroll_y = 0;
s->scroll_x = 0;
s->phases = 0;
s->scrolled = false;
s->notch_rest_y = 0;
s->notch_rest_x = 0;
s->queue_head = 0;
s->queue_count = 0;
s->overflow = false;
s->owed_phases = 0;
/* The first report the guest reads, which it takes as a scroll */
vmapple_tablet_enqueue(s, &nothing);
s->idle = 0;
s->multiplier = 0;
s->smooth = 0;
}
static void usb_vmapple_tablet_handle_control(USBDevice *dev, USBPacket *p,
int request, int value,
int index, int length,
uint8_t *data)
{
USBVMAppleTabletState *s = USB_VMAPPLE_TABLET(dev);
uint8_t type = value >> 8;
uint8_t id = value & 0xff;
int ret;
ret = usb_desc_handle_control(dev, p, request, value, index, length, data);
if (ret >= 0) {
return;
}
switch (request) {
case InterfaceRequest | USB_REQ_GET_DESCRIPTOR:
if (type != USB_DT_REPORT) {
goto fail;
}
length = MIN(length, sizeof(vmapple_tablet_report_descriptor));
memcpy(data, vmapple_tablet_report_descriptor, length);
p->actual_length = length;
break;
case HID_GET_REPORT:
if (type == 1 && id == VMAPPLE_TABLET_REPORT_INPUT) {
VMAppleTabletReport r = {
.buttons = s->buttons,
.x = s->x,
.y = s->y,
};
p->actual_length = vmapple_tablet_write_report(&r, data, length);
} else if (type == 3 && id == VMAPPLE_TABLET_REPORT_MULTIPLIER &&
length >= 2) {
data[0] = id;
data[1] = s->multiplier;
p->actual_length = 2;
} else if (type == 3 && id == VMAPPLE_TABLET_REPORT_SMOOTH &&
length >= 2) {
data[0] = id;
data[1] = s->smooth;
p->actual_length = 2;
} else {
goto fail;
}
trace_usb_vmapple_tablet_get_report(type, id);
break;
case HID_SET_REPORT:
if (type != 3 || length < 2 || data[0] != id) {
goto fail;
}
if (id == VMAPPLE_TABLET_REPORT_MULTIPLIER) {
s->multiplier = data[1] & 1;
s->notch_rest_y = 0;
s->notch_rest_x = 0;
} else if (id == VMAPPLE_TABLET_REPORT_SMOOTH) {
s->smooth = data[1] & 1;
} else {
goto fail;
}
trace_usb_vmapple_tablet_set_report(id, data[1]);
break;
case HID_GET_IDLE:
data[0] = s->idle;
p->actual_length = 1;
break;
case HID_SET_IDLE:
s->idle = value >> 8;
break;
default:
fail:
p->status = USB_RET_STALL;
break;
}
}
static void usb_vmapple_tablet_handle_data(USBDevice *dev, USBPacket *p)
{
USBVMAppleTabletState *s = USB_VMAPPLE_TABLET(dev);
uint8_t buf[VMAPPLE_TABLET_REPORT_SIZE];
int len;
if (p->pid != USB_TOKEN_IN || p->ep->nr != 1) {
p->status = USB_RET_STALL;
return;
}
/* As usb-tablet does: take the input once the guest reads the device. */
if (!s->input_active) {
qemu_input_handler_activate(s->hs);
s->input_active = true;
}
if (!s->queue_count && s->overflow) {
vmapple_tablet_resync(s);
}
if (!s->queue_count) {
p->status = USB_RET_NAK;
return;
}
len = vmapple_tablet_write_report(&s->queue[s->queue_head], buf,
p->iov.size);
s->queue_head = (s->queue_head + 1) % VMAPPLE_TABLET_QUEUE_LENGTH;
s->queue_count--;
usb_packet_copy(p, buf, len);
}
static void usb_vmapple_tablet_unrealize(USBDevice *dev)
{
USBVMAppleTabletState *s = USB_VMAPPLE_TABLET(dev);
qemu_input_handler_unregister(s->hs);
}
static void usb_vmapple_tablet_realize(USBDevice *dev, Error **errp)
{
ERRP_GUARD();
USBVMAppleTabletState *s = USB_VMAPPLE_TABLET(dev);
dev->usb_desc = &desc_vmapple_tablet;
usb_desc_create_serial(dev);
usb_desc_init(dev);
s->intr = usb_ep_get(dev, USB_TOKEN_IN, 1);
s->hs = qemu_input_handler_register(DEVICE(dev), &vmapple_tablet_handler);
if (s->display) {
qemu_input_handler_bind(s->hs, s->display, s->head, errp);
if (*errp) {
/* A device that fails to realize is freed, not unrealized. */
g_clear_pointer(&s->hs, qemu_input_handler_unregister);
}
}
}
static const VMStateDescription vmstate_vmapple_tablet_report = {
.name = "usb-vmapple-tablet/report",
.version_id = 1,
.minimum_version_id = 1,
.fields = (const VMStateField[]) {
VMSTATE_UINT8(buttons, VMAppleTabletReport),
VMSTATE_UINT16(x, VMAppleTabletReport),
VMSTATE_UINT16(y, VMAppleTabletReport),
VMSTATE_INT16(wheel, VMAppleTabletReport),
VMSTATE_INT16(pan, VMAppleTabletReport),
VMSTATE_INT32(scroll_y, VMAppleTabletReport),
VMSTATE_INT32(scroll_x, VMAppleTabletReport),
VMSTATE_UINT16(phases, VMAppleTabletReport),
VMSTATE_END_OF_LIST()
}
};
static int usb_vmapple_tablet_post_load(void *opaque, int version_id)
{
USBVMAppleTabletState *s = opaque;
if (s->queue_head >= VMAPPLE_TABLET_QUEUE_LENGTH ||
s->queue_count > VMAPPLE_TABLET_QUEUE_LENGTH) {
return -EINVAL;
}
return 0;
}
static bool usb_vmapple_tablet_overflow_needed(void *opaque)
{
USBVMAppleTabletState *s = opaque;
return s->overflow;
}
static const VMStateDescription vmstate_usb_vmapple_tablet_overflow = {
.name = "usb-vmapple-tablet/overflow",
.version_id = 1,
.minimum_version_id = 1,
.needed = usb_vmapple_tablet_overflow_needed,
.fields = (const VMStateField[]) {
VMSTATE_BOOL(overflow, USBVMAppleTabletState),
VMSTATE_UINT16(owed_phases, USBVMAppleTabletState),
VMSTATE_END_OF_LIST()
}
};
static const VMStateDescription vmstate_usb_vmapple_tablet = {
.name = "usb-vmapple-tablet",
.version_id = 1,
.minimum_version_id = 1,
.post_load = usb_vmapple_tablet_post_load,
.fields = (const VMStateField[]) {
VMSTATE_USB_DEVICE(dev, USBVMAppleTabletState),
VMSTATE_UINT8(buttons, USBVMAppleTabletState),
VMSTATE_UINT16(x, USBVMAppleTabletState),
VMSTATE_UINT16(y, USBVMAppleTabletState),
VMSTATE_INT32(notch_rest_y, USBVMAppleTabletState),
VMSTATE_INT32(notch_rest_x, USBVMAppleTabletState),
VMSTATE_STRUCT_ARRAY(queue, USBVMAppleTabletState,
VMAPPLE_TABLET_QUEUE_LENGTH, 1,
vmstate_vmapple_tablet_report,
VMAppleTabletReport),
VMSTATE_UINT32(queue_head, USBVMAppleTabletState),
VMSTATE_UINT32(queue_count, USBVMAppleTabletState),
VMSTATE_STRUCT(last, USBVMAppleTabletState, 1,
vmstate_vmapple_tablet_report, VMAppleTabletReport),
VMSTATE_UINT8(idle, USBVMAppleTabletState),
VMSTATE_UINT8(multiplier, USBVMAppleTabletState),
VMSTATE_UINT8(smooth, USBVMAppleTabletState),
VMSTATE_END_OF_LIST()
},
.subsections = (const VMStateDescription * const []) {
&vmstate_usb_vmapple_tablet_overflow,
NULL
}
};
static const Property usb_vmapple_tablet_properties[] = {
DEFINE_PROP_STRING("display", USBVMAppleTabletState, display),
DEFINE_PROP_UINT32("head", USBVMAppleTabletState, head, 0),
};
static void usb_vmapple_tablet_class_init(ObjectClass *klass,
const void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
uc->product_desc = "QEMU vmapple USB Tablet";
uc->realize = usb_vmapple_tablet_realize;
uc->unrealize = usb_vmapple_tablet_unrealize;
uc->handle_reset = usb_vmapple_tablet_handle_reset;
uc->handle_control = usb_vmapple_tablet_handle_control;
uc->handle_data = usb_vmapple_tablet_handle_data;
uc->handle_attach = usb_desc_attach;
dc->desc = "USB tablet of Virtualization.framework's macOS guests";
dc->vmsd = &vmstate_usb_vmapple_tablet;
device_class_set_props(dc, usb_vmapple_tablet_properties);
set_bit(DEVICE_CATEGORY_INPUT, dc->categories);
}
static const TypeInfo usb_vmapple_tablet_info = {
.name = TYPE_USB_VMAPPLE_TABLET,
.parent = TYPE_USB_DEVICE,
.instance_size = sizeof(USBVMAppleTabletState),
.class_init = usb_vmapple_tablet_class_init,
};
static void usb_vmapple_tablet_register_types(void)
{
type_register_static(&usb_vmapple_tablet_info);
}
type_init(usb_vmapple_tablet_register_types)
+27
View File
@@ -28,6 +28,7 @@
#include "migration/vmstate.h"
#include "hw/pci/msi.h"
#include "hw/pci/msix.h"
#include "hw/pci/pcie.h"
#include "hcd-xhci-pci.h"
#include "trace.h"
#include "qapi/error.h"
@@ -120,6 +121,29 @@ static int xhci_pci_vmstate_post_load(void *opaque, int version_id)
return 0;
}
/*
* An xHC with LTC set supports its interconnect's LTR mechanism (xHCI 4.13.1):
* on PCI Express, LTR in Device Capabilities 2, its enable in Device Control 2
* and the LTR Extended Capability with its two maximum latencies.
*/
#define XHCI_PCI_LTR_OFFSET 0x100
static void xhci_pci_ltr_init(PCIDevice *dev)
{
uint16_t exp_cap = dev->exp.exp_cap;
pci_long_test_and_set_mask(dev->config + exp_cap + PCI_EXP_DEVCAP2,
PCI_EXP_DEVCAP2_LTR);
pci_word_test_and_set_mask(dev->wmask + exp_cap + PCI_EXP_DEVCTL2,
PCI_EXP_DEVCTL2_LTR_EN);
pcie_add_capability(dev, PCI_EXT_CAP_ID_LTR, 1, XHCI_PCI_LTR_OFFSET,
PCI_EXT_CAP_LTR_SIZEOF);
pci_set_word(dev->wmask + XHCI_PCI_LTR_OFFSET + PCI_LTR_MAX_SNOOP_LAT,
PCI_LTR_VALUE_MASK | PCI_LTR_SCALE_MASK);
pci_set_word(dev->wmask + XHCI_PCI_LTR_OFFSET + PCI_LTR_MAX_NOSNOOP_LAT,
PCI_LTR_VALUE_MASK | PCI_LTR_SCALE_MASK);
}
static void usb_xhci_pci_realize(struct PCIDevice *dev, Error **errp)
{
int ret;
@@ -137,6 +161,8 @@ static void usb_xhci_pci_realize(struct PCIDevice *dev, Error **errp)
if (s->conditional_intr_mapping) {
s->xhci.intr_mapping_supported = xhci_pci_intr_mapping_conditional;
}
/* PCI Express has an LTR mechanism, so the xHC supports LTM (4.13.1) */
s->xhci.ltm = pci_bus_is_express(pci_get_bus(dev));
if (!qdev_realize(DEVICE(&s->xhci), NULL, errp)) {
return;
}
@@ -170,6 +196,7 @@ static void usb_xhci_pci_realize(struct PCIDevice *dev, Error **errp)
if (pci_bus_is_express(pci_get_bus(dev))) {
ret = pcie_endpoint_cap_init(dev, 0xa0);
assert(ret > 0);
xhci_pci_ltr_init(dev);
}
if (s->msix != ON_OFF_AUTO_OFF) {
+313 -54
View File
@@ -115,6 +115,8 @@
#define PORTSC_DR (1<<30)
#define PORTSC_WPR (1<<31)
#define HCCP1_LTC (1<<6)
#define CRCR_RCS (1<<0)
#define CRCR_CS (1<<1)
#define CRCR_CA (1<<2)
@@ -291,6 +293,8 @@ struct XHCIEPContext {
unsigned int interval;
int64_t mfindex_last;
QEMUTimer *kick_timer;
/* a Ring Underrun or Overrun event reports this empty ring already */
bool iso_empty_reported;
};
typedef struct XHCIEvRingSeg {
@@ -301,7 +305,8 @@ typedef struct XHCIEvRingSeg {
} XHCIEvRingSeg;
static void xhci_kick_ep(XHCIState *xhci, unsigned int slotid,
unsigned int epid, unsigned int streamid);
unsigned int epid, unsigned int streamid,
bool doorbell);
static void xhci_kick_epctx(XHCIEPContext *epctx, unsigned int streamid);
static TRBCCode xhci_disable_ep(XHCIState *xhci, unsigned int slotid,
unsigned int epid);
@@ -595,18 +600,45 @@ static void xhci_intr_update(XHCIState *xhci, int v)
}
}
/* IMODI and IMODC count in 250 ns steps */
#define IMOD_TICK_NS 250
static uint32_t xhci_imodc(XHCIInterrupter *intr)
{
int64_t left;
if (!timer_pending(intr->imod_timer)) {
return 0;
}
left = timer_expire_time_ns(intr->imod_timer) -
qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
return left <= 0 ? 0 : MIN(DIV_ROUND_UP(left, IMOD_TICK_NS), 0xffff);
}
/*
* Assert interrupter v's interrupt when a non-blocking event awaits (IPE),
* the moderation counter is at 0 and the event handler is not busy (4.17.2):
* set IP and EHB, signal the interrupt, and load IMODC with IMODI.
*/
static void xhci_intr_raise(XHCIState *xhci, int v)
{
bool pending = (xhci->intr[v].erdp_low & ERDP_EHB);
XHCIInterrupter *intr = &xhci->intr[v];
uint32_t imodi = intr->imod & 0xffff;
xhci->intr[v].erdp_low |= ERDP_EHB;
xhci->intr[v].iman |= IMAN_IP;
xhci->usbsts |= USBSTS_EINT;
if (pending) {
if (!intr->ipe || (intr->erdp_low & ERDP_EHB) ||
timer_pending(intr->imod_timer)) {
return;
}
if (!(xhci->intr[v].iman & IMAN_IE)) {
intr->erdp_low |= ERDP_EHB;
intr->iman |= IMAN_IP;
xhci->usbsts |= USBSTS_EINT;
if (imodi) {
timer_mod(intr->imod_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
(int64_t)imodi * IMOD_TICK_NS);
}
if (!(intr->iman & IMAN_IE)) {
return;
}
@@ -615,11 +647,24 @@ static void xhci_intr_raise(XHCIState *xhci, int v)
}
if (xhci->intr_raise) {
if (xhci->intr_raise(xhci, v, true)) {
xhci->intr[v].iman &= ~IMAN_IP;
intr->iman &= ~IMAN_IP;
}
}
}
/* IMODC reached 0 */
static void xhci_imod_timer(void *opaque)
{
XHCIInterrupter *intr = opaque;
XHCIState *xhci = intr->xhci;
MemReentrancyGuard *guard = &xhci->parent.mem_reentrancy_guard;
assert(!guard->engaged_in_io);
guard->engaged_in_io = true;
xhci_intr_raise(xhci, intr - xhci->intr);
guard->engaged_in_io = false;
}
static inline int xhci_running(XHCIState *xhci)
{
return !(xhci->usbsts & USBSTS_HCH);
@@ -660,7 +705,13 @@ static void xhci_write_event(XHCIState *xhci, XHCIEvent *event, int v)
}
}
static void xhci_event(XHCIState *xhci, XHCIEvent *event, int v)
/*
* Post an event on interrupter v's ring. A Transfer Event of a TRB with Block
* Event Interrupt set (4.17.5) is written without asserting the interrupt
* (block_irq): the interrupter's next interrupt brings the guest to it.
*/
static void xhci_event_blockable(XHCIState *xhci, XHCIEvent *event, int v,
bool block_irq)
{
XHCIInterrupter *intr;
dma_addr_t erdp;
@@ -698,11 +749,20 @@ static void xhci_event(XHCIState *xhci, XHCIEvent *event, int v)
DPRINTF("xhci: ER %d full, drop event\n", v);
} else {
xhci_write_event(xhci, event, v);
if (block_irq) {
return;
}
}
intr->ipe = true;
xhci_intr_raise(xhci, v);
}
static void xhci_event(XHCIState *xhci, XHCIEvent *event, int v)
{
xhci_event_blockable(xhci, event, v, false);
}
static void xhci_ring_init(XHCIState *xhci, XHCIRing *ring,
dma_addr_t base)
{
@@ -860,6 +920,7 @@ static void xhci_er_reset(XHCIState *xhci, int v)
intr->er_ep_idx = 0;
intr->er_pcs = 1;
intr->ipe = false;
DPRINTF("xhci: event ring[%d]:" DMA_ADDR_FMT " [%d]\n",
v, intr->er_start, intr->er_size);
@@ -1112,6 +1173,11 @@ static void xhci_ep_kick_timer(void *opaque)
XHCIEPContext *epctx = opaque;
MemReentrancyGuard *guard = &epctx->xhci->parent.mem_reentrancy_guard;
/* a timer armed before a Stop Endpoint restarts nothing (4.6.9) */
if (epctx->state != EP_RUNNING) {
return;
}
assert(!guard->engaged_in_io);
guard->engaged_in_io = true;
@@ -1158,6 +1224,7 @@ static void xhci_init_epctx(XHCIEPContext *epctx,
}
epctx->interval = 1u << MIN((ctx[0] >> 16) & 0xffu, 18u);
epctx->iso_empty_reported = false;
}
static TRBCCode xhci_enable_ep(XHCIState *xhci, unsigned int slotid,
@@ -1470,6 +1537,7 @@ static TRBCCode xhci_set_ep_dequeue(XHCIState *xhci, unsigned int slotid,
xhci_ring_init(xhci, &epctx->ring, dequeue & ~0xF);
epctx->ring.ccs = dequeue & 1;
}
epctx->iso_empty_reported = false;
xhci_set_ep_state(xhci, epctx, sctx, EP_STOPPED);
@@ -1526,12 +1594,34 @@ err:
return -1;
}
/*
* Post the Transfer Events of a transfer's TDs (xHCI 4.10.1.1). Without a
* Short Packet, each TRB with IOC posts Success. A Short Packet ends the
* data of its TD on the TRB it meets: that TRB posts Short Packet with its
* residue if it has ISP or IOC, and that event is the TD Completion Event.
* The xHC then advances to the end of the TD, and each later Transfer TRB
* with IOC posts Short Packet too, with the TD Completion Event's residue
* (4.10.1.1.2): a TD of TRBs with ISP whose last TRB has IOC posts two
* events, and software does not take the TD as complete before the one
* that points at its last TRB. An Event Data TRB after the Short Packet is
* parsed only if no event completed the TD yet, and then only the first
* (PAE is 0, 4.10.1.1.1). An error posts one event, at the first TRB with
* IOC or the TRB where the data transferred ran out, and ends the report.
*/
static void xhci_xfer_report(XHCITransfer *xfer)
{
uint32_t edtla = 0;
unsigned int left;
bool reported = 0;
bool shortpkt = 0;
/*
* The current TD's Short Packet: shortpkt once the TD met it,
* short_reported once the TRB it met it on posted its event, with that
* event's residue in short_length, and ed_parsed once an Event Data TRB
* after it was parsed.
*/
bool shortpkt = false;
bool short_reported = false;
uint32_t short_length = 0;
bool ed_parsed = false;
XHCIEvent event = {ER_TRANSFER, CC_SUCCESS};
XHCIState *xhci = xfer->epctx->xhci;
int i;
@@ -1541,6 +1631,8 @@ static void xhci_xfer_report(XHCITransfer *xfer)
for (i = 0; i < xfer->trb_count; i++) {
XHCITRB *trb = &xfer->trbs[i];
unsigned int chunk = 0;
bool short_trb = false;
bool post;
switch (TRB_TYPE(*trb)) {
case TR_SETUP:
@@ -1555,32 +1647,56 @@ static void xhci_xfer_report(XHCITransfer *xfer)
chunk = trb->status & 0x1ffff;
if (chunk > left) {
chunk = left;
if (xfer->status == CC_SUCCESS) {
shortpkt = 1;
if (xfer->status == CC_SUCCESS && !shortpkt) {
shortpkt = true;
short_trb = true;
}
}
left -= chunk;
edtla += chunk;
break;
case TR_STATUS:
reported = 0;
shortpkt = 0;
/* the Status Stage is a TD of its own */
shortpkt = false;
short_reported = false;
ed_parsed = false;
break;
}
if (!reported && ((trb->control & TRB_TR_IOC) ||
(shortpkt && (trb->control & TRB_TR_ISP)) ||
(xfer->status != CC_SUCCESS && left == 0))) {
event.slotid = xfer->epctx->slotid;
event.epid = xfer->epctx->epid;
event.length = (trb->status & 0x1ffff) - chunk;
event.flags = 0;
event.ptr = trb->addr;
if (xfer->status == CC_SUCCESS) {
event.ccode = shortpkt ? CC_SHORT_PACKET : CC_SUCCESS;
} else {
event.ccode = xfer->status;
event.slotid = xfer->epctx->slotid;
event.epid = xfer->epctx->epid;
event.length = (trb->status & 0x1ffff) - chunk;
event.flags = 0;
event.ptr = trb->addr;
if (xfer->status != CC_SUCCESS) {
post = (trb->control & TRB_TR_IOC) || left == 0;
event.ccode = xfer->status;
} else if (TRB_TYPE(*trb) == TR_EVDATA && shortpkt) {
post = false;
if (!short_reported && !ed_parsed) {
ed_parsed = true;
post = trb->control & TRB_TR_IOC;
}
event.ccode = CC_SHORT_PACKET;
} else if (short_trb) {
post = trb->control & (TRB_TR_IOC | TRB_TR_ISP);
event.ccode = CC_SHORT_PACKET;
if (post) {
short_reported = true;
short_length = event.length;
}
} else if (shortpkt) {
post = trb->control & TRB_TR_IOC;
event.ccode = CC_SHORT_PACKET;
if (short_reported) {
event.length = short_length;
}
} else {
post = trb->control & TRB_TR_IOC;
event.ccode = CC_SUCCESS;
}
if (post) {
if (TRB_TYPE(*trb) == TR_EVDATA) {
event.ptr = trb->parameter;
event.flags |= TRB_EV_ED;
@@ -1588,20 +1704,28 @@ static void xhci_xfer_report(XHCITransfer *xfer)
DPRINTF("xhci_xfer_data: EDTLA=%d\n", event.length);
edtla = 0;
}
xhci_event(xhci, &event, TRB_INTR(*trb));
reported = 1;
/*
* Normal, Isoch and Event Data TRBs have BEI; it blocks the
* interrupt of a completion, not of an error.
*/
xhci_event_blockable(xhci, &event, TRB_INTR(*trb),
(TRB_TYPE(*trb) == TR_NORMAL ||
TRB_TYPE(*trb) == TR_ISOCH ||
TRB_TYPE(*trb) == TR_EVDATA) &&
(trb->control & TRB_TR_BEI) &&
(event.ccode == CC_SUCCESS ||
event.ccode == CC_SHORT_PACKET));
if (xfer->status != CC_SUCCESS) {
return;
}
}
switch (TRB_TYPE(*trb)) {
case TR_SETUP:
reported = 0;
shortpkt = 0;
break;
/* a TRB without Chain, and a Setup Stage TRB, end their TD */
if (TRB_TYPE(*trb) == TR_SETUP || !(trb->control & TRB_TR_CH)) {
shortpkt = false;
short_reported = false;
ed_parsed = false;
}
}
}
@@ -1792,11 +1916,22 @@ static void xhci_calc_iso_kick(XHCIState *xhci, XHCITransfer *xfer,
xfer->mfindex_kick = asap;
}
} else {
/*
* Frame ID holds the frame's low 11 bits, a window of 2048 frames.
* A TD is scheduled at most 895 ms ahead (4.11.2.5), so a frame in
* the half of the window behind the current frame is late and runs
* now, and one in the half ahead is waited for. A late TD used to
* be scheduled 2048 frames ahead once it was more than 32 frames
* late, or 1 frame late just after the window wrapped.
*/
xfer->mfindex_kick = ((xfer->trbs[0].control >> TRB_TR_FRAMEID_SHIFT)
& TRB_TR_FRAMEID_MASK) << 3;
xfer->mfindex_kick |= mfindex & ~0x3fff;
if (xfer->mfindex_kick + 0x100 < mfindex) {
if (xfer->mfindex_kick + 0x2000 <= mfindex) {
xfer->mfindex_kick += 0x4000;
} else if (xfer->mfindex_kick >= mfindex + 0x2000 &&
xfer->mfindex_kick >= 0x4000) {
xfer->mfindex_kick -= 0x4000;
}
}
}
@@ -1876,7 +2011,8 @@ static int xhci_fire_transfer(XHCIState *xhci, XHCITransfer *xfer, XHCIEPContext
}
static void xhci_kick_ep(XHCIState *xhci, unsigned int slotid,
unsigned int epid, unsigned int streamid)
unsigned int epid, unsigned int streamid,
bool doorbell)
{
XHCIEPContext *epctx;
@@ -1894,6 +2030,15 @@ static void xhci_kick_ep(XHCIState *xhci, unsigned int slotid,
return;
}
/*
* 4.6.9: only a doorbell moves a stopped endpoint back to running. A
* device that has data for an endpoint the guest stopped leaves it
* stopped: the guest reads the endpoint context after Stop Endpoint
* completes and expects it stopped until it rings the doorbell.
*/
if (!doorbell && epctx->state != EP_RUNNING) {
return;
}
if (epctx->kick_active) {
return;
}
@@ -1988,8 +2133,14 @@ static void xhci_kick_epctx(XHCIEPContext *epctx, unsigned int streamid)
while (1) {
length = xhci_ring_chain_length(xhci, ring);
if (length <= 0) {
if (epctx->type == ET_ISO_OUT || epctx->type == ET_ISO_IN) {
/* 4.10.3.1 */
/*
* 4.10.3.1: an isochronous ring found empty is reported once,
* when it runs out of TDs, and not again until TDs were queued
* and ran out. A doorbell rung on a ring already reported empty
* reports nothing: the guest may ring it in answer to the event.
*/
if ((epctx->type == ET_ISO_OUT || epctx->type == ET_ISO_IN) &&
!epctx->iso_empty_reported) {
XHCIEvent ev = { ER_TRANSFER };
ev.ccode = epctx->type == ET_ISO_IN ?
CC_RING_OVERRUN : CC_RING_UNDERRUN;
@@ -1997,6 +2148,7 @@ static void xhci_kick_epctx(XHCIEPContext *epctx, unsigned int streamid)
ev.epid = epctx->epid;
ev.ptr = epctx->ring.dequeue;
xhci_event(xhci, &ev, xhci->slots[epctx->slotid-1].intr);
epctx->iso_empty_reported = true;
}
break;
}
@@ -2004,6 +2156,7 @@ static void xhci_kick_epctx(XHCIEPContext *epctx, unsigned int streamid)
if (xfer == NULL) {
break;
}
epctx->iso_empty_reported = false;
for (i = 0; i < length; i++) {
TRBType type;
@@ -2416,10 +2569,16 @@ static TRBCCode xhci_reset_slot(XHCIState *xhci, unsigned int slotid)
return CC_SUCCESS;
}
/*
* The slot a command names, or 0 where it names none that is enabled. Its
* completion holds the command's Slot ID either way (6.4.2.2, and 4.6.4 to
* 4.6.10 set it before checking the slot).
*/
static unsigned int xhci_get_slot(XHCIState *xhci, XHCIEvent *event, XHCITRB *trb)
{
unsigned int slotid;
slotid = (trb->control >> TRB_CR_SLOTID_SHIFT) & TRB_CR_SLOTID_MASK;
event->slotid = slotid;
if (slotid < 1 || slotid > xhci->numslots) {
DPRINTF("xhci: bad slot id %d\n", slotid);
event->ccode = CC_TRB_ERROR;
@@ -2497,9 +2656,8 @@ static void xhci_process_commands(XHCIState *xhci)
{
XHCITRB trb;
TRBType type;
XHCIEvent event = {ER_COMMAND_COMPLETE, CC_SUCCESS};
dma_addr_t addr;
unsigned int i, slotid = 0, count = 0;
unsigned int i, slotid, count = 0;
DPRINTF("xhci_process_commands()\n");
if (!xhci_running(xhci)) {
@@ -2510,7 +2668,17 @@ static void xhci_process_commands(XHCIState *xhci)
xhci->crcr_low |= CRCR_CRR;
while ((type = xhci_ring_fetch(xhci, &xhci->cmd_ring, &trb, &addr))) {
event.ptr = addr;
/*
* Each command completes with a Command Completion Event of its own
* (6.4.2.2): nothing of the previous command's carries over. Its Slot
* ID is the slot the command names, the slot an Enable Slot enabled,
* and 0 for No Op, Set LTV, Get Port Bandwidth, Force Event, a
* command the xHC does not support and an Enable Slot that finds no
* free slot.
*/
XHCIEvent event = { .type = ER_COMMAND_COMPLETE, .ccode = CC_SUCCESS,
.ptr = addr };
switch (type) {
case CR_ENABLE_SLOT:
for (i = 0; i < xhci->numslots; i++) {
@@ -2524,6 +2692,7 @@ static void xhci_process_commands(XHCIState *xhci)
} else {
slotid = i+1;
event.ccode = xhci_enable_slot(xhci, slotid);
event.slotid = slotid;
}
break;
case CR_DISABLE_SLOT:
@@ -2585,6 +2754,20 @@ static void xhci_process_commands(XHCIState *xhci)
event.ccode = xhci_reset_slot(xhci, slotid);
}
break;
case CR_SET_LATENCY_TOLERANCE:
/*
* 4.6.14: an xHC with LTC set records the host's Best Effort
* Latency Tolerance; one without it refuses the command. No LTR
* message carries it on: nothing in QEMU receives one.
*/
if (xhci->ltm) {
xhci->belt = (trb.control >> 16) & 0xfff;
trace_usb_xhci_set_ltv(xhci->belt);
event.ccode = CC_SUCCESS;
} else {
event.ccode = CC_TRB_ERROR;
}
break;
case CR_GET_PORT_BANDWIDTH:
event.ccode = xhci_get_port_bandwidth(xhci, trb.parameter);
break;
@@ -2606,7 +2789,7 @@ static void xhci_process_commands(XHCIState *xhci)
uint32_t val = xhci_nec_challenge(chi, clo);
event.length = val & 0xFFFF;
event.epid = val >> 16;
slotid = val >> 24;
event.slotid = val >> 24;
event.type = 48; /* NEC reply */
} else {
event.ccode = CC_TRB_ERROR;
@@ -2617,7 +2800,6 @@ static void xhci_process_commands(XHCIState *xhci)
event.ccode = CC_TRB_ERROR;
break;
}
event.slotid = slotid;
xhci_event(xhci, &event, 0);
if (count++ > COMMAND_LIMIT) {
@@ -2734,6 +2916,7 @@ static void xhci_reset(DeviceState *dev)
xhci->dcbaap_low = 0;
xhci->dcbaap_high = 0;
xhci->config = 0;
xhci->belt = 0;
for (i = 0; i < xhci->numslots; i++) {
xhci_disable_slot(xhci, i+1);
@@ -2745,7 +2928,9 @@ static void xhci_reset(DeviceState *dev)
for (i = 0; i < xhci->numintrs; i++) {
xhci->intr[i].iman = 0;
xhci->intr[i].imod = 0;
xhci->intr[i].imod = 4000; /* IMODI's default, 1 ms (5.5.2.2) */
xhci->intr[i].ipe = false;
timer_del(xhci->intr[i].imod_timer);
xhci->intr[i].erstsz = 0;
xhci->intr[i].erstba_low = 0;
xhci->intr[i].erstba_high = 0;
@@ -2787,6 +2972,9 @@ static uint64_t xhci_cap_read(void *ptr, hwaddr reg, unsigned size)
} else {
ret = 0x00080001 | (xhci->max_pstreams_mask << 12);
}
if (xhci->ltm) {
ret |= HCCP1_LTC;
}
break;
case 0x14: /* DBOFF */
ret = OFF_DOORBELL;
@@ -2794,6 +2982,9 @@ static uint64_t xhci_cap_read(void *ptr, hwaddr reg, unsigned size)
case 0x18: /* RTSOFF */
ret = OFF_RUNTIME;
break;
case 0x1c: /* HCCPARAMS2 from xHCI 1.1 on, reserved before */
ret = 0; /* none of its capabilities */
break;
/* extended capabilities */
case 0x20: /* Supported Protocol:00 */
@@ -3078,7 +3269,7 @@ static uint64_t xhci_runtime_read(void *ptr, hwaddr reg,
ret = intr->iman;
break;
case 0x04: /* IMOD */
ret = intr->imod;
ret = (xhci_imodc(intr) << 16) | intr->imod;
break;
case 0x08: /* ERSTSZ */
ret = intr->erstsz;
@@ -3134,8 +3325,16 @@ static void xhci_runtime_write(void *ptr, hwaddr reg,
intr->iman |= val & IMAN_IE;
xhci_intr_update(xhci, v);
break;
case 0x04: /* IMOD */
intr->imod = val;
case 0x04: /* IMOD: IMODI, and IMODC, which software may set */
intr->imod = val & 0xffff;
trace_usb_xhci_imod(v, intr->imod, val >> 16);
if (val >> 16) {
timer_mod(intr->imod_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
(int64_t)(val >> 16) * IMOD_TICK_NS);
} else {
timer_del(intr->imod_timer);
xhci_intr_raise(xhci, v);
}
break;
case 0x08: /* ERSTSZ */
intr->erstsz = val & 0xffff;
@@ -3157,15 +3356,19 @@ static void xhci_runtime_write(void *ptr, hwaddr reg,
intr->erdp_low &= ~ERDP_EHB;
}
intr->erdp_low = (val & ~ERDP_EHB) | (intr->erdp_low & ERDP_EHB);
if (val & ERDP_EHB) {
{
dma_addr_t erdp = xhci_addr64(intr->erdp_low, intr->erdp_high);
unsigned int dp_idx = (erdp - intr->er_start) / TRB_SIZE;
/* the ring is empty: no event awaits (4.17.5) */
if (erdp >= intr->er_start &&
erdp < (intr->er_start + TRB_SIZE * intr->er_size) &&
dp_idx != intr->er_ep_idx) {
xhci_intr_raise(xhci, v);
dp_idx == intr->er_ep_idx) {
intr->ipe = false;
}
}
if (val & ERDP_EHB) {
xhci_intr_raise(xhci, v);
}
break;
case 0x1c: /* ERDP high */
intr->erdp_high = val;
@@ -3214,7 +3417,7 @@ static void xhci_doorbell_write(void *ptr, hwaddr reg,
DPRINTF("xhci: bad doorbell %d write: 0x%x\n",
(int)reg, (uint32_t)val);
} else {
xhci_kick_ep(xhci, reg, epid, streamid);
xhci_kick_ep(xhci, reg, epid, streamid, true);
}
}
}
@@ -3395,7 +3598,7 @@ static void xhci_wakeup_endpoint(USBBus *bus, USBEndpoint *ep,
return;
}
prev_engaged = xhci_engage_reentrancy_guard(xhci);
xhci_kick_ep(xhci, slotid, xhci_find_epid(ep), stream);
xhci_kick_ep(xhci, slotid, xhci_find_epid(ep), stream, false);
xhci_restore_reentrancy_guard(xhci, prev_engaged);
}
@@ -3420,6 +3623,8 @@ static void usb_xhci_init(XHCIState *xhci)
xhci->numports = xhci->numports_2 + xhci->numports_3;
usb_bus_new(&xhci->bus, sizeof(xhci->bus), &xhci_bus_ops, xhci->hostOpaque);
/* a NAKed isochronous TD waits in epctx->retry for its endpoint's wakeup */
xhci->bus.iso_nak_retry = true;
for (i = 0; i < usbports; i++) {
speedmask = 0;
@@ -3478,6 +3683,12 @@ static void usb_xhci_realize(DeviceState *dev, Error **errp)
usb_xhci_init(xhci);
xhci->mfwrap_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, xhci_mfwrap_timer, xhci);
for (i = 0; i < xhci->numintrs; i++) {
xhci->intr[i].xhci = xhci;
xhci->intr[i].imod_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL,
xhci_imod_timer,
&xhci->intr[i]);
}
memory_region_init(&xhci->mem, OBJECT(dev), "xhci", XHCI_LEN_REGS);
memory_region_init_io(&xhci->mem_cap, OBJECT(dev), &xhci_cap_ops, xhci,
@@ -3519,6 +3730,9 @@ static void usb_xhci_unrealize(DeviceState *dev)
timer_free(xhci->mfwrap_timer);
xhci->mfwrap_timer = NULL;
}
for (i = 0; i < xhci->numintrs; i++) {
g_clear_pointer(&xhci->intr[i].imod_timer, timer_free);
}
memory_region_del_subregion(&xhci->mem, &xhci->mem_cap);
memory_region_del_subregion(&xhci->mem, &xhci->mem_oper);
@@ -3630,9 +3844,32 @@ static bool xhci_er_full(void *opaque, int version_id)
return false;
}
static bool xhci_intr_moderation_needed(void *opaque)
{
XHCIInterrupter *intr = opaque;
return intr->ipe || timer_pending(intr->imod_timer);
}
static const VMStateDescription vmstate_xhci_intr_moderation = {
.name = "xhci-intr/moderation",
.version_id = 1,
.minimum_version_id = 1,
.needed = xhci_intr_moderation_needed,
.fields = (const VMStateField[]) {
VMSTATE_BOOL(ipe, XHCIInterrupter),
VMSTATE_TIMER_PTR(imod_timer, XHCIInterrupter),
VMSTATE_END_OF_LIST()
}
};
static const VMStateDescription vmstate_xhci_intr = {
.name = "xhci-intr",
.version_id = 1,
.subsections = (const VMStateDescription * const []) {
&vmstate_xhci_intr_moderation,
NULL
},
.fields = (const VMStateField[]) {
/* registers */
VMSTATE_UINT32(iman, XHCIInterrupter),
@@ -3662,10 +3899,32 @@ static const VMStateDescription vmstate_xhci_intr = {
}
};
static bool xhci_belt_needed(void *opaque)
{
XHCIState *xhci = opaque;
return xhci->belt != 0;
}
static const VMStateDescription vmstate_xhci_belt = {
.name = "xhci-core/belt",
.version_id = 1,
.minimum_version_id = 1,
.needed = xhci_belt_needed,
.fields = (const VMStateField[]) {
VMSTATE_UINT16(belt, XHCIState),
VMSTATE_END_OF_LIST()
}
};
const VMStateDescription vmstate_xhci = {
.name = "xhci-core",
.version_id = 1,
.post_load = usb_xhci_post_load,
.subsections = (const VMStateDescription * const []) {
&vmstate_xhci_belt,
NULL
},
.fields = (const VMStateField[]) {
VMSTATE_STRUCT_VARRAY_UINT32(ports, XHCIState, numports, 1,
vmstate_xhci_port, XHCIPort),
+15 -1
View File
@@ -150,8 +150,9 @@ typedef struct XHCIEvent {
} XHCIEvent;
typedef struct XHCIInterrupter {
XHCIState *xhci;
uint32_t iman;
uint32_t imod;
uint32_t imod; /* IMODI; IMODC counts down while imod_timer is pending */
uint32_t erstsz;
uint32_t erstba_low;
uint32_t erstba_high;
@@ -160,6 +161,11 @@ typedef struct XHCIInterrupter {
bool msix_used, er_pcs;
/* Interrupt Pending Enable (4.17.5): a non-blocking event awaits */
bool ipe;
/* expires when IMODC reaches 0 (4.17.2) */
QEMUTimer *imod_timer;
dma_addr_t er_start;
uint32_t er_size;
unsigned int er_ep_idx;
@@ -199,6 +205,11 @@ typedef struct XHCIState {
*/
bool (*intr_mapping_supported)(XHCIState *s);
DeviceState *hostOpaque;
/*
* Latency Tolerance Messaging Capability (LTC, 4.13.1), set where the
* host interconnect has an LTR mechanism (PCI Express)
*/
bool ltm;
/* Operational Registers */
uint32_t usbcmd;
@@ -222,6 +233,9 @@ typedef struct XHCIState {
XHCIRing cmd_ring;
/* the BELT of the last Set LTV Command, 0 while none set one */
uint16_t belt;
bool nec_quirks;
} XHCIState;
+433 -31
View File
@@ -52,6 +52,8 @@
#include "qemu/error-report.h"
#include "qemu/main-loop.h"
#include "qemu/module.h"
#include "qemu/thread.h"
#include "block/thread-pool.h"
#include "system/runstate.h"
#include "system/system.h"
#include "trace.h"
@@ -67,6 +69,8 @@ OBJECT_DECLARE_SIMPLE_TYPE(USBHostDevice, USB_HOST_DEVICE)
typedef struct USBHostRequest USBHostRequest;
typedef struct USBHostIsoXfer USBHostIsoXfer;
typedef struct USBHostIsoRing USBHostIsoRing;
typedef struct USBHostSetIntf USBHostSetIntf;
typedef struct USBHostDeferred USBHostDeferred;
typedef struct libusb_config_descriptor libusb_config_descriptor;
G_DEFINE_AUTOPTR_CLEANUP_FUNC(libusb_config_descriptor,
@@ -97,6 +101,7 @@ struct USBHostDevice {
uint32_t loglevel;
bool allow_one_guest_reset;
bool allow_all_guest_resets;
bool reset_on_close;
bool suppress_remote_wake;
/* state */
@@ -116,6 +121,9 @@ struct USBHostDevice {
bool claimed;
} ifs[USB_MAX_INTERFACES];
/* bInterval of each endpoint of the current settings, [in][number] */
uint8_t ep_interval[2][USB_MAX_ENDPOINTS + 1];
/* callbacks & friends */
QEMUBH *bh_nodev;
QEMUBH *bh_postld;
@@ -125,6 +133,15 @@ struct USBHostDevice {
/* request queues */
QTAILQ_HEAD(, USBHostRequest) requests;
QTAILQ_HEAD(, USBHostIsoRing) isorings;
/* the SET_INTERFACE request a worker thread carries out, if any */
USBHostSetIntf *setintf;
/*
* Set from the start of that request until the submits and cancels that
* waited for it have been made, in their order, from deferred.
*/
bool deferring;
QSIMPLEQ_HEAD(, USBHostDeferred) deferred;
};
struct USBHostRequest {
@@ -139,6 +156,38 @@ struct USBHostRequest {
QTAILQ_ENTRY(USBHostRequest) next;
};
/*
* libusb_set_interface_alt_setting() is synchronous: the kernel holds the
* device while it kills the interface's transfers, sends SET_INTERFACE and
* reconfigures the host controller's endpoints. A worker thread makes the call,
* so QEMU's main loop and vCPUs keep running; the guest's control transfer
* completes when the call returns.
*
* Linux's usbfs takes the same lock of the device for each of its ioctls,
* so the main loop makes none on the device until the call returns: it
* handles no libusb events, where libusb reaps the completed URBs of every
* device it has any for (usb_host_events_pause), and the device's submits and
* cancels wait in its deferred queue (usb_host_submit, usb_host_cancel),
* which runs in order as the call returns.
*/
struct USBHostSetIntf {
USBHostDevice *host;
USBPacket *p; /* NULL once the guest canceled it */
libusb_device_handle *dh;
int iface;
int alt;
int rc;
bool finished;
QemuEvent done; /* the worker's call returned */
};
/* A submit, or a cancel, of a transfer that waits for a SET_INTERFACE call */
struct USBHostDeferred {
struct libusb_transfer *xfer;
bool cancel;
QSIMPLEQ_ENTRY(USBHostDeferred) next;
};
struct USBHostIsoXfer {
USBHostIsoRing *ring;
struct libusb_transfer *xfer;
@@ -150,6 +199,12 @@ struct USBHostIsoXfer {
struct USBHostIsoRing {
USBHostDevice *host;
USBEndpoint *ep;
unsigned int nr_xfers;
/* IN: transfers completed before the stream gave the guest data */
unsigned int nr_primed;
bool primed;
/* OUT: a packet waits for a transfer to complete and free its buffer */
bool out_waiting;
QTAILQ_HEAD(, USBHostIsoXfer) unused;
QTAILQ_HEAD(, USBHostIsoXfer) inflight;
QTAILQ_HEAD(, USBHostIsoXfer) copy;
@@ -164,6 +219,7 @@ static void usb_host_release_interfaces(USBHostDevice *s);
static void usb_host_nodev(USBHostDevice *s);
static void usb_host_detach_kernel(USBHostDevice *s);
static void usb_host_attach_kernel(USBHostDevice *s);
static void usb_host_set_interface_wait(USBHostDevice *s);
/* ------------------------------------------------------------------------ */
@@ -239,6 +295,13 @@ static const char *err_names[] = {
static libusb_context *ctx;
static uint32_t loglevel;
/*
* The SET_INTERFACE calls in flight. While there is one, the main loop
* handles no libusb events: the other devices' completions wait for the
* call, as the whole main loop did while it made the call itself.
*/
static unsigned int events_paused;
#ifndef CONFIG_WIN32
static void usb_host_handle_fd(void *opaque)
@@ -249,6 +312,9 @@ static void usb_host_handle_fd(void *opaque)
static void usb_host_add_fd(int fd, short events, void *user_data)
{
if (events_paused) {
return; /* usb_host_events_resume adds it */
}
qemu_set_fd_handler(fd,
(events & POLLIN) ? usb_host_handle_fd : NULL,
(events & POLLOUT) ? usb_host_handle_fd : NULL,
@@ -260,6 +326,22 @@ static void usb_host_del_fd(int fd, void *user_data)
qemu_set_fd_handler(fd, NULL, NULL, NULL);
}
/* Take libusb's fds out of the main loop, or put them back */
static void usb_host_watch_fds(bool watch)
{
const struct libusb_pollfd **poll = libusb_get_pollfds(ctx);
int i;
for (i = 0; poll && poll[i] != NULL; i++) {
if (watch) {
usb_host_add_fd(poll[i]->fd, poll[i]->events, ctx);
} else {
usb_host_del_fd(poll[i]->fd, ctx);
}
}
free(poll);
}
#else
static QEMUTimer *poll_timer;
@@ -279,12 +361,33 @@ static void usb_host_timer(void *opaque)
{
struct timeval tv = { 0, 0 };
libusb_handle_events_timeout(ctx, &tv);
if (!events_paused) {
libusb_handle_events_timeout(ctx, &tv);
}
usb_host_timer_kick();
}
#endif /* !CONFIG_WIN32 */
static void usb_host_events_pause(void)
{
if (events_paused++ == 0) {
#ifndef CONFIG_WIN32
usb_host_watch_fds(false);
#endif
}
}
static void usb_host_events_resume(void)
{
assert(events_paused > 0);
if (--events_paused == 0) {
#ifndef CONFIG_WIN32
usb_host_watch_fds(true);
#endif
}
}
static int usb_host_init(void)
{
#ifndef CONFIG_WIN32
@@ -362,6 +465,126 @@ static void usb_host_libusb_error(const char *func, int rc)
/* ------------------------------------------------------------------------ */
static void usb_host_defer(USBHostDevice *s, struct libusb_transfer *xfer,
bool cancel)
{
USBHostDeferred *d = g_new0(USBHostDeferred, 1);
d->xfer = xfer;
d->cancel = cancel;
QSIMPLEQ_INSERT_TAIL(&s->deferred, d, next);
}
/* Drop what waits in the deferred queue for a transfer that is done */
static void usb_host_undefer(USBHostDevice *s, struct libusb_transfer *xfer)
{
USBHostDeferred *d, *dn;
QSIMPLEQ_FOREACH_SAFE(d, &s->deferred, next, dn) {
if (d->xfer == xfer) {
QSIMPLEQ_REMOVE(&s->deferred, d, USBHostDeferred, next);
g_free(d);
}
}
}
/*
* Complete a transfer that never reached the kernel through its callback, as
* libusb completes one: with status, and nothing transferred.
*/
static void usb_host_xfer_unsent(struct libusb_transfer *xfer,
enum libusb_transfer_status status)
{
int i;
xfer->status = status;
xfer->actual_length = 0;
for (i = 0; i < xfer->num_iso_packets; i++) {
xfer->iso_packet_desc[i].status = status;
xfer->iso_packet_desc[i].actual_length = 0;
}
xfer->callback(xfer);
}
/* libusb_submit_transfer, or its place in the deferred queue */
static int usb_host_submit(USBHostDevice *s, struct libusb_transfer *xfer)
{
if (s->deferring) {
usb_host_defer(s, xfer, false);
return 0;
}
return libusb_submit_transfer(xfer);
}
/*
* libusb_cancel_transfer, or its place in the deferred queue. A transfer
* whose submit still waits there never reaches the kernel: it leaves the
* queue and completes as canceled.
*/
static void usb_host_cancel(USBHostDevice *s, struct libusb_transfer *xfer)
{
USBHostDeferred *d;
if (!s->deferring) {
libusb_cancel_transfer(xfer);
return;
}
QSIMPLEQ_FOREACH(d, &s->deferred, next) {
if (d->xfer == xfer && !d->cancel) {
QSIMPLEQ_REMOVE(&s->deferred, d, USBHostDeferred, next);
g_free(d);
usb_host_xfer_unsent(xfer, LIBUSB_TRANSFER_CANCELLED);
return;
}
}
usb_host_defer(s, xfer, true);
}
/*
* Make the submits and cancels that waited for a SET_INTERFACE call, in their
* order, with whatever a completion here queues behind them. libusb's events
* stay paused meanwhile, so no transfer completes, and none is freed, under a
* cancel that waits. A submit that fails completes its transfer with the
* error, as one that failed in the kernel would, and a cancel of it that
* waits is dropped. A SET_INTERFACE started meanwhile (the guest canceled
* this one) keeps what is left for its own call.
*/
static void usb_host_run_deferred(USBHostDevice *s)
{
USBHostDeferred *d;
struct libusb_transfer *xfer;
bool cancel;
int rc;
while (!s->setintf && (d = QSIMPLEQ_FIRST(&s->deferred)) != NULL) {
QSIMPLEQ_REMOVE_HEAD(&s->deferred, next);
xfer = d->xfer;
cancel = d->cancel;
g_free(d);
if (cancel) {
libusb_cancel_transfer(xfer);
continue;
}
rc = libusb_submit_transfer(xfer);
if (rc == 0) {
continue;
}
usb_host_libusb_error("libusb_submit_transfer [deferred]", rc);
usb_host_undefer(s, xfer);
usb_host_xfer_unsent(xfer, rc == LIBUSB_ERROR_NO_DEVICE ?
LIBUSB_TRANSFER_NO_DEVICE :
LIBUSB_TRANSFER_ERROR);
if (rc == LIBUSB_ERROR_NO_DEVICE) {
usb_host_nodev(s);
}
}
if (!s->setintf) {
s->deferring = false;
}
}
/* ------------------------------------------------------------------------ */
static bool usb_host_use_combining(USBEndpoint *ep)
{
int type;
@@ -407,6 +630,11 @@ static void usb_host_req_free(USBHostRequest *r)
request_count--;
#endif
QTAILQ_REMOVE(&r->host->requests, r, next);
/*
* A cancel can wait for a transfer that completed: one that libusb had
* reaped in the same pass as a SET_INTERFACE request started.
*/
usb_host_undefer(r->host, r->xfer);
libusb_free_transfer(r->xfer);
g_free(r->buffer);
g_free(r);
@@ -519,7 +747,7 @@ static void usb_host_req_abort(USBHostRequest *r)
}
r->p = NULL;
libusb_cancel_transfer(r->xfer);
usb_host_cancel(s, r->xfer);
}
}
@@ -544,28 +772,58 @@ usb_host_req_complete_iso(struct libusb_transfer *transfer)
}
if (xfer->ring->ep->pid == USB_TOKEN_IN) {
QTAILQ_INSERT_TAIL(&xfer->ring->copy, xfer, next);
if (!xfer->ring->primed) {
xfer->ring->nr_primed++;
}
usb_wakeup(xfer->ring->ep, 0);
} else {
QTAILQ_INSERT_TAIL(&xfer->ring->unused, xfer, next);
if (xfer->ring->out_waiting) {
xfer->ring->out_waiting = false;
usb_wakeup(xfer->ring->ep, 0);
}
}
}
/*
* Packets in each transfer of an endpoint's ring: one millisecond of the
* bus, at most isobsize. A high or super speed endpoint is serviced every
* 2^(bInterval-1) microframes, eight to a millisecond, and a full speed one
* every 2^(bInterval-1) frames, one to a millisecond; an endpoint serviced
* less often than every millisecond gets one packet a transfer.
*/
static unsigned int usb_host_iso_xfer_packets(USBHostDevice *s,
USBEndpoint *ep)
{
USBDevice *udev = USB_DEVICE(s);
unsigned int interval, packets = 1;
if (udev->speed >= USB_SPEED_HIGH) {
interval = s->ep_interval[ep->pid == USB_TOKEN_IN][ep->nr];
interval = MIN(MAX(interval, 1), 4);
packets = 8 >> (interval - 1);
}
return MAX(MIN(packets, s->iso_urb_frames), 1);
}
static USBHostIsoRing *usb_host_iso_alloc(USBHostDevice *s, USBEndpoint *ep)
{
USBHostIsoRing *ring = g_new0(USBHostIsoRing, 1);
USBHostIsoXfer *xfer;
/* FIXME: check interval (for now assume one xfer per frame) */
int packets = s->iso_urb_frames;
int i;
unsigned int packets = usb_host_iso_xfer_packets(s, ep);
unsigned int i;
ring->host = s;
ring->ep = ep;
/* the ring holds isobufs * isobsize packets in all */
ring->nr_xfers = MAX(DIV_ROUND_UP(s->iso_urb_count * s->iso_urb_frames,
packets), 1);
QTAILQ_INIT(&ring->unused);
QTAILQ_INIT(&ring->inflight);
QTAILQ_INIT(&ring->copy);
QTAILQ_INSERT_TAIL(&s->isorings, ring, next);
for (i = 0; i < s->iso_urb_count; i++) {
for (i = 0; i < ring->nr_xfers; i++) {
xfer = g_new0(USBHostIsoXfer, 1);
xfer->ring = ring;
xfer->xfer = libusb_alloc_transfer(packets);
@@ -681,6 +939,7 @@ static void usb_host_iso_data_in(USBHostDevice *s, USBPacket *p)
USBHostIsoRing *ring;
USBHostIsoXfer *xfer;
bool disconnect = false;
bool hold = false;
int rc;
ring = usb_host_iso_find(s, p->ep);
@@ -688,8 +947,29 @@ static void usb_host_iso_data_in(USBHostDevice *s, USBPacket *p)
ring = usb_host_iso_alloc(s, p->ep);
}
/*
* A device sends a packet at each of its endpoint's service intervals
* from the first, but the host's transfers bring them only as each
* completes. Until two have, a controller that retries a NAKed packet
* holds the guest's first packet, and the stream starts a transfer of
* data ahead of the guest; other controllers get empty packets.
*/
if (!ring->primed) {
ring->primed = ring->nr_primed >= MIN(2, ring->nr_xfers) ||
!usb_bus_from_device(USB_DEVICE(s))->iso_nak_retry;
hold = !ring->primed;
}
/* copy data to guest */
xfer = QTAILQ_FIRST(&ring->copy);
xfer = hold ? NULL : QTAILQ_FIRST(&ring->copy);
if (xfer == NULL && usb_bus_from_device(USB_DEVICE(s))->iso_nak_retry) {
/*
* The guest has caught up with the device: QEMU ran its packets
* late, or ran them before handling transfers that had completed
* meanwhile. The device's packet is on its way; wait for it.
*/
hold = true;
}
if (xfer != NULL) {
if (usb_host_iso_data_copy(xfer, p)) {
QTAILQ_REMOVE(&ring->copy, xfer, next);
@@ -701,7 +981,7 @@ static void usb_host_iso_data_in(USBHostDevice *s, USBPacket *p)
while ((xfer = QTAILQ_FIRST(&ring->unused)) != NULL) {
QTAILQ_REMOVE(&ring->unused, xfer, next);
usb_host_iso_reset_xfer(xfer);
rc = libusb_submit_transfer(xfer->xfer);
rc = usb_host_submit(s, xfer->xfer);
if (rc != 0) {
usb_host_libusb_error("libusb_submit_transfer [iso]", rc);
QTAILQ_INSERT_TAIL(&ring->unused, xfer, next);
@@ -716,6 +996,11 @@ static void usb_host_iso_data_in(USBHostDevice *s, USBPacket *p)
QTAILQ_INSERT_TAIL(&ring->inflight, xfer, next);
}
if (hold && !QTAILQ_EMPTY(&ring->inflight)) {
/* usb_host_req_complete_iso wakes the endpoint */
p->status = USB_RET_NAK;
}
if (disconnect) {
usb_host_nodev(s);
}
@@ -743,6 +1028,17 @@ static void usb_host_iso_data_out(USBHostDevice *s, USBPacket *p)
xfer = QTAILQ_FIRST(&ring->unused);
if (xfer == NULL) {
trace_usb_host_iso_out_of_bufs(s->bus_num, s->addr, p->ep->nr);
/*
* Every buffer is on its way to the device. A controller that
* retries a NAKed packet holds this one until a transfer
* completes and wakes the endpoint; other controllers complete
* it with nothing sent.
*/
if (usb_bus_from_device(USB_DEVICE(s))->iso_nak_retry &&
!QTAILQ_EMPTY(&ring->inflight)) {
ring->out_waiting = true;
p->status = USB_RET_NAK;
}
return;
}
QTAILQ_REMOVE(&ring->unused, xfer, next);
@@ -754,7 +1050,7 @@ static void usb_host_iso_data_out(USBHostDevice *s, USBPacket *p)
if (QTAILQ_EMPTY(&ring->inflight)) {
/* wait until half of our buffers are filled
before kicking the iso out stream */
if (filled*2 < s->iso_urb_count) {
if (filled * 2 < ring->nr_xfers) {
return;
}
}
@@ -763,7 +1059,7 @@ static void usb_host_iso_data_out(USBHostDevice *s, USBPacket *p)
while ((xfer = QTAILQ_FIRST(&ring->copy)) != NULL &&
xfer->copy_complete) {
QTAILQ_REMOVE(&ring->copy, xfer, next);
rc = libusb_submit_transfer(xfer->xfer);
rc = usb_host_submit(s, xfer->xfer);
if (rc != 0) {
usb_host_libusb_error("libusb_submit_transfer [iso]", rc);
QTAILQ_INSERT_TAIL(&ring->unused, xfer, next);
@@ -939,6 +1235,7 @@ static void usb_host_ep_update(USBHostDevice *s)
usb_ep_set_max_packet_size(udev, pid, ep,
endp->wMaxPacketSize);
usb_ep_set_type(udev, pid, ep, type);
s->ep_interval[pid == USB_TOKEN_IN][ep] = endp->bInterval;
usb_ep_set_ifnum(udev, pid, ep, intf->bInterfaceNumber);
usb_ep_set_halted(udev, pid, ep, 0);
#ifdef HAVE_STREAMS
@@ -1069,7 +1366,9 @@ fail:
trace_usb_host_open_failure(bus_num, addr);
if (s->dh != NULL) {
usb_host_release_interfaces(s);
libusb_reset_device(s->dh);
if (s->reset_on_close) {
libusb_reset_device(s->dh);
}
usb_host_attach_kernel(s);
libusb_close(s->dh);
s->dh = NULL;
@@ -1080,6 +1379,7 @@ fail:
static void usb_host_abort_xfers(USBHostDevice *s)
{
USBHostDevice *other;
USBHostRequest *r, *rtmp;
int limit = 100;
@@ -1087,6 +1387,16 @@ static void usb_host_abort_xfers(USBHostDevice *s)
usb_host_req_abort(r);
}
if (QTAILQ_FIRST(&s->requests) != NULL) {
/*
* libusb reaps every device's completed URBs below: no other
* device's SET_INTERFACE call may still run, or anything wait for it.
*/
QTAILQ_FOREACH(other, &hostdevs, next) {
usb_host_set_interface_wait(other);
}
}
while (QTAILQ_FIRST(&s->requests) != NULL) {
struct timeval tv;
memset(&tv, 0, sizeof(tv));
@@ -1118,6 +1428,7 @@ static int usb_host_close(USBHostDevice *s)
trace_usb_host_close(s->bus_num, s->addr);
usb_host_set_interface_wait(s);
usb_host_abort_xfers(s);
usb_host_iso_free_all(s);
@@ -1126,7 +1437,9 @@ static int usb_host_close(USBHostDevice *s)
}
usb_host_release_interfaces(s);
libusb_reset_device(s->dh);
if (s->reset_on_close) {
libusb_reset_device(s->dh);
}
usb_host_attach_kernel(s);
libusb_close(s->dh);
s->dh = NULL;
@@ -1161,9 +1474,12 @@ static void usb_host_exit_notifier(struct Notifier *n, void *data)
USBHostDevice *s = container_of(n, USBHostDevice, exit);
if (s->dh) {
usb_host_set_interface_wait(s);
usb_host_abort_xfers(s);
usb_host_release_interfaces(s);
libusb_reset_device(s->dh);
if (s->reset_on_close) {
libusb_reset_device(s->dh);
}
usb_host_attach_kernel(s);
libusb_close(s->dh);
}
@@ -1215,6 +1531,7 @@ static void usb_host_realize(USBDevice *udev, Error **errp)
udev->auto_attach = 0;
QTAILQ_INIT(&s->requests);
QTAILQ_INIT(&s->isorings);
QSIMPLEQ_INIT(&s->deferred);
s->hostfd = -1;
#if LIBUSB_API_VERSION >= 0x01000107 && !defined(CONFIG_WIN32)
@@ -1304,10 +1621,15 @@ static void usb_host_cancel_packet(USBDevice *udev, USBPacket *p)
trace_usb_host_req_canceled(s->bus_num, s->addr, p);
if (s->setintf && s->setintf->p == p) {
s->setintf->p = NULL; /* the call still runs, and its result applies */
return;
}
r = usb_host_req_find(s, p);
if (r && r->p) {
r->p = NULL; /* mark as dead */
libusb_cancel_transfer(r->xfer);
usb_host_cancel(s, r->xfer);
}
}
@@ -1449,11 +1771,79 @@ static void usb_host_set_config(USBHostDevice *s, int config, USBPacket *p)
usb_host_ep_update(s);
}
static int usb_host_set_interface_worker(void *opaque)
{
USBHostSetIntf *job = opaque;
job->rc = libusb_set_interface_alt_setting(job->dh, job->iface, job->alt);
qemu_event_set(&job->done);
return 0;
}
/* Apply what the worker's call did, and complete the guest's request */
static void usb_host_set_interface_finish(USBHostSetIntf *job)
{
USBHostDevice *s = job->host;
USBDevice *udev = USB_DEVICE(s);
USBPacket *p = job->p;
assert(s->setintf == job && !job->finished);
s->setintf = NULL;
job->finished = true;
trace_usb_host_set_interface_done(s->bus_num, s->addr, job->iface,
job->alt, job->rc);
if (job->rc == 0) {
udev->altsetting[job->iface] = job->alt;
usb_host_ep_update(s);
} else {
usb_host_libusb_error("libusb_set_interface_alt_setting", job->rc);
}
/* what waited for the call, then libusb's events, whatever rc is */
usb_host_run_deferred(s);
usb_host_events_resume();
if (p) {
p->status = job->rc == 0 ? USB_RET_SUCCESS : USB_RET_STALL;
trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
usb_generic_async_ctrl_complete(udev, p);
}
if (job->rc == LIBUSB_ERROR_NO_DEVICE) {
usb_host_nodev(s);
}
}
static void usb_host_set_interface_complete(void *opaque, int ret)
{
USBHostSetIntf *job = opaque;
if (!job->finished) {
usb_host_set_interface_finish(job);
}
qemu_event_destroy(&job->done);
g_free(job);
}
/*
* Wait for the SET_INTERFACE request in flight, if any, and apply it, and make
* the submits and cancels that waited for it, before anything else changes
* the device's state or closes its handle.
*/
static void usb_host_set_interface_wait(USBHostDevice *s)
{
USBHostSetIntf *job = s->setintf;
if (job) {
qemu_event_wait(&job->done);
usb_host_set_interface_finish(job);
} else if (s->deferring) {
usb_host_run_deferred(s); /* from a completion that run made */
}
}
static void usb_host_set_interface(USBHostDevice *s, int iface, int alt,
USBPacket *p)
{
USBDevice *udev = USB_DEVICE(s);
int rc;
USBHostSetIntf *job;
trace_usb_host_set_interface(s->bus_num, s->addr, iface, alt);
@@ -1461,21 +1851,23 @@ static void usb_host_set_interface(USBHostDevice *s, int iface, int alt,
if (iface >= USB_MAX_INTERFACES) {
p->status = USB_RET_STALL;
trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
return;
}
rc = libusb_set_interface_alt_setting(s->dh, iface, alt);
if (rc != 0) {
usb_host_libusb_error("libusb_set_interface_alt_setting", rc);
p->status = USB_RET_STALL;
if (rc == LIBUSB_ERROR_NO_DEVICE) {
usb_host_nodev(s);
}
return;
}
udev->altsetting[iface] = alt;
usb_host_ep_update(s);
job = g_new0(USBHostSetIntf, 1);
job->host = s;
job->p = p;
job->dh = s->dh;
job->iface = iface;
job->alt = alt;
qemu_event_init(&job->done, false);
s->setintf = job;
s->deferring = true;
usb_host_events_pause();
thread_pool_submit_aio(usb_host_set_interface_worker, job,
usb_host_set_interface_complete, job);
p->status = USB_RET_ASYNC;
}
static void usb_host_handle_control(USBDevice *udev, USBPacket *p,
@@ -1494,6 +1886,12 @@ static void usb_host_handle_control(USBDevice *udev, USBPacket *p,
return;
}
/*
* Control requests reach the device in the guest's order. One waits here
* only when the guest canceled a SET_INTERFACE that still runs.
*/
usb_host_set_interface_wait(s);
switch (request) {
case DeviceOutRequest | USB_REQ_SET_ADDRESS:
usb_host_set_address(s, value);
@@ -1507,7 +1905,6 @@ static void usb_host_handle_control(USBDevice *udev, USBPacket *p,
case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
usb_host_set_interface(s, index, value, p);
trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
return;
case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:
@@ -1539,7 +1936,7 @@ static void usb_host_handle_control(USBDevice *udev, USBPacket *p,
libusb_fill_control_transfer(r->xfer, s->dh, r->buffer,
usb_host_req_complete_ctrl, r,
CONTROL_TIMEOUT);
rc = libusb_submit_transfer(r->xfer);
rc = usb_host_submit(s, r->xfer);
if (rc != 0) {
/*
* Free the request to avoid a dangling r->p pointer.
@@ -1640,7 +2037,7 @@ static void usb_host_handle_data(USBDevice *udev, USBPacket *p)
return;
}
rc = libusb_submit_transfer(r->xfer);
rc = usb_host_submit(s, r->xfer);
if (rc != 0) {
/*
* Free the request to avoid a dangling r->p pointer.
@@ -1682,6 +2079,7 @@ static void usb_host_handle_reset(USBDevice *udev)
trace_usb_host_reset(s->bus_num, s->addr);
usb_host_set_interface_wait(s);
rc = libusb_reset_device(s->dh);
if (rc != 0) {
usb_host_nodev(s);
@@ -1696,6 +2094,7 @@ static int usb_host_alloc_streams(USBDevice *udev, USBEndpoint **eps,
unsigned char endpoints[30];
int i, rc;
usb_host_set_interface_wait(s);
for (i = 0; i < nr_eps; i++) {
endpoints[i] = eps[i]->nr;
if (eps[i]->pid == USB_TOKEN_IN) {
@@ -1725,6 +2124,7 @@ static void usb_host_free_streams(USBDevice *udev, USBEndpoint **eps,
unsigned char endpoints[30];
int i;
usb_host_set_interface_wait(s);
for (i = 0; i < nr_eps; i++) {
endpoints[i] = eps[i]->nr;
if (eps[i]->pid == USB_TOKEN_IN) {
@@ -1805,6 +2205,8 @@ static const Property usb_host_dev_properties[] = {
allow_one_guest_reset, true),
DEFINE_PROP_BOOL("guest-resets-all", USBHostDevice,
allow_all_guest_resets, false),
DEFINE_PROP_BOOL("reset-on-close", USBHostDevice,
reset_on_close, true),
DEFINE_PROP_UINT32("loglevel", USBHostDevice, loglevel,
LIBUSB_LOG_LEVEL_WARNING),
DEFINE_PROP_BIT("pipeline", USBHostDevice, options,
+1
View File
@@ -38,6 +38,7 @@ system_ss.add(when: 'CONFIG_XLNX_USB_SUBSYS', if_true: files('xlnx-usb-subsystem
system_ss.add(when: 'CONFIG_USB_HUB', if_true: files('dev-hub.c'))
system_ss.add(when: 'CONFIG_USB_HID', if_true: files('dev-hid.c'))
system_ss.add(when: 'CONFIG_USB_TABLET_WACOM', if_true: files('dev-wacom.c'))
system_ss.add(when: 'CONFIG_USB_TABLET_VMAPPLE', if_true: files('dev-vmapple-tablet.c'))
system_ss.add(when: 'CONFIG_USB_STORAGE_CORE', if_true: files('dev-storage.c'))
system_ss.add(when: 'CONFIG_USB_STORAGE_BOT', if_true: files('dev-storage-bot.c'))
system_ss.add(when: 'CONFIG_USB_STORAGE_CLASSIC', if_true: files('dev-storage-classic.c'))
+9
View File
@@ -162,6 +162,8 @@ usb_xhci_doorbell_read(uint32_t off, uint32_t val) "off 0x%04x, ret 0x%08x"
usb_xhci_oper_write(uint32_t off, uint32_t val) "off 0x%04x, val 0x%08x"
usb_xhci_port_write(uint32_t port, uint32_t off, uint32_t val) "port %d, off 0x%04x, val 0x%08x"
usb_xhci_runtime_write(uint32_t off, uint32_t val) "off 0x%04x, val 0x%08x"
usb_xhci_imod(int v, uint32_t imodi, uint32_t imodc) "intr %d, imodi %u, imodc %u"
usb_xhci_set_ltv(uint32_t belt) "belt 0x%03x"
usb_xhci_doorbell_write(uint32_t off, uint32_t val) "off 0x%04x, val 0x%08x"
usb_xhci_irq_intx(uint32_t level) "level %d"
usb_xhci_irq_msi(uint32_t nr) "nr %d"
@@ -332,6 +334,7 @@ usb_host_detach_kernel(int bus, int addr, int interface) "dev %d:%d, if %d"
usb_host_set_address(int bus, int addr, int config) "dev %d:%d, address %d"
usb_host_set_config(int bus, int addr, int config) "dev %d:%d, config %d"
usb_host_set_interface(int bus, int addr, int interface, int alt) "dev %d:%d, interface %d, alt %d"
usb_host_set_interface_done(int bus, int addr, int interface, int alt, int rc) "dev %d:%d, interface %d, alt %d, rc %d"
usb_host_claim_interface(int bus, int addr, int config, int interface) "dev %d:%d, config %d, if %d"
usb_host_release_interface(int bus, int addr, int interface) "dev %d:%d, if %d"
usb_host_req_control(int bus, int addr, void *p, int req, int value, int index) "dev %d:%d, packet %p, req 0x%x, value %d, index %d"
@@ -395,3 +398,9 @@ aspeed_udc_handle_data(int ep_nr, const char *dir, uint32_t iov, int ep_idx) "ep
aspeed_udc_ep_data_in(unsigned ep, uint32_t rptr, uint32_t wptr, uint32_t iov) "ep %u, rptr %u, wptr %u, iov %u"
aspeed_udc_ep_data_out(unsigned ep, uint32_t wptr, uint32_t avail, uint32_t iov) "ep %u, wptr %u, avail %u, iov %u"
aspeed_udc_ep_ack(unsigned ep) "ep %u"
# dev-vmapple-tablet.c
usb_vmapple_tablet_report(uint8_t buttons, uint16_t x, uint16_t y, int16_t wheel, int16_t pan, int32_t scroll_y, int32_t scroll_x, uint16_t phases) "buttons 0x%x x %u y %u wheel %d pan %d scroll y %d x %d phases 0x%x"
usb_vmapple_tablet_queue_full(void) "queue full"
usb_vmapple_tablet_get_report(uint8_t type, uint8_t id) "type %u id %u"
usb_vmapple_tablet_set_report(uint8_t id, uint8_t value) "feature %u value %u"
+25
View File
@@ -36,9 +36,12 @@ DECLARE_INSTANCE_CHECKER(VirtIONetPCI, VIRTIO_NET_PCI,
struct VirtIONetPCI {
VirtIOPCIProxy parent_obj;
VirtIONet vdev;
bool ascending_capabilities;
};
static const Property virtio_net_properties[] = {
DEFINE_PROP_BOOL("x-ascending-capabilities", VirtIONetPCI,
ascending_capabilities, false),
DEFINE_PROP_BIT("ioeventfd", VirtIOPCIProxy, flags,
VIRTIO_PCI_FLAG_USE_IOEVENTFD_BIT, true),
DEFINE_PROP_UINT32("vectors", VirtIOPCIProxy, nvectors,
@@ -61,6 +64,28 @@ static void virtio_net_pci_realize(VirtIOPCIProxy *vpci_dev, Error **errp)
virtio_net_set_netclient_name(&dev->vdev, qdev->id,
object_get_typename(OBJECT(qdev)));
qdev_realize(vdev, BUS(&vpci_dev->bus), errp);
if (dev->ascending_capabilities && qdev_is_realized(vdev)) {
uint8_t *config = vpci_dev->pci_dev.config;
bool capabilities[PCI_CONFIG_SPACE_SIZE] = { false };
unsigned offset, previous = PCI_CAPABILITY_LIST;
/* Local Golden Gate workaround: its cached and fallback capability
* lookups revisit PCI_CFG and NOTIFY forever on descending lists.
* Keep capability contents and offsets; only reorder the links. */
for (offset = config[PCI_CAPABILITY_LIST]; offset;
offset = config[offset + PCI_CAP_LIST_NEXT]) {
capabilities[offset] = true;
}
for (offset = PCI_CONFIG_HEADER_SIZE; offset < PCI_CONFIG_SPACE_SIZE;
offset++) {
if (capabilities[offset]) {
config[previous] = offset;
previous = offset + PCI_CAP_LIST_NEXT;
}
}
config[previous] = 0;
}
}
static void virtio_net_pci_class_init(ObjectClass *klass, const void *data)
+8 -4
View File
@@ -9,14 +9,17 @@ config VMAPPLE_BDIF
config VMAPPLE_CFG
bool
config VMAPPLE_RTC
bool
config VMAPPLE_VIRTIO_BLK
bool
config VMAPPLE
bool
depends on ARM
depends on HVF
default y if ARM
depends on AARCH64
depends on TCG || HVF
default y
imply PCI_DEVICES
select ARM_GICV3
select PLATFORM_BUS
@@ -26,8 +29,9 @@ config VMAPPLE
select PL031 # RTC
select PL061 # GPIO
select PVPANIC_MMIO
select UNIMP
select VMAPPLE_AES
select VMAPPLE_BDIF
select VMAPPLE_CFG
select MAC_PVG_MMIO
select VMAPPLE_RTC
select VMAPPLE_VIRTIO_BLK
+56 -1
View File
@@ -18,6 +18,7 @@
#include "hw/core/sysbus.h"
#include "hw/vmapple/vmapple.h"
#include "migration/vmstate.h"
#include "qapi/error.h"
#include "qemu/cutils.h"
#include "qemu/log.h"
#include "qemu/module.h"
@@ -253,7 +254,7 @@ static bool cmd_iv(AESState *s)
static void dump_data(const char *desc, const void *p, size_t len)
{
static const size_t MAX_LEN = 0x1000;
#define MAX_LEN 0x1000
char hex[MAX_LEN * 2 + 1] = "";
if (len > MAX_LEN) {
@@ -262,6 +263,7 @@ static void dump_data(const char *desc, const void *p, size_t len)
qemu_hexdump_to_buffer(hex, sizeof(hex), p, len);
trace_aes_dump_data(desc, hex);
#undef MAX_LEN
}
static bool cmd_data(AESState *s)
@@ -535,6 +537,16 @@ static const MemoryRegionOps aes2_ops = {
},
};
/*
* A guest reboot resets the engine as it was at power-on, with its FIFO,
* keys, IVs and mode, and lowers its interrupt. 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, which the engine then fails as
* invalid (REG_IRQ_STATUS_INVALID_CMD), and macOS panics on that
* ("AES Error: IntStatus 0x4"). The interrupt line keeps its level across
* a reset unless the device lowers it, and an in-kernel GIC (HVF's, KVM's)
* then raises the line's interrupt in the next boot.
*/
static void aes_reset(Object *obj, ResetType type)
{
AESState *s = APPLE_AES(obj);
@@ -544,6 +556,14 @@ static void aes_reset(Object *obj, ResetType type)
s->irq_status = 0;
s->irq_enable = 0;
s->watermark = 0;
s->flag_info = 0;
memset(s->fifo, 0, sizeof(s->fifo));
s->fifo_idx = 0;
memset(s->key, 0, sizeof(s->key));
memset(s->iv, 0, sizeof(s->iv));
s->is_encrypt = false;
s->block_mode = QCRYPTO_CIPHER_MODE_ECB;
aes_update_irq(s);
}
static void aes_init(Object *obj)
@@ -558,10 +578,45 @@ static void aes_init(Object *obj)
s->as = &address_space_memory;
}
/*
* The guest's DATA commands run on QEMU's ciphers. A build that found no
* crypto library (gnutls, nettle or libgcrypt) has none: each DATA command
* then fails, stays at the head of the FIFO, and the guest waits for it
* forever. A macOS guest sends one as it mounts its root volume, so refuse
* to start rather than hang there.
*/
static void aes_realize(DeviceState *dev, Error **errp)
{
static const QCryptoCipherAlgo algs[] = {
QCRYPTO_CIPHER_ALGO_AES_128,
QCRYPTO_CIPHER_ALGO_AES_192,
QCRYPTO_CIPHER_ALGO_AES_256,
};
static const QCryptoCipherMode modes[] = {
QCRYPTO_CIPHER_MODE_ECB,
QCRYPTO_CIPHER_MODE_CBC,
};
for (size_t a = 0; a < ARRAY_SIZE(algs); a++) {
for (size_t m = 0; m < ARRAY_SIZE(modes); m++) {
if (!qcrypto_cipher_supports(algs[a], modes[m])) {
error_setg(errp, "%s needs %s in %s mode, which this QEMU "
"lacks: build it with a crypto library (gnutls, "
"nettle or libgcrypt)", TYPE_APPLE_AES,
QCryptoCipherAlgo_str(algs[a]),
QCryptoCipherMode_str(modes[m]));
return;
}
}
}
}
static void aes_class_init(ObjectClass *klass, const void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
ResettableClass *rc = RESETTABLE_CLASS(klass);
dc->realize = aes_realize;
rc->phases.hold = aes_reset;
}
+7 -7
View File
@@ -46,13 +46,13 @@ typedef struct VMAppleCfg {
uint8_t pad4[2];
uint8_t reserved[0xa0]; /* 0x060 */
uint32_t cpu_ids[0x80]; /* 0x100 */
uint8_t scratch[0x200]; /* 0x180 */
char serial[32]; /* 0x380 */
char unk8[32]; /* 0x3a0 */
char model[32]; /* 0x3c0 */
uint8_t unk9[32]; /* 0x3e0 */
uint32_t unk10; /* 0x400 */
char soc_name[32]; /* 0x404 */
uint8_t scratch[0x200]; /* 0x300 */
char serial[32]; /* 0x500 */
char unk8[32]; /* 0x520 */
char model[32]; /* 0x540 */
uint8_t unk9[32]; /* 0x560 */
uint32_t unk10; /* 0x580 */
char soc_name[32]; /* 0x584 */
} VMAppleCfg;
struct VMAppleCfgState {
+1
View File
@@ -3,5 +3,6 @@
system_ss.add(when: 'CONFIG_VMAPPLE_AES', if_true: files('aes.c'))
system_ss.add(when: 'CONFIG_VMAPPLE_BDIF', if_true: files('bdif.c'))
system_ss.add(when: 'CONFIG_VMAPPLE_CFG', if_true: files('cfg.c'))
system_ss.add(when: 'CONFIG_VMAPPLE_RTC', if_true: files('rtc.c'))
system_ss.add(when: 'CONFIG_VMAPPLE_VIRTIO_BLK', if_true: files('virtio-blk.c'))
specific_ss.add(when: 'CONFIG_VMAPPLE', if_true: files('vmapple.c'))
+196
View File
@@ -0,0 +1,196 @@
/*
* VMApple RTC
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
/*
* Beside its PL031, Virtualization.framework's machine has a clock that the
* guest's device tree lists as avp-rtc ("avp,rtc"), and that macOS drives
* with its AppleVirtualPlatformRTC driver. The driver reads the device's
* counter of microseconds and keeps the offset from it to calendar time in
* NVRAM, as com.apple.System.rtc-offset, which it sets whenever the guest
* sets its clock. It gives that offset to userspace as
* kern.monotoniclock_offset_usecs, from which timed tells whether the clock
* was reset. macOS's PL031 driver has no offset, so on the PL031 alone timed
* takes the clock for reset on every boot, and sets it back to the last
* write to the guest's filesystem.
*
* The counter counts microseconds of QEMU's rtc clock from the Unix epoch,
* as the PL031 counts seconds, so -rtc base= and clock= apply to both. The
* driver uses 64-bit accesses; the registers are:
*
* 0x00 COUNTER read only, the counter
* 0x18 CTRL bit 0 enables the clock; reads back what was written
* 0x20 INT_EN interrupt enables; reads back what was written
* 0x30 INT_STAT pending interrupts; always 0
* 0x38 INT_CLR write ones to clear pending interrupts
* 0x40 ID reads 0xf001
*
* The driver passes interrupts 1 and 2 on to its user clients. Nothing here
* raises them, so the device has no interrupt line. iBoot keeps avp-rtc in
* the device tree and drops pl031-rtc when ID reads 0xf001, and the reverse
* otherwise.
*/
#include "qemu/osdep.h"
#include "trace.h"
#include "hw/core/sysbus.h"
#include "hw/vmapple/vmapple.h"
#include "qemu/bitops.h"
#include "qemu/cutils.h"
#include "qemu/log.h"
#include "qemu/module.h"
#include "qemu/timer.h"
#include "system/rtc.h"
#include "system/system.h"
OBJECT_DECLARE_SIMPLE_TYPE(VMAppleRTCState, VMAPPLE_RTC)
#define VMAPPLE_RTC_SIZE 0x1000
#define REG_COUNTER 0x00
#define REG_CTRL 0x18
#define REG_INT_EN 0x20
#define REG_INT_STAT 0x30
#define REG_INT_CLR 0x38
#define REG_ID 0x40
#define VMAPPLE_RTC_ID 0xf001
struct VMAppleRTCState {
SysBusDevice parent_obj;
MemoryRegion iomem;
/* Seconds from the rtc clock to the guest's time, as the PL031 keeps */
int64_t tick_offset;
uint64_t ctrl;
uint64_t int_en;
};
static uint64_t vmapple_rtc_usecs(VMAppleRTCState *s)
{
int64_t now = qemu_clock_get_ns(rtc_clock);
return (s->tick_offset * NANOSECONDS_PER_SECOND + now) / SCALE_US;
}
static uint64_t vmapple_rtc_reg(VMAppleRTCState *s, hwaddr reg)
{
switch (reg) {
case REG_COUNTER:
return vmapple_rtc_usecs(s);
case REG_CTRL:
return s->ctrl;
case REG_INT_EN:
return s->int_en;
case REG_INT_STAT:
case REG_INT_CLR:
return 0;
case REG_ID:
return VMAPPLE_RTC_ID;
default:
qemu_log_mask(LOG_UNIMP, "%s: unknown register 0x%" HWADDR_PRIx "\n",
__func__, reg);
return 0;
}
}
static uint64_t vmapple_rtc_read(void *opaque, hwaddr offset, unsigned size)
{
VMAppleRTCState *s = opaque;
unsigned shift = (offset & 7) * BITS_PER_BYTE;
uint64_t val;
val = extract64(vmapple_rtc_reg(s, offset & ~7ULL), shift,
size * BITS_PER_BYTE);
trace_vmapple_rtc_read(offset, size, val);
return val;
}
static void vmapple_rtc_write(void *opaque, hwaddr offset, uint64_t val,
unsigned size)
{
VMAppleRTCState *s = opaque;
unsigned shift = (offset & 7) * BITS_PER_BYTE;
unsigned len = size * BITS_PER_BYTE;
trace_vmapple_rtc_write(offset, size, val);
switch (offset & ~7ULL) {
case REG_CTRL:
s->ctrl = deposit64(s->ctrl, shift, len, val);
break;
case REG_INT_EN:
s->int_en = deposit64(s->int_en, shift, len, val);
break;
case REG_INT_CLR:
/* No interrupt is ever pending. */
break;
default:
qemu_log_mask(LOG_GUEST_ERROR,
"%s: write to read-only or unknown register 0x%"
HWADDR_PRIx "\n", __func__, offset);
break;
}
}
static const MemoryRegionOps vmapple_rtc_ops = {
.read = vmapple_rtc_read,
.write = vmapple_rtc_write,
.endianness = DEVICE_LITTLE_ENDIAN,
.valid = {
.min_access_size = 4,
.max_access_size = 8,
},
/* Whole, so that the counter's halves come from one reading. */
.impl = {
.min_access_size = 4,
.max_access_size = 8,
},
};
static void vmapple_rtc_reset(Object *obj, ResetType type)
{
VMAppleRTCState *s = VMAPPLE_RTC(obj);
s->ctrl = 0;
s->int_en = 0;
}
static void vmapple_rtc_init(Object *obj)
{
VMAppleRTCState *s = VMAPPLE_RTC(obj);
struct tm tm;
memory_region_init_io(&s->iomem, obj, &vmapple_rtc_ops, s, "vmapple-rtc",
VMAPPLE_RTC_SIZE);
sysbus_init_mmio(SYS_BUS_DEVICE(obj), &s->iomem);
qemu_get_timedate(&tm, 0);
s->tick_offset = mktimegm(&tm) -
qemu_clock_get_ns(rtc_clock) / NANOSECONDS_PER_SECOND;
}
static void vmapple_rtc_class_init(ObjectClass *klass, const void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
ResettableClass *rc = RESETTABLE_CLASS(klass);
dc->desc = "VMApple RTC";
rc->phases.hold = vmapple_rtc_reset;
}
static const TypeInfo vmapple_rtc_info = {
.name = TYPE_VMAPPLE_RTC,
.parent = TYPE_SYS_BUS_DEVICE,
.instance_size = sizeof(VMAppleRTCState),
.instance_init = vmapple_rtc_init,
.class_init = vmapple_rtc_class_init,
};
static void vmapple_rtc_register_types(void)
{
type_register_static(&vmapple_rtc_info);
}
type_init(vmapple_rtc_register_types)
+4
View File
@@ -19,3 +19,7 @@ aes_dump_data(const char *desc, const char *hex) "%s%s"
bdif_read(uint64_t offset, uint32_t size, uint64_t value) "offset=0x%"PRIx64" size=0x%x value=0x%"PRIx64
bdif_write(uint64_t offset, uint32_t size, uint64_t value) "offset=0x%"PRIx64" size=0x%x value=0x%"PRIx64
bdif_vblk_read(const char *dev, uint64_t addr, uint64_t offset, uint32_t len, int r) "dev=%s addr=0x%"PRIx64" off=0x%"PRIx64" size=0x%x r=%d"
# rtc.c
vmapple_rtc_read(uint64_t offset, uint32_t size, uint64_t value) "offset=0x%"PRIx64" size=0x%x value=0x%"PRIx64
vmapple_rtc_write(uint64_t offset, uint32_t size, uint64_t value) "offset=0x%"PRIx64" size=0x%x value=0x%"PRIx64
+39
View File
@@ -16,6 +16,7 @@
*/
#include "qemu/osdep.h"
#include "hw/pci/pci.h"
#include "hw/vmapple/vmapple.h"
#include "hw/virtio/virtio-blk.h"
#include "hw/virtio/virtio-pci.h"
@@ -44,6 +45,8 @@ typedef struct VMAppleVirtIOBlk {
OBJECT_DECLARE_SIMPLE_TYPE(VMAppleVirtIOBlkPCI, VMAPPLE_VIRTIO_BLK_PCI)
#define VIRTIO_BLK_T_APPLE_BARRIER 0x10000
#define VMAPPLE_PCI_VNDR_SIZE 14
#define VMAPPLE_PCI_VNDR_DISABLE_ENCRYPTION 1
static bool vmapple_virtio_blk_handle_unknown_request(VirtIOBlockReq *req,
MultiReqBuffer *mrb,
@@ -125,6 +128,10 @@ static void vmapple_virtio_blk_pci_realize(VirtIOPCIProxy *vpci_dev, Error **err
VMAppleVirtIOBlkPCI *dev = VMAPPLE_VIRTIO_BLK_PCI(vpci_dev);
DeviceState *vdev = DEVICE(&dev->vdev);
VirtIOBlkConf *conf = &dev->vdev.parent_obj.conf;
int offset;
uint8_t capabilities[PCI_CONFIG_SPACE_SIZE] = { 0 };
uint8_t *config = vpci_dev->pci_dev.config;
int previous = PCI_CAPABILITY_LIST;
if (dev->variant == VM_APPLE_VIRTIO_BLK_VARIANT_UNSPECIFIED) {
error_setg(errp, "vmapple virtio block device variant unspecified");
@@ -162,6 +169,38 @@ static void vmapple_virtio_blk_pci_realize(VirtIOPCIProxy *vpci_dev, Error **err
pci_config_set_vendor_id(vpci_dev->pci_dev.config, PCI_VENDOR_ID_APPLE);
pci_config_set_device_id(vpci_dev->pci_dev.config,
PCI_DEVICE_ID_APPLE_VIRTIO_BLK);
pci_set_word(vpci_dev->pci_dev.config + PCI_SUBSYSTEM_ID, 0x1100);
/* A non-FileVault Golden Gate root disk requires Apple's vendor
* capability to advertise that transport encryption is disabled. */
offset = pci_add_capability(&vpci_dev->pci_dev, PCI_CAP_ID_VNDR, 0,
VMAPPLE_PCI_VNDR_SIZE, errp);
if (offset < 0) {
return;
}
pci_set_byte(vpci_dev->pci_dev.config + offset + 2,
VMAPPLE_PCI_VNDR_SIZE);
pci_set_byte(vpci_dev->pci_dev.config + offset + 3, 9);
pci_set_word(vpci_dev->pci_dev.config + offset + 4, PCI_VENDOR_ID_APPLE);
pci_set_byte(vpci_dev->pci_dev.config + offset + 6,
VMAPPLE_PCI_VNDR_DISABLE_ENCRYPTION);
/* Golden Gate's cached capability lookup and its fallback disagree on
* descending lists: the storage probe alternates between the final
* vendor capability and VIRTIO_PCI_CAP_PCI_CFG forever. Keep the same
* capabilities and offsets, but enumerate them in address order. */
for (offset = config[PCI_CAPABILITY_LIST]; offset;
offset = config[offset + PCI_CAP_LIST_NEXT]) {
capabilities[offset] = 1;
}
for (offset = PCI_CONFIG_HEADER_SIZE; offset < PCI_CONFIG_SPACE_SIZE;
offset++) {
if (capabilities[offset]) {
config[previous] = offset;
previous = offset + PCI_CAP_LIST_NEXT;
}
}
config[previous] = 0;
}
static void vmapple_virtio_blk_pci_class_init(ObjectClass *klass,
+281 -27
View File
@@ -36,8 +36,10 @@
#include "hw/intc/arm_gic.h"
#include "hw/intc/arm_gicv3_common.h"
#include "hw/misc/pvpanic.h"
#include "hw/misc/unimp.h"
#include "hw/pci-host/gpex.h"
#include "hw/usb/hcd-xhci-pci.h"
#include "hw/virtio/virtio-net.h"
#include "hw/virtio/virtio-pci.h"
#include "hw/vmapple/vmapple.h"
#include "net/net.h"
@@ -47,11 +49,15 @@
#include "qobject/qlist.h"
#include "standard-headers/linux/input.h"
#include "system/hvf.h"
#include "system/kvm.h"
#include "system/reset.h"
#include "system/runstate.h"
#include "system/system.h"
#include "system/tcg.h"
#include "target/arm/gtimer.h"
#include "target/arm/cpu.h"
#include "target/arm/internals.h"
#include "target/arm/kvm_arm.h"
struct VMAppleMachineState {
MachineState parent;
@@ -68,6 +74,10 @@ struct VMAppleMachineState {
MemoryRegion fw_mr;
MemoryRegion ecam_alias;
uint64_t uuid;
char *tablet;
/* The room past RAM (vmapple_pool_room) */
uint64_t pool_room_base;
uint64_t pool_room_size;
};
#define TYPE_VMAPPLE_MACHINE MACHINE_TYPE_NAME("vmapple")
@@ -76,12 +86,17 @@ OBJECT_DECLARE_SIMPLE_TYPE(VMAppleMachineState, VMAPPLE_MACHINE)
/* Number of external interrupt lines to configure the GIC with */
#define NUM_IRQS 256
/* The most guest physical address bits the machine asks of HVF */
#define VMAPPLE_PHYS_BITS 40
enum {
VMAPPLE_FIRMWARE,
VMAPPLE_CONFIG,
VMAPPLE_DMA_CONFIG,
VMAPPLE_MEM,
VMAPPLE_GIC_DIST,
VMAPPLE_GIC_REDIST,
VMAPPLE_GICV2M,
VMAPPLE_UART,
VMAPPLE_RTC,
VMAPPLE_PCIE,
@@ -89,45 +104,48 @@ enum {
VMAPPLE_PCIE_ECAM,
VMAPPLE_GPIO,
VMAPPLE_PVPANIC,
VMAPPLE_APV_GFX,
VMAPPLE_APV_IOSFC,
VMAPPLE_AES_1,
VMAPPLE_AES_2,
VMAPPLE_BDOOR,
VMAPPLE_AVP_RTC,
VMAPPLE_MEMMAP_LAST,
};
static const MemMapEntry memmap[] = {
[VMAPPLE_FIRMWARE] = { 0x00100000, 0x00100000 },
[VMAPPLE_CONFIG] = { 0x00400000, 0x00010000 },
[VMAPPLE_DMA_CONFIG] = { 0x004ffff8, 0x00000008 },
[VMAPPLE_GIC_DIST] = { 0x10000000, 0x00010000 },
[VMAPPLE_GIC_REDIST] = { 0x10010000, 0x00400000 },
[VMAPPLE_GICV2M] = { 0x1FFF0000, 0x00010000 },
[VMAPPLE_UART] = { 0x20010000, 0x00010000 },
[VMAPPLE_RTC] = { 0x20050000, 0x00001000 },
[VMAPPLE_GPIO] = { 0x20060000, 0x00001000 },
[VMAPPLE_PVPANIC] = { 0x20070000, 0x00000002 },
[VMAPPLE_BDOOR] = { 0x30000000, 0x00200000 },
[VMAPPLE_APV_GFX] = { 0x30200000, 0x00010000 },
[VMAPPLE_APV_IOSFC] = { 0x30210000, 0x00010000 },
[VMAPPLE_AES_1] = { 0x30220000, 0x00004000 },
[VMAPPLE_AES_2] = { 0x30230000, 0x00004000 },
[VMAPPLE_AVP_RTC] = { 0x30240000, 0x00001000 },
[VMAPPLE_PCIE_ECAM] = { 0x40000000, 0x10000000 },
[VMAPPLE_PCIE_MMIO] = { 0x50000000, 0x1fff0000 },
/*
* macOS places every BAR below 4 GiB, aligned to its size, so the
* window runs up to 4 GiB and RAM starts there.
*/
[VMAPPLE_PCIE_MMIO] = { 0x50000000, 0xb0000000 },
/* Actual RAM size depends on configuration */
[VMAPPLE_MEM] = { 0x70000000ULL, GiB},
[VMAPPLE_MEM] = { 0x100000000ULL, GiB},
};
static const int irqmap[] = {
[VMAPPLE_UART] = 1,
[VMAPPLE_RTC] = 2,
[VMAPPLE_GPIO] = 0x5,
[VMAPPLE_APV_IOSFC] = 0x10,
[VMAPPLE_APV_GFX] = 0x11,
[VMAPPLE_AES_1] = 0x12,
[VMAPPLE_PCIE] = 0x20,
[VMAPPLE_GICV2M] = 0x80
};
#define GPEX_NUM_IRQS 16
@@ -165,6 +183,21 @@ static void create_bdif(VMAppleMachineState *vms, MemoryRegion *mem)
sysbus_realize_and_unref(bdif_sb, &error_fatal);
}
/*
* macOS's platform driver reads a register of its configuration by writing
* the physical address of a request to 0x004ffff8, an address its code holds
* rather than one the device tree gives. Virtualization.framework's machine
* answers the request. This machine leaves it unanswered, as an address with
* no device is under HVF, and the driver goes on without the register; under
* TCG the write would be an external abort.
*/
static void create_dma_config(VMAppleMachineState *vms)
{
create_unimplemented_device("vmapple.dma-config",
vms->memmap[VMAPPLE_DMA_CONFIG].base,
vms->memmap[VMAPPLE_DMA_CONFIG].size);
}
static void create_pvpanic(VMAppleMachineState *vms, MemoryRegion *mem)
{
SysBusDevice *pvpanic;
@@ -203,20 +236,6 @@ static bool create_cfg(VMAppleMachineState *vms, MemoryRegion *mem,
return true;
}
static void create_gfx(VMAppleMachineState *vms, MemoryRegion *mem)
{
int irq_gfx = vms->irqmap[VMAPPLE_APV_GFX];
int irq_iosfc = vms->irqmap[VMAPPLE_APV_IOSFC];
SysBusDevice *gfx;
gfx = SYS_BUS_DEVICE(qdev_new("apple-gfx-mmio"));
sysbus_mmio_map(gfx, 0, vms->memmap[VMAPPLE_APV_GFX].base);
sysbus_mmio_map(gfx, 1, vms->memmap[VMAPPLE_APV_IOSFC].base);
sysbus_connect_irq(gfx, 0, qdev_get_gpio_in(vms->gic, irq_gfx));
sysbus_connect_irq(gfx, 1, qdev_get_gpio_in(vms->gic, irq_iosfc));
sysbus_realize_and_unref(gfx, &error_fatal);
}
static void create_aes(VMAppleMachineState *vms, MemoryRegion *mem)
{
int irq = vms->irqmap[VMAPPLE_AES_1];
@@ -285,6 +304,27 @@ static void create_gic(VMAppleMachineState *vms, MemoryRegion *mem)
}
}
#define NUM_GICV2M_SPIS 128
static void create_gicv2m(VMAppleMachineState *vms)
{
int i;
int irq = vms->irqmap[VMAPPLE_GICV2M];
DeviceState *dev;
dev = qdev_new("arm-gicv2m");
qdev_prop_set_uint32(dev, "base-spi", irq);
qdev_prop_set_uint32(dev, "num-spi", NUM_GICV2M_SPIS);
qdev_prop_set_uint32(dev, "macos-compat", 1);
sysbus_realize_and_unref(SYS_BUS_DEVICE(dev), &error_fatal);
sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, vms->memmap[VMAPPLE_GICV2M].base);
for (i = 0; i < NUM_GICV2M_SPIS; i++) {
sysbus_connect_irq(SYS_BUS_DEVICE(dev), i,
qdev_get_gpio_in(vms->gic, irq + i));
}
}
static void create_uart(const VMAppleMachineState *vms, int uart,
MemoryRegion *mem, Chardev *chr)
{
@@ -306,6 +346,13 @@ static void create_rtc(const VMAppleMachineState *vms)
int irq = vms->irqmap[VMAPPLE_RTC];
sysbus_create_simple("pl031", base, qdev_get_gpio_in(vms->gic, irq));
/*
* macOS keeps its clock's offset to calendar time only with the second
* clock, avp-rtc in its device tree, so the guest needs it to keep time
* from one boot to the next.
*/
sysbus_create_simple(TYPE_VMAPPLE_RTC, vms->memmap[VMAPPLE_AVP_RTC].base,
NULL);
}
static DeviceState *gpio_key_dev;
@@ -396,8 +443,8 @@ static void create_pcie(VMAppleMachineState *vms)
&vms->ecam_alias);
/*
* Map the MMIO window from [0x50000000-0x7fff0000] in PCI space into
* system address space at [0x50000000-0x7fff0000].
* Map the MMIO window from [0x50000000-0xffffffff] in PCI space into
* system address space at [0x50000000-0xffffffff].
*/
mmio_alias = g_new0(MemoryRegion, 1);
mmio_reg = sysbus_mmio_get_region(SYS_BUS_DEVICE(dev), 1);
@@ -426,7 +473,9 @@ static void create_pcie(VMAppleMachineState *vms)
usb_bus = USB_BUS(object_resolve_type_unambiguous(TYPE_USB_BUS,
&error_fatal));
usb_create_simple(usb_bus, "usb-kbd");
usb_create_simple(usb_bus, "usb-tablet");
/* The user names the tablet, which may not realize on its own. */
usb_realize_and_unref(USB_DEVICE(qdev_new(vms->tablet)), usb_bus,
&error_fatal);
}
}
@@ -438,6 +487,32 @@ static void vmapple_reset(void *opaque)
cpu_set_pc(first_cpu, base);
}
/*
* The room past RAM that a device may map memory into once the guest runs,
* reims-graphics-pci's Shared pool: from the end of RAM, rounded up to 1 GiB,
* to the end of the guest's physical addresses, in whole GiB. The machine
* places nothing past RAM, and the firmware tells macOS of RAM alone. The
* bits are the CPU's PARange, at most VMAPPLE_PHYS_BITS, which macOS's
* kernel maps; under HVF that is the VM's IPA size
* (vmapple_get_physical_address_range), and under KVM it is at most the
* VM's, KVM's maximum (the machine asks KVM for no other size).
*/
static void vmapple_pool_room(VMAppleMachineState *vms, MachineState *machine)
{
hwaddr base = ROUND_UP(vms->memmap[VMAPPLE_MEM].base + machine->ram_size,
GiB);
unsigned int bits = MIN(VMAPPLE_PHYS_BITS, arm_pamax(ARM_CPU(first_cpu)));
uint64_t end;
bool fixed_ipa;
if (kvm_enabled()) {
bits = MIN(bits, kvm_arm_get_max_vm_ipa_size(machine, &fixed_ipa));
}
end = 1ULL << bits;
vms->pool_room_base = base;
vms->pool_room_size = end > base ? QEMU_ALIGN_DOWN(end - base, GiB) : 0;
}
static void mach_vmapple_init(MachineState *machine)
{
VMAppleMachineState *vms = VMAPPLE_MACHINE(machine);
@@ -453,6 +528,27 @@ static void mach_vmapple_init(MachineState *machine)
possible_cpus = mc->possible_cpu_arch_ids(machine);
assert(possible_cpus->len == max_cpus);
/*
* Under KVM, PSCI is the host kernel's, and the CPUs it powers on start
* on the pointer authentication keys KVM resets them to, not the boot
* CPU's, so cpu-on-copies-pauth-keys (below) would never apply. Have
* KVM pass CPU_ON to QEMU, which starts CPUs with it.
*/
if (kvm_enabled() && smp_cpus > 1) {
kvm_arm_forward_psci_cpu_on(&error_fatal);
}
/*
* macOS's pointer authentication calls, SMCCC 0xC1000000 to 0xC10000FF
* (see cpu-on-copies-pauth-keys below): HVF and TCG answer them
* NOT_SUPPORTED in x0 and change no other register, and macOS takes
* x1 to x3 of some of them as they are. KVM's answer zeroes x1 to x3,
* so answer them in QEMU as the others do.
*/
if (kvm_enabled()) {
kvm_arm_forward_smccc_range(0xc1000000, 0x100, &error_fatal);
}
for (n = 0; n < possible_cpus->len; n++) {
Object *cpu;
CPUState *cs;
@@ -480,6 +576,44 @@ static void mach_vmapple_init(MachineState *machine)
object_property_set_int(cpu, "psci-conduit", QEMU_PSCI_CONDUIT_HVC,
&error_fatal);
/*
* Under KVM: vmapple does not initialize KVM's PMU, and KVM will
* not run a vCPU that has one uninitialized; and macOS's ApplePSCI
* accepts PSCI 1.1, which HVF reports, but not the 1.3 that
* current kernels give by default.
*/
if (kvm_enabled()) {
if (object_property_find(cpu, "pmu")) {
object_property_set_bool(cpu, "pmu", false, &error_fatal);
}
object_property_set_str(cpu, "kvm-psci-version", "1.1",
&error_fatal);
}
/*
* macOS's device tree gives every CPU a 24 MHz timebase, the
* frequency of Apple silicon's system counter, which HVF passes
* through to the guest. Run TCG's counter at that frequency too.
*/
if (tcg_enabled()) {
object_property_set_uint(cpu, "cntfrq", 24 * 1000 * 1000,
&error_fatal);
}
/*
* macOS asks the hypervisor to program its pointer authentication
* keys, through the paravirtualized calls SMCCC 0xC1000000 to
* 0xC1000006. Hypervisor.framework answers them itself, without an
* exit to QEMU, and under TCG QEMU's PSCI code answers them; both
* answer that they are not supported, and program no key: the
* guest runs on the keys each CPU holds. The boot firmware sets
* them on the boot CPU only, so start each CPU the guest powers on
* with the keys of the CPU that powers it on, and all CPUs share
* them.
*/
object_property_set_bool(cpu, "cpu-on-copies-pauth-keys", true,
&error_fatal);
/* Secondary CPUs start in PSCI powered-down state */
if (n > 0) {
object_property_set_bool(cpu, "start-powered-off", true,
@@ -493,12 +627,13 @@ static void mach_vmapple_init(MachineState *machine)
memory_region_add_subregion(sysmem, vms->memmap[VMAPPLE_MEM].base,
machine->ram);
vmapple_pool_room(vms, machine);
create_gic(vms, sysmem);
create_gicv2m(vms);
create_bdif(vms, sysmem);
create_pvpanic(vms, sysmem);
create_aes(vms, sysmem);
create_gfx(vms, sysmem);
create_uart(vms, VMAPPLE_UART, sysmem, serial_hd(0));
create_rtc(vms);
create_pcie(vms);
@@ -507,6 +642,7 @@ static void mach_vmapple_init(MachineState *machine)
vmapple_firmware_init(vms, sysmem);
create_cfg(vms, sysmem, &error_fatal);
create_dma_config(vms);
/* connect powerdown request */
vms->powerdown_notifier.notify = vmapple_powerdown_req;
@@ -561,6 +697,39 @@ static const CPUArchIdList *vmapple_possible_cpu_arch_ids(MachineState *ms)
return ms->possible_cpus;
}
/*
* The guest's physical address bits under HVF: VMAPPLE_PHYS_BITS, or the
* most the hypervisor gives where that is fewer. HVF's default is 36 bits,
* 64 GiB, which RAM from 4 GiB fills quickly; macOS's kernel maps physical
* addresses of up to 40 bits (its TCR_EL1.IPS), so the guest reaches all of
* a 40-bit space. HVF gives the guest the size chosen as its
* ID_AA64MMFR0_EL1.PARange. Fails, as virt's does, where RAM ends past the
* bits the hypervisor gives.
*/
static int vmapple_get_physical_address_range(MachineState *ms,
int default_ipa_size,
int max_ipa_size)
{
hwaddr ram_end = memmap[VMAPPLE_MEM].base + ms->ram_size;
int bits = MIN(VMAPPLE_PHYS_BITS, max_ipa_size);
if (ram_end > 1ULL << bits) {
error_report("vmapple: RAM ending at 0x%" HWADDR_PRIx " needs more "
"than the %d bits of guest physical address the "
"hypervisor gives", ram_end, bits);
return -1;
}
return bits;
}
static bool vmapple_get_vgic_bases(const MachineState *ms,
uint64_t *dist_base, uint64_t *redist_base)
{
*dist_base = memmap[VMAPPLE_GIC_DIST].base;
*redist_base = memmap[VMAPPLE_GIC_REDIST].base;
return true;
}
static GlobalProperty vmapple_compat_defaults[] = {
{ TYPE_VIRTIO_PCI, "disable-legacy", "on" },
/*
@@ -569,8 +738,59 @@ static GlobalProperty vmapple_compat_defaults[] = {
* mapping in the XHCI controller works around the problem.
*/
{ TYPE_XHCI_PCI, "conditional-intr-mapping", "on" },
/*
* macOS 27's virtio PCI transport never starts a device whose
* capabilities are linked from high offsets to low.
*/
{ "virtio-net-pci-base", "x-ascending-capabilities", "on" },
{ "virtio-sound-pci", "x-ascending-capabilities", "on" },
/*
* macOS's virtio-net driver can miss the completion of its first control
* command, which QEMU gives before the driver waits for it, and the
* interface then never comes up. Offer no control queue, nor the
* features that need one. The device stays promiscuous, as it resets,
* and passes the guest every frame its backend delivers.
*/
{ TYPE_VIRTIO_NET, "ctrl_vq", "off" },
{ TYPE_VIRTIO_NET, "ctrl_rx", "off" },
{ TYPE_VIRTIO_NET, "ctrl_rx_extra", "off" },
{ TYPE_VIRTIO_NET, "ctrl_vlan", "off" },
{ TYPE_VIRTIO_NET, "ctrl_mac_addr", "off" },
{ TYPE_VIRTIO_NET, "ctrl_guest_offloads", "off" },
{ TYPE_VIRTIO_NET, "guest_announce", "off" },
/*
* Under TCG, the max CPU offers SME with streaming vectors of up to 2048
* bits. macOS 14 sizes a zone for each thread's SME state from the
* longest, and panics as it starts because that zone's element is too
* large. Offer no SME, as an M1 to M3 under HVF gives none. Under HVF
* the CPU gets its "sme" property only as its vCPU starts, after this
* default would apply, so the default is optional and HVF's CPU keeps
* what the host gives.
*/
{ ARM_CPU_TYPE_NAME("max"), "sme", "off", .optional = true },
};
static char *vmapple_get_tablet(Object *obj, Error **errp)
{
VMAppleMachineState *vms = VMAPPLE_MACHINE(obj);
return g_strdup(vms->tablet);
}
static void vmapple_set_tablet(Object *obj, const char *value, Error **errp)
{
VMAppleMachineState *vms = VMAPPLE_MACHINE(obj);
ObjectClass *oc = object_class_by_name(value);
if (!oc || object_class_is_abstract(oc) ||
!object_class_dynamic_cast(oc, TYPE_USB_DEVICE)) {
error_setg(errp, "tablet: '%s' is not a USB device", value);
return;
}
g_free(vms->tablet);
vms->tablet = g_strdup(value);
}
static void vmapple_machine_class_init(ObjectClass *oc, const void *data)
{
MachineClass *mc = MACHINE_CLASS(oc);
@@ -583,13 +803,24 @@ static void vmapple_machine_class_init(ObjectClass *oc, const void *data)
mc->minimum_page_bits = 12;
mc->possible_cpu_arch_ids = vmapple_possible_cpu_arch_ids;
mc->cpu_index_to_instance_props = vmapple_cpu_index_to_props;
mc->default_cpu_type = ARM_CPU_TYPE_NAME("host");
/* Under HVF, max is the host CPU. */
mc->default_cpu_type = ARM_CPU_TYPE_NAME("max");
mc->get_default_cpu_node_id = vmapple_get_default_cpu_node_id;
mc->get_vgic_bases = vmapple_get_vgic_bases;
mc->get_physical_address_range = vmapple_get_physical_address_range;
mc->default_ram_id = "mach-vmapple.ram";
mc->desc = "Apple aarch64 Virtual Machine";
compat_props_add(mc->compat_props, vmapple_compat_defaults,
G_N_ELEMENTS(vmapple_compat_defaults));
object_class_property_add_str(oc, "tablet", vmapple_get_tablet,
vmapple_set_tablet);
object_class_property_set_description(oc, "tablet",
"The USB pointing device: "
"usb-vmapple-tablet (default), "
"or another USB device such as "
"usb-tablet");
}
static void vmapple_instance_init(Object *obj)
@@ -597,10 +828,32 @@ static void vmapple_instance_init(Object *obj)
VMAppleMachineState *vms = VMAPPLE_MACHINE(obj);
vms->irqmap = irqmap;
/*
* macOS drives Virtualization.framework's USB tablet with its own
* driver, which takes smooth scrolling.
*/
vms->tablet = g_strdup("usb-vmapple-tablet");
object_property_add_uint64_ptr(obj, "uuid", &vms->uuid,
OBJ_PROP_FLAG_READWRITE);
object_property_set_description(obj, "uuid", "Machine UUID (SDOM)");
object_property_add_uint64_ptr(obj, "x-pool-room-base",
&vms->pool_room_base, OBJ_PROP_FLAG_READ);
object_property_set_description(obj, "x-pool-room-base",
"Where the room past RAM for a device's "
"pool starts (read-only)");
object_property_add_uint64_ptr(obj, "x-pool-room-size",
&vms->pool_room_size, OBJ_PROP_FLAG_READ);
object_property_set_description(obj, "x-pool-room-size",
"The size of the room past RAM for a "
"device's pool, 0 for none (read-only)");
}
static void vmapple_instance_finalize(Object *obj)
{
VMAppleMachineState *vms = VMAPPLE_MACHINE(obj);
g_free(vms->tablet);
}
static const TypeInfo vmapple_machine_info = {
@@ -609,6 +862,7 @@ static const TypeInfo vmapple_machine_info = {
.instance_size = sizeof(VMAppleMachineState),
.class_init = vmapple_machine_class_init,
.instance_init = vmapple_instance_init,
.instance_finalize = vmapple_instance_finalize,
};
static void machvmapple_machine_init(void)
+2 -3
View File
@@ -92,10 +92,9 @@ typedef struct QEMUWin32AIOState QEMUWin32AIOState;
QEMUWin32AIOState *win32_aio_init(void);
void win32_aio_cleanup(QEMUWin32AIOState *aio);
int win32_aio_attach(QEMUWin32AIOState *aio, HANDLE hfile);
BlockAIOCB *win32_aio_submit(BlockDriverState *bs,
int coroutine_fn win32_aio_co_submit(BlockDriverState *bs,
QEMUWin32AIOState *aio, HANDLE hfile,
uint64_t offset, uint64_t bytes, QEMUIOVector *qiov,
BlockCompletionFunc *cb, void *opaque, int type);
uint64_t offset, uint64_t bytes, QEMUIOVector *qiov, int type);
void win32_aio_detach_aio_context(QEMUWin32AIOState *aio,
AioContext *old_context);
void win32_aio_attach_aio_context(QEMUWin32AIOState *aio,
+11
View File
@@ -158,6 +158,17 @@ void qemu_chr_change(QemuOpts *opts, Error **errp);
*/
void qemu_chr_cleanup(void);
#ifndef _WIN32
/**
* qemu_chr_stdio_term_exit:
*
* Restores the terminal a stdio chardev took, as its atexit handler does:
* for a process that then ends with _exit, which runs no atexit handler.
* Nothing where no stdio chardev took it.
*/
void qemu_chr_stdio_term_exit(void);
#endif
/**
* qemu_chr_new_noreplay:
* @label: the name of the backend
+5
View File
@@ -200,6 +200,11 @@ struct VirtIOSound {
AudioBackend *audio_be;
VMChangeStateEntry *vmstate;
virtio_snd_config snd_conf;
/*
* How many of the streams take input: the last ones. The others,
* first, give output.
*/
uint32_t input_streams;
QTAILQ_HEAD(, virtio_snd_ctrl_command) cmdq;
/*
* Convenience queue to keep track of invalid tx/rx queue messages inside
+8
View File
@@ -281,6 +281,14 @@ struct MachineClass {
int (*get_physical_address_range)(MachineState *machine,
int default_ipa_size, int max_ipa_size);
bool (*get_kernel_irqchip_default) (const MachineState *machine);
/*
* Guest physical addresses of the GICv3 distributor and (first)
* redistributor region, for accelerators (HVF) that must place an
* in-kernel vGIC before any vCPU exists. Returns false when the
* board has no GICv3.
*/
bool (*get_vgic_bases) (const MachineState *machine,
uint64_t *dist_base, uint64_t *redist_base);
BlockInterfaceType block_default_type;
int units_per_default_bus;
+6
View File
@@ -481,6 +481,12 @@ OBJECT_DECLARE_SIMPLE_TYPE(USBBus, USB_BUS)
struct USBBus {
BusState qbus;
USBBusOps *ops;
/*
* The controller holds an isochronous packet its device answers with
* USB_RET_NAK and retries it when the device wakes its endpoint, where
* other controllers complete the packet empty or with an error.
*/
bool iso_nak_retry;
int busnr;
int nfree;
int nused;
+2
View File
@@ -18,6 +18,8 @@
#define TYPE_VMAPPLE_CFG "vmapple-cfg"
#define TYPE_VMAPPLE_RTC "vmapple-rtc"
#define TYPE_VMAPPLE_VIRTIO_BLK_PCI "vmapple-virtio-blk-pci"
#endif /* HW_VMAPPLE_VMAPPLE_H */
+9
View File
@@ -44,6 +44,9 @@ OBJECT_DECLARE_SIMPLE_TYPE(QIOChannelFile, QIO_CHANNEL_FILE)
struct QIOChannelFile {
QIOChannel parent;
int fd;
#ifdef WIN32
bool direct_io;
#endif
};
@@ -111,4 +114,10 @@ qio_channel_file_new_path(const char *path,
mode_t mode,
Error **errp);
QIOChannelFile *
qio_channel_file_new_path_direct(const char *path,
int flags,
mode_t mode,
Error **errp);
#endif /* QIO_CHANNEL_FILE_H */
+17 -17
View File
@@ -146,12 +146,12 @@ struct QIOChannelClass {
ssize_t (*io_pwritev)(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
off_t offset,
int64_t offset,
Error **errp);
ssize_t (*io_preadv)(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
off_t offset,
int64_t offset,
Error **errp);
int (*io_shutdown)(QIOChannel *ioc,
QIOChannelShutdown how,
@@ -160,8 +160,8 @@ struct QIOChannelClass {
bool enabled);
void (*io_set_delay)(QIOChannel *ioc,
bool enabled);
off_t (*io_seek)(QIOChannel *ioc,
off_t offset,
int64_t (*io_seek)(QIOChannel *ioc,
int64_t offset,
int whence,
Error **errp);
void (*io_set_aio_fd_handler)(QIOChannel *ioc,
@@ -579,7 +579,7 @@ int qio_channel_close(QIOChannel *ioc,
*
*/
ssize_t qio_channel_pwritev(QIOChannel *ioc, const struct iovec *iov,
size_t niov, off_t offset, Error **errp);
size_t niov, int64_t offset, Error **errp);
/**
* qio_channel_pwrite
@@ -595,7 +595,7 @@ ssize_t qio_channel_pwritev(QIOChannel *ioc, const struct iovec *iov,
*
*/
ssize_t qio_channel_pwrite(QIOChannel *ioc, void *buf, size_t buflen,
off_t offset, Error **errp);
int64_t offset, Error **errp);
/**
* qio_channel_pwritev_all:
@@ -614,7 +614,7 @@ ssize_t qio_channel_pwrite(QIOChannel *ioc, void *buf, size_t buflen,
int coroutine_mixed_fn qio_channel_pwritev_all(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
off_t offset,
int64_t offset,
Error **errp);
/**
@@ -635,7 +635,7 @@ int coroutine_mixed_fn qio_channel_pwritev_all(QIOChannel *ioc,
int coroutine_mixed_fn qio_channel_pwrite_all(QIOChannel *ioc,
const void *buf,
size_t buflen,
off_t offset,
int64_t offset,
Error **errp);
/**
@@ -656,7 +656,7 @@ int coroutine_mixed_fn qio_channel_pwrite_all(QIOChannel *ioc,
*
*/
ssize_t qio_channel_preadv(QIOChannel *ioc, const struct iovec *iov,
size_t niov, off_t offset, Error **errp);
size_t niov, int64_t offset, Error **errp);
/**
* qio_channel_pread
@@ -672,7 +672,7 @@ ssize_t qio_channel_preadv(QIOChannel *ioc, const struct iovec *iov,
*
*/
ssize_t qio_channel_pread(QIOChannel *ioc, void *buf, size_t buflen,
off_t offset, Error **errp);
int64_t offset, Error **errp);
/**
* qio_channel_preadv_all_eof:
@@ -695,7 +695,7 @@ ssize_t qio_channel_pread(QIOChannel *ioc, void *buf, size_t buflen,
int coroutine_mixed_fn qio_channel_preadv_all_eof(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
off_t offset,
int64_t offset,
Error **errp);
/**
@@ -717,7 +717,7 @@ int coroutine_mixed_fn qio_channel_preadv_all_eof(QIOChannel *ioc,
int coroutine_mixed_fn qio_channel_preadv_all(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
off_t offset,
int64_t offset,
Error **errp);
/**
@@ -741,7 +741,7 @@ int coroutine_mixed_fn qio_channel_preadv_all(QIOChannel *ioc,
int coroutine_mixed_fn qio_channel_pread_all_eof(QIOChannel *ioc,
void *buf,
size_t buflen,
off_t offset,
int64_t offset,
Error **errp);
/**
@@ -763,7 +763,7 @@ int coroutine_mixed_fn qio_channel_pread_all_eof(QIOChannel *ioc,
int coroutine_mixed_fn qio_channel_pread_all(QIOChannel *ioc,
void *buf,
size_t buflen,
off_t offset,
int64_t offset,
Error **errp);
/**
@@ -861,10 +861,10 @@ void qio_channel_set_cork(QIOChannel *ioc,
* Not all implementations will support this facility,
* so may report an error.
*
* Returns: the new position on success, (off_t)-1 on failure
* Returns: the new position on success, (int64_t)-1 on failure
*/
off_t qio_channel_io_seek(QIOChannel *ioc,
off_t offset,
int64_t qio_channel_io_seek(QIOChannel *ioc,
int64_t offset,
int whence,
Error **errp);
+8
View File
@@ -100,6 +100,8 @@ typedef struct AudioBackendClass {
const struct audio_capture_ops *ops,
void *cb_opaque);
void (*del_capture)(AudioBackend *be, CaptureVoiceOut *cap, void *cb_opaque);
/* Optional: run the voices now, as the backend's own period does. */
void (*kick)(AudioBackend *be);
#ifdef CONFIG_GIO
bool (*set_dbus_server)(AudioBackend *be,
@@ -125,6 +127,12 @@ void audio_be_close_out(AudioBackend *be, SWVoiceOut *sw);
size_t audio_be_write(AudioBackend *be, SWVoiceOut *sw, void *pcm_buf, size_t size);
int audio_be_get_buffer_size_out(AudioBackend *be, SWVoiceOut *sw);
void audio_be_set_active_out(AudioBackend *be, SWVoiceOut *sw, bool on);
/*
* Run the backend's voices now, as its own period does: a frontend calls it
* when it has new audio, which is then written without waiting for the
* period.
*/
void audio_be_kick(AudioBackend *be);
bool audio_be_is_active_out(AudioBackend *be, SWVoiceOut *sw);
+12
View File
@@ -174,6 +174,18 @@ int qemu_strtosz_metric(const char *nptr, const char **end, uint64_t *result);
char *size_to_str(uint64_t val);
/**
* qemu_linux_release_meets_floor:
* @release: a Linux kernel release, as uname(2) gives it ("7.3.3-1-cachyos")
*
* Returns: whether @release's leading "MAJOR.MINOR" is 7.2 or later, the
* oldest Linux the reims-graphics device runs on; false where @release does
* not start with two numbers and a dot between them. Before 7.2 a udmabuf
* over large pages is malformed, and an AMD GPU's import of it is bound to
* the wrong pages (reims-vgpu issue 185).
*/
bool qemu_linux_release_meets_floor(const char *release);
/**
* freq_to_str:
* @freq_hz: frequency to stringify
+22
View File
@@ -220,6 +220,28 @@ void kvm_irqchip_add_change_notifier(Notifier *n);
void kvm_irqchip_remove_change_notifier(Notifier *n);
void kvm_irqchip_change_notify(void);
/*
* x86 targets only: @n runs on a vCPU's thread, with its CPUState as the
* data, each time kvm_arch_put_registers has put the vCPU's TSC, at a
* reset or a full put.
*/
void kvm_tsc_put_add_notifier(Notifier *n);
/*
* Deletes the KVM slots of exactly [@gpa, @gpa + @size), in each address
* space that holds one, on any thread, without the BQL, ahead of the removal
* of the RAM region that made them: the listener's removal of that section
* then finds no slot and deletes nothing, so the delete, which zaps what of
* the slot is mapped (measured on a 256 MiB slot: 3-8 ms fully mapped,
* against about 1 ms for the whole removal of an untouched one), is not
* spent under the BQL. Until the removal a guest access there exits, and
* QEMU carries it out on the region's memory. False, with nothing deleted,
* where no address space holds such a slot (the region's add is still to
* come, or was never made); a slot with a dirty log or guest_memfd is left
* to the removal.
*/
bool kvm_unmap_before_del(uint64_t gpa, uint64_t size);
#ifdef COMPILING_PER_TARGET
#include "cpu.h"
+2
View File
@@ -270,6 +270,8 @@ win32_close_exception_handler(struct _EXCEPTION_RECORD*, void*,
struct _CONTEXT*, void*);
void *qemu_win32_map_alloc(size_t size, HANDLE *h, Error **errp);
void *qemu_win32_ram_alloc(size_t size, uint64_t *align, HANDLE *h,
Error **errp);
void qemu_win32_map_free(void *ptr, HANDLE h, Error **errp);
#ifdef __cplusplus
+12 -1
View File
@@ -40,6 +40,14 @@ struct RAMBlock {
Error *cpr_blocker;
int fd;
uint64_t fd_offset;
#ifdef _WIN32
/*
* Shared RAM's section (RAM_SHARED): @host is a view of the whole
* section, which the paging file backs, so another mapping of it shares
* the block's pages. NULL for RAM that is not such a view.
*/
HANDLE section;
#endif
/*
* When RAM_GUEST_MEMFD_PRIVATE flag is set, this ramblock can have
* private pages backed by guest_memfd_private specified, while shared
@@ -60,7 +68,7 @@ struct RAMBlock {
* offset in the file pages belonging to this ramblock are saved,
* used only during migration to a file.
*/
off_t bitmap_offset;
int64_t bitmap_offset;
uint64_t pages_offset;
/* Bitmap of already received pages. Only used on destination side. */
@@ -182,6 +190,9 @@ void qemu_ram_set_migratable(RAMBlock *rb);
void qemu_ram_unset_migratable(RAMBlock *rb);
bool qemu_ram_is_named_file(const RAMBlock *rb);
int qemu_ram_get_fd(const RAMBlock *rb);
#ifdef _WIN32
HANDLE qemu_ram_get_section(const RAMBlock *rb);
#endif
size_t qemu_ram_pagesize(const RAMBlock *block);
size_t qemu_ram_pagesize_largest(void);
+15
View File
@@ -19,6 +19,21 @@ const char *qemu_get_vm_name(void);
void qemu_add_exit_notifier(Notifier *notify);
void qemu_remove_exit_notifier(Notifier *notify);
/*
* Cleanup notifiers run at the end of qemu_cleanup(), with the BQL held and
* the exit status (an int *) as their data: before exit() itself, so before
* every atexit handler. Exit notifiers run from an atexit handler registered
* at QEMU's start, so after every handler registered later, a driver's among
* them.
*/
void qemu_add_cleanup_notifier(Notifier *notify);
/*
* Runs the exit notifiers now, with the BQL held: what exit() runs of them,
* for a process that then ends with _exit, which runs no atexit handler.
*/
void qemu_run_exit_notifiers(void);
void qemu_add_machine_init_done_notifier(Notifier *notify);
void qemu_remove_machine_init_done_notifier(Notifier *notify);
+1
View File
@@ -9,6 +9,7 @@ struct AccelCPUState {
bool ready_for_pic_interrupt;
uint64_t tpr;
bool interruption_pending;
bool loadvm_pending;
/* Must be the last field as it may have a tail */
WHV_RUN_VP_EXIT_CONTEXT exit_ctx;
};
+12
View File
@@ -51,6 +51,13 @@ struct whpx_state {
bool ignore_unknown_msr;
bool intercept_msr_gp;
/* intercept-msr-gp was given on or off, not left to the host's vendor */
bool intercept_msr_gp_given;
/*
* Hyper-V refuses the TSC deadline timer's register, so the guest is
* offered no TSC deadline timer (whpx_tsc_deadline_refused)
*/
bool tsc_deadline_refused;
};
extern struct whpx_state whpx_global;
@@ -119,6 +126,11 @@ void whpx_apic_get(APICCommonState *s);
(WHV_PARTITION_HANDLE Partition, UINT32 VpIndex, \
WHV_VIRTUAL_PROCESSOR_STATE_TYPE StateType, PVOID Buffer, \
UINT32 BufferSizeInBytes)) \
X(HRESULT, WHvAdviseGpaRange, \
(WHV_PARTITION_HANDLE Partition, \
const WHV_MEMORY_RANGE_ENTRY *GpaRanges, UINT32 GpaRangesCount, \
WHV_ADVISE_GPA_RANGE_CODE Advice, const VOID *AdviceBuffer, \
UINT32 AdviceBufferSizeInBytes)) \
LIST_WINHVPLATFORM_FUNCTIONS_SUPPLEMENTAL_ARCH(X)
#define WHP_DEFINE_TYPE(return_type, function_name, signature) \
+45
View File
@@ -28,6 +28,51 @@ extern bool whpx_allowed;
extern bool whpx_irqchip_in_kernel;
#define whpx_enabled() (whpx_allowed)
#define whpx_irqchip_in_kernel() (whpx_irqchip_in_kernel)
/*
* Delivers the MSI of @address and @data as its write to the APIC's MSI
* region does, on any thread, with the BQL held or not. False, with nothing
* delivered, where the platform's APIC is not the hypervisor's
* (whpx_irqchip_in_kernel()), the vector is 0, or the hypervisor refused the
* request: the caller then sends it the usual way (msix_notify), which says
* why it is lost.
*/
bool whpx_send_msi_direct(uint64_t address, uint32_t data);
/*
* Maps @size bytes of host memory at @host into the guest at @gpa, read,
* write and execute, on any thread, without the BQL, ahead of the add of the
* RAM region that holds exactly that memory there: the listener's add of that
* section then maps nothing, so the hypervisor's map, which takes about 26 ms
* a GiB, is not spent under the BQL. The range must hold nothing in the
* guest's address space until that add. False, with nothing mapped, where the
* hypervisor refused it; the add then maps it as usual.
*/
bool whpx_map_ahead(void *host, uint64_t gpa, uint64_t size);
/*
* Undoes a whpx_map_ahead of exactly @gpa, @size and @host whose region was
* never added; nothing where the add took it.
*/
void whpx_unmap_ahead(uint64_t gpa, uint64_t size, void *host);
/*
* Unmaps the @size bytes at @gpa of a RAM region the device is about to take
* out of the guest's address space, on any thread, without the BQL: the
* listener's removal of exactly that section then unmaps nothing, so the
* hypervisor's unmap, which takes about 45 ms a GiB, is not spent under the
* BQL. Until the removal a guest access there exits, and QEMU carries it out
* on the region's memory. False, with nothing unmapped, where the region's add
* mapped ahead is still to come or the hypervisor refused; the removal then
* unmaps it as usual.
*/
bool whpx_unmap_before_del(uint64_t gpa, uint64_t size);
/* Whether the hypervisor has whpx_populate's call (WHvAdviseGpaRange). */
bool whpx_can_populate(void);
/*
* Fills the hypervisor's second-level tables for the @size bytes at @gpa,
* mapped in the guest, ahead of the guest's first touch, for reads and
* writes (WHvAdviseGpaRange's WHvAdviseGpaRangeCodePopulate), on any thread,
* without the BQL. The partition's maps and unmaps wait for the call. 0, or
* -EIO where the hypervisor refused, -ENOTSUP where it has no such call.
*/
int whpx_populate(uint64_t gpa, uint64_t size);
#else /* !CONFIG_WHPX_IS_POSSIBLE */
#define whpx_enabled() 0
#define whpx_irqchip_in_kernel() (0)
+6
View File
@@ -9,6 +9,7 @@
#define INPUT_EVENT_MASK_REL (1<<INPUT_EVENT_KIND_REL)
#define INPUT_EVENT_MASK_ABS (1<<INPUT_EVENT_KIND_ABS)
#define INPUT_EVENT_MASK_MTT (1<<INPUT_EVENT_KIND_MTT)
#define INPUT_EVENT_MASK_SCROLL (1 << INPUT_EVENT_KIND_SCROLL)
#define INPUT_EVENT_ABS_MIN 0x0000
#define INPUT_EVENT_ABS_MAX 0x7FFF
@@ -31,6 +32,7 @@ typedef struct QemuInputEvent {
InputMoveEvent rel;
InputMoveEvent abs;
InputMultiTouchEvent mtt;
InputScrollEvent scroll;
};
} QemuInputEvent;
@@ -74,6 +76,7 @@ void qemu_input_update_buttons(QemuConsole *src, uint32_t *button_map,
uint32_t button_old, uint32_t button_new);
bool qemu_input_is_absolute(const QemuConsole *con);
bool qemu_input_scrolls_smoothly(const QemuConsole *con);
int qemu_input_scale_axis(int value,
int min_in, int max_in,
int min_out, int max_out);
@@ -85,6 +88,9 @@ void qemu_input_queue_mtt(QemuConsole *src, InputMultiTouchType type, int slot,
void qemu_input_queue_mtt_abs(QemuConsole *src, InputAxis axis, int value,
int min_in, int max_in,
int slot, int tracking_id);
void qemu_input_queue_scroll(QemuConsole *src, InputAxis axis, int value,
InputScrollPhase phase,
InputScrollMomentum momentum);
/* Touch devices */
typedef struct touch_slot {
+2 -2
View File
@@ -124,8 +124,8 @@ static int qio_channel_buffer_set_blocking(QIOChannel *ioc G_GNUC_UNUSED,
}
static off_t qio_channel_buffer_seek(QIOChannel *ioc,
off_t offset,
static int64_t qio_channel_buffer_seek(QIOChannel *ioc,
int64_t offset,
int whence,
Error **errp)
{
+233 -10
View File
@@ -27,6 +27,9 @@
#include "qemu/module.h"
#include "qemu/sockets.h"
#include "trace.h"
#ifdef WIN32
#include <winioctl.h>
#endif
QIOChannelFile *
qio_channel_file_new_fd(int fd)
@@ -42,7 +45,7 @@ qio_channel_file_new_fd(int fd)
ioc->fd = fd;
if (lseek(fd, 0, SEEK_CUR) != (off_t)-1) {
if (lseek(fd, 0, SEEK_CUR) != (int64_t)-1) {
qio_channel_set_feature(QIO_CHANNEL(ioc), QIO_CHANNEL_FEATURE_SEEKABLE);
}
@@ -74,6 +77,9 @@ qio_channel_file_new_path(const char *path,
ioc = QIO_CHANNEL_FILE(object_new(TYPE_QIO_CHANNEL_FILE));
#ifdef O_BINARY
flags |= O_BINARY;
#endif
if (flags & O_CREAT) {
ioc->fd = qemu_create(path, flags & ~O_CREAT, mode, errp);
} else {
@@ -84,15 +90,93 @@ qio_channel_file_new_path(const char *path,
return NULL;
}
if (lseek(ioc->fd, 0, SEEK_CUR) != (off_t)-1) {
if (lseek(ioc->fd, 0, SEEK_CUR) != (int64_t)-1) {
qio_channel_set_feature(QIO_CHANNEL(ioc), QIO_CHANNEL_FEATURE_SEEKABLE);
}
#ifdef WIN32
if (flags & O_CREAT) {
HANDLE h = (HANDLE)_get_osfhandle(ioc->fd);
if (h != INVALID_HANDLE_VALUE && GetFileType(h) == FILE_TYPE_DISK) {
DWORD br = 0;
DeviceIoControl(h, FSCTL_SET_SPARSE, NULL, 0, NULL, 0, &br, NULL);
}
}
#endif
trace_qio_channel_file_new_path(ioc, path, flags, mode, ioc->fd);
return ioc;
}
QIOChannelFile *
qio_channel_file_new_path_direct(const char *path,
int flags,
mode_t mode,
Error **errp)
{
#ifdef O_DIRECT
return qio_channel_file_new_path(path, flags | O_DIRECT, mode, errp);
#elif defined(WIN32)
QIOChannelFile *ioc;
g_autofree gunichar2 *wpath = NULL;
DWORD access = 0;
DWORD disp = (flags & O_CREAT) ? OPEN_ALWAYS : OPEN_EXISTING;
DWORD share = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
int accmode = flags & O_ACCMODE;
int crt_flags = _O_BINARY;
HANDLE h;
int fd;
if (accmode == O_RDONLY) {
access = GENERIC_READ;
crt_flags |= _O_RDONLY;
} else if (accmode == O_WRONLY) {
access = GENERIC_WRITE;
} else {
access = GENERIC_READ | GENERIC_WRITE;
}
wpath = g_utf8_to_utf16(path, -1, NULL, NULL, NULL);
if (!wpath) {
error_setg(errp, "Invalid UTF-8 path for direct I/O: %s", path);
return NULL;
}
h = CreateFileW((LPCWSTR)wpath, access, share, NULL, disp,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_NO_BUFFERING, NULL);
if (h == INVALID_HANDLE_VALUE) {
error_setg_win32(errp, GetLastError(),
"Unable to open '%s' with direct I/O", path);
return NULL;
}
if ((flags & O_CREAT) && GetFileType(h) == FILE_TYPE_DISK) {
DWORD br = 0;
DeviceIoControl(h, FSCTL_SET_SPARSE, NULL, 0, NULL, 0, &br, NULL);
}
fd = _open_osfhandle((intptr_t)h, crt_flags);
if (fd < 0) {
CloseHandle(h);
error_setg_errno(errp, errno,
"Unable to wrap direct I/O handle for '%s'", path);
return NULL;
}
ioc = QIO_CHANNEL_FILE(object_new(TYPE_QIO_CHANNEL_FILE));
ioc->fd = fd;
ioc->direct_io = true;
if (lseek(ioc->fd, 0, SEEK_CUR) != (int64_t)-1) {
qio_channel_set_feature(QIO_CHANNEL(ioc), QIO_CHANNEL_FEATURE_SEEKABLE);
}
trace_qio_channel_file_new_path(ioc, path, flags, mode, ioc->fd);
return ioc;
#else
error_setg(errp, "Direct I/O is not supported on this platform");
return NULL;
#endif
}
static void qio_channel_file_init(Object *obj)
{
@@ -170,7 +254,7 @@ static ssize_t qio_channel_file_writev(QIOChannel *ioc,
static ssize_t qio_channel_file_preadv(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
off_t offset,
int64_t offset,
Error **errp)
{
QIOChannelFile *fioc = QIO_CHANNEL_FILE(ioc);
@@ -196,7 +280,7 @@ static ssize_t qio_channel_file_preadv(QIOChannel *ioc,
static ssize_t qio_channel_file_pwritev(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
off_t offset,
int64_t offset,
Error **errp)
{
QIOChannelFile *fioc = QIO_CHANNEL_FILE(ioc);
@@ -216,6 +300,137 @@ static ssize_t qio_channel_file_pwritev(QIOChannel *ioc,
}
return ret;
}
#elif defined(WIN32)
static ssize_t qio_channel_file_prw_win32(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
int64_t offset,
bool is_write,
Error **errp)
{
static const size_t max_chunk = 16U * 1024U * 1024U;
QIOChannelFile *fioc = QIO_CHANNEL_FILE(ioc);
HANDLE h = (HANDLE)_get_osfhandle(fioc->fd);
LARGE_INTEGER zero = { .QuadPart = 0 };
LARGE_INTEGER saved = { .QuadPart = 0 };
bool have_saved = false;
uint64_t cur;
ssize_t total = 0;
ssize_t ret = -1;
size_t i = 0;
if (offset < 0) {
error_setg_errno(errp, EINVAL, "Invalid negative offset for %s",
is_write ? "pwritev" : "preadv");
return -1;
}
if (h == INVALID_HANDLE_VALUE) {
error_setg_errno(errp, EBADF, "Invalid file handle for %s",
is_write ? "pwritev" : "preadv");
return -1;
}
cur = (uint64_t)offset;
have_saved = SetFilePointerEx(h, zero, &saved, FILE_CURRENT);
while (i < niov) {
uint8_t *base = (uint8_t *)iov[i].iov_base;
size_t run = iov[i].iov_len;
size_t j = i + 1;
while (j < niov && (uint8_t *)iov[j].iov_base == base + run &&
run < max_chunk && iov[j].iov_len <= max_chunk - run) {
run += iov[j].iov_len;
j++;
}
if (run == 0) {
i = j;
continue;
}
size_t done = 0;
while (done < run) {
DWORD chunk = (DWORD)MIN(run - done, max_chunk);
DWORD xfer = 0;
OVERLAPPED ov;
BOOL ok;
memset(&ov, 0, sizeof(ov));
ov.Offset = (DWORD)(cur & 0xFFFFFFFFULL);
ov.OffsetHigh = (DWORD)(cur >> 32);
if (is_write) {
ok = WriteFile(h, base + done, chunk, &xfer, &ov);
} else {
ok = ReadFile(h, base + done, chunk, &xfer, &ov);
}
if (!ok) {
DWORD err = GetLastError();
const char *msg = is_write ? "Unable to pwritev to file"
: "Unable to preadv from file";
if (!is_write && err == ERROR_HANDLE_EOF) {
ret = total;
goto out;
}
/*
* A volume can accept the handle and reject an unbuffered
* write. Keep this distinct from disk or media failures
* so the caller can retry with buffering.
*/
if (is_write && fioc->direct_io &&
(err == ERROR_INVALID_PARAMETER ||
err == ERROR_INVALID_FUNCTION ||
err == ERROR_NOT_SUPPORTED)) {
msg = "Unable to pwritev to file with direct I/O";
}
error_setg_win32(errp, err, "%s", msg);
goto out;
}
if (xfer == 0) {
if (!is_write || total > 0) {
ret = total;
goto out;
}
error_setg_errno(errp, EIO, "pwritev made no progress");
goto out;
}
done += xfer;
cur += xfer;
total += xfer;
if (is_write && xfer < chunk) {
/* Preserve short-write semantics for caller retry/error handling. */
ret = total;
goto out;
}
}
i = j;
}
ret = total;
out:
if (have_saved) {
SetFilePointerEx(h, saved, NULL, FILE_BEGIN);
}
return ret;
}
static ssize_t qio_channel_file_preadv(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
int64_t offset,
Error **errp)
{
return qio_channel_file_prw_win32(ioc, iov, niov, offset, false, errp);
}
static ssize_t qio_channel_file_pwritev(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
int64_t offset,
Error **errp)
{
return qio_channel_file_prw_win32(ioc, iov, niov, offset, true, errp);
}
#endif /* CONFIG_PREADV */
static int qio_channel_file_set_blocking(QIOChannel *ioc,
@@ -223,7 +438,11 @@ static int qio_channel_file_set_blocking(QIOChannel *ioc,
Error **errp)
{
#ifdef WIN32
/* not implemented */
QIOChannelFile *fioc = QIO_CHANNEL_FILE(ioc);
if (enabled ||
GetFileType((HANDLE)_get_osfhandle(fioc->fd)) == FILE_TYPE_DISK) {
return 0;
}
error_setg_errno(errp, errno, "Failed to set FD nonblocking");
return -1;
#else
@@ -237,16 +456,20 @@ static int qio_channel_file_set_blocking(QIOChannel *ioc,
}
static off_t qio_channel_file_seek(QIOChannel *ioc,
off_t offset,
static int64_t qio_channel_file_seek(QIOChannel *ioc,
int64_t offset,
int whence,
Error **errp)
{
QIOChannelFile *fioc = QIO_CHANNEL_FILE(ioc);
off_t ret;
int64_t ret;
#ifdef WIN32
ret = (int64_t)_lseeki64(fioc->fd, (int64_t)offset, whence);
#else
ret = lseek(fioc->fd, offset, whence);
if (ret == (off_t)-1) {
#endif
if (ret == (int64_t)-1) {
error_setg_errno(errp, errno,
"Unable to seek to offset %lld whence %d in file",
(long long int)offset, whence);
@@ -314,7 +537,7 @@ static void qio_channel_file_class_init(ObjectClass *klass,
ioc_klass->io_writev = qio_channel_file_writev;
ioc_klass->io_readv = qio_channel_file_readv;
ioc_klass->io_set_blocking = qio_channel_file_set_blocking;
#ifdef CONFIG_PREADV
#if defined(CONFIG_PREADV) || defined(WIN32)
ioc_klass->io_pwritev = qio_channel_file_pwritev;
ioc_klass->io_preadv = qio_channel_file_preadv;
#endif
+2 -2
View File
@@ -105,9 +105,9 @@ qio_channel_null_set_blocking(QIOChannel *ioc G_GNUC_UNUSED,
}
static off_t
static int64_t
qio_channel_null_seek(QIOChannel *ioc G_GNUC_UNUSED,
off_t offset G_GNUC_UNUSED,
int64_t offset G_GNUC_UNUSED,
int whence G_GNUC_UNUSED,
Error **errp G_GNUC_UNUSED)
{
+12 -12
View File
@@ -450,7 +450,7 @@ GSource *qio_channel_add_watch_source(QIOChannel *ioc,
ssize_t qio_channel_pwritev(QIOChannel *ioc, const struct iovec *iov,
size_t niov, off_t offset, Error **errp)
size_t niov, int64_t offset, Error **errp)
{
QIOChannelClass *klass = QIO_CHANNEL_GET_CLASS(ioc);
@@ -468,7 +468,7 @@ ssize_t qio_channel_pwritev(QIOChannel *ioc, const struct iovec *iov,
}
ssize_t qio_channel_pwrite(QIOChannel *ioc, void *buf, size_t buflen,
off_t offset, Error **errp)
int64_t offset, Error **errp)
{
struct iovec iov = {
.iov_base = buf,
@@ -481,7 +481,7 @@ ssize_t qio_channel_pwrite(QIOChannel *ioc, void *buf, size_t buflen,
int coroutine_mixed_fn qio_channel_pwritev_all(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
off_t offset,
int64_t offset,
Error **errp)
{
int ret = -1;
@@ -519,7 +519,7 @@ int coroutine_mixed_fn qio_channel_pwritev_all(QIOChannel *ioc,
int coroutine_mixed_fn qio_channel_pwrite_all(QIOChannel *ioc,
const void *buf,
size_t buflen,
off_t offset,
int64_t offset,
Error **errp)
{
struct iovec iov = { .iov_base = (char *)buf, .iov_len = buflen };
@@ -527,7 +527,7 @@ int coroutine_mixed_fn qio_channel_pwrite_all(QIOChannel *ioc,
}
ssize_t qio_channel_preadv(QIOChannel *ioc, const struct iovec *iov,
size_t niov, off_t offset, Error **errp)
size_t niov, int64_t offset, Error **errp)
{
QIOChannelClass *klass = QIO_CHANNEL_GET_CLASS(ioc);
@@ -545,7 +545,7 @@ ssize_t qio_channel_preadv(QIOChannel *ioc, const struct iovec *iov,
}
ssize_t qio_channel_pread(QIOChannel *ioc, void *buf, size_t buflen,
off_t offset, Error **errp)
int64_t offset, Error **errp)
{
struct iovec iov = {
.iov_base = buf,
@@ -558,7 +558,7 @@ ssize_t qio_channel_pread(QIOChannel *ioc, void *buf, size_t buflen,
int coroutine_mixed_fn qio_channel_preadv_all_eof(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
off_t offset,
int64_t offset,
Error **errp)
{
int ret = -1;
@@ -609,7 +609,7 @@ int coroutine_mixed_fn qio_channel_preadv_all_eof(QIOChannel *ioc,
int coroutine_mixed_fn qio_channel_preadv_all(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
off_t offset,
int64_t offset,
Error **errp)
{
int ret = qio_channel_preadv_all_eof(ioc, iov, niov, offset, errp);
@@ -629,7 +629,7 @@ int coroutine_mixed_fn qio_channel_preadv_all(QIOChannel *ioc,
int coroutine_mixed_fn qio_channel_pread_all_eof(QIOChannel *ioc,
void *buf,
size_t buflen,
off_t offset,
int64_t offset,
Error **errp)
{
struct iovec iov = { .iov_base = buf, .iov_len = buflen };
@@ -639,7 +639,7 @@ int coroutine_mixed_fn qio_channel_pread_all_eof(QIOChannel *ioc,
int coroutine_mixed_fn qio_channel_pread_all(QIOChannel *ioc,
void *buf,
size_t buflen,
off_t offset,
int64_t offset,
Error **errp)
{
struct iovec iov = { .iov_base = buf, .iov_len = buflen };
@@ -696,8 +696,8 @@ int qio_channel_get_peerpid(QIOChannel *ioc,
return 0;
}
off_t qio_channel_io_seek(QIOChannel *ioc,
off_t offset,
int64_t qio_channel_io_seek(QIOChannel *ioc,
int64_t offset,
int whence,
Error **errp)
{
+18 -9
View File
@@ -838,7 +838,7 @@ socket = []
version_res = []
coref = []
iokit = []
pvg = not_found
reims_vgpu = not_found
emulator_link_args = []
midl = not_found
widl = not_found
@@ -864,8 +864,6 @@ elif host_os == 'darwin'
coref = dependency('appleframeworks', modules: 'CoreFoundation')
iokit = dependency('appleframeworks', modules: 'IOKit', required: false)
host_dsosuf = '.dylib'
pvg = dependency('appleframeworks', modules: ['ParavirtualizedGraphics', 'Metal'],
required: get_option('pvg'))
elif host_os == 'sunos'
socket = [cc.find_library('socket'),
cc.find_library('nsl'),
@@ -881,6 +879,16 @@ elif host_os == 'openbsd'
endif
endif
# reims-graphics-pci drives reims-vgpu's C API (reims_vgpu.h), a library
# found through pkg-config: reims-vgpu.pc, which reims-vgpu's `cargo xtask
# dist` writes into its target/dist/lib/pkgconfig. It is linked statically,
# so the binary records no path to it. The library runs on macOS, on Linux
# and on Windows.
if host_os in ['darwin', 'linux', 'windows']
reims_vgpu = dependency('reims-vgpu', method: 'pkg-config', static: true,
required: get_option('reims_vgpu'))
endif
###############################################
# Host-specific configuration of accelerators #
###############################################
@@ -3417,10 +3425,11 @@ foreach target : target_dirs
target_kconfig += 'CONFIG_' + config_target['TARGET_ARCH'].to_upper() + '=y'
target_kconfig += 'CONFIG_TARGET_BIG_ENDIAN=' + config_target['TARGET_BIG_ENDIAN']
# PVG is not cross-architecture. Use accelerator_targets as a proxy to
# figure out which target can support PVG on this host
if pvg.found() and target in accelerator_targets.get('CONFIG_HVF', [])
target_kconfig += 'CONFIG_MAC_PVG=y'
# The reims-graphics device's region is plain host memory the guest maps,
# whatever its architecture or accelerator, so every target may have it:
# x86-64 guests under TCG on a Mac among them.
if reims_vgpu.found()
target_kconfig += 'CONFIG_REIMS_GRAPHICS=y'
endif
config_input = meson.get_external_property(target, 'default')
@@ -5076,8 +5085,8 @@ summary_info += {'libdw': libdw}
if host_os == 'freebsd'
summary_info += {'libinotify-kqueue': inotify}
endif
if host_os == 'darwin'
summary_info += {'ParavirtualizedGraphics support': pvg}
if host_os in ['darwin', 'linux']
summary_info += {'reims-vgpu support': reims_vgpu}
endif
summary_info += {'valgrind': valgrind}
summary(summary_info, bool_yn: true, section: 'Dependencies')
+2 -2
View File
@@ -208,10 +208,10 @@ option('lzfse', type : 'feature', value : 'auto',
description: 'lzfse support for DMG images')
option('lzo', type : 'feature', value : 'auto',
description: 'lzo compression support')
option('pvg', type: 'feature', value: 'auto',
description: 'macOS paravirtualized graphics support')
option('rbd', type : 'feature', value : 'auto',
description: 'Ceph block device driver')
option('reims_vgpu', type : 'feature', value : 'auto',
description: 'reims-vgpu graphics device (reims-graphics-pci)')
option('opengl', type : 'feature', value : 'auto',
description: 'OpenGL support')
option('rdma', type : 'feature', value : 'auto',
+5 -5
View File
@@ -101,7 +101,7 @@ static ssize_t
qio_channel_block_preadv(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
off_t offset,
int64_t offset,
Error **errp)
{
QIOChannelBlock *bioc = QIO_CHANNEL_BLOCK(ioc);
@@ -122,7 +122,7 @@ static ssize_t
qio_channel_block_pwritev(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
off_t offset,
int64_t offset,
Error **errp)
{
QIOChannelBlock *bioc = QIO_CHANNEL_BLOCK(ioc);
@@ -152,9 +152,9 @@ qio_channel_block_set_blocking(QIOChannel *ioc,
}
static off_t
static int64_t
qio_channel_block_seek(QIOChannel *ioc,
off_t offset,
int64_t offset,
int whence,
Error **errp)
{
@@ -169,7 +169,7 @@ qio_channel_block_seek(QIOChannel *ioc,
break;
case SEEK_END:
error_setg(errp, "Size of VMstate region is unknown");
return (off_t)-1;
return (int64_t)-1;
default:
g_assert_not_reached();
}
+1 -1
View File
@@ -39,7 +39,7 @@ OBJECT_DECLARE_SIMPLE_TYPE(QIOChannelBlock, QIO_CHANNEL_BLOCK)
struct QIOChannelBlock {
QIOChannel parent;
BlockDriverState *bs;
off_t offset;
int64_t offset;
};
+107 -21
View File
@@ -16,6 +16,7 @@
#include "io/channel-file.h"
#include "io/channel-socket.h"
#include "io/channel-util.h"
#include "multifd.h"
#include "options.h"
#include "trace.h"
@@ -50,14 +51,17 @@ void file_cleanup_outgoing_migration(void)
outgoing_args.fname = NULL;
}
static void file_enable_direct_io(int *flags)
static QIOChannelFile *file_open_channel(const char *path, int flags,
bool direct_io, Error **errp)
{
#ifdef O_DIRECT
*flags |= O_DIRECT;
#else
/* it should have been rejected when setting the parameter */
g_assert_not_reached();
#endif
if (direct_io) {
/*
* Enable direct I/O for the secondary channels. These are used
* for sending/receiving ram pages and I/O is aligned to page size.
*/
return qio_channel_file_new_path_direct(path, flags, 0, errp);
}
return qio_channel_file_new_path(path, flags, 0, errp);
}
bool file_send_channel_create(gpointer opaque, Error **errp)
@@ -66,16 +70,7 @@ bool file_send_channel_create(gpointer opaque, Error **errp)
int flags = O_WRONLY;
bool ret = true;
if (migrate_direct_io()) {
/*
* Enable O_DIRECT for the secondary channels. These are used
* for sending ram pages and writes should be guaranteed to be
* aligned to at least page size.
*/
file_enable_direct_io(&flags);
}
ioc = qio_channel_file_new_path(outgoing_args.fname, flags, 0, errp);
ioc = file_open_channel(outgoing_args.fname, flags, migrate_direct_io(), errp);
if (!ioc) {
ret = false;
goto out;
@@ -108,7 +103,11 @@ QIOChannel *file_connect_outgoing(MigrationState *s,
goto out;
}
#ifdef WIN32
if (_chsize_s(fioc->fd, (int64_t)offset) != 0) {
#else
if (ftruncate(fioc->fd, offset)) {
#endif
error_setg_errno(errp, errno,
"failed to truncate migration file to offset %" PRIx64,
offset);
@@ -145,18 +144,18 @@ static void file_create_incoming_channels(QIOChannel *ioc, char *filename,
g_autofree QIOChannel **iocs = NULL;
int flags = O_RDONLY;
bool direct_io = false;
if (migrate_multifd()) {
channels += migrate_multifd_channels();
if (migrate_direct_io()) {
file_enable_direct_io(&flags);
}
direct_io = migrate_direct_io();
}
iocs = g_new0(QIOChannel *, channels);
iocs[0] = ioc;
for (i = 1; i < channels; i++) {
QIOChannelFile *fioc = qio_channel_file_new_path(filename, flags, 0, errp);
QIOChannelFile *fioc = file_open_channel(filename, flags, direct_io, errp);
if (!fioc) {
while (i) {
@@ -199,6 +198,84 @@ void file_connect_incoming(FileMigrationArgs *file_args, Error **errp)
file_create_incoming_channels(QIO_CHANNEL(fioc), filename, errp);
}
#ifdef WIN32
/*
* NTFS sparse files allocate in 64 KiB compression units. Coalescing a
* contiguous multifd packet's non-zero pages into one 64 KiB-aligned write
* within the packet's exclusive [pkt_min, pkt_max) span eliminates tiny
* unaligned sparse writes without overlapping any other multifd thread or
* changing the mapped-ram file format or file_bmap.
*/
static int file_write_ramblock_win32_coalesced(QIOChannel *ioc,
int niov,
MultiFDPages_t *pages,
Error **errp)
{
RAMBlock *block = pages->block;
size_t page_size = multifd_ram_page_size();
uint32_t total = pages->num;
uint32_t norm_n = (uint32_t)niov;
ram_addr_t pkt_min, pkt_max, norm_min, norm_max;
if (niov <= 0 || total == 0 || norm_n != pages->normal_num ||
norm_n > total || page_size == 0 || block->used_length < page_size) {
return 1;
}
/* Verify strict ascending order within normal and zero partitions. */
for (uint32_t k = 1; k < norm_n; k++) {
if (pages->offset[k] <= pages->offset[k - 1]) {
return 1;
}
}
for (uint32_t k = norm_n + 1; k < total; k++) {
if (pages->offset[k] <= pages->offset[k - 1]) {
return 1;
}
}
if (pages->offset[norm_n - 1] > block->used_length - page_size) {
return 1;
}
norm_min = pages->offset[0];
norm_max = pages->offset[norm_n - 1] + page_size;
pkt_min = norm_min;
pkt_max = norm_max;
if (norm_n < total) {
if (pages->offset[total - 1] > block->used_length - page_size) {
return 1;
}
if (pages->offset[norm_n] < pkt_min) {
pkt_min = pages->offset[norm_n];
}
if (pages->offset[total - 1] + page_size > pkt_max) {
pkt_max = pages->offset[total - 1] + page_size;
}
}
if ((pkt_max - pkt_min) != (ram_addr_t)total * page_size) {
return 1;
}
const ram_addr_t unit = 64 * 1024;
ram_addr_t start = QEMU_ALIGN_DOWN(norm_min, unit);
ram_addr_t end = QEMU_ALIGN_UP(norm_max, unit);
if (start < pkt_min) {
start = pkt_min;
}
if (end > pkt_max) {
end = pkt_max;
}
struct iovec single = {
.iov_base = block->host + start,
.iov_len = end - start,
};
return qio_channel_pwritev_all(ioc, &single, 1,
block->pages_offset + start, errp);
}
#endif
int file_write_ramblock_iov(QIOChannel *ioc, const struct iovec *iov,
int niov, MultiFDPages_t *pages, Error **errp)
{
@@ -208,6 +285,15 @@ int file_write_ramblock_iov(QIOChannel *ioc, const struct iovec *iov,
size_t len;
RAMBlock *block = pages->block;
#ifdef WIN32
if (niov > 0) {
int cret = file_write_ramblock_win32_coalesced(ioc, niov, pages, errp);
if (cret <= 0) {
return cret;
}
}
#endif
slice_idx = 0;
slice_num = 1;
+29
View File
@@ -63,6 +63,7 @@
#include "system/dirtylimit.h"
#include "qemu/sockets.h"
#include "system/kvm.h"
#include "system/whpx.h"
#include "math.h"
#define NOTIFIER_ELEM_INIT(array, elem) \
@@ -2174,6 +2175,34 @@ void qmp_migrate(const char *uri, bool has_channels,
return;
}
if (whpx_enabled()) {
if (has_resume && resume) {
error_setg(errp, "WHPX: migration resume is not supported");
return;
}
if (migrate_mode() != MIG_MODE_NORMAL) {
error_setg(errp, "WHPX: only normal migration mode is supported");
return;
}
if (runstate_is_running()) {
error_setg(errp,
"WHPX: live migration is not supported while the VM is running; stop the VM first");
return;
}
if (main_ch->addr->transport != MIGRATION_ADDRESS_TYPE_FILE) {
error_setg(errp,
"WHPX: only stopped-VM file suspend (file: URI) is supported");
return;
}
if (migrate_postcopy() || migrate_background_snapshot() ||
migrate_colo() || migrate_dirty_bitmaps() ||
migrate_return_path()) {
error_setg(errp,
"WHPX: unsupported migration capability for stopped-VM file suspend");
return;
}
}
if (!migrate_prepare(s, has_resume && resume, errp)) {
/* Error detected, put into errp */
return;
+29 -33
View File
@@ -24,24 +24,12 @@ static bool multifd_zero_page_enabled(void)
return migrate_zero_page_detection() == ZERO_PAGE_DETECTION_MULTIFD;
}
static void swap_page_offset(ram_addr_t *pages_offset, int a, int b)
{
ram_addr_t temp;
if (a == b) {
return;
}
temp = pages_offset[a];
pages_offset[a] = pages_offset[b];
pages_offset[b] = temp;
}
/**
* multifd_send_zero_page_detect: Perform zero page detection on all pages.
*
* Sorts normal pages before zero pages in p->pages->offset and updates
* p->pages->normal_num.
* Partitions normal pages before zero pages in p->pages->offset while
* preserving ascending offset order so mapped-ram file writes coalesce cleanly,
* and updates p->pages->normal_num.
*
* @param p A pointer to the send params.
*/
@@ -49,32 +37,40 @@ void multifd_send_zero_page_detect(MultiFDSendParams *p)
{
MultiFDPages_t *pages = &p->data->u.ram;
RAMBlock *rb = pages->block;
int i = 0;
int j = pages->num - 1;
size_t page_size = multifd_ram_page_size();
uint32_t normal_num = 0;
uint32_t zero_num = 0;
ram_addr_t stack_zero[128];
g_autofree ram_addr_t *heap_zero = NULL;
ram_addr_t *zero_offsets = stack_zero;
if (!multifd_zero_page_enabled()) {
pages->normal_num = pages->num;
goto out;
}
/*
* Sort the page offset array by moving all normal pages to
* the left and all zero pages to the right of the array.
*/
while (i <= j) {
uint64_t offset = pages->offset[i];
if (!buffer_is_zero(rb->host + offset, multifd_ram_page_size())) {
i++;
continue;
}
swap_page_offset(pages->offset, i, j);
ram_release_page(rb->idstr, offset);
j--;
if (pages->num > ARRAY_SIZE(stack_zero)) {
heap_zero = g_new(ram_addr_t, pages->num);
zero_offsets = heap_zero;
}
pages->normal_num = i;
for (uint32_t i = 0; i < pages->num; i++) {
uint64_t offset = pages->offset[i];
if (!buffer_is_zero(rb->host + offset, page_size)) {
pages->offset[normal_num++] = offset;
} else {
zero_offsets[zero_num++] = offset;
ram_release_page(rb->idstr, offset);
}
}
if (zero_num > 0) {
memcpy(&pages->offset[normal_num], zero_offsets,
zero_num * sizeof(ram_addr_t));
}
pages->normal_num = normal_num;
out:
qatomic_add(&mig_stats.normal_pages, pages->normal_num);
+1 -1
View File
@@ -133,7 +133,7 @@ struct MultiFDRecvData {
void *opaque;
size_t size;
/* for preadv */
off_t file_offset;
int64_t file_offset;
};
typedef struct {
+8 -8
View File
@@ -532,7 +532,7 @@ void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, size_t size)
}
void qemu_put_buffer_at(QEMUFile *f, const uint8_t *buf, size_t buflen,
off_t pos)
int64_t pos)
{
Error *err = NULL;
@@ -550,7 +550,7 @@ void qemu_put_buffer_at(QEMUFile *f, const uint8_t *buf, size_t buflen,
}
size_t qemu_get_buffer_at(QEMUFile *f, uint8_t *buf, size_t buflen, off_t pos,
size_t qemu_get_buffer_at(QEMUFile *f, uint8_t *buf, size_t buflen, int64_t pos,
Error **errp)
{
if (f->last_error) {
@@ -566,10 +566,10 @@ size_t qemu_get_buffer_at(QEMUFile *f, uint8_t *buf, size_t buflen, off_t pos,
return buflen;
}
void qemu_set_offset(QEMUFile *f, off_t off, int whence)
void qemu_set_offset(QEMUFile *f, int64_t off, int whence)
{
Error *err = NULL;
off_t ret;
int64_t ret;
if (qemu_file_is_writable(f)) {
qemu_fflush(f);
@@ -580,20 +580,20 @@ void qemu_set_offset(QEMUFile *f, off_t off, int whence)
}
ret = qio_channel_io_seek(f->ioc, off, whence, &err);
if (ret == (off_t)-1) {
if (ret == (int64_t)-1) {
qemu_file_set_error_obj(f, -EIO, err);
}
}
off_t qemu_get_offset(QEMUFile *f)
int64_t qemu_get_offset(QEMUFile *f)
{
Error *err = NULL;
off_t ret;
int64_t ret;
qemu_fflush(f);
ret = qio_channel_io_seek(f->ioc, 0, SEEK_CUR, &err);
if (ret == (off_t)-1) {
if (ret == (int64_t)-1) {
qemu_file_set_error_obj(f, -EIO, err);
}
return ret;
+4 -4
View File
@@ -72,11 +72,11 @@ QEMUFile *qemu_file_get_return_path(QEMUFile *f);
int qemu_fflush(QEMUFile *f);
bool qemu_file_set_blocking(QEMUFile *f, bool block, Error **errp);
int qemu_file_get_to_fd(QEMUFile *f, int fd, size_t size);
void qemu_set_offset(QEMUFile *f, off_t off, int whence);
off_t qemu_get_offset(QEMUFile *f);
void qemu_set_offset(QEMUFile *f, int64_t off, int whence);
int64_t qemu_get_offset(QEMUFile *f);
void qemu_put_buffer_at(QEMUFile *f, const uint8_t *buf, size_t buflen,
off_t pos);
size_t qemu_get_buffer_at(QEMUFile *f, uint8_t *buf, size_t buflen, off_t pos,
int64_t pos);
size_t qemu_get_buffer_at(QEMUFile *f, uint8_t *buf, size_t buflen, int64_t pos,
Error **errp);
QIOChannel *qemu_file_get_ioc(QEMUFile *file);
+5 -5
View File
@@ -1010,7 +1010,7 @@ static uint64_t physical_memory_sync_dirty_bitmap(RAMBlock *rb,
unsigned long *dest = rb->bmap;
/* start address and length is aligned at the start of a word? */
if (((word * BITS_PER_LONG) << TARGET_PAGE_BITS) ==
if ((((ram_addr_t)word * BITS_PER_LONG) << TARGET_PAGE_BITS) ==
(start + rb->offset) &&
!(length & ((BITS_PER_LONG << TARGET_PAGE_BITS) - 1))) {
int k;
@@ -4137,8 +4137,8 @@ static bool handle_zero_mapped_ram(RAMBlock *block, unsigned long from_bit_idx,
return true;
}
size = TARGET_PAGE_SIZE * (to_bit_idx - from_bit_idx);
offset = from_bit_idx << TARGET_PAGE_BITS;
size = (size_t)TARGET_PAGE_SIZE * (to_bit_idx - from_bit_idx);
offset = ((ram_addr_t)from_bit_idx) << TARGET_PAGE_BITS;
host = host_from_ram_block_offset(block, offset);
if (!host) {
error_setg(errp, "zero page outside of ramblock %s range",
@@ -4172,8 +4172,8 @@ static bool read_ramblock_mapped_ram(QEMUFile *f, RAMBlock *block,
/* Non-zero pages */
clear_bit_idx = find_next_zero_bit(bitmap, num_pages, set_bit_idx + 1);
unread = TARGET_PAGE_SIZE * (clear_bit_idx - set_bit_idx);
offset = set_bit_idx << TARGET_PAGE_BITS;
unread = (size_t)TARGET_PAGE_SIZE * (clear_bit_idx - set_bit_idx);
offset = ((ram_addr_t)set_bit_idx) << TARGET_PAGE_BITS;
while (unread > 0) {
host = host_from_ram_block_offset(block, offset);
+7
View File
@@ -64,6 +64,7 @@
#include "system/runstate.h"
#include "system/system.h"
#include "system/xen.h"
#include "system/whpx.h"
#include "migration/colo.h"
#include "qemu/bitmap.h"
#include "net/announce.h"
@@ -3317,6 +3318,12 @@ bool save_snapshot(const char *name, bool overwrite, const char *vmstate,
return false;
}
if (whpx_enabled()) {
error_setg(errp,
"WHPX: internal VM snapshots are not supported; use stopped-VM file migration");
return false;
}
if (!replay_can_snapshot()) {
error_setg(errp, "Record/replay does not allow making snapshot "
"right now. Try once more later.");
+92 -2
View File
@@ -1120,6 +1120,73 @@
'axis' : 'InputAxis',
'value' : 'int' } }
##
# @InputScrollPhase:
#
# Phase of a scroll gesture, such as two fingers moving on a touchpad.
#
# @none: The scroll is not part of a gesture.
#
# @may-begin: Fingers rest on the device, and a gesture may begin.
#
# @began: A gesture began.
#
# @changed: A gesture moved.
#
# @ended: A gesture ended.
#
# @cancelled: A gesture was cancelled.
#
# Since: 11.2
##
{ 'enum' : 'InputScrollPhase',
'data' : [ 'none', 'may-begin', 'began', 'changed', 'ended',
'cancelled' ] }
##
# @InputScrollMomentum:
#
# Phase of the momentum scrolling that follows a scroll gesture, which
# the source of the events computes.
#
# @none: The scroll is not momentum scrolling.
#
# @began: Momentum scrolling began.
#
# @changed: Momentum scrolling continued.
#
# @ended: Momentum scrolling ended.
#
# Since: 11.2
##
{ 'enum' : 'InputScrollMomentum',
'data' : [ 'none', 'began', 'changed', 'ended' ] }
##
# @InputScrollEvent:
#
# Smooth scroll input event: a distance to scroll rather than wheel
# notches, with the phases of the gesture it belongs to. The events
# up to the next synchronization make one report, and carry the same
# @phase and @momentum.
#
# @axis: Which axis is referenced by @value.
#
# @value: Distance in 1/256 pixel. Positive values scroll up (y) or
# left (x), as @wheel-up and @wheel-left of @InputButton do.
#
# @phase: Phase of the gesture.
#
# @momentum: Phase of the momentum scrolling.
#
# Since: 11.2
##
{ 'struct' : 'InputScrollEvent',
'data' : { 'axis' : 'InputAxis',
'value' : 'int',
'phase' : 'InputScrollPhase',
'momentum' : 'InputScrollMomentum' } }
##
# @InputEventKind:
#
@@ -1133,10 +1200,12 @@
#
# @mtt: a multi-touch input event
#
# @scroll: a smooth scroll input event (since 11.2)
#
# Since: 2.0
##
{ 'enum': 'InputEventKind',
'data': [ 'key', 'btn', 'rel', 'abs', 'mtt' ] }
'data': [ 'key', 'btn', 'rel', 'abs', 'mtt', 'scroll' ] }
##
# @InputKeyEventWrapper:
@@ -1178,6 +1247,16 @@
{ 'struct': 'InputMultiTouchEventWrapper',
'data': { 'data': 'InputMultiTouchEvent' } }
##
# @InputScrollEventWrapper:
#
# @data: Smooth scroll input event
#
# Since: 11.2
##
{ 'struct': 'InputScrollEventWrapper',
'data': { 'data': 'InputScrollEvent' } }
##
# @InputEvent:
# Input event union.
@@ -1193,7 +1272,8 @@
'btn' : 'InputBtnEventWrapper',
'rel' : 'InputMoveEventWrapper',
'abs' : 'InputMoveEventWrapper',
'mtt' : 'InputMultiTouchEventWrapper' } }
'mtt' : 'InputMultiTouchEventWrapper',
'scroll' : 'InputScrollEventWrapper' } }
##
# @input-send-event:
@@ -1260,6 +1340,16 @@
# { "type": "abs", "data" : { "axis": "x", "value" : 20000 } },
# { "type": "abs", "data" : { "axis": "y", "value" : 400 } } ] } }
# <- { "return": {} }
#
# .. qmp-example::
# :title: Begin a scroll gesture, moving 10 pixels up
#
# -> { "execute": "input-send-event" ,
# "arguments": { "events": [
# { "type": "scroll", "data" : { "axis": "y",
# "value" : 2560, "phase": "began",
# "momentum": "none" } } ] } }
# <- { "return": {} }
##
{ 'command': 'input-send-event',
'data': { '*device': 'str',
+4 -3
View File
@@ -2876,7 +2876,7 @@ DEF("smbios", HAS_ARG, QEMU_OPTION_smbios,
"-smbios type=11[,value=str][,path=filename]\n"
" specify SMBIOS type 11 fields\n"
"-smbios type=17[,loc_pfx=str][,bank=str][,manufacturer=str][,serial=str]\n"
" [,asset=str][,part=str][,speed=%d]\n"
" [,asset=str][,part=str][,speed=%d][,memory_type=%d]\n"
" specify SMBIOS type 17 fields\n"
"-smbios type=41[,designation=str][,kind=str][,instance=%d][,pcidev=str]\n"
" specify SMBIOS type 41 fields\n",
@@ -2942,8 +2942,9 @@ SRST
String 3: myapp:some extra data
``-smbios type=17[,loc_pfx=str][,bank=str][,manufacturer=str][,serial=str][,asset=str][,part=str][,speed=%d]``
Specify SMBIOS type 17 fields
``-smbios type=17[,loc_pfx=str][,bank=str][,manufacturer=str][,serial=str][,asset=str][,part=str][,speed=%d][,memory_type=%d]``
Specify SMBIOS type 17 fields. ``memory_type`` is the Memory Type
field's value, 1 to 255 (7, RAM, by default; 26 is DDR4).
``-smbios type=41[,designation=str][,kind=str][,instance=%d][,pcidev=str]``
Specify SMBIOS type 41 fields
Loaded 100 of 136 files, more files were not shown because too many files have changed in this diff. Show more