Compare commits

...
Author SHA1 Message Date
osy 8ab298bc52 usb-redir: attach a device of unknown speed at superspeed if it has superspeed endpoints
The usb-redir protocol has no speed above SuperSpeed. usbredirhost
announces a SuperSpeedPlus (10 Gbit/s) device with an unknown speed, and
an unknown speed is attached as full speed. The device itself still runs
at its own speed on the host, so the guest drives a SuperSpeed device
over a full or high speed link. Enumeration can be made to work, but a
USB Attached SCSI drive, which is what most of these devices are, uses
streams on a SuperSpeed link and none below it, and its first command
times out:

  usb 2-3: new high-speed USB device number 3 using ehci-pci
  scsi host0: uas
  scsi 0:0:0:0: tag#16 uas_eh_abort_handler 0 uas-tag 1 inflight: CMD
  scsi 0:0:0:0: Device offlined - not ready after error recovery

Only a SuperSpeed link has bulk endpoints with 1024 byte packets, and
the endpoint info arrives before the connect. Attach a device of unknown
speed that has such an endpoint at SuperSpeed.

Assisted-by: Claude:claude-fable-5-2
2026-11-10 22:50:30 -08:00
osy e37b2e515d usb-redir: fix up ep0 maxpacket for every device not attached at superspeed
A USB 3 device reports bMaxPacketSize0 = 9 (2^9 bytes) in its device
descriptor. That is only valid on a SuperSpeed link, so the descriptor
of a redirected device is rewritten to 64 when the guest sees the device
at a lower speed. A guest that gets the 9 gives up on the device:

  usb 1-1: new high-speed USB device number 2 using xhci_hcd
  usb 1-1: Invalid ep0 maxpacket: 9

The rewrite was limited to devices whose speed is SuperSpeed on a port
without it. Since usb_pick_speed() (b791c3b38c) the speed of an attached
device is the one it runs at on its port, so that is never the case and
the rewrite did not happen at all:

- A SuperSpeed device on a USB 2 controller is attached at high speed.
- A device the usb-host announces with an unknown speed is attached at
  full or high speed. The usb-redir protocol has no speed above
  SuperSpeed, and usbredirhost announces a SuperSpeedPlus (10 Gbit/s)
  device as unknown.

Rewrite the descriptor whenever the device is not attached at
SuperSpeed. A device that really runs below SuperSpeed never has a 9
there, so nothing changes for those.

Based on a change by giovariot.

Assisted-by: Claude:claude-fable-5-2
2026-11-10 22:50:30 -08:00
osy bb76def9a7 edid: set the established timings III bit of every mode that has one
edid_fill_modes() puts a mode in one of the eight standard timing slots
while there are free ones, and sets the mode's bit in the Established
Timings III descriptor only once the slots are used up. Which modes end
up where depends on their order in the table: with no size limit,
1920x1200, 1600x1200, 1680x1050, 1440x900, 1280x1024 and 1280x960 get a
standard timing and no bit.

A guest that builds its mode list from the established timings and does
not read the standard timings never offers those modes. The QemuVga
driver that Mac OS 9 and Mac OS X use on mac99 is one: it reads the
established timings, the Established Timings III descriptor and the
CTA-861 video data block.

Set the bit whenever the mode has one, next to the standard timing. The
bits are the ones VESA defines for these modes at 60 Hz, and the modes
were advertised before, so a guest that reads both sees the same list.

Based on a change by giovariot.

Assisted-by: Claude:claude-fable-5-2
2026-11-10 22:48:50 -08:00
osy 3c66a354b0 usb/xhci: keep the pace of a busy isochronous endpoint when timers are late
An isochronous transfer without a frame id (SIA) is scheduled one
interval after the previous one. When the endpoint's timer fires more
than four intervals late, xhci_calc_iso_kick() takes the transfer for
the first one after a pause and schedules it from the current
microframe instead. The intervals in between are dropped, although the
guest has transfers queued for every one of them, and the stream runs
slower than the guest's clock from then on.

Four intervals are 0.5 ms for a high-speed endpoint with a 125 us
interval, and 4 ms for a full-speed one. On macOS the main loop's timers
are often later than that, so a guest's USB audio played at a fraction
of its speed: a Linux guest playing to the emulated usb-audio device got
about 0.2x and aplay stopped with an I/O error after a few seconds.

Tell a late timer from a pause in the guest's transfers by the ring.
While the ring has transfers, the next one follows the last, however
late it is served. When the ring was found empty, the guest has four
intervals from that moment to queue the next transfer without a gap, as
it had from the last transfer before; being late ourselves no longer
counts against it. An endpoint that was stopped or reset keeps the old
rule.

Catching up can now serve more transfers in one go than the limit of
xhci_kick_epctx() allows, with no completion or doorbell to continue
after it, so the endpoint's timer is set to go on. That timer is now
also removed when the endpoint's transfers are dropped, so that it
cannot restart a stopped endpoint.

Based on a change by hdu_willsky.

Assisted-by: Claude:claude-fable-5-2
2026-11-10 22:48:09 -08:00
Mike Miller 0f1b8666d1 migration/savevm: answer the command that starts a snapshot job first
snapshot-save, snapshot-load and snapshot-delete start a job whose
coroutine schedules the actual work as a bottom half in the main
AioContext and yields. The command itself runs in a bottom half of the
iohandler context, and its reply is sent by the QMP dispatcher
coroutine, which is woken through that same context once the command
handler returns. The main loop gets to the main AioContext's bottom
half before it gets back to the dispatcher, and the work blocks the
main loop until it is done. So the reply goes out only after the
snapshot has been written or loaded, together with the job's
"concluded" event.

A client that puts a deadline on the reply (QEMUKit, used by UTM, waits
10 s) then reports a save that takes longer as failed, although QEMU
finishes it and the state stays in the image with nothing referring to
it.

Put the work behind the reply: the job coroutine now schedules a bottom
half in the iohandler context, and that one schedules the work in the
main AioContext. It runs in the same pass over the iohandler context as
the dispatcher's wake-up, and the main AioContext is only dispatched
after that pass, so the reply is written first. Errors are reported
through the job as before.

Measured over QMP with an aarch64 HVF guest holding 2 GiB of random data
in tmpfs (2.7 GiB vmstate), time from sending the command to its reply /
to JOB_STATUS_CHANGE "concluded":

                    before                  after
  snapshot-save     1467.4 ms / 1467.5 ms   0.9 ms / 1467.6 ms
  snapshot-load     1433.5 ms / 1433.6 ms   1.3 ms / 1425.4 ms
  snapshot-delete     90.3 ms /   90.3 ms   1.7 ms /   91.6 ms

Upstream QEMU master (v11.2.0-rc0) schedules the work the same way and
has the same ordering.

