Compare commits

...
761 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
Michael Tokarev 0a6a1c7d02 Update version for 10.0.12 release
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-24 10:05:02 +03: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
Haotian Jiang 86db40ecc2 hw/audio/intel-hda: restrict all DMA engine paths to memories
CVE-2021-3611 (commit 79fa99831d) restricted the DMA engine to memories
by setting attrs.memory=true, but only applied this to intel_hda_response.
Three other DMA engine access points still use MEMTXATTRS_UNSPECIFIED,
allowing a malicious guest to trigger DMA-to-self-MMIO reentry:

  - intel_hda_xfer (line 398): called from the audio timer callback
    (hda_codec_xfer -> bus->xfer), so the MemReentrancyGuard does not
    fire (engaged_in_io is false outside MMIO dispatch). A guest that
    points a BDL entry at the HDA controller's own MMIO BAR can write
    audio samples to device registers, triggering whandler side effects
    such as starting/stopping streams or injecting codec commands via
    CORBWP.
  - intel_hda_parse_bdl (line 478): uses pci_dma_read which hardcodes
    MEMTXATTRS_UNSPECIFIED. A guest-controlled BDL base address can
    point at controller MMIO, allowing the DMA engine to read device
    registers as BDL descriptors.
  - intel_hda_corb_run (line 333): ldl_le_pci_dma reads the CORB ring
    with MEMTXATTRS_UNSPECIFIED, allowing the DMA engine to read
    controller MMIO as CORB entries.

Fix all three by passing {.memory = true} explicitly, matching the
fix already applied to intel_hda_response. For intel_hda_parse_bdl,
replace pci_dma_read with pci_dma_rw to pass the controlled attrs.

Fixes: 79fa99831d ("hw/audio/intel-hda: Restrict DMA engine to memories (not MMIO devices)")
Reported-by: Haotian Jiang of Tencent Security (Yunding Lab) <[email protected]>
Signed-off-by: Haotian Jiang <[email protected]>
Cc: [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 c257745248)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-22 12:41:36 +03:00
Bin Meng 0a87506980 hw/net/cadence: Return current Cadence GEM queue pointers
Cadence GEM queue pointer registers are programmed with the descriptor
ring base, but reads return the descriptor currently being accessed.
The model tracked the current positions separately while continuing to
return the configured base.

The Linux macb driver uses the transmit queue pointer when recovering
from a used-buffer interrupt. A stale priority-queue pointer can make
the driver restart DMA before that queue handles its completion
interrupt, causing queue 0 to repeatedly raise TX_USED.

The primary queue has had this mismatch since the initial model.
Priority queue support later copied the same register-read behavior.

A single-queue machine usually handles TX_COMPLETE before TX_USED and
empties the software queue before the restart check, which kept the
issue hidden there.

Return the current RX and TX descriptor positions on queue-pointer reads
and clear those positions on reset.

Fixes: e9f186e514 ("cadence_gem: initial version of device model")
Fixes: 6710172501 ("cadence_gem: Add queue support")
Cc: [email protected]
Signed-off-by: Bin Meng <[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 94c510a5dc)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-22 12:41:36 +03:00
Philippe Mathieu-Daudé 0446371428 hw/misc/applesmc: Fix a typo setting MSSD key
In commit 1ddda5cd36 we meant to set MSSD=3, but due
to a typo we ended setting MSSD=0. Convert the two other
NATJ and MSSP keys to use hexadecimal notation to avoid
similar copy/paste typos.

Cc: [email protected]
Fixes: 1ddda5cd36 ("AppleSMC device emulation")
Reported-by: Matthew Jackson <[email protected]>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Alexander Graf <[email protected]>
Reviewed-by: Pierrick Bouvier <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit 2142689d92)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-22 12:41:36 +03:00
Marc-André Lureau d8d2b58920 replay: fix use of uninitialized pointer on error
When bdrv_snapshot_list() returns a negative error code, sn_tab is
uninitialized. The loop does not execute (since i=0 < negative is
false), but the code falls through to g_free(sn_tab) which frees
an uninitialized pointer.

Fixes: f6baed3d14 ("replay: implement replay-seek command")
Signed-off-by: Marc-Andre Lureau <[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 fe68e4b47b)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-22 12:41:36 +03:00
Marc-André Lureau ce41859ef0 hw/display/qxl: validate monitors_config heads[] in phys2virt
The qxl_phys2virt() call for guest_monitors_config only validates
sizeof(QXLMonitorsConfig), which covers the fixed header (count and
max_allowed) since commit 8efec0ef8b ("hw/display/qxl: Pass requested
buffer size to qxl_phys2virt()"), but not the flexible array member
heads[]. When count == 1, heads[0] is accessed without its memory being
validated, allowing a guest to cause an out-of-bounds read.

Include sizeof(QXLHead) in the size passed to qxl_phys2virt() so that
the first head entry is validated within the guest memory slot, preventing
guest-visible memory reading.

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/4027
Reported-by: Tristan @TristanInSec
Signed-off-by: Marc-Andre Lureau <[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 9f436938c5)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-22 12:41:36 +03:00
Peter Maydell 91d5b334d7 net: Correct padding check in qemu_receive_packet()
In qemu_receive_packet() we check to see if we should pad a short
packet.  This is doing the wrong test: because this function is used
when the device adds a packet to its own incoming queue (i.e.  for
loopback), we should be checking the NetClientState's own do_not_pad
flag, not that for its peer.

We didn't notice this earlier, because at the moment all the real
peers of a network device (i.e.  the network backends) do not set
do_not_pad, so net_peer_needs_padding() always returns true except in
the corner case where the network device has no peer at all.

The effect of this is that if a network device has no peer (e.g.
because QEMU was started with -net none or with -nodefaults) then we
can still let through the kind of "guest misprograms the network
device to loopback-transmit a short packet and then we mishandle it
in the receive path" bug like #3043 which commit a01344d9d7 was
trying to fix.

Since the distinction between "we should check nc->do_not_pad"
and "we should check nc->peer->do_not_pad" is a bit subtle, add
enough documentation commentary to make it more obvious.

Cc: [email protected]
Fixes: a01344d9d7 ("net: pad packets to minimum length in qemu_receive_packet()")
Suggested-by: Bin Meng <[email protected]>
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Bin Meng <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit b1e73b2ddb)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-22 12:41:36 +03:00
Jay Chang 433c3af213 hw/net/xilinx_axienet: Fix PHY register 17 link status reporting
The Marvell 88E1111 PHY register 17 (PHY Specific Status Register)
bit 10 reports real-time link status. Previously, this register
returned a fixed value of 0x8800 with bit 10 always cleared,
causing U-Boot to always detect "No link" even when the link
was up.

Signed-off-by: Jay Chang <[email protected]>
Reviewed-by: Frank Chang <[email protected]>
Message-id: [email protected]
Reviewed-by: Peter Maydell <[email protected]>
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit 8392734722)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-22 12:41:36 +03: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
Thomas Huth b0411a1747 hw/usb/hcd-xhci-sysbus: Fix OOB heap access in xhci_sysbus_intr_raise()
Some machines like the microvm machine instantiate a "sysbus-xhci"
device with just 1 interrupt (by setting the "intrs" property to 1).
xhci_sysbus_realize() then only allocates the s->irq array with one
entry.

When the guest writes to the ERDP register of a corresponding XHCI
"interrupter", the generic XHCI code calls the xhci_sysbus_intr_raise()
function with n > 1, and this function then calls qemu_set_irq() with
s->irq[n] pointing to a bad heap address. The qemu_set_irq() then tries
to call an IRQ handler via a function pointer in that heap space. This
either causes QEMU to die with a segmentation fault (if it's a bad
address), or even worse runs some unexpected code if the destination
of the pointer is executable code.

Looking at the xHCI spec, it is up to the implementation of the host
controller how many interrupters are available. So if we only support
one or some few interrupters, the registers of the other interrupters
should not do anything, i.e. reads should result in zeros and writes
should be completely ignored. (big thanks to Peter Maydell for helping
with the analyzation of the correct way to fix this here)

This way, the xhci_sysbus_intr_raise() function cannot be called with
an invalid interrupt number anymore. But for good measure, also add an
assert() statement to the xhci_sysbus_intr_raise() function to prevent
that similar problems with calling arbitrary function pointers on the
heap could occur again.

Fixes: CVE-2026-16043
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/4001
Reported-by: Tristan Madani <[email protected]>
Reviewed-by: Peter Maydell <[email protected]>
Signed-off-by: Thomas Huth <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit cc479aa897)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-20 22:06:58 +03:00
Thomas Huth d998e2e099 hw/usb/hcd-xhci: Fix guest-triggerable assert() in xhci_find_stream()
The assert() statement in xhci_find_stream() can be triggered by
the guest (see bug tickets #273, #3895 and #3988 on gitlab.com).
Turn it into a qemu_log_mask() instead to fix this problem.

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/273
Reviewed-by: Peter Maydell <[email protected]>
Signed-off-by: Thomas Huth <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit 4daeaa2fe0)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-20 22:06:51 +03:00
Marc-André Lureau 6970b91d90 usbredir: fix infinite loop and SIGFPE with zero max_packet_size
A malicious usbredir peer can send an ep_info message resetting
max_packet_size to 0 after bulk receiving has started. This causes:
- infinite loop in usbredir_buffered_bulk_packet() where the splitting
  loop increments by max_packet_size (0)
- SIGFPE in usbredir_buffered_bulk_in_complete_ftdi() from modulo by 0
- SIGFPE in usbredir_handle_buffered_bulk_in_data() from division by 0
  when computing bytes_per_transfer

Fix by stopping and disabling bulk receiving in usbredir_ep_info() when
max_packet_size is set to 0.

Add post-load check, and assert() for the invariant.

Fixes: CVE-2026-63319
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3995
Reported-by: Tristan @TristanInSec
Signed-off-by: Marc-André Lureau <[email protected]>
Reviewed-by: Thomas Huth <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Thomas Huth <[email protected]>
(cherry picked from commit a002485bfe)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-20 22:06:44 +03:00
Marc-André Lureau e3da91c859 usbredir: fix use-after-free on buffered bulk packet overflow
When usbredir_buffered_bulk_packet() splits a multi-fragment buffered
bulk packet into max-packet-size chunks, only the final fragment owns
the shared parser allocation (via free_on_destroy). If bufp_alloc()
drops the final fragment due to queue overflow, it frees the backing
buffer while earlier fragments already queued still hold interior
pointers into it. Subsequent guest bulk-IN transfers then read from
freed heap memory.

Fix this by tracking how many fragments were queued during the current
packet. When bufp_alloc() fails, remove all already-queued fragments
from the tail of the endpoint queue before breaking out of the loop.
If the dropped fragment was non-final, free the data buffer explicitly
since no fragment took ownership.

Fixes: CVE-2026-15705
Fixes: b2d1fe67d0 ("usbredir: Add support for buffered bulk input (v2)")
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3808
Reported-by: Feifan Qian <[email protected]>
Signed-off-by: Marc-André Lureau <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Thomas Huth <[email protected]>
(cherry picked from commit 9bf52d056a)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-20 22:06:34 +03:00
Xiangfeng Cai 15b917f70f tests/qtest: add xhci-pci unplug finalize regression test
Add a qtest that hot-adds an nec-usb-xhci controller, requests unplug,
resets the system to process the request, and waits for DEVICE_DELETED.
This covers the xHCI PCI host-link refcount cycle by verifying that
device_finalize() runs after unplug.

Signed-off-by: Xiangfeng Cai <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Thomas Huth <[email protected]>
(cherry picked from commit ba54d7e66e)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-20 22:06:22 +03:00
Xiangfeng Cai 12356ead78 hw/usb/hcd-xhci-pci: break host link cycle so device_finalize() runs on unplug
The xHCI PCI wrapper embeds an xhci-core child via object_initialize_child()
and, in usb_xhci_pci_realize(), points the child's "host" link back at the PCI
device:

    object_property_set_link(OBJECT(&s->xhci), "host", OBJECT(s), NULL);

"host" is a DEFINE_PROP_LINK property, which qdev registers as an
OBJ_PROP_LINK_STRONG link. A strong link takes a reference on its target, so
this creates a refcount cycle: the PCI device owns the child, and the child's
strong link pins the PCI device.

On unplug (guest ACPI eject or QMP device_del), pci_qdev_unrealize() calls
pc->exit() but never unrealizes the no-bus child. object_unparent() then drops
only the parent/bus references, leaving the link reference in place. The PCI
device stays at refcount 1 forever, so object_finalize()/device_finalize() is
never reached. Symptom observed under gdb after eject:

    p *((Object *)dev)  =>  ref = 1, parent = 0x0, realized = false
    p ((XHCIPciState *)dev)->xhci.hostOpaque  =>  points back at dev

Fix usb_xhci_pci_exit() to tear down the embedded child explicitly: unrealize
it first (so the set-link-before-realize check passes), then clear the "host"
link. This releases the strong reference, lets the PCI device refcount reach 0,
and allows device_finalize() to run.

Fixes: 8ddab8dd3d ("usb/hcd-xhci: Split pci wrapper for xhci base model")
Signed-off-by: Xiangfeng Cai <[email protected]>
Acked-by: Marc-André Lureau <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Thomas Huth <[email protected]>
(cherry picked from commit 054ef33f67)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-20 22:06:08 +03:00
Feifan Qian 22aac2d401 hw/usb/xhci: clamp interval exponent to avoid UB shift in xhci_init_epctx()
The xHCI endpoint context dword 0 bits 23:16 ("Interval") are written
by the guest and passed directly as the shift amount in:

    epctx->interval = 1 << ((ctx[0] >> 16) & 0xff);

The shift amount can be 0-255.  Shifting a 32-bit `int` left by >= 32
is undefined behaviour under C11 §6.5.7p4.  With UBSan
(halt_on_error=1) this causes QEMU to abort; with aggressive compiler
optimisations that assume UB is unreachable the result is
unpredictable.

Clamp the exponent to [0, 18] with MIN() before the shift, and use
`1u` (unsigned) to avoid shifting a signed integer.  The xHCI
specification defines a maximum meaningful Interval value of 18 for
most endpoint types; thus clamping to 18 is a safe fix that
preserves the full unsigned 32-bit range for any compliant value.

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3703
Reported-by: Feifan Qian <[email protected]>
Signed-off-by: Feifan Qian <[email protected]>
[thuth: Clamp to 18 instead of 31]
Signed-off-by: Thomas Huth <[email protected]>
(cherry picked from commit 12d8ee9d53)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-20 22:06:00 +03:00
Alex Bennée f555fc3e21 accel/tcg: move jit thread manipulation into do_tb_phys_invalidate
To invalidate a TB on MacOS we need to enable write access to the JIT
buffer. We were doing this for tb_phys_invalidate__locked but that is
not the only path into do_tb_phys_invalidate. Move the manipulation
into the shared function that does the work.

As a result we can drop the tb_phys_invalidate__locked function and
update the calls directly.

This enables watchpoints to work in MacOS TCG guests.

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3444
Reviewed-by: Richard Henderson <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alex Bennée <[email protected]>
(cherry picked from commit 78420b59f0)
(Mjt: context fixup for missing v10.0.0-536-g77ad412b326
 "accel/tcg: Convert TARGET_HAS_PRECISE_SMC to TCGCPUOps.precise_smc")
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-20 14:52:18 +03:00
Akihiko Odaki 44e2f8e736 hw/display/virtio-gpu: Check pixman_image_create_bits() results
pixman_image_create_bits() returns NULL for allocation failures and
unaligned strides, which may be supplied by the guest with
VIRTIO_GPU_CMD_SET_SCANOUT_BLOB, and virtio_gpu_do_set_scanout()
subsequently dereferences it.

Fixes: fa06e5cb7b ("virtio-gpu: fix scanout rectangles")
Signed-off-by: Akihiko Odaki <[email protected].i.u-tokyo.ac.jp>
Reviewed-by: Marc-André Lureau <[email protected]>
Message-ID: <[email protected].i.u-tokyo.ac.jp>
(cherry picked from commit f1af81ba2a)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-20 14:19:37 +03:00
Marc-André Lureau 92383edfb6 hw/display/virtio-gpu: handle migration iov allocation failure
An unbounded iov_cnt from the migration stream drives two g_new()
allocations whose combined size can exceed available memory, causing
GLib to abort the process.

Switch to g_try_new() and propagate the failure as a migration error.

Fixes: 0c244e50ee ("virtio-gpu: add live migration support")
Fixes: f66767f75c ("virtio-gpu: add virtio-gpu/blob vmstate subsection")
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3753
Reported-by: Feifan Qian <[email protected]>
Reviewed-by: Akihiko Odaki <[email protected].i.u-tokyo.ac.jp>
Signed-off-by: Marc-André Lureau <[email protected]>
(cherry picked from commit e99488c5d4)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-20 14:18:10 +03:00
Marc-André Lureau 93f5926ebc hw/display/virtio-gpu: cap submit_3d command buffer allocation
Both virgl_cmd_submit_3d() and rutabaga_cmd_submit_3d() pass the
guest-controlled cs.size directly to malloc() without bounds checking. A
malicious guest can set cs.size to an arbitrarily large value, causing
an OOM abort that crashes the QEMU process.

Checking cs.size against the descriptor payload length (iov_size) is not
sufficient: indirect descriptor tables can repeat entries aliasing the
same guest-physical range, inflating iov_size() to nearly 4 GiB while
referring to only a small amount of unique memory.

Instead, cap cs.size at 4 MiB. With 4 KiB pages and QEMU's
VIRTQUEUE_MAX_SIZE (1024) mapped-iov limit, the Linux virtio driver
cannot carry more than ~4 MiB of inline command data, so legitimate
submissions are unaffected.

Fixes: 9d9e152136 ("virtio-gpu: add 3d mode and virgl rendering support.")
Fixes: 1dcc6adbc1 ("gfxstream + rutabaga: add initial support for gfxstream")
Fixes: d52c454aad ("contrib: add vhost-user-gpu")
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3776
Reported-by: [email protected]
Reviewed-by: Akihiko Odaki <[email protected].i.u-tokyo.ac.jp>
Signed-off-by: Marc-André Lureau <[email protected]>
(cherry picked from commit 8720061c6d)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-20 14:17:57 +03:00
Marc-André Lureau 7467c162c0 ui/vnc: validate SetPixelFormat field ranges
The VNC SetPixelFormat message carries red/green/blue_max as 16-bit
values, but PixelFormat stores them as uint8_t. A client sending a
max value above 255 (e.g. 0x0100) passes the existing non-zero check
but silently truncates to 0 on assignment, leading to a division by
zero in the Tight PNG palette path.

Add explicit range checks if any channel max exceeds UINT8_MAX.

Fixes: CVE-2026-15578
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/3976
Reported-by: dong ling
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Daniel P. Berrangé <[email protected]>
Signed-off-by: Marc-Andre Lureau <[email protected]>
(cherry picked from commit 6075444c5a)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-20 14:14:05 +03:00
Marc-André Lureau 6c2f9592de ui/vnc: fix out-of-bounds write in lossy refresh dirty marking
vnc_refresh_lossy_rect() marks a full VNC_STAT_RECT (64) rows of the
dirty bitmap when refreshing a lossy tile. When the display height is
not a multiple of VNC_STAT_RECT, the last tile row is a partial tile and
the loop writes past the end of vs->dirty[VNC_MAX_HEIGHT].

For example, with a 2160-pixel-high display (VNC_MAX_HEIGHT), the last
stat tile starts at y=2112. The unconditional 64-row loop writes rows
2112..2175, overflowing 16 rows (640 bytes) past the dirty bitmap into
subsequent VncState fields.

Fix by passing the effective display height into
vnc_refresh_lossy_rect() and clamping the inner loop.

Fixes: CVE-2026-61475
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3935
Reported-by: "Vulnerability Report" <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: Marc-Andre Lureau <[email protected]>
(cherry picked from commit e650e4fe0f)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-20 14:13:53 +03:00
Akihiko Odaki e8b412c25c ui/gtk: Narrow DMA-BUF critical section
Scanout operations need to be properly ordered to avoid tearing. The
virtio specification allows the guest to use pageflip. With pageflip,
the guest only modifies the invisible framebuffer while the host scans
out the visible framebuffer. The guest may choose not to use pageflip to
avoid its overhead, accepting the risk of tearing.

ui/gtk performs the following procedure to flush a scanout:
1) Queue a draw event.
2) The draw event gets triggered.
3) Blit the guest framebuffer to the host framebuffer.

When flushing a DMA-BUF scanout, ui/gtk blocks the device before 2) if
possible and unblocks it after 3) to enforce proper ordering. However,
blocking the device before 2) has two problems.

First, it can leave the device blocked indefinitely because GTK
sometimes decides to cancel 2) when the window is not visible for
example. ui/gtk regularly repeats 1) as a workaround, but it is not
applicable to GtkGLArea because it causes display corruption.

Second, the behavior is inconsistent with the other types of scanout
that leave the device unblocked between 1) and 2).

To fix these problems, let ui/gtk block the device only when the
queued draw event runs, immediately before 3). Blocking before that is
unnecessary since ui/gtk does not access the framebuffer yet. If the
guest does not use pageflip but instead updates the visible framebuffer
directly, ui/gtk should not add the overhead of a pre-draw block.

ui/gtk still blocks the device during 3) for DMA-BUF. Unlike the other
scanout types, 3) can happen asynchronously with the device for a
DMA-BUF, so ui/gtk needs to keep the visible guest framebuffer stable
for the blit.

With the problems fixed, the workaround to repeat 1) is no longer
necessary and is removed.

Signed-off-by: Akihiko Odaki <[email protected].i.u-tokyo.ac.jp>
Acked-by: Marc-André Lureau <[email protected]>
Message-ID: <[email protected].i.u-tokyo.ac.jp>
(cherry picked from commit 53f0d87db7)
(Mjt: back-port to before v11.0.0-787-g405a42e3655
 "ui/console: rename public API to use consistent qemu_console_ prefix" which
 renamed graphic_hw_gl_block() to qemu_console_hw_gl_block())
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-20 14:13:36 +03:00
Marc-André Lureau c4b40c409b ui/input-barrier: fix off-by-one in keycode bounds check
Use strict "<" to fix the off-by-one.

Fixes: 6105683da3 ("ui: add an embedded Barrier client")
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/3951
Reported-by: huntr bubble
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Laurent Vivier <[email protected]>
Signed-off-by: Marc-Andre Lureau <[email protected]>
(cherry picked from commit 82b4d693d5)
(Mjt: fixup the change to before v11.0.0-365-gd276ad86eb8
 "ui: rename init_keyboard_layout->kbd_layout_new()")
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-20 14:05:32 +03:00
Marc-André Lureau 9f26aa37d8 ui/vnc: validate color shifts in SetPixelFormat
A malicious VNC client can send a SetPixelFormat message with shift
values >= 32, causing UB mask computation
(e.g. red_max << red_shift where red_shift is 255). Apparently, this is
not covered by -fwrapv.

Reject color shifts >= bits_per_pixel || 32 before computing masks.

Fixes: 9f64916da2 ("pixman/vnc: use pixman images in vnc.")
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3948
Reported-by: huntr bubble
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: Marc-Andre Lureau <[email protected]>
(cherry picked from commit fb71c895d7)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-20 14:02:43 +03:00
Marc-André Lureau 5ab666fda9 ui/vnc: fix OOB write in vnc_refresh_lossy_rect
vnc_refresh_lossy_rect() always marks a full VNC_STAT_RECT (64) rows
as dirty when refreshing a lossy tile. When the display height is not
a multiple of VNC_STAT_RECT (e.g. VNC_MAX_HEIGHT = 2160), the bottom
tile is partial -- the last tile at y=2112 has only 48 valid rows.
The unclamped loop writes to vs->dirty[2160..2175], past the end of
the VNC_MAX_HEIGHT-sized array.

Clamp the row count to the actual surface height so partial bottom
tiles only mark valid dirty bitmap entries.

Fixes: CVE-2026-48002
Fixes: 7d964c9d2f ("vnc: refresh lossy rect after a given timeout")
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3950
Reported-by: huntr bubble
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: Marc-Andre Lureau <[email protected]>
(cherry picked from commit 3543c2b855)
(Mjt: fixups for missing v10.0.0-2240-g37ff925d5d4
 "ui/vnc: Introduce the VncWorker type")
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-20 14:01:38 +03:00
Thomas Huth 980a37f161 hw/usb/hcd-xhci: Turn guest-triggerable abort() into qemu_log_mask()
The FIXME macros in xhci_alloc_device_streams() can be triggered
by a (malicious) guest. Since the macro also contains an abort()
statement, this terminates QEMU. Turn the FIXME statements into
a qemu_log_mask() instead to avoid that a guest can shoot itself
this way.

Reported-by: Feifan Qian <[email protected]>
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3784
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: Thomas Huth <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit 5257259428)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-18 11:43:07 +03:00
Thomas Huth 927d2c4d9c hw/usb/hcd-ohci: Make sure that ohci_service_ed_list() cannot loop forever
The inner while loop in ohci_service_ed_list() could theoretically
loop forever if a malicious guest prepares a set of bad descriptors.
Add a check to the loop to avoid this situation.

Reported-by: Feifan Qian <[email protected]>
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3781
Signed-off-by: Thomas Huth <[email protected]>
Reviewed-by: Daniel P. Berrangé <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit 98e5a8eb4f)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-18 11:42:02 +03:00
Marc-André Lureau fab6f73b1e hw/display/virtio-gpu: fix dmabuf_fd leak on remap failure
When virtio_gpu_create_udmabuf() succeeds but virtio_gpu_remap_udmabuf()
fails (mmap returns MAP_FAILED), virtio_gpu_init_udmabuf() returns early
without closing the dmabuf fd. Since res->blob is never set in this
path, later cleanup via virtio_gpu_cleanup_mapping() skips
virtio_gpu_fini_udmabuf() entirely, leaking the file descriptor.

Call virtio_gpu_destroy_udmabuf() before the early return to close
the fd. This function already handles partial state correctly: it
skips the munmap when res->remapped is NULL and closes the fd when
res->dmabuf_fd >= 0.

Fixes: 9b60cdf987 ("virtio-gpu: Add udmabuf helpers")
Signed-off-by: Marc-André Lureau <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Dmitry Osipenko <[email protected]>
Reviewed-by: Akihiko Odaki <[email protected].i.u-tokyo.ac.jp>
Message-ID: <[email protected]>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit 564c4d7e99)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-18 11:39:55 +03:00
Miao Wang 5997746421 hw/scsi/vmw_pvscsi: add a comment to explain the endianness
Add a comment to explain the endianness of the pvscsi device. We have
no information about the endianness should be little-endian or CPU
native endian because the current driver code is designed to work only
on x86 and is not endianness aware. We assume that the pvscsi device is
implicitly little-endian.

Signed-off-by: Miao Wang <[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 ecc569639a)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-18 11:35:05 +03:00
Miao Wang e7ae1d7135 hw/scsi/vmw_pvscsi: translate data endianness
This patch improves the implementation of the pvscsi device by
translating the endianness of the data sent or received from the guest.
This ensures pvscsi can work on big-endian hosts with little-endian
guests.

This patch assumes, although not having found any specifications, that
the pvscsi device is little-endian, since pvscsi seems to be used only
on x86 platforms, which are little-endian.

Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: Miao Wang <[email protected]>
Message-ID: <[email protected]>
[PMD: Rebased on top of commit cb30b8758d physmem API conversion]
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit 5a811329bd)
(Mjt: re-rebased to before commit cb30b8758d physmem API conversion)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-18 11:35:00 +03:00
Dmitry Pimenov 6a8031021b hw/sparc64/niagara: use int64_t for vdisk size to avoid truncation
blk_getlength() returns int64_t, but niagara_init() stored it in an int,
truncating the if=pflash virtual-ramdisk size for images >= 2 GiB. A ~4 GiB
image truncated to 0/negative, failed the `size > 0` check, and exit(1)'d
before the CPU ran, ending with:

  qemu-system-sparc64: could not load ram disk

Signed-off-by: Dmitry Pimenov <[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 76dbe26fd6)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-17 18:11:24 +03:00
Marc-André Lureau 159b84e3a5 hw/display/qxl: fix TOCTOU in cursor chunk data_size handling
Snapshot chunk.data_size into a host-local variable before passing it to
qxl_phys2virt() for validation, and pass it through qxl_cursor() and
qxl_unpack_chunks() so that no subsequent code re-reads the field.

Without this, a racing vCPU can inflate data_size between the
qxl_phys2virt() validation and the memcpy in qxl_unpack_chunks(),
causing a source read past the validated region. In practice the read
stays within the guest's own VRAM mmap, so the impact is limited.

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3757
Reported-by: Feifan Qian <[email protected]>
Signed-off-by: Marc-Andre Lureau <[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 a3cc0069e1)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-17 18:10:37 +03:00
Haotian Jiang f1e15c49c7 hw/misc/ivshmem: clear chardev handlers before freeing peers
ivshmem_exit() frees s->peers and s->msi_vectors but does not clear
the chardev handlers registered in ivshmem_common_realize(). Those
handlers are only removed later in object_finalize() via release_chr,
which runs after ivshmem_exit().

Between exit and finalize, ivshmem_read() can fire on pending chardev
data and process_msg_connect() dereferences the freed s->peers.
Additionally, s->peers, s->nb_peers, and s->msi_vectors are not
zeroed after free, leaving dangling pointers that make the UAF code
paths reachable.

Fix by clearing chardev handlers at the beginning of ivshmem_exit(),
before any resources they access are freed, and nullifying freed
pointers.

Cc: [email protected]
Fixes: f64a078d45 ("ivshmem: fix pci_ivshmem_exit()")
Link: https://gitlab.com/qemu-project/qemu/-/work_items/3594
Reported-by: Haotian Jiang <[email protected]>
Signed-off-by: Haotian Jiang <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit 5157ceb10c)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-17 18:08:55 +03:00
Matt Turner d3996f2887 linux-user/alpha: populate AT_HWCAP from env->amask
Alpha has never set AT_HWCAP in linux-user emulation, so getauxval(AT_HWCAP)
always returned 0 regardless of the emulated CPU model.

The Linux kernel computes ELF_HWCAP as ~amask(-1), i.e. the set of ISA
extension bits that the amask instruction reports as supported (cleared in
its output).  env->amask stores exactly those bits with the same layout
(BWX=0x1, FIX=0x2, CIX=0x4, MVI=0x100, TRAP=0x200, PREFETCH=0x1000), so
returning it directly from get_elf_hwcap matches the kernel convention.

Add HAVE_ELF_HWCAP to target_elf.h and implement get_elf_hwcap() in
elfload.c to expose the emulated CPU's capability mask to user-space
programs via the auxiliary vector.

Without this fix, programs using getauxval(AT_HWCAP) to detect BWX/FIX/CIX
(such as glibc's memcpy or JIT compilers targeting Alpha) incorrectly
concluded that no extensions were available even when emulating ev56+.

Signed-off-by: Matt Turner <[email protected]>
Cc: [email protected]
Reviewed-by: Helge Deller <[email protected]>
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit 7a2e863f9d)
(Mjt: in 10.0.x, the code is in linux-user/elfload.c, -  back-port changes
 to pre-elfload-reorg state: HAVE_ELF_HWCAP is ELF_HWCAP, get_elf_hwcap()
 accepts no argument and returns uint32_t)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-15 15:34:37 +03:00
Matt Turner 0366a61683 linux-user/alpha: add coredump support
Define HAVE_ELF_CORE_DUMP and target_elf_gregset_t in target_elf.h,
mirroring the kernel's elf_gregset_t (ELF_NGREG = 66): r0-r31
[0..31], f0-f31 [32..63], pc [64], unique [65].  Implement
elf_core_copy_regs() in elfload.c to populate the gregset from
CPUAlphaState.

Without this, bprm->core_dump is NULL for Alpha targets.  When a
guest signal goes unhandled, dump_core_and_abort() skips the core
write and falls through to die_with_signal(), which re-raises the
signal to the host.  The host kernel then writes an x86-64 core file
for the qemu-alpha process instead of an Alpha guest core.

v2: Store thread unique field, same as in Linux kernel. Added by Helge &
suggested by Richard.

Signed-off-by: Matt Turner <[email protected]>
Signed-off-by: Helge Deller <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
(cherry picked from commit 9db18ed063)
(Mjt: for 10.0.x, move everything to linux-user/elfload.c:
  v10.1.0-36-g58afe4cfe93 "linux-user: Create target/elfload.c files",
 use USE_ELF_CORE_DUMP define instead of HAVE_ELF_CORE_DUMP:
  v10.1.0-115-gbb130c17588 "linux-user: Rename USE_ELF_CORE_DUMP to HAVE_ELF_CORE_DUMP")
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-15 15:34:37 +03:00
Eric Farman d63cdcf24b s390x/css: firm up handling of chained TIC CCWs
The logic in css_interpret_ccw() correctly returns -EINVAL if a
Transfer-In-Channel (TIC) CCW is command chained to another TIC CCW.
The same routine also correctly returns -EINVAL if 256 CCWs do not
perform a data transfer as part of the I/O operation [0].

What is missing, however, is a combination of these two, where a loop
can be generated that will continue processing CCWs but without
providing an opportunity to catch a breath. Fix this by capping
the number of TIC CCWs in a channel program at the same limit as
the CCWs without data transfer.

[0] See "Invalid Sequence" in z/Architecture Principles of Operation
    (SA22-7832-14), p16-27

Cc: [email protected]
Signed-off-by: Eric Farman <[email protected]>
Acked-by: Christian Borntraeger <[email protected]>
Reviewed-by: Farhan Ali <[email protected]>
Signed-off-by: Christian Borntraeger <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Cornelia Huck <[email protected]>
(cherry picked from commit 33bece0fa1)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-15 15:34:37 +03:00
Christian Borntraeger d278f15e4f s390x/sclp: prevent re-reading the sclp header
We verify the sccb length and then allocate based on that length. The
following access re-reads the sccb again. This can race against other
vCPUs overwriting the length field.

sclp_service_call_protected does not need a change as the ultravisor
provides a consistent snapshot.

Fixes: c1db53a591 ("s390/sclp: read sccb from mem based on provided length")
Cc: [email protected]
Signed-off-by: Christian Borntraeger <[email protected]>
Reviewed-by: Matthew Rosato <[email protected]>
Reviewed-by: Eric Farman <[email protected]>
Reviewed-by: Collin Walling <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Cornelia Huck <[email protected]>
(cherry picked from commit 20701190e0)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-15 15:34:37 +03:00
Philippe Mathieu-Daudé 2278aa7c76 hw/s390x/sclp: Do not ignore address_space_read/write() errors
If address_space_read() fails, return PGM_ADDRESSING. In the
unlikely case address_space_write() fails (we already checked
the address is readable), return PGM_PROTECTION.

Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Thomas Huth <[email protected]>
Reviewed-by: Jason J. Herne <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit d39ac36fe2)
(Mjt: pick this one up for 10.0.x so subsequent changes apply cleanly)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-15 15:34:37 +03:00
Philippe Mathieu-Daudé 519c573646 hw/s390x/sclp: Replace [cpu_physical_memory -> address_space]_r/w()
cpu_physical_memory_read() and cpu_physical_memory_write() are
legacy (see commit b7ecba0f6f), replace by address_space_read()
and address_space_write().

Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Thomas Huth <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Reviewed-by: Eric Farman <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit 0d4e15e8f8)
(Mjt: pick this one up for 10.0.x so subsequent changes apply cleanly)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-15 15:34:37 +03:00
Peter Maydell d4ba78d6dc hw/misc/stm32_rcc: Correct offset-to-irq calculation
In the STM32 RCC, there is a block of 5 "enable" registers, each of
which has 32 bits; each bit determines the level of one of the 5 * 32
= 160 enable_irq output lines.  The code calculates the irq to be
worked on using
  irq_offset = ((addr - STM32_RCC_AHB1_ENR) / 4) * 32;

This assumes that the registers are all consecutive; however, there
is a gap between the AHB1/2/3 registers and the APB1/2 registers, so
for the APB1/2 registers we calculate a number that is 32 too high
and can index off the end of the enable_irq[] array.

The handling of the reset registers has an identical bug.

Adjust the calculation of irq_offset to cope with the gap, and fix
the case labels so accesses to the gap fall into the default
LOG_UNIMP rather than being treated as if they were an actual
register.

Coverity CID: 1663683, 1663686
Cc: [email protected]
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Alistair Francis <[email protected]>
Message-id: [email protected]
(cherry picked from commit 3c27494434)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-15 15:34:37 +03:00
Peter Maydell 0e9da86f9e hw/display/sm501: Don't allow guest to set ram size larger than it is
The SM501 DRAM_CONTROL register has a 7 bit Size field which allows
the guest to change the local memory size.  We use the local memory
size in bounds checks calculations for 2D operations. Currently we
have no check on the validity of the value the guest programs to
this field, which means that the guest can:
 - set it to a reserved value (6 or 7) which will cause
   get_local_mem_size() to read outside sm501_mem_local_size[]
 - set it to a value corresponding to more RAM than the card
   was created with, so that the 2D bounds check will let 2D
   operations access off the end of the memory region

