Compare commits

...
552 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
osy 6601422e1f Merge tag 'v10.0.12' into utm-edition
QEMU v10.0.12 stable release (829 commits since v10.0.2): bug fixes
only, including ~40 memory-safety/CVE fixes (ui/vnc, hw/usb xhci,
9pfs, virtio-blk, hw/uefi, virtio-gpu, qxl/sm501/cirrus display
models).

Conflict resolutions:
- hw/display/virtio-gpu-virgl.c: keep our dead-context fence
  retirement around virgl_renderer_context_create_fence()
- ui/gtk.c: take upstream's gd_resize_event (same HiDPI fix we
  carried, now upstream via c784ce6703), keeping our NULL-window
  guard on gdk_window_get_scale_factor()
- ui/spice-core.c: upstream dropped 'static QemuThread me' in favor
  of bql_locked() (b4feb2ec85); keep our spice_gl_ctx extern

Four local commits are now redundant no-ops (arrived upstream):
650063be4a, d8a30b7576, b3f183123c, 8a783117b7.

Assisted-by: Claude:claude-opus-5
2026-07-26 18:22:11 -07:00
osy 9fc1209477 tcg: only prepare the jit region when a debugger is attached
The iOS 26 splitwx workaround in 4904c33342 ("tcg: new JIT workaround
for iOS 26") hard-failed buffer allocation when no debugger was
attached, and unconditionally trapped into break_prepare_jit_region().
Make the trap conditional instead so the allocation still succeeds
without a debugger.

This brings tcg/region.c in line with the amended version of the
workaround shipped in UTM's qemu-10.0.2-utm.patch.
2026-07-26 17:54:21 -07:00
Mark Cave-Ayland 8a783117b7 target/i386: fix TB exit logic in gen_movl_seg() when writing to SS
Before commit e54ef98c8a ("target/i386: do not trigger IRQ shadow for LSS"), any
write to SS in gen_movl_seg() would cause a TB exit. The changes introduced by
this commit were intended to restrict the DISAS_EOB_INHIBIT_IRQ exit to the case
where inhibit_irq is true, but missed that a DISAS_EOB_NEXT exit can still be
required when writing to SS and inhibit_irq is false.

Comparing the PE(s) && !VM86(s) section with the logic in x86_update_hflags(), we
can see that the DISAS_EOB_NEXT exit is still required for the !CODE32 case when
writing to SS in gen_movl_seg() because any change to the SS flags can affect
hflags. Similarly we can see that the existing CODE32 case is still correct since
a change to any of DS, ES and SS can affect hflags. Finally for the
gen_op_movl_seg_real() case an explicit TB exit is not needed because the segment
register selector does not affect hflags.

Update the logic in gen_movl_seg() so that a write to SS with inhibit_irq set to
false where PE(s) && !VM86(s) will generate a DISAS_EOB_NEXT exit along with the
inline comment. This has the effect of allowing Win98SE to boot in QEMU once
again.

Signed-off-by: Mark Cave-Ayland <[email protected]>
Fixes: e54ef98c8a ("target/i386: do not trigger IRQ shadow for LSS")
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/2987
Link: https://lore.kernel.org/r/[email protected]
Reviewed-by: Peter Maydell <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 0f1d6606c2)
2026-07-26 17:52:57 -07:00
osy 1c5e22deee ui/cocoa: retry the Metal draw when no drawable is available
drawFrame silently returned when nextDrawable came back nil, but the
refresh that dispatched it had already consumed gl_dirty -- the frame was
dropped and the display kept the stale image until the guest happened to
flush again.  Re-arm gl_dirty on that path so the next refresh tick
retries the draw.

Assisted-by: Claude:claude-fable-5
2026-07-23 18:47:27 -07:00
osy 94fd27e4da ui/cocoa: reconfigure the Metal layer only when the scanout parameters change
The guest re-emits SET_SCANOUT_BLOB for every scanned-out frame (the
virtio KMD's FlushToScreen re-binds the scanout per flip), so
scanoutMetalTexture runs at frame rate.  Unconditionally assigning
drawableSize and pixelFormat discards the CAMetalLayer's drawable pool on
every frame, which starves nextDrawable in drawFrame and silently drops
presented frames.  Skip the reconfiguration when scale, format, frame and
drawableSize are unchanged.

Assisted-by: Claude:claude-fable-5
2026-07-23 18:47:13 -07:00
osy 881e5ff38f virtio-gpu-virgl: bound render-server fence-notify latency to 1ms
On the render-server path virgl_renderer_poll() is the only place a
retired renderer fence is discovered (get_poll_fd is vrend-only and
ASYNC_FENCE_CB is off), so a finished fence sits unnoticed until the next
tick of virtio_gpu_fence_poll.  At the old fixed 10ms that put a hard
floor under every guest op blocking on a fence: a Present with no GPU
work parked ~10-13ms, ~99% of a frame.  The timer only re-arms while
cmdq/fenceq are non-empty, so a shorter period costs nothing at idle.

1ms is the QEMU millisecond-timer granularity.  The proper fix is
event-driven async-fence delivery bounced to the BQL via a BH.

Assisted-by: Claude:claude-opus-4-8
2026-07-23 18:46:53 -07:00
osy 60e45e1f9a virtio-ramfb: register the host-visible memory BAR and shm capability
virtio_ramfb_realize() never set up the hostmem region that
virtio_gpu_pci_base_realize() does, so hostmem=NN,blob=true was accepted
on virtio-ramfb / virtio-ramfb-gl while the device exposed neither BAR 4
nor a VIRTIO_PCI_CAP_SHARED_MEMORY_CFG capability.

Guests that discover host memory through that capability then see none.
On the Windows viogpu3d WDDM driver this leaves shmem.available false,
the adapter reports no host-visible memory segment, D3D device creation
fails with 0x80004005 ("KMD reports no 3D/shmem support"), and — because
the display driver has by then taken over scanout with nothing to present
from — the desktop goes black right after the driver installs.

Register the BAR and the shm capability before qdev_realize(), matching
the virtio-gpu-pci path exactly.

Assisted-by: Claude:claude-opus-4-8
2026-07-20 12:54:53 -07:00
osy a0f453befd virtio-gpu: retire fences immediately when the renderer context is dead
virgl_renderer_context_create_fence fails when the proxy render worker
has died (crashed mid-teardown); the fence was silently dropped, never
signaled, and the guest GPU scheduler eventually bugchecked
(VIDEO_TDR_FAILURE) waiting on it.  Respond OK right away instead —
the cmd is not on fenceq yet at this point, so the response both
signals the fence and keeps it off the queue.

Assisted-by: Claude:claude-fable-5
2026-07-20 12:54:16 -07:00
osy d602fffb8b ui/gtk: fix leaked dmabuf fence handler wedging the main loop, and present tearing
A dmabuf render fence that had not yet signalled was left registered when
the dmabuf was released or re-fenced (flip-model guest switching scanout
buffers mid-fence). A sync-file fd stays readable forever once signalled,
so the leaked handler becomes an always-ready priority-0 source: the main
loop spins on it (one core pegged) and GTK's lower-priority redraw/resize
idles are starved forever -- a frozen, unresponsive window -- while
same-priority socket I/O (SSH, QMP) keeps working. The stray
gd_hw_gl_flushed calls the leaked handler makes also close newer pending
fences early, unblocking the virtio-gpu cmdq while a draw still consumes
the previous scanout state (scaled/flipped frame artifacts).

Add gd_dmabuf_cancel_fence() (unregister handler, close fd, release the
gl block) and call it on release and before every re-fence; guard
gd_hw_gl_flushed against a spurious call with no pending fence.

Assisted-by: Claude:claude-opus-4-8
2026-07-09 16:08:23 -07:00
osy 10cd9e21d8 virtio-gpu-virgl: bound the scanout-blob rect like non-blob scanouts
virtio_gpu_update_dmabuf sizes the dmabuf and resizes the console to
the scanout rect, and a zero-area displaysurface aborts inside
qemu_memfd_alloc via error_abort.  The blob path bounds only the
framebuffer dimensions, so a guest-supplied zero rect with a valid
framebuffer passes validation and kills the VM.  Reject rects under
16x16 exactly like virtio_gpu_do_set_scanout does for non-blob
scanouts: the guest gets ERR_INVALID_PARAMETER, never an abort.

Assisted-by: Claude:claude-fable-5
2026-07-09 16:07:47 -07:00
osy 410460413d virtio-gpu/udmabuf: make flip-chain re-presents cheap
virtio_gpu_update_dmabuf() runs at presentation rate: a flip-model guest
re-presents either one primary buffer or alternates SET_SCANOUT_BLOB
between a small set of buffers every frame.  Each call took the full
create + console-resize + EGL/GL import + release path, which churns GL
state on the display thread and hangs the UI ("Not Responding").

Record the source identity of the request that created a VGPUDMABuf (fd,
resource id, source rect, framebuffer geometry).  An identical re-present
of the currently displayed buffer keeps the existing dmabuf and its
import.  A different buffer (flip chain) or new geometry imports fresh --
a long-lived cached import sampled while the guest GPU re-renders that
buffer draws torn/stale content under present storms -- but the console
is only resized when the dimensions actually change, which was the
historically expensive part of the path.

Assisted-by: Claude:claude-opus-4-8
2026-07-09 16:07:39 -07:00
osy 5cb1434ba3 ui/console: force gl-unblock from the watchdog timer
The virtio-gpu command queue is gated on con->gl_block: while a scanout
flush is in flight the device stops processing the guest's command/fence
stream until the display's GL render releases the block.  If that release
is slow -- the window is occluded, the host compositor throttles the frame
callback, or the host GPU stalls -- the guest GPU scheduler is starved and
trips a TDR (dxgmms1 0x7E) about two seconds later.

Make the unblock watchdog force the block clear instead of only warning, so
guest command processing resumes well before the guest's TdrDelay; the worst
case is one stale or torn displayed frame, never a guest crash.  A late real
release after the forced clear must then be a no-op rather than an underflow,
so return early when gl_block is already zero.

Also shorten the fallback from one second to 500 ms: at one second the cmdq
was starved for up to a second per scanout flush whenever the fence was
slow, leaving the guest compositor mostly black.  The display samples the
guest buffer at flush time, so the block lifetime is GPU fence latency;
500 ms is correct backpressure for a slow (shared, possibly saturated) GPU
while still recovering a genuinely stuck fence well inside the guest's ~2 s
TDR budget.

Assisted-by: Claude:claude-opus-4-8
2026-07-09 16:07:17 -07:00
osy b465664e21 vhost-user-gpu: use virgl_renderer_resource_info in set_scanout
virgl_cmd_set_scanout() passes &info to virgl_get_resource_info_modifiers()
and then reads info.tex_id; both operate on struct
virgl_renderer_resource_info.  Declaring info as virgl_renderer_texture_info
is the wrong type for that query, so use virgl_renderer_resource_info.

Assisted-by: Claude:claude-opus-4-8
2026-07-09 16:06:13 -07:00
osy 3b284d7f03 ui/cocoa: fix black screen for 2D surface content in GL mode
Since "cocoa: support scanout of Metal textures" the GL layer is a
manually managed sublayer instead of the view's backing layer, so it no
longer tracks the view's geometry and its frame was only ever set by
cocoa_gl_scanout_texture(). Content presented through the 2D surface
path (ramfb / virtio-gpu before the guest driver starts a GL scanout)
rendered into an EGL surface on a 0x0 layer and never appeared on
screen.

- Give glLayer an initial frame and keep it in sync with the view in
  updateScale while no GL scanout owns it.
- Re-attach and re-size glLayer when the scanout is set back to None
  (e.g. guest reboot back to firmware), instead of leaving it detached.
- Request CGL redraws on glLayer; the view's backing layer no longer
  draws anything.

Assisted-by: Claude:claude-fable-5
2026-07-09 06:45:27 -07:00
osy 268dee8834 virtio-gpu: enable render server for Venus/Neptune on macOS
virtio_gpu_virgl_init() gated VIRGL_RENDERER_RENDER_SERVER behind
#ifndef CONFIG_METAL, so on macOS (CONFIG_METAL defined) the flag was
never set. This virglrenderer build serves Venus/Neptune exclusively
out-of-process via the render-server proxy, so without the flag
proxy_renderer_init() never runs, state.proxy_initialized stays false,
and virgl_renderer_fill_caps(VENUS) leaves the capset zeroed. The guest
Mesa Venus driver then reports "Unsupported wire format version 0" and
vkEnumeratePhysicalDevices fails, leaving llvmpipe as the only device.

Set VIRGL_RENDERER_RENDER_SERVER unconditionally for venus/neptune.
With this, the render servers spawn at init and the guest enumerates the
Venus physical device (Virtio-GPU Venus, DRIVER_ID_MESA_VENUS).

Assisted-by: Claude:claude-opus-4-8
2026-07-05 18:40:28 -07:00
Joelle van Dyne 3263f720f3 cocoa: support scanout of Metal textures
We still require GLES support as a base for now but if Metal is available
and virglrenderer supports native MTLTexture handles, we have a faster
blit path.

Signed-off-by: Joelle van Dyne <[email protected]>
2026-07-05 13:42:22 -07:00
Akihiko Odaki a8a37a3f88 Support Virgil 3D renderer on macOS
Virgil 3D renderer will be available with ui/cocoa on macOS.

ui/cocoa uses OpenGL.framework for the Core profile. ui/cocoa configures
the context using EGL in a way compatible with ANGLE for the ES profile.

Signed-off-by: Akihiko Odaki <[email protected]>
2026-07-05 13:41:48 -07:00
Akihiko Odaki e8a19e64b9 ui/cocoa: Do not automatically zoom for HiDPI
Cocoa automatically zooms for a HiDPI display like Retina and makes
the display blurry. Revert the automatic zooming.

Signed-off-by: Akihiko Odaki <[email protected]>
2026-07-05 11:31:28 -07:00
Akihiko Odaki e115b00da9 ui/cocoa: Use qemu_input_map_osx_to_qcode
ui/cocoa used to have a conversion table from macOS keycode to QKeyCode.
It is an unnecessary redundancy as ui/input-keymap.c already has such a
table. Worse, I added an incorrect mapping of kVK_JIS_Eisu and
kVK_JIS_Kana with commit 708b72557f ("ui/cocoa: Support unique keys of
JIS keyboards").

According to the following documentations, the definitions in
ui/keycodemapdb/keymaps.csv, which ui/input-keymap.c uses, are correct:
https://developer.apple.com/documentation/uikit/uikeyboardhidusage/uikeyboardhidusagekeyboardlang1?language=objc
https://developer.apple.com/documentation/uikit/uikeyboardhidusage/uikeyboardhidusagekeyboardlang2?language=objc
https://docs.microsoft.com/en-us/windows-hardware/design/component-guidelines/keyboard-japan-ime

Use qemu_input_map_osx_to_qcode to eliminate the redundancy and
incorrect mappings.

Fixes: 708b72557f ("ui/cocoa: Support unique keys of JIS keyboards")
Signed-off-by: Akihiko Odaki <[email protected]>
2026-07-05 11:31:24 -07:00
osy a6a16d8dde virtio-gpu-virgl: tear down hostmem region in resource_destroy
Device reset iterates g->reslist via vgc->resource_destroy, which for
the GL device falls through to the base implementation.  The base
destroy frees the resource struct but never tears down a mapped blob's
hostmem MemoryRegion -- the "blob[res_id]" QOM child and its subregion
on b->hostmem are left attached to the device.  The leaked region's
data pointer is then invalidated by the subsequent
virgl_renderer_reset(), and the leftover child object aborts a
subsequent guest MAP_BLOB on the same resource id because
object_initialize_child() rejects the duplicate name.

Override vgc->resource_destroy for the GL device with a virgl-aware
version that tears down the hostmem region, detaches and frees the iov,
and unrefs the renderer resource before chaining into the base destroy.
Promote virtio_gpu_resource_destroy() to a non-static export so
subclasses can chain.

Reset may run while an async RESOURCE_UNMAP_BLOB is in flight, so the
teardown handles each stage: free vmr directly once its finalizer has
run, defer to the finalizer while the subregion is already detached (a
second memory_region_del_subregion() would abort), or tear down
synchronously otherwise.  vmr is not QOM-owned, so each path frees it or
hands it to object_finalize().

Assisted-by: Claude:claude-opus-4-7
Assisted-by: Claude:claude-opus-4-8
2026-05-30 20:36:31 -07:00
osy c4fc99c8b4 virtio-gpu: keep suspended fenced commands at the cmdq head
When virgl_cmd_resource_unmap_blob() or virgl_cmd_resource_unref()
suspends the command to wait for the hostmem MemoryRegion to be freed,
process_cmd returns without calling virgl_renderer_create_fence(), so
no fence has been registered for the command yet.  However, the cmd
still carries VIRTIO_GPU_FLAG_FENCE, so the existing
"!finished && !fenced" check in virtio_gpu_process_cmdq() falls
through and moves the command from cmdq to fenceq.  No fence id will
ever match it in virgl_write_{,context_}fence(), the command sits on
fenceq forever, and g->inflight grows unboundedly.

Track suspend state explicitly on the command and gate the
cmdq-to-fenceq transition on it so the command stays at the head of
cmdq and is re-processed once the async teardown completes.  The
flag is initialized in both handle_ctrl paths since virtqueue_pop()
does not zero the allocation.

Assisted-by: Claude:claude-opus-4-7
2026-05-26 23:33:22 -07:00
Akihiko Odaki 650063be4a virtio-gpu-virgl: Add virtio-gpu-virgl-hostmem-region type
Commit e27194e087 ("virtio-gpu-virgl: correct parent for blob memory
region") made the name member of MemoryRegion unset, causing a NULL
pointer dereference[1]:
> Thread 2 "qemu-system-x86" received signal SIGSEGV, Segmentation fault.
> (gdb) bt
> #0  0x00007ffff56565e2 in __strcmp_evex () at /lib64/libc.so.6
> #1  0x0000555555841bdb in find_fd (head=0x5555572337d0 <cpr_state>,
> name=0x0, id=0) at ../migration/cpr.c:68
> #2  cpr_delete_fd (name=name@entry=0x0, id=id@entry=0) at
> ../migration/cpr.c:77
> #3  0x000055555582290a in qemu_ram_free (block=0x7ff7e93aa7f0) at
> ../system/physmem.c:2615
> #4  0x000055555581ae02 in memory_region_finalize (obj=<optimized out>)
> at ../system/memory.c:1816
> #5  0x0000555555a70ab9 in object_deinit (obj=<optimized out>,
> type=<optimized out>) at ../qom/object.c:715
> #6  object_finalize (data=0x7ff7e936eff0) at ../qom/object.c:729
> #7  object_unref (objptr=0x7ff7e936eff0) at ../qom/object.c:1232
> #8  0x0000555555814fae in memory_region_unref (mr=<optimized out>) at
> ../system/memory.c:1848
> #9  flatview_destroy (view=0x555559ed6c40) at ../system/memory.c:301
> #10 0x0000555555bfc122 in call_rcu_thread (opaque=<optimized out>) at
> ../util/rcu.c:324
> #11 0x0000555555bf17a7 in qemu_thread_start (args=0x555557b99520) at
> ../util/qemu-thread-posix.c:393
> #12 0x00007ffff556f464 in start_thread () at /lib64/libc.so.6
> #13 0x00007ffff55f25ac in __clone3 () at /lib64/libc.so.6

The intention of the aforementioned commit is to prevent a MemoryRegion
from parenting itself while its references is counted indendependently
of the device. To achieve the same goal, add a type of QOM objects that
count references and parent MemoryRegions.

[1] https://lore.kernel.org/qemu-devel/[email protected]/

Cc: [email protected]
Fixes: e27194e087 ("virtio-gpu-virgl: correct parent for blob memory region")
Fixes: 8d5a8ebaaf ("virtio-gpu-virgl: correct parent for blob memory region") in 10.0.x
Signed-off-by: Akihiko Odaki <[email protected].i.u-tokyo.ac.jp>
Tested-by: Dmitry Osipenko <[email protected]>
Tested-by: Joelle van Dyne <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Message-Id: <[email protected].i.u-tokyo.ac.jp>
(cherry picked from commit b2a279094c)
Signed-off-by: Michael Tokarev <[email protected]>
(cherry picked from commit b99e2f4b00)
2026-05-21 22:52:18 -07:00
osyandClaude Opus 4.7 e99e829f38 ui/gtk: fix HiDPI resize event reporting
The GtkGLArea::resize signal delivers width/height in device pixels.
Passing them straight to gd_set_ui_size told the guest to render at
gs× the intended resolution on HiDPI displays. The framebuffer surface
then grew to gs× the logical widget size, while gd_motion_event still
mapped pointer events from the logical widget rect — confining the
guest pointer to the first 1/gs of the surface (the "first quadrant"
on a 200% scaled desktop).

Divide the reported size by the global window scale factor and, in
fixed-scale mode, by the user zoom, so the guest receives buffer-
coordinate dimensions.

Cherry-picked behavior from upstream commit 8fb072472c.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
2026-05-19 20:04:02 -07:00
osy 435e2fc057 virtio-gpu: Support Neptune context
Request Neptune when initializing VirGL and if neptune=true flag is set
for virtio-gpu-gl device. Neptune is a virglrenderer context type that
virtualizes D3D11/D3D12, analogous to how Venus virtualizes Vulkan.

Like Venus, Neptune requires host blob resources and the hostmem memory
window to be enabled.

Assisted-by: Claude:claude-opus-4-7
2026-05-15 20:22:06 -07:00
Paolo Bonzini 7915fda754 linux-headers: update from 6.15 + kvm/next
This brings in the userspace TDX API.

Reviewed-by: Xiaoyao Li <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
2026-04-14 14:09:42 -07:00
myrslint 17cf26aff7 KVM: i386: Default disable ignore guest PAT quirk
Add a new accelerator option that allows the guest to adjust the PAT.
This is already the case for TDX guests and allows using virtio-gpu
Venus with RADV or NVIDIA drivers.

The quirk is disabled by default.  Since this caused problems with
Linux's Bochs video device driver, add a knob to leave it enabled,
and for now do ont enable it by default.

Signed-off-by: Myrsky Lintu <[email protected]>
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/2943
Link: https://lore.kernel.org/r/[email protected]
[Add property; for now leave it off by default. - Paolo]
Signed-off-by: Paolo Bonzini <[email protected]>
2026-04-14 13:59:25 -07:00
Yiwei Zhang d8a30b7576 virtio-gpu: support context init multiple timeline
Venus and later native contexts have their own fence context along with
multiple timelines within. Fences wtih VIRTIO_GPU_FLAG_INFO_RING_IDX in
the flags must be dispatched to be created on the target context. Fence
signaling also has to be handled on the specific timeline within that
target context.

Before this change, venus fencing is completely broken if the host
driver doesn't support implicit fencing with external memory objects.
Frames can go backwards along with random artifacts on screen if the
host driver doesn't attach an implicit fence to the render target. The
symptom could be hidden by certain guest wsi backend that waits on a
venus native VkFence object for the actual payload with limited present
modes or under special configs. e.g. x11 mailbox or xwayland.

After this change, everything related to venus fencing starts making
sense. Confirmed this via guest and host side perfetto tracing.

Cc: [email protected]
Fixes: 94d0ea1c19 ("virtio-gpu: Support Venus context")
Signed-off-by: Yiwei Zhang <[email protected]>
Reviewed-by: Dmitry Osipenko <[email protected]>
Message-Id: <[email protected]>
[AJB: remove version history from commit message]
Tested-by: Dmitry Osipenko <[email protected]>
Signed-off-by: Alex Bennée <[email protected]>
Reviewed-by: Akihiko Odaki <[email protected].i.u-tokyo.ac.jp>
Message-ID: <[email protected]>
2026-04-14 13:58:37 -07:00
osy 9f81c6232f hvf: use private APIs to set IPA size when needed 2026-02-20 22:22:47 -08:00
osy b2babc551d ui/spice-display: support MTLTexture scanout to IOSurface 2026-02-20 22:22:47 -08:00
Joelle van Dyne b3f183123c virtio-gpu-virgl: correct parent for blob memory region
When `owner` == `mr`, `object_unparent` will crash:

object_unparent(mr) ->
object_property_del_child(mr, mr) ->
object_finalize_child_property(mr, name, mr) ->
object_unref(mr) ->
object_finalize(mr) ->
object_property_del_all(mr) ->
object_finalize_child_property(mr, name, mr) ->
object_unref(mr) ->
fail on g_assert(obj->ref > 0)

However, passing a different `owner` to `memory_region_init` does not
work. `memory_region_ref` has an optimization where it takes a ref
only on the owner. That means when flatviews are created, it does not
take a ref on the region and you can get a UAF from `flatview_destroy`
called from RCU.

The correct fix therefore is to use `NULL` as the name which will set
the `owner` but not the `parent` (which is still NULL). This allows us
to use `memory_region_ref` on itself while not having to rely on unparent
for cleanup.

Signed-off-by: Joelle van Dyne <[email protected]>
2026-02-20 22:22:47 -08:00
Joelle van Dyne f7a8c0d523 hvf: support changing IPA granule size
The IPA granule is the smallest page size hv_vm_map() support. For Venus, we
need to support 4KiB pages. macOS 26 introduces a public API for setting
the granule size. We can only use this when compiled with macOS 26 SDK and
run on macOS 26+. Otherwise, we fall back to an older, private, API which
achieves the same purpose.

Signed-off-by: Joelle van Dyne <[email protected]>
2026-02-20 22:22:47 -08:00
Joelle van Dyne 103df0c769 hvf: allow slot size to increase
Instead of having a fixed limit of 32 slots, we allow the number of slots
to expand. Currently there does not seem to be a need to add a limit, but
if the allocation fails, we will abort. The KVM backend was used for
inspiration here.
2026-02-20 22:22:47 -08:00
Joelle van Dyne 9ebfc7b85c hvf: warn when attempting to add unaligned page size
Instead of silently failing, we should print a warning so it is clear why
a future guest access to that location might cause an exception.
2026-02-20 22:22:47 -08:00
Joelle van Dyne b64cf290f7 virtio-gpu-virgl: add support for native blob scanout
On macOS we do not have dmabuf and so we use MTLTexture as our scanout
source. For blob scanout, the buffer is untyped and so we cannot get a
MTLTexture until we pass more information to virglrenderer (surface size,
pixel format, etc). The new API to do this is currently unstable so we
need to define `VIRGL_RENDERER_UNSTABLE_APIS`. This should be removed after
the ABI becomes stable.

Signed-off-by: Joelle van Dyne <[email protected]>
2026-02-20 22:22:47 -08:00
Joelle van Dyne e03f5c90d1 console: add cleanup callback for ScanoutTexture
Before we introduce changes that allow for QemuConsole to take ownership
of a texture handle, we need scaffolding that will allow us to callback
into a cleanup function any time the ScanoutTexture becomes invalid, which
is whenever the `scanout.kind` or `scanout.texture` gets updated.

The ordering is important: we need to first update the DisplayScanout,
then we need to notify all the listeners, and once all the listeners have
had the chance to finish using the previous native texture, we are safe to
call the cleanup function. This means we need to hold on to the previous
scanout native handle locally until all listeners are notified.

Signed-off-by: Joelle van Dyne <[email protected]>
2026-02-20 22:22:47 -08:00
Joelle van Dyne 123780d896 virtio-gpu-virgl: support scanout of Metal textures
When supported, virglrenderer will return a MTLTexture handle that can be
directly used for scanout.

Signed-off-by: Joelle van Dyne <[email protected]>
2026-02-20 22:22:47 -08:00
Joelle van Dyne 4e68da6539 virtio-gpu-virgl: update virglrenderer defines
In order to support additional native texture types, we need to update the
defines in virglrenderer. The changes are backwards compatible and so
builds should work with either the new version or the old version.

https://gitlab.freedesktop.org/virgl/virglrenderer/-/merge_requests/1583

Signed-off-by: Joelle van Dyne <[email protected]>
2026-02-20 22:22:47 -08:00
osy 6136022477 ui/spice-display: support rendering with CGL 2026-02-20 22:22:47 -08:00
osy 435ad1ab54 ui/spice-display: refactor IOSurface code for EGL 2026-02-20 22:22:47 -08:00
osy 58a9b30fc5 ui/egl: rename CONFIG_ANGLE to CONFIG_EGL
Synchronize with @akihikodaki's fork
2026-02-20 22:22:47 -08:00
osy ab61ae603f Revert "egl-headless: Allow to test with Mesa on macOS"
This reverts commit edba23a4d4.
2026-02-20 22:22:47 -08:00
osy 32102c0518 Revert "shaders: support byte swapping of pixels"
This reverts commit e73864e11d.
2026-02-20 22:22:47 -08:00
osy a8b1b963c0 ui/spice-display: move display early init logic to spice-display.c 2026-02-20 22:22:47 -08:00
Joelle van Dyne 3efe3a5992 console: rename d3d_tex2d to native
In order to support native texture scanout beyond D3D, we make this more
generic allowing for multiple native texture handle types.

Signed-off-by: Joelle van Dyne <[email protected]>
2026-02-20 22:22:47 -08:00
Joelle van Dyne f9b62e0ee7 egl-helpers: store handle to native device
Make way for other platforms by making the variable more general. Also we
will be using the device in the future so let's save the pointer in the
global instead of just a boolean flag.

Signed-off-by: Joelle van Dyne <[email protected]>
2026-02-20 22:22:47 -08:00
osy cde37cd6dd Revert "Use virgl_renderer_borrow_texture_for_scanout"
This reverts commit 8b9e3062a4c2e243f0f80482385ebccbb8357f71.
2026-02-20 22:21:33 -08:00
osy 338fdd995e ui/spice-display: fix typo in spice_iosurface_resize 2026-01-02 12:41:52 -08:00
osy 4904c33342 tcg: new JIT workaround for iOS 26
We map the JIT region originally as RX and also mirror map it
as RX. Then we use attached debugger to flag the mirror
mapping as debugger owned. Finally, we change the original map
to RW which should not invalidate code-signing as the mirror
is debugger owned.

Thanks to @JJTech0130 for this workaround.
2025-09-14 11:57:44 -07:00
osy a3955f90f8 hw/i386/pc: no floppy when defaults disabled 2025-08-11 22:24:52 -07:00
osy a172998c2f pc-bios: use 2023 Microsoft UEFI certificates
Restore non-secure vars variants as well.
2025-08-10 22:03:44 -07:00
osy 344a5a3cbe pc-bios: add classicvirtio drivers for m68k/ppc 2025-08-02 19:22:04 -07:00
osy 35ba52817d tcg/tcti: fix goto as first instruction 2025-07-22 10:13:34 -07:00
osy 594fe2f680 tcg/tcti: implement vector immediate shifts
This now seems to be required as a result of the introduction of
gen_gvec_rev{16,32,64} in 38f9950c8e.
2025-07-18 13:29:23 -07:00
Joelle van Dyne 37ba092d59 block: support locking on change medium
New optional argument for 'blockdev-change-medium' QAPI command to allow
the caller to specify if they wish to enable file locking.
2025-07-06 22:18:15 -07:00
osy cb9814d0b6 slirp: update to v4.9.1 2025-07-06 22:15:37 -07:00
osy 6b66fa6047 tcg/tcti: update to support QEMU v10.0 2025-07-06 22:14:39 -07:00
osy 60cd1e9d34 Merge tag 'v10.0.2' into utm-edition
v10.0.2 release
2025-07-06 22:12:32 -07:00
osy 5a4689d9f5 meson: disable strchrnul on Darwin
It is not available on older versions of macOS so it will crash.
2025-07-06 12:12:14 -07:00
Joelle van Dyne c387fd0210 hw/arm/virt: handle hvf with unknown max IPA size
When it is not possible to determine the max IPA bit size, the helper
function will return 0. We do not try to set up the memmap in this case
and instead fall back to the default in machvirt_init().

Signed-off-by: Joelle van Dyne <[email protected]>
2025-07-06 11:56:07 -07:00
Joelle van Dyne cbed46a9a6 hvf: arm: disable unavailable features on older macOS
IPA size queries were introduced in macOS 13. When QEMU is built targeting
a lower version, the compile will fail. If targeting a higher version and
the binary is executed on an older version, QEMU will crash. This will
restore the behaviour before IPA max size querying was added which means
VMs with 64+ GB of RAM will not work if running on < macOS 13.

Signed-off-by: Joelle van Dyne <[email protected]>
2025-07-06 11:56:07 -07:00
Danny Canter eb6eb1fa07 hvf: arm: Implement and use hvf_get_physical_address_range
This patch's main focus is to use the previously added
hvf_get_physical_address_range to inform VM creation
about the IPA size we need for the VM, so we can extend
the default 36b IPA size and support VMs with 64+GB of
RAM. This is done by freezing the memory map, computing
the highest GPA and then (depending on if the platform
supports an IPA size that large) telling the kernel to
use a size >= for the VM. In pursuit of this a couple of
things related to how we handle the physical address range
we expose to guests were altered, but for an explanation of
what we were doing:

Today, to get the IPA size we were reading id_aa64mmfr0_el1's
PARange field from a newly made vcpu. Unfortunately, HVF just
returns the hosts PARange directly for the initial value and
not the IPA size that will actually back the VM, so we believe
we have much more address space than we actually do today it seems.

Starting in macOS 13.0 some APIs were introduced to be able to
query the maximum IPA size the kernel supports, and to set the IPA
size for a given VM. However, this still has a couple of issues
on < macOS 15. Up until macOS 15 (and if the hardware supported
it) the max IPA size was 39 bits which is not a valid PARange
value, so we can't clamp down what we advertise in the vcpu's
id_aa64mmfr0_el1 to our IPA size. Starting in macOS 15 however,
the maximum IPA size is 40 bits (if it's supported in the hardware
as well) which is also a valid PARange value so we can set our IPA
size to the maximum as well as clamp down the PARange we advertise
to the guest. This allows VMs with 64+ GB of RAM and should fix the
oddness of the PARange situation as well.

Signed-off-by: Danny Canter <[email protected]>
Message-id: [email protected]
Reviewed-by: Peter Maydell <[email protected]>
Signed-off-by: Peter Maydell <[email protected]>
2025-07-06 11:55:45 -07:00
Danny Canter fc2f979603 hvf: Split up hv_vm_create logic per arch
This is preliminary work to split up hv_vm_create
logic per platform so we can support creating VMs
with > 64GB of RAM on Apple Silicon machines. This
is done via ARM HVF's hv_vm_config_create() (and
other APIs that modify this config that will be
coming in future patches). This should have no
behavioral difference at all as hv_vm_config_create()
just assigns the same default values as if you just
passed NULL to the function.

Signed-off-by: Danny Canter <[email protected]>
Message-id: [email protected]
Reviewed-by: Peter Maydell <[email protected]>
Signed-off-by: Peter Maydell <[email protected]>
2025-07-06 11:55:45 -07:00
Danny Canter 23c1d05ee4 hw/boards: Add hvf_get_physical_address_range to MachineClass
This addition will be necessary for some HVF related work to follow.
For HVF on ARM there exists a set of APIs in macOS 13 to be able to
adjust the IPA size for a given VM. This is useful as by default HVF
uses 36 bits as the IPA size, so to support guests with > 64GB of RAM
we'll need to reach for this.

To have all the info necessary to carry this out however, we need some
plumbing to be able to grab the memory map and compute the highest GPA
prior to creating the VM. This is almost exactly like what kvm_type is
used for on ARM today, and is also what this will be used for. We will
compute the highest GPA and find what IPA size we'd need to satisfy this,
and if it's valid (macOS today caps at 40b) we'll set this to be the IPA
size in coming patches. This new method is only needed (today at least)
on ARM, and obviously only for HVF/macOS, so admittedly it is much less
generic than kvm_type today, but it seemed a somewhat sane way to get
the information we need from the memmap at VM creation time.

Signed-off-by: Danny Canter <[email protected]>
Message-id: [email protected]
Reviewed-by: Peter Maydell <[email protected]>
[PMM: removed explicit setting of field to NULL on x86]
Signed-off-by: Peter Maydell <[email protected]>
2025-07-06 11:55:45 -07:00
osy a815a0a38d Merge tag 'v9.1.2' into utm-edition
v9.1.2 release
2024-11-23 17:37:12 -08:00
osy d1aea4c51e hvf: arm: support TSO on macOS 15 2024-11-23 17:37:09 -08:00
Michael Tokarev 508081a49b Update version for 9.1.2 release
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-21 00:12:04 +03:00
Guenter Roeck 71c418c4a5 usb-hub: Fix handling port power control messages
The ClearPortFeature control message fails for PORT_POWER because there
is no break; at the end of the case statement, causing it to fall through
to the failure handler. Add the missing break; to solve the problem.

Fixes: 1cc403eb21 ("usb-hub: emulate per port power switching")
Signed-off-by: Guenter Roeck <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit b2cc699979)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-18 19:37:45 +03:00
Paolo Bonzini a7b7953d8d hw/audio/hda: fix memory leak on audio setup
When SET_STREAM_FORMAT is called, the st->buft timer is overwritten, thus
causing a memory leak.  This was originally fixed in commit 816139ae6a5
("hw/audio/hda: fix memory leak on audio setup", 2024-11-14) but that
caused the audio to break in SPICE.

Fortunately, a simpler fix is possible.  The timer only needs to be
reset, because the callback is always the same (st->output is set at
realize time in hda_audio_init); call to timer_new_ns overkill.  Replace
it with timer_del and only initialize the timer once; for simplicity,
do it even if use_timer is false.

An even simpler fix would be to free the old time in hda_audio_setup().
However, it seems better to place the initialization of the timer close
to that of st->ouput.

Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
Reviewed-by: Michael Tokarev <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit 626b39006d)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-18 19:29:56 +03:00
Paolo Bonzini 8d9c6f6fa9 Revert "hw/audio/hda: fix memory leak on audio setup"
This reverts commit 6d03242a7e,
which causes SPICE audio to break.  While arguably this is a SPICE bug,
it is possible to fix the leak in a less heavy-handed way.

Resolves: https://gitlab.com/qemu-project/qemu/-/issues/2639
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
Reviewed-by: Michael Tokarev <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit e125d9835b)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-18 19:29:56 +03:00
Thomas Huth 072d407be3 hw/misc/mos6522: Fix bad class definition of the MOS6522 device
When compiling QEMU with --enable-cfi, the "q800" m68k machine
currently crashes very early, when the q800_machine_init() function
tries to wire the interrupts of the "via1" device.
This happens because TYPE_MOS6522_Q800_VIA1 is supposed to be a
proper SysBus device, but its parent (TYPE_MOS6522) has a mistake
in its class definition where it is only derived from DeviceClass,
and not from SysBusDeviceClass, so we end up in funny memory access
issues here. Using the right class hierarchy for the MOS6522 device
fixes the problem.

Resolves: https://gitlab.com/qemu-project/qemu/-/issues/2675
Signed-off-by: Thomas Huth <[email protected]>
Fixes: 51f233ec92 ("misc: introduce new mos6522 VIA device")
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Mark Cave-Ayland <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit c3d7c18b0d)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-18 19:29:41 +03:00
Cédric Le Goater 019d93004b vfio/container: Fix container object destruction
When commit 96b7af4388 intoduced a .instance_finalize() handler,
it did not take into account that the container was not necessarily
inserted into the container list of the address space. Hence, if
the container object is destroyed, by calling object_unref() for
example, before vfio_address_space_insert() is called, QEMU may
crash when removing the container from the list as done in
vfio_container_instance_finalize(). This was seen with an SEV-SNP
guest for which discarding of RAM fails.

To resolve this issue, use the safe version of QLIST_REMOVE().

Cc: Zhenzhong Duan <[email protected]>
Cc: Eric Auger <[email protected]>
Fixes: 96b7af4388 ("vfio/container: Move vfio_container_destroy() to an instance_finalize() handler")
Reviewed-by: Zhenzhong Duan <[email protected]>
Signed-off-by: Cédric Le Goater <[email protected]>
(cherry picked from commit ebbf7c60bb)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-18 19:29:41 +03:00
Pierrick Bouvier de6c4c8259 target/i386: fix hang when using slow path for ptw_setl
When instrumenting memory accesses for plugin, we force memory accesses
to use the slow path for mmu [1]. This create a situation where we end
up calling ptw_setl_slow. This was fixed recently in [2] but the issue
still could appear out of plugins use case.

Since this function gets called during a cpu_exec, start_exclusive then
hangs. This exclusive section was introduced initially for security
reasons [3].

I suspect this code path was never triggered, because ptw_setl_slow
would always be called transitively from cpu_exec, resulting in a hang.

[1] https://gitlab.com/qemu-project/qemu/-/commit/6d03226b42247b68ab2f0b3663e0f624335a4055
[2] https://gitlab.com/qemu-project/qemu/-/commit/115ade42d50144c15b74368d32dc734ea277d853
[2] https://gitlab.com/qemu-project/qemu/-/commit/3a41aa8226bdaa709121515faea6e0e5ad1efa39 in 9.1.x series
[3] https://gitlab.com/qemu-project/qemu/-/issues/279

Fixes: https://gitlab.com/qemu-project/qemu/-/issues/2566
Signed-off-by: Pierrick Bouvier <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
(cherry picked from commit 7ba055b49b)
Signed-off-by: Michael Tokarev <[email protected]>
(Mjt: mention [2] in 9.1.x series)
2024-11-18 19:29:40 +03:00
Peter Maydell 35e5688153 tcg: Allow top bit of SIMD_DATA_BITS to be set in simd_desc()
In simd_desc() we create a SIMD descriptor from various pieces
including an arbitrary data value from the caller.  We try to
sanitize these to make sure everything will fit: the 'data' value
needs to fit in the SIMD_DATA_BITS (== 22) sized field.  However we
do that sanitizing with:
   tcg_debug_assert(data == sextract32(data, 0, SIMD_DATA_BITS));

This works for the case where the data is supposed to be considered
as a signed integer (which can then be returned via simd_data()).
However, some callers want to treat the data value as unsigned.

Specifically, for the Arm SVE operations, make_svemte_desc()
assembles a data value as a collection of fields, and it needs to use
all 22 bits.  Currently if MTE is enabled then its MTEDESC SIZEM1
field may have the most significant bit set, and then it will trip
this assertion.

Loosen the assertion so that we only check that the data value will
fit into the field in some way, either as a signed or as an unsigned
value.  This means we will fail to detect some kinds of bug in the
callers, but we won't spuriously assert for intentional use of the
data field as unsigned.

Cc: [email protected]
Fixes: db432672dc ("tcg: Add generic vector expanders")
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/2601
Signed-off-by: Peter Maydell <[email protected]>
Message-ID: <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
(cherry picked from commit 8377e3fb85)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-18 19:29:40 +03:00
Richard Henderson e5d832b6d3 linux-user/arm: Select vdso for be8 and be32 modes
In be8 mode, instructions are little-endian.
In be32 mode, instructions are big-endian.

Resolves: https://gitlab.com/qemu-project/qemu/-/issues/2333
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
(cherry picked from commit 95c9e2209c)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-18 19:29:40 +03:00
Richard Henderson 23c24fbfb8 linux-user/arm: Reduce vdso alignment to 4k
Reduce vdso alignment to minimum page size.

Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
(cherry picked from commit f7150b2151)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-18 19:29:40 +03:00
Ilya Leoshkevich b870db1c24 linux-user: Tolerate CONFIG_LSM_MMAP_MIN_ADDR
Running qemu-i386 on a system running with SELinux in enforcing mode
(more precisely: s390x trixie container on Fedora 40) fails with:

    qemu-i386: tests/tcg/i386-linux-user/sigreturn-sigmask: Unable to find a guest_base to satisfy all guest address mapping requirements
      00000000-ffffffff

The reason is that main() determines mmap_min_addr from
/proc/sys/vm/mmap_min_addr, but SELinux additionally defines
CONFIG_LSM_MMAP_MIN_ADDR, which is normally larger: 32K or 64K, but,
in general, can be anything. There is no portable way to query its
value: /boot/config, /proc/config and /proc/config.gz are distro- and
environment-specific.

Once the identity map fails, the magnitude of guest_base does not
matter, so fix by starting the search from 1M or 1G.

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/2598
Suggested-by: Richard Henderson <[email protected]>
Signed-off-by: Ilya Leoshkevich <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
(cherry picked from commit fb7f3572b1)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-18 19:29:40 +03:00
Richard Henderson 6e813172b1 accel/tcg: Fix user-only probe_access_internal plugin check
The acc_flag check for write should have been against PAGE_WRITE_ORG,
not PAGE_WRITE.  But it is better to combine two acc_flag checks
to a single check against access_type.  This matches the system code
in cputlb.c.

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/2647
Signed-off-by: Richard Henderson <[email protected]>
Message-Id: [email protected]
Reviewed-by: Alex Bennée <[email protected]>
(cherry picked from commit 2a339fee45)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-18 19:29:40 +03:00
Richard Henderson a820a85ac8 target/arm: Drop user-only special case in sve_stN_r
This path is reachable with plugins enabled, and provoked
with run-plugin-catch-syscalls-with-libinline.so.

Cc: [email protected]
Reviewed-by: Peter Maydell <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit f275508046)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-18 19:29:40 +03:00
Helge Deller 9699e9f06d linux-user: Fix setreuid and setregid to use direct syscalls
The commit fd6f7798ac ("linux-user: Use direct syscalls for setuid(),
etc") added direct syscall wrappers for setuid(), setgid(), etc since the
system calls have different semantics than the libc functions.

Add and use the corresponding wrappers for setreuid and setregid which
were missed in that commit.

This fixes the build of the debian package of the uid_wrapper library
(https://cwrap.org/uid_wrapper.html) when running linux-user.

Cc: [email protected]
Signed-off-by: Helge Deller <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Reviewed-by: Ilya Leoshkevich <[email protected]>
Message-ID: <Zyo2jMKqq8hG8Pkz@p100>
Signed-off-by: Richard Henderson <[email protected]>
(cherry picked from commit 8491026a08)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-18 19:29:40 +03:00
Peter Maydell 494d6b81fe hw/i386/pc: Don't try to init PCI NICs if there is no PCI bus
The 'isapc' machine type has no PCI bus, but pc_nic_init() still
calls pci_init_nic_devices() passing it a NULL bus pointer.  This
causes the clang sanitizer to complain:

$ ./build/clang/qemu-system-i386 -M isapc
../../hw/pci/pci.c:1866:39: runtime error: member access within null pointer of type 'PCIBus' (aka 'struct PCIBus')
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior ../../hw/pci/pci.c:1866:39 in

This is because pci_init_nic_devices() does
 &bus->qbus
which is undefined behaviour on a NULL pointer even though we're not
actually dereferencing the pointer. (We don't actually crash as
a result, so if you aren't running a sanitizer build then there
are no user-visible effects.)

Make pc_nic_init() avoid trying to initialize PCI NICs on a non-PCI
system.

Cc: [email protected]
Fixes: 8d39f9ba14 ("hw/i386/pc: use qemu_get_nic_info() and pci_init_nic_devices()")
Signed-off-by: Peter Maydell <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit bd0e501e1a)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-18 19:29:40 +03:00
Alexander Graf f7ff24a6e9 target/i386: Fix legacy page table walk
Commit b56617bbcb ("target/i386: Walk NPT in guest real mode") added
logic to run the page table walker even in real mode if we are in NPT
mode.  That function then determined whether real mode or paging is
active based on whether the pg_mode variable was 0.

Unfortunately pg_mode is 0 in two situations:

  1) Paging is disabled (real mode)
  2) Paging is in 2-level paging mode (32bit without PAE)

That means the walker now assumed that 2-level paging mode was real
mode, breaking NetBSD as well as Windows XP.

To fix that, this patch adds a new PG flag to pg_mode which indicates
whether paging is active at all and uses that to determine whether we
are in real mode or not.

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/2654
Fixes: b56617bbcb ("target/i386: Walk NPT in guest real mode")
Fixes: 01bfc2e295 (commit b56617bbcb in stable-9.1.x series)
Signed-off-by: Alexander Graf <[email protected]>
Reported-by: Mark Cave-Ayland <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 8fa11a4df3)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-18 19:29:40 +03:00
Christian Schoenebeck 3d28b84487 9pfs: fix crash on 'Treaddir' request
A bad (broken or malicious) 9p client (guest) could cause QEMU host to
crash by sending a 9p 'Treaddir' request with a numeric file ID (FID) that
was previously opened for a file instead of an expected directory:

  #0  0x0000762aff8f4919 in __GI___rewinddir (dirp=0xf) at
    ../sysdeps/unix/sysv/linux/rewinddir.c:29
  #1  0x0000557b7625fb40 in do_readdir_many (pdu=0x557bb67d2eb0,
    fidp=0x557bb67955b0, entries=0x762afe9fff58, offset=0, maxsize=131072,
    dostat=<optimized out>) at ../hw/9pfs/codir.c:101
  #2  v9fs_co_readdir_many (pdu=pdu@entry=0x557bb67d2eb0,
    fidp=fidp@entry=0x557bb67955b0, entries=entries@entry=0x762afe9fff58,
    offset=0, maxsize=131072, dostat=false) at ../hw/9pfs/codir.c:226
  #3  0x0000557b7625c1f9 in v9fs_do_readdir (pdu=0x557bb67d2eb0,
    fidp=0x557bb67955b0, offset=<optimized out>,
    max_count=<optimized out>) at ../hw/9pfs/9p.c:2488
  #4  v9fs_readdir (opaque=0x557bb67d2eb0) at ../hw/9pfs/9p.c:2602

That's because V9fsFidOpenState was declared as union type. So the
same memory region is used for either an open POSIX file handle (int),
or a POSIX DIR* pointer, etc., so 9p server incorrectly used the
previously opened (valid) POSIX file handle (0xf) as DIR* pointer,
eventually causing a crash in glibc's rewinddir() function.

Root cause was therefore a missing check in 9p server's 'Treaddir'
request handler, which must ensure that the client supplied FID was
really opened as directory stream before trying to access the
aforementioned union and its DIR* member.

Cc: [email protected]
Fixes: d62dbb51f7 ("virtio-9p: Add fidtype so that we can do type ...")
Reported-by: Akihiro Suda <[email protected]>
Tested-by: Akihiro Suda <[email protected]>
Signed-off-by: Christian Schoenebeck <[email protected]>
Reviewed-by: Greg Kurz <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit 042b4ebfd2)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-08 20:42:08 +03:00
Klaus Jensen c5e48f281d hw/nvme: fix handling of over-committed queues
If a host chooses to use the SQHD "hint" in the CQE to know if there is
room in the submission queue for additional commands, it may result in a
situation where there are not enough internal resources (struct
NvmeRequest) available to process the command. For a lack of a better
term, the host may "over-commit" the device (i.e., it may have more
inflight commands than the queue size).

For example, assume a queue with N entries. The host submits N commands
and all are picked up for processing, advancing the head and emptying
the queue. Regardless of which of these N commands complete first, the
SQHD field of that CQE will indicate to the host that the queue is
empty, which allows the host to issue N commands again. However, if the
device has not posted CQEs for all the previous commands yet, the device
will have less than N resources available to process the commands, so
queue processing is suspended.

And here lies an 11 year latent bug. In the absense of any additional
tail updates on the submission queue, we never schedule the processing
bottom-half again unless we observe a head update on an associated full
completion queue. This has been sufficient to handle N-to-1 SQ/CQ setups
(in the absense of over-commit of course). Incidentially, that "kick all
associated SQs" mechanism can now be killed since we now just schedule
queue processing when we return a processing resource to a non-empty
submission queue, which happens to cover both edge cases. However, we
must retain kicking the CQ if it was previously full.

So, apparently, no previous driver tested with hw/nvme has ever used
SQHD (e.g., neither the Linux NVMe driver or SPDK uses it). But then OSv
shows up with the driver that actually does. I salute you.

Fixes: f3c507adcd ("NVMe: Initial commit for new storage interface")
Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/2388
Reported-by: Waldemar Kozaczuk <[email protected]>
Reviewed-by: Keith Busch <[email protected]>
Signed-off-by: Klaus Jensen <[email protected]>
(cherry picked from commit 9529aa6bb4)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-08 20:41:36 +03:00
Hanna Czenczek 0098207eb1 migration: Ensure vmstate_save() sets errp
migration/savevm.c contains some calls to vmstate_save() that are
followed by migrate_set_error() if the integer return value indicates an
error.  migrate_set_error() requires that the `Error *` object passed to
it is set.  Therefore, vmstate_save() is assumed to always set *errp on
error.

Right now, that assumption is not met: vmstate_save_state_v() (called
internally by vmstate_save()) will not set *errp if
vmstate_subsection_save() or vmsd->post_save() fail.  Fix that by adding
an *errp parameter to vmstate_subsection_save(), and by generating a
generic error in case post_save() fails (as is already done for
pre_save()).

Without this patch, qemu will crash after vmstate_subsection_save() or
post_save() have failed inside of a vmstate_save() call (unless
migrate_set_error() then happen to discard the new error because
s->error is already set).  This happens e.g. when receiving the state
from a virtio-fs back-end (virtiofsd) fails.

Signed-off-by: Hanna Czenczek <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Peter Xu <[email protected]>
(cherry picked from commit 37dfcba1a0)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-06 23:09:09 +03:00
Peter Maydell 5e29203bc7 target/arm: Fix SVE SDOT/UDOT/USDOT (4-way, indexed)
Our implementation of the indexed version of SVE SDOT/UDOT/USDOT got
the calculation of the inner loop terminator wrong.  Although we
correctly account for the element size when we calculate the
terminator for the first iteration:
   intptr_t segend = MIN(16 / sizeof(TYPED), opr_sz_n);
we don't do that when we move it forward after the first inner loop
completes.  The intention is that we process the vector in 128-bit
segments, which for a 64-bit element size should mean (1, 2), (3, 4),
(5, 6), etc.  This bug meant that we would iterate (1, 2), (3, 4, 5,
6), (7, 8, 9, 10) etc and apply the wrong indexed element to some of
the operations, and also index off the end of the vector.

You don't see this bug if the vector length is small enough that we
don't need to iterate the outer loop, i.e.  if it is only 128 bits,
or if it is the 64-bit special case from AA32/AA64 AdvSIMD.  If the
vector length is 256 bits then we calculate the right results for the
elements in the vector but do index off the end of the vector. Vector
lengths greater than 256 bits see wrong answers. The instructions
that produce 32-bit results behave correctly.

Fix the recalculation of 'segend' for subsequent iterations, and
restore a version of the comment that was lost in the refactor of
commit 7020ffd656 that explains why we only need to clamp segend to
opr_sz_n for the first iteration, not the later ones.

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/2595
Fixes: 7020ffd656 ("target/arm: Macroize helper_gvec_{s,u}dot_idx_{b,h}")
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Message-id: [email protected]
(cherry picked from commit e6b2fa1b81)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-06 15:36:11 +03:00
Peter Maydell 6d62f309f8 target/arm: Add new MMU indexes for AArch32 Secure PL1&0
Our current usage of MMU indexes when EL3 is AArch32 is confused.
Architecturally, when EL3 is AArch32, all Secure code runs under the
Secure PL1&0 translation regime:
 * code at EL3, which might be Mon, or SVC, or any of the
   other privileged modes (PL1)
 * code at EL0 (Secure PL0)

This is different from when EL3 is AArch64, in which case EL3 is its
own translation regime, and EL1 and EL0 (whether AArch32 or AArch64)
have their own regime.

We claimed to be mapping Secure PL1 to our ARMMMUIdx_EL3, but didn't
do anything special about Secure PL0, which meant it used the same
ARMMMUIdx_EL10_0 that NonSecure PL0 does.  This resulted in a bug
where arm_sctlr() incorrectly picked the NonSecure SCTLR as the
controlling register when in Secure PL0, which meant we were
spuriously generating alignment faults because we were looking at the
wrong SCTLR control bits.

The use of ARMMMUIdx_EL3 for Secure PL1 also resulted in the bug that
we wouldn't honour the PAN bit for Secure PL1, because there's no
equivalent _PAN mmu index for it.

Fix this by adding two new MMU indexes:
 * ARMMMUIdx_E30_0 is for Secure PL0
 * ARMMMUIdx_E30_3_PAN is for Secure PL1 when PAN is enabled
The existing ARMMMUIdx_E3 is used to mean "Secure PL1 without PAN"
(and would be named ARMMMUIdx_E30_3 in an AArch32-centric scheme).

These extra two indexes bring us up to the maximum of 16 that the
core code can currently support.

This commit:
 * adds the new MMU index handling to the various places
   where we deal in MMU index values
 * adds assertions that we aren't AArch32 EL3 in a couple of
   places that currently use the E10 indexes, to document why
   they don't also need to handle the E30 indexes
 * documents in a comment why regime_has_2_ranges() doesn't need
   updating

Notes for backporting: this commit depends on the preceding revert of
4c2c04746932; that revert and this commit should probably be
backported to everywhere that we originally backported 4c2c047469.

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/2326
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/2588
Signed-off-by: Peter Maydell <[email protected]>
Tested-by: Thomas Huth <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Message-id: [email protected]
(cherry picked from commit efbe180ad2)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-06 15:36:11 +03:00
Peter Maydell f147ed377a Revert "target/arm: Fix usage of MMU indexes when EL3 is AArch32"
This reverts commit 4c2c047469.

This commit tried to fix a problem with our usage of MMU indexes when
EL3 is AArch32, using what it described as a "more complicated
approach" where we share the same MMU index values for Secure PL1&0
and NonSecure PL1&0. In theory this should work, but the change
didn't account for (at least) two things:

(1) The design change means we need to flush the TLBs at any point
where the CPU state flips from one to the other.  We already flush
the TLB when SCR.NS is changed, but we don't flush the TLB when we
take an exception from NS PL1&0 into Mon or when we return from Mon
to NS PL1&0, and the commit didn't add any code to do that.

(2) The ATS12NS* address translate instructions allow Mon code (which
is Secure) to do a stage 1+2 page table walk for NS.  I thought this
was OK because do_ats_write() does a page table walk which doesn't
use the TLBs, so because it can pass both the MMU index and also an
ARMSecuritySpace argument we can tell the table walk that we want NS
stage1+2, not S.  But that means that all the code within the ptw
that needs to find e.g.  the regime EL cannot do so only with an
mmu_idx -- all these functions like regime_sctlr(), regime_el(), etc
would need to pass both an mmu_idx and the security_space, so they
can tell whether this is a translation regime controlled by EL1 or
EL3 (and so whether to look at SCTLR.S or SCTLR.NS, etc).

In particular, because regime_el() wasn't updated to look at the
ARMSecuritySpace it would return 1 even when the CPU was in Monitor
mode (and the controlling EL is 3).  This meant that page table walks
in Monitor mode would look at the wrong SCTLR, TCR, etc and would
generally fault when they should not.

Rather than trying to make the complicated changes needed to rescue
the design of 4c2c047469, we revert it in order to instead take the
route that that commit describes as "the most straightforward" fix,
where we add new MMU indexes EL30_0, EL30_3, EL30_3_PAN to correspond
to "Secure PL1&0 at PL0", "Secure PL1&0 at PL1", and "Secure PL1&0 at
PL1 with PAN".

This revert will re-expose the "spurious alignment faults in
Secure PL0" issue #2326; we'll fix it again in the next commit.

Cc: [email protected]
Signed-off-by: Peter Maydell <[email protected]>
Tested-by: Thomas Huth <[email protected]>
Message-id: [email protected]
Reviewed-by: Richard Henderson <[email protected]>
(cherry picked from commit 056c5c90c1)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-06 15:36:11 +03:00
Michael S. Tsirkin 19b80ef0b5 acpi/disassemle-aml.sh: fix up after dir reorg
We moved expected files around, fix up the disassembler script.

Fixes: 7c08eefcaf ("tests/data/acpi: Move x86 ACPI tables under x86/${machine} path")
Fixes: 7434f90467 ("tests/data/acpi/virt: Move ARM64 ACPI tables under aarch64/${machine} path")
Cc: "Sunil V L" <[email protected]>
Message-ID: <ce456091058734b7f765617ac5dfeebcb366d4a9.1730729695.git.mst@redhat.com>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Acked-by: Igor Mammedov <[email protected]>
(cherry picked from commit feb58e3b26)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-06 15:19:07 +03:00
Jonathan Cameron 7ee7418dae hw/acpi: Fix ordering of BDF in Generic Initiator PCI Device Handle.
The ordering in ACPI specification [1] has bus number in the lowest byte.
As ACPI tables are little endian this is the reverse of the ordering
used by PCI_BUILD_BDF().  As a minimal fix split the QEMU BDF up
into bus and devfn and write them as single bytes in the correct
order.

[1] ACPI Spec 6.3, Table 5.80

Fixes: 0a5b5acdf2 ("hw/acpi: Implement the SRAT GI affinity structure")
Reviewed-by: Igor Mammedov <[email protected]>
Tested-by: "Huang, Ying" <[email protected]>
Signed-off-by: Jonathan Cameron <[email protected]>
Message-Id: <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
(cherry picked from commit 16c687d845)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-06 15:01:58 +03:00
Sunil Nimmagadda fac933cae4 qemu-ga: Fix a SIGSEGV in ga_run_command() helper
qemu-ga on a NetBSD -current VM terminates with a SIGSEGV upon receiving
'guest-set-time' command...

Core was generated by `qemu-ga'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0  0x000000000cd37a40 in ga_pipe_read_str (fd=fd@entry=0xffffff922a20, str=str@entry=0xffffff922a18)
    at ../qga/commands-posix.c:88
88	        *str[len] = '\0';
[Current thread is 1 (process 1112)]
(gdb) bt
#0  0x000000000cd37a40 in ga_pipe_read_str (fd=fd@entry=0xffffff922a20, str=str@entry=0xffffff922a18)
    at ../qga/commands-posix.c:88
#1  0x000000000cd37b60 in ga_run_command (argv=argv@entry=0xffffff922a90,
    action=action@entry=0xcda34b8 "set hardware clock to system time", errp=errp@entry=0xffffff922a70, in_str=0x0)
    at ../qga/commands-posix.c:164
#2  0x000000000cd380c4 in qmp_guest_set_time (has_time=<optimized out>, time_ns=<optimized out>,
    errp=errp@entry=0xffffff922ad0) at ../qga/commands-posix.c:304
#3  0x000000000cd253d8 in qmp_marshal_guest_set_time (args=<optimized out>, ret=<optimized out>, errp=0xffffff922b48)
    at qga/qga-qapi-commands.c:193
#4  0x000000000cd4e71c in qmp_dispatch (cmds=cmds@entry=0xcdf5b18 <ga_commands>, request=request@entry=0xf3c711a4b000,
    allow_oob=allow_oob@entry=false, cur_mon=cur_mon@entry=0x0) at ../qapi/qmp-dispatch.c:220
#5  0x000000000cd36524 in process_event (opaque=0xf3c711a79000, obj=0xf3c711a4b000, err=0x0) at ../qga/main.c:677
#6  0x000000000cd526f0 in json_message_process_token (lexer=lexer@entry=0xf3c711a79018, input=0xf3c712072480,
    type=type@entry=JSON_RCURLY, x=28, y=1) at ../qobject/json-streamer.c:99
#7  0x000000000cd93860 in json_lexer_feed_char (lexer=lexer@entry=0xf3c711a79018, ch=125 '}', flush=flush@entry=false)
    at ../qobject/json-lexer.c:313
#8  0x000000000cd93a00 in json_lexer_feed (lexer=lexer@entry=0xf3c711a79018,
    buffer=buffer@entry=0xffffff922d10 "{\"execute\":\"guest-set-time\"}\n", size=<optimized out>)
    at ../qobject/json-lexer.c:350
#9  0x000000000cd5290c in json_message_parser_feed (parser=parser@entry=0xf3c711a79000,
    buffer=buffer@entry=0xffffff922d10 "{\"execute\":\"guest-set-time\"}\n", size=<optimized out>)
    at ../qobject/json-streamer.c:121
#10 0x000000000cd361fc in channel_event_cb (condition=<optimized out>, data=0xf3c711a79000) at ../qga/main.c:703
#11 0x000000000cd3710c in ga_channel_client_event (channel=<optimized out>, condition=<optimized out>, data=0xf3c711b2d300)
    at ../qga/channel-posix.c:94
#12 0x0000f3c7120d9bec in g_main_dispatch () from /usr/pkg/lib/libglib-2.0.so.0
#13 0x0000f3c7120dd25c in g_main_context_iterate_unlocked.constprop () from /usr/pkg/lib/libglib-2.0.so.0
#14 0x0000f3c7120ddbf0 in g_main_loop_run () from /usr/pkg/lib/libglib-2.0.so.0
#15 0x000000000cda00d8 in run_agent_once (s=0xf3c711a79000) at ../qga/main.c:1522
#16 run_agent (s=0xf3c711a79000) at ../qga/main.c:1559
#17 main (argc=<optimized out>, argv=<optimized out>) at ../qga/main.c:1671
(gdb)

The commandline options used on the host machine...
qemu-system-aarch64 \
   -machine type=virt,pflash0=rom \
   -m 8G \
   -cpu host \
   -smp 8 \
   -accel hvf \
   -device virtio-net-pci,netdev=unet \
   -device virtio-blk-pci,drive=hd \
   -drive file=netbsd.qcow2,if=none,id=hd \
   -netdev user,id=unet,hostfwd=tcp::2223-:22 \
   -object rng-random,filename=/dev/urandom,id=viornd0 \
   -device virtio-rng-pci,rng=viornd0 \
   -serial mon:stdio \
   -display none \
   -blockdev node-name=rom,driver=file,filename=/opt/homebrew/Cellar/qemu/9.0.2/share/qemu/edk2-aarch64-code.fd,read-only=true \
   -chardev socket,path=/tmp/qga_netbsd.sock,server=on,wait=off,id=qga0 \
   -device virtio-serial \
   -device virtconsole,chardev=qga0,name=org.qemu.guest_agent.0

This patch rectifies the operator precedence while assigning the NUL
terminator.

Fixes: c3f32c13a3

Signed-off-by: Sunil Nimmagadda <[email protected]>
Reviewed-by: Konstantin Kostiuk <[email protected]>
Reviewed-by: Daniel P. Berrangé <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Konstantin Kostiuk <[email protected]>
(cherry picked from commit 9cfe110d9f)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-06 15:00:18 +03:00
Jan Luebbe e30319cddd hw/sd/sdcard: Fix calculation of size when using eMMC boot partitions
The sd_bootpart_offset() function calculates the *runtime* offset which
changes as the guest switches between accessing the main user data area
and the boot partitions by writing to the EXT_CSD_PART_CONFIG_ACC_MASK
bits, so it shouldn't be used to calculate the main user data area size.

Instead, subtract the boot_part_size directly (twice, as there are two
identical boot partitions defined by the eMMC spec).

Suggested-by: Cédric Le Goater <[email protected]>
Signed-off-by: Jan Luebbe <[email protected]>
Fixes: c8cb19876d ("hw/sd/sdcard: Support boot area in emmc image")
Tested-by: Guenter Roeck <[email protected]>
Reviewed-by: Cédric Le Goater <[email protected]>
(cherry picked from commit c078298301)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-05 19:14:12 +03:00
Ilya Leoshkevich cbfbd13346 tests/tcg: Replace -mpower8-vector with -mcpu=power8
[1] deprecated -mpower8-vector, resulting in:

    powerpc64-linux-gnu-gcc: warning: switch '-mpower8-vector' is no longer supported
    qemu/tests/tcg/ppc64/vsx_f2i_nan.c:4:15: error: expected ';' before 'float'
        4 | typedef vector float vsx_float32_vec_t;
          |               ^~~~~~

Use -mcpu=power8 instead. In order to properly verify that this works,
one needs a big-endian (the minimum supported CPU for 64-bit
little-endian is power8 anyway) GCC configured with --enable-checking
(see GCC commit e154242724b0 ("[RS6000] Don't pass -many to the
assembler").

[1] https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109987

Cc: [email protected]
Signed-off-by: Ilya Leoshkevich <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Acked-by: Alex Bennée <[email protected]>
Signed-off-by: Nicholas Piggin <[email protected]>
(cherry picked from commit ddf4dd46e5)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-05 18:59:18 +03:00
Chalapathi V 2a5eec6dd2 hw/ssi/pnv_spi: Fixes Coverity CID 1558831
In this commit the following coverity scan defect has been fixed
CID 1558831:  Resource leaks  (RESOURCE_LEAK)
  Variable "rsp_payload" going out of scope leaks the storage it
  points to.

Cc: [email protected]
Fixes: Coverity CID 1558831
Signed-off-by: Chalapathi V <[email protected]>
Fixes: b4cb930e40 ("hw/ssi: Extend SPI model")
[PMD: Rebased on previous commit (returning earlier)]
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Nicholas Piggin <[email protected]>
(cherry picked from commit 031324472e)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-05 18:59:01 +03:00
Philippe Mathieu-Daudé 2408ff818d hw/ssi/pnv_spi: Return early in transfer()
Return early to simplify next commit.
No logical change intended.

Cc: [email protected]
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: Nicholas Piggin <[email protected]>
(cherry picked from commit 3feabc18ad)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-05 18:58:37 +03:00
Philippe Mathieu-Daudé 5d305310c4 hw/ssi/pnv_spi: Match _xfer_buffer_free() with _xfer_buffer_new()
pnv_spi_xfer_buffer_new() allocates %payload using g_malloc0(),
and pnv_spi_xfer_buffer_write_ptr() allocates %payload->data
using g_realloc(). Use the API equivalent g_free() to release
the buffers.

Cc: [email protected]
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Nicholas Piggin <[email protected]>
(cherry picked from commit 65f53702d2)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-05 18:58:08 +03:00
Nicholas Piggin a16570419b ppc/pnv: ADU fix possible buffer overrun with invalid size
The ADU LPC transfer-size field is 7 bits, but the supported sizes for
LPC access via ADU appear to be 1, 2, 4, 8. The data buffer could
overrun if firmware set an invalid size field, so add checks to reject
them with a message.

Cc: [email protected]
Reported-by: Cédric Le Goater <[email protected]>
Resolves: Coverity CID 1558830
Fixes: 24bd283bcc ("ppc/pnv: Implement ADU access to LPC space")
Reviewed-by: Cédric Le Goater <[email protected]>
Signed-off-by: Nicholas Piggin <[email protected]>
(cherry picked from commit ddd2a060a0)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-05 18:57:35 +03:00
Nicholas Piggin 963bfe9c62 target/ppc: Fix HFSCR facility checks
The HFSCR defines were being encoded as bit masks, but the users
expect (and analogous FSCR defines are) bit numbers.

Cc: [email protected]
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Nicholas Piggin <[email protected]>
(cherry picked from commit 87de77f6ae)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-05 18:42:01 +03:00
Nicholas Piggin 2a14b2f441 target/ppc: Fix mtDPDES targeting SMT siblings
A typo in the loop over SMT threads to set irq level for doorbells
when storing to DPDES meant everything was aimed at the CPU executing
the instruction.

Cc: [email protected]
Fixes: d24e80b2ae ("target/ppc: Add msgsnd/p and DPDES SMT support")
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Nicholas Piggin <[email protected]>
(cherry picked from commit 0324d236d2)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-05 18:41:42 +03:00
Nicholas Piggin 3583e93223 ppc/pnv: Fix LPC POWER8 register sanity check
POWER8 does not have the ISA IRQ -> SERIRQ routing system of later
CPUs, instead all ISA IRQs are sent to the CPU via a single PSI
interrupt. There is a sanity check in the POWER8 case to ensure the
routing bits have not been set, because that would indicate a
programming error.

Those bits were incorrectly specified because of ppc bit numbering
fun. Coverity detected this as an always-zero expression.

Cc: [email protected]
Reported-by: Cédric Le Goater <[email protected]>
Resolves: Coverity CID 1558829 (partially)
Reviewed-by: Cédric Le Goater <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Nicholas Piggin <[email protected]>
(cherry picked from commit 84416e262e)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-05 18:40:58 +03:00
Nicholas Piggin afbd6b5077 ppc/pnv: Fix LPC serirq routing calculation
The serirq routing table is split over two registers, the calculation
for the high irqs in the second register did not subtract the irq
offset. This was spotted by Coverity as a shift-by-negative. Fix this
and change the open-coded shifting and masking to use extract32()
function so it's less error-prone.

This went unnoticed because irqs >= 14 are not used in a standard
QEMU/OPAL boot, changing the first QEMU serial-isa irq to 14 to test
does demonstrate serial irqs aren't received, and that this change
fixes that.

Cc: [email protected]
Reported-by: Cédric Le Goater <[email protected]>
Resolves: Coverity CID 1558829 (partially)
Reviewed-by: Cédric Le Goater <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Nicholas Piggin <[email protected]>
(cherry picked from commit 899e488650)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-05 18:38:34 +03:00
Ilya Leoshkevich 84fb165d96 target/ppc: Make divd[u] handler method decodetree compatible
This is like commit 86e6202a57 ("target/ppc: Make divw[u] handler
method decodetree compatible."), but for gen_op_arith_divd().

Cc: [email protected]
Suggested-by: Richard Henderson <[email protected]>
Signed-off-by: Ilya Leoshkevich <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: Nicholas Piggin <[email protected]>
(cherry picked from commit 7b4820a3e1)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-05 18:23:22 +03:00
Ilya Leoshkevich 563d60e921 target/ppc: Set ctx->opcode for decode_insn32()
divdu (without a dot) sometimes updates cr0, even though it shouldn't.
The reason is that gen_op_arith_divd() checks Rc(ctx->opcode), which is
not initialized. This field is initialized only for instructions that
go through decode_legacy(), and not decodetree.

There already was a similar issue fixed in commit 86e6202a57
("target/ppc: Make divw[u] handler method decodetree compatible.").

It's not immediately clear what else may access the uninitialized
ctx->opcode, so instead of playing whack-a-mole and changing the check
to compute_rc0, simply initialize ctx->opcode.

Cc: [email protected]
Fixes: 99082815f1 ("target/ppc: Add infrastructure for prefixed insns")
Reviewed-by: Richard Henderson <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: Ilya Leoshkevich <[email protected]>
Signed-off-by: Nicholas Piggin <[email protected]>
(cherry picked from commit c9b8a13a88)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-05 18:22:57 +03:00
Anton Blanchard 56478d5a5e target/riscv: Fix vcompress with rvv_ta_all_1s
vcompress packs vl or less fields into vd, so the tail starts after the
last packed field. This could be more clearly expressed in the ISA,
but for now this thread helps to explain it:

https://github.com/riscv/riscv-v-spec/issues/796

Signed-off-by: Anton Blanchard <[email protected]>
Reviewed-by: Daniel Henrique Barboza <[email protected]>
Reviewed-by: Alistair Francis <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit c128d39ede)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-05 10:39:06 +03:00
Daniel Henrique Barboza 19a4974ca7 target/riscv/kvm: clarify how 'riscv-aia' default works
We do not have control in the default 'riscv-aia' default value. We can
try to set it to a specific value, in this case 'auto', but there's no
guarantee that the host will accept it.

Couple with this we're always doing a 'qemu_log' to inform whether we're
ended up using the host default or if we managed to set the AIA mode to
the QEMU default we wanted to set.

Change the 'riscv-aia' description to better reflect how the option
works, and remove the two informative 'qemu_log' that are now unneeded:
if no message shows, riscv-aia was set to the default or uset-set value.

Signed-off-by: Daniel Henrique Barboza <[email protected]>
Acked-by: Alistair Francis <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit fd16cfb299)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-05 10:38:53 +03:00
Daniel Henrique Barboza 7f9dc099c7 target/riscv/kvm: set 'aia_mode' to default in error path
When failing to set the selected AIA mode, 'aia_mode' is left untouched.
This means that 'aia_mode' will not reflect the actual AIA mode,
retrieved in 'default_aia_mode',

This is benign for now, but it will impact QMP query commands that will
expose the 'aia_mode' value, retrieving the wrong value.

Set 'aia_mode' to 'default_aia_mode' if we fail to change the AIA mode
in KVM.

While we're at it, rework the log/warning messages to be a bit less
verbose. Instead of:

KVM AIA: default mode is emul
qemu-system-riscv64: warning: KVM AIA: failed to set KVM AIA mode

We can use a single warning message:

qemu-system-riscv64: warning: KVM AIA: failed to set KVM AIA mode 'auto', using default host mode 'emul'

Signed-off-by: Daniel Henrique Barboza <[email protected]>
Acked-by: Alistair Francis <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit d201a127e1)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-05 10:38:31 +03:00
Yong-Xuan Wang 2a5c4a91ca hw/intc/riscv_aplic: Check and update pending when write sourcecfg
The section 4.5.2 of the RISC-V AIA specification says that any write
to a sourcecfg register of an APLIC might (or might not) cause the
corresponding interrupt-pending bit to be set to one if the rectified
input value is high (= 1) under the new source mode.

If an interrupt is asserted before the driver configs its interrupt
type to APLIC, it's pending bit will not be set except a relevant
write to a setip or setipnum register. When we write the interrupt
type to sourcecfg register, if the APLIC device doesn't check
rectified input value and update the pending bit, this interrupt
might never becomes pending.

For APLIC.m, we can manully set pending by setip or setipnum
registers in driver. But for APLIC.w, the pending status totally
depends on the rectified input value, we can't control the pending
status via mmio registers. In this case, hw should check and update
pending status for us when writing sourcecfg registers.

Update QEMU emulation to handle "pre-existing" interrupts.

Signed-off-by: Yong-Xuan Wang <[email protected]>
Acked-by: Alistair Francis <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit 2ae6cca1d3)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-05 10:28:23 +03:00
Rob Bradford 08c6ed47e6 target/riscv: Set vtype.vill on CPU reset
The RISC-V unprivileged specification "31.3.11. State of Vector
Extension at Reset" has a note that recommends vtype.vill be set on
reset as part of ensuring that the vector extension have a consistent
state at reset.

This change now makes QEMU consistent with Spike which sets vtype.vill
on reset.

Signed-off-by: Rob Bradford <[email protected]>
Reviewed-by: Daniel Henrique Barboza <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit f8c1f36a2e)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-05 10:28:06 +03:00
Sergey Makarov 59fad1ebad hw/intc: Don't clear pending bits on IRQ lowering
According to PLIC specification (chapter 5), there
is only one case, when interrupt is claimed. Fix
PLIC controller to match this behavior.

Signed-off-by: Sergey Makarov <[email protected]>
Reviewed-by: Alistair Francis <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit a84be2baa9)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-05 10:27:44 +03:00
TANG Tiancheng 1c627d7265 target/riscv: Correct SXL return value for RV32 in RV64 QEMU
Ensure that riscv_cpu_sxl returns MXL_RV32 when runningRV32 in an
RV64 QEMU.

Signed-off-by: TANG Tiancheng <[email protected]>
Fixes: 05e6ca5e15 ("target/riscv: Ignore reserved bits in PTE for RV64")
Reviewed-by: Liu Zhiwei <[email protected]>
Reviewed-by: Alistair Francis <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit 929e4277c1)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-05 10:23:48 +03:00
Evgenii Prokopiev 646746a131 target/riscv/csr.c: Fix an access to VXSAT
The register VXSAT should be RW only to the first bit.
The remaining bits should be 0.

The RISC-V Instruction Set Manual Volume I: Unprivileged Architecture

The vxsat CSR has a single read-write least-significant bit (vxsat[0])
that indicates if a fixed-point instruction has had to saturate an output
value to fit into a destination format. Bits vxsat[XLEN-1:1]
should be written as zeros.

Signed-off-by: Evgenii Prokopiev <[email protected]>
Reviewed-by: Daniel Henrique Barboza <[email protected]>
Reviewed-by: Alistair Francis <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit 5a60026cad)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-05 10:23:21 +03:00
Paolo Bonzini e69b2c6790 stubs: avoid duplicate symbols in libqemuutil.a
qapi_event_send_device_deleted is always included (together with the
rest of QAPI) in libqemuutil.a if either system-mode emulation or tools
are being built, and in that case the stub causes a duplicate symbol
to appear in libqemuutil.a.

Add the symbol only if events are not being requested.

Cc: [email protected]
Reviewed-by: Alex Bennée <[email protected]>
Tested-by: Alex Bennée <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 388b849fb6)
Signed-off-by: Michael Tokarev <[email protected]>
2024-11-04 14:33:33 +03:00
Peter Maydell 13d162d4d0 target/arm: Store FPSR cumulative exception bits in env->vfp.fpsr
Currently we store the FPSR cumulative exception bits in the
float_status fields, and use env->vfp.fpsr only for the NZCV bits.
(The QC bit is stored in env->vfp.qc[].)

This works for TCG, but if QEMU was built without CONFIG_TCG (i.e.
with KVM support only) then we use the stub versions of
vfp_get_fpsr_from_host() and vfp_set_fpsr_to_host() which do nothing,
throwing away the cumulative exception bit state.  The effect is that
if the FPSR state is round-tripped from KVM to QEMU then we lose the
cumulative exception bits.  In particular, this will happen if the VM
is migrated.  There is no user-visible bug when using KVM with a QEMU
binary that was built with CONFIG_TCG.

Fix this by always storing the cumulative exception bits in
env->vfp.fpsr.  If we are using TCG then we may also keep pending
cumulative exception information in the float_status fields, so we
continue to fold that in on reads.

This change will also be helpful for implementing FEAT_AFP later,
because that includes a feature where in some situations we want to
cause input denormals to be flushed to zero without affecting the
existing state of the FPSR.IDC bit, so we need a place to store IDC
which is distinct from the various float_status fields.

(Note for stable backports: the bug goes back to 4a15527c9f but
this code was refactored in commits ea8618382aba..a8ab8706d4cc461, so
fixing it in branches without those refactorings will mean either
backporting the refactor or else implementing a conceptually similar
fix for the old code.)

Cc: [email protected]
Fixes: 4a15527c9f ("target/arm/vfp_helper: Restrict the SoftFloat use to TCG")
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Message-id: [email protected]
(cherry picked from commit d9c7adb601)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-31 19:59:18 +03:00
Ido Plat 10eb3721fc target/arm: Fix arithmetic underflow in SETM instruction
Pass the stage size to step function callback, otherwise do_setm
would hang when size is larger then page size because stage size
would underflow.  This fix changes do_setm to be more inline with
do_setp.

Cc: [email protected]
Fixes: 0e92818887 ("target/arm: Implement the SET* instructions")
Signed-off-by: Ido Plat <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Message-id: [email protected]
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit bab209af35)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-31 19:59:18 +03:00
Peter Maydell fde3af1971 hw/sd/omap_mmc: Don't use sd_cmd_type_t
In commit 1ab08790bb we did some refactoring of the SD card
implementation, which included a rearrangement of the sd_cmd_type_t
enum values.  Unfortunately we didn't notice that this enum is not
used solely inside the SD card model itself, but is also used by the
OMAP MMC controller device.  In the OMAP MMC controller, it is used
to implement the handling of the Type field of the MMC_CMD register,
so changing the enum values so that they no longer lined up with the
bit definitions for that register field broke the controller model.
The effect is that Linux fails to boot from an SD card on the "sx1"
machine.

Give omap-mmc its own enum which we can document as needing to match
the encoding used in this device's register, so it isn't sharing
sd_cmd_type_t with the SD card model any more.  We can then move
sd_cmd_type_t's definition out of sd.h and into sd.c, which is the
only place that uses it.

Cc: [email protected]
Fixes: 1ab08790bb ("hw/sd/sdcard: Store command type in SDProto")
Signed-off-by: Peter Maydell <[email protected]>
Tested-by: Guenter Roeck <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Message-id: [email protected]
(cherry picked from commit 77dd098a5e)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-31 19:59:18 +03:00
Peter Maydell ae0a9ccfe3 target/arm: Don't assert in regime_is_user() for E10 mmuidx values
In regime_is_user() we assert if we're passed an ARMMMUIdx_E10_*
mmuidx value. This used to make sense because we only used this
function in ptw.c and would never use it on this kind of stage 1+2
mmuidx, only for an individual stage 1 or stage 2 mmuidx.

However, when we implemented FEAT_E0PD we added a callsite in
aa64_va_parameters(), which means this can now be called for
stage 1+2 mmuidx values if the guest sets the TCG_ELX.{E0PD0,E0PD1}
bits to enable use of the feature. This will then result in
an assertion failure later, for instance on a TLBI operation:

#6  0x00007ffff6d0e70f in g_assertion_message_expr
    (domain=0x0, file=0x55555676eeba "../../target/arm/internals.h", line=978, func=0x555556771d48 <__func__.5> "regime_is_user", expr=<optimised out>)
    at ../../../glib/gtestutils.c:3279
#7  0x0000555555f286d2 in regime_is_user (env=0x555557f2fe00, mmu_idx=ARMMMUIdx_E10_0) at ../../target/arm/internals.h:978
#8  0x0000555555f3e31c in aa64_va_parameters (env=0x555557f2fe00, va=18446744073709551615, mmu_idx=ARMMMUIdx_E10_0, data=true, el1_is_aa32=false)
    at ../../target/arm/helper.c:12048
#9  0x0000555555f3163b in tlbi_aa64_get_range (env=0x555557f2fe00, mmuidx=ARMMMUIdx_E10_0, value=106721347371041) at ../../target/arm/helper.c:5214
#10 0x0000555555f317e8 in do_rvae_write (env=0x555557f2fe00, value=106721347371041, idxmap=21, synced=true) at ../../target/arm/helper.c:5260
#11 0x0000555555f31925 in tlbi_aa64_rvae1is_write (env=0x555557f2fe00, ri=0x555557fbeae0, value=106721347371041) at ../../target/arm/helper.c:5302
#12 0x0000555556036f8f in helper_set_cp_reg64 (env=0x555557f2fe00, rip=0x555557fbeae0, value=106721347371041) at ../../target/arm/tcg/op_helper.c:965

Since we do know whether these mmuidx values are for usermode
or not, we can easily make regime_is_user() handle them:
ARMMMUIdx_E10_0 is user, and the other two are not.

Cc: [email protected]
Fixes: e4c93e44ab ("target/arm: Implement FEAT_E0PD")
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Reviewed-by: Alex Bennée <[email protected]>
Tested-by: Alex Bennée <[email protected]>
Message-id: [email protected]
(cherry picked from commit 1505b651fd)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-31 19:59:18 +03:00
Bernhard Beschow b5cd9f8b5b net/tap-win32: Fix gcc 14 format truncation errors
The patch fixes the following errors generated by GCC 14.2:

../src/net/tap-win32.c:343:19: error: '%s' directive output may be truncated writing up to 255 bytes into a region of size 176 [-Werror=format-truncation=]
  343 |              "%s\\%s\\Connection",
      |                   ^~
  344 |              NETWORK_CONNECTIONS_KEY, enum_name);
      |                                       ~~~~~~~~~

../src/net/tap-win32.c:341:9: note: 'snprintf' output between 92 and 347 bytes into a destination of size 256
  341 |         snprintf(connection_string,
      |         ^~~~~~~~~~~~~~~~~~~~~~~~~~~
  342 |              sizeof(connection_string),
      |              ~~~~~~~~~~~~~~~~~~~~~~~~~~
  343 |              "%s\\%s\\Connection",
      |              ~~~~~~~~~~~~~~~~~~~~~
  344 |              NETWORK_CONNECTIONS_KEY, enum_name);
      |              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

../src/net/tap-win32.c:242:58: error: '%s' directive output may be truncated writing up to 255 bytes into a region of size 178 [-Werror=format-truncation=]
  242 |         snprintf (unit_string, sizeof(unit_string), "%s\\%s",
      |                                                          ^~
  243 |                   ADAPTER_KEY, enum_name);
      |                                ~~~~~~~~~

../src/net/tap-win32.c:242:9: note: 'snprintf' output between 79 and 334 bytes into a destination of size 256
  242 |         snprintf (unit_string, sizeof(unit_string), "%s\\%s",
      |         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  243 |                   ADAPTER_KEY, enum_name);
      |                   ~~~~~~~~~~~~~~~~~~~~~~~

../src/net/tap-win32.c:620:52: error: '%s' directive output may be truncated writing up to 255 bytes into a region of size 245 [-Werror=format-truncation=]
  620 |     snprintf (device_path, sizeof(device_path), "%s%s%s",
      |                                                    ^~
  621 |               USERMODEDEVICEDIR,
  622 |               device_guid,
      |               ~~~~~~~~~~~
../src/net/tap-win32.c:620:5: note: 'snprintf' output between 16 and 271 bytes into a destination of size 256
  620 |     snprintf (device_path, sizeof(device_path), "%s%s%s",
      |     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  621 |               USERMODEDEVICEDIR,
      |               ~~~~~~~~~~~~~~~~~~
  622 |               device_guid,
      |               ~~~~~~~~~~~~
  623 |               TAPSUFFIX);
      |               ~~~~~~~~~~

Signed-off-by: Bernhard Beschow <[email protected]>
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/2607
Cc: [email protected]
Reviewed-by: Michael Tokarev <[email protected]>
Reviewed-by: Pierrick Bouvier <[email protected]>
Signed-off-by: Jason Wang <[email protected]>
(cherry picked from commit 75fe36b4e8)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-30 03:01:03 +03:00
Daniel P. Berrangé 9657daca0e net: fix build when libbpf is disabled, but libxdp is enabled
The net/af-xdp.c code is enabled when the libxdp library is present,
however, it also has direct API calls to bpf_xdp_query_id &
bpf_xdp_detach which are provided by the libbpf library.

As a result if building with --disable-libbpf, but libxdp gets
auto-detected, we'll fail to link QEMU

  /usr/bin/ld: libcommon.a.p/net_af-xdp.c.o: undefined reference to symbol 'bpf_xdp_query_id@@LIBBPF_0.7.0'

There are two bugs here

 * Since we have direct libbpf API calls, when building
   net/af-xdp.c, we must tell meson that libbpf is a
   dependancy, so that we directly link to it, rather
   than relying on indirect linkage.

 * When must skip probing for libxdp at all, when libbpf
   is not found, raising an error if --enable-libxdp was
   given explicitly.

Fixes: cb039ef3d9
Signed-off-by: Daniel P. Berrangé <[email protected]>
Signed-off-by: Jason Wang <[email protected]>
(cherry picked from commit 1f37280b37)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-30 03:00:35 +03:00
Stefan Weil 289ac098b6 Fix calculation of minimum in colo_compare_tcp
GitHub's CodeQL reports a critical error which is fixed by using the MIN macro:

    Unsigned difference expression compared to zero

Signed-off-by: Stefan Weil <[email protected]>
Cc: [email protected]
Reviewed-by: Zhang Chen <[email protected]>
Signed-off-by: Jason Wang <[email protected]>
(cherry picked from commit e29bc931e1)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-30 02:59:57 +03:00
Akihiko Odaki 6ea3f1f06b net: Check if nc is NULL in qemu_get_vnet_hdr_len()
A netdev may not have a peer specified, resulting in NULL. We should
make it behave like /dev/null in such a case instead of letting it
cause segmentatin fault.

Fixes: 4b52d63249 ("tap: Remove qemu_using_vnet_hdr()")
Cc: [email protected]
Reported-by: Jonathan Cameron <[email protected]>
Signed-off-by: Akihiko Odaki <[email protected]>
Tested-by; Jonathan Cameron <[email protected]>
Acked-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Jason Wang <[email protected]>
(cherry picked from commit 76240dd2a3)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-30 02:58:53 +03:00
Pierrick Bouvier c044440a42 plugins: fix qemu_plugin_reset
34e5e1 refactored the plugin context initialization. After this change,
tcg_ctx->plugin_insn is not reset inconditionnally anymore, but only if
one plugin at least is active.

When uninstalling the last plugin active, we stopped reinitializing
tcg_ctx->plugin_insn, which leads to memory callbacks being emitted.
This results in an error as they don't appear in a plugin op sequence as
expected.

The correct fix is to make sure we reset plugin translation variables
after current block translation ends. This way, we can catch any
potential misuse of those after a given block, in more than fixing the
current bug.

Fixes: https://gitlab.com/qemu-project/qemu/-/issues/2570
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Pierrick Bouvier <[email protected]>
Tested-by: Robbin Ehn <[email protected]>
Message-Id: <[email protected]>
[AJB: trim patch version details from commit msg]
Signed-off-by: Alex Bennée <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit b56f7dd203)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-29 12:10:10 +03:00
Pierrick Bouvier 34f38a1b11 dockerfiles: fix default targets for debian-loongarch-cross
fix system target name, and remove --disable-system (which deactivates
system target).

Found using: make docker-test-build@debian-loongarch-cross V=1

Signed-off-by: Pierrick Bouvier <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Thomas Huth <[email protected]>
Message-Id: <[email protected]>
Signed-off-by: Alex Bennée <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit 24be5341fb)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-29 11:39:01 +03:00
Alex Bennée 4ab2bc6482 gitlab: make check-[dco|patch] a little more verbose
When git fails the rather terse backtrace only indicates it failed
without some useful context. Add some to make the log a little more
useful.

Reviewed-by: Daniel P. Berrangé <[email protected]>
Signed-off-by: Alex Bennée <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit 97f116f9c6)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-28 21:26:26 +03:00
Avihai Horon 7926d4d0d1 vfio/migration: Report only stop-copy size in vfio_state_pending_exact()
vfio_state_pending_exact() is used to update migration core how much
device data is left for the device migration. Currently, the sum of
pre-copy and stop-copy sizes of the VFIO device are reported.

The pre-copy size is obtained via the VFIO_MIG_GET_PRECOPY_INFO ioctl,
which returns the amount of device data available to be transferred
while the device is in the PRE_COPY states.

The stop-copy size is obtained via the VFIO_DEVICE_FEATURE_MIG_DATA_SIZE
ioctl, which returns the total amount of device data left to be
transferred in order to complete the device migration.

According to the above, current implementation is wrong -- it reports
extra overlapping data because pre-copy size is already contained in
stop-copy size. Fix it by reporting only stop-copy size.

Fixes: eda7362af9 ("vfio/migration: Add VFIO migration pre-copy support")
Signed-off-by: Avihai Horon <[email protected]>
Reviewed-by: Cédric Le Goater <[email protected]>
(cherry picked from commit 3b5948f808)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-25 18:18:33 +03:00
Yao Zi b861f65eaf linux-user/riscv: Fix definition of RISCV_HWPROBE_EXT_ZVFHMIN
Current definition yields a negative 32bits value, messing up hwprobe
result when Zvfhmin extension presents. Replace it by using a 1ULL bit
shift value as done in kernel upstream.

Link: https://github.com/torvalds/linux/commit/5ea6764d9095e234b024054f75ebbccc4f0eb146
Fixes: a3432cf227 ("linux-user/riscv: Sync hwprobe keys with Linux")
Cc: [email protected]
Signed-off-by: Yao Zi <[email protected]>
Message-ID: <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
(cherry picked from commit 310df7a9fe)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-25 16:57:49 +03:00
Ilya Leoshkevich 29027de5da linux-user/ppc: Fix sigmask endianness issue in sigreturn
do_setcontext() copies the target sigmask without endianness handling
and then uses target_to_host_sigset_internal(), which expects a
byte-swapped one. Use target_to_host_sigset() instead.

Fixes: bcd4933a23 ("linux-user: ppc signal handling")
Signed-off-by: Ilya Leoshkevich <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
(cherry picked from commit 8704132805)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-25 16:53:44 +03:00
Ilya Leoshkevich 356d3ecec0 linux-user: Emulate /proc/self/maps under mmap_lock
If one thread modifies the mappings and another thread prints them,
a situation may occur that the printer thread sees a guest mapping
without a corresponding host mapping, leading to a crash in
open_self_maps_2().

Cc: [email protected]
Fixes: 7b7a3366e1 ("linux-user: Use walk_memory_regions for open_self_maps")
Signed-off-by: Ilya Leoshkevich <[email protected]>
Reviewed-by: Laurent Vivier <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
(cherry picked from commit bbd5630a75)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-25 16:47:26 +03:00
Richard Henderson 3a41aa8226 target/i386: Use probe_access_full_mmu in ptw_translate
The probe_access_full_mmu function was designed for this purpose,
and does not report the memory operation event to plugins.

Cc: [email protected]
Fixes: 6d03226b42 ("plugins: force slow path when plugins instrument memory ops")
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Alex Bennée <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit 115ade42d5)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-25 16:47:03 +03:00
Alexander Graf 01bfc2e295 target/i386: Walk NPT in guest real mode
When translating virtual to physical address with a guest CPU that
supports nested paging (NPT), we need to perform every page table walk
access indirectly through the NPT, which we correctly do.

However, we treat real mode (no page table walk) special: In that case,
we currently just skip any walks and translate VA -> PA. With NPT
enabled, we also need to then perform NPT walk to do GVA -> GPA -> HPA
which we fail to do so far.

The net result of that is that TCG VMs with NPT enabled that execute
real mode code (like SeaBIOS) end up with GPA==HPA mappings which means
the guest accesses host code and data. This typically shows as failure
to boot guests.

This patch changes the page walk logic for NPT enabled guests so that we
always perform a GVA -> GPA translation and then skip any logic that
requires an actual PTE.

That way, all remaining logic to walk the NPT stays and we successfully
walk the NPT in real mode.

Cc: [email protected]
Fixes: fe441054bb ("target-i386: Add NPT support")
Signed-off-by: Alexander Graf <[email protected]>
Reported-by: Eduard Vlad <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
(cherry picked from commit b56617bbcb)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-25 16:43:53 +03:00
Richard Henderson fbe5afdd30 tcg: Reset data_gen_ptr correctly
This pointer needs to be reset after overflow just like
code_buf and code_ptr.

Cc: [email protected]
Fixes: 57a269469d ("tcg: Infrastructure for managing constant pools")
Acked-by: Alistair Francis <[email protected]>
Reviewed-by: Pierrick Bouvier <[email protected]>
Reviewed-by: LIU Zhiwei <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
(cherry picked from commit a7cfd751fb)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-25 16:31:13 +03:00
Kevin Wolf a22bd36631 raw-format: Fix error message for invalid offset/size
s->offset and s->size are only set at the end of the function and still
contain the old values when formatting the error message. Print the
parameters with the new values that we actually checked instead.

Fixes: 500e243420 ('raw-format: Split raw_read_options()')
Signed-off-by: Kevin Wolf <[email protected]>
Message-ID: <[email protected]>
Reviewed-by: Daniel P. Berrangé <[email protected]>
Reviewed-by: Hanna Czenczek <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit 04bbc3ee52)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-24 18:16:54 +03:00
Peter Maydell 88aaef7205 tests/qemu-iotests/211.out: Update to expect MapEntry 'compressed' field
In commit 52b10c9c0c in 2023 the QAPI MapEntry struct was
updated to add a 'compressed' field. That commit updated a number
of iotest expected-output files, but missed 211, which is vdi
specific. The result is that
 ./check -vdi
and more specifically
 ./check -vdi 211
fails because the expected and actual output don't match.

Update the reference output.

Cc: [email protected]
Fixes: 52b10c9c0c ("qemu-img: map: report compressed data blocks")
Signed-off-by: Peter Maydell <[email protected]>
Message-ID: <[email protected]>
Reviewed-by: Kevin Wolf <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit d60bd080e7)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-24 18:15:20 +03:00
Thomas Huth 6cb943c361 Revert "hw/sh4/r2d: Realize IDE controller before accessing it"
This reverts commit 3c5f86a226.

Changing the order here caused a regression with the "tuxrun"
kernels (from https://storage.tuxboot.com/20230331/) - ATA commands
fail with a "ata1: lost interrupt (Status 0x58)" message.
Apparently we need to wire the interrupt here first before
realizing the device, so revert the change to the original
behavior.

Reported-by: Guenter Roeck <[email protected]>
Acked-by: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: Thomas Huth <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit 68ad89b75a)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-22 20:24:35 +03:00
Stefan Berger 8dca0ab4c4 tests: Wait for migration completion on destination QEMU to avoid failures
Rather than waiting for the completion of migration on the source side,
wait for it on the destination QEMU side to avoid accessing the TPM TIS
memory mapped registers before QEMU could restore their state. This
error condition could be triggered on busy systems where the destination
QEMU did not have enough time to restore the TIS state while the test case
was already reading its registers. The test case was for example reading
the STS register and received an unexpected value (0xffffffff), which
lead to a segmentation fault later on due to trying to read 0xffff bytes
from the TIS into a buffer.

Cc:  <[email protected]>
Reported-by: Fabiano Rosas <[email protected]>
Reviewed-by: Daniel P. Berrangé <[email protected]>
Signed-off-by: Stefan Berger <[email protected]>
(cherry picked from commit d9280ea317)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-21 22:38:51 +03:00
Richard Henderson 065bba4dfa target/i386: Use only 16 and 32-bit operands for IN/OUT
The REX.W prefix is ignored for these instructions.
Mirror the solution already used for INS/OUTS: X86_SIZE_z.

Resolves: https://gitlab.com/qemu-project/qemu/-/issues/2581
Signed-off-by: Richard Henderson <[email protected]>
Cc: [email protected]
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 15d955975b)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-18 19:05:43 +03:00
Tom Dohrmann 474487611b accel/kvm: check for KVM_CAP_READONLY_MEM on VM
KVM_CAP_READONLY_MEM used to be a global capability, but with the
introduction of AMD SEV-SNP confidential VMs, this extension is not
always available on all VM types [1,2].

Query the extension on the VM level instead of on the KVM level.

[1] https://patchwork.kernel.org/project/kvm/patch/[email protected]/
[2] https://patchwork.kernel.org/project/kvm/patch/[email protected]/

Cc: Paolo Bonzini <[email protected]>
Signed-off-by: Tom Dohrmann <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 64e0e63ea1)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-18 19:03:08 +03:00
Paolo Bonzini 6ad00eb0d3 target/i386/tcg: Use DPL-level accesses for interrupts and call gates
Stack accesses should be explicit and use the privilege level of the
target stack.  This ensures that SMAP is not applied when the target
stack is in ring 3.

This fixes a bug wherein i386/tcg assumed that an interrupt return, or a
far call using the CALL or JMP instruction, was always going from kernel
or user mode to kernel mode when using a call gate. This assumption is
violated if the call gate has a DPL that is greater than 0.

Analyzed-by: Robert R. Henry <[email protected]>
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/249
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit e136648c5c)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-18 18:51:49 +03:00
Peter Xu 9eb3cc1641 KVM: Dynamic sized kvm memslots array
Zhiyi reported an infinite loop issue in VFIO use case.  The cause of that
was a separate discussion, however during that I found a regression of
dirty sync slowness when profiling.

Each KVMMemoryListerner maintains an array of kvm memslots.  Currently it's
statically allocated to be the max supported by the kernel.  However after
Linux commit 4fc096a99e ("KVM: Raise the maximum number of user memslots"),
the max supported memslots reported now grows to some number large enough
so that it may not be wise to always statically allocate with the max
reported.

What's worse, QEMU kvm code still walks all the allocated memslots entries
to do any form of lookups.  It can drastically slow down all memslot
operations because each of such loop can run over 32K times on the new
kernels.

Fix this issue by making the memslots to be allocated dynamically.

Here the initial size was set to 16 because it should cover the basic VM
usages, so that the hope is the majority VM use case may not even need to
grow at all (e.g. if one starts a VM with ./qemu-system-x86_64 by default
it'll consume 9 memslots), however not too large to waste memory.

There can also be even better way to address this, but so far this is the
simplest and should be already better even than before we grow the max
supported memslots.  For example, in the case of above issue when VFIO was
attached on a 32GB system, there are only ~10 memslots used.  So it could
be good enough as of now.

In the above VFIO context, measurement shows that the precopy dirty sync
shrinked from ~86ms to ~3ms after this patch applied.  It should also apply
to any KVM enabled VM even without VFIO.

NOTE: we don't have a FIXES tag for this patch because there's no real
commit that regressed this in QEMU. Such behavior existed for a long time,
but only start to be a problem when the kernel reports very large
nr_slots_max value.  However that's pretty common now (the kernel change
was merged in 2021) so we attached cc:stable because we'll want this change
to be backported to stable branches.

Cc: qemu-stable <[email protected]>
Reported-by: Zhiyi Guo <[email protected]>
Tested-by: Zhiyi Guo <[email protected]>
Signed-off-by: Peter Xu <[email protected]>
Acked-by: David Hildenbrand <[email protected]>
Reviewed-by: Fabiano Rosas <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 5504a81261)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-18 17:49:35 +03:00
Paolo Bonzini 994f8717ee tcg/s390x: fix constraint for 32-bit TSTEQ/TSTNE
32-bit TSTEQ and TSTNE is subject to the same constraints as
for 64-bit, but setcond_i32 and negsetcond_i32 were incorrectly
using TCG_CT_CONST ("i") instead of TCG_CT_CONST_CMP ("C").

Adjust the constraint and make tcg_target_const_match use the
same sequence as tgen_cmp2: first check if the constant is a
valid operand for TSTEQ/TSTNE, then accept everything for 32-bit
non-test comparisons, finally check if the constant is a valid
operand for 64-bit non-test comparisons.

Reported-by: Philippe Mathieu-Daudé <[email protected]>
Cc: [email protected]

Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 615586cb35)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-18 17:42:11 +03:00
Michael Tokarev 0ff5ab6f57 Update version for 9.1.1 release
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-18 17:26:37 +03:00
Marc-André Lureau 01fff50626 ui/dbus: fix filtering all update messages
Filtering pending messages when a new scanout is given shouldn't discard
pending cursor changes, for example.

Since filtering happens in a different thread, use atomic set/get.

Fixes: fa88b85dea ("ui/dbus: filter out pending messages when scanout")

Signed-off-by: Marc-André Lureau <[email protected]>
Reviewed-by: Akihiko Odaki <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit cf59889781)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-16 11:16:00 +03:00
Marc-André Lureau e1324ec946 ui/win32: fix potential use-after-free with dbus shared memory
DisplaySurface may be free before the pixman image is freed, since the
image is refcounted and used by different objects, including pending
dbus messages.

Furthermore, setting the destroy function in
create_displaysurface_from() isn't appropriate, as it may not be used,
and may be overriden as in ramfb.

Set the destroy function when the shared handle is set, use the HANDLE
directly for destroy data, using a single common helper
qemu_pixman_win32_image_destroy().

Signed-off-by: Marc-André Lureau <[email protected]>
Reviewed-by: Akihiko Odaki <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit 330ef31deb)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-16 11:15:04 +03:00
Marc-André Lureau 9391f419c7 ui/dbus: fix leak on message filtering
A filter function that wants to drop a message should return NULL, in
which case it must also unref the message itself.

Fixes: fa88b85de ("ui/dbus: filter out pending messages when scanout")

Signed-off-by: Marc-André Lureau <[email protected]>
Reviewed-by: Akihiko Odaki <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit 244d52ff73)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-16 11:14:35 +03:00
Marc-André Lureau 6d03242a7e hw/audio/hda: fix memory leak on audio setup
When SET_STREAM_FORMAT is called, we should clear the existing setup.

Factor out common function to close a stream.

Direct leak of 144 byte(s) in 3 object(s) allocated from:
    #0 0x7f91d38f7350 in calloc (/lib64/libasan.so.8+0xf7350) (BuildId: a4ad7eb954b390cf00f07fa10952988a41d9fc7a)
    #1 0x7f91d2ab7871 in g_malloc0 (/lib64/libglib-2.0.so.0+0x64871) (BuildId: 36b60dbd02e796145a982d0151ce37202ec05649)
    #2 0x562fa2f447ee in timer_new_full /home/elmarco/src/qemu/include/qemu/timer.h:538
    #3 0x562fa2f4486f in timer_new /home/elmarco/src/qemu/include/qemu/timer.h:559
    #4 0x562fa2f448a9 in timer_new_ns /home/elmarco/src/qemu/include/qemu/timer.h:577
    #5 0x562fa2f47955 in hda_audio_setup ../hw/audio/hda-codec.c:490
    #6 0x562fa2f4897e in hda_audio_command ../hw/audio/hda-codec.c:605

Signed-off-by: Marc-André Lureau <[email protected]>
Reviewed-by: Akihiko Odaki <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit 6d6e23361f)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-16 11:14:24 +03:00
Marc-André Lureau 2787ca0e0a hw/audio/hda: free timer on exit
Fixes: 280c1e1cd ("audio/hda: create millisecond timers that handle IO")

Signed-off-by: Marc-André Lureau <[email protected]>
Reviewed-by: Akihiko Odaki <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit f27206ceed)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-16 11:14:04 +03:00
Peter Maydell 10e3edd9b3 hw/char/pl011: Use correct masks for IBRD and FBRD
In commit b88cfee902 we defined masks for the IBRD and FBRD
integer and fractional baud rate divider registers, to prevent the
guest from writing invalid values which could cause division-by-zero.
Unfortunately we got the mask values the wrong way around: the FBRD
register is six bits and the IBRD register is 16 bits, not
vice-versa.

You would only run into this bug if you programmed the UART to a baud
rate of less than 9600, because for 9600 baud and above the IBRD
value will fit into 6 bits, as per the table in
 https://developer.arm.com/documentation/ddi0183/g/programmers-model/register-descriptions/fractional-baud-rate-register--uartfbrd

The only visible effects would be that the value read back from
the register by the guest would be truncated, and we would
print an incorrect baud rate in the debug logs.

Cc: [email protected]
Fixes: b88cfee902 ("hw/char/pl011: Avoid division-by-zero in pl011_get_baudrate()")
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/2610
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Alex Bennée <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Gavin Shan <[email protected]>
Message-id: [email protected]
(cherry picked from commit cd247eae16)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-15 20:33:06 +03:00
Alexandra Diupina 460ddd62fa hw/intc/arm_gicv3_cpuif: Add cast to match the documentation
The result of 1 << regbit with regbit==31 has a 1 in the 32nd bit.
When cast to uint64_t (for further bitwise OR), the 32 most
significant bits will be filled with 1s. However, the documentation
states that the upper 32 bits of ICH_AP[0/1]R<n>_EL2 are reserved.

Add an explicit cast to match the documentation.

Found by Linux Verification Center (linuxtesting.org) with SVACE.

Cc: [email protected]
Fixes: c3f21b065a ("hw/intc/arm_gicv3_cpuif: Support vLPIs")
Signed-off-by: Alexandra Diupina <[email protected]>
Reviewed-by: Peter Maydell <[email protected]>
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit 3db74afec3)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-15 19:40:40 +03:00
Alexandra Diupina 6fecfc5978 hw/intc/arm_gicv3: Add cast to match the documentation
The result of 1 << regbit with regbit==31 has a 1 in the 32nd bit.
When cast to uint64_t (for further bitwise OR), the 32 most
significant bits will be filled with 1s. However, the documentation
states that the upper 32 bits of ICC_AP[0/1]R<n>_EL2 are reserved.

Add an explicit cast to match the documentation.

Found by Linux Verification Center (linuxtesting.org) with SVACE.

Cc: [email protected]
Fixes: 28cca59c46 ("hw/intc/arm_gicv3: Add NMI handling CPU interface registers")
Signed-off-by: Alexandra Diupina <[email protected]>
Reviewed-by: Peter Maydell <[email protected]>
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit 12dc8f6eca)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-15 19:40:19 +03:00
Alexandra Diupina c5f652a053 hw/intc/arm_gicv3: Add cast to match the documentation
The result of 1 << regbit with regbit==31 has a 1 in the 32nd bit.
When cast to uint64_t (for further bitwise OR), the 32 most
significant bits will be filled with 1s. However, the documentation
states that the upper 32 bits of ICH_AP[0/1]R<n>_EL2 are reserved.

Add an explicit cast to match the documentation.

Found by Linux Verification Center (linuxtesting.org) with SVACE.

Cc: [email protected]
Fixes: d2c0c6aab6 ("hw/intc/arm_gicv3: Handle icv_nmiar1_read() for icc_nmiar1_read()")
Signed-off-by: Alexandra Diupina <[email protected]>
Reviewed-by: Peter Maydell <[email protected]>
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit e0c0ea6eca)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-15 19:39:58 +03:00
Paolo Bonzini 997f8d5c2b meson: ensure -mcx16 is passed when detecting ATOMIC128
Moving -mcx16 out of CPU_CFLAGS caused the detection of ATOMIC128 to
fail, because flags have to be specified by hand in cc.compiles and
cc.links invocations (why oh why??).

Ensure that these tests enable all the instruction set extensions that
will be used to build the emulators.

Fixes: c2bf2ccb26 ("configure: move -mcx16 flag out of CPU_CFLAGS", 2024-05-24)
Reported-by: Alex Bennée <[email protected]>
Reviewed-by: Michael Tokarev <[email protected]>
Reviewed-by: Alex Bennée <[email protected]>
Tested-by: Alex Bennée <[email protected]>
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 8db4e0f92e)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-14 20:58:53 +03:00
Paolo Bonzini 22359e0e6e meson: define qemu_isa_flags
Create a separate variable for compiler flags that enable
specific instruction set extensions, so that they can be used with
cc.compiles/cc.links.

Note that -mfpmath=sse is a code generation option but it does not
enable new instructions, therefore I did not make it part of
qemu_isa_flags.

Suggested-by: Pierrick Bouvier <[email protected]>
Reviewed-by: Michael Tokarev <[email protected]>
Reviewed-by: Alex Bennée <[email protected]>
Tested-by: Alex Bennée <[email protected]>
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 6ae8c5382b)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-14 20:57:23 +03:00
Pierrick Bouvier e894be998d meson: fix machine option for x86_version
s/mbmi1/mbmi/

When configuring with -Dx86_version >= 3, meson step works, but
compilation fails because option -mbmi1 is unknown.

Signed-off-by: Pierrick Bouvier <[email protected]>
Reviewed-by: Alex Bennée <[email protected]>
Tested-by: Alex Bennée <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Cc: [email protected]
Fixes: ef7d1adfa8 ("meson: allow configuring the x86-64 baseline", 2024-06-28)
Revieved-by: Michael Tokarev <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 461a9252e2)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-14 20:55:19 +03:00
Richard Henderson a4f9d9a4b2 target/m68k: Always return a temporary from gen_lea_mode
Returning a raw areg does not preserve the value if the areg
is subsequently modified.  Fixes, e.g. "jsr (sp)", where the
return address is pushed before the branch.

Resolves: https://gitlab.com/qemu-project/qemu/-/issues/2483
Signed-off-by: Richard Henderson <[email protected]>
Message-Id: <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit 352cc9f300)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-10 21:03:38 +03:00
Richard Henderson 8f583fd99a tcg/ppc: Use TCG_REG_TMP2 for scratch index in prepare_host_addr
In tcg_out_qemu_ldst_i128, we need a non-zero index register,
which we then use as a base register in several address modes.
Since we always have TCG_REG_TMP2 available, use that.

Cc: [email protected]
Fixes: 526cd4ec01 ("tcg/ppc: Support 128-bit load/store")
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/2597
Signed-off-by: Richard Henderson <[email protected]>
Tested-By: Michael Tokarev <[email protected]>
(cherry picked from commit 3213da7b95)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-10 21:03:38 +03:00
Richard Henderson 854a38fd9d tcg/ppc: Use TCG_REG_TMP2 for scratch tcg_out_qemu_st
In the fallback when STDBRX is not available, avoid clobbering
TCG_REG_TMP1, which might be h.base, which is still in use.
Use TCG_REG_TMP2 instead.

Cc: [email protected]
Fixes: 01a112e2e9 ("tcg/ppc: Reorg tcg_out_tlb_read")
Signed-off-by: Richard Henderson <[email protected]>
Tested-By: Michael Tokarev <[email protected]>
(cherry picked from commit 4cabcb89b1)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-10 21:03:38 +03:00
Richard Henderson 167c8d374a linux-user: Fix parse_elf_properties GNU0_MAGIC check
Comparing a string of 4 bytes only works in little-endian.

Adjust bulk bswap to only apply to the note payload.
Perform swapping of the note header manually; the magic
is defined so that it does not need a runtime swap.

Fixes: 83f990eb5a ("linux-user/elfload: Parse NT_GNU_PROPERTY_TYPE_0 notes")
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/2596
Signed-off-by: Richard Henderson <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Michael Tokarev <[email protected]>
(cherry picked from commit 2884596f5f)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-10 21:03:38 +03:00
Philippe Mathieu-Daudé 18046fbec5 linux-user/flatload: Take mmap_lock in load_flt_binary()
load_flt_binary() calls load_flat_file() -> page_set_flags().

page_set_flags() must be called with the mmap_lock held,
otherwise it aborts:

  $ qemu-arm -L stm32/lib/ stm32/bin/busybox
  qemu-arm: ../accel/tcg/user-exec.c:505: page_set_flags: Assertion `have_mmap_lock()' failed.
  Aborted (core dumped)

Fix by taking the lock in load_flt_binary().

Fixes: fbd3c4cff6 ("linux-user/arm: Mark the commpage executable")
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/2525
Suggested-by: Richard Henderson <[email protected]>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
(cherry picked from commit a9ee641bd4)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-10 21:03:38 +03:00
Marc-André Lureau 5762cdaf45 vnc: fix crash when no console attached
Since commit e99441a379 ("ui/curses: Do not use console_select()")
qemu_text_console_put_keysym() no longer checks for NULL console
argument, which leads to a later crash:

Thread 1 "qemu-system-x86" received signal SIGSEGV, Segmentation fault.
0x00005555559ee186 in qemu_text_console_handle_keysym (s=0x0, keysym=31) at ../ui/console-vc.c:332
332	        } else if (s->echo && (keysym == '\r' || keysym == '\n')) {
(gdb) bt
 #0  0x00005555559ee186 in qemu_text_console_handle_keysym (s=0x0, keysym=31) at ../ui/console-vc.c:332
 #1  0x00005555559e18e5 in qemu_text_console_put_keysym (s=<optimized out>, keysym=<optimized out>) at ../ui/console.c:303
 #2  0x00005555559f2e88 in do_key_event (vs=vs@entry=0x5555579045c0, down=down@entry=1, keycode=keycode@entry=60, sym=sym@entry=65471) at ../ui/vnc.c:2034
 #3  0x00005555559f845c in ext_key_event (vs=0x5555579045c0, down=1, sym=65471, keycode=<optimized out>) at ../ui/vnc.c:2070
 #4  protocol_client_msg (vs=0x5555579045c0, data=<optimized out>, len=<optimized out>) at ../ui/vnc.c:2514
 #5  0x00005555559f515c in vnc_client_read (vs=0x5555579045c0) at ../ui/vnc.c:1607

Fixes: e99441a379 ("ui/curses: Do not use console_select()")
Fixes: https://issues.redhat.com/browse/RHEL-50529
Cc: [email protected]
Signed-off-by: Marc-André Lureau <[email protected]>
Reviewed-by: Akihiko Odaki <[email protected]>
Reviewed-by: Michael Tokarev <[email protected]>
Signed-off-by: Michael Tokarev <[email protected]>
(cherry picked from commit 0e60fc8093)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-04 22:17:20 +03:00
Alex Bennée 02ac67c41f testing: bump mips64el cross to bookworm and fix package list
The mips64el cross setup is very broken for bullseye which has now
entered LTS support so is unlikely to be fixed. While we still can't
build the container with all packages for bookworm due to a single
missing dependency that will hopefully get fixed in due course. For
the sake of keeping the CI green we disable the problematic packages
via the lcitool's mappings.yml file.

See also: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=1081535

Signed-off-by: Alex Bennée <[email protected]>
[thuth: Disable the problematic packages via lcitool's mappings.yml]
Message-ID: <[email protected]>
Reviewed-by: Daniel P. Berrangé <[email protected]>
Signed-off-by: Thomas Huth <[email protected]>
(cherry picked from commit c60473d292)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-03 14:35:11 +03:00
osy 849e1db096 hvf: arm: disable debug features for iOS 2024-10-02 12:14:10 -07:00
osy 81cf7a0723 hvf: arm: fix compile issue for iOS 2024-10-02 12:13:54 -07:00
Jan Luebbe e32ac563b8 hw/sd/sdcard: Fix handling of disabled boot partitions
The enable bits in the EXT_CSD_PART_CONFIG ext_csd register do *not*
specify whether the boot partitions exist, but whether they are enabled
for booting. Existence of the boot partitions is specified by a
EXT_CSD_BOOT_MULT != 0.

Currently, in the case of boot-partition-size=1M and boot-config=0,
Linux detects boot partitions of 1M. But as sd_bootpart_offset always
returns 0, all reads/writes are mapped to the same offset in the backing
file.

Fix this bug by calculating the offset independent of which partition is
enabled for booting.

This bug is unlikely to affect many users with QEMU's current set of
boards, because only aspeed sets boot-partition-size, and it also
sets boot-config to 8. So to run into this a user would have to
manually mark the boot partition non-booting from within the guest.

Cc: [email protected]
Signed-off-by: Jan Luebbe <[email protected]>
Message-id: [email protected]
Reviewed-by: Peter Maydell <[email protected]>
[PMM: added note to commit message about effects of bug]
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit 9601076b3b)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-02 18:10:58 +03:00
Ard Biesheuvel 767e7d8ae1 target/arm: Avoid target_ulong for physical address lookups
target_ulong is typedef'ed as a 32-bit integer when building the
qemu-system-arm target, and this is smaller than the size of an
intermediate physical address when LPAE is being used.

Given that Linux may place leaf level user page tables in high memory
when built for LPAE, the kernel will crash with an external abort as
soon as it enters user space when running with more than ~3 GiB of
system RAM.

So replace target_ulong with vaddr in places where it may carry an
address value that is not representable in 32 bits.

Fixes: f3639a64f6 ("target/arm: Use softmmu tlbs for page table walking")
Cc: [email protected]
Reported-by: Arnd Bergmann <[email protected]>
Tested-by: Arnd Bergmann <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Ard Biesheuvel <[email protected]>
Message-id: [email protected]
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit 67d762e716)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-02 15:44:12 +03:00
osy 847a5380a1 tcg/optimize: disable fold_setcond_zmask for TCTI 2024-10-01 10:03:23 -07:00
osy 6a233bbe9f tcg: disable HAVE_CMPXCHG128 for TCTI 2024-10-01 10:03:23 -07:00
osy f0866dd714 tcg/optimize: disable env memory folding for TCTI 2024-10-01 10:03:23 -07:00
osy b65c350e24 tcg/tcti: update code gen for latest TCG changes 2024-10-01 10:03:22 -07:00
Fiona Ebner 7eefbf8bb7 block/reqlist: allow adding overlapping requests
Allow overlapping request by removing the assert that made it
impossible. There are only two callers:

1. block_copy_task_create()

It already asserts the very same condition before calling
reqlist_init_req().

2. cbw_snapshot_read_lock()

There is no need to have read requests be non-overlapping in
copy-before-write when used for snapshot-access. In fact, there was no
protection against two callers of cbw_snapshot_read_lock() calling
reqlist_init_req() with overlapping ranges and this could lead to an
assertion failure [1].

In particular, with the reproducer script below [0], two
cbw_co_snapshot_block_status() callers could race, with the second
calling reqlist_init_req() before the first one finishes and removes
its conflicting request.

[0]:

> #!/bin/bash -e
> dd if=/dev/urandom of=/tmp/disk.raw bs=1M count=1024
> ./qemu-img create /tmp/fleecing.raw -f raw 1G
> (
> ./qemu-system-x86_64 --qmp stdio \
> --blockdev raw,node-name=node0,file.driver=file,file.filename=/tmp/disk.raw \
> --blockdev raw,node-name=node1,file.driver=file,file.filename=/tmp/fleecing.raw \
> <<EOF
> {"execute": "qmp_capabilities"}
> {"execute": "blockdev-add", "arguments": { "driver": "copy-before-write", "file": "node0", "target": "node1", "node-name": "node3" } }
> {"execute": "blockdev-add", "arguments": { "driver": "snapshot-access", "file": "node3", "node-name": "snap0" } }
> {"execute": "nbd-server-start", "arguments": {"addr": { "type": "unix", "data": { "path": "/tmp/nbd.socket" } } } }
> {"execute": "block-export-add", "arguments": {"id": "exp0", "node-name": "snap0", "type": "nbd", "name": "exp0"}}
> EOF
> ) &
> sleep 5
> while true; do
> ./qemu-nbd -d /dev/nbd0
> ./qemu-nbd -c /dev/nbd0 nbd:unix:/tmp/nbd.socket:exportname=exp0 -f raw -r
> nbdinfo --map 'nbd+unix:///exp0?socket=/tmp/nbd.socket'
> done

[1]:

> #5  0x000071e5f0088eb2 in __GI___assert_fail (...) at ./assert/assert.c:101
> #6  0x0000615285438017 in reqlist_init_req (...) at ../block/reqlist.c:23
> #7  0x00006152853e2d98 in cbw_snapshot_read_lock (...) at ../block/copy-before-write.c:237
> #8  0x00006152853e3068 in cbw_co_snapshot_block_status (...) at ../block/copy-before-write.c:304
> #9  0x00006152853f4d22 in bdrv_co_snapshot_block_status (...) at ../block/io.c:3726
> #10 0x000061528543a63e in snapshot_access_co_block_status (...) at ../block/snapshot-access.c:48
> #11 0x00006152853f1a0a in bdrv_co_do_block_status (...) at ../block/io.c:2474
> #12 0x00006152853f2016 in bdrv_co_common_block_status_above (...) at ../block/io.c:2652
> #13 0x00006152853f22cf in bdrv_co_block_status_above (...) at ../block/io.c:2732
> #14 0x00006152853d9a86 in blk_co_block_status_above (...) at ../block/block-backend.c:1473
> #15 0x000061528538da6c in blockstatus_to_extents (...) at ../nbd/server.c:2374
> #16 0x000061528538deb1 in nbd_co_send_block_status (...) at ../nbd/server.c:2481
> #17 0x000061528538f424 in nbd_handle_request (...) at ../nbd/server.c:2978
> #18 0x000061528538f906 in nbd_trip (...) at ../nbd/server.c:3121
> #19 0x00006152855a7caf in coroutine_trampoline (...) at ../util/coroutine-ucontext.c:175

Cc: [email protected]
Suggested-by: Vladimir Sementsov-Ogievskiy <[email protected]>
Signed-off-by: Fiona Ebner <[email protected]>
Message-Id: <[email protected]>
Reviewed-by: Vladimir Sementsov-Ogievskiy <[email protected]>
Signed-off-by: Vladimir Sementsov-Ogievskiy <[email protected]>
(cherry picked from commit 6475155d51)
Signed-off-by: Michael Tokarev <[email protected]>
2024-10-01 19:21:40 +03:00
Alex Bennée bb630d9251 util/timer: avoid deadlock when shutting down
When we shut down a guest we disable the timers. However this can
cause deadlock if the guest has queued some async work that is trying
to advance system time and spins forever trying to wind time forward.
Pay attention to the return code and bail early if we can't wind time
forward.

Reported-by: Elisha Hollander <[email protected]>
Signed-off-by: Alex Bennée <[email protected]>
Reviewed-by: Pierrick Bouvier <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit bc02be4508)
Signed-off-by: Michael Tokarev <[email protected]>
2024-09-30 23:07:38 +03:00
osy 52dbd298e5 tcg/tcti: bring back movcond 2024-09-30 12:58:11 -07:00
osy 254bd0efa3 tcg/tcti: move gadgets generation to library 2024-09-30 12:56:33 -07:00
osy 361d160a68 roms: replace BIOS with UTM variants 2024-09-30 12:51:20 -07:00
osy f940d8d684 Merge remote-tracking branch 'mcayland/screamer-v9.1.0' into HEAD 2024-09-30 12:51:20 -07:00
osy ce02743156 screamer: remove old screamer code 2024-09-30 12:51:20 -07:00
Alexander Graf aea06209c4 hw/intc/arm_gicv3: Bump ITT entry size to 16
Some Operating Systems (like Windows) can only deal with ITT entry sizes
that are a power of 2. While the spec allows arbitrarily sized ITT entry
sizes, in practice all hardware will use power of 2 because that
simplifies offset calculation and ensures that a power of 2 sized region
can hold a set of entries without gap at the end.

So let's just bump the entry size to 16. That gives us enough space for
the 12 bytes of data that we want to have in each ITT entry and makes
QEMU look a bit more like real hardware.

Signed-off-by: Alexander Graf <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
2024-09-29 12:06:36 -07:00
Alexander Graf 888bb9e3bf hw/intc/arm_gicv3: Make ITT entry size configurable
An ITT entry is opaque to the OS. The only thing it does get told by HW is
its size. In theory, that size can be any byte aligned number, in practice
HW will always use power of 2s to simplify offset calculation. We currently
expose the size as 12, which is not a power of 2.

To prepare for a future where we expose power of 2 sized entry sizes, let's
make the size itself configurable. We only need to watch out that we don't
have an entry be smaller than the fields we want to access inside. Bigger
is always fine.

Signed-off-by: Alexander Graf <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Tested-by: Joelle van Dyne <[email protected]>
2024-09-29 12:06:36 -07:00
osy 59cc5b96e2 tpm-crb: fix page size for macs 2024-09-29 12:06:36 -07:00
Mark Cave-Ayland 8fc8dd2efd hw/mips/jazz: fix typo in in-built NIC alias
Commit e104edbb9d ("hw/mips/jazz: use qemu_find_nic_info()") contained a typo
in the NIC alias which caused initialisation of the in-built dp83932 NIC to fail
when using the normal -nic user,model=dp83932 command line.

Fixes: e104edbb9d ("hw/mips/jazz: use qemu_find_nic_info()")
Signed-off-by: Mark Cave-Ayland <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: David Woodhouse <[email protected]>
Reviewed-by: Michael Tokarev <[email protected]>
Signed-off-by: Michael Tokarev <[email protected]>
(cherry picked from commit 2e4fdf5660)
Signed-off-by: Michael Tokarev <[email protected]>
2024-09-28 07:35:30 +03:00
Fabiano Rosas f8244f3b8c target/ppc: Fix lxvx/stxvx facility check
The XT check for the lxvx/stxvx instructions is currently
inverted. This was introduced during the move to decodetree.

>From the ISA:
  Chapter 7. Vector-Scalar Extension Facility
  Load VSX Vector Indexed X-form

  lxvx XT,RA,RB
  if TX=0 & MSR.VSX=0 then VSX_Unavailable()
  if TX=1 & MSR.VEC=0 then Vector_Unavailable()
  ...
  Let XT be the value 32×TX + T.

The code currently does the opposite:

    if (paired || a->rt >= 32) {
        REQUIRE_VSX(ctx);
    } else {
        REQUIRE_VECTOR(ctx);
    }

This was already fixed for lxv/stxv at commit "2cc0e449d1 (target/ppc:
Fix lxv/stxv MSR facility check)", but the indexed forms were missed.

Cc: [email protected]
Fixes: 70426b5bb7 ("target/ppc: moved stxvx and lxvx from legacy to decodtree")
Signed-off-by: Fabiano Rosas <[email protected]>
Reviewed-by: Claudio Fontana <[email protected]>
Acked-by: Ilya Leoshkevich <[email protected]>
Reviewed-by: Fabiano Rosas <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
(cherry picked from commit 8bded2e73e)
Signed-off-by: Michael Tokarev <[email protected]>
2024-09-28 07:25:19 +03:00
TANG Tiancheng 4c7c0d2442 tcg: Fix iteration step in 32-bit gvec operation
The loop in the 32-bit case of the vector compare operation
was incorrectly incrementing by 8 bytes per iteration instead
of 4 bytes. This caused the function to process only half of
the intended elements.

Cc: [email protected]
Fixes: 9622c697d1 (tcg: Add gvec compare with immediate and scalar operand)
Signed-off-by: TANG Tiancheng <[email protected]>
Reviewed-by: Liu Zhiwei <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit 9d8d5a5b90)
Signed-off-by: Michael Tokarev <[email protected]>
2024-09-28 07:24:24 +03:00
Bibo Mao 51c943931d hw/loongarch/virt: Add description for virt machine type
The description about virt machine type is removed by mistake, add
new description here. Here is output result with command
"./qemu-system-loongarch64 -M help"

Supported machines are:
none                 empty machine
virt                 QEMU LoongArch Virtual Machine (default)
x-remote             Experimental remote machine

Without the patch, it shows as follows:
Supported machines are:
none                 empty machine
virt                 (null) (default)
x-remote             Experimental remote machine

Fixes: ef2f11454c(hw/loongarch/virt: Replace Loongson IPI with LoongArch IPI)
Signed-off-by: Bibo Mao <[email protected]>
Reviewed-by: Thomas Huth <[email protected]>
Reviewed-by: Michael Tokarev <[email protected]>
Signed-off-by: Michael Tokarev <[email protected]>
(cherry picked from commit 4265b4f358)
Signed-off-by: Michael Tokarev <[email protected]>
2024-09-26 13:15:03 +03:00
Fabiano Rosas 9cd1fd4b50 migration/multifd: Fix p->iov leak in multifd-uadk.c
The send_cleanup() hook should free the p->iov that was allocated at
send_setup(). This was missed because the UADK code is conditional on
the presence of the accelerator, so it's not tested by default.

Fixes: 819dd20636 ("migration/multifd: Add UADK initialization")
Reported-by: Peter Xu <[email protected]>
Reviewed-by: Peter Xu <[email protected]>
Signed-off-by: Fabiano Rosas <[email protected]>
(cherry picked from commit 405e352d28)
Signed-off-by: Michael Tokarev <[email protected]>
2024-09-25 21:05:48 +03:00
Arman Nabiev f84b79a8fc target/ppc: Fix migration of CPUs with TLB_EMB TLB type
In vmstate_tlbemb a cut-and-paste error meant we gave
this vmstate subsection the same "cpu/tlb6xx" name as
the vmstate_tlb6xx subsection. This breaks migration load
for any CPU using the TLB_EMB CPU type, because when we
see the "tlb6xx" name in the incoming data we try to
interpret it as a vmstate_tlb6xx subsection, which it
isn't the right format for:

 $ qemu-system-ppc -drive
 if=none,format=qcow2,file=/home/petmay01/test-images/virt/dummy.qcow2
 -monitor stdio -M bamboo
 QEMU 9.0.92 monitor - type 'help' for more information
 (qemu) savevm foo
 (qemu) loadvm foo
 Missing section footer for cpu
 Error: Error -22 while loading VM state

Correct the incorrect vmstate section name. Since migration
for these CPU types was completely broken before, we don't
need to care that this is a migration compatibility break.

This affects the PPC 405, 440, 460 and e200 CPU families.

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/2522
Reviewed-by: Peter Maydell <[email protected]>
Signed-off-by: Arman Nabiev <[email protected]>
Signed-off-by: Fabiano Rosas <[email protected]>
(cherry picked from commit 203beb6f04)
Signed-off-by: Michael Tokarev <[email protected]>
2024-09-25 21:05:48 +03:00
Helge Deller eb40b14740 target/hppa: Fix random 32-bit linux-user crashes
The linux-user hppa target crashes randomly for me since commit
081a0ed188 ("target/hppa: Do not mask in copy_iaoq_entry").

That commit dropped the masking of the IAOQ addresses while copying them
from other registers and instead keeps them with all 64 bits up until
the full gva is formed with the help of hppa_form_gva_psw().

So, when running in linux-user mode on an emulated 64-bit CPU, we need
to mask to a 32-bit address space at the very end in hppa_form_gva_psw()
if the PSW-W flag isn't set (which is the case for linux-user on hppa).

Fixes: 081a0ed188 ("target/hppa: Do not mask in copy_iaoq_entry")
Cc: [email protected] # v9.1+
Signed-off-by: Helge Deller <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
(cherry picked from commit d33d3adb57)
Signed-off-by: Michael Tokarev <[email protected]>
2024-09-25 21:05:48 +03:00
Peter Maydell 03ee5e0c53 target/arm: Correct ID_AA64ISAR1_EL1 value for neoverse-v1
The Neoverse-V1 TRM is a bit confused about the layout of the
ID_AA64ISAR1_EL1 register, and so its table 3-6 has the wrong value
for this ID register.  Trust instead section 3.2.74's list of which
fields are set.

This means that we stop incorrectly reporting FEAT_XS as present, and
now report the presence of FEAT_BF16.

Cc: [email protected]
Reported-by: Marcin Juszkiewicz <[email protected]>
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Message-id: [email protected]
(cherry picked from commit 8676007eff)
Signed-off-by: Michael Tokarev <[email protected]>
2024-09-25 21:05:48 +03:00
Jacob Abrams 1faa437db9 hw/char/stm32l4x5_usart.c: Enable USART ACK bit response
SW modifying USART_CR1 TE bit should cuase HW to respond by altering
USART_ISR TEACK bit, and likewise for RE and REACK bit.

This resolves some but not all issues necessary for the official STM USART
HAL driver to function as is.

Fixes: 87b77e6e01 ("hw/char/stm32l4x5_usart: Enable serial read and write")
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/2540
Signed-off-by: Jacob Abrams <[email protected]>
Message-id: [email protected]
Reviewed-by: Peter Maydell <[email protected]>
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit 6cce0dcc6f)
Signed-off-by: Michael Tokarev <[email protected]>
2024-09-25 21:05:48 +03:00
Fabiano Rosas 9b42e33bda migration/multifd: Fix rb->receivedmap cleanup race
Fix a segmentation fault in multifd when rb->receivedmap is cleared
too early.

After commit 5ef7e26bdb ("migration/multifd: solve zero page causing
multiple page faults"), multifd started using the rb->receivedmap
bitmap, which belongs to ram.c and is initialized and *freed* from the
ram SaveVMHandlers.

Multifd threads are live until migration_incoming_state_destroy(),
which is called after qemu_loadvm_state_cleanup(), leading to a crash
when accessing rb->receivedmap.

process_incoming_migration_co()        ...
  qemu_loadvm_state()                  multifd_nocomp_recv()
    qemu_loadvm_state_cleanup()          ramblock_recv_bitmap_set_offset()
      rb->receivedmap = NULL               set_bit_atomic(..., rb->receivedmap)
  ...
  migration_incoming_state_destroy()
    multifd_recv_cleanup()
      multifd_recv_terminate_threads(NULL)

Move the loadvm cleanup into migration_incoming_state_destroy(), after
multifd_recv_cleanup() to ensure multifd threads have already exited
when rb->receivedmap is cleared.

Adjust the postcopy listen thread comment to indicate that we still
want to skip the cpu synchronization.

CC: [email protected]
Fixes: 5ef7e26bdb ("migration/multifd: solve zero page causing multiple page faults")
Signed-off-by: Fabiano Rosas <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
[peterx: added comment in migration_incoming_state_destroy()]
Signed-off-by: Peter Xu <[email protected]>
(cherry picked from commit 4ce5622908)
Signed-off-by: Michael Tokarev <[email protected]>
2024-09-25 21:05:48 +03:00
Mattias Nissler 73f5d5bfb7 mac_dbdma: Remove leftover dma_memory_unmap calls
These were passing a NULL buffer pointer unconditionally, which happens
to behave in a mostly benign way (except for the chance of an excess
memory region unref and a bounce buffer leak). Per the function comment,
this was never meant to be accepted though, and triggers an assertion
with the "softmmu: Support concurrent bounce buffers" change.

Given that the code in question never sets up any mappings, just remove
the unnecessary dma_memory_unmap calls along with the DBDMA_io struct
fields that are now entirely unused.

Signed-off-by: Mattias Nissler <[email protected]>
Message-Id: <[email protected]>
Fixes: be1e343995 ("macio: switch over to new byte-aligned DMA helpers")
Reviewed-by: Mark Cave-Ayland <[email protected]>
Tested-by: Mark Cave-Ayland <[email protected]>
Signed-off-by: Mark Cave-Ayland <[email protected]>
(cherry picked from commit 2d0a071e62)
Signed-off-by: Michael Tokarev <[email protected]>
2024-09-25 21:05:07 +03:00
Fea.Wang 97fa3d7fcc softmmu/physmem.c: Keep transaction attribute in address_space_map()
The follow-up transactions may use the data in the attribution, so keep
the value of attribution from the function parameter just as
flatview_translate() above.

Signed-off-by: Fea.Wang <[email protected]>
Cc: [email protected]
Fixes: f26404fbee ("Make address_space_map() take a MemTxAttrs argument")
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Peter Xu <[email protected]>
(cherry picked from commit d8d5ca4004)
Signed-off-by: Michael Tokarev <[email protected]>
2024-09-25 21:04:10 +03:00
David Hildenbrand 659eeb16b3 softmmu/physmem: fix memory leak in dirty_memory_extend()
As reported by Peter, we might be leaking memory when removing the
highest RAMBlock (in the weird ram_addr_t space), and adding a new one.

We will fail to realize that we already allocated bitmaps for more
dirty memory blocks, and effectively discard the pointers to them.

Fix it by getting rid of last_ram_page() and by remembering the number
of dirty memory blocks that have been allocated already.

While at it, let's use "unsigned int" for the number of blocks, which
should be sufficient until we reach ~32 exabytes.

Looks like this leak was introduced as we switched from using a single
bitmap_zero_extend() to allocating multiple bitmaps:
bitmap_zero_extend() relies on g_renew() which should have taken care of
this.

Resolves: https://lkml.kernel.org/r/CAFEAcA-k7a+VObGAfCFNygQNfCKL=AfX6A4kScq=VSSK0peqPg@mail.gmail.com
Reported-by: Peter Maydell <[email protected]>
Fixes: 5b82b703b6 ("memory: RCU ram_list.dirty_memory[] for safe RAM hotplug")
Reviewed-by: Stefan Hajnoczi <[email protected]>
Reviewed-by: Peter Xu <[email protected]>
Tested-by: Peter Maydell <[email protected]>
Cc: [email protected]
Cc: Stefan Hajnoczi <[email protected]>
Cc: Paolo Bonzini <[email protected]>
Cc: Peter Xu <[email protected]>
Cc: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: David Hildenbrand <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Peter Xu <[email protected]>
(cherry picked from commit b84f06c2be)
Signed-off-by: Michael Tokarev <[email protected]>
2024-09-25 21:04:10 +03:00
Mattias Nissler 0d889c5c86 softmmu: Support concurrent bounce buffers
When DMA memory can't be directly accessed, as is the case when
running the device model in a separate process without shareable DMA
file descriptors, bounce buffering is used.

It is not uncommon for device models to request mapping of several DMA
regions at the same time. Examples include:
 * net devices, e.g. when transmitting a packet that is split across
   several TX descriptors (observed with igb)
 * USB host controllers, when handling a packet with multiple data TRBs
   (observed with xhci)

Previously, qemu only provided a single bounce buffer per AddressSpace
and would fail DMA map requests while the buffer was already in use. In
turn, this would cause DMA failures that ultimately manifest as hardware
errors from the guest perspective.

This change allocates DMA bounce buffers dynamically instead of
supporting only a single buffer. Thus, multiple DMA mappings work
correctly also when RAM can't be mmap()-ed.

The total bounce buffer allocation size is limited individually for each
AddressSpace. The default limit is 4096 bytes, matching the previous
maximum buffer size. A new x-max-bounce-buffer-size parameter is
provided to configure the limit for PCI devices.

Signed-off-by: Mattias Nissler <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Acked-by: Peter Xu <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Peter Xu <[email protected]>
(cherry picked from commit 637b0aa139)
Signed-off-by: Michael Tokarev <[email protected]>
2024-09-25 21:04:10 +03:00
Daniel P. Berrangé 02833b07b6 gitlab: fix logic for changing docker tag on stable branches
This fixes:

  commit e28112d007
  Author: Daniel P. Berrangé <[email protected]>
  Date:   Thu Jun 8 17:40:16 2023 +0100

    gitlab: stable staging branches publish containers in a separate tag

Due to a copy+paste mistake, that commit included "QEMU_JOB_SKIPPED"
in the final rule that was meant to be a 'catch all' for staging
branches.

As a result stable branches are still splattering dockers from the
primary development branch.

Signed-off-by: Daniel P. Berrangé <[email protected]>
Reviewed-by: Michael Tokarev <[email protected]>
Tested-by: Michael Tokarev <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Thomas Huth <[email protected]>
(cherry picked from commit 8d5ab746b1)
Signed-off-by: Michael Tokarev <[email protected]>
2024-09-25 21:04:10 +03:00
Gert Wollny b95002f47a ui/sdl2: set swap interval explicitly when OpenGL is enabled
Before 176e3783f2 (ui/sdl2: OpenGL window context)
SDL_CreateRenderer was called unconditionally setting
the swap interval to 0. Since SDL_CreateRenderer is now no
longer called when OpenGL is enabled, the swap interval is
no longer set explicitly and vsync handling depends on
the environment settings which may lead to a performance
regression with virgl as reported in
   https://gitlab.com/qemu-project/qemu/-/issues/2565

Restore the old vsync handling by explicitly calling
SDL_GL_SetSwapInterval if OpenGL is enabled.

Fixes: 176e3783f2 (ui/sdl2: OpenGL window context)
Closes: https://gitlab.com/qemu-project/qemu/-/issues/2565

Signed-off-by: Gert Wollny <[email protected]>
Acked-by: Marc-André Lureau <[email protected]>
Message-ID: <01020191e05ce6df-84da6386-62c2-4ce8-840e-ad216ac253dd-000000@eu-west-1.amazonses.com>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit ae23cd0017)
Signed-off-by: Michael Tokarev <[email protected]>
2024-09-25 21:04:10 +03:00
Jan Klötzke bec9a96934 hw/intc/arm_gic: fix spurious level triggered interrupts
On GICv2 and later, level triggered interrupts are pending when either
the interrupt line is asserted or the interrupt was made pending by a
GICD_ISPENDRn write. Making a level triggered interrupt pending by
software persists until either the interrupt is acknowledged or cleared
by writing GICD_ICPENDRn. As long as the interrupt line is asserted,
the interrupt is pending in any case.

This logic is transparently implemented in gic_test_pending() for
GICv1 and GICv2.  The function combines the "pending" irq_state flag
(used for edge triggered interrupts and software requests) and the
line status (tracked in the "level" field).  However, we also
incorrectly set the pending flag on a guest write to GICD_ISENABLERn
if the line of a level triggered interrupt was asserted.  This keeps
the interrupt pending even if the line is de-asserted after some
time.

This incorrect logic is a leftover of the initial 11MPCore GIC
implementation.  That handles things slightly differently to the
architected GICv1 and GICv2.  The 11MPCore TRM does not give a lot of
detail on the corner cases of its GIC's behaviour, and historically
we have not wanted to investigate exactly what it does in reality, so
QEMU's GIC model takes the approach of "retain our existing behaviour
for 11MPCore, and implement the architectural standard for later GIC
revisions".

On that basis, commit 8d999995e4 in 2013 is where we added the
"level-triggered interrupt with the line asserted" handling to
gic_test_pending(), and we deliberately kept the old behaviour of
gic_test_pending() for REV_11MPCORE.  That commit should have added
the "only if 11MPCore" condition to the setting of the pending bit on
writes to GICD_ISENABLERn, but forgot it.

Add the missing "if REV_11MPCORE" condition, so that our behaviour
on GICv1 and GICv2 matches the GIC architecture requirements.

Cc: [email protected]
Fixes: 8d999995e4 ("arm_gic: Fix GIC pending behavior")
Signed-off-by: Jan Klötzke <[email protected]>
Message-id: [email protected]
Reviewed-by: Peter Maydell <[email protected]>
[PMM: expanded comment a little and converted to coding-style form;
 expanded commit message with the historical backstory]
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit 110684c9a6)
Signed-off-by: Michael Tokarev <[email protected]>
2024-09-25 21:04:10 +03:00
Volker Rümelin df9aa3dd8c hw/audio/virtio-sound: fix heap buffer overflow
Currently, the guest may write to the device configuration space,
whereas the virtio sound device specification in chapter 5.14.4
clearly states that the fields in the device configuration space
are driver-read-only.

Remove the set_config function from the virtio_snd class.

This also prevents a heap buffer overflow. See QEMU issue #2296.

Resolves: https://gitlab.com/qemu-project/qemu/-/issues/2296
Signed-off-by: Volker Rümelin <[email protected]>
Message-Id: <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
(cherry picked from commit 7fc6611cad)
Signed-off-by: Michael Tokarev <[email protected]>
2024-09-25 21:04:10 +03:00
Thomas Huth cd320c8a82 contrib/plugins/Makefile: Add a 'distclean' target
Running "make distclean" in the build tree currently fails since this
tries to run the "distclean" target in the contrib/plugins/ folder, too,
but the Makefile there is missing this target. Thus add 'distclean' there
to fix this issue.

And to avoid regressions with "make distclean", add this command to one
of the build jobs, too.

Message-ID: <[email protected]>
Reviewed-by: Pierrick Bouvier <[email protected]>
Signed-off-by: Thomas Huth <[email protected]>
(cherry picked from commit 1231bc7d12)
Signed-off-by: Michael Tokarev <[email protected]>
2024-09-25 21:04:10 +03:00
Alex Bennée 27a15a2a32 tests/docker: update debian i686 and mipsel images to bookworm
Whatever issues there were which stopped these being updates when the
rest were have now been resolved. However mips64el continues to be
broken so don't update it here.

Reviewed-by: Pierrick Bouvier <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Alex Bennée <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit 19d2111059)
Signed-off-by: Michael Tokarev <[email protected]>
2024-09-25 21:04:10 +03:00
Alex Bennée a160fa0fc3 tests/docker: remove debian-armel-cross
As debian-11 transitions to LTS we are starting to have problems
building the image. While we could update to a later Debian building a
32 bit QEMU without modern floating point is niche host amongst the
few remaining 32 bit hosts we regularly build for. For now we still
have armhf-debian-cross-container which is currently built from the
more recent debian-12.

Reviewed-by: Pierrick Bouvier <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Alex Bennée <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit d0068b746a)
Signed-off-by: Michael Tokarev <[email protected]>
2024-09-25 21:04:10 +03:00
Daniel P. Berrangé 3148a16b30 crypto: avoid leak of ctx when bad cipher mode is given
Fixes: Coverity CID 1546884
Reviewed-by: Peter Maydell <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: Daniel P. Berrangé <[email protected]>
(cherry picked from commit 586ac2c67d)
Signed-off-by: Michael Tokarev <[email protected]>
2024-09-25 21:04:10 +03:00
Daniel P. Berrangé 0e8f3eb43f crypto: check gnutls & gcrypt support the requested pbkdf hash
Both gnutls and gcrypt can be configured to exclude support for certain
algorithms via a runtime check against system crypto policies. Thus it
is not sufficient to have a compile time test for hash support in their
pbkdf implementations.

Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: Daniel P. Berrangé <[email protected]>
(cherry picked from commit e6c09ea4f9)
Signed-off-by: Michael Tokarev <[email protected]>
2024-09-25 21:04:10 +03:00
Tiago Pasqualini ae2dc2a27a crypto: run qcrypto_pbkdf2_count_iters in a new thread
CPU time accounting in the kernel has been demonstrated to have a
sawtooth pattern[1][2]. This can cause the getrusage system call to
not be as accurate as we are expecting, which can cause this calculation
to stall.

The kernel discussions shows that this inaccuracy happens when CPU time
gets big enough, so this patch changes qcrypto_pbkdf2_count_iters to run
in a fresh thread to avoid this inaccuracy. It also adds a sanity check
to fail the process if CPU time is not accounted.

[1] https://lore.kernel.org/lkml/159231011694.16989.16351419333851309713.tip-bot2@tip-bot2/
[2] https://lore.kernel.org/lkml/[email protected]/t/#m1c7f2fdc0ea742776a70fd1aa2a2e414c437f534

Resolves: #2398
Signed-off-by: Tiago Pasqualini <[email protected]>
Signed-off-by: Daniel P. Berrangé <[email protected]>
(cherry picked from commit c72cab5ad9)
Signed-off-by: Michael Tokarev <[email protected]>
2024-09-25 21:04:10 +03:00
Mark Cave-Ayland 1c47688ed6 WIP: remove byte swap implementation
- Fixes OS X 10.1 and 10.2 crackling
- Clearly this register does something different than I expect...
2024-09-23 23:18:55 +01:00
Mark Cave-Ayland 3c1a7a3265 WIP: more updates, current status:
-M mac99, OS 9.0 - boots, but silent
-M mac99, OS 9.2 - works
-M mac99,via=pmu, OS 9.2 - works
-M mac99 - OS X 10.2 - works
-M mac99,via=pmu, OS X 10.2 - patchy noise (incorrect timer?)
2024-09-23 23:18:55 +01:00
Mark Cave-Ayland 66a5df7c15 WIP: update 2024-09-23 23:18:55 +01:00
Mark Cave-Ayland 39858ec734 WIP: Add OpenBIOS with screamer support 2024-09-23 23:18:52 +01:00
Mark Cave-Ayland 89f1a628cf WIP: update DBDMA status after FLUSH 2024-09-23 21:31:57 +01:00
Mark Cave-Ayland 9b649c3e9f WIP: working sound in MacOS 9.1/9.2 2024-09-23 21:31:57 +01:00
Mark Cave-Ayland 4ed9ad7f1b WIP: screamer now able to play on Debian Linux/snd_powermac 2024-09-23 21:31:56 +01:00
Mark Cave-Ayland ef29d0dadd WIP: wire up to new world machine 2024-09-23 21:31:56 +01:00
Mark Cave-Ayland 36d2758b9d WIP: basic DMA functionality for screamer 2024-09-23 21:31:56 +01:00
Mark Cave-Ayland 4431f3f2aa screamer: some basic reg work, plus basic DMA wire-up 2024-09-23 21:31:56 +01:00
Mark Cave-Ayland 44036c8eb7 macio: basic AWACS/screamer hookup
Signed-off-by: Mark Cave-Ayland <[email protected]>
2024-09-23 21:31:56 +01:00
Mark Cave-Ayland c3af08a16e audio: add dummy screamer device
Signed-off-by: Mark Cave-Ayland <[email protected]>
2024-09-23 21:31:56 +01:00
osy 903085638b sysbus-fdt: falsely claim TPM CRB device is TPM TIS
OVMF firmware is hard coded to recognize a TPM TIS device. If we lie,
the code will properly detect that it is a CRB device. In Linux, this
will cause the device to be not recognized properly but the separate
ACPI device will cause it to work regardless.
2024-09-15 05:15:32 -07:00
osy 11b4067b9e Merge tag 'patchew/[email protected]' into utm-edition-v9.1.0 2024-09-15 05:15:32 -07:00
Daniel P. Berrangé f74e5bd9b9 iotests: fix expected output from gnutls
Error reporting from gnutls was improved by:

  commit 57941c9c86
  Author: Daniel P. Berrangé <[email protected]>
  Date:   Fri Mar 15 14:07:58 2024 +0000

    crypto: push error reporting into TLS session I/O APIs

This has the effect of changing the output from one of the NBD
tests.

Reported-by: Thomas Huth <[email protected]>
Signed-off-by: Daniel P. Berrangé <[email protected]>
(cherry picked from commit 48b8583698)
Signed-off-by: Michael Tokarev <[email protected]>
2024-09-11 08:56:04 +03:00
osy d6441003a3 Merge tag 'v9.1.0' into utm-edition
v9.1.0 release
2024-09-10 03:13:24 -07:00
Helge Deller 20eee6cb3d target/hppa: Fix PSW V-bit packaging in cpu_hppa_get for hppa64
While adding hppa64 support, the psw_v variable got extended from 32 to 64
bits.  So, when packaging the PSW-V bit from the psw_v variable for interrupt
processing, check bit 31 instead the 63th (sign) bit.

This fixes a hard to find Linux kernel boot issue where the loss of the PSW-V
bit due to an ITLB interruption in the middle of a series of ds/addc
instructions (from the divU milicode library) generated the wrong division
result and thus triggered a Linux kernel crash.

Link: https://lore.kernel.org/lkml/[email protected]/
Reported-by: Guenter Roeck <[email protected]>
Signed-off-by: Helge Deller <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Tested-by: Guenter Roeck <[email protected]>
Fixes: 931adff314 ("target/hppa: Update cpu_hppa_get/put_psw for hppa64")
Cc: [email protected] # v8.2+
(cherry picked from commit ead5078cf1)
Signed-off-by: Michael Tokarev <[email protected]>
2024-09-05 22:48:29 +03:00
Joelle van Dyne 6e95fc98a5 tests: add TPM-CRB sysbus tests for aarch64
- Factor out common test code from tpm-crb-test.c -> tpm-tests.c
- Store device addr in `tpm_device_base_addr` (unify with TIS tests)
- Add new tests for aarch64

Signed-off-by: Joelle van Dyne <[email protected]>
Reviewed-by: Stefan Berger <[email protected]>
Message-Id: <[email protected]>
2023-11-14 15:49:41 +00:00
Joelle van Dyne 6744c812b4 tests: acpi: updated expected blobs for TPM CRB
Signed-off-by: Joelle van Dyne <[email protected]>
Tested-by: Stefan Berger <[email protected]>
Message-Id: <[email protected]>
2023-11-14 15:49:41 +00:00
Joelle van Dyne a1658ba0df tests: acpi: implement TPM CRB tests for ARM virt
Signed-off-by: Joelle van Dyne <[email protected]>
Reviewed-by: Stefan Berger <[email protected]>
Message-Id: <[email protected]>
2023-11-14 15:49:41 +00:00
Joelle van Dyne 4653477a12 tpm_crb_sysbus: introduce TPM CRB SysBus device
This SysBus variant of the CRB interface supports dynamically locating
the MMIO interface so that Virt machines can use it. This interface
is currently the only one supported by QEMU that works on Windows 11
ARM64 as 'tpm-tis-device' does not work with current Windows drivers.
We largely follow that device as a template.

To try out this device with Windows 11 before OVMF is updated, you
will need to modify `sysbus-fdt.c` and change the added line from:

```c
    TYPE_BINDING(TYPE_TPM_CRB_SYSBUS, no_fdt_node),
```

to

```c
    TYPE_BINDING(TYPE_TPM_CRB_SYSBUS, add_tpm_tis_fdt_node),
```

This change was not included because it can confuse Linux (although
from testing, it seems like Linux is able to properly ignore the
device from the TPM TIS driver and recognize it from the ACPI device
in the TPM CRB driver). A proper fix would require OVMF to recognize
the ACPI device and not depend on the FDT node for recognizing TPM.

The command line to try out this device with SWTPM is:

```
$ qemu-system-aarch64 \
    -chardev socket,id=chrtpm0,path=tpm.sock \
    -tpmdev emulator,id=tpm0,chardev=chrtpm0 \
    -device tpm-crb-device,tpmdev=tpm0
```

along with SWTPM:

```
$ swtpm \
    --ctrl type=unixio,path=tpm.sock,terminate \
    --tpmstate backend-uri=file://tpm.data \
    --tpm2
```

Signed-off-by: Joelle van Dyne <[email protected]>
Reviewed-by: Stefan Berger <[email protected]>
Message-Id: <[email protected]>
2023-11-14 15:49:41 +00:00
Joelle van Dyne 61819be7f1 tests: acpi: prepare for TPM CRB tests
Signed-off-by: Joelle van Dyne <[email protected]>
Reviewed-by: Stefan Berger <[email protected]>
Message-Id: <[email protected]>
2023-11-14 15:49:40 +00:00
Joelle van Dyne 3f0d5bac18 tpm_tis_sysbus: move DSDT AML generation to device
This reduces redundant code in different machine types with ACPI table
generation. Additionally, this will allow us to support different TPM
interfaces with the same AML logic. Finally, this matches up with the
TPM TIS ISA implementation.

Ideally, we would be able to call `qbus_build_aml` and avoid any TPM
specific code in the ACPI table generation. However, currently we
still have to call `build_tpm2` anyways and it does not look like
most other ACPI devices support the `ACPI_DEV_AML_IF` interface.

Signed-off-by: Joelle van Dyne <[email protected]>
Reviewed-by: Stefan Berger <[email protected]>
Message-Id: <[email protected]>
2023-11-14 15:49:40 +00:00
Joelle van Dyne 323c2b9a2e hw/loongarch/virt: connect TPM to platform bus
Signed-off-by: Joelle van Dyne <[email protected]>
Reviewed-by: Stefan Berger <[email protected]>
Message-Id: <[email protected]>
2023-11-14 15:49:40 +00:00
Joelle van Dyne 3e3a3d6370 hw/arm/virt: connect TPM to platform bus
Signed-off-by: Joelle van Dyne <[email protected]>
Reviewed-by: Stefan Berger <[email protected]>
Message-Id: <[email protected]>
2023-11-14 15:49:40 +00:00
Joelle van Dyne 8c7c8c1be9 tpm-sysbus: add plug handler for TPM on SysBus
TPM needs to know its own base address in order to generate its DSDT
device entry.

Signed-off-by: Joelle van Dyne <[email protected]>
Reviewed-by: Stefan Berger <[email protected]>
Message-Id: <[email protected]>
2023-11-14 15:49:40 +00:00
Joelle van Dyne f94d1bb04f tpm_crb: move ACPI table building to device interface
This logic is similar to TPM TIS ISA device. Since TPM CRB can only
support TPM 2.0 backends, we check for this in realize.

Signed-off-by: Joelle van Dyne <[email protected]>
Message-Id: <[email protected]>
2023-11-14 15:49:40 +00:00
Joelle van Dyne 156a7df98f tpm_crb: use a single read-as-mem/write-as-mmio mapping
On Apple Silicon, when Windows performs a LDP on the CRB MMIO space,
the exception is not decoded by hardware and we cannot trap the MMIO
read. This led to the idea from @agraf to use the same mapping type as
ROM devices: namely that reads should be seen as memory type and
writes should trap as MMIO.

Once that was done, the second memory mapping of the command buffer
region was redundent and was removed.

A note about the removal of the read trap for `CRB_LOC_STATE`:
The only usage was to return the most up-to-date value for
`tpmEstablished`. However, `tpmEstablished` is only cleared when a
TPM2_HashStart operation is called which only exists for locality 4.
We do not handle locality 4. Indeed, the comment for the write handler
of `CRB_LOC_CTRL` makes the same argument for why it is not calling
the backend to reset the `tpmEstablished` bit (to 1).
As this bit is unused, we do not need to worry about updating it for
reads.

In order to maintain migration compatibility with older versions of
QEMU, we store a copy of the register data and command data which is
used only during save/restore.

Signed-off-by: Joelle van Dyne <[email protected]>
Reviewed-by: Stefan Berger <[email protected]>
Message-Id: <[email protected]>
2023-11-14 15:49:40 +00:00
Joelle van Dyne c1bd61b8ec tpm_ppi: refactor memory space initialization
Instead of calling `memory_region_add_subregion` directly, we defer to
the caller to do it. This allows us to re-use the code for a SysBus
device.

Signed-off-by: Joelle van Dyne <[email protected]>
Reviewed-by: Stefan Berger <[email protected]>
Message-Id: <[email protected]>
2023-11-14 15:49:40 +00:00
Joelle van Dyne c24b94f4d3 tpm_crb: CTRL_RSP_ADDR is 64-bits wide
The register is actually 64-bits but in order to make this more clear
than the specification, we define two 32-bit registers:
CTRL_RSP_LADDR and CTRL_RSP_HADDR to match the CTRL_CMD_* naming. This
deviates from the specs but is way more clear.

Previously, the only CRB device uses a fixed system address so this
was not an issue. However, once we support SysBus CRB device, the
address can be anywhere in 64-bit space.

Signed-off-by: Joelle van Dyne <[email protected]>
Reviewed-by: Stefan Berger <[email protected]>
Message-Id: <[email protected]>
2023-11-14 15:49:40 +00:00
Joelle van Dyne 32f32b3918 tpm_crb: refactor common code
In preparation for the SysBus variant, we move common code styled
after the TPM TIS devices.

To maintain compatibility, we do not rename the existing tpm-crb
device.

Signed-off-by: Joelle van Dyne <[email protected]>
Reviewed-by: Stefan Berger <[email protected]>
Message-Id: <[email protected]>
2023-11-14 15:49:40 +00:00
osy 8eb68166a7 edk2: add secure boot variant to aarch64 firmware 2023-07-08 14:41:16 -07:00
osy 2bbbeb0eaf Merge tag 'v8.0.2' into utm-edition
v8.0.2 release
2023-07-02 22:32:38 -05:00
Michael Tokarev f7f686b61c Update version for 8.0.2 release
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-30 14:59:47 +03:00
Kevin Wolf bea933e430 block/export: Fix null pointer dereference in error path
There are some error paths in blk_exp_add() that jump to 'fail:' before
'exp' is even created. So we can't just unconditionally access exp->blk.

Add a NULL check, and switch from exp->blk to blk, which is available
earlier, just to be extra sure that we really cover all cases where
BlockDevOps could have been set for it (in practice, this only happens
in drv->create() today, so this part of the change isn't strictly
necessary).

Fixes: Coverity CID 1509238
Fixes: de79b52604
Signed-off-by: Kevin Wolf <[email protected]>
Message-Id: <[email protected]>
Reviewed-by: Eric Blake <[email protected]>
Tested-by: Eric Blake <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit a184563778)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-30 00:16:58 +03:00
Michael Tokarev dabb4183d1 Update version for 8.0.1 release
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-29 18:19:22 +03:00
Paolo Bonzini ff692a15bb virtio: qmp: fix memory leak
The VirtioInfoList is already allocated by QAPI_LIST_PREPEND and
need not be allocated by the caller.

Fixes Coverity CID 1508724.

Reviewed-by: Daniel P. Berrangé <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 0bfd14149b)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-27 12:54:07 +03:00
Igor Mammedov 134253a4fe machine: do not crash if default RAM backend name has been stolen
QEMU aborts when default RAM backend should be used (i.e. no
explicit '-machine memory-backend=' specified) but user
has created an object which 'id' equals to default RAM backend
name used by board.

 $QEMU -machine pc \
       -object memory-backend-ram,id=pc.ram,size=4294967296

 Actual results:
 QEMU 7.2.0 monitor - type 'help' for more information
 (qemu) Unexpected error in object_property_try_add() at ../qom/object.c:1239:
 qemu-kvm: attempt to add duplicate property 'pc.ram' to object (type 'container')
 Aborted (core dumped)

Instead of abort, check for the conflicting 'id' and exit with
an error, suggesting how to remedy the issue.

Buglink: https://bugzilla.redhat.com/show_bug.cgi?id=2207886
Signed-off-by: Igor Mammedov <[email protected]>
Message-Id: <[email protected]>
Tested-by: Thomas Huth <[email protected]>
Reviewed-by: Thomas Huth <[email protected]>
Reviewed-by: Shaoqin Huang <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: Thomas Huth <[email protected]>
(cherry picked from commit a37531f238)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-26 19:46:01 +03:00
Thomas Huth e49884a909 hw/scsi/lsi53c895a: Fix reentrancy issues in the LSI controller (CVE-2023-0330)
We cannot use the generic reentrancy guard in the LSI code, so
we have to manually prevent endless reentrancy here. The problematic
lsi_execute_script() function has already a way to detect whether
too many instructions have been executed - we just have to slightly
change the logic here that it also takes into account if the function
has been called too often in a reentrant way.

The code in fuzz-lsi53c895a-test.c has been taken from an earlier
patch by Mauro Matteo Cascella.

Resolves: https://gitlab.com/qemu-project/qemu/-/issues/1563
Message-Id: <[email protected]>
Reviewed-by: Stefan Hajnoczi <[email protected]>
Reviewed-by: Alexander Bulekov <[email protected]>
Signed-off-by: Thomas Huth <[email protected]>
(cherry picked from commit b987718bbb)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-26 18:56:39 +03:00
Paolo Bonzini 9d622451fd usb/ohci: Set pad to 0 after frame update
When the OHCI controller's framenumber is incremented, HccaPad1 register
should be set to zero (Ref OHCI Spec 4.4)

ReactOS uses hccaPad1 to determine if the OHCI hardware is running,
consequently it fails this check in current qemu master.

Signed-off-by: Ryan Wendland <[email protected]>
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/1048
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 6301460ce9)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-26 10:49:10 +03:00
Akihiko Odaki 668aeea0ec util/vfio-helpers: Use g_file_read_link()
When _FORTIFY_SOURCE=2, glibc version is 2.35, and GCC version is
12.1.0, the compiler complains as follows:

In file included from /usr/include/features.h:490,
                 from /usr/include/bits/libc-header-start.h:33,
                 from /usr/include/stdint.h:26,
                 from /usr/lib/gcc/aarch64-unknown-linux-gnu/12.1.0/include/stdint.h:9,
                 from /home/alarm/q/var/qemu/include/qemu/osdep.h:94,
                 from ../util/vfio-helpers.c:13:
In function 'readlink',
    inlined from 'sysfs_find_group_file' at ../util/vfio-helpers.c:116:9,
    inlined from 'qemu_vfio_init_pci' at ../util/vfio-helpers.c:326:18,
    inlined from 'qemu_vfio_open_pci' at ../util/vfio-helpers.c:517:9:
/usr/include/bits/unistd.h:119:10: error: argument 2 is null but the corresponding size argument 3 value is 4095 [-Werror=nonnull]
  119 |   return __glibc_fortify (readlink, __len, sizeof (char),
      |          ^~~~~~~~~~~~~~~

This error implies the allocated buffer can be NULL. Use
g_file_read_link(), which allocates buffer automatically to avoid the
error.

Signed-off-by: Akihiko Odaki <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Cédric Le Goater <[email protected]>
Signed-off-by: Cédric Le Goater <[email protected]>
(cherry picked from commit dbdea0dbfe)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-26 10:47:30 +03:00
Stefan Hajnoczi fae9449998 rtl8139: fix large_send_mss divide-by-zero
If the driver sets large_send_mss to 0 then a divide-by-zero occurs.
Even if the division wasn't a problem, the for loop that emits MSS-sized
packets would never terminate.

Solve these issues by skipping offloading when large_send_mss=0.

This issue was found by OSS-Fuzz as part of Alexander Bulekov's device
fuzzing work. The reproducer is:

  $ cat << EOF | ./qemu-system-i386 -display none -machine accel=qtest, -m \
  512M,slots=1,maxmem=0xffff000000000000 -machine q35 -nodefaults -device \
  rtl8139,netdev=net0 -netdev user,id=net0 -device \
  pc-dimm,id=nv1,memdev=mem1,addr=0xb800a64602800000 -object \
  memory-backend-ram,id=mem1,size=2M  -qtest stdio
  outl 0xcf8 0x80000814
  outl 0xcfc 0xe0000000
  outl 0xcf8 0x80000804
  outw 0xcfc 0x06
  write 0xe0000037 0x1 0x04
  write 0xe00000e0 0x2 0x01
  write 0x1 0x1 0x04
  write 0x3 0x1 0x98
  write 0xa 0x1 0x8c
  write 0xb 0x1 0x02
  write 0xc 0x1 0x46
  write 0xd 0x1 0xa6
  write 0xf 0x1 0xb8
  write 0xb800a646028c000c 0x1 0x08
  write 0xb800a646028c000e 0x1 0x47
  write 0xb800a646028c0010 0x1 0x02
  write 0xb800a646028c0017 0x1 0x06
  write 0xb800a646028c0036 0x1 0x80
  write 0xe00000d9 0x1 0x40
  EOF

Buglink: https://gitlab.com/qemu-project/qemu/-/issues/1582
Closes: https://gitlab.com/qemu-project/qemu/-/issues/1582
Cc: [email protected]
Cc: Peter Maydell <[email protected]>
Fixes: 6d71357a3b ("rtl8139: honor large send MSS value")
Reported-by: Alexander Bulekov <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Tested-by: Alexander Bulekov <[email protected]>
Signed-off-by: Stefan Hajnoczi <[email protected]>
Signed-off-by: Jason Wang <[email protected]>
(cherry picked from commit 792676c165)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-24 18:07:21 +03:00
Akihiko Odaki 02bd13ae3a igb: Always copy ethernet header
igb_receive_internal() used to check the iov length to determine
copy the iovs to a contiguous buffer, but the check is flawed in two
ways:
- It does not ensure that iovcnt > 0.
- It does not take virtio-net header into consideration.

The size of this copy is just 22 octets, which can be even less than
the code size required for checks. This (wrong) optimization is probably
not worth so just remove it. Removing this also allows igb to assume
aligned accesses for the ethernet header.

Fixes: 3a977deebe ("Intrdocue igb device emulation")
Signed-off-by: Akihiko Odaki <[email protected]>
Reviewed-by: Sriram Yagnaraman <[email protected]>
Signed-off-by: Jason Wang <[email protected]>
(cherry picked from commit dc9ef1bf45)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-24 16:37:48 +03:00
Akihiko Odaki c84bcff3d3 e1000e: Always copy ethernet header
e1000e_receive_internal() used to check the iov length to determine
copy the iovs to a contiguous buffer, but the check is flawed in two
ways:
- It does not ensure that iovcnt > 0.
- It does not take virtio-net header into consideration.

The size of this copy is just 18 octets, which can be even less than
the code size required for checks. This (wrong) optimization is probably
not worth so just remove it.

Fixes: 6f3fbe4ed0 ("net: Introduce e1000e device emulation")
Signed-off-by: Akihiko Odaki <[email protected]>
Signed-off-by: Jason Wang <[email protected]>
(cherry picked from commit 310a128eae)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-24 16:35:30 +03:00
Akihiko Odaki 5c4f2f1b60 net/net_rx_pkt: Use iovec for net_rx_pkt_set_protocols()
igb does not properly ensure the buffer passed to
net_rx_pkt_set_protocols() is contiguous for the entire L2/L3/L4 header.
Allow it to pass scattered data to net_rx_pkt_set_protocols().

Fixes: 3a977deebe ("Intrdocue igb device emulation")
Signed-off-by: Akihiko Odaki <[email protected]>
Reviewed-by: Sriram Yagnaraman <[email protected]>
Signed-off-by: Jason Wang <[email protected]>
(cherry picked from commit 2f0fa232b8)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-24 16:34:46 +03:00
Akihiko Odaki ba3c7bf178 igb: Clear IMS bits when committing ICR access
The datasheet says contradicting statements regarding ICR accesses so it
is not reliable to determine the behavior of ICR accesses. However,
e1000e does clear IMS bits when reading ICR accesses and Linux also
expects ICR accesses will clear IMS bits according to:
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/drivers/net/ethernet/intel/igb/igb_main.c?h=v6.2#n8048

Fixes: 3a977deebe ("Intrdocue igb device emulation")
Signed-off-by: Akihiko Odaki <[email protected]>
Reviewed-by: Sriram Yagnaraman <[email protected]>
Signed-off-by: Jason Wang <[email protected]>
(cherry picked from commit f0b1df5c45)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-24 16:34:28 +03:00
Akihiko Odaki 6e260100d0 igb: Do not require CTRL.VME for tx VLAN tagging
While the datasheet of e1000e says it checks CTRL.VME for tx VLAN
tagging, igb's datasheet has no such statements. It also says for
"CTRL.VLE":
> This register only affects the VLAN Strip in Rx it does not have any
> influence in the Tx path in the 82576.
(Appendix A. Changes from the 82575)

There is no "CTRL.VLE" so it is more likely that it is a mistake of
CTRL.VME.

Fixes: fba7c3b788 ("igb: respect VMVIR and VMOLR for VLAN")
Signed-off-by: Akihiko Odaki <[email protected]>
Reviewed-by: Sriram Yagnaraman <[email protected]>
Signed-off-by: Jason Wang <[email protected]>
(cherry picked from commit e209716749)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-24 16:34:04 +03:00
Akihiko Odaki 9ff3fe63fc igb: Fix Rx packet type encoding
igb's advanced descriptor uses a packet type encoding different from
one used in e1000e's extended descriptor. Fix the logic to encode
Rx packet type accordingly.

Fixes: 3a977deebe ("Intrdocue igb device emulation")
Signed-off-by: Akihiko Odaki <[email protected]>
Reviewed-by: Sriram Yagnaraman <[email protected]>
Signed-off-by: Jason Wang <[email protected]>
(cherry picked from commit ed447c60b3)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-24 16:33:54 +03:00
Akihiko Odaki 0f7ca2bf2c e1000x: Fix BPRC and MPRC
Before this change, e1000 and the common code updated BPRC and MPRC
depending on the matched filter, but e1000e and igb decided to update
those counters by deriving the packet type independently. This
inconsistency caused a multicast packet to be counted twice.

Updating BPRC and MPRC depending on are fundamentally flawed anyway as
a filter can be used for different types of packets. For example, it is
possible to filter broadcast packets with MTA.

Always determine what counters to update by inspecting the packets.

Fixes: 3b27430177 ("e1000: Implementing various counters")
Signed-off-by: Akihiko Odaki <[email protected]>
Reviewed-by: Sriram Yagnaraman <[email protected]>
Signed-off-by: Jason Wang <[email protected]>
(cherry picked from commit f3f9b726af)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-24 16:31:45 +03:00
[email protected] eb134d1d58 e1000e: Fix tx/rx counters
The bytes and packets counter registers are cleared on read.

Copying the "total counter" registers to the "good counter" registers has
side effects.
If the "total" register is never read by the OS, it only gets incremented.
This leads to exponential growth of the "good" register.

This commit increments the counters individually to avoid this.

Signed-off-by: Timothée Cocault <[email protected]>
Signed-off-by: Jason Wang <[email protected]>
(cherry picked from commit 8d689f6aae)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-23 22:07:47 +03:00
Kevin Wolf a7002f15c8 nbd/server: Fix drained_poll to wake coroutine in right AioContext
nbd_drained_poll() generally runs in the main thread, not whatever
iothread the NBD server coroutine is meant to run in, so it can't
directly reenter the coroutines to wake them up.

The code seems to have the right intention, it specifies the correct
AioContext when it calls qemu_aio_coroutine_enter(). However, this
functions doesn't schedule the coroutine to run in that AioContext, but
it assumes it is already called in the home thread of the AioContext.

To fix this, add a new thread-safe qio_channel_wake_read() that can be
called in the main thread to wake up the coroutine in its AioContext,
and use this in nbd_drained_poll().

Cc: [email protected]
Signed-off-by: Kevin Wolf <[email protected]>
Message-Id: <[email protected]>
Reviewed-by: Eric Blake <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit 7c1f51bf38)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-22 20:54:40 +03:00
Kevin Wolf d001f222e3 graph-lock: Disable locking for now
In QEMU 8.0, we've been seeing deadlocks in bdrv_graph_wrlock(). They
come from callers that hold an AioContext lock, which is not allowed
during polling. In theory, we could temporarily release the lock, but
callers are inconsistent about whether they hold a lock, and if they do,
some are also confused about which one they hold. While all of this is
fixable, it's not trivial, and the best course of action for 8.0.1 is
probably just disabling the graph locking code temporarily.

We don't currently rely on graph locking yet. It is supposed to replace
the AioContext lock eventually to enable multiqueue support, but as long
as we still have the AioContext lock, it is sufficient without the graph
lock. Once the AioContext lock goes away, the deadlock doesn't exist any
more either and this commit can be reverted. (Of course, it can also be
reverted while the AioContext lock still exists if the callers have been
fixed.)

Cc: [email protected]
Signed-off-by: Kevin Wolf <[email protected]>
Message-Id: <[email protected]>
Reviewed-by: Eric Blake <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit 80fc5d2600)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-22 20:54:40 +03:00
Stefan Hajnoczi 84d839e499 block: compile out assert_bdrv_graph_readable() by default
reader_count() is a performance bottleneck because the global
aio_context_list_lock mutex causes thread contention. Put this debugging
assertion behind a new ./configure --enable-debug-graph-lock option and
disable it by default.

The --enable-debug-graph-lock option is also enabled by the more general
--enable-debug option.

Signed-off-by: Stefan Hajnoczi <[email protected]>
Message-Id: <[email protected]>
Reviewed-by: Kevin Wolf <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit 58a2e3f5c3)
Signed-off-by: Michael Tokarev <[email protected]>
(Mjt: pick this one up so the next patch which disables this applies cleanly)
2023-05-22 20:53:40 +03:00
Stefan Hajnoczi a0b89ba845 tested: add test for nested aio_poll() in poll handlers
Cc: [email protected]
Signed-off-by: Stefan Hajnoczi <[email protected]>
Message-Id: <[email protected]>
[kwolf: Restrict to CONFIG_POSIX, Windows doesn't support polling]
Tested-by: Kevin Wolf <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit 844a12a63e)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-22 19:38:44 +03:00
Stefan Hajnoczi a91defe16b aio-posix: do not nest poll handlers
QEMU's event loop supports nesting, which means that event handler
functions may themselves call aio_poll(). The condition that triggered a
handler must be reset before the nested aio_poll() call, otherwise the
same handler will be called and immediately re-enter aio_poll. This
leads to an infinite loop and stack exhaustion.

Poll handlers are especially prone to this issue, because they typically
reset their condition by finishing the processing of pending work.
Unfortunately it is during the processing of pending work that nested
aio_poll() calls typically occur and the condition has not yet been
reset.

Disable a poll handler during ->io_poll_ready() so that a nested
aio_poll() call cannot invoke ->io_poll_ready() again. As a result, the
disabled poll handler and its associated fd handler do not run during
the nested aio_poll(). Calling aio_set_fd_handler() from inside nested
aio_poll() could cause it to run again. If the fd handler is pending
inside nested aio_poll(), then it will also run again.

In theory fd handlers can be affected by the same issue, but they are
more likely to reset the condition before calling nested aio_poll().

This is a special case and it's somewhat complex, but I don't see a way
around it as long as nested aio_poll() is supported.

Cc: [email protected]
Buglink: https://bugzilla.redhat.com/show_bug.cgi?id=2186181
Fixes: c382706925 ("block: Mark bdrv_co_io_(un)plug() and callers GRAPH_RDLOCK")
Cc: Kevin Wolf <[email protected]>
Cc: Emanuele Giuseppe Esposito <[email protected]>
Cc: Paolo Bonzini <[email protected]>
Signed-off-by: Stefan Hajnoczi <[email protected]>
Message-Id: <[email protected]>
Reviewed-by: Kevin Wolf <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit 6d740fb01b)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-22 19:38:44 +03:00
Mauro Matteo Cascella 81d13aa5e0 virtio-crypto: fix NULL pointer dereference in virtio_crypto_free_request
Ensure op_info is not NULL in case of QCRYPTODEV_BACKEND_ALG_SYM algtype.

Fixes: 0e660a6f90 ("crypto: Introduce RSA algorithm")
Signed-off-by: Mauro Matteo Cascella <[email protected]>
Reported-by: Yiming Tao <[email protected]>
Message-Id: <[email protected]>
Reviewed-by: Gonglei <[email protected]>
Reviewed-by: zhenwei pi<[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
(cherry picked from commit 3e69908907)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-22 19:38:44 +03:00
Eugenio Pérez 302ac06ab9 virtio-net: not enable vq reset feature unconditionally
The commit 93a97dc520 ("virtio-net: enable vq reset feature") enables
unconditionally vq reset feature as long as the device is emulated.
This makes impossible to actually disable the feature, and it causes
migration problems from qemu version previous than 7.2.

The entire final commit is unneeded as device system already enable or
disable the feature properly.

This reverts commit 93a97dc520.
Fixes: 93a97dc520 ("virtio-net: enable vq reset feature")
Signed-off-by: Eugenio Pérez <[email protected]>

Message-Id: <[email protected]>
Reviewed-by: Xuan Zhuo <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
(cherry picked from commit 1fac00f70b)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-22 19:38:44 +03:00
Leonardo Bras adc49750d2 hw/pci: Disable PCI_ERR_UNCOR_MASK register for machine type < 8.0
Since it's implementation on v8.0.0-rc0, having the PCI_ERR_UNCOR_MASK
set for machine types < 8.0 will cause migration to fail if the target
QEMU version is < 8.0.0 :

qemu-system-x86_64: get_pci_config_device: Bad config data: i=0x10a read: 40 device: 0 cmask: ff wmask: 0 w1cmask:0
qemu-system-x86_64: Failed to load PCIDevice:config
qemu-system-x86_64: Failed to load e1000e:parent_obj
qemu-system-x86_64: error while loading state for instance 0x0 of device '0000:00:02.0/e1000e'
qemu-system-x86_64: load of migration failed: Invalid argument

The above test migrated a 7.2 machine type from QEMU master to QEMU 7.2.0,
with this cmdline:

./qemu-system-x86_64 -M pc-q35-7.2 [-incoming XXX]

In order to fix this, property x-pcie-err-unc-mask was introduced to
control when PCI_ERR_UNCOR_MASK is enabled. This property is enabled by
default, but is disabled if machine type <= 7.2.

Fixes: 010746ae1d ("hw/pci/aer: Implement PCI_ERR_UNCOR_MASK register")
Suggested-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Leonardo Bras <[email protected]>
Message-Id: <[email protected]>
Reviewed-by: Jonathan Cameron <[email protected]>
Reviewed-by: Peter Xu <[email protected]>
Reviewed-by: Juan Quintela <[email protected]>
Fixes: https://gitlab.com/qemu-project/qemu/-/issues/1576
Tested-by: Fiona Ebner <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
(cherry picked from commit 5ed3dabe57)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-22 19:38:44 +03:00
Hawkins Jiawei a9144eed6c vhost: fix possible wrap in SVQ descriptor ring
QEMU invokes vhost_svq_add() when adding a guest's element
into SVQ. In vhost_svq_add(), it uses vhost_svq_available_slots()
to check whether QEMU can add the element into SVQ. If there is
enough space, then QEMU combines some out descriptors and some
in descriptors into one descriptor chain, and adds it into
`svq->vring.desc` by vhost_svq_vring_write_descs().

Yet the problem is that, `svq->shadow_avail_idx - svq->shadow_used_idx`
in vhost_svq_available_slots() returns the number of occupied elements,
or the number of descriptor chains, instead of the number of occupied
descriptors, which may cause wrapping in SVQ descriptor ring.

Here is an example. In vhost_handle_guest_kick(), QEMU forwards
as many available buffers to device by virtqueue_pop() and
vhost_svq_add_element(). virtqueue_pop() returns a guest's element,
and then this element is added into SVQ by vhost_svq_add_element(),
a wrapper to vhost_svq_add(). If QEMU invokes virtqueue_pop() and
vhost_svq_add_element() `svq->vring.num` times,
vhost_svq_available_slots() thinks QEMU just ran out of slots and
everything should work fine. But in fact, virtqueue_pop() returns
`svq->vring.num` elements or descriptor chains, more than
`svq->vring.num` descriptors due to guest memory fragmentation,
and this causes wrapping in SVQ descriptor ring.

This bug is valid even before marking the descriptors used.
If the guest memory is fragmented, SVQ must add chains
so it can try to add more descriptors than possible.

This patch solves it by adding `num_free` field in
VhostShadowVirtqueue structure and updating this field
in vhost_svq_add() and vhost_svq_get_buf(), to record
the number of free descriptors.

Fixes: 100890f7ca ("vhost: Shadow virtqueue buffers forwarding")
Signed-off-by: Hawkins Jiawei <[email protected]>
Acked-by: Eugenio Pérez <[email protected]>
Message-Id: <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Tested-by: Lei Yang <[email protected]>
(cherry picked from commit 5d410557de)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-19 23:23:50 +03:00
Xinyu Li 0de5117819 target/i386: fix avx2 instructions vzeroall and vpermdq
vzeroall: xmm_regs should be used instead of xmm_t0
vpermdq: bit 3 and 7 of imm should be considered

Signed-off-by: Xinyu Li <[email protected]>
Message-Id: <[email protected]>
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 056d649007)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-18 20:46:55 +03:00
Paolo Bonzini db8051ad59 target/i386: fix operand size for VCOMI/VUCOMI instructions
Compared to other SSE instructions, VUCOMISx and VCOMISx are different:
the single and double precision versions are distinguished through a
prefix, however they use no-prefix and 0x66 for SS and SD respectively.
Scalar values usually are associated with 0xF2 and 0xF3.

Because of these, they incorrectly perform a 128-bit memory load instead
of a 32- or 64-bit load.  Fix this by writing a custom decoding function.

I tested that the reproducer is fixed and the test-avx output does not
change.

Reported-by: Gabriele Svelto <[email protected]>
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/1637
Fixes: f8d19eec0d ("target/i386: reimplement 0x0f 0x28-0x2f, add AVX", 2022-10-18)
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 2b55e479e6)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-18 20:46:47 +03:00
Paolo Bonzini 1e029102e6 scsi-generic: fix buffer overflow on block limits inquiry
Using linux 6.x guest, at boot time, an inquiry on a scsi-generic
device makes qemu crash.  This is caused by a buffer overflow when
scsi-generic patches the block limits VPD page.

Do the operations on a temporary on-stack buffer that is guaranteed
to be large enough.

Reported-by: Théo Maillart <[email protected]>
Analyzed-by: Théo Maillart <[email protected]>
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 9bd634b2f5)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-18 20:46:29 +03:00
Richard Henderson c283a4bc76 target/arm: Fix vd == vm overlap in sve_ldff1_z
If vd == vm, copy vm to scratch, so that we can pre-zero
the output and still access the gather indicies.

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/1612
Signed-off-by: Richard Henderson <[email protected]>
Message-id: [email protected]
Reviewed-by: Peter Maydell <[email protected]>
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit a6771f2f5c)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-18 17:56:51 +03:00
Eric Blake c0ad2a9191 migration: Attempt disk reactivation in more failure scenarios
Commit fe904ea824 added a fail_inactivate label, which tries to
reactivate disks on the source after a failure while s->state ==
MIGRATION_STATUS_ACTIVE, but didn't actually use the label if
qemu_savevm_state_complete_precopy() failed.  This failure to
reactivate is also present in commit 6039dd5b1c (also covering the new
s->state == MIGRATION_STATUS_DEVICE state) and 403d18ae (ensuring
s->block_inactive is set more reliably).

Consolidate the two labels back into one - no matter HOW migration is
failed, if there is any chance we can reach vm_start() after having
attempted inactivation, it is essential that we have tried to restart
disks before then.  This also makes the cleanup more like
migrate_fd_cancel().

Suggested-by: Kevin Wolf <[email protected]>
Signed-off-by: Eric Blake <[email protected]>
Message-Id: <[email protected]>
Acked-by: Peter Xu <[email protected]>
Reviewed-by: Juan Quintela <[email protected]>
Reviewed-by: Kevin Wolf <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit 6dab4c93ec)
Signed-off-by: Michael Tokarev <[email protected]>
(Mjt: minor context tweak near added comment in migration/migration.c)
2023-05-18 16:59:30 +03:00
Eric Blake d2a811dd7d migration: Minor control flow simplification
No need to declare a temporary variable.

Suggested-by: Juan Quintela <[email protected]>
Fixes: 1df36e8c6289 ("migration: Handle block device inactivation failures better")
Signed-off-by: Eric Blake <[email protected]>
Reviewed-by: Juan Quintela <[email protected]>
Signed-off-by: Juan Quintela <[email protected]>
(cherry picked from commit 5d39f44d7a)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-18 16:57:44 +03:00
Eric Blake cb898262a4 migration: Handle block device inactivation failures better
Consider what happens when performing a migration between two host
machines connected to an NFS server serving multiple block devices to
the guest, when the NFS server becomes unavailable.  The migration
attempts to inactivate all block devices on the source (a necessary
step before the destination can take over); but if the NFS server is
non-responsive, the attempt to inactivate can itself fail.  When that
happens, the destination fails to get the migrated guest (good,
because the source wasn't able to flush everything properly):

  (qemu) qemu-kvm: load of migration failed: Input/output error

at which point, our only hope for the guest is for the source to take
back control.  With the current code base, the host outputs a message, but then appears to resume:

  (qemu) qemu-kvm: qemu_savevm_state_complete_precopy_non_iterable: bdrv_inactivate_all() failed (-1)

  (src qemu)info status
   VM status: running

but a second migration attempt now asserts:

  (src qemu) qemu-kvm: ../block.c:6738: int bdrv_inactivate_recurse(BlockDriverState *): Assertion `!(bs->open_flags & BDRV_O_INACTIVE)' failed.

Whether the guest is recoverable on the source after the first failure
is debatable, but what we do not want is to have qemu itself fail due
to an assertion.  It looks like the problem is as follows:

In migration.c:migration_completion(), the source sets 'inactivate' to
true (since COLO is not enabled), then tries
savevm.c:qemu_savevm_state_complete_precopy() with a request to
inactivate block devices.  In turn, this calls
block.c:bdrv_inactivate_all(), which fails when flushing runs up
against the non-responsive NFS server.  With savevm failing, we are
now left in a state where some, but not all, of the block devices have
been inactivated; but migration_completion() then jumps to 'fail'
rather than 'fail_invalidate' and skips an attempt to reclaim those
those disks by calling bdrv_activate_all().  Even if we do attempt to
reclaim disks, we aren't taking note of failure there, either.

Thus, we have reached a state where the migration engine has forgotten
all state about whether a block device is inactive, because we did not
set s->block_inactive in enough places; so migration allows the source
to reach vm_start() and resume execution, violating the block layer
invariant that the guest CPUs should not be restarted while a device
is inactive.  Note that the code in migration.c:migrate_fd_cancel()
will also try to reactivate all block devices if s->block_inactive was
set, but because we failed to set that flag after the first failure,
the source assumes it has reclaimed all devices, even though it still
has remaining inactivated devices and does not try again.  Normally,
qmp_cont() will also try to reactivate all disks (or correctly fail if
the disks are not reclaimable because NFS is not yet back up), but the
auto-resumption of the source after a migration failure does not go
through qmp_cont().  And because we have left the block layer in an
inconsistent state with devices still inactivated, the later migration
attempt is hitting the assertion failure.

Since it is important to not resume the source with inactive disks,
this patch marks s->block_inactive before attempting inactivation,
rather than after succeeding, in order to prevent any vm_start() until
it has successfully reactivated all devices.

See also https://bugzilla.redhat.com/show_bug.cgi?id=2058982

Signed-off-by: Eric Blake <[email protected]>
Reviewed-by: Juan Quintela <[email protected]>
Acked-by: Lukas Straub <[email protected]>
Tested-by: Lukas Straub <[email protected]>
Signed-off-by: Juan Quintela <[email protected]>
(cherry picked from commit 403d18ae38)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-18 16:57:30 +03:00
Michael Tokarev 45a67df841 linux-user: fix getgroups/setgroups allocations
linux-user getgroups(), setgroups(), getgroups32() and setgroups32()
used alloca() to allocate grouplist arrays, with unchecked gidsetsize
coming from the "guest".  With NGROUPS_MAX being 65536 (linux, and it
is common for an application to allocate NGROUPS_MAX for getgroups()),
this means a typical allocation is half the megabyte on the stack.
Which just overflows stack, which leads to immediate SIGSEGV in actual
system getgroups() implementation.

An example of such issue is aptitude, eg
https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=811087#72

Cap gidsetsize to NGROUPS_MAX (return EINVAL if it is larger than that),
and use heap allocation for grouplist instead of alloca().  While at it,
fix coding style and make all 4 implementations identical.

Try to not impose random limits - for example, allow gidsetsize to be
negative for getgroups() - just do not allocate negative-sized grouplist
in this case but still do actual getgroups() call.  But do not allow
negative gidsetsize for setgroups() since its argument is unsigned.

Capping by NGROUPS_MAX seems a bit arbitrary, - we can do more, it is
not an error if set size will be NGROUPS_MAX+1. But we should not allow
integer overflow for the array being allocated. Maybe it is enough to
just call g_try_new() and return ENOMEM if it fails.

Maybe there's also no need to convert setgroups() since this one is
usually smaller and known beforehand (KERN_NGROUPS_MAX is actually 63, -
this is apparently a kernel-imposed limit for runtime group set).

The patch fixes aptitude segfault mentioned above.

Signed-off-by: Michael Tokarev <[email protected]>
Message-Id: <[email protected]>
Signed-off-by: Laurent Vivier <[email protected]>
(cherry picked from commit 1e35d32789)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-18 14:44:13 +03:00
Daniil Kovalev 69a6ea7c4b linux-user: Fix mips fp64 executables loading
If a program requires fr1, we should set the FR bit of CP0 control status
register and add F64 hardware flag. The corresponding `else if` branch
statement is copied from the linux kernel sources (see `arch_check_elf` function
in linux/arch/mips/kernel/elf.c).

Signed-off-by: Daniil Kovalev <[email protected]>
Reviewed-by: Jiaxun Yang <[email protected]>
Message-Id: <[email protected]>
Signed-off-by: Laurent Vivier <[email protected]>
(cherry picked from commit a0f8d2701b)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-18 14:44:13 +03:00
Alex Bennée 0b1b5a4204 tests/docker: bump the xtensa base to debian:11-slim
Stretch is going out of support so things like security updates will
fail. As the toolchain itself is binary it hopefully won't mind the
underlying OS being updated.

Message-Id: <[email protected]>
Reviewed-by: Thomas Huth <[email protected]>
Reviewed-by: Juan Quintela <[email protected]>
Signed-off-by: Alex Bennée <[email protected]>
Reported-by: Richard Henderson <[email protected]>
(cherry picked from commit 3217b84f3c)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-18 14:44:13 +03:00
Lizhi Yang eb82a80f51 docs/about/emulation: fix typo
Duplicated word "are".

Signed-off-by: Lizhi Yang <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Message-Id: <[email protected]>
Signed-off-by: Thomas Huth <[email protected]>
(cherry picked from commit c70bb9a771)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-17 12:27:58 +03:00
Claudio Imbrenda 8ad637881f util/async-teardown: wire up query-command-line-options
Add new -run-with option with an async-teardown=on|off parameter. It is
visible in the output of query-command-line-options QMP command, so it
can be discovered and used by libvirt.

The option -async-teardown is now redundant, deprecate it.

Reported-by: Boris Fiuczynski <[email protected]>
Fixes: c891c24b1a ("os-posix: asynchronous teardown for shutdown on Linux")
Signed-off-by: Claudio Imbrenda <[email protected]>
Message-Id: <[email protected]>
[thuth: Add curly braces to fix error with GCC 8.5, fix bug in deprecated.rst]
Signed-off-by: Thomas Huth <[email protected]>
(cherry picked from commit 80bd81cadd)
Signed-off-by: Michael Tokarev <[email protected]>
(Mjt: context tweak in docs/about/deprecated.rst)
2023-05-17 12:27:58 +03:00
Claudio Imbrenda 21b54a683d s390x/pv: Fix spurious warning with asynchronous teardown
Kernel commit 292a7d6fca33 ("KVM: s390: pv: fix asynchronous teardown
for small VMs") causes the KVM_PV_ASYNC_CLEANUP_PREPARE ioctl to fail
if the VM is not larger than 2GiB. QEMU would attempt it and fail,
print an error message, and then proceed with a normal teardown.

Avoid attempting to use asynchronous teardown altogether when the VM is
not larger than 2 GiB. This will avoid triggering the error message and
also avoid pointless overhead; normal teardown is fast enough for small
VMs.

Reported-by: Marc Hartmayer <[email protected]>
Fixes: c3a073c610 ("s390x/pv: Add support for asynchronous teardown for reboot")
Link: https://lore.kernel.org/all/[email protected]/
Signed-off-by: Claudio Imbrenda <[email protected]>
Message-Id: <[email protected]>
Reviewed-by: Thomas Huth <[email protected]>
[thuth: Fix inline function parameter in pv.h]
Signed-off-by: Thomas Huth <[email protected]>
(cherry picked from commit 88693ab2a5)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-17 12:27:58 +03:00
Richard Henderson 36cd9bc8e2 tcg/i386: Set P_REXW in tcg_out_addi_ptr
The REXW bit must be set to produce a 64-bit pointer result; the
bit is disabled in 32-bit mode, so we can do this unconditionally.

Fixes: 7d9e1ee424 ("tcg/i386: Adjust assert in tcg_out_addi_ptr")
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/1592
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/1642
Signed-off-by: Richard Henderson <[email protected]>
(cherry picked from commit 988998503b)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-17 12:27:58 +03:00
Jason Andryuk 117f33c9a7 9pfs/xen: Fix segfault on shutdown
xen_9pfs_free can't use gnttabdev since it is already closed and NULL-ed
out when free is called.  Do the teardown in _disconnect().  This
matches the setup done in _connect().

trace-events are also added for the XenDevOps functions.

Signed-off-by: Jason Andryuk <[email protected]>
Reviewed-by: Stefano Stabellini <[email protected]>
Message-Id: <[email protected]>
[C.S.: - Remove redundant return in xen_9pfs_free().
       - Add comment to trace-events. ]
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit 92e667f6fd)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-17 12:27:58 +03:00
Ilya Leoshkevich e347aa89dd s390x/tcg: Fix LDER instruction format
It's RRE, not RXE.

Found by running valgrind's none/tests/s390x/bfp-2.

Fixes: 86b59624c4 ("s390x/tcg: Implement LOAD LENGTHENED short HFP to long HFP")
Reviewed-by: David Hildenbrand <[email protected]>
Signed-off-by: Ilya Leoshkevich <[email protected]>
Message-Id: <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Thomas Huth <[email protected]>
(cherry picked from commit 970641de01)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-17 12:27:58 +03:00
Ilya Leoshkevich b858c53ef6 target/s390x: Fix EXECUTE of relative branches
Fix a problem similar to the one fixed by commit 703d03a4aa
("target/s390x: Fix EXECUTE of relative long instructions"), but now
for relative branches.

Reported-by: Nina Schoetterl-Glausch <[email protected]>
Signed-off-by: Ilya Leoshkevich <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Message-Id: <[email protected]>
Signed-off-by: Thomas Huth <[email protected]>
(cherry picked from commit e8ecdfeb30)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-16 19:08:39 +03:00
Shivaprasad G Bhat 7ceebe3f90 tcg: ppc64: Fix mask generation for vextractdm
In function do_extractm() the mask is calculated as
dup_const(1 << (element_width - 1)). '1' being signed int
works fine for MO_8,16,32. For MO_64, on PPC64 host
this ends up becoming 0 on compilation. The vextractdm
uses MO_64, and it ends up having mask as 0.

Explicitly use 1ULL instead of signed int 1 like its
used everywhere else.

Resolves: https://gitlab.com/qemu-project/qemu/-/issues/1536
Signed-off-by: Shivaprasad G Bhat <[email protected]>
Reviewed-by: Alex Bennée <[email protected]>
Reviewed-by: Lucas Mateus Castro <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Reviewed-by: Cédric Le Goater <[email protected]>
Message-Id: <168319292809.1159309.5817546227121323288.stgit@ltc-boston1.aus.stglabs.ibm.com>
Signed-off-by: Daniel Henrique Barboza <[email protected]>
(cherry picked from commit 6a5d81b172)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-15 18:42:50 +03:00
Cédric Le Goater 950882af67 async: Suppress GCC13 false positive in aio_bh_poll()
GCC13 reports an error :

../util/async.c: In function ‘aio_bh_poll’:
include/qemu/queue.h:303:22: error: storing the address of local variable ‘slice’ in ‘*ctx.bh_slice_list.sqh_last’ [-Werror=dangling-pointer=]
  303 |     (head)->sqh_last = &(elm)->field.sqe_next;                          \
      |     ~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~
../util/async.c:169:5: note: in expansion of macro ‘QSIMPLEQ_INSERT_TAIL’
  169 |     QSIMPLEQ_INSERT_TAIL(&ctx->bh_slice_list, &slice, next);
      |     ^~~~~~~~~~~~~~~~~~~~
../util/async.c:161:17: note: ‘slice’ declared here
  161 |     BHListSlice slice;
      |                 ^~~~~
../util/async.c:161:17: note: ‘ctx’ declared here

But the local variable 'slice' is removed from the global context list
in following loop of the same routine. Add a pragma to silent GCC.

Cc: Stefan Hajnoczi <[email protected]>
Cc: Paolo Bonzini <[email protected]>
Cc: Daniel P. Berrangé <[email protected]>
Signed-off-by: Cédric Le Goater <[email protected]>
Reviewed-by: Daniel Henrique Barboza <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Stefan Hajnoczi <[email protected]>
Reviewed-by: Thomas Huth <[email protected]>
Tested-by: Daniel Henrique Barboza <[email protected]>
Message-Id: <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit d66ba6dc1c)
Signed-off-by: Michael Tokarev <[email protected]>
(Mjt: cherry-picked to stable-8.0 to eliminate CI failures on win*)
2023-05-15 18:03:51 +03:00
Peter Maydell e09f912550 target/arm: Correct AArch64.S2MinTxSZ 32-bit EL1 input size check
In check_s2_mmu_setup() we have a check that is attempting to
implement the part of AArch64.S2MinTxSZ that is specific to when EL1
is AArch32:

    if !s1aarch64 then
        // EL1 is AArch32
        min_txsz = Min(min_txsz, 24);

Unfortunately we got this wrong in two ways:

(1) The minimum txsz corresponds to a maximum inputsize, but we got
the sense of the comparison wrong and were faulting for all
inputsizes less than 40 bits

(2) We try to implement this as an extra check that happens after
we've done the same txsz checks we would do for an AArch64 EL1, but
in fact the pseudocode is *loosening* the requirements, so that txsz
values that would fault for an AArch64 EL1 do not fault for AArch32
EL1, because it does Min(old_min, 24), not Max(old_min, 24).

You can see this also in the text of the Arm ARM in table D8-8, which
shows that where the implemented PA size is less than 40 bits an
AArch32 EL1 is still OK with a configured stage2 T0SZ for a 40 bit
IPA, whereas if EL1 is AArch64 then the T0SZ must be big enough to
constrain the IPA to the implemented PA size.

Because of part (2), we can't do this as a separate check, but
have to integrate it into aa64_va_parameters(). Add a new argument
to that function to indicate that EL1 is 32-bit. All the existing
callsites except the one in get_phys_addr_lpae() can pass 'false',
because they are either doing a lookup for a stage 1 regime or
else they don't care about the tsz/tsz_oob fields.

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/1627
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Message-id: [email protected]
(cherry picked from commit 478dccbb99)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-14 11:25:57 +03:00
Peter Maydell 80a2c1b5fe ui: Fix pixel colour channel order for PNG screenshots
When we take a PNG screenshot the ordering of the colour channels in
the data is not correct, resulting in the image having weird
colouring compared to the actual display.  (Specifically, on a
little-endian host the blue and red channels are swapped; on
big-endian everything is wrong.)

This happens because the pixman idea of the pixel data and the libpng
idea differ.  PIXMAN_a8r8g8b8 defines that pixels are 32-bit values,
with A in bits 24-31, R in bits 16-23, G in bits 8-15 and B in bits
0-7.  This means that on little-endian systems the bytes in memory
are
   B G R A
and on big-endian systems they are
   A R G B

libpng, on the other hand, thinks of pixels as being a series of
values for each channel, so its format PNG_COLOR_TYPE_RGB_ALPHA
always wants bytes in the order
   R G B A

This isn't the same as the pixman order for either big or little
endian hosts.

The alpha channel is also unnecessary bulk in the output PNG file,
because there is no alpha information in a screenshot.

To handle the endianness issue, we already define in ui/qemu-pixman.h
various PIXMAN_BE_* and PIXMAN_LE_* values that give consistent
byte-order pixel channel formats.  So we can use PIXMAN_BE_r8g8b8 and
PNG_COLOR_TYPE_RGB, which both have an in-memory byte order of
    R G B
and 3 bytes per pixel.

(PPM format screenshots get this right; they already use the
PIXMAN_BE_r8g8b8 format.)

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/1622
Fixes: 9a0a119a38 ("Added parameter to take screenshot with screendump as PNG")
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Marc-André Lureau <[email protected]>
Message-id: [email protected]
(cherry picked from commit cd22a0f520)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-14 11:24:05 +03:00
Peter Maydell 3148fe1ac8 target/arm: Fix handling of SW and NSW bits for stage 2 walks
We currently don't correctly handle the VSTCR_EL2.SW and VTCR_EL2.NSW
configuration bits.  These allow configuration of whether the stage 2
page table walks for Secure IPA and NonSecure IPA should do their
descriptor reads from Secure or NonSecure physical addresses. (This
is separate from how the translation table base address and other
parameters are set: an NS IPA always uses VTTBR_EL2 and VTCR_EL2
for its base address and walk parameters, regardless of the NSW bit,
and similarly for Secure.)

Provide a new function ptw_idx_for_stage_2() which returns the
MMU index to use for descriptor reads, and use it to set up
the .in_ptw_idx wherever we call get_phys_addr_lpae().

For a stage 2 walk, wherever we call get_phys_addr_lpae():
 * .in_ptw_idx should be ptw_idx_for_stage_2() of the .in_mmu_idx
 * .in_secure should be true if .in_mmu_idx is Stage2_S

This allows us to correct S1_ptw_translate() so that it consistently
always sets its (out_secure, out_phys) to the result it gets from the
S2 walk (either by calling get_phys_addr_lpae() or by TLB lookup).
This makes better conceptual sense because the S2 walk should return
us an (address space, address) tuple, not an address that we then
randomly assign to S or NS.

Our previous handling of SW and NSW was broken, so guest code
trying to use these bits to put the s2 page tables in the "other"
address space wouldn't work correctly.

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/1600
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Message-id: [email protected]
(cherry picked from commit fcc0b0418f)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-14 11:23:49 +03:00
Richard Henderson 4b59b5bd14 accel/tcg: Fix atomic_mmu_lookup for reads
A copy-paste bug had us looking at the victim cache for writes.

Cc: [email protected]
Reported-by: Peter Maydell <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
Fixes: 08dff435e2 ("tcg: Probe the proper permissions for atomic ops")
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Peter Maydell <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit 8c313254e6)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-11 15:40:16 +03:00
Jonathan Cameron 488ad8b302 hw/pci-bridge: pci_expander_bridge fix type in pxb_cxl_dev_reset()
Reproduce issue with

configure --enable-qom-cast-debug ...

qemu-system-x86_64 -display none -machine q35,cxl=on -device pxb-cxl,bus=pcie.0

  hw/pci-bridge/pci_expander_bridge.c:54:PXB_DEV: Object 0x5570e0b1ada0 is not an instance of type pxb
  Aborted

The type conversion results in the right state structure, but PXB_DEV is
not a parent of PXB_CXL_DEV hence the error. Rather than directly
cleaning up the inheritance, this is the minimal fix which will be
followed by the cleanup.

Fixes: 154070eaf6 ("hw/pxb-cxl: Support passthrough HDM Decoders unless overridden")
Reported-by: Peter Maydell <[email protected]>
Signed-off-by: Jonathan Cameron <[email protected]>
Message-Id: <[email protected]>
Reviewed-by: Thomas Huth <[email protected]>
Cc: [email protected]
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
(cherry picked from commit 9136f661c7)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-10 20:50:38 +03:00
Bin Meng f91d0db71e target/riscv: Restore the predicate() NULL check behavior
When reading a non-existent CSR QEMU should raise illegal instruction
exception, but currently it just exits due to the g_assert() check.

This actually reverts commit 0ee342256a.
Some comments are also added to indicate that predicate() must be
provided for an implemented CSR.

Reported-by: Fei Wu <[email protected]>
Signed-off-by: Bin Meng <[email protected]>
Reviewed-by: Daniel Henrique Barboza <[email protected]>
Reviewed-by: Weiwei Li <[email protected]>
Reviewed-by: Alistair Francis <[email protected]>
Reviewed-by: LIU Zhiwei <[email protected]>
Message-Id: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit eae04c4c13)
(mjt: context edit after ce3af0bbbc "target/riscv: add support for Zcmt extension")
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-10 20:50:38 +03:00
LIU Zhiwei f5301431e8 target/riscv: Fix itrigger when icount is used
When I boot a ubuntu image, QEMU output a "Bad icount read" message and exit.
The reason is that when execute helper_mret or helper_sret, it will
cause a call to icount_get_raw_locked (), which needs set can_do_io flag
on cpustate.

Thus we setting this flag when execute these two instructions.

Signed-off-by: LIU Zhiwei <[email protected]>
Reviewed-by: Weiwei Li <[email protected]>
Acked-by: Alistair Francis <[email protected]>
Message-Id: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit df3ac6da47)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-10 20:50:38 +03:00
Kevin Wolf 3b02d0db4a block: Don't call no_coroutine_fns in qmp_block_resize()
This QMP handler runs in a coroutine, so it must use the corresponding
no_co_wrappers instead.

Fixes: https://bugzilla.redhat.com/show_bug.cgi?id=2185688
Cc: [email protected]
Signed-off-by: Kevin Wolf <[email protected]>
Reviewed-by: Eric Blake <[email protected]>
Reviewed-by: Stefan Hajnoczi <[email protected]>
Message-Id: <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit 0c7d204f50)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-10 20:50:38 +03:00
Kevin Wolf e0deae4f49 block: bdrv/blk_co_unref() for calls in coroutine context
These functions must not be called in coroutine context, because they
need write access to the graph.

Cc: [email protected]
Signed-off-by: Kevin Wolf <[email protected]>
Reviewed-by: Eric Blake <[email protected]>
Reviewed-by: Stefan Hajnoczi <[email protected]>
Message-Id: <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit b2ab5f545f)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-10 20:50:38 +03:00
Kevin Wolf 38a598aee3 block: Consistently call bdrv_activate() outside coroutine
Migration code can call bdrv_activate() in coroutine context, whereas
other callers call it outside of coroutines. As it calls other code that
is not supposed to run in coroutines, standardise on running outside of
coroutines.

This adds a no_co_wrapper to switch to the main loop before calling
bdrv_activate().

Cc: [email protected]
Signed-off-by: Kevin Wolf <[email protected]>
Reviewed-by: Eric Blake <[email protected]>
Reviewed-by: Stefan Hajnoczi <[email protected]>
Message-Id: <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit da4afaff07)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-10 20:50:38 +03:00
Kevin Wolf 2197a94cb4 block: Fix use after free in blockdev_mark_auto_del()
job_cancel_locked() drops the job list lock temporarily and it may call
aio_poll(). We must assume that the list has changed after this call.
Also, with unlucky timing, it can end up freeing the job during
job_completed_txn_abort_locked(), making the job pointer invalid, too.

For both reasons, we can't just continue at block_job_next_locked(job).
Instead, start at the head of the list again after job_cancel_locked()
and skip those jobs that we already cancelled (or that are completing
anyway).

Cc: [email protected]
Signed-off-by: Kevin Wolf <[email protected]>
Message-Id: <[email protected]>
Reviewed-by: Stefan Hajnoczi <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit e2626874a3)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-10 20:50:38 +03:00
Paolo Bonzini 8322e5300f meson: leave unnecessary modules out of the build
meson.build files choose whether to build modules based on foo.found()
expressions.  If a feature is enabled (e.g. --enable-gtk), these expressions
are true even if the code is not used by any emulator, and this results
in an unexpected difference between modular and non-modular builds.

For non-modular builds, the files are not included in any binary, and
therefore the source files are never processed.  For modular builds,
however, all .so files are unconditionally built by default, and therefore
a normal "make" tries to build them.  However, the corresponding trace-*.h
files are absent due to this conditional:

if have_system
  trace_events_subdirs += [
    ...
    'ui',
    ...
  ]
endif

which was added to avoid wasting time running tracetool on unused trace-events
files.  This causes a compilation failure; fix it by skipping module builds
entirely if (depending on the module directory) have_block or have_system
are false.

Reported-by: Michael Tokarev <[email protected]>
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit ef709860ea)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-10 20:50:38 +03:00
Shivaprasad G Bhat 4dc5df865c softfloat: Fix the incorrect computation in float32_exp2
The float32_exp2 function is computing wrong exponent of 2.

For example, with the following set of values {0.1, 2.0, 2.0, -1.0},
the expected output would be {1.071773, 4.000000, 4.000000, 0.500000}.
Instead, the function is computing {1.119102, 3.382044, 3.382044, -0.191022}

Looking at the code, the float32_exp2() attempts to do this

                  2     3     4     5           n
  x        x     x     x     x     x           x
 e  = 1 + --- + --- + --- + --- + --- + ... + --- + ...
           1!    2!    3!    4!    5!          n!

But because of the typo it ends up doing

  x        x     x     x     x     x           x
 e  = 1 + --- + --- + --- + --- + --- + ... + --- + ...
           1!    2!    3!    4!    5!          n!

This is because instead of the xnp which holds the numerator, parts_muladd
is using the xp which is just 'x'.  Commit '572c4d862ff2' refactored this
function, and mistakenly used xp instead of xnp.

Cc: [email protected]
Fixes: 572c4d862f "softfloat: Convert float32_exp2 to FloatParts"
Partially-Resolves: https://gitlab.com/qemu-project/qemu/-/issues/1623
Reported-By: Luca Barbato (https://gitlab.com/lu-zero)
Signed-off-by: Shivaprasad G Bhat <[email protected]>
Signed-off-by: Vaibhav Jain <[email protected]>
Message-Id: <168304110865.537992.13059030916325018670.stgit@localhost.localdomain>
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
(cherry picked from commit 1098cc3fcf)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-10 20:50:38 +03:00
Stefan Hajnoczi a458252c16 block/export: call blk_set_dev_ops(blk, NULL, NULL)
Most export types install BlockDeviceOps pointers. It is easy to forget
to remove them because that happens automatically via the "drive" qdev
property in hw/ but not block/export/.

Put blk_set_dev_ops(blk, NULL, NULL) calls in the core export.c code so
the export types don't need to remember.

This fixes the nbd and vhost-user-blk export types.

Fixes: fd6afc501a ("nbd/server: Use drained block ops to quiesce the server")
Fixes: ca858a5fe9 ("vhost-user-blk-server: notify client about disk resize")
Signed-off-by: Stefan Hajnoczi <[email protected]>
Reviewed-by: Eric Blake <[email protected]>
Message-Id: <[email protected]>
Signed-off-by: Eric Blake <[email protected]>
(cherry picked from commit de79b52604)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-10 20:50:38 +03:00
Peter Maydell f6227dd60d hw/net/allwinner-sun8i-emac: Correctly byteswap descriptor fields
In allwinner-sun8i-emac we just read directly from guest memory into
a host FrameDescriptor struct and back.  This only works on
little-endian hosts.  Reading and writing of descriptors is already
abstracted into functions; make those functions also handle the
byte-swapping so that TransferDescriptor structs as seen by the rest
of the code are always in host-order, and fix two places that were
doing ad-hoc descriptor reading without using the functions.

Cc: [email protected]
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Thomas Huth <[email protected]>
Reviewed-by: Alex Bennée <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Message-id: [email protected]
(cherry picked from commit a4ae17e5ec)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-10 20:50:38 +03:00
Peter Maydell 2daa9e4d7e hw/sd/allwinner-sdhost: Correctly byteswap descriptor fields
In allwinner_sdhost_process_desc() we just read directly from
guest memory into a host TransferDescriptor struct and back.
This only works on little-endian hosts. Abstract the reading
and writing of descriptors into functions that handle the
byte-swapping so that TransferDescriptor structs as seen by
the rest of the code are always in host-order.

This fixes a failure of one of the avocado tests on s390.

Cc: [email protected]
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Thomas Huth <[email protected]>
Reviewed-by: Alex Bennée <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Message-id: [email protected]
(cherry picked from commit 3e20d90824)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-10 20:50:38 +03:00
Peter Maydell 6944823a6f target/arm: Define and use new load_cpu_field_low32()
In several places in the 32-bit Arm translate.c, we try to use
load_cpu_field() to load from a CPUARMState field into a TCGv_i32
where the field is actually 64-bit. This works on little-endian
hosts, but gives the wrong half of the register on big-endian.

Add a new load_cpu_field_low32() which loads the low 32 bits
of a 64-bit field into a TCGv_i32. The new macro includes a
compile-time check against accidentally using it on a field
of the wrong size. Use it to fix the two places in the code
where we were using load_cpu_field() on a 64-bit field.

This fixes a bug where on big-endian hosts the guest would
crash after executing an ERET instruction, and a more corner
case one where some UNDEFs for attempted accesses to MSR
banked registers from Secure EL1 might go to the wrong EL.

Cc: [email protected]
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Message-id: [email protected]
(cherry picked from commit 7f3a3d3dc4)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-10 20:50:38 +03:00
Peter Maydell af08c70ef5 hw/intc/allwinner-a10-pic: Don't use set_bit()/clear_bit()
The Allwinner PIC model uses set_bit() and clear_bit() to update the
values in its irq_pending[] array when an interrupt arrives.  However
it is using these functions wrongly: they work on an array of type
'long', and it is passing an array of type 'uint32_t'.  Because the
code manually figures out the right array element, this works on
little-endian hosts and on 32-bit big-endian hosts, where bits 0..31
in a 'long' are in the same place as they are in a 'uint32_t'.
However it breaks on 64-bit big-endian hosts.

Remove the use of set_bit() and clear_bit() in favour of using
deposit32() on the array element.  This fixes a bug where on
big-endian 64-bit hosts the guest kernel would hang early on in
bootup.

Cc: [email protected]
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Thomas Huth <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Message-id: [email protected]
(cherry picked from commit 2c5fa0778c)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-10 20:50:38 +03:00
Peter Maydell 975f12aa52 hw/arm/raspi: Use arm_write_bootloader() to write boot code
When writing the secondary-CPU stub boot loader code to the guest,
use arm_write_bootloader() instead of directly calling
rom_add_blob_fixed().  This fixes a bug on big-endian hosts, because
arm_write_bootloader() will correctly byte-swap the host-byte-order
array values into the guest-byte-order to write into the guest
memory.

Cc: [email protected]
Signed-off-by: Peter Maydell <[email protected]>
Tested-by: Cédric Le Goater <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Message-id: [email protected]
(cherry picked from commit 0acbdb4c4a)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-10 20:50:38 +03:00
Cédric Le Goater 5477a21350 hw/arm/aspeed: Use arm_write_bootloader() to write the bootloader
When writing the secondary-CPU stub boot loader code to the guest,
use arm_write_bootloader() instead of directly calling
rom_add_blob_fixed().  This fixes a bug on big-endian hosts, because
arm_write_bootloader() will correctly byte-swap the host-byte-order
array values into the guest-byte-order to write into the guest
memory.

Cc: [email protected]
Signed-off-by: Cédric Le Goater <[email protected]>
Tested-by: Cédric Le Goater <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: Peter Maydell <[email protected]>
Message-id: [email protected]
[PMM: Moved the "make arm_write_bootloader() function public" part
 to its own patch; updated commit message to note that this fixes
 an actual bug; adjust to the API changes noted in previous commit]
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit 902bba549f)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-10 20:50:38 +03:00
Cédric Le Goater 168f193c5b hw/arm/boot: Make write_bootloader() public as arm_write_bootloader()
The arm boot.c code includes a utility function write_bootloader()
which assists in writing a boot-code fragment into guest memory,
including handling endianness and fixing it up with entry point
addresses and similar things.  This is useful not just for the boot.c
code but also in board model code, so rename it to
arm_write_bootloader() and make it globally visible.

Since we are making it public, make its API a little neater: move the
AddressSpace* argument to be next to the hwaddr argument, and allow
the fixupcontext array to be const, since we never modify it in this
function.

Cc: [email protected]
Signed-off-by: Cédric Le Goater <[email protected]>
Tested-by: Cédric Le Goater <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: Peter Maydell <[email protected]>
Message-id: [email protected]
[PMM: Split out from another patch by Cédric, added doc comment]
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit 0fe43f0abf)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-10 20:50:38 +03:00
Peter Maydell 61ef050639 hw/net/msf2-emac: Don't modify descriptor in-place in emac_store_desc()
The msf2-emac ethernet controller has functions emac_load_desc() and
emac_store_desc() which read and write the in-memory descriptor
blocks and handle conversion between guest and host endianness.

As currently written, emac_store_desc() does the endianness
conversion in-place; this means that it effectively consumes the
input EmacDesc struct, because on a big-endian host the fields will
be overwritten with the little-endian versions of their values.
Unfortunately, in all the callsites the code continues to access
fields in the EmacDesc struct after it has called emac_store_desc()
-- specifically, it looks at the d.next field.

The effect of this is that on a big-endian host networking doesn't
work because the address of the next descriptor is corrupted.

We could fix this by making the callsite avoid using the struct; but
it's more robust to have emac_store_desc() leave its input alone.

(emac_load_desc() also does an in-place conversion, but here this is
fine, because the function is supposed to be initializing the
struct.)

Cc: [email protected]
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Thomas Huth <[email protected]>
Message-id: [email protected]
(cherry picked from commit d565f58b38)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-10 20:50:38 +03:00
Akihiko Odaki f0c5a78029 target/arm: Initialize debug capabilities only once
kvm_arm_init_debug() used to be called several times on a SMP system as
kvm_arch_init_vcpu() calls it. Move the call to kvm_arch_init() to make
sure it will be called only once; otherwise it will overwrite pointers
to memory allocated with the previous call and leak it.

Fixes: e4482ab7e3 ("target-arm: kvm - add support for HW assisted debug")
Suggested-by: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: Akihiko Odaki <[email protected]>
Message-id: [email protected]
Reviewed-by: Peter Maydell <[email protected]>
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit ad5c6ddea3)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-10 20:50:38 +03:00
Peter Maydell 9448a0fa11 docs/about/deprecated.rst: Add "since 7.1" tag to dtb-kaslr-seed deprecation
In commit 5242876f37 we deprecated the dtb-kaslr-seed property of
the virt board, but forgot the "since n.n" tag in the documentation
of this in deprecated.rst.

This deprecation note first appeared in the 7.1 release, so
retrospectively add the correct "since 7.1" annotation to it.

Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Alex Bennée <[email protected]>
Message-id: [email protected]
(cherry picked from commit ac64ebbecf)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-10 20:50:38 +03:00
Alex Bennée 8c3cf36260 qemu-options: finesse the recommendations around -blockdev
We are a bit premature in recommending -blockdev/-device as the best
way to configure block devices. It seems there are times the more
human friendly -drive still makes sense especially when -snapshot is
involved.

Improve the language to hopefully make things clearer.

Suggested-by: Michael Tokarev <[email protected]>
Signed-off-by: Alex Bennée <[email protected]>
Reviewed-by: Thomas Huth <[email protected]>
Cc: Markus Armbruster <[email protected]>
Cc: Kevin Wolf <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit c1654c3e37)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-10 20:50:38 +03:00
Wang Liang f528cfc3fa block/monitor: Fix crash when executing HMP commit
hmp_commit() calls blk_is_available() from a non-coroutine context (and
in the main loop). blk_is_available() is a co_wrapper_mixed_bdrv_rdlock
function, and in the non-coroutine context it calls AIO_WAIT_WHILE(),
which crashes if the aio_context lock is not taken before.

Resolves: https://gitlab.com/qemu-project/qemu/-/issues/1615
Signed-off-by: Wang Liang <[email protected]>
Message-Id: <[email protected]>
Reviewed-by: Emanuele Giuseppe Esposito <[email protected]>
Reviewed-by: Kevin Wolf <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit 8c1e8fb2e7)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-10 20:50:38 +03:00
Igor Mammedov bb47b5bc2e acpi: pcihp: allow repeating hot-unplug requests
with Q35 using ACPI PCI hotplug by default, user's request to unplug
device is ignored when it's issued before guest OS has been booted.
And any additional attempt to request device hot-unplug afterwards
results in following error:

  "Device XYZ is already in the process of unplug"

arguably it can be considered as a regression introduced by [2],
before which it was possible to issue unplug request multiple
times.

Accept new uplug requests after timeout (1ms). This brings ACPI PCI
hotplug on par with native PCIe unplug behavior [1] and allows user
to repeat unplug requests at propper times.
Set expire timeout to arbitrary 1msec so user won't be able to
flood guest with SCI interrupts by calling device_del in tight loop.

PS:
ACPI spec doesn't mandate what OSPM can do with GPEx.status
bits set before it's booted => it's impl. depended.
Status bits may be retained (I tested with one Windows version)
or cleared (Linux since 2.6 kernel times) during guest's ACPI
subsystem initialization.
Clearing status bits (though not wrong per se) hides the unplug
event from guest, and it's upto user to repeat device_del later
when guest is able to handle unplug requests.

1) 18416c62e3 ("pcie: expire pending delete")
2)
Fixes: cce8944cc9 ("qdev-monitor: Forbid repeated device_del")
Signed-off-by: Igor Mammedov <[email protected]>
Acked-by: Gerd Hoffmann <[email protected]>
CC: [email protected]
CC: [email protected]
CC: [email protected]
CC: [email protected]
Message-Id: <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Reviewed-by: Ani Sinha <[email protected]>
(cherry picked from commit 0f689cf5ad)
Signed-off-by: Michael Tokarev <[email protected]>
2023-05-10 20:50:38 +03:00
osy 689c8fd77a Merge tag 'v8.0.0' into utm-edition
v8.0.0 release
2023-04-30 20:14:13 -07:00
Axel Heider 134a1a3320 hw/timer/imx_epit: fix limit check
Fix the limit check. If the limit is less than the compare value,
the timer can never reach this value, thus it will never fire.

Resolves: https://gitlab.com/qemu-project/qemu/-/issues/1491
Signed-off-by: Axel Heider <[email protected]>
Message-id: [email protected]
Reviewed-by: Peter Maydell <[email protected]>
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit 25d758175d)
Signed-off-by: Michael Tokarev <[email protected]>
2023-04-27 08:51:16 +03:00
Axel Heider ac7f07ebc8 hw/timer/imx_epit: don't shadow variable
Fix issue reported by Coverity.

Signed-off-by: Axel Heider <[email protected]>
Message-id: [email protected]
Reviewed-by: Peter Maydell <[email protected]>
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit 542fd43d79)
Signed-off-by: Michael Tokarev <[email protected]>
2023-04-27 08:51:16 +03:00
Yang Zhong 3ed99d232c target/i386: Change wrong XFRM value in SGX CPUID leaf
The previous patch wrongly replaced FEAT_XSAVE_XCR0_{LO|HI} with
FEAT_XSAVE_XSS_{LO|HI} in CPUID(EAX=12,ECX=1):{ECX,EDX}.  As a result,
SGX enclaves only supported SSE and x87 feature (xfrm=0x3).

Fixes: 301e90675c ("target/i386: Enable support for XSAVES based features")
Signed-off-by: Yang Zhong <[email protected]>
Reviewed-by: Yang Weijiang <[email protected]>
Reviewed-by: Kai Huang <[email protected]>
Message-Id: <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 72497cff89)
Signed-off-by: Michael Tokarev <[email protected]>
2023-04-27 08:51:16 +03:00
Paolo Bonzini 6f7b9f7b6f vnc: avoid underflow when accessing user-provided address
If hostlen is zero, there is a possibility that addrstr[hostlen - 1]
underflows and, if a closing bracked is there, hostlen - 2 is passed
to g_strndup() on the next line.  If websocket==false then
addrstr[0] would be a colon, but if websocket==true this could in
principle happen.

Fix it by checking hostlen.

Reported by Coverity.

Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 3f9c41c5df)
Signed-off-by: Michael Tokarev <[email protected]>
2023-04-26 18:17:51 +03:00
osy bd2fc471e7 Merge branch 'with_tcti_vectors' into utm-edition 2023-03-06 15:23:31 -08:00
Katherine Temkin 550af33ef5 meson tweaks for building with and _without_ JIT 2023-03-06 10:10:05 -08:00
osy 80c0e3099f vmnet: stop recieving events when VM is stopped
When the VM is stopped using the HMP command "stop", soon the handler will
stop reading from the vmnet interface. This causes a flood of
`VMNET_INTERFACE_PACKETS_AVAILABLE` events to arrive and puts the host CPU
at 100%. We fix this by removing the event handler from vmnet when the VM
is no longer in a running state and restore it when we return to a running
state.
2023-01-01 16:51:56 -08:00
osy c874e68e5a tcti: disable TARGET_TB_PCREL for TCTI
It is currently not supported.
2022-12-30 20:24:00 -08:00
osy 531da34587 hvf: support TSO mode (private feature)
Apple Silicon supports TSO mode which can be used for emulating strong
memory ordering in the guest. This feature requires the private entitlement
`com.apple.private.hypervisor` as well as a private function to modify
ACTLR_EL1 not exposed by the public Hypervisor framework.
2022-12-29 00:26:07 -08:00
osy 34b035535e spice-display: remove redundant glBindTexture 2022-12-24 17:08:52 -08:00
osy bb5c41eb13 spice-display: fix memory leak issues
1) Some of the error cases did not free GL memory.
2) Remove some unneeded logic and simplify the code.
3) Add a `eglMakeCurrent` to `spice_iosurface_destroy` to make sure we are
   freeing objects in the right context.
2022-12-20 15:56:07 -08:00
osy b3cf3579f5 Merge tag 'v7.2.0' into utm-edition
v7.2.0 release
2022-12-17 22:29:34 -08:00
osy 96e76ff0a1 Revert "egl-helpers: update EGL client version to 3.0"
This reverts commit f357b925b3.
2022-12-17 15:04:19 -08:00
osy 3ef0f0db05 Merge tag 'v7.1.0' into utm-edition
v7.1.0 release
2022-10-29 17:33:45 -07:00
osy f129a2b8db usbredir: avoid queuing hello packet on snapshot restore
When launching QEMU with "-loadvm", usbredir_create_parser() should avoid
setting up the hello packet (just as with "-incoming". On the latest version
of libusbredir, usbredirparser_unserialize() will return error if the parser
is not "pristine."
2022-08-08 16:13:20 -07:00
osy 6e9f737fcc vl: on -loadvm set run state to "restore-vm"
This allows us to differentiate between a fresh boot and a restore boot.
2022-08-08 16:11:21 -07:00
osy 51a16884c3 Revert "usbredir: avoid queuing hello packet on snapshot restore"
Run state is also in RUN_STATE_PRELAUNCH while "-S" is used.

This reverts commit 12d182898a.
2022-08-08 14:44:10 -07:00
osy 6626058f22 net/vmnet: use availability check at runtime
MAC_OS_X_VERSION_MIN_REQUIRED is set at compile time so this means that when
we target an older macOS version, it disables the newer features. With a
runtime check, we can selectively disable newer API features.
2022-05-17 19:48:48 -07:00
osy 0fbf694119 ui/cocoa: fix compile issues after merge 2022-05-11 16:34:54 -07:00
osy 12d182898a usbredir: avoid queuing hello packet on snapshot restore
When launching QEMU with "-loadvm", usbredir_create_parser() should avoid
setting up the hello packet (just as with "-incoming". On the latest version
of libusbredir, usbredirparser_unserialize() will return error if the parser
is not "pristine."
2022-05-06 21:09:31 -07:00
osy 25dfefc810 hw/arm/virt: revert old behaviour of highmem=off
On < macOS 12.4, a kernel panic is triggered for highmem=on and an error
is shown for highmem=off. We workaround this by inhibiting the error so
older versions of macOS can still use highmem=off.
2022-04-29 10:50:45 -07:00
osy 397bb125e1 Merge tag 'v7.0.0' into utm-edition
v7.0.0 release
2022-04-22 11:38:37 -07:00
osy 355b0824c6 Merge remote-tracking branch 'akihikodaki/macos' into utm-edition 2022-04-22 11:38:17 -07:00
Akihiko Odaki 84641e7ceb coreaudio: Initialize the buffer for device change
Signed-off-by: Akihiko Odaki <[email protected]>
2022-03-25 16:12:13 +09:00
Akihiko Odaki 1716a3f189 ui/cocoa: Use qemu_add_mouse_change_notifier
This eliminates the polling in cocoa_refresh and implements the
propagation of the mouse mode change from absolute to relative.

Signed-off-by: Akihiko Odaki <[email protected]>
2022-03-25 16:12:08 +09:00
Gustavo Noronha Silva aac64f9286 ui/cocoa: handle mouse grab properly on window being key changes
Being key is similar to being focused on other platforms. When the
window loses focus at the moment it will still keep the mouse grabbed
unless it is using an absolute pointing device like a USB tablet.

That may happen in several ways as Mac OS does not let Qemu handle some
of the events even when it has a grab. Command-Tab will switch applications
if full-grab is off, and even if it is on you can still switch away from
by using 3-finger gestures on the trackpad to change spaces or open
Mission Control, for instance.

That behaviour is not ideal, as even though Qemu still believes it is
getting all the events, Mac OS has effectively released the mouse.
And it is worse with full-grab turned on, as it will still capture
the key events, making you unable to use the keyboard on the Mac OS
environment.

This change makes Qemu properly release the grab when Mac OS effectively
does it. In addition, it properly automatically regrabs the mouse when
the window becomes key and is fullscreen. While it makes sense to wait
for a click on a non-fullscreen window, as the user may just be moving
the window around, for instance, when it's fullscreen there is no point.

Signed-off-by: Gustavo Noronha Silva <[email protected]>
2022-03-25 16:12:02 +09:00
Akihiko Odaki 85af432691 ui/cocoa: Divide ui/cocoa.m 2022-03-25 16:11:56 +09:00
Akihiko Odaki a0167d013f ui/cocoa: Isolate fragments with preprocessor 2022-03-25 16:11:48 +09:00
Akihiko Odaki 3acd8e70ba ui/cocoa: Define types early 2022-03-25 16:11:42 +09:00
Akihiko Odaki e0af80866a Use virgl_renderer_borrow_texture_for_scanout
Signed-off-by: Akihiko Odaki <[email protected]>
2022-03-25 16:11:35 +09:00
Akihiko Odaki b3ebe68e23 ui/cocoa: Update cursor
Signed-off-by: Akihiko Odaki <[email protected]>
2022-03-25 16:11:28 +09:00
Akihiko Odaki 9e45375602 ui/cocoa: Take refresh rate into account
Signed-off-by: Akihiko Odaki <[email protected]>
2022-03-25 16:11:22 +09:00
Akihiko Odaki bdf261c858 Support Virgil 3D renderer on macOS
Virgil 3D renderer will be available with ui/cocoa on macOS.

The OpenGL backend is NSOpenGLContext for core profile, and
EGL (in particular, ANGLE) for ES profile.

Signed-off-by: Akihiko Odaki <[email protected]>
2022-03-25 16:11:15 +09:00
Akihiko Odaki ad2fe378fe ui/cocoa: Do not scale UI without "Zoom To Fit"
Cocoa scales UI for high-resolution display like Retina, but we do not
need it since we now have our own "Zoom To Fit" work well also for
windows, and the guest is aware of the resolution thanks to UI
information. This change reverts the scaling.

Signed-off-by: Akihiko Odaki <[email protected]>
2022-03-25 16:11:10 +09:00
Akihiko Odaki 3f620296d8 ui/curses: Do not use console_select
ui/curses is the only user of console_select. Move the implementation
to ui/curses.

Signed-off-by: Akihiko Odaki <[email protected]>
2022-03-25 16:11:03 +09:00
Akihiko Odaki f2098f2c30 ui/cocoa: Do not use console_select
ui/cocoa needs to update the UI info when switching the console.
The behavior was implemented in cocoa_switch which was used to be called
by console_select. The function was however to switch the DisplaySurface
and overloaded. Have its own implementation of console_select and
update the UI info with it.

Signed-off-by: Akihiko Odaki <[email protected]>
2022-03-25 16:10:57 +09:00
Akihiko Odaki 7dfd20c7e8 ui/vnc: Do not use console_select
console_select is shared by other displays and switching in one of them
triggers switching also in ui/vnc, circumventing key state
reinitialization specific to ui/vnc. Use its internal state to track
the current active console instead.

Signed-off-by: Akihiko Odaki <[email protected]>
2022-03-25 16:10:48 +09:00
Akihiko Odaki 41eb76f5bf ui/vnc: Respect bound console
Signed-off-by: Akihiko Odaki <[email protected]>
2022-03-25 16:10:40 +09:00
Akihiko Odaki 99ac5e48e4 ui/console: Check console before emitting GL event
Signed-off-by: Akihiko Odaki <[email protected]>
2022-03-25 16:10:09 +09:00
Akihiko Odaki 67876f074e ui/cocoa: Respect left-command-key option
Signed-off-by: Akihiko Odaki <[email protected]>
2022-03-25 13:04:32 +09:00
Akihiko Odaki 781a23afc7 audio/mixeng: Do not declare unused variables
The unused variables when FLOAT_MIXENG is defined caused warnings on
Apple clang version 13.1.6 (clang-1316.0.21.2).

Signed-off-by: Akihiko Odaki <[email protected]>
2022-03-25 13:04:24 +09:00
Akihiko Odaki 1f24abea06 ui/cocoa: Use qemu_input_map_osx_to_qcode
ui/cocoa used to have a conversion table from macOS keycode to QKeyCode.
It is an unnecessary redundancy as ui/input-keymap.c already has such a
table. Worse, I added an incorrect mapping of kVK_JIS_Eisu and
kVK_JIS_Kana with commit 708b72557f.
According to the following documentations, the definitions in
ui/keycodemapdb/keymaps.csv, which ui/input-keymap.c uses, are correct:
https://developer.apple.com/documentation/uikit/uikeyboardhidusage/uikeyboardhidusagekeyboardlang1?language=objc
https://developer.apple.com/documentation/uikit/uikeyboardhidusage/uikeyboardhidusagekeyboardlang2?language=objc
https://docs.microsoft.com/en-us/windows-hardware/design/component-guidelines/keyboard-japan-ime

Use qemu_input_map_osx_to_qcode to eliminate the redundancy and
incorrect mappings.

Signed-off-by: Akihiko Odaki <[email protected]>
2022-03-25 13:04:17 +09:00
Akihiko Odaki de8f1b03d0 block/file-posix: Use O_RDWR for locking on macOS
qemu_lock_fd_test always returns 0 when fd is not open for writing and
exclusive is true on macOS 11.3.1.

Signed-off-by: Akihiko Odaki <[email protected]>
2022-03-25 13:04:11 +09:00
Akihiko Odaki 66553a8213 ui/cocoa: Use NSWindow's ability to resize
This change brings two new features:
- The window will be resizable if "Zoom To Fit" is eanbled
- The window can be made full screen by clicking full screen button
  provided by the platform. (The left-top green button.)

Signed-off-by: Akihiko Odaki <[email protected]>
2022-03-25 13:04:04 +09:00
Akihiko Odaki 4214699f96 coreaudio: Commit the result of init in the end
init_out_device may only commit some part of the result and leave the
state inconsistent when it encounters an error. Commit the result in
the end of the function so that it commits the result iif it sees no
error.

With this change, handle_voice_change can rely on core->outputDeviceID
to know whether the output device is initialized after calling
init_out_device.

Signed-off-by: Akihiko Odaki <[email protected]>
2022-03-25 13:03:58 +09:00
Akihiko Odaki 401a81844b ui/cocoa: Do not raise keys before QEMU resigns active
ui/cocoa used to raise all keys before it resigns active to prevent a
stuck key problem caused by key up events it does not see while it is
inactive. The problem is solved by checking -[NSEvent modifierFlags] in
commit 6d73bb643a, which is better
because it handles the case that key *down* events are missed while it
is inactive.

Signed-off-by: Akihiko Odaki <[email protected]>
2022-03-25 13:03:53 +09:00
Akihiko Odaki 129127242d virtio-gpu: Respect UI refresh rate for EDID
This change adds a new member, refresh_rate to QemuUIInfo in
include/ui/console.h. It represents the refresh rate of the
physical display backend, and it is more appropriate than
GUI update interval as the refresh rate which the emulated device
reports:
- sdl may set GUI update interval shorter than the refresh rate
  of the physical display to respond to user-generated events.
- sdl and vnc aggressively changes GUI update interval, but
  a guests is typically not designed to respond to frequent
  refresh rate changes, or frequent "display mode" changes in
  general. The frequency of refresh rate changes of the physical
  display backend matches better to the guest's expectation.

QemuUIInfo also has other members representing "display mode",
which makes it suitable for refresh rate representation. It has
a throttling of update notifications, and prevents frequent changes
of the display mode.

Signed-off-by: Akihiko Odaki <[email protected]>
2022-03-25 13:03:47 +09:00
Akihiko Odaki c146fe8095 ui/cocoa: Initialize before setting UID and GID
Signed-off-by: Akihiko Odaki <[email protected]>
2022-03-25 13:02:50 +09:00
Akihiko Odaki e6441f8683 Merge tag 'patchew/[email protected]' 2022-03-18 18:20:45 +09:00
Vladislav Yaroshchuk 7135bae71b net/vmnet: update hmp-commands.hx
Signed-off-by: Vladislav Yaroshchuk <[email protected]>
Message-Id: <[email protected]>
2022-03-17 17:36:38 +00:00
Vladislav Yaroshchuk c9eb230657 net/vmnet: update qemu-options.hx
Signed-off-by: Vladislav Yaroshchuk <[email protected]>
Message-Id: <[email protected]>
2022-03-17 17:36:38 +00:00
Vladislav Yaroshchuk ee9a9b425f net/vmnet: implement bridged mode (vmnet-bridged)
Signed-off-by: Vladislav Yaroshchuk <[email protected]>
Message-Id: <[email protected]>
2022-03-17 17:36:38 +00:00
Vladislav Yaroshchuk 5286a192c8 net/vmnet: implement host mode (vmnet-host)
Signed-off-by: Vladislav Yaroshchuk <[email protected]>
Message-Id: <[email protected]>
2022-03-17 17:36:38 +00:00
Vladislav Yaroshchuk f854a87eeb net/vmnet: implement shared mode (vmnet-shared)
Interaction with vmnet.framework in different modes
differs only on configuration stage, so we can create
common `send`, `receive`, etc. procedures and reuse them.

Signed-off-by: Phillip Tennen <[email protected]>
Signed-off-by: Vladislav Yaroshchuk <[email protected]>
Message-Id: <[email protected]>
2022-03-17 17:36:38 +00:00
Vladislav Yaroshchuk 1699eb16a7 net/vmnet: add vmnet backends to qapi/net
Create separate netdevs for each vmnet operating mode:
- vmnet-host
- vmnet-shared
- vmnet-bridged

Acked-by: Markus Armbruster <[email protected]>
Signed-off-by: Vladislav Yaroshchuk <[email protected]>
Message-Id: <[email protected]>
2022-03-17 17:36:38 +00:00
Vladislav Yaroshchuk d1792ff228 net/vmnet: add vmnet dependency and customizable option
vmnet.framework dependency is added with 'vmnet' option
to enable or disable it. Default value is 'auto'.

used vmnet features are available since macOS 11.0,
but new backend can be built and work properly with
subset of them on 10.15 too.

Signed-off-by: Vladislav Yaroshchuk <[email protected]>
Message-Id: <[email protected]>
2022-03-17 17:36:38 +00:00
Paolo Bonzini cd85cb5abe ui/cocoa: run qemu_init in the main thread
Simplify the initialization dance by running qemu_init() in the main
thread before the Cocoa event loop starts.  The cocoa_display_init()
code that is post-applicationDidFinishLaunching: moves to the
application delegate itself, and the secondary thread only runs
the rest of qemu_main(), namely qemu_main_loop() and qemu_cleanup().

This fixes a case where addRemovableDevicesMenuItems() calls
qmp_query_block() while expecting the main thread to still hold
the BQL.  The newly-introduced assertions in the block layer
complain about this.

Signed-off-by: Paolo Bonzini <[email protected]>
Message-Id: <[email protected]>
[PMD: Fixed trivial build failures & rebased]
Reviewed-by: Peter Maydell <[email protected]>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
Message-Id: <[email protected]>
2022-03-17 13:01:51 +00:00
Philippe Mathieu-Daudé c94e174af8 ui/cocoa: Code movement
Pure code movement in preparation for the next commit.

Reviewed-by: Peter Maydell <[email protected]>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
Message-Id: <[email protected]>
2022-03-17 13:01:51 +00:00
osy 8f1617b581 pc: add option to disable PS/2 mouse/keyboard
On some older software like Windows 7 installer, having both a PS/2
mouse and USB mouse results in only one device working property (which
might be a different device each boot). While the workaround to not use
a USB mouse with such software is valid, it creates an inconsistent
experience if the user wishes to always use a USB mouse.

This introduces a new machine property to inhibit the creation of the
i8042 PS/2 controller.
2022-02-27 12:48:07 -08:00
osy fc43b65e06 rcu: do not register constructor thread if shared library
On iOS 15, the constructor can run on a new thread that is destroyed
after construction is finished in dyld. When this happens the TLS gets
freed and causes use-after-free when QEMU is built in shared library
mode. This moves the rcu_register_thread() call to qemu_init()
2022-02-25 23:57:19 -08:00
osy 6409730ff9 spice-display: reduce race in sending IOSurface
There is a kernel bug detailed in
https://github.com/utmapp/UTM/issues/2743#issuecomment-1047175257
which results in a race whenever IOSurfaceGetID/IOSurfaceLookup is used.
As a result, we need a way to "indicate" to the receiver that the
surface id in the pipe is now stale and should not be used. To do this
we send POLLHUP to poll() by closing the write FD when the surface is
about to be deallocated.

Note this does not fix the race completely as there is still a small
chance that the race happens between the close() and the CFRelease() but
the chance of that is small and the whole FD passing surface ID system
is a hack anyways that should be replaced with a proper set of SPICE
APIs one day...
2022-02-21 18:04:32 -08:00
osy cc24c9b7cb meson: build qemu-img as shared library 2022-01-10 15:35:44 -08:00
Alexander Graf 0d24c5332f HACK: hvf: arm: Always treat SMC as enabled conduit
The Windows 10 and 11 for ARM boot code implicitly assumes that SMC is a valid
SMCCC conduit to call for an OEM SMCCC call.

This patch forces HVF to treat SMC as an always active conduit, even when the
user has configured HVC. That way, the OEM SMCCC call gets handled as an
unimplemented SMCCC function (return -1) rather than an invalid conduit (inject
undefined instruction exception) which crashes Windows.

With this patch applied, I can successfully boot Windows for ARM Insider
Previews.

Signed-off-by: Alexander Graf <[email protected]>
2021-12-30 08:33:01 -08:00
osy 44cfb32e24 Merge tag 'v6.2.0' into utm-edition
v6.2.0 release
2021-12-29 11:44:40 -08:00
osy e73864e11d shaders: support byte swapping of pixels
Some EGL implementations do not support GL_BGRA_EXT so we always use
a surface format of GL_RGBA and then swap the bytes with a fragment
shader.
2021-09-08 20:03:21 -07:00
osy 2b73a7937d virtio-ramfb: break out GL supported device
This follows the same convention as other devices.
2021-09-07 01:36:59 -07:00
osy 753fffe1ea spice-display: support GL_TEXTURE_RECTANGLE_ANGLE
On macOS with CGL rendering backend, IOSurface only supports rectangle
texture targets. On iOS, EAGL, and Metal rendering backends IOSurface
only supports 2D texture targets.
2021-08-25 15:46:30 -07:00
osy e19e3cb9b5 Merge tag 'v6.1.0' into utm-edition
v6.1.0 release
2021-08-25 14:23:36 -07:00
osy 26324b7d94 Merge tag 'v6.1.0-rc4' into utm-edition
v6.1.0-rc4 release
2021-08-23 20:01:14 -07:00
osy 929b3859bd spice-display: send IOSurfaceID through pipe
This is still a hacky workaround to using mach ports but should support
different processes on macOS.
2021-08-08 12:18:33 -07:00
osy fdd3d1d3a0 virtio-ramfb: enable GL if supported 2021-08-08 12:18:33 -07:00
osy 345ec3279b tcti: fix build after latest TCG changes 2021-08-08 12:18:33 -07:00
osy e8f8220618 spice-display: fix crash in destroy texture with IOSurface 2021-08-02 11:27:44 -07:00
osy f275f433af Merge tag 'v6.1.0-rc1' into utm-edition
v6.1.0-rc1 release
2021-08-02 11:26:27 -07:00
osy f384e2c7eb spice-display: initial support for IOSurface rendering
In both surface and scanout mode, we blit the texture to a ANGLE texture
backed pbuffer using IOSurface. This IOSurface can be shared with a
separate process.

What needs to be done:
1) Handing of IOSurfaceRef through mach ports (Unix sockets are not
   supported. This implementation hacks in by passing the pointer through
   a file descriptor but this will fail if client is running in a separate
   process).
2) Cursor handling through QEMU (currently, the SPICE client will handle
   it).
2021-08-01 22:24:02 -07:00
osy dc386f9eb0 spice-display: support ANGLE backend
Add support for creating a pbuffer surface and setup from SPICE.
2021-08-01 22:22:14 -07:00
osy 1adb9ff17d spice-display: make GBM conditional 2021-08-01 22:17:23 -07:00
osy ce01739e6d egl-headless: fix compile without GBM 2021-08-01 22:13:51 -07:00
osy f357b925b3 egl-helpers: update EGL client version to 3.0
Required for Metal ANGLE to work on iOS
2021-08-01 22:13:11 -07:00
Akihiko Odaki edba23a4d4 egl-headless: Allow to test with Mesa on macOS
Signed-off-by: Akihiko Odaki <[email protected]>
2021-07-26 14:38:10 -07:00
osy 3428101c02 configure: disable plugins for shared_lib builds 2021-07-26 14:32:44 -07:00
osy 1e8db1949d file-posix: fix holepunch build on iOS 2021-07-26 14:32:28 -07:00
osy e91d59cbea Merge branch 'utm-edition-v6.0.0' into utm-edition-v6.1.0-rc0 2021-07-26 14:30:35 -07:00
osy eace1c8c9f Merge branch 'virgl-support' into utm-edition-v6.1.0-rc0 2021-07-25 19:11:11 -07:00
Akihiko Odaki c800dbb61e block/file-posix: Use O_RDWR for locking on macOS
qemu_lock_fd_test always returns 0 when fd is not open for writing and
exclusive is true on macOS 11.3.1.

Signed-off-by: Akihiko Odaki <[email protected]>
2021-07-14 14:55:03 +09:00
Akihiko Odaki b3a305701e ui: update keycodemapdb submodule commit
The change of ui/keycodemapdb effective on QEMU is only commit
d21009b1c9f94b740ea66be8e48a1d8ad8124023, which adds mappings for key
codes added in commit d7696ff884.

d21009b1c9f94b740ea66be8e48a1d8ad8124023 Add QEMU QKeyCode "lang1" and "lang2"
320f92c36a80bfafc5d57834592a7be5fd79f104 rust: fix cargo clippy
e62d42f0fd76f7bb8bf78385a83c060e66ff52b0 tests: add rust test
3e25e1ca1772fc3f2039f739f8f920450dc68e50 gen: add --lang rust
9133a0b8022d1fb063a81cc2ba3b627c14ccdfd1 tests: fix argument order

Signed-off-by: Akihiko Odaki <[email protected]>
2021-07-14 14:54:59 +09:00
Akihiko Odaki 21954ae12a coreaudio: Commit the result of init in the end
init_out_device may only commit some part of the result and leave the
state inconsistent when it encounters an error. Commit the result in
the end of the function so that it commits the result iif it sees no
error.

With this change, handle_voice_change can rely on core->outputDeviceID
to know whether the output device is initialized after calling
init_out_device.

Signed-off-by: Akihiko Odaki <[email protected]>
2021-07-14 14:54:51 +09:00
Akihiko Odaki 61f5befa07 virtio-gpu: Call Virgl only in the main thread
Virgl relies on callbacks provided by the OpenGL display, and such a
display may rely on eglMakeCurrent. eglMakeCurrent will fail if the
given context is current to some other thread. The easiest way to avoid
such a failure is to call the OpenGL display in a single thread. As all
operations except virtio_gpu_virgl_reset happens in the main thread,
this change makes virtio_gpu_virgl_reset happen only in the main thread.

Signed-off-by: Akihiko Odaki <[email protected]>
2021-07-14 14:54:45 +09:00
Gustavo Noronha Silva 45c171c238 ui/cocoa: handle mouse grab properly on window being key changes
Being key is similar to being focused on other platforms. When the
window loses focus at the moment it will still keep the mouse grabbed
unless it is using an absolute pointing device like a USB tablet.

That may happen in several ways as Mac OS does not let Qemu handle some
of the events even when it has a grab. Command-Tab will switch applications
if full-grab is off, and even if it is on you can still switch away from
by using 3-finger gestures on the trackpad to change spaces or open
Mission Control, for instance.

That behaviour is not ideal, as even though Qemu still believes it is
getting all the events, Mac OS has effectively released the mouse.
And it is worse with full-grab turned on, as it will still capture
the key events, making you unable to use the keyboard on the Mac OS
environment.

This change makes Qemu properly release the grab when Mac OS effectively
does it. In addition, it properly automatically regrabs the mouse when
the window becomes key and is fullscreen. While it makes sense to wait
for a click on a non-fullscreen window, as the user may just be moving
the window around, for instance, when it's fullscreen there is no point.

Signed-off-by: Gustavo Noronha Silva <[email protected]>
2021-07-14 14:54:37 +09:00
Phillip Tennen 1b10cab21a net/macos: implement vmnet-based netdev
This patch implements a new netdev device, reachable via -netdev
vmnet-macos, that’s backed by macOS’s vmnet framework.

The vmnet framework provides native bridging support, and its usage in
this patch is intended as a replacement for attempts to use a tap device
via the tuntaposx kernel extension. Notably, the tap/tuntaposx approach
never would have worked in the first place, as QEMU interacts with the
tap device via poll(), and macOS does not support polling device files.

vmnet requires either a special entitlement, granted via a provisioning
profile, or root access. Otherwise attempts to create the virtual
interface will fail with a “generic error” status code. QEMU may not
currently be signed with an entitlement granted in a provisioning
profile, as this would necessitate pre-signed binary build distribution,
rather than source-code distribution. As such, using this netdev
currently requires that qemu be run with root access. I’ve opened a
feedback report with Apple to allow the use of the relevant entitlement
with this use case:
https://openradar.appspot.com/radar?id=5007417364447232

vmnet offers three operating modes, all of which are supported by this
patch via the “mode=host|shared|bridge” option:

* "Host" mode: Allows the vmnet interface to communicate with other
* vmnet
interfaces that are in host mode and also with the native host.
* "Shared" mode: Allows traffic originating from the vmnet interface to
reach the Internet through a NAT. The vmnet interface can also
communicate with the native host.
* "Bridged" mode: Bridges the vmnet interface with a physical network
interface.

Each of these modes also provide some extra configuration that’s
supported by this patch:

* "Bridged" mode: The user may specify the physical interface to bridge
with. Defaults to en0.
* "Host" mode / "Shared" mode: The user may specify the DHCP range and
subnet. Allocated by vmnet if not provided.

vmnet also offers some extra configuration options that are not
supported by this patch:

* Enable isolation from other VMs using vmnet
* Port forwarding rules
* Enabling TCP segmentation offload
* Only applicable in "shared" mode: specifying the NAT IPv6 prefix
* Only available in "host" mode: specifying the IP address for the VM
within an isolated network

Note that this patch requires macOS 10.15 as a minimum, as this is when
bridging support was implemented in vmnet.framework.

Rebased to commit 9aef095419 by Akihiko
Odaki.

Signed-off-by: Phillip Tennen <[email protected]>
Signed-off-by: Akihiko Odaki <[email protected]>
Message-Id: <[email protected]>
2021-07-14 14:54:30 +09:00
Akihiko Odaki c61c853e1f ui/cocoa: Divide ui/cocoa.m 2021-07-14 14:54:25 +09:00
Akihiko Odaki 8681835e66 ui/cocoa: Isolate fragments with preprocessor 2021-07-14 14:54:19 +09:00
Akihiko Odaki adaef950b5 ui/cocoa: Define types early 2021-07-14 14:54:14 +09:00
Akihiko Odaki a1cbf10708 ui/cocoa: Use qemu_input_map_osx_to_qcode
ui/cocoa used to have a conversion table from macOS keycode to QKeyCode.
It is an unnecessary redundancy as ui/input-keymap.c already has such a
table. Worse, I added an incorrect mapping of kVK_JIS_Eisu and
kVK_JIS_Kana with commit 708b72557f.
According to the following documentations, the definitions in
ui/keycodemapdb/keymaps.csv, which ui/input-keymap.c uses, are correct:
https://developer.apple.com/documentation/uikit/uikeyboardhidusage/uikeyboardhidusagekeyboardlang1?language=objc
https://developer.apple.com/documentation/uikit/uikeyboardhidusage/uikeyboardhidusagekeyboardlang2?language=objc
https://docs.microsoft.com/en-us/windows-hardware/design/component-guidelines/keyboard-japan-ime

Use qemu_input_map_osx_to_qcode to eliminate the redundancy and
incorrect mappings.

Signed-off-by: Akihiko Odaki <[email protected]>
2021-07-14 14:54:08 +09:00
Akihiko Odaki d0c0d66796 ui/cocoa: Do not raise keys before QEMU resigns active
ui/cocoa used to raise all keys before it resigns active to prevent a
stuck key problem caused by key up events it does not see while it is
inactive. The problem is solved by checking -[NSEvent modifierFlags] in
commit 6d73bb643a, which is better
because it handles the case that key *down* events are missed while it
is inactive.

Signed-off-by: Akihiko Odaki <[email protected]>
2021-07-14 14:54:04 +09:00
Akihiko Odaki 920d2875a0 Use virgl_renderer_borrow_texture_for_scanout
virgl_renderer_borrow_texture_for_scanout is a replacement of
virgl_renderer_resource_get_info and performs configurations such as
swizzle and sRGB decode.

Signed-off-by: Akihiko Odaki <[email protected]>
2021-07-14 14:53:59 +09:00
Akihiko Odaki 5ba17fba6e ui/cocoa: Update cursor
Signed-off-by: Akihiko Odaki <[email protected]>
2021-07-14 14:53:53 +09:00
Akihiko Odaki 51f8c2e5b8 ui/cocoa: Take refresh rate into account
Signed-off-by: Akihiko Odaki <[email protected]>
2021-07-14 14:53:48 +09:00
Akihiko Odaki 3184f37bbe Support Virgil 3D renderer on macOS
Virgil 3D renderer will be available with ui/cocoa on macOS.

The OpenGL backend is NSOpenGLContext for core profile, and
EGL (in particular, ANGLE) for ES profile.

As a notable change, CONFIG_OPENGL_DMABUF is replaced with the
combination of CONFIG_EGL and CONFIG_GBM. In fact, the old
detection of DMA-BUF in configure script was not working
because EGL_MESA_image_dma_buf_export is always defined in
<epoxy/egl.h>. Therefore, the new combination should
behave in the same way.

Signed-off-by: Akihiko Odaki <[email protected]>
2021-07-14 14:53:43 +09:00
Akihiko Odaki 110dbe7e89 ui/spice: Use HAVE_SPICE_GL for OpenGL checks
Some code in ui/spice used CONFIG_OPENGL for OpenGL conditionals, but
SPICE also depends on CONFIG_GBM and SPICE server whose version is
0.13.1 or later for OpenGL. Always use HAVE_SPICE_GL, which defines the
precise condition.

Signed-off-by: Akihiko Odaki <[email protected]>
2021-07-14 14:53:29 +09:00
Akihiko Odaki 2565eea22b ui/egl-headless: Remove a check for CONFIG_OPENGL
ui/egl-headless is only built when CONFIG_OPENGL is defined because it
depends on CONFIG_OPENGL without condition. Remove a redundant
conditonal in ui/egl-headless.c

Signed-off-by: Akihiko Odaki <[email protected]>
2021-07-14 14:53:17 +09:00
Akihiko Odaki 8c2f5eff66 virtio-gpu: Respect UI refresh rate for EDID
This change adds a new member, refresh_rate to QemuUIInfo in
include/ui/console.h. It represents the refresh rate of the
physical display backend, and it is more appropriate than
GUI update interval as the refresh rate which the emulated device
reports:
- sdl may set GUI update interval shorter than the refresh rate
  of the physical display to respond to user-generated events.
- sdl and vnc aggressively changes GUI update interval, but
  a guests is typically not designed to respond to frequent
  refresh rate changes, or frequent "display mode" changes in
  general. The frequency of refresh rate changes of the physical
  display backend matches better to the guest's expectation.

QemuUIInfo also has other members representing "display mode",
which makes it suitable for refresh rate representation. It has
a throttling of update notifications, and prevents frequent changes
of the display mode.

Signed-off-by: Akihiko Odaki <[email protected]>
2021-07-14 12:15:46 +09:00
Akihiko Odaki db430377c0 ui/cocoa: Do not scale UI without "Zoom To Fit"
Cocoa scales UI for high-resolution display like Retina, but we do not
need it since we now have our own "Zoom To Fit" work well also for
windows, and the guest is aware of the resolution thanks to UI
information. This change reverts the scaling.

Signed-off-by: Akihiko Odaki <[email protected]>
2021-07-14 12:15:30 +09:00
Akihiko Odaki b2708c4684 ui/cocoa: Use the standard about panel
This provides standard look and feel for the about panel and reduces
code.

Signed-off-by: Akihiko Odaki <[email protected]>
2021-07-14 12:15:23 +09:00
Akihiko Odaki 9ea8f7a804 ui/cocoa: Do not perform unsafe cast of argv
Signed-off-by: Akihiko Odaki <[email protected]>
2021-07-14 12:15:10 +09:00
Akihiko Odaki 6a1e678f5b ui/cocoa: Use NSWindow's ability to resize
This change brings two new features:
- The window will be resizable if "Zoom To Fit" is eanbled
- The window can be made full screen by clicking full screen button
  provided by the platform. (The left-top green button.)

Signed-off-by: Akihiko Odaki <[email protected]>
2021-07-14 12:14:21 +09:00
Akihiko Odaki 902616b2f0 Merge tag 'patchew/[email protected]' 2021-07-14 12:02:33 +09:00
Gustavo Noronha Silva bc73e87997 ui/cocoa: add option to swap Option and Command
On Mac OS X the Option key maps to Alt and Command to Super/Meta. This change
swaps them around so that Alt is the key closer to the space bar and Meta/Super
is between Control and Alt, like on non-Mac keyboards.

It is a cocoa display option, disabled by default.

Acked-by: Markus Armbruster <[email protected]>
Reviewed-by: Akihiko Odaki <[email protected]>
Signed-off-by: Gustavo Noronha Silva <[email protected]>
Message-Id: <[email protected]>
2021-07-13 23:00:52 +00:00
Gustavo Noronha Silva 7292f1fc18 ui/cocoa: capture all keys and combos when mouse is grabbed
Applications such as Gnome may use Alt-Tab and Super-Tab for different
purposes, some use Ctrl-arrows so we want to allow qemu to handle
everything when it captures the mouse/keyboard.

However, Mac OS handles some combos like Command-Tab and Ctrl-arrows
at an earlier part of the event handling chain, not letting qemu see it.

We add a global Event Tap that allows qemu to see all events when the
mouse is grabbed. Note that this requires additional permissions.

See:

https://developer.apple.com/documentation/coregraphics/1454426-cgeventtapcreate?language=objc#discussion
https://support.apple.com/en-in/guide/mac-help/mh32356/mac

Acked-by: Markus Armbruster <[email protected]>
Reviewed-by: Akihiko Odaki <[email protected]>
Signed-off-by: Gustavo Noronha Silva <[email protected]>
Message-Id: <[email protected]>
2021-07-13 23:00:52 +00:00
Yasuo Kuwahara 2ee6330b9e tcg/aarch64: Fix tcg_out_rotl
The last argument of tcg_out_extr() must be in the range 0-31 if ext==0.
Before the fix, when m==0 it becomes 32 and it crashes with an Illegal
instruction on Apple Silicon.  After the fix, it will be 0.  If m is in
the range 1-31, it is the same as before.

Signed-off-by: Yasuo Kuwahara <[email protected]>
Message-Id: <CAHfJ0vSXnmnTLmT0kR=a8ACRdw_UsLYOhStzUzgVEHoH8U-7sA@mail.gmail.com>
Signed-off-by: Richard Henderson <[email protected]>
2021-07-09 13:36:27 -07:00
Alexander Graf a0db5bfa90 hvf: arm: Handle Windows 10 SMC call
Windows 10 calls an SMCCC call via SMC unconditionally on boot. It lives
in the trusted application call number space, but its purpose is unknown.

In our current SMC implementation, we inject a UDEF for unknown SMC calls,
including this one. However, Windows breaks on boot when we do this. Instead,
let's return an error code.

With this patch applied I can successfully boot the current Windows 10
Insider Preview in HVF.

Signed-off-by: Alexander Graf <[email protected]>

Message-Id: <[email protected]>
2021-05-27 12:30:14 +00:00
Alexander Graf 998320a3da arm: Enable Windows 10 trusted SMCCC boot call
Windows 10 calls an SMCCC call via SMC unconditionally on boot. It lives
in the trusted application call number space, but its purpose is unknown.

In our current SMC implementation, we inject a UDEF for unknown SMC calls,
including this one. However, Windows breaks on boot when we do this. Instead,
let's return an error code.

With this and -M virt,virtualization=on I can successfully boot the current
Windows 10 Insider Preview in TCG.

Signed-off-by: Alexander Graf <[email protected]>
Message-Id: <[email protected]>
2021-05-27 12:30:13 +00:00
Alexander Graf 8137225fde arm: Add Hypervisor.framework build target
Now that we have all logic in place that we need to handle Hypervisor.framework
on Apple Silicon systems, let's add CONFIG_HVF for aarch64 as well so that we
can build it.

Signed-off-by: Alexander Graf <[email protected]>
Reviewed-by: Roman Bolshakov <[email protected]>
Tested-by: Roman Bolshakov <[email protected]> (x86 only)

Message-Id: <[email protected]>
2021-05-27 12:30:13 +00:00
Alexander Graf 3f09807e7f hvf: arm: Implement PSCI handling
We need to handle PSCI calls. Most of the TCG code works for us,
but we can simplify it to only handle aa64 mode and we need to
handle SUSPEND differently.

This patch takes the TCG code as template and duplicates it in HVF.

To tell the guest that we support PSCI 0.2 now, update the check in
arm_cpu_initfn() as well.

Signed-off-by: Alexander Graf <[email protected]>

Message-Id: <[email protected]>
2021-05-27 12:30:13 +00:00
Alexander Graf 17d38dc6d9 hvf: arm: Implement -cpu host
Now that we have working system register sync, we push more target CPU
properties into the virtual machine. That might be useful in some
situations, but is not the typical case that users want.

So let's add a -cpu host option that allows them to explicitly pass all
CPU capabilities of their host CPU into the guest.

Signed-off-by: Alexander Graf <[email protected]>
Acked-by: Roman Bolshakov <[email protected]>

Message-Id: <[email protected]>
2021-05-27 12:30:13 +00:00
Peter Collingbourne 66c71d88ed arm/hvf: Add a WFI handler
Sleep on WFI until the VTIMER is due but allow ourselves to be woken
up on IPI.

In this implementation IPI is blocked on the CPU thread at startup and
pselect() is used to atomically unblock the signal and begin sleeping.
The signal is sent unconditionally so there's no need to worry about
races between actually sleeping and the "we think we're sleeping"
state. It may lead to an extra wakeup but that's better than missing
it entirely.

Signed-off-by: Peter Collingbourne <[email protected]>
[agraf: Remove unused 'set' variable, always advance PC on WFX trap]
Signed-off-by: Alexander Graf <[email protected]>
Acked-by: Roman Bolshakov <[email protected]>

Message-Id: <[email protected]>
2021-05-27 12:30:12 +00:00
Alexander Graf 30adfa9b1d hvf: Add Apple Silicon support
With Apple Silicon available to the masses, it's a good time to add support
for driving its virtualization extensions from QEMU.

This patch adds all necessary architecture specific code to get basic VMs
working. It's still pretty raw, but definitely functional.

Known limitations:

  - Vtimer acknowledgement is hacky
  - Should implement more sysregs and fault on invalid ones then
  - WFI handling is missing, need to marry it with vtimer

Signed-off-by: Alexander Graf <[email protected]>
Reviewed-by: Roman Bolshakov <[email protected]>

Message-Id: <[email protected]>
2021-05-27 12:30:12 +00:00
Alexander Graf 3bf12f1f40 hvf: Simplify post reset/init/loadvm hooks
The hooks we have that call us after reset, init and loadvm really all
just want to say "The reference of all register state is in the QEMU
vcpu struct, please push it".

We already have a working pushing mechanism though called cpu->vcpu_dirty,
so we can just reuse that for all of the above, syncing state properly the
next time we actually execute a vCPU.

This fixes PSCI resets on ARM, as they modify CPU state even after the
post init call has completed, but before we execute the vCPU again.

To also make the scheme work for x86, we have to make sure we don't
move stale eflags into our env when the vcpu state is dirty.

Signed-off-by: Alexander Graf <[email protected]>
Reviewed-by: Roman Bolshakov <[email protected]>
Tested-by: Roman Bolshakov <[email protected]>
Message-Id: <[email protected]>
2021-05-27 12:30:12 +00:00
Alexander Graf 4c82b50085 hvf: Introduce hvf vcpu struct
We will need more than a single field for hvf going forward. To keep
the global vcpu struct uncluttered, let's allocate a special hvf vcpu
struct, similar to how hax does it.

Signed-off-by: Alexander Graf <[email protected]>
Reviewed-by: Roman Bolshakov <[email protected]>
Tested-by: Roman Bolshakov <[email protected]>
Reviewed-by: Alex Bennée <[email protected]>

Message-Id: <[email protected]>
2021-05-27 12:30:12 +00:00
Alexander Graf f3b4506f14 hvf: Remove hvf-accel-ops.h
We can move the definition of hvf_vcpu_exec() into our internal
hvf header, obsoleting the need for hvf-accel-ops.h.

Signed-off-by: Alexander Graf <[email protected]>
Message-Id: <[email protected]>
2021-05-27 12:30:12 +00:00
Alexander Graf 056bdd9a51 hvf: Make synchronize functions static
The hvf accel synchronize functions are only used as input for local
callback functions, so we can make them static.

Signed-off-by: Alexander Graf <[email protected]>
Message-Id: <[email protected]>
2021-05-27 12:30:11 +00:00
Alexander Graf 0bc7389a8e hvf: Use cpu_synchronize_state()
There is no reason to call the hvf specific hvf_cpu_synchronize_state()
when we can just use the generic cpu_synchronize_state() instead. This
allows us to have less dependency on internal function definitions and
allows us to make hvf_cpu_synchronize_state() static.

Signed-off-by: Alexander Graf <[email protected]>
Message-Id: <[email protected]>
2021-05-27 12:30:11 +00:00
Alexander Graf 9517f7e873 hvf: Split out common code on vcpu init and destroy
Until now, Hypervisor.framework has only been available on x86_64 systems.
With Apple Silicon shipping now, it extends its reach to aarch64. To
prepare for support for multiple architectures, let's start moving common
code out into its own accel directory.

This patch splits the vcpu init and destroy functions into a generic and
an architecture specific portion. This also allows us to move the generic
functions into the generic hvf code, removing exported functions.

Signed-off-by: Alexander Graf <[email protected]>
Message-Id: <[email protected]>
2021-05-27 12:30:11 +00:00
Alexander Graf 30c2f78449 hvf: Remove use of hv_uvaddr_t and hv_gpaddr_t
The ARM version of Hypervisor.framework no longer defines these two
types, so let's just revert to standard ones.

Signed-off-by: Alexander Graf <[email protected]>
Message-Id: <[email protected]>
2021-05-27 12:30:11 +00:00
Alexander Graf ea9f45cec5 hvf: Make hvf_set_phys_mem() static
The hvf_set_phys_mem() function is only called within the same file.
Make it static.

Signed-off-by: Alexander Graf <[email protected]>
Message-Id: <[email protected]>
2021-05-27 12:30:10 +00:00
Alexander Graf 82e6e2bdff hvf: Move hvf internal definitions into common header
Until now, Hypervisor.framework has only been available on x86_64 systems.
With Apple Silicon shipping now, it extends its reach to aarch64. To
prepare for support for multiple architectures, let's start moving common
code out into its own accel directory.

This patch moves a few internal struct and constant defines over.

Signed-off-by: Alexander Graf <[email protected]>
Message-Id: <[email protected]>
2021-05-27 12:30:10 +00:00
Alexander Graf ffb51175ba hvf: Move cpu functions into common directory
Until now, Hypervisor.framework has only been available on x86_64 systems.
With Apple Silicon shipping now, it extends its reach to aarch64. To
prepare for support for multiple architectures, let's start moving common
code out into its own accel directory.

This patch moves CPU and memory operations over. While at it, make sure
the code is consumable on non-i386 systems.

Signed-off-by: Alexander Graf <[email protected]>
Message-Id: <[email protected]>
2021-05-27 12:30:10 +00:00
Alexander Graf a13fec6c17 hvf: Move vcpu thread functions into common directory
Until now, Hypervisor.framework has only been available on x86_64 systems.
With Apple Silicon shipping now, it extends its reach to aarch64. To
prepare for support for multiple architectures, let's start moving common
code out into its own accel directory.

This patch moves the vCPU thread loop over.

Signed-off-by: Alexander Graf <[email protected]>
Message-Id: <[email protected]>
2021-05-27 12:30:10 +00:00
Alexander Graf cf664b3a04 hvf: Move assert_hvf_ok() into common directory
Until now, Hypervisor.framework has only been available on x86_64 systems.
With Apple Silicon shipping now, it extends its reach to aarch64. To
prepare for support for multiple architectures, let's start moving common
code out into its own accel directory.

This patch moves assert_hvf_ok() and introduces generic build infrastructure.

Signed-off-by: Alexander Graf <[email protected]>
Message-Id: <[email protected]>
2021-05-27 12:30:09 +00:00
John Arbuckle 5897229105 Implement the Screamer sound chip for the mac99 machine type
This patch enables the playback of audio on a Mac OS 9 or Mac OS X guest.

Signed-off-by: John Arbuckle <[email protected]>
Message-Id: <[email protected]>
2021-05-23 20:30:23 -07:00
osy d35954d3c9 tcti: mark gadgets static to reduce symbol size in shared library builds 2021-05-23 20:30:23 -07:00
Kate Temkin 64dcc3969b TCTI: add TCTI TCG backend for acceleration on non-JIT AArch64 2021-05-23 20:30:23 -07:00
Phillip Tennen 06962e1aaa net/macos: implement vmnet-based netdev
This patch implements a new netdev device, reachable via -netdev
vmnet-macos, that’s backed by macOS’s vmnet framework.

The vmnet framework provides native bridging support, and its usage in
this patch is intended as a replacement for attempts to use a tap device
via the tuntaposx kernel extension. Notably, the tap/tuntaposx approach
never would have worked in the first place, as QEMU interacts with the
tap device via poll(), and macOS does not support polling device files.

vmnet requires either a special entitlement, granted via a provisioning
profile, or root access. Otherwise attempts to create the virtual
interface will fail with a “generic error” status code. QEMU may not
currently be signed with an entitlement granted in a provisioning
profile, as this would necessitate pre-signed binary build distribution,
rather than source-code distribution. As such, using this netdev
currently requires that qemu be run with root access. I’ve opened a
feedback report with Apple to allow the use of the relevant entitlement
with this use case:
https://openradar.appspot.com/radar?id=5007417364447232

vmnet offers three operating modes, all of which are supported by this
patch via the “mode=host|shared|bridge” option:

* "Host" mode: Allows the vmnet interface to communicate with other
* vmnet
interfaces that are in host mode and also with the native host.
* "Shared" mode: Allows traffic originating from the vmnet interface to
reach the Internet through a NAT. The vmnet interface can also
communicate with the native host.
* "Bridged" mode: Bridges the vmnet interface with a physical network
interface.

Each of these modes also provide some extra configuration that’s
supported by this patch:

* "Bridged" mode: The user may specify the physical interface to bridge
with. Defaults to en0.
* "Host" mode / "Shared" mode: The user may specify the DHCP range and
subnet. Allocated by vmnet if not provided.

vmnet also offers some extra configuration options that are not
supported by this patch:

* Enable isolation from other VMs using vmnet
* Port forwarding rules
* Enabling TCP segmentation offload
* Only applicable in "shared" mode: specifying the NAT IPv6 prefix
* Only available in "host" mode: specifying the IP address for the VM
within an isolated network

Note that this patch requires macOS 10.15 as a minimum, as this is when
bridging support was implemented in vmnet.framework.

Rebased to commit 571d413b5d by Akihiko
Odaki.

Signed-off-by: Phillip Tennen <[email protected]>
Signed-off-by: Akihiko Odaki <[email protected]>
Message-Id: <[email protected]>
2021-05-23 20:30:23 -07:00
osy ec151f4659 Merge branch 'hvf-aarch64-patch-v8' into utm-edition-v6.0.0 2021-05-23 20:28:47 -07:00
Alexander Graf 9d9ca24b72 hvf: arm: Handle Windows 10 SMC call
Windows 10 calls an SMCCC call via SMC unconditionally on boot. It lives
in the trusted application call number space, but its purpose is unknown.

In our current SMC implementation, we inject a UDEF for unknown SMC calls,
including this one. However, Windows breaks on boot when we do this. Instead,
let's return an error code.

With this patch applied I can successfully boot the current Windows 10
Insider Preview in HVF.

Signed-off-by: Alexander Graf <[email protected]>

Message-Id: <[email protected]>
2021-05-23 20:26:29 -07:00
Alexander Graf fe1b754eab arm: Enable Windows 10 trusted SMCCC boot call
Windows 10 calls an SMCCC call via SMC unconditionally on boot. It lives
in the trusted application call number space, but its purpose is unknown.

In our current SMC implementation, we inject a UDEF for unknown SMC calls,
including this one. However, Windows breaks on boot when we do this. Instead,
let's return an error code.

With this and -M virt,virtualization=on I can successfully boot the current
Windows 10 Insider Preview in TCG.

Signed-off-by: Alexander Graf <[email protected]>
Message-Id: <[email protected]>
2021-05-23 20:26:29 -07:00
Alexander Graf 6d6e43ebce arm: Add Hypervisor.framework build target
Now that we have all logic in place that we need to handle Hypervisor.framework
on Apple Silicon systems, let's add CONFIG_HVF for aarch64 as well so that we
can build it.

Signed-off-by: Alexander Graf <[email protected]>
Reviewed-by: Roman Bolshakov <[email protected]>
Tested-by: Roman Bolshakov <[email protected]> (x86 only)

Message-Id: <[email protected]>
2021-05-23 20:26:29 -07:00
Alexander Graf f479e7eacd hvf: arm: Implement PSCI handling
We need to handle PSCI calls. Most of the TCG code works for us,
but we can simplify it to only handle aa64 mode and we need to
handle SUSPEND differently.

This patch takes the TCG code as template and duplicates it in HVF.

To tell the guest that we support PSCI 0.2 now, update the check in
arm_cpu_initfn() as well.

Signed-off-by: Alexander Graf <[email protected]>

Message-Id: <[email protected]>
2021-05-23 20:26:29 -07:00
Alexander Graf dbbbd13bf6 hvf: arm: Implement -cpu host
Now that we have working system register sync, we push more target CPU
properties into the virtual machine. That might be useful in some
situations, but is not the typical case that users want.

So let's add a -cpu host option that allows them to explicitly pass all
CPU capabilities of their host CPU into the guest.

Signed-off-by: Alexander Graf <[email protected]>
Acked-by: Roman Bolshakov <[email protected]>

Message-Id: <[email protected]>
2021-05-23 20:26:29 -07:00
Peter Collingbourne dc32fd2d89 arm/hvf: Add a WFI handler
Sleep on WFI until the VTIMER is due but allow ourselves to be woken
up on IPI.

In this implementation IPI is blocked on the CPU thread at startup and
pselect() is used to atomically unblock the signal and begin sleeping.
The signal is sent unconditionally so there's no need to worry about
races between actually sleeping and the "we think we're sleeping"
state. It may lead to an extra wakeup but that's better than missing
it entirely.

Signed-off-by: Peter Collingbourne <[email protected]>
[agraf: Remove unused 'set' variable, always advance PC on WFX trap]
Signed-off-by: Alexander Graf <[email protected]>
Acked-by: Roman Bolshakov <[email protected]>

Message-Id: <[email protected]>
2021-05-23 20:26:29 -07:00
Alexander Graf 3354c800ac hvf: Add Apple Silicon support
With Apple Silicon available to the masses, it's a good time to add support
for driving its virtualization extensions from QEMU.

This patch adds all necessary architecture specific code to get basic VMs
working. It's still pretty raw, but definitely functional.

Known limitations:

  - Vtimer acknowledgement is hacky
  - Should implement more sysregs and fault on invalid ones then
  - WFI handling is missing, need to marry it with vtimer

Signed-off-by: Alexander Graf <[email protected]>
Reviewed-by: Roman Bolshakov <[email protected]>

Message-Id: <[email protected]>
2021-05-23 20:26:29 -07:00
Alexander Graf 365294d55a hvf: Simplify post reset/init/loadvm hooks
The hooks we have that call us after reset, init and loadvm really all
just want to say "The reference of all register state is in the QEMU
vcpu struct, please push it".

We already have a working pushing mechanism though called cpu->vcpu_dirty,
so we can just reuse that for all of the above, syncing state properly the
next time we actually execute a vCPU.

This fixes PSCI resets on ARM, as they modify CPU state even after the
post init call has completed, but before we execute the vCPU again.

To also make the scheme work for x86, we have to make sure we don't
move stale eflags into our env when the vcpu state is dirty.

Signed-off-by: Alexander Graf <[email protected]>
Reviewed-by: Roman Bolshakov <[email protected]>
Tested-by: Roman Bolshakov <[email protected]>
Message-Id: <[email protected]>
2021-05-23 20:26:29 -07:00
Alexander Graf a6bff5ccc8 hvf: Introduce hvf vcpu struct
We will need more than a single field for hvf going forward. To keep
the global vcpu struct uncluttered, let's allocate a special hvf vcpu
struct, similar to how hax does it.

Signed-off-by: Alexander Graf <[email protected]>
Reviewed-by: Roman Bolshakov <[email protected]>
Tested-by: Roman Bolshakov <[email protected]>
Reviewed-by: Alex Bennée <[email protected]>

Message-Id: <[email protected]>
2021-05-23 20:26:29 -07:00
Alexander Graf c803fc9d7d hvf: Remove hvf-accel-ops.h
We can move the definition of hvf_vcpu_exec() into our internal
hvf header, obsoleting the need for hvf-accel-ops.h.

Signed-off-by: Alexander Graf <[email protected]>
Message-Id: <[email protected]>
2021-05-23 20:26:29 -07:00
Alexander Graf 653cc15628 hvf: Make synchronize functions static
The hvf accel synchronize functions are only used as input for local
callback functions, so we can make them static.

Signed-off-by: Alexander Graf <[email protected]>
Message-Id: <[email protected]>
2021-05-23 20:26:29 -07:00
Alexander Graf 2e77c788d8 hvf: Use cpu_synchronize_state()
There is no reason to call the hvf specific hvf_cpu_synchronize_state()
when we can just use the generic cpu_synchronize_state() instead. This
allows us to have less dependency on internal function definitions and
allows us to make hvf_cpu_synchronize_state() static.

Signed-off-by: Alexander Graf <[email protected]>
Message-Id: <[email protected]>
2021-05-23 20:26:28 -07:00
Alexander Graf 1534c4fe04 hvf: Split out common code on vcpu init and destroy
Until now, Hypervisor.framework has only been available on x86_64 systems.
With Apple Silicon shipping now, it extends its reach to aarch64. To
prepare for support for multiple architectures, let's start moving common
code out into its own accel directory.

This patch splits the vcpu init and destroy functions into a generic and
an architecture specific portion. This also allows us to move the generic
functions into the generic hvf code, removing exported functions.

Signed-off-by: Alexander Graf <[email protected]>
Message-Id: <[email protected]>
2021-05-23 20:26:28 -07:00
Alexander Graf 3a513c9db4 hvf: Remove use of hv_uvaddr_t and hv_gpaddr_t
The ARM version of Hypervisor.framework no longer defines these two
types, so let's just revert to standard ones.

Signed-off-by: Alexander Graf <[email protected]>
Message-Id: <[email protected]>
2021-05-23 20:26:28 -07:00
Alexander Graf e27df17c9c hvf: Make hvf_set_phys_mem() static
The hvf_set_phys_mem() function is only called within the same file.
Make it static.

Signed-off-by: Alexander Graf <[email protected]>
Message-Id: <[email protected]>
2021-05-23 20:26:28 -07:00
Alexander Graf aa7ebf9a77 hvf: Move hvf internal definitions into common header
Until now, Hypervisor.framework has only been available on x86_64 systems.
With Apple Silicon shipping now, it extends its reach to aarch64. To
prepare for support for multiple architectures, let's start moving common
code out into its own accel directory.

This patch moves a few internal struct and constant defines over.

Signed-off-by: Alexander Graf <[email protected]>
Message-Id: <[email protected]>
2021-05-23 20:26:28 -07:00
Alexander Graf be54898fd5 hvf: Move cpu functions into common directory
Until now, Hypervisor.framework has only been available on x86_64 systems.
With Apple Silicon shipping now, it extends its reach to aarch64. To
prepare for support for multiple architectures, let's start moving common
code out into its own accel directory.

This patch moves CPU and memory operations over. While at it, make sure
the code is consumable on non-i386 systems.

Signed-off-by: Alexander Graf <[email protected]>
Message-Id: <[email protected]>
2021-05-23 20:26:28 -07:00
Alexander Graf 7a64de81ce hvf: Move vcpu thread functions into common directory
Until now, Hypervisor.framework has only been available on x86_64 systems.
With Apple Silicon shipping now, it extends its reach to aarch64. To
prepare for support for multiple architectures, let's start moving common
code out into its own accel directory.

This patch moves the vCPU thread loop over.

Signed-off-by: Alexander Graf <[email protected]>
Message-Id: <[email protected]>
2021-05-23 20:26:28 -07:00
Alexander Graf 71f21b796f hvf: Move assert_hvf_ok() into common directory
Until now, Hypervisor.framework has only been available on x86_64 systems.
With Apple Silicon shipping now, it extends its reach to aarch64. To
prepare for support for multiple architectures, let's start moving common
code out into its own accel directory.

This patch moves assert_hvf_ok() and introduces generic build infrastructure.

Signed-off-by: Alexander Graf <[email protected]>
Message-Id: <[email protected]>
2021-05-23 20:26:28 -07:00
Kate Temkin 13c9a7c820 TCTI: expand vector support to all ops 2021-05-06 16:58:56 -06:00
Kate Temkin 21ad741c1c TCTI: add initial vector instruction support 2021-05-06 08:53:59 -06:00
Kate Temkin 671b3cefcc TCTI: add remaining scalar ops 2021-05-04 08:02:19 -06:00
Kate Temkin 026956a474 TCTI: minor gadget optimizations 2021-05-04 06:19:41 -06:00
Kate Temkin 919856f02e Merge branch 'with_tcti_modular' into with_tcti 2021-04-30 11:44:01 -06:00
Kate Temkin cd4b5da233 TCTI: optimize I/O operation and helper call speeds 2021-04-30 11:40:17 -06:00
Joelle van Dyne 4e70afa94d coroutine: add libucontext as external library
iOS does not support ucontext natively for aarch64 and the sigaltstack is
also unsupported (even worse, it fails silently, see:
https://openradar.appspot.com/13002712 )

As a workaround we include a library implementation of ucontext and add it
as a build option.
2021-04-29 23:29:35 -07:00
osy 36195a781c tcg: custom APRR implementation 2021-04-29 23:29:35 -07:00
Marc-André Lureau 2541dde936 build-sys: make libslirp a meson subproject
Remove the manual build.

Signed-off-by: Marc-André Lureau <[email protected]>
Message-Id: <[email protected]>
2021-04-29 23:29:35 -07:00
Marc-André Lureau ecc067a3ba slirp: update to git master
git cherry-diff:

Commits on bacb71f1c3ed5f40e393afd8be81bedfba13a401 branch that is not on 8f43a99191afb47ca3f3c6972f6306209f367ece branch
+ 1021b0dc38d39f1dc95a296fe3e05a24a087cdc6 disable_dns option
+ 0f94ceec752592e4ac632a24e3c64a97dd09bf4c limit vnameserver_addr to port 53
+ b57bafa852ef16b133907a13678ec69e9531f177 libslirp.h: fix SlirpConfig v3 documentation
+ 1abf18b2b5edb462797629ed47ad4515a195686e Update CHANGELOG
+ ff4ecf9b6c6542b24b4ac6ea178be9d44e159f79 Release v4.3.0
+ 21f1d933050a40d62612c6274c32de60b811d9ea changelog: post-release
+ 376187c4b14c795763d472214812826eebe7e9c2 Release v4.3.1
+ 73336e08902a7e826f7d960453df037380266186 changelog: post-release
+ 5c1c9d43be61571608e9b14615045b67b830daf5 udp, udp6, icmp: handle TTL value
+ 73ed49ab71998d4288e71e954ef6214b70f23d79 icmp, icmp6: Add icmp_forward_error and icmp6_forward_error
+ 7a4840a57ec7dbc37cca1ab96f058a9610b26950 udp, udp6, icmp, icmp6: Enable forwarding errors on Linux
+ e9b2bc19ae652a2907f247e621b2e4773bdd2aab TCPIPHDR_DELTA: Fix potential negative value
+ 39f9a363eec082f04513413046321abd04163148 .gitlab-ci: add a Coverity stage
+ 1b0093b973cfa0dc041522e5d4e6f576b2df642e sosendoob: better document what urgc is used for
+ 5b9ad89ebbb8afa50162c9156fabd5fc56291088 Add G_GNUC_PRINTF to local function slirp_vsnprintf
+ 8a808aa493980e212b4d5f5465330905c8294e59 meson: remove meson-dist script
+ 0b669b5fbe4d3c25a682a67f1059d8633c963b3d meson: support compiling as subproject
+ 9f82a47b81f2864422b82c1e40e51a2ed9c6ac32 Add DNS resolving for iOS
+ c0eac03e8ce1b9a743231f2fe21e7cb579fc9339 Remove the QEMU-special make build-system
+ 1bfd4d9368f9fa2e4f0731e1266bec05bbc83a80 socket: consume empty packets
+ 92413be68914f8cae2f5bad4bf3ab8491dcbc5d7 Release v4.4.0
+ 07e8cfac69766081871ab620d9f16a630543d302 changelog: post-release
+ 4c4e035813313d02b63fdeb920d56fb2fdc0a5b1 Remove some needless (void)casts
+ eee9db9d115d91aa82f33685c4e76d656db92976 fork_exec_child_setup: improve signal handling
+ 216f434a018b3af182a4f31bbe5a00daee170343 Fix unused variables

Signed-off-by: Marc-André Lureau <[email protected]>
Message-Id: <[email protected]>
2021-04-29 23:29:35 -07:00
Gerd Hoffmann 819b2c2984 hw/display: add virtio-ramfb device
Like virtio-vga, but using ramfb instead of legacy vga.
Useful for booting from OVMF into Windows ARM which expects a linear FB.
2021-04-29 23:29:35 -07:00
osy 8ed0f7cb4d meson: option to build as shared library
On iOS, we cannot fork() new processes, so the best way to load QEMU into an
app is through a shared library. We add a new configure option
`--enable-shared-lib` that will build the bulk of QEMU into a shared lib.
The usual executables will then link to the library.
2021-04-29 23:29:35 -07:00
Joelle van Dyne d1bf1e28b6 slirp: feature detection for smbd
Replace Windows specific macro with a more generic feature detection
macro. Allows slirp smb feature to be disabled manually as well.
2021-04-29 23:29:35 -07:00
Joelle van DyneandWarner Losh 47cd50d3d2 block: detect DKIOCGETBLOCKCOUNT/SIZE before use
iOS hosts do not have these defined so we fallback to the
default behaviour.

Co-authored-by: Warner Losh <[email protected]>
2021-04-29 23:29:35 -07:00
Joelle van Dyne 324cef19f8 block: check for sys/disk.h
Some BSD platforms do not have this header.
2021-04-29 23:29:35 -07:00
Joelle van Dyne e252078b6e block: feature detection for host block support
On Darwin (iOS), there are no system level APIs for directly accessing
host block devices. We detect this at configure time.
2021-04-29 23:29:35 -07:00
Kate Temkin 69c9fe3f2e TCTI: modularize things more for fast clang 2021-04-29 04:23:23 -06:00
Kate Temkin 6764fe306f TCTI: more modular hacks 2021-04-28 05:37:42 -06:00
Kate Temkin 744075b9ee TCTI: dramatically speed up build & reduce footprint 2021-04-28 03:29:08 +00:00
Kate Temkin c77bed1d5c split gadgets into multiple files 2021-04-27 13:47:14 -06:00
Kate Temkin 1e4d72b004 TCTI: add TCTI TCG backend for acceleration on non-JIT AArch64 2021-04-27 13:21:48 -06:00
Kate Temkin 6c39f9e99b get building for an iOS target, as well 2021-04-27 13:21:47 -06:00
Joelle van Dyne ad73633ab3 coroutine: add libucontext as external library
iOS does not support ucontext natively for aarch64 and the sigaltstack is
also unsupported (even worse, it fails silently, see:
https://openradar.appspot.com/13002712 )

As a workaround we include a library implementation of ucontext and add it
as a build option.
2021-04-27 13:21:20 -06:00
osy a6b59f6dee tcg: custom APRR implementation 2021-04-27 13:21:20 -06:00
Roman Bolshakov 5db66c67b9 util/osdep: Avoid mprotect() RWX->NONE on Big Sur 11.2
There's a change in mprotect() behaviour [1] in the latest macOS on M1
and it's not yet clear if it's going to be fixed by Apple. For now we
can avoid unsupported mprotect() calls. QEMU and qtests work fine
without it.

1. https://gist.github.com/hikalium/75ae822466ee4da13cbbe486498a191f

Buglink: https://bugs.launchpad.net/qemu/+bug/1914849
Apple-Feedback: FB8994773
Signed-off-by: Roman Bolshakov <[email protected]>
Message-Id: <[email protected]>
2021-04-27 13:21:20 -06:00
Marc-André Lureau c78951da1b build-sys: make libslirp a meson subproject
Remove the manual build.

Signed-off-by: Marc-André Lureau <[email protected]>
Message-Id: <[email protected]>
2021-04-27 13:21:20 -06:00
Marc-André Lureau 138287176b slirp: update to git master
git cherry-diff:

Commits on bacb71f1c3ed5f40e393afd8be81bedfba13a401 branch that is not on 8f43a99191afb47ca3f3c6972f6306209f367ece branch
+ 1021b0dc38d39f1dc95a296fe3e05a24a087cdc6 disable_dns option
+ 0f94ceec752592e4ac632a24e3c64a97dd09bf4c limit vnameserver_addr to port 53
+ b57bafa852ef16b133907a13678ec69e9531f177 libslirp.h: fix SlirpConfig v3 documentation
+ 1abf18b2b5edb462797629ed47ad4515a195686e Update CHANGELOG
+ ff4ecf9b6c6542b24b4ac6ea178be9d44e159f79 Release v4.3.0
+ 21f1d933050a40d62612c6274c32de60b811d9ea changelog: post-release
+ 376187c4b14c795763d472214812826eebe7e9c2 Release v4.3.1
+ 73336e08902a7e826f7d960453df037380266186 changelog: post-release
+ 5c1c9d43be61571608e9b14615045b67b830daf5 udp, udp6, icmp: handle TTL value
+ 73ed49ab71998d4288e71e954ef6214b70f23d79 icmp, icmp6: Add icmp_forward_error and icmp6_forward_error
+ 7a4840a57ec7dbc37cca1ab96f058a9610b26950 udp, udp6, icmp, icmp6: Enable forwarding errors on Linux
+ e9b2bc19ae652a2907f247e621b2e4773bdd2aab TCPIPHDR_DELTA: Fix potential negative value
+ 39f9a363eec082f04513413046321abd04163148 .gitlab-ci: add a Coverity stage
+ 1b0093b973cfa0dc041522e5d4e6f576b2df642e sosendoob: better document what urgc is used for
+ 5b9ad89ebbb8afa50162c9156fabd5fc56291088 Add G_GNUC_PRINTF to local function slirp_vsnprintf
+ 8a808aa493980e212b4d5f5465330905c8294e59 meson: remove meson-dist script
+ 0b669b5fbe4d3c25a682a67f1059d8633c963b3d meson: support compiling as subproject
+ 9f82a47b81f2864422b82c1e40e51a2ed9c6ac32 Add DNS resolving for iOS
+ c0eac03e8ce1b9a743231f2fe21e7cb579fc9339 Remove the QEMU-special make build-system
+ 1bfd4d9368f9fa2e4f0731e1266bec05bbc83a80 socket: consume empty packets
+ 92413be68914f8cae2f5bad4bf3ab8491dcbc5d7 Release v4.4.0
+ 07e8cfac69766081871ab620d9f16a630543d302 changelog: post-release
+ 4c4e035813313d02b63fdeb920d56fb2fdc0a5b1 Remove some needless (void)casts
+ eee9db9d115d91aa82f33685c4e76d656db92976 fork_exec_child_setup: improve signal handling
+ 216f434a018b3af182a4f31bbe5a00daee170343 Fix unused variables

Signed-off-by: Marc-André Lureau <[email protected]>
Message-Id: <[email protected]>
2021-04-27 13:21:20 -06:00
Gerd Hoffmann 17ebce776d hw/display: add virtio-ramfb device
Like virtio-vga, but using ramfb instead of legacy vga.
Useful for booting from OVMF into Windows ARM which expects a linear FB.
2021-04-27 13:21:20 -06:00
osy e034ab0b4d meson: option to build as shared library
On iOS, we cannot fork() new processes, so the best way to load QEMU into an
app is through a shared library. We add a new configure option
`--enable-shared-lib` that will build the bulk of QEMU into a shared lib.
The usual executables will then link to the library.
2021-04-27 13:21:20 -06:00
Joelle van Dyne d4e9108ef1 slirp: feature detection for smbd
Replace Windows specific macro with a more generic feature detection
macro. Allows slirp smb feature to be disabled manually as well.
2021-04-27 13:21:18 -06:00
Joelle van DyneandWarner Losh 36c2febd7f block: detect DKIOCGETBLOCKCOUNT/SIZE before use
iOS hosts do not have these defined so we fallback to the
default behaviour.

Co-authored-by: Warner Losh <[email protected]>
2021-04-27 13:20:46 -06:00
Joelle van Dyne 1913d4d2a7 block: check for sys/disk.h
Some BSD platforms do not have this header.
2021-04-27 13:20:46 -06:00
Joelle van Dyne 4f59dc2db0 block: feature detection for host block support
On Darwin (iOS), there are no system level APIs for directly accessing
host block devices. We detect this at configure time.
2021-04-27 13:20:46 -06:00
Kate Temkin 4de86e6de1 TCTI: add TCTI TCG backend for acceleration on non-JIT AArch64 2021-04-07 10:34:23 -06:00
Kate Temkin e16a18d2d9 get building for an iOS target, as well 2021-03-27 15:46:31 -06:00
Joelle van Dyne 4373fc4514 coroutine: add libucontext as external library
iOS does not support ucontext natively for aarch64 and the sigaltstack is
also unsupported (even worse, it fails silently, see:
https://openradar.appspot.com/13002712 )

As a workaround we include a library implementation of ucontext and add it
as a build option.
2021-03-08 17:28:49 -08:00
osy 37aa4a1894 tcg: custom APRR implementation 2021-03-08 17:28:49 -08:00
Roman Bolshakov cf8a85ad18 util/osdep: Avoid mprotect() RWX->NONE on Big Sur 11.2
There's a change in mprotect() behaviour [1] in the latest macOS on M1
and it's not yet clear if it's going to be fixed by Apple. For now we
can avoid unsupported mprotect() calls. QEMU and qtests work fine
without it.

1. https://gist.github.com/hikalium/75ae822466ee4da13cbbe486498a191f

Buglink: https://bugs.launchpad.net/qemu/+bug/1914849
Apple-Feedback: FB8994773
Signed-off-by: Roman Bolshakov <[email protected]>
Message-Id: <[email protected]>
2021-03-08 17:28:49 -08:00
Marc-André Lureau da1d34255c build-sys: make libslirp a meson subproject
Remove the manual build.

Signed-off-by: Marc-André Lureau <[email protected]>
Message-Id: <[email protected]>
2021-03-08 17:28:49 -08:00
Marc-André Lureau ff51693eef slirp: update to git master
git cherry-diff:

Commits on bacb71f1c3ed5f40e393afd8be81bedfba13a401 branch that is not on 8f43a99191afb47ca3f3c6972f6306209f367ece branch
+ 1021b0dc38d39f1dc95a296fe3e05a24a087cdc6 disable_dns option
+ 0f94ceec752592e4ac632a24e3c64a97dd09bf4c limit vnameserver_addr to port 53
+ b57bafa852ef16b133907a13678ec69e9531f177 libslirp.h: fix SlirpConfig v3 documentation
+ 1abf18b2b5edb462797629ed47ad4515a195686e Update CHANGELOG
+ ff4ecf9b6c6542b24b4ac6ea178be9d44e159f79 Release v4.3.0
+ 21f1d933050a40d62612c6274c32de60b811d9ea changelog: post-release
+ 376187c4b14c795763d472214812826eebe7e9c2 Release v4.3.1
+ 73336e08902a7e826f7d960453df037380266186 changelog: post-release
+ 5c1c9d43be61571608e9b14615045b67b830daf5 udp, udp6, icmp: handle TTL value
+ 73ed49ab71998d4288e71e954ef6214b70f23d79 icmp, icmp6: Add icmp_forward_error and icmp6_forward_error
+ 7a4840a57ec7dbc37cca1ab96f058a9610b26950 udp, udp6, icmp, icmp6: Enable forwarding errors on Linux
+ e9b2bc19ae652a2907f247e621b2e4773bdd2aab TCPIPHDR_DELTA: Fix potential negative value
+ 39f9a363eec082f04513413046321abd04163148 .gitlab-ci: add a Coverity stage
+ 1b0093b973cfa0dc041522e5d4e6f576b2df642e sosendoob: better document what urgc is used for
+ 5b9ad89ebbb8afa50162c9156fabd5fc56291088 Add G_GNUC_PRINTF to local function slirp_vsnprintf
+ 8a808aa493980e212b4d5f5465330905c8294e59 meson: remove meson-dist script
+ 0b669b5fbe4d3c25a682a67f1059d8633c963b3d meson: support compiling as subproject
+ 9f82a47b81f2864422b82c1e40e51a2ed9c6ac32 Add DNS resolving for iOS
+ c0eac03e8ce1b9a743231f2fe21e7cb579fc9339 Remove the QEMU-special make build-system
+ 1bfd4d9368f9fa2e4f0731e1266bec05bbc83a80 socket: consume empty packets
+ 92413be68914f8cae2f5bad4bf3ab8491dcbc5d7 Release v4.4.0
+ 07e8cfac69766081871ab620d9f16a630543d302 changelog: post-release
+ 4c4e035813313d02b63fdeb920d56fb2fdc0a5b1 Remove some needless (void)casts
+ eee9db9d115d91aa82f33685c4e76d656db92976 fork_exec_child_setup: improve signal handling
+ 216f434a018b3af182a4f31bbe5a00daee170343 Fix unused variables

Signed-off-by: Marc-André Lureau <[email protected]>
Message-Id: <[email protected]>
2021-03-08 17:28:49 -08:00
Gerd Hoffmann 4ef61a5fd7 hw/display: add virtio-ramfb device
Like virtio-vga, but using ramfb instead of legacy vga.
Useful for booting from OVMF into Windows ARM which expects a linear FB.
2021-03-08 17:28:49 -08:00
osy bcdcc525e4 meson: option to build as shared library
On iOS, we cannot fork() new processes, so the best way to load QEMU into an
app is through a shared library. We add a new configure option
`--enable-shared-lib` that will build the bulk of QEMU into a shared lib.
The usual executables will then link to the library.
2021-03-08 17:28:49 -08:00
Joelle van Dyne 69819144f1 slirp: feature detection for smbd
Replace Windows specific macro with a more generic feature detection
macro. Allows slirp smb feature to be disabled manually as well.
2021-03-08 16:24:07 -08:00
Joelle van DyneandWarner Losh f314014422 block: detect DKIOCGETBLOCKCOUNT/SIZE before use
iOS hosts do not have these defined so we fallback to the
default behaviour.

Co-authored-by: Warner Losh <[email protected]>
2021-03-07 18:42:43 -08:00
Joelle van Dyne e0a033d9d4 block: check for sys/disk.h
Some BSD platforms do not have this header.
2021-03-07 18:42:20 -08:00
Joelle van Dyne 0272e162b7 block: feature detection for host block support
On Darwin (iOS), there are no system level APIs for directly accessing
host block devices. We detect this at configure time.
2021-03-07 16:52:13 -08:00
190 changed files with 12154 additions and 1421 deletions

No files matched your search

+186 -17
View File
@@ -48,23 +48,84 @@
*/
#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"
#include "exec/exec-all.h"
#include "gdbstub/enums.h"
#include "hw/boards.h"
#include "qapi/error.h"
#include "qapi/visitor.h"
#include "system/accel-ops.h"
#include "system/cpus.h"
#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"
HVFState *hvf_state;
bool hvf_tso_mode = 0;
uint32_t hvf_ipa_granule_size = 0;
/* Memory slots */
/* Default num of memslots to be allocated when VM starts */
#define HVF_MEMSLOTS_NUM_ALLOC_DEFAULT 32
static bool hvf_slots_grow(HVFState *state, unsigned int num_slots_new)
{
unsigned int i, cur = state->num_slots;
hvf_slot *slots;
hvf_mac_slot *mac_slots;
assert(num_slots_new > cur);
if (cur == 0) {
slots = g_new0(hvf_slot, num_slots_new);
if (!slots) {
return false;
}
mac_slots = g_new0(hvf_mac_slot, num_slots_new);
if (!mac_slots) {
g_free(slots);
return false;
}
} else {
slots = g_renew(hvf_slot, state->slots, num_slots_new);
if (!slots) {
return false;
}
mac_slots = g_renew(hvf_mac_slot, state->mac_slots, num_slots_new);
if (!mac_slots) {
/* save allocated slots but not new size */
state->slots = slots;
return false;
}
/*
* g_renew() doesn't initialize extended buffers, however hvf
* memslots require fields to be zero-initialized. E.g. pointers,
* memory_size field, etc.
*/
memset(&slots[cur], 0x0, sizeof(slots[0]) * (num_slots_new - cur));
memset(&mac_slots[cur], 0x0, sizeof(mac_slots[0]) * (num_slots_new - cur));
}
for (i = cur; i < num_slots_new; i++) {
slots[i].slot_id = i;
}
state->slots = slots;
state->mac_slots = mac_slots;
state->num_slots = num_slots_new;
return true;
}
hvf_slot *hvf_find_overlap_slot(uint64_t start, uint64_t size)
{
hvf_slot *slot;
@@ -79,21 +140,46 @@ hvf_slot *hvf_find_overlap_slot(uint64_t start, uint64_t size)
return NULL;
}
struct mac_slot {
int present;
uint64_t size;
uint64_t gpa_start;
uint64_t gva;
};
#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;
struct mac_slot mac_slots[32];
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)
{
struct mac_slot *macslot;
hvf_mac_slot *macslot;
hv_return_t ret;
macslot = &mac_slots[slot->slot_id];
macslot = &hvf_state->mac_slots[slot->slot_id];
if (macslot->present) {
if (macslot->size != slot->size) {
@@ -110,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;
@@ -135,8 +236,20 @@ static void hvf_set_phys_mem(MemoryRegionSection *section, bool add)
}
}
if (hvf_ipa_granule_size) {
page_size = hvf_ipa_granule_size;
}
if (!QEMU_IS_ALIGNED(int128_get64(section->size), page_size) ||
!QEMU_IS_ALIGNED(section->offset_within_address_space, page_size)) {
if (add) {
warn_report("Cannot add 0x%016llX:0x%016llX because it is not "
"aligned to page size (0x%X)",
section->offset_within_address_space,
section->offset_within_address_space +
int128_get64(section->size),
(uint32_t)page_size);
}
/* Not page aligned, so we can not map as RAM */
add = false;
}
@@ -185,8 +298,11 @@ static void hvf_set_phys_mem(MemoryRegionSection *section, bool add)
}
if (x == hvf_state->num_slots) {
error_report("No free slots");
abort();
if (!hvf_slots_grow(hvf_state, hvf_state->num_slots * 2)) {
error_report("Cannot allocate any more slots");
abort();
}
mem = &hvf_state->slots[x];
}
mem->size = int128_get64(section->size);
@@ -323,6 +439,7 @@ static int hvf_accel_init(MachineState *ms)
HVFState *s;
int pa_range = 36;
MachineClass *mc = MACHINE_GET_CLASS(ms);
bool success;
if (mc->hvf_get_physical_address_range) {
pa_range = mc->hvf_get_physical_address_range(ms);
@@ -331,16 +448,13 @@ static int hvf_accel_init(MachineState *ms)
}
}
ret = hvf_arch_vm_create(ms, (uint32_t)pa_range);
ret = hvf_arch_vm_create(ms, (uint32_t)pa_range, hvf_ipa_granule_size);
assert_hvf_ok(ret);
s = g_new0(HVFState, 1);
s->num_slots = ARRAY_SIZE(s->slots);
for (x = 0; x < s->num_slots; ++x) {
s->slots[x].size = 0;
s->slots[x].slot_id = x;
}
success = hvf_slots_grow(s, HVF_MEMSLOTS_NUM_ALLOC_DEFAULT);
assert(success);
QTAILQ_INIT(&s->hvf_sw_breakpoints);
@@ -350,11 +464,53 @@ static int hvf_accel_init(MachineState *ms)
return hvf_arch_init();
}
#if defined(__aarch64__)
static bool hvf_get_tso(Object *obj, Error **errp)
{
return hvf_tso_mode;
}
static void hvf_set_tso(Object *obj, bool value, Error **errp)
{
hvf_tso_mode = value;
}
#endif
static inline int hvf_gdbstub_sstep_flags(void)
{
return SSTEP_ENABLE | SSTEP_NOIRQ;
}
static void hvf_get_ipa_granule_size(Object *obj, Visitor *v,
const char *name, void *opaque,
Error **errp)
{
HVFState *s = HVF_STATE(obj);
uint32_t value = hvf_ipa_granule_size;
visit_type_uint32(v, name, &value, errp);
}
static void hvf_set_ipa_granule_size(Object *obj, Visitor *v,
const char *name, void *opaque,
Error **errp)
{
HVFState *s = HVF_STATE(obj);
uint32_t value;
if (!visit_type_uint32(v, name, &value, errp)) {
return;
}
if (value & (value - 1)) {
error_setg(errp, "ipa-granule-size must be a power of two.");
return;
}
hvf_ipa_granule_size = value;
}
static void hvf_accel_class_init(ObjectClass *oc, void *data)
{
AccelClass *ac = ACCEL_CLASS(oc);
@@ -362,6 +518,19 @@ static void hvf_accel_class_init(ObjectClass *oc, void *data)
ac->init_machine = hvf_accel_init;
ac->allowed = &hvf_allowed;
ac->gdbstub_supported_sstep_flags = hvf_gdbstub_sstep_flags;
#if defined(__aarch64__)
object_class_property_add_bool(oc, "tso",
hvf_get_tso, hvf_set_tso);
object_class_property_set_description(oc, "tso",
"Set on/off to enable/disable total store ordering mode");
#endif
object_class_property_add(oc, "ipa-granule-size", "uint32",
hvf_get_ipa_granule_size, hvf_set_ipa_granule_size,
NULL, NULL);
object_class_property_set_description(oc, "ipa-granule-size",
"Size of a single guest page");
}
static const TypeInfo hvf_accel_type = {
+1
View File
@@ -3945,6 +3945,7 @@ static void kvm_accel_instance_init(Object *obj)
s->xen_evtchn_max_pirq = 256;
s->device = NULL;
s->msr_energy.enable = false;
s->honor_guest_pat = ON_OFF_AUTO_OFF;
}
/**
+1
View File
@@ -29,6 +29,7 @@
#include "exec/page-protection.h"
#include "exec/translation-block.h"
#include "tcg/tcg.h"
#include "tcg/tcg-apple-jit.h"
#include "qemu/atomic.h"
#include "qemu/rcu.h"
#include "exec/log.h"
+2 -1
View File
@@ -2890,7 +2890,8 @@ static void do_st16_mmu(CPUState *cpu, vaddr addr, Int128 val,
#include "atomic_template.h"
#endif
#if defined(CONFIG_ATOMIC128) || HAVE_CMPXCHG128
/* FIXME: this doesn't work in TCTI */
#if (defined(CONFIG_ATOMIC128) && !defined(CONFIG_TCG_THREADED_INTERPRETER)) || HAVE_CMPXCHG128
#define DATA_SIZE 16
#include "atomic_template.h"
#endif
+1
View File
@@ -28,6 +28,7 @@
#include "tb-internal.h"
#include "system/tcg.h"
#include "tcg/tcg.h"
#include "tcg/tcg-apple-jit.h"
#include "tb-hash.h"
#include "tb-context.h"
#include "tb-internal.h"
+6
View File
@@ -64,6 +64,12 @@ void tcg_cpu_init_cflags(CPUState *cpu, bool parallel)
cflags |= parallel ? CF_PARALLEL : 0;
cflags |= icount_enabled() ? CF_USE_ICOUNT : 0;
#if defined(CONFIG_TCG_THREADED_INTERPRETER)
// GOTO_PTR is too complex to emit a simple gadget for.
// We'll let C handle it, since the overhead is similar.
cflags |= CF_NO_GOTO_PTR;
cpu->cflags_next_tb = CF_NO_GOTO_PTR;
#endif
tcg_cflags_set(cpu, cflags);
}
+1
View File
@@ -23,6 +23,7 @@
#include "disas/disas.h"
#include "exec/exec-all.h"
#include "tcg/tcg.h"
#include "tcg/tcg-apple-jit.h"
#if defined(CONFIG_USER_ONLY)
#include "qemu.h"
#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
+24 -6
View File
@@ -1415,12 +1415,21 @@ void audio_run(AudioState *s, const char *msg)
#endif
}
void audio_generic_initialize_buffer_in(HWVoiceIn *hw)
{
if (hw->buf_emul) {
g_free(hw->buf_emul);
}
hw->size_emul = hw->samples * hw->info.bytes_per_frame;
hw->buf_emul = g_malloc(hw->size_emul);
hw->pos_emul = hw->pending_emul = 0;
}
void audio_generic_run_buffer_in(HWVoiceIn *hw)
{
if (unlikely(!hw->buf_emul)) {
hw->size_emul = hw->samples * hw->info.bytes_per_frame;
hw->buf_emul = g_malloc(hw->size_emul);
hw->pos_emul = hw->pending_emul = 0;
audio_generic_initialize_buffer_in(hw);
}
while (hw->pending_emul < hw->size_emul) {
@@ -1454,6 +1463,17 @@ void audio_generic_put_buffer_in(HWVoiceIn *hw, void *buf, size_t size)
hw->pending_emul -= size;
}
void audio_generic_initialize_buffer_out(HWVoiceOut *hw)
{
if (hw->buf_emul) {
g_free(hw->buf_emul);
}
hw->size_emul = hw->samples * hw->info.bytes_per_frame;
hw->buf_emul = g_malloc(hw->size_emul);
hw->pos_emul = hw->pending_emul = 0;
}
size_t audio_generic_buffer_get_free(HWVoiceOut *hw)
{
if (hw->buf_emul) {
@@ -1485,9 +1505,7 @@ void audio_generic_run_buffer_out(HWVoiceOut *hw)
void *audio_generic_get_buffer_out(HWVoiceOut *hw, size_t *size)
{
if (unlikely(!hw->buf_emul)) {
hw->size_emul = hw->samples * hw->info.bytes_per_frame;
hw->buf_emul = g_malloc(hw->size_emul);
hw->pos_emul = hw->pending_emul = 0;
audio_generic_initialize_buffer_out(hw);
}
*size = MIN(hw->size_emul - hw->pending_emul,
+2
View File
@@ -187,9 +187,11 @@ struct audio_pcm_ops {
void (*volume_in)(HWVoiceIn *hw, Volume *vol);
};
void audio_generic_initialize_buffer_in(HWVoiceIn *hw);
void audio_generic_run_buffer_in(HWVoiceIn *hw);
void *audio_generic_get_buffer_in(HWVoiceIn *hw, size_t *size);
void audio_generic_put_buffer_in(HWVoiceIn *hw, void *buf, size_t size);
void audio_generic_initialize_buffer_out(HWVoiceOut *hw);
void audio_generic_run_buffer_out(HWVoiceOut *hw);
size_t audio_generic_buffer_get_free(HWVoiceOut *hw);
void *audio_generic_get_buffer_out(HWVoiceOut *hw, size_t *size);
+46 -22
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;
@@ -355,7 +370,10 @@ static OSStatus audioDeviceIOProc(
static OSStatus init_out_device(coreaudioVoiceOut *core)
{
OSStatus status;
AudioDeviceID deviceID;
AudioValueRange frameRange;
UInt32 audioDevicePropertyBufferFrameSize;
AudioDeviceIOProcID ioprocid;
AudioStreamBasicDescription streamBasicDescription = {
.mBitsPerChannel = core->hw.info.bits,
@@ -368,20 +386,19 @@ static OSStatus init_out_device(coreaudioVoiceOut *core)
.mSampleRate = core->hw.info.freq
};
status = coreaudio_get_voice(&core->outputDeviceID);
status = coreaudio_get_voice(&deviceID);
if (status != kAudioHardwareNoError) {
coreaudio_playback_logerr (status,
"Could not get default output Device\n");
return status;
}
if (core->outputDeviceID == kAudioDeviceUnknown) {
if (deviceID == kAudioDeviceUnknown) {
dolog ("Could not initialize playback - Unknown Audiodevice\n");
return status;
}
/* get minimum and maximum buffer frame sizes */
status = coreaudio_get_framesizerange(core->outputDeviceID,
&frameRange);
status = coreaudio_get_framesizerange(deviceID, &frameRange);
if (status == kAudioHardwareBadObjectError) {
return 0;
}
@@ -392,31 +409,31 @@ static OSStatus init_out_device(coreaudioVoiceOut *core)
}
if (frameRange.mMinimum > core->frameSizeSetting) {
core->audioDevicePropertyBufferFrameSize = (UInt32) frameRange.mMinimum;
audioDevicePropertyBufferFrameSize = (UInt32) frameRange.mMinimum;
dolog ("warning: Upsizing Buffer Frames to %f\n", frameRange.mMinimum);
} else if (frameRange.mMaximum < core->frameSizeSetting) {
core->audioDevicePropertyBufferFrameSize = (UInt32) frameRange.mMaximum;
audioDevicePropertyBufferFrameSize = (UInt32) frameRange.mMaximum;
dolog ("warning: Downsizing Buffer Frames to %f\n", frameRange.mMaximum);
} else {
core->audioDevicePropertyBufferFrameSize = core->frameSizeSetting;
audioDevicePropertyBufferFrameSize = core->frameSizeSetting;
}
/* set Buffer Frame Size */
status = coreaudio_set_framesize(core->outputDeviceID,
&core->audioDevicePropertyBufferFrameSize);
status = coreaudio_set_framesize(deviceID,
&audioDevicePropertyBufferFrameSize);
if (status == kAudioHardwareBadObjectError) {
return 0;
}
if (status != kAudioHardwareNoError) {
coreaudio_playback_logerr (status,
"Could not set device buffer frame size %" PRIu32 "\n",
(uint32_t)core->audioDevicePropertyBufferFrameSize);
(uint32_t)audioDevicePropertyBufferFrameSize);
return status;
}
/* get Buffer Frame Size */
status = coreaudio_get_framesize(core->outputDeviceID,
&core->audioDevicePropertyBufferFrameSize);
status = coreaudio_get_framesize(deviceID,
&audioDevicePropertyBufferFrameSize);
if (status == kAudioHardwareBadObjectError) {
return 0;
}
@@ -425,11 +442,9 @@ static OSStatus init_out_device(coreaudioVoiceOut *core)
"Could not get device buffer frame size\n");
return status;
}
core->hw.samples = core->bufferCount * core->audioDevicePropertyBufferFrameSize;
/* set Samplerate */
status = coreaudio_set_streamformat(core->outputDeviceID,
&streamBasicDescription);
status = coreaudio_set_streamformat(deviceID, &streamBasicDescription);
if (status == kAudioHardwareBadObjectError) {
return 0;
}
@@ -437,7 +452,6 @@ static OSStatus init_out_device(coreaudioVoiceOut *core)
coreaudio_playback_logerr (status,
"Could not set samplerate %lf\n",
streamBasicDescription.mSampleRate);
core->outputDeviceID = kAudioDeviceUnknown;
return status;
}
@@ -451,20 +465,25 @@ static OSStatus init_out_device(coreaudioVoiceOut *core)
* Therefore, the specified callback must be designed to avoid a deadlock
* with the callers of AudioObjectGetPropertyData.
*/
core->ioprocid = NULL;
status = AudioDeviceCreateIOProcID(core->outputDeviceID,
ioprocid = NULL;
status = AudioDeviceCreateIOProcID(deviceID,
audioDeviceIOProc,
&core->hw,
&core->ioprocid);
&ioprocid);
if (status == kAudioHardwareBadDeviceError) {
return 0;
}
if (status != kAudioHardwareNoError || core->ioprocid == NULL) {
if (status != kAudioHardwareNoError || ioprocid == NULL) {
coreaudio_playback_logerr (status, "Could not set IOProc\n");
core->outputDeviceID = kAudioDeviceUnknown;
return status;
}
core->outputDeviceID = deviceID;
core->audioDevicePropertyBufferFrameSize = audioDevicePropertyBufferFrameSize;
core->hw.samples = core->bufferCount * core->audioDevicePropertyBufferFrameSize;
audio_generic_initialize_buffer_out(&core->hw);
core->ioprocid = ioprocid;
return 0;
}
@@ -548,7 +567,9 @@ static OSStatus handle_voice_change(
fini_out_device(core);
}
if (!init_out_device(core)) {
init_out_device(core);
if (core->outputDeviceID) {
update_device_playback_state(core);
}
@@ -636,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);
}
+23 -2
View File
@@ -44,10 +44,10 @@
#if defined(__APPLE__) && (__MACH__)
#include <sys/ioctl.h>
#if defined(HAVE_HOST_BLOCK_DEVICE)
#include <paths.h>
#include <sys/param.h>
#include <sys/mount.h>
#if defined(HAVE_HOST_BLOCK_DEVICE)
#include <paths.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/IOBSD.h>
#include <IOKit/storage/IOMediaBSDClient.h>
@@ -285,6 +285,13 @@ static int raw_normalize_devicepath(const char **filename, Error **errp)
}
#endif
#if defined(CONFIG_IOS)
static int probe_logical_blocksize(int fd, unsigned int *sector_size_p)
{
return -ENOTSUP; /* not supported on iOS */
}
#else /* CONFIG_IOS */
/*
* Get logical block size via ioctl. On success store it in @sector_size_p.
*/
@@ -318,6 +325,8 @@ static int probe_logical_blocksize(int fd, unsigned int *sector_size_p)
return success ? 0 : -errno;
}
#endif
/**
* Get physical block size of @fd.
* On success, store it in @blk_size and return 0.
@@ -1665,12 +1674,24 @@ static bool preadv_present = true;
static ssize_t
qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
{
#ifdef CONFIG_DARWIN /* preadv introduced in macOS 11 */
if (!__builtin_available(macOS 11, iOS 14, watchOS 7, tvOS 14, *)) {
preadv_present = false;
return -ENOSYS;
} else
#endif
return preadv(fd, iov, nr_iov, offset);
}
static ssize_t
qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
{
#ifdef CONFIG_DARWIN /* pwritev introduced in macOS 11 */
if (!__builtin_available(macOS 11, iOS 14, watchOS 7, tvOS 14, *)) {
preadv_present = false;
return -ENOSYS;
} else
#endif
return pwritev(fd, iov, nr_iov, offset);
}
+1 -1
View File
@@ -1008,5 +1008,5 @@ void hmp_change_medium(Monitor *mon, const char *device, const char *target,
}
qmp_blockdev_change_medium(device, NULL, target, arg, true, force,
!!read_only, read_only_mode, errp);
!!read_only, read_only_mode, false, 0, errp);
}
+22
View File
@@ -311,6 +311,8 @@ void qmp_blockdev_change_medium(const char *device,
bool has_force, bool force,
bool has_read_only,
BlockdevChangeReadOnlyMode read_only,
bool has_file_locking_mode,
BlockdevChangeFileLockingMode file_locking_mode,
Error **errp)
{
BlockBackend *blk;
@@ -362,6 +364,26 @@ void qmp_blockdev_change_medium(const char *device,
qdict_put_str(options, "driver", format);
}
if (!has_file_locking_mode) {
file_locking_mode = BLOCKDEV_CHANGE_FILE_LOCKING_MODE_AUTO;
}
switch (file_locking_mode) {
case BLOCKDEV_CHANGE_FILE_LOCKING_MODE_AUTO:
break;
case BLOCKDEV_CHANGE_FILE_LOCKING_MODE_OFF:
qdict_put_str(options, "file.locking", "off");
break;
case BLOCKDEV_CHANGE_FILE_LOCKING_MODE_ON:
qdict_put_str(options, "file.locking", "on");
break;
default:
abort();
}
medium_bs = bdrv_open(filename, NULL, options, bdrv_flags, errp);
if (!medium_bs) {
+1 -1
View File
@@ -341,7 +341,7 @@ virgl_get_resource_info_modifiers(uint32_t resource_id,
*info = info_ext.base;
*modifiers = info_ext.modifiers;
#else
ret = virgl_renderer_resource_get_info(resource_id, info);
ret = virgl_renderer_borrow_texture_for_scanout(resource_id, info);
if (ret) {
return ret;
}
+2
View File
@@ -47,6 +47,8 @@ operating system.
QEMU files related to TPM CRB interface:
- ``hw/tpm/tpm_crb.c``
- ``hw/tpm/tpm_crb_common.c``
- ``hw/tpm/tpm_crb_sysbus.c``
SPAPR interface
---------------
+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.
+7
View File
@@ -82,6 +82,13 @@ of virtio-gpu host memory window. This is typically between 256M and 8G.
.. _venus: https://gitlab.freedesktop.org/virgl/venus-protocol/
Translation via the Neptune protocol is also supported when available in
`virglrenderer`_. Like Venus, Neptune requires host blob support (``hostmem``
and ``blob`` fields) and should be enabled using the ``neptune`` field.
.. parsed-literal::
-device virtio-gpu-gl,hostmem=8G,blob=true,neptune=true
virtio-gpu rutabaga
-------------------
@@ -11,7 +11,8 @@
#ifndef HOST_ATOMIC128_CAS_H
#define HOST_ATOMIC128_CAS_H
#if defined(CONFIG_ATOMIC128)
/* FIXME: this doesn't work in TCTI */
#if defined(CONFIG_ATOMIC128) && !defined(CONFIG_TCG_THREADED_INTERPRETER)
static inline Int128 ATTRIBUTE_ATOMIC128_OPT
atomic16_cmpxchg(Int128 *ptr, Int128 cmp, Int128 new)
{
+6 -1
View File
@@ -31,6 +31,7 @@
#include "hw/pci/pci_bus.h"
#include "hw/pci/pci_bridge.h"
#include "qemu/cutils.h"
#include "qom/object.h"
static GArray *build_alloc_array(void)
{
@@ -2365,7 +2366,7 @@ void build_tpm2(GArray *table_data, BIOSLinker *linker, GArray *tcpalog,
{
uint8_t start_method_params[12] = {};
unsigned log_addr_offset;
uint64_t control_area_start_address;
uint64_t baseaddr, control_area_start_address;
TPMIf *tpmif = tpm_find();
uint32_t start_method;
AcpiTable table = { .sig = "TPM2", .rev = 4,
@@ -2383,6 +2384,10 @@ void build_tpm2(GArray *table_data, BIOSLinker *linker, GArray *tcpalog,
} else if (TPM_IS_CRB(tpmif)) {
control_area_start_address = TPM_CRB_ADDR_CTRL;
start_method = TPM2_START_METHOD_CRB;
} else if (TPM_IS_CRB_SYSBUS(tpmif)) {
baseaddr = object_property_get_uint(OBJECT(tpmif), "x-baseaddr", NULL);
control_area_start_address = baseaddr + A_CRB_CTRL_REQ;
start_method = TPM2_START_METHOD_CRB;
} else {
g_assert_not_reached();
}
+1
View File
@@ -8,6 +8,7 @@ config ARM_VIRT
imply VFIO_AMD_XGBE
imply VFIO_PLATFORM
imply VFIO_XGMAC
imply TPM_CRB_SYSBUS
imply TPM_TIS_SYSBUS
imply TPM_TIS_I2C
imply NVDIMM
+2 -36
View File
@@ -34,6 +34,7 @@
#include "hw/core/cpu.h"
#include "hw/acpi/acpi-defs.h"
#include "hw/acpi/acpi.h"
#include "hw/acpi/acpi_aml_interface.h"
#include "hw/nvram/fw_cfg_acpi.h"
#include "hw/acpi/bios-linker-loader.h"
#include "hw/acpi/aml-build.h"
@@ -168,41 +169,6 @@ static void acpi_dsdt_add_gpio(Aml *scope, const MemMapEntry *gpio_memmap,
aml_append(scope, dev);
}
#ifdef CONFIG_TPM
static void acpi_dsdt_add_tpm(Aml *scope, VirtMachineState *vms)
{
PlatformBusDevice *pbus = PLATFORM_BUS_DEVICE(vms->platform_bus_dev);
hwaddr pbus_base = vms->memmap[VIRT_PLATFORM_BUS].base;
SysBusDevice *sbdev = SYS_BUS_DEVICE(tpm_find());
MemoryRegion *sbdev_mr;
hwaddr tpm_base;
if (!sbdev) {
return;
}
tpm_base = platform_bus_get_mmio_addr(pbus, sbdev, 0);
assert(tpm_base != -1);
tpm_base += pbus_base;
sbdev_mr = sysbus_mmio_get_region(sbdev, 0);
Aml *dev = aml_device("TPM0");
aml_append(dev, aml_name_decl("_HID", aml_string("MSFT0101")));
aml_append(dev, aml_name_decl("_STR", aml_string("TPM 2.0 Device")));
aml_append(dev, aml_name_decl("_UID", aml_int(0)));
Aml *crs = aml_resource_template();
aml_append(crs,
aml_memory32_fixed(tpm_base,
(uint32_t)memory_region_size(sbdev_mr),
AML_READ_WRITE));
aml_append(dev, aml_name_decl("_CRS", crs));
aml_append(scope, dev);
}
#endif
#define ID_MAPPING_ENTRY_SIZE 20
#define SMMU_V3_ENTRY_SIZE 68
#define ROOT_COMPLEX_ENTRY_SIZE 36
@@ -862,7 +828,7 @@ build_dsdt(GArray *table_data, BIOSLinker *linker, VirtMachineState *vms)
acpi_dsdt_add_power_button(scope);
#ifdef CONFIG_TPM
acpi_dsdt_add_tpm(scope, vms);
call_dev_aml_func(DEVICE(tpm_find()), scope);
#endif
aml_append(dsdt, scope);
+106 -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;
@@ -1871,7 +1940,11 @@ static void virt_set_memmap(VirtMachineState *vms, int pa_bits)
* irrespective of the underlying capabilities of the HW.
*/
if (!vms->highmem) {
#ifdef CONFIG_DARWIN
pa_bits = 36;
#else
pa_bits = 32;
#endif
}
/*
@@ -1896,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 */
@@ -2590,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;
}
@@ -2976,6 +3063,13 @@ static void virt_machine_device_plug_cb(HotplugHandler *hotplug_dev,
vms->virtio_iommu_bdf = pci_get_bdf(pdev);
create_virtio_iommu_dt_bindings(vms);
}
#ifdef CONFIG_TPM
if (object_dynamic_cast(OBJECT(dev), TYPE_TPM_IF)) {
tpm_sysbus_plug(TPM_IF(dev), OBJECT(vms->platform_bus_dev),
vms->memmap[VIRT_PLATFORM_BUS].base);
}
#endif
}
static void virt_dimm_unplug_request(HotplugHandler *hotplug_dev,
@@ -3103,6 +3197,11 @@ static int virt_hvf_get_physical_address_range(MachineState *ms)
int default_ipa_size = hvf_arm_get_default_ipa_bit_size();
int max_ipa_size = hvf_arm_get_max_ipa_bit_size();
/* Unknown max ipa size, we'll let the caller figure it out */
if (max_ipa_size == 0) {
return 0;
}
/* We freeze the memory map to compute the highest gpa */
virt_set_memmap(vms, max_ipa_size);
@@ -3173,6 +3272,7 @@ static void virt_machine_class_init(ObjectClass *oc, void *data)
machine_class_allow_dynamic_sysbus_dev(mc, TYPE_UEFI_VARS_SYSBUS);
#ifdef CONFIG_TPM
machine_class_allow_dynamic_sysbus_dev(mc, TYPE_TPM_TIS_SYSBUS);
machine_class_allow_dynamic_sysbus_dev(mc, TYPE_TPM_CRB_SYSBUS);
#endif
mc->block_default_type = IF_VIRTIO;
mc->no_cdrom = 1;
+6
View File
@@ -55,3 +55,9 @@ config VIRTIO_SND
bool
default y
depends on VIRTIO
config MARVELL_88W8618
bool
config SCREAMER
bool
+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)
+1
View File
@@ -11,6 +11,7 @@ system_ss.add(when: 'CONFIG_MARVELL_88W8618', if_true: files('marvell_88w8618.c'
system_ss.add(when: 'CONFIG_PCSPK', if_true: files('pcspk.c'))
system_ss.add(when: 'CONFIG_PL041', if_true: files('pl041.c', 'lm4549.c'))
system_ss.add(when: 'CONFIG_SB16', if_true: files('sb16.c'))
system_ss.add(when: 'CONFIG_SCREAMER', if_true: files('screamer.c'))
system_ss.add(when: 'CONFIG_VT82C686', if_true: files('via-ac97.c'))
system_ss.add(when: 'CONFIG_WM8750', if_true: files('wm8750.c'))
system_ss.add(when: ['CONFIG_VIRTIO_SND', 'CONFIG_VIRTIO'], if_true: files('virtio-snd.c'))
+595
View File
@@ -0,0 +1,595 @@
/*
* QEMU PowerMac Awacs Screamer device support
*
* Copyright (c) 2016 Mark Cave-Ayland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "qemu/osdep.h"
#include "audio/audio.h"
#include "hw/hw.h"
#include "hw/irq.h"
#include "audio/audio.h"
#include "hw/audio/screamer.h"
#include "hw/qdev-properties.h"
#include "qemu/timer.h"
#include "hw/ppc/mac_dbdma.h"
#include "system/system.h"
#include "qemu/cutils.h"
#include "qemu/log.h"
#include "qemu/typedefs.h"
/* debug screamer */
//#define DEBUG_SCREAMER
#ifdef DEBUG_SCREAMER
#define SCREAMER_DPRINTF(fmt, ...) \
do { printf("SCREAMER: " fmt , ## __VA_ARGS__); } while (0)
#else
#define SCREAMER_DPRINTF(fmt, ...)
#endif
/* chip registers */
#define SND_CTRL_REG 0x0
#define CODEC_CTRL_REG 0x1
#define CODEC_STAT_REG 0x2
#define CLIP_CNT_REG 0x3
#define BYTE_SWAP_REG 0x4
#define FRAME_CNT_REG 0x5
#define CODEC_CTRL_MASKECMD (0x1 << 24)
#define CODEC_CTRL1_RECALIBRATE 0x4
#define CODEC_STAT_MANUFACTURER_CRYSTAL 0x100
#define CODEC_STAT_AWACS_REVISION 0x3000
#define CODEC_STAT_MASK_VALID (0x1 << 22)
/* Audio */
static const char *s_spk = "screamer";
/*
* 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;
uint32_t frames;
screamer_tx_credit_update(s, limit);
frames = MIN(io->len >> s->shift, s->tx_credit);
if (frames) {
screamer_ring_write(s, io->addr, frames);
io->addr += frames << s->shift;
io->len -= frames << s->shift;
s->tx_credit -= frames;
/* 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);
}
}
static void pmac_screamer_tx(DBDMA_io *io)
{
ScreamerState *s = io->opaque;
SCREAMER_DPRINTF("DMA TX transfer: addr %" HWADDR_PRIx
" len: %x\n", io->addr, io->len);
memcpy(&s->io, io, sizeof(DBDMA_io));
/* 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;
SCREAMER_DPRINTF("DMA TX flush!\n");
#if 0
cmd = le16_to_cpu(current->command) & COMMAND_MASK;
if (cmd == OUTPUT_MORE || cmd == OUTPUT_LAST ||
cmd == INPUT_MORE || cmd == INPUT_LAST) {
screamer_dma_update_status(ch, io->len);
}
#endif
/*
* 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) {
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);
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) {
screamer_dma_update_status(ch, io->len);
}
#endif
}
void macio_screamer_register_dma(ScreamerState *s, void *dbdma, int txchannel, int rxchannel)
{
s->dbdma = dbdma;
DBDMA_register_channel(dbdma, txchannel, s->dma_tx_irq,
pmac_screamer_tx, pmac_screamer_tx_flush, s);
DBDMA_register_channel(dbdma, rxchannel, s->dma_rx_irq,
pmac_screamer_rx, pmac_screamer_rx_flush, s);
}
static void screamerspk_callback(void *opaque, int free_b)
{
ScreamerState *s = opaque;
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;
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;
}
}
static void screamer_update_settings(ScreamerState *s)
{
struct audsettings as = { s->rate, 2, AUDIO_FORMAT_S16,
1 };
s->voice = AUD_open_out(&s->card, s->voice, s_spk, s, screamerspk_callback, &as);
if (!s->voice) {
AUD_log(s_spk, "Could not open voice\n");
return;
}
AUD_set_active_out(s->voice, true);
}
static void screamer_update_volume(ScreamerState *s)
{
uint8_t muted = s->codec_ctrl_regs[0x1] & 0x80 ? 1 : 0;
uint8_t att_left = (s->codec_ctrl_regs[0x4] & 0xf);
uint8_t att_right = (s->codec_ctrl_regs[0x4] & 0x3c0) >> 6;
SCREAMER_DPRINTF("setting mute: %d, attenuation L: %d R: %d\n",
muted, att_left, att_right);
AUD_set_volume_out(s->voice, muted, (0xf - att_left) << 4,
(0xf - att_right) << 4);
}
static void screamer_reset(DeviceState *dev)
{
ScreamerState *s = SCREAMER(dev);
memset(s->regs, 0, sizeof(s->regs));
memset(s->codec_ctrl_regs, 0, sizeof(s->codec_ctrl_regs));
memset(&s->io, 0, sizeof(DBDMA_io));
s->rate = 44100;
screamer_update_settings(s);
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;
}
static void screamer_realizefn(DeviceState *dev, Error **errp)
{
ScreamerState *s = SCREAMER(dev);
if (!AUD_register_card(s_spk, &s->card, 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);
}
static void screamer_control_write(ScreamerState *s, uint32_t val)
{
SCREAMER_DPRINTF("%s: val %" PRId32 "\n", __func__, val);
/* Basic rate selection */
switch ((val & 0x700) >> 8) {
case 0x00:
s->rate = 44100;
break;
case 0x1:
s->rate = 29400;
break;
case 0x2:
s->rate = 22050;
break;
case 0x3:
s->rate = 17640;
break;
case 0x4:
s->rate = 14700;
break;
case 0x5:
s->rate = 11025;
break;
case 0x6:
s->rate = 8820;
break;
case 0x7:
s->rate = 7350;
break;
}
SCREAMER_DPRINTF("basic rate: %d\n", s->rate);
screamer_update_settings(s);
s->regs[0] = val;
}
static void screamer_codec_write(ScreamerState *s, hwaddr addr, uint64_t val)
{
//SCREAMER_DPRINTF("%s: addr " HWADDR_PRIx " val %" PRIx64 "\n", __func__, addr, val);
switch (addr) {
case 0x1:
/* Clear recalibrate if set */
val = val & ~CODEC_CTRL1_RECALIBRATE;
/* Update volume in case mute set */
screamer_update_volume(s);
break;
case 0x4:
/* Speaker attenuation */
screamer_update_volume(s);
break;
}
s->codec_ctrl_regs[addr] = val;
}
static uint64_t screamer_read(void *opaque, hwaddr addr, unsigned size)
{
ScreamerState *s = opaque;
uint32_t val;
addr = addr >> 4;
switch (addr) {
case SND_CTRL_REG:
val = s->regs[addr];
break;
case CODEC_CTRL_REG:
val = s->regs[addr] & ~CODEC_CTRL_MASKECMD;
break;
case CODEC_STAT_REG:
if (s->codec_ctrl_regs[7] & 1) {
/* Read back mode */
val = s->codec_ctrl_regs[(s->codec_ctrl_regs[7] >> 1) & 0xe];
} else {
/* Return status register */
val = s->regs[addr] & ~0xff00;
val |= CODEC_STAT_MANUFACTURER_CRYSTAL | CODEC_STAT_AWACS_REVISION |
CODEC_STAT_MASK_VALID;
}
break;
case CLIP_CNT_REG:
case BYTE_SWAP_REG:
case FRAME_CNT_REG:
val = s->regs[addr];
break;
default:
qemu_log_mask(LOG_UNIMP,
"screamer: Unimplemented register read "
"reg 0x%" HWADDR_PRIx " size 0x%x\n",
addr, size);
val = 0;
break;
}
SCREAMER_DPRINTF("%s: addr " HWADDR_FMT_plx " -> %x\n", __func__, addr, val);
return val;
}
static void screamer_write(void *opaque, hwaddr addr,
uint64_t val, unsigned size)
{
ScreamerState *s = opaque;
uint32_t codec_addr;
addr = addr >> 4;
SCREAMER_DPRINTF("%s: addr " HWADDR_FMT_plx " val %" PRIx64 "\n", __func__, addr, val);
switch (addr) {
case SND_CTRL_REG:
screamer_control_write(s, val & 0xffffffff);
break;
case CODEC_CTRL_REG:
s->regs[addr] = val & 0xffffffff;
codec_addr = (val & 0x7fff) >> 12;
screamer_codec_write(s, codec_addr, val & 0xfff);
break;
case CODEC_STAT_REG:
case CLIP_CNT_REG:
case BYTE_SWAP_REG:
s->regs[addr] = val & 0xffffffff;
break;
default:
qemu_log_mask(LOG_UNIMP,
"screamer: Unimplemented register write "
"reg 0x%" HWADDR_PRIx " size 0x%x value 0x%" PRIx64 "\n",
addr, size, val);
break;
}
return;
}
static const MemoryRegionOps screamer_ops = {
.read = screamer_read,
.write = screamer_write,
.endianness = DEVICE_LITTLE_ENDIAN,
.valid = {
.min_access_size = 4,
.max_access_size = 4,
}
};
static void screamer_initfn(Object *obj)
{
SysBusDevice *d = SYS_BUS_DEVICE(obj);
ScreamerState *s = SCREAMER(obj);
memory_region_init_io(&s->mem, obj, &screamer_ops, s, "screamer", 0x1000);
sysbus_init_mmio(d, &s->mem);
sysbus_init_irq(d, &s->irq);
sysbus_init_irq(d, &s->dma_tx_irq);
sysbus_init_irq(d, &s->dma_rx_irq);
}
static const Property screamer_properties[] = {
DEFINE_AUDIO_PROPERTIES(ScreamerState, card),
};
static void screamer_class_init(ObjectClass *oc, void *data)
{
DeviceClass *dc = DEVICE_CLASS(oc);
dc->realize = screamer_realizefn;
device_class_set_legacy_reset(dc, screamer_reset);
device_class_set_props(dc, screamer_properties);
}
static const TypeInfo screamer_type_info = {
.name = TYPE_SCREAMER,
.parent = TYPE_SYS_BUS_DEVICE,
.instance_size = sizeof(ScreamerState),
.instance_init = screamer_initfn,
.class_init = screamer_class_init,
};
static void screamer_register_types(void)
{
type_register_static(&screamer_type_info);
}
type_init(screamer_register_types)
+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"
+1
View File
@@ -94,6 +94,7 @@ GlobalProperty hw_compat_7_2[] = {
{ "virtio-mem", "x-early-migration", "false" },
{ "migration", "x-preempt-pre-7-2", "true" },
{ TYPE_PCI_DEVICE, "x-pcie-err-unc-mask", "off" },
{ "arm-gicv3-its", "itt-entry-size", "12" },
};
const size_t hw_compat_7_2_len = G_N_ELEMENTS(hw_compat_7_2);
+1
View File
@@ -516,6 +516,7 @@ static const BindingEntry bindings[] = {
#endif
#ifdef CONFIG_TPM
TYPE_BINDING(TYPE_TPM_TIS_SYSBUS, add_tpm_tis_fdt_node),
TYPE_BINDING(TYPE_TPM_CRB_SYSBUS, add_tpm_tis_fdt_node),
#endif
TYPE_BINDING(TYPE_RAMFB_DEVICE, no_fdt_node),
TYPE_BINDING(TYPE_UEFI_VARS_SYSBUS, add_uefi_vars_node),
+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) {
+10
View File
@@ -91,6 +91,16 @@ if config_all_devices.has_key('CONFIG_VIRTIO_GPU')
endif
endif
if config_all_devices.has_key('CONFIG_FW_CFG_DMA')
virtio_ramfb_ss = ss.source_set()
virtio_ramfb_ss.add(when: 'CONFIG_FW_CFG_DMA', if_true: files('virtio-ramfb.c'))
hw_display_modules += {'virtio-ramfb': virtio_ramfb_ss}
virtio_ramfb_gl_ss = ss.source_set()
virtio_ramfb_gl_ss.add(when: ['CONFIG_FW_CFG_DMA', virgl, opengl],
if_true: files('virtio-ramfb-gl.c'))
hw_display_modules += {'virtio-ramfb-gl': virtio_ramfb_gl_ss}
endif
if config_all_devices.has_key('CONFIG_VIRTIO_PCI')
virtio_gpu_pci_ss = ss.source_set()
virtio_gpu_pci_ss.add(when: ['CONFIG_VIRTIO_GPU', 'CONFIG_VIRTIO_PCI'],
+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);
}
+9 -3
View File
@@ -90,9 +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;
virtio_gpu_ctrl_cmd_init(cmd, vq);
QTAILQ_INSERT_TAIL(&g->cmdq, cmd, next);
cmd = virtqueue_pop(vq, sizeof(struct virtio_gpu_ctrl_command));
}
@@ -159,6 +157,8 @@ static const Property virtio_gpu_gl_properties[] = {
VIRTIO_GPU_FLAG_STATS_ENABLED, false),
DEFINE_PROP_BIT("venus", VirtIOGPU, parent_obj.conf.flags,
VIRTIO_GPU_FLAG_VENUS_ENABLED, false),
DEFINE_PROP_BIT("neptune", VirtIOGPU, parent_obj.conf.flags,
VIRTIO_GPU_FLAG_NEPTUNE_ENABLED, false),
};
static void virtio_gpu_gl_device_unrealize(DeviceState *qdev)
@@ -169,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);
@@ -193,6 +198,7 @@ static void virtio_gpu_gl_class_init(ObjectClass *klass, void *data)
vgc->handle_ctrl = virtio_gpu_gl_handle_ctrl;
vgc->process_cmd = virtio_gpu_virgl_process_cmd;
vgc->update_cursor_data = virtio_gpu_gl_update_cursor_data;
vgc->resource_destroy = virtio_gpu_virgl_resource_destroy;
vdc->realize = virtio_gpu_gl_device_realize;
vdc->unrealize = virtio_gpu_gl_device_unrealize;
+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));
}
+51 -8
View File
@@ -188,11 +188,38 @@ static VGPUDMABuf
qemu_pixman_to_drm_format(fb->format),
0, res->dmabuf_fd, true, false);
dmabuf->scanout_id = scanout_id;
/* Remember the request identity so a later identical present can reuse
* this dmabuf + its EGL import instead of re-creating it. */
dmabuf->src_fd = res->dmabuf_fd;
dmabuf->src_res_id = res->resource_id;
dmabuf->src_w = r->width;
dmabuf->src_h = r->height;
dmabuf->src_x = r->x;
dmabuf->src_y = r->y;
dmabuf->fb_w = fb->width;
dmabuf->fb_h = fb->height;
dmabuf->fb_stride = fb->stride;
dmabuf->fb_format = fb->format;
QTAILQ_INSERT_HEAD(&g->dmabuf.bufs, dmabuf, next);
return dmabuf;
}
static bool virtio_gpu_dmabuf_matches(const VGPUDMABuf *d,
uint32_t scanout_id,
const struct virtio_gpu_simple_resource *res,
const struct virtio_gpu_framebuffer *fb,
const struct virtio_gpu_rect *r)
{
return d->scanout_id == scanout_id &&
d->src_fd == res->dmabuf_fd &&
d->src_res_id == res->resource_id &&
d->src_w == r->width && d->src_h == r->height &&
d->src_x == r->x && d->src_y == r->y &&
d->fb_w == fb->width && d->fb_h == fb->height &&
d->fb_stride == fb->stride && d->fb_format == fb->format;
}
int virtio_gpu_update_dmabuf(VirtIOGPU *g,
uint32_t scanout_id,
struct virtio_gpu_simple_resource *res,
@@ -200,27 +227,43 @@ int virtio_gpu_update_dmabuf(VirtIOGPU *g,
struct virtio_gpu_rect *r)
{
struct virtio_gpu_scanout *scanout = &g->parent_obj.scanout[scanout_id];
VGPUDMABuf *new_primary, *old_primary = NULL;
VGPUDMABuf *primary = g->dmabuf.primary[scanout_id];
VGPUDMABuf *new_primary;
uint32_t width, height;
/* Identical re-present of the displayed buffer: only refresh content.
* The flip-model guest re-presents at ~60 Hz; re-importing every time
* churns GL state on the display thread and hangs the UI. */
if (primary && virtio_gpu_dmabuf_matches(primary, scanout_id, res, fb, r)) {
return 0;
}
/* A different buffer (flip chain) or new geometry: import fresh. The
* import must be fresh per switch -- a cached EGL import sampled while
* the guest GPU re-renders that buffer draws torn/stale content under
* present storms (cursor movement). The historically expensive part
* of this path was the unconditional console resize, not the import;
* only resize when the dimensions actually change. */
new_primary = virtio_gpu_create_dmabuf(g, scanout_id, res, fb, r);
if (!new_primary) {
return -EINVAL;
}
if (g->dmabuf.primary[scanout_id]) {
old_primary = g->dmabuf.primary[scanout_id];
}
width = qemu_dmabuf_get_width(new_primary->buf);
height = qemu_dmabuf_get_height(new_primary->buf);
g->dmabuf.primary[scanout_id] = new_primary;
qemu_console_resize(scanout->con, width, height);
if (!primary ||
qemu_dmabuf_get_width(primary->buf) != width ||
qemu_dmabuf_get_height(primary->buf) != height) {
qemu_console_resize(scanout->con, width, height);
}
dpy_gl_scanout_dmabuf(scanout->con, new_primary->buf);
if (old_primary) {
virtio_gpu_free_dmabuf(g, old_primary);
if (primary) {
virtio_gpu_free_dmabuf(g, primary);
}
return 0;
}
+623 -73
View File
@@ -22,11 +22,37 @@
#include "ui/egl-helpers.h"
#define VIRGL_RENDERER_UNSTABLE_APIS
#include <virglrenderer.h>
#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 *
@@ -42,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)
@@ -55,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"
@@ -69,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) {
@@ -94,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);
}
@@ -150,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);
@@ -161,60 +276,139 @@ 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
virtio_gpu_virgl_destroy_hostmem_region(VirtIOGPU *g,
struct virtio_gpu_virgl_resource *res)
{
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
* 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; 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 (vmr->unmapping) {
/* Async unmap detached the subregion; let the finalizer free vmr. */
OBJECT(vmr)->free = g_free;
vmr->g = NULL;
res->mr = NULL;
return;
}
/* No unmap in flight; tear down here and neutralize the finalizer. */
OBJECT(vmr)->free = g_free;
vmr->g = NULL;
memory_region_set_enabled(res->mr, false);
memory_region_del_subregion(&b->hostmem, res->mr);
object_unparent(OBJECT(vmr));
res->mr = NULL;
virgl_renderer_resource_unmap(res->base.resource_id);
}
#endif
void virtio_gpu_virgl_resource_destroy(VirtIOGPU *g,
struct virtio_gpu_simple_resource *res,
Error **errp)
{
struct virtio_gpu_virgl_resource *vres =
container_of(res, struct virtio_gpu_virgl_resource, base);
struct iovec *res_iovs = NULL;
int num_iovs = 0;
#if VIRGL_VERSION_MAJOR >= 1
if (vres->mr) {
virtio_gpu_virgl_destroy_hostmem_region(g, vres);
}
#endif
virgl_renderer_resource_detach_iov(res->resource_id, &res_iovs, &num_iovs);
if (res_iovs && num_iovs) {
virtio_gpu_cleanup_mapping_iov(g, res_iovs, num_iovs);
}
/* The detached iov is the same allocation virgl took at attach time;
* clear res->iov so the base destroy does not free it again. */
res->iov = NULL;
res->iov_cnt = 0;
virgl_renderer_resource_unref(res->resource_id);
virtio_gpu_resource_destroy(g, res, errp);
}
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;
@@ -233,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;
@@ -262,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;
@@ -281,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;
@@ -330,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
@@ -436,19 +647,45 @@ 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;
void *d3d_tex2d = NULL;
ScanoutTextureNative native = NO_NATIVE_TEXTURE;
#if VIRGL_VERSION_MAJOR >= 1
struct virgl_renderer_resource_info_ext ext;
memset(&ext, 0, sizeof(ext));
ret = virgl_renderer_resource_get_info_ext(ss.resource_id, &ext);
info = ext.base;
d3d_tex2d = ext.d3d_tex2d;
#else
/* fallback to older version */
native = (ScanoutTextureNative){
.type = ext.d3d_tex2d ? SCANOUT_TEXTURE_NATIVE_TYPE_D3D :
SCANOUT_TEXTURE_NATIVE_TYPE_NONE,
.handle = ext.d3d_tex2d,
};
#if VIRGL_RENDERER_RESOURCE_INFO_EXT_VERSION >= NATIVE_HANDLE_SUPPORT_VERSION
if (ext.version >= VIRGL_RENDERER_RESOURCE_INFO_EXT_VERSION) {
switch (ext.native_type) {
#ifdef CONFIG_METAL
case VIRGL_NATIVE_HANDLE_METAL_TEXTURE: {
native.type = SCANOUT_TEXTURE_NATIVE_TYPE_METAL;
native.handle = ext.native_handle;
break;
}
#endif
case VIRGL_NATIVE_HANDLE_NONE:
case VIRGL_NATIVE_HANDLE_D3D_TEX2D: {
/* already handled above */
break;
}
default: {
/* ignore unsupported hint texture type */
break;
}
}
}
#endif
#else /* VIRGL_VERSION_MAJOR < 1 */
memset(&info, 0, sizeof(info));
ret = virgl_renderer_resource_get_info(ss.resource_id, &info);
#endif
@@ -459,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();
@@ -467,8 +705,14 @@ static void virgl_cmd_set_scanout(VirtIOGPU *g,
info.flags & VIRTIO_GPU_RESOURCE_FLAG_Y_0_TOP,
info.width, info.height,
ss.r.x, ss.r.y, ss.r.width, ss.r.height,
d3d_tex2d);
} else {
native, NULL);
} 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);
@@ -692,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;
@@ -716,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);
@@ -775,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;
@@ -793,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;
@@ -806,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);
@@ -824,13 +1107,76 @@ 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)
static void virgl_scanout_native_blob_cleanup(ScanoutTextureNative *native)
{
assert(native->type == SCANOUT_TEXTURE_NATIVE_TYPE_METAL);
virgl_renderer_release_handle_for_scanout(VIRGL_NATIVE_HANDLE_METAL_TEXTURE,
native->handle);
}
static bool virgl_scanout_native_blob(VirtIOGPU *g,
struct virtio_gpu_set_scanout_blob *ss)
{
struct virtio_gpu_scanout *scanout = &g->parent_obj.scanout[ss->scanout_id];
enum virgl_renderer_native_handle_type type;
virgl_renderer_native_handle handle;
ScanoutTextureNative native;
type = virgl_renderer_create_handle_for_scanout(ss->resource_id,
ss->width,
ss->height,
ss->format,
ss->padding,
ss->strides[0],
ss->offsets[0],
&handle);
#ifdef CONFIG_METAL
if (type == VIRGL_NATIVE_HANDLE_METAL_TEXTURE) {
native = (ScanoutTextureNative){
.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(
scanout->con, 0,
false,
ss->width, ss->height,
ss->r.x, ss->r.y, ss->r.width, ss->r.height,
native, virgl_scanout_native_blob_cleanup);
scanout->resource_id = ss->resource_id;
return true;
}
#endif
/* don't leak memory if handle type is unknown */
if (type != VIRGL_NATIVE_HANDLE_NONE) {
virgl_renderer_release_handle_for_scanout(type, handle);
}
return false;
}
#endif
static void virgl_cmd_set_scanout_blob(VirtIOGPU *g,
struct virtio_gpu_ctrl_command *cmd)
{
@@ -856,8 +1202,14 @@ static void virgl_cmd_set_scanout_blob(VirtIOGPU *g,
return;
}
/* The scanout rect sizes the displaysurface (virtio_gpu_update_dmabuf
* resizes the console to r.width x r.height, and a zero-area surface
* aborts in qemu_memfd_alloc), so bound the rect exactly like
* virtio_gpu_do_set_scanout does for non-blob scanouts. */
if (ss.width < 16 ||
ss.height < 16 ||
ss.r.width < 16 ||
ss.r.height < 16 ||
ss.r.x + ss.r.width > ss.width ||
ss.r.y + ss.r.height > ss.height) {
qemu_log_mask(LOG_GUEST_ERROR, "%s: illegal scanout %d bounds for"
@@ -869,6 +1221,12 @@ static void virgl_cmd_set_scanout_blob(VirtIOGPU *g,
return;
}
#if defined(HAVE_VIRGL_RENDERER_NATIVE_SCANOUT)
if (virgl_scanout_native_blob(g, &ss)) {
return;
}
#endif
res = virtio_gpu_virgl_find_resource(g, ss.resource_id);
if (!res) {
qemu_log_mask(LOG_GUEST_ERROR, "%s: resource does not exist %d\n",
@@ -916,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);
@@ -970,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);
@@ -987,7 +1345,9 @@ void virtio_gpu_virgl_process_cmd(VirtIOGPU *g,
break;
}
if (cmd_suspended || cmd->finished) {
cmd->suspended = cmd_suspended;
if (cmd_suspended || cmd->finished || cmd->deferred) {
return;
}
if (cmd->error) {
@@ -1004,10 +1364,27 @@ void virtio_gpu_virgl_process_cmd(VirtIOGPU *g,
trace_virtio_gpu_fence_ctrl(cmd->cmd_hdr.fence_id, cmd->cmd_hdr.type);
#if VIRGL_VERSION_MAJOR >= 1
if (cmd->cmd_hdr.flags & VIRTIO_GPU_FLAG_INFO_RING_IDX) {
virgl_renderer_context_create_fence(cmd->cmd_hdr.ctx_id,
int ret = virgl_renderer_context_create_fence(cmd->cmd_hdr.ctx_id,
VIRGL_RENDERER_FENCE_FLAG_MERGEABLE,
cmd->cmd_hdr.ring_idx,
cmd->cmd_hdr.fence_id);
if (ret) {
/*
* The renderer context is gone (e.g. its render-server
* worker died mid-teardown): this fence can never retire
* through the timeline. Complete it now — the cmd is not
* yet on fenceq, so responding here both signals the fence
* to the guest and keeps it off the queue. Leaving it
* pending wedges the guest's GPU scheduler (VIDEO_TDR_
* FAILURE bugcheck on Windows).
*/
fprintf(stderr,
"%s: create_fence failed (%d) for dead ctx %u; "
"retiring fence %" PRIu64 " immediately\n",
__func__, ret, cmd->cmd_hdr.ctx_id,
(uint64_t)cmd->cmd_hdr.fence_id);
virtio_gpu_ctrl_response_nodata(g, cmd, VIRTIO_GPU_RESP_OK_NODATA);
}
return;
}
#endif
@@ -1066,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)
@@ -1143,7 +1606,39 @@ static void virtio_gpu_fence_poll(void *opaque)
virgl_renderer_poll();
virtio_gpu_process_cmdq(g);
if (!QTAILQ_EMPTY(&g->cmdq) || !QTAILQ_EMPTY(&g->fenceq)) {
timer_mod(gl->fence_poll, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + 10);
/*
* 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.
*/
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);
}
}
@@ -1165,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)
@@ -1177,16 +1674,52 @@ 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
#ifdef VIRGL_RENDERER_D3D11_SHARE_TEXTURE
if (qemu_egl_angle_d3d) {
if (qemu_egl_angle_native_device) {
#if defined(VIRGL_RENDERER_NATIVE_SHARE_TEXTURE)
flags |= VIRGL_RENDERER_NATIVE_SHARE_TEXTURE;
#elif defined(VIRGL_RENDERER_D3D11_SHARE_TEXTURE) && defined(WIN32)
flags |= VIRGL_RENDERER_D3D11_SHARE_TEXTURE;
}
#endif
}
#if VIRGL_VERSION_MAJOR >= 1
if (virtio_gpu_venus_enabled(g->parent_obj.conf)) {
flags |= VIRGL_RENDERER_VENUS | VIRGL_RENDERER_RENDER_SERVER;
flags |= VIRGL_RENDERER_VENUS;
flags |= VIRGL_RENDERER_RENDER_SERVER;
}
#endif
#ifdef VIRGL_RENDERER_NEPTUNE
if (virtio_gpu_neptune_enabled(g->parent_obj.conf)) {
flags |= VIRGL_RENDERER_NEPTUNE;
flags |= VIRGL_RENDERER_RENDER_SERVER;
}
#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
@@ -1207,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;
@@ -1246,5 +1785,16 @@ GArray *virtio_gpu_virgl_get_capsets(VirtIOGPU *g)
}
}
#ifdef VIRGL_RENDERER_NEPTUNE
if (virtio_gpu_neptune_enabled(g->parent_obj.conf)) {
virgl_renderer_get_cap_set(VIRTIO_GPU_CAPSET_NEPTUNE,
&capset_max_ver,
&capset_max_size);
if (capset_max_size) {
virtio_gpu_virgl_add_capset(capset_ids, VIRTIO_GPU_CAPSET_NEPTUNE);
}
}
#endif
return capset_ids;
}
+103 -10
View File
@@ -393,9 +393,9 @@ void virtio_gpu_disable_scanout(VirtIOGPU *g, int scanout_id)
scanout->height = 0;
}
static void virtio_gpu_resource_destroy(VirtIOGPU *g,
struct virtio_gpu_simple_resource *res,
Error **errp)
void virtio_gpu_resource_destroy(VirtIOGPU *g,
struct virtio_gpu_simple_resource *res,
Error **errp)
{
int i;
@@ -1061,8 +1061,23 @@ void virtio_gpu_process_cmdq(VirtIOGPU *g)
/* process command */
vgc->process_cmd(g, cmd);
/* command suspended */
if (!cmd->finished && !(cmd->cmd_hdr.flags & VIRTIO_GPU_FLAG_FENCE)) {
/*
* 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
* must not be moved to fenceq like a normal in-flight fence.
*/
if (cmd->suspended ||
(!cmd->finished && !(cmd->cmd_hdr.flags & VIRTIO_GPU_FLAG_FENCE))) {
trace_virtio_gpu_cmd_suspended(cmd->cmd_hdr.type);
break;
}
@@ -1123,9 +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;
virtio_gpu_ctrl_cmd_init(cmd, vq);
QTAILQ_INSERT_TAIL(&g->cmdq, cmd, next);
cmd = virtqueue_pop(vq, sizeof(struct virtio_gpu_ctrl_command));
}
@@ -1503,12 +1516,22 @@ void virtio_gpu_device_realize(DeviceState *qdev, Error **errp)
{
VirtIODevice *vdev = VIRTIO_DEVICE(qdev);
VirtIOGPU *g = VIRTIO_GPU(qdev);
bool have_ext_memory;
if (virtio_gpu_blob_enabled(g->parent_obj.conf)) {
#ifdef CONFIG_METAL
have_ext_memory = virtio_gpu_venus_enabled(g->parent_obj.conf);
#ifdef HAVE_VIRGL_RENDERER_NEPTUNE
have_ext_memory = have_ext_memory ||
virtio_gpu_neptune_enabled(g->parent_obj.conf);
#endif
#else
have_ext_memory = virtio_gpu_have_udmabuf();
#endif
if (!virtio_gpu_rutabaga_enabled(g->parent_obj.conf) &&
!virtio_gpu_virgl_enabled(g->parent_obj.conf) &&
!virtio_gpu_have_udmabuf()) {
error_setg(errp, "need rutabaga or udmabuf for blob resources");
!have_ext_memory) {
error_setg(errp, "need rutabaga or ext memory for blob resources");
return;
}
@@ -1537,6 +1560,19 @@ void virtio_gpu_device_realize(DeviceState *qdev, Error **errp)
#endif
}
if (virtio_gpu_neptune_enabled(g->parent_obj.conf)) {
#ifdef HAVE_VIRGL_RENDERER_NEPTUNE
if (!virtio_gpu_blob_enabled(g->parent_obj.conf) ||
!virtio_gpu_hostmem_enabled(g->parent_obj.conf)) {
error_setg(errp, "neptune requires enabled blob and hostmem options");
return;
}
#else
error_setg(errp, "virglrenderer does not support neptune");
return;
#endif
}
if (!virtio_gpu_base_device_realize(qdev,
virtio_gpu_handle_ctrl_cb,
virtio_gpu_handle_cursor_cb,
@@ -1597,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);
+50
View File
@@ -0,0 +1,50 @@
#include "qemu/osdep.h"
#include "hw/pci/pci.h"
#include "hw/qdev-properties.h"
#include "hw/virtio/virtio-gpu.h"
#include "hw/display/vga.h"
#include "qapi/error.h"
#include "qemu/module.h"
#include "virtio-ramfb.h"
#include "qom/object.h"
#define TYPE_VIRTIO_RAMFB_GL "virtio-ramfb-gl"
typedef struct VirtIORAMFBGL VirtIORAMFBGL;
DECLARE_INSTANCE_CHECKER(VirtIORAMFBGL, VIRTIO_RAMFB_GL,
TYPE_VIRTIO_RAMFB_GL)
struct VirtIORAMFBGL {
VirtIORAMFBBase parent_obj;
VirtIOGPUGL vdev;
};
static void virtio_ramfb_gl_inst_initfn(Object *obj)
{
VirtIORAMFBGL *dev = VIRTIO_RAMFB_GL(obj);
virtio_instance_init_common(obj, &dev->vdev, sizeof(dev->vdev),
TYPE_VIRTIO_GPU_GL);
VIRTIO_RAMFB_BASE(dev)->vgpu = VIRTIO_GPU_BASE(&dev->vdev);
}
static VirtioPCIDeviceTypeInfo virtio_ramfb_gl_info = {
.generic_name = TYPE_VIRTIO_RAMFB_GL,
.parent = TYPE_VIRTIO_RAMFB_BASE,
.instance_size = sizeof(VirtIORAMFBGL),
.instance_init = virtio_ramfb_gl_inst_initfn,
};
module_obj(TYPE_VIRTIO_RAMFB_GL);
static void virtio_ramfb_register_types(void)
{
if (have_vga) {
virtio_pci_types_register(&virtio_ramfb_gl_info);
}
}
type_init(virtio_ramfb_register_types)
module_dep("hw-display-virtio-ramfb");
+208
View File
@@ -0,0 +1,208 @@
#include "qemu/osdep.h"
#include "system/system.h"
#include "hw/pci/pci.h"
#include "ui/console.h"
#include "hw/qdev-properties.h"
#include "virtio-ramfb.h"
#include "qapi/error.h"
#include "qom/object.h"
static int virtio_ramfb_get_flags(void *opaque)
{
VirtIORAMFBBase *vramfb = opaque;
VirtIOGPUBase *g = vramfb->vgpu;
if (g->hw_ops->get_flags) {
return g->hw_ops->get_flags(g);
} else {
return 0;
}
}
static void virtio_ramfb_invalidate_display(void *opaque)
{
VirtIORAMFBBase *vramfb = opaque;
VirtIOGPUBase *g = vramfb->vgpu;
if (g->enable) {
g->hw_ops->invalidate(g);
}
}
static void virtio_ramfb_text_update(void *opaque, console_ch_t *chardata)
{
VirtIORAMFBBase *vramfb = opaque;
VirtIOGPUBase *g = vramfb->vgpu;
if (g->hw_ops->text_update) {
g->hw_ops->text_update(g, chardata);
}
}
static void virtio_ramfb_update_display(void *opaque)
{
VirtIORAMFBBase *vramfb = opaque;
VirtIOGPUBase *g = vramfb->vgpu;
if (g->enable) {
g->hw_ops->gfx_update(g);
} else {
ramfb_display_update(g->scanout[0].con, vramfb->ramfb);
}
}
static void virtio_ramfb_ui_info(void *opaque, uint32_t idx, QemuUIInfo *info)
{
VirtIORAMFBBase *vramfb = opaque;
VirtIOGPUBase *g = vramfb->vgpu;
if (g->hw_ops->ui_info) {
g->hw_ops->ui_info(g, idx, info);
}
}
static void virtio_ramfb_gl_block(void *opaque, bool block)
{
VirtIORAMFBBase *vramfb = opaque;
VirtIOGPUBase *g = vramfb->vgpu;
if (g->hw_ops->gl_block) {
g->hw_ops->gl_block(g, block);
}
}
static const GraphicHwOps virtio_ramfb_ops = {
.get_flags = virtio_ramfb_get_flags,
.invalidate = virtio_ramfb_invalidate_display,
.gfx_update = virtio_ramfb_update_display,
.text_update = virtio_ramfb_text_update,
.ui_info = virtio_ramfb_ui_info,
.gl_block = virtio_ramfb_gl_block,
};
static const VMStateDescription vmstate_virtio_ramfb = {
.name = "virtio-ramfb",
.version_id = 2,
.minimum_version_id = 2,
.fields = (VMStateField[]) {
/* no pci stuff here, saving the virtio device will handle that */
/* FIXME */
VMSTATE_END_OF_LIST()
}
};
/* RAMFB device wrapper around PCI device around virtio GPU */
static void virtio_ramfb_realize(VirtIOPCIProxy *vpci_dev, Error **errp)
{
VirtIORAMFBBase *vramfb = VIRTIO_RAMFB_BASE(vpci_dev);
VirtIOGPUBase *g = vramfb->vgpu;
int i;
if (virtio_gpu_hostmem_enabled(g->conf)) {
vpci_dev->msix_bar_idx = 1;
vpci_dev->modern_mem_bar_idx = 2;
memory_region_init(&g->hostmem, OBJECT(g), "virtio-gpu-hostmem",
g->conf.hostmem);
pci_register_bar(&vpci_dev->pci_dev, 4,
PCI_BASE_ADDRESS_SPACE_MEMORY |
PCI_BASE_ADDRESS_MEM_PREFETCH |
PCI_BASE_ADDRESS_MEM_TYPE_64,
&g->hostmem);
virtio_pci_add_shm_cap(vpci_dev, 4, 0, g->conf.hostmem,
VIRTIO_GPU_SHM_ID_HOST_VISIBLE);
}
/* init virtio bits */
virtio_pci_force_virtio_1(vpci_dev);
if (!qdev_realize(DEVICE(g), BUS(&vpci_dev->bus), errp)) {
return;
}
/* init ramfb */
vramfb->ramfb = ramfb_setup(errp);
graphic_console_set_hwops(g->scanout[0].con, &virtio_ramfb_ops, vramfb);
for (i = 0; i < g->conf.max_outputs; i++) {
object_property_set_link(OBJECT(g->scanout[i].con), "device",
OBJECT(vpci_dev), &error_abort);
}
}
static void virtio_ramfb_reset_hold(Object *obj, ResetType type)
{
VirtIORAMFBBase *dev = VIRTIO_RAMFB_BASE(obj);
VirtIORAMFBBaseClass *klass = VIRTIO_RAMFB_BASE_GET_CLASS(dev);
/* reset virtio-gpu */
if (klass->parent_phases.hold) {
klass->parent_phases.hold(obj, type);
}
}
static const Property virtio_ramfb_base_properties[] = {
DEFINE_VIRTIO_GPU_PCI_PROPERTIES(VirtIOPCIProxy),
};
static void virtio_ramfb_base_class_init(ObjectClass *klass, void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
VirtioPCIClass *k = VIRTIO_PCI_CLASS(klass);
VirtIORAMFBBaseClass *v = VIRTIO_RAMFB_BASE_CLASS(klass);
PCIDeviceClass *pcidev_k = PCI_DEVICE_CLASS(klass);
ResettableClass *rc = RESETTABLE_CLASS(klass);
set_bit(DEVICE_CATEGORY_DISPLAY, dc->categories);
device_class_set_props(dc, virtio_ramfb_base_properties);
dc->vmsd = &vmstate_virtio_ramfb;
dc->hotpluggable = false;
resettable_class_set_parent_phases(rc, NULL, virtio_ramfb_reset_hold, NULL,
&v->parent_phases);
k->realize = virtio_ramfb_realize;
pcidev_k->class_id = PCI_CLASS_DISPLAY_OTHER;
}
static const TypeInfo virtio_ramfb_base_info = {
.name = TYPE_VIRTIO_RAMFB_BASE,
.parent = TYPE_VIRTIO_PCI,
.instance_size = sizeof(VirtIORAMFBBase),
.class_size = sizeof(VirtIORAMFBBaseClass),
.class_init = virtio_ramfb_base_class_init,
.abstract = true,
};
#define TYPE_VIRTIO_RAMFB "virtio-ramfb"
typedef struct VirtIORAMFB VirtIORAMFB;
DECLARE_INSTANCE_CHECKER(VirtIORAMFB, VIRTIO_RAMFB,
TYPE_VIRTIO_RAMFB)
struct VirtIORAMFB {
VirtIORAMFBBase parent_obj;
VirtIOGPU vdev;
};
static void virtio_ramfb_inst_initfn(Object *obj)
{
VirtIORAMFB *dev = VIRTIO_RAMFB(obj);
virtio_instance_init_common(obj, &dev->vdev, sizeof(dev->vdev),
TYPE_VIRTIO_GPU);
VIRTIO_RAMFB_BASE(dev)->vgpu = VIRTIO_GPU_BASE(&dev->vdev);
}
static VirtioPCIDeviceTypeInfo virtio_ramfb_info = {
.generic_name = TYPE_VIRTIO_RAMFB,
.parent = TYPE_VIRTIO_RAMFB_BASE,
.instance_size = sizeof(VirtIORAMFB),
.instance_init = virtio_ramfb_inst_initfn,
};
static void virtio_ramfb_register_types(void)
{
type_register_static(&virtio_ramfb_base_info);
virtio_pci_types_register(&virtio_ramfb_info);
}
type_init(virtio_ramfb_register_types)
+28
View File
@@ -0,0 +1,28 @@
#ifndef VIRTIO_RAMFB_H
#define VIRTIO_RAMFB_H
#include "hw/virtio/virtio-gpu-pci.h"
#include "hw/display/ramfb.h"
#include "qom/object.h"
/*
* virtio-ramfb-base: This extends VirtioPCIProxy.
*/
#define TYPE_VIRTIO_RAMFB_BASE "virtio-ramfb-base"
OBJECT_DECLARE_TYPE(VirtIORAMFBBase, VirtIORAMFBBaseClass,
VIRTIO_RAMFB_BASE)
struct VirtIORAMFBBase {
VirtIOPCIProxy parent_obj;
VirtIOGPUBase *vgpu;
RAMFBState *ramfb;
};
struct VirtIORAMFBBaseClass {
VirtioPCIClass parent_class;
ResettablePhases parent_phases;
};
#endif /* VIRTIO_RAMFB_H */
+1 -15
View File
@@ -1724,21 +1724,7 @@ build_dsdt(GArray *table_data, BIOSLinker *linker,
#ifdef CONFIG_TPM
if (TPM_IS_CRB(tpm)) {
dev = aml_device("TPM");
aml_append(dev, aml_name_decl("_HID", aml_string("MSFT0101")));
aml_append(dev, aml_name_decl("_STR",
aml_string("TPM 2.0 Device")));
crs = aml_resource_template();
aml_append(crs, aml_memory32_fixed(TPM_CRB_ADDR_BASE,
TPM_CRB_ADDR_SIZE, AML_READ_WRITE));
aml_append(dev, aml_name_decl("_CRS", crs));
aml_append(dev, aml_name_decl("_STA", aml_int(0xf)));
aml_append(dev, aml_name_decl("_UID", aml_int(1)));
tpm_build_ppi_acpi(tpm, dev);
aml_append(sb_scope, dev);
call_dev_aml_func(DEVICE(tpm), scope);
}
#endif
+2 -2
View File
@@ -470,7 +470,7 @@ static void pc_i440fx_machine_options(MachineClass *m)
m->default_machine_opts = "firmware=bios-256k.bin";
m->default_display = "std";
m->default_nic = "e1000";
m->no_floppy = !module_object_class_by_name(TYPE_ISA_FDC);
m->no_floppy = !defaults_enabled() || !module_object_class_by_name(TYPE_ISA_FDC);
m->no_parallel = !module_object_class_by_name(TYPE_ISA_PARALLEL);
machine_class_allow_dynamic_sysbus_dev(m, TYPE_RAMFB_DEVICE);
machine_class_allow_dynamic_sysbus_dev(m, TYPE_VMBUS_BRIDGE);
@@ -816,7 +816,7 @@ static void isapc_machine_options(MachineClass *m)
pcmc->has_reserved_memory = false;
m->default_nic = "ne2k_isa";
m->default_cpu_type = X86_CPU_TYPE_NAME("486");
m->no_floppy = !module_object_class_by_name(TYPE_ISA_FDC);
m->no_floppy = !defaults_enabled() || !module_object_class_by_name(TYPE_ISA_FDC);
m->no_parallel = !module_object_class_by_name(TYPE_ISA_PARALLEL);
}
+10 -3
View File
@@ -215,7 +215,7 @@ static bool update_ite(GICv3ITSState *s, uint32_t eventid, const DTEntry *dte,
{
AddressSpace *as = &s->gicv3->dma_as;
MemTxResult res = MEMTX_OK;
hwaddr iteaddr = dte->ittaddr + eventid * ITS_ITT_ENTRY_SIZE;
hwaddr iteaddr = dte->ittaddr + eventid * s->itt_entry_size;
uint64_t itel = 0;
uint32_t iteh = 0;
@@ -253,7 +253,7 @@ static MemTxResult get_ite(GICv3ITSState *s, uint32_t eventid,
MemTxResult res = MEMTX_OK;
uint64_t itel;
uint32_t iteh;
hwaddr iteaddr = dte->ittaddr + eventid * ITS_ITT_ENTRY_SIZE;
hwaddr iteaddr = dte->ittaddr + eventid * s->itt_entry_size;
itel = address_space_ldq_le(as, iteaddr, MEMTXATTRS_UNSPECIFIED, &res);
if (res != MEMTX_OK) {
@@ -1931,6 +1931,12 @@ static void gicv3_arm_its_realize(DeviceState *dev, Error **errp)
}
}
if (s->itt_entry_size < MIN_ITS_ITT_ENTRY_SIZE) {
error_setg(errp, "ITT entry size must be at least %d",
MIN_ITS_ITT_ENTRY_SIZE);
return;
}
gicv3_add_its(s->gicv3, dev);
gicv3_its_init_mmio(s, &gicv3_its_control_ops, &gicv3_its_translation_ops);
@@ -1938,7 +1944,7 @@ static void gicv3_arm_its_realize(DeviceState *dev, Error **errp)
/* set the ITS default features supported */
s->typer = FIELD_DP64(s->typer, GITS_TYPER, PHYSICAL, 1);
s->typer = FIELD_DP64(s->typer, GITS_TYPER, ITT_ENTRY_SIZE,
ITS_ITT_ENTRY_SIZE - 1);
s->itt_entry_size - 1);
s->typer = FIELD_DP64(s->typer, GITS_TYPER, IDBITS, ITS_IDBITS);
s->typer = FIELD_DP64(s->typer, GITS_TYPER, DEVBITS, ITS_DEVBITS);
s->typer = FIELD_DP64(s->typer, GITS_TYPER, CIL, 1);
@@ -2005,6 +2011,7 @@ static void gicv3_its_post_load(GICv3ITSState *s)
static const Property gicv3_its_props[] = {
DEFINE_PROP_LINK("parent-gicv3", GICv3ITSState, gicv3, "arm-gicv3",
GICv3State *),
DEFINE_PROP_UINT8("itt-entry-size", GICv3ITSState, itt_entry_size, 16),
};
static void gicv3_its_class_init(ObjectClass *klass, void *data)
+1 -1
View File
@@ -462,7 +462,7 @@ FIELD(VINVALL_1, VPEID, 32, 16)
* the value of that field in memory cannot be relied upon -- older
* versions of QEMU did not correctly write to that memory.)
*/
#define ITS_ITT_ENTRY_SIZE 0xC
#define MIN_ITS_ITT_ENTRY_SIZE 0xC
FIELD(ITE_L, VALID, 0, 1)
FIELD(ITE_L, INTTYPE, 1, 1)
+1
View File
@@ -8,6 +8,7 @@ config LOONGARCH_VIRT
imply PCI_DEVICES
imply NVDIMM
imply TPM_TIS_SYSBUS
imply TPM_CRB_SYSBUS
select SERIAL_MM
select VIRTIO_PCI
select PLATFORM_BUS
+2 -36
View File
@@ -14,6 +14,7 @@
#include "target/loongarch/cpu.h"
#include "hw/acpi/acpi-defs.h"
#include "hw/acpi/acpi.h"
#include "hw/acpi/acpi_aml_interface.h"
#include "hw/nvram/fw_cfg.h"
#include "hw/acpi/bios-linker-loader.h"
#include "migration/vmstate.h"
@@ -438,41 +439,6 @@ static void build_flash_aml(Aml *scope, LoongArchVirtMachineState *lvms)
aml_append(scope, dev);
}
#ifdef CONFIG_TPM
static void acpi_dsdt_add_tpm(Aml *scope, LoongArchVirtMachineState *vms)
{
PlatformBusDevice *pbus = PLATFORM_BUS_DEVICE(vms->platform_bus_dev);
hwaddr pbus_base = VIRT_PLATFORM_BUS_BASEADDRESS;
SysBusDevice *sbdev = SYS_BUS_DEVICE(tpm_find());
MemoryRegion *sbdev_mr;
hwaddr tpm_base;
if (!sbdev) {
return;
}
tpm_base = platform_bus_get_mmio_addr(pbus, sbdev, 0);
assert(tpm_base != -1);
tpm_base += pbus_base;
sbdev_mr = sysbus_mmio_get_region(sbdev, 0);
Aml *dev = aml_device("TPM0");
aml_append(dev, aml_name_decl("_HID", aml_string("MSFT0101")));
aml_append(dev, aml_name_decl("_STR", aml_string("TPM 2.0 Device")));
aml_append(dev, aml_name_decl("_UID", aml_int(0)));
Aml *crs = aml_resource_template();
aml_append(crs,
aml_memory32_fixed(tpm_base,
(uint32_t)memory_region_size(sbdev_mr),
AML_READ_WRITE));
aml_append(dev, aml_name_decl("_CRS", crs));
aml_append(scope, dev);
}
#endif
/* build DSDT */
static void
build_dsdt(GArray *table_data, BIOSLinker *linker, MachineState *machine)
@@ -492,7 +458,7 @@ build_dsdt(GArray *table_data, BIOSLinker *linker, MachineState *machine)
build_la_ged_aml(dsdt, machine);
build_flash_aml(dsdt, lvms);
#ifdef CONFIG_TPM
acpi_dsdt_add_tpm(dsdt, lvms);
call_dev_aml_func(DEVICE(tpm_find()), dsdt);
#endif
/* System State Package */
scope = aml_scope("\\");
+8
View File
@@ -1076,6 +1076,13 @@ static void virt_device_plug_cb(HotplugHandler *hotplug_dev,
} else if (object_dynamic_cast(OBJECT(dev), TYPE_LOONGARCH_CPU)) {
virt_cpu_plug(hotplug_dev, dev, errp);
}
#ifdef CONFIG_TPM
if (object_dynamic_cast(OBJECT(dev), TYPE_TPM_IF)) {
tpm_sysbus_plug(TPM_IF(dev), OBJECT(lvms->platform_bus_dev),
VIRT_PLATFORM_BUS_BASEADDRESS);
}
#endif
}
static HotplugHandler *virt_get_hotplug_handler(MachineState *machine,
@@ -1187,6 +1194,7 @@ static void virt_class_init(ObjectClass *oc, void *data)
machine_class_allow_dynamic_sysbus_dev(mc, TYPE_UEFI_VARS_SYSBUS);
#ifdef CONFIG_TPM
machine_class_allow_dynamic_sysbus_dev(mc, TYPE_TPM_TIS_SYSBUS);
machine_class_allow_dynamic_sysbus_dev(mc, TYPE_TPM_CRB_SYSBUS);
#endif
}
+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;
}
}
+23 -1
View File
@@ -102,6 +102,13 @@ static bool macio_common_realize(PCIDevice *d, Error **errp)
memory_region_add_subregion(&s->bar, 0x08000,
sysbus_mmio_get_region(sbd, 0));
if (!qdev_realize(DEVICE(&s->screamer), BUS(&s->macio_bus), errp)) {
return false;
}
sbd = SYS_BUS_DEVICE(&s->screamer);
memory_region_add_subregion(&s->bar, 0x14000,
sysbus_mmio_get_region(sbd, 0));
qdev_prop_set_uint32(DEVICE(&s->escc), "disabled", 0);
qdev_prop_set_uint32(DEVICE(&s->escc), "frequency", ESCC_CLOCK);
qdev_prop_set_uint32(DEVICE(&s->escc), "it_shift", 4);
@@ -110,7 +117,6 @@ static bool macio_common_realize(PCIDevice *d, Error **errp)
if (!qdev_realize(DEVICE(&s->escc), BUS(&s->macio_bus), errp)) {
return false;
}
macio_bar_setup(s);
pci_register_bar(d, 0, PCI_BASE_ADDRESS_SPACE_MEMORY, &s->bar);
@@ -191,6 +197,13 @@ static void macio_oldworld_realize(PCIDevice *d, Error **errp)
0x1a, errp)) {
return;
}
/* Screamer */
sbd = SYS_BUS_DEVICE(&s->screamer);
sysbus_connect_irq(sbd, 0, qdev_get_gpio_in(pic_dev, OLDWORLD_SCREAMER_TX_IRQ));
sysbus_connect_irq(sbd, 1, qdev_get_gpio_in(pic_dev, OLDWORLD_SCREAMER_TX_DMA_IRQ));
sysbus_connect_irq(sbd, 1, qdev_get_gpio_in(pic_dev, OLDWORLD_SCREAMER_RX_IRQ));
macio_screamer_register_dma(SCREAMER(sbd), &s->dbdma, 0x10, 0x12);
}
static void macio_init_ide(MacIOState *s, MACIOIDEState *ide, int index)
@@ -344,6 +357,13 @@ static void macio_newworld_realize(PCIDevice *d, Error **errp)
memory_region_add_subregion(&s->bar, 0x16000,
sysbus_mmio_get_region(sbd, 0));
}
/* Screamer */
sbd = SYS_BUS_DEVICE(&s->screamer);
sysbus_connect_irq(sbd, 0, qdev_get_gpio_in(pic_dev, NEWWORLD_SCREAMER_IRQ));
sysbus_connect_irq(sbd, 1, qdev_get_gpio_in(pic_dev, NEWWORLD_SCREAMER_DMA_IRQ));
sysbus_connect_irq(sbd, 2, qdev_get_gpio_in(pic_dev, NEWWORLD_SCREAMER_RX_IRQ));
macio_screamer_register_dma(SCREAMER(sbd), &s->dbdma, 0x10, 0x12);
}
static void macio_newworld_init(Object *obj)
@@ -373,6 +393,8 @@ static void macio_instance_init(Object *obj)
object_initialize_child(obj, "dbdma", &s->dbdma, TYPE_MAC_DBDMA);
object_initialize_child(obj, "escc", &s->escc, TYPE_ESCC);
object_initialize_child(obj, "screamer", &s->screamer, TYPE_SCREAMER);
}
static const VMStateDescription vmstate_macio_oldworld = {
+2
View File
@@ -127,6 +127,7 @@ config MAC_OLDWORLD
select HEATHROW_PIC
select MACIO
select FW_CFG_PPC
select SCREAMER
config MAC_NEWWORLD
bool
@@ -142,6 +143,7 @@ config MAC_NEWWORLD
select MAC_PMU
select UNIN_PCI
select FW_CFG_PPC
select SCREAMER
config E500
bool
+1
View File
@@ -48,6 +48,7 @@ config RISCV_VIRT
imply PCI_DEVICES
imply VIRTIO_VGA
imply TEST_DEVICES
imply TPM_CRB_SYSBUS
imply TPM_TIS_SYSBUS
select DEVICE_TREE
select RISCV_NUMA
+1
View File
@@ -1939,6 +1939,7 @@ static void virt_machine_class_init(ObjectClass *oc, void *data)
machine_class_allow_dynamic_sysbus_dev(mc, TYPE_UEFI_VARS_SYSBUS);
#ifdef CONFIG_TPM
machine_class_allow_dynamic_sysbus_dev(mc, TYPE_TPM_TIS_SYSBUS);
machine_class_allow_dynamic_sysbus_dev(mc, TYPE_TPM_CRB_SYSBUS);
#endif
object_class_property_add_bool(oc, "aclint", virt_get_aclint,
+5
View File
@@ -25,6 +25,11 @@ config TPM_CRB
depends on TPM && PC
select TPM_BACKEND
config TPM_CRB_SYSBUS
bool
depends on TPM
select TPM_BACKEND
config TPM_SPAPR
bool
default y
+5
View File
@@ -1,8 +1,13 @@
system_ss.add(when: 'CONFIG_TPM_TIS', if_true: files('tpm_tis_common.c'))
system_ss.add(when: 'CONFIG_TPM_TIS_ISA', if_true: files('tpm_tis_isa.c'))
system_ss.add(when: 'CONFIG_TPM_TIS_SYSBUS', if_true: files('tpm_tis_sysbus.c'))
system_ss.add(when: 'CONFIG_TPM_TIS_SYSBUS', if_true: files('tpm-sysbus.c'))
system_ss.add(when: 'CONFIG_TPM_TIS_I2C', if_true: files('tpm_tis_i2c.c'))
system_ss.add(when: 'CONFIG_TPM_CRB', if_true: files('tpm_crb.c'))
system_ss.add(when: 'CONFIG_TPM_CRB', if_true: files('tpm_crb_common.c'))
system_ss.add(when: 'CONFIG_TPM_CRB_SYSBUS', if_true: files('tpm_crb_sysbus.c'))
system_ss.add(when: 'CONFIG_TPM_CRB_SYSBUS', if_true: files('tpm_crb_common.c'))
system_ss.add(when: 'CONFIG_TPM_CRB_SYSBUS', if_true: files('tpm-sysbus.c'))
system_ss.add(when: 'CONFIG_TPM_TIS', if_true: files('tpm_ppi.c'))
system_ss.add(when: 'CONFIG_TPM_CRB', if_true: files('tpm_ppi.c'))
+47
View File
@@ -0,0 +1,47 @@
/*
* tpm-sysbus.c - Support functions for SysBus TPM devices
*
* Copyright (c) 2023 QEMU contributors
*
* Authors:
* Joelle van Dyne <j@getutm.app>
*
* This work is licensed under the terms of the GNU GPL, version 2 or later.
* See the COPYING file in the top-level directory.
*/
#include "system/tpm.h"
#include "hw/platform-bus.h"
#include "hw/sysbus.h"
#include "qapi/error.h"
/**
* Called from a machine's pre_plug handler to set the device's physical addr.
*/
void tpm_sysbus_plug(TPMIf *tpmif, Object *pbus, hwaddr pbus_base)
{
PlatformBusDevice *pbusdev = PLATFORM_BUS_DEVICE(pbus);
SysBusDevice *sbdev = SYS_BUS_DEVICE(tpmif);
MemoryRegion *sbdev_mr;
hwaddr tpm_base;
uint64_t tpm_size;
/* exit early if TPM is not a sysbus device */
if (!object_dynamic_cast(OBJECT(tpmif), TYPE_SYS_BUS_DEVICE)) {
return;
}
assert(object_dynamic_cast(pbus, TYPE_PLATFORM_BUS_DEVICE));
tpm_base = platform_bus_get_mmio_addr(pbusdev, sbdev, 0);
assert(tpm_base != -1);
tpm_base += pbus_base;
sbdev_mr = sysbus_mmio_get_region(sbdev, 0);
tpm_size = memory_region_size(sbdev_mr);
object_property_set_uint(OBJECT(sbdev), "x-baseaddr",
tpm_base, &error_abort);
object_property_set_uint(OBJECT(sbdev), "x-size",
tpm_size, &error_abort);
}
+74 -232
View File
@@ -19,6 +19,8 @@
#include "qemu/module.h"
#include "qapi/error.h"
#include "exec/address-spaces.h"
#include "hw/acpi/acpi_aml_interface.h"
#include "hw/acpi/tpm.h"
#include "hw/qdev-properties.h"
#include "hw/pci/pci_ids.h"
#include "hw/acpi/tpm.h"
@@ -31,256 +33,83 @@
#include "tpm_ppi.h"
#include "trace.h"
#include "qom/object.h"
#include "tpm_crb.h"
struct CRBState {
DeviceState parent_obj;
TPMBackend *tpmbe;
TPMBackendCmd cmd;
uint32_t regs[TPM_CRB_R_MAX];
MemoryRegion mmio;
MemoryRegion cmdmem;
TPMCRBState state;
size_t be_buffer_size;
bool ppi_enabled;
TPMPPI ppi;
/* These states are only for migration */
uint32_t saved_regs[TPM_CRB_R_MAX];
MemoryRegion saved_cmdmem;
};
typedef struct CRBState CRBState;
DECLARE_INSTANCE_CHECKER(CRBState, CRB,
TYPE_TPM_CRB)
#define CRB_INTF_TYPE_CRB_ACTIVE 0b1
#define CRB_INTF_VERSION_CRB 0b1
#define CRB_INTF_CAP_LOCALITY_0_ONLY 0b0
#define CRB_INTF_CAP_IDLE_FAST 0b0
#define CRB_INTF_CAP_XFER_SIZE_64 0b11
#define CRB_INTF_CAP_FIFO_NOT_SUPPORTED 0b0
#define CRB_INTF_CAP_CRB_SUPPORTED 0b1
#define CRB_INTF_IF_SELECTOR_CRB 0b1
#define CRB_CTRL_CMD_SIZE (TPM_CRB_ADDR_SIZE - A_CRB_DATA_BUFFER)
enum crb_loc_ctrl {
CRB_LOC_CTRL_REQUEST_ACCESS = BIT(0),
CRB_LOC_CTRL_RELINQUISH = BIT(1),
CRB_LOC_CTRL_SEIZE = BIT(2),
CRB_LOC_CTRL_RESET_ESTABLISHMENT_BIT = BIT(3),
};
enum crb_ctrl_req {
CRB_CTRL_REQ_CMD_READY = BIT(0),
CRB_CTRL_REQ_GO_IDLE = BIT(1),
};
enum crb_start {
CRB_START_INVOKE = BIT(0),
};
enum crb_cancel {
CRB_CANCEL_INVOKE = BIT(0),
};
#define TPM_CRB_NO_LOCALITY 0xff
static uint64_t tpm_crb_mmio_read(void *opaque, hwaddr addr,
unsigned size)
{
CRBState *s = CRB(opaque);
void *regs = (void *)&s->regs + (addr & ~3);
unsigned offset = addr & 3;
uint32_t val = *(uint32_t *)regs >> (8 * offset);
switch (addr) {
case A_CRB_LOC_STATE:
val |= !tpm_backend_get_tpm_established_flag(s->tpmbe);
break;
}
trace_tpm_crb_mmio_read(addr, size, val);
return val;
}
static uint8_t tpm_crb_get_active_locty(CRBState *s)
{
if (!ARRAY_FIELD_EX32(s->regs, CRB_LOC_STATE, locAssigned)) {
return TPM_CRB_NO_LOCALITY;
}
return ARRAY_FIELD_EX32(s->regs, CRB_LOC_STATE, activeLocality);
}
static void tpm_crb_mmio_write(void *opaque, hwaddr addr,
uint64_t val, unsigned size)
{
CRBState *s = CRB(opaque);
uint8_t locty = addr >> 12;
trace_tpm_crb_mmio_write(addr, size, val);
switch (addr) {
case A_CRB_CTRL_REQ:
switch (val) {
case CRB_CTRL_REQ_CMD_READY:
ARRAY_FIELD_DP32(s->regs, CRB_CTRL_STS,
tpmIdle, 0);
break;
case CRB_CTRL_REQ_GO_IDLE:
ARRAY_FIELD_DP32(s->regs, CRB_CTRL_STS,
tpmIdle, 1);
break;
}
break;
case A_CRB_CTRL_CANCEL:
if (val == CRB_CANCEL_INVOKE &&
s->regs[R_CRB_CTRL_START] & CRB_START_INVOKE) {
tpm_backend_cancel_cmd(s->tpmbe);
}
break;
case A_CRB_CTRL_START:
if (val == CRB_START_INVOKE &&
!(s->regs[R_CRB_CTRL_START] & CRB_START_INVOKE) &&
tpm_crb_get_active_locty(s) == locty) {
void *mem = memory_region_get_ram_ptr(&s->cmdmem);
s->regs[R_CRB_CTRL_START] |= CRB_START_INVOKE;
s->cmd = (TPMBackendCmd) {
.in = mem,
.in_len = MIN(tpm_cmd_get_size(mem), s->be_buffer_size),
.out = mem,
.out_len = s->be_buffer_size,
};
tpm_backend_deliver_request(s->tpmbe, &s->cmd);
}
break;
case A_CRB_LOC_CTRL:
switch (val) {
case CRB_LOC_CTRL_RESET_ESTABLISHMENT_BIT:
/* not loc 3 or 4 */
break;
case CRB_LOC_CTRL_RELINQUISH:
ARRAY_FIELD_DP32(s->regs, CRB_LOC_STATE,
locAssigned, 0);
ARRAY_FIELD_DP32(s->regs, CRB_LOC_STS,
Granted, 0);
break;
case CRB_LOC_CTRL_REQUEST_ACCESS:
ARRAY_FIELD_DP32(s->regs, CRB_LOC_STS,
Granted, 1);
ARRAY_FIELD_DP32(s->regs, CRB_LOC_STS,
beenSeized, 0);
ARRAY_FIELD_DP32(s->regs, CRB_LOC_STATE,
locAssigned, 1);
break;
}
break;
}
}
static const MemoryRegionOps tpm_crb_memory_ops = {
.read = tpm_crb_mmio_read,
.write = tpm_crb_mmio_write,
.endianness = DEVICE_LITTLE_ENDIAN,
.valid = {
.min_access_size = 1,
.max_access_size = 4,
},
};
static void tpm_crb_request_completed(TPMIf *ti, int ret)
static void tpm_crb_none_request_completed(TPMIf *ti, int ret)
{
CRBState *s = CRB(ti);
s->regs[R_CRB_CTRL_START] &= ~CRB_START_INVOKE;
if (ret != 0) {
ARRAY_FIELD_DP32(s->regs, CRB_CTRL_STS,
tpmSts, 1); /* fatal error */
}
memory_region_set_dirty(&s->cmdmem, 0, CRB_CTRL_CMD_SIZE);
tpm_crb_request_completed(&s->state, ret);
}
static enum TPMVersion tpm_crb_get_version(TPMIf *ti)
static enum TPMVersion tpm_crb_none_get_version(TPMIf *ti)
{
CRBState *s = CRB(ti);
return tpm_backend_get_tpm_version(s->tpmbe);
return tpm_crb_get_version(&s->state);
}
static int tpm_crb_pre_save(void *opaque)
/**
* For migrating to an older version of QEMU
*/
static int tpm_crb_none_pre_save(void *opaque)
{
CRBState *s = opaque;
void *saved_cmdmem = memory_region_get_ram_ptr(&s->saved_cmdmem);
tpm_backend_finish_sync(s->tpmbe);
tpm_crb_mem_save(&s->state, s->saved_regs, saved_cmdmem);
return tpm_crb_pre_save(&s->state);
}
/**
* For migrating from an older version of QEMU
*/
static int tpm_crb_none_post_load(void *opaque, int version_id)
{
CRBState *s = opaque;
void *saved_cmdmem = memory_region_get_ram_ptr(&s->saved_cmdmem);
tpm_crb_mem_load(&s->state, s->saved_regs, saved_cmdmem);
return 0;
}
static const VMStateDescription vmstate_tpm_crb = {
static const VMStateDescription vmstate_tpm_crb_none = {
.name = "tpm-crb",
.pre_save = tpm_crb_pre_save,
.pre_save = tpm_crb_none_pre_save,
.post_load = tpm_crb_none_post_load,
.fields = (const VMStateField[]) {
VMSTATE_UINT32_ARRAY(regs, CRBState, TPM_CRB_R_MAX),
VMSTATE_UINT32_ARRAY(saved_regs, CRBState, TPM_CRB_R_MAX),
VMSTATE_END_OF_LIST(),
}
};
static const Property tpm_crb_properties[] = {
DEFINE_PROP_TPMBE("tpmdev", CRBState, tpmbe),
DEFINE_PROP_BOOL("ppi", CRBState, ppi_enabled, true),
static const Property tpm_crb_none_properties[] = {
DEFINE_PROP_TPMBE("tpmdev", CRBState, state.tpmbe),
DEFINE_PROP_BOOL("ppi", CRBState, state.ppi_enabled, true),
};
static void tpm_crb_reset(void *dev)
static void tpm_crb_none_reset(void *dev)
{
CRBState *s = CRB(dev);
if (s->ppi_enabled) {
tpm_ppi_reset(&s->ppi);
}
tpm_backend_reset(s->tpmbe);
memset(s->regs, 0, sizeof(s->regs));
ARRAY_FIELD_DP32(s->regs, CRB_LOC_STATE,
tpmRegValidSts, 1);
ARRAY_FIELD_DP32(s->regs, CRB_CTRL_STS,
tpmIdle, 1);
ARRAY_FIELD_DP32(s->regs, CRB_INTF_ID,
InterfaceType, CRB_INTF_TYPE_CRB_ACTIVE);
ARRAY_FIELD_DP32(s->regs, CRB_INTF_ID,
InterfaceVersion, CRB_INTF_VERSION_CRB);
ARRAY_FIELD_DP32(s->regs, CRB_INTF_ID,
CapLocality, CRB_INTF_CAP_LOCALITY_0_ONLY);
ARRAY_FIELD_DP32(s->regs, CRB_INTF_ID,
CapCRBIdleBypass, CRB_INTF_CAP_IDLE_FAST);
ARRAY_FIELD_DP32(s->regs, CRB_INTF_ID,
CapDataXferSizeSupport, CRB_INTF_CAP_XFER_SIZE_64);
ARRAY_FIELD_DP32(s->regs, CRB_INTF_ID,
CapFIFO, CRB_INTF_CAP_FIFO_NOT_SUPPORTED);
ARRAY_FIELD_DP32(s->regs, CRB_INTF_ID,
CapCRB, CRB_INTF_CAP_CRB_SUPPORTED);
ARRAY_FIELD_DP32(s->regs, CRB_INTF_ID,
InterfaceSelector, CRB_INTF_IF_SELECTOR_CRB);
ARRAY_FIELD_DP32(s->regs, CRB_INTF_ID,
RID, 0b0000);
ARRAY_FIELD_DP32(s->regs, CRB_INTF_ID2,
VID, PCI_VENDOR_ID_IBM);
s->regs[R_CRB_CTRL_CMD_SIZE] = CRB_CTRL_CMD_SIZE;
s->regs[R_CRB_CTRL_CMD_LADDR] = TPM_CRB_ADDR_BASE + A_CRB_DATA_BUFFER;
s->regs[R_CRB_CTRL_RSP_SIZE] = CRB_CTRL_CMD_SIZE;
s->regs[R_CRB_CTRL_RSP_ADDR] = TPM_CRB_ADDR_BASE + A_CRB_DATA_BUFFER;
s->be_buffer_size = MIN(tpm_backend_get_buffer_size(s->tpmbe),
CRB_CTRL_CMD_SIZE);
if (tpm_backend_startup_tpm(s->tpmbe, s->be_buffer_size) < 0) {
exit(1);
}
return tpm_crb_reset(&s->state, TPM_CRB_ADDR_BASE);
}
static void tpm_crb_realize(DeviceState *dev, Error **errp)
static void tpm_crb_none_realize(DeviceState *dev, Error **errp)
{
CRBState *s = CRB(dev);
@@ -288,64 +117,77 @@ static void tpm_crb_realize(DeviceState *dev, Error **errp)
error_setg(errp, "at most one TPM device is permitted");
return;
}
if (!s->tpmbe) {
if (!s->state.tpmbe) {
error_setg(errp, "'tpmdev' property is required");
return;
}
memory_region_init_io(&s->mmio, OBJECT(s), &tpm_crb_memory_ops, s,
"tpm-crb-mmio", sizeof(s->regs));
memory_region_init_ram(&s->cmdmem, OBJECT(s),
if (tpm_crb_none_get_version(TPM_IF(s)) != TPM_VERSION_2_0) {
error_setg(errp, "TPM CRB only supports TPM 2.0 backends");
return;
}
tpm_crb_init_memory(OBJECT(s), &s->state, errp);
/* only used for migration */
memory_region_init_ram(&s->saved_cmdmem, OBJECT(s),
"tpm-crb-cmd", CRB_CTRL_CMD_SIZE, errp);
memory_region_add_subregion(get_system_memory(),
TPM_CRB_ADDR_BASE, &s->mmio);
memory_region_add_subregion(get_system_memory(),
TPM_CRB_ADDR_BASE + sizeof(s->regs), &s->cmdmem);
TPM_CRB_ADDR_BASE, &s->state.mmio);
if (s->ppi_enabled) {
tpm_ppi_init(&s->ppi, get_system_memory(),
TPM_PPI_ADDR_BASE, OBJECT(s));
if (s->state.ppi_enabled) {
memory_region_add_subregion(get_system_memory(),
TPM_PPI_ADDR_BASE, &s->state.ppi.ram);
}
if (xen_enabled()) {
tpm_crb_reset(dev);
tpm_crb_none_reset(dev);
} else {
qemu_register_reset(tpm_crb_reset, dev);
qemu_register_reset(tpm_crb_none_reset, dev);
}
}
static void tpm_crb_class_init(ObjectClass *klass, void *data)
static void build_tpm_crb_none_aml(AcpiDevAmlIf *adev, Aml *scope)
{
tpm_crb_build_aml(TPM_IF(adev), scope, TPM_CRB_ADDR_BASE, TPM_CRB_ADDR_SIZE,
true);
}
static void tpm_crb_none_class_init(ObjectClass *klass, void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
TPMIfClass *tc = TPM_IF_CLASS(klass);
AcpiDevAmlIfClass *adevc = ACPI_DEV_AML_IF_CLASS(klass);
dc->realize = tpm_crb_realize;
device_class_set_props(dc, tpm_crb_properties);
dc->vmsd = &vmstate_tpm_crb;
dc->realize = tpm_crb_none_realize;
device_class_set_props(dc, tpm_crb_none_properties);
dc->vmsd = &vmstate_tpm_crb_none;
dc->user_creatable = true;
tc->model = TPM_MODEL_TPM_CRB;
tc->get_version = tpm_crb_get_version;
tc->request_completed = tpm_crb_request_completed;
tc->get_version = tpm_crb_none_get_version;
tc->request_completed = tpm_crb_none_request_completed;
adevc->build_dev_aml = build_tpm_crb_none_aml;
set_bit(DEVICE_CATEGORY_MISC, dc->categories);
}
static const TypeInfo tpm_crb_info = {
static const TypeInfo tpm_crb_none_info = {
.name = TYPE_TPM_CRB,
/* could be TYPE_SYS_BUS_DEVICE (or LPC etc) */
.parent = TYPE_DEVICE,
.instance_size = sizeof(CRBState),
.class_init = tpm_crb_class_init,
.class_init = tpm_crb_none_class_init,
.interfaces = (InterfaceInfo[]) {
{ TYPE_TPM_IF },
{ TYPE_ACPI_DEV_AML_IF },
{ }
}
};
static void tpm_crb_register(void)
static void tpm_crb_none_register(void)
{
type_register_static(&tpm_crb_info);
type_register_static(&tpm_crb_none_info);
}
type_init(tpm_crb_register)
type_init(tpm_crb_none_register)
+79
View File
@@ -0,0 +1,79 @@
/*
* tpm_crb.h - QEMU's TPM CRB interface emulator
*
* Copyright (c) 2018 Red Hat, Inc.
*
* Authors:
* Marc-André Lureau <marcandre.lureau@redhat.com>
*
* This work is licensed under the terms of the GNU GPL, version 2 or later.
* See the COPYING file in the top-level directory.
*
* tpm_crb is a device for TPM 2.0 Command Response Buffer (CRB) Interface
* as defined in TCG PC Client Platform TPM Profile (PTP) Specification
* Family “2.0” Level 00 Revision 01.03 v22
*/
#ifndef TPM_TPM_CRB_H
#define TPM_TPM_CRB_H
#include "exec/memory.h"
#include "hw/acpi/tpm.h"
#include "system/tpm_backend.h"
#include "tpm_ppi.h"
#define CRB_CTRL_CMD_SIZE (TPM_CRB_ADDR_SIZE - A_CRB_DATA_BUFFER)
typedef struct TPMCRBState {
TPMBackend *tpmbe;
TPMBackendCmd cmd;
MemoryRegion mmio;
size_t be_buffer_size;
bool ppi_enabled;
TPMPPI ppi;
} TPMCRBState;
#define CRB_INTF_TYPE_CRB_ACTIVE 0b1
#define CRB_INTF_VERSION_CRB 0b1
#define CRB_INTF_CAP_LOCALITY_0_ONLY 0b0
#define CRB_INTF_CAP_IDLE_FAST 0b0
#define CRB_INTF_CAP_XFER_SIZE_64 0b11
#define CRB_INTF_CAP_FIFO_NOT_SUPPORTED 0b0
#define CRB_INTF_CAP_CRB_SUPPORTED 0b1
#define CRB_INTF_IF_SELECTOR_CRB 0b1
enum crb_loc_ctrl {
CRB_LOC_CTRL_REQUEST_ACCESS = BIT(0),
CRB_LOC_CTRL_RELINQUISH = BIT(1),
CRB_LOC_CTRL_SEIZE = BIT(2),
CRB_LOC_CTRL_RESET_ESTABLISHMENT_BIT = BIT(3),
};
enum crb_ctrl_req {
CRB_CTRL_REQ_CMD_READY = BIT(0),
CRB_CTRL_REQ_GO_IDLE = BIT(1),
};
enum crb_start {
CRB_START_INVOKE = BIT(0),
};
enum crb_cancel {
CRB_CANCEL_INVOKE = BIT(0),
};
#define TPM_CRB_NO_LOCALITY 0xff
void tpm_crb_request_completed(TPMCRBState *s, int ret);
enum TPMVersion tpm_crb_get_version(TPMCRBState *s);
int tpm_crb_pre_save(TPMCRBState *s);
void tpm_crb_reset(TPMCRBState *s, uint64_t baseaddr);
void tpm_crb_init_memory(Object *obj, TPMCRBState *s, Error **errp);
void tpm_crb_mem_save(TPMCRBState *s, uint32_t *saved_regs, void *saved_cmdmem);
void tpm_crb_mem_load(TPMCRBState *s, const uint32_t *saved_regs,
const void *saved_cmdmem);
void tpm_crb_build_aml(TPMIf *ti, Aml *scope, uint32_t baseaddr, uint32_t size,
bool build_ppi);
#endif /* TPM_TPM_CRB_H */
+264
View File
@@ -0,0 +1,264 @@
/*
* tpm_crb.c - QEMU's TPM CRB interface emulator
*
* Copyright (c) 2018 Red Hat, Inc.
*
* Authors:
* Marc-André Lureau <marcandre.lureau@redhat.com>
*
* This work is licensed under the terms of the GNU GPL, version 2 or later.
* See the COPYING file in the top-level directory.
*
* tpm_crb is a device for TPM 2.0 Command Response Buffer (CRB) Interface
* as defined in TCG PC Client Platform TPM Profile (PTP) Specification
* Family “2.0” Level 00 Revision 01.03 v22
*/
#include "qemu/osdep.h"
#include "qemu/module.h"
#include "qapi/error.h"
#include "exec/address-spaces.h"
#include "hw/qdev-properties.h"
#include "hw/pci/pci_ids.h"
#include "hw/acpi/tpm.h"
#include "migration/vmstate.h"
#include "system/tpm_backend.h"
#include "system/tpm_util.h"
#include "tpm_prop.h"
#include "tpm_ppi.h"
#include "trace.h"
#include "qom/object.h"
#include "tpm_crb.h"
static uint8_t tpm_crb_get_active_locty(TPMCRBState *s, uint32_t *regs)
{
if (!ARRAY_FIELD_EX32(regs, CRB_LOC_STATE, locAssigned)) {
return TPM_CRB_NO_LOCALITY;
}
return ARRAY_FIELD_EX32(regs, CRB_LOC_STATE, activeLocality);
}
static void tpm_crb_mmio_write(void *opaque, hwaddr addr,
uint64_t val, unsigned size)
{
TPMCRBState *s = opaque;
uint8_t locty = addr >> 12;
uint32_t *regs;
void *mem;
trace_tpm_crb_mmio_write(addr, size, val);
regs = memory_region_get_ram_ptr(&s->mmio);
mem = &regs[R_CRB_DATA_BUFFER];
assert(regs);
/* receive TPM command bytes in DATA_BUFFER */
if (addr >= A_CRB_DATA_BUFFER) {
assert(addr + size <= TPM_CRB_ADDR_SIZE);
assert(size <= sizeof(val));
memcpy(mem + addr - A_CRB_DATA_BUFFER, &val, size);
memory_region_set_dirty(&s->mmio, addr, size);
return;
}
/* otherwise we are doing MMIO writes */
switch (addr) {
case A_CRB_CTRL_REQ:
switch (val) {
case CRB_CTRL_REQ_CMD_READY:
ARRAY_FIELD_DP32(regs, CRB_CTRL_STS,
tpmIdle, 0);
break;
case CRB_CTRL_REQ_GO_IDLE:
ARRAY_FIELD_DP32(regs, CRB_CTRL_STS,
tpmIdle, 1);
break;
}
break;
case A_CRB_CTRL_CANCEL:
if (val == CRB_CANCEL_INVOKE &&
regs[R_CRB_CTRL_START] & CRB_START_INVOKE) {
tpm_backend_cancel_cmd(s->tpmbe);
}
break;
case A_CRB_CTRL_START:
if (val == CRB_START_INVOKE &&
!(regs[R_CRB_CTRL_START] & CRB_START_INVOKE) &&
tpm_crb_get_active_locty(s, regs) == locty) {
regs[R_CRB_CTRL_START] |= CRB_START_INVOKE;
s->cmd = (TPMBackendCmd) {
.in = mem,
.in_len = MIN(tpm_cmd_get_size(mem), s->be_buffer_size),
.out = mem,
.out_len = s->be_buffer_size,
};
tpm_backend_deliver_request(s->tpmbe, &s->cmd);
}
break;
case A_CRB_LOC_CTRL:
switch (val) {
case CRB_LOC_CTRL_RESET_ESTABLISHMENT_BIT:
/* not loc 3 or 4 */
break;
case CRB_LOC_CTRL_RELINQUISH:
ARRAY_FIELD_DP32(regs, CRB_LOC_STATE,
locAssigned, 0);
ARRAY_FIELD_DP32(regs, CRB_LOC_STS,
Granted, 0);
break;
case CRB_LOC_CTRL_REQUEST_ACCESS:
ARRAY_FIELD_DP32(regs, CRB_LOC_STS,
Granted, 1);
ARRAY_FIELD_DP32(regs, CRB_LOC_STS,
beenSeized, 0);
ARRAY_FIELD_DP32(regs, CRB_LOC_STATE,
locAssigned, 1);
break;
}
break;
}
memory_region_set_dirty(&s->mmio, 0, A_CRB_DATA_BUFFER);
}
const MemoryRegionOps tpm_crb_memory_ops = {
.write = tpm_crb_mmio_write,
.endianness = DEVICE_LITTLE_ENDIAN,
.valid = {
.min_access_size = 1,
.max_access_size = 4,
},
};
void tpm_crb_request_completed(TPMCRBState *s, int ret)
{
uint32_t *regs = memory_region_get_ram_ptr(&s->mmio);
assert(regs);
regs[R_CRB_CTRL_START] &= ~CRB_START_INVOKE;
if (ret != 0) {
ARRAY_FIELD_DP32(regs, CRB_CTRL_STS,
tpmSts, 1); /* fatal error */
}
memory_region_set_dirty(&s->mmio, 0, TPM_CRB_ADDR_SIZE);
}
enum TPMVersion tpm_crb_get_version(TPMCRBState *s)
{
return tpm_backend_get_tpm_version(s->tpmbe);
}
int tpm_crb_pre_save(TPMCRBState *s)
{
tpm_backend_finish_sync(s->tpmbe);
return 0;
}
void tpm_crb_reset(TPMCRBState *s, uint64_t baseaddr)
{
uint32_t *regs = memory_region_get_ram_ptr(&s->mmio);
assert(regs);
if (s->ppi_enabled) {
tpm_ppi_reset(&s->ppi);
}
tpm_backend_reset(s->tpmbe);
memset(regs, 0, TPM_CRB_ADDR_SIZE);
ARRAY_FIELD_DP32(regs, CRB_LOC_STATE,
tpmRegValidSts, 1);
ARRAY_FIELD_DP32(regs, CRB_LOC_STATE,
tpmEstablished, 1);
ARRAY_FIELD_DP32(regs, CRB_CTRL_STS,
tpmIdle, 1);
ARRAY_FIELD_DP32(regs, CRB_INTF_ID,
InterfaceType, CRB_INTF_TYPE_CRB_ACTIVE);
ARRAY_FIELD_DP32(regs, CRB_INTF_ID,
InterfaceVersion, CRB_INTF_VERSION_CRB);
ARRAY_FIELD_DP32(regs, CRB_INTF_ID,
CapLocality, CRB_INTF_CAP_LOCALITY_0_ONLY);
ARRAY_FIELD_DP32(regs, CRB_INTF_ID,
CapCRBIdleBypass, CRB_INTF_CAP_IDLE_FAST);
ARRAY_FIELD_DP32(regs, CRB_INTF_ID,
CapDataXferSizeSupport, CRB_INTF_CAP_XFER_SIZE_64);
ARRAY_FIELD_DP32(regs, CRB_INTF_ID,
CapFIFO, CRB_INTF_CAP_FIFO_NOT_SUPPORTED);
ARRAY_FIELD_DP32(regs, CRB_INTF_ID,
CapCRB, CRB_INTF_CAP_CRB_SUPPORTED);
ARRAY_FIELD_DP32(regs, CRB_INTF_ID,
InterfaceSelector, CRB_INTF_IF_SELECTOR_CRB);
ARRAY_FIELD_DP32(regs, CRB_INTF_ID,
RID, 0b0000);
ARRAY_FIELD_DP32(regs, CRB_INTF_ID2,
VID, PCI_VENDOR_ID_IBM);
baseaddr += A_CRB_DATA_BUFFER;
regs[R_CRB_CTRL_CMD_SIZE] = CRB_CTRL_CMD_SIZE;
regs[R_CRB_CTRL_CMD_LADDR] = (uint32_t)baseaddr;
regs[R_CRB_CTRL_CMD_HADDR] = (uint32_t)(baseaddr >> 32);
regs[R_CRB_CTRL_RSP_SIZE] = CRB_CTRL_CMD_SIZE;
regs[R_CRB_CTRL_RSP_LADDR] = (uint32_t)baseaddr;
regs[R_CRB_CTRL_RSP_HADDR] = (uint32_t)(baseaddr >> 32);
s->be_buffer_size = MIN(tpm_backend_get_buffer_size(s->tpmbe),
CRB_CTRL_CMD_SIZE);
if (tpm_backend_startup_tpm(s->tpmbe, s->be_buffer_size) < 0) {
exit(1);
}
memory_region_rom_device_set_romd(&s->mmio, true);
memory_region_set_dirty(&s->mmio, 0, TPM_CRB_ADDR_SIZE);
}
void tpm_crb_init_memory(Object *obj, TPMCRBState *s, Error **errp)
{
uint64_t page_size = qemu_real_host_page_size();
memory_region_init_rom_device_nomigrate(&s->mmio, obj, &tpm_crb_memory_ops,
s, "tpm-crb-mem", ROUND_UP(TPM_CRB_ADDR_SIZE, page_size), errp);
if (s->ppi_enabled) {
tpm_ppi_init_memory(&s->ppi, obj);
}
}
void tpm_crb_mem_save(TPMCRBState *s, uint32_t *saved_regs, void *saved_cmdmem)
{
uint32_t *regs = memory_region_get_ram_ptr(&s->mmio);
memcpy(saved_regs, regs, A_CRB_DATA_BUFFER);
memcpy(saved_cmdmem, &regs[R_CRB_DATA_BUFFER], CRB_CTRL_CMD_SIZE);
}
void tpm_crb_mem_load(TPMCRBState *s, const uint32_t *saved_regs,
const void *saved_cmdmem)
{
uint32_t *regs = memory_region_get_ram_ptr(&s->mmio);
memcpy(regs, saved_regs, A_CRB_DATA_BUFFER);
memcpy(&regs[R_CRB_DATA_BUFFER], saved_cmdmem, CRB_CTRL_CMD_SIZE);
}
void tpm_crb_build_aml(TPMIf *ti, Aml *scope, uint32_t baseaddr, uint32_t size,
bool build_ppi)
{
Aml *dev, *crs;
dev = aml_device("TPM");
aml_append(dev, aml_name_decl("_HID", aml_string("MSFT0101")));
aml_append(dev, aml_name_decl("_STR", aml_string("TPM 2.0 Device")));
aml_append(dev, aml_name_decl("_UID", aml_int(1)));
aml_append(dev, aml_name_decl("_STA", aml_int(0xF)));
crs = aml_resource_template();
aml_append(crs, aml_memory32_fixed(baseaddr, size, AML_READ_WRITE));
aml_append(dev, aml_name_decl("_CRS", crs));
if (build_ppi) {
tpm_build_ppi_acpi(ti, dev);
}
aml_append(scope, dev);
}
+161
View File
@@ -0,0 +1,161 @@
/*
* tpm_crb_sysbus.c - QEMU's TPM CRB interface emulator
*
* Copyright (c) 2018 Red Hat, Inc.
*
* Authors:
* Marc-André Lureau <marcandre.lureau@redhat.com>
* Joelle van Dyne <j@getutm.app>
*
* This work is licensed under the terms of the GNU GPL, version 2 or later.
* See the COPYING file in the top-level directory.
*
* tpm_crb is a device for TPM 2.0 Command Response Buffer (CRB) Interface
* as defined in TCG PC Client Platform TPM Profile (PTP) Specification
* Family “2.0” Level 00 Revision 01.03 v22
*/
#include "qemu/osdep.h"
#include "hw/acpi/acpi_aml_interface.h"
#include "hw/acpi/tpm.h"
#include "hw/qdev-properties.h"
#include "migration/vmstate.h"
#include "tpm_prop.h"
#include "hw/sysbus.h"
#include "qapi/visitor.h"
#include "qom/object.h"
#include "system/tpm_util.h"
#include "trace.h"
#include "tpm_crb.h"
struct TPMCRBStateSysBus {
/*< private >*/
SysBusDevice parent_obj;
/*< public >*/
TPMCRBState state;
uint64_t baseaddr;
uint64_t size;
};
OBJECT_DECLARE_SIMPLE_TYPE(TPMCRBStateSysBus, TPM_CRB_SYSBUS)
static void tpm_crb_sysbus_request_completed(TPMIf *ti, int ret)
{
TPMCRBStateSysBus *s = TPM_CRB_SYSBUS(ti);
return tpm_crb_request_completed(&s->state, ret);
}
static enum TPMVersion tpm_crb_sysbus_get_tpm_version(TPMIf *ti)
{
TPMCRBStateSysBus *s = TPM_CRB_SYSBUS(ti);
return tpm_crb_get_version(&s->state);
}
static int tpm_crb_sysbus_pre_save(void *opaque)
{
TPMCRBStateSysBus *s = opaque;
return tpm_crb_pre_save(&s->state);
}
static const VMStateDescription vmstate_tpm_crb_sysbus = {
.name = "tpm-crb-sysbus",
.pre_save = tpm_crb_sysbus_pre_save,
.fields = (const VMStateField[]) {
VMSTATE_END_OF_LIST(),
}
};
static const Property tpm_crb_sysbus_properties[] = {
DEFINE_PROP_TPMBE("tpmdev", TPMCRBStateSysBus, state.tpmbe),
DEFINE_PROP_UINT64("x-baseaddr", TPMCRBStateSysBus,
baseaddr, TPM_CRB_ADDR_BASE),
DEFINE_PROP_UINT64("x-size", TPMCRBStateSysBus,
size, TPM_CRB_ADDR_SIZE),
};
static void tpm_crb_sysbus_initfn(Object *obj)
{
TPMCRBStateSysBus *s = TPM_CRB_SYSBUS(obj);
tpm_crb_init_memory(obj, &s->state, NULL);
vmstate_register_ram(&s->state.mmio, DEVICE(obj));
sysbus_init_mmio(SYS_BUS_DEVICE(obj), &s->state.mmio);
}
static void tpm_crb_sysbus_reset(DeviceState *dev)
{
TPMCRBStateSysBus *s = TPM_CRB_SYSBUS(dev);
return tpm_crb_reset(&s->state, s->baseaddr);
}
static void tpm_crb_sysbus_realizefn(DeviceState *dev, Error **errp)
{
TPMCRBStateSysBus *s = TPM_CRB_SYSBUS(dev);
if (!tpm_find()) {
error_setg(errp, "at most one TPM device is permitted");
return;
}
if (!s->state.tpmbe) {
error_setg(errp, "'tpmdev' property is required");
return;
}
if (tpm_crb_sysbus_get_tpm_version(TPM_IF(s)) != TPM_VERSION_2_0) {
error_setg(errp, "TPM CRB only supports TPM 2.0 backends");
return;
}
}
static void build_tpm_crb_sysbus_aml(AcpiDevAmlIf *adev, Aml *scope)
{
TPMCRBStateSysBus *s = TPM_CRB_SYSBUS(adev);
tpm_crb_build_aml(TPM_IF(adev), scope, s->baseaddr, s->size, false);
}
static void tpm_crb_sysbus_class_init(ObjectClass *klass, void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
TPMIfClass *tc = TPM_IF_CLASS(klass);
AcpiDevAmlIfClass *adevc = ACPI_DEV_AML_IF_CLASS(klass);
device_class_set_props(dc, tpm_crb_sysbus_properties);
dc->vmsd = &vmstate_tpm_crb_sysbus;
tc->model = TPM_MODEL_TPM_CRB;
dc->realize = tpm_crb_sysbus_realizefn;
dc->user_creatable = true;
device_class_set_legacy_reset(dc, tpm_crb_sysbus_reset);
tc->request_completed = tpm_crb_sysbus_request_completed;
tc->get_version = tpm_crb_sysbus_get_tpm_version;
set_bit(DEVICE_CATEGORY_MISC, dc->categories);
adevc->build_dev_aml = build_tpm_crb_sysbus_aml;
}
static const TypeInfo tpm_crb_sysbus_info = {
.name = TYPE_TPM_CRB_SYSBUS,
.parent = TYPE_SYS_BUS_DEVICE,
.instance_size = sizeof(TPMCRBStateSysBus),
.instance_init = tpm_crb_sysbus_initfn,
.class_init = tpm_crb_sysbus_class_init,
.interfaces = (InterfaceInfo[]) {
{ TYPE_TPM_IF },
{ TYPE_ACPI_DEV_AML_IF },
{ }
}
};
static void tpm_crb_sysbus_register(void)
{
type_register_static(&tpm_crb_sysbus_info);
}
type_init(tpm_crb_sysbus_register)
+1 -4
View File
@@ -44,8 +44,7 @@ void tpm_ppi_reset(TPMPPI *tpmppi)
}
}
void tpm_ppi_init(TPMPPI *tpmppi, MemoryRegion *m,
hwaddr addr, Object *obj)
void tpm_ppi_init_memory(TPMPPI *tpmppi, Object *obj)
{
size_t host_page_size = qemu_real_host_page_size();
@@ -54,6 +53,4 @@ void tpm_ppi_init(TPMPPI *tpmppi, MemoryRegion *m,
memory_region_init_ram_device_ptr(&tpmppi->ram, obj, "tpm-ppi",
TPM_PPI_ADDR_SIZE, tpmppi->buf);
vmstate_register_ram(&tpmppi->ram, DEVICE(obj));
memory_region_add_subregion(m, addr, &tpmppi->ram);
}
+3 -7
View File
@@ -20,17 +20,13 @@ typedef struct TPMPPI {
} TPMPPI;
/**
* tpm_ppi_init:
* tpm_ppi_init_memory:
* @tpmppi: a TPMPPI
* @m: the address-space / MemoryRegion to use
* @addr: the address of the PPI region
* @obj: the owner object
*
* Register the TPM PPI memory region at @addr on the given address
* space for the object @obj.
* Creates the TPM PPI memory region.
**/
void tpm_ppi_init(TPMPPI *tpmppi, MemoryRegion *m,
hwaddr addr, Object *obj);
void tpm_ppi_init_memory(TPMPPI *tpmppi, Object *obj);
/**
* tpm_ppi_reset:
+3 -2
View File
@@ -133,8 +133,9 @@ static void tpm_tis_isa_realizefn(DeviceState *dev, Error **errp)
TPM_TIS_ADDR_BASE, &s->mmio);
if (s->ppi_enabled) {
tpm_ppi_init(&s->ppi, isa_address_space(ISA_DEVICE(dev)),
TPM_PPI_ADDR_BASE, OBJECT(dev));
tpm_ppi_init_memory(&s->ppi, OBJECT(dev));
memory_region_add_subregion(isa_address_space(ISA_DEVICE(dev)),
TPM_PPI_ADDR_BASE, &s->ppi.ram);
}
}
+37
View File
@@ -30,6 +30,7 @@
#include "hw/sysbus.h"
#include "tpm_tis.h"
#include "qom/object.h"
#include "hw/acpi/acpi_aml_interface.h"
struct TPMStateSysBus {
/*< private >*/
@@ -37,6 +38,8 @@ struct TPMStateSysBus {
/*< public >*/
TPMState state; /* not a QOM object */
uint64_t baseaddr;
uint64_t size;
};
OBJECT_DECLARE_SIMPLE_TYPE(TPMStateSysBus, TPM_TIS_SYSBUS)
@@ -93,6 +96,10 @@ static void tpm_tis_sysbus_reset(DeviceState *dev)
static const Property tpm_tis_sysbus_properties[] = {
DEFINE_PROP_UINT32("irq", TPMStateSysBus, state.irq_num, TPM_TIS_IRQ),
DEFINE_PROP_TPMBE("tpmdev", TPMStateSysBus, state.be_driver),
DEFINE_PROP_UINT64("x-baseaddr", TPMStateSysBus, baseaddr,
TPM_TIS_ADDR_BASE),
DEFINE_PROP_UINT64("x-size", TPMStateSysBus, size,
TPM_TIS_ADDR_SIZE),
};
static void tpm_tis_sysbus_initfn(Object *obj)
@@ -124,10 +131,38 @@ static void tpm_tis_sysbus_realizefn(DeviceState *dev, Error **errp)
}
}
static void build_tpm_tis_sysbus_aml(AcpiDevAmlIf *adev, Aml *scope)
{
Aml *dev, *crs;
TPMStateSysBus *sbdev = TPM_TIS_SYSBUS(adev);
TPMIf *ti = TPM_IF(sbdev);
dev = aml_device("TPM");
if (tpm_tis_sysbus_get_tpm_version(ti) == TPM_VERSION_2_0) {
aml_append(dev, aml_name_decl("_HID", aml_string("MSFT0101")));
aml_append(dev, aml_name_decl("_STR", aml_string("TPM 2.0 Device")));
} else {
aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0C31")));
}
aml_append(dev, aml_name_decl("_UID", aml_int(0)));
aml_append(dev, aml_name_decl("_STA", aml_int(0xF)));
crs = aml_resource_template();
aml_append(crs, aml_memory32_fixed(sbdev->baseaddr, sbdev->size,
AML_READ_WRITE));
/*
* FIXME: TPM_TIS_IRQ=5 conflicts with PNP0C0F irqs,
* fix default TPM_TIS_IRQ value there to use some unused IRQ
*/
/* aml_append(crs, aml_irq_no_flags(sbdev->state.irq_num)); */
aml_append(dev, aml_name_decl("_CRS", crs));
aml_append(scope, dev);
}
static void tpm_tis_sysbus_class_init(ObjectClass *klass, void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
TPMIfClass *tc = TPM_IF_CLASS(klass);
AcpiDevAmlIfClass *adevc = ACPI_DEV_AML_IF_CLASS(klass);
device_class_set_props(dc, tpm_tis_sysbus_properties);
dc->vmsd = &vmstate_tpm_tis_sysbus;
@@ -137,6 +172,7 @@ static void tpm_tis_sysbus_class_init(ObjectClass *klass, void *data)
tc->request_completed = tpm_tis_sysbus_request_completed;
tc->get_version = tpm_tis_sysbus_get_tpm_version;
set_bit(DEVICE_CATEGORY_MISC, dc->categories);
adevc->build_dev_aml = build_tpm_tis_sysbus_aml;
}
static const TypeInfo tpm_tis_sysbus_info = {
@@ -147,6 +183,7 @@ static const TypeInfo tpm_tis_sysbus_info = {
.class_init = tpm_tis_sysbus_class_init,
.interfaces = (InterfaceInfo[]) {
{ TYPE_TPM_IF },
{ TYPE_ACPI_DEV_AML_IF },
{ }
}
};
+1 -1
View File
@@ -1,6 +1,6 @@
# See docs/devel/tracing.rst for syntax documentation.
# tpm_crb.c
# tpm_crb_common.c
tpm_crb_mmio_read(uint64_t addr, unsigned size, uint32_t val) "CRB read 0x%016" PRIx64 " len:%u val: 0x%" PRIx32
tpm_crb_mmio_write(uint64_t addr, unsigned size, uint32_t val) "CRB write 0x%016" PRIx64 " len:%u val: 0x%" PRIx32
+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;
}
}
+37 -7
View File
@@ -1283,7 +1283,8 @@ static void usbredir_create_parser(USBRedirDevice *dev)
}
#endif
if (runstate_check(RUN_STATE_INMIGRATE)) {
if (runstate_check(RUN_STATE_INMIGRATE) ||
runstate_check(RUN_STATE_RESTORE_VM)) {
flags |= usbredirparser_fl_no_hello;
}
usbredirparser_init(dev->parser, VERSION, caps, USB_REDIR_CAPS_SIZE,
@@ -1644,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)
{
@@ -1676,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,
@@ -2001,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 &&
+5 -1
View File
@@ -13,10 +13,14 @@
#endif
/* GETPC is the true target of the return instruction that we'll execute. */
#ifdef CONFIG_TCG_INTERPRETER
#if defined(CONFIG_TCG_INTERPRETER)
extern __thread uintptr_t tci_tb_ptr;
# define GETPC() tci_tb_ptr
#elif defined(CONFIG_TCG_THREADED_INTERPRETER)
extern __thread uintptr_t tcti_call_return_address;
# define GETPC() tcti_call_return_address
#else
/* Note that this is correct for TCTI also; whose gadget behaves like native code. */
# define GETPC() \
((uintptr_t)__builtin_extract_return_addr(__builtin_return_address(0)))
#endif
+1
View File
@@ -412,6 +412,7 @@ typedef struct disassemble_info {
typedef int (*disassembler_ftype) (bfd_vma, disassemble_info *);
int print_insn_tci(bfd_vma, disassemble_info*);
int print_insn_tcti(bfd_vma, disassemble_info*);
int print_insn_big_mips (bfd_vma, disassemble_info*);
int print_insn_little_mips (bfd_vma, disassemble_info*);
int print_insn_nanomips (bfd_vma, disassemble_info*);
+2 -1
View File
@@ -174,7 +174,8 @@ REG32(CRB_CTRL_CMD_SIZE, 0x58)
REG32(CRB_CTRL_CMD_LADDR, 0x5C)
REG32(CRB_CTRL_CMD_HADDR, 0x60)
REG32(CRB_CTRL_RSP_SIZE, 0x64)
REG32(CRB_CTRL_RSP_ADDR, 0x68)
REG32(CRB_CTRL_RSP_LADDR, 0x68)
REG32(CRB_CTRL_RSP_HADDR, 0x6C)
REG32(CRB_DATA_BUFFER, 0x80)
#define TPM_CRB_ADDR_BASE 0xFED40000
+77
View File
@@ -0,0 +1,77 @@
/*
* QEMU PowerMac Awacs Screamer device support
*
* Copyright (c) 2016 Mark Cave-Ayland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef HW_AUDIO_SCREAMER_H
#define HW_AUDIO_SCREAMER_H
#include "qemu/osdep.h"
#include "hw/sysbus.h"
#include "hw/ppc/mac_dbdma.h"
#include "audio/audio.h"
#define TYPE_SCREAMER "screamer"
OBJECT_DECLARE_SIMPLE_TYPE(ScreamerState, SCREAMER)
#define SCREAMER_BUFFER_SIZE 0x4000
struct ScreamerState {
/*< private >*/
SysBusDevice parent_obj;
/*< public >*/
MemoryRegion mem;
qemu_irq irq;
void *dbdma;
qemu_irq dma_tx_irq;
qemu_irq dma_rx_irq;
QEMUSoundCard card;
SWVoiceOut *voice;
uint8_t *mixbuf; /* ring of TX frames waiting for the host */
int samples; /* ring size in frames */
int shift;
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];
};
void macio_screamer_register_dma(ScreamerState *s, void *dbdma, int txchannel, int rxchannel);
#endif
+1
View File
@@ -66,6 +66,7 @@ struct GICv3ITSState {
int dev_fd; /* kvm device fd if backed by kvm vgic support */
uint64_t gits_translater_gpa;
bool translater_gpa_known;
uint8_t itt_entry_size;
/* Registers */
uint32_t ctlr;
+9
View File
@@ -36,6 +36,7 @@
#include "hw/nvram/mac_nvram.h"
#include "hw/ppc/mac_dbdma.h"
#include "hw/ppc/openpic.h"
#include "hw/audio/screamer.h"
#include "qom/object.h"
/* Old World IRQs */
@@ -46,6 +47,9 @@
#define OLDWORLD_IDE0_DMA_IRQ 0x2
#define OLDWORLD_IDE1_IRQ 0xe
#define OLDWORLD_IDE1_DMA_IRQ 0x3
#define OLDWORLD_SCREAMER_TX_IRQ 0x11
#define OLDWORLD_SCREAMER_TX_DMA_IRQ 0x08
#define OLDWORLD_SCREAMER_RX_IRQ 0x09
/* New World IRQs */
#define NEWWORLD_CUDA_IRQ 0x19
@@ -58,6 +62,9 @@
#define NEWWORLD_IDE1_DMA_IRQ 0x3
#define NEWWORLD_EXTING_GPIO1 0x2f
#define NEWWORLD_EXTING_GPIO9 0x37
#define NEWWORLD_SCREAMER_IRQ 0x18
#define NEWWORLD_SCREAMER_DMA_IRQ 0x09
#define NEWWORLD_SCREAMER_RX_IRQ 0x0a
/* MacIO virtual bus */
#define TYPE_MACIO_BUS "macio-bus"
@@ -112,6 +119,7 @@ struct MacIOState {
PMUState pmu;
DBDMAState dbdma;
ESCCState escc;
ScreamerState screamer;
uint64_t frequency;
};
@@ -140,6 +148,7 @@ struct NewWorldMacIOState {
bool has_pmu;
bool has_adb;
OpenPICState pic;
MACIOIDEState ide[2];
MacIOGPIOState gpio;
};
+68 -1
View File
@@ -100,6 +100,7 @@ enum virtio_gpu_base_conf_flags {
VIRTIO_GPU_FLAG_RUTABAGA_ENABLED,
VIRTIO_GPU_FLAG_VENUS_ENABLED,
VIRTIO_GPU_FLAG_RESOURCE_UUID_ENABLED,
VIRTIO_GPU_FLAG_NEPTUNE_ENABLED,
};
#define virtio_gpu_virgl_enabled(_cfg) \
@@ -122,12 +123,16 @@ enum virtio_gpu_base_conf_flags {
(_cfg.hostmem > 0)
#define virtio_gpu_venus_enabled(_cfg) \
(_cfg.flags & (1 << VIRTIO_GPU_FLAG_VENUS_ENABLED))
#define virtio_gpu_neptune_enabled(_cfg) \
(_cfg.flags & (1 << VIRTIO_GPU_FLAG_NEPTUNE_ENABLED))
struct virtio_gpu_base_conf {
uint32_t max_outputs;
uint32_t flags;
uint32_t xres;
uint32_t yres;
/* mHz, used when the display reports none */
uint32_t refresh_rate;
uint64_t hostmem;
};
@@ -137,9 +142,29 @@ struct virtio_gpu_ctrl_command {
struct virtio_gpu_ctrl_hdr cmd_hdr;
uint32_t error;
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;
@@ -153,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];
@@ -171,11 +204,21 @@ 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;
uint32_t scanout_id;
/* Source identity of the scanout request that created this dmabuf, so a
* re-present of the SAME underlying buffer -- including a flip chain
* alternating between a small set of buffers -- can switch scanout
* without a costly EGL/GL re-import (which churns/hangs the display
* thread). */
int src_fd;
uint32_t src_res_id;
uint32_t src_w, src_h, src_x, src_y;
uint32_t fb_w, fb_h, fb_stride, fb_format;
QTAILQ_ENTRY(VGPUDMABuf) next;
} VGPUDMABuf;
@@ -231,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 */
@@ -239,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;
@@ -248,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 {
@@ -340,6 +400,9 @@ void virtio_gpu_cleanup_mapping(VirtIOGPU *g,
void virtio_gpu_process_cmdq(VirtIOGPU *g);
void virtio_gpu_device_realize(DeviceState *qdev, Error **errp);
void virtio_gpu_reset(VirtIODevice *vdev);
void virtio_gpu_resource_destroy(VirtIOGPU *g,
struct virtio_gpu_simple_resource *res,
Error **errp);
void virtio_gpu_simple_process_cmd(VirtIOGPU *g, struct virtio_gpu_ctrl_command *cmd);
void virtio_gpu_update_cursor_data(VirtIOGPU *g,
struct virtio_gpu_scanout *s,
@@ -383,7 +446,11 @@ void virtio_gpu_virgl_process_cmd(VirtIOGPU *g,
void virtio_gpu_virgl_fence_poll(VirtIOGPU *g);
void virtio_gpu_virgl_reset_scanout(VirtIOGPU *g);
void virtio_gpu_virgl_reset(VirtIOGPU *g);
void virtio_gpu_virgl_resource_destroy(VirtIOGPU *g,
struct virtio_gpu_simple_resource *res,
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
+1 -20
View File
@@ -807,29 +807,10 @@ int qemu_msync(void *addr, size_t length, int fd);
*/
size_t qemu_get_host_physmem(void);
/*
* Toggle write/execute on the pages marked MAP_JIT
* for the current thread.
*/
#ifdef __APPLE__
static inline void qemu_thread_jit_execute(void)
{
pthread_jit_write_protect_np(true);
}
static inline void qemu_thread_jit_write(void)
{
pthread_jit_write_protect_np(false);
}
#else
static inline void qemu_thread_jit_write(void) {}
static inline void qemu_thread_jit_execute(void) {}
#endif
/**
* Platforms which do not support system() return ENOSYS
*/
#ifndef HAVE_SYSTEM_FUNCTION
#if !defined(HAVE_SYSTEM_FUNCTION) || defined(CONFIG_IOS)
#define system platform_does_not_support_system
static inline int platform_does_not_support_system(const char *command)
{
@@ -312,6 +312,7 @@ struct virtio_gpu_cmd_submit {
/* 3 is reserved for gfxstream */
#define VIRTIO_GPU_CAPSET_VENUS 4
#define VIRTIO_GPU_CAPSET_DRM 6
#define VIRTIO_GPU_CAPSET_NEPTUNE 7
/* VIRTIO_GPU_CMD_GET_CAPSET_INFO */
struct virtio_gpu_get_capset_info {
+30 -2
View File
@@ -19,9 +19,25 @@ typedef hv_vcpu_t hvf_vcpuid;
typedef hv_vcpuid_t hvf_vcpuid;
#endif
#if defined(CONFIG_HVF_PRIVATE)
extern hv_return_t _hv_vm_config_set_isa(hv_vm_config_t config, uint32_t isa);
extern hv_return_t _hv_vcpu_get_actlr(hv_vcpu_t vcpu, uint64_t* value);
extern hv_return_t _hv_vcpu_set_actlr(hv_vcpu_t vcpu, uint64_t value);
#endif
#if defined(__aarch64__)
#if defined(CONFIG_HVF_PRIVATE)
#define HV_VM_CONFIG_ISA_PRIVATE (3)
#define ACTLR_EL1_TSO_ENABLE_MASK ((1 << 1) | (1 << 9))
#else
#define ACTLR_EL1_TSO_ENABLE_MASK ((1 << 1))
#endif
#endif
/* hvf_slot flags */
#define HVF_SLOT_LOG (1 << 0)
/* Represent memory logically mapped by QEMU */
typedef struct hvf_slot {
uint64_t start;
uint64_t size;
@@ -31,6 +47,14 @@ typedef struct hvf_slot {
MemoryRegion *region;
} hvf_slot;
/* Represent memory currently mapped in HVF */
typedef struct hvf_mac_slot {
int present;
uint64_t size;
uint64_t gpa_start;
uint64_t gva;
} hvf_mac_slot;
typedef struct hvf_vcpu_caps {
uint64_t vmx_cap_pinbased;
uint64_t vmx_cap_procbased;
@@ -42,7 +66,8 @@ typedef struct hvf_vcpu_caps {
struct HVFState {
AccelState parent;
hvf_slot slots[32];
hvf_slot *slots;
hvf_mac_slot *mac_slots;
int num_slots;
hvf_vcpu_caps *hvf_caps;
@@ -50,6 +75,8 @@ struct HVFState {
QTAILQ_HEAD(, hvf_sw_breakpoint) hvf_sw_breakpoints;
};
extern HVFState *hvf_state;
extern bool hvf_tso_mode;
extern uint32_t hvf_ipa_granule_size;
struct AccelCPUState {
hvf_vcpuid fd;
@@ -65,7 +92,8 @@ void assert_hvf_ok_impl(hv_return_t ret, const char *file, unsigned int line,
#define assert_hvf_ok(EX) assert_hvf_ok_impl((EX), __FILE__, __LINE__, #EX)
const char *hvf_return_string(hv_return_t ret);
int hvf_arch_init(void);
hv_return_t hvf_arch_vm_create(MachineState *ms, uint32_t pa_range);
hv_return_t hvf_arch_vm_create(MachineState *ms, uint32_t pa_range,
uint32_t ipa_granule_size);
int hvf_arch_init_vcpu(CPUState *cpu);
void hvf_arch_vcpu_destroy(CPUState *cpu);
int hvf_vcpu_exec(CPUState *);
+1
View File
@@ -166,6 +166,7 @@ struct KVMState
uint16_t xen_gnttab_max_frames;
uint16_t xen_evtchn_max_pirq;
char *device;
OnOffAuto honor_guest_pat;
};
void kvm_memory_listener_register(KVMState *s, KVMMemoryListener *kml,
+7
View File
@@ -12,6 +12,8 @@
#ifndef QEMU_TPM_H
#define QEMU_TPM_H
#include "qemu/osdep.h"
#include "exec/hwaddr.h"
#include "qapi/qapi-types-tpm.h"
#include "qom/object.h"
@@ -47,6 +49,7 @@ struct TPMIfClass {
#define TYPE_TPM_TIS_ISA "tpm-tis"
#define TYPE_TPM_TIS_SYSBUS "tpm-tis-device"
#define TYPE_TPM_CRB "tpm-crb"
#define TYPE_TPM_CRB_SYSBUS "tpm-crb-device"
#define TYPE_TPM_SPAPR "tpm-spapr"
#define TYPE_TPM_TIS_I2C "tpm-tis-i2c"
@@ -56,6 +59,8 @@ struct TPMIfClass {
object_dynamic_cast(OBJECT(chr), TYPE_TPM_TIS_SYSBUS)
#define TPM_IS_CRB(chr) \
object_dynamic_cast(OBJECT(chr), TYPE_TPM_CRB)
#define TPM_IS_CRB_SYSBUS(chr) \
object_dynamic_cast(OBJECT(chr), TYPE_TPM_CRB_SYSBUS)
#define TPM_IS_SPAPR(chr) \
object_dynamic_cast(OBJECT(chr), TYPE_TPM_SPAPR)
#define TPM_IS_TIS_I2C(chr) \
@@ -78,6 +83,8 @@ static inline TPMVersion tpm_get_version(TPMIf *ti)
return TPM_IF_GET_CLASS(ti)->get_version(ti);
}
void tpm_sysbus_plug(TPMIf *tpmif, Object *pbus, hwaddr pbus_base);
#else /* CONFIG_TPM */
#define tpm_init() (0)
+100
View File
@@ -0,0 +1,100 @@
/*
* Apple Silicon functions for JIT handling
*
* Copyright (c) 2020 osy
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TCG_APPLE_JIT_H
#define TCG_APPLE_JIT_H
/*
* APRR handling
* Credits to: https://siguza.github.io/APRR/
* Reversed from /usr/lib/system/libsystem_pthread.dylib
*/
#if defined(__aarch64__) && defined(CONFIG_DARWIN)
#define _COMM_PAGE_START_ADDRESS (0x0000000FFFFFC000ULL) /* In TTBR0 */
#define _COMM_PAGE_APRR_SUPPORT (_COMM_PAGE_START_ADDRESS + 0x10C)
#define _COMM_PAGE_APPR_WRITE_ENABLE (_COMM_PAGE_START_ADDRESS + 0x110)
#define _COMM_PAGE_APRR_WRITE_DISABLE (_COMM_PAGE_START_ADDRESS + 0x118)
static __attribute__((__always_inline__)) bool jit_write_protect_supported(void)
{
/* Access shared kernel page at fixed memory location. */
uint8_t aprr_support = *(volatile uint8_t *)_COMM_PAGE_APRR_SUPPORT;
return aprr_support > 0;
}
/* write protect enable = write disable */
static __attribute__((__always_inline__)) void jit_write_protect(int enabled)
{
/* Access shared kernel page at fixed memory location. */
uint8_t aprr_support = *(volatile uint8_t *)_COMM_PAGE_APRR_SUPPORT;
if (aprr_support == 0 || aprr_support > 3) {
return;
} else if (aprr_support == 1) {
__asm__ __volatile__ (
"mov x0, %0\n"
"ldr x0, [x0]\n"
"msr S3_4_c15_c2_7, x0\n"
"isb sy\n"
:: "r" (enabled ? _COMM_PAGE_APRR_WRITE_DISABLE
: _COMM_PAGE_APPR_WRITE_ENABLE)
: "memory", "x0"
);
} else {
__asm__ __volatile__ (
"mov x0, %0\n"
"ldr x0, [x0]\n"
"msr S3_6_c15_c1_5, x0\n"
"isb sy\n"
:: "r" (enabled ? _COMM_PAGE_APRR_WRITE_DISABLE
: _COMM_PAGE_APPR_WRITE_ENABLE)
: "memory", "x0"
);
}
}
#else /* defined(__aarch64__) && defined(CONFIG_DARWIN) */
static __attribute__((__always_inline__)) bool jit_write_protect_supported(void)
{
return false;
}
static __attribute__((__always_inline__)) void jit_write_protect(int enabled)
{
}
#endif
static inline void qemu_thread_jit_execute(void)
{
if (jit_write_protect_supported()) {
jit_write_protect(true);
}
}
static inline void qemu_thread_jit_write(void)
{
if (jit_write_protect_supported()) {
jit_write_protect(false);
}
}
#endif /* define TCG_APPLE_JIT_H */
+12
View File
@@ -40,7 +40,11 @@ DEF(mb, 0, 0, 1, TCG_OPF_NOT_PRESENT)
DEF(mov_i32, 1, 1, 0, TCG_OPF_NOT_PRESENT)
DEF(setcond_i32, 1, 2, 1, 0)
DEF(negsetcond_i32, 1, 2, 1, 0)
#if defined(CONFIG_TCG_THREADED_INTERPRETER)
DEF(movcond_i32, 1, 4, 1, TCG_OPF_NOT_PRESENT)
#else
DEF(movcond_i32, 1, 4, 1, 0)
#endif
/* load/store */
DEF(ld8u_i32, 1, 1, 1, 0)
DEF(ld8s_i32, 1, 1, 1, 0)
@@ -105,7 +109,11 @@ DEF(ctpop_i32, 1, 1, 0, 0)
DEF(mov_i64, 1, 1, 0, TCG_OPF_NOT_PRESENT)
DEF(setcond_i64, 1, 2, 1, 0)
DEF(negsetcond_i64, 1, 2, 1, 0)
#if defined(CONFIG_TCG_THREADED_INTERPRETER)
DEF(movcond_i64, 1, 4, 1, TCG_OPF_NOT_PRESENT)
#else
DEF(movcond_i64, 1, 4, 1, 0)
#endif
/* load/store */
DEF(ld8u_i64, 1, 1, 1, 0)
DEF(ld8s_i64, 1, 1, 1, 0)
@@ -183,7 +191,11 @@ DEF(insn_start, 0, 0, DATA64_ARGS, TCG_OPF_NOT_PRESENT)
DEF(exit_tb, 0, 0, 1, TCG_OPF_BB_EXIT | TCG_OPF_BB_END | TCG_OPF_NOT_PRESENT)
DEF(goto_tb, 0, 0, 1, TCG_OPF_BB_EXIT | TCG_OPF_BB_END | TCG_OPF_NOT_PRESENT)
#if defined(CONFIG_TCG_THREADED_INTERPRETER)
DEF(goto_ptr, 0, 1, 0, TCG_OPF_BB_EXIT | TCG_OPF_BB_END | TCG_OPF_NOT_PRESENT)
#else
DEF(goto_ptr, 0, 1, 0, TCG_OPF_BB_EXIT | TCG_OPF_BB_END)
#endif
DEF(plugin_cb, 0, 0, 1, TCG_OPF_NOT_PRESENT)
DEF(plugin_mem_cb, 0, 1, 1, TCG_OPF_NOT_PRESENT)
+1 -1
View File
@@ -940,7 +940,7 @@ static inline size_t tcg_current_code_size(TCGContext *s)
#define TB_EXIT_IDXMAX 1
#define TB_EXIT_REQUESTED 3
#ifdef CONFIG_TCG_INTERPRETER
#if defined(CONFIG_TCG_INTERPRETER) || defined(CONFIG_TCG_THREADED_INTERPRETER)
uintptr_t tcg_qemu_tb_exec(CPUArchState *env, const void *tb_ptr);
#else
typedef uintptr_t tcg_prologue_fn(CPUArchState *env, const void *tb_ptr);
+25 -3
View File
@@ -131,6 +131,26 @@ struct QemuConsoleClass {
ObjectClass parent_class;
};
typedef enum ScanoutTextureNativeType {
SCANOUT_TEXTURE_NATIVE_TYPE_NONE,
SCANOUT_TEXTURE_NATIVE_TYPE_D3D,
SCANOUT_TEXTURE_NATIVE_TYPE_METAL,
} ScanoutTextureNativeType;
typedef struct ScanoutTextureNative {
ScanoutTextureNativeType type;
void *handle;
} ScanoutTextureNative;
#define NO_NATIVE_TEXTURE ((ScanoutTextureNative){ \
.type = SCANOUT_TEXTURE_NATIVE_TYPE_NONE \
})
/**
* Cleanup callback function when ScanoutTexture is about to be destroyed
*/
typedef void (*ScanoutTextureCleanup)(ScanoutTextureNative *native);
typedef struct ScanoutTexture {
uint32_t backing_id;
bool backing_y_0_top;
@@ -140,7 +160,8 @@ typedef struct ScanoutTexture {
uint32_t y;
uint32_t width;
uint32_t height;
void *d3d_tex2d;
ScanoutTextureNative native;
ScanoutTextureCleanup cb_cleanup;
} ScanoutTexture;
typedef struct QemuUIInfo {
@@ -245,7 +266,7 @@ typedef struct DisplayChangeListenerOps {
uint32_t backing_height,
uint32_t x, uint32_t y,
uint32_t w, uint32_t h,
void *d3d_tex2d);
ScanoutTextureNative native);
/* optional (default to true if has dpy_gl_scanout_dmabuf) */
bool (*dpy_has_dmabuf)(DisplayChangeListener *dcl);
/* optional */
@@ -329,7 +350,8 @@ void dpy_gl_scanout_texture(QemuConsole *con,
uint32_t backing_id, bool backing_y_0_top,
uint32_t backing_width, uint32_t backing_height,
uint32_t x, uint32_t y, uint32_t w, uint32_t h,
void *d3d_tex2d);
ScanoutTextureNative native,
ScanoutTextureCleanup cb_cleanup);
void dpy_gl_scanout_dmabuf(QemuConsole *con,
QemuDmaBuf *dmabuf);
void dpy_gl_cursor_dmabuf(QemuConsole *con, QemuDmaBuf *dmabuf,
+11 -2
View File
@@ -12,12 +12,13 @@
extern EGLDisplay *qemu_egl_display;
extern EGLConfig qemu_egl_config;
extern DisplayGLMode qemu_egl_mode;
extern bool qemu_egl_angle_d3d;
extern void *qemu_egl_angle_native_device;
typedef struct egl_fb {
int width;
int height;
GLuint texture;
GLenum texture_target;
GLuint framebuffer;
bool delete_texture;
QemuDmaBuf *dmabuf;
@@ -27,8 +28,11 @@ typedef struct egl_fb {
void egl_fb_destroy(egl_fb *fb);
void egl_fb_setup_default(egl_fb *fb, int width, int height);
void egl_fb_setup_for_tex_target(egl_fb *fb, int width, int height,
GLuint texture, GLenum target, bool delete);
void egl_fb_setup_for_tex(egl_fb *fb, int width, int height,
GLuint texture, bool delete);
void egl_fb_setup_new_tex_target(egl_fb *fb, int width, int height, GLenum target);
void egl_fb_setup_new_tex(egl_fb *fb, int width, int height);
void egl_fb_blit(egl_fb *dst, egl_fb *src, bool flip);
void egl_fb_read(DisplaySurface *dst, egl_fb *src);
@@ -56,7 +60,12 @@ void egl_dmabuf_create_fence(QemuDmaBuf *dmabuf);
#endif
EGLSurface qemu_egl_init_surface_x11(EGLContext ectx, EGLNativeWindowType win);
EGLSurface qemu_egl_init_surface(EGLContext ectx, EGLNativeWindowType win);
EGLSurface qemu_egl_init_buffer_surface(EGLContext ectx, EGLenum buftype,
EGLClientBuffer buffer, const EGLint *attrib_list);
bool qemu_egl_destroy_surface(EGLSurface surface);
int qemu_egl_init_dpy_cocoa(DisplayGLMode mode);
#if defined(CONFIG_X11) || defined(CONFIG_GBM)
+5 -4
View File
@@ -21,7 +21,7 @@
#include "ui/clipboard.h"
#include "ui/console.h"
#include "ui/kbd-state.h"
#if defined(CONFIG_OPENGL)
#if defined(CONFIG_OPENGL) && defined(CONFIG_EGL)
#include "ui/egl-helpers.h"
#include "ui/egl-context.h"
#endif
@@ -43,7 +43,7 @@ typedef struct VirtualGfxConsole {
cairo_surface_t *surface;
double scale_x;
double scale_y;
#if defined(CONFIG_OPENGL)
#if defined(CONFIG_OPENGL) && defined(CONFIG_EGL)
QemuGLShader *gls;
EGLContext ectx;
EGLSurface esurface;
@@ -157,6 +157,7 @@ extern bool gtk_use_gl_area;
void gd_update_windowsize(VirtualConsole *vc);
void gd_update_monitor_refresh_rate(VirtualConsole *vc, GtkWidget *widget);
void gd_hw_gl_flushed(void *vc);
void gd_dmabuf_cancel_fence(VirtualConsole *vc, QemuDmaBuf *dmabuf);
/* ui/gtk-egl.c */
void gd_egl_init(VirtualConsole *vc);
@@ -176,7 +177,7 @@ void gd_egl_scanout_texture(DisplayChangeListener *dcl,
uint32_t backing_height,
uint32_t x, uint32_t y,
uint32_t w, uint32_t h,
void *d3d_tex2d);
ScanoutTextureNative native);
void gd_egl_scanout_dmabuf(DisplayChangeListener *dcl,
QemuDmaBuf *dmabuf);
void gd_egl_cursor_dmabuf(DisplayChangeListener *dcl,
@@ -213,7 +214,7 @@ void gd_gl_area_scanout_texture(DisplayChangeListener *dcl,
uint32_t backing_height,
uint32_t x, uint32_t y,
uint32_t w, uint32_t h,
void *d3d_tex2d);
ScanoutTextureNative native);
void gd_gl_area_scanout_disable(DisplayChangeListener *dcl);
void gd_gl_area_scanout_flush(DisplayChangeListener *dcl,
uint32_t x, uint32_t y, uint32_t w, uint32_t h);
+1
View File
@@ -27,6 +27,7 @@
#include "qemu/config-file.h"
void qemu_spice_input_init(void);
void qemu_spice_display_early_init(void);
void qemu_spice_display_init(void);
void qemu_spice_display_init_done(void);
bool qemu_spice_have_display_interface(QemuConsole *con);
+3 -3
View File
@@ -22,7 +22,7 @@
#endif
#include "ui/kbd-state.h"
#ifdef CONFIG_OPENGL
#if defined(CONFIG_OPENGL) && defined(CONFIG_EGL)
# include "ui/egl-helpers.h"
#endif
@@ -45,7 +45,7 @@ struct sdl2_console {
bool gui_keysym;
SDL_GLContext winctx;
QKbdState *kbd;
#ifdef CONFIG_OPENGL
#if defined(CONFIG_OPENGL) && defined(CONFIG_EGL)
QemuGLShader *gls;
egl_fb guest_fb;
egl_fb win_fb;
@@ -93,7 +93,7 @@ void sdl2_gl_scanout_texture(DisplayChangeListener *dcl,
uint32_t backing_height,
uint32_t x, uint32_t y,
uint32_t w, uint32_t h,
void *d3d_tex2d);
ScanoutTextureNative native);
void sdl2_gl_scanout_flush(DisplayChangeListener *dcl,
uint32_t x, uint32_t y, uint32_t w, uint32_t h);
+57 -3
View File
@@ -27,7 +27,12 @@
#include "ui/qemu-pixman.h"
#include "ui/console.h"
#if defined(CONFIG_OPENGL) && defined(CONFIG_GBM)
#if defined(CONFIG_IOSURFACE)
#include <CoreFoundation/CoreFoundation.h>
#include <IOSurface/IOSurfaceRef.h>
#endif
#if defined(CONFIG_OPENGL)
# define HAVE_SPICE_GL 1
# include "ui/egl-helpers.h"
# include "ui/egl-context.h"
@@ -72,6 +77,13 @@ typedef struct QXLCookie {
QXLRect area;
int redraw;
} render;
struct {
QXLInstance *qxl;
uint32_t x;
uint32_t y;
uint32_t w;
uint32_t h;
} gl_draw;
void *data;
} u;
} QXLCookie;
@@ -81,6 +93,7 @@ QXLCookie *qxl_cookie_new(int type, uint64_t io);
typedef struct SimpleSpiceDisplay SimpleSpiceDisplay;
typedef struct SimpleSpiceUpdate SimpleSpiceUpdate;
typedef struct SimpleSpiceCursor SimpleSpiceCursor;
typedef void *SpiceDisplayMetalContext;
struct SimpleSpiceDisplay {
DisplaySurface *ds;
@@ -125,8 +138,30 @@ struct SimpleSpiceDisplay {
bool have_scanout;
bool have_surface;
#if defined(CONFIG_GBM)
QemuDmaBuf *guest_dmabuf;
bool guest_dmabuf_refresh;
#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
#endif
#if defined(CONFIG_EGL)
EGLSurface esurface;
egl_fb iosurface_fb;
#endif
GLuint tex_id;
bool y_0_top;
bool render_cursor;
egl_fb guest_fb;
@@ -150,8 +185,6 @@ struct SimpleSpiceCursor {
QXLCursor cursor;
};
extern bool spice_opengl;
int qemu_spice_rect_is_empty(const QXLRect* r);
void qemu_spice_rect_union(QXLRect *dest, const QXLRect *r);
@@ -182,4 +215,25 @@ void qemu_spice_display_start(void);
void qemu_spice_display_stop(void);
int qemu_spice_display_is_running(SimpleSpiceDisplay *ssd);
#if defined(CONFIG_METAL) && defined(CONFIG_IOSURFACE)
typedef void *MTLTexture_id;
typedef void (*SpiceDisplayMetalCompletion)(void *data);
SpiceDisplayMetalContext qemu_spice_display_metal_create_context(IOSurfaceRef surface,
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);
void qemu_spice_display_metal_scanout_disable(SpiceDisplayMetalContext ctx);
bool qemu_spice_display_metal_has_scanout(SpiceDisplayMetalContext ctx);
void qemu_spice_display_metal_draw_frame(SpiceDisplayMetalContext ctx,
uint32_t x, uint32_t y, uint32_t w, uint32_t h,
SpiceDisplayMetalCompletion completion,
void *data);
#endif
#endif
+71
View File
@@ -439,6 +439,7 @@ struct kvm_sync_regs {
#define KVM_X86_QUIRK_MWAIT_NEVER_UD_FAULTS (1 << 6)
#define KVM_X86_QUIRK_SLOT_ZAP_ALL (1 << 7)
#define KVM_X86_QUIRK_STUFF_FEATURE_MSRS (1 << 8)
#define KVM_X86_QUIRK_IGNORE_GUEST_PAT (1 << 9)
#define KVM_STATE_NESTED_FORMAT_VMX 0
#define KVM_STATE_NESTED_FORMAT_SVM 1
@@ -925,4 +926,74 @@ struct kvm_hyperv_eventfd {
#define KVM_X86_SNP_VM 4
#define KVM_X86_TDX_VM 5
/* Trust Domain eXtension sub-ioctl() commands. */
enum kvm_tdx_cmd_id {
KVM_TDX_CAPABILITIES = 0,
KVM_TDX_INIT_VM,
KVM_TDX_INIT_VCPU,
KVM_TDX_INIT_MEM_REGION,
KVM_TDX_FINALIZE_VM,
KVM_TDX_GET_CPUID,
KVM_TDX_CMD_NR_MAX,
};
struct kvm_tdx_cmd {
/* enum kvm_tdx_cmd_id */
__u32 id;
/* flags for sub-commend. If sub-command doesn't use this, set zero. */
__u32 flags;
/*
* data for each sub-command. An immediate or a pointer to the actual
* data in process virtual address. If sub-command doesn't use it,
* set zero.
*/
__u64 data;
/*
* Auxiliary error code. The sub-command may return TDX SEAMCALL
* status code in addition to -Exxx.
*/
__u64 hw_error;
};
struct kvm_tdx_capabilities {
__u64 supported_attrs;
__u64 supported_xfam;
__u64 reserved[254];
/* Configurable CPUID bits for userspace */
struct kvm_cpuid2 cpuid;
};
struct kvm_tdx_init_vm {
__u64 attributes;
__u64 xfam;
__u64 mrconfigid[6]; /* sha384 digest */
__u64 mrowner[6]; /* sha384 digest */
__u64 mrownerconfig[6]; /* sha384 digest */
/* The total space for TD_PARAMS before the CPUIDs is 256 bytes */
__u64 reserved[12];
/*
* Call KVM_TDX_INIT_VM before vcpu creation, thus before
* KVM_SET_CPUID2.
* This configuration supersedes KVM_SET_CPUID2s for VCPUs because the
* TDX module directly virtualizes those CPUIDs without VMM. The user
* space VMM, e.g. qemu, should make KVM_SET_CPUID2 consistent with
* those values. If it doesn't, KVM may have wrong idea of vCPUIDs of
* the guest, and KVM may wrongly emulate CPUIDs or MSRs that the TDX
* module doesn't virtualize.
*/
struct kvm_cpuid2 cpuid;
};
#define KVM_TDX_MEASURE_MEMORY_REGION _BITULL(0)
struct kvm_tdx_init_mem_region {
__u64 source_addr;
__u64 gpa;
__u64 nr_pages;
};
#endif /* _ASM_X86_KVM_H */
+1
View File
@@ -369,6 +369,7 @@ struct kvm_run {
#define KVM_SYSTEM_EVENT_WAKEUP 4
#define KVM_SYSTEM_EVENT_SUSPEND 5
#define KVM_SYSTEM_EVENT_SEV_TERM 6
#define KVM_SYSTEM_EVENT_TDX_FATAL 7
__u32 type;
__u32 ndata;
union {
+98 -14
View File
@@ -53,6 +53,7 @@ bsd_oses = ['gnu/kfreebsd', 'freebsd', 'netbsd', 'openbsd', 'dragonfly', 'darwin
supported_oses = ['windows', 'freebsd', 'netbsd', 'openbsd', 'darwin', 'sunos', 'linux']
supported_cpus = ['ppc', 'ppc64', 's390x', 'riscv32', 'riscv64', 'x86', 'x86_64',
'arm', 'aarch64', 'loongarch64', 'mips', 'mips64', 'sparc64']
tcti_supported_cpus = ['aarch64']
cpu = host_machine.cpu_family()
@@ -512,6 +513,12 @@ ucontext_probe = '''
# For POSIX prefer ucontext, but it's not always possible. The fallback
# is sigcontext.
supported_backends = []
ucontext = dependency('libucontext', required : false)
if ucontext.found() or get_option('ucontext').enabled()
supported_backends += ['libucontext']
endif
if host_os == 'windows'
supported_backends += ['windows']
else
@@ -528,6 +535,10 @@ elif coroutine_backend not in supported_backends
.format(coroutine_backend, ', '.join(supported_backends)))
endif
if coroutine_backend == 'libucontext'
coroutine_backend = 'ucontext'
endif
# Compiles if SafeStack *not* enabled
safe_stack_probe = '''
int main(void)
@@ -829,7 +840,10 @@ socket = []
version_res = []
coref = []
iokit = []
iosurface = not_found
pvg = not_found
metal = not_found
quartzcore = not_found
emulator_link_args = []
midl = not_found
widl = not_found
@@ -850,9 +864,12 @@ if host_os == 'windows'
elif host_os == 'darwin'
coref = dependency('appleframeworks', modules: 'CoreFoundation')
iokit = dependency('appleframeworks', modules: 'IOKit', required: false)
iosurface = dependency('appleframeworks', modules: 'IOSurface', required: false)
host_dsosuf = '.dylib'
pvg = dependency('appleframeworks', modules: ['ParavirtualizedGraphics', 'Metal'],
required: get_option('pvg'))
metal = dependency('appleframeworks', modules: 'Metal', required: false)
quartzcore = dependency('appleframeworks', modules: ['OpenGL', 'QuartzCore'], required: false)
elif host_os == 'sunos'
socket = [cc.find_library('socket'),
cc.find_library('nsl'),
@@ -868,6 +885,13 @@ elif host_os == 'openbsd'
endif
endif
if not ucontext.found() and get_option('ucontext').enabled()
libucontext_proj = subproject('libucontext',
default_options: ['default_library=static',
'freestanding=true'])
ucontext = libucontext_proj.get_variable('libucontext_dep')
endif
###############################################
# Host-specific configuration of accelerators #
###############################################
@@ -918,6 +942,13 @@ if get_option('tcg').allowed()
endif
if get_option('tcg_interpreter')
tcg_arch = 'tci'
elif get_option('tcg_threaded_interpreter')
if cpu not in tcti_supported_cpus
error('Unsupported CPU @0@ for TCTI, try --enable-tcg-interpreter'.format(cpu))
else
warning('TCTI is extremely experimental and incomplete! Things might break!')
tcg_arch = '@0@-tcti'.format(cpu)
endif
elif host_arch == 'x86_64'
tcg_arch = 'i386'
elif host_arch == 'ppc64'
@@ -1198,7 +1229,7 @@ if get_option('attr').allowed()
endif
cocoa = dependency('appleframeworks',
modules: ['Cocoa', 'CoreVideo', 'QuartzCore'],
modules: ['Cocoa', 'CoreVideo', 'OpenGL', 'QuartzCore'],
required: get_option('cocoa'))
vmnet = dependency('appleframeworks', modules: 'vmnet', required: get_option('vmnet'))
@@ -1763,14 +1794,13 @@ if not get_option('coreaudio').auto() or (host_os == 'darwin' and have_system)
required: get_option('coreaudio'))
endif
egl = not_found
opengl = not_found
if not get_option('opengl').auto() or have_system or have_vhost_user_gpu
epoxy = dependency('epoxy', method: 'pkg-config',
opengl = dependency('epoxy', method: 'pkg-config',
required: get_option('opengl'))
if cc.has_header('epoxy/egl.h', dependencies: epoxy)
opengl = epoxy
elif get_option('opengl').enabled()
error('epoxy/egl.h not found')
if cc.has_header('epoxy/egl.h', dependencies: opengl)
egl = opengl
endif
endif
gbm = not_found
@@ -2449,6 +2479,10 @@ if get_option('kvm').allowed() and host_os == 'linux'
endif
config_host_data.set('CONFIG_KVM_TARGETS', kvm_targets_c)
if get_option('hvf').allowed() and hvf.found()
config_host_data.set('CONFIG_HVF_PRIVATE', get_option('hvf_private'))
endif
if get_option('module_upgrades') and not enable_modules
error('Cannot enable module-upgrades as modules are not enabled')
endif
@@ -2513,6 +2547,7 @@ if numa.found()
cc.has_function('numa_has_preferred_many',
dependencies: numa))
endif
config_host_data.set('CONFIG_EGL', egl.found())
config_host_data.set('CONFIG_OPENGL', opengl.found())
config_host_data.set('CONFIG_PLUGIN', get_option('plugins'))
config_host_data.set('CONFIG_RBD', rbd.found())
@@ -2527,11 +2562,13 @@ if seccomp.found()
endif
config_host_data.set('CONFIG_PIXMAN', pixman.found())
config_host_data.set('CONFIG_SLIRP', slirp.found())
config_host_data.set('CONFIG_LIBUCONTEXT', ucontext.found())
config_host_data.set('CONFIG_SNAPPY', snappy.found())
config_host_data.set('CONFIG_SOLARIS', host_os == 'sunos')
if get_option('tcg').allowed()
config_host_data.set('CONFIG_TCG', 1)
config_host_data.set('CONFIG_TCG_INTERPRETER', tcg_arch == 'tci')
config_host_data.set('CONFIG_TCG_THREADED_INTERPRETER', tcg_arch.endswith('tcti'))
endif
config_host_data.set('CONFIG_TPM', have_tpm)
config_host_data.set('CONFIG_TSAN', get_option('tsan'))
@@ -2553,7 +2590,18 @@ config_host_data.set('CONFIG_VNC', vnc.found())
config_host_data.set('CONFIG_VNC_JPEG', jpeg.found())
config_host_data.set('CONFIG_VNC_SASL', sasl.found())
if virgl.found()
config_host_data.set('HAVE_VIRGL_RENDERER_NATIVE_SCANOUT',
cc.has_function('virgl_renderer_create_handle_for_scanout',
args: '-DVIRGL_RENDERER_UNSTABLE_APIS',
prefix: '#include <virglrenderer.h>',
dependencies: virgl))
config_host_data.set('VIRGL_VERSION_MAJOR', virgl.version().split('.')[0])
config_host_data.set('HAVE_VIRGL_RENDERER_NEPTUNE',
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())
@@ -2586,6 +2634,7 @@ config_host_data.set('CONFIG_SPICE', spice.found())
config_host_data.set('CONFIG_X11', x11.found())
config_host_data.set('CONFIG_DBUS_DISPLAY', dbus_display)
config_host_data.set('CONFIG_CFI', get_option('cfi'))
config_host_data.set('CONFIG_IOSURFACE', iosurface.found())
config_host_data.set('CONFIG_SELINUX', selinux.found())
config_host_data.set('CONFIG_XEN_BACKEND', xen.found())
config_host_data.set('CONFIG_LIBDW', libdw.found())
@@ -2597,10 +2646,12 @@ if xen.found()
('0' + xen_version[2]).substring(-2)
config_host_data.set('CONFIG_XEN_CTRL_INTERFACE_VERSION', xen_ctrl_version)
endif
config_host_data.set('CONFIG_METAL', metal.found())
config_host_data.set('QEMU_VERSION', '"@0@"'.format(meson.project_version()))
config_host_data.set('QEMU_VERSION_MAJOR', meson.project_version().split('.')[0])
config_host_data.set('QEMU_VERSION_MINOR', meson.project_version().split('.')[1])
config_host_data.set('QEMU_VERSION_MICRO', meson.project_version().split('.')[2])
config_host_data.set('CONFIG_SHARED_LIBRARY_BUILD', get_option('shared_lib'))
config_host_data.set_quoted('CONFIG_HOST_DSOSUF', host_dsosuf)
config_host_data.set('HAVE_HOST_BLOCK_DEVICE', have_host_block_device)
@@ -2664,7 +2715,7 @@ config_host_data.set('HAVE_GETIFADDRS', cc.has_function('getifaddrs'))
config_host_data.set('HAVE_GLIB_WITH_SLICE_ALLOCATOR', glib_has_gslice)
config_host_data.set('HAVE_GLIB_WITH_ALIGNED_ALLOC', glib_has_aligned_alloc)
config_host_data.set('HAVE_OPENPTY', cc.has_function('openpty', dependencies: util))
config_host_data.set('HAVE_STRCHRNUL', cc.has_function('strchrnul', prefix: osdep_prefix))
config_host_data.set('HAVE_STRCHRNUL', cc.has_function('strchrnul') and host_os != 'darwin')
config_host_data.set('HAVE_SYSTEM_FUNCTION', cc.has_function('system', prefix: '#include <stdlib.h>'))
if rbd.found()
config_host_data.set('HAVE_RBD_NAMESPACE_EXISTS',
@@ -3719,7 +3770,7 @@ util_ss = util_ss.apply({})
libqemuutil = static_library('qemuutil',
build_by_default: false,
sources: util_ss.sources() + stub_ss.sources() + genh,
dependencies: [util_ss.dependencies(), libm, threads, glib, socket, malloc])
dependencies: [util_ss.dependencies(), libm, threads, glib, socket, malloc, ucontext])
qemuutil_deps = [event_loop_base]
if host_os != 'windows'
qemuutil_deps += [rt]
@@ -4251,20 +4302,37 @@ foreach target : target_dirs
lib_deps += dep.partial_dependency(compile_args: true, includes: true)
endforeach
lib = static_library('qemu-' + target,
if get_option('shared_lib')
build_lib_args = {
'target_type': 'shared_library',
'install': true,
'dependencies': arch_deps,
'link_depends': [block_syms, qemu_syms],
'link_args': link_args,
'gnu_symbol_visibility': 'default'
}
else
build_lib_args = {
'target_type': 'static_library',
'install': false,
'dependencies': lib_deps
}
endif
lib = build_target('qemu-' + target,
sources: arch_srcs + genh,
dependencies: lib_deps,
objects: objects,
include_directories: target_inc,
c_args: c_args,
build_by_default: false)
build_by_default: false,
kwargs: build_lib_args)
if target.endswith('-softmmu')
execs = [{
'name': 'qemu-system-' + target_name,
'win_subsystem': 'console',
'sources': files('system/main.c'),
'dependencies': [sdl]
'dependencies': [sdl, coref]
}]
if host_os == 'windows' and (sdl.found() or gtk.found())
execs += [{
@@ -4297,11 +4365,19 @@ foreach target : target_dirs
exe_name += '-unsigned'
endif
if get_option('shared_lib')
exe_deps = [declare_dependency(link_with: lib)]
exe_objs = []
else
exe_deps = arch_deps
exe_objs = lib.extract_all_objects(recursive: true)
endif
emulator = executable(exe_name, exe['sources'],
install: true,
c_args: c_args,
dependencies: arch_deps + exe['dependencies'],
objects: lib.extract_all_objects(recursive: true),
dependencies: exe_deps + exe['dependencies'],
objects: exe_objs,
link_depends: [block_syms, qemu_syms],
link_args: link_args,
win_subsystem: exe['win_subsystem'])
@@ -4362,6 +4438,10 @@ if xkbcommon.found()
endif
if have_tools
if get_option('shared_lib')
qemu_img_lib = shared_library('qemu-img', [files('qemu-img.c'), hxdep],
dependencies: [authz, block, crypto, io, qom, qemuutil], install: true)
endif
qemu_img = executable('qemu-img', [files('qemu-img.c'), hxdep],
link_args: '@block.syms', link_depends: block_syms,
dependencies: [authz, block, crypto, io, qom, qemuutil], install: true)
@@ -4514,6 +4594,7 @@ summary(summary_info, bool_yn: true, section: 'Directories')
# Host binaries
summary_info = {}
summary_info += {'build shared lib': get_option('shared_lib')}
summary_info += {'python': '@0@ (version: @1@)'.format(python.full_path(), python.language_version())}
summary_info += {'sphinx-build': sphinx_build}
@@ -4668,6 +4749,8 @@ summary_info += {'TCG support': config_all_accel.has_key('CONFIG_TCG')}
if config_all_accel.has_key('CONFIG_TCG')
if get_option('tcg_interpreter')
summary_info += {'TCG backend': 'TCI (TCG with bytecode interpreter, slow)'}
elif get_option('tcg_threaded_interpreter')
summary_info += {'TCG backend': 'TCTI (TCG with threaded-dispatch bytecode interpreter, experimental and slow; but faster than TCI)'}
else
summary_info += {'TCG backend': 'native (@0@)'.format(cpu)}
endif
@@ -4687,6 +4770,7 @@ summary(summary_info, bool_yn: true, section: 'Targets and accelerators')
# Block layer
summary_info = {}
summary_info += {'libucontext support': ucontext.found()}
summary_info += {'coroutine backend': coroutine_backend}
summary_info += {'coroutine pool': have_coroutine_pool}
if have_block
+9 -1
View File
@@ -34,7 +34,7 @@ option('fuzzing_engine', type : 'string', value : '',
option('trace_file', type: 'string', value: 'trace',
description: 'Trace file prefix for simple backend')
option('coroutine_backend', type: 'combo',
choices: ['ucontext', 'sigaltstack', 'windows', 'auto'],
choices: ['libucontext', 'ucontext', 'sigaltstack', 'windows', 'auto'],
value: 'auto', description: 'coroutine backend to use')
# Everything else can be set via --enable/--disable-* option
@@ -63,6 +63,8 @@ option('tools', type : 'feature', value : 'auto',
description: 'build support utilities that come with QEMU')
option('qga_vss', type : 'feature', value: 'auto',
description: 'build QGA VSS support (broken with MinGW)')
option('shared_lib', type: 'boolean', value: false,
description: 'Build QEMU as a shared library')
option('malloc_trim', type : 'feature', value : 'auto',
description: 'enable libc malloc_trim() for memory optimization')
@@ -75,6 +77,8 @@ option('whpx', type: 'feature', value: 'auto',
description: 'WHPX acceleration support')
option('hvf', type: 'feature', value: 'auto',
description: 'HVF acceleration support')
option('hvf_private', type: 'boolean', value: 'false',
description: 'HVF private features (entitlements required)')
option('nvmm', type: 'feature', value: 'auto',
description: 'NVMM acceleration support')
option('xen', type: 'feature', value: 'auto',
@@ -91,6 +95,8 @@ option('debug_remap', type: 'boolean', value: false,
description: 'syscall buffer debugging support')
option('tcg_interpreter', type: 'boolean', value: false,
description: 'TCG with bytecode interpreter (slow)')
option('tcg_threaded_interpreter', type: 'boolean', value: false,
description: 'TCG with threaded-dispatch bytecode interpreter (experimental and slow, but less slow than TCI)')
option('safe_stack', type: 'boolean', value: false,
description: 'SafeStack Stack Smash Protection (requires clang/llvm and coroutine backend ucontext)')
option('asan', type: 'boolean', value: false,
@@ -275,6 +281,8 @@ option('fuse', type: 'feature', value: 'auto',
description: 'FUSE block device export')
option('fuse_lseek', type : 'feature', value : 'auto',
description: 'SEEK_HOLE/SEEK_DATA support for FUSE exports')
option('ucontext', type : 'feature', value : 'disabled',
description: 'libucontext support')
option('trace_backends', type: 'array', value: ['log'],
choices: ['dtrace', 'ftrace', 'log', 'nop', 'simple', 'syslog', 'ust'],
+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;
}
+15 -3
View File
@@ -88,6 +88,16 @@ static bool validate_options(const Netdev *netdev, Error **errp)
return false;
}
if (__builtin_available(macOS 11, *)) {
// clang requires a true branch
} else {
if (options->has_isolated) {
error_setg(errp,
"vmnet-bridged.isolated feature is "
"unavailable: outdated vmnet.framework API");
return false;
}
}
return true;
}
@@ -106,9 +116,11 @@ static xpc_object_t build_if_desc(const Netdev *netdev)
vmnet_shared_interface_name_key,
options->ifname);
xpc_dictionary_set_bool(if_desc,
vmnet_enable_isolation_key,
options->isolated);
if (__builtin_available(macOS 11, *)) {
xpc_dictionary_set_bool(if_desc,
vmnet_enable_isolation_key,
options->isolated);
}
return if_desc;
}
+32 -14
View File
@@ -21,12 +21,28 @@
static bool validate_options(const Netdev *netdev, Error **errp)
{
const NetdevVmnetHostOptions *options = &(netdev->u.vmnet_host);
QemuUUID net_uuid;
if (options->net_uuid &&
qemu_uuid_parse(options->net_uuid, &net_uuid) < 0) {
error_setg(errp, "Invalid UUID provided in 'net-uuid'");
return false;
if (__builtin_available(macOS 11, *)) {
QemuUUID net_uuid;
if (options->net_uuid &&
qemu_uuid_parse(options->net_uuid, &net_uuid) < 0) {
error_setg(errp, "Invalid UUID provided in 'net-uuid'");
return false;
}
} else {
if (options->has_isolated) {
error_setg(errp,
"vmnet-host.isolated feature is "
"unavailable: outdated vmnet.framework API");
return false;
}
if (options->net_uuid) {
error_setg(errp,
"vmnet-host.net-uuid feature is "
"unavailable: outdated vmnet.framework API");
return false;
}
}
if ((options->start_address ||
@@ -53,16 +69,18 @@ static xpc_object_t build_if_desc(const Netdev *netdev)
vmnet_operation_mode_key,
VMNET_HOST_MODE);
xpc_dictionary_set_bool(if_desc,
vmnet_enable_isolation_key,
options->isolated);
if (__builtin_available(macOS 11, *)) {
xpc_dictionary_set_bool(if_desc,
vmnet_enable_isolation_key,
options->isolated);
QemuUUID net_uuid;
if (options->net_uuid) {
qemu_uuid_parse(options->net_uuid, &net_uuid);
xpc_dictionary_set_uuid(if_desc,
vmnet_network_identifier_key,
net_uuid.data);
QemuUUID net_uuid;
if (options->net_uuid) {
qemu_uuid_parse(options->net_uuid, &net_uuid);
xpc_dictionary_set_uuid(if_desc,
vmnet_network_identifier_key,
net_uuid.data);
}
}
if (options->start_address) {
+18 -5
View File
@@ -21,6 +21,17 @@ static bool validate_options(const Netdev *netdev, Error **errp)
{
const NetdevVmnetSharedOptions *options = &(netdev->u.vmnet_shared);
if (__builtin_available(macOS 11, *)) {
// clang requires a true branch
} else {
if (options->has_isolated) {
error_setg(errp,
"vmnet-shared.isolated feature is "
"unavailable: outdated vmnet.framework API");
return false;
}
}
if ((options->start_address ||
options->end_address ||
options->subnet_mask) &&
@@ -66,11 +77,13 @@ static xpc_object_t build_if_desc(const Netdev *netdev)
options->subnet_mask);
}
xpc_dictionary_set_bool(
if_desc,
vmnet_enable_isolation_key,
options->isolated
);
if (__builtin_available(macOS 11, *)) {
xpc_dictionary_set_bool(
if_desc,
vmnet_enable_isolation_key,
options->isolated
);
}
return if_desc;
}
+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
}
Binary file not shown.
Loaded 100 of 190 files, more files were not shown because too many files have changed in this diff. Show more