(cherry picked from commit 3f572363b83a3b64de9fd2d21a5fbbfc652caff8
 of https://github.com/emkey1/qemu; commit message rewritten)
Assisted-by: Claude:claude-opus-5-5
Assisted-by: Claude:claude-fable-5-2
2026-11-10 18:01:46 -08:00
osy e1c17c2009 target/ppc: clear the BATs on CPU reset
On 6xx/7xx/74xx CPUs the BAT registers are kept in env->IBAT[] and
env->DBAT[], not in env->spr[]. ppc_cpu_reset_hold() restores env->spr[]
from the SPR defaults and flushes the TLB, but it never touches the BAT
arrays, so they are zero on a cold boot (the CPU state is allocated
zeroed) and keep the guest's last values on every later reset.

OpenBIOS relies on the cold boot state: it turns translation on without
loading the BATs first and expects the next instruction fetch to raise
an ISI, which is how it starts filling its page table. When a guest OS
that has mapped the firmware's address range with a BAT resets the
machine (Mac OS 9 "Restart" on mac99, or system_reset from the
monitor), that fetch goes through the stale mapping instead. OpenBIOS
then executes whatever the guest left there and hangs before it
reinitialises the display, so the restart ends on a black screen:

  CPU Reset (CPU 0)
  Raise exception at fff08b3c => HV_EMU (96) error=21

Clear both arrays in the reset handler so a reset starts from the same
BAT state as a cold boot. This is done for all accelerators: with KVM
the arrays are what kvm_arch_put_registers() pushes to the kernel after
a reset.

Upstream QEMU master has the same omission as of v11.2.0-rc0.

Reported-by: TinBane
Assisted-by: Claude:claude-fable-5-2
2026-11-10 18:00:55 -08:00
osy 7d312eb47a hda-codec: catch up at once after a stall the ring covers
The output pacing forgave any debt beyond B_SIZE / 8 (5 ms at 48 kHz
stereo), and forgiven time comes back only at 1/32. A main loop that is
late by more than that over and over therefore played the guest's audio
slow: with the loop blocked for 12 ms 34 times a second, a 10 s tone took
12.4 s to play, where it took 10.0 s before pacing. A host that coalesces
timers to 8 ms did the same (a 20 s tone took 31 s).

Allow a burst of the whole ring, so that a stall the ring can take is
caught up at once, as it was before pacing. After a longer stall the debt
is still forgiven down to B_SIZE / 8, so the guest's position does not
jump.

Assisted-by: Claude:claude-fable-5-2
2026-11-10 14:20:21 -08:00
osy 7fe362b132 screamer: let a late TX tick catch up
The TX credit was capped at the 128-frame FIFO on every update, so a
pacing tick more than ~3 ms late threw away frames that were already
due. The guest's DMA then ran slower than the sample rate, the host
ring drained, and FRAME_CNT fell behind real time.

Within a transfer, let a late tick catch up to twice the FIFO. Idle time
before a descriptor starts still only fills the FIFO, and stopping the
channel drops any surplus, so a new ring still cannot complete at once.

Assisted-by: Claude:claude-opus-5-5
2026-11-10 10:47:12 -08:00
osy 9c6999578b screamer, mac_dbdma: fix stuck and replayed DMA with paced transfers
TX and RX transfers now stay in flight on a timer, which exposed a few
paths that assumed they complete at once:

- A zero-length INPUT descriptor never completed: the RX timer returned
  early on len == 0, so the channel stayed "processing" forever.
- mac_dbdma_reset left io.processing set while screamer_reset deleted the
  timers that would clear it, so sound stayed dead after a guest reboot
  that interrupted playback or recording.
- tx_flush cleared io.processing on PAUSE or FLUSH too, so DBDMA restarted
  the descriptor still being paced and its frames were sent twice. Only
  clear it when the guest stops the channel, as rx_flush does.
- If the virtual clock went backwards (loadvm), TX got no credit until
  it caught up again.

Also factor the duplicated res_count/xfer_status write-back and the
"guest cleared RUN" test into helpers, and fix a block comment style.

Assisted-by: Claude:claude-opus-5-5
2026-11-10 10:47:12 -08:00
Bruno Castelló b93cf1ab64 mac_dbdma, screamer: fix LOAD_WORD, s0-s7 status bits and RX DMA
- LOAD_WORD: store the loaded data in the cmdDep field of the command in
  memory, as real DBDMA does. Since only res_count/xfer_status are written
  back now, the Mac OS 9 Screamer driver (VM off, >= 1 GB) never saw the
  frame counter it samples with LOAD_WORD.
- dbdma_control_write: honour the software-settable device status bits
  s0-s7. The Mac OS 9 sound input driver sets s0 to make its INPUT command
  branch out of the ring; it was ignored, so the ring never stopped.
- screamer RX: instead of completing INPUT commands instantly with nothing
  transferred and forcing RUN off (a workaround for the above), deliver
  silence and complete each command after its duration at the sample rate.

Assisted-by: Claude:claude-opus-5-5
2026-11-10 10:47:12 -08:00
Bruno Castelló a8dfd66f4c mac_dbdma, screamer: only write back res_count and xfer_status
The hardware only updates those two fields when a command completes.
Writing back the whole cached descriptor could undo changes the guest
made to it in the meantime.

Assisted-by: Claude:claude-opus-5-5
2026-11-10 10:47:12 -08:00
Bruno Castelló 93019576da screamer: pace TX DMA to the sample rate
With 1 GB or more RAM Mac OS 9 turns VM off and its sound driver uses a
single 4 KiB ring. Screamer consumed the whole ring at once, so the
driver saw both half-buffer interrupts before anything played and kept
restarting: alert sounds came out as short blips.

Complete OUTPUT commands at the codec sample rate instead, with a small
FIFO lead, and count FRAME_CNT as frames are consumed.

Assisted-by: Claude:claude-opus-5-5
2026-11-10 10:47:12 -08:00
osy aa44dfaca1 ui/spice-display-metal: convert scanouts the surface cannot hold verbatim
The Metal scanout path copies the guest's scanout texture into the
shared IOSurface with a blit.  The surface is BGRA8 or RGBA8, but a
scanout can be R10G10B10A2 (a 10-bit fullscreen primary): a blit copies
raw bits, so the 10-bit pixels were shown as BGRA8 (an orange clear came
out blue).

When the scanout is a 10-bit UNORM format (RGB10A2, BGR10A2), draw it
instead: a full-screen triangle whose fragments read the source texel at
the position the blit would copy from, scissored to the damaged rect.
Its values are display-encoded like an 8-bit scanout's, so they are
written as read, with alpha forced opaque (scanout alpha carries
nothing).  The scissor is clamped to the surface and to the scanout
texture past its origin; a 10-bit scanout is never blitted raw (with an
empty rect, or a pipeline that failed to build, the frame is skipped),
and a failed pipeline build is not retried every frame.  A 16-bit-float scanout (normally scRGB: linear, values
above 1.0) would need clamping and sRGB encoding and is left on the blit
path, as is every same-layout format, sRGB twins included.

Measured with exclusive fullscreen at 800x600 cleared orange (1.0, 0.5,
0.0), R10G10B10A2 and R8G8B8A8/B8G8R8A8, blt and flip model: the VM
window shows orange (window capture 239,135,51 after display colour
management); before, the 10-bit cases showed blue (screenshot 50,28,255).

Assisted-by: Claude:claude-opus-5-5
2026-11-10 10:36:41 -08:00
Josh Guyette 1219f88549 accel/hvf, os-posix: support -overcommit mem-lock=on on macOS
mlockall() returns ENOSYS on macOS, so -overcommit mem-lock=on failed at
startup. Lock each guest RAM mapping with mlock() as HVF maps it instead,
and let os_mlock() succeed on macOS.

On a 2017 Intel MacBook Pro (16 GB) with an 8 GB Windows 11 guest, about
8 GB stays wired with the option on. Without it, a memory-heavy run on our
earlier fork left only 2.8 GB resident. On utm-edition I measured no idle
CPU difference and no clear speed benefit.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Josh Guyette <[email protected]>
2026-11-10 09:59:28 -08:00
Josh Guyette 65ddba202f audio/coreaudio: jitter buffer
Start playing only once half of the ring is queued, and prime again after
an underrun. Without the cushion, playback runs with about one buffer
queued, and every late audio timer costs a whole buffer of silence.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Josh Guyette <[email protected]>
2026-11-10 09:47:22 -08:00
Josh Guyette 80d3e749a8 audio: steadier HDA playback on a busy Mac
Three changes, based on OmacVM's patches (MIT,
github.com/gillesgoetsch/OmacVM, PR #93):

- system/main.c: on macOS the main loop thread asks for user-interactive
  QoS. It feeds the HDA DMA timer and the audio timer and runs virgl; at
  the default QoS it waits behind the vCPU threads, so the sound breaks up.
  QEMU_MAIN_LOOP_QOS=default keeps the old behaviour.
- hda-codec: on a full output ring, keep the queued samples and only reset
  the catch-up debt, instead of dropping the whole 8 KB buffer (~42 ms).
- hda-codec: pacing (new "pace" property, on by default). After a stalled
  main loop, take the guest's audio at most 1/32 faster than real time
  instead of all at once.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Josh Guyette <[email protected]>
2026-11-10 09:47:04 -08:00
Josh Guyette 5e2b2062bf virtio-gpu-virgl: keep the VGA framebuffer until a real scanout
virgl_cmd_set_scanout switched virtio-vga away from the VGA framebuffer
for every SET_SCANOUT, including ones that disable the scanout. Windows'
viogpu3d driver disables scanout 0 hundreds of times during boot before
DWM's first frame, so the boot screen was replaced by "Display output is
not active." for about 12 seconds.

Only switch away from VGA when a resource is actually scanned out, like
the 2D path in virtio-gpu.c does, and also on the Metal native blob path,
which did not set it at all and relied on the disable calls.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Josh Guyette <[email protected]>
2026-11-10 09:45:57 -08:00
Josh Guyette 9e1333a432 ui/cocoa: add hidpi=off and fill the window with Metal scanouts
The Metal scanout layer was sized to the guest texture divided by the
backing scale factor and pinned at the view origin, so with zoom-to-fit a
guest that does not follow the window size (a Windows guest stuck at
1024x768) was drawn in the bottom-left corner of a full-screen window.
With zoom-to-fit the layer now fills the view and Core Animation scales the
drawable, as the 2D path does.

Also add the hidpi option: on a Retina screen the window size is reported
to the guest in physical pixels, so a full-screen guest on a 15" MacBook
Pro renders 2880x1800. With hidpi=off the window is sized one guest pixel
per point and the guest gets 1440x900, which the host scales up 2x.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Josh Guyette <[email protected]>
2026-11-10 09:39:54 -08:00
Josh Guyette 681717abd3 accel/hvf: map non-executable host memory without EXEC on Intel
Intel Hypervisor.framework rejects hv_vm_map() with HV_MEMORY_EXEC when
the host mapping's maximum protection lacks execute, returning HV_ERROR.
virtio-gpu blob resources shared from the render server are mapped
read/write only (maxprot=RW), so the first Neptune/venus blob map aborted
QEMU in do_hvf_set_memory() (utmapp/UTM#8036). Arm64 HVF does not reject
these mappings.

Check the host entries backing a slot and leave EXEC out when any of them
cannot be executable. Guest RAM is unaffected. Tested on a MacBookPro14,3
(i7-7700HQ, Radeon Pro 555) with a Windows 11 x64 guest: blob maps now
succeed and Neptune contexts are created.

Fixes: https://github.com/utmapp/UTM/issues/8036

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Josh Guyette <[email protected]>
2026-11-10 09:39:15 -08:00
Allen Wang ed597a6131 tcg/aarch64-tcti: correct reversed vector comparisons
Signed-off-by: Allen Wang <[email protected]>
2026-11-10 09:31:40 -08:00
lovelyKoishi 2de5a329bc ui/gtk: match the X11 drawing area visual to the EGL config
GTK's default X11 visual may differ from the native visual required by
the selected EGL configuration. On NVIDIA PRIME this can make
window surface creation fail with EGL_BAD_MATCH.

Select the corresponding GdkVisual before realizing the drawing area.
Keep the current visual when the query or lookup fails. Also report
the EGL error string if window surface creation fails.

Assisted-by: Codex:unknown
2026-11-10 09:29:14 -08:00
lovelyKoishi 4b9b007c2a ui/spice-display: fix the Linux GL update build
Declare the guest dma-buf dimensions in the scope where they are used.
Drop the stale boolean argument to egl_texture_blend() so that the call
matches its declaration.

These errors prevent the Linux SPICE/OpenGL display code from compiling.

Assisted-by: Codex:unknown
2026-11-10 09:28:38 -08:00
Kaede fa05ee46ed target/arm/hvf: report an external abort for an access with no syndrome
A data abort without a valid instruction syndrome (a store pair, SIMD
or SVE access) on an address nothing is mapped at cannot be emulated,
and QEMU aborted on assert(isv), taking the VM down.  A Windows guest
gets there at shutdown: it turns off the virtio-gpu device's memory
decoding, so its BARs drop out of the address space, while an
application is still writing through its mapping of a hostmem blob.

Inject a synchronous external abort into the guest instead, which is
what QEMU does for the same access under KVM
(kvm_arm_handle_dabt_nisv()).

Assisted-by: Claude:claude-opus-5-5
2026-11-10 09:25:28 -08:00
Kaede 1fe2938b42 target/arm/hvf: retry a data abort on RAM that is mapped again
A memory topology update unmaps and then maps again every hvf slot it
touches.  A vCPU that accesses such a range in between takes a stage-2
translation fault, and handles it only after the update is done, once
it gets the BQL; by then the IPA is RAM again.  QEMU still treats the
exit as MMIO, so an access without a valid instruction syndrome (a
store pair or SIMD store from memcpy) aborts on assert(isv), and one
with a syndrome is emulated into RAM.

This is easy to hit with virtio-gpu's hostmem BAR, whose layout changes
whenever a blob is mapped or unmapped while guest processes keep
writing to the blobs that stay: shutting down a Windows guest while an
application is still drawing aborted QEMU this way.

If the IPA is covered by a RAM slot, retry the access instead, as the
x86 hvf code does for EPT violations.  Writes to read-only and
dirty-logged slots still go through emulation.

Assisted-by: Claude:claude-opus-5-5
2026-11-10 09:25:28 -08:00
Kaede 9974fed690 virtio-gpu: keep the hostmem BAR decoding after a guest reset
A device reset destroys every resource, and with them every blob mapped
into the hostmem BAR.  The guest driver cannot always revoke the CPU
mappings it handed out before it resets: the Windows display driver
resets the device on its way to D3 at shutdown and reboot, while
user-mode processes (DWM drawing the "Restarting" screen, a game that
is still exiting) can keep writing through their mappings.  Those
writes then land in holes of the BAR.

On hvf such a write is usually a store pair or a SIMD store from
memcpy, which exits without a valid instruction syndrome, so QEMU
aborts on assert(isv) in hvf_handle_exception() and the VM dies on its
way down (UTM reports a QEMULauncher crash when a Windows VM is shut
down after running a D3D12 game).  Under TCG the guest takes an
external abort instead.  A real GPU's BAR keeps decoding.

When a guest-initiated reset finds blobs mapped, put RAM behind the
blob subregions (priority -1, so every blob mapped later shadows it)
and keep it until the next machine reset, after which no guest code
can hold a stale mapping.  A reset with nothing mapped (firmware,
driver start) leaves the BAR untouched, so a normal boot pays nothing.
The RAM is only reserved; host pages are committed only for what the
stale mappings touch.  Guest-initiated and machine resets are told
apart the way virtio_gpu_reset() already does, by whether the reset
runs on a vCPU thread.

Assisted-by: Claude:claude-opus-5-5
2026-11-10 09:25:07 -08:00
osy 2934963d17 Revert "edid: carry the host refresh rate consistently, up to DisplayID 2.0"
This reverts commit 71bfcf2c06.

Assisted-by: Claude:claude-opus-5-5
2026-10-28 15:38:24 -07:00
Dragos Hont 7ebc0f66a3 virtio-gpu: add a refresh_rate property for displays that report none
The EDID only carries the host refresh rate when the display reports it
in QemuUIInfo. GTK and Cocoa do, but SPICE has no field for it, so a
SPICE guest always gets a synthesised 75 Hz mode. On a 60 Hz host
display about one frame in five is rendered and never shown, and a
120 Hz display can't be used.

Add a refresh_rate property (mHz, default 0) to the virtio-gpu base
device. It seeds every output and is used whenever the display reports
no rate, e.g.

  -device virtio-gpu-pci,refresh_rate=60000

Values below 1000 are rejected, since a rate passed in Hz would produce
a ~0.06 Hz mode.

Signed-off-by: Dragos Hont <[email protected]>
Assisted-by: GitHub Copilot:claude-opus-5.5
Assisted-by: Claude:claude-opus-5-5
2026-10-28 13:46:19 -07:00
osy ae92cdc41f usb-storage: don't park a CSW that arrives while the command completes
usb_msd_command_complete() completed the pending data packet before it
dropped s->req.  Completing a packet lets the host controller process
the next TRB on that endpoint synchronously, and when the guest has
already queued its CSW request, usb_msd_handle_data() runs re-entrantly
in CSW mode, sees s->req still set and parks the packet as "still in
flight".  The command has finished by then, so nothing ever completes
that packet: the guest times out the transfer, stops the endpoint and
resets the device before it retries.

Windows' USB storage timeout is 10 s, so a Windows install from a USB
CD stalled ~10 s after every short burst of reads (ep_stop, msd reset,
slot reset each time).  The window is narrow, but with the HVF in-kernel
GICv3 the guest takes the interrupt and queues the CSW fast enough to
hit it on nearly every burst: copying Windows files went from ~160 s to
~1230 s.

Release the request before completing the packet, so a packet handled
re-entrantly sees the same state as one that arrives after
usb_msd_command_complete() returns: the CSW gets its status immediately.
The SCSI layer holds its own reference across the complete callback,
and nothing after the release touches the request, so dropping ours
earlier is safe.  The same install now copies its files in ~135 s with
the in-kernel GIC, with no timeout resets.

Assisted-by: Claude:claude-opus-5-5
2026-10-16 12:01:52 -07:00
osy 88e5ee7ec6 virtio-gpu: initialise popped control commands in one helper
virtio_gpu_process_cmdq() reads cmd->suspended and cmd->deferred for every
device, but each handle_ctrl loop reset the per-command state on its own.
fdaf37123a fixed the GL loop for deferred; the rutabaga loop still set only
vq, error and finished, so its commands carried leftover g_malloc bytes in
both flags and could be parked at the queue head or dropped without a
response.

Move the reset into virtio_gpu_ctrl_cmd_init() and call it from all three
loops, so a new per-command flag is initialised in one place.

Assisted-by: Claude:claude-opus-5-5
2026-10-13 10:42:13 -07:00
osy fdaf37123a virtio-gpu-gl: initialise the deferred flag on every popped command
3bdba2ae2e added virtio_gpu_ctrl_command.deferred and cleared it in
virtio_gpu_handle_ctrl, but the GL device pops commands through
virtio_gpu_gl_handle_ctrl, which never set it.  virtqueue_pop allocates
with g_malloc, so the flag held leftover heap bytes: a command that
landed on a non-zero byte was processed, then taken off cmdq as deferred
and never answered or freed.

The guest sees those as commands that never complete.  On Windows a lost
CREATE_BLOB reply made the KMD retry the id ("resource already exists
25"), and lost unref/fence replies hung shutdown on the "Restarting"
screen (34 unanswered descriptors, empty cmdq and fenceq).  On Linux a
lost context or fence reply stalled Fire Strike and Time Spy at the
second D3D context.

Clear it with the other per-command flags.  Windows install -> reboot ->
desktop: 4/4 pass after, 3/4 failed before.

Assisted-by: Claude:claude-opus-5-5
2026-10-07 00:30:16 -07:00
osy 40b5b1ff33 virtio-gpu: let a create wait for a deferred unref of the same id
An UNREF of a still-mapped blob is deferred until its MemoryRegion
finalizes while the control queue keeps flowing (3bdba2ae2e).  A guest
that reuses the id as soon as it has queued the UNREF -- the Windows
viogpu3d KMD does when it re-establishes its blob windows -- had its
CREATE rejected with INVALID_RESOURCE_ID ("resource already exists") and
came up with no display.

Park a CREATE_2D/3D/BLOB whose id has a deferred unref at the cmdq head,
the way a re-MAP is parked.  The unmap completion releases the block,
completes the unref and resumes the queue, and the create re-runs
against a free id.

Assisted-by: Claude:claude-fable-5-1
2026-10-07 00:30:16 -07:00
osy 71bfcf2c06 edid: carry the host refresh rate consistently, up to DisplayID 2.0
Two places in the generated EDID contradicted the preferred detailed
timing, which already carried the host's refresh rate.

The standard timing descriptors hardcoded 60 Hz in their six-bit rate
field, so a guest that builds its mode list from them gave every mode
60 Hz. Windows does exactly that, and drove a 120 Hz display at 60.
Encode the rate the UI reported, saturated to the 60..123 Hz the field
spans, and keep the 60 Hz DMT modes when the UI reported nothing rather
than the 75 Hz placeholder the detailed timing is synthesised from.

The display range limits descriptor declared a fixed 50..125 Hz and
30..160 kHz. A host display faster than 125 Hz, or a large mode whose
line rate passes 160 kHz, puts the preferred timing outside the range
the same EDID declares. Windows rejects an EDID that contradicts itself:
it drops the monitor's mode list for a default one, the adapter stops
driving the display, and D3D device creation fails with E_FAIL. Widen
the range to contain the preferred timing as the guest derives it from
the detailed timing, rounding the minimum down and the maximum up, and
use EDID 1.4's +255 offset flags for a maximum that does not fit a
byte; 510 is the most the descriptor can express.

A rate in the standard timings that no DMT mode carries asks the guest
to derive a raster from a formula, so declare one, together with the
continuous frequency feature bit that has to accompany it. Declare CVT
rather than the GTF that EDID 1.4 deprecates, and give the preferred
timing the horizontal blanking of CVT reduced blanking v2. The narrow
blanking keeps the pixel clock of common fast modes inside the
655.35 MHz a detailed timing descriptor holds, so 2560x1440 at 144 Hz
or 1920x1080 at 240 Hz stay in the base block, and under the 2550 MHz
the range limits can express.

Past the range limits descriptor, 510 Hz, 510 kHz per line and
2550 MHz, the base block cannot describe the timing at all, and neither
can a DisplayID 1.3 section, whose type I timing counts the pixel clock
in tens of kHz and which carries no range of its own. A 4K display past
about 220 Hz, whose line rate passes 510 kHz, has no way to state what
it does. Emit a DisplayID 2.0 section for such a timing: its type VII
timing counts the pixel clock in kHz, and the dynamic video timing
range limits block beside it holds a 24 bit pixel clock and a ten bit
vertical rate, and constrains no line rate at all. Only such a timing
gets one. A guest has understood type I timings far longer than type
VII ones, which Linux learned to read in 5.18, so anything a 1.3
section can describe keeps the 1.3 section it always had.

The type I and type VII timings share one writer, which stores the
clock one less than it counts as DisplayID requires; the 1.3 section
used to publish it 10 kHz high.

None of this applies to a host that reports no rate, or one whose rate
the standard timings already carry. The EDID those produce stays byte
for byte the one QEMU has always generated, unless its range limits
already contradicted its preferred timing, as a 4K display's 167 kHz
line rate did at the 75 Hz placeholder, or it carries that DisplayID
clock.

Have vfio-display pass on the rate the UI reports as well, and give
qemu-edid a -r option to generate an EDID for a given rate.

Assisted-by: Claude:claude-fable-5-1
Assisted-by: Claude:claude-opus-5
2026-10-07 00:29:38 -07:00
osy 2bd696cdce ui/cocoa: report display info whenever it changes
updateUIInfo only reached the guest on a user resize or a move to another
screen. The guest therefore ran with whatever refresh rate, backing-pixel
size and physical size happened to be current at the first resize, and
never learned about the host display at startup, after a guest mode set,
or when the display's own parameters changed under it.

Report at those points too. The mode-set path cannot start a resize loop:
resizeWindow suppresses windowDidResize's report, and the size reported
back is the mode the guest has just set.

Also zero-initialise QemuUIInfo. The refresh rate was left holding stack
garbage when the view had no window or the display link could not be
created.

Assisted-by: Claude:claude-fable-5-1
2026-10-07 00:29:38 -07:00
osy b795d6de88 hw/display/apple-gfx: build against the macOS 27 SDK
PGNewDeviceWithDescriptor is obsoleted in the macOS 27 SDK and is no
longer exported from the ParavirtualizedGraphics stub, so linking fails.
Use PGCreateDeviceWithDescriptor on macOS 15.2+ and look up the old
symbol at runtime on older hosts.

Assisted-by: Claude:claude-opus-5
2026-09-15 03:41:04 +02:00
osy b44153a4b6 ui/cocoa: read the Metal scanout at the flush, not from the refresh timer
A flip-model guest hands the displaced buffer back to its application as
soon as the flip is submitted and orders the application's next writes
behind the flip on the GPU, so a scanout buffer is only intact from the
RESOURCE_FLUSH that publishes it until the next flip.  The Cocoa display
read it from the 30 ms refresh timer instead, up to a full flip interval
late, and on Windows with DXMT (whose ClearRenderTargetView is an
immediate clear pass) the read landed on the next frame's clear about
twice a second: 1-2 frame black flashes on 2.4-3 % of frames.

Blit and present when the guest flushes the frame.  One read is in
flight at a time so a guest flipping faster than the display refreshes
never exhausts the drawable pool; a flush that finds a read in flight is
served when it completes, and the refresh timer only retries a read that
found no drawable.

Windows Fire Strike: DXMT 2.4 % / ~100 flashes -> 0.7 % / the three
fullscreen transitions, matching D3DMetal; fps unchanged on both.

Assisted-by: Claude:claude-fable-5-1
2026-09-02 22:02:00 -07:00
osy 227f8b678b arm/hvf: serve PMCCNTR_EL0 reads without the BQL
Windows on Arm reads the PMU cycle counter constantly -- its x64
emulator implements RDTSC on it -- and HVF cannot virtualize the PMU, so
under an emulated game the guest takes several hundred thousand
PMCCNTR_EL0 traps per second (measured 640k/s at load, ~300k/s in play).
Each went through the general exit path: BQL, vtimer sync, and a return
to the vCPU thread loop.  Serve the common case -- counter enabled,
unfiltered, 64-bit -- from the exit handler with no lock and no state
sync, and go straight back into the guest unless something is pending; a
kick that races is sticky in HVF and surfaces as a CANCELED exit on the
next run.

The counter state the fast path reads is not entirely private to the
vCPU thread: event counters arm cpu->pmu_timer, and arm_pmu_timer_cb()
on the main-loop thread transiently parks the raw cycle count in
c15_ccnt_delta inside its pmu_op_start()/pmu_op_finish() span.
pmu_op_start/finish therefore flag their span via a per-CPU seqlock
(pmu_op_lock), and the fast path validates it before committing, falling
back to the locked path on a race.  It also bails to the slow path for
EL0 reads that PMUSERENR_EL0 denies, so the access trap is still raised
architecturally.

Assisted-by: Claude:claude-fable-5
Assisted-by: Claude:claude-opus-5
2026-08-30 02:18:07 -07:00
osy 161407f4c5 arm/hvf: emulate a full PMUv3 so guests get a sampling profiler
Apple silicon has no architected PMUv3 (ID_AA64DFR0_EL1.PMUVer == 0), so
guests had no CPU sampling source: Windows on Arm refuses ETW
sampled-profile sessions with ERROR_NOT_SUPPORTED and Linux perf finds
no PMU.

Advertise base PMUv3 (PMUVer = 1) with six event counters
(reset_pmcr_el0 = 6 << PMCRN_SHIFT; IMP/IDCODE left 0 like the TCG CPUs
that don't model a specific implementation) and emulate the whole unit:

 - Replace hvf.c's partial hand-rolled PMU register emulation (which had
   drifted from helper.c: PMINTENCLR_EL1 set instead of clearing,
   PMINTENSET_EL1/PMOVSSET_EL0 UNDEFed, PMCEID read as zero, no event
   counters) with hvf_sysreg_access_pmu(), which routes every PMU
   register through the cpreg handlers helper.c registers.  This shares
   TCG's implementation of PMUSERENR_EL0 access control (EL0 denial
   raises the architectural trap, mirroring access_check_cp_reg()),
   per-counter op_start/finish bracketing, the pre-FEAT_PMUv3p5 RES0
   masking of event counter reads, the c14_pmevcntr_delta re-baseline on
   event type changes, and PMCEID0/1 derived from pm_events.
 - Refresh env->pstate from HV_REG_CPSR on EC_SYSTEMREGISTERTRAP
   (hvf_sync_pstate()) so arm_current_el() is accurate for the cpreg
   access checks instead of stuck at its reset value.
 - Under HVF the vCPU runs unobserved between traps, so PMEVTYPER.P/U
   cannot be honoured per-EL, and evaluating them at trap-time EL would
   permanently disable e.g. perf's cycles:u (the registers are only
   touched from EL1): pmu_counter_enabled() now counts unless the filter
   excludes every EL, leaving sample attribution to the interrupted PC.
 - pmcr_write() re-evaluates the interrupt line when PMCR_EL0.E changes
   (per CheckForPMUOverflow(); TCG had the same latent gap), and a
   per-CPU reset deasserts the level-triggered PPI, which nothing
   lowered across a CPU_OFF/CPU_ON cycle since a single-CPU reset does
   not reset the GICv3.
 - Add a cpu/pmu-sysregs vmstate subsection carrying the raw PMU fields
   (with the pmevtyper_rawwrite()-style delta re-baseline on load): HVF
   rebuilds the cpreg list from the registers the hypervisor can sync,
   which excludes the emulated PMU, so its state silently reset across
   savevm/loadvm.
 - ID_AA64DFR0_EL1 needs no manual sync: it is in hvf_sreg_match[], so
   hvf_put_registers() pushes the model's value before the first run,
   and pmu=off keeps reporting PMUVer == 0 since realize zeroes the isar
   field (Windows reads PMCCNTR_EL0 even then, so it cannot boot with
   the PMU off; noted at the site).

The helper.c machinery (virtual-clock cycle counts, pmu_timer overflow,
PPI 23 already wired on the virt board and advertised in the MADT) does
the rest.

Verified: Ubuntu boots, registers armv8_pmuv3 with 6 counters, perf stat
counts cycles at the virtual clock rate, perf record -e cycles and
cycles:u both deliver samples with overflow IRQs matching sample counts,
an EL0 PMCCNTR_EL0 read with PMUSERENR_EL0 == 0 takes SIGILL, and Venus
comes up.  Windows 11 arm64 boots and wpr -start CPU records real
SampledProfile events with stacks (previously 0x80070032).

Assisted-by: Claude:claude-fable-5
Assisted-by: Claude:claude-opus-5
2026-08-30 02:18:07 -07:00
osy e8f144d846 ui/cocoa: access gl_dirty atomically
drawFrame re-arms gl_dirty from the Cocoa main thread when nextDrawable
returns nil, but the scanout and update callbacks set it and
cocoa_gl_refresh consumes it on the QEMU IO thread.  As a plain bool the
consume can swallow that re-arm, so the dropped present is never retried
and the Metal layer keeps no fresh frame -- the display goes black until
the guest happens to flush again.  A sustained fullscreen guest drops
presents often enough for this to read as a steady flicker.

Consume with qatomic_xchg and set with qatomic_set so a re-arm is never
lost.

Assisted-by: Claude:claude-opus-5
2026-08-30 02:18:07 -07:00
osy 3bdba2ae2e virtio-gpu: don't stall the control queue behind a blob unmap
Unmapping a hostmem blob detaches its MemoryRegion, and the virgl mapping
has to survive until that MR is fully unreferenced (a flat view may still
be under an RCU reader), which takes ~100 ms.  Blocking all command
processing for that grace period, as before, serialized a burst of unmaps
into multi-second round trips for every other command: a D3D12 guest
tearing down hundreds of staging heaps pushed unrelated packets past
dxgkrnl's timeout, and the app died with DXGI_ERROR_DEVICE_RESET.

Keep the queue flowing instead.  UNMAP_BLOB is answered as soon as the
subregion is gone -- the guest cannot reach the pages any more -- and the
virgl unmap runs from the resume BH once the region finalizes.  Only work
that needs that unmap to have happened waits for it, and per resource
rather than per queue: an UNREF of a still-mapped resource is completed
(virgl unref + response) from the same BH, leaving the queue meanwhile
(cmd->deferred), and a re-MAP of a resource whose previous mapping is
still going away is the one case that still suspends the queue.

Assisted-by: Claude:claude-fable-5
2026-08-30 02:18:07 -07:00
osy 3824e0d996 virtio-gpu: enable async fencing on the render-server path without EGL
Upstream gates async fencing behind qemu_egl_display because vrend's
async path needs EGL.  The render-server proxy does not: it retires
fences on its own sync thread, fed by an eventfd/pipe the render worker
writes per retire.  On a macOS Cocoa/Metal build qemu_egl_display is
NULL, so the feature was inert and the only retire discovery for
venus/neptune fences was the 1 ms fence_poll timer.  Install the async
callbacks and pass ASYNC_FENCE_CB | THREAD_SYNC whenever the render
server is in use (virglrenderer scopes the flags away from vrend where
it lacks eventfd support).

The async BH now delegates to virgl_write_fence() /
virgl_write_context_fence() instead of carrying its own matching loop:
upstream's loop let a context fence complete a global fenced cmd with a
numerically smaller id, but global and per-context fence ids are
separate counters here, and the strict handlers also keep per-cmd
inflight accounting.

fence_poll stays as a watchdog: while any global (non-ring) fence is
pending it keeps the 1 ms rate -- vrend fences still retire only from
virgl_renderer_poll() -- and relaxes to 100 ms when only ring fences
(async-delivered) remain.

Assisted-by: Claude:claude-fable-5
2026-08-30 02:18:07 -07:00
Dmitry Osipenko 2870e745b9 virtio-gpu: Support asynchronous fencing
Support asynchronous fencing feature of virglrenderer. It allows Qemu to
handle fence as soon as it's signalled instead of periodically polling
the fence status. This feature is required for enabling DRM context
support in Qemu because legacy fencing mode isn't supported for DRM
contexts in virglrenderer.

Reviewed-by: Akihiko Odaki <[email protected]>
Acked-by: Michael S. Tsirkin <[email protected]>
Tested-by: Alex Bennée <[email protected]>
Reviewed-by: Alex Bennée <[email protected]>
Acked-by: Pierre-Eric Pelloux-Prayer <[email protected]>
Reviewed-by: Yiwei Zhang <[email protected]>
Tested-by: Yiwei Zhang <[email protected]>
Signed-off-by: Dmitry Osipenko <[email protected]>
Message-ID: <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alex Bennée <[email protected]>
2026-08-30 02:18:07 -07:00
osy 7311c3651c hw/arm/virt: shrink the high PCIe MMIO window to fit small PA spaces
Previously, if the high PCIe MMIO window did not fit in the guest
physical address space, it was silently disabled, leaving no room to
place any 64-bit BAR too large for the 32-bit window. On hosts with a
small IPA space (e.g. a 36-bit IPA), this made devices like virtio-gpu
with a large hostmem BAR unusable.

Instead, shrink the window to the largest power of two that fits (no
smaller than 1GiB) and warn about it. Only if even the minimum does not
fit is the window disabled, and each high region now warns when it is
disabled for not fitting rather than vanishing silently.

To make room at all on such hosts, skip the legacy 256GiB floor for the
high IO region when the high regions cannot fit there, placing them
right above RAM instead. !highmem keeps the floor since disabling the
regions is the point of that option.

Accordingly, highmem-mmio-size now accepts any power of 2 down to 1GiB
instead of rejecting values below the 512GiB default.

Assisted-by: Claude:claude-fable-5
2026-08-02 21:04:16 -07:00
osy 27d8515de3 Revert "ui/console: force gl-unblock from the watchdog timer"
This reverts commit 5cb1434ba3.
2026-07-29 16:20:12 -07:00
osy 6c0ee26536 ui/spice: carry the guest scanout's pixel format to the IOSurface
The shared IOSurface was created with a hardcoded 'BGRA' pixel format,
and that format was hardcoded again at every consumer, including the
fourcc reported to the client through spice_qxl_gl_scanout().

A scanout is in whatever format the guest allocated. That is normally
BGRA, but a fullscreen D3D swapchain becomes the scanout directly and may
be R8G8B8A8, so its bytes ended up in a surface every consumer read as
BGRA and red and blue came out transposed. Windowed output was unaffected
because the scanout is then the desktop primary, which is BGRA.

Take the format from the scanout MTLTexture, recreate the surface when it
changes just as for a size change, and report the real fourcc.
SpiceGlScanout.format is documented as the drm fourcc format; it was
being filled with a constant.

The EGL path takes the format too. The CGL path cannot: for 8-bit colour
CGLTexImageIOSurface2D only accepts GL_BGRA with
GL_UNSIGNED_INT_8_8_8_8_REV, and that combination reads the surface as
BGRA no matter what its fourcc says, so a non-BGRA surface there is
refused rather than silently transposed. Only the Metal path is ever
asked for a different order.

Assisted-by: Claude:claude-opus-5
2026-07-29 01:19:17 -07:00
osy 7e67e276de hvf: fix lost interrupt delivery during WFI
cpus_kick_thread() can race hvf_wait_for_ipi() and deadlock the VM: its
thread_kicked dedup can swallow a kick that was issued right after
hvf_wait_for_ipi() cleared the flag but before it entered pselect(). The
vCPU then sleeps in WFI with the interrupt or stop request still pending,
which stalls guest interrupts indefinitely and hangs pause_all_vcpus() on
guest reset.

Always send the signal instead of relying on the dedup, and bound the
otherwise open-ended pselect() so that a kick lost for any other reason
degrades to a short delay rather than an unbounded sleep.

Assisted-by: Claude:claude-fable-5
2026-07-28 10:04:32 -07:00
osy 263d9536fa spice-display: avoid sending duplicate scanout
If the same surface + size is sent, ignore sending scanout to the client.

Guests using flip-model presentation issue a set_scanout for every frame
with a different backing buffer of the same dimensions. The IOSurface and
its ID are unchanged in that case, so re-announcing it also closes the
previous pipe and trips the client's stale-POLLHUP protection. Frame
content is delivered by gl_draw regardless.

Assisted-by: Claude:claude-fable-5
2026-07-28 10:04:14 -07:00
osy 833c112710 ui/cocoa: don't report QEMU-initiated window resizes as ui_info
When the guest changes its display mode, the console resize runs
resizeWindow, which keeps the current window size and only fixes the
aspect ratio. The windowDidResize delegate then echoed that stale size
to the guest via dpy_set_ui_info, asking it to switch back to the old
resolution; a guest resolution agent that honors the request stomps the
mode the application just set, about a second later (the dpy_set_ui_info
debounce).

Flag frame changes made by resizeWindow itself and skip the ui_info
update for them. Only user or window-manager resizes are forwarded as
resolution requests.

Assisted-by: Claude:claude-fable-5
2026-07-27 00:28:09 -07:00
40 changed files with 2132 additions and 535 deletions

No files matched your search

+54
View File
@@ -48,6 +48,10 @@
*/
#include "qemu/osdep.h"
#ifdef HOST_X86_64
#include <mach/mach.h>
#include <mach/mach_vm.h>
#endif
#include "qemu/error-report.h"
#include "qemu/main-loop.h"
#include "exec/address-spaces.h"
@@ -61,6 +65,7 @@
#include "system/hvf.h"
#include "system/hvf_int.h"
#include "system/runstate.h"
#include "system/system.h"
#include "qemu/guest-random.h"
#include "hw/boards.h"
@@ -135,6 +140,40 @@ hvf_slot *hvf_find_overlap_slot(uint64_t start, uint64_t size)
return NULL;
}
#ifdef HOST_X86_64
/*
* Intel Hypervisor.framework refuses hv_vm_map() with HV_MEMORY_EXEC when the
* host mapping's maximum protection lacks execute. virtio-gpu blobs shared
* from the render server are mapped read/write only, so check the host
* entries backing [mem, mem + size) and leave EXEC out for such memory.
*/
static bool hvf_host_mem_executable(void *mem, uint64_t size)
{
mach_vm_address_t addr = (mach_vm_address_t)mem;
mach_vm_address_t end = addr + size;
while (addr < end) {
mach_vm_address_t start = addr;
mach_vm_size_t len = 0;
natural_t depth = 1;
vm_region_submap_info_data_64_t info;
mach_msg_type_number_t count = VM_REGION_SUBMAP_INFO_COUNT_64;
if (mach_vm_region_recurse(mach_task_self(), &start, &len, &depth,
(vm_region_recurse_info_t)&info,
&count) != KERN_SUCCESS ||
start > addr) {
return true;
}
if (!(info.max_protection & VM_PROT_EXECUTE)) {
return false;
}
addr = start + len;
}
return true;
}
#endif
static int do_hvf_set_memory(hvf_slot *slot, hv_memory_flags_t flags)
{
hvf_mac_slot *macslot;
@@ -157,6 +196,21 @@ static int do_hvf_set_memory(hvf_slot *slot, hv_memory_flags_t flags)
macslot->present = 1;
macslot->gpa_start = slot->start;
macslot->size = slot->size;
#ifdef HOST_X86_64
if (!hvf_host_mem_executable(slot->mem, slot->size)) {
flags &= ~HV_MEMORY_EXEC;
}
#endif
/*
* mlockall() returns ENOSYS on macOS, and left alone the host compresses
* guest RAM until every touch faults, so honour -overcommit mem-lock=on
* for each RAM mapping.
*/
if (should_mlock(mlock_state) && memory_region_is_ram(slot->region) &&
mlock(slot->mem, slot->size) < 0) {
error_report_once("hvf: mlock of guest RAM failed: %s",
strerror(errno));
}
ret = hv_vm_map(slot->mem, slot->start, slot->size, flags);
assert_hvf_ok(ret);
return 0;
+18
View File
@@ -42,6 +42,7 @@ typedef struct coreaudioVoiceOut {
UInt32 audioDevicePropertyBufferFrameSize;
AudioDeviceIOProcID ioprocid;
bool enabled;
bool primed;
} coreaudioVoiceOut;
static const AudioObjectPropertyAddress voice_addr = {
@@ -325,8 +326,22 @@ static OSStatus audioDeviceIOProc(
frameCount = core->audioDevicePropertyBufferFrameSize;
pending_frames = hw->pending_emul / hw->info.bytes_per_frame;
/*
* Jitter buffer: start playing only once half of the ring is queued, and
* prime again after an underrun. Without the cushion, playback runs with
* about one buffer queued, and every late audio timer (the main loop also
* runs the vCPUs' I/O and virgl) costs a whole buffer of silence.
*/
if (!core->primed && pending_frames < hw->samples / 2) {
inInputTime = 0;
coreaudio_buf_unlock (core, "audioDeviceIOProc(priming)");
return 0;
}
core->primed = true;
/* if there are not enough samples, set signal and return */
if (pending_frames < frameCount) {
core->primed = false;
inInputTime = 0;
coreaudio_buf_unlock (core, "audioDeviceIOProc(empty)");
return 0;
@@ -642,6 +657,9 @@ static void coreaudio_enable_out(HWVoiceOut *hw, bool enable)
coreaudioVoiceOut *core = (coreaudioVoiceOut *) hw;
core->enabled = enable;
if (enable) {
core->primed = false;
}
update_device_playback_state(core);
}
+5 -2
View File
@@ -145,8 +145,11 @@ highmem-mmio
The default is ``on``.
highmem-mmio-size
Set the high memory region size for PCI MMIO. Must be a power of 2 and
greater than or equal to the default size (512G).
Set the high memory region size for PCI MMIO. Must be a power of 2 and at
least 1G. The default is 512G. If the requested window does not fit in the
guest physical address space, it is shrunk to the largest power of 2 that
does (but no smaller than 1G) and a warning is emitted; if even that does
not fit, the window is disabled.
gic-version
Specify the version of the Generic Interrupt Controller (GIC) to provide.
+89 -6
View File
@@ -197,6 +197,8 @@ static const MemMapEntry base_memmap[] = {
/* Update the docs for highmem-mmio-size when changing this default */
#define DEFAULT_HIGH_PCIE_MMIO_SIZE_GB 512
#define DEFAULT_HIGH_PCIE_MMIO_SIZE (DEFAULT_HIGH_PCIE_MMIO_SIZE_GB * GiB)
/* Smallest window we will auto-shrink to, or accept from the user */
#define VIRT_HIGH_PCIE_MMIO_MIN_SIZE (1 * GiB)
/*
* Highmem IO Regions: This memory map is floating, located after the RAM.
@@ -1812,6 +1814,40 @@ static inline bool *virt_get_high_memmap_enabled(VirtMachineState *vms,
return enabled_array[index - VIRT_LOWMEMMAP_LAST];
}
static inline const char *virt_high_memmap_name(int index)
{
static const char * const names[] = {
"GIC redistributor",
"PCIe ECAM",
"PCIe MMIO",
};
assert(ARRAY_SIZE(extended_memmap) - VIRT_LOWMEMMAP_LAST ==
ARRAY_SIZE(names));
assert(index - VIRT_LOWMEMMAP_LAST < ARRAY_SIZE(names));
return names[index - VIRT_LOWMEMMAP_LAST];
}
/*
* Return the first address above the high memmap if it were laid out
* starting at @base, assuming every region fits at full size. Mirrors the
* placement rules of virt_set_high_memmap().
*/
static hwaddr virt_high_memmap_end(VirtMachineState *vms, hwaddr base)
{
int i;
for (i = VIRT_LOWMEMMAP_LAST; i < ARRAY_SIZE(extended_memmap); i++) {
if (vms->highmem_compact && !*virt_get_high_memmap_enabled(vms, i)) {
continue;
}
base = ROUND_UP(base, extended_memmap[i].size) + extended_memmap[i].size;
}
return base;
}
static void virt_set_high_memmap(VirtMachineState *vms,
hwaddr base, int pa_bits)
{
@@ -1824,6 +1860,33 @@ static void virt_set_high_memmap(VirtMachineState *vms,
region_base = ROUND_UP(base, extended_memmap[i].size);
region_size = extended_memmap[i].size;
/*
* The high PCIe MMIO window is the only configurable high region
* and by far the largest. If it doesn't fit (e.g. in a 36-bit PA
* space), shrink it to the largest power of two that does rather
* than dropping it: without it, no 64-bit BAR too large for the
* 32-bit window can ever be placed.
*/
if (i == VIRT_HIGH_PCIE_MMIO && *region_enabled && vms->highmem) {
while (region_size > VIRT_HIGH_PCIE_MMIO_MIN_SIZE &&
region_base + region_size > BIT_ULL(pa_bits)) {
region_size /= 2;
region_base = ROUND_UP(base, region_size);
}
if (region_base + region_size > BIT_ULL(pa_bits)) {
/* Not even the minimum fits; restore and disable below */
region_size = extended_memmap[i].size;
region_base = ROUND_UP(base, region_size);
} else if (region_size != extended_memmap[i].size) {
g_autofree char *from = size_to_str(extended_memmap[i].size);
g_autofree char *to = size_to_str(region_size);
warn_report("high PCIe MMIO window shrunk from %s to %s to fit "
"in a %d-bit physical address space", from, to,
pa_bits);
}
}
vms->memmap[i].base = region_base;
vms->memmap[i].size = region_size;
@@ -1836,6 +1899,12 @@ static void virt_set_high_memmap(VirtMachineState *vms,
* For each device that doesn't fit, disable it.
*/
fits = (region_base + region_size) <= BIT_ULL(pa_bits);
/* !highmem disables these on purpose, so keep quiet about it */
if (*region_enabled && !fits && vms->highmem) {
warn_report("high %s region does not fit in a %d-bit physical "
"address space and has been disabled",
virt_high_memmap_name(i), pa_bits);
}
*region_enabled &= fits;
if (vms->highmem_compact && !*region_enabled) {
continue;
@@ -1851,7 +1920,7 @@ static void virt_set_high_memmap(VirtMachineState *vms,
static void virt_set_memmap(VirtMachineState *vms, int pa_bits)
{
MachineState *ms = MACHINE(vms);
hwaddr base, device_memory_base, device_memory_size, memtop;
hwaddr base, device_memory_base, device_memory_size, memtop, legacy_base;
int i;
vms->memmap = extended_memmap;
@@ -1900,8 +1969,18 @@ static void virt_set_memmap(VirtMachineState *vms, int pa_bits)
error_report("maxmem/slots too huge");
exit(EXIT_FAILURE);
}
if (base < vms->memmap[VIRT_MEM].base + LEGACY_RAMLIMIT_BYTES) {
base = vms->memmap[VIRT_MEM].base + LEGACY_RAMLIMIT_BYTES;
/*
* Pin the high IO region at 256GiB so a VM with less than 255GiB of
* RAM keeps the legacy memory map. Skip that floor when the high
* regions cannot fit there in the PA space, as they would all be
* disabled and the guest left with no 64-bit MMIO window. !highmem
* keeps the floor: disabling them is the point of that option.
*/
legacy_base = vms->memmap[VIRT_MEM].base + LEGACY_RAMLIMIT_BYTES;
if (base < legacy_base &&
(!vms->highmem ||
virt_high_memmap_end(vms, legacy_base) <= BIT_ULL(pa_bits))) {
base = legacy_base;
}
/* We know for sure that at least the memory fits in the PA space */
@@ -2594,10 +2673,14 @@ static void virt_set_highmem_mmio_size(Object *obj, Visitor *v,
return;
}
if (size < DEFAULT_HIGH_PCIE_MMIO_SIZE) {
char *sz = size_to_str(DEFAULT_HIGH_PCIE_MMIO_SIZE);
/*
* Windows smaller than the default are allowed: a host with a small
* PA space cannot fit the default anywhere.
*/
if (size < VIRT_HIGH_PCIE_MMIO_MIN_SIZE) {
char *sz = size_to_str(VIRT_HIGH_PCIE_MMIO_MIN_SIZE);
error_setg(errp, "highmem-mmio-size cannot be set to a lower value "
"than the default (%s)", sz);
"than %s", sz);
g_free(sz);
return;
}
+79 -5
View File
@@ -172,6 +172,11 @@ struct HDAAudioStream {
int64_t wpos;
QEMUTimer *buft;
int64_t buft_start;
/* output pacing, see hda_audio_output_pace() */
bool primed;
int64_t run_ns;
int64_t pace_ns;
int64_t budget;
};
struct HDAAudioState {
@@ -188,6 +193,7 @@ struct HDAAudioState {
uint32_t debug;
bool mixer;
bool use_timer;
bool pace;
};
static inline uint32_t hda_bytes_per_second(HDAAudioStream *st)
@@ -287,6 +293,64 @@ static void hda_audio_input_cb(void *opaque, int avail)
hda_timer_sync_adjust(st, -((wpos - rpos) - (B_SIZE >> 1)));
}
/*
* Bounded catch-up after a stalled main loop.
*
* The output timer takes guest audio by the clock. When the main loop stalls
* for S ms (virgl, or a Mac with every core busy), the backend keeps playing
* from its own ring, and the next timer runs take the S of guest audio that
* is owed. That is right while the ring here can hold it. After a longer
* stall it cannot: the guest saw its DMA position jump and under-ran unless
* its own buffer was larger, and the sync corrections pulled faster still.
*
* Once the stream has run for HDA_PACE_PRIME, the guest's audio is taken at
* most 1/32 faster than real time plus a burst of HDA_PACE_BURST, the whole
* ring. A debt beyond the burst is forgiven down to HDA_PACE_RESUME (the
* guest's clock pauses during the stall) and the backend's ring covers the
* stall. pace=off restores the old behaviour.
* Based on OmacVM's qemu-hda-no-catch-up.patch (MIT).
*
* The burst must not be smaller than a stall that comes often. Forgiven time
* comes back only at 1/32, so a main loop that is late by more than the burst
* over and over (a frame of virgl work, coalesced timers) plays the guest's
* audio slow.
*/
#define HDA_PACE_BURST B_SIZE
#define HDA_PACE_RESUME (B_SIZE / 8)
#define HDA_PACE_PRIME (250 * SCALE_MS)
static int64_t hda_audio_output_pace(HDAAudioStream *st, int64_t now,
int64_t wanted, int64_t to_transfer)
{
int64_t bps = hda_bytes_per_second(st);
if (!st->state->pace || bps <= 0) {
return to_transfer;
}
if (!st->primed) {
if (now - st->run_ns < HDA_PACE_PRIME) {
st->pace_ns = now;
return to_transfer;
}
st->primed = true;
st->budget = HDA_PACE_BURST;
}
if (st->pace_ns && now > st->pace_ns) {
st->budget += muldiv64(now - st->pace_ns, bps + bps / 32,
NANOSECONDS_PER_SECOND);
}
st->pace_ns = now;
st->budget = MIN(st->budget, (int64_t)HDA_PACE_BURST);
if (wanted - st->wpos > (int64_t)HDA_PACE_BURST) {
int64_t excess = wanted - st->wpos - HDA_PACE_RESUME;
st->buft_start += muldiv64(excess, NANOSECONDS_PER_SECOND, bps);
st->budget = MIN(st->budget, (int64_t)HDA_PACE_RESUME);
trace_hda_audio_pace_forgive(st->node->name, excess);
}
return MIN(to_transfer, st->budget & -4);
}
static void hda_audio_output_timer(void *opaque)
{
HDAAudioStream *st = opaque;
@@ -313,6 +377,7 @@ static void hda_audio_output_timer(void *opaque)
}
int64_t to_transfer = MIN(B_SIZE - (wpos - rpos), wanted_wpos - wpos);
to_transfer = hda_audio_output_pace(st, now, wanted_wpos, to_transfer);
while (to_transfer) {
uint32_t start = (wpos & B_MASK);
uint32_t chunk = MIN(B_SIZE - start, to_transfer);
@@ -324,6 +389,7 @@ static void hda_audio_output_timer(void *opaque)
wpos += chunk;
to_transfer -= chunk;
st->wpos += chunk;
st->budget -= chunk;
}
out_timer:
@@ -343,12 +409,15 @@ static void hda_audio_output_cb(void *opaque, int avail)
int64_t to_transfer = MIN(wpos - rpos, avail);
if (wpos - rpos == B_SIZE) {
/* drop buffer, reset timer adjust */
st->rpos = 0;
st->wpos = 0;
st->buft_start = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
/*
* Keep the queued samples (dropping them is an audible gap) and only
* discard the elapsed-time catch-up debt.
* Based on OmacVM's qemu-hda-full-ring-recovery.patch (MIT).
*/
int64_t now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
st->buft_start = now - muldiv64(wpos, NANOSECONDS_PER_SECOND,
hda_bytes_per_second(st));
trace_hda_audio_overrun(st->node->name);
return;
}
while (to_transfer) {
@@ -434,6 +503,10 @@ static void hda_audio_set_running(HDAAudioStream *st, bool running)
st->rpos = 0;
st->wpos = 0;
st->buft_start = now;
st->primed = false;
st->run_ns = now;
st->pace_ns = 0;
st->budget = 0;
timer_mod_anticipate_ns(st->buft, now + HDA_TIMER_TICKS);
} else {
timer_del(st->buft);
@@ -862,6 +935,7 @@ static const Property hda_audio_properties[] = {
DEFINE_PROP_UINT32("debug", HDAAudioState, debug, 0),
DEFINE_PROP_BOOL("mixer", HDAAudioState, mixer, true),
DEFINE_PROP_BOOL("use-timer", HDAAudioState, use_timer, true),
DEFINE_PROP_BOOL("pace", HDAAudioState, pace, true),
};
static void hda_audio_init_output(HDACodecDevice *hda, Error **errp)
+204 -88
View File
@@ -64,26 +64,135 @@
/* Audio */
static const char *s_spk = "screamer";
static void pmac_screamer_tx_transfer(ScreamerState *s)
/*
* The real chip pulls TX samples from DBDMA at the codec sample rate through
* a small FIFO, so OUTPUT descriptors complete in real time. Emulate that:
* TX DMA may consume s->rate frames per second of virtual time, plus up to
* SCREAMER_FIFO_FRAMES of lead. Without this a guest ring that fits in our
* buffer completes (and raises its interrupts) almost instantly, which is
* what the Mac OS 9 driver does with VM off (>= 1 GB RAM): one 4 KiB page.
*/
#define SCREAMER_FIFO_FRAMES 128
#define SCREAMER_TX_TICK_NS (1 * SCALE_MS)
/*
* Within a transfer, a late tick may catch up on frames that are already
* due, up to this bound so one long host stall cannot drain a guest ring.
*/
#define SCREAMER_TX_MAX_CREDIT (2 * SCREAMER_FIFO_FRAMES)
/* Accrue TX credit for the virtual time elapsed, up to @limit frames */
static void screamer_tx_credit_update(ScreamerState *s, uint32_t limit)
{
int64_t now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
uint64_t frames;
if (now <= s->tx_last_ns) {
/* The virtual clock went back (loadvm): restart the accounting */
s->tx_last_ns = now;
return;
}
frames = muldiv64(now - s->tx_last_ns, s->rate, NANOSECONDS_PER_SECOND);
s->tx_last_ns += muldiv64(frames, NANOSECONDS_PER_SECOND, s->rate);
if (s->tx_credit < limit) {
s->tx_credit = MIN(s->tx_credit + frames, limit);
}
}
/* Copy guest frames into the ring; drop the oldest if the host lags */
static void screamer_ring_write(ScreamerState *s, hwaddr addr, uint32_t frames)
{
while (frames) {
uint32_t n = MIN(frames, s->samples - s->wpos);
MemTxResult res;
res = dma_memory_read(&address_space_memory, addr,
&s->mixbuf[s->wpos << s->shift], n << s->shift,
MEMTXATTRS_UNSPECIFIED);
if (res != MEMTX_OK) {
qemu_log_mask(LOG_GUEST_ERROR,
"screamer: TX DMA read failed at 0x%" HWADDR_PRIx
"\n", addr);
}
s->wpos = (s->wpos + n) % s->samples;
s->fill += n;
addr += n << s->shift;
frames -= n;
}
if (s->fill > s->samples) {
SCREAMER_DPRINTF("TX ring overrun, dropped %d frames\n",
s->fill - s->samples);
s->rpos = s->wpos;
s->fill = s->samples;
}
}
/* Write back res_count and xfer_status of the current command */
static void screamer_dma_update_status(DBDMA_channel *ch, uint32_t len)
{
dbdma_cmd *current = &ch->current;
current->xfer_status = cpu_to_le16(ch->regs[DBDMA_STATUS]);
current->res_count = cpu_to_le16(len);
dma_memory_write(&address_space_memory,
ch->regs[DBDMA_CMDPTR_LO] +
offsetof(dbdma_cmd, res_count),
&current->res_count,
sizeof(current->res_count) +
sizeof(current->xfer_status),
MEMTXATTRS_UNSPECIFIED);
}
/* Is the flush caused by the guest clearing RUN? */
static bool screamer_dma_stopping(DBDMA_channel *ch)
{
return ((ch->regs[DBDMA_CONTROL] >> 16) & RUN) &&
!(ch->regs[DBDMA_CONTROL] & RUN);
}
static void pmac_screamer_tx_transfer(ScreamerState *s, uint32_t limit)
{
DBDMA_io *io = &s->io;
int samples;
uint32_t frames;
samples = MIN(io->len >> s->shift, s->samples - s->wpos);
dma_memory_read(&address_space_memory, io->addr,
&s->mixbuf[s->wpos << s->shift], samples << s->shift,
MEMTXATTRS_UNSPECIFIED);
screamer_tx_credit_update(s, limit);
frames = MIN(io->len >> s->shift, s->tx_credit);
SCREAMER_DPRINTF("DMA actually transferred 0x%x, wpos is %d\n", samples << s->shift, s->wpos);
if (frames) {
screamer_ring_write(s, io->addr, frames);
io->addr += frames << s->shift;
io->len -= frames << s->shift;
s->tx_credit -= frames;
io->addr += (samples << s->shift);
io->len -= (samples << s->shift);
s->wpos += samples;
/* The frame counter counts frames sent to the codec */
s->regs[FRAME_CNT_REG] += frames;
SCREAMER_DPRINTF("DMA actually transferred 0x%x\n",
frames << s->shift);
}
/* A trailing partial frame can never be consumed; drop it */
if (io->len < (1 << s->shift)) {
io->len = 0;
}
/* Continue DBDMA if we have completed the transfer, otherwise defer */
if (io->len == 0) {
SCREAMER_DPRINTF("-> End of transfer\n");
io->dma_end(io);
} else if (!timer_pending(s->tx_timer)) {
timer_mod(s->tx_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
SCREAMER_TX_TICK_NS);
}
}
static void screamer_tx_timer_cb(void *opaque)
{
ScreamerState *s = opaque;
if (s->io.len) {
SCREAMER_DPRINTF("Continue deferred transfer\n");
pmac_screamer_tx_transfer(s, SCREAMER_TX_MAX_CREDIT);
}
}
@@ -95,15 +204,13 @@ static void pmac_screamer_tx(DBDMA_io *io)
" len: %x\n", io->addr, io->len);
memcpy(&s->io, io, sizeof(DBDMA_io));
//if (s->wpos + (s->io.len >> s->shift) > s->samples) {
// return;
//}
pmac_screamer_tx_transfer(s);
/* Time the channel spent idle only fills the FIFO */
pmac_screamer_tx_transfer(s, SCREAMER_FIFO_FRAMES);
}
static void pmac_screamer_tx_flush(DBDMA_io *io)
{
ScreamerState *s = io->opaque;
DBDMA_channel *ch = io->channel;
dbdma_cmd *current = &ch->current;
uint16_t cmd;
@@ -113,59 +220,86 @@ static void pmac_screamer_tx_flush(DBDMA_io *io)
cmd = le16_to_cpu(current->command) & COMMAND_MASK;
if (cmd == OUTPUT_MORE || cmd == OUTPUT_LAST ||
cmd == INPUT_MORE || cmd == INPUT_LAST) {
current->xfer_status = cpu_to_le16(ch->regs[DBDMA_STATUS]);
current->res_count = cpu_to_le16(io->len);
dma_memory_write(&address_space_memory, ch->regs[DBDMA_CMDPTR_LO],
&ch->current, sizeof(dbdma_cmd),
MEMTXATTRS_UNSPECIFIED);
screamer_dma_update_status(ch, io->len);
}
#endif
ch->io.processing = false;
/*
* The guest is stopping the channel: abandon any deferred transfer.
* Otherwise (PAUSE, FLUSH) let it finish: it completes through
* dma_end, and clearing processing now would make DBDMA restart the
* same descriptor and send its frames twice.
*/
if (screamer_dma_stopping(ch)) {
s->io.len = 0;
s->tx_credit = MIN(s->tx_credit, SCREAMER_FIFO_FRAMES);
timer_del(s->tx_timer);
ch->io.processing = false;
}
cmd = le16_to_cpu(current->command) & COMMAND_MASK;
if (cmd == INPUT_MORE || cmd == INPUT_LAST) {
current->xfer_status = cpu_to_le16(ch->regs[DBDMA_STATUS]);
current->res_count = cpu_to_le16(io->len);
dma_memory_write(&address_space_memory, ch->regs[DBDMA_CMDPTR_LO],
&ch->current, sizeof(dbdma_cmd),
MEMTXATTRS_UNSPECIFIED);
screamer_dma_update_status(ch, io->len);
}
}
/*
* There is no capture source: RX DMA receives silence. Like real hardware,
* an INPUT descriptor completes only after its frames have been sampled,
* i.e. after len / frame size / rate seconds.
*/
static void screamer_rx_timer_cb(void *opaque)
{
ScreamerState *s = opaque;
DBDMA_io *io = &s->rx_io;
/*
* Only armed for a live transfer (flush and reset delete it); a
* zero-length INPUT still has to complete.
*/
if (dma_memory_set(&address_space_memory, io->addr, 0, io->len,
MEMTXATTRS_UNSPECIFIED) != MEMTX_OK) {
qemu_log_mask(LOG_GUEST_ERROR,
"screamer: RX DMA write failed at 0x%" HWADDR_PRIx
"\n", io->addr);
}
io->addr += io->len;
io->len = 0;
io->dma_end(io);
}
static void pmac_screamer_rx(DBDMA_io *io)
{
ScreamerState *s = io->opaque;
uint64_t frames = io->len >> s->shift;
SCREAMER_DPRINTF("DMA RX transfer: addr %" HWADDR_PRIx
" len: %x\n", io->addr, io->len);
//ScreamerState *s = io->opaque;
DBDMA_channel *ch = io->channel;
/* FIXME: stop channel after updating with status to stop MacOS 9 freezing */
ch->regs[DBDMA_STATUS] &= ~RUN;
io->dma_end(io);
memcpy(&s->rx_io, io, sizeof(DBDMA_io));
timer_mod(s->rx_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
muldiv64(frames, NANOSECONDS_PER_SECOND, s->rate));
}
static void pmac_screamer_rx_flush(DBDMA_io *io)
{
ScreamerState *s = io->opaque;
DBDMA_channel *ch = io->channel;
dbdma_cmd *current = &ch->current;
uint16_t cmd;
SCREAMER_DPRINTF("DMA RX flush!\n");
/* The guest is stopping the channel: abandon the pending transfer */
if (screamer_dma_stopping(ch)) {
s->rx_io.len = 0;
timer_del(s->rx_timer);
ch->io.processing = false;
}
#if 1
cmd = le16_to_cpu(current->command) & COMMAND_MASK;
if (cmd == INPUT_MORE || cmd == INPUT_LAST) {
current->xfer_status = cpu_to_le16(ch->regs[DBDMA_STATUS]);
current->res_count = cpu_to_le16(io->len);
dma_memory_write(&address_space_memory, ch->regs[DBDMA_CMDPTR_LO],
&ch->current, sizeof(dbdma_cmd),
MEMTXATTRS_UNSPECIFIED);
screamer_dma_update_status(ch, io->len);
}
#endif
}
@@ -182,51 +316,22 @@ void macio_screamer_register_dma(ScreamerState *s, void *dbdma, int txchannel, i
static void screamerspk_callback(void *opaque, int free_b)
{
ScreamerState *s = opaque;
DBDMA_io *io = &s->io;
int samples, generated;
if (free_b == 0) {
return;
}
while (s->fill && free_b >= (1 << s->shift)) {
uint32_t n = MIN(MIN(free_b >> s->shift, s->fill),
s->samples - s->rpos);
size_t written;
if (s->wpos - s->rpos == 0) {
return;
}
samples = MIN(s->samples, free_b >> s->shift);
generated = MIN(samples, s->wpos - s->rpos);
AUD_write(s->voice, s->mixbuf + (uintptr_t)(s->rpos << s->shift),
generated << s->shift);
SCREAMER_DPRINTF(" - generated %d, wpos %d, rpos %d\n", generated, s->wpos, s->rpos);
s->regs[FRAME_CNT_REG] += generated;
s->rpos += generated;
if (s->rpos < s->wpos) {
return;
}
s->wpos = 0;
s->rpos = 0;
if (io->len) {
DBDMA_channel *ch = io->channel;
uint32_t status = ch->regs[DBDMA_STATUS];
SCREAMER_DPRINTF("Continue deferred transfer\n");
/* Disable channel so we only complete the current transfer */
ch->regs[DBDMA_STATUS] &= ~RUN;
/* Perform deferred transfer */
pmac_screamer_tx_transfer(s);
/* Re-enable channel */
ch->regs[DBDMA_STATUS] = status;
/* Kick channel to continue */
DBDMA_kick(container_of(ch, DBDMAState, channels[ch->channel]));
written = AUD_write(s->voice, &s->mixbuf[s->rpos << s->shift],
n << s->shift) >> s->shift;
SCREAMER_DPRINTF(" - generated %zu, fill %d, rpos %d\n", written,
s->fill, s->rpos);
if (!written) {
break;
}
s->rpos = (s->rpos + written) % s->samples;
s->fill -= written;
free_b -= written << s->shift;
}
}
@@ -241,10 +346,6 @@ static void screamer_update_settings(ScreamerState *s)
return;
}
s->shift = 2;
s->samples = AUD_get_buffer_size_out(s->voice) >> s->shift;
s->mixbuf = g_malloc0(s->samples << s->shift);
AUD_set_active_out(s->voice, true);
}
@@ -275,6 +376,15 @@ static void screamer_reset(DeviceState *dev)
s->bpos = 0;
s->ppos = 0;
timer_del(s->tx_timer);
timer_del(s->rx_timer);
memset(&s->rx_io, 0, sizeof(DBDMA_io));
s->tx_last_ns = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
s->tx_credit = 0;
s->wpos = 0;
s->rpos = 0;
s->fill = 0;
return;
}
@@ -286,6 +396,12 @@ static void screamer_realizefn(DeviceState *dev, Error **errp)
return;
}
s->shift = 2;
s->samples = SCREAMER_BUFFER_SIZE >> s->shift;
s->mixbuf = g_malloc0(SCREAMER_BUFFER_SIZE);
s->tx_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, screamer_tx_timer_cb, s);
s->rx_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, screamer_rx_timer_cb, s);
s->rate = 44100;
screamer_update_settings(s);
}
+1
View File
@@ -22,6 +22,7 @@ hda_audio_running(const char *stream, int nr, bool running) "st %s, nr %d, run %
hda_audio_format(const char *stream, int chan, const char *fmt, int freq) "st %s, %d x %s @ %d Hz"
hda_audio_adjust(const char *stream, int pos) "st %s, pos %d"
hda_audio_overrun(const char *stream) "st %s"
hda_audio_pace_forgive(const char *stream, int64_t bytes) "st %s forgiven %" PRId64 " bytes"
#via-ac97.c
via_ac97_codec_write(uint8_t addr, uint16_t val) "0x%x <- 0x%x"
+24 -1
View File
@@ -28,6 +28,7 @@
#include <mach/mach.h>
#include <mach/mach_vm.h>
#include <dispatch/dispatch.h>
#include <dlfcn.h>
#import <ParavirtualizedGraphics/ParavirtualizedGraphics.h>
@@ -740,6 +741,24 @@ static id<MTLDevice> copy_suitable_metal_device(void)
return dev;
}
/*
* PGNewDeviceWithDescriptor is obsoleted in the macOS 27 SDK and no longer
* exported for linking. Use the replacement where available and look up the
* old symbol at runtime on older hosts. Both return a retained object.
*/
static id<PGDevice> apple_gfx_new_device(PGDeviceDescriptor *desc)
{
id<PGDevice> (*new_device)(PGDeviceDescriptor *);
#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 150200
if (@available(macOS 15.2, *)) {
return PGCreateDeviceWithDescriptor(desc);
}
#endif
new_device = dlsym(RTLD_DEFAULT, "PGNewDeviceWithDescriptor");
return new_device ? new_device(desc) : nil;
}
bool apple_gfx_common_realize(AppleGFXState *s, DeviceState *dev,
PGDeviceDescriptor *desc, Error **errp)
{
@@ -767,7 +786,11 @@ bool apple_gfx_common_realize(AppleGFXState *s, DeviceState *dev,
s->cursor_show = true;
s->pgdev = PGNewDeviceWithDescriptor(desc);
s->pgdev = apple_gfx_new_device(desc);
if (!s->pgdev) {
error_setg(errp, "Failed to create ParavirtualizedGraphics device");
return false;
}
disp_desc = apple_gfx_prepare_display_descriptor(s);
/*
+10 -6
View File
@@ -142,13 +142,17 @@ static void edid_fill_modes(uint8_t *edid, uint8_t *xtra3, uint8_t *dta,
if (mode->byte) {
edid[mode->byte] |= (1 << mode->bit);
} else if (std < 54) {
rc = edid_std_mode(edid + std, mode->xres, mode->yres);
if (rc == 0) {
std += 2;
} else {
if (std < 54) {
rc = edid_std_mode(edid + std, mode->xres, mode->yres);
if (rc == 0) {
std += 2;
}
}
/* a mode with a standard timing too: not every guest reads those */
if (mode->xtra3 && xtra3) {
xtra3[mode->xtra3] |= (1 << mode->bit);
}
} else if (mode->xtra3 && xtra3) {
xtra3[mode->xtra3] |= (1 << mode->bit);
}
if (dta && mode->dta) {
+1
View File
@@ -27,6 +27,7 @@ vmware_verify_rect_surface_bound_exceeded(const char *name, const char *componen
vmware_update_rect_delayed_flush(void) "display update FIFO full - forcing flush"
# virtio-gpu-base.c
virtio_gpu_hostmem_scratch(bool mapped) "mapped=%d"
virtio_gpu_features(bool virgl) "virgl %d"
# virtio-gpu-3d.c
+9 -1
View File
@@ -96,7 +96,9 @@ static void virtio_gpu_ui_info(void *opaque, uint32_t idx, QemuUIInfo *info)
g->req_state[idx].x = info->xoff;
g->req_state[idx].y = info->yoff;
g->req_state[idx].refresh_rate = info->refresh_rate;
/* displays such as SPICE report no rate */
g->req_state[idx].refresh_rate = info->refresh_rate ? info->refresh_rate
: g->conf.refresh_rate;
g->req_state[idx].width = info->width;
g->req_state[idx].height = info->height;
g->req_state[idx].width_mm = info->width_mm;
@@ -182,6 +184,11 @@ virtio_gpu_base_device_realize(DeviceState *qdev,
return false;
}
if (g->conf.refresh_rate && g->conf.refresh_rate < 1000) {
error_setg(errp, "refresh_rate is in mHz, e.g. 60000 for 60 Hz");
return false;
}
if (virtio_gpu_virgl_enabled(g->conf)) {
error_setg(&g->migration_blocker, "virgl is not yet migratable");
if (migrate_add_blocker(&g->migration_blocker, errp) < 0) {
@@ -209,6 +216,7 @@ virtio_gpu_base_device_realize(DeviceState *qdev,
g->hw_ops = &virtio_gpu_ops;
for (i = 0; i < g->conf.max_outputs; i++) {
g->req_state[i].refresh_rate = g->conf.refresh_rate;
g->scanout[i].con =
graphic_console_init(DEVICE(g), i, &virtio_gpu_ops, g);
}
+6 -4
View File
@@ -90,10 +90,7 @@ static void virtio_gpu_gl_handle_ctrl(VirtIODevice *vdev, VirtQueue *vq)
cmd = virtqueue_pop(vq, sizeof(struct virtio_gpu_ctrl_command));
while (cmd) {
cmd->vq = vq;
cmd->error = 0;
cmd->finished = false;
cmd->suspended = false;
virtio_gpu_ctrl_cmd_init(cmd, vq);
QTAILQ_INSERT_TAIL(&g->cmdq, cmd, next);
cmd = virtqueue_pop(vq, sizeof(struct virtio_gpu_ctrl_command));
}
@@ -172,6 +169,11 @@ static void virtio_gpu_gl_device_unrealize(DeviceState *qdev)
if (gl->renderer_state >= RS_INITED) {
#if VIRGL_VERSION_MAJOR >= 1
qemu_bh_delete(gl->cmdq_resume_bh);
if (gl->async_fence_bh) {
virtio_gpu_virgl_reset_async_fences(g);
qemu_bh_delete(gl->async_fence_bh);
}
#endif
if (virtio_gpu_stats_enabled(g->parent_obj.conf)) {
timer_free(gl->print_stats);
+1 -3
View File
@@ -1066,9 +1066,7 @@ static void virtio_gpu_rutabaga_handle_ctrl(VirtIODevice *vdev, VirtQueue *vq)
cmd = virtqueue_pop(vq, sizeof(struct virtio_gpu_ctrl_command));
while (cmd) {
cmd->vq = vq;
cmd->error = 0;
cmd->finished = false;
virtio_gpu_ctrl_cmd_init(cmd, vq);
QTAILQ_INSERT_TAIL(&g->cmdq, cmd, next);
cmd = virtqueue_pop(vq, sizeof(struct virtio_gpu_ctrl_command));
}
+415 -77
View File
@@ -27,9 +27,32 @@
#define NATIVE_HANDLE_SUPPORT_VERSION (1)
/*
* VIRGL_CHECK_VERSION available since libvirglrenderer 1.0.1 and was fixed
* in 1.1.0. Undefine bugged version of the macro and provide our own.
*/
#if defined(VIRGL_CHECK_VERSION) && \
VIRGL_VERSION_MAJOR == 1 && VIRGL_VERSION_MINOR < 1
#undef VIRGL_CHECK_VERSION
#endif
#ifndef VIRGL_CHECK_VERSION
#define VIRGL_CHECK_VERSION(major, minor, micro) \
(VIRGL_VERSION_MAJOR > (major) || \
VIRGL_VERSION_MAJOR == (major) && VIRGL_VERSION_MINOR > (minor) || \
VIRGL_VERSION_MAJOR == (major) && VIRGL_VERSION_MINOR == (minor) && \
VIRGL_VERSION_MICRO >= (micro))
#endif
struct virtio_gpu_virgl_resource {
struct virtio_gpu_simple_resource base;
MemoryRegion *mr;
/* RESOURCE_UNREF that arrived while the blob mapping was still being
* torn down; completed (virgl unref + response) once the MR finalizes. */
struct virtio_gpu_ctrl_command *unref_cmd;
/* A MAP_BLOB is suspended at the cmdq head (renderer_blocked held)
* until the in-flight unmap of this resource finalizes. */
bool map_blocked;
};
static struct virtio_gpu_virgl_resource *
@@ -45,6 +68,29 @@ virtio_gpu_virgl_find_resource(VirtIOGPU *g, uint32_t resource_id)
return container_of(res, struct virtio_gpu_virgl_resource, base);
}
/*
* A guest may reuse a resource id as soon as it has queued the UNREF, but
* the UNREF of a mapped blob completes only when its MemoryRegion
* finalizes. Park a create of that id at the cmdq head, as a re-MAP is
* parked; the finalizer releases the block, completes the unref and
* resumes the queue. Returns true if the create was parked.
*/
static bool
virtio_gpu_virgl_create_waits_for_unref(VirtIOGPU *g,
struct virtio_gpu_virgl_resource *res,
bool *cmd_suspended)
{
if (!res->unref_cmd) {
return false;
}
if (!res->map_blocked) {
res->map_blocked = true;
VIRTIO_GPU_BASE(g)->renderer_blocked++;
}
*cmd_suspended = true;
return true;
}
#if VIRGL_RENDERER_CALLBACKS_VERSION >= 4
static void *
virgl_get_egl_display(G_GNUC_UNUSED void *cookie)
@@ -58,7 +104,11 @@ struct virtio_gpu_virgl_hostmem_region {
Object parent_obj;
MemoryRegion mr;
struct VirtIOGPU *g;
struct virtio_gpu_virgl_resource *res;
/* Subregion detached; the MR is being finalized asynchronously. */
bool unmapping;
bool finish_unmapping;
QTAILQ_ENTRY(virtio_gpu_virgl_hostmem_region) done_next;
};
#define TYPE_VIRTIO_GPU_VIRGL_HOSTMEM_REGION "virtio-gpu-virgl-hostmem-region"
@@ -72,23 +122,86 @@ to_hostmem_region(MemoryRegion *mr)
return container_of(mr, struct virtio_gpu_virgl_hostmem_region, mr);
}
/*
* Finish the unmap of a hostmem region whose MemoryRegion has finalized:
* drop the virgl mapping, and complete a RESOURCE_UNREF that was deferred
* behind it. Main-loop only (virglrenderer runs on the GL thread).
*/
static void
virtio_gpu_virgl_finish_unmap(VirtIOGPU *g,
struct virtio_gpu_virgl_hostmem_region *vmr)
{
struct virtio_gpu_virgl_resource *res = vmr->res;
VirtIOGPUBase *b = VIRTIO_GPU_BASE(g);
VirtIOGPUGL *gl = VIRTIO_GPU_GL(g);
struct virtio_gpu_ctrl_command *cmd;
struct iovec *res_iovs = NULL;
int num_iovs = 0;
int ret;
QTAILQ_REMOVE(&gl->unmap_done_list, vmr, done_next);
res->mr = NULL;
g_free(vmr);
ret = virgl_renderer_resource_unmap(res->base.resource_id);
if (ret) {
qemu_log_mask(LOG_GUEST_ERROR,
"%s: failed to unmap virgl resource: %s\n",
__func__, strerror(-ret));
}
if (res->map_blocked) {
res->map_blocked = false;
b->renderer_blocked--;
}
cmd = res->unref_cmd;
if (!cmd) {
return;
}
res->unref_cmd = NULL;
virgl_renderer_resource_detach_iov(res->base.resource_id,
&res_iovs, &num_iovs);
if (res_iovs != NULL && num_iovs != 0) {
virtio_gpu_cleanup_mapping_iov(g, res_iovs, num_iovs);
}
virgl_renderer_resource_unref(res->base.resource_id);
QTAILQ_REMOVE(&g->reslist, &res->base, next);
g_free(res);
virtio_gpu_ctrl_response_nodata(g, cmd, VIRTIO_GPU_RESP_OK_NODATA);
g_free(cmd);
}
static void virtio_gpu_virgl_resume_cmdq_bh(void *opaque)
{
VirtIOGPU *g = opaque;
VirtIOGPUGL *gl = VIRTIO_GPU_GL(g);
struct virtio_gpu_virgl_hostmem_region *vmr;
while ((vmr = QTAILQ_FIRST(&gl->unmap_done_list)) != NULL) {
virtio_gpu_virgl_finish_unmap(g, vmr);
}
virtio_gpu_process_cmdq(g);
}
/*
* MR could outlive the resource if MR's reference is held outside of
* virtio-gpu. In order to prevent unmapping resource while MR is alive,
* and thus, making the data pointer invalid, we will block virtio-gpu
* command processing until MR is fully unreferenced and freed.
* virtio-gpu (a flat view still under an RCU reader), so the virgl mapping
* stays alive until the MR is fully unreferenced and freed; only then is
* the resource unmapped. That grace period is on the order of 100 ms, and
* blocking the whole control queue for it (as upstream does) turns a burst
* of unmaps into multi-second round trips for every other command -- past
* a WDDM guest's GPU-scheduler timeout. The queue therefore keeps flowing:
* UNMAP_BLOB is answered once the subregion is gone (the guest cannot reach
* the pages any more), and only work that needs the virgl unmap to have
* happened -- an UNREF of the resource, a re-MAP -- waits for it.
*/
static void virtio_gpu_virgl_hostmem_region_finalize(Object *obj)
{
struct virtio_gpu_virgl_hostmem_region *vmr = VIRTIO_GPU_VIRGL_HOSTMEM_REGION(obj);
VirtIOGPUBase *b;
VirtIOGPUGL *gl;
if (!vmr->g) {
@@ -97,15 +210,13 @@ static void virtio_gpu_virgl_hostmem_region_finalize(Object *obj)
vmr->finish_unmapping = true;
b = VIRTIO_GPU_BASE(vmr->g);
b->renderer_blocked--;
/*
* memory_region_unref() is executed from RCU thread context, while
* virglrenderer works only on the main-loop thread that's holding GL
* context.
*/
gl = VIRTIO_GPU_GL(vmr->g);
QTAILQ_INSERT_TAIL(&gl->unmap_done_list, vmr, done_next);
qemu_bh_schedule(gl->cmdq_resume_bh);
}
@@ -153,6 +264,7 @@ virtio_gpu_virgl_map_resource_blob(VirtIOGPU *g,
object_initialize_child(OBJECT(g), name, vmr,
TYPE_VIRTIO_GPU_VIRGL_HOSTMEM_REGION);
vmr->g = g;
vmr->res = res;
mr = &vmr->mr;
memory_region_init_ram_ptr(mr, OBJECT(vmr), "mr", size, data);
@@ -164,55 +276,47 @@ virtio_gpu_virgl_map_resource_blob(VirtIOGPU *g,
return 0;
}
static int
/*
* Begin (or, once the MR has finalized, finish) unmapping a blob:
*
* 1. Detach the subregion: the guest loses access immediately, and the
* MR goes away asynchronously once its last (RCU) reference drops.
* 2. virtio_gpu_virgl_hostmem_region_finalize() queues the region for the
* main loop, which drops the virgl mapping and completes any UNREF
* deferred behind it (virtio_gpu_virgl_finish_unmap).
*
* Returns true while the unmap is still in flight (res->mr stays set until
* it completes), false when the resource is unmapped on return.
*/
static bool
virtio_gpu_virgl_unmap_resource_blob(VirtIOGPU *g,
struct virtio_gpu_virgl_resource *res,
bool *cmd_suspended)
struct virtio_gpu_virgl_resource *res)
{
struct virtio_gpu_virgl_hostmem_region *vmr;
VirtIOGPUBase *b = VIRTIO_GPU_BASE(g);
MemoryRegion *mr = res->mr;
int ret;
if (!mr) {
return 0;
return false;
}
vmr = to_hostmem_region(res->mr);
/*
* Perform async unmapping in 3 steps:
*
* 1. Begin async unmapping with memory_region_del_subregion()
* and suspend/block cmd processing.
* 2. Wait for res->mr to be freed and cmd processing resumed
* asynchronously by virtio_gpu_virgl_hostmem_region_finalize().
* 3. Finish the unmapping with final virgl_renderer_resource_unmap().
*/
if (vmr->finish_unmapping) {
res->mr = NULL;
g_free(vmr);
ret = virgl_renderer_resource_unmap(res->base.resource_id);
if (ret) {
qemu_log_mask(LOG_GUEST_ERROR,
"%s: failed to unmap virgl resource: %s\n",
__func__, strerror(-ret));
return ret;
}
} else {
*cmd_suspended = true;
/* render will be unblocked once MR is freed */
b->renderer_blocked++;
/* Finalized, but the completion BH has not run yet: finish here. */
virtio_gpu_virgl_finish_unmap(g, vmr);
return false;
}
if (!vmr->unmapping) {
vmr->unmapping = true;
/* memory region owns self res->mr object and frees it by itself */
memory_region_set_enabled(mr, false);
memory_region_del_subregion(&b->hostmem, mr);
object_unparent(OBJECT(vmr));
}
return 0;
return true;
}
static void
@@ -221,24 +325,42 @@ virtio_gpu_virgl_destroy_hostmem_region(VirtIOGPU *g,
{
struct virtio_gpu_virgl_hostmem_region *vmr = to_hostmem_region(res->mr);
VirtIOGPUBase *b = VIRTIO_GPU_BASE(g);
VirtIOGPUGL *gl = VIRTIO_GPU_GL(g);
/*
* Reset drops queued commands without a response (see the cmdq flush in
* virtio_gpu_reset); a deferred UNREF is no different. The resource is
* being destroyed by the caller either way.
*/
if (res->unref_cmd) {
g_free(res->unref_cmd);
res->unref_cmd = NULL;
}
if (res->map_blocked) {
res->map_blocked = false;
b->renderer_blocked--;
}
/*
* vmr is not QOM-owned, so object_finalize() does not free it; the unmap
* step 3 normally does. Reset can run here at any stage of an in-flight
* unmap, where step 3 may not run. This and the finalizer both hold the
* BQL, so free vmr or hand it to object_finalize() per the stage.
* completion normally does. Reset can run here at any stage of an
* in-flight unmap, where the completion may not run. This and the
* finalizer both hold the BQL, so free vmr or hand it to
* object_finalize() per the stage.
*/
if (vmr->finish_unmapping) {
/* Finalizer ran and balanced renderer_blocked; just free vmr. */
/* Finalizer ran; the completion BH has not: just free vmr. */
QTAILQ_REMOVE(&gl->unmap_done_list, vmr, done_next);
res->mr = NULL;
g_free(vmr);
virgl_renderer_resource_unmap(res->base.resource_id);
return;
}
if (res->mr->container != &b->hostmem) {
if (vmr->unmapping) {
/* Async unmap detached the subregion; let the finalizer free vmr. */
OBJECT(vmr)->free = g_free;
vmr->g = NULL;
res->mr = NULL;
return;
}
@@ -285,7 +407,8 @@ void virtio_gpu_virgl_resource_destroy(VirtIOGPU *g,
}
static void virgl_cmd_create_resource_2d(VirtIOGPU *g,
struct virtio_gpu_ctrl_command *cmd)
struct virtio_gpu_ctrl_command *cmd,
bool *cmd_suspended)
{
struct virtio_gpu_resource_create_2d c2d;
struct virgl_renderer_resource_create_args args;
@@ -304,6 +427,9 @@ static void virgl_cmd_create_resource_2d(VirtIOGPU *g,
res = virtio_gpu_virgl_find_resource(g, c2d.resource_id);
if (res) {
if (virtio_gpu_virgl_create_waits_for_unref(g, res, cmd_suspended)) {
return;
}
qemu_log_mask(LOG_GUEST_ERROR, "%s: resource already exists %d\n",
__func__, c2d.resource_id);
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_RESOURCE_ID;
@@ -333,7 +459,8 @@ static void virgl_cmd_create_resource_2d(VirtIOGPU *g,
}
static void virgl_cmd_create_resource_3d(VirtIOGPU *g,
struct virtio_gpu_ctrl_command *cmd)
struct virtio_gpu_ctrl_command *cmd,
bool *cmd_suspended)
{
struct virtio_gpu_resource_create_3d c3d;
struct virgl_renderer_resource_create_args args;
@@ -352,6 +479,9 @@ static void virgl_cmd_create_resource_3d(VirtIOGPU *g,
res = virtio_gpu_virgl_find_resource(g, c3d.resource_id);
if (res) {
if (virtio_gpu_virgl_create_waits_for_unref(g, res, cmd_suspended)) {
return;
}
qemu_log_mask(LOG_GUEST_ERROR, "%s: resource already exists %d\n",
__func__, c3d.resource_id);
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_RESOURCE_ID;
@@ -401,11 +531,21 @@ static void virgl_cmd_resource_unref(VirtIOGPU *g,
}
#if VIRGL_VERSION_MAJOR >= 1
if (virtio_gpu_virgl_unmap_resource_blob(g, res, cmd_suspended)) {
cmd->error = VIRTIO_GPU_RESP_ERR_UNSPEC;
if (res->unref_cmd) {
qemu_log_mask(LOG_GUEST_ERROR, "%s: resource %d already being unref'd\n",
__func__, unref.resource_id);
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_RESOURCE_ID;
return;
}
if (*cmd_suspended) {
if (virtio_gpu_virgl_unmap_resource_blob(g, res)) {
/*
* The mapping is still being torn down: the virgl unref must wait
* for it, and so must this command's completion -- but not the
* commands behind it. virtio_gpu_virgl_finish_unmap() completes
* the unref and answers the command.
*/
res->unref_cmd = cmd;
cmd->deferred = true;
return;
}
#endif
@@ -507,7 +647,6 @@ static void virgl_cmd_set_scanout(VirtIOGPU *g,
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_SCANOUT_ID;
return;
}
g->parent_obj.enable = 1;
if (ss.resource_id && ss.r.width && ss.r.height) {
struct virgl_renderer_resource_info info;
@@ -557,6 +696,7 @@ static void virgl_cmd_set_scanout(VirtIOGPU *g,
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_RESOURCE_ID;
return;
}
g->parent_obj.enable = 1;
qemu_console_resize(g->parent_obj.scanout[ss.scanout_id].con,
ss.r.width, ss.r.height);
virgl_renderer_force_ctx_0();
@@ -566,7 +706,13 @@ static void virgl_cmd_set_scanout(VirtIOGPU *g,
info.width, info.height,
ss.r.x, ss.r.y, ss.r.width, ss.r.height,
native, NULL);
} else {
} else if (g->parent_obj.enable) {
/*
* Disabling a scanout that never showed a resource leaves
* virtio-vga on the VGA framebuffer. Windows' viogpu3d disables
* the scanout repeatedly during boot, before DWM's first frame,
* which otherwise blanks the boot screen for many seconds.
*/
dpy_gfx_replace_surface(
g->parent_obj.scanout[ss.scanout_id].con, NULL);
dpy_gl_scanout_disable(g->parent_obj.scanout[ss.scanout_id].con);
@@ -790,7 +936,8 @@ static void virgl_cmd_get_capset(VirtIOGPU *g,
#if VIRGL_VERSION_MAJOR >= 1
static void virgl_cmd_resource_create_blob(VirtIOGPU *g,
struct virtio_gpu_ctrl_command *cmd)
struct virtio_gpu_ctrl_command *cmd,
bool *cmd_suspended)
{
struct virgl_renderer_resource_create_blob_args virgl_args = { 0 };
g_autofree struct virtio_gpu_virgl_resource *res = NULL;
@@ -814,11 +961,18 @@ static void virgl_cmd_resource_create_blob(VirtIOGPU *g,
return;
}
if (virtio_gpu_virgl_find_resource(g, cblob.resource_id)) {
qemu_log_mask(LOG_GUEST_ERROR, "%s: resource already exists %d\n",
__func__, cblob.resource_id);
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_RESOURCE_ID;
return;
{
struct virtio_gpu_virgl_resource *old =
virtio_gpu_virgl_find_resource(g, cblob.resource_id);
if (old) {
if (virtio_gpu_virgl_create_waits_for_unref(g, old, cmd_suspended)) {
return;
}
qemu_log_mask(LOG_GUEST_ERROR, "%s: resource already exists %d\n",
__func__, cblob.resource_id);
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_RESOURCE_ID;
return;
}
}
res = g_new0(struct virtio_gpu_virgl_resource, 1);
@@ -873,7 +1027,8 @@ static void virgl_cmd_resource_create_blob(VirtIOGPU *g,
}
static void virgl_cmd_resource_map_blob(VirtIOGPU *g,
struct virtio_gpu_ctrl_command *cmd)
struct virtio_gpu_ctrl_command *cmd,
bool *cmd_suspended)
{
struct virtio_gpu_resource_map_blob mblob;
struct virtio_gpu_virgl_resource *res;
@@ -891,6 +1046,38 @@ static void virgl_cmd_resource_map_blob(VirtIOGPU *g,
return;
}
if (res->unref_cmd) {
qemu_log_mask(LOG_GUEST_ERROR, "%s: resource %d is being unref'd\n",
__func__, mblob.resource_id);
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_RESOURCE_ID;
return;
}
if (res->mr) {
struct virtio_gpu_virgl_hostmem_region *vmr = to_hostmem_region(res->mr);
if (!vmr->unmapping) {
qemu_log_mask(LOG_GUEST_ERROR, "%s: resource %d already mapped\n",
__func__, mblob.resource_id);
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_PARAMETER;
return;
}
if (virtio_gpu_virgl_unmap_resource_blob(g, res)) {
/*
* Re-mapping a blob whose previous mapping is still being torn
* down: the virgl map must follow the virgl unmap, so wait it
* out at the cmdq head (rare; the guest normally has the UNREF
* or a fresh resource by now).
*/
if (!res->map_blocked) {
res->map_blocked = true;
VIRTIO_GPU_BASE(g)->renderer_blocked++;
}
*cmd_suspended = true;
return;
}
}
ret = virtio_gpu_virgl_map_resource_blob(g, res, mblob.offset);
if (ret) {
cmd->error = VIRTIO_GPU_RESP_ERR_UNSPEC;
@@ -904,12 +1091,10 @@ static void virgl_cmd_resource_map_blob(VirtIOGPU *g,
}
static void virgl_cmd_resource_unmap_blob(VirtIOGPU *g,
struct virtio_gpu_ctrl_command *cmd,
bool *cmd_suspended)
struct virtio_gpu_ctrl_command *cmd)
{
struct virtio_gpu_resource_unmap_blob ublob;
struct virtio_gpu_virgl_resource *res;
int ret;
VIRTIO_GPU_FILL_CMD(ublob);
virtio_gpu_unmap_blob_bswap(&ublob);
@@ -922,11 +1107,20 @@ static void virgl_cmd_resource_unmap_blob(VirtIOGPU *g,
return;
}
ret = virtio_gpu_virgl_unmap_resource_blob(g, res, cmd_suspended);
if (ret) {
cmd->error = VIRTIO_GPU_RESP_ERR_UNSPEC;
if (res->unref_cmd) {
qemu_log_mask(LOG_GUEST_ERROR, "%s: resource %d is being unref'd\n",
__func__, ublob.resource_id);
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_RESOURCE_ID;
return;
}
/*
* The subregion is gone before this returns, so the guest cannot reach
* the pages any more: answer now. Dropping the virgl mapping waits for
* the MR to finalize but nothing the guest can do depends on it, except
* an UNREF or a re-MAP of this resource, which each wait on their own.
*/
virtio_gpu_virgl_unmap_resource_blob(g, res);
}
#if defined(HAVE_VIRGL_RENDERER_NATIVE_SCANOUT)
@@ -959,6 +1153,7 @@ static bool virgl_scanout_native_blob(VirtIOGPU *g,
.type = SCANOUT_TEXTURE_NATIVE_TYPE_METAL,
.handle = handle,
};
g->parent_obj.enable = 1;
qemu_console_resize(scanout->con,
ss->r.width, ss->r.height);
dpy_gl_scanout_texture(
@@ -1079,10 +1274,10 @@ void virtio_gpu_virgl_process_cmd(VirtIOGPU *g,
virgl_cmd_context_destroy(g, cmd);
break;
case VIRTIO_GPU_CMD_RESOURCE_CREATE_2D:
virgl_cmd_create_resource_2d(g, cmd);
virgl_cmd_create_resource_2d(g, cmd, &cmd_suspended);
break;
case VIRTIO_GPU_CMD_RESOURCE_CREATE_3D:
virgl_cmd_create_resource_3d(g, cmd);
virgl_cmd_create_resource_3d(g, cmd, &cmd_suspended);
break;
case VIRTIO_GPU_CMD_SUBMIT_3D:
virgl_cmd_submit_3d(g, cmd);
@@ -1133,13 +1328,13 @@ void virtio_gpu_virgl_process_cmd(VirtIOGPU *g,
break;
#if VIRGL_VERSION_MAJOR >= 1
case VIRTIO_GPU_CMD_RESOURCE_CREATE_BLOB:
virgl_cmd_resource_create_blob(g, cmd);
virgl_cmd_resource_create_blob(g, cmd, &cmd_suspended);
break;
case VIRTIO_GPU_CMD_RESOURCE_MAP_BLOB:
virgl_cmd_resource_map_blob(g, cmd);
virgl_cmd_resource_map_blob(g, cmd, &cmd_suspended);
break;
case VIRTIO_GPU_CMD_RESOURCE_UNMAP_BLOB:
virgl_cmd_resource_unmap_blob(g, cmd, &cmd_suspended);
virgl_cmd_resource_unmap_blob(g, cmd);
break;
case VIRTIO_GPU_CMD_SET_SCANOUT_BLOB:
virgl_cmd_set_scanout_blob(g, cmd);
@@ -1152,7 +1347,7 @@ void virtio_gpu_virgl_process_cmd(VirtIOGPU *g,
cmd->suspended = cmd_suspended;
if (cmd_suspended || cmd->finished) {
if (cmd_suspended || cmd->finished || cmd->deferred) {
return;
}
if (cmd->error) {
@@ -1248,6 +1443,92 @@ static void virgl_write_context_fence(void *opaque, uint32_t ctx_id,
}
#endif
void virtio_gpu_virgl_reset_async_fences(VirtIOGPU *g)
{
struct virtio_gpu_virgl_context_fence *f;
VirtIOGPUGL *gl = VIRTIO_GPU_GL(g);
while (!QSLIST_EMPTY(&gl->async_fenceq)) {
f = QSLIST_FIRST(&gl->async_fenceq);
QSLIST_REMOVE_HEAD(&gl->async_fenceq, next);
g_free(f);
}
}
#if VIRGL_CHECK_VERSION(1, 1, 2)
static void virtio_gpu_virgl_async_fence_bh(void *opaque)
{
QSLIST_HEAD(, virtio_gpu_virgl_context_fence) async_fenceq;
struct virtio_gpu_virgl_context_fence *f;
VirtIOGPU *g = opaque;
VirtIOGPUGL *gl = VIRTIO_GPU_GL(g);
if (gl->renderer_state != RS_INITED) {
return;
}
QSLIST_MOVE_ATOMIC(&async_fenceq, &gl->async_fenceq);
while (!QSLIST_EMPTY(&async_fenceq)) {
f = QSLIST_FIRST(&async_fenceq);
QSLIST_REMOVE_HEAD(&async_fenceq, next);
/*
* Delegate to the same completion logic the synchronous callbacks
* use: virgl_write_fence() completes only global (non-ring) fenced
* cmds and virgl_write_context_fence() only ring fences matching
* ctx/ring, each with per-cmd inflight accounting. Upstream's BH
* matched more loosely (a context fence could complete a global
* fenced cmd with a numerically smaller id from an unrelated id
* space); global and per-context fence ids are separate counters
* here, so keep the strict matching.
*/
if (f->ring_idx == UINT32_MAX) {
virgl_write_fence(g, (uint32_t)f->fence_id);
} else {
virgl_write_context_fence(g, f->ctx_id, f->ring_idx, f->fence_id);
}
g_free(f);
}
}
static void
virtio_gpu_virgl_push_async_fence(VirtIOGPU *g, uint32_t ctx_id,
uint32_t ring_idx, uint64_t fence_id)
{
struct virtio_gpu_virgl_context_fence *f;
VirtIOGPUGL *gl = VIRTIO_GPU_GL(g);
f = g_new(struct virtio_gpu_virgl_context_fence, 1);
f->ctx_id = ctx_id;
f->ring_idx = ring_idx;
f->fence_id = fence_id;
QSLIST_INSERT_HEAD_ATOMIC(&gl->async_fenceq, f, next);
qemu_bh_schedule(gl->async_fence_bh);
}
static void virgl_write_async_fence(void *opaque, uint32_t fence)
{
VirtIOGPU *g = opaque;
virtio_gpu_virgl_push_async_fence(g, 0, UINT32_MAX, fence);
}
static void virgl_write_async_context_fence(void *opaque, uint32_t ctx_id,
uint32_t ring_idx, uint64_t fence)
{
VirtIOGPU *g = opaque;
virtio_gpu_virgl_push_async_fence(g, ctx_id, ring_idx, fence);
}
#endif
static virgl_renderer_gl_context
virgl_create_context(void *opaque, int scanout_idx,
struct virgl_renderer_gl_ctx_param *params)
@@ -1326,16 +1607,38 @@ static void virtio_gpu_fence_poll(void *opaque)
virtio_gpu_process_cmdq(g);
if (!QTAILQ_EMPTY(&g->cmdq) || !QTAILQ_EMPTY(&g->fenceq)) {
/*
* On the render-server path virgl_renderer_poll() is the only place a
* retired renderer fence is discovered: virgl_renderer_get_poll_fd()
* is vrend-only and VIRGL_RENDERER_ASYNC_FENCE_CB is not enabled, so
* nothing wakes QEMU when a fence signals. This period is therefore a
* hard floor under every guest operation that blocks on a fence, so
* keep it at the millisecond-timer granularity. The timer only
* re-arms while cmdq/fenceq are non-empty, so it costs nothing at
* idle.
* Without async fencing, virgl_renderer_poll() is the only place a
* retired renderer fence is discovered, so this period is a hard
* floor under every guest operation that blocks on a fence -- keep
* it at the millisecond-timer granularity.
*
* With async fencing, ring (venus/neptune context) fences retire
* through the proxy sync thread and async_fence_bh; the poll's job
* shrinks to discovering vrend/global fences, which still retire
* only from virgl_renderer_poll() (vrend's async path is EGL-only
* and disabled here). While only ring fences are pending, relax to
* a slow tick -- it still runs process_cmdq and catches any global
* fence that appears; virgl_renderer_poll() skips proxy contexts
* under ASYNC_FENCE_CB, so it cannot rescue a missed ring-fence
* wake (the sync thread's poll on the worker socket covers worker
* death instead). Any pending global fence keeps the 1 ms rate.
*/
timer_mod(gl->fence_poll, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + 1);
uint64_t period_ms = 1;
if (gl->async_fence_enabled) {
struct virtio_gpu_ctrl_command *cmd;
bool poll_needed = !QTAILQ_EMPTY(&g->cmdq);
QTAILQ_FOREACH(cmd, &g->fenceq, next) {
if (!(cmd->cmd_hdr.flags & VIRTIO_GPU_FLAG_INFO_RING_IDX)) {
poll_needed = true;
break;
}
}
if (!poll_needed) {
period_ms = 100;
}
}
timer_mod(gl->fence_poll,
qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + period_ms);
}
}
@@ -1357,6 +1660,8 @@ void virtio_gpu_virgl_reset_scanout(VirtIOGPU *g)
void virtio_gpu_virgl_reset(VirtIOGPU *g)
{
virgl_renderer_reset();
virtio_gpu_virgl_reset_async_fences(g);
}
int virtio_gpu_virgl_init(VirtIOGPU *g)
@@ -1369,6 +1674,12 @@ int virtio_gpu_virgl_init(VirtIOGPU *g)
if (qemu_egl_display) {
virtio_gpu_3d_cbs.version = 4;
virtio_gpu_3d_cbs.get_egl_display = virgl_get_egl_display;
#if VIRGL_CHECK_VERSION(1, 1, 2)
virtio_gpu_3d_cbs.write_fence = virgl_write_async_fence;
virtio_gpu_3d_cbs.write_context_fence = virgl_write_async_context_fence;
flags |= VIRGL_RENDERER_ASYNC_FENCE_CB;
flags |= VIRGL_RENDERER_THREAD_SYNC;
#endif
}
#endif
if (qemu_egl_angle_native_device) {
@@ -1391,6 +1702,27 @@ int virtio_gpu_virgl_init(VirtIOGPU *g)
}
#endif
#if VIRGL_CHECK_VERSION(1, 1, 2)
if (flags & VIRGL_RENDERER_RENDER_SERVER) {
/*
* Async fencing needs no EGL on the render-server path: the proxy
* retires fences on its own sync thread, fed by an eventfd/pipe the
* render worker writes per retire. Upstream's qemu_egl_display gate
* above exists for vrend, whose async path does need EGL. Without
* this, the only retire discovery for venus/neptune fences is the
* fence_poll timer below -- a 1 ms floor under every guest fence
* wait.
*/
virtio_gpu_3d_cbs.write_fence = virgl_write_async_fence;
virtio_gpu_3d_cbs.write_context_fence = virgl_write_async_context_fence;
flags |= VIRGL_RENDERER_ASYNC_FENCE_CB;
flags |= VIRGL_RENDERER_THREAD_SYNC;
gl->async_fence_enabled = true;
fprintf(stderr, "virtio-gpu: async fence delivery enabled "
"(render-server proxy)\n");
}
#endif
ret = virgl_renderer_init(g, flags, &virtio_gpu_3d_cbs);
if (ret != 0) {
error_report("virgl could not be initialized: %d", ret);
@@ -1408,9 +1740,15 @@ int virtio_gpu_virgl_init(VirtIOGPU *g)
}
#if VIRGL_VERSION_MAJOR >= 1
QTAILQ_INIT(&gl->unmap_done_list);
gl->cmdq_resume_bh = virtio_bh_io_new_guarded(DEVICE(g),
virtio_gpu_virgl_resume_cmdq_bh,
g);
#if VIRGL_CHECK_VERSION(1, 1, 2)
gl->async_fence_bh = virtio_bh_io_new_guarded(DEVICE(g),
virtio_gpu_virgl_async_fence_bh,
g);
#endif
#endif
return 0;
+68 -4
View File
@@ -1061,6 +1061,16 @@ void virtio_gpu_process_cmdq(VirtIOGPU *g)
/* process command */
vgc->process_cmd(g, cmd);
/*
* A deferred command is owned by whoever deferred it, which responds
* and frees it once its host-side work lands. Unlike a suspended
* command it must not hold up the queue behind it.
*/
if (cmd->deferred) {
QTAILQ_REMOVE(&g->cmdq, cmd, next);
continue;
}
/*
* A suspended command has not registered its fence (if any) yet
* and must be re-processed at the cmdq head after resume, so it
@@ -1128,10 +1138,7 @@ static void virtio_gpu_handle_ctrl(VirtIODevice *vdev, VirtQueue *vq)
cmd = virtqueue_pop(vq, sizeof(struct virtio_gpu_ctrl_command));
while (cmd) {
cmd->vq = vq;
cmd->error = 0;
cmd->finished = false;
cmd->suspended = false;
virtio_gpu_ctrl_cmd_init(cmd, vq);
QTAILQ_INSERT_TAIL(&g->cmdq, cmd, next);
cmd = virtqueue_pop(vq, sizeof(struct virtio_gpu_ctrl_command));
}
@@ -1626,11 +1633,68 @@ static void virtio_gpu_reset_bh(void *opaque)
qemu_cond_signal(&g->reset_cond);
}
/*
* A reset destroys every resource, so every blob mapped into the hostmem
* BAR goes away with it. The guest driver cannot always revoke the CPU
* mappings it handed out first: a Windows display driver resets the device
* on its way to D3 while user-mode processes (DWM drawing the "Restarting"
* screen, or an application that is still exiting) keep writing through
* their mappings. Those accesses then land in holes of the BAR. A real
* GPU's BAR keeps decoding, but here a hole is unassigned memory: with hvf
* a store pair or SIMD store there exits without a valid ISS and QEMU
* aborts (assert(isv)), and under TCG the guest takes an external abort.
*
* So a guest-initiated reset that finds blobs mapped puts RAM behind the
* blob subregions (priority -1, shadowed by every blob mapped later) and
* keeps it there until the next machine reset, when no guest code can be
* holding a stale mapping. Resets with nothing mapped (firmware, driver
* start) leave the BAR as it is. The RAM is only reserved: host pages are
* committed only for what stale mappings actually touch.
*/
static void virtio_gpu_hostmem_scratch_update(VirtIOGPU *g, bool guest_reset)
{
VirtIOGPUBase *b = VIRTIO_GPU_BASE(g);
Error *local_err = NULL;
if (!virtio_gpu_hostmem_enabled(b->conf) ||
guest_reset == b->hostmem_scratch_mapped) {
return;
}
if (guest_reset && QTAILQ_EMPTY(&b->hostmem.subregions)) {
return;
}
if (!guest_reset) {
memory_region_del_subregion(&b->hostmem, &b->hostmem_scratch);
b->hostmem_scratch_mapped = false;
trace_virtio_gpu_hostmem_scratch(false);
return;
}
if (!b->hostmem_scratch_init) {
if (!memory_region_init_ram_nomigrate(&b->hostmem_scratch, OBJECT(g),
"virtio-gpu-hostmem-scratch",
b->conf.hostmem, &local_err)) {
warn_reportf_err(local_err, "virtio-gpu: hostmem scratch: ");
return;
}
b->hostmem_scratch_init = true;
}
memory_region_add_subregion_overlap(&b->hostmem, 0, &b->hostmem_scratch,
-1);
b->hostmem_scratch_mapped = true;
trace_virtio_gpu_hostmem_scratch(true);
}
void virtio_gpu_reset(VirtIODevice *vdev)
{
VirtIOGPU *g = VIRTIO_GPU(vdev);
struct virtio_gpu_ctrl_command *cmd;
/* Before the resources (and their blob mappings) are destroyed. */
virtio_gpu_hostmem_scratch_update(g, qemu_in_vcpu_thread());
if (qemu_in_vcpu_thread()) {
g->reset_finished = false;
qemu_bh_schedule(g->reset_bh);
+27 -2
View File
@@ -103,8 +103,18 @@ static void dbdma_cmdptr_save(DBDMA_channel *ch)
ch->regs[DBDMA_CMDPTR_LO],
le16_to_cpu(ch->current.xfer_status),
le16_to_cpu(ch->current.res_count));
dma_memory_write(&address_space_memory, ch->regs[DBDMA_CMDPTR_LO],
&ch->current, sizeof(dbdma_cmd), MEMTXATTRS_UNSPECIFIED);
/*
* Like the real controller, only write back res_count and xfer_status:
* the guest may have rewritten the rest of the descriptor since we
* loaded it, and restoring our stale copy would undo that.
*/
dma_memory_write(&address_space_memory,
ch->regs[DBDMA_CMDPTR_LO] +
offsetof(dbdma_cmd, res_count),
&ch->current.res_count,
sizeof(ch->current.res_count) +
sizeof(ch->current.xfer_status),
MEMTXATTRS_UNSPECIFIED);
}
static void kill_channel(DBDMA_channel *ch)
@@ -374,6 +384,12 @@ static void load_word(DBDMA_channel *ch, int key, uint32_t addr,
dma_memory_read(&address_space_memory, addr, &current->cmd_dep, len,
MEMTXATTRS_UNSPECIFIED);
/* The loaded data goes to the cmdDep field of the command in memory */
dma_memory_write(&address_space_memory,
ch->regs[DBDMA_CMDPTR_LO] + offsetof(dbdma_cmd, cmd_dep),
&current->cmd_dep, sizeof(current->cmd_dep),
MEMTXATTRS_UNSPECIFIED);
if (conditional_wait(ch))
goto wait;
@@ -602,6 +618,13 @@ static void dbdma_control_write(DBDMA_channel *ch)
* logic to ensure all cases are covered.
*/
/*
* The device status bits s0-s7 can be set and cleared by SW (or by
* the device); they are tested by the interrupt, branch and wait
* conditions of the channel program.
*/
status = (status & ~(mask & DEVSTAT)) | (value & mask & DEVSTAT);
/* Setting RUN will tentatively activate the channel
*/
if ((mask & RUN) && (value & RUN)) {
@@ -863,6 +886,8 @@ static void mac_dbdma_reset(DeviceState *d)
for (i = 0; i < DBDMA_CHANNELS; i++) {
memset(s->channels[i].regs, 0, DBDMA_SIZE);
/* No command is in progress after a reset */
s->channels[i].io.processing = false;
}
}
+10 -2
View File
@@ -273,6 +273,16 @@ void usb_msd_command_complete(SCSIRequest *req, size_t resid)
s->csw.residue = cpu_to_le32(s->data_len);
s->csw.status = req->status != 0;
/*
* Release the request before completing the packet: completing it can
* make the host controller process the guest's already queued CSW
* request synchronously, and usb_msd_handle_data() would park that
* packet as "still in flight" while s->req is set, with nothing left
* to complete it.
*/
scsi_req_unref(req);
s->req = NULL;
if (s->packet) {
if (s->data_len == 0 && s->mode == USB_MSDM_DATAOUT) {
/* A deferred packet with no write data remaining must be
@@ -300,8 +310,6 @@ void usb_msd_command_complete(SCSIRequest *req, size_t resid)
} else if (s->data_len == 0) {
s->mode = USB_MSDM_CSW;
}
scsi_req_unref(req);
s->req = NULL;
}
void usb_msd_request_cancelled(SCSIRequest *req)
+26 -1
View File
@@ -292,6 +292,8 @@ struct XHCIEPContext {
/* iso xfer scheduling */
unsigned int interval;
int64_t mfindex_last;
/* iso: when the ring was found empty, negative while it has transfers */
int64_t mfindex_idle;
QEMUTimer *kick_timer;
};
@@ -1115,6 +1117,7 @@ static void xhci_init_epctx(XHCIEPContext *epctx,
dequeue = xhci_addr64(ctx[2] & ~0xf, ctx[3]);
epctx->type = (ctx[1] >> EP_TYPE_SHIFT) & EP_TYPE_MASK;
epctx->mfindex_idle = 0;
epctx->pctx = pctx;
epctx->max_psize = ctx[1]>>16;
epctx->max_psize *= 1+((ctx[1]>>8)&0xff);
@@ -1245,6 +1248,10 @@ static int xhci_ep_nuke_xfers(XHCIState *xhci, unsigned int slotid,
epctx = slot->eps[epid-1];
/* no transfer is left to kick, and the next one does not follow these */
timer_del(epctx->kick_timer);
epctx->mfindex_idle = epctx->mfindex_last;
for (;;) {
xfer = QTAILQ_FIRST(&epctx->transfers);
if (xfer == NULL) {
@@ -1754,12 +1761,22 @@ static void xhci_calc_iso_kick(XHCIState *xhci, XHCITransfer *xfer,
if (xfer->trbs[0].control & TRB_TR_SIA) {
uint64_t asap = ((mfindex + epctx->interval - 1) &
~(epctx->interval-1));
/*
* The transfers of a busy endpoint are one interval apart, so this
* one follows the last however late we get to it: starting over
* from now would drop the time we are behind for good. Once the
* ring was empty, the guest has a few intervals from then to go on
* without a gap.
*/
if (asap >= epctx->mfindex_last &&
asap <= epctx->mfindex_last + epctx->interval * 4) {
(epctx->mfindex_idle < 0 ||
asap <= MAX(epctx->mfindex_last, epctx->mfindex_idle) +
epctx->interval * 4)) {
xfer->mfindex_kick = epctx->mfindex_last + epctx->interval;
} else {
xfer->mfindex_kick = asap;
}
epctx->mfindex_idle = -1;
} else {
xfer->mfindex_kick = ((xfer->trbs[0].control >> TRB_TR_FRAMEID_SHIFT)
& TRB_TR_FRAMEID_MASK) << 3;
@@ -1971,6 +1988,9 @@ static void xhci_kick_epctx(XHCIEPContext *epctx, unsigned int streamid)
if (epctx->type == ET_ISO_OUT || epctx->type == ET_ISO_IN) {
/* 4.10.3.1 */
XHCIEvent ev = { ER_TRANSFER };
if (epctx->mfindex_idle < 0) {
epctx->mfindex_idle = xhci_mfindex_get(xhci);
}
ev.ccode = epctx->type == ET_ISO_IN ?
CC_RING_OVERRUN : CC_RING_UNDERRUN;
ev.slotid = epctx->slotid;
@@ -2024,6 +2044,11 @@ static void xhci_kick_epctx(XHCIEPContext *epctx, unsigned int streamid)
}
if (count++ > TRANSFER_LIMIT) {
trace_usb_xhci_enforced_limit("transfers");
if (epctx->type == ET_ISO_OUT || epctx->type == ET_ISO_IN) {
/* still behind: go on once the main loop had its turn */
timer_mod(epctx->kick_timer,
qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL));
}
break;
}
}
+35 -6
View File
@@ -1645,6 +1645,23 @@ static void usbredir_hello(void *priv, struct usb_redir_hello_header *h)
}
}
static bool usbredir_has_superspeed_endpoints(USBRedirDevice *dev)
{
int i;
if (!usbredirparser_peer_has_cap(dev->parser,
usb_redir_cap_ep_info_max_packet_size)) {
return false;
}
for (i = 0; i < MAX_ENDPOINTS; i++) {
if (dev->endpoint[i].type == usb_redir_type_bulk &&
dev->endpoint[i].max_packet_size == 1024) {
return true;
}
}
return false;
}
static void usbredir_device_connect(void *priv,
struct usb_redir_device_connect_header *device_connect)
{
@@ -1677,8 +1694,18 @@ static void usbredir_device_connect(void *priv,
dev->dev.speed = USB_SPEED_SUPER;
break;
default:
speed = "unknown speed";
dev->dev.speed = USB_SPEED_FULL;
/*
* The protocol has no speed above super, and usbredirhost sends
* unknown for one (SuperSpeedPlus). Only a SuperSpeed link has
* bulk endpoints of 1024 bytes.
*/
if (usbredir_has_superspeed_endpoints(dev)) {
speed = "unknown speed, taken for super speed";
dev->dev.speed = USB_SPEED_SUPER;
} else {
speed = "unknown speed";
dev->dev.speed = USB_SPEED_FULL;
}
}
if (usbredirparser_peer_has_cap(dev->parser,
@@ -2002,10 +2029,12 @@ static void usbredir_control_packet(void *priv, uint64_t id,
DPRINTF("ctrl-in status %d len %d id %"PRIu64"\n", control_packet->status,
len, id);
/* Fix up USB-3 ep0 maxpacket size to allow superspeed connected devices
* to work redirected to a not superspeed capable hcd */
if (dev->dev.speed == USB_SPEED_SUPER &&
!((dev->dev.port->speedmask & USB_SPEED_MASK_SUPER)) &&
/*
* Fix up USB-3 ep0 maxpacket size to allow superspeed connected devices
* to work when they are not attached at superspeed: redirected to a not
* superspeed capable hcd, or announced at a speed we do not know.
*/
if (dev->dev.speed != USB_SPEED_SUPER &&
control_packet->requesttype == 0x80 &&
control_packet->request == 6 &&
control_packet->value == 0x100 && control_packet->index == 0 &&
+12 -4
View File
@@ -48,18 +48,26 @@ struct ScreamerState {
QEMUSoundCard card;
SWVoiceOut *voice;
uint8_t *mixbuf;
int samples;
uint8_t *mixbuf; /* ring of TX frames waiting for the host */
int samples; /* ring size in frames */
int shift;
uint32_t wpos;
uint32_t rpos;
uint32_t wpos; /* ring write index (frames) */
uint32_t rpos; /* ring read index (frames) */
uint32_t fill; /* frames in the ring */
QEMUTimer *tx_timer; /* paces TX DMA at the sample rate */
int64_t tx_last_ns;
uint32_t tx_credit; /* frames TX DMA may consume now */
uint32_t bpos;
uint32_t ppos;
uint32_t rate;
DBDMA_io io;
QEMUTimer *rx_timer; /* completes RX DMA at the sample rate */
DBDMA_io rx_io;
uint32_t regs[6];
uint32_t codec_ctrl_regs[8];
};
+48 -1
View File
@@ -131,6 +131,8 @@ struct virtio_gpu_base_conf {
uint32_t flags;
uint32_t xres;
uint32_t yres;
/* mHz, used when the display reports none */
uint32_t refresh_rate;
uint64_t hostmem;
};
@@ -142,9 +144,27 @@ struct virtio_gpu_ctrl_command {
bool finished;
/* Set if process_cmd deferred completion; keep at cmdq head for resume. */
bool suspended;
/*
* Set if process_cmd took ownership of the command to complete it later
* (a mapped blob's teardown waits for the memory region to finalize):
* it leaves cmdq without a response and without blocking the queue.
*/
bool deferred;
QTAILQ_ENTRY(virtio_gpu_ctrl_command) next;
};
/* virtqueue_pop() does not zero the element, so every popper must reset
* the per-command state that virtio_gpu_process_cmdq() reads. */
static inline void virtio_gpu_ctrl_cmd_init(struct virtio_gpu_ctrl_command *cmd,
VirtQueue *vq)
{
cmd->vq = vq;
cmd->error = 0;
cmd->finished = false;
cmd->suspended = false;
cmd->deferred = false;
}
struct VirtIOGPUBase {
VirtIODevice parent_obj;
@@ -158,6 +178,14 @@ struct VirtIOGPUBase {
int enable;
MemoryRegion hostmem;
/*
* Lowest-priority RAM behind the blob subregions, enabled from a
* guest-initiated reset until the next machine reset (see
* virtio_gpu_hostmem_scratch_update()).
*/
MemoryRegion hostmem_scratch;
bool hostmem_scratch_init;
bool hostmem_scratch_mapped;
struct virtio_gpu_scanout scanout[VIRTIO_GPU_MAX_SCANOUTS];
@@ -176,7 +204,8 @@ struct VirtIOGPUBaseClass {
DEFINE_PROP_BIT("edid", _state, _conf.flags, \
VIRTIO_GPU_FLAG_EDID_ENABLED, true), \
DEFINE_PROP_UINT32("xres", _state, _conf.xres, 1280), \
DEFINE_PROP_UINT32("yres", _state, _conf.yres, 800)
DEFINE_PROP_UINT32("yres", _state, _conf.yres, 800), \
DEFINE_PROP_UINT32("refresh_rate", _state, _conf.refresh_rate, 0)
typedef struct VGPUDMABuf {
QemuDmaBuf *buf;
@@ -245,6 +274,13 @@ struct VirtIOGPUClass {
Error **errp);
};
struct virtio_gpu_virgl_context_fence {
uint32_t ctx_id;
uint32_t ring_idx;
uint64_t fence_id;
QSLIST_ENTRY(virtio_gpu_virgl_context_fence) next;
};
/* VirtIOGPUGL renderer states */
typedef enum {
RS_START, /* starting state */
@@ -253,6 +289,8 @@ typedef enum {
RS_RESET, /* inited and reset pending, moves to start after reset */
} RenderState;
struct virtio_gpu_virgl_hostmem_region;
struct VirtIOGPUGL {
struct VirtIOGPU parent_obj;
@@ -262,6 +300,14 @@ struct VirtIOGPUGL {
QEMUTimer *print_stats;
QEMUBH *cmdq_resume_bh;
/* Hostmem regions whose MemoryRegion finalized; cmdq_resume_bh finishes
* their unmap (and any deferred unref) on the main loop. */
QTAILQ_HEAD(, virtio_gpu_virgl_hostmem_region) unmap_done_list;
QEMUBH *async_fence_bh;
QSLIST_HEAD(, virtio_gpu_virgl_context_fence) async_fenceq;
/* fences retire via async_fence_bh; fence_poll is only a watchdog */
bool async_fence_enabled;
};
struct VhostUserGPU {
@@ -405,5 +451,6 @@ void virtio_gpu_virgl_resource_destroy(VirtIOGPU *g,
Error **errp);
int virtio_gpu_virgl_init(VirtIOGPU *g);
GArray *virtio_gpu_virgl_get_capsets(VirtIOGPU *g);
void virtio_gpu_virgl_reset_async_fences(VirtIOGPU *g);
#endif
+9
View File
@@ -144,7 +144,14 @@ struct SimpleSpiceDisplay {
#endif
#if defined(CONFIG_IOSURFACE)
IOSurfaceRef iosurface;
/* IOSurface pixel format ('BGRA'/'RGBA') the surface was created with;
* a guest scanout in a different channel order forces a recreate. */
uint32_t iosurface_fourcc;
int surface_send_fd;
/* last geometry sent via spice_qxl_gl_scanout/monitor_config so we can
* skip re-sending the scanout for pure back-buffer flips */
uint32_t scanout_last_x, scanout_last_y, scanout_last_w, scanout_last_h;
bool scanout_last_y0top;
#if defined(CONFIG_METAL)
SpiceDisplayMetalContext metal_context;
#endif
@@ -216,6 +223,8 @@ SpiceDisplayMetalContext qemu_spice_display_metal_create_context(IOSurfaceRef su
uint32_t width,
uint32_t height);
void qemu_spice_display_metal_destroy_context(SpiceDisplayMetalContext ctx);
/* IOSurface pixel format matching a scanout MTLTexture, 0 if unsupported. */
uint32_t qemu_spice_display_metal_texture_fourcc(void *texture);
void qemu_spice_display_metal_scanout_texture(SpiceDisplayMetalContext ctx,
MTLTexture_id tex, uint32_t x, uint32_t y,
uint32_t w, uint32_t h);
+2
View File
@@ -2600,6 +2600,8 @@ if virgl.found()
cc.has_header_symbol('virglrenderer.h',
'VIRGL_RENDERER_NEPTUNE',
dependencies: virgl))
config_host_data.set('VIRGL_VERSION_MINOR', virgl.version().split('.')[1])
config_host_data.set('VIRGL_VERSION_MICRO', virgl.version().split('.')[2])
endif
config_host_data.set('CONFIG_VIRTFS', have_virtfs)
config_host_data.set('CONFIG_VTE', vte.found())
+26 -6
View File
@@ -3547,6 +3547,7 @@ typedef struct SnapshotJob {
Coroutine *co;
Error **errp;
bool ret;
QEMUBHFunc *work;
} SnapshotJob;
static void qmp_snapshot_job_free(SnapshotJob *s)
@@ -3605,13 +3606,30 @@ static void snapshot_delete_job_bh(void *opaque)
aio_co_wake(s->co);
}
/*
* A snapshot job's work holds up the main loop, so QEMU answers nothing until
* it is done, and that includes the command that started the job, whose answer
* is still on its way out. A client that gives up on that answer takes a long
* save for a failed one, while the save goes on and stays in the image. So the
* work goes behind the answer: the monitor's wake-up is waiting in the monitor's
* context when this runs there, and the main context's turn comes after it.
*/
static void snapshot_job_after_answer_bh(void *opaque)
{
Job *job = opaque;
SnapshotJob *s = container_of(job, SnapshotJob, common);
aio_bh_schedule_oneshot(qemu_get_aio_context(), s->work, job);
}
static int coroutine_fn snapshot_save_job_run(Job *job, Error **errp)
{
SnapshotJob *s = container_of(job, SnapshotJob, common);
s->errp = errp;
s->co = qemu_coroutine_self();
aio_bh_schedule_oneshot(qemu_get_aio_context(),
snapshot_save_job_bh, job);
s->work = snapshot_save_job_bh;
aio_bh_schedule_oneshot(iohandler_get_aio_context(),
snapshot_job_after_answer_bh, job);
qemu_coroutine_yield();
return s->ret ? 0 : -1;
}
@@ -3621,8 +3639,9 @@ static int coroutine_fn snapshot_load_job_run(Job *job, Error **errp)
SnapshotJob *s = container_of(job, SnapshotJob, common);
s->errp = errp;
s->co = qemu_coroutine_self();
aio_bh_schedule_oneshot(qemu_get_aio_context(),
snapshot_load_job_bh, job);
s->work = snapshot_load_job_bh;
aio_bh_schedule_oneshot(iohandler_get_aio_context(),
snapshot_job_after_answer_bh, job);
qemu_coroutine_yield();
return s->ret ? 0 : -1;
}
@@ -3632,8 +3651,9 @@ static int coroutine_fn snapshot_delete_job_run(Job *job, Error **errp)
SnapshotJob *s = container_of(job, SnapshotJob, common);
s->errp = errp;
s->co = qemu_coroutine_self();
aio_bh_schedule_oneshot(qemu_get_aio_context(),
snapshot_delete_job_bh, job);
s->work = snapshot_delete_job_bh;
aio_bh_schedule_oneshot(iohandler_get_aio_context(),
snapshot_job_after_answer_bh, job);
qemu_coroutine_yield();
return s->ret ? 0 : -1;
}
+6 -1
View File
@@ -329,7 +329,7 @@ void os_set_line_buffering(void)
int os_mlock(bool on_fault)
{
#ifdef HAVE_MLOCKALL
#if defined(HAVE_MLOCKALL) && !defined(CONFIG_DARWIN)
int ret = 0;
int flags = MCL_CURRENT | MCL_FUTURE;
@@ -350,6 +350,11 @@ int os_mlock(bool on_fault)
return ret;
#else
(void)on_fault;
#ifdef CONFIG_DARWIN
/* mlockall() fails with ENOSYS on macOS; HVF locks each RAM mapping. */
return 0;
#else
return -ENOSYS;
#endif
#endif
}
+8 -1
View File
@@ -1436,6 +1436,12 @@
# @zoom-interpolation: Apply interpolation to smooth output when
# zoom-to-fit is enabled. Defaults to "off". (Since 9.0)
#
# @hidpi: Report the window size to the guest in physical pixels on
# Retina displays. When "off" the guest gets the size in points
# and its output is scaled up to the display, which halves the
# guest resolution on a 2x screen. Defaults to "on".
# (Since 10.1)
#
# Since: 7.0
##
{ 'struct': 'DisplayCocoa',
@@ -1444,7 +1450,8 @@
'*full-grab': 'bool',
'*swap-opt-cmd': 'bool',
'*zoom-to-fit': 'bool',
'*zoom-interpolation': 'bool'
'*zoom-interpolation': 'bool',
'*hidpi': 'bool'
} }
##
+27
View File
@@ -39,12 +39,39 @@
#ifdef CONFIG_DARWIN
#include <CoreFoundation/CoreFoundation.h>
#include <pthread/qos.h>
#endif
#ifdef CONFIG_DARWIN
/*
* The main loop feeds the sound card (the HDA DMA timer and the audio timer)
* and runs virgl. At the default QoS it competes with the vCPU threads, so a
* busy guest on a busy Mac delays it by tens of ms and the sound breaks up.
* Ask for user-interactive QoS, as the window thread has.
* QEMU_MAIN_LOOP_QOS=default keeps the default.
* Based on OmacVM's qemu-darwin-main-loop-qos.patch (MIT).
*/
static void darwin_main_loop_qos(void)
{
const char *v = getenv("QEMU_MAIN_LOOP_QOS");
if (v && strcmp(v, "default") == 0) {
return;
}
if (pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0) != 0) {
fprintf(stderr, "main loop: user-interactive QoS refused\n");
}
}
#endif
static void *qemu_default_main(void *opaque)
{
int status;
#ifdef CONFIG_DARWIN
darwin_main_loop_qos();
#endif
replay_mutex_lock();
bql_lock();
status = qemu_main_loop();
+14
View File
@@ -38,6 +38,7 @@
#if !defined(CONFIG_USER_ONLY)
#include "hw/loader.h"
#include "hw/boards.h"
#include "hw/irq.h"
#ifdef CONFIG_TCG
#include "hw/intc/armv7m_nvic.h"
#endif /* CONFIG_TCG */
@@ -239,6 +240,17 @@ static void arm_cpu_reset_hold(Object *obj, ResetType type)
g_hash_table_foreach(cpu->cp_regs, cp_reg_reset, cpu);
g_hash_table_foreach(cpu->cp_regs, cp_reg_check_reset, cpu);
#ifndef CONFIG_USER_ONLY
/*
* The PMU overflow PPI is level-triggered and a per-CPU reset (a
* CPU_OFF/CPU_ON cycle) does not reset the GIC, so a latched assert
* must be dropped here now that the PMU state that raised it is gone,
* or the re-onlined CPU takes a spurious overflow interrupt with
* PMOVSCLR_EL0 == 0.
*/
qemu_set_irq(cpu->pmu_interrupt, 0);
#endif
env->vfp.xregs[ARM_VFP_FPSID] = cpu->reset_fpsid;
env->vfp.xregs[ARM_VFP_MVFR0] = cpu->isar.mvfr0;
env->vfp.xregs[ARM_VFP_MVFR1] = cpu->isar.mvfr1;
@@ -1490,6 +1502,8 @@ static void arm_cpu_initfn(Object *obj)
QLIST_INIT(&cpu->pre_el_change_hooks);
QLIST_INIT(&cpu->el_change_hooks);
seqlock_init(&cpu->pmu_op_lock);
#ifdef CONFIG_USER_ONLY
# ifdef TARGET_AARCH64
/*
+21
View File
@@ -22,6 +22,7 @@
#include "kvm-consts.h"
#include "qemu/cpu-float.h"
#include "qemu/seqlock.h"
#include "hw/registerfields.h"
#include "cpu-qom.h"
#include "exec/cpu-defs.h"
@@ -900,6 +901,14 @@ struct ArchCPU {
* pmu_op_finish() - it does not need other handling during migration
*/
QEMUTimer *pmu_timer;
/*
* Write side is taken (by pmu_op_start/finish) around every span that
* transiently holds the PMU counter state in a mixed form, so BQL-free
* readers of that state (the HVF PMCCNTR_EL0 read fast path) can
* detect a concurrent update by arm_pmu_timer_cb() on the main-loop
* thread and fall back to the locked path. All writers hold the BQL.
*/
QemuSeqLock pmu_op_lock;
/* Timer used for WFxT timeouts */
QEMUTimer *wfxt_timer;
@@ -1314,6 +1323,18 @@ static inline bool is_a64(CPUARMState *env)
void pmu_op_start(CPUARMState *env);
void pmu_op_finish(CPUARMState *env);
/**
* pmu_evcntr_delta_rebaseline
* @env: CPUARMState
*
* Recompute the event-counter delta baselines from the current contents of
* c14_pmevtyper[]. Required after event types have been loaded raw behind
* the back of an enclosing pmu_op_start(), whose baselines were computed
* with the pre-load event types, so that the closing pmu_op_finish()
* converts the loaded counter values using the right events.
*/
void pmu_evcntr_delta_rebaseline(CPUARMState *env);
/*
* Called when a PMU counter is due to overflow
*/
+57
View File
@@ -23,6 +23,7 @@
#include "exec/translation-block.h"
#include "hw/irq.h"
#include "system/cpu-timers.h"
#include "system/hvf.h"
#include "system/kvm.h"
#include "system/tcg.h"
#include "qapi/error.h"
@@ -1063,6 +1064,26 @@ static bool pmu_counter_enabled(CPUARMState *env, uint8_t counter)
filtered = m != p;
}
if (hvf_enabled()) {
/*
* Under HVF the vCPU runs unobserved between traps: EL changes are
* invisible, so per-EL filtering cannot be honoured, and evaluating
* the filter at trap-time EL is biased -- counters are programmed
* from EL1, so an EL0-only filter (perf's cycles:u) would read as
* permanently disabled here and a sampling session would silently
* record nothing. Count unless the filter excludes every EL the
* guest can run at, and leave attributing samples to the guest's
* view of the interrupted PC.
*/
bool el0_filtered = secure ? u : u != nsu;
bool el1_filtered = secure ? p : p != nsk;
filtered = el0_filtered && el1_filtered;
if (arm_feature(env, ARM_FEATURE_EL2)) {
filtered = filtered && !nsh;
}
}
if (counter != 31) {
/*
* If not checking PMCCNTR, ensure the counter is setup to an event we
@@ -1243,6 +1264,17 @@ static void pmevcntr_op_finish(CPUARMState *env, uint8_t counter)
void pmu_op_start(CPUARMState *env)
{
unsigned int i;
/*
* The HVF PMCCNTR_EL0 read fast path reads the counter state from the
* vCPU thread without the BQL, while pmccntr_op_start() transiently
* stores the raw cycle count in c15_ccnt_delta and arm_pmu_timer_cb()
* runs this on the main-loop thread. Flag the whole span -- including
* whatever the caller mutates before pmu_op_finish() -- as a write in
* progress so the reader can detect it and retry. Every caller holds
* the BQL, which serializes the write side.
*/
seqlock_write_begin(&env_archcpu(env)->pmu_op_lock);
pmccntr_op_start(env);
for (i = 0; i < pmu_num_counters(env); i++) {
pmevcntr_op_start(env, i);
@@ -1256,6 +1288,24 @@ void pmu_op_finish(CPUARMState *env)
for (i = 0; i < pmu_num_counters(env); i++) {
pmevcntr_op_finish(env, i);
}
seqlock_write_end(&env_archcpu(env)->pmu_op_lock);
}
void pmu_evcntr_delta_rebaseline(CPUARMState *env)
{
unsigned int i;
/* Mirrors what pmevtyper_rawwrite() does for a single counter */
for (i = 0; i < pmu_num_counters(env); i++) {
uint16_t event = env->cp15.c14_pmevtyper[i] & PMXEVTYPER_EVTCOUNT;
if (event_supported(event)) {
uint16_t event_idx = supported_event_map[event];
env->cp15.c14_pmevcntr_delta[i] =
pm_events[event_idx].get_count(env);
}
}
}
void pmu_pre_el_change(ARMCPU *cpu, void *ignored)
@@ -1303,6 +1353,13 @@ static void pmcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
env->cp15.c9_pmcr |= (value & PMCR_WRITABLE_MASK);
pmu_op_finish(env);
/*
* PMCR_EL0.E gates the overflow interrupt line (see the ARM ARM's
* CheckForPMUOverflow() pseudocode): re-evaluate it, or toggling E with
* PMOVSR and PMINTEN already set leaves the level-triggered PPI stale.
*/
pmu_update_irq(env);
}
static uint64_t pmcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
+345 -183
View File
@@ -199,15 +199,66 @@ void hvf_arm_init_debug(void)
#define SYSREG_PMUSERENR_EL0 SYSREG(3, 3, 9, 14, 0)
#define SYSREG_PMCNTENSET_EL0 SYSREG(3, 3, 9, 12, 1)
#define SYSREG_PMCNTENCLR_EL0 SYSREG(3, 3, 9, 12, 2)
#define SYSREG_PMINTENSET_EL1 SYSREG(3, 0, 9, 14, 1)
#define SYSREG_PMINTENCLR_EL1 SYSREG(3, 0, 9, 14, 2)
#define SYSREG_PMOVSCLR_EL0 SYSREG(3, 3, 9, 12, 3)
#define SYSREG_PMOVSSET_EL0 SYSREG(3, 3, 9, 14, 3)
#define SYSREG_PMSWINC_EL0 SYSREG(3, 3, 9, 12, 4)
#define SYSREG_PMSELR_EL0 SYSREG(3, 3, 9, 12, 5)
#define SYSREG_PMCEID0_EL0 SYSREG(3, 3, 9, 12, 6)
#define SYSREG_PMCEID1_EL0 SYSREG(3, 3, 9, 12, 7)
#define SYSREG_PMCCNTR_EL0 SYSREG(3, 3, 9, 13, 0)
#define SYSREG_PMXEVTYPER_EL0 SYSREG(3, 3, 9, 13, 1)
#define SYSREG_PMXEVCNTR_EL0 SYSREG(3, 3, 9, 13, 2)
#define SYSREG_PMCCFILTR_EL0 SYSREG(3, 3, 14, 15, 7)
/*
* PMEVCNTR<n>_EL0: op0=3 op1=3 crn=14 crm=0b10:n<4:3> op2=n<2:0>
* PMEVTYPER<n>_EL0: op0=3 op1=3 crn=14 crm=0b11:n<4:3> op2=n<2:0>
* for n = 0..30 (the would-be n = 31 typer encoding is PMCCFILTR_EL0,
* which has its own case; the n = 31 counter encoding is unallocated).
*/
static bool sysreg_is_pmev(uint32_t reg)
{
unsigned n;
if (SYSREG_OP0(reg) != 3 || SYSREG_OP1(reg) != 3 ||
SYSREG_CRN(reg) != 14 || SYSREG_CRM(reg) < 8) {
return false;
}
n = (SYSREG_CRM(reg) & 3) * 8 + SYSREG_OP2(reg);
return n <= 30;
}
/*
* The PMUv3 registers this file routes to the QEMU PMU model's cpreg
* handlers (helper.c define_pmu_regs() and friends).
*/
static bool sysreg_is_pmu(uint32_t reg)
{
switch (reg) {
case SYSREG_PMCR_EL0:
case SYSREG_PMUSERENR_EL0:
case SYSREG_PMCNTENSET_EL0:
case SYSREG_PMCNTENCLR_EL0:
case SYSREG_PMINTENSET_EL1:
case SYSREG_PMINTENCLR_EL1:
case SYSREG_PMOVSCLR_EL0:
case SYSREG_PMOVSSET_EL0:
case SYSREG_PMSWINC_EL0:
case SYSREG_PMSELR_EL0:
case SYSREG_PMCEID0_EL0:
case SYSREG_PMCEID1_EL0:
case SYSREG_PMCCNTR_EL0:
case SYSREG_PMXEVTYPER_EL0:
case SYSREG_PMXEVCNTR_EL0:
case SYSREG_PMCCFILTR_EL0:
return true;
default:
return sysreg_is_pmev(reg);
}
}
#define SYSREG_ICC_AP0R0_EL1 SYSREG(3, 0, 12, 8, 4)
#define SYSREG_ICC_AP0R1_EL1 SYSREG(3, 0, 12, 8, 5)
#define SYSREG_ICC_AP0R2_EL1 SYSREG(3, 0, 12, 8, 6)
@@ -930,6 +981,26 @@ static bool hvf_arm_get_host_cpu_features(ARMHostCPUFeatures *ahcf)
*/
host_isar.id_aa64pfr1 &= ~R_ID_AA64PFR1_SME_MASK;
/*
* Apple silicon has no architected PMUv3 (the host's
* ID_AA64DFR0_EL1.PMUVer is 0); every PMU register access from the
* guest traps and QEMU emulates the whole unit, counting cycles on the
* virtual clock (helper.c pm_events) and raising the overflow PPI from
* the pmu_timer. Advertise base PMUv3 with six event counters so
* guests get a real sampling source (Windows' ETW profiler refuses to
* sample with PMUVer == 0; note Windows reads PMCCNTR_EL0 even with
* PMUVer == 0, so -cpu host,pmu=off cannot boot it). PMUVER lands in
* the vCPU's ID_AA64DFR0_EL1 via the cpreg resetvalue that
* hvf_put_registers() pushes before the first run (realize zeroes it
* again for pmu=off); PMCR_EL0.N comes from reset_pmcr_el0 via the
* PMCR cpreg resetvalue and pmu_num_counters(). PMCR_EL0.{IMP,IDCODE}
* are left 0 like the TCG CPUs that don't model a specific
* implementation's PMU.
*/
host_isar.id_aa64dfr0 = FIELD_DP64(host_isar.id_aa64dfr0, ID_AA64DFR0,
PMUVER, 1);
host_isar.reset_pmcr_el0 = 6 << PMCRN_SHIFT; /* six event counters */
ahcf->isar = host_isar;
/*
@@ -1213,6 +1284,13 @@ int hvf_arch_init_vcpu(CPUState *cpu)
ret = hv_vcpu_set_sys_reg(cpu->accel->fd, HV_SYS_REG_ID_AA64PFR0_EL1, pfr);
assert_hvf_ok(ret);
/*
* ID_AA64DFR0_EL1 (which carries the emulated PMU's PMUVer, including
* the 0 of -cpu host,pmu=off) needs no manual sync: it is in
* hvf_sreg_match[], so hvf_put_registers() pushes the model's value
* from the cpreg resetvalue before the first run.
*/
/* We're limited to underlying hardware caps, override internal versions */
ret = hv_vcpu_get_sys_reg(cpu->accel->fd, HV_SYS_REG_ID_AA64MMFR0_EL1,
&arm_cpu->isar.id_aa64mmfr0);
@@ -1242,7 +1320,21 @@ int hvf_arch_init_vcpu(CPUState *cpu)
void hvf_kick_vcpu_thread(CPUState *cpu)
{
cpus_kick_thread(cpu);
/*
* Do not use cpus_kick_thread(): its thread_kicked dedup races with
* hvf_wait_for_ipi() clearing thread_kicked right before an unbounded
* pselect(). A kick that is skipped because thread_kicked was still set
* from an already-consumed kick is lost forever: the vCPU sleeps in WFI
* with the interrupt (or stop request) pending, which delays guest
* interrupts indefinitely and deadlocks pause_all_vcpus() on guest
* reset (zombie VM). Always send the signal.
*/
qatomic_set(&cpu->thread_kicked, true);
int err = pthread_kill(cpu->thread->thread, SIG_IPI);
if (err && err != ESRCH) {
fprintf(stderr, "qemu:%s: %s", __func__, strerror(err));
exit(1);
}
hv_vcpus_exit(&cpu->accel->fd, 1);
}
@@ -1441,48 +1533,80 @@ static bool hvf_sysreg_read_cp(CPUState *cpu, uint32_t reg, uint64_t *val)
return false;
}
static int hvf_sysreg_read(CPUState *cpu, uint32_t reg, uint64_t *val)
/*
* Route a PMUv3 register access to the QEMU PMU model's cpreg handlers.
*
* Unlike most cpregs (see the GICv3 note at the hvf_sysreg_read_cp() call
* sites), the PMU handlers are safe to call from here: they only touch the
* cp15 state, the pmu_timer and the overflow interrupt line, and never
* need a TCG context. Routing through them keeps HVF on the same
* implementation TCG uses -- per-EL access checks (PMUSERENR_EL0),
* per-counter start/finish bracketing, the pre-FEAT_PMUv3p5 RES0 masking
* of event counters, and the delta re-baselining when an event type
* changes.
*
* The caller has refreshed env->pstate (hvf_sync_pstate()), so
* arm_current_el() is accurate for the access checks.
*/
static int hvf_sysreg_access_pmu(CPUState *cpu, uint32_t reg, uint64_t *val,
bool isread, uint64_t syndrome)
{
ARMCPU *arm_cpu = ARM_CPU(cpu);
CPUARMState *env = &arm_cpu->env;
const ARMCPRegInfo *ri;
CPAccessResult res;
ri = get_arm_cp_reginfo(arm_cpu->cp_regs, hvf_reg2cp_reg(reg));
if (!ri || !cp_access_ok(arm_current_el(env), ri, isread)) {
/*
* No cpreg (an unimplemented counter index: PMEVCNTR<n>_EL0 with
* n >= PMCR_EL0.N) or a wrong-EL/wrong-direction access: UNDEF,
* as under TCG.
*/
cpu_synchronize_state(cpu);
hvf_raise_exception(cpu, EXCP_UDEF, syn_uncategorized());
return 1;
}
res = ri->accessfn ? ri->accessfn(env, ri, isread) : CP_ACCESS_OK;
if (res != CP_ACCESS_OK) {
/*
* Mirror TCG's access_check_cp_reg(): a configurable trap (EL0
* denied by PMUSERENR_EL0) presents the sysreg-trap syndrome and
* CP_ACCESS_UNDEFINED is uncategorized. Without EL2/EL3 the only
* reachable target is EL1, which hvf_raise_exception() assumes.
*/
cpu_synchronize_state(cpu);
hvf_raise_exception(cpu, EXCP_UDEF,
res == CP_ACCESS_UNDEFINED ? syn_uncategorized() :
(uint32_t)syndrome);
return 1;
}
if (isread) {
if (ri->type & ARM_CP_CONST) {
*val = ri->resetvalue;
} else if (ri->readfn) {
*val = ri->readfn(env, ri);
} else {
*val = CPREG_FIELD64(env, ri);
}
} else if (ri->writefn) {
ri->writefn(env, ri, *val);
} else {
CPREG_FIELD64(env, ri) = *val;
}
return 0;
}
static int hvf_sysreg_read(CPUState *cpu, uint32_t reg, uint64_t syndrome,
uint64_t *val)
{
ARMCPU *arm_cpu = ARM_CPU(cpu);
CPUARMState *env = &arm_cpu->env;
if (arm_feature(env, ARM_FEATURE_PMU)) {
switch (reg) {
case SYSREG_PMCR_EL0:
*val = env->cp15.c9_pmcr;
return 0;
case SYSREG_PMCCNTR_EL0:
pmu_op_start(env);
*val = env->cp15.c15_ccnt;
pmu_op_finish(env);
return 0;
case SYSREG_PMCNTENCLR_EL0:
*val = env->cp15.c9_pmcnten;
return 0;
case SYSREG_PMOVSCLR_EL0:
*val = env->cp15.c9_pmovsr;
return 0;
case SYSREG_PMSELR_EL0:
*val = env->cp15.c9_pmselr;
return 0;
case SYSREG_PMINTENCLR_EL1:
*val = env->cp15.c9_pminten;
return 0;
case SYSREG_PMCCFILTR_EL0:
*val = env->cp15.pmccfiltr_el0;
return 0;
case SYSREG_PMCNTENSET_EL0:
*val = env->cp15.c9_pmcnten;
return 0;
case SYSREG_PMUSERENR_EL0:
*val = env->cp15.c9_pmuserenr;
return 0;
case SYSREG_PMCEID0_EL0:
case SYSREG_PMCEID1_EL0:
/* We can't really count anything yet, declare all events invalid */
*val = 0;
return 0;
}
if (arm_feature(env, ARM_FEATURE_PMU) && sysreg_is_pmu(reg)) {
return hvf_sysreg_access_pmu(cpu, reg, val, true, syndrome);
}
switch (reg) {
@@ -1618,82 +1742,6 @@ static int hvf_sysreg_read(CPUState *cpu, uint32_t reg, uint64_t *val)
return 1;
}
static void pmu_update_irq(CPUARMState *env)
{
ARMCPU *cpu = env_archcpu(env);
qemu_set_irq(cpu->pmu_interrupt, (env->cp15.c9_pmcr & PMCRE) &&
(env->cp15.c9_pminten & env->cp15.c9_pmovsr));
}
static bool pmu_event_supported(uint16_t number)
{
return false;
}
/* Returns true if the counter (pass 31 for PMCCNTR) should count events using
* the current EL, security state, and register configuration.
*/
static bool pmu_counter_enabled(CPUARMState *env, uint8_t counter)
{
uint64_t filter;
bool enabled, filtered = true;
int el = arm_current_el(env);
enabled = (env->cp15.c9_pmcr & PMCRE) &&
(env->cp15.c9_pmcnten & (1 << counter));
if (counter == 31) {
filter = env->cp15.pmccfiltr_el0;
} else {
filter = env->cp15.c14_pmevtyper[counter];
}
if (el == 0) {
filtered = filter & PMXEVTYPER_U;
} else if (el == 1) {
filtered = filter & PMXEVTYPER_P;
}
if (counter != 31) {
/*
* If not checking PMCCNTR, ensure the counter is setup to an event we
* support
*/
uint16_t event = filter & PMXEVTYPER_EVTCOUNT;
if (!pmu_event_supported(event)) {
return false;
}
}
return enabled && !filtered;
}
static void pmswinc_write(CPUARMState *env, uint64_t value)
{
unsigned int i;
for (i = 0; i < pmu_num_counters(env); i++) {
/* Increment a counter's count iff: */
if ((value & (1 << i)) && /* counter's bit is set */
/* counter is enabled and not filtered */
pmu_counter_enabled(env, i) &&
/* counter is SW_INCR */
(env->cp15.c14_pmevtyper[i] & PMXEVTYPER_EVTCOUNT) == 0x0) {
/*
* Detect if this write causes an overflow since we can't predict
* PMSWINC overflows like we can for other events
*/
uint32_t new_pmswinc = env->cp15.c14_pmevcntr[i] + 1;
if (env->cp15.c14_pmevcntr[i] & ~new_pmswinc & INT32_MIN) {
env->cp15.c9_pmovsr |= (1 << i);
pmu_update_irq(env);
}
env->cp15.c14_pmevcntr[i] = new_pmswinc;
}
}
}
static bool hvf_sysreg_write_cp(CPUState *cpu, uint32_t reg, uint64_t val)
{
ARMCPU *arm_cpu = ARM_CPU(cpu);
@@ -1721,7 +1769,8 @@ static bool hvf_sysreg_write_cp(CPUState *cpu, uint32_t reg, uint64_t val)
return false;
}
static int hvf_sysreg_write(CPUState *cpu, uint32_t reg, uint64_t val)
static int hvf_sysreg_write(CPUState *cpu, uint32_t reg, uint64_t syndrome,
uint64_t val)
{
ARMCPU *arm_cpu = ARM_CPU(cpu);
CPUARMState *env = &arm_cpu->env;
@@ -1734,66 +1783,8 @@ static int hvf_sysreg_write(CPUState *cpu, uint32_t reg, uint64_t val)
SYSREG_OP2(reg),
val);
if (arm_feature(env, ARM_FEATURE_PMU)) {
switch (reg) {
case SYSREG_PMCCNTR_EL0:
pmu_op_start(env);
env->cp15.c15_ccnt = val;
pmu_op_finish(env);
return 0;
case SYSREG_PMCR_EL0:
pmu_op_start(env);
if (val & PMCRC) {
/* The counter has been reset */
env->cp15.c15_ccnt = 0;
}
if (val & PMCRP) {
unsigned int i;
for (i = 0; i < pmu_num_counters(env); i++) {
env->cp15.c14_pmevcntr[i] = 0;
}
}
env->cp15.c9_pmcr &= ~PMCR_WRITABLE_MASK;
env->cp15.c9_pmcr |= (val & PMCR_WRITABLE_MASK);
pmu_op_finish(env);
return 0;
case SYSREG_PMUSERENR_EL0:
env->cp15.c9_pmuserenr = val & 0xf;
return 0;
case SYSREG_PMCNTENSET_EL0:
env->cp15.c9_pmcnten |= (val & pmu_counter_mask(env));
return 0;
case SYSREG_PMCNTENCLR_EL0:
env->cp15.c9_pmcnten &= ~(val & pmu_counter_mask(env));
return 0;
case SYSREG_PMINTENCLR_EL1:
pmu_op_start(env);
env->cp15.c9_pminten |= val;
pmu_op_finish(env);
return 0;
case SYSREG_PMOVSCLR_EL0:
pmu_op_start(env);
env->cp15.c9_pmovsr &= ~val;
pmu_op_finish(env);
return 0;
case SYSREG_PMSWINC_EL0:
pmu_op_start(env);
pmswinc_write(env, val);
pmu_op_finish(env);
return 0;
case SYSREG_PMSELR_EL0:
env->cp15.c9_pmselr = val & 0x1f;
return 0;
case SYSREG_PMCCFILTR_EL0:
pmu_op_start(env);
env->cp15.pmccfiltr_el0 = val & PMCCFILTR_EL0;
pmu_op_finish(env);
return 0;
}
if (arm_feature(env, ARM_FEATURE_PMU) && sysreg_is_pmu(reg)) {
return hvf_sysreg_access_pmu(cpu, reg, &val, false, syndrome);
}
switch (reg) {
@@ -1967,13 +1958,28 @@ static uint64_t hvf_vtimer_val(void)
static void hvf_wait_for_ipi(CPUState *cpu, struct timespec *ts)
{
/*
* Cap open-ended waits so that a lost kick degrades to a short delay
* instead of an unbounded sleep (defense in depth on top of the
* unconditional signal in hvf_kick_vcpu_thread()).
*/
struct timespec bounded = { .tv_sec = 0, .tv_nsec = 10 * SCALE_MS };
/*
* Use pselect to sleep so that other threads can IPI us while we're
* sleeping.
*/
qatomic_set_mb(&cpu->thread_kicked, false);
/*
* A kick sent before thread_kicked was cleared may have been deduped;
* re-check the conditions it would have signalled before sleeping.
*/
if (qatomic_read(&cpu->stop) ||
(cpu->interrupt_request & (CPU_INTERRUPT_HARD | CPU_INTERRUPT_FIQ))) {
return;
}
bql_unlock();
pselect(0, 0, 0, 0, ts, &cpu->accel->unblock_ipi_mask);
pselect(0, 0, 0, 0, ts ? ts : &bounded, &cpu->accel->unblock_ipi_mask);
bql_lock();
}
@@ -2055,6 +2061,107 @@ static void hvf_sync_vtimer(CPUState *cpu)
}
}
/*
* Refresh env->pstate from the vCPU. The sysreg trap handlers run without
* a full cpu_synchronize_state(), but the cpreg access checks and the PMU
* model depend on arm_current_el(env), which would otherwise be stuck at
* whatever the last full sync (or reset) left behind.
*/
static void hvf_sync_pstate(CPUState *cpu)
{
uint64_t cpsr;
hv_return_t r;
if (cpu->accel->dirty) {
/* env is authoritative and about to be pushed; don't clobber it */
return;
}
r = hv_vcpu_get_reg(cpu->accel->fd, HV_REG_CPSR, &cpsr);
assert_hvf_ok(r);
pstate_write(&ARM_CPU(cpu)->env, cpsr);
}
/*
* PMCCNTR_EL0 read fast path.
*
* HVF cannot virtualize the PMU, so every guest read of the cycle counter
* is a full VM exit. Windows on Arm reads it constantly -- its x64
* emulator implements RDTSC on it -- at hundreds of thousands of reads per
* second under an emulated game. The general exit path takes the BQL,
* syncs the vtimer and returns to the vCPU thread loop for every one of
* them. Serve the common case without any of that: the counter is
* enabled, unfiltered and 64-bit (no overflow interrupt to raise), so its
* value is a pure function of the virtual clock and this vCPU's own cp15
* state. The only other writer of that state is arm_pmu_timer_cb() on the
* main-loop thread; pmu_op_start/finish flag its update spans via
* pmu_op_lock, which is checked before committing. Returns false to take
* the general path.
*/
static bool hvf_pmccntr_read_fast(CPUState *cpu, uint64_t syndrome)
{
ARMCPU *arm_cpu = ARM_CPU(cpu);
CPUARMState *env = &arm_cpu->env;
hv_return_t r;
unsigned seq;
if (!(syndrome & 1) || (syndrome & SYSREG_MASK) != SYSREG_PMCCNTR_EL0) {
return false;
}
if (cpu->singlestep_enabled || cpu->accel->dirty ||
cpu->accel->vtimer_masked) {
return false;
}
seq = seqlock_read_begin(&arm_cpu->pmu_op_lock);
if (!arm_feature(env, ARM_FEATURE_PMU) ||
(env->cp15.c9_pmcr & (PMCRE | PMCRLC)) != (PMCRE | PMCRLC) ||
!(env->cp15.c9_pmcnten & (1u << 31)) ||
(env->cp15.pmccfiltr_el0 & (PMXEVTYPER_P | PMXEVTYPER_U))) {
return false;
}
/*
* EL0 reads need PMUSERENR_EL0.{EN,CR}; when neither is set, bail if
* we are at EL0 so the general path can raise the access trap.
*/
if (!(env->cp15.c9_pmuserenr & 0x5)) {
uint64_t cpsr;
r = hv_vcpu_get_reg(cpu->accel->fd, HV_REG_CPSR, &cpsr);
assert_hvf_ok(r);
if (((cpsr >> 2) & 3) == 0) {
return false;
}
}
/*
* Same value pmccntr_op_start would compute for the enabled counter
* (helper.c's cycles_get_count: 1 GHz on the virtual clock).
*/
const uint64_t cycles = muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1000000000, NANOSECONDS_PER_SECOND);
const uint64_t val = cycles - env->cp15.c15_ccnt_delta;
const uint32_t rt = (syndrome >> 5) & 0x1f;
uint64_t pc;
if (seqlock_read_retry(&arm_cpu->pmu_op_lock, seq)) {
/* Raced an update; the general path will read a settled value */
return false;
}
if (rt < 31) {
r = hv_vcpu_set_reg(cpu->accel->fd, HV_REG_X0 + rt, val);
assert_hvf_ok(r);
}
r = hv_vcpu_get_reg(cpu->accel->fd, HV_REG_PC, &pc);
assert_hvf_ok(r);
r = hv_vcpu_set_reg(cpu->accel->fd, HV_REG_PC, pc + 4);
assert_hvf_ok(r);
return true;
}
int hvf_vcpu_exec(CPUState *cpu)
{
ARMCPU *arm_cpu = ARM_CPU(cpu);
@@ -2075,13 +2182,31 @@ int hvf_vcpu_exec(CPUState *cpu)
flush_cpu_state(cpu);
uint64_t exit_reason, syndrome;
uint32_t ec;
bql_unlock();
run_again:
assert_hvf_ok(hv_vcpu_run(cpu->accel->fd));
/* handle VMEXIT */
uint64_t exit_reason = hvf_exit->reason;
uint64_t syndrome = hvf_exit->exception.syndrome;
uint32_t ec = syn_get_ec(syndrome);
exit_reason = hvf_exit->reason;
syndrome = hvf_exit->exception.syndrome;
ec = syn_get_ec(syndrome);
if (exit_reason == HV_EXIT_REASON_EXCEPTION &&
ec == EC_SYSTEMREGISTERTRAP && hvf_pmccntr_read_fast(cpu, syndrome)) {
/*
* Served without the BQL. Go straight back into the guest unless
* something is pending for the general path; a kick that raced us
* is sticky in HVF and surfaces as a CANCELED exit on the next run.
*/
if (!qatomic_read(&cpu->interrupt_request) &&
!qatomic_read(&cpu->exit_request) && !cpu->halted) {
goto run_again;
}
bql_lock();
return 0;
}
ret = 0;
bql_lock();
@@ -2167,7 +2292,42 @@ int hvf_vcpu_exec(CPUState *cpu)
break;
}
assert(isv);
/*
* A memory topology update unmaps and maps again every hvf slot it
* touches. A vCPU that faults on such a range in between only
* gets here once the update is done and the RAM is mapped again,
* so retry the access instead of emulating it: it may well have
* no valid syndrome (a store pair or SIMD access from memcpy).
* Writes to read-only and dirty-logged slots are still emulated.
*/
{
hvf_slot *slot = hvf_find_overlap_slot(
hvf_exit->exception.physical_address, 1);
if (slot && memory_region_is_ram(slot->region) &&
!(iswrite && (slot->region->readonly ||
(slot->flags & HVF_SLOT_LOG)))) {
break;
}
}
if (!isv) {
/*
* Nothing is mapped there to retry on, and without a syndrome
* (a store pair, SIMD or SVE access) the access cannot be
* emulated. Report a synchronous external abort to the guest,
* as KVM does, instead of aborting QEMU.
*/
int same_el;
cpu_synchronize_state(cpu);
same_el = arm_current_el(env) == 1;
env->exception.vaddress = hvf_exit->exception.virtual_address;
hvf_raise_exception(cpu, EXCP_DATA_ABORT,
syn_data_abort_no_iss(same_el, 0, 1, 0, s1ptw,
iswrite, 0x10));
break;
}
if (iswrite) {
val = hvf_get_reg(cpu, srt);
@@ -2194,8 +2354,10 @@ int hvf_vcpu_exec(CPUState *cpu)
uint64_t val;
int sysreg_ret = 0;
hvf_sync_pstate(cpu);
if (isread) {
sysreg_ret = hvf_sysreg_read(cpu, reg, &val);
sysreg_ret = hvf_sysreg_read(cpu, reg, syndrome, &val);
if (!sysreg_ret) {
trace_hvf_sysreg_read(reg,
SYSREG_OP0(reg),
@@ -2208,7 +2370,7 @@ int hvf_vcpu_exec(CPUState *cpu)
}
} else {
val = hvf_get_reg(cpu, rt);
sysreg_ret = hvf_sysreg_write(cpu, reg, val);
sysreg_ret = hvf_sysreg_write(cpu, reg, syndrome, val);
}
advance_pc = !sysreg_ret;
+51
View File
@@ -1,6 +1,7 @@
#include "qemu/osdep.h"
#include "cpu.h"
#include "qemu/error-report.h"
#include "system/hvf.h"
#include "system/kvm.h"
#include "system/tcg.h"
#include "kvm_arm.h"
@@ -343,6 +344,55 @@ static const VMStateDescription vmstate_serror = {
}
};
static bool pmu_sysregs_needed(void *opaque)
{
ARMCPU *cpu = opaque;
/*
* Under HVF the cpreg list is rebuilt to hold only the sysregs the
* hypervisor can get/set directly (hvf_arch_init_vcpu()), which
* excludes the fully-emulated PMU: the cpreg_vmstate arrays that
* normally carry the PMU registers omit them, so send the raw fields.
* Other accelerators keep migrating them via the cpreg list.
*/
return hvf_enabled() && arm_feature(&cpu->env, ARM_FEATURE_PMU);
}
static int pmu_sysregs_post_load(void *opaque, int version_id)
{
ARMCPU *cpu = opaque;
/*
* cpu_pre_load() ran pmu_op_start() before the event types above were
* loaded, so the delta baselines may be for the wrong events; redo
* them so the pmu_op_finish() in cpu_post_load() converts the loaded
* counter values with the right baselines.
*/
pmu_evcntr_delta_rebaseline(&cpu->env);
return 0;
}
static const VMStateDescription vmstate_pmu_sysregs = {
.name = "cpu/pmu-sysregs",
.version_id = 1,
.minimum_version_id = 1,
.needed = pmu_sysregs_needed,
.post_load = pmu_sysregs_post_load,
.fields = (const VMStateField[]) {
VMSTATE_UINT64(env.cp15.c15_ccnt, ARMCPU),
VMSTATE_UINT64(env.cp15.pmccfiltr_el0, ARMCPU),
VMSTATE_UINT64(env.cp15.c9_pmcr, ARMCPU),
VMSTATE_UINT64(env.cp15.c9_pmcnten, ARMCPU),
VMSTATE_UINT64(env.cp15.c9_pmovsr, ARMCPU),
VMSTATE_UINT64(env.cp15.c9_pminten, ARMCPU),
VMSTATE_UINT64(env.cp15.c9_pmselr, ARMCPU),
VMSTATE_UINT64(env.cp15.c9_pmuserenr, ARMCPU),
VMSTATE_UINT64_ARRAY(env.cp15.c14_pmevcntr, ARMCPU, 31),
VMSTATE_UINT64_ARRAY(env.cp15.c14_pmevtyper, ARMCPU, 31),
VMSTATE_END_OF_LIST()
}
};
static bool irq_line_state_needed(void *opaque)
{
return true;
@@ -1106,6 +1156,7 @@ const VMStateDescription vmstate_arm_cpu = {
&vmstate_za,
#endif
&vmstate_serror,
&vmstate_pmu_sysregs,
&vmstate_irq_line_state,
&vmstate_wfxt_timer,
NULL
+9
View File
@@ -7282,6 +7282,15 @@ static void ppc_cpu_reset_hold(Object *obj, ResetType type)
#if !defined(CONFIG_USER_ONLY)
env->nip = env->hreset_vector | env->excp_prefix;
/*
* The BATs live outside env->spr[], so the loop over the SPR defaults
* below does not touch them. Clear them here, otherwise the mappings
* of the previous boot are still valid when the firmware turns
* translation back on after a guest-initiated reset.
*/
memset(env->IBAT, 0, sizeof(env->IBAT));
memset(env->DBAT, 0, sizeof(env->DBAT));
if (tcg_enabled()) {
cpu_breakpoint_remove_all(cs, BP_CPU);
cpu_watchpoint_remove_all(cs, BP_CPU);
+4 -4
View File
@@ -1739,25 +1739,25 @@ static void tcg_out_vec_op(TCGContext *s, TCGOpcode opc, unsigned vecl, unsigned
tcg_out_ternary_vector_gadget_with_scalar(s, cmgt, is_scalar, vece, w0, w1, w2);
break;
case TCG_COND_LE:
tcg_out_ternary_vector_gadget_with_scalar(s, cmgt, is_scalar, vece, w0, w2, w1);
tcg_out_ternary_vector_gadget_with_scalar(s, cmge, is_scalar, vece, w0, w2, w1);
break;
case TCG_COND_GE:
tcg_out_ternary_vector_gadget_with_scalar(s, cmge, is_scalar, vece, w0, w1, w2);
break;
case TCG_COND_LT:
tcg_out_ternary_vector_gadget_with_scalar(s, cmge, is_scalar, vece, w0, w2, w1);
tcg_out_ternary_vector_gadget_with_scalar(s, cmgt, is_scalar, vece, w0, w2, w1);
break;
case TCG_COND_GTU:
tcg_out_ternary_vector_gadget_with_scalar(s, cmhi, is_scalar, vece, w0, w1, w2);
break;
case TCG_COND_LEU:
tcg_out_ternary_vector_gadget_with_scalar(s, cmhi, is_scalar, vece, w0, w2, w1);
tcg_out_ternary_vector_gadget_with_scalar(s, cmhs, is_scalar, vece, w0, w2, w1);
break;
case TCG_COND_GEU:
tcg_out_ternary_vector_gadget_with_scalar(s, cmhs, is_scalar, vece, w0, w1, w2);
break;
case TCG_COND_LTU:
tcg_out_ternary_vector_gadget_with_scalar(s, cmhs, is_scalar, vece, w0, w2, w1);
tcg_out_ternary_vector_gadget_with_scalar(s, cmhi, is_scalar, vece, w0, w2, w1);
break;
default:
g_assert_not_reached();
+172 -43
View File
@@ -97,6 +97,7 @@ static int left_command_key_enabled = 1;
static bool swap_opt_cmd;
static bool zoom_interpolation;
static bool hidpi = true;
static NSTextField *pauseLabel;
static bool allow_events;
@@ -111,7 +112,18 @@ static QemuCocoaPasteboardTypeOwner *cbowner;
@interface QemuCGLLayer : CAOpenGLLayer
@end
/* Consumed on the QEMU IO thread, re-armed from the Cocoa main thread by
* drawFrame: every access must be atomic. */
static bool gl_dirty;
#ifdef USE_METAL
/* One display read of a scanout texture; see cocoa_gl_read_dispatch. */
typedef struct CocoaGLRead {
id<MTLTexture> texture;
MTLOrigin origin;
MTLSize size;
} CocoaGLRead;
static void cocoa_gl_read_done(CocoaGLRead *read);
#endif
static uint32_t gl_scanout_id;
static bool gl_scanout_y0_top;
static QEMUGLContext gl_view_ctx;
@@ -282,6 +294,11 @@ typedef NS_ENUM(NSInteger, QemuCocoaViewScanout) {
*/
BOOL isMouseGrabbed;
BOOL isAbsoluteEnabled;
/* isSelfResizing is set while resizeWindow changes the window frame
* itself so that windowDidResize does not report the resize back to
* the guest as a ui_info resolution request.
*/
BOOL isSelfResizing;
CFMachPortRef eventsTap;
CGColorSpaceRef colorspace;
QEMUCursor *cursor;
@@ -304,18 +321,16 @@ typedef NS_ENUM(NSInteger, QemuCocoaViewScanout) {
- (bool) handleEventLocked:(NSEvent *)event;
- (void) notifyMouseModeChange;
- (BOOL) isMouseGrabbed;
- (BOOL) isSelfResizing;
- (void) raiseAllKeys;
- (void) setScanout:(QemuCocoaViewScanout)scanout;
#ifdef USE_METAL
@property (nonatomic,readonly) CAMetalLayer* metalLayer;
@property (nonatomic,readonly) id<MTLCommandQueue> commandQueue;
@property (nonatomic,retain) id<MTLTexture> fbTexture;
@property (nonatomic,assign) MTLOrigin fbOrigin;
@property (nonatomic,assign) MTLSize fbSize;
- (void)scanoutMetalTexture:(id<MTLTexture>)metalTexture origin:(MTLOrigin)origin size:(MTLSize)size;
- (void)drawFrame;
- (void)scanoutMetalTexture:(id<MTLTexture>)metalTexture size:(MTLSize)size;
- (void)drawFrame:(CocoaGLRead *)read;
#endif
@end
@@ -418,7 +433,6 @@ static CGEventRef handleTapEvent(CGEventTapProxy proxy, CGEventType type, CGEven
[_glLayer release];
#endif
#ifdef USE_METAL
[_fbTexture release];
[_commandQueue release];
[_metalLayer release];
#endif
@@ -658,11 +672,15 @@ static CGEventRef handleTapEvent(CGEventTapProxy proxy, CGEventType type, CGEven
- (void) resizeWindow
{
/* setContentSize: delivers windowDidResize synchronously */
isSelfResizing = YES;
[[self window] setContentAspectRatio:NSMakeSize(screen.width, screen.height)];
if (!([[self window] styleMask] & NSWindowStyleMaskResizable)) {
CGFloat width = screen.width / [[self window] backingScaleFactor];
CGFloat height = screen.height / [[self window] backingScaleFactor];
CGFloat scale = hidpi ? [[self window] backingScaleFactor] : 1;
CGFloat width = screen.width / scale;
CGFloat height = screen.height / scale;
[[self window] setContentSize:NSMakeSize(width, height)];
[[self window] center];
@@ -672,6 +690,8 @@ static CGEventRef handleTapEvent(CGEventTapProxy proxy, CGEventType type, CGEven
} else {
[[self window] setContentSize:[self fixAspectRatio:[self frame].size]];
}
isSelfResizing = NO;
}
- (void) updateScale
@@ -700,7 +720,7 @@ static CGEventRef handleTapEvent(CGEventTapProxy proxy, CGEventType type, CGEven
{
/* Must be called with the BQL, i.e. via updateUIInfo */
NSSize frameSize;
QemuUIInfo info;
QemuUIInfo info = { 0 };
if (!qemu_console_is_graphic(dcl.con)) {
return;
@@ -736,8 +756,13 @@ static CGEventRef handleTapEvent(CGEventTapProxy proxy, CGEventType type, CGEven
info.xoff = 0;
info.yoff = 0;
info.width = frameSize.width * [[self window] backingScaleFactor];
info.height = frameSize.height * [[self window] backingScaleFactor];
if (hidpi) {
info.width = frameSize.width * [[self window] backingScaleFactor];
info.height = frameSize.height * [[self window] backingScaleFactor];
} else {
info.width = frameSize.width;
info.height = frameSize.height;
}
dpy_set_ui_info(dcl.con, &info, TRUE);
}
@@ -774,6 +799,15 @@ static CGEventRef handleTapEvent(CGEventTapProxy proxy, CGEventType type, CGEven
[self resizeWindow];
[self updateScale];
}
/* The window now matches the guest's surface (resizeWindow suppresses
* windowDidResize's report), so this is the point where the guest
* learns the window's backing-pixel size, physical size and the host
* display's refresh rate; it feeds the virtio-gpu EDID. Reporting a
* size equal to the mode the guest just set cannot start a resize
* loop.
*/
[self updateUIInfo];
}
- (void) setFullGrab:(id)sender
@@ -1264,6 +1298,7 @@ static CGEventRef handleTapEvent(CGEventTapProxy proxy, CGEventType type, CGEven
}
}
- (BOOL) isMouseGrabbed {return isMouseGrabbed;}
- (BOOL) isSelfResizing {return isSelfResizing;}
/*
* Makes the target think all down keys are being released.
@@ -1297,9 +1332,6 @@ static CGEventRef handleTapEvent(CGEventTapProxy proxy, CGEventType type, CGEven
#endif
#ifdef USE_METAL
[self.metalLayer removeFromSuperlayer];
if (scanout != QemuCocoaViewScanoutMetal) {
self.fbTexture = nil;
}
#endif
switch (scanout) {
#ifdef CONFIG_OPENGL
@@ -1320,17 +1352,20 @@ static CGEventRef handleTapEvent(CGEventTapProxy proxy, CGEventType type, CGEven
}
#ifdef USE_METAL
- (void)scanoutMetalTexture:(id<MTLTexture>)metalTexture origin:(MTLOrigin)origin size:(MTLSize)size
- (void)scanoutMetalTexture:(id<MTLTexture>)metalTexture size:(MTLSize)size
{
COCOA_DEBUG("QemuCocoaView: scanoutMetalTexture(%p) origin:(%d, %d) size:(%d, %d)\n",
metalTexture, origin.x, origin.y, size.width, size.height);
self.fbTexture = metalTexture;
self.fbOrigin = origin;
self.fbSize = size;
COCOA_DEBUG("QemuCocoaView: scanoutMetalTexture(%p) size:(%d, %d)\n",
metalTexture, size.width, size.height);
if (metalTexture) {
CGFloat scale = self.window.backingScaleFactor;
CGRect frame = CGRectMake(0, 0, size.width / scale, size.height / scale);
/*
* With zoom-to-fit the layer fills the view and Core Animation scales
* the drawable, as the 2D path does; otherwise it is one texel per
* physical pixel.
*/
CGRect frame = ([self window].styleMask & NSWindowStyleMaskResizable) ?
[self.layer bounds] :
CGRectMake(0, 0, size.width / scale, size.height / scale);
CGSize drawableSize = CGSizeMake(size.width, size.height);
/*
* A guest may re-emit SET_SCANOUT_BLOB for every scanned-out frame, so
@@ -1352,12 +1387,9 @@ static CGEventRef handleTapEvent(CGEventTapProxy proxy, CGEventType type, CGEven
}
}
- (void)drawFrame
- (void)drawFrame:(CocoaGLRead *)read
{
@autoreleasepool {
if (!self.fbTexture) {
return;
}
id<CAMetalDrawable> drawable = [self.metalLayer nextDrawable];
if (!drawable) {
/*
@@ -1366,18 +1398,19 @@ static CGEventRef handleTapEvent(CGEventTapProxy proxy, CGEventType type, CGEven
* dropped and the display keeps the stale image until the guest
* flushes again.
*/
gl_dirty = true;
qatomic_set(&gl_dirty, true);
cocoa_gl_read_done(read);
return;
}
id<MTLCommandBuffer> commandBuffer = [self.commandQueue commandBuffer];
id<MTLBlitCommandEncoder> blit = [commandBuffer blitCommandEncoder];
[blit copyFromTexture:self.fbTexture
[blit copyFromTexture:read->texture
sourceSlice:0
sourceLevel:0
sourceOrigin:self.fbOrigin
sourceSize:self.fbSize
sourceOrigin:read->origin
sourceSize:read->size
toTexture:drawable.texture
destinationSlice:0
destinationLevel:0
@@ -1385,6 +1418,9 @@ static CGEventRef handleTapEvent(CGEventTapProxy proxy, CGEventType type, CGEven
[blit endEncoding];
[commandBuffer addCompletedHandler:^(id<MTLCommandBuffer> cb) {
cocoa_gl_read_done(read);
}];
[commandBuffer presentDrawable:drawable];
[commandBuffer commit];
}
@@ -1501,6 +1537,10 @@ static CGEventRef handleTapEvent(CGEventTapProxy proxy, CGEventType type, CGEven
{
COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
allow_events = true;
/* Deliver the UI info that updateUIInfo dropped while events were
* disallowed during startup.
*/
[cocoaView updateUIInfo];
}
- (void)applicationWillTerminate:(NSNotification *)aNotification
@@ -1537,6 +1577,14 @@ static CGEventRef handleTapEvent(CGEventTapProxy proxy, CGEventType type, CGEven
[cocoaView updateUIInfo];
}
/* Refresh rate or scale of the current display changed (System Settings,
* display replug) without the window moving to another screen.
*/
- (void)applicationDidChangeScreenParameters:(NSNotification *)notification
{
[cocoaView updateUIInfo];
}
- (void)windowDidEnterFullScreen:(NSNotification *)notification
{
[cocoaView grabMouse];
@@ -1551,7 +1599,9 @@ static CGEventRef handleTapEvent(CGEventTapProxy proxy, CGEventType type, CGEven
- (void)windowDidResize:(NSNotification *)notification
{
[cocoaView updateScale];
[cocoaView updateUIInfo];
if (![cocoaView isSelfResizing]) {
[cocoaView updateUIInfo];
}
}
/* Called when the user clicks on a window's close button */
@@ -2338,12 +2388,74 @@ static void cocoa_gl_destroy_context(DisplayGLCtx *dgc, QEMUGLContext ctx)
CGLDestroyContext(ctx);
}
#ifdef USE_METAL
/*
* The Metal scanout is the guest's own buffer. A flip-model guest hands
* the displaced buffer back to its application as soon as the flip is
* submitted and orders the application's next writes behind the flip on
* the GPU, so the buffer is only guaranteed intact from RESOURCE_FLUSH
* until the next flip. The display therefore reads (blits and presents)
* at the flush. One read is in flight at a time so a guest flipping
* faster than the display refreshes never exhausts the drawable pool; a
* flush that finds one in flight is served as soon as it completes, and
* the refresh tick only retries a read that found no drawable. All
* state below belongs to the main loop.
*/
static id<MTLTexture> gl_scanout_src;
static MTLOrigin gl_scanout_origin;
static MTLSize gl_scanout_size;
static bool gl_read_inflight;
static void cocoa_gl_read_dispatch(void);
static void cocoa_gl_read_done_bh(void *opaque)
{
CocoaGLRead *read = opaque;
gl_read_inflight = false;
[read->texture release];
g_free(read);
if (gl_scanout_src && qatomic_xchg(&gl_dirty, false)) {
cocoa_gl_read_dispatch();
}
}
static void cocoa_gl_read_done(CocoaGLRead *read)
{
aio_bh_schedule_oneshot(qemu_get_aio_context(), cocoa_gl_read_done_bh,
read);
}
static void cocoa_gl_read_dispatch(void)
{
CocoaGLRead *read = g_new(CocoaGLRead, 1);
read->texture = [gl_scanout_src retain];
read->origin = gl_scanout_origin;
read->size = gl_scanout_size;
gl_read_inflight = true;
dispatch_async(dispatch_get_main_queue(), ^{
[cocoaView drawFrame:read];
});
}
static void cocoa_gl_scanout_set(id<MTLTexture> texture,
MTLOrigin origin, MTLSize size)
{
[gl_scanout_src release];
gl_scanout_src = [texture retain];
gl_scanout_origin = origin;
gl_scanout_size = size;
}
#endif
static void cocoa_gl_update(DisplayChangeListener *dcl,
int x, int y, int w, int h)
{
with_gl_view_ctx(^{
surface_gl_update_texture(dgc.gls, surface, x, y, w, h);
gl_dirty = true;
qatomic_set(&gl_dirty, true);
});
}
@@ -2356,7 +2468,7 @@ static void cocoa_gl_switch(DisplayChangeListener *dcl,
});
cocoa_switch(dcl, new_surface);
gl_dirty = true;
qatomic_set(&gl_dirty, true);
}
static void cocoa_gl_render(void)
@@ -2382,15 +2494,17 @@ static void cocoa_gl_refresh(DisplayChangeListener *dcl)
{
cocoa_refresh(dcl);
if (gl_dirty) {
gl_dirty = false;
if (qatomic_xchg(&gl_dirty, false)) {
#ifdef CONFIG_EGL
#ifdef USE_METAL
if (cocoaView.scanout == QemuCocoaViewScanoutMetal) {
dispatch_async(dispatch_get_main_queue(), ^{
[cocoaView drawFrame];
});
if (gl_scanout_src) {
if (gl_read_inflight) {
qatomic_set(&gl_dirty, true);
} else {
cocoa_gl_read_dispatch();
}
}
} else
#endif
if (egl_surface) {
@@ -2413,7 +2527,10 @@ static void cocoa_gl_refresh(DisplayChangeListener *dcl)
static void cocoa_gl_scanout_disable(DisplayChangeListener *dcl)
{
gl_scanout_id = 0;
gl_dirty = true;
#ifdef USE_METAL
cocoa_gl_scanout_set(nil, MTLOriginMake(0, 0, 0), MTLSizeMake(0, 0, 0));
#endif
qatomic_set(&gl_dirty, true);
dispatch_async(dispatch_get_main_queue(), ^{
cocoaView.scanout = QemuCocoaViewScanoutNone;
});
@@ -2430,14 +2547,15 @@ static void cocoa_gl_scanout_texture(DisplayChangeListener *dcl,
{
gl_scanout_id = backing_id;
gl_scanout_y0_top = backing_y_0_top;
gl_dirty = true;
qatomic_set(&gl_dirty, true);
#ifdef USE_METAL
if (native.type == SCANOUT_TEXTURE_NATIVE_TYPE_METAL) {
id<MTLTexture> mtlTexture = [(id<MTLTexture>)native.handle retain];
MTLOrigin mtlOrigin = MTLOriginMake(x, y, 0);
MTLSize mtlSize = MTLSizeMake(w, h, 1);
cocoa_gl_scanout_set(mtlTexture, mtlOrigin, mtlSize);
dispatch_async(dispatch_get_main_queue(), ^{
[cocoaView scanoutMetalTexture:mtlTexture origin:mtlOrigin size:mtlSize];
[cocoaView scanoutMetalTexture:mtlTexture size:mtlSize];
[mtlTexture release];
});
} else
@@ -2456,7 +2574,14 @@ static void cocoa_gl_scanout_flush(DisplayChangeListener *dcl,
uint32_t x, uint32_t y,
uint32_t w, uint32_t h)
{
gl_dirty = true;
#ifdef USE_METAL
if (gl_scanout_src && !gl_read_inflight) {
qatomic_set(&gl_dirty, false);
cocoa_gl_read_dispatch();
return;
}
#endif
qatomic_set(&gl_dirty, true);
}
static const DisplayChangeListenerOps dcl_gl_ops = {
@@ -2601,6 +2726,10 @@ static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
zoom_interpolation = opts->u.cocoa.has_zoom_interpolation &&
opts->u.cocoa.zoom_interpolation;
if (opts->u.cocoa.has_hidpi) {
hidpi = opts->u.cocoa.hidpi;
}
create_initial_menus();
/*
* Create the menu entries which depend on QEMU state (for consoles
+2 -43
View File
@@ -166,32 +166,7 @@ void qemu_console_co_wait_update(QemuConsole *con)
static void graphic_hw_gl_unblock_timer(void *opaque)
{
QemuConsole *con = opaque;
/*
* The display's GL render did not release the block within the timeout
* (e.g. the gtk window is occluded, the host compositor throttled the
* frame callback, or the host GPU stalled). The device's command queue is
* gated on this block (virtio-gpu: renderer_blocked), so a stuck display
* stalls the guest GPU scheduler into a TDR (dxgmms1 0x7E) ~2 s later.
* Force the unblock so guest command/fence processing resumes well before
* the guest's TdrDelay; the worst case is one stale/torn displayed frame,
* never a guest crash. A late real release is absorbed in
* graphic_hw_gl_block() (con->gl_block already 0 -> no-op).
*/
/* Rate-limited: this can fire repeatedly when the display fence is
* persistently slow; an occasional line is enough to know it's active. */
static unsigned _ub;
if ((_ub++ % 60u) == 0u) {
warn_report("console: gl-unblock fallback firing (display GL fence slow); "
"forcing unblock to keep the guest cmdq moving");
}
if (con->gl_block > 0) {
con->gl_block = 0;
if (con->hw_ops->gl_block) {
con->hw_ops->gl_block(con->hw, false);
}
}
warn_report("console: no gl-unblock within one second");
}
void graphic_hw_gl_block(QemuConsole *con, bool block)
@@ -202,13 +177,6 @@ void graphic_hw_gl_block(QemuConsole *con, bool block)
if (block) {
con->gl_block++;
} else {
/*
* A late release after graphic_hw_gl_unblock_timer() force-cleared the
* block (con->gl_block already 0) must be a safe no-op, not underflow.
*/
if (con->gl_block == 0) {
return;
}
con->gl_block--;
}
assert(con->gl_block >= 0);
@@ -222,16 +190,7 @@ void graphic_hw_gl_block(QemuConsole *con, bool block)
if (block) {
timeout = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
/* Safety net only. The display samples (blits + fences) the guest
* buffer directly at flush time, so the block lifetime is the GPU
* fence latency -- not the host compositor's frame clock -- and
* releasing the guest early TEARS: it re-renders into the buffer
* while the queued blit still reads it (scaled/shifted frame
* artifacts under present storms). 500ms is correct backpressure
* for a slow (shared, possibly saturated) GPU while still
* recovering a genuinely stuck fence well inside the guest's ~2s
* TDR budget. */
timeout += 500;
timeout += 1000; /* one sec */
timer_mod(con->gl_unblock_timer, timeout);
} else {
timer_del(con->gl_unblock_timer);
+2 -1
View File
@@ -426,7 +426,8 @@ EGLSurface qemu_egl_init_surface(EGLContext ectx, EGLNativeWindowType win)
qemu_egl_config,
win, NULL);
if (esurface == EGL_NO_SURFACE) {
error_report("egl: eglCreateWindowSurface failed");
error_report("egl: eglCreateWindowSurface failed: %s",
qemu_egl_get_error_string());
return NULL;
}
+14
View File
@@ -2297,6 +2297,20 @@ static GSList *gd_vc_gfx_init(GtkDisplayState *s, VirtualConsole *vc,
} else {
#ifdef CONFIG_X11
vc->gfx.drawing_area = gtk_drawing_area_new();
/*
* The EGL config's X11 visual may differ from GTK's default,
* notably with PRIME offload. A mismatched native window makes
* eglCreateWindowSurface fail with EGL_BAD_MATCH on NVIDIA.
*/
EGLint visual_id;
if (eglGetConfigAttrib(qemu_egl_display, qemu_egl_config,
EGL_NATIVE_VISUAL_ID, &visual_id)) {
GdkVisual *visual = gdk_x11_screen_lookup_visual(
gdk_screen_get_default(), visual_id);
if (visual) {
gtk_widget_set_visual(vc->gfx.drawing_area, visual);
}
}
/*
* gtk_widget_set_double_buffered() was deprecated in 3.14.
* It is required for opengl rendering on X11 though. A
+142 -16
View File
@@ -6,6 +6,7 @@
*/
#include "qemu/osdep.h"
#include "qemu/error-report.h"
#include "ui/egl-helpers.h"
#include "ui/spice-display.h"
#include <CoreGraphics/CoreGraphics.h>
@@ -18,6 +19,10 @@
@property (nonatomic, readonly) id<MTLCommandQueue> commandQueue;
@property (nonatomic, nullable, retain) id<MTLTexture> scanoutTexture;
@property (nonatomic, assign) CGRect scanoutRect;
/* draws a scanout whose texel layout differs from the surface's (a 10-bit
* fullscreen primary into the 8-bit surface): a blit copies raw bits */
@property (nonatomic, nullable, retain) id<MTLRenderPipelineState> convertPipeline;
@property (nonatomic, assign) BOOL convertPipelineFailed;
- (instancetype)initWithDevice:(id<MTLDevice>)device
surface:(IOSurfaceRef)surface
@@ -38,7 +43,10 @@
{
if (self = [super init]) {
MTLTextureDescriptor *textureDescriptor = [[MTLTextureDescriptor alloc] init];
textureDescriptor.pixelFormat = MTLPixelFormatBGRA8Unorm;
/* must match the surface, which follows the guest scanout's order */
textureDescriptor.pixelFormat =
IOSurfaceGetPixelFormat(surface) == 'RGBA' ? MTLPixelFormatRGBA8Unorm
: MTLPixelFormatBGRA8Unorm;
textureDescriptor.width = width;
textureDescriptor.height = height;
textureDescriptor.usage = MTLTextureUsageRenderTarget;
@@ -59,6 +67,7 @@
- (void)dealloc
{
[_scanoutTexture release];
[_convertPipeline release];
[_commandQueue release];
[_renderTarget release];
[super dealloc];
@@ -76,6 +85,70 @@
self.scanoutRect = CGRectMake(0, 0, 0, 0);
}
/* A full-screen triangle whose fragments read the source texel at the same
* position the blit would copy from (destination pixel + scanout origin).
* Scanout alpha carries nothing (DXGI ignores it), so the output is opaque. */
static NSString *const convert_shader_source =
@"#include <metal_stdlib>\n"
"using namespace metal;\n"
"struct V { float4 pos [[position]]; };\n"
"vertex V convert_vs(uint vid [[vertex_id]]) {\n"
" float2 p = float2((vid << 1) & 2, vid & 2);\n"
" return { float4(p * 2.0 - 1.0, 0.0, 1.0) };\n"
"}\n"
"fragment float4 convert_fs(V in [[stage_in]],\n"
" texture2d<float> src [[texture(0)]],\n"
" constant uint2 &origin [[buffer(0)]]) {\n"
" return float4(src.read(uint2(in.pos.xy) + origin).rgb, 1.0);\n"
"}\n";
/* Formats the conversion may copy unencoded into the 8-bit surface: the
* 10-bit UNORM scanouts, which carry the same (sRGB-encoded) values as an
* 8-bit one. A 16-bit-float scanout is normally scRGB (linear, can
* exceed 1.0) and would need clamping and sRGB encoding, so it is not
* converted here. */
static bool convertible(MTLPixelFormat f)
{
switch (f) {
case MTLPixelFormatRGB10A2Unorm:
case MTLPixelFormatBGR10A2Unorm:
return true;
default:
return false;
}
}
- (id<MTLRenderPipelineState>)pipeline
{
if (!self.convertPipeline && !self.convertPipelineFailed) {
id<MTLDevice> device = self.commandQueue.device;
NSError *err = nil;
id<MTLLibrary> lib = [device newLibraryWithSource:convert_shader_source
options:nil
error:&err];
if (!lib) {
error_report("spice-display-metal: conversion shader: %s",
err.localizedDescription.UTF8String);
self.convertPipelineFailed = YES;
return nil;
}
MTLRenderPipelineDescriptor *desc = [[MTLRenderPipelineDescriptor alloc] init];
desc.vertexFunction = [[lib newFunctionWithName:@"convert_vs"] autorelease];
desc.fragmentFunction = [[lib newFunctionWithName:@"convert_fs"] autorelease];
desc.colorAttachments[0].pixelFormat = self.renderTarget.pixelFormat;
self.convertPipeline = [[device newRenderPipelineStateWithDescriptor:desc
error:&err] autorelease];
[desc release];
[lib release];
if (!self.convertPipeline) {
error_report("spice-display-metal: conversion pipeline: %s",
err.localizedDescription.UTF8String);
self.convertPipelineFailed = YES;
}
}
return self.convertPipeline;
}
- (void)drawFrameAtRect:(CGRect)rect completion:(void (^)(void))completion
{
@autoreleasepool {
@@ -84,23 +157,58 @@
}
id<MTLCommandBuffer> commandBuffer = [self.commandQueue commandBuffer];
id<MTLBlitCommandEncoder> blit = [commandBuffer blitCommandEncoder];
MTLOrigin origin = MTLOriginMake(self.scanoutRect.origin.x + rect.origin.x,
self.scanoutRect.origin.y + rect.origin.y,
0);
MTLSize size = MTLSizeMake(rect.size.width, rect.size.height, 1);
MTLPixelFormat srcFormat = self.scanoutTexture.pixelFormat;
/* the rect comes from the guest's flush: keep the scissor inside
* the attachment, as Metal requires, and the reads inside the
* scanout texture past its origin */
NSUInteger ox = (NSUInteger)self.scanoutRect.origin.x;
NSUInteger oy = (NSUInteger)self.scanoutRect.origin.y;
NSUInteger srcw = self.scanoutTexture.width > ox ? self.scanoutTexture.width - ox : 0;
NSUInteger srch = self.scanoutTexture.height > oy ? self.scanoutTexture.height - oy : 0;
NSUInteger tw = MIN(self.renderTarget.width, srcw);
NSUInteger th = MIN(self.renderTarget.height, srch);
NSUInteger sx = MIN((NSUInteger)MAX(rect.origin.x, 0), tw);
NSUInteger sy = MIN((NSUInteger)MAX(rect.origin.y, 0), th);
NSUInteger sw = MIN((NSUInteger)MAX(rect.size.width, 0), tw - sx);
NSUInteger sh = MIN((NSUInteger)MAX(rect.size.height, 0), th - sy);
if (convertible(srcFormat)) {
/* never blit a 10-bit scanout raw: with nothing to draw (an
* empty rect, or no pipeline) the frame is skipped */
if (sw && sh && [self pipeline]) {
MTLRenderPassDescriptor *pass = [MTLRenderPassDescriptor renderPassDescriptor];
pass.colorAttachments[0].texture = self.renderTarget;
pass.colorAttachments[0].loadAction = MTLLoadActionLoad;
pass.colorAttachments[0].storeAction = MTLStoreActionStore;
id<MTLRenderCommandEncoder> enc =
[commandBuffer renderCommandEncoderWithDescriptor:pass];
uint32_t origin[2] = { (uint32_t)self.scanoutRect.origin.x,
(uint32_t)self.scanoutRect.origin.y };
[enc setRenderPipelineState:self.convertPipeline];
[enc setScissorRect:(MTLScissorRect){ sx, sy, sw, sh }];
[enc setFragmentTexture:self.scanoutTexture atIndex:0];
[enc setFragmentBytes:origin length:sizeof(origin) atIndex:0];
[enc drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3];
[enc endEncoding];
}
} else {
id<MTLBlitCommandEncoder> blit = [commandBuffer blitCommandEncoder];
MTLOrigin origin = MTLOriginMake(self.scanoutRect.origin.x + rect.origin.x,
self.scanoutRect.origin.y + rect.origin.y,
0);
MTLSize size = MTLSizeMake(rect.size.width, rect.size.height, 1);
[blit copyFromTexture:self.scanoutTexture
sourceSlice:0
sourceLevel:0
sourceOrigin:origin
sourceSize:size
toTexture:self.renderTarget
destinationSlice:0
destinationLevel:0
destinationOrigin:(MTLOrigin){rect.origin.x,rect.origin.y,0}];
[blit copyFromTexture:self.scanoutTexture
sourceSlice:0
sourceLevel:0
sourceOrigin:origin
sourceSize:size
toTexture:self.renderTarget
destinationSlice:0
destinationLevel:0
destinationOrigin:(MTLOrigin){rect.origin.x,rect.origin.y,0}];
[blit endEncoding];
[blit endEncoding];
}
[commandBuffer addCompletedHandler:^(id<MTLCommandBuffer> cb) {
completion();
@@ -112,6 +220,24 @@
@end
uint32_t qemu_spice_display_metal_texture_fourcc(void *texture)
{
id<MTLTexture> tex = (id<MTLTexture>)texture;
if (!tex) {
return 0;
}
switch (tex.pixelFormat) {
case MTLPixelFormatBGRA8Unorm:
return 'BGRA';
case MTLPixelFormatRGBA8Unorm:
return 'RGBA';
default:
/* no IOSurface equivalent wired up; caller keeps its default */
return 0;
}
}
SpiceDisplayMetalContext qemu_spice_display_metal_create_context(IOSurfaceRef surface,
uint32_t width,
uint32_t height)
+79 -24
View File
@@ -818,9 +818,10 @@ static void AddIntegerValue(CFMutableDictionaryRef dictionary, const CFStringRef
CFRelease(number);
}
static bool spice_iosurface_create_egl(SimpleSpiceDisplay *ssd, int width, int height,
IOSurfaceRef surface)
static bool spice_iosurface_create_egl_fmt(SimpleSpiceDisplay *ssd, int width, int height,
IOSurfaceRef surface, uint32_t fourcc)
{
const GLenum egl_internal_format = (fourcc == 'RGBA') ? GL_RGBA : GL_BGRA_EXT;
#if defined(CONFIG_EGL)
EGLint target = 0;
GLenum tex_target = 0;
@@ -845,7 +846,7 @@ static bool spice_iosurface_create_egl(SimpleSpiceDisplay *ssd, int width, int h
EGL_HEIGHT, height,
EGL_IOSURFACE_PLANE_ANGLE, 0,
EGL_TEXTURE_TARGET, target,
EGL_TEXTURE_INTERNAL_FORMAT_ANGLE, GL_BGRA_EXT,
EGL_TEXTURE_INTERNAL_FORMAT_ANGLE, egl_internal_format,
EGL_TEXTURE_FORMAT, EGL_TEXTURE_RGBA,
EGL_TEXTURE_TYPE_ANGLE, GL_UNSIGNED_BYTE,
EGL_IOSURFACE_USAGE_HINT_ANGLE, EGL_IOSURFACE_WRITE_HINT_ANGLE,
@@ -872,11 +873,23 @@ static bool spice_iosurface_create_egl(SimpleSpiceDisplay *ssd, int width, int h
}
static bool spice_iosurface_create_cgl(SimpleSpiceDisplay *ssd, int width, int height,
IOSurfaceRef surface)
IOSurfaceRef surface, uint32_t fourcc)
{
#if defined(HAVE_SPICE_MAC_CGL)
GLuint tex;
/*
* CGLTexImageIOSurface2D accepts only GL_BGRA/GL_UNSIGNED_INT_8_8_8_8_REV
* for 8-bit colour (see the table in <OpenGL/CGLIOSurface.h>; anything else
* returns kCGLBadValue), and that combination reads the surface as BGRA
* whatever its fourcc says. So this path cannot carry a differently-ordered
* scanout at all, and must refuse rather than silently transpose.
*/
if (fourcc != 'BGRA') {
error_report("spice_iosurface_create: CGL supports BGRA surfaces only");
return false;
}
CGLSetCurrentContext(spice_gl_ctx);
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_RECTANGLE, tex);
@@ -904,14 +917,15 @@ static bool spice_iosurface_create_cgl(SimpleSpiceDisplay *ssd, int width, int h
#endif
}
static bool spice_iosurface_create(SimpleSpiceDisplay *ssd, int width, int height)
static bool spice_iosurface_create(SimpleSpiceDisplay *ssd, int width, int height,
uint32_t fourcc)
{
IOSurfaceRef surface;
CFMutableDictionaryRef dict = CFDictionaryCreateMutable(
kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
AddIntegerValue(dict, kIOSurfaceWidth, width);
AddIntegerValue(dict, kIOSurfaceHeight, height);
AddIntegerValue(dict, kIOSurfacePixelFormat, 'BGRA');
AddIntegerValue(dict, kIOSurfacePixelFormat, (int)fourcc);
AddIntegerValue(dict, kIOSurfaceBytesPerElement, 4);
#if TARGET_OS_OSX
CFDictionaryAddValue(dict, kIOSurfaceIsGlobal, kCFBooleanTrue);
@@ -926,18 +940,19 @@ static bool spice_iosurface_create(SimpleSpiceDisplay *ssd, int width, int heigh
}
if (spice_opengl == DISPLAY_GL_MODE_CORE) {
if (!spice_iosurface_create_cgl(ssd, width, height, surface)) {
if (!spice_iosurface_create_cgl(ssd, width, height, surface, fourcc)) {
CFRelease(surface);
return false;
}
} else {
if (!spice_iosurface_create_egl(ssd, width, height, surface)) {
if (!spice_iosurface_create_egl_fmt(ssd, width, height, surface, fourcc)) {
CFRelease(surface);
return false;
}
}
ssd->iosurface = surface;
ssd->iosurface_fourcc = fourcc;
#if defined(CONFIG_METAL)
ssd->metal_context = qemu_spice_display_metal_create_context(surface, width, height);
@@ -995,18 +1010,21 @@ static void spice_iosurface_destroy(SimpleSpiceDisplay *ssd)
ssd->iosurface = NULL;
}
static bool spice_iosurface_resize(SimpleSpiceDisplay *ssd, int width, int height)
/* returns -1 on error, 0 if the surface is unchanged, 1 if (re)created */
static int spice_iosurface_resize(SimpleSpiceDisplay *ssd, int width, int height,
uint32_t fourcc)
{
if (ssd->iosurface) {
if (IOSurfaceGetHeight(ssd->iosurface) != height ||
IOSurfaceGetWidth(ssd->iosurface) != width) {
IOSurfaceGetWidth(ssd->iosurface) != width ||
ssd->iosurface_fourcc != fourcc) {
spice_iosurface_destroy(ssd);
return spice_iosurface_create(ssd, width, height);
return spice_iosurface_create(ssd, width, height, fourcc) ? 1 : -1;
} else {
return true;
return 0;
}
} else {
return spice_iosurface_create(ssd, width, height);
return spice_iosurface_create(ssd, width, height, fourcc) ? 1 : -1;
}
}
@@ -1030,7 +1048,7 @@ static int spice_iosurface_create_fd(SimpleSpiceDisplay *ssd, int *fourcc)
// when we close it, POLLHUP will be seen by the other side and know that
// the surface ID is stale and should not be used
ssd->surface_send_fd = fds[1];
*fourcc = 'BGRA';
*fourcc = (int)ssd->iosurface_fourcc;
surfaceid = IOSurfaceGetID(ssd->iosurface);
write(ssd->surface_send_fd, &surfaceid, sizeof(surfaceid));
return fds[0];
@@ -1277,7 +1295,7 @@ static void spice_gl_switch(DisplayChangeListener *dcl,
qemu_spice_display_metal_scanout_disable(ssd->metal_context);
}
#endif
if (spice_iosurface_resize(ssd, width, height)) {
if (spice_iosurface_resize(ssd, width, height, 'BGRA') >= 0) {
fd = spice_iosurface_create_fd(ssd, &fourcc);
if (fd < 0) {
error_report("spice_gl_switch: failed to create fd");
@@ -1390,13 +1408,30 @@ static void qemu_spice_gl_scanout_texture(DisplayChangeListener *dcl,
#if defined(CONFIG_GBM)
fd = egl_get_fd_for_texture(tex_id, &stride, &fourcc, NULL);
#elif defined(CONFIG_IOSURFACE)
if (spice_iosurface_resize(ssd, backing_width, backing_height)) {
ssd->tex_id = tex_id;
ssd->y_0_top = y_0_top;
fd = spice_iosurface_create_fd(ssd, &fourcc);
} else {
fd = -1;
/*
* The surface is shared with the client verbatim, so it has to be in the
* guest scanout's channel order: a fullscreen D3D swapchain can be
* R8G8B8A8 while the desktop is B8G8R8A8. Only the Metal path can honour
* a non-BGRA order end to end, so everything else stays BGRA.
*/
uint32_t want_fourcc = 'BGRA';
#if defined(CONFIG_METAL)
if (native.type == SCANOUT_TEXTURE_NATIVE_TYPE_METAL &&
spice_opengl != DISPLAY_GL_MODE_CORE) {
uint32_t native_fourcc =
qemu_spice_display_metal_texture_fourcc(native.handle);
if (native_fourcc) {
want_fourcc = native_fourcc;
}
}
#endif
int res = spice_iosurface_resize(ssd, backing_width, backing_height,
want_fourcc);
if (res < 0) {
fprintf(stderr, "%s: failed to create IOSurface\n", __func__);
return;
}
ssd->tex_id = tex_id;
#if defined(CONFIG_METAL)
if (ssd->metal_context && native.type == SCANOUT_TEXTURE_NATIVE_TYPE_METAL) {
qemu_spice_display_metal_scanout_texture(ssd->metal_context,
@@ -1406,6 +1441,26 @@ static void qemu_spice_gl_scanout_texture(DisplayChangeListener *dcl,
qemu_spice_display_metal_scanout_disable(ssd->metal_context);
}
#endif
/*
* Guests using flip-model presentation issue a set_scanout for every
* frame with a different backing buffer of the same dimensions. The
* IOSurface (and its ID) is unchanged in that case, so avoid spamming
* the SPICE client with gl_scanout/monitors_config messages (which
* would also close the previous pipe and trigger the client's
* stale-POLLHUP protection). Frame content is delivered by gl_draw.
*/
if (res == 0 && ssd->have_scanout &&
ssd->y_0_top == y_0_top &&
ssd->scanout_last_x == x && ssd->scanout_last_y == y &&
ssd->scanout_last_w == w && ssd->scanout_last_h == h) {
return;
}
ssd->y_0_top = y_0_top;
ssd->scanout_last_x = x;
ssd->scanout_last_y = y;
ssd->scanout_last_w = w;
ssd->scanout_last_h = h;
fd = spice_iosurface_create_fd(ssd, &fourcc);
#endif
if (fd < 0) {
fprintf(stderr, "%s: failed to get fd for texture\n", __func__);
@@ -1513,8 +1568,8 @@ static void qemu_spice_gl_update(DisplayChangeListener *dcl,
if (ssd->guest_dmabuf_refresh) {
QemuDmaBuf *dmabuf = ssd->guest_dmabuf;
width = qemu_dmabuf_get_width(dmabuf);
height = qemu_dmabuf_get_height(dmabuf);
int width = qemu_dmabuf_get_width(dmabuf);
int height = qemu_dmabuf_get_height(dmabuf);
if (render_cursor) {
egl_dmabuf_import_texture(dmabuf);
@@ -1565,7 +1620,7 @@ static void qemu_spice_gl_update(DisplayChangeListener *dcl,
egl_texture_blit(ssd->gls, &ssd->blit_fb, &ssd->guest_fb,
!y_0_top);
egl_texture_blend(ssd->gls, &ssd->blit_fb, &ssd->cursor_fb,
!y_0_top, false, ptr_x, ptr_y, 1.0, 1.0);
!y_0_top, ptr_x, ptr_y, 1.0, 1.0);
glFlush();
}
#elif defined(CONFIG_IOSURFACE)