Fix this by decoupling the value the guest reads and writes to this
field from the internal size we consider the local memory to have.
We validate changes and ignore them except for readback if they would
be reserved values or values for more memory than the card has.

Cc: [email protected]
Reported-by: Heechan Kang
Tested-by: BALATON Zoltan <[email protected]>
Reviewed-by: BALATON Zoltan <[email protected]>
Signed-off-by: Peter Maydell <[email protected]>
Message-id: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3811
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit 2ac2cf0483)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-15 15:34:37 +03:00
Peter Maydell 728ba0a0a4 hw/display/sm501: Avoid overflow problems in bounds check calculations
When we check that a 2D rectangle operation isn't going to run off
the end of video RAM, we do the calculations as 32 bit arithmetic.
This means that carefully chosen guest register values can cause an
overflow so we don't detect that the operation is going to go outside
video memory.

Abstract the check out into a function, do the calculations as
64-bit arithmetic, and add assertions about the ranges of the
inputs.

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3584
Signed-off-by: Peter Maydell <[email protected]>
Tested-by: BALATON Zoltan <[email protected]>
Reviewed-by: BALATON Zoltan <[email protected]>
Message-id: [email protected]
(cherry picked from commit 422734d5fc)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-15 15:34:37 +03:00
Peter Maydell 1c21d7c9b7 hw/display/sm501: Catch bad coordinates for RTL operations
The sm501 code doesn't check whether a right-to-left operation has
specified a width greater than the x-coordinate (which would make it
extend off the left edge of the screen), or similarly a height
greater than the y-coordinate.  This means the guest can misprogram
the device so that we underflow when calculating the address of the
top left pixel, which might result in accessing out of bounds
memory.  Catch this as a guest error and ignore the operation.

Reported-by: Yannick Wang
Tested-by: BALATON Zoltan <[email protected]>
Reviewed-by: BALATON Zoltan <[email protected]>
Signed-off-by: Peter Maydell <[email protected]>
Message-id: [email protected]
Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3920
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit b378a1bd86)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-15 15:34:37 +03:00
Peter Maydell b6dd635ec7 hw/usb/dev-wacom: Don't write off end of buffer
In usb_wacom_handle_data() we allocate a buffer with a size
determined by the transfer size requested by the guest.  We then fill
it in by calling either usb_mouse_poll() or usb_wacom_poll(), both of
which functions take a length and return an actual length, which we
pass to usb_packet_copy().  However, usb_mouse_poll() doesn't check
the buffer size as it fills in the buffer, so if the guest passes an
overly short transfer size then it will write off the end of the
allocated buffer.

Check the length is at least big enough for the minimum 3 byte
packet and return nothing if it is not, as usb_wacom_poll() does.

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3672
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Message-id: [email protected]
(cherry picked from commit 2c6fae7d7d)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-15 15:34:37 +03:00
Peter Maydell d02fed2283 hw/net/vmxnet3: Correct bounds check on tx queue index
In vmxnet3_io_bar0_write(), we try to bounds-check the TX queue index
provided by the guest against the total number of queues.  However,
we have an off-by-one error: the valid indexes are from 0 to
txq_num-1, so we need a "<" comparison, not "<=".

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3780
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Message-id: [email protected]
(cherry picked from commit 4571c79c57)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-15 15:34:37 +03:00
Richard Henderson 37e0080754 target/arm: Be more defensive for invalid tlbi_aa64_get_range
It's possible to program TCR_ELx with an invalid granule size,
which could match passing an invalid granule size to TLBI RVA,
which would then fall through to assert in arm_granule_bits.

Cc: [email protected]
Fixes: 3c003f7029 ("target/arm: Use ARMGranuleSize in ARMVAParameters")
Signed-off-by: Richard Henderson <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Message-id: [email protected]
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit 79cabc6cb7)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-15 15:34:37 +03:00
Peter Maydell 872c54a20d linux-user: Validate guest-passed dm_ioctl data_size
In do_ioctl_dm() we work with a struct dm_ioctl from the guest.  This
has a fixed initial part, and then a variable data part; the guest
tells us how long that part is by setting the data_size field.  The
data_size is supposed to include the length of the fixed parts of the
struct dm_ioctl.  Currently we don't validate anything about the
guest-provided data_size, and we use it to allocate a buffer which we
then copy the fixed part of the dm_ioctl struct into.  This means
that if the guest passes a very small data_size the copy of the fixed
part will overrun the buffer.

Perform the same sanitizing of the minimum and maximum limits of the
data_size that the kernel does in drivers/md/dm-ioctl.c in the
copy_params() function.

Cc: [email protected]
Fixes: 56e904ecb2 ("linux-user: implement device mapper ioctls")
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3736
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Helge Deller <[email protected]>
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit a47e3c26b1)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-15 15:34:37 +03:00
Heinrich Schuchardt 086d43a06f tests: update SPCR loongarch64 and riscv64 test data
On LoongArch and RISC-V the SPCR test data contained:

    Terminal Type : 00
    Language : 03

The corrected values are:

    Terminal Type : 03
    Language : 00

See the specification of the table in
https://learn.microsoft.com/en-us/windows-hardware/drivers/bringup/serial-port-console-redirection-table

The ACPI table data was rebuilt with
tests/data/acpi/rebuild-expected-aml.sh.

Remove SPCR expections from tests/qtest/bios-tables-test-allowed-diff.h.

Signed-off-by: Heinrich Schuchardt <[email protected]>
Acked-by: Alistair Francis <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit ec7d324287)
(Mjt: for 10.0.x, keep risv table only, loongarch is not there yet)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-15 15:34:37 +03:00
Heinrich Schuchardt 53826e2e67 hw/acpi: correct field sequence in SPCR table
On LoongArch and RISC-V invalid SPCR tables are created:

    Terminal Type : 00
    Language : 03

The correct values are:

    Terminal Type : 03
    Language : 00

This is due to commit 7dd0b070fa ("hw/arm/virt-acpi-build.c: Migrate
SPCR creation to common location") that swapped the fields.

See the specification of the table in
https://learn.microsoft.com/en-us/windows-hardware/drivers/bringup/serial-port-console-redirection-table

This page shows version 1.10. But the sequence of the fields was not changed
since version 1.0.

Our LoongArch and ARM code uses version 1.07 of the specification.
Our RISC-V code uses version 1.10 of the specification.

Fixes: 7dd0b070fa ("hw/arm/virt-acpi-build.c: Migrate SPCR creation to common location")
Origin: https://lore.kernel.org/qemu-devel/[email protected]/T/#u
Bug-Ubuntu: https://bugs.launchpad.net/ubuntu/+source/qemu/+bug/2146419
Signed-off-by: Heinrich Schuchardt <[email protected]>
Reviewed-by: Alistair Francis <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit 15c73b0f17)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-15 15:34:37 +03:00
Heinrich Schuchardt 12f0bf324c tests: allow differences in SPCR
For easier bisection add the SPCR table to bios-tables-test-allowed-diff.h.

Signed-off-by: Heinrich Schuchardt <[email protected]>
Acked-by: Alistair Francis <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit 18a5220990)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-15 15:34:37 +03:00
Alistair Francis 0d5950ff2a hw/pci/pcie_doe: Check mailbox length for overflows
It was possible that a guest could overflow the `doe_cap->write_mbox`
buffer by writing more then PCI_DOE_DW_SIZE_MAX dwords.
`doe_cap->write_mbox_len` would continue to increment and there were no
bounds checks on the length when offsetting into doe_cap->write_mbox.

This patch adds a check and reports a guest error if we would overflow.

On an overflow we also silenty discard the entire object as instructed
to do in the PCIe spec when the length specified in the header
(up to PCI_DOE_DW_SIZE_MAX dwords) doesn't match the length of the
object.

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3679
Signed-off-by: Alistair Francis <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Tao Tang <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit c7e6185454)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-15 15:34:37 +03:00
Akihiko Odaki b82a9699be hw/riscv/riscv-iommu: Fix MemoryRegion owner
as points to the MemoryRegion itself. s is the device that owns the
MemoryRegion.

Signed-off-by: Akihiko Odaki <[email protected].i.u-tokyo.ac.jp>
Reviewed-by: Daniel Henrique Barboza <[email protected]>
Reviewed-by: Nutty Liu <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Message-ID: <[email protected].i.u-tokyo.ac.jp>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit c497ef6739)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-15 15:34:37 +03:00
Daniel Henrique Barboza eab76d5bd4 hw/riscv/riscv-iommu.c: set ftype and iova in riscv_iommu_ctx()
We're hardcoding faulting type as READ, where it could very well be a
write access, and we're not recording the faulting addr/iova.

A note was added in the fault_type logic because I wasn't able to
trivially handle a probable code repeitition it in this same patch.
Something to do in a later date.

Fixes: 0c54acb824 ("hw/riscv: add RISC-V IOMMU base emulation")
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3564
Signed-off-by: Daniel Henrique Barboza <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit ce7fb32827)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-15 15:34:37 +03:00
Frank Chang b3554b5bda hw/riscv: riscv-iommu: Don't look up DDT cache in Off and Bare modes
According to the RISC-V IOMMU specification:

* When ddtp.iommu_mode is set to Off, there is no DDT look-up, and an "All
  inbound transactions disallowed" fault (cause = 256) is reported for any
  inbound transaction.

* When ddtp.iommu_mode is set to Bare, there is no DDT look-up, and the
  translated address is the same as the IOVA, unless the transaction type
  is disallowed (cause = 260).

In the current implementation, the DDT cache is incorrectly looked up
even when ddtp.iommu_mode is set to Off or Bare. This may result in
unintended cache hits.

Therefore, the DDT cache must not be looked up when ddtp.iommu_mode is
set to Off or Bare. For other modes, software is required to issue cache
invalidation commands before any inbound transactions.

Signed-off-by: Frank Chang <[email protected]>
Acked-by: Alistair Francis <[email protected]>
Reviewed-by: Daniel Henrique Barboza <[email protected]>
Reviewed-by: Jim Shu <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit 15406cc593)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-15 15:34:37 +03:00
Chengbo Gao 6eee3411e8 hw/riscv/riscv-iommu: Avoid caching PCI device IDs
PCI bus numbers may still be unassigned when QEMU initializes a PCI
device's bus-master address space.  For devices behind bridges,
pci_bus_num() can return 0 at that point because the guest has not yet
programmed the bridge Secondary Bus Number register.

The RISC-V IOMMU currently stores a fixed device_id in RISCVIOMMUSpace
when the address space is created.  If the guest later enumerates the
device on a non-zero bus, DMA translation still uses the stale device_id
and may look up the wrong device context in the DDT.

Store the stable PCIBus pointer and devfn in RISCVIOMMUSpace instead,
and compute the device_id from the current bus number when it is needed.
This keeps DMA translation and ATS invalidation in sync with guest PCI
bus enumeration.

Signed-off-by: Chengbo Gao <[email protected]>
Reviewed-by: Daniel Henrique Barboza <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit ca7bac51e0)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-15 15:34:37 +03:00
Daniel Henrique Barboza 5cf7ba472d hw/riscv/riscv-iommu: forbid GATE/SADE if caps.AMO_HWADD is zero
When capabilities.AMO_HWADD isn't set, DC.tc.GADE and DC.tc.SADE are
reserved bits and setting them throws a DDT_MISCONFIGURED error.

Fixes: 0c54acb824 ("hw/riscv: add RISC-V IOMMU base emulation")
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3549
Signed-off-by: Daniel Henrique Barboza <[email protected]>
Reviewed-by: Nutty Liu <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit 6d2b9d542f)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-15 15:34:37 +03:00
Daniel Henrique Barboza 3bc064e3ba hw/riscv/riscv-iommu.c: update ioval2 when faulting in spa_fetch()
riscv_iommu_translate(), the only caller of riscv_iommu_spa_fetch(),
will use riscv_iommu_report_fault() for all faults it detects.  And it
will use iotlb->translated_addr as 'iotval2' every time.

At this moment we're updating iotlb->translated_addr only after a
translation step is completed, meaning any fault that occur before that
will have a zeroed iotlb->translated_addr, and as a result iotval2 will
also be zero later on.

Keep iotlb->translated_addr updated with the latest translated addr we
have.

Fixes: 0c54acb824 ("hw/riscv: add RISC-V IOMMU base emulation")
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3559
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 79616dd6e4)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-15 15:34:37 +03:00
Daniel Henrique Barboza 95f716f121 hw/riscv/riscv-iommu.c: check for misaligned IOHGATP_PPN
We must check if IOHGATP_PPN is 16kb aligned for non-bare GATP modes.

Fixes: 69a9ae4836 ("hw/riscv/riscv-iommu: add ATS support")
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3550
Signed-off-by: Daniel Henrique Barboza <[email protected]>
Reviewed-by: Chao Liu <[email protected]>
Reviewed-by: Nutty Liu <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit bf274c5429)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-15 15:34:37 +03:00
Daniel Henrique Barboza 14d7810478 hw/riscv/riscv-iommu-sys.c: record fault on IOMMU-generated MSI write
The riscv-iommu spec requires that the IOMMU records its own generated
MSI write faults.

Fixes: 01c1caa9d1 ("hw/riscv/virt.c, riscv-iommu-sys.c: add MSIx support")
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3572
Signed-off-by: Daniel Henrique Barboza <[email protected]>
Reviewed-by: Nutty Liu <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit 58e801f74e)
(Mjt: include list context fixup in hw/riscv/riscv-iommu-sys.c)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-15 15:34:36 +03:00
Daniel Henrique Barboza d57c84d010 hw/riscv/riscv-iommu.c: check reserved MSI PTE basic bits
We need to throw an MSI_MISCONFIGURED error when any of the reserved PTE
bits (first doubleword only) are set.

Fixes: Fixes: 0c54acb824 ("hw/riscv: add RISC-V IOMMU base emulation")
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3563
Signed-off-by: Daniel Henrique Barboza <[email protected]>
Reviewed-by: Nutty Liu <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit 11486349ad)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-15 15:34:36 +03:00
Daniel Henrique Barboza d974cdb61e hw/riscv/riscv-iommu.c: fault for non-user PTE in G_STAGE
riscv-iommu spec 1.0 says:

"When checking the U bit in a second-stage PTE, the transaction
 is treated as not requesting supervisor privilege."

We need to *always* fault in case we're on G_STAGE and PTE_U is cleared
since we can't be on supervisor mode at this point.

Fixes: 0c54acb824 ("hw/riscv: add RISC-V IOMMU base emulation")
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3555
Signed-off-by: Daniel Henrique Barboza <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit 9158c900ab)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-15 15:34:36 +03:00
Daniel Henrique Barboza 5952919d77 hw/riscv/riscv-iommu.c: fault when !PTE_U and no priv access
All IOMMU accesses are assumed to be user mode unless told otherwise,
i.e. we have a process_id.  In case we have a non-user mode leaf PTE
(PTE_U isn't set) and we are running in user mode, we need to throw a
fault.

This also reflects on qos-riscv-iommu tests: the tests always run in
user mode so our PTEs must have PTE_U (bit 0x10) set.

Fixes: 0c54acb824 ("hw/riscv: add RISC-V IOMMU base emulation")
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3553
Signed-off-by: Daniel Henrique Barboza <[email protected]>
Reviewed-by: Nutty Liu <[email protected]>
Reviewed-by: Chao Liu <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit b795ea0ba4)
(Mjt: omit changes in tests/qtest/libqos/qos-riscv-iommu.h which was added later)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-15 15:34:36 +03:00
Daniel Henrique Barboza 37388042d8 hw/riscv/riscv-iommu.c: check for reserved PTE bits
We need to fault if reserved PTE bits (60:54) are set.

Fixes: 0c54acb824 ("hw/riscv: add RISC-V IOMMU base emulation")
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3554
Signed-off-by: Daniel Henrique Barboza <[email protected]>
Reviewed-by: Nutty Liu <[email protected]>
Reviewed-by: Chao Liu <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit c1d5ec3a2f)
(Mjt: PTE_RESERVED was a constant in 10.0.x, not a macro)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-11 11:18:14 +03:00
Daniel Henrique Barboza 12422e1f44 hw/riscv/riscv-iommu.c: fix fault type for spa_fetch() faults
Under certain circunstances, like the one described in [1] and [2],
a read operation that faults will be logged as a write fault instead,
and vice-versa, if they happen after the translation phase in
riscv_iommu_spa_fetch().

The first problem is that we're overwriting iotlb->perm with PTE flags,
so an IOMMU_RO access flag can be overwritten by whatever flags
the PTE has.  This will cause the wrong fault type to be thrown at
the end of the function in case a fault happens.

To solve the iotlb->perm overwrite we'll bit_and the original
iotlb->perm access flags with the PTE access flags, preserving the
original access type.  So a IOMMU_RO access in a R+W PTE will result in
a IOMMU_RO perm.

Second, the resulting fault is received by riscv_iommu_translate(), which
will then report the fault.  To do that we require a transaction type
(ttype).  We're prioritizing checking "perm & IOMMU_RW" to set a
UADDR_WR ttype, and then checking "perm & IOMMU_RO" to set UADDR_RD
ttype.  The issue with that is IOMMU_RO=1 and IOMMU_RW=3, thus checking
"perm & IOMMU_RW" for a write then "perm & IOMMU_RO" for a read will
cause the read fault to always be diagnosed as write.

Make the iotlb->perm matches more strict: "perm & IOMMU_RW" must be
exactly IOMMU_RW, ensuring that 'perm' has both flags.  Then we can
check perm & IOMMU_WO and perm & IOMMU_RO without worrying about
overlapping with the RW flag.

[1] https://gitlab.com/qemu-project/qemu/-/work_items/3557
[2] https://gitlab.com/qemu-project/qemu/-/work_items/3577

Fixes: 69a9ae4836 ("hw/riscv/riscv-iommu: add ATS support")
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3557
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3577
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 b18e3f0e2d)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-11 09:33:42 +03:00
Jia Jia 4493fb4d1b hw/ufs: avoid double unref of wrapped scsi-hd
ufs_init_scsi_device() creates an internal scsi-hd and adds it as a
child of lu->bus. qdev_realize_and_unref() then drops the construction
reference, leaving the bus child ownership to tear it down.

ufs_lu_unrealize() still unrefs lu->scsi_dev directly. If the UFS
controller is ejected through ACPI PCI hotplug, the scsi-hd object can be
finalized there and then the bus child removal RCU callback later unrefs
the same object again.

Keep lu->scsi_dev as a borrowed pointer and clear it during unrealize
without unreffing it.

Add a qtest that ejects the UFS controller through the x86 ACPI PCI
hotplug eject register. On an ASAN build, the test reproduces the UAF
before the fix.

Fixes: 096434fea1 ("hw/ufs: Modify lu.c to share codes with SCSI subsystem")
Cc: [email protected]
Signed-off-by: Jia Jia <[email protected]>
Signed-off-by: Jeuk Kim <[email protected]>
(cherry picked from commit 90aacd5bc4)
(Mjt: tests/qtest/ufs-test.c: context fixup)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-10 13:41:35 +03: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
Randy Schifflin f63a90b82e target/sh4: fixup tcg for sh4 fipr/ftrv instructions
Fixes TCG generation for sh4 `fipr` and `ftrv` instructions.
Updates the current logic for these instructions to check the
FPSCR register appropriately (according to the sh4 cpu manual, `fipr`
and `ftrv` are only defined when the FPSCR register PR flag is 0).
Also fixes the mth/nth-vector operands by multiplying by 4 to convert
to the correct floating point register offset.

Signed-off-by: Randy Schifflin <[email protected]>
Reviewed-by: Yoshinori Sato <[email protected]>
Message-ID: <20260629-fixup-sh4-tcg-fpu-instructions-b4-v1-2-4356b305f971@gmail.com>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit 614a52cf54)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-09 08:58:04 +03:00
Richard Henderson d0b6f70a90 tcg/loongarch64: Fix cmp_vec with TCG_COND_NE
For NE we need to invert EQ, not swap operands.

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3589
Signed-off-by: Richard Henderson <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit c56ebd64b8)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-09 08:50:20 +03:00
Richard Henderson c7832b4281 tcg/loongarch64: Improve constraints for TCG_CT_CONST_VCMP
Use the TCGCond given to tcg_target_const_match to exactly match
the supported constant.  Adjust the code generation to assume this
has been done -- recall that encode_*_insn contain assertions that
the constants are valid.

Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
(cherry picked from commit 911f7328e9)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-09 08:50:05 +03:00
Richard Henderson cd365f3085 tcg/loongarch64: Fix vec_val computation in tcg_target_const_match
Only use vece for a vector constant.  This avoids an assertion
failure in sextract64 when vece contains garbage.

Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
(cherry picked from commit a079836005)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-09 08:49:58 +03:00
Ilya Leoshkevich f51b0292ad accel/tcg: Make PageFlagsNodes' start and last immutable
page_check_range() may race with pageflags_set_clear() as follows:

    T1                                     T2
    -------------------------------------  --------------------------------
                                           p = pageflags_find(start, last);
    interval_tree_remove(&p->itree, ...);
    p->itree.start = last + 1;
                                           if (start < p->itree.start) {
                                               ret = false;
    interval_tree_insert(&p->itree, ...);

leading to errors like

    fail indirect write 0x72f0a659aff0 (Bad address)

in vma-pthread test. I am able to reliably reproduce this on a machine
with 32 SMT threads as follows in about 25 seconds:

    jobs=32; \
    seq "$jobs" | \
        time -p parallel \
            --jobs="$jobs" \
            --halt=now,done=1 \
            --ungroup \
            '
                _={};
                while ./qemu-s390x tests/tcg/s390x-linux-user/vma-pthread; do
                    printf .;
                done
            '

Also wasmtime project reported a similar failure pattern in their CI [1]
with a similar reproducer [2].

There are other races like this. In general, region bounds mutating
underneath the reader are very hard to reason about. So fix this by
preventing mutations and creating copies instead. Use RCU guards in
readers to avoid uses-after-frees.

Now, when the reader finds a node, it may fearlessly access its fields
and be certain that at some point in time the respective region had the
respective bounds and permissions. The downside is slightly more
expensive mprotect(), but complexity reduction is worth it.

Lockless field accesses should probably be wrapped in qatomic_read(),
but this is a pre-existing issue, so do not change it here.

[1] https://github.com/bytecodealliance/wasmtime/issues/10000
[2] https://gist.github.com/alexcrichton/f14f23a892ffb9df2522754572d51b1c

Cc: [email protected]
Reported-by: Alex Crichton <[email protected]>
Reported-by: Ulrich Weigand <[email protected]>
Fixes: 67ff2186b0 ("accel/tcg: Use interval tree for user-only page tracking")
Signed-off-by: Ilya Leoshkevich <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Reviewed-by: Pierrick Bouvier <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit e03b7dac65)
(Mjt: context fix for 10.0.x for lack of v10.1.0-1315-gf55fc1c092
 "accel/tcg: Add clear_flags argument to page_set_flags")
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-09 08:38:00 +03:00
Richard Henderson ff4ef54ebc accel/tcg: Use TLB_FORCE_SLOW not TLB_MMIO for user-only plugins
In 6d03226b42 we set TLB_MMIO to a non-zero value for user-only
so that we could return a non-zero value from probe_* functions
so that we could force callers like Arm SVE vector moves to use
the slow path rather than direct access.  All for the sake of
exposing these accesses to plugins.

Back then, TLB_FORCE_SLOW did not exist, so TLB_MMIO seemed like
a reasonable solution.  However, user-only doesn't really have
MMIO and this has knock-on effects, like forcing Arm SVE first-fault
vector loads to stop.  Better to use TLB_FORCE_SLOW as a more exact
trigger for plugins.

Cc: [email protected]
Fixes: 6d03226b42 ("plugins: force slow path when plugins instrument memory ops")
Acked-by: Alex Bennée <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit b79a9b6e5b)
(Mjt: backport to 10.0.x, move changes from include/exec/tlb-flags.h to cpu-all.h
 across v10.0.0-145-g4d43552abe "exec/cpu-all: extract tlb flags defines to exec/tlb-flags.h"
 and adjust for lack of subsequent changes in this area)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-09 07:21:09 +03:00
Sanjeeva Yerrapureddy fd9f6eaa54 hw/net: fix e1000e/igb ip_len inflation by Ethernet minimum-frame padding
When a guest transmits a short Ethernet frame, iov_size() returns the
padded wire length including any bytes added to reach the Ethernet
minimum frame size of 60 bytes.  net_tx_pkt_rebuild_payload() uses
this inflated size as payload_len.  net_tx_pkt_update_ip_hdr_checksum()
then overwrites the IPv4 Total Length field with payload_len +
l3_hdr_len, inflating it by the padding.  The receiver interprets
Ethernet padding as IP payload, producing a malformed packet.

Fix by removing the ip_len write from net_tx_pkt_update_ip_hdr_checksum()
so it only recomputes the checksum, and moving the ip_len assignment
into net_tx_pkt_update_ip_checksums() where it is only performed for
TSO (where ip_len must be derived from payload_len since the guest sets
ip_len=0 per Intel 82574 datasheet §7.3.4 for super-packets the host
will segment).

Both e1000e and igb already call net_tx_pkt_update_ip_hdr_checksum()
from their IXSM paths, so both are corrected by this single common-
layer change.

Signed-off-by: Sanjeeva Yerrapureddy <[email protected]>
Reivewed-by: Akihiko Odaki <[email protected].i.u-tokyo.ac.jp>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Message-ID: <20260629-net-tx-pkt-ip-length-padding-v5-1-16760e30252e@gmail.com>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit 9e41b5d22a)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-08 15:41:42 +03:00
hemanshu.khilari.foss 789a233561 hw/core/qdev-clock: Fix potential null pointer dereference
qdev_get_clocklist() function returns a pointer to the NamedClockList
struct. This function is called in qdev_alias_clock() and the returned
pointer is immediately dereferenced without a null check.

Passing a clock name that doesn't exist to qdev_get_clocklist() is a
programming error, and so this change is not fixing a bug, only making
the reporting of that programming error a bit more helpful and bringing
it in to line with qdev_get_clock_in() and qdev_get_clock_out().

Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/2342
Signed-off-by: hemanshu.khilari.foss <[email protected]>
Message-id: [email protected]
Reviewed-by: Luc Michel <[email protected]>
Reviewed-by: Peter Maydell <[email protected]>
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit 7913b3b946)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-08 13:27:01 +03:00
lizhaoxin04 a2001d0efd vdpa: fix use-after-free of vqs in vhost_vdpa_device_unrealize
vhost_vdpa_device_unrealize() frees s->dev.vqs before
vhost_dev_cleanup(), but vhost_dev_cleanup() still accesses hdev->vqs
while tearing down virtqueues. This leads to a use-after-free and may
crash QEMU with SIGSEGV during vDPA hot-unplug.

Save the vqs pointer in a local variable, call vhost_dev_cleanup(),
and free it afterward. This matches the cleanup pattern used by
vhost-scsi.

Fixes: b430a2bd23 ("vdpa: add vdpa-dev support")
Co-developed-by: Miao Kezhan <[email protected]>
Signed-off-by: Li Zhaoxin <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit e03463812e)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-08 13:27:01 +03:00
Thomas Huth 3e8ac84f9d hw/display/qxl: Fix mono cursor validation that can read past a cursor chunk
qxl_render_cursor() maps the guest-provided QXLCursor object using the
guest-controlled cursor->chunk.data_size.
For a mono cursor, qxl_cursor() then validates the expected bitmap size
against cursor->data_size, but it does not validate that the first chunk
actually contains that many bytes.
A guest could set cursor->data_size to the correct full mono cursor size
while setting cursor->chunk.data_size to zero. In that case, cursor_set_mono()
reads the AND/XOR masks starting at cursor->chunk.data. If the cursor object
is placed at the end of the QXL RAM BAR, those reads cross the mapped RAM
region and could crash the QEMU process (e.g. under ASan).

Fix it by double-checking cursor->chunk.data_size for the correct size.

This patch is based on the suggested changes by the reporter in the bug
ticket.

Reported-by: huntr bubble
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3646
Signed-off-by: Thomas Huth <[email protected]>
Acked-by: Marc-André Lureau <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit 0e51b71c7b)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-08 13:27:01 +03:00
Peter Maydell 43bfc32cb7 hw/scsi/mptsas: Reset doorbell state on reset
Currently the mptsas reset function clears intr_status, but it
doesn't reset the doorbell state machine.  This means that the state
machine and the interrupt state get out of sync, and the guest can
trigger an assertion failure in mptsas_doorbell_read() where
s->doorbell_state is still DOORBELL_READ but s->intr_status does not
have MPI_HIS_DOORBELL_INTERRUPT set.

Fix this by having reset also reset the doorbell state.  Strictly
speaking we don't need to also clear doorbell_reply_idx and
doorbell_reply_size, because those are only read when in
DOORBELL_READ state, and the code always sets them up before
transitioning into that state.  But it's less confusing to clear them
out on reset.

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/304
Signed-off-by: Peter Maydell <[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 831a13665a)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-08 13:27:01 +03:00
Peter Maydell 7fb6ffe10a hw/dma/i8257: Return zeroes for read_memory in verify mode
The i8257 DMA controller has a "verify" mode, which the datasheet
describes like this:

> DMA verify, which does not actually involve the transfer of data.
> When an 8257 channel is in the DMA verify mode, it will respond the
> same as described for transfer operations, except that no memory or
> I/O read/write control signals will be generated.  When an 8257
> channel is in the DMA verify mode, it will respond the same as
> described for transfer operations, except that no memory or I/O read
> /write control signals will be generated, thus preventing the
> transfer of data.  The 8257, however, will gain control of the system
> bus and will acknowledge the peripheral's DMA request for each DMA
> cycle.  The perihperal can use these acknowledge signals to enable an
> internal access of each byte of a data block in order to execute some
> verification procedure, such as the accumulation of a CRC check word.

In practice, for QEMU's purposes the only real user of this is the
floppy controller, which can be made to perform a "read data from
floppy disk and check the checksum" by telling the fdc to do a read
and the DMA controller to do a verify.  This causes the fdc to do all
the usual read actions including the checksum, but the data is never
written to memory.  However, it is possible for a guest doing
something silly to program the DMA controller to do a verify
operation for a device that wants to read from memory.  Currently we
simply return early from i8257_dma_read_memory() without writing to
the buffer.  None of the callers (the GUS, sb16 and cs4231a sound
cards, plus the fdc) expect this, so they will take the uninitialized
data as if it were from the guest.  This can cause us to leak host
data off the stack into the guest.

Make i8257_dma_read_memory() fill the buffer with zeroes rather
than leaving it untouched for a verify operation.

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3487
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Daniel P. Berrangé <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit 03071f99a3)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-08 13:27:01 +03:00
Denis V. Lunev e239226959 tests/qtest/ahci: test ATAPI read completing after engine restart
Add a regression test for the crash that occurs when a buffered ATAPI
read completes after the command engine has been restarted. Issue an
ATAPI READ_10 against a blkdebug-backed CD, suspend the backend read so
it stays in flight, stop and restart the port's command engine (which
re-maps the command list and clears cur_cmd), then release the read.

The PIO and DMA reply paths fault in different AHCI helpers
(ahci_pio_transfer() vs ahci_dma_rw_buf()), so cover both. The DMA
variant is the reliable guard: on engine restart check_cmd() can re-arm
cur_cmd before the old read completes, so the PIO variant does not fault
in every build.

The test only asserts that qemu survives a subsequent register access;
if the blkdebug breakpoint ever failed to park the read it would pass
without exercising the bug, as with the existing break/resume tests.

Signed-off-by: Denis V. Lunev <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit cb7bc10385)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-08 13:27:01 +03:00
Denis V. Lunev 39327c6b1a hw/ide/ahci: cancel in-flight buffered reads on command engine restart
ATAPI CD reads are issued through ide_buffered_readv()
(cd_read_sector() and ide_atapi_cmd_read_dma_cb() in hw/ide/atapi.c).
The PIO path discards the returned aiocb; the DMA path stores it in
s->bus->dma->aiocb.

A guest can stop and restart a port's command engine
(PxCMD.ST 1 -> 0 -> 1) while such a read is still in flight. Stopping
the engine unmaps the command list (ahci_unmap_clb_address()) and
restarting it re-maps the list and clears AHCIDevice.cur_cmd to NULL,
but nothing tears down the outstanding read. This path does not run
ide_reset(), so the drive's transfer state is preserved and the read
still completes. Its callbacks then dereference the stale or NULL
cur_cmd in the AHCI transfer helpers:

  PIO: cd_read_sector_cb() -> ide_atapi_cmd_reply_end() ->
       ide_transfer_start_norecurse() -> ahci_pio_transfer()

  DMA: ide_atapi_cmd_read_dma_cb() -> ahci_dma_rw_buf() ->
       ahci_populate_sglist()

Both crash with a NULL cur_cmd; the PIO variant has been seen in the
field.

Cancel the outstanding I/O when the command list is unmapped, reusing
ide_cancel_dma_sync() as the ATAPI DEVICE RESET command does. It runs
the completion callback with -ECANCELED (which tears down
s->bus->dma->aiocb for the DMA case) and orphans the buffered request,
so the eventual asynchronous completion is a no-op. Merely setting the
orphaned flag is not enough: it would leave s->bus->dma->aiocb pointing
at a freed aiocb that a later reset would cancel.

Fixes: 1d8c11d631 ("ide: add support for IDEBufferedRequest")
Signed-off-by: Denis V. Lunev <[email protected]>
Message-ID: <[email protected]>
[PMD: Use ide_bus_active_if()]
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit d9f78431d8)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-08 13:27:01 +03:00
Torin Carey 09dcdbae04 hw/misc/edu: restrict dma access to dma buffer
The EDU device doesn't enforce any bound checks on the addresses provided,
allowing users of the device to perform arbitrary reads and writes to QEMU's
address space.

Signed-off-by: Torin Carey <[email protected]>
Cc: [email protected]
Fixes: 7b608e5d6c ("hw: misc: edu: use qemu_log_mask instead of hw_error")
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3852
Reviewed-by: Peter Maydell <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit 42f599172a)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-08 13:27:00 +03:00
Eric Farman b9056d47fb s390x/css: limit number of CHPIDs in description
virtio-ccw uses a single virtual CHPID for all devices and
device-types, but vfio-ccw (passthrough) shares real CHPID
information with the guest. A sufficiently large passthrough
configuration would exceed the defined response payload.

Fix this by limiting the number of CHPID descriptions that
are returned based on the given response format.

Cc: [email protected]
Reviewed-by: Christian Borntraeger <[email protected]>
Reviewed-by: Matthew Rosato <[email protected]>
Signed-off-by: Eric Farman <[email protected]>
Signed-off-by: Christian Borntraeger <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Cornelia Huck <[email protected]>
(cherry picked from commit 22f2da06a8)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-08 10:39:13 +03:00
Matthew Rosato 04e0a1376e s390x/ioinst: Require strict length and format for SEI CHSC handler
Ensure SEI commands that are received are of the appropriate length and
format before handling.

Cc: [email protected]
Fixes: 8cba80c3a0 ("s390: Add PCI bus support")
Reviewed-by: Christian Borntraeger <[email protected]>
Reviewed-by: Farhan Ali <[email protected]>
Reviewed-by: Eric Farman <[email protected]>
Signed-off-by: Matthew Rosato <[email protected]>
Signed-off-by: Christian Borntraeger <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Cornelia Huck <[email protected]>
(cherry picked from commit 386268daea)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-08 10:39:13 +03:00
Matthew Rosato a40c0d9791 s390x/pci: Shrink RPCIT ranges to registered window
Today, if a RPCIT instruction is presented from the guest whose range
exceeds the previously-registered IOAT, QEMU will process the range
so long as 1) the specified range at least partially overlaps with
what was previously registered and 2) the guest has valid IOAT entries
in its table.  If the entries are not present (invalid), then the
RPCIT will unnecessarily spend time reporting the invalid
region/segment entries.

Optimize this path by exiting immediately if the requested range falls
completely outside of the previously-registered range or if the
requested range ends before it starts (which would only occur if the
guest-specified address + length would overflow a u64).  Otherwise,
clamp the request to only the portion of the range that overlaps with
what was previously registered, effectively ignoring the portion
outside of the registered range.

