Author SHA1 Message Date
千川白浪 d6e2e83d78 Merge pull request #11 from reims-go/reiasu2/win32-ioring
block/win32-aio: use Windows 11 IORING for zero-waiter completions (rebased #5)
2026-12-05 14:25:05 +08:00
千川白浪 501093c1a2 Merge pull request #10 from reims-go/reiasu2/whpx-msix-direct
virtio-pci, hw/nvme: direct MSI-X on WHPX and NVMe doorbell offsets (rebased #2)
2026-12-05 14:24:13 +08:00
棠渚听潮andClaude Opus 5.5 c088828a40 block/win32-aio: use Windows 11 IORING for zero-waiter completions
Batch native I/O submissions and dispatch completions from the owning AioContext using a ring event and userspace polling. Fall back to the existing IOCP waiter when IORING is unavailable or disabled.

Rebased onto intel-vm-suspend after #8 (maintainer): the bounce cache
keeps #8's size, #8's zero-copy scatter/gather stays on the IOCP path
only (its completions need the IOCP waiter, which IORING mode does not
run), and util/aio-win32.c gains aio_poll_disabled(), which the IORING
submit reads and which only aio-posix.c defined.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 23:11:36 -07:00
棠渚听潮 0f28928e75 virtio-pci: deliver queue MSI-X directly on WHPX
Mirror eligible software virtio-blk queue routes under a transport mutex. Preserve masked notifications in the MSI-X PBA across route changes, device stop, and VM state save. Retain software notifiers for config changes and delivery fallback.
2026-12-04 23:08:59 -07:00
棠渚听潮andClaude Opus 5.5 edae6d7473 hw/nvme: keep doorbell ioeventfd offsets and notifiers across DBBUF_CONFIG
Queue IDs reach 65535, so the doorbell offset of a queue above 8191,
(qid << 3) plus the CQ's 4, overflows a uint16_t and registers the
ioeventfd at the wrong address; hold it in a uint32_t. A guest that sends
Doorbell Buffer Config again re-initialised the notifiers of queues that
already had them; skip queues whose ioeventfd is enabled.

Taken from "whpx: accelerate MMIO ioeventfd writes with doorbells" in
reims-go/qemu-reims-vgpu#2, whose WHPX doorbells #8 has since provided.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 23:08:59 -07:00
千川白浪 8c402d1825 Merge pull request #6 from reiasu2/fix/hid-f13-f24-usages
hw/input/hid: fix F13-F24 USB HID usage mappings for keycodemapdb QNUMs
2026-12-05 13:44:29 +08:00
Xiaochi You c6f4d7b5c6 Merge pull request #8 from reims-go/perf/win32-aio-whpx-nvme
perf(win32,whpx,nvme): fast MMIO, WHPX doorbells, batched scatter-gather AIO, and IOThread polling
2026-12-05 11:53:18 +08:00
YXC0915 b8f4997fb0 perf(win32,whpx,nvme): fast MMIO path, WHPX doorbells, batched IOCP scatter-gather, and IOThread polling 2026-12-05 11:52:24 +08:00
YXC0915 44866c2d20 win32: advertise the fixed native block AIO backend 2026-12-05 11:49:47 +08:00
Xiaochi You a9415d94d0 Merge pull request #7 from yxc0915/steelbrain/sync-qemu-f073adf
Merge the latest upstream QEMU into the Windows runtime branch
2026-12-04 16:11:06 +08:00
YXC0915 0c0d881c49 Compare resolved symlink targets on Windows
Windows readlink can use the extended path prefix for the same target. Keep checking that the entry is a symlink and compare the resolved target, including entries built after configure.
2026-12-04 16:04:37 +08:00
YXC0915 dbe8ab5fce Merge original Reims QEMU at f073adfb3e
Keep the Windows suspend, mapped RAM, and Winsock changes. Use the upstream WHPX timer probe and graphics RAM-device mapping while keeping pool pieces outside migration.
2026-12-04 16:02:54 +08:00
Anees Iqbal f073adfb3e 🐛 Make reims-graphics' pool pieces RAM devices, which vfio may skip
A VM with a vfio-pci device beside reims-graphics-pci ended as the guest's
graphics driver started: "vfio_container_dma_map(..., 0xcc0000000, 0x1000000,
...) = -14 (Bad address)", then "vfio: DMA mapping failed, unable to
continue" (steelbrain/reims-vgpu#213, a Linux host with an RX 6700 XT and a
USB controller passed through). 0xcc0000000 is the guest's Shared pool's
first piece, a 16 MiB block of the GPU's memory that the library has QEMU map
into the guest. The host's mapping of that memory is a dma-buf's, which the
IOMMU refused to map. vfio's listener maps every RAM section for the passed-
through device's DMA, and at run time a refused map is a hardware error for
plain RAM and a warning, once, for a RAM device (hw/vfio/listener.c).

Each pool piece is now a RAM device (memory_region_init_ram_device_ptr), with
no property or option. In this QEMU a RAM device is otherwise RAM: KVM's and
WHPX's slot maps, HVF's, TCG's softmmu and a device's DMA
(memory_access_is_direct, which reads memory_region_is_ram alone) take it as
before. What changes besides vfio: vhost-vdpa skips it, a guest memory dump
leaves it out, and `info mtree` names it ramd. The guest's RAM and BAR 2, the
device's region, stay plain RAM: vfio maps them as before.

(cherry picked from commit 325206b3c747feaa6675fcc9562680c21bf8cfe9)
2026-12-03 16:40:11 -08:00
Anees Iqbal d20c59a10e ✅ Run symlink-install-tree's test with the script's whole path
The test runs the script in each case's own build directory, so a relative
SCRIPT, as meson test never gives it but a run from the source tree does,
named no file there and every case failed.
2026-12-03 16:14:45 -08:00
Anees Iqbal 828402520c 🐛 Copy into qemu-bundle where the host refuses a symbolic link
Configuring QEMU on a Windows host without Developer Mode or an
administrator's rights stopped at symlink-install-tree.py: os.symlink fails
there with WinError 1314, a required privilege not held, and the script
raised on every error but EEXIST, after a line asking for Developer Mode.
qemu-bundle only serves a run from the build tree; `ninja install`, which
installs from the build, never reads it.

Where os.symlink is refused, for any error but EEXIST, the script now copies
the entry instead: a file with its metadata, a directory whole. An entry
built after the configure step (the executables, built firmware, generated
files) does not exist yet and is left out, which only a run from the build
tree misses; one line says how many entries were copied and left out.

tests/symlink-install-tree runs the script over a fake MESONINTROSPECT's
install list in a scratch build directory: with os.symlink refused under
three errnos, the bundle holds copies of the file and the directory, leaves
out the entry not built yet, and configures again over its copies; and
where the host makes links, it makes them, as before, and keeps them on a
second run. meson test runs it in the suite scripts.
2026-12-03 16:12:27 -08:00
Anees Iqbal 2f7c68a7dc 🐛 Put reims-graphics' last pixel at the tablet's maximum
The device gave QEMU's input layer the window's pixel, at most size - 1,
and QEMU scales [0, size] over the tablet's range, so the last pixel never
reached the tablet's maximum, and no position put a macOS guest's cursor in
a display's last column or row. Measured with capture off on macOS 26
guests: the last column of a display 2016 pixels across went as 0x7fee and
put an x86-64 26.7.2 guest's cursor at 2014.92, and the last row of 1260 as
0x7fe4, at 1258.94, over KWin's Wayland and SDL's X11 (potluck jobs
m3-max-84927, m3-max-85009); on a Windows host at 1439.45 of 1440 and
809.47 of 810 (m3-max-85087); and an arm64 guest's at 1007.43 of 1008
points across, at 2x (m3-max-84982).

The last pixel of each axis now goes as size, the tablet's maximum
(reims_pointer_axis, hw/display/reims-pointer.h), on every display: at
the maximum the cursor was at 2015.98 and 1259.98, and at 1007.98 on arm64
(m3-max-84928, m3-max-84980, m3-max-84983). A display of the guest's placed beside it does not take the
maximum, as the guest scales the tablet over the display its cursor is on:
with display 1 right of display 0, the maximum on display 0 left the cursor
at 2015.98 of display 0 (m3-max-84980).

tablet-right-edge-head, which gave the maximum to the x of one display, as
an opt-in property, goes with its page in docs/system/devices; reims-ctl
never set it. tests/unit/test-reims-pointer.c checks the values QEMU's
scaling then gives.
2026-12-03 12:19:25 -08:00
Anees Iqbal 3ea8ab3b78 🔥 Drop reims-graphics' Dock pressure and the motion-only mouse
dock-pressure moved a second USB mouse, usb-mouse with motion-only=on
(relative Y, no buttons), down 18 counts 32 times, 80 ms apart, once the
window's pointer reached a display's bottom row, for macOS to show a Dock
hidden there. Measured with capture off, without the property and then
with it, on macOS 26 guests:

- An x86-64 26.7.2 guest's tablet alone shows its hidden Dock at the
  bottom, right and left edges, over KWin's Wayland and SDL's X11 on Linux
  and on a Windows host (potluck jobs m3-max-84927, m3-max-85009,
  m3-max-85087). With the property the Dock showed the same; the pulses
  moved the cursor from 1258.94 to 1259.98 of 1260 (m3-max-84928), the last
  row, which the next commit gives the tablet itself.
- An arm64 guest under TCG shows its hidden Dock at the right and left, and
  not at the bottom: not with the tablet at the bottom row (629.45 of 630
  points) nor at the tablet's maximum (629.98; m3-max-84982), and not after
  the pulses either, which took the cursor to 629.98 (m3-max-84983).

The pulses showed no Dock the tablet did not, so they go with the second
mouse, and reims-ctl's command stays as it is: hw/input/hid.c's and
hw/usb/dev-hid.c's motion-only mode and its case in
tests/qtest/usb-hcd-xhci-test.c, the device's timer with its reset and
finalize, and reims_pointer_bottom with its unit test.
2026-12-03 12:19:08 -08:00
charlysound 72759d2840 Expose pointer edge properties and test USB motion-only reports
Replace environment switches with explicit opt-in device properties, share pointer arithmetic with unit tests and cancel pressure timers at reset. An xHCI regression reads actual USB reports: ordinary mice retain buttons, motion-only mice deliver relative Y without buttons beside a tablet.

Validated before the host reboot: full x86 QEMU build, two pointer unit tests, 16 existing xHCI cases, the new report regression and PCI syntax checking with warnings denied. AI-assisted downstream contribution; no DCO certification is asserted.
2026-12-03 14:37:25 +01:00
charlysound ba62be0dee Preserve reims tablet endpoints and add bounded Dock pressure with motion-only HID 2026-12-03 12:27:24 +01:00
棠渚听潮 c28df53863 hw/input/hid: fix F13-F24 USB HID usage mappings for keycodemapdb QNUMs
usb-kbd converts guest keyboard events through linux -> qnum -> hid_usage_keys[].
The legacy hid_usage_keys[] slots did not match QEMU's keycodemapdb QNUM values
for KEY_F13..KEY_F24:

- F13..F15 (qnum 0x5d..0x5f) mapped to F17..F19 (0x6c..0x6e)
- F20 (qnum 0x5a) mapped to F14 (0x69)
- F16..F19, F21..F24 (qnum 0x55, 0x83, 0xf7, 0x84, 0x74, 0xf9, 0x6d, 0x6f) mapped to 0x00 and were silently dropped

None of these 12 QNUM indices collide with any other entry in
input-keymap-linux-to-qnum.c.inc. Update hid_usage_keys[] so F13-F24
round-trip losslessly to USB HID usages 0x68-0x73 (needed for macOS
modifier-key remapping carriers F20/F21/F22/F24 and extended F-keys).
2026-12-03 13:32:27 +08:00
Anees Iqbal 445170b5c6 🆕 Let -smbios type=17 give the array empty slots and a form factor
QEMU's memory array has only the devices RAM fills, as DIMMs: on current
machines one, so a macOS guest's System Information lists a single slot,
where the Mac it presents may have four SO-DIMM slots.

slots= makes the array that many devices, those past the ones RAM fills
empty (size 0, type and speed unknown, only their locators named), and
type 16's Number of Memory Devices counts them all; form_factor= sets every
device's Form Factor (9, DIMM, by default). Without them the tables are as
before. bios-tables-test's smbios-memory-slots checks both cases.
2026-12-02 16:50:00 -08:00
Anees Iqbal 1d61410693 🆕 Let reims-graphics-pci's resolution give each display its size
The resolution property gave every display the same size: each window's
first size, or each display's mode without a window. A VM of several
displays on screens of different sizes could not open each window at its
screen's size. The property now also takes a comma-separated list of one
size per display, in the displays' order (on QEMU's command line each comma
is written ",,": resolution=2560x1440,,1920x1080): each window opens at its
own, and without a window each display offers its own as its mode, through
the library's headless_modes. Another count of sizes than displays is
refused at realize, saying so. One size is every display's, as before, and
the device then gives the library the config it gave before.
2026-12-02 15:44:29 -08:00
Anees Iqbal d72b4ac321 🐛 Let -smbios type=16 set the memory array's error correction
QEMU wrote 0x06, multi-bit ECC, as the memory array's Memory Error
Correction on every machine, and OpenCore copies it into an x86-64 macOS
guest's SMBIOS, so System Information shows the memory as "ECC: Enabled" on
an iMac20,1, whose RAM has none. The new error_correction option sets the
field, 1 to 7 as SMBIOS numbers them (3 is none); without it the field
stays 6.

bios-tables-test: smbios-error-correction reads type 16's field without the
option (6) and with error_correction=3 (3). Red before this commit
(m3-max-80517): QEMU refused -smbios type=16 ("Don't know how to build
fields for SMBIOS type 16").
2026-12-02 15:09:09 -08:00
Anees Iqbal 79d47edfe1 🐛 Keep the TPR an emulated instruction writes under WHPX
With kernel-irqchip=off the guest's xAPIC is QEMU's, and its TPR is
mirrored in the vCPU's CR8. whpx_set_registers set vcpu->tpr, the TPR CR8
is taken to hold, from the APIC at every level, but wrote CR8 only above
WHPX_LEVEL_FAST_RUNTIME_STATE, the level an emulated instruction's
registers go back at. So a TPR the instruction changed (a read-modify-write
of the xAPIC's TPR at 0xfee00080, or an x2APIC WRMSR) matched vcpu->tpr
without reaching CR8: whpx_vcpu_pre_run saw nothing to write, and at the
next exit whpx_vcpu_post_run put CR8's old TPR back into the APIC, undoing
the guest's write. vcpu->tpr now changes only where CR8 is written, so
pre_run writes the new TPR to CR8.

Measured on an i7-8700B under Windows 11's WHPX with a guest of our own
that ORs 0x50 into the TPR and reads it back: kernel-irqchip=off read 0x00
in 3 of 3 runs, kernel-irqchip=on 0x50 in 3 of 3 (QEMU a86885f8, the same
lines as 21e66365; potluck job m3-max-80368).
2026-12-02 14:36:40 -08:00
Anees Iqbal 0beafad0d8 🐛 Enable a firmware flash drive's I/O status for its stop
1e223049 stops the VM through blk_error_action() where a flash write finds
the host disk full, and the stop records the error in the drive's I/O
status, which asserts that the status is enabled: QEMU aborted instead of
pausing (qtest pflash-cfi01/enospc-pauses, potluck job m3-max-80263). A
writable flash drive now enables it at realize, as IDE and virtio-blk do,
so the VM pauses and query-block answers the drive's io-status nospace,
which reims-ctl reads to name the file whose disk is full.
2026-12-02 14:16:45 -08:00
Anees Iqbal 1e223049b2 🐛 Pause the VM where a flash write finds the host disk full
pflash_cfi01, the firmware's flash (an x86-64 guest's OVMF variables),
wrote each program and erase to its drive and, where the write failed,
logged "Could not update PFLASH" and went on: its memory kept the new bytes,
so the guest read them, but the file never got them, and the change was
gone at the VM's next start. On a full host disk that is any variable the
firmware or the guest's boot loader writes. The disks' devices pause the
VM instead, under -drive's default werror=enospc.

Now a write whose drive's error action is stop marks its bytes to write
again, and pauses the VM with io-error as the disks' devices do; as the VM
resumes, the flash writes them again from its memory, and pauses again
where that fails too. The drive's action is -drive's (if=pflash takes no
werror, so ENOSPC stops), and a drive's other errors still only log the
line, as before.

What the guest sees: on a full host disk the VM pauses at the flash write,
and after space is freed and the VM resumes, the variable is in the file.

The qtest pflash-cfi01-test: enospc-pauses (red before this: the VM ran on
and the file kept 0xff), and eio-runs, which held before and still holds.
2026-12-02 14:12:27 -08:00
Anees Iqbal 51d47e288e 🐛 Pause the VM where an NVMe write finds the host disk full
A VM whose disk is on QEMU's nvme device went on running when the host's
disk filled: the device completed the failed write to the guest with Write
Fault, which macOS's file system takes as a failed disk. AHCI and
virtio-blk pause the VM instead, under -drive's default werror=enospc, and
QEMU runs the writes again once the VM resumes, so the guest never sees
them fail and carries on once space is freed.

nvme and nvme-ns forced report/report on their drive, having no rerror and
werror properties (a zeroed BlockConf reads as report), and no completion
path asked the drive's error action. Now both devices take the properties,
AUTO by default as virtio-blk's are, so a -drive's werror and rerror apply;
a failed Read, Write, Write Zeroes, Flush or Dataset Management on an I/O
queue of a namespace that is not zoned follows the drive's action. Under
stop the command is held on its SQ with no completion, QEMU pauses the VM
with io-error and query-block gives the drive's io-status (nospace), and
the VM's resume runs the command again from its fetched copy. Under ignore
it completes as done, and under report with its error, as before, now with
QMP's BLOCK_IO_ERROR as the other devices send it. Other commands (Copy,
Compare, Verify, zone commands, admin commands) and cancels keep reporting.
A reset while the VM is paused drops the held commands with the queues,
and a migration with one held is refused, where it would have asserted.

What the guest sees: on a full host disk the VM pauses with no I/O error,
and after space is freed and the VM resumes, the write completes. An I/O
error other than ENOSPC still reaches the guest as before.

The qtests: enospc-pauses (red before this: the write completed with
status 0x280 and the VM ran on), enospc-reset, and eio-reports, which held
before and still holds.
2026-12-02 14:02:32 -08:00
Anees Iqbal 21e663657d 🐛 Release reims-graphics at a quit of a VM that was not running
At QEMU's quit, vm_shutdown stops the VM, and the device's VM state handler
tears it down: the library's release of its last device lets go of the GPU
device before the process exits. A VM that was not running at the quit hears
no such stop: one paused (by QMP's stop, or by a full disk), one never started
past -S, or one paused by a shutdown whose action pauses (-no-shutdown). Its
device stayed to the exit, the library's quiesce at the end of QEMU's cleanup
answered that it still held a GPU device, and QEMU ended with _exit.

The cleanup notifier now first tears down each device no teardown ran for
(its VM state handler still set), BAR 2 out of the guest's address space
first, as at a stop. The release then lets go of the GPU device, the quiesce
answers true, and QEMU ends with exit(), running its exit handlers. Only a
device a display's read kept (the GPU stopped answering) still ends QEMU with
_exit.

What changes for the host: QEMU quits such a VM by exit() instead of _exit;
the guest sees nothing, as it no longer runs.
2026-12-02 12:07:38 -08:00
Anees Iqbal 0f7f65aea1 🆕 Offer the resolution as a windowless display's mode
With REIMS_VGPU_WINDOW=0, or another display of QEMU's, the device passed
the library no window config, and the resolution property went nowhere:
every display offered the guest 1920x1080 whatever the VM's setting. The
library's config now carries a headless mode (headless_mode_width and
_height, read only where window is NULL), and the device gives it the
resolution there, so a VM started headless gets the mode its settings
name, at 60 Hz.
2026-12-02 10:45:25 -08:00
Anees Iqbal a60aa2b328 📝 Say a STATUS write of 0 also waits for the reset's settle
reims-vgpu's reset now waits, before it returns, until the GPU work the
guest committed before it has completed and run its completed handlers, at
most 30 s, so none of it writes the guest's memory after the reset. A STATUS
write of 0 runs that reset on the vCPU, which calls the library with no BQL.
The settle waits for nothing of QEMU's: the completed handlers' raise is
the irqfd's write, msi_lock, which waits for nothing else, or a bottom
half. So the register accesses still need no BQL, and the comment above
them says what a STATUS write of 0 waits for.
2026-12-02 10:19:07 -08:00
Anees Iqbal 364cd3645e 🐎 Trim dsound's reserve and rate through the resampler
A dsound playback voice placed its write position 60 ms past DirectSound's
write cursor and kept that reserve for the stream's life. An x86-64 macOS
guest's posts come down to their least margin past the write cursor once a
turn of their 41.67 ms grid, so most of the reserve was latency: a period's
first frame waited 107 ms at the median to play (p99 129) where the guest's
players are told 2 ms. And the host's device plays to its own clock: one
that runs fast eats the reserve until the audio runs out before the write
cursor, a gap of silence each time (forced 227 ppm fast, one every 260 s;
at 100 ppm about one every 10 minutes); one that runs slow grows the fill
and the latency.

Now the voice trims the rate its guest's audio is resampled to. In 2 s
buckets of its reads with audio flowing it takes the margin's least. The
level is the least of the last five buckets, and the drift the slope of the
buckets' least margins, with what the trim itself played out added back, by
least squares over the last 30 once 15 are in. The voice plays at its rate
less the drift and 1 Hz more for each millisecond the level stands past the
15 ms it keeps, within 1000 ppm (44 Hz at 44.1 kHz, 1.7 cents of pitch). A
gap keeps 10 ms more, up to 45, and starts the buckets again; the drift
stays. A stream still starts 60 ms past the write cursor, which its first
posts need whatever their phase on the grid, and trims from there. The
trace event dsound_trim records each bucket.

The rate moves through the mixing engine's resampler: st_rate_set_out_mhz()
sets a rate converter's output rate with its interpolation going on from
where it stands, and audio_pcm_hw_trim_out() sets it for a voice's soft
voices. A converter once trimmed interpolates from then on, even where its
rates come out equal: going back to copying would drop the frame the
interpolation holds. DirectSound's own frequency was tried first and
clicked: on a Windows 11 host each IDirectSoundBuffer_SetFrequency, of any
size, moved the audio by 4 to 19 us some 35 ms later, 10.8 clicks a minute
at rest.

What the guest hears on a Windows host: its sound about 35 ms sooner at the
median, and no gap from the device's drift, at a pitch within 1.7 cents of
its own. Other hosts: nothing changes, since no other backend trims.

Measured on our Windows 11 test host (UHD 630): a 26.7.2 x86-64
guest played a two-tone sine, captured by WASAPI loopback, 200 s at rest,
200 s busy, then 840 s with a scratch hook (never landed) setting the
buffer's DirectSound frequency 10 Hz (227 ppm) fast at the stream's start.
Base da50fbf9 with the hook (m3-max-78857) against this with it
(m3-max-79145):
- clicks a minute at rest 0 and 0, busy 0.93 and 0, in the drift phase
  0.58 and 0;
- a period's first frame's wait from 60 s in, median / p99: at rest
  106.7 / 129.3 ms and 71.7 / 96.4, busy 104.6 / 127.3 and 72.7 / 97.0;
- gaps in 834 s at +227 ppm: 3 (260 s apart) and 0, the margin's least
  11.8 ms, the drift taken as 10.2 Hz.

test-dsound-ring holds the trim's arithmetic: on the functions without the
trim its five trim tests fail. test-audio-rate holds the resampler: the
output stays on the input's curve while the rate moves, at 48 to 44.1 kHz
and at equal rates, where a converter that went back to copying stepped by
a whole frame (0.14 of the amplitude).
2026-12-02 10:12:06 -08:00
Xiaochi You 7aa1f2fb78 Merge PR #4: Optimize WHPX MMIO and Win32 polling
whpx, win32: fast-path aligned 32-bit MMIO MOV stores and reuse main-loop fd_sets
2026-12-02 23:59:28 +08:00
棠渚听潮 847827bb31 whpx, win32: reuse main-loop fd_sets and reduce interrupt/I/O polling overhead 2026-12-02 19:33:10 +08:00
棠渚听潮 9a361cb96d whpx: fast-path aligned 32-bit MMIO MOV stores 2026-12-02 19:33:10 +08:00
棠渚听潮 da50fbf90e 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)

reims-vgpu's take of PR 22, whole, as benched (planner's verdict 12-02).
reims-ctl runs every Windows disk with aio=threads and cache=writeback,
through the file driver. On that path this PR fixes reads that failed and
came back as zeros with success, a leaked request on a failed flush, and a
truncate that could set the wrong end of file. Both silent-corruption
defects reproduced on the base and are clean here. The coroutine hooks
need this commit's win32-aio.c, so the PR is carried whole. aio=native is
not turned on by this.

A change the PR does not name: buffered files get request alignment 1
where it was the volume's sector size. That is what the POSIX side does
for buffered files. No 4096-byte-sector volume was available to run it on.

Bench on the Windows mini, venue C:, its system disk, a USB NVMe (the
only disk online). qemu-img bench, qcow2 over 4 GiB, -t writeback -i
threads. Seconds a1/a2/b1/b2 (A = the fork before, B = this PR), then
the a and b spreads:
  1M seq write QD16       8.13/7.57/7.39/7.43    7.4%  0.5%
  1M overwrite            6.05/3.83/5.02/3.24   57.7% 55.0%
  1M seq read             7.01/7.10/6.78/6.94    1.2%  2.4%
  4K seq write QD16       3.74/3.82/3.79/3.84    2.1%  1.2%
  4K seq read QD16       24.23/24.15/23.56/22.75 0.3%  3.5%
  4K rand write QD16      1.39/1.51/1.41/1.33    9.2%  5.8%
  4K rand read QD16      19.25/19.61/19.45/16.41 1.9% 18.5%
  4K rand write QD1       0.57/0.60/0.61/0.71    6.0% 16.9%
  4K rand read QD1        4.41/4.24/4.19/3.89    4.1%  7.8%
  1M rand write QD16      1.97/1.44/2.38/1.71   36.9% 39.2%
  1M rand read QD16       8.35/8.09/7.99/6.76    3.2% 18.2%
  4K, a flush per write   9.04/9.39/9.09/7.99    3.9% 13.7%
  64K QD16, flush per 16  1.17/1.18/1.32/1.02    1.5% 29.6%