Cc: [email protected]
Fixes: 5d1abf2344 ("s390x/pci: enforce zPCI state checking")
Reviewed-by: Christian Borntraeger <[email protected]>
Reviewed-by: Farhan Ali <[email protected]>
Signed-off-by: Matthew Rosato <[email protected]>
Signed-off-by: Christian Borntraeger <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Cornelia Huck <[email protected]>
(cherry picked from commit b8c8ec1d75)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-08 10:39:13 +03:00
Matthew Rosato d580823dde s390x/pci: Tighten region detection for BAR read/write
For PCISTG/PCISTB/PCILG instruction emulation, ensure that the offset
and length provided by the guest does not overflow, and only return
a memory region when the specified offset+length combination matches
an existing subregion or the parent region.

Cc: [email protected]
Fixes: 4f6482bfe3 ("s390x/pci: search for subregion inside the BARs")
Signed-off-by: Matthew Rosato <[email protected]>
Reviewed-by: Christian Borntraeger <[email protected]>
Reviewed-by: Farhan Ali <[email protected]>
Signed-off-by: Christian Borntraeger <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Cornelia Huck <[email protected]>
(cherry picked from commit 2d709a70c7)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-08 10:39:13 +03:00
Christian Borntraeger f4116bc4cb s390x/sclp: reject invalid write event data headers
If a guest submits an sccb with a tiny header length but a large number
of event mask entries, the write_event_mask handler will
1. return the wrong RC (ok instead of error)
2. write to memory after the allocated sccb in qemu host memory.

Add the necessary checks.

Cc: [email protected]
Reviewed-by: Hendrik Brueckner <[email protected]>
Reviewed-by: Matthew Rosato <[email protected]>
Reviewed-by: Eric Farman <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: Christian Borntraeger <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Cornelia Huck <[email protected]>
(cherry picked from commit d88cd8f557)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-08 10:39:13 +03:00
Keith Busch f5f603e1f9 hw/nvme: ensure sgl forward progress
A degenerate host can create segment loops of zero-byte data descriptors
that the controller never breaks out of. While the spec allows zero
length segments, it provides no guidance on handling loops. It
makes no sense for a host to submit such a descriptor anyway since it
can and trivially should point to the next transfer segment, so don't
even try to work with such behavior. Just reject the command,
terminating the loop.

Cc: [email protected]
Reported-by: Feifan Qian <[email protected]>
Reported-by: boy juju <[email protected]>
Signed-off-by: Keith Busch <[email protected]>
Reviewed-by: Klaus Jensen <[email protected]>
Signed-off-by: Klaus Jensen <[email protected]>
(cherry picked from commit 034baf047f)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-08 09:49:21 +03:00
Jesper Wendel Devantier cd1a6a2f9c hw/nvme: fix FDP set FDP events
Addresses an issue reported whereby user-provided event type values
could trigger two issues:

 1. if provided event_type == 0xff -> out-of-bounds access

 2. if provided event_type > 7 -> generate a value too large for the
    u8 event mask.

This patch fixes (1) by correctly adjusting the length of the look-up
array to be 256 values.
This patch fixes (2) by:
  a. changing the event_type mask to 64bit, matching
     NvmeRuHandle.event_filter
  b. Matching the behavior of Get Feature - FDP Events by skipping
     event type values which we do not support.
     5.2.26.1.21 of the 2.3 Base specification does not explicitly
     tell us to reject unsupported event type values.
  c. Documenting in the event type lookup table, that supporting
     event types greater than 63 requires refactoring the masking
     code.

Cc: [email protected]
Reported-by: jaeyeong <[email protected]>
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3631
Signed-off-by: Jesper Wendel Devantier <[email protected]>
Reviewed-by: Klaus Jensen <[email protected]>
Signed-off-by: Klaus Jensen <[email protected]>
(cherry picked from commit ec917cd499)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-08 09:49:21 +03:00
Alex Bennée 2ae284c52e hw/arm: use cortex-a9 mpcore base for CBAR on npcm7xx machines
CBAR is an IMPDEF register and according to the A9 TRM [1]:

  In Cortex-A9 MPCore implementations, the base address is reset to
  PERIPHBASE[31:13] so that software can determine the location of the
  private memory region [2].

If it doesn't we will confuse the Linux kernel as it probes the system
SCU registers [3] and erroneously assumes the system is a buggy Aegis SOC
and nerf the emission of SEV instructions, deadlocking any WFE's in
the kernel (or QEMU smpboot code).

[1] https://developer.arm.com/documentation/ddi0388/i/system-control/register-descriptions/configuration-base-address-register
[2] https://developer.arm.com/documentation/ddi0407/g/Introduction/Private-Memory-Region
[3] https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/arch/arm/kernel/head.S?h=v7.1#n550

Fixes: 2d8f048c25 ("hw/arm: Add NPCM730 and NPCM750 SoC models")
Cc: [email protected]
Signed-off-by: Alex Bennée <[email protected]>
Reviewed-by: Peter Maydell <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Message-id: [email protected]
Suggested-by: Arnd Bergmann <[email protected]>
Reviewed-by: Peter Maydell <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit 62b425bec3)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-08 09:49:21 +03:00
Feifan Qian 3425f5396f hw/net/fsl_etsec: validate FCB offsets in process_tx_fcb()
The TX Frame Control Block (FCB) is prepended to a TX frame when
BD_TX_TOEUN is set. It contains two guest-controlled u8 offset
fields that process_tx_fcb() uses to locate L3/L4 headers within
the frame buffer:

  l3_header_offset = FCB byte 3 (0..255)
  l4_header_offset = FCB byte 2 (0..255)

These offsets are applied without any bounds check. When the
UDP-no-CTU branch is taken, the function writes zero to
l4_header[6] and l4_header[7]. With both offsets set to 0xFF the
write target is:

  tx_buffer + 8 + 255 + 255 + 6/7 = tx_buffer + 525

A malicious guest can therefore corrupt up to 509 bytes of heap
memory beyond a minimally-sized (16 B) TX frame.

Fix: reject the frame and log a guest error when the minimum
required buffer length

  8 (FCB) + l3_header_offset + l4_header_offset + 8

exceeds tx_buffer_len. Move the l3_header and l4_header pointer
declarations past the new guard so that out-of-bounds pointers
are never materialised.

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3517
Signed-off-by: Feifan Qian <[email protected]>
Reviewed-by: Peter Maydell <[email protected]>
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit bc22c7e418)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-08 09:49:21 +03:00
Junjie Cao 105e518277 virtio-net: validate RSS indirections_len in post_load
virtio_net_handle_rss() enforces that indirections_len is a non-zero
power of two no larger than VIRTIO_NET_RSS_MAX_TABLE_LEN, but
virtio_net_rss_post_load() applies none of these checks to values
restored from the migration stream.

A corrupted save file or crafted migration stream can set
indirections_len to 0.  Even if it also clears redirect,
virtio_load() calls set_features_nocheck() after the device vmstate
(including the RSS subsection and its post_load) has already been
loaded, re-deriving redirect from the negotiated guest features.
When VIRTIO_NET_F_RSS was negotiated, redirect is set back to true
regardless of the migration stream value.  The receive path then
computes

    hash & (indirections_len - 1)   /* wraps to 0xFFFFFFFF via int promotion */

and uses the result to index into indirections_table, which was not
allocated by the VMState loader when the element count is zero (see
vmstate_handle_alloc()), resulting in a NULL pointer dereference that
crashes QEMU:

  #0  virtio_net_process_rss    ../hw/net/virtio-net.c:1901
  #1  virtio_net_receive_rcu    ../hw/net/virtio-net.c:1921
  #2  virtio_net_do_receive     ../hw/net/virtio-net.c:2061
  #3  nc_sendv_compat           ../net/net.c:823
  #4  qemu_deliver_packet_iov   ../net/net.c:870

The RSS subsection is only loaded when rss_data.enabled is true (via
virtio_net_rss_needed()), and the command path always produces
indirections_len in {1, 2, 4, …, 128}, so an unconditional check
cannot reject a legitimate migration stream.

Factor the validation into virtio_net_rss_indirections_len_valid()
and call it from both virtio_net_handle_rss() and
virtio_net_rss_post_load().

Fixes: e41b711485 ("virtio-net: add migration support for RSS and hash report")
Cc: [email protected]
Signed-off-by: Junjie Cao <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit 32a90850e1)
(Mjt: backport to 10.0.x series, introducing small parts of commit
 v10.0.0-2242-g7b6e7e4990 "virtio-net: Retrieve peer hashing capability"
 which added virtio_net_rss_post_load() method to vmstate_virtio_net_rss)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-08 09:47:43 +03:00
Laurent Vivier 8afd46704e hw/char/virtio-serial-bus: fix guest-triggerable OOM in control_out()
A malicious guest can craft virtqueue descriptors with arbitrary lengths.
control_out() calls iov_size() on the guest-supplied scatter-gather list
and passes the result directly to g_malloc(), allowing a guest to force
QEMU to attempt multi-gigabyte allocations and crash the host process.

Fix this by copying at most sizeof(struct virtio_console_control) into a
stack-local variable instead of allocating a buffer sized by the guest.
handle_control_message() only accesses the fixed-size id, event, and
value fields, so no data beyond the struct was ever needed.

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/3585
Signed-off-by: Laurent Vivier <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit 36b37f8494)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-07 11:01:33 +03: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
Daniel Henrique Barboza d8f216a703 hw/riscv/riscv-iommu.c: always fault with SADE=0 and A=0
riscv-iommu spec: "If SADE is 1, the IOMMU updates A and D bits in
first-stage PTEs atomically. If SADE is 0, the IOMMU causes a
page-fault corresponding to the original access type if the
A bit is 0 or if the memory access is a store and the D bit is 0.".

Note that SADE=0 and A=0 will always cause a fault regardless of the
original access type.  Right now we're faulting in this case just for
reads.

Fixes: 0c54acb824 ("hw/riscv: add RISC-V IOMMU base emulation")
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3551
Signed-off-by: Daniel Henrique Barboza <[email protected]>
Acked-by: Alistair Francis <[email protected]>
Reviewed-by: Nutty Liu <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit 64ce9ac187)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-03 22:12:54 +03:00
SeungJu Cheon c239e12ec5 target/riscv: Apply UXL WARL handling to vsstatus
write_mstatus() already handles the reserved UXL value by writing a
legal value instead.

Apply the same handling when writing vsstatus so that reserved UXL
values follow the same WARL behavior.

Factor the common logic into a local helper riscv_write_uxl() and use
it for both mstatus and vsstatus.

Suggested-by: Daniel Henrique Barboza <[email protected]>
Fixes: f310df58bd ("target/riscv: Enable uxl field write")
Signed-off-by: SeungJu Cheon <[email protected]>
Reviewed-by: Daniel Henrique Barboza <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit dcd0285177)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-03 22:11:26 +03:00
ZhengXiang Qin 3dcae5226a target/riscv: avoid abort when reading vtype before env->xl is set
TCG plugins may read registers from the vcpu_init_cb() callback.  For
vtype, this reaches read_vtype() before env->xl has been initialized.

In that case read_vtype() currently hits g_assert_not_reached() because
env->xl is zero.  Fall back to the CPU's maximum XLEN only for this
early-init case.

Fixes: 638181a180 ("core/cpu-common: initialise plugin state before thread creation")
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/3545
Signed-off-by: ZhengXiang Qin <[email protected]>
Reviewed-by: Daniel Henrique Barboza <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit 46d96da130)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-03 22:10:04 +03:00
Qingwei Hu 1af169451e hw/riscv/virt-acpi-build: Fix RINTC PLIC context ID for KVM
Each RISC-V MADT RINTC entry contains an External Interrupt Controller
ID field. On the virt machine without AIA, this field identifies the
S-mode PLIC context associated with the hart.

TCG virt has both M-mode and S-mode PLIC contexts, so the S-mode context
ID is odd and 2 * local_cpu_id + 1 is correct. KVM virt exposes only
S-mode PLIC contexts, and those contexts are numbered contiguously from
0. Reporting the TCG context ID for KVM makes the guest enable a
different PLIC context from the one used by QEMU.

With ACPI enabled, this can leave PCI INTx interrupts pending in QEMU
while the guest-programmed PLIC context remains disabled. A virtio-blk
root disk can then stall during boot because its first interrupt is never
delivered.

Use local_cpu_id for KVM and keep the existing odd S-mode context ID for
TCG.

Fixes: d641da6ed4 ("hw/riscv/virt-acpi-build.c: Add PLIC in MADT")
Signed-off-by: Qingwei Hu <[email protected]>
Reviewed-by: Nutty Liu <[email protected]>
Reviewed-by: Sunil V L <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit fdfcd98f66)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-03 22:09:40 +03:00
Inochi Amaoto 0c6a12b9e4 target/riscv: Check PMP before updating PTE
According to the RISC-V spec, the PTE update is a supervisor write
operations, and it should also follow the CPU PMP configuration like
the PTE read.

Cc: [email protected]
Signed-off-by: Inochi Amaoto <[email protected]>
Reviewed-by: Alistair Francis <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit fa2cf74883)
Signed-off-by: Michael Tokarev <[email protected]>
2026-07-02 13:56:35 +03:00
Christian Schoenebeck dbe1907c54 hw/9pfs/local: harden local_fid_fd() on FID types
local_fid_fd() returns fs->fd for any FID type that is not P9_FID_DIR.

Since P9_FID_XATTR and P9_FID_NONE share union V9fsFidOpenState, calling
local_fid_fd() on these types misinterprets xattr state as a file
descriptor, potentially leading to undefined behaviour or information
disclosure.

Even though we are catching these FID type mismatches on protocol level
in 9p.c already, previous patches proofed this to be error prone.

So let's add another safety layer in local_fid_fd() that would return -1
if the FID type would not possess a valid file descriptor, to prevent
wrong file descriptors from reaching fs backend calls.

Link: https://lore.kernel.org/qemu-devel/531f6b81bc1bf1a48c3d4afaa60a65db10511041.1781621428.git.qemu_oss@crudebyte.com
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit 75893c058b)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-30 09:40:16 +03:00
Christian Schoenebeck 29f1f4b3ab hw/9pfs: fix invalid union access by v9fs_co_fstat()
The individual FID types (P9_FID_NONE, P9_FID_FILE, P9_FID_DIR, P9_FID_XATTR)
share union V9fsFidOpenState with FID-type specific fields. Accessing any of
the union fields must comply with the FID-type to avoid undefined behaviour
or information disclosure.

Fix this in v9fs_lock() and v9fs_getlock() by checking if FID has a valid
file descriptor before calling v9fs_co_fstat().

Fixes: 10b468bdc5 ("virtio-9p: Implement TXATTRCREATE")
Link: https://lore.kernel.org/qemu-devel/4b33cd1aaa2551efda220a6f651e3660d27f4746.1781621428.git.qemu_oss@crudebyte.com
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit c3aa2491cd)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-30 09:40:16 +03:00
Christian Schoenebeck 54f705e422 hw/9pfs: fix invalid union access by v9fs_co_fsync()
The individual FID types (P9_FID_NONE, P9_FID_FILE, P9_FID_DIR, P9_FID_XATTR)
share union V9fsFidOpenState with FID-type specific fields. Accessing any of
the union fields must comply with the FID-type to avoid undefined behaviour
or information disclosure.

Fix this in v9fs_fsync() and v9fs_wstat() by checking if FID has a valid file
descriptor before calling v9fs_co_fsync().

Fixes: 10b468bdc5 ("virtio-9p: Implement TXATTRCREATE")
Reported-by: Feifan Qian <[email protected]>
Link: https://lore.kernel.org/qemu-devel/b583e29d5a0776e41263732c93ac9f0da0a6016d.1781621428.git.qemu_oss@crudebyte.com
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit 32cae47c33)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-30 09:40:16 +03:00
Christian Schoenebeck b59ee536a3 tests/9p: add 3 xattr FID limit test cases (local fs driver)
Analogue to the previously added 3 synth tests, add (similar) 3 test
cases using the "local" fs driver to verify correct xattr FID limit
enforcement of 9pfs server with a real filesystem.

These 3 new local tests use the shared test code of the previously
added 3 synth tests. The only difference is that the local fs driver
does not expose the current internal xattr FID counter, so we can't
verify this with the local tests.

This is a slow test (may take several seconds) and therefore
registered as "slow" test and not running by default.

Use -m slow to run this test.

Link: https://lore.kernel.org/qemu-devel/d23fa874df4f474ee7cbe738a35c1483426057f0.1781361555.git.qemu_oss@crudebyte.com
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit 04a62cdfe8)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-30 09:40:16 +03:00
Christian Schoenebeck 865fc2874f tests/9p: add 3 xattr FID limit test cases (synth fs driver)
Add 3 test cases to verify correct xattr FID limit enforcement of
9pfs server.

 - 1. test with default max_xattr=1024
 - 2. test with custom max_xattr=100
 - 3. test with unlimited max_xattr=0

These are tests using the synth driver. Advantage: by using the
synth driver the tests cannot only check when the xattr FID limit
kicks in (server would return an Rlerror response with ENOSPC),
but can also validate the current 9p server internal xattr FID
counter at any moment.

This is a slow test (may take several seconds) and therefore
registered as "slow" test and not running by default.

Use -m slow to run this test.

Link: https://lore.kernel.org/qemu-devel/540c51faa074d9dd736bbf2170084a12288e23ef.1781361555.git.qemu_oss@crudebyte.com
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit 0e1085819e)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-30 09:40:16 +03:00
Christian Schoenebeck d94e27ac4d tests/9p: add virtio_9p_add_synth_driver_args() test client function
Add virtio_9p_add_synth_driver_args() to allow appending custom
QEMU options for individual 9p synth tests.

Link: https://lore.kernel.org/qemu-devel/7fe3eca5d17292464676b68d0513052564cd432a.1781361555.git.qemu_oss@crudebyte.com
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit 84525ece68)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-30 09:40:16 +03:00
Christian Schoenebeck 92375047a3 tests/9p: increase P9_MAX_SIZE for test client
Increase the maximum 9P message size ('msize') of 9p test client from
4k to 32k to support larger messages.

This is needed for the xattr tests being added with the subsequent
patches which are going to transmit xattrs of size 8k. It would have
also been possible to send them in multiple chunks, however let's not
overcomplicate things.

This new msize is still reasonable small compared to common msize
values on production systems.

Link: https://lore.kernel.org/qemu-devel/2dcb1243c80ea97d085af5171785850cf012be36.1781361555.git.qemu_oss@crudebyte.com
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit df88255543)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-30 09:40:16 +03:00
Christian Schoenebeck 2842b9eeb5 hw/9pfs: add xattr count query interface to fs synth driver
Add a synthetic "/stat/xattr_count" file path that, if being read
by 9p client, returns the 9p server internal xattr FID counter to
client.

This allows to test and verify that the xattr FID limit is being
enforced correctly.

Link: https://lore.kernel.org/qemu-devel/357c20fc244c04dcbd36b13aa20a5c9b2034e9f0.1781361555.git.qemu_oss@crudebyte.com
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit 7e42d569a6)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-30 09:40:16 +03:00
Christian Schoenebeck d7370cf880 hw/9pfs: enable xattr (mockup) support for synth fs driver
The synth backend is used for testing only. Enable xattr operations
by making lsetxattr and lremovexattr callbacks to return success
result.

They are still actually not doing anything, they just pretend to be
working to prevent 9pfs server from erroring out on xattr requests.

This allows the subsequent test case patches to verify xattr FID
limit enforcement.

Link: https://lore.kernel.org/qemu-devel/9c1c7128135f3bd9c2f62a3f64bb730b6a94ec7a.1781361555.git.qemu_oss@crudebyte.com
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit 0e3085ddc7)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-30 09:40:16 +03:00
Christian Schoenebeck cd5a727509 tests/9p: add Txattrcreate / Rxattrcreate test client functions
Add v9fs_txattrcreate() and v9fs_rxattrcreate() functions to the
9P test client for testing creation of xattrs with 9pfs server.

Link: https://lore.kernel.org/qemu-devel/5dbc5061dab1f7829fffc40bf89d7ff443e4bcab.1781361555.git.qemu_oss@crudebyte.com
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit 7664feb26f)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-30 09:40:16 +03:00
Christian Schoenebeck 7fd23f05c2 tests/9p: add Tclunk / Rclunk test client functions
Add v9fs_tclunk() and v9fs_rclunk() functions to the 9P test client
for closing file handles (or "FIDs") in test cases.

Link: https://lore.kernel.org/qemu-devel/d53f0337eb7f8525a14e394599d809ecf6805e5e.1781361555.git.qemu_oss@crudebyte.com
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit c46150530b)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-30 09:40:16 +03:00
Christian Schoenebeck f443a27e86 tests/9p: add Tread / Rread test client functions
Add v9fs_tread() and v9fs_rread() functions to the 9P test client
for reading files from 9pfs server in test cases.

Link: https://lore.kernel.org/qemu-devel/049bdd1e66416f5200fb3d59d2da5e8ec149926d.1781361555.git.qemu_oss@crudebyte.com
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit 54b8f64c42)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-30 09:40:16 +03:00
Christian Schoenebeck 5b33debb83 qemu-options: document 9pfs max_xattr option
Add documentation for the new "max_xattr" command line option
of 9pfs server, introduced by the previous commit.

Link: https://lore.kernel.org/qemu-devel/b5a1a6ba299a49183d0032d9e4cd5e009d4aae47.1781361555.git.qemu_oss@crudebyte.com
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit 44cb540d2d)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-30 09:40:16 +03:00
Christian Schoenebeck c6ead5d4fa hw/9pfs: add max_xattr option
Previous patch introduced a limit of max. 1024 simultaneous xattr FIDs.

This patch introduces an option "max_attr" that allows to override this
limit, just for the case that some user might run into this limit for
some reason, even if unlikely; or for reducing the limit further down
(e.g. that default limit of 1024 would cap at max. 64 MiB host memory,
at least on Linux hosts where the limit per xattr is 64k).

This new "max_xattr" option can be specified with both -fsdev and
-virtfs command line options, with the "local" and the "synth" fs
drivers.

The previous limit of 1024 is preserved as the default value.

Link: https://lore.kernel.org/qemu-devel/b7631ac0d8dde0629bc7c4f2c4185d9f57b962b4.1781361555.git.qemu_oss@crudebyte.com
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit e6116a81f0)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-30 09:40:16 +03:00
Christian Schoenebeck 4f9e9601d0 hw/9pfs: add xattr FID limit to prevent memory exhaustion
Add a limit on the number of simultaneously open xattr FIDs to prevent
host memory exhaustion attacks. Each xattr FID contains a buffer for the
xattr value, and without a limit, a malicious priviliged guest with
direct communication access to 9p server could create a huge number of
xattr FIDs until host memory is eventually exhausted.

Fix this by:

 - add xattr_fid_limit to struct FsContext for the max. amount
 - add xattr_fid_count to struct FsContext for the current amount
 - init xattr_fid_limit with 1024
 - init xattr_fid_count with 0
 - add function xattr_fid_count_inc() to increment the count
 - add function xattr_fid_count_decr() to decrement the count
 - call xattr_fid_count_inc() in Txattrcreate handler
 - call xattr_fid_count_inc() in Txattrwalk handler
 - call xattr_fid_count_decr() when a xattr FID is freed

Additionally:

 - reset the xattr FID counter in virtfs_reset()

When the limit is reached then xattr_fid_count_inc() returns -ENOSPC and
the request handler is aborted on its error path without turning the
FID into an xattr type and without allocating memory for the xattr.

The default value of 1024 was chosen, as (sane usage of) xattr requests
in the 9p protocol are usually very short-lived, and even machines with
128 cores with very high xattr activity should have plenty of head room
without ever hitting this limit.

Fixes: 10b468bdc5 ("virtio-9p: Implement TXATTRCREATE")
Fixes: CVE-2026-8348
Reported-by: Feifan Qian <[email protected]>
Link: https://lore.kernel.org/qemu-devel/eb3787869745d47234fb662600187bf773e1ef8a.1781361555.git.qemu_oss@crudebyte.com
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit 693b296b17)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-30 09:40:16 +03:00
Christian Schoenebeck 169537e616 hw/9pfs: cap Treaddir allocation (CVE-2026-9238)
Constrain max_count in v9fs_readdir() to transport's current, real
response buffer size before calling v9fs_do_readdir() to prevent
excessive host memory allocation for specific, crafted, huge
directories (large amount of entries) by bad clients.

Client may send a Treaddir request with a large 'count' parameter, and
while the negotiated 'msize' provides some limit, it accounts for guest
being somewhat faithful on the negotiated 'msize' value throughout the
session.

A bad guest client could have negotiated a large 'msize' but provide a
small reply buffer for Treaddir request, causing QEMU to allocate host
memory proportional to 'msize' before discovering the reply cannot fit.

Possible consequence was a potential DoS by a priviliged guest, causing
a disconnection of guest communication due to transport device being
marked as "broken", however QEMU process would have continued to run with
potentially giant host memory allocation, which might have negative
impact on other services running on host.

Fixes: CVE-2026-9238
Fixes: 2149675b19 ("9pfs: add new function v9fs_co_readdir_many()")
Reported-by: Feifan Qian <[email protected]>
Reviewed-by: Stefano Stabellini <[email protected]>
Link: https://lore.kernel.org/qemu-devel/f81a387a2de4f2172fd5830c5654f49d78102254.1781287774.git.qemu_oss@crudebyte.com
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit 64c6c7e0df)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-30 09:40:16 +03:00
Christian Schoenebeck 8221af89af 9pfs/xen: implement response_buffer_size callback
Add and implement the response_buffer_size callback for the Xen
transport.

Returns the size of the response buffer from the rings in_sg, as limit
for 9p server while generating a response for supplied PDU.

We use a local iovec array variable in_sg[2] instead of ring->sg, as
ring->sg is only allocated by init_in_iov_from_pdu() and
init_out_iov_from_pdu() during request / response processing.
response_buffer_size() however may be called before those allocators,
which would dereference ring->sg as NULL pointer. The local array
avoids this.

Reviewed-by: Stefano Stabellini <[email protected]>
Link: https://lore.kernel.org/qemu-devel/3b139769eb1d3f9d91ee5281228e6467f9a08b99.1781287774.git.qemu_oss@crudebyte.com
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit 69c8f5e694)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-30 09:40:16 +03:00
Christian Schoenebeck 7e493da015 9pfs/virtio: implement response_buffer_size callback
Add and implement the response_buffer_size callback for the virtio
transport.

Returns the actual current virtio response buffer size for the supplied
PDU, which will be used as safety guard for limiting the response size
when generating a 9p response.

Link: https://lore.kernel.org/qemu-devel/5bbed2768f7a0da8fa2be183e75928c5d1ef691d.1781287774.git.qemu_oss@crudebyte.com
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit 12bcbdca8a)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-30 09:40:16 +03:00
Christian Schoenebeck 6505b0d95f hw/9pfs: add response_buffer_size transport callback
Add a new callback to the V9fsTransport interface that allows each transport
to provide the real size of its current response buffer.

This is needed for subsequent safety guards that will limit generated
responses appropriately before trying to allocate, generate, and send a
response to guest.

This is especially required for request handlers that need to allocate
dynamic and potentially large host memory for generating a response. These
safety guards are mandatory to counter bad clients that try to trick server
by supplying response buffers being smaller than the previously negotiated
msize value.

Link: https://lore.kernel.org/qemu-devel/703ed8ce4401c4550ef2cd99f30ab808665d6e85.1781287774.git.qemu_oss@crudebyte.com
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit 4b615eaa1b)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-30 09:40:16 +03:00
Christian Schoenebeck b5c5d5767f hw/9pfs: cap negotiated msize to transport limit
The 'msize' parameter negotiated during Tversion handshake can be
arbitrarily large as requested by the guest. So far 9p server accepted
any msize value suggested by guest, i.e. server did not cap it at all,
no matter how large, as in practice the upper limit of msize is a client
capability. But as subsequent's security patch shows, capping msize on
server side makes sense as additional safety-net.

Let's cap msize to transport's theoretical limit for msize, mainly to
prevent a bad client from triggering excessive host memory allocations
throughout the session.

We intentionally don't cap msize to transport's current, real response
buffer size, as the response buffer size may vary between individual
requests.

Link: https://lore.kernel.org/qemu-devel/2105e9a3578c6f751bb64af55c16dd953f393f20.1781287774.git.qemu_oss@crudebyte.com
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit bb5ab96e35)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-30 09:40:16 +03:00
Christian Schoenebeck 6e3f13e9cd 9pfs/xen: implement msize_limit callback
Add and implement the msize_limit callback for the Xen transport.

The limit is calculated using XEN_FLEX_RING_SIZE() based on the
negotiated ring_order. For the theoretical maximum ring_order of 9,
this results in a maximum 'msize' of 1048576 bytes (1 MiB).

The minimum limit of all rings is picked, because multiple rings
could theoretically have different ring_orders.

Reviewed-by: Stefano Stabellini <[email protected]>
Link: https://lore.kernel.org/qemu-devel/9471786bc47b93e822f6c6233a83f2b9f61e6c82.1781287774.git.qemu_oss@crudebyte.com
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit 815d1799c3)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-30 09:40:16 +03:00
Christian Schoenebeck 116cd8d035 9pfs/virtio: implement msize_limit callback
Add and implement the msize_limit callback for the virtio transport.

This new callback function provides the theoretical maximum 'msize'
value supported by this virtio transport.

The limit is calculated as (VIRTQUEUE_MAX_SIZE - 2) * 4096 bytes,
where 2 virtio descriptors are lost exactly for:

  - 1 descriptor for the original request (typically being small)

  - 1 descriptor as indirect table pointer (when used), which just
    contains a pointer to the separate sglist containing the
    response's actual payload data

And 4096 bytes are assumed as standard page size used by Linux 9p
client. This results in a maximum 'msize' of 4186112 bytes.

Theoretically Linux client could support a much larger size, e.g. by
using multiple consecutive pages per sg entry / descriptor. However
that's currently not the case and unlikely to change any time soon.
And due to recent security issues, let's handle this limit
conservatively until really necessary to be raised.

Link: https://lore.kernel.org/qemu-devel/4c34426bc906e19423e7e2389c419c2e972d9b9b.1781287774.git.qemu_oss@crudebyte.com
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit 4a1a2fa4d3)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-30 09:40:16 +03:00
Christian Schoenebeck ea8487ec43 hw/9pfs: add msize_limit transport callback
Add a new callback 'msize_limit' to the V9fsTransport structure.

This allows each transport implementation to provide its theoretical
maximum 'msize' value, which will be used to cap the negotiated
msize during Tversion handshake.

Link: https://lore.kernel.org/qemu-devel/7c4e53eb73c0580d7a321dbf3823ba5647652298.1781287774.git.qemu_oss@crudebyte.com
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit a1c0e5a737)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-30 09:40:16 +03:00
Greg Kurz 29070a13e7 9pfs: local : Introduce local_fid_fd() helper
Factor out duplicated code to a single helper. More users to come.

Signed-off-by: Greg Kurz <[email protected]>
Reviewed-by: Christian Schoenebeck <[email protected]>
Message-Id: <[email protected]>
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit 4f82ce8cd9)
(Mjt: pick this one up so subsequent commits are applied cleanly)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-30 09:40:02 +03:00
Greg Kurz c84ebaa6b2 9pfs: Don't use file descriptors in core code
v9fs_getattr() currently peeks into V9fsFidOpenState to know if a fid
has a valid file descriptor or directory stream. Even though the fields
are accessible, this is an implementation detail of the local backend
that should not be manipulated directly by the server code.

Abstract that with a new has_valid_file_handle() backend operation.

Signed-off-by: Greg Kurz <[email protected]>
Reviewed-by: Christian Schoenebeck <[email protected]>
Message-Id: <[email protected]>
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit f2bb367d2b)
(Mjt: pick this one up so subsequent commits are applied cleanly)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-30 09:39:09 +03:00
Christian Borntraeger b5c0ca965b s390x/kvm: clamp stsi 3.2.2 size
The stsi 3.2.2 page is being prepared by the kvm module and the size is
clamped by the kernel. As the memory is mapped in the guest, another
guest VCPU could race and overwrite the count and messing up the move
operation. For any out of bound count, fall back to the kernel buffer.

Cc: [email protected]
Signed-off-by: Christian Borntraeger <[email protected]>
Reviewed-by: Eric Farman <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Cornelia Huck <[email protected]>
(cherry picked from commit a57e4612b6)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-29 21:37:30 +03:00
Marc-André Lureau 6bbc297819 ui/gtk: fix bad widget realize on non-GFX VC
The GTK VirtualConsole is a union, it may be .gfx or .vte depending on
the type.

Fixes: 565f85a9c2 ("ui/gtk: force realization of drawing area")
Reviewed-by: Daniel P. Berrangé <[email protected]>
Reviewed-by: Akihiko Odaki <[email protected].i.u-tokyo.ac.jp>
Signed-off-by: Marc-André Lureau <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit 27f6d5ba9c)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-26 07:44:29 +03:00
Michael Tokarev e3ad0582fd Update version for 10.0.11 release
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-25 14:09:17 +03:00
Akshit Yadav a34cc9750b linux-user: Fix AT_PHDR when program headers are relocated into their own segment
When a binary is patched or relocated such that the program header table is
moved into a separate PT_LOAD segment (rather than sitting at the start of the
first loadable segment), QEMU's AT_PHDR auxv entry becomes incorrect. The
loader was computing AT_PHDR as load_addr + e_phoff, which assumes the headers
are mapped 1:1 from file offset 0. This breaks when the headers are elsewhere.

The Linux kernel instead locates the PT_LOAD segment that contains e_phoff,
then computes the in-memory address as p_vaddr + (e_phoff - p_offset). This
correctly handles relocated headers.

Fix by:
1. Add phdr_addr field to image_info to cache the resolved address.
2. Initialize to load_addr + e_phoff (fallback for headers outside any PT_LOAD).
3. In the PT_LOAD mapping loop, detect if the segment contains e_phoff and
   override with the segment-relative address.
4. Use info->phdr_addr for AT_PHDR instead of the incorrect formula.

Signed-off-by: Akshit Yadav <[email protected]>
Reviewed-by: Helge Deller <[email protected]>
(cherry picked from commit 156e536a7b)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-24 16:36:05 +03:00
Aditya Gupta d55463da56 hw/pci: Replace assert with bounds check and return
As reported in https://gitlab.com/qemu-project/qemu/-/work_items/3334,
callers of 'pci_host_config_{read,write}_common' can pass length as 8,
causing an assert failure

The original issue with pnv_phb3 triggering the assert was fixed in a
previous commit

Instead of asserting on invalid length, check if the length is valid
(<=4), otherwise return (with the failure error code in read)

Reported-by: Zexiang Zhang <[email protected]>
Signed-off-by: Aditya Gupta <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit c7209c5671)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-24 16:36:05 +03:00
Aditya Gupta d088b316c6 ppc/pnv_phb3: Error out on invalid config access
PHB in Power8 supports 8 byte registers, and hence the ops structure
allows accessing of 8 bytes in 'pnv_phb3_reg_ops'

Both 'pnv_phb3_reg_read' & 'pnv_phb3_reg_write' pass the arguments as is
to 'pnv_phb3_config_{read,write}', if offset is PHB_CONFIG_DATA.

This when called with size as 8, causes following assert failure in
'pci_host_config_read_common' & 'pci_host_config_write_common':

    assert(len <= 4);

Validate that size is <=4, before jumping to pci_host_config_{read,write}_common

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3334
Reported-by: Zexiang Zhang <[email protected]>
Fixes: 9ae1329ee2 ("ppc/pnv: Add models for POWER8 PHB3 PCIe Host bridge")
Signed-off-by: Aditya Gupta <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit 2181097812)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-24 16:36:05 +03:00
Matt Turner aec8aff4ef linux-user/xtensa: fix unlock of uninitialized frame pointer on sigreturn
If lock_user_struct fails, frame is uninitialized but the badframe
label unconditionally calls unlock_user_struct on it. Handle the
lock failure inline so badframe is only reached with a valid lock.

Signed-off-by: Matt Turner <[email protected]>
Cc: [email protected]
Reviewed-by: Helge Deller <[email protected]>
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit 54e08dbe8f)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-24 16:36:05 +03:00
Matt Turner 07e6aa22bf linux-user/xtensa: save/restore FP registers across signal delivery
Add support for saving and restoring f0-f15 across signal delivery.
The target_xtensa_xtregs_fp struct carries 32-bit f-regs for cores
with XTENSA_OPTION_FP_COPROCESSOR; target_xtensa_xtregs_dfp carries
64-bit f-regs for cores with XTENSA_OPTION_DFP_COPROCESSOR.

Lock the xtregs region via lock_user before reading on sigreturn,
since sc_xtregs is a user-space pointer that may lie outside the
locked sigframe.

Signed-off-by: Matt Turner <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit 6858e3a71c)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-24 16:36:05 +03:00
Matt Turner 2c11498d44 target/xtensa: add cpu_set_fcr/fsr helpers to sync fp_status
Factor FCR→fp_status and FSR→fp_status synchronisation out of the
wur_fpu{2k,}_fcr/wur_fpu_fsr helpers into cpu_set_fcr(), cpu_set_fsr(),
and cpu_get_fsr(). Signal delivery code needs to restore the FP rounding
mode and exception flags without duplicating the flag-mapping tables.

cpu_set_fcr() applies the union mask 0xfffff07f (superset of the
wur_fpu_fcr mask 0x0000007f and the wur_fpu2k_fcr mask 0xfffff07f) so
that FCR bits valid only on fpu2k configs are preserved while MBZ bits
7-11 are always cleared.

Signed-off-by: Matt Turner <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit 7e859bacea)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-24 16:36:05 +03:00
Ryan Zhang c5333ef57b ui/sdl2: Set GL ES profile before creating initial GL context
When the user selects GLES via '-display sdl,gl=es', we need to set
SDL_GL_CONTEXT_PROFILE_MASK to SDL_GL_CONTEXT_PROFILE_ES before
calling SDL_GL_CreateContext(). This ensures SDL_GL_LoadLibrary()
loads the correct GLES driver instead of the desktop OpenGL driver.