No row is slower beyond 3% and beyond both spreads. qemu-img check and
compare: every arm identical to a1. A byte-range lock held by another
process: the base reads zeros with success ("Pattern verification failed
at offset 0"); this PR answers "Input/output error". 400 truncates under
writes: the base lost the tail (offset 66060288); this PR is clean at
464 MiB.
2026-12-02 03:08:00 -08:00
棠渚听潮 2655904c24 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 03:07:44 -08:00
棠渚听潮 55e5a3ca42 Merge pull request #22 from reiasu2/fix/win32-aio-iothread-direct 2026-12-02 03:07:44 -08:00
Anees Iqbal 34d2bb1592 📝 Say every kernel at the floor knows the pool's KVM capability
The comment on reims_graphics_kvm_pool_host_memory (5d0e52bd) counted a
kernel older than KVM_CAP_ARM_CACHEABLE_PFNMAP_SUPPORTED among the hosts that
answer none. Linux 6.18's headers define the capability (243), and the
device's realize refuses a Linux host below 7.2 (458f4b7b) before it asks, so
no host the device runs on is such a kernel: the clause is dropped, and the
comment says the floor's kernels all know the capability.

The comment at the check's call in the realize is wrapped at 80 columns.
Nothing the device does changes.
2026-12-02 02:07:29 -08:00
Anees Iqbal 30d1109732 🎨 Wrap WHPX's nested virtualization and MMIO lines at 80 columns
The warning that nested virtualization could not be turned on (73977854)
was one line of 122 columns, indented as though inside a block it is not
in, and the guest-error log of an MMIO write the fast path dispatched
(0c429b2a) ran to 87. Both are wrapped, and the warning's block indented as
its if.

The warning now reads "WHPX: Failed to enable nested virtualization,
hr=...: going on without it"; nothing else changes.
2026-12-02 02:07:29 -08:00
Anees Iqbal 2d8960b843 🎨 Report a fiber that cannot be made with error_report
qemu_coroutine_new's and qemu_coroutine_self's checks of the fiber they make
(6059c36f) wrote their failure with fprintf, where QEMU's code reports
through error_report, which gives the line QEMU's prefix and timestamp and
sends it to the monitor where one is current; one line was also past 80
columns. The comment on CreateFiberEx now says what the call does and why.

Nothing changes but the failure's line: "CreateFiberEx of a 1048576-byte
stack, 65536 bytes committed, failed: error N", or "ConvertThreadToFiber
failed: error N", before the abort as before.
2026-12-02 02:01:28 -08:00
Anees Iqbal 8b67676b8c 🐛 Ask the TSC deadline probe's partition with the guest's processor
The probe of whether Hyper-V refuses the TSC deadline timer's register runs
on a partition of its own (81437f75), which got a processor count of one and
the local APIC's emulation and nothing else of the guest's partition: Hyper-V
gave it its default processor features, not the feature banks the guest's
partition was set to, so it could answer for another processor than the
guest's.

The probe's partition now takes what whpx_accel_init gave the guest's: the
processor feature banks where the host is not legacy Windows, and nested
virtualization where the local APIC is Hyper-V's and the banks offer it.
Where a step of the probe fails, QEMU now warns, naming the step and its
HRESULT, where it went on silently; the guest is offered the timer then, as
before. The comment says why the probe has a partition of its own.

What hosts see: the refusal line, and the guest's TSC deadline timer, follow
the guest's own processor; a probe that fails is named in QEMU's log.
2026-12-02 02:00:58 -08:00
Anees Iqbal 2517812ef9 ✅ Test WHPX's MMIO store decoder and address check
whpx-mmio.h's decoder (whpx_decode_mov_store32), effective address
(whpx_mov_store32_ea) and address check (whpx_mmio_write32_address_valid)
are built only into whpx-all.c, which only a Windows host builds, so nothing
held them on the hosts our checks run on. A wrong answer there writes a
guest's store to another register or with another value, or moves RIP past
the wrong number of bytes, with no emulator to catch it.

tests/unit/test-whpx-mmio.c holds them on any host:
- the stores the fast path takes, MOV r/m32, r32 and MOV r/m32, imm32 with
  and without REX.R, REX.X and REX.B, through a base, a SIB with and without
  an index, RIP and a SIB's disp32 alone, with each field the decoder gives;
- what it leaves to the emulator: REX.W, register destinations, C7 /1, other
  opcodes, every legacy prefix, bytes short of the instruction, more than 16
  bytes and an exit length other than the decoded one;
- the effective address, the displacement sign-extended, RIP-relative from
  the next instruction;
- the address check, which takes only the exit's guest virtual address,
  4-aligned and at the guest physical address's place in its page.

What a Windows host runs does not change.
2026-12-02 02:00:52 -08:00
Alex Gleason 7588dea425 Merge pull request #20 from alexgleason/collapse-opt-in 2026-12-02 01:54:05 -08:00
vintoware 5d0e52bd2d 🐛 Ask for a pool of host memory where KVM maps no cached GPU memory
Linux's KVM on arm64 takes a cacheable VM_PFNMAP mapping as a memory slot
only where the CPU has stage-2 forced write-back and CACHE_DIC, and the VM
says so as KVM_CAP_ARM_CACHEABLE_PFNMAP_SUPPORTED. Every host mapping of a
Honeykrisp allocation is VM_PFNMAP, so on an M1 Pro under Fedora Asahi Remix
45 the reims-graphics device's first Shared pool piece failed
KVM_SET_USER_MEMORY_REGION2 with EINVAL, and QEMU exited
(steelbrain/reims-vgpu#174).

The device now sets the library's pool_host_memory where it runs under KVM on
an arm64 host and the VM does not answer the capability, which a kernel older
than it does not either: the pool's blocks are then memfds of the library's
that the GPU imports, which KVM maps as guest memory, cached, as it maps the
guest's RAM. The check is in reims-graphics-pci-kvm.c, which only targets
with KVM link, with its stub beside the others; it asks the VM through
kvm_vm_ioctl, since kvm_vm_check_extension is declared for per-target builds
alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 0d6ff26282)
2026-12-02 01:48:46 -08:00
vintoware 14e100f44c Merge pull request #19 from vintoware/steelbrain/pool-host-memory 2026-12-02 01:48:46 -08:00
棠渚听潮 f0b5bd62f9 whpx, win32: reduce LAPIC IRR, PIO IN, and aio-win32 polling overhead
(cherry picked from commit f2cf08332b)
2026-12-02 01:48:46 -08:00
棠渚听潮 0c429b2a7d whpx: fast-path aligned 32-bit MMIO MOV stores
(cherry picked from commit b448d406e6)
2026-12-02 01:48:46 -08:00
棠渚听潮 7c06db0409 Merge pull request #23 from reiasu2/pr/whpx-mmio-fastpath-and-cleanup 2026-12-02 01:48:46 -08:00
棠渚听潮 f2cf08332b whpx, win32: reduce LAPIC IRR, PIO IN, and aio-win32 polling overhead 2026-12-02 16:50:04 +08:00
棠渚听潮 b448d406e6 whpx: fast-path aligned 32-bit MMIO MOV stores 2026-12-02 16:50:03 +08:00
Xiaochi You e6d7cb7422 Merge PR #1: Fix Windows user NAT socket starvation
Size Winsock select fd_sets from the current socket count.
2026-12-02 01:13:18 +08:00
ssdsl0126 08ebfef76c util/main-loop: size Win32 select fd_sets dynamically
On Windows, the default Winsock FD_SETSIZE is 64. In util/main-loop.c,
os_host_main_loop_wait() populated fixed stack-allocated fd_set buffers
with FD_SET(), silently dropping any sockets past the first 64 entries in
gpollfds. Under libslirp user NAT, background guest traffic (for example
macOS Tahoe right after boot) routinely exceeds 64 active sockets, causing
newly created UDP/ICMP sockets to starve until older UDP flows expire.

Introduce a Win64-safe dynamically allocated QemuWin32FdSet helper
(include/qemu/win32-fdset.h) with compile-time fd_set ABI layout
assertions and deduplication, allocate read/write/exception sets for
gpollfds->len in util/main-loop.c, and add a Windows-only unit test
(tests/unit/test-win32-fdset.c) covering empty/duplicate handling and
63/64/65/128/1024 simultaneously ready Winsock sockets.
2026-12-02 00:47:58 +08:00
棠渚听潮 e60f01ecb6 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.
2026-12-01 22:38:10 +09:00
棠渚听潮 edfe3ebd86 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).
2026-12-01 22:12:35 +09:00
Nwflower 6059c36fe4 util/coroutine-windows: reserve 1 MiB stack with 64 KiB initial commit and check fiber creation
CreateFiber(1 MiB, ...) commits the full 1 MiB stack upfront per coroutine, which can exhaust Windows commit charge during burst disk I/O + GPU workloads and return NULL (later crashing inside SwitchToFiber(NULL)). Use CreateFiberEx(64 KiB, stack_size, 0, ...), reuse existing fibers via IsThreadAFiber(), and abort with GetLastError() on NULL.
2026-11-30 00:06:07 -07:00
Nwflower 7397785484 whpx: make nested virtualization property failure non-fatal
Some Windows 11 hosts report NestedVirtSupport via WHvGetCapability yet fail WHvSetPartitionProperty(WHvPartitionPropertyCodeNestedVirtualization) with hr=0x80370302 (WHV_E_UNKNOWN_PROPERTY). Log a warning and clear Bank1.NestedVirtSupport instead of aborting VM startup so kernel-irqchip=on remains usable.
2026-11-30 00:06:07 -07:00
Nwflower 81437f752b whpx: probe TSC deadline on throwaway partition and guard WHvResetPartition
Fixes two crashes on Windows 10 22H2 (Build 19045) WHPX hosts:
1. whpx_tsc_deadline_refused() previously created and deleted vCPU 0 on the real partition, causing whpx_init_vcpu() to fail with E_INVALIDARG (0x80070057) when recreating vCPU 0. Probe on a throwaway partition instead.
2. Guard whp_dispatch.WHvResetPartition before calling it in whpx_set_registers(), as this function pointer is NULL on Windows 10.
2026-11-30 00:06:06 -07:00
vintowareandClaude Opus 5.5 0d6ff26282 🐛 Ask for a pool of host memory where KVM maps no cached GPU memory
Linux's KVM on arm64 takes a cacheable VM_PFNMAP mapping as a memory slot
only where the CPU has stage-2 forced write-back and CACHE_DIC, and the VM
says so as KVM_CAP_ARM_CACHEABLE_PFNMAP_SUPPORTED. Every host mapping of a
Honeykrisp allocation is VM_PFNMAP, so on an M1 Pro under Fedora Asahi Remix
45 the reims-graphics device's first Shared pool piece failed
KVM_SET_USER_MEMORY_REGION2 with EINVAL, and QEMU exited
(steelbrain/reims-vgpu#174).

The device now sets the library's pool_host_memory where it runs under KVM on
an arm64 host and the VM does not answer the capability, which a kernel older
than it does not either: the pool's blocks are then memfds of the library's
that the GPU imports, which KVM maps as guest memory, cached, as it maps the
guest's RAM. The check is in reims-graphics-pci-kvm.c, which only targets
with KVM link, with its stub beside the others; it asks the VM through
kvm_vm_ioctl, since kvm_vm_check_extension is declared for per-target builds
alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 17:46:43 +00:00
Alex Gleason 9b887cfcce 🐛 Collapse guest RAM into huge pages only where asked
On a Radeon 890M host (RADV, Mesa 26.1.8, Linux 6.18.59), a macOS 26.7.2
guest on reims-graphics-pci over collapsed RAM panicked 80 to 154 s into
every boot, its kernel's memory overwritten: pmap's pv lists, an rw lock,
a ledger, IOKit matching. With the same memfd preallocated and the
collapse skipped, it ran clean for 11 minutes, then 9 more at 8 vCPUs
and 12 GiB, with apps opening throughout. With plain VGA in the device's
place, collapsed RAM ran clean too: the panics need both.

Skip the collapse unless QEMU_HOSTMEM_COLLAPSE=1, until where it goes wrong
(the import of udmabufs over large shmem folios, or KVM's 2 MiB maps beside
it) is found. reims-vgpu#185 has the bisect.
2026-11-25 18:40:08 -06:00
59 changed files with 5752 additions and 647 deletions

No files matched your search

+187
View File
@@ -177,6 +177,75 @@ int whpx_first_vcpu_starting(CPUState *cpu)
return 0;
}
static void whpx_print_stats(void)
{
const char *env = getenv("REIMS_WHPX_STATS");
CPUState *c;
uint64_t fast_w = 0, fast_r = 0, slow = 0;
uint64_t pio = 0, msr = 0, cpuid = 0, eoi = 0, halt = 0, canceled = 0;
uint64_t hv_runtime = 0, hv_io = 0, hv_cpuid = 0, hv_msr = 0;
uint64_t hv_other = 0, hv_emul = 0, hv_npf = 0;
bool have_hv_counters = false;
if (!env || env[0] != '1') {
return;
}
CPU_FOREACH(c) {
AccelCPUState *vc = c->accel;
if (!vc) {
continue;
}
fast_w += vc->stats.mmio_fast_write;
fast_r += vc->stats.mmio_fast_read;
slow += vc->stats.mmio_slow;
pio += vc->stats.pio;
msr += vc->stats.msr;
cpuid += vc->stats.cpuid;
eoi += vc->stats.apic_eoi;
halt += vc->stats.halt;
canceled += vc->stats.canceled;
if (whp_dispatch.WHvGetVirtualProcessorCounters && whpx_global.partition) {
WHV_PROCESSOR_RUNTIME_COUNTERS rt = {};
WHV_PROCESSOR_ACTIVITY_COUNTERS act = {};
if (SUCCEEDED(whp_dispatch.WHvGetVirtualProcessorCounters(
whpx_global.partition, c->cpu_index,
WHvProcessorCounterSetRuntime, &rt, sizeof(rt), NULL))) {
hv_runtime += rt.TotalRuntime100ns;
have_hv_counters = true;
}
if (SUCCEEDED(whp_dispatch.WHvGetVirtualProcessorCounters(
whpx_global.partition, c->cpu_index,
WHvProcessorCounterSetIntercepts, &act, sizeof(act), NULL))) {
hv_io += act.IoInstructions.Count;
hv_cpuid += act.CpuidInstructions.Count;
hv_msr += act.MsrAccesses.Count;
hv_other += act.OtherIntercepts.Count;
hv_emul += act.EmulatedInstructions.Count;
hv_npf += act.NestedPageFaultIntercepts.Count;
have_hv_counters = true;
}
}
}
fprintf(stderr,
"[whpx-stats] mmio_fast_w=%" PRIu64 " mmio_fast_r=%" PRIu64
" mmio_slow=%" PRIu64 " pio=%" PRIu64 " msr=%" PRIu64
" cpuid=%" PRIu64 " apic_eoi=%" PRIu64 " halt=%" PRIu64
" canceled=%" PRIu64,
fast_w, fast_r, slow, pio, msr, cpuid, eoi, halt, canceled);
if (have_hv_counters) {
fprintf(stderr,
" hv_rt_ms=%" PRIu64 " hv_io=%" PRIu64 " hv_cpuid=%" PRIu64
" hv_msr=%" PRIu64 " hv_other=%" PRIu64 " hv_emul=%" PRIu64
" hv_npf=%" PRIu64,
hv_runtime / 10000, hv_io, hv_cpuid, hv_msr,
hv_other, hv_emul, hv_npf);
}
fprintf(stderr, "\n");
}
/*
* This function is called when the last VCPU has finished running.
* It is used to remove any previously set breakpoints from memory.
@@ -184,6 +253,7 @@ int whpx_first_vcpu_starting(CPUState *cpu)
int whpx_last_vcpu_stopping(CPUState *cpu)
{
whpx_apply_breakpoints(whpx_global.breakpoints.breakpoints, cpu, false);
whpx_print_stats();
return 0;
}
@@ -580,6 +650,119 @@ static void whpx_log_sync(MemoryListener *listener,
memory_region_set_dirty(mr, 0, int128_get64(section->size));
}
static void whpx_build_doorbell_match(MemoryRegionSection *section,
bool match_data, uint64_t data,
WHV_DOORBELL_MATCH_DATA *match,
bool *valid)
{
uint64_t size = int128_get64(section->size);
memset(match, 0, sizeof(*match));
if (size > 8) {
*valid = false;
return;
}
match->GuestAddress = section->offset_within_address_space;
match->Value = match_data ? data : 0;
match->Length = (UINT32)size;
match->MatchOnValue = match_data ? 1 : 0;
match->MatchOnLength = (size > 0 && size <= 8) ? 1 : 0;
*valid = true;
}
static bool whpx_doorbell_same_match(const WHV_DOORBELL_MATCH_DATA *a,
const WHV_DOORBELL_MATCH_DATA *b)
{
return a->Value == b->Value &&
a->Length == b->Length &&
a->MatchOnValue == b->MatchOnValue &&
a->MatchOnLength == b->MatchOnLength;
}
static bool whpx_doorbell_equal(const WHV_DOORBELL_MATCH_DATA *a,
const WHV_DOORBELL_MATCH_DATA *b)
{
return a->GuestAddress == b->GuestAddress &&
whpx_doorbell_same_match(a, b);
}
static void whpx_mem_ioeventfd_add(MemoryListener *listener,
MemoryRegionSection *section,
bool match_data, uint64_t data,
EventNotifier *e)
{
struct whpx_state *whpx = &whpx_global;
WHV_DOORBELL_MATCH_DATA match;
bool valid = false;
HRESULT hr;
if (!whpx->partition || !whp_dispatch.WHvRegisterPartitionDoorbellEvent) {
return;
}
whpx_build_doorbell_match(section, match_data, data, &match, &valid);
if (!valid) {
return;
}
for (unsigned i = 0; i < whpx->nr_doorbells; i++) {
if (whpx_doorbell_equal(&whpx->doorbells[i], &match)) {
return;
}
/*
* Win10 1904x WinHvPlatform.dll keys its doorbell map without
* GuestAddress and FailFasts (0xc0000409) on duplicate match tuples.
* Keep userspace dispatch active for secondary queues.
*/
if (whpx->doorbell_unique_match_bug &&
whpx_doorbell_same_match(&whpx->doorbells[i], &match)) {
return;
}
}
hr = whp_dispatch.WHvRegisterPartitionDoorbellEvent(
whpx->partition, &match, event_notifier_get_handle(e));
if (FAILED(hr)) {
/* Userspace memory_region_dispatch_write_eventfds remains active. */
return;
}
if (whpx->nr_doorbells == whpx->cap_doorbells) {
whpx->cap_doorbells = whpx->cap_doorbells ? whpx->cap_doorbells * 2 : 16;
whpx->doorbells = g_renew(WHV_DOORBELL_MATCH_DATA, whpx->doorbells,
whpx->cap_doorbells);
}
whpx->doorbells[whpx->nr_doorbells++] = match;
}
static void whpx_mem_ioeventfd_del(MemoryListener *listener,
MemoryRegionSection *section,
bool match_data, uint64_t data,
EventNotifier *e)
{
struct whpx_state *whpx = &whpx_global;
WHV_DOORBELL_MATCH_DATA match;
bool valid = false;
if (!whpx->partition || !whp_dispatch.WHvUnregisterPartitionDoorbellEvent) {
return;
}
whpx_build_doorbell_match(section, match_data, data, &match, &valid);
if (!valid) {
return;
}
for (unsigned i = 0; i < whpx->nr_doorbells; i++) {
if (whpx_doorbell_equal(&whpx->doorbells[i], &match)) {
whpx->doorbells[i] = whpx->doorbells[--whpx->nr_doorbells];
whp_dispatch.WHvUnregisterPartitionDoorbellEvent(whpx->partition, &match);
return;
}
}
}
static MemoryListener whpx_memory_listener = {
.name = "whpx",
.begin = whpx_transaction_begin,
@@ -587,6 +770,8 @@ static MemoryListener whpx_memory_listener = {
.region_add = whpx_region_add,
.region_del = whpx_region_del,
.log_sync = whpx_log_sync,
.eventfd_add = whpx_mem_ioeventfd_add,
.eventfd_del = whpx_mem_ioeventfd_del,
.priority = MEMORY_LISTENER_PRIORITY_ACCEL,
};
@@ -635,6 +820,8 @@ static bool load_whp_dispatch_fns(HMODULE *handle,
case WINHV_PLATFORM_FNS_SUPPLEMENTAL:
WHP_LOAD_LIB(WINHV_PLATFORM_DLL, hLib)
LIST_WINHVPLATFORM_FUNCTIONS_SUPPLEMENTAL(WHP_LOAD_FIELD_OPTIONAL)
whpx_global.doorbell_unique_match_bug =
(GetProcAddress(hLib, "WHvCreateNotificationPort") == NULL);
break;
}
+12
View File
@@ -438,6 +438,18 @@ static size_t audio_pcm_hw_get_free(HWVoiceOut *hw)
hw->info.bytes_per_frame;
}
void audio_pcm_hw_trim_out(HWVoiceOut *hw, int64_t offset_mhz)
{
SWVoiceOut *sw;
QLIST_FOREACH(sw, &hw->sw_head, entries) {
if (sw->rate) {
st_rate_set_out_mhz(sw->rate, sw->info.freq,
(int64_t)hw->info.freq * 1000 - offset_mhz);
}
}
}
static void audio_pcm_hw_clip_out(HWVoiceOut *hw, void *pcm_buf, size_t len)
{
size_t clipped = 0;
+9
View File
@@ -241,6 +241,15 @@ void audio_pcm_info_clear_buf (struct audio_pcm_info *info, void *buf, int len);
void audio_run(AudioMixengBackend *s, const char *msg);
/*
* Plays @hw's soft voices @offset_mhz millihertz faster than @hw's rate
* (slower where it is negative), through each one's resampler, which goes on
* from where it stands: the voice's rate takes up its device's drift with no
* step in its audio. A soft voice that joins later plays at the voice's own
* rate until the next call.
*/
void audio_pcm_hw_trim_out(HWVoiceOut *hw, int64_t offset_mhz);
typedef struct RateCtl {
int64_t start_ticks;
int64_t bytes_sent;
+209 -3
View File
@@ -1,8 +1,9 @@
/*
* QEMU DirectSound audio driver: its playback buffer's arithmetic
* QEMU DirectSound audio driver: its playback buffer's arithmetic, and the
* trim of its playback rate
*
* Moved out of dsoundaudio.c, which builds only on Windows, unchanged, so
* that tests/unit/test-dsound-ring.c holds it on any host.
* Apart from dsoundaudio.c, which builds only on Windows, so that
* tests/unit/test-dsound-ring.c holds it on any host.
*
* SPDX-License-Identifier: MIT
*/
@@ -63,4 +64,209 @@ static inline size_t dsound_filled_after(size_t filled, size_t played,
return filled - played;
}
/*
* The trim of a playback voice's rate.
*
* Placed DSOUND_RESERVE_US past the write cursor, a voice holds more audio
* than its guest needs once the guest's posts show where they fall: its
* margin past the write cursor (its fill less the write cursor's lead) comes
* down to its least once a turn of the guest's post grid, every 1.79 s for an
* x86-64 macOS guest, and the rest of the reserve is only latency. And the
* host's device plays to its own clock, not the guest's, so it takes the
* guest's audio a little faster or slower than the guest posts it: faster, it
* eats the margin until the audio runs out before the write cursor (a gap);
* slower, the fill and the latency grow. The voice corrects both through the
* rate its guest's audio is resampled to (audio_pcm_hw_trim_out), a little
* over or under its own frequency.
*
* Over the voice's reads with audio flowing, in buckets of
* DSOUND_TRIM_BUCKET_NS, the trim takes the margin's least. The level is the
* least of the last DSOUND_TRIM_LEVEL buckets. The drift is how fast the host's
* device takes the voice's audio past the guest, in millihertz of the voice's
* frequency: the slope of the buckets' least margins, with what the trim's
* own offset played out added back, by least squares over the last
* DSOUND_TRIM_BUCKETS buckets, once DSOUND_TRIM_DRIFT_MIN are in. The offset
* is the drift's negative, and 1 Hz more for each millisecond the level stands
* past the margin kept, DSOUND_TRIM_KEEP_US, within DSOUND_TRIM_MAX_PPM of the
* voice's frequency: at 44100 Hz, 44 Hz either way, a drain of 1 ms a second.
* A gap keeps DSOUND_TRIM_KEEP_STEP_US more, up to DSOUND_TRIM_KEEP_MAX_US, and
* starts the buckets again, as a placement of the write position does; the
* drift stays, as a property of the device.
*
* Replayed on an x86-64 macOS guest's posts on a Windows host (2026-11-25, the
* guest busy, 192 s each, tiled to 769 s), with the device forced 20 Hz
* either way: no gap, the margin's least 9 to 13 ms, and the fill at a post's
* write 70 ms at the median, where the fixed reserve gave 97 to 99. Measured
* on a Windows 11 host (2026-12-02), the device forced 10 Hz fast: no gap in
* 834 s, where the fixed reserve had one every 260 s, the margin's least
* 11.8 ms; at rest and busy the fill at a post's write was 72 ms at the
* median, where the fixed reserve gave 105 to 107.
*/
#define DSOUND_TRIM_BUCKET_NS (2 * 1000000000LL)
#define DSOUND_TRIM_LEVEL 5
#define DSOUND_TRIM_BUCKETS 30
#define DSOUND_TRIM_DRIFT_MIN 15
#define DSOUND_TRIM_KEEP_US 15000
#define DSOUND_TRIM_KEEP_STEP_US 10000
#define DSOUND_TRIM_KEEP_MAX_US 45000
#define DSOUND_TRIM_MAX_PPM 1000
typedef struct DSoundTrimBucket {
/* Its last read; the margin's least in it, in us. */
int64_t end_ns;
int64_t least_us;
/* What the offset played out from the buckets' start to its end, in us. */
int64_t played_us;
} DSoundTrimBucket;
typedef struct DSoundTrim {
/* The voice's frequency, in Hz. */
int freq;
/* The buckets, oldest first from @head - @buckets; the open one. */
DSoundTrimBucket bucket[DSOUND_TRIM_BUCKETS];
unsigned buckets;
unsigned head;
bool open;
int64_t start_ns;
int64_t least_us;
/* The last read, and the offset times the time since the buckets began. */
int64_t read_ns;
int64_t played_hz_ns;
/* The margin kept, in us; the drift, in mHz; the offset, in Hz. */
int64_t keep_us;
int64_t drift_mhz;
int offset_hz;
} DSoundTrim;
/* @mhz in whole hertz, halves away from zero. */
static inline int64_t dsound_trim_round(int64_t mhz)
{
return mhz >= 0 ? (mhz + 500) / 1000 : -((-mhz + 500) / 1000);
}
/* @mhz within DSOUND_TRIM_MAX_PPM of the voice's frequency. */
static inline int64_t dsound_trim_clamp(const DSoundTrim *t, int64_t mhz)
{
int64_t max = (int64_t)t->freq * DSOUND_TRIM_MAX_PPM / 1000;
return MIN(MAX(mhz, -max), max);
}
/* A voice of @freq Hz, with no drift known. */
static inline void dsound_trim_init(DSoundTrim *t, int freq)
{
memset(t, 0, sizeof(*t));
t->freq = freq;
t->keep_us = DSOUND_TRIM_KEEP_US;
}
/*
* The buckets start again, at a placement of the write position: the offset
* is the drift's alone until two buckets show the level.
*/
static inline void dsound_trim_restart(DSoundTrim *t)
{
t->buckets = 0;
t->head = 0;
t->open = false;
t->played_hz_ns = 0;
t->offset_hz = dsound_trim_round(dsound_trim_clamp(t, -t->drift_mhz));
}
/* The audio ran out before the write cursor: keep more, and start again. */
static inline void dsound_trim_gap(DSoundTrim *t)
{
t->keep_us = MIN(t->keep_us + DSOUND_TRIM_KEEP_STEP_US,
DSOUND_TRIM_KEEP_MAX_US);
dsound_trim_restart(t);
}
/* The bucket @i back from the newest. */
static inline const DSoundTrimBucket *dsound_trim_bucket(const DSoundTrim *t,
unsigned i)
{
return &t->bucket[(t->head + DSOUND_TRIM_BUCKETS - 1 - i) %
DSOUND_TRIM_BUCKETS];
}
/*
* The drift, in mHz: the least squares slope of the buckets' least margins
* with what the offset played out added back, in us a second, times the
* frequency, negated (a margin that falls is a device that plays fast).
*/
static inline int64_t dsound_trim_drift(const DSoundTrim *t)
{
double n = t->buckets, sx = 0, sy = 0, sxx = 0, sxy = 0, d, mhz;
int64_t t0 = dsound_trim_bucket(t, t->buckets - 1)->end_ns;
unsigned i;
for (i = 0; i < t->buckets; i++) {
const DSoundTrimBucket *b = dsound_trim_bucket(t, i);
double x = (double)(b->end_ns - t0) / 1e9;
double y = (double)(b->least_us + b->played_us);
sx += x;
sy += y;
sxx += x * x;
sxy += x * y;
}
d = n * sxx - sx * sx;
if (d <= 0) {
return t->drift_mhz;
}
mhz = -(n * sxy - sx * sy) / d * t->freq / 1000;
return dsound_trim_clamp(t, (int64_t)(mhz >= 0 ? mhz + 0.5 : mhz - 0.5));
}
/*
* A read of the voice at @now_ns with its audio flowing, @margin_us past the
* write cursor. Returns whether the offset changed.
*/
static inline bool dsound_trim_read(DSoundTrim *t, int64_t now_ns,
int64_t margin_us)
{
DSoundTrimBucket *b;
int64_t level, mhz;
unsigned i;
int old = t->offset_hz;
if (!t->open) {
t->open = true;
t->start_ns = now_ns;
t->read_ns = now_ns;
t->least_us = margin_us;
return false;
}
t->played_hz_ns += (int64_t)t->offset_hz * (now_ns - t->read_ns);
t->read_ns = now_ns;
t->least_us = MIN(t->least_us, margin_us);
if (now_ns - t->start_ns < DSOUND_TRIM_BUCKET_NS) {
return false;
}
b = &t->bucket[t->head];
b->end_ns = now_ns;
b->least_us = t->least_us;
b->played_us = t->played_hz_ns / ((int64_t)t->freq * 1000);
t->head = (t->head + 1) % DSOUND_TRIM_BUCKETS;
t->buckets = MIN(t->buckets + 1, DSOUND_TRIM_BUCKETS);
t->start_ns = now_ns;
t->least_us = margin_us;
if (t->buckets >= DSOUND_TRIM_DRIFT_MIN) {
t->drift_mhz = dsound_trim_drift(t);
}
mhz = -t->drift_mhz;
if (t->buckets >= 2) {
level = INT64_MAX;
for (i = 0; i < MIN(t->buckets, DSOUND_TRIM_LEVEL); i++) {
level = MIN(level, dsound_trim_bucket(t, i)->least_us);
}
/* 1 Hz a millisecond: 1 mHz a microsecond. */
mhz += level - t->keep_us;
}
t->offset_hz = dsound_trim_round(dsound_trim_clamp(t, mhz));
return t->offset_hz != old;
}
#endif
+1
View File
@@ -264,6 +264,7 @@ static int dsound_init_out(HWVoiceOut *hw, struct audsettings *as)
#ifndef DSBTYPE_IN
ds->buffer_ns = muldiv64(hw->samples, NANOSECONDS_PER_SECOND,
hw->info.freq);
dsound_trim_init(&ds->trim, hw->info.freq);
#endif
trace_dsound_buffer_bytes(bc.dwBufferBytes, bd.dwBufferBytes);
+45 -5
View File
@@ -67,8 +67,16 @@ struct AudioDsound {
* 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.
* (virtio-snd does). What the play cursor has passed becomes silence, so a
* gap plays silence.
*
* The reserve is latency, and the host's device keeps its own clock: the
* voice's trim (dsound-ring.h) plays out what the guest's posts show the
* reserve need not hold, and matches the device's rate to the guest's,
* through the mixing engine's resampler (audio_pcm_hw_trim_out), which
* changes rate with no step in the audio. DirectSound's own frequency is
* not used: on a Windows 11 host each IDirectSoundBuffer_SetFrequency, of any
* size, moved the audio by 4 to 19 us some 35 ms later, a click.
*/
typedef struct {
HWVoiceOut hw;
@@ -84,6 +92,8 @@ typedef struct {
bool primed;
/* The times the audio written ran out before the write cursor. */
uint32_t gaps;
/* The trim of the voice's rate. */
DSoundTrim trim;
} DSoundVoiceOut;
typedef struct {
@@ -427,6 +437,14 @@ static void dsound_clear_out(HWVoiceOut *hw, DWORD pos, size_t len)
dsound_unlock_out(ds->dsound_buffer, p1, p2, blen1, blen2);
}
/* Play the voice's soft voices at its trim's offset. */
static void dsound_trim_apply(HWVoiceOut *hw)
{
DSoundVoiceOut *ds = (DSoundVoiceOut *)hw;
audio_pcm_hw_trim_out(hw, (int64_t)ds->trim.offset_hz * 1000);
}
/*
* 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,
@@ -441,9 +459,13 @@ static void dsound_place_out(HWVoiceOut *hw, DWORD ppos, DWORD wpos)
if (ds->primed) {
ds->gaps++;
dsound_trim_gap(&ds->trim);
} else {
dsound_trim_restart(&ds->trim);
}
trace_dsound_place_out(hw, ppos, wpos, ds->filled, reserve, ds->primed,
ds->gaps);
dsound_trim_apply(hw);
dsound_clear_out(hw, wpos, reserve);
hw->pos_emul = (wpos + reserve) % hw->size_emul;
ds->filled = lead + reserve;
@@ -456,7 +478,7 @@ static size_t dsound_buffer_get_free(HWVoiceOut *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;
size_t played, lead;
HRESULT hr;
DWORD ppos, wpos;
@@ -493,9 +515,27 @@ static size_t dsound_buffer_get_free(HWVoiceOut *hw)
* 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)) {
lead = audio_ring_dist(wpos, ppos, hw->size_emul);
if (!ds->primed || ds->filled < lead) {
dsound_place_out(hw, ppos, wpos);
} else {
unsigned head = ds->trim.head;
dsound_trim_read(&ds->trim, now,
muldiv64((ds->filled - lead) / bpf, 1000000,
hw->info.freq));
/*
* A bucket closed: the offset may have changed, and a soft voice
* that joined since takes it.
*/
if (ds->trim.head != head) {
const DSoundTrimBucket *b = dsound_trim_bucket(&ds->trim, 0);
trace_dsound_trim(hw, b->least_us, ds->trim.drift_mhz,
ds->trim.keep_us, ds->trim.offset_hz,
ds->trim.buckets);
dsound_trim_apply(hw);
}
}
trace_dsound_buffer_get_free(hw, ppos, wpos, ds->filled);
+25 -2
View File
@@ -469,8 +469,16 @@ struct rate {
uint64_t opos_inc;
uint32_t ipos; /* position in the input stream (integer) */
struct st_sample ilast; /* last sample in the input stream */
/* Set by st_rate_set_out_mhz(): the rate interpolates from then on. */
bool trimmed;
};
/* Whether @rate copies its input, its rates being equal and never trimmed. */
static inline bool st_rate_copies(const struct rate *rate)
{
return rate->opos_inc == 1ULL << 32 && !rate->trimmed;
}
/*
* Prepare processing.
*/
@@ -502,6 +510,21 @@ void st_rate_stop (void *opaque)
g_free (opaque);
}
/*
* From now on @opaque resamples its input of @inrate Hz to @outrate_mhz
* millihertz of output. The interpolation goes on from where it stands, so
* the output has no step where the rate changes. A rate set this way
* interpolates from then on, even where its rates come out equal: going back
* to copying would drop the input frame the interpolation holds.
*/
void st_rate_set_out_mhz(void *opaque, int inrate, int64_t outrate_mhz)
{
struct rate *rate = opaque;
rate->opos_inc = ((uint64_t)inrate << 32) * 1000 / (uint64_t)outrate_mhz;
rate->trimmed = true;
}
/**
* st_rate_frames_out() - returns the number of frames the resampling code
* generates from frames_in frames
@@ -520,7 +543,7 @@ uint32_t st_rate_frames_out(void *opaque, uint32_t frames_in)
uint32_t ipos_end;
uint32_t frames_out;
if (rate->opos_inc == 1ULL << 32) {
if (st_rate_copies(rate)) {
return frames_in;
}
@@ -559,7 +582,7 @@ uint32_t st_rate_frames_in(void *opaque, uint32_t frames_out)
uint64_t opos_start, opos_end;
uint32_t ipos_start, ipos_end;
if (rate->opos_inc == 1ULL << 32) {
if (st_rate_copies(rate)) {
return frames_out;
}
+1
View File
@@ -51,6 +51,7 @@ void st_rate_flow(void *opaque, st_sample *ibuf, st_sample *obuf,
void st_rate_flow_mix(void *opaque, st_sample *ibuf, st_sample *obuf,
size_t *isamp, size_t *osamp);
void st_rate_stop (void *opaque);
void st_rate_set_out_mhz(void *opaque, int inrate, int64_t outrate_mhz);
uint32_t st_rate_frames_out(void *opaque, uint32_t frames_in);
uint32_t st_rate_frames_in(void *opaque, uint32_t frames_out);
void mixeng_clear (struct st_sample *buf, int len);
+1 -1
View File
@@ -46,7 +46,7 @@ void NAME (void *opaque, struct st_sample *ibuf, struct st_sample *obuf,
ostart = obuf;
oend = obuf + *osamp;
if (rate->opos_inc == (1ULL + UINT_MAX)) {
if (st_rate_copies(rate)) {
int i, n = *isamp > *osamp ? *osamp : *isamp;
for (i = 0; i < n; i++) {
OP (obuf[i].l, ibuf[i].l);
+1
View File
@@ -34,6 +34,7 @@ dsound_wave_format(uint16_t wFormatTag, uint16_t nChannels, uint32_t nSamplesPer
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"
dsound_trim(void *voice, int64_t least_us, int64_t drift_mhz, int64_t keep_us, int offset_hz, uint32_t buckets) "voice=%p, least_us=%" PRId64 ", drift_mhz=%" PRId64 ", keep_us=%" PRId64 ", offset_hz=%d, buckets=%u"
# jackaudio.c
jack_client_recover(void) "attempting to reconnect to server"
+3
View File
@@ -129,6 +129,9 @@ int is_windows_drive(const char *filename)
if (strstart(filename, "\\\\.\\", NULL) ||
strstart(filename, "//./", NULL))
return 1;
if (g_ascii_strncasecmp(filename, "\\\\?\\Volume{", 11) == 0 ||
g_ascii_strncasecmp(filename, "//?/Volume{", 11) == 0)
return 1;
return 0;
}
#endif
+587 -183
View File
File diff suppressed because it is too large. Load diff
+925 -133
View File
File diff suppressed because it is too large. Load diff
+63 -1
View File
@@ -85,6 +85,17 @@ struct PFlashCFI01 {
void *storage;
VMChangeStateEntry *vmstate;
/*
* The bytes of storage whose write to the drive failed under the drive's
* stop action (a host disk with no space, by -drive's default
* werror=enospc), [dirty_start, dirty_end), empty where dirty_start is
* not below dirty_end: written again from storage as the VM resumes
* (pflash_rewrite_cb).
*/
uint64_t dirty_start;
uint64_t dirty_end;
VMChangeStateEntry *rewrite;
/* block update buffer */
unsigned char *blk_bytes;
uint32_t blk_offset;
@@ -401,13 +412,47 @@ static void pflash_update(PFlashCFI01 *pfl, int offset,
offset_end = QEMU_ALIGN_UP(offset_end, BDRV_SECTOR_SIZE);
ret = blk_pwrite(pfl->blk, offset, offset_end - offset,
pfl->storage + offset, 0);
if (ret < 0) {
if (ret < 0 &&
blk_get_error_action(pfl->blk, false, -ret) ==
BLOCK_ERROR_ACTION_STOP) {
/*
* storage holds the bytes, which the guest reads on; only the
* drive lacks them. They are written again as the VM resumes,
* and QEMU pauses the VM meanwhile, as the disks' devices do.
*/
if (pfl->dirty_start < pfl->dirty_end) {
pfl->dirty_start = MIN(pfl->dirty_start, offset);
pfl->dirty_end = MAX(pfl->dirty_end, offset_end);
} else {
pfl->dirty_start = offset;
pfl->dirty_end = offset_end;
}
blk_error_action(pfl->blk, BLOCK_ERROR_ACTION_STOP, false, -ret);
} else if (ret < 0) {
/* TODO set error bit in status */
error_report("Could not update PFLASH: %s", strerror(-ret));
}
}
}
/*
* As the VM resumes, writes the bytes whose write failed under the drive's
* stop action again from storage (pflash_update): where it fails again so,
* they stay to write and QEMU pauses the VM again.
*/
static void pflash_rewrite_cb(void *opaque, bool running, RunState state)
{
PFlashCFI01 *pfl = opaque;
uint64_t start = pfl->dirty_start, end = pfl->dirty_end;
if (!running || start >= end) {
return;
}
pfl->dirty_start = pfl->dirty_end = 0;
pflash_update(pfl, start, end - start);
}
/* copy current flash content to block update buffer */
static void pflash_blk_write_start(PFlashCFI01 *pfl, hwaddr offset)
{
@@ -871,6 +916,22 @@ static void pflash_cfi01_realize(DeviceState *dev, Error **errp)
pfl->blk_bytes = g_malloc(pfl->writeblock_size);
pfl->blk_offset = -1;
if (pfl->blk && !pfl->ro) {
/* blk_error_action()'s stop records its error in the I/O status */
blk_iostatus_enable(pfl->blk);
pfl->rewrite = qemu_add_vm_change_state_handler(pflash_rewrite_cb, pfl);
}
}
static void pflash_cfi01_unrealize(DeviceState *dev)
{
PFlashCFI01 *pfl = PFLASH_CFI01(dev);
if (pfl->rewrite) {
qemu_del_vm_change_state_handler(pfl->rewrite);
pfl->rewrite = NULL;
}
}
static void pflash_cfi01_system_reset(DeviceState *dev)
@@ -931,6 +992,7 @@ static void pflash_cfi01_class_init(ObjectClass *klass, const void *data)
device_class_set_legacy_reset(dc, pflash_cfi01_system_reset);
dc->realize = pflash_cfi01_realize;
dc->unrealize = pflash_cfi01_unrealize;
device_class_set_props(dc, pflash_cfi01_properties);
dc->vmsd = &vmstate_pflash;
set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
+5
View File
@@ -16,3 +16,8 @@ const ReimsGraphicsPrefaultOps *reims_graphics_kvm_prefault_ops(void)
{
return NULL;
}
bool reims_graphics_kvm_pool_host_memory(void)
{
return false;
}
+15
View File
@@ -18,6 +18,21 @@
#include "reims-graphics-pci-prefault.h"
#include "trace.h"
bool reims_graphics_kvm_pool_host_memory(void)
{
#if defined(__aarch64__)
/*
* The capability is the VM's (KVM_CHECK_EXTENSION on the VM's fd);
* kvm_vm_check_extension is declared for per-target builds alone.
*/
return kvm_enabled() &&
kvm_vm_ioctl(kvm_state, KVM_CHECK_EXTENSION,
KVM_CAP_ARM_CACHEABLE_PFNMAP_SUPPORTED) <= 0;
#else
return false;
#endif
}
bool reims_graphics_kvm_disable_slot_zap_all(void)
{
#ifdef KVM_X86_QUIRK_SLOT_ZAP_ALL
+14
View File
@@ -29,4 +29,18 @@ bool reims_graphics_kvm_disable_slot_zap_all(void);
*/
const ReimsGraphicsPrefaultOps *reims_graphics_kvm_prefault_ops(void);
/*
* Whether the guest's Shared pool's blocks are to be host memory the GPU
* imports: under KVM on an arm64 host whose VM does not answer
* KVM_CAP_ARM_CACHEABLE_PFNMAP_SUPPORTED. KVM takes a cacheable VM_PFNMAP
* mapping, as a GPU driver's mapping of its own memory is, as guest memory
* only where the CPU has stage-2 forced write-back and CACHE_DIC, which the
* VM answers as that capability; elsewhere the pool's first piece's slot is
* refused, and QEMU exits. A memfd's mapping, as the guest's RAM's, is
* taken. False elsewhere. Every kernel the device runs on (Linux 7.2 and
* later, reims_graphics_linux_floor) knows the capability, which Linux
* 6.18's headers already define.
*/
bool reims_graphics_kvm_pool_host_memory(void);
#endif
+161 -63
View File
@@ -67,13 +67,19 @@
* The device has the displays property's count of displays, 1 to
* RVG_GRAPHICS_DISPLAYS_MAX (1 by default), display i head i of QEMU's UI,
* with a console of its own. Under -display none the library opens a window
* for each display, unless REIMS_VGPU_WINDOW is "0": each opens at the
* resolution property's size, "<width>x<height>" (1920x1080 without it), then
* keeps the size the person gives it, and the guest follows it. A window's
* input reaches the guest through its display's console. A console shows what
* its display shows, read back from the library on a thread of the device's
* pool at each of its updates (rvg_graphics_device_read_display_at): QEMU's
* own displays and its screendump of the console's head read it there. A
* for each display, unless REIMS_VGPU_WINDOW is "0": each opens at its size
* of the resolution property, "<width>x<height>" for every display or a
* comma-separated list of one size per display, in the displays' order
* (1920x1080 without it; QEMU's command line writes each comma ",,"), then
* keeps the size the person gives it, and the guest follows it. With no
* window (REIMS_VGPU_WINDOW "0", or another display of QEMU's), each display
* offers the guest its size of the resolution property as its mode, at 60 Hz
* (the config's headless mode, or with several sizes each display's own).
* A window's input reaches the guest through its display's console. A
* console shows what its display shows, read back from the library on a
* thread of the device's pool at each of its updates
* (rvg_graphics_device_read_display_at): QEMU's own displays and its
* screendump of the console's head read it there. A
* read waits for its draw on the GPU; one still waiting 3 s after it started
* is late, and a screendump is answered then with what the console shows, so
* that the QMP monitors, which wait for the screendump's command, go on. Each
@@ -86,7 +92,10 @@
* At QEMU's quit, once the VM stopped for good, the device is torn down
* (reims_graphics_pci_vm_state_change): every pool piece leaves the guest's
* address space, and the library's release of its last device lets go of
* the GPU device before the process exits. A read of a
* the GPU device before the process exits. A quit of a VM that was not
* running (paused, stopped, or paused by a shutdown whose action pauses)
* tears it down at the end of QEMU's cleanup instead
* (reims_graphics_pci_cleanup). A read of a
* display still waiting for the GPU 5 s into the teardown keeps the device to
* the exit instead, so a GPU that stopped answering does not hold the quit.
* Whether released or kept, the library is quiesced at the end of QEMU's
@@ -141,6 +150,7 @@
#include "reims-graphics-pci-kvm.h"
#endif
#include "reims-graphics-pci-prefault.h"
#include "reims-pointer.h"
#include "ui/console.h"
#include "ui/input.h"
#include <reims_vgpu.h>
@@ -249,7 +259,11 @@ struct ReimsGraphicsPCIState {
QSIMPLEQ_HEAD(, ReimsGraphicsEvent) events; /* event_lock protected */
QEMUBH *event_bh;
char *resolution; /* the property: each window's first size, or NULL */
/*
* The property: each window's first size, or each display's mode with
* no window, one size for every display or one for each; or NULL.
*/
char *resolution;
uint32_t displays; /* the property: 1 to RVG_GRAPHICS_DISPLAYS_MAX */
/* Mutable state (BQL protected) */
@@ -604,11 +618,16 @@ static void reims_graphics_input_pointer(ReimsGraphicsPCIState *s,
uint16_t width = MAX(event->pointer.width, 1);
uint16_t height = MAX(event->pointer.height, 1);
/* QEMU's input layer does not clamp absolute axes. */
/*
* QEMU's input layer does not clamp absolute axes, and the last pixel
* goes as the tablet's maximum (reims-pointer.h).
*/
qemu_input_queue_abs(con, INPUT_AXIS_X,
MIN(event->pointer.x, width - 1), 0, width);
reims_pointer_axis(event->pointer.x, width),
0, width);
qemu_input_queue_abs(con, INPUT_AXIS_Y,
MIN(event->pointer.y, height - 1), 0, height);
reims_pointer_axis(event->pointer.y, height),
0, height);
qemu_input_update_buttons(con, button_map, s->input_buttons,
event->pointer.buttons);
s->input_buttons = event->pointer.buttons;
@@ -957,31 +976,52 @@ static void reims_graphics_cursor_move_cb(void *ctx)
}
/*
* The window's first size, from the resolution property: NULL is 0x0, which
* the library opens at 1920x1080, else "<width>x<height>", each 1 to 65535
* pixels.
* Each display's window's first size, or its mode where the device has no
* window, from the resolution property, into sizes[0 .. displays - 1]: NULL
* is 0x0 for every display, which the library takes as 1920x1080; else
* "<width>x<height>", each 1 to 65535 pixels, for every display, or a
* comma-separated list of exactly one such size per display. *count is how
* many sizes the property gives: 1 for NULL and for one size.
*/
static bool reims_graphics_parse_resolution(const char *str, uint16_t *width,
uint16_t *height, Error **errp)
static bool reims_graphics_parse_resolution(const char *str, uint32_t displays,
RvgDisplayCoord *sizes,
uint32_t *count, Error **errp)
{
g_auto(GStrv) parts = NULL;
const char *endptr;
uint32_t i, n;
int w, h;
*width = 0;
*height = 0;
memset(sizes, 0, displays * sizeof(*sizes));
*count = 1;
if (str == NULL) {
return true;
}
if (qemu_strtoi(str, &endptr, 10, &w) || w <= 0 || w > UINT16_MAX ||
*endptr != 'x' ||
qemu_strtoi(endptr + 1, &endptr, 10, &h) || h <= 0 ||
h > UINT16_MAX || *endptr != '\0') {
error_setg(errp, "%s: resolution must be <width>x<height>, each 1 to "
"65535 pixels, not '%s'", TYPE_REIMS_GRAPHICS_PCI, str);
parts = g_strsplit(str, ",", -1);
n = g_strv_length(parts);
if (n != 1 && n != displays) {
error_setg(errp, "%s: resolution gives %" PRIu32 " sizes for %" PRIu32
" display%s: give one size for every display, or one for "
"each, not '%s'", TYPE_REIMS_GRAPHICS_PCI, n, displays,
displays == 1 ? "" : "s", str);
return false;
}
*width = w;
*height = h;
for (i = 0; i < n; i++) {
if (qemu_strtoi(parts[i], &endptr, 10, &w) || w <= 0 ||
w > UINT16_MAX || *endptr != 'x' ||
qemu_strtoi(endptr + 1, &endptr, 10, &h) || h <= 0 ||
h > UINT16_MAX || *endptr != '\0') {
error_setg(errp, "%s: resolution must be <width>x<height>, each 1 "
"to 65535 pixels, not '%s'", TYPE_REIMS_GRAPHICS_PCI,
parts[i]);
return false;
}
sizes[i] = (RvgDisplayCoord) { .x = w, .y = h };
}
for (i = n; i < displays; i++) {
sizes[i] = sizes[0];
}
*count = n;
return true;
}
@@ -1003,8 +1043,9 @@ static bool reims_graphics_window_wanted(void)
/*
* The vCPU calls the library itself: an access waits at most for the command
* the control thread is taking, which waits for nothing of QEMU's, so it
* needs no BQL. A DOORBELL write of a command queue's ring may answer the
* the control thread is taking, and a STATUS write of 0 also for the settle
* of the GPU work committed before it, neither of which waits for anything
* of QEMU's, so it needs no BQL. A DOORBELL write of a command queue's ring may answer the
* queue's next command buffer on the vCPU and raise the interrupt there,
* waiting for nothing and allocating nothing.
*/
@@ -1244,12 +1285,19 @@ static void reims_graphics_routes_close(ReimsGraphicsPCIState *s)
* which the library fills with blocks of host memory as the pool grows: one
* piece a block, each its own RAM region (so the flat view never merges two,
* and an add or a removal touches no other piece's KVM slot or WHPX mapping),
* owned by an object of its own, a ReimsGraphicsPoolPiece. The library asks
* on its threads (pool_add, pool_remove); the asks are queued and carried out
* on the main loop, under the BQL, in order. Under WHPX the add's hypervisor
* map runs on the asking thread first, outside the BQL (whpx_map_ahead), and
* so does a removal's unmap (whpx_unmap_before_del); under KVM, a removal's
* slot delete (kvm_unmap_before_del).
* owned by an object of its own, a ReimsGraphicsPoolPiece. Each is a RAM
* device: a block is the GPU's memory, which an IOMMU may refuse to map (a
* host mapping of a dma-buf), and vfio's listener, which maps every RAM
* section for a passed-through device's DMA, takes a refused map of a RAM
* device as a warning, where at run time it ends QEMU for any other RAM
* (hw/vfio/listener.c). A RAM device is otherwise RAM here: KVM's and WHPX's
* maps, TCG's and a device's DMA (memory_access_is_direct) take it as any.
*
* The library asks on its threads (pool_add, pool_remove); the asks are queued
* and carried out on the main loop, under the BQL, in order. Under WHPX the
* add's hypervisor map runs on the asking thread first, outside the BQL
* (whpx_map_ahead), and so does a removal's unmap (whpx_unmap_before_del);
* under KVM, a removal's slot delete (kvm_unmap_before_del).
*
* A piece leaves the guest's address space at its removal, under the BQL, but
* a flat view of an older generation or a device's DMA map
@@ -1390,9 +1438,9 @@ static bool reims_graphics_pool_add(ReimsGraphicsPCIState *s,
piece = REIMS_GRAPHICS_POOL_PIECE(object_new(TYPE_REIMS_GRAPHICS_POOL_PIECE));
piece->s = s;
piece->gpa = ask->gpa;
memory_region_init_ram_ptr(&piece->mr, OBJECT(piece),
"reims-graphics-pci.pool-piece", ask->size,
ask->host);
memory_region_init_ram_device_ptr(&piece->mr, OBJECT(piece),
"reims-graphics-pci.pool-piece",
ask->size, ask->host);
qemu_ram_unset_migratable(piece->mr.ram_block);
/*
* Inside the add's transaction: on its own, set_unmergeable commits
@@ -2337,14 +2385,15 @@ static void reims_graphics_pci_check_low_ram(void)
* runs no more of the device's MMIO.
*
* A shutdown whose action pauses the VM (-action shutdown=pause,
* -no-shutdown) keeps the device, which the guest uses again after a reset,
* and then so does its quit, as does a quit of a VM stopped before it: no
* handler hears it. The device then stays to the exit. So does it when a read
* of a display under way still waits for the GPU 5 s into the teardown
* (reims_graphics_pci_teardown). Either way the library's quiesce at the end
* of QEMU's cleanup (reims_graphics_pci_cleanup) stops its GPU work, and QEMU
* then ends with _exit, so the driver's exit handlers never run with the GPU
* device live.
* -no-shutdown) keeps the device, which the guest uses again after a reset.
* Its quit, as a quit of a VM stopped before it (paused, or never started
* past -S), stops no running VM, so no handler hears it: the end of QEMU's
* cleanup tears such a device down (reims_graphics_pci_cleanup). A read of a
* display under way that still waits for the GPU 5 s into the teardown
* (reims_graphics_pci_teardown) keeps the device to the exit; the library's
* quiesce at the end of QEMU's cleanup then stops its GPU work, and QEMU ends
* with _exit, so the driver's exit handlers never run with the GPU device
* live.
*/
static void reims_graphics_pci_vm_state_change(void *opaque, bool running,
RunState state)
@@ -2418,22 +2467,54 @@ static bool reims_graphics_pci_exit_hooked;
*/
static bool reims_graphics_pci_cleaned_up;
/*
* Adds @obj to the list at @opaque where it is a device no teardown ran for:
* one whose VM was not running at the quit
* (reims_graphics_pci_vm_state_change), so its VM state handler is still
* set. For object_child_foreach_recursive, which the teardown, closing the
* device's consoles, must not run inside.
*/
static int reims_graphics_pci_find_left(Object *obj, void *opaque)
{
GSList **left = opaque;
ReimsGraphicsPCIState *s = (ReimsGraphicsPCIState *)
object_dynamic_cast(obj, TYPE_REIMS_GRAPHICS_PCI);
if (s && s->vm_state) {
*left = g_slist_prepend(*left, s);
}
return 0;
}
/*
* At the end of QEMU's cleanup (qemu_add_cleanup_notifier), on every quit
* that reaches it: once the device was released, and where it stays to the
* exit (a shutdown action that pauses, a quit of a stopped VM, a read of a
* display that kept it, reims_graphics_pci_vm_state_change). That is before
* exit() runs any exit handler, so before the GPU driver's: QEMU's own exit
* notifiers run after the driver's, from a handler registered before it
* loaded. Where the release let go of the GPU device, the quiesce answers
* true and the exit goes on. Where the library still holds one, it answers
* false, and QEMU ends with _exit and the cleanup's exit status, after its
* own exit work (reims_graphics_pci_end).
* that reaches it, with the BQL held. A device whose VM was not running at
* the quit (paused, stopped before it, or paused by a shutdown whose action
* pauses: reims_graphics_pci_vm_state_change) is torn down first, as a
* running VM's is at its stop, so the library's release of its last device
* lets go of the GPU device. That is before exit() runs any exit handler, so
* before the GPU driver's: QEMU's own exit notifiers run after the driver's,
* from a handler registered before it loaded. Where the release let go of
* the GPU device, the quiesce answers true and the exit goes on. Where the
* library still holds one (a read of a display that kept the device), it
* answers false, and QEMU ends with _exit and the cleanup's exit status,
* after its own exit work (reims_graphics_pci_end).
*/
static void reims_graphics_pci_cleanup(Notifier *notifier, void *data)
{
int status = *(int *)data;
GSList *left = NULL;
object_child_foreach_recursive(object_get_root(),
reims_graphics_pci_find_left, &left);
for (GSList *l = left; l; l = l->next) {
ReimsGraphicsPCIState *s = l->data;
/* BAR 2 leaves the guest's address space first, as at a stop. */
memory_region_set_enabled(&s->region, false);
reims_graphics_pci_teardown(s, true);
}
g_slist_free(left);
if (!reims_graphics_pci_quiesce("cleanup")) {
reims_graphics_pci_end("cleanup", status);
}
@@ -2691,8 +2772,9 @@ static void reims_graphics_pci_realize(PCIDevice *dev, Error **errp)
};
RvgMemoryMap memory_map;
RvgStatus status;
uint16_t mode_width = 0;
uint16_t mode_height = 0;
/* Each display's size of the resolution property, and how many it gave */
RvgDisplayCoord sizes[RVG_GRAPHICS_DISPLAYS_MAX];
uint32_t size_count;
uint8_t *base;
uint64_t size;
hwaddr pool_base = 0;
@@ -2708,13 +2790,13 @@ static void reims_graphics_pci_realize(PCIDevice *dev, Error **errp)
s->displays);
return;
}
if (!reims_graphics_parse_resolution(s->resolution, &mode_width,
&mode_height, errp)) {
if (!reims_graphics_parse_resolution(s->resolution, s->displays, sizes,
&size_count, errp)) {
return;
}
/*
* Under -display none, a window per display, each at the resolution
* property's size: the library opens it at that mode, and ignores the
* Under -display none, a window per display, each at its size of the
* resolution property: the library opens it at that mode, and ignores the
* flags.
*/
for (i = 0; i < s->displays; i++) {
@@ -2729,8 +2811,8 @@ static void reims_graphics_pci_realize(PCIDevice *dev, Error **errp)
window_configs[i] = (RvgWindowConfig) {
.struct_size = sizeof(window_configs[i]),
.callbacks = &window_callbacks[i],
.mode_width = mode_width,
.mode_height = mode_height,
.mode_width = sizes[i].x,
.mode_height = sizes[i].y,
};
if (i > 0) {
display_windows[i - 1] = &window_configs[i];
@@ -2740,6 +2822,14 @@ static void reims_graphics_pci_realize(PCIDevice *dev, Error **errp)
if (window) {
config.window = &window_configs[0];
config.display_windows = s->displays > 1 ? display_windows : NULL;
} else {
/*
* With no window, each display offers its size of the resolution as
* its mode: one size for every display, or each display's own.
*/
config.headless_mode_width = sizes[0].x;
config.headless_mode_height = sizes[0].y;
config.headless_modes = size_count > 1 ? sizes : NULL;
}
reims_graphics_pci_check_low_ram();
@@ -2794,6 +2884,14 @@ static void reims_graphics_pci_realize(PCIDevice *dev, Error **errp)
reims_graphics_pool_room_machine(&pool_base, &pool_room)) {
config.pool_physical_address = pool_base;
config.pool_physical_length = pool_room;
#ifdef CONFIG_LINUX
/*
* Blocks of host memory where KVM takes no cacheable mapping of the
* GPU's own memory as guest memory
* (reims_graphics_kvm_pool_host_memory).
*/
config.pool_host_memory = reims_graphics_kvm_pool_host_memory();
#endif
}
/* The windows' input runs from here on; the callbacks need the BHs. */
+31
View File
@@ -0,0 +1,31 @@
/*
* reims-graphics-pci: where a window's pointer goes on the guest's tablet.
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef HW_DISPLAY_REIMS_POINTER_H
#define HW_DISPLAY_REIMS_POINTER_H
/*
* The value the device gives QEMU's input layer, which scales [0, @size]
* over the tablet's range, for the pointer at pixel @at of a display @size
* pixels along one axis: each pixel as itself, one past the last held at
* the last, and the last as @size, the tablet's maximum.
*
* A macOS guest scales the tablet's range back over the display its cursor
* is on, and the last pixel sent as itself left the cursor short of it: at
* x 2014.92 and y 1258.94 of a display of 2016 x 1260 pixels (x86-64 macOS
* 26.7.2), and at 1007.43 of 1008 points across (arm64 macOS 26 at 2x), so
* never in its last column or row. The maximum puts it at 2015.98 and
* 1259.98, in the last pixel and still on its display, with a display of
* the guest's placed beside it too.
*/
static inline uint16_t reims_pointer_axis(uint16_t at, uint16_t size)
{
if (size <= 1) {
return 0;
}
return at >= size - 1 ? size : at;
}
#endif
+7 -7
View File
@@ -48,14 +48,14 @@ static const uint8_t hid_usage_keys[0x100] = {
0xe2, 0x2c, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e,
0x3f, 0x40, 0x41, 0x42, 0x43, 0x53, 0x47, 0x5f,
0x60, 0x61, 0x56, 0x5c, 0x5d, 0x5e, 0x57, 0x59,
0x5a, 0x5b, 0x62, 0x63, 0x46, 0x00, 0x64, 0x44,
0x45, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e,
0x5a, 0x5b, 0x62, 0x63, 0x46, 0x6b, 0x64, 0x44,
0x45, 0x68, 0x6f, 0x6a, 0x6b, 0x68, 0x69, 0x6a,
0xe8, 0xe9, 0x71, 0x72, 0x73, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x85, 0x00, 0x00, 0x00, 0x00,
0x88, 0x00, 0x00, 0x87, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x85, 0x00, 0x72, 0x00, 0x73,
0x88, 0x00, 0x00, 0x87, 0x70, 0x00, 0x00, 0x00,
0x00, 0x8a, 0x00, 0x8b, 0x00, 0x89, 0xe7, 0x65,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x6c, 0x6e, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x58, 0xe4, 0x00, 0x00,
@@ -69,8 +69,8 @@ static const uint8_t hid_usage_keys[0x100] = {
0x00, 0x00, 0x00, 0xe3, 0xe7, 0x65, 0x66, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6d,
0x00, 0x71, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
bool hid_has_events(HIDState *hs)
+196 -8
View File
@@ -208,6 +208,7 @@
#include "system/system.h"
#include "system/block-backend.h"
#include "system/hostmem.h"
#include "system/runstate.h"
#include "hw/pci/msix.h"
#include "hw/pci/pcie_sriov.h"
#include "system/spdm-socket.h"
@@ -719,6 +720,7 @@ static void nvme_req_clear(NvmeRequest *req)
req->aiocb = NULL;
memset(&req->cqe, 0x0, sizeof(req->cqe));
req->status = NVME_SUCCESS;
req->held = false;
}
static inline void nvme_sg_init(NvmeCtrl *n, NvmeSg *sg, bool dma)
@@ -873,6 +875,16 @@ static uint16_t nvme_map_addr(NvmeCtrl *n, NvmeSg *sg, hwaddr addr, size_t len)
return NVME_INVALID_USE_OF_CMB | NVME_DNR;
}
/* Merge physically contiguous PRP/SGL entries before checking IOV_MAX. */
if (sg->qsg.nsg > 0) {
ScatterGatherEntry *last = &sg->qsg.sg[sg->qsg.nsg - 1];
if (last->base + last->len == addr && len <= INT32_MAX - last->len) {
last->len += len;
sg->qsg.size += len;
return NVME_SUCCESS;
}
}
if (sg->qsg.nsg + 1 > IOV_MAX) {
goto max_mappings_exceeded;
}
@@ -913,10 +925,17 @@ static uint16_t nvme_map_prp(NvmeCtrl *n, NvmeSg *sg, uint64_t prp1,
len -= trans_len;
if (len) {
if (len > n->page_size) {
g_autofree uint64_t *prp_list = g_new(uint64_t, n->max_prp_ents);
uint64_t prp_list_stack[512];
g_autofree uint64_t *prp_list_heap = NULL;
uint64_t *prp_list = prp_list_stack;
uint32_t nents, prp_trans;
int i = 0;
if (unlikely(n->max_prp_ents > ARRAY_SIZE(prp_list_stack))) {
prp_list_heap = g_new(uint64_t, n->max_prp_ents);
prp_list = prp_list_heap;
}
/*
* The first PRP list entry, pointed to by PRP2 may contain offset.
* Hence, we need to calculate the number of entries in based on
@@ -2152,6 +2171,74 @@ static inline bool nvme_is_write(NvmeRequest *req)
rw->opcode == NVME_CMD_WRITE_ZEROES;
}
/*
* What a failed I/O command does, by its drive's error actions (rerror and
* werror: -drive's defaults report every read error and stop the VM on a
* write that finds no space, as virtio-blk and IDE follow them). Under
* BLOCK_ERROR_ACTION_STOP the command is held: it stays on its SQ's
* out_req_list with no completion to the guest, QEMU pauses the VM with
* io-error, and query-block gives the drive's io-status (nospace for ENOSPC);
* the VM's resume runs the command again (nvme_run_held()). Under IGNORE it
* completes as done, and under REPORT with its error, as every failure did
* before. Each action but STOP's sends QMP's BLOCK_IO_ERROR here; STOP's is
* sent by nvme_hold().
*
* Only a command whose second run gives the guest what one run would takes
* the drive's actions: Read, Write, Write Zeroes, Flush and Dataset
* Management, on an I/O queue of a namespace that is not zoned (a zoned
* write moves its zone's write pointer). Every other command, a cancelled
* one among them, keeps BLOCK_ERROR_ACTION_REPORT with no event.
*/
static BlockErrorAction nvme_error_action(NvmeRequest *req, BlockBackend *blk,
int ret)
{
bool is_read = req->cmd.opcode == NVME_CMD_READ;
BlockErrorAction action;
switch (req->cmd.opcode) {
case NVME_CMD_READ:
case NVME_CMD_WRITE:
case NVME_CMD_WRITE_ZEROES:
case NVME_CMD_FLUSH:
case NVME_CMD_DSM:
break;
default:
return BLOCK_ERROR_ACTION_REPORT;
}
if (!blk || !req->sq->sqid || ret == -ECANCELED ||
(req->ns && req->ns->params.zoned)) {
return BLOCK_ERROR_ACTION_REPORT;
}
action = blk_get_error_action(blk, is_read, -ret);
if (action != BLOCK_ERROR_ACTION_STOP) {
blk_error_action(blk, action, is_read, -ret);
}
return action;
}
/*
* Holds the failed command `req` for the VM's resume (nvme_error_action()),
* then pauses the VM: its data mapping and AIO are let go, and the run at the
* resume maps the command's data again from its PRPs or SGLs, whose memory
* the guest cannot have reused, since the command has not completed.
*/
static void nvme_hold(NvmeRequest *req, BlockBackend *blk, int ret)
{
bool is_read = req->cmd.opcode == NVME_CMD_READ;
trace_pci_nvme_err_aio(nvme_cid(req), strerror(-ret), 0);
nvme_sg_unmap(&req->sg);
req->aiocb = NULL;
req->opaque = NULL;
req->held = true;
blk_error_action(blk, BLOCK_ERROR_ACTION_STOP, is_read, -ret);
}
static void nvme_misc_cb(void *opaque, int ret)
{
NvmeRequest *req = opaque;
@@ -2160,6 +2247,19 @@ static void nvme_misc_cb(void *opaque, int ret)
trace_pci_nvme_misc_cb(cid);
if (ret) {
BlockBackend *blk = req->ns ? req->ns->blkconf.blk : NULL;
switch (nvme_error_action(req, blk, ret)) {
case BLOCK_ERROR_ACTION_STOP:
nvme_hold(req, blk, ret);
return;
case BLOCK_ERROR_ACTION_IGNORE:
req->status = NVME_SUCCESS;
nvme_enqueue_req_completion(nvme_cq(req), req);
return;
default:
break;
}
if (!req->status) {
req->status = NVME_INTERNAL_DEV_ERROR;
}
@@ -2180,6 +2280,20 @@ void nvme_rw_complete_cb(void *opaque, int ret)
trace_pci_nvme_rw_complete_cb(nvme_cid(req), blk_name(blk));
if (ret) {
switch (nvme_error_action(req, blk, ret)) {
case BLOCK_ERROR_ACTION_STOP:
nvme_hold(req, blk, ret);
return;
case BLOCK_ERROR_ACTION_IGNORE:
req->status = NVME_SUCCESS;
ret = 0;
break;
default:
break;
}
}
if (ret) {
Error *err = NULL;
@@ -3571,6 +3685,10 @@ static void nvme_flush_ns_cb(void *opaque, int ret)
if (ret < 0) {
iocb->ret = ret;
iocb->req->status = NVME_WRITE_FAULT;
/* the namespace whose flush failed, whose error actions apply */
if (ret != -ECANCELED) {
iocb->req->ns = nvme_ns(nvme_ctrl(iocb->req), iocb->nsid);
}
goto out;
} else if (iocb->ret < 0) {
goto out;
@@ -4779,6 +4897,49 @@ static uint16_t nvme_io_cmd(NvmeCtrl *n, NvmeRequest *req)
g_assert_not_reached();
}
/*
* Runs each held command again as the VM resumes (nvme_error_action()), in
* the order of its SQ, from the copy of its command taken as it was fetched.
* A command that fails again holds again, and pauses the VM again. A reset
* of the controller while the VM is paused drops the held commands with the
* rest of its queues.
*/
static void nvme_run_held(void *opaque, bool running, RunState state)
{
NvmeCtrl *n = opaque;
if (!running) {
return;
}
for (int i = 1; i < n->num_queues; i++) {
NvmeSQueue *sq = n->sq[i];
NvmeRequest *req, *next;
if (!sq) {
continue;
}
QTAILQ_FOREACH_SAFE(req, &sq->out_req_list, entry, next) {
uint16_t status;
if (!req->held) {
continue;
}
nvme_req_clear(req);
req->cqe.sq_id = cpu_to_le16(sq->sqid);
req->cqe.cid = req->cmd.cid;
status = nvme_io_cmd(n, req);
if (status != NVME_NO_COMPLETE) {
req->status = status;
nvme_enqueue_req_completion(n->cq[sq->cqid], req);
}
}
}
}
static void nvme_cq_notifier(EventNotifier *e)
{
NvmeCQueue *cq = container_of(e, NvmeCQueue, notifier);
@@ -4804,7 +4965,7 @@ static void nvme_cq_notifier(EventNotifier *e)
static int nvme_init_cq_ioeventfd(NvmeCQueue *cq)
{
NvmeCtrl *n = cq->ctrl;
uint16_t offset = (cq->cqid << 3) + (1 << 2);
uint32_t offset = (cq->cqid << 3) + (1 << 2);
int ret;
ret = event_notifier_init(&cq->notifier, 0);
@@ -4833,7 +4994,7 @@ static void nvme_sq_notifier(EventNotifier *e)
static int nvme_init_sq_ioeventfd(NvmeSQueue *sq)
{
NvmeCtrl *n = sq->ctrl;
uint16_t offset = sq->sqid << 3;
uint32_t offset = sq->sqid << 3;
int ret;
ret = event_notifier_init(&sq->notifier, 0);
@@ -4870,7 +5031,7 @@ static void nvme_sq_cancel_inflight(NvmeSQueue *sq, uint16_t status)
static void nvme_free_sq(NvmeSQueue *sq, NvmeCtrl *n)
{
uint16_t offset = sq->sqid << 3;
uint32_t offset = sq->sqid << 3;
n->sq[sq->sqid] = NULL;
qemu_bh_delete(sq->bh);
@@ -5604,7 +5765,7 @@ static uint16_t nvme_get_log(NvmeCtrl *n, NvmeRequest *req)
static void nvme_free_cq(NvmeCQueue *cq, NvmeCtrl *n)
{
PCIDevice *pci = PCI_DEVICE(n);
uint16_t offset = (cq->cqid << 3) + (1 << 2);
uint32_t offset = (cq->cqid << 3) + (1 << 2);
n->cq[cq->cqid] = NULL;
qemu_bh_delete(cq->bh);
@@ -7448,7 +7609,8 @@ static uint16_t nvme_dbbuf_config(NvmeCtrl *n, const NvmeRequest *req)
sq->ei_addr = eis_addr + (i << 3);
stl_le_pci_dma(pci, sq->db_addr, sq->tail, MEMTXATTRS_UNSPECIFIED);
if (n->params.ioeventfd && sq->sqid != 0) {
if (n->params.ioeventfd && sq->sqid != 0 &&
!sq->ioeventfd_enabled) {
if (!nvme_init_sq_ioeventfd(sq)) {
sq->ioeventfd_enabled = true;
}
@@ -7461,7 +7623,8 @@ static uint16_t nvme_dbbuf_config(NvmeCtrl *n, const NvmeRequest *req)
cq->ei_addr = eis_addr + (i << 3) + (1 << 2);
stl_le_pci_dma(pci, cq->db_addr, cq->head, MEMTXATTRS_UNSPECIFIED);
if (n->params.ioeventfd && cq->cqid != 0) {
if (n->params.ioeventfd && cq->cqid != 0 &&
!cq->ioeventfd_enabled) {
if (!nvme_init_cq_ioeventfd(cq)) {
cq->ioeventfd_enabled = true;
}
@@ -9716,6 +9879,9 @@ static void nvme_realize(PCIDevice *pci_dev, Error **errp)
if (!nvme_set_migration_blockers(n, pci_dev, errp)) {
return;
}
n->held_rerun = qdev_add_vm_change_state_handler(dev, nvme_run_held,
NULL, n);
}
static void nvme_exit(PCIDevice *pci_dev)
@@ -9724,6 +9890,11 @@ static void nvme_exit(PCIDevice *pci_dev)
NvmeNamespace *ns;
int i;
if (n->held_rerun) {
qemu_del_vm_change_state_handler(n->held_rerun);
n->held_rerun = NULL;
}
nvme_ctrl_reset(n, NVME_RESET_FUNCTION);
for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
@@ -9777,6 +9948,7 @@ static void nvme_exit(PCIDevice *pci_dev)
static const Property nvme_props[] = {
DEFINE_BLOCK_PROPERTIES(NvmeCtrl, namespace.blkconf),
DEFINE_BLOCK_ERROR_PROPERTIES(NvmeCtrl, namespace.blkconf),
DEFINE_PROP_LINK("pmrdev", NvmeCtrl, pmr.dev, TYPE_MEMORY_BACKEND,
HostMemoryBackend *),
DEFINE_PROP_LINK("subsys", NvmeCtrl, subsys, TYPE_NVME_SUBSYS,
@@ -9794,7 +9966,7 @@ static const Property nvme_props[] = {
DEFINE_PROP_UINT8("vsl", NvmeCtrl, params.vsl, 7),
DEFINE_PROP_BOOL("use-intel-id", NvmeCtrl, params.use_intel_id, false),
DEFINE_PROP_BOOL("legacy-cmb", NvmeCtrl, params.legacy_cmb, false),
DEFINE_PROP_BOOL("ioeventfd", NvmeCtrl, params.ioeventfd, false),
DEFINE_PROP_BOOL("ioeventfd", NvmeCtrl, params.ioeventfd, true),
DEFINE_PROP_BOOL("dbcs", NvmeCtrl, params.dbcs, true),
DEFINE_PROP_UINT8("zoned.zasl", NvmeCtrl, params.zasl, 0),
DEFINE_PROP_BOOL("zoned.auto_transition", NvmeCtrl,
@@ -10166,6 +10338,11 @@ static bool pre_save_validate_aer_req(NvmeRequest *req, Error **errp)
return false;
}
if (req->held) {
error_setg(errp, "req->held");
return false;
}
if (req->sg.flags & NVME_SG_ALLOC) {
error_setg(errp, "unexpected NVME_SG_ALLOC flag in req->sg.flags");
return false;
@@ -10196,6 +10373,11 @@ static bool pre_save_validate_cq_req(NvmeRequest *req, Error **errp)
return false;
}
if (req->held) {
error_setg(errp, "req->held");
return false;
}
if (req->sg.flags & NVME_SG_ALLOC) {
error_setg(errp, "unexpected NVME_SG_ALLOC flag in req->sg.flags");
return false;
@@ -10288,6 +10470,12 @@ static bool nvme_ctrl_pre_save(void *opaque, Error **errp)
sq->head, sq->tail, sq->size);
QTAILQ_FOREACH(req, &sq->out_req_list, entry) {
if (req->held) {
error_setg(errp, "an NVMe command waits for the VM's resume "
"to run again after its drive's error: resume "
"the VM first");
return false;
}
assert(req->cmd.opcode == NVME_ADM_CMD_ASYNC_EV_REQ);
}
}
+3
View File
@@ -240,6 +240,8 @@ static int nvme_ns_init_blk(NvmeNamespace *ns, Error **errp)
}
blk_set_dev_ops(ns->blkconf.blk, &nvme_ns_block_ops, ns);
/* query-block's io-status: why the drive's stop action paused the VM */
blk_iostatus_enable(ns->blkconf.blk);
if (ns->blkconf.discard_granularity == -1) {
ns->blkconf.discard_granularity =
@@ -1140,6 +1142,7 @@ const VMStateDescription nvme_vmstate_ns = {
static const Property nvme_ns_props[] = {
DEFINE_BLOCK_PROPERTIES(NvmeNamespace, blkconf),
DEFINE_BLOCK_ERROR_PROPERTIES(NvmeNamespace, blkconf),
DEFINE_PROP_BOOL("detached", NvmeNamespace, params.detached, false),
DEFINE_PROP_BOOL("shared", NvmeNamespace, params.shared, true),
DEFINE_PROP_UINT32("nsid", NvmeNamespace, params.nsid, 0),
+10
View File
@@ -450,6 +450,13 @@ typedef struct NvmeRequest {
BlockAcctCookie acct;
NvmeSg sg;
bool atomic_write;
/*
* The command failed under the drive's stop action (a host disk with no
* space, by -drive's default werror=enospc) and waits on its SQ's
* out_req_list, with no completion to the guest, for the VM's resume to
* run it again (nvme_hold_on_error()).
*/
bool held;
QTAILQ_ENTRY(NvmeRequest)entry;
/*
* If you add a new field here, please make sure to update
@@ -684,6 +691,9 @@ typedef struct NvmeCtrl {
/* Migration-related stuff */
Error *migration_blocker;
/* Runs held commands again as the VM resumes (nvme_run_held()) */
VMChangeStateEntry *held_rerun;
} NvmeCtrl;
typedef enum NvmeResetType {
+26 -2
View File
@@ -155,6 +155,9 @@ void msix_set_mask(PCIDevice *dev, int vector, bool mask)
offset = vector * PCI_MSIX_ENTRY_SIZE + PCI_MSIX_ENTRY_VECTOR_CTRL;
if (dev->msix_route_update) {
dev->msix_route_update(dev, true);
}
was_masked = msix_is_masked(dev, vector);
if (mask) {
@@ -164,6 +167,9 @@ void msix_set_mask(PCIDevice *dev, int vector, bool mask)
}
msix_handle_mask_update(dev, vector, was_masked);
if (dev->msix_route_update) {
dev->msix_route_update(dev, false);
}
}
static bool msix_masked(PCIDevice *dev)
@@ -227,9 +233,15 @@ static void msix_table_mmio_write(void *opaque, hwaddr addr,
assert(addr + size <= dev->msix_entries_nr * PCI_MSIX_ENTRY_SIZE);
if (dev->msix_route_update) {
dev->msix_route_update(dev, true);
}
was_masked = msix_is_masked(dev, vector);
pci_set_long(dev->msix_table + addr, val);
msix_handle_mask_update(dev, vector, was_masked);
if (dev->msix_route_update) {
dev->msix_route_update(dev, false);
}
}
static const MemoryRegionOps msix_table_mmio_ops = {
@@ -249,10 +261,16 @@ static uint64_t msix_pba_mmio_read(void *opaque, hwaddr addr,
unsigned size)
{
PCIDevice *dev = opaque;
if (dev->msix_vector_poll_notifier) {
if (dev->msix_pba_sync || dev->msix_vector_poll_notifier) {
unsigned vector_start = addr * 8;
unsigned vector_end = MIN((addr + size) * 8, dev->msix_entries_nr);
dev->msix_vector_poll_notifier(dev, vector_start, vector_end);
if (dev->msix_vector_poll_notifier) {
dev->msix_vector_poll_notifier(dev, vector_start, vector_end);
}
if (dev->msix_pba_sync) {
dev->msix_pba_sync(dev, vector_start, vector_end);
}
}
return pci_get_long(dev->msix_pba + addr);
@@ -562,12 +580,18 @@ void msix_reset(PCIDevice *dev)
if (!msix_present(dev)) {
return;
}
if (dev->msix_route_update) {
dev->msix_route_update(dev, true);
}
msix_clear_all_vectors(dev);
dev->config[dev->msix_cap + MSIX_CONTROL_OFFSET] &=
~dev->wmask[dev->msix_cap + MSIX_CONTROL_OFFSET];
memset(dev->msix_table, 0, dev->msix_entries_nr * PCI_MSIX_ENTRY_SIZE);
memset(dev->msix_pba, 0, QEMU_ALIGN_UP(dev->msix_entries_nr, 64) / 8);
msix_mask_all(dev, dev->msix_entries_nr);
if (dev->msix_route_update) {
dev->msix_route_update(dev, false);
}
}
/* PCI spec suggests that devices make it possible for software to configure
+13
View File
@@ -574,6 +574,10 @@ static void pci_do_device_reset(PCIDevice *dev)
return;
}
if (dev->msix_route_update) {
dev->msix_route_update(dev, true);
}
pci_device_deassert_intx(dev);
assert(dev->irq_state == 0);
@@ -600,6 +604,9 @@ static void pci_do_device_reset(PCIDevice *dev)
msi_reset(dev);
msix_reset(dev);
pcie_sriov_pf_reset(dev);
if (dev->msix_route_update) {
dev->msix_route_update(dev, false);
}
}
/*
@@ -3473,6 +3480,9 @@ void pci_set_enabled(PCIDevice *d, bool state)
return;
}
if (d->msix_route_update) {
d->msix_route_update(d, true);
}
d->enabled = state;
pci_update_mappings(d);
pci_set_master(d, (pci_get_word(d->config + PCI_COMMAND)
@@ -3480,6 +3490,9 @@ void pci_set_enabled(PCIDevice *d, bool state)
if (qdev_is_realized(&d->qdev)) {
pci_device_reset(d);
}
if (d->msix_route_update) {
d->msix_route_update(d, false);
}
}
static const TypeInfo pci_device_type_info = {
+116 -9
View File
@@ -106,12 +106,22 @@ static struct {
char **values;
} type11;
static struct {
uint8_t error_correction;
} type16 = {
.error_correction = 0x06, /* Multi-bit ECC (for Microsoft, per SeaBIOS) */
};
static struct {
const char *loc_pfx, *bank, *manufacturer, *serial, *asset, *part;
uint16_t speed;
uint8_t memory_type;
/* The array's devices, past the ones RAM fills empty; 0 for those alone. */
uint16_t slots;
uint8_t form_factor;
} type17 = {
.memory_type = 0x07, /* RAM */
.form_factor = 0x09, /* DIMM */
};
static QEnumLookup type41_kind_lookup = {
@@ -439,6 +449,20 @@ static const QemuOptDesc qemu_smbios_type11_opts[] = {
{ /* end of list */ }
};
static const QemuOptDesc qemu_smbios_type16_opts[] = {
{
.name = "type",
.type = QEMU_OPT_NUMBER,
.help = "SMBIOS element type",
},{
.name = "error_correction",
.type = QEMU_OPT_NUMBER,
.help = "memory error correction (6, multi-bit ECC, by default; "
"3 is none)",
},
{ /* end of list */ }
};
static const QemuOptDesc qemu_smbios_type17_opts[] = {
{
.name = "type",
@@ -476,6 +500,15 @@ static const QemuOptDesc qemu_smbios_type17_opts[] = {
.name = "memory_type",
.type = QEMU_OPT_NUMBER,
.help = "memory type (7, RAM, by default; 26 is DDR4)",
},{
.name = "slots",
.type = QEMU_OPT_NUMBER,
.help = "memory devices in the array, those RAM does not fill "
"empty (by default the ones RAM fills)",
},{
.name = "form_factor",
.type = QEMU_OPT_NUMBER,
.help = "memory form factor (9, DIMM, by default; 13 is SO-DIMM)",
},
{ /* end of list */ }
};
@@ -853,7 +886,7 @@ static void smbios_build_type_11_table(void)
#define MAX_T16_STD_SZ 0x80000000 /* 2T in Kilobytes */
static void smbios_build_type_16_table(unsigned dimm_cnt)
static void smbios_build_type_16_table(unsigned dev_cnt)
{
uint64_t size_kb;
@@ -861,7 +894,7 @@ static void smbios_build_type_16_table(unsigned dimm_cnt)
t->location = 0x01; /* Other */
t->use = 0x03; /* System memory */
t->error_correction = 0x06; /* Multi-bit ECC (for Microsoft, per SeaBIOS) */
t->error_correction = type16.error_correction;
size_kb = QEMU_ALIGN_UP(current_machine->ram_size, KiB) / KiB;
if (size_kb < MAX_T16_STD_SZ) {
t->maximum_capacity = cpu_to_le32(size_kb);
@@ -871,7 +904,7 @@ static void smbios_build_type_16_table(unsigned dimm_cnt)
t->extended_maximum_capacity = cpu_to_le64(current_machine->ram_size);
}
t->memory_error_information_handle = cpu_to_le16(0xFFFE); /* Not provided */
t->number_of_memory_devices = cpu_to_le16(dimm_cnt);
t->number_of_memory_devices = cpu_to_le16(dev_cnt);
SMBIOS_BUILD_TABLE_POST;
}
@@ -899,7 +932,7 @@ static void smbios_build_type_17_table(unsigned instance, uint64_t size)
t->size = cpu_to_le16(MAX_T17_STD_SZ);
t->extended_size = cpu_to_le32(size_mb);
}
t->form_factor = 0x09; /* DIMM */
t->form_factor = type17.form_factor;
t->device_set = 0; /* Not in a set */
snprintf(loc_str, sizeof(loc_str), "%s %d", type17.loc_pfx, instance);
SMBIOS_TABLE_SET_STR(17, device_locator_str, loc_str);
@@ -920,6 +953,43 @@ static void smbios_build_type_17_table(unsigned instance, uint64_t size)
SMBIOS_BUILD_TABLE_POST;
}
/*
* An empty slot of the array (-smbios type=17,slots=): no memory device
* installed (size 0), its type and speed unknown, its locators alone named.
*/
static void smbios_build_type_17_empty_table(unsigned instance)
{
char loc_str[128];
SMBIOS_BUILD_TABLE_PRE(17, T17_BASE + instance, true); /* required */
t->physical_memory_array_handle = cpu_to_le16(0x1000); /* Type 16 above */
t->memory_error_information_handle = cpu_to_le16(0xFFFE); /* Not provided */
t->total_width = cpu_to_le16(0xFFFF); /* Unknown */
t->data_width = cpu_to_le16(0xFFFF); /* Unknown */
t->size = cpu_to_le16(0); /* No memory device installed */
t->extended_size = cpu_to_le32(0);
t->form_factor = type17.form_factor;
t->device_set = 0; /* Not in a set */
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 = 0x02; /* Unknown */
t->type_detail = cpu_to_le16(0x04); /* Unknown */
t->speed = cpu_to_le16(0); /* Unknown */
t->manufacturer_str = 0; /* None */
t->serial_number_str = 0;
t->asset_tag_number_str = 0;
t->part_number_str = 0;
t->attributes = 0; /* Unknown */
t->configured_clock_speed = cpu_to_le16(0); /* Unknown */
t->minimum_voltage = cpu_to_le16(0); /* Unknown */
t->maximum_voltage = cpu_to_le16(0); /* Unknown */
t->configured_voltage = cpu_to_le16(0); /* Unknown */
SMBIOS_BUILD_TABLE_POST;
}
static void smbios_build_type_19_table(unsigned instance, unsigned offset,
uint64_t start, uint64_t size)
{
@@ -1108,7 +1178,7 @@ static bool smbios_get_tables_ep(MachineState *ms,
uint8_t **anchor, size_t *anchor_len,
Error **errp)
{
unsigned i, dimm_cnt, offset;
unsigned i, dimm_cnt, dev_cnt, offset;
MachineClass *mc = MACHINE_GET_CLASS(ms);
ERRP_GUARD();
@@ -1146,6 +1216,8 @@ static bool smbios_get_tables_ep(MachineState *ms,
dimm_cnt = QEMU_ALIGN_UP(current_machine->ram_size,
mc->smbios_memory_device_size) /
mc->smbios_memory_device_size;
/* The array's devices: the ones RAM fills, then empty slots to slots=. */
dev_cnt = MAX(dimm_cnt, type17.slots);
/*
* The offset determines if we need to keep additional space between
@@ -1154,14 +1226,17 @@ static bool smbios_get_tables_ep(MachineState *ms,
* memory and DIMM like chunks of 16 GiB, the default space between
* the two tables (T19_BASE - T17_BASE = 512) is not enough.
*/
offset = (dimm_cnt > (T19_BASE - T17_BASE)) ? \
dimm_cnt - (T19_BASE - T17_BASE) : 0;
offset = (dev_cnt > (T19_BASE - T17_BASE)) ? \
dev_cnt - (T19_BASE - T17_BASE) : 0;
smbios_build_type_16_table(dimm_cnt);
smbios_build_type_16_table(dev_cnt);
for (i = 0; i < dimm_cnt; i++) {
smbios_build_type_17_table(i, GET_DIMM_SZ);
}
for (; i < dev_cnt; i++) {
smbios_build_type_17_empty_table(i);
}
for (i = 0; i < mem_array_size; i++) {
smbios_build_type_19_table(i, offset, mem_array[i].address,
@@ -1540,8 +1615,24 @@ void smbios_entry_add(QemuOpts *opts, Error **errp)
return;
}
return;
case 16: {
uint64_t error_correction;
if (!qemu_opts_validate(opts, qemu_smbios_type16_opts, errp)) {
return;
}
error_correction = qemu_opt_get_number(opts, "error_correction",
0x06 /* multi-bit ECC */);
if (error_correction < 0x01 || error_correction > 0x07) {
error_setg(errp, "SMBIOS memory error correction %" PRIu64
" is out of range (1 to 7)", error_correction);
return;
}
type16.error_correction = error_correction;
return;
}
case 17: {
uint64_t memory_type;
uint64_t memory_type, slots, form_factor;
if (!qemu_opts_validate(opts, qemu_smbios_type17_opts, errp)) {
return;
@@ -1562,6 +1653,22 @@ void smbios_entry_add(QemuOpts *opts, Error **errp)
return;
}
type17.memory_type = memory_type;
slots = qemu_opt_get_number(opts, "slots", 0);
if (slots > 256) {
error_setg(errp, "SMBIOS memory slots %" PRIu64
" are too many (at most 256)", slots);
return;
}
type17.slots = slots;
form_factor = qemu_opt_get_number(opts, "form_factor",
0x09 /* DIMM */);
if (form_factor == 0 || form_factor > UINT8_MAX) {
error_setg(errp, "SMBIOS memory form factor %" PRIu64
" is out of range (1 to %d)", form_factor,
UINT8_MAX);
return;
}
type17.form_factor = form_factor;
return;
}
case 41: {
+249 -5
View File
@@ -21,6 +21,8 @@
#include "standard-headers/linux/virtio_pci.h"
#include "standard-headers/linux/virtio_ids.h"
#include "hw/core/boards.h"
#include "hw/i386/apic-msidef.h"
#include "hw/virtio/virtio-blk.h"
#include "hw/virtio/virtio.h"
#include "migration/qemu-file-types.h"
#include "hw/pci/pci.h"
@@ -36,6 +38,7 @@
#include "hw/core/loader.h"
#include "system/accel-irq.h"
#include "system/kvm.h"
#include "system/whpx.h"
#include "hw/virtio/virtio-pci.h"
#include "qemu/range.h"
#include "hw/virtio/virtio-bus.h"
@@ -70,6 +73,186 @@ static inline VirtIOPCIProxy *to_virtio_pci_proxy_fast(DeviceState *d)
return container_of(d, VirtIOPCIProxy, pci_dev.qdev);
}
struct VirtIOPCIMSIXRoute {
MSIMessage msg;
bool used;
bool masked;
bool direct_ok;
bool shadow_pending;
};
static bool virtio_pci_notify_queue_direct(DeviceState *d, VirtIODevice *vdev,
unsigned int n)
{
VirtIOPCIProxy *proxy = to_virtio_pci_proxy_fast(d);
VirtIOPCIMSIXRoute *route;
uint16_t vector;
if (!whpx_irqchip_in_kernel()) {
return false;
}
QEMU_LOCK_GUARD(&proxy->msix_lock);
if (!proxy->msix_direct_active || n >= proxy->msix_direct_nvqs ||
virtio_device_disabled_atomic(vdev)) {
return false;
}
vector = proxy->msix_queue_vectors[n];
if (vector == VIRTIO_NO_VECTOR) {
return false;
}
route = &proxy->msix_routes[vector];
if (!route->used) {
return false;
}
if (route->masked) {
route->shadow_pending = true;
return true;
}
return route->direct_ok &&
whpx_send_msi_direct(route->msg.address, route->msg.data);
}
static void virtio_pci_msix_direct_disable(DeviceState *d, VirtIODevice *vdev)
{
VirtIOPCIProxy *proxy = to_virtio_pci_proxy_fast(d);
QEMU_LOCK_GUARD(&proxy->msix_lock);
proxy->msix_direct_active = false;
qatomic_set(&vdev->broken, true);
}
/* BQL and msix_lock are held by the caller. */
static void virtio_pci_msix_merge_pending(VirtIOPCIProxy *proxy,
unsigned int start, unsigned int end)
{
for (unsigned int i = start; i < end; i++) {
if (proxy->msix_routes[i].shadow_pending) {
msix_set_pending(&proxy->pci_dev, i);
proxy->msix_routes[i].shadow_pending = false;
}
}
}
static void virtio_pci_msix_sync_pba(PCIDevice *dev, unsigned int start,
unsigned int end)
{
VirtIOPCIProxy *proxy = to_virtio_pci_proxy(&dev->qdev);
QEMU_LOCK_GUARD(&proxy->msix_lock);
virtio_pci_msix_merge_pending(proxy, start, end);
}
static void virtio_pci_msix_revoke(VirtIOPCIProxy *proxy)
{
if (!proxy->msix_routes) {
return;
}
QEMU_LOCK_GUARD(&proxy->msix_lock);
proxy->msix_direct_active = false;
virtio_pci_msix_merge_pending(proxy, 0, proxy->pci_dev.msix_entries_nr);
}
static void virtio_pci_msix_stop(VirtIOPCIProxy *proxy)
{
virtio_pci_msix_revoke(proxy);
proxy->msix_direct_nvqs = 0;
}
static bool virtio_pci_whpx_msi_supported(MSIMessage msg)
{
const uint64_t addr_fields = MSI_ADDR_DEST_ID_MASK |
(1U << MSI_ADDR_DEST_MODE_SHIFT) | (1U << MSI_ADDR_REDIRECTION_SHIFT);
const uint32_t delivery_mask =
MSI_DATA_DELIVERY_MODE_MASK << MSI_DATA_DELIVERY_MODE_SHIFT;
const uint32_t level = 1U << MSI_DATA_LEVEL_SHIFT;
const uint32_t trigger = 1U << MSI_DATA_TRIGGER_SHIFT;
const uint32_t data_fields = MSI_DATA_VECTOR_MASK | delivery_mask |
level | trigger;
/* WHvRequestInterrupt supports fixed/lowest priority and asserts level. */
return (msg.address & ~addr_fields) == 0xfee00000 &&
(msg.data & MSI_DATA_VECTOR_MASK) && !(msg.data & ~data_fields) &&
(msg.data & delivery_mask) <= (1U << MSI_DATA_DELIVERY_MODE_SHIFT) &&
((msg.data & (trigger | level)) != trigger);
}
static void virtio_pci_msix_publish(VirtIOPCIProxy *proxy)
{
PCIDevice *dev = &proxy->pci_dev;
VirtIODevice *vdev;
PCIBus *iommu_bus;
if (!proxy->msix_routes || proxy->msix_update_depth ||
!proxy->msix_direct_nvqs || !proxy->bus.ioeventfd_started ||
proxy->bus.ioeventfd_grabbed || dev->msix_vector_use_notifier ||
!proxy->msix_direct_trigger ||
dev->msi_trigger != proxy->msix_direct_trigger ||
dev->msix_prepare_message != proxy->msix_direct_prepare ||
!dev->is_master || !(dev->config[PCI_COMMAND] & PCI_COMMAND_MASTER) ||
!msix_enabled(dev)) {
return;
}
vdev = virtio_bus_get_device(&proxy->bus);
if (!vdev->vm_running) {
return;
}
pci_device_get_iommu_bus_devfn(dev, &iommu_bus, NULL, NULL);
if (iommu_bus ||
pci_device_iommu_address_space(dev) != &address_space_memory) {
return;
}
QEMU_LOCK_GUARD(&proxy->msix_lock);
if (virtio_device_disabled_atomic(vdev)) {
return;
}
for (unsigned int i = 0; i < proxy->msix_direct_nvqs; i++) {
unsigned int vector = virtio_queue_vector(vdev, i);
proxy->msix_queue_vectors[i] = vector < dev->msix_entries_nr ?
vector : VIRTIO_NO_VECTOR;
}
for (unsigned int i = 0; i < dev->msix_entries_nr; i++) {
VirtIOPCIMSIXRoute *route = &proxy->msix_routes[i];
route->used = dev->msix_entry_used[i] != 0;
route->masked = msix_is_masked(dev, i);
route->msg = msix_get_message(dev, i);
route->direct_ok = virtio_pci_whpx_msi_supported(route->msg);
}
proxy->msix_direct_active = true;
}
static void virtio_pci_msix_route_update(PCIDevice *dev, bool begin)
{
VirtIOPCIProxy *proxy = to_virtio_pci_proxy(&dev->qdev);
if (!proxy->msix_routes) {
return;
}
/*
* Config writes can re-enter through FLR and the PCI config window.
* Keep the routes disabled until the outermost update finishes.
*/
if (begin) {
if (proxy->msix_update_depth++ == 0) {
virtio_pci_msix_revoke(proxy);
}
} else if (--proxy->msix_update_depth == 0) {
virtio_pci_msix_publish(proxy);
}
}
static void virtio_pci_ioeventfd_started(DeviceState *d)
{
virtio_pci_msix_publish(to_virtio_pci_proxy(d));
}
static void virtio_pci_notify(DeviceState *d, uint16_t vector)
{
VirtIOPCIProxy *proxy = to_virtio_pci_proxy_fast(d);
@@ -89,6 +272,7 @@ static void virtio_pci_save_config(DeviceState *d, QEMUFile *f)
VirtIOPCIProxy *proxy = to_virtio_pci_proxy(d);
VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
virtio_pci_msix_stop(proxy);
pci_device_save(&proxy->pci_dev, f);
msix_save(&proxy->pci_dev, f);
if (msix_present(&proxy->pci_dev))
@@ -225,6 +409,7 @@ static int virtio_pci_load_config(DeviceState *d, QEMUFile *f)
uint16_t vector;
int ret;
virtio_pci_msix_stop(proxy);
ret = pci_device_load(&proxy->pci_dev, f);
if (ret) {
return ret;
@@ -416,11 +601,12 @@ static int virtio_pci_ioeventfd_assign(DeviceState *d, EventNotifier *notifier,
static void virtio_pci_start_ioeventfd(VirtIOPCIProxy *proxy)
{
virtio_bus_start_ioeventfd(&proxy->bus);
virtio_device_start_ioeventfd(virtio_bus_get_device(&proxy->bus));
}
static void virtio_pci_stop_ioeventfd(VirtIOPCIProxy *proxy)
{
virtio_pci_msix_stop(proxy);
virtio_bus_stop_ioeventfd(&proxy->bus);
}
@@ -488,6 +674,7 @@ static void virtio_ioport_write(void *opaque, uint32_t addr, uint32_t val)
}
break;
case VIRTIO_MSI_CONFIG_VECTOR:
virtio_pci_msix_route_update(&proxy->pci_dev, true);
if (vdev->config_vector != VIRTIO_NO_VECTOR) {
msix_vector_unuse(&proxy->pci_dev, vdev->config_vector);
}
@@ -498,8 +685,10 @@ static void virtio_ioport_write(void *opaque, uint32_t addr, uint32_t val)
val = VIRTIO_NO_VECTOR;
}
vdev->config_vector = val;
virtio_pci_msix_route_update(&proxy->pci_dev, false);
break;
case VIRTIO_MSI_QUEUE_VECTOR:
virtio_pci_msix_route_update(&proxy->pci_dev, true);
vector = virtio_queue_vector(vdev, vdev->queue_sel);
if (vector != VIRTIO_NO_VECTOR) {
msix_vector_unuse(&proxy->pci_dev, vector);
@@ -511,6 +700,7 @@ static void virtio_ioport_write(void *opaque, uint32_t addr, uint32_t val)
val = VIRTIO_NO_VECTOR;
}
virtio_queue_set_vector(vdev, vdev->queue_sel, val);
virtio_pci_msix_route_update(&proxy->pci_dev, false);
break;
default:
qemu_log_mask(LOG_GUEST_ERROR,
@@ -798,6 +988,7 @@ static void virtio_write_config(PCIDevice *pci_dev, uint32_t address,
VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
struct virtio_pci_cfg_cap *cfg;
virtio_pci_msix_route_update(pci_dev, true);
pci_default_write_config(pci_dev, address, val, len);
if (proxy->flags & VIRTIO_PCI_FLAG_INIT_FLR) {
@@ -809,12 +1000,14 @@ static void virtio_write_config(PCIDevice *pci_dev, uint32_t address,
}
if (range_covers_byte(address, len, PCI_COMMAND)) {
if (!(pci_dev->config[PCI_COMMAND] & PCI_COMMAND_MASTER)) {
virtio_set_disabled(vdev, true);
bool master = pci_dev->config[PCI_COMMAND] & PCI_COMMAND_MASTER;
if (vdev->use_disabled_flag) {
qatomic_set(&vdev->disabled, !master);
}
if (!master) {
virtio_pci_stop_ioeventfd(proxy);
virtio_set_status(vdev, vdev->status & ~VIRTIO_CONFIG_S_DRIVER_OK);
} else {
virtio_set_disabled(vdev, false);
}
}
@@ -834,6 +1027,7 @@ static void virtio_write_config(PCIDevice *pci_dev, uint32_t address,
virtio_address_space_write(proxy, off, cfg->pci_cfg_data, caplen);
}
}
virtio_pci_msix_route_update(pci_dev, false);
}
static uint32_t virtio_read_config(PCIDevice *pci_dev,
@@ -1262,6 +1456,9 @@ static int virtio_pci_set_guest_notifiers(DeviceState *d, int nvqs, bool assign)
}
assert(assign || nvqs == proxy->nvqs_with_notifiers);
if (!assign) {
virtio_pci_msix_stop(proxy);
}
proxy->nvqs_with_notifiers = nvqs;
/* Must unset vector notifier while guest notifier is still assigned */
@@ -1318,6 +1515,9 @@ static int virtio_pci_set_guest_notifiers(DeviceState *d, int nvqs, bool assign)
}
}
if (assign && !with_irqfd && proxy->msix_routes) {
proxy->msix_direct_nvqs = n;
}
return 0;
notifiers_error:
@@ -1638,6 +1838,7 @@ static void virtio_pci_common_write(void *opaque, hwaddr addr,
}
break;
case VIRTIO_PCI_COMMON_MSIX:
virtio_pci_msix_route_update(&proxy->pci_dev, true);
if (vdev->config_vector != VIRTIO_NO_VECTOR) {
msix_vector_unuse(&proxy->pci_dev, vdev->config_vector);
}
@@ -1649,6 +1850,7 @@ static void virtio_pci_common_write(void *opaque, hwaddr addr,
}
virtio_pci_set_vector(vdev, proxy, VIRTIO_CONFIG_IRQ_IDX,
vdev->config_vector, val);
virtio_pci_msix_route_update(&proxy->pci_dev, false);
break;
case VIRTIO_PCI_COMMON_STATUS:
if (!(val & VIRTIO_CONFIG_S_DRIVER_OK)) {
@@ -1678,6 +1880,7 @@ static void virtio_pci_common_write(void *opaque, hwaddr addr,
virtio_init_region_cache(vdev, vdev->queue_sel);
break;
case VIRTIO_PCI_COMMON_Q_MSIX:
virtio_pci_msix_route_update(&proxy->pci_dev, true);
vector = virtio_queue_vector(vdev, vdev->queue_sel);
if (vector != VIRTIO_NO_VECTOR) {
msix_vector_unuse(&proxy->pci_dev, vector);
@@ -1689,6 +1892,7 @@ static void virtio_pci_common_write(void *opaque, hwaddr addr,
val = VIRTIO_NO_VECTOR;
}
virtio_pci_set_vector(vdev, proxy, vdev->queue_sel, vector, val);
virtio_pci_msix_route_update(&proxy->pci_dev, false);
break;
case VIRTIO_PCI_COMMON_Q_ENABLE:
if (val == 1) {
@@ -1735,12 +1939,14 @@ static void virtio_pci_common_write(void *opaque, hwaddr addr,
break;
case VIRTIO_PCI_COMMON_Q_RESET:
if (val == 1) {
virtio_pci_msix_route_update(&proxy->pci_dev, true);
proxy->vqs[vdev->queue_sel].reset = 1;
virtio_queue_reset(vdev, vdev->queue_sel);
proxy->vqs[vdev->queue_sel].reset = 0;
proxy->vqs[vdev->queue_sel].enabled = 0;
virtio_pci_msix_route_update(&proxy->pci_dev, false);
}
break;
default:
@@ -2147,6 +2353,18 @@ static void virtio_pci_device_plugged(DeviceState *d, Error **errp)
}
}
if (whpx_irqchip_in_kernel() && msix_present(&proxy->pci_dev) &&
object_dynamic_cast(OBJECT(vdev), TYPE_VIRTIO_BLK)) {
PCIDevice *dev = &proxy->pci_dev;
int nvqs = virtio_get_num_queues(vdev);
proxy->msix_routes = g_new0(VirtIOPCIMSIXRoute, dev->msix_entries_nr);
proxy->msix_queue_vectors = g_new(uint16_t, nvqs);
proxy->msix_direct_prepare = dev->msix_prepare_message;
dev->msix_route_update = virtio_pci_msix_route_update;
dev->msix_pba_sync = virtio_pci_msix_sync_pba;
}
proxy->pci_dev.config_write = virtio_write_config;
proxy->pci_dev.config_read = virtio_read_config;
@@ -2334,8 +2552,13 @@ static void virtio_pci_exit(PCIDevice *pci_dev)
!pci_bus_is_root(pci_get_bus(pci_dev));
bool modern_pio = proxy->flags & VIRTIO_PCI_FLAG_MODERN_PIO_NOTIFY;
virtio_pci_msix_stop(proxy);
pcie_sriov_pf_exit(&proxy->pci_dev);
pci_dev->msix_route_update = NULL;
pci_dev->msix_pba_sync = NULL;
msix_uninit_exclusive_bar(pci_dev);
g_clear_pointer(&proxy->msix_routes, g_free);
g_clear_pointer(&proxy->msix_queue_vectors, g_free);
if (proxy->flags & VIRTIO_PCI_FLAG_AER && pcie_port &&
pci_is_express(pci_dev)) {
pcie_aer_exit(pci_dev);
@@ -2352,6 +2575,7 @@ static void virtio_pci_reset(DeviceState *qdev)
VirtioBusState *bus = VIRTIO_BUS(&proxy->bus);
int i;
virtio_pci_msix_stop(proxy);
virtio_bus_reset(bus);
msix_unuse_all_vectors(&proxy->pci_dev);
@@ -2435,6 +2659,21 @@ static void virtio_pci_dc_realize(DeviceState *qdev, Error **errp)
}
vpciklass->parent_dc_realize(qdev, errp);
proxy->msix_direct_trigger = pci_dev->msi_trigger;
}
static void virtio_pci_instance_init(Object *obj)
{
VirtIOPCIProxy *proxy = VIRTIO_PCI(obj);
qemu_mutex_init(&proxy->msix_lock);
}
static void virtio_pci_instance_finalize(Object *obj)
{
VirtIOPCIProxy *proxy = VIRTIO_PCI(obj);
qemu_mutex_destroy(&proxy->msix_lock);
}
static int virtio_pci_sync_config(DeviceState *dev, Error **errp)
@@ -2468,6 +2707,8 @@ static const TypeInfo virtio_pci_info = {
.name = TYPE_VIRTIO_PCI,
.parent = TYPE_PCI_DEVICE,
.instance_size = sizeof(VirtIOPCIProxy),
.instance_init = virtio_pci_instance_init,
.instance_finalize = virtio_pci_instance_finalize,
.class_init = virtio_pci_class_init,
.class_size = sizeof(VirtioPCIClass),
.abstract = true,
@@ -2638,6 +2879,8 @@ static void virtio_pci_bus_class_init(ObjectClass *klass, const void *data)
VirtioBusClass *k = VIRTIO_BUS_CLASS(klass);
bus_class->max_dev = 1;
k->notify = virtio_pci_notify;
k->notify_queue_direct = virtio_pci_notify_queue_direct;
k->msix_direct_disable = virtio_pci_msix_direct_disable;
k->save_config = virtio_pci_save_config;
k->load_config = virtio_pci_load_config;
k->save_queue = virtio_pci_save_queue;
@@ -2654,6 +2897,7 @@ static void virtio_pci_bus_class_init(ObjectClass *klass, const void *data)
k->device_unplugged = virtio_pci_device_unplugged;
k->query_nvectors = virtio_pci_query_nvectors;
k->ioeventfd_enabled = virtio_pci_ioeventfd_enabled;
k->ioeventfd_started = virtio_pci_ioeventfd_started;
k->ioeventfd_assign = virtio_pci_ioeventfd_assign;
k->get_dma_as = virtio_pci_get_dma_as;
k->iommu_enabled = virtio_pci_iommu_enabled;
+2 -2
View File
@@ -743,8 +743,8 @@ VirtioStatus *qmp_x_query_virtio_status(const char *path, Error **errp)
status->isr = vdev->isr;
status->queue_sel = vdev->queue_sel;
status->vm_running = vdev->vm_running;
status->broken = vdev->broken;
status->disabled = vdev->disabled;
status->broken = qatomic_read(&vdev->broken);
status->disabled = qatomic_read(&vdev->disabled);
status->use_started = vdev->use_started;
status->started = vdev->started;
status->start_on_kick = vdev->start_on_kick;
+41 -18
View File
@@ -721,7 +721,7 @@ static int virtio_queue_split_empty(VirtQueue *vq)
{
bool empty;
if (virtio_device_disabled(vq->vdev)) {
if (virtio_device_disabled_atomic(vq->vdev)) {
return 1;
}
@@ -744,7 +744,7 @@ static int virtio_queue_packed_empty_rcu(VirtQueue *vq)
struct VRingPackedDesc desc;
VRingMemoryRegionCaches *cache;
if (virtio_device_disabled(vq->vdev)) {
if (virtio_device_disabled_atomic(vq->vdev)) {
return 1;
}
@@ -809,7 +809,7 @@ static bool virtio_queue_packed_poll(VirtQueue *vq, unsigned shadow_idx)
static bool virtio_queue_poll(VirtQueue *vq, unsigned shadow_idx)
{
if (virtio_device_disabled(vq->vdev)) {
if (virtio_device_disabled_atomic(vq->vdev)) {
return false;
}
@@ -1056,7 +1056,7 @@ void virtqueue_fill(VirtQueue *vq, const VirtQueueElement *elem,
virtqueue_unmap_sg(vq, elem, len);
if (virtio_device_disabled(vq->vdev)) {
if (virtio_device_disabled_atomic(vq->vdev)) {
return;
}
@@ -1190,7 +1190,7 @@ static void virtqueue_ordered_flush(VirtQueue *vq)
void virtqueue_flush(VirtQueue *vq, unsigned int count)
{
if (virtio_device_disabled(vq->vdev)) {
if (virtio_device_disabled_atomic(vq->vdev)) {
vq->inuse -= count;
return;
}
@@ -2036,7 +2036,7 @@ err_undo_map:
void *virtqueue_pop(VirtQueue *vq, size_t sz)
{
if (virtio_device_disabled(vq->vdev)) {
if (virtio_device_disabled_atomic(vq->vdev)) {
return NULL;
}
@@ -2138,7 +2138,7 @@ unsigned int virtqueue_drop_all(VirtQueue *vq)
{
struct VirtIODevice *vdev = vq->vdev;
if (virtio_device_disabled(vq->vdev)) {
if (virtio_device_disabled_atomic(vq->vdev)) {
return 0;
}
@@ -2259,7 +2259,7 @@ static void virtio_notify_vector(VirtIODevice *vdev, uint16_t vector)
BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
if (virtio_device_disabled(vdev)) {
if (virtio_device_disabled_atomic(vdev)) {
return;
}
@@ -2514,7 +2514,7 @@ static void virtio_queue_notify_vq(VirtQueue *vq)
if (vq->vring.desc && vq->handle_output) {
VirtIODevice *vdev = vq->vdev;
if (unlikely(vdev->broken)) {
if (unlikely(qatomic_read(&vdev->broken))) {
return;
}
@@ -2531,7 +2531,7 @@ void virtio_queue_notify(VirtIODevice *vdev, int n)
{
VirtQueue *vq = &vdev->vq[n];
if (unlikely(!vq->vring.desc || vdev->broken)) {
if (unlikely(!vq->vring.desc || qatomic_read(&vdev->broken))) {
return;
}
@@ -2716,11 +2716,22 @@ static void virtio_notify_irqfd_deferred_fn(void *opaque)
{
EventNotifier *notifier = opaque;
VirtQueue *vq = container_of(notifier, VirtQueue, guest_notifier);
BusState *qbus = qdev_get_parent_bus(DEVICE(vq->vdev));
VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
trace_virtio_notify_irqfd_deferred_fn(vq->vdev, vq);
if (k->notify_queue_direct && !virtio_device_disabled_atomic(vq->vdev) &&
k->notify_queue_direct(qbus->parent, vq->vdev, vq->queue_index)) {
return;
}
event_notifier_set(notifier);
}
static void virtio_notify_config_deferred_fn(void *opaque)
{
event_notifier_set(opaque);
}
static void virtio_irq(VirtQueue *vq)
{
/*
@@ -2774,7 +2785,7 @@ void virtio_notify_config(VirtIODevice *vdev)
vdev->generation++;
if (qemu_in_iothread()) {
defer_call(virtio_notify_irqfd_deferred_fn, &vdev->config_notifier);
defer_call(virtio_notify_config_deferred_fn, &vdev->config_notifier);
} else {
virtio_notify_vector(vdev, vdev->config_vector);
}
@@ -2832,7 +2843,7 @@ static bool virtio_broken_needed(void *opaque)
{
VirtIODevice *vdev = opaque;
return vdev->broken;
return qatomic_read(&vdev->broken);
}
static bool virtio_started_needed(void *opaque)
@@ -2846,7 +2857,7 @@ static bool virtio_disabled_needed(void *opaque)
{
VirtIODevice *vdev = opaque;
return vdev->disabled;
return qatomic_read(&vdev->disabled);
}
static const VMStateDescription vmstate_virtqueue = {
@@ -3456,12 +3467,12 @@ void virtio_reset(VirtIODevice *vdev)
vdev->start_on_kick = false;
vdev->started = false;
vdev->broken = false;
qatomic_set(&vdev->broken, false);
virtio_features_clear(features);
virtio_set_features_nocheck(vdev, features);
vdev->queue_sel = 0;
vdev->status = 0;
vdev->disabled = false;
qatomic_set(&vdev->disabled, false);
qatomic_set(&vdev->isr, 0);
vdev->config_vector = VIRTIO_NO_VECTOR;
virtio_notify_vector(vdev, vdev->config_vector);
@@ -3794,7 +3805,7 @@ void virtio_init(VirtIODevice *vdev, uint16_t device_id, size_t config_size)
vdev->config_vector = VIRTIO_NO_VECTOR;
vdev->vq = g_new0(VirtQueue, VIRTIO_QUEUE_MAX);
vdev->vm_running = runstate_is_running();
vdev->broken = false;
qatomic_set(&vdev->broken, false);
for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
vdev->vq[i].vector = VIRTIO_NO_VECTOR;
vdev->vq[i].vdev = vdev;
@@ -4226,6 +4237,8 @@ void virtio_device_set_child_bus_name(VirtIODevice *vdev, char *bus_name)
void G_GNUC_PRINTF(2, 3) virtio_error(VirtIODevice *vdev, const char *fmt, ...)
{
BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
va_list ap;
va_start(ap, fmt);
@@ -4237,7 +4250,11 @@ void G_GNUC_PRINTF(2, 3) virtio_error(VirtIODevice *vdev, const char *fmt, ...)
virtio_notify_config(vdev);
}
vdev->broken = true;
if (k->msix_direct_disable) {
k->msix_direct_disable(qbus->parent, vdev);
} else {
qatomic_set(&vdev->broken, true);
}
}
static void virtio_memory_listener_commit(MemoryListener *listener)
@@ -4420,8 +4437,14 @@ int virtio_device_start_ioeventfd(VirtIODevice *vdev)
{
BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
VirtioBusState *vbus = VIRTIO_BUS(qbus);
VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
bool started = vbus->ioeventfd_started;
int ret = virtio_bus_start_ioeventfd(vbus);
return virtio_bus_start_ioeventfd(vbus);
if (!ret && !started && k->ioeventfd_started) {
k->ioeventfd_started(qbus->parent);
}
return ret;
}
static void virtio_device_stop_ioeventfd_impl(VirtIODevice *vdev)
+3 -3
View File
@@ -91,11 +91,11 @@ static inline bool luring_has_fua(void)
typedef struct QEMUWin32AIOState QEMUWin32AIOState;
QEMUWin32AIOState *win32_aio_init(void);
void win32_aio_cleanup(QEMUWin32AIOState *aio);
void win32_aio_flush(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,
+4
View File
@@ -141,6 +141,10 @@ struct PCIDevice {
unsigned *msix_entry_used;
/* MSIX function mask set or MSIX disabled */
bool msix_function_masked;
/* Optional host-side route and pending-bit synchronization under BQL. */
void (*msix_route_update)(PCIDevice *dev, bool begin);
void (*msix_pba_sync)(PCIDevice *dev, unsigned int start, unsigned int end);
/* Version id needed for VMState */
int32_t version_id;
+16
View File
@@ -28,6 +28,7 @@
#include "hw/core/qdev.h"
#include "hw/virtio/virtio.h"
#include "qom/object.h"
#include "qemu/atomic.h"
#define TYPE_VIRTIO_BUS "virtio-bus"
#define VIRTIO_QUEUE_SIZE_OVERRIDE "x-override-queue-size"
@@ -41,6 +42,14 @@ struct VirtioBusClass {
/* This is what a VirtioBus must implement */
BusClass parent;
void (*notify)(DeviceState *d, uint16_t vector);
/* Optional IOThread delivery after publishing a queue's used ring. */
bool (*notify_queue_direct)(DeviceState *d, VirtIODevice *vdev,
unsigned int n);
/*
* Disable direct delivery and publish vdev->broken under the transport
* lock without taking the BQL.
*/
void (*msix_direct_disable)(DeviceState *d, VirtIODevice *vdev);
void (*save_config)(DeviceState *d, QEMUFile *f);
void (*save_queue)(DeviceState *d, int n, QEMUFile *f);
void (*save_extra_state)(DeviceState *d, QEMUFile *f);
@@ -76,6 +85,7 @@ struct VirtioBusClass {
*/
/* Returns true if the ioeventfd is enabled for the device. */
bool (*ioeventfd_enabled)(DeviceState *d);
void (*ioeventfd_started)(DeviceState *d);
/*
* Assigns/deassigns the ioeventfd backing for the transport on
* the device for queue number n. Returns an error value on
@@ -130,6 +140,12 @@ void virtio_bus_get_vdev_config(VirtioBusState *bus, uint8_t *config);
/* Set config of the plugged device. */
void virtio_bus_set_vdev_config(VirtioBusState *bus, uint8_t *config);
static inline bool virtio_device_disabled_atomic(VirtIODevice *vdev)
{
return unlikely(qatomic_read(&vdev->disabled) ||
qatomic_read(&vdev->broken));
}
static inline VirtIODevice *virtio_bus_get_device(VirtioBusState *bus)
{
BusState *qbus = &bus->parent_obj;
+14
View File
@@ -17,6 +17,7 @@
#include "hw/pci/msi.h"
#include "hw/virtio/virtio-bus.h"
#include "qemu/thread.h"
#include "qom/object.h"
@@ -112,6 +113,8 @@ typedef struct VirtIOPCIQueue {
uint32_t used[2];
} VirtIOPCIQueue;
typedef struct VirtIOPCIMSIXRoute VirtIOPCIMSIXRoute;
struct VirtIOPCIProxy {
PCIDevice pci_dev;
MemoryRegion bar;
@@ -150,6 +153,17 @@ struct VirtIOPCIProxy {
VirtIOIRQFD *vector_irqfd;
int nvqs_with_notifiers;
/* Host-only MSI-X routes. Lock order: BQL -> msix_lock -> WHPX MSI lock. */
QemuMutex msix_lock;
VirtIOPCIMSIXRoute *msix_routes;
uint16_t *msix_queue_vectors;
unsigned int msix_direct_nvqs;
unsigned int msix_update_depth;
bool msix_direct_active;
MSITriggerFunc *msix_direct_trigger;
MSIxPrepareMessageFunc *msix_direct_prepare;
VirtioBusState bus;
};
+44
View File
@@ -0,0 +1,44 @@
/*
* Dynamically sized Winsock fd_set helpers to avoid the default
* FD_SETSIZE=64 truncation in Win32 main-loop select().
*/
#ifndef QEMU_WIN32_FDSET_H
#define QEMU_WIN32_FDSET_H
typedef struct QemuWin32FdSet {
u_int fd_count;
SOCKET fd_array[];
} QemuWin32FdSet;
G_STATIC_ASSERT(offsetof(QemuWin32FdSet, fd_array) == offsetof(fd_set, fd_array));
G_STATIC_ASSERT(sizeof(QemuWin32FdSet) == sizeof(SOCKET));
static inline QemuWin32FdSet *qemu_win32_fdset_new(guint capacity)
{
return g_malloc0_n((size_t)capacity + 1, sizeof(SOCKET));
}
static inline bool qemu_win32_fdset_contains(const QemuWin32FdSet *set,
SOCKET fd)
{
for (u_int i = 0; i < set->fd_count; i++) {
if (set->fd_array[i] == fd) {
return true;
}
}
return false;
}
static inline void qemu_win32_fdset_add(QemuWin32FdSet *set, SOCKET fd)
{
if (!qemu_win32_fdset_contains(set, fd)) {
set->fd_array[set->fd_count++] = fd;
}
}
static inline fd_set *qemu_win32_fdset_native(QemuWin32FdSet *set)
{
return (fd_set *)set;
}
#endif
+1 -8
View File
@@ -21,9 +21,8 @@
#define TYPE_IOTHREAD "iothread"
#ifdef CONFIG_POSIX
/*
* Benchmark results from 2016 on NVMe SSD drives show max polling times around
* Benchmark results on NVMe SSD drives show max polling times around
* 16-32 microseconds yield IOPS improvements for both iodepth=1 and iodepth=32
* workloads.
*/
@@ -31,12 +30,6 @@
#define IOTHREAD_POLL_GROW_DEFAULT 2ULL
#define IOTHREAD_POLL_SHRINK_DEFAULT 2ULL
#define IOTHREAD_POLL_WEIGHT_DEFAULT 3ULL
#else
#define IOTHREAD_POLL_MAX_NS_DEFAULT 0ULL
#define IOTHREAD_POLL_GROW_DEFAULT 0ULL
#define IOTHREAD_POLL_SHRINK_DEFAULT 0ULL
#define IOTHREAD_POLL_WEIGHT_DEFAULT 0ULL
#endif
struct IOThread {
EventLoopBase parent_obj;
+15
View File
@@ -10,6 +10,21 @@ struct AccelCPUState {
uint64_t tpr;
bool interruption_pending;
bool loadvm_pending;
bool emu_cr_valid;
uint64_t emu_cr0;
uint64_t emu_cr3;
uint64_t emu_cr4;
struct {
uint64_t mmio_fast_write;
uint64_t mmio_fast_read;
uint64_t mmio_slow;
uint64_t pio;
uint64_t msr;
uint64_t cpuid;
uint64_t apic_eoi;
uint64_t halt;
uint64_t canceled;
} stats;
/* Must be the last field as it may have a tail */
WHV_RUN_VP_EXIT_CONTEXT exit_ctx;
};
+15
View File
@@ -58,6 +58,11 @@ struct whpx_state {
* offered no TSC deadline timer (whpx_tsc_deadline_refused)
*/
bool tsc_deadline_refused;
bool doorbell_unique_match_bug;
WHV_DOORBELL_MATCH_DATA *doorbells;
unsigned nr_doorbells;
unsigned cap_doorbells;
};
extern struct whpx_state whpx_global;
@@ -131,6 +136,16 @@ void whpx_apic_get(APICCommonState *s);
const WHV_MEMORY_RANGE_ENTRY *GpaRanges, UINT32 GpaRangesCount, \
WHV_ADVISE_GPA_RANGE_CODE Advice, const VOID *AdviceBuffer, \
UINT32 AdviceBufferSizeInBytes)) \
X(HRESULT, WHvRegisterPartitionDoorbellEvent, \
(WHV_PARTITION_HANDLE Partition, \
const WHV_DOORBELL_MATCH_DATA *MatchData, HANDLE EventHandle)) \
X(HRESULT, WHvUnregisterPartitionDoorbellEvent, \
(WHV_PARTITION_HANDLE Partition, \
const WHV_DOORBELL_MATCH_DATA *MatchData)) \
X(HRESULT, WHvGetVirtualProcessorCounters, \
(WHV_PARTITION_HANDLE Partition, UINT32 VpIndex, \
WHV_PROCESSOR_COUNTER_SET CounterSet, VOID *Buffer, \
UINT32 BufferSizeInBytes, UINT32 *BytesWritten)) \
LIST_WINHVPLATFORM_FUNCTIONS_SUPPLEMENTAL_ARCH(X)
#define WHP_DEFINE_TYPE(return_type, function_name, signature) \
+15 -1
View File
@@ -2875,8 +2875,11 @@ DEF("smbios", HAS_ARG, QEMU_OPTION_smbios,
" specify SMBIOS type 8 fields\n"
"-smbios type=11[,value=str][,path=filename]\n"
" specify SMBIOS type 11 fields\n"
"-smbios type=16[,error_correction=%d]\n"
" specify SMBIOS type 16 fields\n"
"-smbios type=17[,loc_pfx=str][,bank=str][,manufacturer=str][,serial=str]\n"
" [,asset=str][,part=str][,speed=%d][,memory_type=%d]\n"
" [,slots=%d][,form_factor=%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,9 +2945,20 @@ 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][,memory_type=%d]``
``-smbios type=16[,error_correction=%d]``
Specify SMBIOS type 16 fields. ``error_correction`` is the Memory
Error Correction field's value, 1 to 7 (6, multi-bit ECC, by default;
3 is none).
``-smbios type=17[,loc_pfx=str][,bank=str][,manufacturer=str][,serial=str][,asset=str][,part=str][,speed=%d][,memory_type=%d][,slots=%d][,form_factor=%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).
``slots`` is the memory devices of the array, at most 256: those past
the ones RAM fills are empty slots, of size 0, whose type and speed are
unknown (by default there are only the ones RAM fills). Type 16's Number
of Memory Devices counts them all. ``form_factor`` is every device's
Form Factor field's value, 1 to 255 (9, DIMM, by default; 13 is
SO-DIMM).
``-smbios type=41[,designation=str][,kind=str][,instance=%d][,pcidev=str]``
Specify SMBIOS type 41 fields
+34 -4
View File
@@ -5,6 +5,7 @@ import errno
import json
import os
import shlex
import shutil
import subprocess
import sys
@@ -14,9 +15,26 @@ def destdir_join(d1: str, d2: str) -> str:
# c:\destdir + c:\prefix must produce c:\destdir\prefix
return str(PurePath(d1, *PurePath(d2).parts[1:]))
# Where the host refuses a symbolic link (Windows without Developer Mode or
# an administrator's rights: WinError 1314), the bundle gets a copy of each
# file or directory the configure step finds instead. What is built later
# (the executables, built firmware and generated files) has no copy, which
# only a run from the build tree misses; `ninja install` installs it all.
def copy_instead(source: str, bundle_dest: str) -> bool:
if os.path.isdir(source):
shutil.copytree(source, bundle_dest, dirs_exist_ok=True)
elif os.path.exists(source):
shutil.copy2(source, bundle_dest)
else:
return False
return True
introspect = os.environ.get('MESONINTROSPECT')
out = subprocess.run([*shlex.split(introspect), '--installed'],
stdout=subprocess.PIPE, check=True).stdout
refused = None
copied = 0
left_out = 0
for source, dest in json.loads(out).items():
bundle_dest = destdir_join('qemu-bundle', dest)
path = os.path.dirname(bundle_dest)
@@ -28,9 +46,21 @@ for source, dest in json.loads(out).items():
try:
os.symlink(source, bundle_dest)
except BaseException as e:
if not isinstance(e, OSError) or e.errno != errno.EEXIST:
if os.name == 'nt':
print('Please enable Developer Mode to support soft link '
'without Administrator permission')
if isinstance(e, OSError) and e.errno == errno.EEXIST:
continue
if not isinstance(e, OSError):
print(f'error making symbolic link {dest}', file=sys.stderr)
raise e
refused = refused or e
try:
if copy_instead(source, bundle_dest):
copied += 1
else:
left_out += 1
except BaseException as e2:
print(f'error making symbolic link {dest} ({e}), or a copy',
file=sys.stderr)
raise e2
if refused:
print(f'symbolic links refused ({refused}): qemu-bundle holds copies of '
f'{copied} entries, and leaves out {left_out} not built yet')
+5 -2
View File
@@ -877,8 +877,11 @@ static MachineClass *find_default_machine(GSList *machines)
static void version(void)
{
printf("QEMU emulator version " QEMU_FULL_VERSION "\n"
QEMU_COPYRIGHT "\n");
printf("QEMU emulator version " QEMU_FULL_VERSION
#ifdef _WIN32
" [reims-win32-native-aio]"
#endif
"\n" QEMU_COPYRIGHT "\n");
}
static void help(int exitcode)
+1 -1
View File
@@ -180,7 +180,7 @@ static void decode_imm(CPUX86State *env, struct x86_decode *decode,
{
if (8 == decode->operand_size) {
decode_immediate(env, decode, op, 4);
op->val = sign(op->val, decode->operand_size);
op->val = sign(op->val, 4);
} else {
decode_immediate(env, decode, op, decode->operand_size);
}
+557 -79
View File
@@ -28,6 +28,7 @@
#include "hw/i386/x86.h"
#include "hw/i386/apic_internal.h"
#include "qemu/error-report.h"
#include "qemu/log.h"
#include "qapi/error.h"
#include "qapi/qapi-types-common.h"
#include "qapi/qapi-type-infos-common.h"
@@ -592,8 +593,6 @@ void whpx_set_registers(CPUState *cpu, WHPXStateLevel level)
v86 = (env->eflags & VM_MASK);
r86 = !(env->cr[0] & CR0_PE_MASK);
vcpu->tpr = cpu_get_apic_tpr(x86_cpu->apic_state);
idx = 0;
/* Indexes for first 16 registers match between HV and QEMU definitions */
@@ -649,8 +648,16 @@ void whpx_set_registers(CPUState *cpu, WHPXStateLevel level)
vcxt.values[idx++].Reg64 = env->cr[3];
assert(whpx_register_names[idx] == WHvX64RegisterCr4);
vcxt.values[idx++].Reg64 = env->cr[4];
/* For kernel-irqchip=on, TPR is managed as part of APIC state */
/*
* For kernel-irqchip=on, TPR is managed as part of APIC state.
* vcpu->tpr is the TPR CR8 holds, so it changes only where CR8 is
* written: at WHPX_LEVEL_FAST_RUNTIME_STATE, after an emulated
* instruction, a TPR the instruction changed differs from it, and
* whpx_vcpu_pre_run writes CR8, rather than whpx_vcpu_post_run
* putting CR8's old TPR back into the APIC.
*/
if (!whpx_irqchip_in_kernel()) {
vcpu->tpr = cpu_get_apic_tpr(x86_cpu->apic_state);
WHV_REGISTER_VALUE cr8 = {.Reg64 = vcpu->tpr};
whpx_set_reg(cpu, WHvX64RegisterCr8, cr8);
}
@@ -1208,17 +1215,73 @@ void whpx_get_registers(CPUState *cpu, WHPXStateLevel level)
}
}
static void whpx_commit_changed_fast_regs(CPUState *cpu,
const uint64_t orig_regs[CPU_NB_REGS],
uint64_t orig_eip,
uint64_t orig_eflags)
{
X86CPU *x86_cpu = X86_CPU(cpu);
CPUX86State *env = &x86_cpu->env;
WHV_REGISTER_NAME names[CPU_NB_REGS + 2];
WHV_REGISTER_VALUE values[CPU_NB_REGS + 2];
UINT32 count = 0;
lflags_to_rflags(env);
for (int i = 0; i < CPU_NB_REGS; i++) {
if ((uint64_t)env->regs[i] != orig_regs[i]) {
names[count] = WHvX64RegisterRax + i;
values[count].Reg64 = (uint64_t)env->regs[i];
count++;
}
}
if (env->eip != orig_eip) {
names[count] = WHvX64RegisterRip;
values[count].Reg64 = env->eip;
count++;
}
if (env->eflags != orig_eflags) {
names[count] = WHvX64RegisterRflags;
values[count].Reg64 = env->eflags;
count++;
}
if (count > 0) {
HRESULT hr = whp_dispatch.WHvSetVirtualProcessorRegisters(
whpx_global.partition, cpu->cpu_index, names, count, values);
if (FAILED(hr)) {
error_report("WHPX: Failed to set fast runtime registers, hr=%08lx",
hr);
}
}
}
static int emulate_instruction(CPUState *cpu, const uint8_t *insn_bytes, size_t insn_len)
{
X86CPU *x86_cpu = X86_CPU(cpu);
CPUX86State *env = &x86_cpu->env;
AccelCPUState *vcpu = cpu->accel;
struct x86_decode decode = { 0 };
x86_insn_stream stream = { .bytes = insn_bytes, .len = insn_len };
uint64_t orig_regs[CPU_NB_REGS];
uint64_t orig_eip;
uint64_t orig_eflags;
whpx_get_registers(cpu, WHPX_LEVEL_FAST_RUNTIME_STATE);
for (int i = 0; i < CPU_NB_REGS; i++) {
orig_regs[i] = env->regs[i];
}
orig_eip = env->eip;
orig_eflags = vcpu->exit_ctx.VpContext.Rflags;
vcpu->emu_cr_valid = false;
decode_instruction_stream(env, &decode, &stream);
exec_instruction(env, &decode);
whpx_set_registers(cpu, WHPX_LEVEL_FAST_RUNTIME_STATE);
vcpu->emu_cr_valid = false;
if (!cpu->vcpu_dirty) {
whpx_commit_changed_fast_regs(cpu, orig_regs, orig_eip, orig_eflags);
}
return 0;
}
@@ -1244,11 +1307,317 @@ static int emulate_msr_instruction(CPUState *cpu,
return 0;
}
static int whpx_handle_mmio(CPUState *cpu, WHV_RUN_VP_EXIT_CONTEXT *exit_ctx)
static bool whpx_fast_mmio_read_gpr(CPUState *cpu, int gpr_idx, uint64_t *out)
{
WHV_REGISTER_NAME name = WHvX64RegisterRax + gpr_idx;
WHV_REGISTER_VALUE val = {};
HRESULT hr = whp_dispatch.WHvGetVirtualProcessorRegisters(
whpx_global.partition, cpu->cpu_index, &name, 1, &val);
if (FAILED(hr)) {
return false;
}
*out = val.Reg64;
return true;
}
static bool whpx_try_fast_mmio(CPUState *cpu, WHV_RUN_VP_EXIT_CONTEXT *exit_ctx)
{
WHV_MEMORY_ACCESS_CONTEXT *ctx = &exit_ctx->MemoryAccess;
const uint8_t *bytes = ctx->InstructionBytes;
uint8_t avail = MIN(ctx->InstructionByteCount, (uint8_t)15);
uint8_t vp_len = exit_ctx->VpContext.InstructionLength;
uint8_t insn_len;
bool op_size_override = false;
bool has_rex = false;
bool rex_w = false;
bool rex_r = false;
bool is_write = false;
bool is_imm = false;
bool zero_ext = false;
bool is_high8 = false;
uint8_t mem_size = 0;
uint8_t dst_size = 0;
uint8_t imm_size = 0;
uint8_t opcode, modrm, mod, reg_field, rm;
uint8_t gpr_idx = 0;
uint8_t disp_size = 0;
uint64_t val = 0;
uint8_t pos = 0;
if (cpu->vcpu_dirty ||
!ctx->AccessInfo.GpaUnmapped ||
exit_ctx->VpContext.ExecutionState.DebugActive ||
exit_ctx->VpContext.ExecutionState.InterruptShadow ||
exit_ctx->VpContext.ExecutionState.InterruptionPending ||
(exit_ctx->VpContext.Rflags & (TF_MASK | RF_MASK)) ||
cpu_single_stepping(cpu) ||
!exit_ctx->VpContext.ExecutionState.EferLma ||
!exit_ctx->VpContext.Cs.Long) {
return false;
}
if (ctx->AccessInfo.AccessType != WHvMemoryAccessRead &&
ctx->AccessInfo.AccessType != WHvMemoryAccessWrite) {
return false;
}
if (avail == 0 || (vp_len != 0 && (vp_len > avail || vp_len > 15))) {
return false;
}
while (pos < avail) {
uint8_t p = bytes[pos];
if (p == 0x66) {
op_size_override = true;
pos++;
} else if (p == 0x26 || p == 0x2E ||
p == 0x36 || p == 0x3E || p == 0x64 || p == 0x65) {
pos++;
} else if (p == 0x67 || p == 0xF0 || p == 0xF2 || p == 0xF3) {
return false;
} else {
break;
}
}
if (pos < avail && (bytes[pos] & 0xF0) == 0x40) {
uint8_t rex = bytes[pos++];
has_rex = true;
rex_w = !!(rex & 0x08);
rex_r = !!(rex & 0x04);
}
if (pos >= avail) {
return false;
}
opcode = bytes[pos++];
switch (opcode) {
case 0x88: /* MOV r/m8, r8 */
is_write = true;
mem_size = 1;
break;
case 0x89: /* MOV r/m16/32/64, r16/32/64 */
is_write = true;
mem_size = rex_w ? 8 : (op_size_override ? 2 : 4);
break;
case 0xC6: /* MOV r/m8, imm8 */
is_write = true;
is_imm = true;
mem_size = 1;
imm_size = 1;
break;
case 0xC7: /* MOV r/m16/32/64, imm16/32 */
is_write = true;
is_imm = true;
mem_size = rex_w ? 8 : (op_size_override ? 2 : 4);
imm_size = (op_size_override && !rex_w) ? 2 : 4;
break;
case 0x8A: /* MOV r8, r/m8 */
is_write = false;
mem_size = 1;
dst_size = 1;
break;
case 0x8B: /* MOV r16/32/64, r/m16/32/64 */
is_write = false;
mem_size = rex_w ? 8 : (op_size_override ? 2 : 4);
dst_size = mem_size;
zero_ext = (mem_size == 4);
break;
case 0x0F:
if (pos >= avail) {
return false;
}
opcode = bytes[pos++];
if (opcode == 0xB6) { /* MOVZX r16/32/64, r/m8 */
is_write = false;
mem_size = 1;
dst_size = rex_w ? 8 : (op_size_override ? 2 : 4);
zero_ext = true;
} else if (opcode == 0xB7) { /* MOVZX r32/64, r/m16 */
is_write = false;
mem_size = 2;
dst_size = rex_w ? 8 : (op_size_override ? 2 : 4);
zero_ext = true;
} else {
return false;
}
break;
default:
return false;
}
if ((is_write ? WHvMemoryAccessWrite : WHvMemoryAccessRead) !=
ctx->AccessInfo.AccessType) {
return false;
}
if (pos >= avail) {
return false;
}
modrm = bytes[pos++];
mod = (modrm >> 6) & 3;
reg_field = (modrm >> 3) & 7;
rm = modrm & 7;
if (mod == 3) {
return false;
}
if (is_imm && reg_field != 0) {
return false;
}
if (rm == 4) {
uint8_t sib;
if (pos >= avail) {
return false;
}
sib = bytes[pos++];
if (mod == 0 && (sib & 7) == 5) {
disp_size = 4;
}
} else if (mod == 0 && rm == 5) {
disp_size = 4;
}
if (mod == 1) {
disp_size = 1;
} else if (mod == 2) {
disp_size = 4;
}
if (pos + disp_size + imm_size > avail) {
return false;
}
insn_len = pos + disp_size + imm_size;
if (vp_len != 0 && vp_len != insn_len) {
return false;
}
pos += disp_size;
/* Reject cross-page accesses safely back to the full emulator. */
if (((ctx->Gpa & 0xfff) + mem_size) > 0x1000) {
return false;
}
if (!is_imm) {
if (mem_size == 1 && !zero_ext && !has_rex &&
reg_field >= 4 && reg_field <= 7) {
is_high8 = true;
gpr_idx = reg_field - 4;
} else {
gpr_idx = reg_field | (rex_r ? 8 : 0);
}
}
if (is_write) {
if (is_imm) {
if (imm_size == 1) {
val = bytes[pos];
} else if (imm_size == 2) {
val = lduw_le_p(bytes + pos);
} else {
val = (uint64_t)(int64_t)(int32_t)ldl_le_p(bytes + pos);
}
} else {
if (!whpx_fast_mmio_read_gpr(cpu, gpr_idx, &val)) {
return false;
}
if (is_high8) {
val = (val >> 8) & 0xff;
}
}
MemTxResult res = address_space_write(&address_space_memory, ctx->Gpa,
MEMTXATTRS_UNSPECIFIED, &val,
mem_size);
if (res != MEMTX_OK) {
qemu_log_mask(LOG_GUEST_ERROR,
"WHPX: MMIO write at GPA 0x%" PRIx64
" returned 0x%" PRIx32 "\n",
(uint64_t)ctx->Gpa, res);
if (res == MEMTX_ACCESS_ERROR) {
/* Leave RIP at the denied write, matching exec_mov(). */
cpu->accel->stats.mmio_fast_write++;
return true;
}
}
if (!cpu->vcpu_dirty) {
WHV_REGISTER_VALUE rip_reg = {
.Reg64 = exit_ctx->VpContext.Rip + insn_len,
};
whpx_set_reg(cpu, WHvX64RegisterRip, rip_reg);
} else {
X86_CPU(cpu)->env.eip = exit_ctx->VpContext.Rip + insn_len;
}
cpu->accel->stats.mmio_fast_write++;
return true;
} else {
MemTxResult res = address_space_read(&address_space_memory, ctx->Gpa,
MEMTXATTRS_UNSPECIFIED, &val,
mem_size);
uint64_t new_gpr;
uint64_t mask = (mem_size == 8) ? UINT64_MAX : ((1ULL << (mem_size * 8)) - 1);
uint64_t loaded = (res == MEMTX_DECODE_ERROR) ? mask : (val & mask);
if (dst_size >= 4) {
new_gpr = (dst_size == 4) ? (uint32_t)loaded : loaded;
} else {
uint64_t cur_gpr = 0;
if (cpu->vcpu_dirty) {
cur_gpr = X86_CPU(cpu)->env.regs[gpr_idx];
} else if (!whpx_fast_mmio_read_gpr(cpu, gpr_idx, &cur_gpr)) {
return false;
}
if (dst_size == 1) {
if (is_high8) {
new_gpr = (cur_gpr & ~0xff00ULL) | ((loaded & 0xff) << 8);
} else {
new_gpr = (cur_gpr & ~0xffULL) | (loaded & 0xff);
}
} else { /* dst_size == 2 */
new_gpr = (cur_gpr & ~0xffffULL) | (loaded & 0xffff);
}
}
if (!cpu->vcpu_dirty) {
WHV_REGISTER_NAME names[2] = {
WHvX64RegisterRip,
WHvX64RegisterRax + gpr_idx,
};
WHV_REGISTER_VALUE values[2] = {
{ .Reg64 = exit_ctx->VpContext.Rip + insn_len },
{ .Reg64 = new_gpr },
};
HRESULT hr = whp_dispatch.WHvSetVirtualProcessorRegisters(
whpx_global.partition, cpu->cpu_index, names, 2, values);
if (FAILED(hr)) {
error_report("WHPX: Failed to commit fast MMIO read, hr=%08lx",
hr);
}
} else {
X86CPU *x86_cpu = X86_CPU(cpu);
x86_cpu->env.eip = exit_ctx->VpContext.Rip + insn_len;
x86_cpu->env.regs[gpr_idx] = new_gpr;
}
cpu->accel->stats.mmio_fast_read++;
return true;
}
}
static int whpx_handle_mmio(CPUState *cpu, WHV_RUN_VP_EXIT_CONTEXT *exit_ctx,
bool allow_fast_path)
{
WHV_MEMORY_ACCESS_CONTEXT *ctx = &exit_ctx->MemoryAccess;
int ret;
if (allow_fast_path && whpx_try_fast_mmio(cpu, exit_ctx)) {
return 0;
}
cpu->accel->stats.mmio_slow++;
ret = emulate_instruction(cpu, ctx->InstructionBytes, ctx->InstructionByteCount);
if (ret < 0) {
error_report("failed to emulate mmio");
@@ -1353,9 +1722,10 @@ static int whpx_handle_portio(CPUState *cpu,
if (!ctx->AccessInfo.StringOp && !ctx->AccessInfo.IsWrite) {
uint64_t val = 0;
WHV_REGISTER_VALUE reg;
WHV_REGISTER_VALUE reg = { .Reg64 = ctx->Rax };
uint64_t rip = exit_ctx->VpContext.Rip +
exit_ctx->VpContext.InstructionLength;
whpx_get_reg(cpu, WHvX64RegisterRax, &reg);
handle_io(cpu, ctx->PortNumber, &val, 0, ctx->AccessInfo.AccessSize, 1);
if (ctx->AccessInfo.AccessSize == 1) {
reg.Reg8 = val;
@@ -1368,10 +1738,19 @@ static int whpx_handle_portio(CPUState *cpu,
}
/* vmport calls cpu_synchronize_state on an I/O port read */
if (!cpu->vcpu_dirty) {
whpx_bump_rip(cpu, exit_ctx);
whpx_set_reg(cpu, WHvX64RegisterRax, reg);
const WHV_REGISTER_NAME names[] = {
WHvX64RegisterRip, WHvX64RegisterRax,
};
const WHV_REGISTER_VALUE values[] = { { .Reg64 = rip }, reg };
HRESULT hr = whp_dispatch.WHvSetVirtualProcessorRegisters(
whpx_global.partition, cpu->cpu_index, names,
ARRAY_SIZE(names), values);
if (FAILED(hr)) {
error_report("WHPX: Failed to write IN registers, hr=%08lx",
hr);
}
} else {
env->eip = exit_ctx->VpContext.Rip + exit_ctx->VpContext.InstructionLength;
env->eip = rip;
env->regs[R_EAX] = reg.Reg64;
}
return 0;
@@ -1438,6 +1817,18 @@ static void whpx_read_segment_descriptor(CPUState *cpu, WHV_X64_SEGMENT_REGISTER
*reg = vcpu->exit_ctx.VpContext.Cs;
return;
}
if (vcpu->exit_ctx.VpContext.ExecutionState.EferLma &&
vcpu->exit_ctx.VpContext.Cs.Long &&
(seg == R_ES || seg == R_SS || seg == R_DS)) {
memset(reg, 0, sizeof(*reg));
reg->Base = 0;
reg->Limit = 0xffffffff;
reg->Granularity = 1;
reg->Present = 1;
reg->NonSystemSegment = 1;
reg->SegmentType = 3;
return;
}
if (vcpu->exit_ctx.ExitReason == WHvRunVpExitReasonX64IoPortAccess) {
if (seg == R_DS) {
*reg = vcpu->exit_ctx.IoPortAccess.Ds;
@@ -1483,9 +1874,38 @@ static bool is_user_mode(CPUState *cpu)
static target_ulong read_cr(CPUState *cpu, int cr)
{
AccelCPUState *vcpu = cpu->accel;
WHV_REGISTER_NAME whv_cr;
WHV_REGISTER_VALUE val;
if (cr == 0 || cr == 3 || cr == 4) {
if (!vcpu->emu_cr_valid) {
static const WHV_REGISTER_NAME cr_names[3] = {
WHvX64RegisterCr0,
WHvX64RegisterCr3,
WHvX64RegisterCr4,
};
WHV_REGISTER_VALUE cr_vals[3] = {};
HRESULT hr = whp_dispatch.WHvGetVirtualProcessorRegisters(
whpx_global.partition, cpu->cpu_index, cr_names, 3, cr_vals);
if (SUCCEEDED(hr)) {
vcpu->emu_cr0 = cr_vals[0].Reg64;
vcpu->emu_cr3 = cr_vals[1].Reg64;
vcpu->emu_cr4 = cr_vals[2].Reg64;
vcpu->emu_cr_valid = true;
}
}
if (vcpu->emu_cr_valid) {
if (cr == 0) {
return vcpu->emu_cr0;
} else if (cr == 3) {
return vcpu->emu_cr3;
} else {
return vcpu->emu_cr4;
}
}
}
switch (cr) {
case 0:
whv_cr = WHvX64RegisterCr0;
@@ -1652,8 +2072,8 @@ uint32_t whpx_get_supported_cpuid(uint32_t func, uint32_t idx, int reg)
bool temp_cpu = true;
HRESULT hr;
/* Legacy OSes don't have WHvGetVirtualProcessorCpuidOutput */
if (whpx_is_legacy_os()) {
/* Older builds without WHvGetVirtualProcessorCpuidOutput use legacy path */
if (!whp_dispatch.WHvGetVirtualProcessorCpuidOutput) {
return whpx_get_supported_cpuid_legacy(func, idx, reg);
}
@@ -2295,12 +2715,11 @@ static void whpx_vcpu_pre_run(CPUState *cpu)
X86CPU *x86_cpu = X86_CPU(cpu);
CPUX86State *env = &x86_cpu->env;
int irq;
uint8_t tpr;
WHV_X64_PENDING_INTERRUPTION_REGISTER new_int;
UINT32 reg_count = 0;
WHV_REGISTER_VALUE reg_values[3];
WHV_REGISTER_NAME reg_names[3];
int irr = apic_get_highest_priority_irr(x86_cpu->apic_state);
int irr;
memset(&new_int, 0, sizeof(new_int));
memset(reg_values, 0, sizeof(reg_values));
@@ -2357,6 +2776,7 @@ static void whpx_vcpu_pre_run(CPUState *cpu)
}
}
irr = apic_get_highest_priority_irr(x86_cpu->apic_state);
if (irr == -1) {
if (isa_pic != NULL && pic_get_output(isa_pic)) {
/* In case it's a PIC interrupt */
@@ -2417,13 +2837,16 @@ static void whpx_vcpu_pre_run(CPUState *cpu)
}
/* Sync the TPR to the CR8 if was modified during the intercept */
tpr = cpu_get_apic_tpr(x86_cpu->apic_state);
if (!whpx_irqchip_in_kernel() && tpr != vcpu->tpr) {
vcpu->tpr = tpr;
reg_values[reg_count].Reg64 = tpr;
qatomic_set(&cpu->exit_request, true);
reg_names[reg_count] = WHvX64RegisterCr8;
reg_count += 1;
if (!whpx_irqchip_in_kernel()) {
uint8_t tpr = cpu_get_apic_tpr(x86_cpu->apic_state);
if (tpr != vcpu->tpr) {
vcpu->tpr = tpr;
reg_values[reg_count].Reg64 = tpr;
qatomic_set(&cpu->exit_request, true);
reg_names[reg_count] = WHvX64RegisterCr8;
reg_count += 1;
}
}
/* Update the state of the interrupt delivery notification */
@@ -2709,10 +3132,12 @@ int whpx_vcpu_run(CPUState *cpu)
switch (vcpu->exit_ctx.ExitReason) {
case WHvRunVpExitReasonMemoryAccess:
ret = whpx_handle_mmio(cpu, &vcpu->exit_ctx);
ret = whpx_handle_mmio(cpu, &vcpu->exit_ctx,
exclusive_step_mode == WHPX_STEP_NONE);
break;
case WHvRunVpExitReasonX64IoPortAccess:
vcpu->stats.pio++;
ret = whpx_handle_portio(cpu, &vcpu->exit_ctx);
break;
@@ -2733,6 +3158,7 @@ int whpx_vcpu_run(CPUState *cpu)
break;
case WHvRunVpExitReasonX64ApicEoi:
assert(whpx_irqchip_in_kernel());
vcpu->stats.apic_eoi++;
ioapic_eoi_broadcast(vcpu->exit_ctx.ApicEoi.InterruptVector);
break;
@@ -2740,10 +3166,12 @@ int whpx_vcpu_run(CPUState *cpu)
/*
* Used for kernel-irqchip=off
*/
vcpu->stats.halt++;
ret = whpx_handle_halt(cpu);
break;
case WHvRunVpExitReasonCanceled:
vcpu->stats.canceled++;
if (exclusive_step_mode != WHPX_STEP_NONE) {
/*
* We are trying to step over a single instruction, and
@@ -2765,6 +3193,8 @@ int whpx_vcpu_run(CPUState *cpu)
bool raises_gpf = false;
uint64_t val;
vcpu->stats.msr++;
if (vcpu->exit_ctx.MsrAccess.AccessInfo.IsWrite) {
val = ((uint32_t)vcpu->exit_ctx.MsrAccess.Rax) |
((uint64_t)(vcpu->exit_ctx.MsrAccess.Rdx) << 32);
@@ -2912,6 +3342,8 @@ int whpx_vcpu_run(CPUState *cpu)
X86CPU *x86_cpu = X86_CPU(cpu);
CPUX86State *env = &x86_cpu->env;
vcpu->stats.cpuid++;
reg_names[0] = WHvX64RegisterRip;
reg_names[1] = WHvX64RegisterRax;
reg_names[2] = WHvX64RegisterRcx;
@@ -3435,62 +3867,95 @@ void whpx_arch_accel_class_init(ObjectClass *oc)
/*
* Whether Hyper-V refuses the TSC deadline timer's register, asked as the
* reset of each vCPU sets it (whpx_set_registers), of a vCPU made for the
* question before any other. Hyper-V on a Ryzen 5 5600G refused it
* (hr=c0350005) while its CPUID offered the timer, and a macOS guest, whose
* kernel arms the TSC deadline timer where CPUID offers one, waited at boot
* for interrupts that never came; with the CPU model's tsc-deadline dropped
* it took the local APIC's timer and booted (measured on that host,
* 2026-11-16). Where the register is refused, the leaf the host supports
* offers no TSC deadline timer (whpx_get_supported_cpuid), so the CPU model's
* tsc-deadline is filtered out as any feature the host lacks is, and with
* "check" QEMU says so. KVM likewise offers the timer only where its own
* capability says it has one (KVM_CAP_TSC_DEADLINE_TIMER). Where the vCPU
* cannot be made, the timer is offered as before.
* reset of each vCPU sets it (whpx_set_registers), of the one vCPU of a
* partition made for the question at init and deleted after it. That
* partition has the guest's partition's processor: its local APIC's
* emulation, its nested virtualization and the processor feature banks it
* was given (@features), as whpx_accel_init set them. It is a partition of
* its own because Windows 10 19045, after a vCPU 0 was made and deleted on
* the guest's partition, refused to make vCPU 0 there again (E_INVALIDARG),
* so the guest's first vCPU could not be made.
*
* Hyper-V on a Ryzen 5 5600G refused the register (hr=c0350005) while its
* CPUID offered the timer, and a macOS guest, whose kernel arms the TSC
* deadline timer where CPUID offers one, waited at boot for interrupts that
* never came; with the CPU model's tsc-deadline dropped it took the local
* APIC's timer and booted (measured on that host, 2026-11-16). Where the
* register is refused, the leaf the host supports offers no TSC deadline
* timer (whpx_get_supported_cpuid), so the CPU model's tsc-deadline is
* filtered out as any feature the host lacks is, and with "check" QEMU says
* so. KVM likewise offers the timer only where its own capability says it
* has one (KVM_CAP_TSC_DEADLINE_TIMER). Where the probe's partition or its
* vCPU cannot be made, QEMU warns and the timer is offered as before.
*/
static bool whpx_tsc_deadline_refused(void)
static bool whpx_tsc_deadline_refused(
const WHV_PROCESSOR_FEATURES_BANKS *features)
{
WHV_REGISTER_NAME name = WHvX64RegisterTscDeadline;
WHV_REGISTER_VALUE value = {};
WHV_PARTITION_HANDLE probe = NULL;
WHV_PARTITION_PROPERTY prop = {};
const char *step = "its creation";
HRESULT hr;
bool refused = false;
/*
* Probe on a throwaway partition: on Windows 10 (e.g. 19045), deleting
* vCPU 0 on the real partition causes a subsequent WHvCreateVirtualProcessor
* for vCPU 0 in whpx_init_vcpu() to fail with E_INVALIDARG (0x80070057).
*/
hr = whp_dispatch.WHvCreatePartition(&probe);
if (FAILED(hr)) {
return false;
goto unasked;
}
step = "its processor count";
prop.ProcessorCount = 1;
hr = whp_dispatch.WHvSetPartitionProperty(
probe, WHvPartitionPropertyCodeProcessorCount, &prop, sizeof(prop));
if (FAILED(hr)) {
goto out;
goto unasked;
}
if (whpx_irqchip_in_kernel()) {
WHV_X64_LOCAL_APIC_EMULATION_MODE mode =
WHvX64LocalApicEmulationModeX2Apic;
step = "its local APIC's emulation";
hr = whp_dispatch.WHvSetPartitionProperty(
probe, WHvPartitionPropertyCodeLocalApicEmulationMode,
&mode, sizeof(mode));
if (FAILED(hr)) {
goto out;
goto unasked;
}
}
/* As the guest's partition has it (whpx_accel_init). */
if (whpx_irqchip_in_kernel() && features->Bank1.NestedVirtSupport) {
step = "its nested virtualization";
memset(&prop, 0, sizeof(prop));
prop.NestedVirtualization = 1;
hr = whp_dispatch.WHvSetPartitionProperty(
probe, WHvPartitionPropertyCodeNestedVirtualization,
&prop, sizeof(prop));
if (FAILED(hr)) {
goto unasked;
}
}
/* The guest's partition takes the banks only where it is not legacy. */
if (!whpx_is_legacy_os()) {
step = "its processor feature banks";
hr = whp_dispatch.WHvSetPartitionProperty(
probe, WHvPartitionPropertyCodeProcessorFeaturesBanks,
features, sizeof(*features));
if (FAILED(hr)) {
goto unasked;
}
}
step = "its setup";
hr = whp_dispatch.WHvSetupPartition(probe);
if (FAILED(hr)) {
goto out;
goto unasked;
}
step = "its vCPU";
hr = whp_dispatch.WHvCreateVirtualProcessor(probe, 0, 0);
if (FAILED(hr)) {
goto out;
goto unasked;
}
hr = whp_dispatch.WHvSetVirtualProcessorRegisters(probe, 0, &name, 1, &value);
hr = whp_dispatch.WHvSetVirtualProcessorRegisters(probe, 0, &name, 1,
&value);
whp_dispatch.WHvDeleteVirtualProcessor(probe, 0);
if (FAILED(hr)) {
warn_report("WHPX: Hyper-V refuses the TSC deadline timer's register,"
@@ -3498,9 +3963,15 @@ static bool whpx_tsc_deadline_refused(void)
hr);
refused = true;
}
goto out;
unasked:
warn_report("WHPX: the TSC deadline timer's probe partition failed at %s,"
" hr=%08lx: the guest is offered the timer unasked", step, hr);
out:
whp_dispatch.WHvDeletePartition(probe);
if (probe) {
whp_dispatch.WHvDeletePartition(probe);
}
return refused;
}
@@ -3620,8 +4091,10 @@ int whpx_accel_init(AccelState *as, MachineState *ms)
* are implemented starting from Windows Server 2022 (build 20348).
*/
if (FAILED(hr)) {
warn_report("WHPX: Failed to get performance "
"monitoring features, hr=%08lx", hr);
if (hr != WHV_E_UNKNOWN_CAPABILITY && hr != WHV_E_UNKNOWN_PROPERTY) {
warn_report("WHPX: Failed to get performance "
"monitoring features, hr=%08lx", hr);
}
is_modern_os = false;
} else {
hr = whp_dispatch.WHvSetPartitionProperty(
@@ -3671,16 +4144,21 @@ int whpx_accel_init(AccelState *as, MachineState *ms)
}
}
/* Set all the supported features, to follow the MSHV example */
/*
* Probe 2-bank processor features first (supported on Win10 20H2+ /
* Server 2022 / Win11), and fall back to legacy 1-bank capability only
* if the host rejects the 2-bank query.
*/
memset(&processor_features, 0, sizeof(WHV_PROCESSOR_FEATURES_BANKS));
processor_features.BanksCount = 2;
if (whpx_is_legacy_os()) {
/*
* WHvCapabilityCodeProcessorFeaturesBanks is implemented starting
* from Windows 10 version 20H2 (19041). Fall back to the single-bank
* capability on earlier Windows 10 releases.
*/
bool have_feature_banks = false;
hr = whp_dispatch.WHvGetCapability(
WHvCapabilityCodeProcessorFeaturesBanks, &processor_features,
sizeof(WHV_PROCESSOR_FEATURES_BANKS), &whpx_cap_size);
if (SUCCEEDED(hr)) {
have_feature_banks = true;
} else {
WHV_PROCESSOR_FEATURES legacy_features = {0};
processor_features.BanksCount = 1;
@@ -3688,27 +4166,19 @@ int whpx_accel_init(AccelState *as, MachineState *ms)
WHvCapabilityCodeProcessorFeatures, &legacy_features,
sizeof(legacy_features), &whpx_cap_size);
if (FAILED(hr)) {
warn_report("WHPX: Failed to get legacy processor features,"
" hr=%08lx", hr);
} else {
processor_features.Bank0 = legacy_features;
}
} else {
hr = whp_dispatch.WHvGetCapability(
WHvCapabilityCodeProcessorFeaturesBanks, &processor_features,
sizeof(WHV_PROCESSOR_FEATURES_BANKS), &whpx_cap_size);
if (FAILED(hr)) {
error_report("WHPX: Failed to get processor features,"
" hr=%08lx", hr);
error_report("WHPX: Failed to get processor features, hr=%08lx",
hr);
ret = -ENOSPC;
goto error;
}
processor_features.Bank0 = legacy_features;
}
whpx_rdtsc_cap = processor_features.Bank0.RdtscpSupport;
whpx_invpcid_cap = processor_features.Bank0.InvpcidSupport;
if (whpx_irqchip_in_kernel() && processor_features.Bank1.NestedVirtSupport) {
if (have_feature_banks && whpx_irqchip_in_kernel() &&
processor_features.Bank1.NestedVirtSupport) {
memset(&prop, 0, sizeof(WHV_PARTITION_PROPERTY));
prop.NestedVirtualization = 1;
hr = whp_dispatch.WHvSetPartitionProperty(
@@ -3716,9 +4186,10 @@ int whpx_accel_init(AccelState *as, MachineState *ms)
WHvPartitionPropertyCodeNestedVirtualization,
&prop,
sizeof(WHV_PARTITION_PROPERTY));
if (FAILED(hr)) {
warn_report("WHPX: Failed to enable nested virtualization, hr=%08lx; continuing without nested virt", hr);
processor_features.Bank1.NestedVirtSupport = 0;
if (FAILED(hr)) {
warn_report("WHPX: Failed to enable nested virtualization,"
" hr=%08lx: going on without it", hr);
processor_features.Bank1.NestedVirtSupport = 0;
}
}
@@ -3748,12 +4219,7 @@ int whpx_accel_init(AccelState *as, MachineState *ms)
}
}
/*
* The matching partition property is available on Windows 10 version
* 20H2 (19041). and later. Rely on the whpx_is_legacy_os() check to
* enable this code only on Server 2022 or Windows 11.
*/
if (!whpx_is_legacy_os()) {
if (have_feature_banks) {
hr = whp_dispatch.WHvSetPartitionProperty(
whpx->partition,
WHvPartitionPropertyCodeProcessorFeaturesBanks,
@@ -3765,6 +4231,18 @@ int whpx_accel_init(AccelState *as, MachineState *ms)
ret = -EINVAL;
goto error;
}
} else {
hr = whp_dispatch.WHvSetPartitionProperty(
whpx->partition,
WHvPartitionPropertyCodeProcessorFeatures,
&processor_features.Bank0,
sizeof(WHV_PROCESSOR_FEATURES));
if (FAILED(hr)) {
error_report("WHPX: Failed to set legacy processor features,"
" hr=%08lx", hr);
ret = -EINVAL;
goto error;
}
}
@@ -3880,7 +4358,7 @@ int whpx_accel_init(AccelState *as, MachineState *ms)
goto error;
}
whpx->tsc_deadline_refused = whpx_tsc_deadline_refused();
whpx->tsc_deadline_refused = whpx_tsc_deadline_refused(&processor_features);
whpx_memory_init();
whpx_init_emu();
+125
View File
@@ -0,0 +1,125 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
#ifndef WHPX_MMIO_H
#define WHPX_MMIO_H
#include <stdbool.h>
#include <stdint.h>
typedef struct WhpxMovStore32 {
unsigned int len;
unsigned int reg;
uint32_t value;
bool immediate;
bool has_base;
unsigned int base_reg;
bool has_index;
unsigned int index_reg;
unsigned int scale;
bool rip_relative;
int32_t disp;
} WhpxMovStore32;
static inline uint64_t whpx_mov_store32_ea(const WhpxMovStore32 *store,
uint64_t rip, uint64_t base,
uint64_t index)
{
if (store->rip_relative) {
base = rip + store->len;
}
return base + index * store->scale + store->disp;
}
static inline bool whpx_mmio_write32_address_valid(uint64_t gpa, uint64_t gva,
uint64_t ea)
{
return ea == gva && (ea & 3) == 0 && (ea & 0xfff) <= 0xffc &&
(gpa & 0xfff) == (ea & 0xfff);
}
static inline uint32_t whpx_mov_read_le32(const uint8_t *bytes)
{
return (uint32_t)bytes[0] | ((uint32_t)bytes[1] << 8) |
((uint32_t)bytes[2] << 16) | ((uint32_t)bytes[3] << 24);
}
static inline bool whpx_decode_mov_store32(const uint8_t *bytes,
unsigned int available,
unsigned int exit_len,
WhpxMovStore32 *store)
{
unsigned int len = 0;
uint8_t rex = 0;
if (available < 2 || available > 16) {
return false;
}
if ((bytes[0] & 0xf0) == 0x40) {
rex = bytes[len++];
if ((rex & 8) || available < 3) {
return false;
}
}
uint8_t opcode = bytes[len++];
if (opcode != 0x89 && opcode != 0xc7) {
return false;
}
uint8_t modrm = bytes[len++];
unsigned int mod = modrm >> 6;
unsigned int reg = (modrm >> 3) & 7;
unsigned int base = modrm & 7;
bool immediate = opcode == 0xc7;
bool has_sib = base == 4;
unsigned int index = 4;
unsigned int scale = 1;
if (mod == 3 || (immediate && reg != 0)) {
return false;
}
if (has_sib) {
if (len == available) {
return false;
}
uint8_t sib = bytes[len++];
base = sib & 7;
index = ((sib >> 3) & 7) + ((rex & 2) ? 8 : 0);
scale = 1U << (sib >> 6);
}
/* mod=00/base=5 means disp32, with or without a SIB or REX.B. */
bool has_base = mod != 0 || base != 5;
unsigned int disp_size = (mod == 2 || !has_base) ? 4 : (mod == 1);
const uint8_t *disp = bytes + len;
len += disp_size;
if (immediate) {
len += 4;
}
if (len > available || (exit_len && len != exit_len)) {
return false;
}
*store = (WhpxMovStore32) {
.len = len,
.reg = reg + ((rex & 4) ? 8 : 0),
.immediate = immediate,
.has_base = has_base,
.base_reg = base + ((rex & 1) ? 8 : 0),
.has_index = index != 4,
.index_reg = index,
.scale = scale,
.rip_relative = !has_sib && !has_base,
};
if (disp_size == 4) {
store->disp = (int32_t)whpx_mov_read_le32(disp);
} else if (disp_size == 1) {
store->disp = (int8_t)*disp;
}
if (immediate) {
store->value = whpx_mov_read_le32(bytes + len - 4);
}
return true;
}
#endif
+1
View File
@@ -90,3 +90,4 @@ subdir('qtest')
subdir('migration-stress')
subdir('functional')
subdir('tracetool')
subdir('symlink-install-tree')
+106
View File
@@ -99,6 +99,15 @@ typedef struct {
uint16_t smbios_core_count2;
uint8_t smbios_thread_count;
uint16_t smbios_thread_count2;
/* Type 16's Memory Error Correction, 0 for unchecked. */
uint8_t smbios_mem_error_correction;
/*
* Type 16's Number of Memory Devices, which is the type 17s there are,
* all but the first empty (size 0), 0 for unchecked; and each type 17's
* Form Factor, 0 for unchecked.
*/
uint16_t smbios_mem_devices;
uint8_t smbios_mem_form_factor;
uint8_t *required_struct_types;
int required_struct_types_len;
int type4_count;
@@ -711,6 +720,41 @@ static void smbios_cpu_test(test_data *data, uint32_t addr,
}
}
static void smbios_mem_array_test(test_data *data, uint32_t addr)
{
uint8_t expected = data->smbios_mem_error_correction;
uint8_t error_correction = qtest_readb(data->qts,
addr + offsetof(struct smbios_type_16, error_correction));
uint16_t devices = qtest_readw(data->qts,
addr + offsetof(struct smbios_type_16, number_of_memory_devices));
if (expected) {
g_assert_cmpuint(error_correction, ==, expected);
}
if (data->smbios_mem_devices) {
g_assert_cmpuint(devices, ==, data->smbios_mem_devices);
}
}
/* A type 17's checks; counts it in *count, and in *empty where its size is 0. */
static void smbios_mem_device_test(test_data *data, uint32_t addr, int *count,
int *empty)
{
uint8_t form_factor = qtest_readb(data->qts,
addr + offsetof(struct smbios_type_17, form_factor));
uint16_t size = qtest_readw(data->qts,
addr + offsetof(struct smbios_type_17, size));
if (data->smbios_mem_form_factor) {
g_assert_cmpuint(form_factor, ==, data->smbios_mem_form_factor);
}
(*count)++;
if (size == 0) {
(*empty)++;
}
}
static void smbios_type4_count_test(test_data *data, int type4_count)
{
int expected_type4_count = data->type4_count;
@@ -726,6 +770,7 @@ static void test_smbios_structs(test_data *data, SmbiosEntryPointType ep_type)
SmbiosEntryPoint *ep_table = &data->smbios_ep_table;
int i = 0, len, max_len = 0, type4_count = 0;
int type17_count = 0, type17_empty = 0;
uint8_t type, prv, crt;
uint64_t addr;
@@ -754,6 +799,14 @@ static void test_smbios_structs(test_data *data, SmbiosEntryPointType ep_type)
type4_count++;
}
if (type == 16) {
smbios_mem_array_test(data, addr);
}
if (type == 17) {
smbios_mem_device_test(data, addr, &type17_count, &type17_empty);
}
/* seek to end of unformatted string area of this struct ("\0\0") */
prv = crt = 1;
while (prv || crt) {
@@ -797,6 +850,11 @@ static void test_smbios_structs(test_data *data, SmbiosEntryPointType ep_type)
}
smbios_type4_count_test(data, type4_count);
if (data->smbios_mem_devices) {
g_assert_cmpint(type17_count, ==, data->smbios_mem_devices);
g_assert_cmpint(type17_empty, ==, data->smbios_mem_devices - 1);
}
}
static void test_acpi_load_tables(test_data *data)
@@ -2560,6 +2618,50 @@ static void test_acpi_pc_smbios_options(void)
free_test_data(&data);
}
static void test_acpi_pc_smbios_mem_error_correction(void)
{
uint8_t req_type16[] = { 16 };
test_data data = {
.machine = MACHINE_PC,
.arch = "x86",
.required_struct_types = req_type16,
.required_struct_types_len = ARRAY_SIZE(req_type16),
};
/* Without the option, multi-bit ECC, as before it. */
data.smbios_mem_error_correction = 0x06;
test_smbios(NULL, &data);
free_test_data(&data);
/* None. */
data.smbios_mem_error_correction = 0x03;
test_smbios("-smbios type=16,error_correction=3", &data);
free_test_data(&data);
}
static void test_acpi_pc_smbios_mem_slots(void)
{
uint8_t req_type16_17[] = { 16, 17 };
test_data data = {
.machine = MACHINE_PC,
.arch = "x86",
.required_struct_types = req_type16_17,
.required_struct_types_len = ARRAY_SIZE(req_type16_17),
};
/* Without the options, one DIMM, as before them. */
data.smbios_mem_devices = 1;
data.smbios_mem_form_factor = 0x09;
test_smbios(NULL, &data);
free_test_data(&data);
/* Four SO-DIMM slots, the RAM in the first and three empty. */
data.smbios_mem_devices = 4;
data.smbios_mem_form_factor = 0x0D;
test_smbios("-smbios type=17,slots=4,form_factor=13", &data);
free_test_data(&data);
}
static void test_acpi_pc_smbios_blob(void)
{
uint8_t req_type11[] = { 11 };
@@ -2839,6 +2941,10 @@ int main(int argc, char *argv[])
test_acpi_pc_smbios_blob);
qtest_add_func("acpi/piix4/smbios-legacy",
test_acpi_isapc_smbios_legacy);
qtest_add_func("acpi/piix4/smbios-error-correction",
test_acpi_pc_smbios_mem_error_correction);
qtest_add_func("acpi/piix4/smbios-memory-slots",
test_acpi_pc_smbios_mem_slots);
}
if (qtest_has_machine(MACHINE_Q35)) {
qtest_add_func("acpi/q35", test_acpi_q35_tcg);
+1
View File
@@ -70,6 +70,7 @@ qtests_i386 = \
(igvm.found() and
config_all_devices.has_key('CONFIG_FW_CFG_DMA') ? ['launchupdate-test'] : []) + \
(config_all_devices.has_key('CONFIG_I440FX') ? ['i440fx-test'] : []) + \
(config_all_devices.has_key('CONFIG_I440FX') ? ['pflash-cfi01-test'] : []) + \
(config_all_devices.has_key('CONFIG_I440FX') ? ['ide-test'] : []) + \
(config_all_devices.has_key('CONFIG_I440FX') ? ['numa-test'] : []) + \
(config_all_devices.has_key('CONFIG_I440FX') ? ['test-x86-cpuid-compat'] : []) + \
+244
View File
@@ -14,6 +14,8 @@
#include "qemu/units.h"
#include "libqtest.h"
#include "libqtest-single.h"
#include "qobject/qdict.h"
#include "qobject/qlist.h"
#include "libqos/qgraph.h"
#include "libqos/pci.h"
#include "block/nvme.h"
@@ -554,6 +556,230 @@ static void test_migrate(void *obj, void *data, QGuestAllocator *alloc)
g_string_free(dest_cmdline, true);
}
/*
* Error actions: the namespace the tests write to (nsid 2) is a blkdebug
* drive whose first write fails with the errno the test names. The drive
* takes -drive's default werror=enospc, which virtio-blk and IDE follow.
*/
#define ERR_NSID 2
#define ERR_DRIVE(err) \
"-drive id=drv1,if=none,format=raw,file.driver=blkdebug," \
"file.image.driver=null-co,file.image.read-zeroes=on," \
"file.inject-error.0.event=write_aio," \
"file.inject-error.0.errno=" err "," \
"file.inject-error.0.once=on " \
"-device nvme-ns,drive=drv1,bus=nvme0,nsid=2"
static void nvme_submit(nvme_sq *sq, uint8_t opcode, uint16_t cid,
uint32_t nsid, uint64_t prp1,
uint32_t cdw10, uint32_t cdw11, uint32_t cdw12)
{
QTestState *qts = sq->common.ctrl->pdev->bus->qts;
uint64_t sqe = nvme_get_next_sqe(sq, opcode, cid, prp1);
qtest_writel(qts, PHYS_ADDR_OF_FIELD(NvmeCmd, sqe, nsid), nsid);
qtest_writel(qts, PHYS_ADDR_OF_FIELD(NvmeCmd, sqe, cdw10), cdw10);
qtest_writel(qts, PHYS_ADDR_OF_FIELD(NvmeCmd, sqe, cdw11), cdw11);
qtest_writel(qts, PHYS_ADDR_OF_FIELD(NvmeCmd, sqe, cdw12), cdw12);
nvme_commit_sqe(sq);
}
static const char *vm_status(QTestState *qts)
{
static char status[32];
QDict *rsp = qtest_qmp(qts, "{ 'execute': 'query-status' }");
g_strlcpy(status,
qdict_get_str(qdict_get_qdict(rsp, "return"), "status"),
sizeof(status));
qobject_unref(rsp);
return status;
}
/* The io-status query-block gives the drive drv1. */
static char *drv1_io_status(QTestState *qts)
{
QDict *rsp = qtest_qmp(qts, "{ 'execute': 'query-block' }");
QList *blocks = qdict_get_qlist(rsp, "return");
const QListEntry *e;
char *io_status = NULL;
QLIST_FOREACH_ENTRY(blocks, e) {
QDict *b = qobject_to(QDict, qlist_entry_obj(e));
if (!strcmp(qdict_get_str(b, "device"), "drv1")) {
io_status = g_strdup(qdict_haskey(b, "io-status") ?
qdict_get_str(b, "io-status") : "none");
}
}
qobject_unref(rsp);
g_assert(io_status);
return io_status;
}
/*
* Waits up to 5 s for the write's completion or for QEMU to pause the VM,
* whichever comes first: true where a completion is there.
*/
static bool nvme_wait_cqe_or_pause(nvme_cq *cq, QTestState *qts)
{
for (int i = 0; i < 5000; i++) {
if (nvme_cqe_pending(cq)) {
return true;
}
if (!strcmp(vm_status(qts), "io-error")) {
return false;
}
g_usleep(1000);
}
g_assert_not_reached();
}
/* An I/O queue pair (qid 1), and a one-block write to ERR_NSID on it. */
static void nvme_err_setup(nvme_ctrl *ctrl, nvme_sq *io_sq, nvme_cq *io_cq,
void *obj, QGuestAllocator *alloc)
{
QNvme *nvme = obj;
NvmeCqe cqe;
uint64_t buf;
qpci_device_enable(&nvme->dev);
ctrl->alloc = alloc;
ctrl->pdev = &nvme->dev;
ctrl->bar = qpci_iomap(ctrl->pdev, 0, NULL);
test_migrate_setup_nvme_ctrl(ctrl);
/* I/O queues take the entry sizes CC gives, which an enable sets. */
qpci_io_writel(ctrl->pdev, ctrl->bar, NVME_REG_CC, 0);
nvme_wait_ready(ctrl, 0);
{
uint32_t cc = 0;
NVME_SET_CC_EN(cc, 1);
NVME_SET_CC_IOSQES(cc, 6);
NVME_SET_CC_IOCQES(cc, 4);
qpci_io_writel(ctrl->pdev, ctrl->bar, NVME_REG_CC, cc);
}
nvme_wait_ready(ctrl, 1);
nvme_init_cq(ctrl, io_cq, 3, 4);
nvme_submit(&ctrl->admin_sq, NVME_ADM_CMD_CREATE_CQ, 1, 0,
io_cq->phys_cqe, (3 << 16) | 1, 1, 0);
cqe = nvme_wait(&ctrl->admin_sq);
g_assert(nvme_is_cqe_success(&cqe));
nvme_init_sq(ctrl, io_sq, 2, 4, io_cq);
nvme_submit(&ctrl->admin_sq, NVME_ADM_CMD_CREATE_SQ, 2, 0,
io_sq->phys_sqe, (3 << 16) | 1, (1 << 16) | 1, 0);
cqe = nvme_wait(&ctrl->admin_sq);
g_assert(nvme_is_cqe_success(&cqe));
buf = guest_alloc(alloc, 4096);
qtest_memset(ctrl->pdev->bus->qts, buf, 0xa5, 4096);
nvme_submit(io_sq, NVME_CMD_WRITE, 7, ERR_NSID, buf, 0, 0, 0);
}
/*
* A write that fails with ENOSPC, as a full host disk fails it, pauses the
* VM with the write held, as virtio-blk and IDE do under werror=enospc: the
* guest sees no error. query-block says the drive found no space, and cont
* runs the write again, which then completes.
*/
static void nvmetest_enospc_pauses(void *obj, void *data,
QGuestAllocator *alloc)
{
g_autofree nvme_ctrl *ctrl = g_malloc0(sizeof(*ctrl));
nvme_sq io_sq;
nvme_cq io_cq;
QTestState *qts;
g_autofree char *io_status = NULL;
QDict *rsp;
NvmeCqe cqe;
nvme_err_setup(ctrl, &io_sq, &io_cq, obj, alloc);
qts = ctrl->pdev->bus->qts;
if (nvme_wait_cqe_or_pause(&io_cq, qts)) {
cqe = nvme_handle_cqe(&io_sq);
g_test_message("the write completed to the guest, status 0x%x, "
"and the VM runs", le16_to_cpu(cqe.status) >> 1);
g_assert_not_reached();
}
io_status = drv1_io_status(qts);
g_assert_cmpstr(io_status, ==, "nospace");
g_assert(!nvme_cqe_pending(&io_cq));
rsp = qtest_qmp(qts, "{ 'execute': 'cont' }");
g_assert(qdict_haskey(rsp, "return"));
qobject_unref(rsp);
g_assert(nvme_wait_cqe_or_pause(&io_cq, qts));
cqe = nvme_handle_cqe(&io_sq);
g_assert_cmpint(le16_to_cpu(cqe.cid), ==, 7);
g_assert_cmphex(le16_to_cpu(cqe.status) >> 1, ==, NVME_SUCCESS);
g_assert_cmpstr(vm_status(qts), ==, "running");
qpci_iounmap(ctrl->pdev, ctrl->bar);
}
/*
* A reset while the VM is paused with a write held drops the write with the
* controller's queues: the resume runs nothing again, and QEMU runs on.
*/
static void nvmetest_enospc_reset(void *obj, void *data,
QGuestAllocator *alloc)
{
g_autofree nvme_ctrl *ctrl = g_malloc0(sizeof(*ctrl));
nvme_sq io_sq;
nvme_cq io_cq;
QTestState *qts;
QDict *rsp;
int i;
nvme_err_setup(ctrl, &io_sq, &io_cq, obj, alloc);
qts = ctrl->pdev->bus->qts;
g_assert(!nvme_wait_cqe_or_pause(&io_cq, qts));
rsp = qtest_qmp(qts, "{ 'execute': 'system_reset' }");
g_assert(qdict_haskey(rsp, "return"));
qobject_unref(rsp);
for (i = 0; i < 5000 && !strcmp(vm_status(qts), "io-error"); i++) {
g_usleep(1000);
}
g_assert_cmpstr(vm_status(qts), ==, "prelaunch");
rsp = qtest_qmp(qts, "{ 'execute': 'cont' }");
g_assert(qdict_haskey(rsp, "return"));
qobject_unref(rsp);
g_usleep(100 * 1000);
g_assert_cmpstr(vm_status(qts), ==, "running");
g_assert(!nvme_cqe_pending(&io_cq));
}
/*
* A write that fails otherwise (EIO) still completes to the guest with its
* error under werror=enospc, and the VM runs on.
*/
static void nvmetest_eio_reports(void *obj, void *data, QGuestAllocator *alloc)
{
g_autofree nvme_ctrl *ctrl = g_malloc0(sizeof(*ctrl));
nvme_sq io_sq;
nvme_cq io_cq;
QTestState *qts;
NvmeCqe cqe;
nvme_err_setup(ctrl, &io_sq, &io_cq, obj, alloc);
qts = ctrl->pdev->bus->qts;
g_assert(nvme_wait_cqe_or_pause(&io_cq, qts));
cqe = nvme_handle_cqe(&io_sq);
g_assert_cmpint(le16_to_cpu(cqe.cid), ==, 7);
g_assert_cmphex(le16_to_cpu(cqe.status) >> 1, ==, NVME_WRITE_FAULT);
g_assert_cmpstr(vm_status(qts), ==, "running");
qpci_iounmap(ctrl->pdev, ctrl->bar);
}
static void nvme_register_nodes(void)
{
QOSGraphEdgeOptions opts = {
@@ -582,6 +808,24 @@ static void nvme_register_nodes(void)
qos_add_test("reg-read", "nvme", nvmetest_reg_read_test, NULL);
qos_add_test("migrate", "nvme", test_migrate, NULL);
qos_add_test("enospc-pauses", "nvme", nvmetest_enospc_pauses,
&(QOSGraphTestOptions) {
.edge.extra_device_opts = "id=nvme0",
.edge.after_cmd_line = ERR_DRIVE("28"),
});
qos_add_test("enospc-reset", "nvme", nvmetest_enospc_reset,
&(QOSGraphTestOptions) {
.edge.extra_device_opts = "id=nvme0",
.edge.after_cmd_line = ERR_DRIVE("28"),
});
qos_add_test("eio-reports", "nvme", nvmetest_eio_reports,
&(QOSGraphTestOptions) {
.edge.extra_device_opts = "id=nvme0",
.edge.after_cmd_line = ERR_DRIVE("5"),
});
}
libqos_init(nvme_register_nodes);
+150
View File
@@ -0,0 +1,150 @@
/*
* QTest testcase for the CFI01 parallel flash on a host disk with no space
*
* The pc machine's firmware flash (pflash_cfi01, -drive if=pflash) on a
* blkdebug drive whose first write fails with the errno a test names, over a
* file of the flash's size. -drive's default werror=enospc applies.
*
* This work is licensed under the terms of the GNU GPL, version 2 or later.
* See the COPYING file in the top-level directory.
*/
#include "qemu/osdep.h"
#include <glib/gstdio.h>
#include "libqtest.h"
#include "qobject/qdict.h"
#define FLASH_SIZE (128 * 1024)
#define FLASH_BASE (0x100000000ULL - FLASH_SIZE)
/* A byte of the flash, in its first sector */
#define BYTE_OFF 0x1000
typedef struct Flash {
QTestState *qts;
char *path;
} Flash;
static Flash flash_start(int err)
{
Flash f;
g_autofree uint8_t *ones = g_malloc(FLASH_SIZE);
int fd = g_file_open_tmp("pflash-cfi01-test-XXXXXX", &f.path, NULL);
g_assert(fd >= 0);
memset(ones, 0xff, FLASH_SIZE);
g_assert_cmpint(write(fd, ones, FLASH_SIZE), ==, FLASH_SIZE);
close(fd);
f.qts = qtest_initf("-machine pc "
"-drive if=pflash,format=raw,file.driver=blkdebug,"
"file.image.driver=file,file.image.filename=%s,"
"file.inject-error.0.event=write_aio,"
"file.inject-error.0.errno=%d,"
"file.inject-error.0.once=on",
f.path, err);
return f;
}
static void flash_end(Flash *f)
{
qtest_quit(f->qts);
g_unlink(f->path);
g_free(f->path);
}
static char *vm_status(QTestState *qts)
{
QDict *rsp = qtest_qmp(qts, "{ 'execute': 'query-status' }");
char *status = g_strdup(qdict_get_str(qdict_get_qdict(rsp, "return"),
"status"));
qobject_unref(rsp);
return status;
}
/* The status the VM reaches within 5 s other than running, or running. */
static char *vm_status_settled(QTestState *qts)
{
for (int i = 0; i < 500; i++) {
char *status = vm_status(qts);
if (strcmp(status, "running")) {
return status;
}
g_free(status);
g_usleep(10 * 1000);
}
return vm_status(qts);
}
/* The byte at BYTE_OFF in the flash's file */
static uint8_t file_byte(Flash *f)
{
uint8_t b = 0;
int fd = open(f->path, O_RDONLY);
g_assert(fd >= 0);
g_assert_cmpint(pread(fd, &b, 1, BYTE_OFF), ==, 1);
close(fd);
return b;
}
/* Programs one byte through the flash's single byte program command. */
static void flash_program(Flash *f, uint8_t value)
{
qtest_writeb(f->qts, FLASH_BASE + BYTE_OFF, 0x40);
qtest_writeb(f->qts, FLASH_BASE + BYTE_OFF, value);
qtest_writeb(f->qts, FLASH_BASE + BYTE_OFF, 0xff);
}
/*
* A program whose write to the drive fails with ENOSPC, as a full host disk
* fails it, pauses the VM (io-error) as the disks' devices do; the guest
* reads the byte it wrote meanwhile, and cont writes the byte to the drive.
*/
static void test_enospc_pauses(void)
{
Flash f = flash_start(ENOSPC);
g_autofree char *status = NULL;
g_autofree char *after = NULL;
QDict *rsp;
flash_program(&f, 0x5a);
status = vm_status_settled(f.qts);
g_assert_cmpstr(status, ==, "io-error");
g_assert_cmphex(qtest_readb(f.qts, FLASH_BASE + BYTE_OFF), ==, 0x5a);
g_assert_cmphex(file_byte(&f), ==, 0xff);
rsp = qtest_qmp(f.qts, "{ 'execute': 'cont' }");
g_assert(qdict_haskey(rsp, "return"));
qobject_unref(rsp);
after = vm_status_settled(f.qts);
g_assert_cmpstr(after, ==, "running");
g_assert_cmphex(file_byte(&f), ==, 0x5a);
flash_end(&f);
}
/* A program whose write fails otherwise (EIO) leaves the VM running. */
static void test_eio_runs(void)
{
Flash f = flash_start(EIO);
g_autofree char *status = NULL;
flash_program(&f, 0x5a);
status = vm_status_settled(f.qts);
g_assert_cmpstr(status, ==, "running");
g_assert_cmphex(qtest_readb(f.qts, FLASH_BASE + BYTE_OFF), ==, 0x5a);
g_assert_cmphex(file_byte(&f), ==, 0xff);
flash_end(&f);
}
int main(int argc, char **argv)
{
g_test_init(&argc, &argv, NULL);
qtest_add_func("pflash-cfi01/enospc-pauses", test_enospc_pauses);
qtest_add_func("pflash-cfi01/eio-runs", test_eio_runs);
return g_test_run();
}
+7
View File
@@ -0,0 +1,7 @@
# SPDX-License-Identifier: GPL-2.0-or-later
test('symlink-install-tree',
python,
args: [meson.current_source_dir() / 'symlink-install-tree-test.py',
meson.project_source_root() / 'scripts' / 'symlink-install-tree.py'],
suite: ['scripts'])
@@ -0,0 +1,133 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0-or-later
"""symlink-install-tree-test.py SCRIPT: runs SCRIPT, scripts/symlink-install-tree.py,
over a fake MESONINTROSPECT's install list in a scratch build directory: with
os.symlink refused, as a Windows host without Developer Mode or an
administrator's rights refuses it (WinError 1314), and as the host makes links
where it does."""
import contextlib
import errno
import io
import json
import os
import runpy
import shlex
import sys
import tempfile
import unittest
from pathlib import Path
from unittest import mock
SCRIPT = None
def refusal(err):
"""os.symlink's stand-in on a host that refuses links, with errno ERR."""
def symlink(*args, **kwargs):
raise OSError(err, 'A required privilege is not held by the client')
return symlink
class InstallTree:
"""A source tree with a file and a directory to install, an entry built
later (missing at configure time), and a build directory."""
def __init__(self, top):
self.top = Path(top)
src = self.top / 'src'
(src / 'keymaps').mkdir(parents=True)
(src / 'bios.bin').write_bytes(b'\x55\xaa firmware')
(src / 'keymaps' / 'en-us').write_text('map: en-us\n')
(src / 'keymaps' / 'de').write_text('map: de\n')
self.build = self.top / 'build'
self.build.mkdir()
self.installed = {
str(src / 'bios.bin'): '/prefix/share/qemu/bios.bin',
str(src / 'keymaps'): '/prefix/share/qemu/keymaps',
str(self.build / 'qemu-system-x86_64'): '/prefix/bin/qemu-system-x86_64',
}
listing = self.top / 'installed.json'
listing.write_text(json.dumps(self.installed))
fake = self.top / 'introspect.py'
fake.write_text('import sys\n'
'assert sys.argv[1:] == ["--installed"], sys.argv\n'
f'sys.stdout.write(open({listing.as_posix()!r}).read())\n')
self.introspect = shlex.join([Path(sys.executable).as_posix(),
fake.as_posix()])
def bundle(self, dest):
return self.build / 'qemu-bundle' / Path(*Path(dest).parts[1:])
def configure(self, symlink=None):
"""Runs SCRIPT as meson's configure step does, in the build
directory, with os.symlink replaced by SYMLINK where given. Returns
what it printed."""
out = io.StringIO()
cwd = os.getcwd()
patch = (mock.patch('os.symlink', symlink) if symlink
else contextlib.nullcontext())
try:
os.chdir(self.build)
with mock.patch.dict(os.environ,
{'MESONINTROSPECT': self.introspect}), \
patch, contextlib.redirect_stdout(out):
runpy.run_path(SCRIPT, run_name='__main__')
finally:
os.chdir(cwd)
return out.getvalue()
def links_allowed():
with tempfile.TemporaryDirectory() as d:
try:
os.symlink(d, os.path.join(d, 'link'))
except OSError:
return False
return True
class SymlinkInstallTree(unittest.TestCase):
def test_refused_links_become_copies_whatever_the_errno(self):
for err in (errno.EINVAL, errno.EPERM, errno.EACCES):
with self.subTest(errno=errno.errorcode[err]), \
tempfile.TemporaryDirectory() as top:
t = InstallTree(top)
said = t.configure(refusal(err))
bios = t.bundle('/prefix/share/qemu/bios.bin')
self.assertFalse(bios.is_symlink())
self.assertEqual(bios.read_bytes(), b'\x55\xaa firmware')
keymaps = t.bundle('/prefix/share/qemu/keymaps')
self.assertEqual(sorted(p.name for p in keymaps.iterdir()),
['de', 'en-us'])
self.assertEqual((keymaps / 'de').read_text(), 'map: de\n')
# Built later: left out, not a failure.
self.assertFalse(
t.bundle('/prefix/bin/qemu-system-x86_64').exists())
self.assertIn('symbolic links refused', said)
self.assertIn('copies of 2 entries, and leaves out 1', said)
# Configured again over the copies.
t.configure(refusal(err))
self.assertEqual(bios.read_bytes(), b'\x55\xaa firmware')
@unittest.skipUnless(links_allowed(), 'this host makes no symbolic links')
def test_links_where_the_host_makes_them(self):
with tempfile.TemporaryDirectory() as top:
t = InstallTree(top)
said = t.configure()
for source, dest in t.installed.items():
link = t.bundle(dest)
self.assertTrue(link.is_symlink(), dest)
self.assertEqual(link.resolve(), Path(source).resolve())
self.assertNotIn('refused', said)
# Configured again: the links exist, and are kept.
self.assertEqual(t.configure(), '')
if __name__ == '__main__':
if len(sys.argv) < 2:
sys.exit(__doc__)
# Whole, as each run is in its own build directory.
SCRIPT = os.path.abspath(sys.argv.pop(1))
unittest.main()
+9
View File
@@ -27,6 +27,10 @@ tests = {
'test-cutils': [],
# all code tested by test-dsound-ring is inside audio/dsound-ring.h
'test-dsound-ring': [],
# all code tested by test-reims-pointer is inside hw/display/reims-pointer.h
'test-reims-pointer': [],
# all code tested by test-whpx-mmio is inside target/i386/whpx/whpx-mmio.h
'test-whpx-mmio': [],
'test-div128': [],
'test-shift128': [],
'test-mul64': [],
@@ -54,6 +58,10 @@ tests = {
'test-envlist': [],
}
if host_os == 'windows'
tests += {'test-win32-fdset': []}
endif
if have_system or have_tools
tests += {
'test-qmp-event': [testqapi],
@@ -135,6 +143,7 @@ if have_system
'test-opts-visitor': [testqapi],
'test-xs-node': [qom],
'test-virtio-dmabuf': [meson.project_source_root() / 'hw/display/virtio-dmabuf.c'],
'test-audio-rate': [meson.project_source_root() / 'audio/mixeng.c', genh, libm],
'test-qmp-cmds': [testqapi],
'test-xbzrle': [migration],
'test-util-sockets': ['socket-helpers.c'],
+146
View File
@@ -0,0 +1,146 @@
/*
* The mixing engine's resampler (audio/mixeng.c) as a playback voice's trim
* moves its rate (st_rate_set_out_mhz): the output stays on the input's
* curve, with no step where the rate changes.
*
* SPDX-License-Identifier: MIT
*/
#include "qemu/osdep.h"
#include <math.h>
#include "audio/audio_int.h"
#define TONE_HZ 997.0
#define AMPLITUDE 1073741824.0 /* half of a 32-bit sample's range */
/* The input stream: a sine of TONE_HZ at @inrate, both channels. */
static struct st_sample *tone(int inrate, size_t frames)
{
struct st_sample *in = g_new(struct st_sample, frames);
size_t i;
for (i = 0; i < frames; i++) {
double v = AMPLITUDE * sin(2 * M_PI * TONE_HZ * i / inrate);
in[i].l = v;
in[i].r = -v;
}
return in;
}
/*
* Resample @inrate's tone in pieces of 10 ms of input, the output rate set
* to @out_mhz[k] millihertz from piece @every * k on (0: the rate as made),
* and return the largest distance of an output frame from the tone at the
* input position the output frame stands for: the sum of the increments
* before it, each 1000 * @inrate / the output rate then. Linear interpolation
* of the tone at 44100 Hz or more strays from it by at most 0.0026 of its
* amplitude; a frame dropped or repeated, or the interpolation's fraction
* lost, moves an output frame by up to 0.14 of it. @made is the output frames
* made, and @want the output frames the rates set make of the pieces.
*/
static double run(int inrate, int outrate, const int64_t *out_mhz,
size_t steps, size_t every, size_t pieces, size_t *made_out,
double *want_out)
{
size_t piece = inrate / 100, total = piece * (pieces + 1), taken = 0;
struct st_sample *in = tone(inrate, total);
struct st_sample *out = g_new0(struct st_sample, total * 2);
void *rate = st_rate_start(inrate, outrate);
double pos = 0, inc = (double)inrate / outrate, worst = 0;
double frames_per_piece = (double)piece * outrate / inrate, want = 0;
size_t made = 0, k, i;
for (k = 0; k < pieces; k++) {
size_t isamp, osamp = piece * 2;
if (k % every == 0 && k / every < steps && out_mhz[k / every]) {
st_rate_set_out_mhz(rate, inrate, out_mhz[k / every]);
/* What the converter steps by, to its 32-bit fraction. */
inc = (double)(((uint64_t)inrate << 32) * 1000 /
(uint64_t)out_mhz[k / every]) / 4294967296.0;
frames_per_piece = (double)piece * out_mhz[k / every] / 1000 /
inrate;
}
want += frames_per_piece;
isamp = MIN(piece * (k + 1), total) - taken;
st_rate_flow(rate, in + taken, out + made, &isamp, &osamp);
taken += isamp;
for (i = made; i < made + osamp; i++) {
double at = AMPLITUDE * sin(2 * M_PI * TONE_HZ * pos / inrate);
worst = MAX(worst, fabs((double)out[i].l - at) / AMPLITUDE);
worst = MAX(worst, fabs((double)out[i].r + at) / AMPLITUDE);
pos += inc;
}
made += osamp;
}
st_rate_stop(rate);
g_free(in);
g_free(out);
*made_out = made;
*want_out = want;
return worst;
}
/*
* A 48 kHz voice on a 44.1 kHz device, its rate trimmed every 2 s, up and
* down by up to 1000 ppm: no step in the output, and the output made follows
* the rates set (the input's last frame held back, a frame or two short).
*/
static void test_trim_48k(void)
{
static const int64_t out_mhz[] = {
0, 44100000 + 36000, 44100000 - 44000, 44100000 + 1000,
44100000, 44100000 - 7000,
};
size_t made;
double want, worst = run(48000, 44100, out_mhz, ARRAY_SIZE(out_mhz), 200,
1200, &made, &want);
g_assert_cmpfloat(worst, <, 0.004);
g_assert_cmpfloat(fabs(made - want), <=, 2);
/* 2 s at each rate, the first and the fifth the device's own. */
g_assert_cmpfloat(fabs(want - 2 * (44100 * 2 + 44136 + 44056 + 44101 +
44093)), <, 1e-6);
}
/*
* A voice at its device's own rate copies its input until its trim first
* sets a rate, then interpolates, also when the trim comes back to the rate
* as made: going back to copying would drop the frame the interpolation
* holds, a step in the output.
*/
static void test_trim_equal_rates(void)
{
static const int64_t out_mhz[] = {
0, 44100000 + 5000, 44100000, 44100000 - 3000, 44100000,
};
size_t made;
double want, worst = run(44100, 44100, out_mhz, ARRAY_SIZE(out_mhz), 100,
600, &made, &want);
g_assert_cmpfloat(worst, <, 0.004);
g_assert_cmpfloat(fabs(made - want), <=, 2);
}
/* A rate never trimmed copies its input frame for frame. */
static void test_untrimmed_copies(void)
{
static const int64_t out_mhz[] = { 0 };
size_t made;
double want;
g_assert_cmpfloat(run(44100, 44100, out_mhz, 1, 100, 100, &made, &want),
<, 1e-6);
g_assert_cmpuint(made, ==, 44100);
}
int main(int argc, char **argv)
{
g_test_init(&argc, &argv, NULL);
g_test_add_func("/audio/rate/trim-48k", test_trim_48k);
g_test_add_func("/audio/rate/trim-equal-rates", test_trim_equal_rates);
g_test_add_func("/audio/rate/untrimmed-copies", test_untrimmed_copies);
return g_test_run();
}
+178 -3
View File
@@ -1,7 +1,7 @@
/*
* The DirectSound audio driver's playback buffer arithmetic
* (audio/dsound-ring.h), which audio/dsoundaudio.c builds with on Windows
* alone, held on any host.
* The DirectSound audio driver's playback buffer arithmetic and the trim of
* its playback rate (audio/dsound-ring.h), which audio/dsoundaudio.c builds
* with on Windows alone, held on any host.
*
* SPDX-License-Identifier: MIT
*/
@@ -55,6 +55,176 @@ static void test_filled_after(void)
==, 0);
}
/*
* A voice under its trim, as a Windows host plays an x86-64 macOS guest's
* sound: the guest posts 4096 frames of 48 kHz (85.33 ms) at a time, each
* post on its 41.67 ms grid, and the voice's 44100 Hz DirectSound buffer
* starts 60 ms of reserve past the write cursor. The host's device takes the
* audio @drift_hz past the voice's frequency, and the trim's offset more.
* Reads come every 10 ms and at each post. Until the first post the write
* position keeps its place; after it, a read whose margin past the write
* cursor is below 0 is a gap, which places the write position 60 ms past the
* write cursor again. Over @secs s from a grid phase of @phase_ns, it reports
* the gaps, the margin's least over the run's last half, and the offset at
* its end.
*/
typedef struct {
unsigned gaps;
double least_ms;
int offset_hz;
} TrimRun;
static TrimRun trim_run(double drift_hz, int secs, int64_t phase_ns)
{
const double period_ms = 4096 * 1000.0 / 48000, grid_ms = 1000.0 / 24;
const double reserve_ms = 60, freq = 44100;
DSoundTrim t;
TrimRun r = { .least_ms = 1e9 };
double margin = reserve_ms, now = 0, next_read = 10;
int64_t k = 0;
dsound_trim_init(&t, 44100);
dsound_trim_restart(&t);
while (now < secs * 1000.0) {
/* Post k, on the first line of the grid past its audio's place. */
double post = (int64_t)((k * period_ms + phase_ns / 1e6) / grid_ms + 1)
* grid_ms;
double at = MIN(post, next_read);
bool is_post = post <= next_read;
margin -= (at - now) * (freq + drift_hz + t.offset_hz) / freq;
now = at;
if (!k) {
/* Until audio comes, the write position keeps its place. */
margin = reserve_ms;
dsound_trim_restart(&t);
} else if (margin < 0) {
r.gaps++;
dsound_trim_gap(&t);
margin = reserve_ms;
} else {
dsound_trim_read(&t, (int64_t)(now * 1e6),
(int64_t)(margin * 1000));
}
if (now >= secs * 500.0) {
r.least_ms = MIN(r.least_ms, margin);
}
if (is_post) {
margin += period_ms;
k++;
} else {
next_read += 10;
}
}
r.offset_hz = t.offset_hz;
return r;
}
/*
* The reserve's rest is trimmed: from 60 ms past the write cursor, the margin
* comes down to about what is kept at its least, with no gap, and the offset
* back to the drift's alone, whatever the grid's phase at the start.
*/
static void test_trim_level(void)
{
int64_t phase;
for (phase = 0; phase < 41666666; phase += 8333333) {
TrimRun r = trim_run(0, 600, phase);
g_assert_cmpuint(r.gaps, ==, 0);
g_assert_cmpfloat(r.least_ms, >=, DSOUND_TRIM_KEEP_US / 1000.0 - 3);
g_assert_cmpfloat(r.least_ms, <=, DSOUND_TRIM_KEEP_US / 1000.0 + 3);
g_assert_cmpint(r.offset_hz, >=, -1);
g_assert_cmpint(r.offset_hz, <=, 1);
}
}
/*
* A device that plays 10 Hz (227 ppm) fast or slow: no gap where it is
* fast, no fill that grows where it is slow, and an offset that matches it.
* Without the trim, a fast device eats the reserve's margin in minutes.
*/
static void test_trim_drift(void)
{
int drift;
for (drift = -10; drift <= 10; drift += 20) {
TrimRun r = trim_run(drift, 1200, 20833333);
g_assert_cmpuint(r.gaps, ==, 0);
g_assert_cmpfloat(r.least_ms, >=, DSOUND_TRIM_KEEP_US / 1000.0 - 5);
g_assert_cmpfloat(r.least_ms, <=, DSOUND_TRIM_KEEP_US / 1000.0 + 5);
g_assert_cmpint(r.offset_hz, >=, -drift - 2);
g_assert_cmpint(r.offset_hz, <=, -drift + 2);
}
}
/*
* The drift is the slope of the buckets' least margins, with what the offset
* played out added back: margins that fall 2268 us a minute against a
* 44100 Hz voice are a device 0.84 Hz fast, whatever the offset was.
*/
static void test_trim_slope(void)
{
DSoundTrim t;
int64_t ns;
dsound_trim_init(&t, 44100);
dsound_trim_restart(&t);
for (ns = 0; ns <= 70 * 1000000000LL; ns += 10000000) {
/* 37.8 us a second: the margin falls, its offset playing out none. */
dsound_trim_read(&t, ns, 40000 - ns / 1000 * 378 / 10000000 -
t.played_hz_ns / 44100000);
}
g_assert_cmpint(t.drift_mhz, >=, 1667 - 50);
g_assert_cmpint(t.drift_mhz, <=, 1667 + 50);
}
/*
* The offset is 1 Hz for each millisecond the level stands from the margin
* kept, within 1000 ppm of the voice's frequency.
*/
static void test_trim_clamp(void)
{
DSoundTrim t;
int64_t ns;
dsound_trim_init(&t, 44100);
dsound_trim_restart(&t);
for (ns = 0; ns <= 10 * 1000000000LL; ns += 10000000) {
dsound_trim_read(&t, ns, 500000);
}
g_assert_cmpint(t.offset_hz, ==, 44);
dsound_trim_init(&t, 48000);
dsound_trim_restart(&t);
for (ns = 0; ns <= 10 * 1000000000LL; ns += 10000000) {
dsound_trim_read(&t, ns, 0);
}
g_assert_cmpint(t.offset_hz, ==, -15);
}
/*
* A gap keeps 10 ms more, up to 45 ms, and starts the buckets again; the
* drift stays, and the offset is the drift's alone until the level is known.
*/
static void test_trim_gap(void)
{
DSoundTrim t;
dsound_trim_init(&t, 44100);
t.drift_mhz = 7400;
dsound_trim_gap(&t);
g_assert_cmpint(t.keep_us, ==, 25000);
g_assert_cmpuint(t.buckets, ==, 0);
g_assert_cmpint(t.offset_hz, ==, -7);
dsound_trim_gap(&t);
dsound_trim_gap(&t);
dsound_trim_gap(&t);
g_assert_cmpint(t.keep_us, ==, 45000);
g_assert_cmpint(t.drift_mhz, ==, 7400);
}
int main(int argc, char **argv)
{
g_test_init(&argc, &argv, NULL);
@@ -63,5 +233,10 @@ int main(int argc, char **argv)
g_test_add_func("/dsound-ring/reserve", test_reserve);
g_test_add_func("/dsound-ring/cursor_frames", test_cursor_frames);
g_test_add_func("/dsound-ring/filled_after", test_filled_after);
g_test_add_func("/dsound-ring/trim_level", test_trim_level);
g_test_add_func("/dsound-ring/trim_drift", test_trim_drift);
g_test_add_func("/dsound-ring/trim_slope", test_trim_slope);
g_test_add_func("/dsound-ring/trim_clamp", test_trim_clamp);
g_test_add_func("/dsound-ring/trim_gap", test_trim_gap);
return g_test_run();
}
+66
View File
@@ -0,0 +1,66 @@
/*
* reims-graphics-pci: where a window's pointer goes on the guest's tablet
* (hw/display/reims-pointer.h).
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "qemu/osdep.h"
#include "qemu/host-utils.h"
#include "hw/display/reims-pointer.h"
/* The tablet's value for @at, as QEMU's input layer scales it. */
static uint64_t tablet(uint16_t at, uint16_t size)
{
return muldiv64(reims_pointer_axis(at, size), 0x7fff, MAX(size, 1));
}
static void test_each_pixel_but_the_last_goes_as_itself(void)
{
g_assert_cmpuint(reims_pointer_axis(0, 2016), ==, 0);
g_assert_cmpuint(reims_pointer_axis(1, 2016), ==, 1);
g_assert_cmpuint(reims_pointer_axis(1007, 2016), ==, 1007);
g_assert_cmpuint(reims_pointer_axis(2014, 2016), ==, 2014);
g_assert_cmpuint(tablet(0, 2016), ==, 0);
g_assert_cmpuint(tablet(2014, 2016), ==, 0x7fde);
}
static void test_the_last_pixel_goes_as_the_tablet_s_maximum(void)
{
g_assert_cmpuint(reims_pointer_axis(2015, 2016), ==, 2016);
g_assert_cmpuint(reims_pointer_axis(1259, 1260), ==, 1260);
g_assert_cmpuint(tablet(2015, 2016), ==, 0x7fff);
g_assert_cmpuint(tablet(1259, 1260), ==, 0x7fff);
/* What it went as before: 0x7fee and 0x7fe4, short of the last pixel. */
g_assert_cmpuint(muldiv64(2015, 0x7fff, 2016), ==, 0x7fee);
g_assert_cmpuint(muldiv64(1259, 0x7fff, 1260), ==, 0x7fe4);
}
static void test_past_the_last_pixel_holds_at_it(void)
{
g_assert_cmpuint(reims_pointer_axis(2016, 2016), ==, 2016);
g_assert_cmpuint(reims_pointer_axis(65535, 2016), ==, 2016);
g_assert_cmpuint(reims_pointer_axis(65535, 65535), ==, 65535);
g_assert_cmpuint(tablet(65535, 2016), ==, 0x7fff);
}
static void test_a_display_of_one_pixel_has_its_first_alone(void)
{
g_assert_cmpuint(reims_pointer_axis(0, 1), ==, 0);
g_assert_cmpuint(reims_pointer_axis(10, 1), ==, 0);
g_assert_cmpuint(reims_pointer_axis(10, 0), ==, 0);
g_assert_cmpuint(tablet(10, 1), ==, 0);
}
int main(int argc, char **argv)
{
g_test_init(&argc, &argv, NULL);
g_test_add_func("/reims-pointer/pixels",
test_each_pixel_but_the_last_goes_as_itself);
g_test_add_func("/reims-pointer/last-pixel",
test_the_last_pixel_goes_as_the_tablet_s_maximum);
g_test_add_func("/reims-pointer/past-the-last-pixel",
test_past_the_last_pixel_holds_at_it);
g_test_add_func("/reims-pointer/one-pixel",
test_a_display_of_one_pixel_has_its_first_alone);
return g_test_run();
}
+333
View File
@@ -0,0 +1,333 @@
/*
* WHPX's fast path for aligned 32-bit MMIO stores
* (target/i386/whpx/whpx-mmio.h): its decoder of a MOV store and its check
* of the store's address, which whpx-all.c builds with on Windows alone,
* held on any host.
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "qemu/osdep.h"
#include "target/i386/whpx/whpx-mmio.h"
typedef struct DecodeCase {
const char *insn;
uint8_t bytes[17];
unsigned int available;
unsigned int exit_len;
bool decodes;
WhpxMovStore32 want;
} DecodeCase;
#define RAX 0
#define RCX 1
#define RSP 4
#define RBP 5
#define RDI 7
#define R9 9
#define R12 12
#define R13 13
#define R15 15
/*
* The stores the fast path takes: MOV r/m32, r32 (0x89) and MOV r/m32, imm32
* (0xc7 /0) in 64-bit mode, with a REX prefix or none, to memory through a
* base, a SIB or RIP. A field that does not apply (the base without one, the
* index and scale without one, the value of a register's store) is not
* compared.
*/
static const DecodeCase stores[] = {
{ "mov [rdi], eax", { 0x89, 0x07 }, 2, 2, true,
{ .len = 2, .reg = RAX, .has_base = true, .base_reg = RDI } },
{ "mov [rdi+0x10], eax", { 0x89, 0x47, 0x10 }, 3, 3, true,
{ .len = 3, .reg = RAX, .has_base = true, .base_reg = RDI,
.disp = 0x10 } },
{ "mov [rdi-0x10], eax", { 0x89, 0x47, 0xf0 }, 3, 3, true,
{ .len = 3, .reg = RAX, .has_base = true, .base_reg = RDI,
.disp = -0x10 } },
{ "mov [rdi+0x100], eax", { 0x89, 0x87, 0x00, 0x01, 0x00, 0x00 }, 6, 6,
true,
{ .len = 6, .reg = RAX, .has_base = true, .base_reg = RDI,
.disp = 0x100 } },
{ "mov [rdi-0x80000000], eax", { 0x89, 0x87, 0x00, 0x00, 0x00, 0x80 },
6, 6, true,
{ .len = 6, .reg = RAX, .has_base = true, .base_reg = RDI,
.disp = INT32_MIN } },
/* A REX prefix with no bits set changes nothing. */
{ "rex mov [rdi], eax", { 0x40, 0x89, 0x07 }, 3, 3, true,
{ .len = 3, .reg = RAX, .has_base = true, .base_reg = RDI } },
/* REX.R: the source is r8d to r15d. */
{ "mov [rdi], r15d", { 0x44, 0x89, 0x3f }, 3, 3, true,
{ .len = 3, .reg = R15, .has_base = true, .base_reg = RDI } },
/* rm 4 is a SIB; base 4 with no index is rsp, with REX.B r12. */
{ "mov [rsp], eax", { 0x89, 0x04, 0x24 }, 3, 3, true,
{ .len = 3, .reg = RAX, .has_base = true, .base_reg = RSP } },
{ "mov [r12], eax", { 0x41, 0x89, 0x04, 0x24 }, 4, 4, true,
{ .len = 4, .reg = RAX, .has_base = true, .base_reg = R12 } },
{ "mov [r12+8], r15d", { 0x45, 0x89, 0x7c, 0x24, 0x08 }, 5, 5, true,
{ .len = 5, .reg = R15, .has_base = true, .base_reg = R12,
.disp = 8 } },
/* A SIB whose index is 4 has no index, whatever its scale. */
{ "mov [rax], eax (sib)", { 0x89, 0x04, 0x20 }, 3, 3, true,
{ .len = 3, .reg = RAX, .has_base = true, .base_reg = RAX } },
{ "mov [rax], eax (sib, scale 2)", { 0x89, 0x04, 0x60 }, 3, 3, true,
{ .len = 3, .reg = RAX, .has_base = true, .base_reg = RAX } },
/* With REX.X, index 4 is r12. */
{ "mov [rax+r12*4], eax", { 0x42, 0x89, 0x04, 0xa0 }, 4, 4, true,
{ .len = 4, .reg = RAX, .has_base = true, .base_reg = RAX,
.has_index = true, .index_reg = R12, .scale = 4 } },
{ "mov [r13+r9*4+0x10], eax", { 0x43, 0x89, 0x44, 0x8d, 0x10 }, 5, 5,
true,
{ .len = 5, .reg = RAX, .has_base = true, .base_reg = R13,
.has_index = true, .index_reg = R9, .scale = 4, .disp = 0x10 } },
{ "mov [rax+rcx*8], eax", { 0x89, 0x04, 0xc8 }, 3, 3, true,
{ .len = 3, .reg = RAX, .has_base = true, .base_reg = RAX,
.has_index = true, .index_reg = RCX, .scale = 8 } },
/* rm 5 with mod 1 or 2 is rbp, with REX.B r13, and a displacement. */
{ "mov [rbp+0], eax", { 0x89, 0x45, 0x00 }, 3, 3, true,
{ .len = 3, .reg = RAX, .has_base = true, .base_reg = RBP } },
{ "mov [r13+0], eax", { 0x41, 0x89, 0x45, 0x00 }, 4, 4, true,
{ .len = 4, .reg = RAX, .has_base = true, .base_reg = R13 } },
/* rm 5 with mod 0 is RIP-relative, with REX.B too. */
{ "mov [rip+0x12345678], eax", { 0x89, 0x05, 0x78, 0x56, 0x34, 0x12 },
6, 6, true,
{ .len = 6, .reg = RAX, .rip_relative = true, .disp = 0x12345678 } },
{ "rex.b mov [rip-4], eax", { 0x41, 0x89, 0x05, 0xfc, 0xff, 0xff, 0xff },
7, 7, true,
{ .len = 7, .reg = RAX, .rip_relative = true, .disp = -4 } },
/* A SIB's base 5 with mod 0 is a disp32 alone, not RIP-relative. */
{ "mov [0x1000], eax", { 0x89, 0x04, 0x25, 0x00, 0x10, 0x00, 0x00 }, 7, 7,
true,
{ .len = 7, .reg = RAX, .disp = 0x1000 } },
{ "mov [rcx*4+0x1000], eax", { 0x89, 0x04, 0x8d, 0x00, 0x10, 0x00, 0x00 },
7, 7, true,
{ .len = 7, .reg = RAX, .has_index = true, .index_reg = RCX,
.scale = 4, .disp = 0x1000 } },
{ "rex.b mov [0x1000], eax",
{ 0x41, 0x89, 0x04, 0x25, 0x00, 0x10, 0x00, 0x00 }, 8, 8, true,
{ .len = 8, .reg = RAX, .disp = 0x1000 } },
/* The immediate's form, C7 /0, with its value after the address. */
{ "mov dword [rdi], 0x12345678",
{ 0xc7, 0x07, 0x78, 0x56, 0x34, 0x12 }, 6, 6, true,
{ .len = 6, .immediate = true, .value = 0x12345678, .has_base = true,
.base_reg = RDI } },
{ "mov dword [rdi+8], 1",
{ 0xc7, 0x47, 0x08, 0x01, 0x00, 0x00, 0x00 }, 7, 7, true,
{ .len = 7, .immediate = true, .value = 1, .has_base = true,
.base_reg = RDI, .disp = 8 } },
{ "mov dword [r12+0x200], 0xdeadbeef",
{ 0x41, 0xc7, 0x84, 0x24, 0x00, 0x02, 0x00, 0x00,
0xef, 0xbe, 0xad, 0xde }, 12, 12, true,
{ .len = 12, .immediate = true, .value = 0xdeadbeef, .has_base = true,
.base_reg = R12, .disp = 0x200 } },
{ "mov dword [rip+0x10], 42",
{ 0xc7, 0x05, 0x10, 0x00, 0x00, 0x00, 0x2a, 0x00, 0x00, 0x00 }, 10, 10,
true,
{ .len = 10, .immediate = true, .value = 42, .rip_relative = true,
.disp = 0x10 } },
{ "mov dword [0xfffffffffee00000], 0",
{ 0xc7, 0x04, 0x25, 0x00, 0x00, 0xe0, 0xfe, 0x00, 0x00, 0x00, 0x00 },
11, 11, true,
{ .len = 11, .immediate = true, .value = 0,
.disp = (int32_t)0xfee00000 } },
/* An exit length of 0 takes the decoded length; bytes past it are left. */
{ "mov [rdi], eax; nop; nop", { 0x89, 0x07, 0x90, 0x90 }, 4, 0, true,
{ .len = 2, .reg = RAX, .has_base = true, .base_reg = RDI } },
{ "mov [rdi], eax; nop; nop (exit length 2)", { 0x89, 0x07, 0x90, 0x90 },
4, 2, true,
{ .len = 2, .reg = RAX, .has_base = true, .base_reg = RDI } },
};
/* What the fast path leaves to the emulator: every other instruction. */
static const DecodeCase refused[] = {
/* 64-bit stores (REX.W), register destinations, C7 with reg 1. */
{ "mov [rdi], rax", { 0x48, 0x89, 0x07 }, 3, 3 },
{ "mov qword [rdi], 1", { 0x48, 0xc7, 0x07, 0x01, 0x00, 0x00, 0x00 },
7, 7 },
{ "mov eax, eax", { 0x89, 0xc0 }, 2, 2 },
{ "mov eax, 1", { 0xc7, 0xc0, 0x01, 0x00, 0x00, 0x00 }, 6, 6 },
{ "c7 /1", { 0xc7, 0x4f, 0x08, 0x01, 0x00, 0x00, 0x00 }, 7, 7 },
/* Other opcodes: loads, other widths, vector stores. */
{ "mov byte [rdi], al", { 0x88, 0x07 }, 2, 2 },
{ "mov byte [rdi], 1", { 0xc6, 0x07, 0x01 }, 3, 3 },
{ "mov eax, [rdi]", { 0x8b, 0x07 }, 2, 2 },
{ "movups [rdi], xmm0", { 0x0f, 0x11, 0x07 }, 3, 3 },
{ "movnti [rdi], eax", { 0x0f, 0xc3, 0x07 }, 3, 3 },
/* Any legacy prefix: operand and address size, a segment, lock, rep. */
{ "mov word [rdi], ax", { 0x66, 0x89, 0x07 }, 3, 3 },
{ "mov [edi], eax", { 0x67, 0x89, 0x07 }, 3, 3 },
{ "mov gs:[rdi], eax", { 0x65, 0x89, 0x07 }, 3, 3 },
{ "mov fs:[rdi], eax", { 0x64, 0x89, 0x07 }, 3, 3 },
{ "lock prefix", { 0xf0, 0x89, 0x07 }, 3, 3 },
{ "rep prefix", { 0xf3, 0x89, 0x07 }, 3, 3 },
{ "prefix after rex", { 0x41, 0x66, 0x89, 0x07 }, 4, 4 },
{ "two rex prefixes", { 0x41, 0x41, 0x89, 0x07 }, 4, 4 },
/* Bytes short of the instruction. */
{ "nothing", { 0 }, 0, 0 },
{ "opcode alone", { 0x89 }, 1, 0 },
{ "rex and opcode", { 0x41, 0x89 }, 2, 0 },
{ "no sib", { 0x89, 0x04 }, 2, 0 },
{ "rex, no sib", { 0x41, 0x89, 0x04 }, 3, 0 },
{ "no disp8", { 0x89, 0x47 }, 2, 0 },
{ "short disp32", { 0x89, 0x87, 0x00, 0x01, 0x00 }, 5, 0 },
{ "short rip disp32", { 0x89, 0x05, 0x00, 0x00, 0x00 }, 5, 0 },
{ "short imm32", { 0xc7, 0x07, 0x78, 0x56, 0x34 }, 5, 0 },
{ "short imm32 after disp8", { 0xc7, 0x47, 0x08, 0x01, 0x00, 0x00 }, 6, 0 },
/* More bytes than an instruction has. */
{ "17 bytes", { 0x89, 0x07 }, 17, 0 },
/* An exit length other than the decoded one. */
{ "exit length 3 for 2", { 0x89, 0x07, 0x90 }, 3, 3 },
{ "exit length 2 for 3", { 0x89, 0x47, 0x10 }, 3, 2 },
{ "exit length 6 for 10",
{ 0xc7, 0x05, 0x10, 0x00, 0x00, 0x00, 0x2a, 0x00, 0x00, 0x00 }, 10, 6 },
};
static void check_store(const DecodeCase *c, const WhpxMovStore32 *got)
{
const WhpxMovStore32 *want = &c->want;
g_assert_cmpuint(got->len, ==, want->len);
g_assert_cmpint(got->immediate, ==, want->immediate);
if (want->immediate) {
g_assert_cmpuint(got->value, ==, want->value);
} else {
g_assert_cmpuint(got->reg, ==, want->reg);
}
g_assert_cmpint(got->rip_relative, ==, want->rip_relative);
g_assert_cmpint(got->has_base, ==, want->has_base);
if (want->has_base) {
g_assert_cmpuint(got->base_reg, ==, want->base_reg);
}
g_assert_cmpint(got->has_index, ==, want->has_index);
if (want->has_index) {
g_assert_cmpuint(got->index_reg, ==, want->index_reg);
g_assert_cmpuint(got->scale, ==, want->scale);
}
g_assert_cmpint(got->disp, ==, want->disp);
}
static void test_decode_stores(void)
{
for (size_t i = 0; i < ARRAY_SIZE(stores); i++) {
const DecodeCase *c = &stores[i];
WhpxMovStore32 got;
g_test_message("%s", c->insn);
g_assert_true(whpx_decode_mov_store32(c->bytes, c->available,
c->exit_len, &got));
check_store(c, &got);
}
}
static void test_decode_refused(void)
{
for (size_t i = 0; i < ARRAY_SIZE(refused); i++) {
const DecodeCase *c = &refused[i];
WhpxMovStore32 got;
g_test_message("%s", c->insn);
g_assert_false(whpx_decode_mov_store32(c->bytes, c->available,
c->exit_len, &got));
}
}
/*
* The store's effective address: the base, plus the index times the scale,
* plus the sign-extended displacement, in 64 bits; RIP-relative from the
* next instruction's RIP.
*/
static void test_effective_address(void)
{
WhpxMovStore32 store = { .len = 3, .has_base = true, .scale = 1,
.disp = -0x10 };
g_assert_cmpuint(whpx_mov_store32_ea(&store, 0, 0x1000, 0), ==, 0xff0);
store.disp = -0x20;
g_assert_cmpuint(whpx_mov_store32_ea(&store, 0, 0x10, 0), ==,
0xfffffffffffffff0ULL);
store = (WhpxMovStore32) { .len = 5, .has_base = true, .has_index = true,
.scale = 8, .disp = 4 };
g_assert_cmpuint(whpx_mov_store32_ea(&store, 0, 0x1000, 3), ==, 0x101c);
store = (WhpxMovStore32) { .len = 6, .rip_relative = true, .scale = 1,
.disp = 0x10 };
g_assert_cmpuint(whpx_mov_store32_ea(&store, 0xfffff80000001000ULL, 0, 0),
==, 0xfffff80000001016ULL);
store.disp = -0x100;
g_assert_cmpuint(whpx_mov_store32_ea(&store, 0x1000, 0, 0), ==, 0xf06);
/* A disp32 alone, which the caller passes no base or index for. */
store = (WhpxMovStore32) { .len = 11, .scale = 1,
.disp = (int32_t)0xfee00000 };
g_assert_cmpuint(whpx_mov_store32_ea(&store, 0x1000, 0, 0), ==,
0xfffffffffee00000ULL);
}
/*
* The address check: the decoded address is the exit's guest virtual
* address, 4-aligned (so in one page), and in the same place in its page as
* the guest physical address.
*/
static void test_address_valid(void)
{
const uint64_t gva = 0xffffff8012341010ULL;
g_assert_true(whpx_mmio_write32_address_valid(0xfebf1010, gva, gva));
/* The last dword of a page. */
g_assert_true(whpx_mmio_write32_address_valid(0xfebf1ffc,
0xffffff8012341ffcULL,
0xffffff8012341ffcULL));
/* Not the exit's address: a segment base, or bytes of another insn. */
g_assert_false(whpx_mmio_write32_address_valid(0xfebf1010, gva, gva + 4));
g_assert_false(whpx_mmio_write32_address_valid(0xfebf1010, gva,
gva + 0x1000));
/* Unaligned, and so for 0xffd to 0xfff across the page's end. */
for (unsigned int off = 1; off < 4; off++) {
g_assert_false(whpx_mmio_write32_address_valid(0xfebf1010 + off,
gva + off, gva + off));
g_assert_false(whpx_mmio_write32_address_valid(
0xfebf1ffc + off, 0xffffff8012341ffcULL + off,
0xffffff8012341ffcULL + off));
}
/* The guest physical address elsewhere in its page. */
g_assert_false(whpx_mmio_write32_address_valid(0xfebf1020, gva, gva));
g_assert_false(whpx_mmio_write32_address_valid(0xfebf1014, gva, gva));
}
/*
* The three together, as the fast path runs them on an exit: a doorbell's
* MOV [rdi+0x10], eax at RDI 0xffffff8012340ff0 is taken; the same store
* 2 bytes lower, across the page's end, is not.
*/
static void test_doorbell_store(void)
{
static const uint8_t mov[] = { 0x89, 0x47, 0x10 };
static const uint8_t mov_across[] = { 0x89, 0x47, 0x0e };
const uint64_t rdi = 0xffffff8012340ff0ULL;
WhpxMovStore32 store;
uint64_t ea;
g_assert_true(whpx_decode_mov_store32(mov, sizeof(mov), sizeof(mov),
&store));
ea = whpx_mov_store32_ea(&store, 0x1000, rdi, 0);
g_assert_cmpuint(ea, ==, 0xffffff8012341000ULL);
g_assert_true(whpx_mmio_write32_address_valid(0xfebf1000, ea, ea));
g_assert_true(whpx_decode_mov_store32(mov_across, sizeof(mov_across),
sizeof(mov_across), &store));
ea = whpx_mov_store32_ea(&store, 0x1000, rdi, 0);
g_assert_cmpuint(ea, ==, 0xffffff8012340ffeULL);
g_assert_false(whpx_mmio_write32_address_valid(0xfebf0ffe, ea, ea));
}
int main(int argc, char **argv)
{
g_test_init(&argc, &argv, NULL);
g_test_add_func("/whpx-mmio/decode/stores", test_decode_stores);
g_test_add_func("/whpx-mmio/decode/refused", test_decode_refused);
g_test_add_func("/whpx-mmio/effective-address", test_effective_address);
g_test_add_func("/whpx-mmio/address-valid", test_address_valid);
g_test_add_func("/whpx-mmio/doorbell-store", test_doorbell_store);
return g_test_run();
}
+94
View File
@@ -0,0 +1,94 @@
#include "qemu/osdep.h"
#include "qemu/win32-fdset.h"
/*
* Exercise raw Winsock SOCKET handles directly (matching libslirp's
* slirp_os_socket), bypassing os-win32.h's POSIX/CRT fd wrapper macros.
*/
#undef socket
#undef bind
#undef getsockname
#undef sendto
#undef recv
static void test_duplicate_and_empty(void)
{
QemuWin32FdSet *set = qemu_win32_fdset_new(2);
SOCKET first = (SOCKET)UINT64_C(0x100000041);
g_assert_cmpuint(set->fd_count, ==, 0);
g_assert_false(qemu_win32_fdset_contains(set, first));
qemu_win32_fdset_add(set, first);
qemu_win32_fdset_add(set, first);
qemu_win32_fdset_add(set, first + 1);
g_assert_cmpuint(set->fd_count, ==, 2);
g_assert_true(qemu_win32_fdset_contains(set, first));
g_assert_true(qemu_win32_fdset_contains(set, first + 1));
g_free(set);
}
static void test_many_ready_sockets(gconstpointer opaque)
{
guint count = GPOINTER_TO_UINT(opaque);
SOCKET *receivers = g_new(SOCKET, count);
QemuWin32FdSet *set = qemu_win32_fdset_new(count);
struct timeval timeout = { .tv_sec = 5 };
SOCKET sender = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
char value = 'x';
int ready;
g_assert_true(sender != INVALID_SOCKET);
for (guint i = 0; i < count; i++) {
struct sockaddr_in addr = {
.sin_family = AF_INET,
.sin_addr.s_addr = htonl(INADDR_LOOPBACK),
};
int length = sizeof(addr);
receivers[i] = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
g_assert_true(receivers[i] != INVALID_SOCKET);
g_assert_cmpint(bind(receivers[i], (struct sockaddr *)&addr,
sizeof(addr)), ==, 0);
g_assert_cmpint(getsockname(receivers[i], (struct sockaddr *)&addr,
&length), ==, 0);
g_assert_cmpint(sendto(sender, &value, 1, 0,
(struct sockaddr *)&addr, length), ==, 1);
qemu_win32_fdset_add(set, receivers[i]);
qemu_win32_fdset_add(set, receivers[i]);
}
g_assert_cmpuint(set->fd_count, ==, count);
ready = select(0, qemu_win32_fdset_native(set), NULL, NULL, &timeout);
g_assert_cmpint(ready, ==, count);
for (guint i = 0; i < count; i++) {
g_assert_true(qemu_win32_fdset_contains(set, receivers[i]));
g_assert_cmpint(recv(receivers[i], &value, 1, 0), ==, 1);
closesocket(receivers[i]);
}
closesocket(sender);
g_free(receivers);
g_free(set);
}
int main(int argc, char **argv)
{
WSADATA data;
int result;
g_assert_cmpint(WSAStartup(MAKEWORD(2, 2), &data), ==, 0);
g_test_init(&argc, &argv, NULL);
g_test_add_func("/win32-fdset/duplicate-empty", test_duplicate_and_empty);
g_test_add_data_func("/win32-fdset/63", GUINT_TO_POINTER(63),
test_many_ready_sockets);
g_test_add_data_func("/win32-fdset/64", GUINT_TO_POINTER(64),
test_many_ready_sockets);
g_test_add_data_func("/win32-fdset/65", GUINT_TO_POINTER(65),
test_many_ready_sockets);
g_test_add_data_func("/win32-fdset/128", GUINT_TO_POINTER(128),
test_many_ready_sockets);
g_test_add_data_func("/win32-fdset/1024", GUINT_TO_POINTER(1024),
test_many_ready_sockets);
result = g_test_run();
WSACleanup();
return result;
}
+363 -52
View File
@@ -22,20 +22,35 @@
#include "qemu/queue.h"
#include "qemu/sockets.h"
#include "qapi/error.h"
#include "qemu/rcu.h"
#include "qemu/rcu_queue.h"
#include "qemu/error-report.h"
#include "system/iothread.h"
struct AioHandler {
EventNotifier *e;
IOHandler *io_read;
IOHandler *io_write;
EventNotifierHandler *io_notify;
AioPollFn *io_poll;
EventNotifierHandler *io_poll_ready;
EventNotifierHandler *io_poll_begin;
EventNotifierHandler *io_poll_end;
GPollFD pfd;
int deleted;
bool poll_ready;
void *opaque;
AioPolledEvent poll;
int64_t last_dispatch_timestamp;
QLIST_ENTRY(AioHandler) node;
QLIST_ENTRY(AioHandler) node_poll;
};
bool aio_poll_disabled(AioContext *ctx)
{
return qatomic_read(&ctx->poll_disable_cnt);
}
static void aio_remove_fd_handler(AioContext *ctx, AioHandler *node)
{
/*
@@ -58,6 +73,7 @@ static void aio_remove_fd_handler(AioContext *ctx, AioHandler *node)
* releasing the list_lock.
*/
QLIST_REMOVE(node, node);
QLIST_SAFE_REMOVE(node, node_poll);
g_free(node);
}
}
@@ -73,6 +89,7 @@ void aio_set_fd_handler(AioContext *ctx,
AioHandler *old_node;
AioHandler *node = NULL;
SOCKET s;
int poll_disable_change = 0;
if (!fd_is_socket(fd)) {
error_report("fd=%d is not a socket, AIO implementation is missing", fd);
@@ -97,10 +114,10 @@ void aio_set_fd_handler(AioContext *ctx,
node->pfd.fd = s;
node->pfd.events = 0;
if (node->io_read) {
if (io_read) {
node->pfd.events |= G_IO_IN;
}
if (node->io_write) {
if (io_write) {
node->pfd.events |= G_IO_OUT;
}
@@ -120,8 +137,17 @@ void aio_set_fd_handler(AioContext *ctx,
}
QLIST_INSERT_HEAD_RCU(&ctx->aio_handlers, node, node);
if (!old_node) {
poll_disable_change = 1;
}
event = event_notifier_get_handle(&ctx->notifier);
qemu_socket_select_nofail(fd, event, bitmask);
} else if (old_node) {
poll_disable_change = -1;
}
if (poll_disable_change) {
qatomic_set(&ctx->poll_disable_cnt,
qatomic_read(&ctx->poll_disable_cnt) + poll_disable_change);
}
if (old_node) {
aio_remove_fd_handler(ctx, old_node);
@@ -138,10 +164,15 @@ void aio_set_event_notifier(AioContext *ctx,
EventNotifierHandler *io_poll_ready)
{
AioHandler *node;
int poll_disable_change = 0;
if (io_poll && !io_poll_ready) {
io_poll = NULL;
}
qemu_lockcnt_lock(&ctx->list_lock);
QLIST_FOREACH(node, &ctx->aio_handlers, node) {
if (node->e == e && !node->deleted) {
if (node->e == e && !node->io_read && !node->io_write && !node->deleted) {
break;
}
}
@@ -149,6 +180,7 @@ void aio_set_event_notifier(AioContext *ctx,
/* Are we deleting the fd handler? */
if (!io_notify) {
if (node) {
poll_disable_change = -!node->io_poll;
aio_remove_fd_handler(ctx, node);
}
} else {
@@ -161,9 +193,30 @@ void aio_set_event_notifier(AioContext *ctx,
QLIST_INSERT_HEAD_RCU(&ctx->aio_handlers, node, node);
g_source_add_poll(&ctx->source, &node->pfd);
if (!io_poll) {
poll_disable_change = 1;
} else {
QLIST_INSERT_HEAD(&ctx->poll_aio_handlers, node, node_poll);
}
} else {
bool had_poll = node->io_poll != NULL;
bool has_poll = io_poll != NULL;
poll_disable_change = !has_poll - !had_poll;
if (has_poll && !had_poll) {
QLIST_INSERT_HEAD(&ctx->poll_aio_handlers, node, node_poll);
} else if (!has_poll && had_poll) {
QLIST_SAFE_REMOVE(node, node_poll);
}
}
/* Update handler with latest information */
node->io_notify = io_notify;
node->io_poll = io_poll;
node->io_poll_ready = io_poll_ready;
}
if (poll_disable_change) {
qatomic_set(&ctx->poll_disable_cnt,
qatomic_read(&ctx->poll_disable_cnt) + poll_disable_change);
}
qemu_lockcnt_unlock(&ctx->list_lock);
@@ -175,53 +228,114 @@ void aio_set_event_notifier_poll(AioContext *ctx,
EventNotifierHandler *io_poll_begin,
EventNotifierHandler *io_poll_end)
{
/* Not implemented */
AioHandler *node;
qemu_lockcnt_lock(&ctx->list_lock);
QLIST_FOREACH(node, &ctx->aio_handlers, node) {
if (node->e == notifier && !node->io_read && !node->io_write &&
!node->deleted) {
node->io_poll_begin = io_poll_begin;
node->io_poll_end = io_poll_end;
break;
}
}
qemu_lockcnt_unlock(&ctx->list_lock);
}
bool aio_prepare(AioContext *ctx)
static bool win32_poll_set_started(AioContext *ctx, bool started)
{
AioHandler *node;
bool any_ready = false;
if (started == ctx->poll_started) {
return false;
}
ctx->poll_started = started;
QLIST_FOREACH(node, &ctx->poll_aio_handlers, node_poll) {
EventNotifierHandler *fn;
if (node->deleted) {
continue;
}
fn = started ? node->io_poll_begin : node->io_poll_end;
if (fn) {
fn(node->e);
}
if (!started && node->io_poll && node->io_poll(node->e)) {
node->poll_ready = true;
any_ready = true;
}
}
return any_ready;
}
/* Caller must hold ctx->list_lock. */
static bool aio_prepare_select(AioContext *ctx)
{
static struct timeval tv0;
AioHandler *node;
bool have_sockets = false;
bool have_select_revents = false;
fd_set rfds, wfds;
/*
* We have to walk very carefully in case aio_set_fd_handler is
* called while we're walking.
*/
qemu_lockcnt_inc(&ctx->list_lock);
/* fill fd sets */
FD_ZERO(&rfds);
FD_ZERO(&wfds);
/* Fill fd sets lazily so IOThreads without sockets skip Winsock select(). */
QLIST_FOREACH_RCU(node, &ctx->aio_handlers, node) {
if (node->io_read) {
FD_SET ((SOCKET)node->pfd.fd, &rfds);
if (node->deleted) {
continue;
}
if (node->io_write) {
FD_SET ((SOCKET)node->pfd.fd, &wfds);
if (node->io_read || node->io_write) {
if (!have_sockets) {
FD_ZERO(&rfds);
FD_ZERO(&wfds);
have_sockets = true;
}
if (node->io_read) {
FD_SET((SOCKET)node->pfd.fd, &rfds);
}
if (node->io_write) {
FD_SET((SOCKET)node->pfd.fd, &wfds);
}
}
}
if (select(0, &rfds, &wfds, NULL, &tv0) > 0) {
if (have_sockets && select(0, &rfds, &wfds, NULL, &tv0) > 0) {
QLIST_FOREACH_RCU(node, &ctx->aio_handlers, node) {
if (node->deleted || (!node->io_read && !node->io_write)) {
continue;
}
node->pfd.revents = 0;
if (FD_ISSET(node->pfd.fd, &rfds)) {
if (node->io_read && FD_ISSET(node->pfd.fd, &rfds)) {
node->pfd.revents |= G_IO_IN;
have_select_revents = true;
}
if (FD_ISSET(node->pfd.fd, &wfds)) {
if (node->io_write && FD_ISSET(node->pfd.fd, &wfds)) {
node->pfd.revents |= G_IO_OUT;
have_select_revents = true;
}
}
}
qemu_lockcnt_dec(&ctx->list_lock);
return have_select_revents;
}
bool aio_prepare(AioContext *ctx)
{
bool poll_ready;
bool select_ready;
/*
* We have to walk very carefully in case aio_set_fd_handler is
* called while we're walking.
*/
qemu_lockcnt_inc(&ctx->list_lock);
poll_ready = win32_poll_set_started(ctx, false);
select_ready = aio_prepare_select(ctx);
qemu_lockcnt_dec(&ctx->list_lock);
return poll_ready || select_ready;
}
bool aio_pending(AioContext *ctx)
{
AioHandler *node;
@@ -233,6 +347,10 @@ bool aio_pending(AioContext *ctx)
*/
qemu_lockcnt_inc(&ctx->list_lock);
QLIST_FOREACH_RCU(node, &ctx->aio_handlers, node) {
if (node->poll_ready && node->io_poll_ready) {
result = true;
break;
}
if (node->pfd.revents && node->io_notify) {
result = true;
break;
@@ -252,7 +370,8 @@ bool aio_pending(AioContext *ctx)
return result;
}
static bool aio_dispatch_handlers(AioContext *ctx, HANDLE event)
static bool aio_dispatch_handlers(AioContext *ctx, HANDLE event,
int64_t dispatch_ns)
{
AioHandler *node;
bool progress = false;
@@ -264,6 +383,30 @@ static bool aio_dispatch_handlers(AioContext *ctx, HANDLE event)
*/
QLIST_FOREACH_SAFE_RCU(node, &ctx->aio_handlers, node, tmp) {
int revents = node->pfd.revents;
bool poll_ready = node->poll_ready;
node->poll_ready = false;
if (!node->deleted && poll_ready && revents == 0 &&
event_notifier_get_handle(node->e) != event &&
node->io_poll_ready) {
/*
* Remove temporarily to avoid infinite loops if ->io_poll_ready()
* invokes nested aio_poll().
*/
QLIST_SAFE_REMOVE(node, node_poll);
node->io_poll_ready(node->e);
if (!node->deleted && node->io_poll &&
!QLIST_IS_INSERTED(node, node_poll)) {
QLIST_INSERT_HEAD(&ctx->poll_aio_handlers, node, node_poll);
}
if (ctx->poll_max_ns && QLIST_IS_INSERTED(node, node_poll)) {
node->last_dispatch_timestamp = dispatch_ns;
}
if (node->e != &ctx->notifier) {
progress = true;
}
}
if (!node->deleted &&
(revents || event_notifier_get_handle(node->e) == event) &&
@@ -271,6 +414,10 @@ static bool aio_dispatch_handlers(AioContext *ctx, HANDLE event)
node->pfd.revents = 0;
node->io_notify(node->e);
if (ctx->poll_max_ns && QLIST_IS_INSERTED(node, node_poll)) {
node->last_dispatch_timestamp = dispatch_ns;
}
/* aio_notify() does not count as progress */
if (node->e != &ctx->notifier) {
progress = true;
@@ -302,6 +449,7 @@ static bool aio_dispatch_handlers(AioContext *ctx, HANDLE event)
if (node->deleted) {
if (qemu_lockcnt_dec_if_lock(&ctx->list_lock)) {
QLIST_REMOVE(node, node);
QLIST_SAFE_REMOVE(node, node_poll);
g_free(node);
qemu_lockcnt_inc_and_unlock(&ctx->list_lock);
}
@@ -315,18 +463,134 @@ void aio_dispatch(AioContext *ctx)
{
qemu_lockcnt_inc(&ctx->list_lock);
aio_bh_poll(ctx);
aio_dispatch_handlers(ctx, INVALID_HANDLE_VALUE);
aio_dispatch_handlers(ctx, INVALID_HANDLE_VALUE, 0);
qemu_lockcnt_dec(&ctx->list_lock);
timerlistgroup_run_timers(&ctx->tlg);
}
static bool win32_run_poll_handlers_once(AioContext *ctx, int64_t *timeout_ns)
{
AioHandler *node;
AioHandler *tmp;
bool progress = false;
QLIST_FOREACH_SAFE(node, &ctx->poll_aio_handlers, node_poll, tmp) {
if (!node->deleted && node->io_poll && node->io_poll(node->e)) {
node->poll_ready = true;
*timeout_ns = 0;
if (node->e != &ctx->notifier) {
progress = true;
}
}
}
return progress;
}
static bool win32_try_poll_mode(AioContext *ctx, int64_t *timeout_ns)
{
int64_t max_ns;
int64_t start_time;
int64_t elapsed_time;
bool progress = false;
if (qatomic_read(&ctx->poll_disable_cnt) ||
QLIST_EMPTY(&ctx->poll_aio_handlers)) {
return false;
}
max_ns = qemu_soonest_timeout(*timeout_ns, ctx->poll_ns);
if (!max_ns) {
return false;
}
win32_poll_set_started(ctx, true);
RCU_READ_LOCK_GUARD();
start_time = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
do {
if (win32_run_poll_handlers_once(ctx, timeout_ns)) {
progress = true;
break;
}
elapsed_time = qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - start_time;
if (qatomic_read(&ctx->poll_disable_cnt)) {
break;
}
max_ns = qemu_soonest_timeout(*timeout_ns, max_ns);
} while (elapsed_time < max_ns);
if (!progress && *timeout_ns != -1) {
*timeout_ns -= MIN(*timeout_ns, elapsed_time);
}
return progress;
}
static void win32_adjust_polling_time(AioContext *ctx, int64_t block_ns)
{
if (block_ns > ctx->poll_ns) {
int64_t grow = ctx->poll_grow;
if (block_ns > ctx->poll_ns * grow) {
ctx->poll_ns = block_ns;
} else {
ctx->poll_ns *= grow;
}
if (ctx->poll_ns > ctx->poll_max_ns) {
ctx->poll_ns = ctx->poll_max_ns;
}
} else if (block_ns < (ctx->poll_ns / ctx->poll_shrink)) {
ctx->poll_ns /= ctx->poll_shrink;
}
}
static void win32_update_handler_poll_times(AioContext *ctx, int64_t block_ns,
int64_t dispatch_time)
{
AioHandler *node;
int64_t max_poll_ns = -1;
QLIST_FOREACH(node, &ctx->poll_aio_handlers, node_poll) {
if (node->deleted) {
continue;
}
if (node->last_dispatch_timestamp == dispatch_time) {
node->poll.ns = node->poll.ns
? (node->poll.ns - (node->poll.ns >> ctx->poll_weight))
+ (block_ns >> ctx->poll_weight) : block_ns;
if (node->poll.ns > ctx->poll_max_ns) {
node->poll.ns = 0;
}
max_poll_ns = MAX(max_poll_ns, node->poll.ns);
} else {
if (node->poll.ns != 0) {
node->poll.ns += block_ns;
if (node->poll.ns > ctx->poll_max_ns) {
node->poll.ns = 0;
}
}
}
}
if (max_poll_ns >= 0) {
win32_adjust_polling_time(ctx, max_poll_ns);
}
}
bool aio_poll(AioContext *ctx, bool blocking)
{
AioHandler *node;
HANDLE events[MAXIMUM_WAIT_OBJECTS];
bool progress, have_select_revents, first;
bool progress, have_select_revents, poll_hit, first;
bool use_notify_me;
unsigned count;
int timeout;
int64_t timeout_ns;
int64_t start = 0;
int64_t dispatch_ns = 0;
int64_t block_ns = 0;
/*
* There cannot be two concurrent aio_poll calls for the same AioContext (or
@@ -341,25 +605,52 @@ bool aio_poll(AioContext *ctx, bool blocking)
qemu_get_aio_context() : ctx));
progress = false;
/* aio_notify can avoid the expensive event_notifier_set if
* everything (file descriptors, bottom halves, timers) will
* be re-evaluated before the next blocking poll(). This is
* already true when aio_poll is called with blocking == false;
* if blocking == true, it is only true after poll() returns,
* so disable the optimization now.
*/
if (blocking) {
qemu_lockcnt_inc(&ctx->list_lock);
if (ctx->poll_max_ns) {
start = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
}
have_select_revents = aio_prepare_select(ctx);
timeout_ns = (blocking && !have_select_revents)
? aio_compute_timeout(ctx) : 0;
poll_hit = (ctx->poll_max_ns && timeout_ns != 0)
? win32_try_poll_mode(ctx, &timeout_ns) : false;
if (poll_hit && !qatomic_read(&ctx->poll_disable_cnt) &&
!have_select_revents) {
aio_notify_accept(ctx);
dispatch_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
block_ns = dispatch_ns - start;
progress |= aio_bh_poll(ctx);
progress |= aio_dispatch_handlers(ctx, INVALID_HANDLE_VALUE, dispatch_ns);
win32_update_handler_poll_times(ctx, block_ns, dispatch_ns);
qemu_lockcnt_dec(&ctx->list_lock);
progress |= timerlistgroup_run_timers(&ctx->tlg);
return progress;
}
/* Disable poll mode before entering WaitForMultipleObjects (and on non-blocking calls). */
if (ctx->poll_started && (timeout_ns != 0 || !blocking)) {
if (win32_poll_set_started(ctx, false)) {
timeout_ns = 0;
poll_hit = true;
}
}
use_notify_me = timeout_ns != 0;
if (use_notify_me) {
qatomic_set(&ctx->notify_me, qatomic_read(&ctx->notify_me) + 2);
/*
* Write ctx->notify_me before computing the timeout
* (reading bottom half flags, etc.). Pairs with
* Write ctx->notify_me before reading ctx->notified. Pairs with
* smp_mb in aio_notify().
*/
smp_mb();
}
qemu_lockcnt_inc(&ctx->list_lock);
have_select_revents = aio_prepare(ctx);
if (qatomic_read(&ctx->notified)) {
timeout_ns = 0;
}
}
/* fill fd sets */
count = 0;
@@ -382,20 +673,21 @@ bool aio_poll(AioContext *ctx, bool blocking)
do {
HANDLE event;
int ret;
int timeout_ms = (first && timeout_ns != 0 && !have_select_revents && !poll_hit)
? qemu_timeout_ns_to_ms(timeout_ns) : 0;
timeout = blocking && !have_select_revents
? qemu_timeout_ns_to_ms(aio_compute_timeout(ctx)) : 0;
ret = WaitForMultipleObjects(count, events, FALSE, timeout);
if (blocking) {
assert(first);
ret = WaitForMultipleObjects(count, events, FALSE, timeout_ms);
if (first && use_notify_me) {
qatomic_store_release(&ctx->notify_me,
qatomic_read(&ctx->notify_me) - 2);
aio_notify_accept(ctx);
}
if (first) {
aio_notify_accept(ctx);
if (ctx->poll_max_ns) {
dispatch_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
block_ns = dispatch_ns - start;
}
progress |= aio_bh_poll(ctx);
first = false;
}
/* if we have any signaled events, dispatch event */
@@ -403,16 +695,21 @@ bool aio_poll(AioContext *ctx, bool blocking)
if ((DWORD) (ret - WAIT_OBJECT_0) < count) {
event = events[ret - WAIT_OBJECT_0];
events[ret - WAIT_OBJECT_0] = events[--count];
} else if (!have_select_revents) {
} else if (!have_select_revents && !(first && poll_hit)) {
first = false;
break;
}
have_select_revents = false;
blocking = false;
first = false;
progress |= aio_dispatch_handlers(ctx, event);
progress |= aio_dispatch_handlers(ctx, event, dispatch_ns);
} while (count > 0);
if (ctx->poll_max_ns) {
win32_update_handler_poll_times(ctx, block_ns, dispatch_ns);
}
qemu_lockcnt_dec(&ctx->list_lock);
progress |= timerlistgroup_run_timers(&ctx->tlg);
@@ -432,11 +729,25 @@ void aio_context_set_poll_params(AioContext *ctx, int64_t max_ns,
int64_t grow, int64_t shrink,
int64_t weight, Error **errp)
{
if (max_ns) {
error_setg(errp, "AioContext polling is not implemented on Windows");
AioHandler *node;
qemu_lockcnt_inc(&ctx->list_lock);
QLIST_FOREACH(node, &ctx->aio_handlers, node) {
node->poll.ns = 0;
}
qemu_lockcnt_dec(&ctx->list_lock);
ctx->poll_max_ns = max_ns;
ctx->poll_grow = (grow ? grow : IOTHREAD_POLL_GROW_DEFAULT);
ctx->poll_shrink = (shrink ? shrink : IOTHREAD_POLL_SHRINK_DEFAULT);
ctx->poll_weight = (weight ? weight : IOTHREAD_POLL_WEIGHT_DEFAULT);
ctx->poll_ns = 0;
aio_notify(ctx);
}
void aio_context_set_aio_params(AioContext *ctx, int64_t max_batch)
{
ctx->aio_max_batch = max_batch;
aio_notify(ctx);
}
+10 -12
View File
@@ -23,6 +23,7 @@
*/
#include "qemu/osdep.h"
#include "qemu/error-report.h"
#include "qemu/coroutine_int.h"
#include "qemu/coroutine-tls.h"
@@ -79,18 +80,17 @@ Coroutine *qemu_coroutine_new(void)
co = g_malloc0(sizeof(*co));
/*
* CreateFiber(stack_size, ...) commits the full 1 MiB stack up front,
* which can exhaust Windows commit charge during burst disk I/O + GPU
* workloads and return NULL (later crashing inside SwitchToFiber(NULL)
* reading 0x10). Reserve stack_size while committing only 64 KiB upfront.
* The fiber's stack is reserved whole and committed 64 KiB at first, the
* rest as the stack grows into it. CreateFiber committed all 1 MiB of it
* for each coroutine, and with the host's commit charge used up it
* returned NULL, which SwitchToFiber then crashed on.
*/
co->fiber = CreateFiberEx(commit_size, stack_size, 0,
coroutine_trampoline, &co->base);
if (!co->fiber) {
fprintf(stderr,
"qemu_coroutine_new: CreateFiberEx(commit=%zu, reserve=%zu) failed: "
"GetLastError()=%lu\n",
commit_size, stack_size, (unsigned long)GetLastError());
error_report("CreateFiberEx of a %zu-byte stack, %zu bytes committed, "
"failed: error %lu", stack_size, commit_size,
(unsigned long)GetLastError());
abort();
}
return &co->base;
@@ -119,10 +119,8 @@ Coroutine *qemu_coroutine_self(void)
leader->fiber = ConvertThreadToFiber(NULL);
}
if (!leader->fiber) {
fprintf(stderr,
"qemu_coroutine_self: ConvertThreadToFiber failed: "
"GetLastError()=%lu\n",
(unsigned long)GetLastError());
error_report("ConvertThreadToFiber failed: error %lu",
(unsigned long)GetLastError());
abort();
}
}
+104 -40
View File
@@ -36,6 +36,10 @@
#include "qemu/queue.h"
#include "qom/object.h"
#ifdef _WIN32
#include "qemu/win32-fdset.h"
#endif
#ifndef _WIN32
#include <sys/wait.h>
#endif
@@ -188,7 +192,9 @@ void qemu_notify_event(void)
qemu_bh_schedule(qemu_notify_bh);
}
#ifndef _WIN32
static GArray *gpollfds;
#endif
int qemu_init_main_loop(Error **errp)
{
@@ -208,7 +214,9 @@ int qemu_init_main_loop(Error **errp)
}
qemu_set_current_aio_context(qemu_aio_context);
qemu_notify_bh = qemu_bh_new(notify_event_cb, NULL);
#ifndef _WIN32
gpollfds = g_array_new(FALSE, FALSE, sizeof(GPollFD));
#endif
src = aio_get_g_source(qemu_aio_context);
g_source_set_name(src, "aio-context");
g_source_attach(src, NULL);
@@ -281,9 +289,8 @@ static void main_loop_register_types(void)
type_init(main_loop_register_types)
static int max_priority;
#ifndef _WIN32
static int max_priority;
static int glib_pollfds_idx;
static int glib_n_poll_fds;
@@ -445,68 +452,105 @@ void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
}
}
static int pollfds_fill(GArray *pollfds, fd_set *rfds, fd_set *wfds,
fd_set *xfds)
static bool pollfds_fill(GArray *pollfds, QemuWin32FdSet *rfds,
QemuWin32FdSet *wfds, QemuWin32FdSet *xfds)
{
int nfds = -1;
bool have_sockets = false;
int i;
for (i = 0; i < pollfds->len; i++) {
GPollFD *pfd = &g_array_index(pollfds, GPollFD, i);
int fd = pfd->fd;
SOCKET fd = pfd->fd;
int events = pfd->events;
if (events & G_IO_IN) {
FD_SET(fd, rfds);
nfds = MAX(nfds, fd);
qemu_win32_fdset_add(rfds, fd);
have_sockets = true;
}
if (events & G_IO_OUT) {
FD_SET(fd, wfds);
nfds = MAX(nfds, fd);
qemu_win32_fdset_add(wfds, fd);
have_sockets = true;
}
if (events & G_IO_PRI) {
FD_SET(fd, xfds);
nfds = MAX(nfds, fd);
qemu_win32_fdset_add(xfds, fd);
have_sockets = true;
}
}
return nfds;
return have_sockets;
}
static void pollfds_poll(GArray *pollfds, int nfds, fd_set *rfds,
fd_set *wfds, fd_set *xfds)
static void pollfds_poll(GArray *pollfds, QemuWin32FdSet *rfds,
QemuWin32FdSet *wfds, QemuWin32FdSet *xfds)
{
int i;
for (i = 0; i < pollfds->len; i++) {
GPollFD *pfd = &g_array_index(pollfds, GPollFD, i);
int fd = pfd->fd;
SOCKET fd = pfd->fd;
int revents = 0;
if (FD_ISSET(fd, rfds)) {
if (qemu_win32_fdset_contains(rfds, fd)) {
revents |= G_IO_IN;
}
if (FD_ISSET(fd, wfds)) {
if (qemu_win32_fdset_contains(wfds, fd)) {
revents |= G_IO_OUT;
}
if (FD_ISSET(fd, xfds)) {
if (qemu_win32_fdset_contains(xfds, fd)) {
revents |= G_IO_PRI;
}
pfd->revents = revents & pfd->events;
}
}
static int os_host_main_loop_wait(int64_t timeout)
typedef struct Win32PollState {
GArray *pollfds;
guint capacity;
QemuWin32FdSet *rfds, *wfds, *xfds;
struct Win32PollState *next;
} Win32PollState;
static Win32PollState *win32_poll_free;
static int pollfds_select(Win32PollState *poll)
{
static struct timeval tv0;
if (!poll->pollfds->len) {
return 0;
}
if (poll->capacity < poll->pollfds->len) {
size_t count = (size_t)poll->pollfds->len + 1;
poll->rfds = g_realloc_n(poll->rfds, count, sizeof(SOCKET));
poll->wfds = g_realloc_n(poll->wfds, count, sizeof(SOCKET));
poll->xfds = g_realloc_n(poll->xfds, count, sizeof(SOCKET));
poll->capacity = poll->pollfds->len;
}
poll->rfds->fd_count = 0;
poll->wfds->fd_count = 0;
poll->xfds->fd_count = 0;
if (!pollfds_fill(poll->pollfds, poll->rfds, poll->wfds, poll->xfds)) {
return 0;
}
int ret = select(0, qemu_win32_fdset_native(poll->rfds),
qemu_win32_fdset_native(poll->wfds),
qemu_win32_fdset_native(poll->xfds), &tv0);
if (ret > 0) {
pollfds_poll(poll->pollfds, poll->rfds, poll->wfds, poll->xfds);
}
return ret;
}
static int os_host_main_loop_wait(int64_t timeout, Win32PollState *poll)
{
GMainContext *context = g_main_context_default();
GPollFD poll_fds[1024 * 2]; /* this is probably overkill */
int select_ret = 0;
int g_poll_ret, ret, i, n_poll_fds;
int select_ret;
int g_poll_ret, ret, i, n_poll_fds, max_priority;
PollingEntry *pe;
WaitObjects *w = &wait_objects;
gint poll_timeout;
int64_t poll_timeout_ns;
static struct timeval tv0;
fd_set rfds, wfds, xfds;
int nfds;
g_main_context_acquire(context);
@@ -520,18 +564,9 @@ static int os_host_main_loop_wait(int64_t timeout)
return ret;
}
FD_ZERO(&rfds);
FD_ZERO(&wfds);
FD_ZERO(&xfds);
nfds = pollfds_fill(gpollfds, &rfds, &wfds, &xfds);
if (nfds >= 0) {
select_ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv0);
if (select_ret != 0) {
timeout = 0;
}
if (select_ret > 0) {
pollfds_poll(gpollfds, nfds, &rfds, &wfds, &xfds);
}
select_ret = pollfds_select(poll);
if (select_ret != 0) {
timeout = 0;
}
g_main_context_prepare(context, &max_priority);
@@ -597,10 +632,27 @@ void main_loop_poll_remove_notifier(Notifier *notify)
void main_loop_wait(int nonblocking)
{
static uint64_t fill_gen;
#ifdef _WIN32
/* Keep the poll array checked out through all callbacks that use it. */
Win32PollState *poll = win32_poll_free;
if (poll) {
win32_poll_free = poll->next;
} else {
poll = g_new0(Win32PollState, 1);
poll->pollfds = g_array_new(FALSE, FALSE, sizeof(GPollFD));
}
#endif
MainLoopPoll mlpoll = {
.state = MAIN_LOOP_POLL_FILL,
.timeout = UINT32_MAX,
#ifdef _WIN32
.pollfds = poll->pollfds,
#else
.pollfds = gpollfds,
#endif
};
int ret;
int64_t timeout_ns;
@@ -610,7 +662,8 @@ void main_loop_wait(int nonblocking)
}
/* poll any events */
g_array_set_size(gpollfds, 0); /* reset for new iteration */
g_array_set_size(mlpoll.pollfds, 0);
uint64_t my_gen = ++fill_gen;
/* XXX: separate device handlers from system ones */
notifier_list_notify(&main_loop_poll_notifiers, &mlpoll);
@@ -624,9 +677,20 @@ void main_loop_wait(int nonblocking)
timerlistgroup_deadline_ns(
&main_loop_tlg));
#ifdef _WIN32
ret = os_host_main_loop_wait(timeout_ns, poll);
#else
ret = os_host_main_loop_wait(timeout_ns);
mlpoll.state = ret < 0 ? MAIN_LOOP_POLL_ERR : MAIN_LOOP_POLL_OK;
notifier_list_notify(&main_loop_poll_notifiers, &mlpoll);
#endif
/* A nested fill can replace libslirp's pollfd indices. */
if (fill_gen == my_gen) {
mlpoll.state = ret < 0 ? MAIN_LOOP_POLL_ERR : MAIN_LOOP_POLL_OK;
notifier_list_notify(&main_loop_poll_notifiers, &mlpoll);
}
#ifdef _WIN32
poll->next = win32_poll_free;
win32_poll_free = poll;
#endif
if (icount_enabled()) {
/*