Fix the below issue: qemu-system-aarch64: /usr/src/debug/libepoxy
/1.5.10/src/dispatch_common.c:872: epoxy_get_proc_address: Assertion
`0 && "Couldn't find current GLX or EGL context.\n"' failed.

sdl2_gl_create_context() already sets the profile mask correctly for
ES mode, but the initial context created in sdl2_window_create() is
missing the same treatment.

Fixes:da3f7a3ab9ea0091955b58f8909dfcee01f4043e ("ui/sdl: try to instantiate the matching opengl renderer")

Signed-off-by: [email protected]
Reviewed-by: Marc-André Lureau <[email protected]>
Message-ID: <DU2PR04MB9018BB3650BA218438C01F2A83042@DU2PR04MB9018.eurprd04.prod.outlook.com>
(cherry picked from commit 490a3e1867)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-24 16:35:40 +03:00
Christian Schoenebeck 90d713b15b hw/9pfs: reject . and .. in Twstat rename
The other Trename and Trenameat handlers already reject "." and ".."
as new name on rename requests by returning -EISDIR in this case.

The legacy Twstat rename handler is missing this validation. While passing
"." or ".." does not trigger a crash as fixed by the previous patch (since
the fs backend driver's system calls handle these gracefully), it creates
a behavioral inconsistency, as it is semantically meaningless to rename a
file to a directory reference in the first place.

Fix this by rejecting "." and ".." in Twstat rename handler with -EISDIR
to match behavior of Trename and Trenameat handlers.

Fixes: 8cf89e007a ("virtio-9p: Add P9_TWSTAT support")
Link: https://lore.kernel.org/qemu-devel/662333331d371c6c343c8091161de8eaa121880e.1780072238.git.qemu_oss@crudebyte.com
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit 08750e31fc)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-19 08:47:15 +03:00
Christian Schoenebeck 02a1f7835e hw/9pfs: fix abort due to illegal name with Twstat rename
The legacy Twstat 9p request can be used to rename files and directories.
Unlike the other, more recent rename requests like Trename and Trenameat,
Twstat does not validate the submitted new name before passing it to
v9fs_complete_rename().

A priviliged guest user with direct communication access to 9p server
could pass a string containing '/' as new name, which causes an assertion
fault (DoS) in local_name_to_path().

Fix this by rejecting such strings by checking the client supplied new
name with name_is_illegal(), similar to how Trename and Trenameat handlers
do already.

Reported-by: Feifan Qian <[email protected]>
Fixes: 8cf89e007a ("virtio-9p: Add P9_TWSTAT support")
Link: https://lore.kernel.org/qemu-devel/ba09716828e82992f9d8cac7f00eee0bc1c43c61.1780072238.git.qemu_oss@crudebyte.com
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit 7f5445e7e4)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-19 08:47:15 +03:00
Mathias Krause b7e3ea6eb3 gdbstub: Update x86 control register bits
The control register bits haven't been updated in a few years, making
them lack behind features QEMU ganied in these years.

Update them to the current version of the SDM and sort the 32bit version
to be in line with all the other definitions (descending order).

This should remove confusion when debugging, for example, CET-enabled
guests:

- before the change:
  (gdb) info registers cr4
  cr4            0x8000f0            [ PGE MCE PAE PSE ]

- after the change:
  (gdb) info registers cr4
  cr4            0x8000f0            [ CET PGE MCE PAE PSE ]

Signed-off-by: Mathias Krause <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 88d39a2937)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-19 08:43:08 +03:00
Paolo Bonzini 5f0e74c93d target/i386: apply mod to immediate count of an RCL/RCR operation
RCR and RCL instructions with a count of 9 are the same as if the
count was 0, but they generated incorrect code because the can_be_zero
flag is false.  This causes 0 to underflow into -1 at
tcg_gen_subi_tl(count, count, 1).

Fix by absorbing the modulo computation into gen_shift_count(), now
renamed gen_shift_count_1(), so that it can handle both reductions.

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3452
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit e38d0afade)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-19 08:37:21 +03:00
Gerd Hoffmann 6e7d0ddfc2 hw/uefi: fix parse_hexstr
Make sure we actually have two input characters available before going
to parse two hex digits.  Fixes one byte buffer overflow of the output
buffer in case the input string has an odd number of characters.

Fixes: CVE-2026-48915
Fixes: 12058948ab ("hw/uefi: add var-service-json.c + qapi for NV vars.")
Reported-by: Feifan Qian <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: Gerd Hoffmann <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit d6601a7e1c)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-18 00:29:44 +03:00
Abhigyan Kumar e73255f1db target/riscv: mask vxrm csrw write to the low 2 bits
Citing the RISC-V specification:

    "The vector fixed-point rounding-mode register holds a two-bit
    read-write rounding-mode field in the least-significant bits
    (vxrm[1:0]). The upper bits, vxrm[XLEN-1:2], should be written as
    zeros."

QEMU wrote full value into env->vxrm causing read of upper bits too.
Used existing macros for bit-masking. Previous had a hard-coded value.

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3470
Signed-off-by: Abhigyan Kumar <[email protected]>
Reviewed-by: Alistair Francis <[email protected]>
Reviewed-by: Daniel Henrique Barboza <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit 9f550a0b63)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-17 10:19:26 +03:00
Daniel Henrique Barboza 21ca98189e disas/riscv.c: fix inst_length()
inst_length() can return 0 if 'inst' happens to not match any known
encoding (like [1]).  Returning 0 is not desirable, even for unknown
encodings, given that it will cause a loop in target_disas() later on.

The most recent version of the RISC-V unpriv spec ditched the
sophisticated instruction-length encoding.  We're now supporting only
16-bit and 32-bit length instructions, where:

"All the 32-bit instructions in the base ISA have their lowest two bits
set to 11.  The optional compressed 16-bit instruction-set extensions
have their lowest two bits equal to 00, 01, or 10."

So the code is now simpler, never returning 0, and in fact it's the same
thing we're already doing in insn_len() from target/riscv/internals.h.
Due to include shenarigans we can't use that function in disas/riscv.c,
but I believe we can cut ourselves some slack this time and not lose
sleep over a 1 line of duplicated logic.  We're documenting it though!

[1] https://gitlab.com/qemu-project/qemu/-/work_items/3479

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3479
Signed-off-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 758dce9c98)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-17 10:19:26 +03:00
Daniel Henrique Barboza 6464782893 target/riscv/cpu_helper.c: add PMA access fault
We're not doing anything special w.r.t PMA (Physical Memory Access)
related faults, handling them like regular faults that will eventually
turn to be regular page faults.

Turns out we can't do that.  Priv spec section "Virtual Address
Translation Process" mentions:

"If a store to the PTE at address a+va.vpn[i]×PTESIZE would violate a
PMA or PMP check, raise an access-fault exception corresponding to the
original access type."

This means that we should handle PMA violations with access faults, like
we're already doing with PMP.  One clear code path where we should throw
a PMA failure, exposed by [1], is the error return from
address_space_ld* call.

There's a separated issue with the error code being returned by them (it
always return DECODE_ERROR even with 'rejected' reads) that we're going
to work around it by assuming that we did a good job with the PTE
address sanitization beforehand, and interpret that the error here is
related to PMA.  This is of course not ideal but fixing this QEMU API is
out of scope for this work.

All this said, we'll set the new pmp_pma_violation flag when we have
either a PMP or a PMA fault, and everything else shall fall into place.

[1] https://gitlab.com/qemu-project/qemu/-/work_items/3502

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3502
Signed-off-by: Daniel Henrique Barboza <[email protected]>
Reviewed-by: Alistair Francis <[email protected]>
Reviewed-by: Chao Liu <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit 8e090ecfa9)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-17 10:19:26 +03:00
Daniel Henrique Barboza 4463191962 target/riscv/cpu_helper.c: fault with reserved PTE.PBMT val
We need to fault during any access done while PTE bits 62-61 are both
set, according to the RISC-V priv spec.

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3494
Signed-off-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 3e33da68f1)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-17 10:19:26 +03:00
Daniel Henrique Barboza 9ad7b15c49 target/riscv/insn_trans/trans_rvzicbo.c.inc: save opcode before helpers
All helpers from this file can trigger ILLEGAL_INSN exceptions via
check_zicbo_envcfg() directly, bypassing the usual exception code from
translate.c.   If we don't save the opcode before each helper,
riscv_raise_exception() is triggered and env->bins won't be unwind during
cpu_loop_exit_restore() (code path cpu_restore_state ->
cpu_restore_state_from_tb() -> restore_state_to_opc()).

And finally, in riscv_cpu_do_interrupt(), we will set (m)tval = 0 when we can,
instead, set it to the cbo opcode that generated the exception.

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3380
Signed-off-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 d6c5855c76)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-17 10:19:26 +03:00
Daniel Henrique Barboza 09e8e27750 disas/riscv.c: add 'cbo' insns to disassembler
We forgot to add 'cbo' insns to disas/riscv.c.  The result is that the
disassembler recognizes all of them as 'lq', an insn that happens to
share the same opcode space.

While we're at it reorder cbo_* entries in insn32.decode using opcode
order instead of insn name.

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3480
Signed-off-by: Daniel Henrique Barboza <[email protected]>
Reviewed-by: Chao Liu <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit 9273cda722)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-17 10:19:26 +03:00
Daniel Henrique Barboza e7efb2fa07 target/riscv/csr.c: fix mstatus.UXL reserved value
By the priv spec the value "3" is marked as 'Reserved' for mstatus.UXL.
Handle a mstatus.UXL = 3 write by writing the current 'xl' instead.

Fixes: https://gitlab.com/qemu-project/qemu/-/work_items/3367
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 ddfd33f196)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-17 10:19:26 +03:00
Daniel Henrique Barboza 7c9787408a target/riscv/csr.c: do not allow mstatus MPV/GVA writes
The priv spec states the following about mstatus.MPV:

"The MPV bit (Machine Previous Virtualization Mode) is written by the
implementation whenever a trap is taken into M-mode."

And, about mstatus.GVA:

"Field GVA (Guest Virtual Address) is written by the implementation
whenever a trap is taken into M-mode."

Both are written during riscv_cpu_do_interrupt().  They're not supposed
to be written by userspace.  As far as write_mstatus goes these fields
are read only.  The same applies for mstatush.MPV/mstatush.GVA.

Fixes: 03dd405dd5 ("target/riscv: Support MSTATUS.MPV/GVA only when RVH is enabled")
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 18645f1957)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-17 10:19:26 +03:00
Daniel Henrique Barboza 81073858e6 target/riscv/cpu_helper.c: allow LOAD_ADDR_MIS promotion to AMO fault
promote_load_fault() is missing the promotion of misaligned AMO load
addresses, i.e. RISCV_EXCP_LOAD_ADDR_MIS should be promoted to
RISCV_EXCP_STORE_AMO_ADDR_MIS when RISCV_UW2_ALWAYS_STORE_AMO (i.e.
always_storeamo is true).

All other load AMO faults are already being covered.

Cc: [email protected]
Fixes: 98f21c30f5 ("target/riscv: AMO operations always raise store/AMO fault")
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3503
Signed-off-by: Daniel Henrique Barboza <[email protected]>
Reviewed-by: Alistair Francis <[email protected]>
Reviewed-by: Chao Liu <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit d85a4ec06a)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-16 22:38:15 +03:00
Eugenio Pérez 6e676a01bb virtio: Allow to fill a whole virtqueue in order
As the while steps < max_steps is already one less than the vq size, the
right maximum max_steps variable is queue length, not the maximum
possible remainder of % vq->vring.num.

Fixes: b44135daa3 ("virtio: virtqueue_ordered_fill - VIRTIO_F_IN_ORDER support")
Signed-off-by: Eugenio Pérez <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit eceff0982f)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-16 19:27:23 +03:00
Stefano Garzarella 5aee2ee368 libvduse: fix buffer overflow in vduse_queue_read_indirect_desc()
vduse_queue_read_indirect_desc() copies an indirect descriptor table
into a buffer in chunks when the table crosses a memory region
boundary. The destination is a struct vring_desc pointer but is
advanced by a byte count, so each increment moves the pointer by
read_len elements instead of read_len bytes, writing beyond the
buffer.

Use a char pointer for the destination so that the arithmetic
advances correctly.

While at it, change the source from a struct vring_desc pointer
to a void pointer: when the table is split across regions,
iova_to_va() can return a pointer into the middle of a descriptor,
so casting it to a struct vring_desc pointer is wrong. The pointer is
only used as a memcpy() source, so a void pointer is fine.

Fixes: CVE-2026-6425
Fixes: a6caeee811 ("libvduse: Add VDUSE (vDPA Device in Userspace) library")
Cc: [email protected]
Reported-by: DARKNAVY <[email protected]>
Signed-off-by: Stefano Garzarella <[email protected]>
Reviewed-by: Daniel P. Berrangé <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit 9f1b6d013d)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-16 19:15:43 +03:00
Stefano Garzarella b55b909db6 libvhost-user: fix buffer overflow in virtqueue_read_indirect_desc()
virtqueue_read_indirect_desc() copies an indirect descriptor table
into a buffer in chunks when the table crosses a memory region
boundary. The destination is a struct vring_desc pointer but is
advanced by a byte count, so each increment moves the pointer by
read_len elements instead of read_len bytes, writing beyond the
buffer.

Use a char pointer for the destination so that the arithmetic
advances correctly.

While at it, change the source from a struct vring_desc pointer
to a void pointer: when the table is split across regions,
vu_gpa_to_va() can return a pointer into the middle of a descriptor,
so casting it to a struct vring_desc pointer is wrong. The pointer is
only used as a memcpy() source, so a void pointer is fine.

Fixes: CVE-2026-6425
Fixes: 293084a719 ("libvhost-user: Support across-memory-boundary access")
Cc: [email protected]
Reported-by: DARKNAVY <[email protected]>
Signed-off-by: Stefano Garzarella <[email protected]>
Reviewed-by: Daniel P. Berrangé <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit 85805ee887)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-16 19:15:20 +03:00
Costas Argyris 6d4d9b69de tests/qtest: Add amd-iommu command buffer head wrap test
Add a qtest for AMD IOMMU command buffer head pointer wraparound.
The test programs a command buffer, fills it with COMPLETION_WAIT commands,
advances the tail to consume all but the final entry, then wraps the tail
to zero to force the final command to advance CmdHeadPtr past the end of
the buffer. The guest-visible CmdHeadPtr register must then wrap back to zero.

This covers the case fixed by an earlier CmdHeadPtr wraparound patch.

The Linux kernel AMD IOMMU driver is not affected by this bug because it
uses COMPLETION_WAIT with a memory store doorbell to detect command progress.

Signed-off-by: Costas Argyris <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit 8a1c09cbd3)
(Mjt: context fixup in MAINTAINERS)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-16 17:47:15 +03:00
Alejandro Jimenez aa6fc45019 amd_iommu: Update command buffer head ptr in MMIO region after wraparound
When processing a command, amdvi_cmdbuf_run() increments cmdbuf_head and
writes it to the emulated MMIO register space before checking whether it
has reached the end of the command buffer.

If the incremented value reaches the end of the buffer and the tail pointer
is zero, the loop exits and the COMMAND_HEAD offset still contains an
unwrapped value. There are no errors in command processing since internal
cmdbuf_head state is always correctly updated, but the spec defines the
CmdHeadPtr field in MMIO Offset 2000h Command Buffer Head Pointer Register
as RW i.e. guest-visible, so it should be kept consistent.

Wrap cmdbuf_head before updating COMMAND_HEAD so the MMIO-visible register
always matches the internal command buffer head pointer position.

Cc: [email protected]
Signed-off-by: Alejandro Jimenez <[email protected]>
Reviewed-by: Sairaj Kodilkar <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit 3c98e446af)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-16 17:45:41 +03:00
Paolo Bonzini 57a8fe8c3d amd_iommu: restrict command buffer head/tail ranges to ring size
The AMD IOMMU command buffer is a ring buffer of cmdbuf_len (a power
of two) entries.  Each entry is 16 bytes and the head pointer cycles
through the set:

  [0, 16, 32, ..., (cmdbuf_len - 1) * AMDVI_COMMAND_SIZE]

The tail pointer is written by the guest through the COMMAND_TAIL MMIO
register (offset 0x2008); the while loop in amdvi_cmdbuf_run() only
terminates when head == tail.  If tail is set to a value higher than
cmdbuf_len * 16, head will cycle through all the elements of the ring
buffer indefinitely, without ever matching tail.  Fix this by further
masking tail (and head, for consistency) against the size of the
ring buffer.

Reported-by: Yunhe Wang <[email protected]>
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
Reviewed-by: Alejandro Jimenez <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Message-Id: <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
(cherry picked from commit 3097d54016)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-16 17:45:21 +03:00
Dominique Martinet b5c8e7d291 linux-user: add preadv2/preadv2
Some programs apparently use these, like the python test suite.

The flags argument (rwf_t) is an int, with values shared on all arches
and does not need translating.

This was tested manually with the following python script:
```
import os
fd = os.open('test', os.O_RDWR|os.O_CREAT)
os.pwritev(fd, [b'test', b'ok'], 0, os.RWF_HIPRI)
buf = [bytearray(3), bytearray(10)]
os.preadv(fd, buf, 0, os.RWF_HIPRI)
print(buf[0])
print(buf[1])
```

Signed-off-by: Dominique Martinet <[email protected]>
Reviewed-by: Helge Deller <[email protected]>
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit fb4c08147b)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-14 08:53:07 +03:00
Thomas Huth 16df89d95f system/rtc: Fix a possible year-2038 integer overflow problem
rtc_realtime_clock_offset is initialized with:

  rtc_realtime_clock_offset = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) / 1000;

And QEMU_CLOCK_REALTIME might be based on gettimeofday() in certain
cases (see get_clock_realtime() in include/qemu/timer.h). So this
counter will exceed 32 bits in the year 2038, thus we should not
store this value in a normal integer variable. Change it to a time_t
to fix the problem.
And while we're at it, also adjust the nearby rtc_host_datetime_offset
variable to be on the safe side in the related code.

Signed-off-by: Thomas Huth <[email protected]>
Reviewed-by: Daniel P. Berrangé <[email protected]>
Reviewed-by: Laurent Vivier <[email protected]>
Reviewed-by: Michael Tokarev <[email protected]>
Signed-off-by: Michael Tokarev <[email protected]>
(cherry picked from commit ae84c738e4)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-14 08:51:01 +03:00
Xinhui Yang f5e02d6a30 linux-user/strace: add fsmount series of syscalls
Following the addition of fsmount(2) series of syscalls in the syscall
handler, strace support is added, with a dedicated function to print the
parameters of fsconfig(2), which contains parameters that can be
interpreted as multiple types.

Snippet of the strace dump when running `mount -t tmpfs tmpfs /media`:

18 fsopen(tmpfs,1) = 3
18 read(3,0x407fcf1c,8191) = -1 errno=61 (No data available)
18 fsconfig(3,FSCONFIG_SET_STRING,"source","tmpfs",0) = 0
18 read(3,0x407fce3c,8191) = -1 errno=61 (No data available)
18 fsconfig(3,FSCONFIG_CMD_CREATE,NULL,NULL,0) = 0
18 read(3,0x407fce3c,8191) = -1 errno=61 (No data available)
18 fsmount(3,1,0) = 4
18 read(3,0x407fce3c,8191) = -1 errno=61 (No data available)
18 statx(4,"",AT_EMPTY_PATH|AT_STATX_SYNC_AS_STAT,0x1000,0x407fee98) = 0
18 move_mount(4,,-100,/media,4) = 0
18 read(3,0x407fcfcc,8191) = -1 errno=61 (No data available)
18 close(3) = 0
18 close(4) = 0

v2: Fixed build on RHEL9 due to missing syscalls (Helge)

Signed-off-by: Xinhui Yang <[email protected]>
Reviewed-by: Pierrick Bouvier <[email protected]>
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit 6e0aa9f6c7)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-12 00:28:23 +03:00
Xinhui Yang ec4c92057b linux-user: implement fsmount(2) series of syscalls
This series of syscalls replaces the old mount(2) syscall with a series
of syscalls that operates around a filesystem context. This series of
syscalls is available since Linux 5.2 and glibc 2.36+.

Their users include systemd since v259 and libmount from util-linux, and
possibly other widely used projects.

Preliminary checks are implemented to ensure the validity of the
interface.

v2: Add syscall wrappers in case the build machine does not
support the fsmount() syscalls. (added by Helge Deller)

Signed-off-by: Xinhui Yang <[email protected]>
Reviewed-by: Pierrick Bouvier <[email protected]>
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit 767c32fe69)
(Mjt: context fixup)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-12 00:28:15 +03:00
Richard Henderson 31710e350a fpu: Handle all rounding modes in partsN_uncanon_normal
Missed float_round_nearest_even_max when recomputing round.

CC: [email protected]
Fixes: 72330260cd ("softfloat: Add float_round_nearest_even_max")
Reported-by: Peter Maydell <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
Reviewed-by: Peter Maydell <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Message-id: [email protected]
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit a6a1f92d5a)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-11 23:28:19 +03:00
Munkhbaatar Enkhbaatar e5b0b727a5 hw/usb/hcd-ohci: Clean up USBPacket before freeing ISO TD packet
ohci_service_iso_td() allocates a USBPacket and frees it after synchronous
completion, but it does not call usb_packet_cleanup() first.

Call usb_packet_cleanup() before g_free() so resources owned by USBPacket
are released.

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3463

Signed-off-by: Munkhbaatar Enkhbaatar <[email protected]>
Reviewed-by: Peter Maydell <[email protected]>
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit 163f9a4e06)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-11 22:27:44 +03:00
Fabiano Rosas 4c0acec503 qed: Don't try to flush during incoming migration
It's not possible to access the image file while there is an incoming
migration in progress, the QEMU process doesn't hold any locks to the
storage at this point so nodes are inactive. Attempting to flush leads
to an assert at bdrv_co_write_req_prepare():

   assert(!(bs->open_flags & BDRV_O_INACTIVE))

The issue is reproducible by running iotest 181 on a host under cpu
load. The migration must coincide with the header already containing
the QED_F_NEED_CHECK flag.

The sequence of events is as follows, with the respective call stacks
referenced below:

During block device init, bdrv_qed_attach_aio_context() starts the
'need_check' timer. The timer will not fire during incoming migration
as it uses QEMU_CLOCK_VIRTUAL (to avoid this very issue, as the code
comment indicates).                                                   (0)

However, there's still bdrv_qed_drain_begin() which uses the fact that
the timer is live to decide whether to start the
qed_need_check_timer_entry() directly.                                (1)

The qed_need_check_timer_entry() eventually calls into
qed_write_header() -> bdrv_co_pwrite() leading to the assert.         (2)

Skip creating the 'need_check' timer whenever the image is inactive.

The stacks:

(0) == issues timer_mod ==
 #6  in qed_start_need_check_timer       at ../block/qed.c:340
 #7  in bdrv_qed_attach_aio_context      at ../block/qed.c:373
 #8  in bdrv_qed_do_open                 at ../block/qed.c:556
 #9  in bdrv_qed_open_entry              at ../block/qed.c:582
 #10 in coroutine_trampoline             at ../util/coroutine-ucontext.c:175
 #0  in qemu_coroutine_switch<+120>      at ../util/coroutine-ucontext.c:321
 #1  in qemu_aio_coroutine_enter<+356>   at ../util/qemu-coroutine.c:293
 #2  in aio_co_enter<+179>               at ../util/async.c:710
 #3  in aio_co_wake<+53>                 at ../util/async.c:695
 #4  in thread_pool_co_cb<+47>           at ../util/thread-pool.c:283
 #5  in thread_pool_completion_bh<+241>  at ../util/thread-pool.c:202
 #6  in aio_bh_call<+109>                at ../util/async.c:173
 #7  in aio_bh_poll<+299>                at ../util/async.c:220
 #8  in aio_poll<+690>                   at ../util/aio-posix.c:745
 #9  in bdrv_qed_open<+392>              at ../block/qed.c:607
 #10 in bdrv_open_driver<+327>           at ../block.c:1678
 #11 in bdrv_open_common<+1619>          at ../block.c:2008
 #12 in bdrv_open_inherit<+2556>         at ../block.c:4191
 #13 in bdrv_open<+118>                  at ../block.c:4286
 #14 in blk_new_open<+199>               at ../block/block-backend.c:458
 #15 in blockdev_init<+2011>             at ../blockdev.c:612
 #16 in drive_new<+3008>                 at ../blockdev.c:1008
 #17 in drive_init_func<+51>             at ../system/vl.c:662
 #18 in qemu_opts_foreach<+227>          at ../util/qemu-option.c:1148
 #19 in configure_blockdev<+350>         at ../system/vl.c:721
 #20 in qemu_create_early_backends<+343> at ../system/vl.c:2076
 #21 in qemu_init<+12483>                at ../system/vl.c:3778
 #22 in main<+46>                        at ../system/main.c:71

(1) == sees timer_pending ==
 #6  in bdrv_qed_drain_begin             at ../block/qed.c:391
 #7  in bdrv_do_drained_begin            at ../block/io.c:366
 #8  in bdrv_do_drained_begin_quiesce    at ../block/io.c:386
 #9  in bdrv_child_cb_drained_begin      at ../block.c:1207
 #10 in bdrv_parent_drained_begin_single at ../block/io.c:133
 #11 in bdrv_parent_drained_begin        at ../block/io.c:64
 #12 in bdrv_do_drained_begin            at ../block/io.c:364
 #13 in bdrv_drained_begin               at ../block/io.c:393
 #14 in blk_drain                        at ../block/block-backend.c:2101
 #15 in blk_unref                        at ../block/block-backend.c:544
 #16 in bdrv_open_inherit                at ../block.c:4197
 #17 in bdrv_open                        at ../block.c:4286
 #18 in blk_new_open                     at ../block/block-backend.c:458
 #19 in blockdev_init                    at ../blockdev.c:612
 #20 in drive_new                        at ../blockdev.c:1008
 #21 in drive_init_func                  at ../system/vl.c:662
 #22 in qemu_opts_foreach                at ../util/qemu-option.c:1148
 #23 in configure_blockdev               at ../system/vl.c:721
 #24 in qemu_create_early_backends       at ../system/vl.c:2076
 #25 in qemu_init                        at ../system/vl.c:3778
 #26 in main                             at ../system/main.c:71

(2) == crashes ==
 #5  in __assert_fail (assertion="!(bs->open_flags & BDRV_O_INACTIVE)", file="../block/io.c", line=1977
 #6  in bdrv_co_write_req_prepare  at ../block/io.c:1977
 #7  in bdrv_aligned_pwritev       at ../block/io.c:2099
 #8  in bdrv_co_pwritev_part       at ../block/io.c:2316
 #9  in bdrv_co_pwritev            at ../block/io.c:2233
 #10 in bdrv_co_pwrite             at ../include/block/block_int-io.h:77
 #11 in qed_write_header           at ../block/qed.c:128
 #12 in qed_need_check_timer       at ../block/qed.c:305
 #13 in qed_need_check_timer_entry at ../block/qed.c:319

Note that this issue is not exactly the same as what's been reported
in Gitlab, but given how easily this reproduces, I imagine it has to
be happening in that setup as well.

Link: https://gitlab.com/qemu-project/qemu/-/work_items/3515
Signed-off-by: Fabiano Rosas <[email protected]>
Message-ID: <[email protected]>
Reviewed-by: Stefan Hajnoczi <[email protected]>
Reviewed-by: Kevin Wolf <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit 7e573b660f)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-11 06:58:40 +03:00
Thomas Lamprecht ae4c0e5730 qcow2: Fix data loss on zero write with detect-zeroes=unmap
Commit b8bfb1478d ("qcow2: Fix corruption on discard during write with
COW") added a wait_for_dependencies() at the start of
qcow2_subcluster_zeroize(). That fixes the inconsistency it set out to
fix, but turns the lock-protected pre-check in the caller,
qcow2_co_pwrite_zeroes(), into a stale one: the wait yields s->lock,
so an in-flight allocating write whose QCowL2Meta is already on
s->cluster_allocs (but whose L2 entry is not yet linked) gets to link
its entry during the yield. When the zeroize wakes, the cluster is now
NORMAL, and with BDRV_REQ_MAY_UNMAP the free path in zero_in_l2_slice()
unmaps the just-written cluster, silently dropping the data write's
payload.

This is reachable with detect-zeroes=unmap (the default for VirtIO
disks with discard on in Proxmox VE), under which the block layer
auto-promotes all-zero buffers to BDRV_REQ_ZERO_WRITE |
BDRV_REQ_MAY_UNMAP. A memory-constrained Debian guest running 'apt
full-upgrade' on such a disk reproduces it as random SIGSEGVs:
swapped-out code pages come back as zero.

Wait for in-flight dependencies before the lock-protected check in
qcow2_co_pwrite_zeroes(). If a write linked its L2 entry during the
wait, the type check now fails and the block layer falls back to a
bounce-buffered zero write that only touches the requested subrange,
preserving the racing write's data. Promote wait_for_dependencies() to
qcow2_wait_for_dependencies() so qcow2.c can call it.

Fixes: b8bfb1478d ("qcow2: Fix corruption on discard during write with COW")
Fixes: 9c3d7bf39f ("qcow2: Fix corruption on discard during write with COW") in 10.0.x series
Cc: [email protected]
Tested-by: Fiona Ebner <[email protected]>
Reviewed-by: Fiona Ebner <[email protected]>
Signed-off-by: Thomas Lamprecht <[email protected]>
Message-ID: <[email protected]>
[kwolf: Reverted unnecessary change to 'nr' assignment]
Reviewed-by: Kevin Wolf <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit 1d47eb6898)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-11 06:50:26 +03:00
Kevin Wolf e60fa4a9f5 iotests/046: Test that discard/write_zeroes wait for dependencies
This is a regression test for the bug fixed in the previous commit where
discard and write_zeroes operations wouldn't consider their dependencies
in s->cluster_allocs. Without the fix, this results in a corrupted
image.

Signed-off-by: Kevin Wolf <[email protected]>
Message-ID: <[email protected]>
Reviewed-by: Denis V. Lunev <[email protected]>
Tested-by: Denis V. Lunev <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit 389f5bcc74)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-11 06:48:34 +03:00
Kevin Wolf 9c3d7bf39f qcow2: Fix corruption on discard during write with COW
Most code in qcow2 that accesses (and potentially modifies) L2 tables
does so while holding s->lock.

There is one exception, which is allocating writes. They hold the lock
initially while allocating clusters, but drop it for writing the guest
payload before taking the lock again for updating the L2 tables. This
allows concurrent requests that touch other parts of the image file to
continue in parallel and is an important performance optimisation.

However, this means that other requests that run while the lock is
dropped for writing guest data must synchronise with the list of
allocating requests in s->cluster_allocs and wait if they would overlap.
For writes, this is done in handle_dependencies(), but discard and write
zeros operations neglect to synchronise with s->cluster_allocs.

This means that discard can free a cluster whose L2 entry will already
be modified in qcow2_alloc_cluster_link_l2() by a previously started
write. In the case of a pre-allocated zero cluster that is in the
process of being overwritten, this means that discard can lead to a
situation where the cluster is still mapped (because the write will
restore the L2 entry just without the zero flag), but its refcount has
been decreased, resulting in a corrupted image.

Add the missing synchronisation to qcow2_cluster_discard() and
qcow2_subcluster_zeroize() to fix the problem.

Cc: [email protected]
Reported-by: Denis V. Lunev <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
Message-ID: <[email protected]>
Reviewed-by: Denis V. Lunev <[email protected]>
Tested-by: Denis V. Lunev <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit b8bfb1478d)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-11 06:48:34 +03:00
Kevin Wolf 827192607b qemu-io: Add 'aio_discard' command
Testing interactions between multiple requests that include discard
requests require that qemu-io can do the discard asynchronously, like it
already does for reads and writes. To this effect, add an 'aio_discard'
command.

Signed-off-by: Kevin Wolf <[email protected]>
Message-ID: <[email protected]>
Reviewed-by: Denis V. Lunev <[email protected]>
Tested-by: Denis V. Lunev <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit 7f8466e2ce)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-11 06:48:34 +03:00
Stefan Hajnoczi d2e7fd9fe2 virtio-blk: add missing VIRTIO_BLK_T_SCSI_CMD size check (CVE-2026-48914)
Check that the iovec containing struct virtio_scsi_inhdr is large enough
before storing an error value there.

Feifan Qian <[email protected]> pointed out that this can be used to
corrupt heap memory when the descriptor uses an MMIO address and a
length of 1, forcing QEMU to allocate a 1-byte heap bounce buffer.
virtio_stl_p() stores 4 bytes and therefore corrupts whatever is beyond
the bounce buffer.

Fixes: CVE-2026-48914
Fixes: f34e73cd69 ("virtio-blk: report non-zero status when failing SG_IO requests")
Reported-by: Feifan Qian <[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 aeea0c2804)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-11 06:38:44 +03:00
Fiona Ebner 01abfc1ae1 block/io: fallback to bounce buffer if BLKZEROOUT is not supported because of alignment
Commit 5634622bcb ("file-posix: allow BLKZEROOUT with -t writeback")
enables the BLKZEROOUT ioctl when using 'writeback' cache, regressing
certain 'qemu-img convert' invocations, because of a pre-existing
issue. Namely, the BLKZEROOUT ioctl might fail with errno EINVAL when
the request is shorter than the block size of the block device.
Fallback to the bounce buffer, similar to when the ioctl is not
supported at all, rather than treating such an error as fatal.

Resolves: https://gitlab.com/qemu-project/qemu/-/issues/3257
Resolves: https://bugzilla.proxmox.com/show_bug.cgi?id=7197
Cc: [email protected]
Signed-off-by: Fiona Ebner <[email protected]>
Message-ID: <[email protected]>
[Added TODO comment describing a larger fix that could be implemented in
the future.
--Stefan]
Signed-off-by: Stefan Hajnoczi <[email protected]>
(cherry picked from commit b4e28c304b)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-08 20:27:51 +03:00
Farhan Ali 34cbeb27ff s390x/pci: Fix interrupt forwarding disable for interpreted devices
Remove the FH_MASK_ENABLE check when disabling interrupt forwarding
during device reset. This check was broken for the default case in
the switch statement above, preventing proper cleanup of interrupt
forwarding.

The pbdev->aif check in s390_pci_kvm_aif_disable() already guards
against double-disabling of interrupt forwarding.

Cc: [email protected]
Reported-by: Niklas Schnelle <[email protected]>
Signed-off-by: Farhan Ali <[email protected]>
Reviewed-by: Matthew Rosato <[email protected]>
Tested-by: Omar Elghoul <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Cornelia Huck <[email protected]>
(cherry picked from commit 442f727b8b)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-07 07:25:43 +03:00
Alexandra Winter e9f0c22c6a target/s390x: Make container ids in SysIB_15x 1-based
The Container Id in a container-type TLE of SysIB_15x is defined as 8-bit
unsigned nonzero integer. Make stsi fc 15 emulation architecture compliant,
by starting the container ids at 1 for the lowest numbered container.

The qemu misbehaviour without this patch becomes obvious due to a recently
proposed kernel fix. Older linux kernels pass the container ids from stsi
fc15 unchanged to sysfs, i.e. starting at 1 on s390 hardware. This resulted
in off-by-one values when compared to the values from HMC. A Linux kernel
fix is being proposed to correct the sysfs topology ids by -1, so they
start at 0, e.g. when displayed by 'lscpu -ye'. In case a KVM guest with a
fixed kernel runs on a host with a qemu without this fix, this can result
in container ids erroneously being shown as 255.
Example (Fixed guest on unfixed qemu):
$ lscpu -ye
CPU NODE DRAWER BOOK SOCKET CORE L1d:L1i:L2 ONLINE CONFIGURED POLARIZATION ADDRESS
  0    0    255  255    255    0 0:0:0         yes yes        vert-medium  0
  1    0    255  255      0    1 1:1:1         yes yes        vert-medium  1
After this fix:
$ lscpu -ye
CPU NODE DRAWER BOOK SOCKET CORE L1d:L1i:L2 ONLINE CONFIGURED POLARIZATION ADDRESS
  0    0      0    0      0    0 0:0:0         yes yes        vert-medium  0
  1    0      0    0      1    1 1:1:1         yes yes        vert-medium  1

Fixes: f4f54b582f ("target/s390x/cpu topology: handle STSI(15) and build the SYSIB")
Signed-off-by: Alexandra Winter <[email protected]>
Acked-by: Hendrik Brueckner <[email protected]>
Acked-by: Christian Borntraeger <[email protected]>
Reviewed-by: Gautam Gala <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Cornelia Huck <[email protected]>
(cherry picked from commit 1f1ccb6f3c)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-07 07:23:12 +03:00
Denis V. Lunev 3c03b50076 tests/unit: add test-envlist covering setenv/unsetenv name matching
util/envlist had no test coverage. Add tests/unit/test-envlist
exercising the public envlist API and pinning down the prefix-match
hazard fixed in the previous commit:

  - envlist_unsetenv("FOO") must not remove an entry named "FOOBAR";
  - envlist_setenv("FOO=...") must not replace an existing "FOOBAR=..."
    entry placed earlier in the list (envlist_setenv() inserts at the
    head, so the first prefix match wins under the old strncmp rule).

Also cover the rest of the contract: head-insertion order observed
through envlist_to_environ(), replacement of an existing variable,
the count argument of envlist_to_environ(), and the documented EINVAL
paths (NULL inputs, setenv without '=', unsetenv with '=').

Signed-off-by: Denis V. Lunev <[email protected]>
Reviewed-by: Stefan Hajnoczi <[email protected]>
Message-id: [email protected]
Cc: Stefan Hajnoczi <[email protected]>
Cc: Markus Armbruster <[email protected]>
Cc: Paolo Bonzini <[email protected]>
Signed-off-by: Stefan Hajnoczi <[email protected]>
(cherry picked from commit 05221c600a)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-04 22:57:10 +03:00
Denis V. Lunev 69a43064dc util/envlist: fix prefix-match in envlist_unsetenv() name lookup
envlist_unsetenv() looked up the entry to remove with
strncmp(entry->ev_var, env, strlen(env)). The comparison length is
the requested name's length, so any stored entry whose name *starts*
with that name compares equal. envlist_setenv() inserts at the head
of the list, so the first hit wins: with FOO=... stored first and
FOOBAR=... stored afterward, envlist_unsetenv("FOO") iterates from
the head, matches FOOBAR=... on the prefix, and drops it instead of
FOO=...

linux-user and bsd-user reach this code via the -U command-line
switch, so the bug is reachable from a normal qemu-user invocation.

envlist_setenv() used the same strncmp pattern but with
envname_len = (eq_sign - env + 1), so the '=' byte sat inside the
compared window and acted as an implicit boundary. setenv was
therefore not buggy -- but the safety lived in the byte layout of
ev_var rather than in the entry, so a future edit could easily
drift the two sites apart again.

Store the name length on each entry at insertion time and compare
with explicit length equality plus memcmp via a small helper. Use
the helper at both lookup sites so the boundary becomes a
structural property of the entry: envlist_unsetenv() stops
prefix-matching, and envlist_setenv()'s self-search no longer
depends on the '=' byte serving as a sentinel.

Fixes: 04a6dfebb6 ("linux-user: Add generic env variable handling")
Signed-off-by: Denis V. Lunev <[email protected]>
Reviewed-by: Stefan Hajnoczi <[email protected]>
Message-id: [email protected]
Cc: Stefan Hajnoczi <[email protected]>
Cc: Markus Armbruster <[email protected]>
Cc: Paolo Bonzini <[email protected]>
Signed-off-by: Stefan Hajnoczi <[email protected]>
(cherry picked from commit c131ae56c1)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-04 22:56:55 +03:00
sin99xx e9cd45327e 9pfs: fix missing rename lock in v9fs_co_readdir_many (CVE-2026-48004)
v9fs_co_readdir_many() dispatches do_readdir_many() to a worker thread
that reads V9fsFidState's path.data without holding a rename lock.

A concurrent rename request, e.g. of its parent dir, causes the FID's
absolute path to be altered by freeing the old path string and
assigning a new one. This causes a heap-use-after-free race condition
while do_readdir_many() is still accessing the old object.

This allows a DoS by an unprivileged guest user.

Fix this by wrapping the worker thread dispatch block within a pair of
v9fs_path_read_lock() and v9fs_path_unlock() calls, like it's done at
other places.

Fixes: 2149675b19 ("9pfs: add new function v9fs_co_readdir_many()")
Fixes: CVE-2026-48004
Reported-by: sin99xx <[email protected]>
Signed-off-by: sin99xx <[email protected]>
[Christian Schoenebeck: add commit log message]
Link: https://lore.kernel.org/qemu-devel/[email protected]
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit 5a8da7e979)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-01 21:02:55 +03:00
Christian Schoenebeck 7e35875428 tests/9pfs: add deep absolute path test
Add fs_deep_absolute_path test that creates a deep directory
structure with an absolute path length exceeding 16-bit range
(i.e. >65536) to verify the previous buffer overflow fix.

This is a slow test (may take several seconds) and therefore
registered as "slow" test and not running by default.

Use -m slow to run this test.

Link: https://gitlab.com/qemu-project/qemu/-/issues/3358
Link: https://lore.kernel.org/qemu-devel/933552b2cfc2c442fac7f4e68c777dce20ee8d7e.1779126034.git.qemu_oss@crudebyte.com
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit 198627807a)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-01 21:02:55 +03:00
Christian Schoenebeck c56c4b8d1c tests/qtest/libqos: add qvirtqueue_reset_pool() for descriptor pool reset
Add a function to reset the virtqueue descriptor pool state without
reinitializing the device. This is useful for tests that issue a high
number of requests and are limited by the simplified virtio test
driver's descriptor tracking, which decrements num_free but never
increments it back.

The function is safe for synchronous test code where requests are
sent and completed before the next request is issued.

Acked-by: Fabiano Rosas <[email protected]>
Link: https://lore.kernel.org/qemu-devel/96cf23eea1204b34443218fe76bd4a5eaf9163e8.1779126034.git.qemu_oss@crudebyte.com
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit be33c56898)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-01 21:02:55 +03:00
Christian Schoenebeck a336841626 hw/9pfs: let callers of v9fs_path_sprintf() and v9fs_fix_path() handle errors
This patch mitigates issues with very large absolute paths.

- Add error handling to all v9fs_path_sprintf() calls in
  local_name_to_path()

- Update callers of v9fs_fix_path() to check return values.

- When path formatting fails, clunk the affected FIDs to prevent use of
  invalid paths.

- Use g_autofree for temporary variables to simplify code.

Even though paths are usually limited to PATH_MAX (typically 4k) on guest,
this limitation can be circumvented by using *at() functions on guest and
creating very deep directory structures. This was a problem for QEMU 9p
server, as it currently tracks the absolute path for each FID internally
that always requires assembly of a (potentially ver large) absolute path.

A true long-term fix would be getting rid of storing an absolute path for
each FID internally. However that would likely be a massive change with
uncertain implications.

This patch therefore just mitigates the problem by immediately clunking
(i.e. closing) all FIDs whose path exceed a limit that we could handle.
As this only accounts to very unusual large absolute paths not ever been
reported on (sane) production machines, this is currently considered an
acceptable mitigation that should only (counter)affect malicious attempts.

Fixes: 2f008a8c97 ("hw/9pfs: Use the correct signed type ...")
Reported-by: Wang Jihe <[email protected]>
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/3358
Link: https://lore.kernel.org/qemu-devel/1d11dcbfc95b811dcdb48c6d7f3894d0ebd073a2.1779126034.git.qemu_oss@crudebyte.com
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit 3802c0e755)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-01 21:02:55 +03:00
Christian Schoenebeck a71e1a8cd1 hw/9pfs: add error handling to v9fs_fix_path()
Update v9fs_fix_path() to return int and propagate errors from
v9fs_path_sprintf(). This allows callers to detect and handle
path formatting failures.

Link: https://lore.kernel.org/qemu-devel/a0592741a918b7cbe751980ec7ec0c03f505924c.1779126034.git.qemu_oss@crudebyte.com
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit 54dd352c59)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-01 21:02:55 +03:00
Christian Schoenebeck 658deac8cc hw/9pfs: change V9fsPath.size to size_t and v9fs_path_sprintf() return type
- Change V9fsPath.size from uint16_t to size_t to support paths larger
  than 65536 bytes.

- Change v9fs_path_sprintf() return type from void to int to allow error
  reporting.

Link: https://lore.kernel.org/qemu-devel/2d2348d94ff43fbe4cc0aea24fb312c5c15ee809.1779126034.git.qemu_oss@crudebyte.com
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit dbaf84e148)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-01 21:02:55 +03:00
Christian Schoenebeck 501d01317e hw/9pfs: add NULL check in v9fs_path_is_ancestor()
Add NULL check for s1->data and s2->data before using them in
string operations. This prevents potential crashes when dealing
with uninitialized paths.

This is just a defensive measure. We are currently never passing
NULL to this function.

Link: https://lore.kernel.org/qemu-devel/3348c4d683f061c23083bd45994d527be4fb7cbc.1779126034.git.qemu_oss@crudebyte.com
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit abb0cc02fb)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-01 21:02:55 +03:00
Sean Wei fbb903c605 hw/9pfs: move G_GNUC_PRINTF to header
v9fs_path_sprintf() is annotated with G_GNUC_PRINTF(2, 3) in
hw/9pfs/9p.c, but the prototype in hw/9pfs/9p.h is missing the
attribute, so callers that include only the header do not get format
checking.

Move the annotation to the header and delete the duplicate in the
source file. No behavior change.

Signed-off-by: Sean Wei <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Message-ID: <[email protected]>
[CS: fix code style (max. 80 chars per line)]
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit 44f51c1a3c)
(Mjt: pick this harmless one up so the next changes applies cleanly)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-01 21:02:26 +03:00
Matt Turner 1f51ab5eb9 linux-user/s390x: restore fpu_status rounding mode from FPC on sigreturn
QEMU keeps the s390x floating-point control register (FPC) in env->fpc.
The rounding mode bits [2:0] of FPC are reflected into the derived
env->fpu_status via set_float_rounding_mode(); every architectural
write to FPC goes through HELPER(sfpc) which keeps the two in sync.

restore_sigregs() restored FPC with a direct assignment:

    __get_user(env->fpc, &sc->fpregs.fpc);

This wrote env->fpc correctly but never updated env->fpu_status, so on
sigreturn the interrupted code resumed with whatever rounding mode the
signal handler last installed in fpu_status.

Factor the two-step "write fpc + sync fpu_status" logic out of
HELPER(sfpc) into cpu_s390x_load_fpc(), declare it in cpu.h, and call
it from restore_sigregs() in place of the direct assignment.

cpu_s390x_load_fpc() partially reuses the sanity check from
HELPER(sfpc): if the FPC value has an invalid rounding mode or reserved
bits set, it falls back to 0, matching the kernel's fpu_lfpc_safe()
behavior where a corrupt signal frame value causes a specification
exception and 0 is used instead.

HELPER(sfpc) now calls cpu_s390x_load_fpc() after its full
specification-exception check, including the FEAT_FLOATING_POINT_EXT
test that is not needed for the signal restore path.

Fixes: 2941e0fa05 ("linux-user/s390x: Save/restore fpc when handling a signal")
Cc: [email protected]
Signed-off-by: Matt Turner <[email protected]>
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit 2762cd51ee)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-01 20:27:32 +03:00
Matt Turner 4ccb8c1604 linux-user/sh4: restore FP rounding mode on sigreturn
The SH4 FPSCR rounding-mode (RM) and denormal (DN) bits are not held
only in env->fpscr: they are also reflected into the derived
env->fp_status via set_float_rounding_mode()/set_flush_to_zero(). The
guest keeps the two in sync by routing every write to FPSCR through
helper_ld_fpscr().

restore_sigcontext() wrote the saved value straight into env->fpscr and
never touched env->fp_status, so on sigreturn the interrupted code
resumed with whatever FP rounding mode and flush-to-zero setting the
signal handler last installed. (regs->flags = 0 forces the FR/SZ/PR TB
flags to be recomputed, but fp_status is runtime float state, not a TB
flag, so it was left stale.) This is the FP analogue of the T/M/Q bit
problem just fixed for the integer status register.

Factor the FPSCR -> fp_status synchronisation out of helper_ld_fpscr()
into cpu_load_fpscr() and use it from restore_sigcontext() so the
rounding mode round-trips correctly across signal delivery.

Fixes: c3b5bc8ab3 ("SH4: Signal handling for the user space emulator, by Magnus Damm.")
Cc: [email protected]
Reviewed-by: Yoshinori Sato <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Matt Turner <[email protected]>
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit a740f17ed0)
(Mjt: context fixup in target/sh4/cpu.h)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-01 20:26:11 +03:00
Matt Turner fb08827358 linux-user/sh4: preserve T/M/Q bits across signal delivery
QEMU keeps the SH4 T, M and Q status-register bits outside env->sr, in
the dedicated env->sr_t, env->sr_m and env->sr_q fields; cpu_read_sr()
folds them back into the architectural SR value and cpu_write_sr()
splits them back out.

setup_sigcontext() saved the bare env->sr (so the T/M/Q bits were always
zero in the signal frame) and restore_sigcontext() wrote the value
straight back into env->sr without updating sr_t/sr_m/sr_q. As a result
the T bit was never preserved across signal delivery: on sigreturn the
interrupted code resumed with whatever T value the signal handler last
left behind. Any conditional branch (or addc/subc/rotcl/div1, etc.)
immediately following the interrupted instruction could then take the
wrong path.

This is the cause of the long-standing intermittent failures of the
tests/tcg/multiarch/signals.c test on sh4, which was marked BROKEN. With
a SIGRTMIN timer firing every millisecond across many threads, the race
was hit a few percent of the time and corrupted the guest heap, surfacing
as a SIGSEGV in memset, a malloc assertion, or an rseq registration abort.

Traced on a deterministic rr recording: a cmp/hi set T=0, the timer
signal interrupted the very next instruction (a bf), the handler left
T=1, and the resumed bf took glibc calloc's MORECORE_CLEARS branch,
using the old top-chunk size as the clear length for a freshly split
small chunk and running memset off the end of the heap.

Fix setup_sigcontext()/restore_sigcontext() to use cpu_read_sr() and
cpu_write_sr() so the T, M and Q bits round-trip correctly, and drop the
BROKEN annotation on the sh4 signals test.

Fixes: c3b5bc8ab3 ("SH4: Signal handling for the user space emulator, by Magnus Damm.")
Cc: [email protected]
Reviewed-by: Yoshinori Sato <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Matt Turner <[email protected]>
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit 6bf4c0295c)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-01 20:24:56 +03:00
Matt Turner bbad51c546 linux-user/mips: save/restore FCSR across signal delivery
QEMU keeps the MIPS FPU control/status register (FCSR, fcr31) in
env->active_fpu.fcr31.  The rounding mode, flush-to-zero (FS), and
NaN-2008 mode bits in fcr31 are reflected into the derived
env->active_fpu.fp_status via set_float_rounding_mode() and friends;
every architectural write to FCSR goes through helper_ctc1() which
calls restore_fp_status() to keep the two in sync.

Both target_sigcontext variants (O32 and N32/N64) have an sc_fpc_csr
field that holds FCSR, but setup_sigcontext() never wrote it and
restore_sigcontext() never read it.  As a result:

  - The signal frame always delivered sc_fpc_csr == 0 to the handler,
    so sigaction(SA_SIGINFO) handlers that inspect the interrupted
    context see the wrong FCSR.

  - On sigreturn, active_fpu.fcr31 retained whatever value the signal
    handler last installed (if any), and active_fpu.fp_status was
    never resynced.  Interrupted code resumed with the wrong rounding
    mode, FS flag, and NaN-2008 semantics.

Fix setup_sigcontext() to save fcr31 into sc_fpc_csr.  Fix
restore_sigcontext() to read it back (masked to fcr31_rw_bitmask as
the kernel does) and call cpu_mips_restore_fp_status() to resync
fp_status from the restored fcr31.

Add cpu_mips_restore_fp_status() in target/mips/fpu.c (which already
defines ieee_rm and includes fpu_helper.h), and declare it in cpu.h.

Fixes: 084d0497a0 ("mips-linux-user: Save and restore fpu and dsp from sigcontext")
Cc: [email protected]
Signed-off-by: Matt Turner <[email protected]>
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit 84b920ccb5)
(Mjt: context fixup in target/mips/cpu.h)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-01 20:24:02 +03:00
Matt Turner 00335af674 linux-user/ppc: restore fp_status from FPSCR on sigreturn
restore_user_regs() restores the PPC FPSCR with a direct assignment:

    env->fpscr = (uint32_t) fpscr;

ppc_store_fpscr() exists precisely to write FPSCR and keep the derived
env->fp_status in sync: it calls fpscr_set_rounding_mode() to update
the softfloat rounding mode, and set_float_rebias_overflow/underflow()
to reflect the FP_OE/FP_UE enable bits.  The direct assignment bypasses
all of this.

On sigreturn, interrupted code resumes with whatever rounding mode and
overflow/underflow-rebias state the signal handler last installed in
fp_status, rather than the state that was saved at signal delivery.

Replace the direct assign with ppc_store_fpscr().  The FPSCR_MTFS_MASK
applied inside ppc_store_fpscr() only excludes the computed FP_FEX and
FP_VX bits, which it re-derives correctly from the exception and enable
bits in the restored value.

Fixes: bcd4933a23 ("linux-user: ppc signal handling")
Cc: [email protected]
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Matt Turner <[email protected]>
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit 3f50dd4666)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-01 20:22:14 +03: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
Peter Maydell 20589a3245 hw/net/rocker_of_dpa: Avoid unaligned accesses in _of_dpa_flow_match()
_of_dpa_flow_match() tries to do masked comparisons of OfDpaFlowkey
structs by casting pointers to them to uint64_t* and then doing the
memory accesses as 64-bit. This is undefined behaviour because the
pointers might not be 64-bit aligned, and the UB sanitizer spots this:

../../hw/net/rocker/rocker_of_dpa.c:321:20: runtime error: load of misaligned address 0x512000164044 for type 'uint64_t' (aka 'unsigned long'), which requires 8 byte alignment
0x512000164044: note: pointer points here
  02 00 00 00 00 00 ff ff  00 00 00 00 ff ff ff ff  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00
              ^

We do know that OfDpaFlowKey structs must be at least aligned enough
for uint32_t accesses, because that's the type of the first field.
Switch to using uint32_t accesses in the loop.

Because the "width" field is always set via the FLOW_KEY_WIDTH macro
and not exposed to the guest, we can adjust the macro to store the
number of uint32_t to be checked rather than needing to change the
loop boundary in the match function.

Cc: [email protected]
Signed-off-by: Peter Maydell <[email protected]>
Signed-off-by: Jason Wang <[email protected]>
(cherry picked from commit 71d027cfee)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-30 09:57:25 +03:00
Peter Maydell c878785913 hw/net/rocker_of_dpa: Check group ID pointers are not NULL
In of_dpa_cmd_add_l2_flood(), we use rocker_tlv_parse_nested()
to fill in a tlvs[] array. If the guest command is valid then
the entries should be pointers to TLV data items with group IDs.
However, if the guest gives us bogus data then rocker_tlv_parse_nested()
indicates this by leaving the tlvs[] entries NULL. In the other
places that use this function, we check for this before using
the value, but here we forgot, and the result is that QEMU can
crash:

#0  __memcpy_avx_unaligned_erms () at ../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:331
#1  0x00005555574f7137 in __asan_memcpy ()
#2  0x0000555558106792 in ldl_he_p (ptr=0x8) at /home/pm215/qemu/include/qemu/bswap.h:278
#3  0x0000555558106755 in ldl_le_p (ptr=0x8) at /home/pm215/qemu/include/qemu/bswap.h:311
#4  0x00005555580f85ed in rocker_tlv_get_le32 (tlv=0x0) at ../../hw/net/rocker/rocker_tlv.h:114
#5  0x000055555810a8ad in of_dpa_cmd_add_l2_flood (of_dpa=0x506000082e38, group=0x503000b4e440, group_tlvs=0x7fff68702c20)
    at ../../hw/net/rocker/rocker_of_dpa.c:2032
#6  0x0000555558108a74 in of_dpa_cmd_group_do (of_dpa=0x506000082e38, group_id=1073741824, group=0x503000b4e440, group_tlvs=0x7fff68702c20)
    at ../../hw/net/rocker/rocker_of_dpa.c:2115
#7  0x0000555558108730 in of_dpa_cmd_group_add (of_dpa=0x506000082e38, group_id=1073741824, group_tlvs=0x7fff68702c20)
    at ../../hw/net/rocker/rocker_of_dpa.c:2135
#8  0x00005555580f66ec in of_dpa_group_cmd
    (of_dpa=0x506000082e38, info=0x514000072e40, buf=0x5070002356c0 "\001", cmd=7, group_tlvs=0x7fff68702c20)
    at ../../hw/net/rocker/rocker_of_dpa.c:2194

Check for NULL values and return an error.

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/1851
Signed-off-by: Peter Maydell <[email protected]>
Signed-off-by: Jason Wang <[email protected]>
(cherry picked from commit 8526b7d6b6)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-30 09:57:25 +03:00
Peter Maydell c0a6758888 target/arm: Don't assert if 64-bit EL2 AT insn sees a Domain fault
The Domain fault type can only happen for 32-bit short-format
descriptors.  This means that it almost never needs to be encoded in
a long-format fault status code.  However, there is one corner case
where we do need to report it as a long-format FSC: if a 64-bit EL2
does an AT insn on an AArch32 EL1&0 translation regime that is using
short-descriptors and that translation operation hits a Domain fault,
then this is reported in the PAR_EL1 in long-format.

The PAR_EL1 register description defines that this should be reported
as 0b111101 for a level 1 Domain fault or 0b111110 for a level 2
Domain fault.

The Arm ARM pseudocode special cases this in the function
AArch64_PARFaultStatus() (because no other "fault to LFSC" code path
can be a Domain fault).  For QEMU, implement it in arm_fi_to_lfsc().

Cc: [email protected]
Fixes: 1fa498fe0d ("target/arm: Provide fault type enum and FSR conversion functions")
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3512
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Message-id: [email protected]
(cherry picked from commit bb95753047)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-30 09:57:25 +03:00
Peter Maydell fce3a467a6 target/arm: Set correct fp flags for FLOGB when FPCR.AH = 1
Our implementation of the FLOGB insn does the operations entirely
in the helper function, without needing to use fpu functions.
This means it needs to handle all the fp status flags itself.
We aren't setting float_flag_input_denormal_used when we
use (i.e. do not flush to zero) an input denormal, which means
that FPCR.IDC isn't set when it should be for FPCR.AH=1.
We missed this when we added float_flag_input_denormal_used
and made the fpu/ code set it.

Add the missing float_raise().

Cc: [email protected]
Fixes: d38a57a3f ("target/arm: Enable FEAT_AFP for '-cpu max'")
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Alex Bennée <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Message-id: [email protected]
(cherry picked from commit 23ece2805f)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-30 09:57:25 +03:00
Peter Maydell b3ae9008d0 target/arm: Use FPST_A64_F16 for SVE FCVTLT_hs
We should be using the F16-specific float_status for conversions from
half-precision, because halfprec inputs never set Input Denormal.  If
we use the FPST_A64 fpstatus then we will incorrectly set FPCR.IDC
for input-denormals when FPCR.AH=1.

In commit e07b48995a we updated most of the halfprec-to-other
conversion insns to use FPST_A64_F16 as part of implementing
FEAT_AHP.  However we missed the SVE FCVTLT instruction, which has a
halfprec-to-single encoding.

Correct the FPST we use for the hs variant of FCVTLT.

Cc: [email protected]
Fixes: e07b48995a ("target/arm: Use FPST_A64_F16 for halfprec-to-other conversions")a
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Alex Bennée <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Message-id: [email protected]
(cherry picked from commit aa42300f86)
(Mjt: context fixup across v10.2.0-1344-g895d4367d6
     "target/arm/tcg: Use "or SME" feature checks where needed")
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-30 09:57:25 +03:00
Peter Maydell 38930e8fe4 target/arm: SVE2 FMAXP, FMINP must honour AH=1
The behaviour of floating-point maximum and minimum insns has
some odd special cases when FPCR.AH=1. We get this right in most
places (for instance, the ASIMD FMAXP, FMINP) but forgot about
it for the SVE2 versions of FMAXP and FMINP.

Cc: [email protected]
Fixes: 384433e709 ("target/arm: Implement FPCR.AH semantics for FMINP and FMAXP")
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Alex Bennée <[email protected]>
Message-id: [email protected]
(cherry picked from commit 446050c4df)
(Mjt: fixup for lack of v10.2.0-1344-g895d4367d6
 "target/arm/tcg: Use "or SME" feature checks where needed")
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-30 09:57:25 +03:00
Denis V. Lunev 85692f4bd6 block/linux-aio: bound ioq_submit() recursion depth
qemu_laio_process_completions() wraps its body in defer_call_begin /
defer_call_end. Inside the section, completion callbacks wake coroutines
that queue new aiocbs; laio_do_submit() defers laio_deferred_fn. At the
bottom of qemu_laio_process_completions() the defer_call_end() fires
laio_deferred_fn, which calls ioq_submit(), closing the cycle:

  ioq_submit
    -> io_submit(2)                           // some sync completions
    -> qemu_laio_process_completions          // defer_call_begin
         -> aio_co_wake                       // resumes coroutine
              -> laio_do_submit
                   -> defer_call(laio_deferred_fn, s)   // enqueued
         -> defer_call_end                    // nesting drops to 0
              -> laio_deferred_fn
                   -> ioq_submit              // +1 stack frame, loop

When io_submit(2) returns asynchronously (O_DIRECT) the cycle
terminates in one extra frame: the fresh aiocb is still in flight, no
completion is drained, no coroutine wakes, no new submission queues.
When submissions complete synchronously (non-O_DIRECT, or per-descriptor
drivers such as vmdk) each level enqueues more work for the next
defer_call_end() to drain, so recursion grows without bound and QEMU
crashes with SIGSEGV on the thread guard page.

The cycle was closed by two performance commits, each correct in
isolation:

  076682885d ("block/linux-aio: convert to blk_io_plug_call() API")
    -- introduced laio_deferred_fn and wired
       laio_do_submit -> defer_call(laio_deferred_fn, s).

  84d61e5f36 ("virtio: use defer_call() in virtio_irqfd_notify()")
    -- added defer_call_begin/end around qemu_laio_process_completions
       so virtio-irqfd notifications batch across a completion pass.

The supported aio=native + cache=none pairing keeps submissions
asynchronous, so the cycle stays bounded; nothing in the code enforces
that contract. Observed in production as a SIGSEGV during a backup job
configured with --cached + aio=native; reproducible on upstream with
qemu-io against vmdk.

Cap ioq_submit() recursion with a counter on LaioQueue, which is only
accessed from the AioContext home thread. On overflow, return without
submitting. The pending work is drained by s->completion_bh, which
qemu_laio_process_completions() has already scheduled on entry -- no
work is lost; one event-loop round-trip of latency is paid only when
the bound is hit, which cannot happen on a supported configuration.

Signed-off-by: Denis V. Lunev <[email protected]>
CC: Kevin Wolf <[email protected]>
CC: Hanna Reitz <[email protected]>
CC: Stefan Hajnoczi <[email protected]>
CC: Paolo Bonzini <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Stefan Hajnoczi <[email protected]>
(cherry picked from commit 6864bec553)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-30 09:57:25 +03:00
Jinjie Ruan f35327446b mc146818rtc: Fix get_guest_rtc_ns() overflow bug
In get_guest_rtc_ns(), "s->base_rtc" is uint64_t, which multiplied by
"NANOSECONDS_PER_SECOND" may overflow the uint64_t type, which will
cause the QEMU Linux Virtual Machine's RTC time to jump and in turn
triggers a kernel Soft Lockup and ultimately leads to a crash.

Fix it by avoiding adding s->base_rtc in get_guest_rtc_ns_offset(),
because get_guest_rtc_ns() is used either take the remainder of
NANOSECONDS_PER_SECOND or take the quotient of NANOSECONDS_PER_SECOND.

Fixes: 56038ef623 ("RTC: Update the RTC clock only when reading it")
Signed-off-by: Jinjie Ruan <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 4b6c088c88)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-30 09:57:25 +03:00
Paolo Bonzini 0fc3b3aa63 apic: fix delivery bitmask with modified xAPIC ids
Self-IPIs (or all-but-self IPIs) in QEMU can cause a out-of-bounds access
to deliver_bitmask, because the access uses the APIC ID register which
is writable by the guest.  However, foreach_apic uses the delivery
bitmask indexes to look up the local_apics[] array, which is indexed
by *initial* APIC id.  Using the right id fixes both a possible heap
write overflow if the modified APIC id is too large for max_apic_words,
and a mis-delivery of both self and all-but-self IPIs.

Reported-by: Wei Che Kao <[email protected]>
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 153dc2fa7b)
(Mjt: fixup for 10.0.x)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-30 09:57:25 +03:00
Paolo Bonzini efe581a63f lsi53c895a: clear tag byte when processing messages
Instead of simply ORing the message byte, clear what
was there before.

Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 4494dec8c2)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-30 09:57:25 +03:00
Paolo Bonzini 765c528ef0 lsi53c895a: fix use-after-free of cancelled request
When processing the Message Out phase, the lsi53c895a controller
can cancel a request and the continue by processing more messages.
When this happens, it is important that a cancelled request is not
processed further, because scsi_req_cancel can cause the request
to be freed.

Right now this is happening in two cases, but not when cancelling
the entire queue of requests after an ABORT, CLEAR QUEUE or
BUS DEVICE RESET message.  In that case, a subsequent ABORT TAG
message can use a dangling current_req.

There are three possible fixes:

- add a missing check inside the loop, clearing current_req
  if p->req == current_req.  This is obvious but complicates the
  code inside the foreach loop.

- change the conditional prior to the loop from "if (s->current)"
  to "if (current_req)".  This would work, because s->current != NULL
  implies current_req != NULL, and would clear current_req correctly.
  However it is less obvious because the point of the code
  is to clear the entire queue, which consists of s->current
  and s->queue; current_req is not special here.

- delay the retrieval of current_req until an ABORT TAG message
  is seen.  This is the most correct option, because the SCSI
  protocol only deals with tags; requests are a QEMU concept
  that only makes sense for the purpose of calling into the
  SCSI layer.

Reported-by: Wei Che Kao <[email protected]>
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 5297a0fc65)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-30 09:57:25 +03:00
Heechan Kang 527a3e84d6 ui: fix validation of VNC extended clipboard data length
QEMU's VNC extended clipboard handler inflates a client-controlled
compressed clipboard payload. The code checks the declared text size
against the total inflated buffer size:

    if (tsize < size)

but then copies from:

    tbuf = buf + 4;
    qemu_clipboard_set_data(..., tsize, tbuf, true);

The correct bound is the remaining data length after the 4-byte length
field, not the total inflated buffer length.

As a result, a VNC client can make QEMU copy up to 3 bytes past the end
of the inflated heap buffer. With a second VNC client, those copied
bytes are observable through the normal VNC extended clipboard PROVIDE
path.

Fixes: CVE-2026-8343
Reported-by: Heechan Kang <[email protected]>
Reported-by: Feifan Qian <[email protected]>
Reviewed-by: Daniel P. Berrangé <[email protected]>
Signed-off-by: Heechan Kang <[email protected]>
[DB: added #include and 'return' statements]
Signed-off-by: Daniel P. Berrangé <[email protected]>
Reviewed-by: Marc-André Lureau <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit e56b4bbff1)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-30 09:57:25 +03:00
Daniel P. Berrangé f0a2a6e87f ui/vnc: fix OOB read updating VNC update frequency stats
Incorrect loop bounds in vnc_update_freq result in iterating past the
last row and past the last column in the VNC stats array. With suitably
chosen dimensions this could be a OOB read that accesses memory beyond
the VncDisplay struct that the stats array is embedded in.

Should this hit a guard page, it could trigger a guest crash. If it
does not, then the VNC frequency stats will be updated with garbage.

Fixes: CVE-2026-48003
Reported-by: boy juju <[email protected]>
Reviewed-by: Marc-André Lureau <[email protected]>
Signed-off-by: Daniel P. Berrangé <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit d0c7b82d3a)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-30 09:57:25 +03:00
Daniel P. Berrangé fa7c684371 ui/vnc: fix OOB write in lossy rect worker code
Incorrect calculation of the boundary condition when tracking lossy
rectangles in the worker thread will result in an OOB write which
can corrupt further worker state, and/or trigger any guard pages
that may lie beyond the VncWorker struct. This can be triggered
through careful choice of the display resolution in the guest
OS by an unprivileged user.

Fixes: CVE-2026-48002
Reported-by: Marc-André Lureau <[email protected]>
Signed-off-by: Daniel P. Berrangé <[email protected]>
Message-ID: <[email protected]>
[Marc-André - added assert() suggest by [email protected]]
Signed-off-by: Marc-André Lureau <[email protected]>
(cherry picked from commit 46ee49034d)
(Mjt: context fixup for 10.0.x)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-30 09:57:25 +03:00
Daniel P. Berrangé 21782c170d ui/vnc: fix OOB write in VNC stats array
The VncSurface struct maintains update statistics in an array:

    VncRectStat stats[VNC_STAT_ROWS][VNC_STAT_COLS];

where the dimensions are defined as:

  #define VNC_STAT_RECT  64
  #define VNC_STAT_COLS (VNC_MAX_WIDTH / VNC_STAT_RECT)
  #define VNC_STAT_ROWS (VNC_MAX_HEIGHT / VNC_STAT_RECT)

If VNC_MAX_WIDTH / VNC_MAX_HEIGHT are not an exact multiple of
VNC_STAT_REC, the COLS/ROWS will be undersized by 1.

Unfortunately:

  #define VNC_MAX_HEIGHT 2160

is not a multiple of 64, so there is potential for OOB reads and
writes in the 'stats' array, if the guest surface is over 2112
pixels in height. An array overflow occurs when vnc_update_stats()
records new statistics, either scribbling over data later in the
VncDisplay struct that 'stats' is embedded in, or performing an
OOB write on the allocated struct memory.

Fixes: CVE-2026-48002
Reported-by: boy juju <[email protected]>
Reviewed-by: Marc-André Lureau <[email protected]>
Signed-off-by: Daniel P. Berrangé <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit c3c6226fa4)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-30 09:57:25 +03:00
Daniel P. Berrangé 3e8558b0cb ui/vnc: fix OOB read access in VNC SASL mechname array
When reading the SASL mechname array off the VNC connection, if
malicious, the received data may contain embedded NULs. If this
happens the memory buffer returned by g_strndup may be shorter
than the original data. Unfortunately the code continued to
index into this buffer with an offset equal to the original
length. This is a potential OOB read of the array.

Fixes: 5847d9e1 (ui/vnc: simplify and avoid strncpy)
Reported-by: boy juju <[email protected]>
Reviewed-by: Marc-André Lureau <[email protected]>
Signed-off-by: Daniel P. Berrangé <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit ae18df638f)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-30 09:57:25 +03: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
Zishun Yi 215f525e0b target/riscv: clear mseccfg on reset for all dependent extensions
Currently, the `mseccfg` CSR is only cleared to 0 during reset if the
`ext_smepmp` is enabled. However, this register is now shared by
several other extensions such as `zkr`, `smmpm`, and `zicfilp`.

Fix by clearing `mseccfg` if any dependent extension is present, and
adjusting the relevant comments.

This vulnerability was discovered and reported by SpecHunter, an
AI-driven architecture specification analysis tool.

Link: https://github.com/yizishun/rv-isa-sec/blob/master/output/riscv-svvptc/pr-134/qemu.txt
Signed-off-by: Zishun Yi <[email protected]>
Reviewed-by: Daniel Henrique Barboza <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit 8158a74f0a)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-26 17:15:31 +03:00
Alistair Francis 9c63647c8d target/riscv: Update the local interrupt mask
The RISC-V spec describes bits 0-15 as standard fixed interrupts. The
AIA spec on the other hand describes bits 0-12 as standard fixed
interrupts. This conflict causes issues for us as we don't dynamically
determine if AIA is enabled when setting the *delegable_ints consts.

This means currently we incorrectly treat the LCOFIP bit as delegable,
even if AIA is disabled, which is incorrect (see the issues mentioned
below).

The AIA spec indicates that implementations can determine which bits of
13-63 in mvien are writable, so let's just make it bits 15-63 to match
the main spec.

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3133
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3134
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3135
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3138
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3140
Signed-off-by: Alistair Francis <[email protected]>
Reviewed-by: Daniel Henrique Barboza <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit 27f9566dcd)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-26 17:15:31 +03:00
Zishun Yi 8cff79c690 target/riscv: Add mseccfg to VMStateDescription
Currently, the Machine Security Configuration Register (mseccfg) was
missing from the live migration state. This omission causes the register
to be reset to zero on the destination host after migration.

Fixed by adding vmstate_mseccfg subsection

This vulnerability was discovered and reported by SpecHunter, an
AI-driven architecture specification analysis tool.

Link: https://github.com/yizishun/rv-isa-sec/blob/a22e4459cd026ae970791dfbd9cfe5d110fbd46b/output/riscv-isa-manual/pr-1879/qemu.txt#L121
Signed-off-by: Zishun Yi <[email protected]>
Reviewed-by: Alistair Francis <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit eccb1d6940)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-26 17:15:31 +03:00
TANG Tiancheng 94fb9c29f2 target/riscv: Save stimer and vstimer in CPU vmstate
vmstate_riscv_cpu was missing env.stimer and env.vstimer.
Without migrating these QEMUTimer fields, active S/VS-mode
timer events are lost after snapshot or migration.

Add VMSTATE_TIMER_PTR() entries to save and restore them.

Reviewed-by: LIU Zhiwei <[email protected]>
Reviewed-by: Daniel Henrique Barboza <[email protected]>
Signed-off-by: TANG Tiancheng <[email protected]>
Reviewed-by: Alistair Francis <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit b0daaa172a)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-26 17:15:31 +03:00
Zishun Yi 2e8601ac14 target/riscv/pmp: Fix integer overflow in TOR and NA4 address computation
According to the RISC-V Privileged Manual: "The Sv32 page-based
virtual-memory scheme described in sv32 supports 34-bit physical
addresses for RV32, so the PMP scheme must support addresses wider than
XLEN for RV32."

However, the current QEMU implementation uses `target_ulong` (which
resolves to `uint32_t` on RV32) for PMP address variables.  When
shifting these addresses left (e.g., `this_addr << 2`), an integer
overflow occurs, truncating the high bits of the 34-bit physical
address.

Fix this issue by changing the types of PMP address variables
(`this_addr` and `prev_addr`) to `hwaddr`.

This issue was discovered and reported by SpecHunter, an AI-driven
architecture specification analysis tool.

Link: https://github.com/yizishun/rv-isa-sec/blob/master/output/riscv-isa-manual/pr-2472/qemu.txt
Signed-off-by: Zishun Yi <[email protected]>
Reviewed-by: Alistair Francis <[email protected]>
Reviewed-by: Daniel Henrique Barboza <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit 612f22c19d)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-26 17:15:31 +03:00
Abhigyan Kumar 6622e096de target/riscv: Fix medeleg[11] read-only zero bit for M-mode ECALL
RISC-V Privileged Specification 3.1.8 (Machine Trap Delegation Registers
(medeleg and mideleg)) mentions:

"For exceptions that cannot occur in less privileged modes, the
corresponding medeleg bits should be read-only zero. In particular,
medeleg[11] is read-only zero."

QEMU incorrectly included RISCV_EXCP_M_ECALL in DELEGABLE_EXCPS. It
allowed the 11th bit to be written and read as set. Fixed by removing it
from the DELEGABLE_EXCPS mask, adhering to the specification.

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3438
Signed-off-by: Abhigyan Kumar <[email protected]>
Reviewed-by: Alistair Francis <[email protected]>
Message-ID: <[email protected]>
[ Changes by AF:
 - Remove comment
]
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit a0946caf1d)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-26 17:15:31 +03:00
Frank Chang b36f00f785 hw/char: sifive_uart: Implement txctrl.txen and rxctrl.rxen
Implement txctrl.txen and rxctrl.rxen as follows:

* txctrl.txen
  The txen bit controls whether the Tx channel is active. When cleared,
  transmission of Tx FIFO contents is suppressed, and the txd pin is
  driven high.

* rxctrl.rxen:
  The rxen bit controls whether the Rx channel is active. When cleared,
  the state of the rxd pin is ignored, and no characters will be
  enqueued into the Rx FIFO.

Therefore, the Tx FIFO should not be dequeued when txctrl.txen is
cleared, and the Rx FIFO should not be enqueued when rxctrl.rxen is
cleared.

Signed-off-by: Frank Chang <[email protected]>
Reviewed-by: Alistair Francis <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit e6051fa61b)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-26 17:14:50 +03:00
Florian Lugou 44725d33b6 hw/char: sifive_uart: Avoid infinite delay of async xmit function
The current handler for TXFIFO writes schedules an async callback to
pop characters from the queue. When software writes to TXFIFO faster
than the async callback delay (100ns), the timer may be pushed back
while the previous character has not be dequeued yet. This happens in
particular when using -icount with small shift values. This is
especially worrysome when software repetitively issues amoor.w
instructions (as suggested by SiFive specification) and the FIFO is
full, leading to the callback being infinitly pushed back.

This commit fixes the issue by never pushing back the timer, only
updating it if it is not already active.

Signed-off-by: Florian Lugou <[email protected]>
Reviewed-by: Alistair Francis <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit 61240e3a06)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-26 17:13:50 +03:00
Zishun Yi 2ff5fd4be2 target/riscv: Allow mseccfg access based on ext_zicfilp
The Zicfilp extension adds the MLPE field to the mseccfg CSR. According
to the RISC-V Privileged Specification, mseccfg exists if any extension
that adds a field to it is implemented.

Currently, the `have_mseccfg()` predicate function checks for Smepmp,
Zkr, and Smmpm, but misses Zicfilp. As a result, if a CPU is configured
with `zicfilp=true` but without the other extensions, accessing the
mseccfg CSR will incorrectly raise an illegal instruction exception.

This patch adds the missing check for `ext_zicfilp` to ensure the CSR
is properly accessible when the Zicfilp extension is enabled.

This issue was discovered and reported by SpecHunter, an AI-driven
architecture specification analysis tool.

Link: https://github.com/yizishun/rv-isa-sec/blob/master/output/riscv-isa-manual/pr-2561/qemu.txt
Signed-off-by: Zishun Yi <[email protected]>
Reviewed-by: Chao Liu <[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 2494836232)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-26 09:56:33 +03:00
Andrew Jones 3c5cffd170 hw/riscv/riscv-iommu: Fix Svnapot 64KB pages
The Svnapot extension encodes a 64KB leaf PTE by setting PTE_N and
storing bits [3:0] of the PPN as a NAPOT size indicator. The IOMMU
model wasn't checking PTE_N and therefore was using the raw (NAPOT-
encoded) PPN directly in the physical address, yielding an address
32 KB above the correct base.

Fix both riscv_iommu_spa_fetch() and pdt_memory_read() by mirroring
the Svnapot handling already present in target/riscv/cpu_helper.c:

  napot_bits  = ctz64(ppn) + 1          /* 4 for 64KB */
  napot_mask  = (1 << napot_bits) - 1   /* 0xF */
  phys_base   = PPN_PHYS(ppn & ~napot_mask)
  page_offset = addr & (PPN_PHYS(napot_mask) | (TARGET_PAGE_SIZE - 1))

The spec only defines napot_bits == 4 (64KB); any other value is
treated as a reserved encoding.

This is a fix, rather than new feature support, because the spec
says "IOMMU implementations must support the Svnapot standard
extension for NAPOT Translation Contiguity."

Fixes: 0c54acb824 ("hw/riscv: add RISC-V IOMMU base emulation")
Cc: [email protected]
Signed-off-by: Andrew Jones <[email protected]>
Reviewed-by: Daniel Henrique Barboza <[email protected]>
Reviewed-by: Nutty Liu <[email protected]>
Reviewed-by: Tomasz Jeznach <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit fcbd93e96b)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-26 09:55:51 +03:00
Frank Chang 3a942fbf06 target/riscv: Update MISA.X for non-standard extensions
MISA.X is set if there are any non-standard extensions.
We should set MISA.X when any of the vendor extensions is enabled.

Signed-off-by: Frank Chang <[email protected]>
Reviewed-by: Max Chou <[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 613bb1949f)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-26 09:55:51 +03:00
Frank Chang 938e567b49 target/riscv: Update MISA.C for Zc* extensions
MISA.C is set if the following extensions are selected:
  * Zca and not F.
  * Zca, Zcf and F (but not D) is specified (RV32 only).
  * Zca, Zcf and Zcd if D is specified (RV32 only).
  * Zca, Zcd if D is specified (RV64 only).

Therefore, MISA.C must be set according to the Zc* extension rules.

Warn the user if RVC is explicitly disabled but MISA.C is required by
the rules above.

Signed-off-by: Frank Chang <[email protected]>
Reviewed-by: Max Chou <[email protected]>
Reviewed-by: Alistair Francis <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit f0433a8bc4)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-26 09:55:51 +03: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
339 changed files with 15947 additions and 2040 deletions

No files matched your search

+1
View File
@@ -3766,6 +3766,7 @@ F: tests/qtest/intel-iommu-test.c
AMD-Vi Emulation
S: Orphan
F: hw/i386/amd_iommu.?
F: tests/qtest/amd-iommu-test.c
OpenSBI Firmware
L: [email protected]
+1 -1
View File
@@ -1 +1 @@
10.0.10
10.0.12
+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
+24 -28
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"
@@ -921,6 +922,7 @@ static void do_tb_phys_invalidate(TranslationBlock *tb, bool rm_from_page_list)
uint32_t orig_cflags = tb_cflags(tb);
assert_memory_lock();
qemu_thread_jit_write();
/* make sure no further incoming jumps will be chained to this TB */
qemu_spin_lock(&tb->jmp_lock);
@@ -931,33 +933,27 @@ static void do_tb_phys_invalidate(TranslationBlock *tb, bool rm_from_page_list)
phys_pc = tb_page_addr0(tb);
h = tb_hash_func(phys_pc, (orig_cflags & CF_PCREL ? 0 : tb->pc),
tb->flags, tb->cs_base, orig_cflags);
if (!qht_remove(&tb_ctx.htable, tb, h)) {
return;
if (qht_remove(&tb_ctx.htable, tb, h)) {
/* remove the TB from the page list */
if (rm_from_page_list) {
tb_remove(tb);
}
/* remove the TB from the hash list */
tb_jmp_cache_inval_tb(tb);
/* suppress this TB from the two jump lists */
tb_remove_from_jmp_list(tb, 0);
tb_remove_from_jmp_list(tb, 1);
/* suppress any remaining jumps to this TB */
tb_jmp_unlink(tb);
qatomic_set(&tb_ctx.tb_phys_invalidate_count,
tb_ctx.tb_phys_invalidate_count + 1);
}
/* remove the TB from the page list */
if (rm_from_page_list) {
tb_remove(tb);
}
/* remove the TB from the hash list */
tb_jmp_cache_inval_tb(tb);
/* suppress this TB from the two jump lists */
tb_remove_from_jmp_list(tb, 0);
tb_remove_from_jmp_list(tb, 1);
/* suppress any remaining jumps to this TB */
tb_jmp_unlink(tb);
qatomic_set(&tb_ctx.tb_phys_invalidate_count,
tb_ctx.tb_phys_invalidate_count + 1);
}
static void tb_phys_invalidate__locked(TranslationBlock *tb)
{
qemu_thread_jit_write();
do_tb_phys_invalidate(tb, true);
qemu_thread_jit_execute();
}
@@ -1025,7 +1021,7 @@ void tb_invalidate_phys_range(tb_page_addr_t start, tb_page_addr_t last)
assert_memory_lock();
PAGE_FOR_EACH_TB(start, last, unused, tb, n) {
tb_phys_invalidate__locked(tb);
do_tb_phys_invalidate(tb, true);
}
}
@@ -1090,7 +1086,7 @@ bool tb_invalidate_phys_page_unwind(tb_page_addr_t addr, uintptr_t pc)
current_tb_modified = true;
cpu_restore_state_from_tb(current_cpu, current_tb, pc);
}
tb_phys_invalidate__locked(tb);
do_tb_phys_invalidate(tb, true);
}
if (current_tb_modified) {
@@ -1153,7 +1149,7 @@ tb_invalidate_phys_page_range__locked(struct page_collection *pages,
cpu_restore_state_from_tb(current_cpu, current_tb, retaddr);
}
#endif /* TARGET_HAS_PRECISE_SMC */
tb_phys_invalidate__locked(tb);
do_tb_phys_invalidate(tb, true);
}
}
+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__)
+23 -18
View File
@@ -222,13 +222,16 @@ void page_dump(FILE *f)
int page_get_flags(target_ulong address)
{
PageFlagsNode *p = pageflags_find(address, address);
PageFlagsNode *p;
RCU_READ_LOCK_GUARD();
/*
* See util/interval-tree.c re lockless lookups: no false positives but
* there are false negatives. If we find nothing, retry with the mmap
* lock acquired.
*/
p = pageflags_find(address, address);
if (p) {
return p->flags;
}
@@ -327,15 +330,15 @@ static void pageflags_create_merge(target_ulong start, target_ulong last,
if (prev) {
if (next) {
prev->itree.last = next->itree.last;
pageflags_create(prev->itree.start, next->itree.last, flags);
g_free_rcu(next, rcu);
} else {
prev->itree.last = last;
pageflags_create(prev->itree.start, last, flags);
}
interval_tree_insert(&prev->itree, &pageflags_root);
g_free_rcu(prev, rcu);
} else if (next) {
next->itree.start = start;
interval_tree_insert(&next->itree, &pageflags_root);
pageflags_create(start, next->itree.last, flags);
g_free_rcu(next, rcu);
} else {
pageflags_create(start, last, flags);
}
@@ -405,8 +408,8 @@ static bool pageflags_set_clear(target_ulong start, target_ulong last,
if (set_flags != merge_flags) {
if (p_start < start) {
interval_tree_remove(&p->itree, &pageflags_root);
p->itree.last = start - 1;
interval_tree_insert(&p->itree, &pageflags_root);
pageflags_create(p_start, start - 1, p_flags);
g_free_rcu(p, rcu);
if (last < p_last) {
if (merge_flags) {
@@ -428,11 +431,11 @@ static bool pageflags_set_clear(target_ulong start, target_ulong last,
}
if (last < p_last) {
interval_tree_remove(&p->itree, &pageflags_root);
p->itree.start = last + 1;
interval_tree_insert(&p->itree, &pageflags_root);
pageflags_create(last + 1, p_last, p_flags);
if (merge_flags) {
pageflags_create(start, last, merge_flags);
}
g_free_rcu(p, rcu);
} else {
if (merge_flags) {
p->flags = merge_flags;
@@ -453,8 +456,8 @@ static bool pageflags_set_clear(target_ulong start, target_ulong last,
if (set_flags == p_flags) {
if (start < p_start) {
interval_tree_remove(&p->itree, &pageflags_root);
p->itree.start = start;
interval_tree_insert(&p->itree, &pageflags_root);
pageflags_create(start, p_last, p_flags);
g_free_rcu(p, rcu);
}
if (p_last < last) {
start = p_last + 1;
@@ -466,8 +469,8 @@ static bool pageflags_set_clear(target_ulong start, target_ulong last,
/* Maybe split out head and/or tail ranges with the original flags. */
interval_tree_remove(&p->itree, &pageflags_root);
if (p_start < start) {
p->itree.last = start - 1;
interval_tree_insert(&p->itree, &pageflags_root);
pageflags_create(p_start, start - 1, p_flags);
g_free_rcu(p, rcu);
if (p_last < last) {
goto restart;
@@ -476,8 +479,8 @@ static bool pageflags_set_clear(target_ulong start, target_ulong last,
pageflags_create(last + 1, p_last, p_flags);
}
} else if (last < p_last) {
p->itree.start = last + 1;
interval_tree_insert(&p->itree, &pageflags_root);
pageflags_create(last + 1, p_last, p_flags);
g_free_rcu(p, rcu);
} else {
g_free_rcu(p, rcu);
goto restart;
@@ -545,6 +548,8 @@ bool page_check_range(target_ulong start, target_ulong len, int flags)
return false; /* wrap around */
}
RCU_READ_LOCK_GUARD();
locked = have_mmap_lock();
while (true) {
PageFlagsNode *p = pageflags_find(start, last);
@@ -807,7 +812,7 @@ static int probe_access_internal(CPUArchState *env, vaddr addr,
if (page_flags & acc_flag) {
if (access_type != MMU_INST_FETCH
&& cpu_plugin_mem_cbs_enabled(env_cpu(env))) {
return TLB_MMIO;
return TLB_FORCE_SLOW;
}
return 0; /* success */
}
@@ -842,7 +847,7 @@ void *probe_access(CPUArchState *env, vaddr addr, int size,
g_assert(-(addr | TARGET_PAGE_MASK) >= size);
flags = probe_access_internal(env, addr, size, access_type, false, ra);
g_assert((flags & ~TLB_MMIO) == 0);
g_assert((flags & ~TLB_FORCE_SLOW) == 0);
return size ? g2h(env_cpu(env), addr) : NULL;
}
+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);
}
+12 -1
View File
@@ -1920,7 +1920,18 @@ bdrv_co_do_pwrite_zeroes(BlockDriverState *bs, int64_t offset, int64_t bytes,
assert(!bs->supported_zero_flags);
}
if (ret == -ENOTSUP && !(flags & BDRV_REQ_NO_FALLBACK)) {
/*
* TODO The ret == -EINVAL && num < alignment case is a workaround for
* when request_alignment is 1 on files with cache=writeback. The Linux
* ioctl(BLKZEROOUT) requires block alignment and will fail with
* EINVAL. The block layer should align the request to
* write_zeroes_alignment instead of trying the syscall, failing, and
* falling back to a bounce buffer. Doing that is not easy so for now
* we use a bounce buffer:
* https://lore.kernel.org/qemu-devel/[email protected]/
*/
if ((ret == -ENOTSUP || (ret == -EINVAL && num < alignment)) &&
!(flags & BDRV_REQ_NO_FALLBACK)) {
/* Fall back to bounce buffer if write zeroes is unsupported */
BdrvRequestFlags write_flags = flags & ~BDRV_REQ_ZERO_WRITE;
+22
View File
@@ -36,6 +36,19 @@
/* Maximum number of requests in a batch. (default value) */
#define DEFAULT_MAX_BATCH 32
/*
* Bound on how deep ioq_submit() may recurse on a single LaioQueue via the
* ioq_submit -> qemu_laio_process_completions -> defer_call_end ->
* laio_deferred_fn -> ioq_submit cycle. The cycle terminates naturally
* when io_submit(2) returns asynchronously (O_DIRECT), but can grow
* without bound when submissions complete synchronously. On overflow
* the caller returns without submitting; the outermost
* qemu_laio_process_completions() has already scheduled s->completion_bh
* (via qemu_bh_schedule() at the top of that function), which resumes
* submission from the next event-loop dispatch.
*/
#define IOQ_SUBMIT_MAX_DEPTH 8
struct qemu_laiocb {
Coroutine *co;
LinuxAioState *ctx;
@@ -61,6 +74,7 @@ typedef struct {
unsigned int in_queue;
unsigned int in_flight;
bool blocked;
unsigned int submit_depth;
QSIMPLEQ_HEAD(, qemu_laiocb) pending;
} LaioQueue;
@@ -331,6 +345,7 @@ static void ioq_init(LaioQueue *io_q)
io_q->in_queue = 0;
io_q->in_flight = 0;
io_q->blocked = false;
io_q->submit_depth = 0;
}
static void ioq_submit(LinuxAioState *s)
@@ -340,6 +355,11 @@ static void ioq_submit(LinuxAioState *s)
struct iocb *iocbs[MAX_EVENTS];
QSIMPLEQ_HEAD(, qemu_laiocb) completed;
if (s->io_q.submit_depth >= IOQ_SUBMIT_MAX_DEPTH) {
return;
}
s->io_q.submit_depth++;
do {
if (s->io_q.in_flight >= MAX_EVENTS) {
break;
@@ -385,6 +405,8 @@ static void ioq_submit(LinuxAioState *s)
* pended requests will be submitted from there.
*/
}
s->io_q.submit_depth--;
}
static uint64_t laio_max_batch(LinuxAioState *s, uint64_t dev_max_batch)
+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) {
+49 -3
View File
@@ -1392,6 +1392,9 @@ count_single_write_clusters(BlockDriverState *bs, int nb_clusters,
* the same cluster. In this case we need to wait until the previous
* request has completed and updated the L2 table accordingly.
*
* If allow_shortening == true, instead of waiting for a dependency, *cur_bytes
* can be shortened so that the cluster allocations don't overlap.
*
* Returns:
* 0 if there was no dependency. *cur_bytes indicates the number of
* bytes from guest_offset that can be read before the next
@@ -1403,7 +1406,9 @@ count_single_write_clusters(BlockDriverState *bs, int nb_clusters,
*/
static int coroutine_fn handle_dependencies(BlockDriverState *bs,
uint64_t guest_offset,
uint64_t *cur_bytes, QCowL2Meta **m)
uint64_t *cur_bytes,
bool allow_shortening,
QCowL2Meta **m)
{
BDRVQcow2State *s = bs->opaque;
QCowL2Meta *old_alloc;
@@ -1434,7 +1439,7 @@ static int coroutine_fn handle_dependencies(BlockDriverState *bs,
/* Conflict */
if (start < old_start) {
if (start < old_start && allow_shortening) {
/* Stop at the start of a running allocation */
bytes = old_start - start;
} else {
@@ -1469,6 +1474,29 @@ static int coroutine_fn handle_dependencies(BlockDriverState *bs,
return 0;
}
void coroutine_mixed_fn qcow2_wait_for_dependencies(BlockDriverState *bs,
uint64_t guest_offset,
uint64_t bytes)
{
BDRVQcow2State *s = bs->opaque;
QCowL2Meta *m = NULL;
int ret;
/*
* Discard has some non-coroutine callers (creating internal snapshots and
* make empty). They are calling from qemu-img or in a drained section, so
* we know that no writes can be in progress.
*/
if (!qemu_in_coroutine()) {
assert(QLIST_EMPTY(&s->cluster_allocs));
return;
}
do {
ret = handle_dependencies(bs, guest_offset, &bytes, false, &m);
} while (ret == -EAGAIN);
}
/*
* Checks how many already allocated clusters that don't require a new
* allocation there are at the given guest_offset (up to *bytes).
@@ -1840,7 +1868,7 @@ again:
* the right synchronisation between the in-flight request and
* the new one.
*/
ret = handle_dependencies(bs, start, &cur_bytes, m);
ret = handle_dependencies(bs, start, &cur_bytes, true, m);
if (ret == -EAGAIN) {
/* Currently handle_dependencies() doesn't yield if we already had
* an allocation. If it did, we would have to clean up the L2Meta
@@ -2002,6 +2030,15 @@ int qcow2_cluster_discard(BlockDriverState *bs, uint64_t offset,
int64_t cleared;
int ret;
/*
* If we're touching a cluster for which allocating writes are in flight,
* wait for them to complete to avoid conflicting metadata updates.
*
* We don't need to allocate a QCowL2Meta for the discard operation because
* s->lock is held for the duration of the whole operation.
*/
qcow2_wait_for_dependencies(bs, offset, bytes);
/* Caller must pass aligned values, except at image end */
assert(QEMU_IS_ALIGNED(offset, s->cluster_size));
assert(QEMU_IS_ALIGNED(end_offset, s->cluster_size) ||
@@ -2164,6 +2201,15 @@ int coroutine_fn qcow2_subcluster_zeroize(BlockDriverState *bs, uint64_t offset,
int64_t cleared;
int ret;
/*
* If we're touching a cluster for which allocating writes are in flight,
* wait for them to complete to avoid conflicting metadata updates.
*
* We don't need to allocate a QCowL2Meta for the zeroize operation because
* s->lock is held for the duration of the whole operation.
*/
qcow2_wait_for_dependencies(bs, offset, bytes);
/* If we have to stay in sync with an external data file, zero out
* s->data_file first. */
if (data_file_is_raw(bs)) {
+7 -1
View File
@@ -4088,10 +4088,16 @@ qcow2_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset, int64_t bytes,
}
qemu_co_mutex_lock(&s->lock);
/* We can have new write after previous check */
offset -= head;
bytes = s->subcluster_size;
nr = s->subcluster_size;
/*
* Wait for in-flight allocating writes first: otherwise the type
* check below could pass on UNALLOCATED while a yet-to-link_l2 write
* completes during qcow2_subcluster_zeroize()'s own wait, letting the
* resumed MAY_UNMAP discard the just-written data.
*/
qcow2_wait_for_dependencies(bs, offset, bytes);
ret = qcow2_get_host_offset(bs, offset, &nr, &off, &type);
if (ret < 0 ||
(type != QCOW2_SUBCLUSTER_UNALLOCATED_PLAIN &&
+4
View File
@@ -958,6 +958,10 @@ int coroutine_fn GRAPH_RDLOCK
qcow2_subcluster_zeroize(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
int flags);
void coroutine_mixed_fn
qcow2_wait_for_dependencies(BlockDriverState *bs, uint64_t guest_offset,
uint64_t bytes);
int GRAPH_RDLOCK
qcow2_expand_zero_clusters(BlockDriverState *bs,
BlockDriverAmendStatusCB *status_cb,
+11 -5
View File
@@ -351,16 +351,22 @@ static void bdrv_qed_detach_aio_context(BlockDriverState *bs)
{
BDRVQEDState *s = bs->opaque;
qed_cancel_need_check_timer(s);
timer_free(s->need_check_timer);
s->need_check_timer = NULL;
if (s->need_check_timer) {
qed_cancel_need_check_timer(s);
timer_free(s->need_check_timer);
s->need_check_timer = NULL;
}
}
static void bdrv_qed_attach_aio_context(BlockDriverState *bs,
AioContext *new_context)
static void GRAPH_RDLOCK bdrv_qed_attach_aio_context(BlockDriverState *bs,
AioContext *new_context)
{
BDRVQEDState *s = bs->opaque;
if (bdrv_is_inactive(bs)) {
return;
}
s->need_check_timer = aio_timer_new(new_context,
QEMU_CLOCK_VIRTUAL, SCALE_NS,
qed_need_check_timer_cb, s);
+8 -1
View File
@@ -202,6 +202,13 @@ virgl_cmd_submit_3d(VuGpu *g,
VUGPU_FILL_CMD(cs);
if (cs.size > VIRTIO_GPU_MAX_CMD_SUBMIT_SIZE) {
g_critical("%s: command buffer too large (%u)",
__func__, cs.size);
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_PARAMETER;
return;
}
buf = g_malloc(cs.size);
s = iov_to_buf(cmd->elem.out_sg, cmd->elem.out_num,
sizeof(cs), buf, cs.size);
@@ -334,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;
}
+9
View File
@@ -22,6 +22,7 @@
#include "qemu/queue.h"
#include "qemu/iov.h"
#include "qemu/bswap.h"
#include "qemu/units.h"
#include "vugbm.h"
typedef enum VhostUserGpuRequest {
@@ -163,6 +164,14 @@ struct virtio_gpu_ctrl_command {
QTAILQ_ENTRY(virtio_gpu_ctrl_command) next;
};
/*
* With 4 KiB pages and QEMU's VIRTQUEUE_MAX_SIZE (1024) mapped-iov
* limit, the largest inline command is ~4 MiB. Cap submit_3d
* allocations to this value to prevent a malicious guest from
* triggering an OOM abort via an inflated cs.size field.
*/
#define VIRTIO_GPU_MAX_CMD_SUBMIT_SIZE (4 * MiB)
#define VUGPU_FILL_CMD(out) do { \
size_t vugpufillcmd_s_ = \
iov_to_buf(cmd->elem.out_sg, cmd->elem.out_num, 0, \
+30 -19
View File
@@ -984,6 +984,10 @@ typedef enum {
rv_op_ssamoswap_d = 953,
rv_op_c_sspush = 954,
rv_op_c_sspopchk = 955,
rv_op_cbo_inval = 956,
rv_op_cbo_clean = 957,
rv_op_cbo_flush = 958,
rv_op_cbo_zero = 959,
} rv_op;
/* register names */
@@ -2254,6 +2258,10 @@ const rv_opcode_data rvi_opcode_data[] = {
rv_op_sspush, 0 },
{ "c.sspopchk", rv_codec_cmop_ss, rv_fmt_rs1, NULL, rv_op_sspopchk,
rv_op_sspopchk, 0 },
{ "cbo.inval", rv_codec_r, rv_fmt_rs1, NULL, 0, 0, 0 },
{ "cbo.clean", rv_codec_r, rv_fmt_rs1, NULL, 0, 0, 0 },
{ "cbo.flush", rv_codec_r, rv_fmt_rs1, NULL, 0, 0, 0 },
{ "cbo.zero", rv_codec_r, rv_fmt_rs1, NULL, 0, 0, 0 },
};
/* CSR names */
@@ -2875,7 +2883,26 @@ static void decode_inst_opcode(rv_decode *dec, rv_isa isa)
switch ((inst >> 12) & 0b111) {
case 0: op = rv_op_fence; break;
case 1: op = rv_op_fence_i; break;
case 2: op = rv_op_lq; break;
case 2:
/*
* 'lq' shares the "(...) 010 ..... 0001111" opcode space
* with 'cbo' insns. Check the next 5 bits to select
* what we want:
*
* cbo_inval 0000000 00000 ..... 010 00000 0001111
* cbo_clean 0000000 00001 ..... 010 00000 0001111
* cbo_flush 0000000 00010 ..... 010 00000 0001111
* cbo_zero 0000000 00100 ..... 010 00000 0001111
*
* Anything that doesn't match these will default to 'lq'.
*/
switch ((inst >> 17) & 0b11111) {
case 0: op = rv_op_cbo_inval; break;
case 1: op = rv_op_cbo_clean; break;
case 2: op = rv_op_cbo_flush; break;
case 4: op = rv_op_cbo_zero; break;
default: op = rv_op_lq; break;
}
}
break;
case 4:
@@ -5056,26 +5083,10 @@ static bool check_constraints(rv_decode *dec, const rvc_constraint *c)
return true;
}
/* instruction length */
/* Same as insn_len() from target/riscv/internals.h */
static size_t inst_length(rv_inst inst)
{
/* NOTE: supports maximum instruction size of 64-bits */
/*
* instruction length coding
*
* aa - 16 bit aa != 11
* bbb11 - 32 bit bbb != 111
* 011111 - 48 bit
* 0111111 - 64 bit
*/
return (inst & 0b11) != 0b11 ? 2
: (inst & 0b11100) != 0b11100 ? 4
: (inst & 0b111111) == 0b011111 ? 6
: (inst & 0b1111111) == 0b0111111 ? 8
: 0;
return (inst & 3) == 3 ? 4 : 2;
}
/* format instruction */
+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
-------------------
+1
View File
@@ -375,6 +375,7 @@ static void partsN(uncanon_normal)(FloatPartsN *p, float_status *s,
/* Need to recompute round-to-even/round-to-odd. */
switch (s->float_rounding_mode) {
case float_round_nearest_even:
case float_round_nearest_even_max:
if (N > 64 && frac_lsb == 0) {
inc = ((p->frac_hi & 1) ||
(p->frac_lo & round_mask) != frac_lsbm1
+13 -1
View File
@@ -79,6 +79,11 @@ typedef struct ExtendedOps {
#define V9FS_SEC_MASK 0x0000003C
/*
* Limits the maximum amount of simultaneously open xattr FIDs to prevent
* host memory exhaustion (as each xattr FID contains a xattr value buffer).
*/
#define V9FS_MAX_XATTR_DEFAULT 1024
typedef struct FileOperations FileOperations;
typedef struct XattrOperations XattrOperations;
@@ -94,6 +99,8 @@ typedef struct FsDriverEntry {
FsThrottle fst;
mode_t fmode;
mode_t dmode;
/* temporary storage for parse_opts only */
uint32_t max_xattr;
} FsDriverEntry;
struct FsContext {
@@ -107,10 +114,14 @@ struct FsContext {
void *private;
mode_t fmode;
mode_t dmode;
/* max. amount of simultaneously open xattr FIDs */
uint32_t xattr_fid_limit;
/* current amount of open xattr FIDs */
uint32_t xattr_fid_count;
};
struct V9fsPath {
uint16_t size;
size_t size;
char *data;
};
P9ARRAY_DECLARE_TYPE(V9fsPath);
@@ -164,6 +175,7 @@ struct FileOperations {
int (*renameat)(FsContext *ctx, V9fsPath *olddir, const char *old_name,
V9fsPath *newdir, const char *new_name);
int (*unlinkat)(FsContext *ctx, V9fsPath *dir, const char *name, int flags);
bool (*has_valid_file_handle)(int fid_type, V9fsFidOpenState *fs);
};
#endif
+6
View File
@@ -46,6 +46,9 @@ static QemuOptsList qemu_fsdev_opts = {
}, {
.name = "dmode",
.type = QEMU_OPT_NUMBER,
}, {
.name = "max_xattr",
.type = QEMU_OPT_NUMBER,
},
THROTTLE_OPTS,
@@ -92,6 +95,9 @@ static QemuOptsList qemu_virtfs_opts = {
}, {
.name = "dmode",
.type = QEMU_OPT_NUMBER,
}, {
.name = "max_xattr",
.type = QEMU_OPT_NUMBER,
},
{ /*End of list */ }
+1 -1
View File
@@ -45,7 +45,7 @@ typedef struct FsDriverListEntry {
static QTAILQ_HEAD(, FsDriverListEntry) fsdriver_entries =
QTAILQ_HEAD_INITIALIZER(fsdriver_entries);
#define COMMON_FS_DRIVER_OPTIONS "id", "fsdriver", "readonly"
#define COMMON_FS_DRIVER_OPTIONS "id", "fsdriver", "readonly", "max_xattr"
static FsDriverTable FsDrivers[] = {
{
+27 -20
View File
@@ -87,27 +87,34 @@
</flags>
<flags id="i386_cr4" size="4">
<field name="VME" start="0" end="0"/>
<field name="PVI" start="1" end="1"/>
<field name="TSD" start="2" end="2"/>
<field name="DE" start="3" end="3"/>
<field name="PSE" start="4" end="4"/>
<field name="PAE" start="5" end="5"/>
<field name="MCE" start="6" end="6"/>
<field name="PGE" start="7" end="7"/>
<field name="PCE" start="8" end="8"/>
<field name="OSFXSR" start="9" end="9"/>
<field name="OSXMMEXCPT" start="10" end="10"/>
<field name="UMIP" start="11" end="11"/>
<field name="LA57" start="12" end="12"/>
<field name="VMXE" start="13" end="13"/>
<field name="SMXE" start="14" end="14"/>
<field name="FSGSBASE" start="16" end="16"/>
<field name="PCIDE" start="17" end="17"/>
<field name="OSXSAVE" start="18" end="18"/>
<field name="SMEP" start="20" end="20"/>
<field name="SMAP" start="21" end="21"/>
<field name="LAM_SUP" start="28" end="28"/>
<field name="LASS" start="27" end="27"/>
<field name="UINTR" start="25" end="25"/>
<field name="PKS" start="24" end="24"/>
<field name="CET" start="23" end="23"/>
<field name="PKE" start="22" end="22"/>
<field name="PKE" start="22" end="22"/>
<field name="SMAP" start="21" end="21"/>
<field name="SMEP" start="20" end="20"/>
<field name="KL" start="19" end="19"/>
<field name="OSXSAVE" start="18" end="18"/>
<field name="PCIDE" start="17" end="17"/>
<field name="FSGSBASE" start="16" end="16"/>
<field name="SMXE" start="14" end="14"/>
<field name="VMXE" start="13" end="13"/>
<field name="LA57" start="12" end="12"/>
<field name="UMIP" start="11" end="11"/>
<field name="OSXMMEXCPT" start="10" end="10"/>
<field name="OSFXSR" start="9" end="9"/>
<field name="PCE" start="8" end="8"/>
<field name="PGE" start="7" end="7"/>
<field name="MCE" start="6" end="6"/>
<field name="PAE" start="5" end="5"/>
<field name="PSE" start="4" end="4"/>
<field name="DE" start="3" end="3"/>
<field name="TSD" start="2" end="2"/>
<field name="PVI" start="1" end="1"/>
<field name="VME" start="0" end="0"/>
</flags>
<flags id="i386_efer" size="4">
+7
View File
@@ -102,9 +102,16 @@
</flags>
<flags id="x64_cr4" size="8">
<field name="FRED" start="32" end="32"/>
<field name="LAM_SUP" start="28" end="28"/>
<field name="LASS" start="27" end="27"/>
<field name="UINTR" start="25" end="25"/>
<field name="PKS" start="24" end="24"/>
<field name="CET" start="23" end="23"/>
<field name="PKE" start="22" end="22"/>
<field name="SMAP" start="21" end="21"/>
<field name="SMEP" start="20" end="20"/>
<field name="KL" start="19" end="19"/>
<field name="OSXSAVE" start="18" end="18"/>
<field name="PCIDE" start="17" end="17"/>
<field name="FSGSBASE" start="16" end="16"/>
@@ -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)
{
+47 -21
View File
@@ -766,16 +766,22 @@ out:
return err;
}
static int local_fid_fd(int fid_type, V9fsFidOpenState *fs)
{
if (fid_type == P9_FID_DIR) {
return dirfd(fs->dir.stream);
} else if (fid_type == P9_FID_FILE) {
return fs->fd;
} else {
errno = EBADF;
return -1;
}
}
static int local_fstat(FsContext *fs_ctx, int fid_type,
V9fsFidOpenState *fs, struct stat *stbuf)
{
int err, fd;
if (fid_type == P9_FID_DIR) {
fd = dirfd(fs->dir.stream);
} else {
fd = fs->fd;
}
int err, fd = local_fid_fd(fid_type, fs);
err = fstat(fd, stbuf);
if (err) {
@@ -1167,13 +1173,7 @@ out:
static int local_fsync(FsContext *ctx, int fid_type,
V9fsFidOpenState *fs, int datasync)
{
int fd;
if (fid_type == P9_FID_DIR) {
fd = dirfd(fs->dir.stream);
} else {
fd = fs->fd;
}
int fd = local_fid_fd(fid_type, fs);
if (datasync) {
return qemu_fdatasync(fd);
@@ -1243,26 +1243,35 @@ static int local_name_to_path(FsContext *ctx, V9fsPath *dir_path,
} else if (!strcmp(name, "..")) {
if (!strcmp(dir_path->data, ".")) {
/* ".." relative to the root is "." */
v9fs_path_sprintf(target, ".");
if (v9fs_path_sprintf(target, ".") < 0) {
return -1;
}
} else {
char *tmp = g_path_get_dirname(dir_path->data);
g_autofree char *tmp = g_path_get_dirname(dir_path->data);
/* Symbolic links are resolved by the client. We can assume
* that ".." relative to "foo/bar" is equivalent to "foo"
*/
v9fs_path_sprintf(target, "%s", tmp);
g_free(tmp);
if (v9fs_path_sprintf(target, "%s", tmp) < 0) {
return -1;
}
}
} else {
assert(!strchr(name, '/'));
v9fs_path_sprintf(target, "%s/%s", dir_path->data, name);
if (v9fs_path_sprintf(target, "%s/%s", dir_path->data, name) < 0) {
return -1;
}
}
} else if (!strcmp(name, "/") || !strcmp(name, ".") ||
!strcmp(name, "..")) {
/* This is the root fid */
v9fs_path_sprintf(target, ".");
if (v9fs_path_sprintf(target, ".") < 0) {
return -1;
}
} else {
assert(!strchr(name, '/'));
v9fs_path_sprintf(target, "./%s", name);
if (v9fs_path_sprintf(target, "./%s", name) < 0) {
return -1;
}
}
return 0;
}
@@ -1500,6 +1509,15 @@ static int local_parse_opts(QemuOpts *opts, FsDriverEntry *fse, Error **errp)
const char *path = qemu_opt_get(opts, "path");
const char *multidevs = qemu_opt_get(opts, "multidevs");
uint64_t val = qemu_opt_get_number(opts, "max_xattr",
V9FS_MAX_XATTR_DEFAULT);
if (val > UINT32_MAX) {
error_setg(errp, "max_xattr value '%s' too large",
qemu_opt_get(opts, "max_xattr"));
return -1;
}
fse->max_xattr = val;
if (!sec_model) {
error_setg(errp, "security_model property not set");
error_append_security_model_hint(errp);
@@ -1575,6 +1593,13 @@ static int local_parse_opts(QemuOpts *opts, FsDriverEntry *fse, Error **errp)
return 0;
}
static bool local_has_valid_file_handle(int fid_type, V9fsFidOpenState *fs)
{
return
(fid_type == P9_FID_FILE && fs->fd != -1) ||
(fid_type == P9_FID_DIR && fs->dir.stream != NULL);
}
FileOperations local_ops = {
.parse_opts = local_parse_opts,
.init = local_init,
@@ -1612,4 +1637,5 @@ FileOperations local_ops = {
.name_to_path = local_name_to_path,
.renameat = local_renameat,
.unlinkat = local_unlinkat,
.has_valid_file_handle = local_has_valid_file_handle,
};
+53 -4
View File
@@ -25,6 +25,8 @@
#include "qemu/rcu_queue.h"
#include "qemu/cutils.h"
#include "system/qtest.h"
#include "qapi/error.h"
#include "qemu/option.h"
/* Root node for synth file system */
static V9fsSynthNode synth_root = {
@@ -461,15 +463,15 @@ static int synth_lsetxattr(FsContext *ctx, V9fsPath *path,
const char *name, void *value,
size_t size, int flags)
{
errno = ENOTSUP;
return -1;
/* pretend it worked */
return 0;
}
static int synth_lremovexattr(FsContext *ctx,
V9fsPath *path, const char *name)
{
errno = ENOTSUP;
return -1;
/* pretend it worked */
return 0;
}
static int synth_name_to_path(FsContext *ctx, V9fsPath *dir_path,
@@ -549,6 +551,19 @@ static ssize_t v9fs_synth_qtest_flush_write(void *buf, int len, off_t offset,
return 1;
}
/* transmits internal xattr counter to client */
static ssize_t v9fs_synth_read_xattr_count(void *buf, int len, off_t offset,
void *arg)
{
FsContext *ctx = arg;
size_t local_count = ctx->xattr_fid_count;
if (len < (int)sizeof(size_t)) {
return -ENOSPC;
}
memcpy(buf, &local_count, sizeof(size_t));
return sizeof(size_t);
}
static int synth_init(FsContext *ctx, Error **errp)
{
QLIST_INIT(&synth_root.child);
@@ -610,12 +625,45 @@ static int synth_init(FsContext *ctx, Error **errp)
g_free(name);
}
}
/* Directory for internal statistic queries */
{
V9fsSynthNode *stat_dir = NULL;
ret = qemu_v9fs_synth_mkdir(NULL, 0755, "stat", &stat_dir);
assert(!ret);
/* File for internal xattr count query */
ret = qemu_v9fs_synth_add_file(stat_dir, 0444, "xattr_count",
v9fs_synth_read_xattr_count,
NULL, ctx);
assert(!ret);
}
}
return 0;
}
static int synth_parse_opts(QemuOpts *opts, FsDriverEntry *fse, Error **errp)
{
uint64_t val = qemu_opt_get_number(opts, "max_xattr",
V9FS_MAX_XATTR_DEFAULT);
if (val > UINT32_MAX) {
error_setg(errp, "max_xattr value '%s' too large",
qemu_opt_get(opts, "max_xattr"));
return -1;
}
fse->max_xattr = val;
return 0;
}
static bool synth_has_valid_file_handle(int fid_type, V9fsFidOpenState *fs)
{
return false;
}
FileOperations synth_ops = {
.parse_opts = synth_parse_opts,
.init = synth_init,
.lstat = synth_lstat,
.readlink = synth_readlink,
@@ -650,4 +698,5 @@ FileOperations synth_ops = {
.name_to_path = synth_name_to_path,
.renameat = synth_renameat,
.unlinkat = synth_unlinkat,
.has_valid_file_handle = synth_has_valid_file_handle,
};
+157 -16
View File
@@ -201,17 +201,24 @@ void v9fs_path_free(V9fsPath *path)
}
void G_GNUC_PRINTF(2, 3)
v9fs_path_sprintf(V9fsPath *path, const char *fmt, ...)
int v9fs_path_sprintf(V9fsPath *path, const char *fmt, ...)
{
va_list ap;
int ret;
v9fs_path_free(path);
va_start(ap, fmt);
/* Bump the size for including terminating NULL */
path->size = g_vasprintf(&path->data, fmt, ap) + 1;
ret = g_vasprintf(&path->data, fmt, ap);
va_end(ap);
if (ret < 0) {
error_report_once("9pfs: unusual path formatting failure; "
"invalidating associated FID");
return -1;
}
/* Bump the size for including terminating NULL */
path->size = ret + 1;
return 0;
}
void v9fs_path_copy(V9fsPath *dst, const V9fsPath *src)
@@ -240,6 +247,9 @@ int v9fs_name_to_path(V9fsState *s, V9fsPath *dirpath,
*/
static int v9fs_path_is_ancestor(V9fsPath *s1, V9fsPath *s2)
{
if (!s1->data || !s2->data) {
return 0;
}
if (!strncmp(s1->data, s2->data, s1->size - 1)) {
if (s2->data[s1->size - 1] == '\0' || s2->data[s1->size - 1] == '/') {
return 1;
@@ -253,6 +263,31 @@ static size_t v9fs_string_size(V9fsString *str)
return str->size;
}
static int xattr_fid_count_inc(V9fsPDU *pdu)
{
V9fsState *s = pdu->s;
if (s->ctx.xattr_fid_limit > 0 &&
s->ctx.xattr_fid_count >= s->ctx.xattr_fid_limit) {
error_report_once("9pfs: xattr_fid_count limit exceeded "
"(configurable by option 'max_xattr').");
return -ENOSPC;
}
s->ctx.xattr_fid_count++;
return 0;
}
static void xattr_fid_count_decr(V9fsPDU *pdu)
{
V9fsState *s = pdu->s;
if (s->ctx.xattr_fid_count > 0) {
s->ctx.xattr_fid_count--;
} else {
error_report_once("9pfs: xattr_fid_count underflow detected");
}
}
/*
* returns 0 if fid got re-opened, 1 if not, < 0 on error
*/
@@ -385,6 +420,7 @@ static int coroutine_fn free_fid(V9fsPDU *pdu, V9fsFidState *fidp)
}
} else if (fidp->fid_type == P9_FID_XATTR) {
retval = v9fs_xattr_fid_clunk(pdu, fidp);
xattr_fid_count_decr(pdu);
}
v9fs_path_free(&fidp->path);
g_free(fidp);
@@ -614,6 +650,14 @@ static void coroutine_fn virtfs_reset(V9fsPDU *pdu)
fidp->clunked = true;
put_fid(pdu, fidp);
}
/*
* Explicitly reset the xattr FID counter.
*
* free_fid() already decrements the counter for each P9_FID_XATTR, so the
* counter should already be zero, hence this is just a defensive measure.
*/
s->ctx.xattr_fid_count = 0;
}
#define P9_QID_TYPE_DIR 0x80
@@ -1397,13 +1441,15 @@ static void print_sg(struct iovec *sg, int cnt)
}
/* Will call this only for path name based fid */
static void v9fs_fix_path(V9fsPath *dst, V9fsPath *src, int len)
static int v9fs_fix_path(V9fsPath *dst, V9fsPath *src, int len)
{
V9fsPath str;
int ret;
v9fs_path_init(&str);
v9fs_path_copy(&str, dst);
v9fs_path_sprintf(dst, "%s%s", src->data, str.data + len);
ret = v9fs_path_sprintf(dst, "%s%s", src->data, str.data + len);
v9fs_path_free(&str);
return ret;
}
static inline bool is_ro_export(FsContext *ctx)
@@ -1447,6 +1493,16 @@ static void coroutine_fn v9fs_version(void *opaque)
goto out;
}
/* cap msize to transport's theoretical limit */
if (s->transport->msize_limit) {
size_t limit = s->transport->msize_limit(s);
if (s->msize > limit) {
s->msize = limit;
warn_report_once("9p: client msize capped to %zu (transport limit)",
limit);
}
}
/* 8192 is the default msize of Linux clients */
if (s->msize <= 8192 && !(s->ctx.export_flags & V9FS_NO_PERF_WARN)) {
warn_report_once(
@@ -1595,6 +1651,11 @@ out_nofid:
pdu_complete(pdu, err);
}
static bool fid_has_valid_file_handle(V9fsState *s, V9fsFidState *fidp)
{
return s->ops->has_valid_file_handle(fidp->fid_type, &fidp->fs);
}
static void coroutine_fn v9fs_getattr(void *opaque)
{
int32_t fid;
@@ -1617,9 +1678,7 @@ static void coroutine_fn v9fs_getattr(void *opaque)
retval = -ENOENT;
goto out_nofid;
}
if ((fidp->fid_type == P9_FID_FILE && fidp->fs.fd != -1) ||
(fidp->fid_type == P9_FID_DIR && fidp->fs.dir.stream))
{
if (fid_has_valid_file_handle(pdu->s, fidp)) {
retval = v9fs_co_fstat(pdu, fidp, &stbuf);
} else {
retval = v9fs_co_lstat(pdu, &fidp->path, &stbuf);
@@ -2214,10 +2273,15 @@ static void coroutine_fn v9fs_fsync(void *opaque)
err = -ENOENT;
goto out_nofid;
}
if (!fid_has_valid_file_handle(pdu->s, fidp)) {
err = -EBADF;
goto out;
}
err = v9fs_co_fsync(pdu, fidp, datasync);
if (!err) {
err = offset;
}
out:
put_fid(pdu, fidp);
out_nofid:
pdu_complete(pdu, err);
@@ -2622,6 +2686,7 @@ static void coroutine_fn v9fs_readdir(void *opaque)
uint32_t max_count;
V9fsPDU *pdu = opaque;
V9fsState *s = pdu->s;
size_t max_resp_sz;
retval = pdu_unmarshal(pdu, offset, "dqd", &fid,
&initial_offset, &max_count);
@@ -2630,9 +2695,28 @@ static void coroutine_fn v9fs_readdir(void *opaque)
}
trace_v9fs_readdir(pdu->tag, pdu->id, fid, initial_offset, max_count);
max_resp_sz = s->msize;
/*
* Constrain max_count to transport's current, actual response buffer size.
* A bad client might provide a response buffer < msize.
*/
if (s->transport->response_buffer_size) {
size_t buf_size = s->transport->response_buffer_size(pdu);
if (max_resp_sz > buf_size) {
max_resp_sz = buf_size;
}
}
/* Enough space for a R_readdir header: size[4] Rreaddir tag[2] count[4] */
if (max_count > s->msize - 11) {
max_count = s->msize - 11;
if (max_resp_sz > 11) {
max_resp_sz -= 11;
} else {
max_resp_sz = 0;
}
if (max_count > max_resp_sz) {
max_count = max_resp_sz;
warn_report_once(
"9p: bad client: T_readdir with count > msize - 11"
);
@@ -3292,12 +3376,14 @@ static int coroutine_fn v9fs_complete_rename(V9fsPDU *pdu, V9fsFidState *fidp,
goto out;
}
} else {
char *dir_name = g_path_get_dirname(fidp->path.data);
g_autofree char *dir_name = g_path_get_dirname(fidp->path.data);
V9fsPath dir_path;
v9fs_path_init(&dir_path);
v9fs_path_sprintf(&dir_path, "%s", dir_name);
g_free(dir_name);
err = v9fs_path_sprintf(&dir_path, "%s", dir_name);
if (err < 0) {
goto out;
}
err = v9fs_co_name_to_path(pdu, &dir_path, name->data, &new_path);
v9fs_path_free(&dir_path);
@@ -3318,7 +3404,10 @@ static int coroutine_fn v9fs_complete_rename(V9fsPDU *pdu, V9fsFidState *fidp,
while (g_hash_table_iter_next(&iter, &fid, (gpointer *) &tfidp)) {
if (v9fs_path_is_ancestor(&fidp->path, &tfidp->path)) {
/* replace the name */
v9fs_fix_path(&tfidp->path, &new_path, strlen(fidp->path.data));
if (v9fs_fix_path(&tfidp->path, &new_path,
strlen(fidp->path.data)) < 0) {
clunk_fid(s, tfidp->fid);
}
}
}
out:
@@ -3415,7 +3504,10 @@ static int coroutine_fn v9fs_fix_fid_paths(V9fsPDU *pdu, V9fsPath *olddir,
while (g_hash_table_iter_next(&iter, &fid, (gpointer *) &tfidp)) {
if (v9fs_path_is_ancestor(&oldpath, &tfidp->path)) {
/* replace the name */
v9fs_fix_path(&tfidp->path, &newpath, strlen(oldpath.data));
if (v9fs_fix_path(&tfidp->path, &newpath,
strlen(oldpath.data)) < 0) {
clunk_fid(s, tfidp->fid);
}
}
}
out:
@@ -3543,6 +3635,10 @@ static void coroutine_fn v9fs_wstat(void *opaque)
}
/* do we need to sync the file? */
if (donttouch_stat(&v9stat)) {
if (!fid_has_valid_file_handle(s, fidp)) {
err = -EBADF;
goto out;
}
err = v9fs_co_fsync(pdu, fidp, 0);
goto out;
}
@@ -3597,6 +3693,15 @@ static void coroutine_fn v9fs_wstat(void *opaque)
err = -EOPNOTSUPP;
goto out;
}
if (name_is_illegal(v9stat.name.data)) {
err = -ENOENT;
goto out;
}
if (!strcmp(".", v9stat.name.data) || !strcmp("..", v9stat.name.data)) {
err = -EISDIR;
goto out;
}
v9fs_path_write_lock(s);
err = v9fs_complete_rename(pdu, fidp, -1, &v9stat.name);
v9fs_path_unlock(s);
@@ -3802,6 +3907,10 @@ static void coroutine_fn v9fs_lock(void *opaque)
err = -ENOENT;
goto out_nofid;
}
if (!fid_has_valid_file_handle(pdu->s, fidp)) {
err = -EBADF;
goto out;
}
err = v9fs_co_fstat(pdu, fidp, &stbuf);
if (err < 0) {
goto out;
@@ -3847,6 +3956,10 @@ static void coroutine_fn v9fs_getlock(void *opaque)
err = -ENOENT;
goto out_nofid;
}
if (!fid_has_valid_file_handle(pdu->s, fidp)) {
err = -EBADF;
goto out;
}
err = v9fs_co_fstat(pdu, fidp, &stbuf);
if (err < 0) {
goto out;
@@ -3965,6 +4078,14 @@ static void coroutine_fn v9fs_xattrwalk(void *opaque)
clunk_fid(s, xattr_fidp->fid);
goto out;
}
/* Check xattr FID limit */
err = xattr_fid_count_inc(pdu);
if (err < 0) {
clunk_fid(s, xattr_fidp->fid);
goto out;
}
/*
* Read the xattr value
*/
@@ -3972,6 +4093,7 @@ static void coroutine_fn v9fs_xattrwalk(void *opaque)
xattr_fidp->fid_type = P9_FID_XATTR;
xattr_fidp->fs.xattr.xattrwalk_fid = true;
xattr_fidp->fs.xattr.value = g_malloc0(size);
if (size) {
err = v9fs_co_llistxattr(pdu, &xattr_fidp->path,
xattr_fidp->fs.xattr.value,
@@ -3998,6 +4120,14 @@ static void coroutine_fn v9fs_xattrwalk(void *opaque)
clunk_fid(s, xattr_fidp->fid);
goto out;
}
/* Check xattr FID limit */
err = xattr_fid_count_inc(pdu);
if (err < 0) {
clunk_fid(s, xattr_fidp->fid);
goto out;
}
/*
* Read the xattr value
*/
@@ -4005,6 +4135,7 @@ static void coroutine_fn v9fs_xattrwalk(void *opaque)
xattr_fidp->fid_type = P9_FID_XATTR;
xattr_fidp->fs.xattr.xattrwalk_fid = true;
xattr_fidp->fs.xattr.value = g_malloc0(size);
if (size) {
err = v9fs_co_lgetxattr(pdu, &xattr_fidp->path,
&name, xattr_fidp->fs.xattr.value,
@@ -4096,6 +4227,12 @@ static void coroutine_fn v9fs_xattrcreate(void *opaque)
goto out_put_fid;
}
/* Check xattr FID limit */
err = xattr_fid_count_inc(pdu);
if (err < 0) {
goto out_put_fid;
}
/* Make the file fid point to xattr */
xattr_fidp = file_fidp;
xattr_fidp->fid_type = P9_FID_XATTR;
@@ -4358,6 +4495,10 @@ int v9fs_device_realize_common(V9fsState *s, const V9fsTransport *t,
s->reclaiming = false;
/* init xattr FID limit from fsdev config */
s->ctx.xattr_fid_limit = fse->max_xattr;
s->ctx.xattr_fid_count = 0;
rc = 0;
out:
if (rc) {
+4 -1
View File
@@ -456,7 +456,8 @@ static inline uint8_t v9fs_request_cancelled(V9fsPDU *pdu)
void coroutine_fn v9fs_reclaim_fd(V9fsPDU *pdu);
void v9fs_path_init(V9fsPath *path);
void v9fs_path_free(V9fsPath *path);
void v9fs_path_sprintf(V9fsPath *path, const char *fmt, ...);
int G_GNUC_PRINTF(2, 3) v9fs_path_sprintf(V9fsPath *path, const char *fmt,
...);
void v9fs_path_copy(V9fsPath *dst, const V9fsPath *src);
size_t v9fs_readdir_response_size(V9fsString *name);
int v9fs_name_to_path(V9fsState *s, V9fsPath *dirpath,
@@ -480,6 +481,8 @@ struct V9fsTransport {
void (*init_out_iov_from_pdu)(V9fsPDU *pdu, struct iovec **piov,
unsigned int *pniov, size_t size);
void (*push_and_notify)(V9fsPDU *pdu);
size_t (*msize_limit)(V9fsState *s);
size_t (*response_buffer_size)(V9fsPDU *pdu);
};
#endif
+3
View File
@@ -219,13 +219,16 @@ int coroutine_fn v9fs_co_readdir_many(V9fsPDU *pdu, V9fsFidState *fidp,
bool dostat)
{
int err = 0;
V9fsState *s = pdu->s;
if (v9fs_request_cancelled(pdu)) {
return -EINTR;
}
v9fs_path_read_lock(s);
v9fs_co_run_in_worker({
err = do_readdir_many(pdu, fidp, entries, offset, maxsize, dostat);
});
v9fs_path_unlock(s);
return err;
}
+17
View File
@@ -192,12 +192,29 @@ static void virtio_init_out_iov_from_pdu(V9fsPDU *pdu, struct iovec **piov,
*pniov = elem->out_num;
}
static size_t virtio_9p_msize_limit(V9fsState *s)
{
const size_t guestPageSize = 4096;
return (VIRTQUEUE_MAX_SIZE - 2) * guestPageSize;
}
static size_t virtio_9p_response_buffer_size(V9fsPDU *pdu)
{
V9fsState *s = pdu->s;
V9fsVirtioState *v = container_of(s, V9fsVirtioState, state);
VirtQueueElement *elem = v->elems[pdu->idx];
return iov_size(elem->in_sg, elem->in_num);
}
static const V9fsTransport virtio_9p_transport = {
.pdu_vmarshal = virtio_pdu_vmarshal,
.pdu_vunmarshal = virtio_pdu_vunmarshal,
.init_in_iov_from_pdu = virtio_init_in_iov_from_pdu,
.init_out_iov_from_pdu = virtio_init_out_iov_from_pdu,
.push_and_notify = virtio_9p_push_and_notify,
.msize_limit = virtio_9p_msize_limit,
.response_buffer_size = virtio_9p_response_buffer_size,
};
static void virtio_9p_device_realize(DeviceState *dev, Error **errp)
+31
View File
@@ -250,12 +250,43 @@ static void xen_9pfs_push_and_notify(V9fsPDU *pdu)
qemu_bh_schedule(ring->bh);
}
static size_t xen_9p_msize_limit(V9fsState *s)
{
Xen9pfsDev *xen_9pfs = container_of(s, Xen9pfsDev, state);
size_t limit;
int i;
if (!xen_9pfs->num_rings) {
return 0;
}
limit = XEN_FLEX_RING_SIZE(xen_9pfs->rings[0].ring_order);
for (i = 1; i < xen_9pfs->num_rings; i++) {
limit = MIN(limit, XEN_FLEX_RING_SIZE(xen_9pfs->rings[i].ring_order));
}
return limit;
}
static size_t xen_9pfs_response_buffer_size(V9fsPDU *pdu)
{
Xen9pfsDev *priv = container_of(pdu->s, Xen9pfsDev, state);
Xen9pfsRing *ring = &priv->rings[pdu->tag % priv->num_rings];
struct iovec in_sg[2];
int num;
xen_9pfs_in_sg(ring, in_sg, &num, pdu->idx, 0);
return iov_size(in_sg, num);
}
static const V9fsTransport xen_9p_transport = {
.pdu_vmarshal = xen_9pfs_pdu_vmarshal,
.pdu_vunmarshal = xen_9pfs_pdu_vunmarshal,
.init_in_iov_from_pdu = xen_9pfs_init_in_iov_from_pdu,
.init_out_iov_from_pdu = xen_9pfs_init_out_iov_from_pdu,
.push_and_notify = xen_9pfs_push_and_notify,
.msize_limit = xen_9p_msize_limit,
.response_buffer_size = xen_9pfs_response_buffer_size,
};
static int xen_9pfs_init(struct XenLegacyDevice *xendev)
+8 -3
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)
{
@@ -2106,10 +2107,10 @@ void build_spcr(GArray *table_data, BIOSLinker *linker,
build_append_int_noprefix(table_data, f->stop_bits, 1);
/* Flow Control */
build_append_int_noprefix(table_data, f->flow_control, 1);
/* Language */
build_append_int_noprefix(table_data, f->language, 1);
/* Terminal Type */
build_append_int_noprefix(table_data, f->terminal_type, 1);
/* Language */
build_append_int_noprefix(table_data, f->language, 1);
/* PCI Device ID */
build_append_int_noprefix(table_data, f->pci_device_id, 2);
/* PCI Vendor ID */
@@ -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
+1 -1
View File
@@ -492,7 +492,7 @@ static void npcm7xx_realize(DeviceState *dev, Error **errp)
/* CPUs */
for (i = 0; i < nc->num_cpus; i++) {
object_property_set_int(OBJECT(&s->cpu[i]), "reset-cbar",
NPCM7XX_GIC_CPU_IF_ADDR, &error_abort);
NPCM7XX_CPUP_BA, &error_abort);
object_property_set_bool(OBJECT(&s->cpu[i]), "reset-hivecs", true,
&error_abort);
+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)
+6 -3
View File
@@ -305,6 +305,7 @@ static int intel_hda_send_command(IntelHDAState *d, uint32_t verb)
static void intel_hda_corb_run(IntelHDAState *d)
{
const MemTxAttrs attrs = { .memory = true };
hwaddr addr;
uint32_t rp, verb;
@@ -330,7 +331,7 @@ static void intel_hda_corb_run(IntelHDAState *d)
rp = (d->corb_rp + 1) & 0xff;
addr = intel_hda_addr(d->corb_lbase, d->corb_ubase);
ldl_le_pci_dma(&d->pci, addr + 4 * rp, &verb, MEMTXATTRS_UNSPECIFIED);
ldl_le_pci_dma(&d->pci, addr + 4 * rp, &verb, attrs);
d->corb_rp = rp;
dprint(d, 2, "%s: [rp 0x%x] verb 0x%08x\n", __func__, rp, verb);
@@ -395,7 +396,7 @@ static void intel_hda_response(HDACodecDevice *dev, bool solicited, uint32_t res
static bool intel_hda_xfer(HDACodecDevice *dev, uint32_t stnr, bool output,
uint8_t *buf, uint32_t len)
{
const MemTxAttrs attrs = MEMTXATTRS_UNSPECIFIED;
const MemTxAttrs attrs = { .memory = true };
HDACodecBus *bus = HDA_BUS(dev->qdev.parent_bus);
IntelHDAState *d = container_of(bus, IntelHDAState, codecs);
hwaddr addr;
@@ -466,6 +467,7 @@ static bool intel_hda_xfer(HDACodecDevice *dev, uint32_t stnr, bool output,
static void intel_hda_parse_bdl(IntelHDAState *d, IntelHDAStream *st)
{
const MemTxAttrs attrs = { .memory = true };
hwaddr addr;
uint8_t buf[16];
uint32_t i;
@@ -475,7 +477,8 @@ static void intel_hda_parse_bdl(IntelHDAState *d, IntelHDAStream *st)
g_free(st->bpl);
st->bpl = g_new(bpl, st->bentries);
for (i = 0; i < st->bentries; i++, addr += 16) {
pci_dma_read(&d->pci, addr, buf, 16);
pci_dma_rw(&d->pci, addr, buf, 16,
DMA_DIRECTION_TO_DEVICE, attrs);
st->bpl[i].addr = le64_to_cpu(*(uint64_t *)buf);
st->bpl[i].len = le32_to_cpu(*(uint32_t *)(buf + 8));
st->bpl[i].flags = le32_to_cpu(*(uint32_t *)(buf + 12));
+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"
+7 -1
View File
@@ -203,10 +203,16 @@ static void virtio_blk_handle_scsi(VirtIOBlockReq *req)
/*
* The scsi inhdr is placed in the second-to-last input segment, just
* before the regular inhdr.
* before the regular inhdr. VIRTIO implementations normally do not rely on
* the precise message framing, but legacy implementations did and so we do
* too for the legacy virtio-blk SCSI request type.
*
* Just put anything nonzero so that the ioctl fails in the guest.
*/
if (elem->in_sg[elem->in_num - 2].iov_len != sizeof(*scsi)) {
status = VIRTIO_BLK_S_IOERR;
goto fail;
}
scsi = (void *)elem->in_sg[elem->in_num - 2].iov_base;
virtio_stl_p(vdev, &scsi->errors, 255);
status = VIRTIO_BLK_S_UNSUPP;
+20 -5
View File
@@ -84,6 +84,11 @@ static gboolean sifive_uart_xmit(void *do_not_use, GIOCondition cond,
return G_SOURCE_REMOVE;
}
/* Don't pop the FIFO if transmit is disabled. */
if (!SIFIVE_UART_TXEN(s->txctrl)) {
return G_SOURCE_REMOVE;
}
/* Don't pop the FIFO in case the write fails */
characters = fifo8_peek_bufptr(&s->tx_fifo,
fifo8_num_used(&s->tx_fifo), &numptr);
@@ -112,11 +117,19 @@ static gboolean sifive_uart_xmit(void *do_not_use, GIOCondition cond,
return G_SOURCE_REMOVE;
}
static void sifive_uart_write_tx_fifo(SiFiveUARTState *s, const uint8_t *buf,
int size)
static void sifive_uart_trigger_tx_fifo(SiFiveUARTState *s)
{
uint64_t current_time = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
if (!timer_pending(s->fifo_trigger_handle)) {
timer_mod(s->fifo_trigger_handle, current_time +
TX_INTERRUPT_TRIGGER_DELAY_NS);
}
}
static void sifive_uart_write_tx_fifo(SiFiveUARTState *s, const uint8_t *buf,
int size)
{
if (size > fifo8_num_free(&s->tx_fifo)) {
size = fifo8_num_free(&s->tx_fifo);
qemu_log_mask(LOG_GUEST_ERROR, "sifive_uart: TX FIFO overflow");
@@ -128,8 +141,7 @@ static void sifive_uart_write_tx_fifo(SiFiveUARTState *s, const uint8_t *buf,
s->txfifo |= SIFIVE_UART_TXFIFO_FULL;
}
timer_mod(s->fifo_trigger_handle, current_time +
TX_INTERRUPT_TRIGGER_DELAY_NS);
sifive_uart_trigger_tx_fifo(s);
}
static uint64_t
@@ -186,6 +198,9 @@ sifive_uart_write(void *opaque, hwaddr addr,
return;
case SIFIVE_UART_TXCTRL:
s->txctrl = val64;
if (SIFIVE_UART_TXEN(s->txctrl) && !fifo8_is_empty(&s->tx_fifo)) {
sifive_uart_trigger_tx_fifo(s);
}
return;
case SIFIVE_UART_RXCTRL:
s->rxctrl = val64;
@@ -233,7 +248,7 @@ static int sifive_uart_can_rx(void *opaque)
{
SiFiveUARTState *s = opaque;
return s->rx_fifo_len < sizeof(s->rx_fifo);
return SIFIVE_UART_RXEN(s->rxctrl) && (s->rx_fifo_len < sizeof(s->rx_fifo));
}
static void sifive_uart_event(void *opaque, QEMUChrEvent event)
+7 -27
View File
@@ -344,22 +344,16 @@ void virtio_serial_throttle_port(VirtIOSerialPort *port, bool throttle)
}
/* Guest wants to notify us of some event */
static void handle_control_message(VirtIOSerial *vser, void *buf, size_t len)
static void handle_control_message(VirtIOSerial *vser,
struct virtio_console_control *gcpkt)
{
VirtIODevice *vdev = VIRTIO_DEVICE(vser);
struct VirtIOSerialPort *port;
VirtIOSerialPortClass *vsc;
struct virtio_console_control cpkt, *gcpkt;
struct virtio_console_control cpkt;
uint8_t *buffer;
size_t buffer_len;
gcpkt = buf;
if (len < sizeof(cpkt)) {
/* The guest sent an invalid control packet */
return;
}
cpkt.event = virtio_lduw_p(vdev, &gcpkt->event);
cpkt.value = virtio_lduw_p(vdev, &gcpkt->value);
@@ -457,41 +451,27 @@ static void control_in(VirtIODevice *vdev, VirtQueue *vq)
static void control_out(VirtIODevice *vdev, VirtQueue *vq)
{
struct virtio_console_control cpkt;
VirtQueueElement *elem;
VirtIOSerial *vser;
uint8_t *buf;
size_t len;
vser = VIRTIO_SERIAL(vdev);
len = 0;
buf = NULL;
for (;;) {
size_t cur_len;
elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
if (!elem) {
break;
}
cur_len = iov_size(elem->out_sg, elem->out_num);
/*
* Allocate a new buf only if we didn't have one previously or
* if the size of the buf differs
*/
if (cur_len > len) {
g_free(buf);
buf = g_malloc(cur_len);
len = cur_len;
len = iov_to_buf(elem->out_sg, elem->out_num, 0, &cpkt, sizeof(cpkt));
if (len == sizeof(cpkt)) {
handle_control_message(vser, &cpkt);
}
iov_to_buf(elem->out_sg, elem->out_num, 0, buf, cur_len);
handle_control_message(vser, buf, cur_len);
virtqueue_push(vq, elem, 0);
g_free(elem);
}
g_free(buf);
virtio_notify(vdev, vq);
}
+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);
+8 -1
View File
@@ -157,7 +157,14 @@ Clock *qdev_alias_clock(DeviceState *dev, const char *name,
DeviceState *alias_dev, const char *alias_name)
{
NamedClockList *ncl = qdev_get_clocklist(dev, name);
Clock *clk = ncl->clock;
Clock *clk;
if (!ncl) {
error_report("Can not find clock '%s' for device type '%s'",
name, object_get_typename(OBJECT(dev)));
abort();
}
clk = ncl->clock;
ncl = qdev_init_clocklist(alias_dev, alias_name, true, ncl->output, clk);
+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'],
+20 -12
View File
@@ -217,7 +217,8 @@ void qxl_render_update_area_done(PCIQXLDevice *qxl, QXLCookie *cookie)
}
static void qxl_unpack_chunks(void *dest, size_t size, PCIQXLDevice *qxl,
QXLDataChunk *chunk, uint32_t group_id)
QXLDataChunk *chunk, uint32_t group_id,
uint32_t chunk_data_size)
{
uint32_t max_chunks = 32;
size_t offset = 0;
@@ -225,22 +226,21 @@ static void qxl_unpack_chunks(void *dest, size_t size, PCIQXLDevice *qxl,
QXLPHYSICAL next_chunk_phys = 0;
for (;;) {
bytes = MIN(size - offset, chunk->data_size);
bytes = MIN(size - offset, chunk_data_size);
memcpy(dest + offset, chunk->data, bytes);
offset += bytes;
if (offset == size) {
return;
}
next_chunk_phys = chunk->next_chunk;
/* fist time, only get the next chunk's data size */
chunk = qxl_phys2virt(qxl, next_chunk_phys, group_id,
sizeof(QXLDataChunk));
if (!chunk) {
return;
}
/* second time, check data size and get data */
chunk_data_size = chunk->data_size;
chunk = qxl_phys2virt(qxl, next_chunk_phys, group_id,
sizeof(QXLDataChunk) + chunk->data_size);
sizeof(QXLDataChunk) + chunk_data_size);
if (!chunk) {
return;
}
@@ -252,7 +252,7 @@ static void qxl_unpack_chunks(void *dest, size_t size, PCIQXLDevice *qxl,
}
static QEMUCursor *qxl_cursor(PCIQXLDevice *qxl, QXLCursor *cursor,
uint32_t group_id)
uint32_t group_id, uint32_t chunk_data_size)
{
QEMUCursor *c;
uint8_t *and_mask, *xor_mask;
@@ -272,9 +272,11 @@ static QEMUCursor *qxl_cursor(PCIQXLDevice *qxl, QXLCursor *cursor,
case SPICE_CURSOR_TYPE_MONO:
/* Assume that the full cursor is available in a single chunk. */
size = 2 * cursor_get_mono_bpl(c) * c->height;
if (size != cursor->data_size) {
fprintf(stderr, "%s: bad monochrome cursor %ux%u with size %u\n",
__func__, c->width, c->height, cursor->data_size);
if (size != cursor->data_size || chunk_data_size < size) {
qxl_set_guest_bug(qxl, "%s: bad monochrome cursor %ux%u"
" data_size %u chunk_size %u",
__func__, c->width, c->height,
cursor->data_size, chunk_data_size);
goto fail;
}
and_mask = cursor->chunk.data;
@@ -286,7 +288,8 @@ static QEMUCursor *qxl_cursor(PCIQXLDevice *qxl, QXLCursor *cursor,
break;
case SPICE_CURSOR_TYPE_ALPHA:
size = sizeof(uint32_t) * c->width * c->height;
qxl_unpack_chunks(c->data, size, qxl, &cursor->chunk, group_id);
qxl_unpack_chunks(c->data, size, qxl, &cursor->chunk, group_id,
chunk_data_size);
if (qxl->debug > 2) {
cursor_print_ascii_art(c, "qxl/alpha");
}
@@ -323,19 +326,23 @@ int qxl_render_cursor(PCIQXLDevice *qxl, QXLCommandExt *ext)
}
switch (cmd->type) {
case QXL_CURSOR_SET:
{
uint32_t chunk_data_size;
/* First read the QXLCursor to get QXLDataChunk::data_size ... */
cursor = qxl_phys2virt(qxl, cmd->u.set.shape, ext->group_id,
sizeof(QXLCursor));
if (!cursor) {
return 1;
}
chunk_data_size = cursor->chunk.data_size;
/* Then read including the chunked data following QXLCursor. */
cursor = qxl_phys2virt(qxl, cmd->u.set.shape, ext->group_id,
sizeof(QXLCursor) + cursor->chunk.data_size);
sizeof(QXLCursor) + chunk_data_size);
if (!cursor) {
return 1;
}
c = qxl_cursor(qxl, cursor, ext->group_id);
c = qxl_cursor(qxl, cursor, ext->group_id, chunk_data_size);
if (c == NULL) {
c = cursor_builtin_left_ptr();
}
@@ -349,6 +356,7 @@ int qxl_render_cursor(PCIQXLDevice *qxl, QXLCommandExt *ext)
qemu_mutex_unlock(&qxl->ssd.lock);
qemu_bh_schedule(qxl->ssd.cursor_bh);
break;
}
case QXL_CURSOR_MOVE:
qemu_mutex_lock(&qxl->ssd.lock);
qxl->ssd.mouse_x = cmd->u.position.x;
+1 -1
View File
@@ -275,7 +275,7 @@ static void qxl_spice_monitors_config_async(PCIQXLDevice *qxl, int replay)
}
cfg = qxl_phys2virt(qxl, qxl->guest_monitors_config, MEMSLOT_GROUP_GUEST,
sizeof(QXLMonitorsConfig));
sizeof(QXLMonitorsConfig) + sizeof(QXLHead));
if (cfg != NULL && cfg->count == 1) {
qxl->guest_primary.resized = 1;
qxl->guest_head0_width = cfg->heads[0].width;
+55 -9
View File
@@ -570,6 +570,25 @@ static uint32_t get_local_mem_size_index(uint32_t size)
return index;
}
static void set_new_local_mem_size_index(SM501State *s, uint32_t idx)
{
/*
* Update local_mem_size_index on guest write. We don't allow this
* to be set to larger than the actual RAM size. (The guest will
* still read back the SYSTEM_CONTROL.Size bits that it wrote.)
*/
if (idx < ARRAY_SIZE(sm501_mem_local_size) &&
sm501_mem_local_size[idx] <= memory_region_size(&s->local_mem_region)) {
s->local_mem_size_index = idx;
return;
}
qemu_log_mask(LOG_GUEST_ERROR,
"sm501: Guest set DRAM_CONTROL.Size to 0x%x but "
"local memory is not that large\n",
idx);
/* Don't change the effective size, leave it as whatever it was */
}
static ram_addr_t get_fb_addr(SM501State *s, int crt)
{
return (crt ? s->dc_crt_fb_addr : s->dc_panel_fb_addr) & 0x3FFFFF0;
@@ -681,6 +700,28 @@ static inline void hwc_invalidate(SM501State *s, int crt)
get_fb_addr(s, crt) + start, end - start);
}
static bool sm501_rect_outside_vram(SM501State *s, uint32_t base,
uint32_t x, uint32_t y,
uint32_t width, uint32_t height,
uint32_t pitch, uint32_t bypp)
{
/*
* Return true if the 2D area specified by the arguments is
* partially or completely outside the VRAM (a guest error)
*
* Limits on the input sizes mean we can't overflow as long as
* we do all the arithmetic at 64 bits.
*/
uint64_t rect_size, last_addr;
assert(x <= UINT16_MAX && y <= UINT16_MAX && height <= UINT16_MAX &&
pitch <= UINT16_MAX && bypp <= 8);
rect_size = (((uint64_t)y + height) * pitch + x + width) * bypp;
last_addr = base + rect_size;
return last_addr >= get_local_mem_size(s);
}
static void sm501_2d_operation(SM501State *s)
{
int cmd = (s->twoD_control >> 16) & 0x1F;
@@ -722,13 +763,16 @@ static void sm501_2d_operation(SM501State *s)
}
if (rtl) {
if (dst_x < (width - 1) || dst_y < (height - 1)) {
qemu_log_mask(LOG_GUEST_ERROR, "sm501: RTL op out of bounds\n");
return;
}
dst_x -= width - 1;
dst_y -= height - 1;
}
if (dst_base >= get_local_mem_size(s) ||
dst_base + (dst_x + width + (dst_y + height) * dst_pitch) * bypp >=
get_local_mem_size(s)) {
if (sm501_rect_outside_vram(s, dst_base, dst_x, dst_y, width, height,
dst_pitch, bypp)) {
qemu_log_mask(LOG_GUEST_ERROR, "sm501: 2D op dest is outside vram.\n");
return;
}
@@ -747,13 +791,16 @@ static void sm501_2d_operation(SM501State *s)
}
if (rtl) {
if (src_x < (width - 1) || src_y < (height - 1)) {
qemu_log_mask(LOG_GUEST_ERROR, "sm501: RTL op out of bounds\n");
return;
}
src_x -= width - 1;
src_y -= height - 1;
}
if (src_base >= get_local_mem_size(s) ||
src_base + (src_x + width + (src_y + height) * src_pitch) * bypp >=
get_local_mem_size(s)) {
if (sm501_rect_outside_vram(s, src_base, src_x, src_y, width, height,
src_pitch, bypp)) {
qemu_log_mask(LOG_GUEST_ERROR,
"sm501: 2D op src is outside vram.\n");
return;
@@ -961,7 +1008,7 @@ static uint64_t sm501_system_config_read(void *opaque, hwaddr addr,
ret = 0x050100A0;
break;
case SM501_DRAM_CONTROL:
ret = (s->dram_control & 0x07F107C0) | s->local_mem_size_index << 13;
ret = (s->dram_control & 0x07F1E7C0);
break;
case SM501_ARBTRTN_CONTROL:
ret = s->arbitration_control;
@@ -1020,8 +1067,7 @@ static void sm501_system_config_write(void *opaque, hwaddr addr,
s->gpio_63_32_control = value & 0xFF80FFFF;
break;
case SM501_DRAM_CONTROL:
s->local_mem_size_index = (value >> 13) & 0x7;
/* TODO : check validity of size change */
set_new_local_mem_size_index(s, (value >> 13) & 0x7);
s->dram_control &= 0x80000000;
s->dram_control |= value & 0x7FFFFFC3;
break;
+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;
+9 -3
View File
@@ -351,6 +351,14 @@ rutabaga_cmd_submit_3d(VirtIOGPU *g,
VIRTIO_GPU_FILL_CMD(cs);
trace_virtio_gpu_cmd_ctx_submit(cs.hdr.ctx_id, cs.size);
if (cs.size > VIRTIO_GPU_MAX_CMD_SUBMIT_SIZE) {
qemu_log_mask(LOG_GUEST_ERROR,
"%s: command buffer too large (%u)\n",
__func__, cs.size);
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_PARAMETER;
return;
}
buf = g_new0(uint8_t, cs.size);
s = iov_to_buf(cmd->elem.out_sg, cmd->elem.out_num,
sizeof(cs), buf, cs.size);
@@ -1058,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));
}
+52 -8
View File
@@ -142,6 +142,7 @@ void virtio_gpu_init_udmabuf(struct virtio_gpu_simple_resource *res)
}
virtio_gpu_remap_udmabuf(res);
if (!res->remapped) {
virtio_gpu_destroy_udmabuf(res);
return;
}
pdata = res->remapped;
@@ -187,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,
@@ -199,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;
}
+631 -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);
@@ -486,6 +730,14 @@ static void virgl_cmd_submit_3d(VirtIOGPU *g,
VIRTIO_GPU_FILL_CMD(cs);
trace_virtio_gpu_cmd_ctx_submit(cs.hdr.ctx_id, cs.size);
if (cs.size > VIRTIO_GPU_MAX_CMD_SUBMIT_SIZE) {
qemu_log_mask(LOG_GUEST_ERROR,
"%s: command buffer too large (%u)\n",
__func__, cs.size);
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_PARAMETER;
return;
}
buf = g_malloc(cs.size);
s = iov_to_buf(cmd->elem.out_sg, cmd->elem.out_num,
sizeof(cs), buf, cs.size);
@@ -684,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;
@@ -708,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);
@@ -767,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;
@@ -785,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;
@@ -798,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);
@@ -816,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)
{
@@ -848,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"
@@ -861,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",
@@ -908,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);
@@ -962,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);
@@ -979,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) {
@@ -996,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
@@ -1058,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)
@@ -1135,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);
}
}
@@ -1157,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)
@@ -1169,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
@@ -1199,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;
@@ -1238,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;
}
+125 -14
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;
@@ -670,6 +670,10 @@ static bool virtio_gpu_do_set_scanout(VirtIOGPU *g,
void *ptr = data + fb->offset;
rect = pixman_image_create_bits(fb->format, r->width, r->height,
ptr, fb->stride);
if (!rect) {
*error = VIRTIO_GPU_RESP_ERR_UNSPEC;
return false;
}
if (res->image) {
pixman_image_ref(res->image);
@@ -1057,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;
}
@@ -1119,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));
}
@@ -1336,8 +1353,15 @@ static int virtio_gpu_load(QEMUFile *f, void *opaque, size_t size,
return -EINVAL;
}
res->addrs = g_new(uint64_t, res->iov_cnt);
res->iov = g_new(struct iovec, res->iov_cnt);
res->addrs = g_try_new(uint64_t, res->iov_cnt);
res->iov = g_try_new(struct iovec, res->iov_cnt);
if (res->iov_cnt && (!res->addrs || !res->iov)) {
pixman_image_unref(res->image);
g_free(res->addrs);
g_free(res->iov);
g_free(res);
return -EINVAL;
}
/* read data */
for (i = 0; i < res->iov_cnt; i++) {
@@ -1409,8 +1433,15 @@ static int virtio_gpu_blob_load(QEMUFile *f, void *opaque, size_t size,
res->resource_id = resource_id;
res->blob_size = qemu_get_be32(f);
res->iov_cnt = qemu_get_be32(f);
res->addrs = g_new(uint64_t, res->iov_cnt);
res->iov = g_new(struct iovec, res->iov_cnt);
res->addrs = g_try_new(uint64_t, res->iov_cnt);
res->iov = g_try_new(struct iovec, res->iov_cnt);
if (res->iov_cnt && (!res->addrs || !res->iov)) {
g_free(res->addrs);
g_free(res->iov);
g_free(res);
return -EINVAL;
}
/* read data */
for (i = 0; i < res->iov_cnt; i++) {
@@ -1485,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;
}
@@ -1519,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,
@@ -1579,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 */
+13
View File
@@ -406,6 +406,19 @@ static int i8257_dma_read_memory(IsaDma *obj, int nchan, void *buf, int pos,
hwaddr addr = ((r->pageh & 0x7f) << 24) | (r->page << 16) | r->now[ADDR];
if (i8257_is_verify_transfer(r)) {
/*
* If the device is expecting this verify operation then
* it won't care about the nonexistent data. But if it
* is expecting a real read (i.e. the guest has misprogrammed
* the DMA controller and the device) it's going to try to do
* something with the buffer contents. Give it zeroes.
* (It's not clear whether this is exactly what happens if
* you do this on real hardware. In practice no device QEMU
* emulates has a use for verify on a memory-read transfer,
* so we don't care beyond avoiding the guest being able to
* trigger the caller reading uninitialized data.)
*/
memset(buf, 0, len);
return len;
}
+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
+5 -3
View File
@@ -583,12 +583,12 @@ static void amdvi_cmdbuf_run(AMDVIState *s)
trace_amdvi_command_exec(s->cmdbuf_head, s->cmdbuf_tail, s->cmdbuf);
amdvi_cmdbuf_exec(s);
s->cmdbuf_head += AMDVI_COMMAND_SIZE;
amdvi_writeq_raw(s, AMDVI_MMIO_COMMAND_HEAD, s->cmdbuf_head);
/* wrap head pointer */
if (s->cmdbuf_head >= s->cmdbuf_len * AMDVI_COMMAND_SIZE) {
s->cmdbuf_head = 0;
}
amdvi_writeq_raw(s, AMDVI_MMIO_COMMAND_HEAD, s->cmdbuf_head);
}
}
@@ -674,7 +674,8 @@ static inline void amdvi_handle_devtab_write(AMDVIState *s)
static inline void amdvi_handle_cmdhead_write(AMDVIState *s)
{
s->cmdbuf_head = amdvi_readq(s, AMDVI_MMIO_COMMAND_HEAD)
& AMDVI_MMIO_CMDBUF_HEAD_MASK;
& AMDVI_MMIO_CMDBUF_HEAD_MASK
& (s->cmdbuf_len * AMDVI_COMMAND_SIZE - 1);
amdvi_cmdbuf_run(s);
}
@@ -690,7 +691,8 @@ static inline void amdvi_handle_cmdbase_write(AMDVIState *s)
static inline void amdvi_handle_cmdtail_write(AMDVIState *s)
{
s->cmdbuf_tail = amdvi_readq(s, AMDVI_MMIO_COMMAND_TAIL)
& AMDVI_MMIO_CMDBUF_TAIL_MASK;
& AMDVI_MMIO_CMDBUF_TAIL_MASK
& (s->cmdbuf_len * AMDVI_COMMAND_SIZE - 1);
amdvi_cmdbuf_run(s);
}
+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);
}
+3
View File
@@ -740,6 +740,9 @@ static bool ahci_map_clb_address(AHCIDevice *ad)
static void ahci_unmap_clb_address(AHCIDevice *ad)
{
/* Cancel in-flight reads that would complete against a cleared cur_cmd. */
ide_cancel_dma_sync(ide_bus_active_if(&ad->port));
if (ad->lst == NULL) {
trace_ahci_unmap_clb_address_null(ad->hba, ad->port_no);
return;
+8 -9
View File
@@ -659,13 +659,6 @@ static void apic_deliver(DeviceState *dev, uint32_t dest, uint8_t dest_mode,
APICCommonState *apic_iter;
uint32_t deliver_bitmask_size = max_apic_words * sizeof(uint32_t);
g_autofree uint32_t *deliver_bitmask = g_new(uint32_t, max_apic_words);
uint32_t current_apic_id;
if (is_x2apic_mode(dev)) {
current_apic_id = s->initial_apic_id;
} else {
current_apic_id = s->id;
}
switch (dest_shorthand) {
case 0:
@@ -673,14 +666,20 @@ static void apic_deliver(DeviceState *dev, uint32_t dest, uint8_t dest_mode,
break;
case 1:
memset(deliver_bitmask, 0x00, deliver_bitmask_size);
apic_set_bit(deliver_bitmask, current_apic_id);
/*
* The self and all-but-self cases do not use apic_match_dest() and
* directly fill in deliver_bitmask; the bitmask's indexes in turn
* map to local_apics[] slots which are never changed even if the
* xAPIC id is modified. So use s->initial_apic_id instead of s->id.
*/
apic_set_bit(deliver_bitmask, s->initial_apic_id);
break;
case 2:
memset(deliver_bitmask, 0xff, deliver_bitmask_size);
break;
case 3:
memset(deliver_bitmask, 0xff, deliver_bitmask_size);
apic_reset_bit(deliver_bitmask, current_apic_id);
apic_reset_bit(deliver_bitmask, s->initial_apic_id);
break;
}
+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
}
+3 -3
View File
@@ -333,9 +333,9 @@ static void applesmc_isa_realize(DeviceState *dev, Error **errp)
applesmc_add_key(s, "REV ", 6, "\x01\x13\x0f\x00\x00\x03");
applesmc_add_key(s, "OSK0", 32, s->osk);
applesmc_add_key(s, "OSK1", 32, s->osk + 32);
applesmc_add_key(s, "NATJ", 1, "\0");
applesmc_add_key(s, "MSSP", 1, "\0");
applesmc_add_key(s, "MSSD", 1, "\0x3");
applesmc_add_key(s, "NATJ", 1, "\x00");
applesmc_add_key(s, "MSSP", 1, "\x00");
applesmc_add_key(s, "MSSD", 1, "\x03");
}
static void applesmc_unrealize(DeviceState *dev)
+14 -10
View File
@@ -103,7 +103,7 @@ static void edu_lower_irq(EduState *edu, uint32_t val)
}
}
static void edu_check_range(uint64_t xfer_start, uint64_t xfer_size,
static bool edu_check_range(uint64_t xfer_start, uint64_t xfer_size,
uint64_t dma_start, uint64_t dma_size)
{
uint64_t xfer_end = xfer_start + xfer_size;
@@ -115,13 +115,15 @@ static void edu_check_range(uint64_t xfer_start, uint64_t xfer_size,
*/
if (dma_end >= dma_start && xfer_end >= xfer_start &&
xfer_start >= dma_start && xfer_end <= dma_end) {
return;
return true;
}
qemu_log_mask(LOG_GUEST_ERROR,
"EDU: DMA range 0x%016"PRIx64"-0x%016"PRIx64
" out of bounds (0x%016"PRIx64"-0x%016"PRIx64")!",
xfer_start, xfer_end - 1, dma_start, dma_end - 1);
return false;
}
static dma_addr_t edu_clamp_addr(const EduState *edu, dma_addr_t addr)
@@ -148,16 +150,18 @@ static void edu_dma_timer(void *opaque)
if (EDU_DMA_DIR(edu->dma.cmd) == EDU_DMA_FROM_PCI) {
uint64_t dst = edu->dma.dst;
edu_check_range(dst, edu->dma.cnt, DMA_START, DMA_SIZE);
dst -= DMA_START;
pci_dma_read(&edu->pdev, edu_clamp_addr(edu, edu->dma.src),
edu->dma_buf + dst, edu->dma.cnt);
if (edu_check_range(dst, edu->dma.cnt, DMA_START, DMA_SIZE)) {
dst -= DMA_START;
pci_dma_read(&edu->pdev, edu_clamp_addr(edu, edu->dma.src),
edu->dma_buf + dst, edu->dma.cnt);
}
} else {
uint64_t src = edu->dma.src;
edu_check_range(src, edu->dma.cnt, DMA_START, DMA_SIZE);
src -= DMA_START;
pci_dma_write(&edu->pdev, edu_clamp_addr(edu, edu->dma.dst),
edu->dma_buf + src, edu->dma.cnt);
if (edu_check_range(src, edu->dma.cnt, DMA_START, DMA_SIZE)) {
src -= DMA_START;
pci_dma_write(&edu->pdev, edu_clamp_addr(edu, edu->dma.dst),
edu->dma_buf + src, edu->dma.cnt);
}
}
edu->dma.cmd &= ~EDU_DMA_RUN;
+6
View File
@@ -920,6 +920,9 @@ static void ivshmem_exit(PCIDevice *dev)
IVShmemState *s = IVSHMEM_COMMON(dev);
int i;
qemu_chr_fe_set_handlers(&s->server_chr,
NULL, NULL, NULL, NULL, NULL, NULL, true);
migrate_del_blocker(&s->migration_blocker);
if (memory_region_is_mapped(s->ivshmem_bar2)) {
@@ -948,6 +951,8 @@ static void ivshmem_exit(PCIDevice *dev)
close_peer_eventfds(s, i);
}
g_free(s->peers);
s->peers = NULL;
s->nb_peers = 0;
}
if (ivshmem_has_feature(s, IVSHMEM_MSI)) {
@@ -955,6 +960,7 @@ static void ivshmem_exit(PCIDevice *dev)
}
g_free(s->msi_vectors);
s->msi_vectors = NULL;
}
static int ivshmem_pre_load(void *opaque)
+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 = {
+27 -4
View File
@@ -53,6 +53,27 @@ static uint64_t stm32_rcc_read(void *opaque, hwaddr addr, unsigned int size)
return value;
}
static int reg_offset_to_irq_offset(hwaddr addr)
{
/*
* The reset and enable registers aren't all consecutive. In getting the
* irq index from the register offset, we need to account for the gap
* between the AHB regs and the APB regs.
*/
switch (addr) {
case STM32_RCC_AHB1_RSTR ... STM32_RCC_AHB3_RSTR:
return ((addr - STM32_RCC_AHB1_RSTR) / 4) * 32;
case STM32_RCC_APB1_RSTR ... STM32_RCC_APB2_RSTR:
return ((addr - STM32_RCC_APB1_RSTR) / 4) * 32 + STM32_RCC_N_AHB_IRQS;
case STM32_RCC_AHB1_ENR ... STM32_RCC_AHB3_ENR:
return ((addr - STM32_RCC_AHB1_ENR) / 4) * 32;
case STM32_RCC_APB1_ENR ... STM32_RCC_APB2_ENR:
return ((addr - STM32_RCC_APB1_ENR) / 4) * 32 + STM32_RCC_N_AHB_IRQS;
default:
g_assert_not_reached();
}
}
static void stm32_rcc_write(void *opaque, hwaddr addr,
uint64_t val64, unsigned int size)
{
@@ -69,11 +90,12 @@ static void stm32_rcc_write(void *opaque, hwaddr addr,
}
switch (addr) {
case STM32_RCC_AHB1_RSTR...STM32_RCC_APB2_RSTR:
case STM32_RCC_AHB1_RSTR ... STM32_RCC_AHB3_RSTR:
case STM32_RCC_APB1_RSTR ... STM32_RCC_APB2_RSTR:
prev_value = s->regs[addr / 4];
s->regs[addr / 4] = value;
irq_offset = ((addr - STM32_RCC_AHB1_RSTR) / 4) * 32;
irq_offset = reg_offset_to_irq_offset(addr);
for (int i = 0; i < 32; i++) {
new_value = extract32(value, i, 1);
if (extract32(prev_value, i, 1) && !new_value) {
@@ -82,11 +104,12 @@ static void stm32_rcc_write(void *opaque, hwaddr addr,
}
}
return;
case STM32_RCC_AHB1_ENR...STM32_RCC_APB2_ENR:
case STM32_RCC_AHB1_ENR ... STM32_RCC_AHB3_ENR:
case STM32_RCC_APB1_ENR ... STM32_RCC_APB2_ENR:
prev_value = s->regs[addr / 4];
s->regs[addr / 4] = value;
irq_offset = ((addr - STM32_RCC_AHB1_ENR) / 4) * 32;
irq_offset = reg_offset_to_irq_offset(addr);
for (int i = 0; i < 32; i++) {
new_value = extract32(value, i, 1);
if (!extract32(prev_value, i, 1) && new_value) {
+16 -1
View File
@@ -1469,6 +1469,8 @@ static void gem_reset(DeviceState *d)
/* Set post reset register values */
memset(&s->regs[0], 0, sizeof(s->regs));
memset(&s->rx_desc_addr[0], 0, sizeof(s->rx_desc_addr));
memset(&s->tx_desc_addr[0], 0, sizeof(s->tx_desc_addr));
s->regs[R_NWCFG] = 0x00080000;
s->regs[R_NWSTATUS] = 0x00000006;
s->regs[R_DMACFG] = 0x00020784;
@@ -1582,9 +1584,22 @@ static uint64_t gem_read(void *opaque, hwaddr offset, unsigned size)
offset >>= 2;
retval = s->regs[offset];
DB_PRINT("offset: 0x%04x read: 0x%08x\n", (unsigned)offset*4, retval);
DB_PRINT("offset: 0x%04x read: 0x%08x\n", (unsigned)offset * 4,
retval);
switch (offset) {
case R_RXQBASE:
retval = s->rx_desc_addr[0];
break;
case R_TXQBASE:
retval = s->tx_desc_addr[0];
break;
case R_TRANSMIT_Q1_PTR ... R_TRANSMIT_Q7_PTR:
retval = s->tx_desc_addr[offset - R_TRANSMIT_Q1_PTR + 1];
break;
case R_RECEIVE_Q1_PTR ... R_RECEIVE_Q7_PTR:
retval = s->rx_desc_addr[offset - R_RECEIVE_Q1_PTR + 1];
break;
case R_ISR:
DB_PRINT("lowering irqs on ISR read\n");
/* The interrupts get updated at the end of the function. */
+21 -6
View File
@@ -175,16 +175,31 @@ static void tx_padding_and_crc(eTSEC *etsec, uint32_t min_frame_len)
static void process_tx_fcb(eTSEC *etsec)
{
uint8_t flags = (uint8_t)(*etsec->tx_buffer);
/* L3 header offset from start of frame */
/* L3 header offset from start of frame (FCB byte 3) */
uint8_t l3_header_offset = (uint8_t)*(etsec->tx_buffer + 3);
/* L4 header offset from start of L3 header */
/* L4 header offset from start of L3 header (FCB byte 2) */
uint8_t l4_header_offset = (uint8_t)*(etsec->tx_buffer + 2);
/* L3 header */
uint8_t *l3_header = etsec->tx_buffer + 8 + l3_header_offset;
/* L4 header */
uint8_t *l4_header = l3_header + l4_header_offset;
uint8_t *l3_header;
uint8_t *l4_header;
int csum = 0;
/*
* Validate FCB header offsets before pointer arithmetic. The highest
* byte accessed is l4_header[7], at offset
* 8 (FCB size) + l3_header_offset + l4_header_offset + 7
* from tx_buffer. Drop the frame if this exceeds the buffer length.
*/
if (etsec->tx_buffer_len < 8u + l3_header_offset + l4_header_offset + 8u) {
qemu_log_mask(LOG_GUEST_ERROR,
"eTSEC: FCB offsets exceed frame length, dropping\n");
return;
}
/* L3 header */
l3_header = etsec->tx_buffer + 8 + l3_header_offset;
/* L4 header */
l4_header = l3_header + l4_header_offset;
/* if packet is IP4 and IP checksum is requested */
if (flags & FCB_TX_IP && flags & FCB_TX_CIP) {
csum |= CSUM_IP;
+3 -4
View File
@@ -93,9 +93,6 @@ void net_tx_pkt_update_ip_hdr_checksum(struct NetTxPkt *pkt)
uint16_t csum;
assert(pkt);
pkt->l3_hdr.ip.ip_len = cpu_to_be16(pkt->payload_len +
pkt->vec[NET_TX_PKT_L3HDR_FRAG].iov_len);
pkt->l3_hdr.ip.ip_sum = 0;
csum = net_raw_checksum(pkt->l3_hdr.octets,
pkt->vec[NET_TX_PKT_L3HDR_FRAG].iov_len);
@@ -117,7 +114,9 @@ void net_tx_pkt_update_ip_checksums(struct NetTxPkt *pkt)
if (gso_type == VIRTIO_NET_HDR_GSO_TCPV4 ||
gso_type == VIRTIO_NET_HDR_GSO_UDP) {
/* Calculate IP header checksum */
/* Set ip_len and calculate IP header checksum */
pkt->l3_hdr.ip.ip_len = cpu_to_be16(pkt->payload_len +
pkt->vec[NET_TX_PKT_L3HDR_FRAG].iov_len);
net_tx_pkt_update_ip_hdr_checksum(pkt);
/* Calculate IP pseudo header checksum */
+10 -6
View File
@@ -99,13 +99,13 @@ typedef struct of_dpa_flow_key {
} nd;
} ipv6;
};
int width; /* how many uint64_t's in key? */
int width; /* how many uint32_t's in key? */
} OfDpaFlowKey;
/* Width of key which includes field 'f' in u64s, rounded up */
/* Width of key which includes field 'f' in u32s, rounded up */
#define FLOW_KEY_WIDTH(f) \
DIV_ROUND_UP(offsetof(OfDpaFlowKey, f) + sizeof_field(OfDpaFlowKey, f), \
sizeof(uint64_t))
sizeof(uint32_t))
typedef struct of_dpa_flow_action {
uint32_t goto_tbl;
@@ -308,9 +308,9 @@ static void _of_dpa_flow_match(void *key, void *value, void *user_data)
{
OfDpaFlow *flow = value;
OfDpaFlowMatch *match = user_data;
uint64_t *k = (uint64_t *)&flow->key;
uint64_t *m = (uint64_t *)&flow->mask;
uint64_t *v = (uint64_t *)&match->value;
uint32_t *k = (uint32_t *)&flow->key;
uint32_t *m = (uint32_t *)&flow->mask;
uint32_t *v = (uint32_t *)&match->value;
int i;
if (flow->key.tbl_id == match->value.tbl_id) {
@@ -2033,6 +2033,10 @@ static int of_dpa_cmd_add_l2_flood(OfDpa *of_dpa, OfDpaGroup *group,
group_tlvs[ROCKER_TLV_OF_DPA_GROUP_IDS]);
for (i = 0; i < group->l2_flood.group_count; i++) {
if (!tlvs[i + 1]) {
err = -ROCKER_EINVAL;
goto err_out;
}
group->l2_flood.group_ids[i] = rocker_tlv_get_le32(tlvs[i + 1]);
}
+22 -7
View File
@@ -1380,6 +1380,11 @@ static void virtio_net_unload_ebpf(VirtIONet *n)
ebpf_rss_unload(&n->ebpf_rss);
}
static bool virtio_net_rss_indirections_len_valid(uint16_t len)
{
return is_power_of_2(len) && len <= VIRTIO_NET_RSS_MAX_TABLE_LEN;
}
static uint16_t virtio_net_handle_rss(VirtIONet *n,
struct iovec *iov,
unsigned int iov_cnt,
@@ -1417,14 +1422,9 @@ static uint16_t virtio_net_handle_rss(VirtIONet *n,
if (!do_rss) {
n->rss_data.indirections_len = 0;
}
if (n->rss_data.indirections_len >= VIRTIO_NET_RSS_MAX_TABLE_LEN) {
err_msg = "Too large indirection table";
err_value = n->rss_data.indirections_len;
goto error;
}
n->rss_data.indirections_len++;
if (!is_power_of_2(n->rss_data.indirections_len)) {
err_msg = "Invalid size of indirection table";
if (!virtio_net_rss_indirections_len_valid(n->rss_data.indirections_len)) {
err_msg = "Invalid indirection table length";
err_value = n->rss_data.indirections_len;
goto error;
}
@@ -3311,6 +3311,20 @@ static const VMStateDescription vmstate_virtio_net_has_vnet = {
},
};
static int virtio_net_rss_post_load(void *opaque, int version_id)
{
VirtIONet *n = VIRTIO_NET(opaque);
if (!virtio_net_rss_indirections_len_valid(n->rss_data.indirections_len)) {
error_report("virtio-net: saved image has invalid RSS "
"indirections_len: %u",
n->rss_data.indirections_len);
return -EINVAL;
}
return 0;
}
static bool virtio_net_rss_needed(void *opaque)
{
return VIRTIO_NET(opaque)->rss_data.enabled;
@@ -3320,6 +3334,7 @@ static const VMStateDescription vmstate_virtio_net_rss = {
.name = "virtio-net-device/rss",
.version_id = 1,
.minimum_version_id = 1,
.post_load = virtio_net_rss_post_load,
.needed = virtio_net_rss_needed,
.fields = (const VMStateField[]) {
VMSTATE_BOOL(rss_data.enabled, VirtIONet),
+1 -1
View File
@@ -1092,7 +1092,7 @@ vmxnet3_io_bar0_write(void *opaque, hwaddr addr,
int tx_queue_idx =
VMW_MULTIREG_IDX_BY_ADDR(addr, VMXNET3_REG_TXPROD,
VMXNET3_REG_ALIGN);
if (tx_queue_idx <= s->txq_num) {
if (tx_queue_idx < s->txq_num) {
vmxnet3_process_tx_queue(s, tx_queue_idx);
} else {
qemu_log_mask(LOG_GUEST_ERROR, "vmxnet3: Illegal TX queue %d/%d\n",
+3
View File
@@ -103,6 +103,9 @@ static unsigned int tdk_read(struct PHY *phy, unsigned int req)
case 17:
/* Marvell PHY on many xilinx boards. */
r = 0x8000; /* 1000Mb */
if (phy->link) {
r |= 0x0400; /* Link is up */
}
break;
case 18:
{
+29 -6
View File
@@ -1085,6 +1085,8 @@ static uint16_t nvme_map_sgl(NvmeCtrl *n, NvmeSg *sg, NvmeSglDescriptor sgl,
}
for (;;) {
size_t prev_len = len;
switch (NVME_SGL_TYPE(sgld->type)) {
case NVME_SGL_DESCR_TYPE_SEGMENT:
case NVME_SGL_DESCR_TYPE_LAST_SEGMENT:
@@ -1165,6 +1167,17 @@ static uint16_t nvme_map_sgl(NvmeCtrl *n, NvmeSg *sg, NvmeSglDescriptor sgl,
if (status) {
goto unmap;
}
/*
* Reject if this segment made no forward progress. The host should
* have skipped linking an empty segment. While not strictly spec
* compliant, allowing this makes it easy for a pathological host to
* create an infinite loop.
*/
if (len == prev_len) {
status = NVME_INVALID_SGL_SEG_DESCR | NVME_DNR;
goto unmap;
}
}
out:
@@ -6240,10 +6253,6 @@ static uint16_t nvme_get_feature_fdp_events(NvmeCtrl *n, NvmeNamespace *ns,
for (uint8_t event_type = 0; event_type < FDP_EVT_MAX; event_type++) {
uint8_t shift = nvme_fdp_evf_shifts[event_type];
if (!shift && event_type) {
/*
* only first entry (event_type == 0) has a shift value of 0
* other entries are simply unpopulated.
*/
continue;
}
@@ -6488,9 +6497,9 @@ static uint16_t nvme_set_feature_fdp_events(NvmeCtrl *n, NvmeNamespace *ns,
uint8_t noet = (cdw11 >> 16) & 0xff;
uint16_t ret, ruhid;
uint8_t enable = le32_to_cpu(cmd->cdw12) & 0x1;
uint8_t event_mask = 0;
uint64_t event_mask = 0;
unsigned int i;
g_autofree uint8_t *events = g_malloc0(noet);
g_autofree uint8_t *events = NULL;
NvmeRuHandle *ruh = NULL;
assert(ns);
@@ -6503,15 +6512,29 @@ static uint16_t nvme_set_feature_fdp_events(NvmeCtrl *n, NvmeNamespace *ns,
return NVME_INVALID_FIELD | NVME_DNR;
}
if (unlikely(noet == 0)) {
return NVME_SUCCESS;
}
ruhid = ns->fdp.phs[ph];
ruh = &n->subsys->endgrp.fdp.ruhs[ruhid];
events = g_malloc0(noet);
ret = nvme_h2c(n, events, noet, req);
if (ret) {
return ret;
}
for (i = 0; i < noet; i++) {
/*
* We ignore requests to enable tracking of unsupported FDP event types
*/
uint8_t event_type = events[i];
uint8_t shift = nvme_fdp_evf_shifts[event_type];
if (!shift && event_type) {
continue;
}
event_mask |= (1 << nvme_fdp_evf_shifts[events[i]]);
}
Loaded 100 of 339 files, more files were not shown because too many files have changed in this diff. Show more