Compare commits

...
242 Commits
Author SHA1 Message Date
Michael Tokarev 3e0bcba1ca Update version for 10.2.4 release
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-25 14:09:07 +03:00
Akshit Yadav dd0ee6af65 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:35:22 +03:00
Aditya Gupta c4bd8d7569 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:35:22 +03:00
Aditya Gupta 7f9d07e217 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:35:22 +03:00
Matt Turner bceecd60f4 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:35:22 +03:00
Matt Turner be5b3bcab8 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:35:22 +03:00
Matt Turner 35959a2e1f 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:35:22 +03:00
Ryan Zhang 5ce8ce8ae1 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:14 +03:00
Christian Schoenebeck 97455be941 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 13fb032376 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 1f6b545bf2 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:16 +03:00
Paolo Bonzini 2eccca8141 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 c9e9794efe 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 da1bd55372 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 08:32:51 +03:00
Daniel Henrique Barboza 58276e92dd 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 08:32:09 +03:00
Daniel Henrique Barboza 38f9b1ab7e target/riscv/tcg: disable svnapot if satp_mode < sv39
We did a recent change to disable svpbmt if satp_mode < sv39 that was
discovered via a gitlab report.

This time we don't have an opened bug but the problem is similar: RISC-V
privileged ISA, chapter '"Svnapot" Extension for NAPOT Translation
Contiguity, Version 1.0' states:

"The Svnapot extension depends on the Sv39 extension."

Do the same thing with svnapot, including the user warning in case we
try to enable it without the required satp_mode:

$ ./build/qemu-system-riscv64 -M virt,dumpdtb=fdt.dtb \
     -cpu max,sv39=off,sv48=off,sv57=off,sv64=off,svnapot=on
qemu-system-riscv64: warning: svnapot requires at least satp sv39, current satp mode: none

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 601c8494c6)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-17 08:31:57 +03:00
Daniel Henrique Barboza 7ff877d4a5 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 08:31:22 +03:00
Daniel Henrique Barboza ef2c884673 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 08:30:03 +03:00
Daniel Henrique Barboza 70c4653d40 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 08:29:53 +03:00
Daniel Henrique Barboza d293278f68 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 08:29:24 +03:00
Daniel Henrique Barboza 4686ecc71a 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 08:29:14 +03:00
Daniel Henrique Barboza 1b1ce90d17 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 08:28:58 +03:00
Daniel Henrique Barboza e46cde90a8 target/riscv/tcg: disable svpbmt if satp_mode < sv39
Priv spec chapter "Svpbmt Extension for Page-Based Memory Types, Version
1.0" mentions that "The Svpbmt extension depends on the Sv39
extension.".

We're not doing any satp checks when enabling svpbmt.  This causes
problems with the riscv32 'max' CPU that happens to be enabling svpbmt
even though it doesn't support the required satp mode.  In fact all rv32
CPUs are allowing menvcfg.PBMTE writes, which doesn't make sense for
them in any circunstance since svpbmt is not possible for rv32 at this
moment [1].

This also impacts rv64 CPUs that are running in satp 'bare' mode and are
reporting svpbmt in the riscv,isa.

All these problems can be solved by disabling svpbmt if satp_mode is not
at least sv39.  The problem reported in [1] goes away because we'll
never enable MENVCFG_PBMTE write mask in write_menvcfgh().  We're also
become consistent with how svpbmt is enabled for rv64.

In case the user enables svpbmt in the command line using an invalid setup,
not just disable svpbmt but also throw a warning:

$ ./build/qemu-system-riscv64 -M virt,dumpdtb=fdt.dtb \
    -cpu max,sv39=off,sv48=off,sv57=off,sv64=off,svpbmt=on
qemu-system-riscv64: warning: svpbmt requires at least satp sv39, current satp mode: none

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

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3473
Signed-off-by: Daniel Henrique Barboza <[email protected]>
Reviewed-by: Chao Liu <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit 109856754c)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-17 08:24:25 +03:00
Daniel Henrique Barboza 2b8147e719 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 99685f9b0f 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
Alejandro Jimenez 15e63b7baf amd_iommu: Reject non-decreasing NextLevel in fetch_pte()
The AMD-Vi specification requires that the NextLevel field for a page table
entry must not be greater or equal to the current page table entry level.
Enforce this to avoid infinite page walk loops on corrupted or buggy guest
page tables.

The initial implementation of fetch_pte() did not implement this check, but
was not vulnerable since the page walk code explicitly decremented the level
instead of retrieving it from the page table entry.

Cc: [email protected]
Reviewed-by: Sairaj Kodilkar <[email protected]>
Signed-off-by: Alejandro Jimenez <[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 291aa70ad2)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-16 19:16:26 +03:00
Alejandro Jimenez ad734bea5f amd_iommu: Follow root pointer before page walk and use 1-based levels
DTE[Mode] and PTE NextLevel encode page table levels as 1-based values, but
fetch_pte() currently uses a 0-based level counter, making the logic
harder to follow and requiring conversions between DTE mode and level.

Switch the page table walk logic to use 1-based level accounting in
fetch_pte() and the relevant macro helpers. To further simplify the page
walking loop, split the root page table access from the walk i.e. rework
fetch_pte() to follow the DTE Page Table Root Pointer and retrieve the top
level pagetable entry before entering the loop, then iterate only over the
PDE/PTE entries.

The reworked algorithm fixes a page walk bug where the page size was
calculated for the next level before checking if the current PTE was already
a leaf/hugepage. That caused hugepage mappings to be reported as 4K pages,
leading to performance degradation and failures in some setups.

Fixes: a74bb3110a ("amd_iommu: Add helpers to walk AMD v1 Page Table format")
Cc: [email protected]
Reported-by: David Hoppenbrouwers <[email protected]>
Reviewed-By: David Hoppenbrouwers <[email protected]>
Reviewed-by: Sairaj Kodilkar <[email protected]>
Signed-off-by: Alejandro Jimenez <[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 786550e2d3)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-16 19:16:15 +03:00
Stefano Garzarella 8dd516fb8d 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 b57a0a6074 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 e95df98116 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)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-16 17:45:53 +03:00
Alejandro Jimenez 8257e296a2 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 8f534ac546 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 6b9a3169c9 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 991a955c0f 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 c66b045e8e 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-11 23:29:20 +03:00
Xinhui Yang bb78f2e214 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)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-11 23:29:20 +03:00
Richard Henderson 60a842b7b0 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 20610cb4e2 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 e8bd35dc12 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:36 +03:00
Thomas Lamprecht a2658ebea8 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: d85e00dd03 ("qcow2: Fix corruption on discard during write with COW") in 10.2.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:51:04 +03:00
Kevin Wolf e8007fd576 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 d85e00dd03 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 b5d9c7b920 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 4868c7e2b0 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 60d7dc1e4c 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 cfcd162a25 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 6988973554 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 75186d2898 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 f133678a7e 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 1b39738f3b 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 20:57:06 +03:00
Christian Schoenebeck 4e004b7333 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 20:57:06 +03:00
Christian Schoenebeck ae1239bebe 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 20:57:06 +03:00
Christian Schoenebeck ec47de83c8 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 20:57:06 +03:00
Christian Schoenebeck 3d5a395596 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 20:57:06 +03:00
Christian Schoenebeck 98281c6c7b 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 20:57:06 +03:00
Christian Schoenebeck ac34777326 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 20:57:06 +03:00
Matt Turner 9b521ab4f8 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 1ae8a0c19b 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)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-01 20:25:10 +03:00
Matt Turner 1c90ba5f94 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 27c8d295c1 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)
Signed-off-by: Michael Tokarev <[email protected]>
2026-06-01 20:22:37 +03:00
Matt Turner ff0ec45901 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
Peter Maydell 73682aabb6 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-29 23:03:53 +03:00
Peter Maydell 2b2473835a 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-29 23:03:37 +03:00
Peter Maydell f8d04f4dac target/arm: SME BFCVT, BFCVTN have "Alternate BFloat16 behaviors"
The Arm ARM A1.5.10 notes that some instructions have "Alternate
Bfloat16 behaviors" when FPCR.AH == 1.  We implement these using the
FPST_AH and FPST_AH_F16 fp_status words.  The list includes the SME
BFVCT (single-precision to BFloat16) and BFCVTN, but we forgot to
make those use FPST_AH_F16 when we implemented them. (We get the
ASIMD and SVE insns on the list right.)

Add the missing logic to select the right FPST.

Cc: [email protected]
Fixes: 465d36db0e ("target/arm: Implement SME2 BFCVT, BFCVTN, FCVT, FCVTN")
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Peter Maydell <[email protected]>
Message-id: [email protected]
(cherry picked from commit ca33de9844)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-29 22:56:24 +03:00
Peter Maydell 1d33b6607d 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-29 22:55:59 +03:00
Richard Henderson 940dd1a30f target/arm: Enable REVD for SVE2.1
Cc: [email protected]
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 f12e7ba6f4)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-29 22:53:01 +03:00
Chenyi Qiang 72ee171628 vfio/container: Restrict dma_map_file() to shared RAM or RAM devices
vfio_container_dma_map() uses dma_map_file() whenever a RAMBlock has an
fd and the VFIO IOMMU backend supports file-based DMA mapping. That is
not correct for private file-backed guest RAM.

dma_map_file() resolves PFNs from the backing file, but private guest
RAM mappings (MAP_PRIVATE) can run on different PFNs than the file
because they are subject to copy-on-write (COW) anomalies. As a result,
using dma_map_file() on a privately mapped RAMBlock can program DMA
against pages that do not back QEMU's actual guest memory.

Fix this by using dma_map_file() only for shared mapped RAMBlocks
(MAP_SHARED) or RAM device regions.

Fixes: fb32965b6d ("vfio/iommufd: use IOMMU_IOAS_MAP_FILE")
Reported-by: Farrah Chen <[email protected]>
Closes: https://bugzilla.kernel.org/show_bug.cgi?id=220776
Reviewed-by: Zhenzhong Duan <[email protected]>
Suggested-by: Cédric Le Goater <[email protected]>
Signed-off-by: Chenyi Qiang <[email protected]>
Link: https://lore.kernel.org/qemu-devel/[email protected]
Reviewed-by: Cédric Le Goater <[email protected]>
Signed-off-by: Cédric Le Goater <[email protected]>
(cherry picked from commit e6c47bebdf)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-28 08:59:19 +03:00
Peter Maydell 6215e6cacd 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-26 22:15:29 +03:00
Peter Maydell 2cbc32cf2b 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-26 22:14:19 +03:00
Peter Maydell 75f552089a 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-26 22:11:36 +03:00
Denis V. Lunev a51b907129 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-26 22:02:11 +03:00
Jinjie Ruan 87f2e53429 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-26 22:01:46 +03:00
Paolo Bonzini 278e203a55 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)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-26 21:55:57 +03:00
Paolo Bonzini 81b834f458 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-26 21:55:57 +03:00
Paolo Bonzini 2f69229f8b 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-26 21:55:57 +03:00
Heechan Kang 5501ddefdd 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-26 18:38:17 +03:00
Daniel P. Berrangé a625c70daf 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-26 18:37:56 +03:00
Daniel P. Berrangé ed14000163 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)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-26 18:32:52 +03:00
Daniel P. Berrangé 4f22b8179f 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-26 18:32:31 +03:00
Daniel P. Berrangé 3b489576ee 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-26 18:32:31 +03:00
Matt Turner d1cd4d92e3 linux-user/mips64: fix mipsn32 elf_core_copy_regs entry width
For mipsn32 (TARGET_ABI32=y, TARGET_LONG_BITS=64):
  abi_ulong = uint32_t (4 bytes) — for pointers and ABI-sized fields
  target_ulong = uint64_t (8 bytes) — for general-purpose registers

linux-user/elfload.c allocates target_elf_prstatus using the
mips64/target_elf.h definition where target_elf_gregset_t has
target_ulong reserved[45] (8 bytes each, 360 bytes total).

However, in linux-user/mips64/elfload.c, #include "target_elf.h" inside
the included mips/elfload.c resolves to mips/target_elf.h (compiler
searches the file's own directory first), where the union uses abi_ulong
reserved[45].  For mipsn32 this gives 4-byte entries (180 bytes), not
the 8-byte entries (360 bytes) that elfload.c actually allocated.

Writing via r->reserved[34] therefore lands at byte offset 34*4=136
instead of the correct 34*8=272, silently zeroing the EPC in the core
file.

Fix by casting the pointer to target_ulong * so writes always use 8-byte
slots and land at the offsets matching the allocated layout.

This does not change behavior for mips64 (N64) where abi_ulong already
equals target_ulong (both 8 bytes).

Signed-off-by: Matt Turner <[email protected]>
Cc: [email protected]
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit 6033df08e9)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-26 18:28:47 +03:00
Matt Turner 62211ae35b linux-user/mips64: fix elf_core_copy_regs register layout in core files
mips64/elfload.c uses #include "../mips/elfload.c" to share code. When
the compiler processes mips/elfload.c the quoted #include "target_elf.h"
resolves relative to the including file's directory, so it picks up
mips/target_elf.h instead of mips64/target_elf.h.  mips/target_elf.h
pulls in mips/target_ptrace.h, whose target_pt_regs has a pad0[6] field
before regs[].  As a result elf_core_copy_regs writes:

  r->pt.regs[i]   -> reserved[6+i]   (shifted by 6 from the correct index)
  r->pt.cp0_epc   -> reserved[40]    (correct mips64 N64 index is 34)

The Linux kernel and glibc both use the mips64 N64 layout (no pad0): EPC
at reserved[34].  Debuggers and libunwind reading the core with N64
constants therefore see a completely wrong register set — EPC points to
GP, RA holds the branch target instead of the link address, etc.

Fix by:
 - Guarding the mips32 elf_core_copy_regs in mips/elfload.c with #ifndef
   TARGET_MIPS64 so it is not compiled for mips64/mipsn32 targets.
 - Providing a mips64-specific elf_core_copy_regs in mips64/elfload.c
   that writes directly to r->reserved[i] with the correct N64 indices,
   bypassing the struct field names that are tainted by the wrong header
   include.

The mipsn32 (TARGET_ABI_MIPSN32) and mips64el targets are covered by the
same mips64/elfload.c and benefit from the same fix.

Signed-off-by: Matt Turner <[email protected]>
Cc: [email protected]
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit dd3a906d35)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-26 18:20:27 +03:00
Daniel Henrique Barboza c31bf31966 target/riscv/csr.c: fix read of pmpaddr(0-63) CSRs
The priv spec defines, for RV64, that the upper 10 bits of
pmpaddr0-pmpaddr63 are WARL and are supposed to be cleared.

After this patch, using the bug reproducer in [1], writing
ffffffffffffffff in pmpaddr0 and reading it back now results in
003fffffffffffff.  Here's the 'diff -cp' dump before and after
this change:

*************** IN:
*** 5272,5278 ****
   pmpcfg10 0000000000000000
   pmpcfg12 0000000000000000
   pmpcfg14 0000000000000000
!  pmpaddr0 ffffffffffffffff
   pmpaddr1 0000000000000000
   pmpaddr2 0000000000000000
   pmpaddr3 0000000000000000
Reviewed-by: Alistair Francis <[email protected]>
Message-ID: <[email protected]>

Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit 53cc9747ed)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-26 17:11:47 +03:00
Zishun Yi 145fbcd739 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:11:47 +03:00
Alistair Francis 841b65421b 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:11:47 +03:00
Zishun Yi 3831bb79a6 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:11:47 +03:00
Zishun Yi 7c1766af7a 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:11:47 +03:00
Abhigyan Kumar 69a494b797 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:11:47 +03:00
Frank Chang b946ccbc67 hw/char: Check interrupt after txctrl register is written
It's possible that the transmit watermark level (txctrl.txcnt) is
updated when the user writes to txctrl register, which may decrease the
transmit watermark level to less than the number of entries in the
transmit FIFO. In such a case, the interrupt should be raised so we need to
call sifive_uart_update_irq() to check and update interrupt when txctrl
register is written. Otherwise, the interrupt will have to be delayed
until next TX FIFO transmission is processed.

Suggested-by: Chao Liu <[email protected]>
Signed-off-by: Frank Chang <[email protected]>
Reviewed-by: Jim Shu <[email protected]>
Reviewed-by: Alistair Francis <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit e07077a766)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-26 17:11:43 +03:00
Frank Chang e42c35ff87 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:11:12 +03:00
Anton Blanchard eb2bf63c37 target/riscv: rvv: Handle source overlap of vector widening reduction instructions
Widening reductions read vs2 as a vector of SEW elements and vs1[0] as a
scalar of 2*SEW. The ISA does not allow the same vector register to be read
with different EEWs, so they must not overlap.

vs1 is read as a scalar from element 0, so it is treated as a single vector
register (independent of LMUL) when checking overlap.

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3208
Signed-off-by: Anton Blanchard <[email protected]>
Acked-by: Alistair Francis <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit caf3bef5f0)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-26 09:56:41 +03:00
Zishun Yi f47f133a69 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 15e4d626eb 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 fd6e3f752c 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 11d81cdbb8 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
Michael Tokarev 2e7e8b7eae Update version for 10.2.3 release
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-25 20:13:18 +03:00
Denis V. Lunev 9972a3f283 block/graph-lock: fix missed wakeup in bdrv_graph_co_rdunlock()
tests/qemu-iotests/tests/iothreads-create reproduces the hang on
master under `stress-ng --cpu $(nproc) --timeout 0`.  The iotest's
vm.run_job() times out and qemu stays permanently stuck in
ppoll(timeout=-1) inside bdrv_graph_wrlock_drained -> blk_remove_bs
during qemu_cleanup().  The timing window is narrow on modern
bare-metal hardware and much wider in a VM guest; downstream trees
that still use plain bdrv_graph_wrlock() in blk_remove_bs() hit it
on the first iteration under the same stress.

bdrv_graph_wrlock() zeroes has_writer around its AIO_WAIT_WHILE loop
so that callbacks dispatched by aio_poll() can still take the read
lock on the fast path.  The rdunlock side, however, only kicks a
waiting writer when has_writer is observed set; a reader that drops
its lock inside the polling window silently returns and nothing ever
wakes the writer:

  main thread                         iothread0 coroutine
  -----------                         -------------------
  bdrv_graph_wrlock:                  rdlock held, reader_count=1
    bdrv_drain_all_begin_nopoll
    has_writer = 0
    AIO_WAIT_WHILE_UNLOCKED(
        NULL, reader_count >= 1):
      num_waiters++
      smp_mb
      aio_poll(main_ctx, true)   -->  bdrv_graph_co_rdunlock:
        (ppoll, blocked)                reader_count-- -> 0
                                        smp_mb
                                        read has_writer = 0
                                        skip aio_wait_kick()
                                      return

reader_count is now 0 and num_waiters is still 1, but no BH, fd or
timer on the main AioContext will fire -- the only entity that could
kick just decided it did not have to.  Main stays in ppoll() holding
BQL, so RCU, VCPUs and any iothread path that needs BQL stall behind
it.  The hang is final; no timeout, no forward progress, no recovery
as there is no other source of wake up inside qemu_cleanup().

bdrv_drain_all_begin() does not close the race on its own: it
quiesces in-flight I/O, but graph readers also include non-I/O
coroutines (block-job cleanup, virtio-scsi polling) that drain does
not evict.  The bdrv_graph_wrlock_drained() wrapper narrows the
window but does not eliminate it; every plain bdrv_graph_wrlock()
site is exposed on the same basis.

Drop the has_writer check in bdrv_graph_co_rdunlock() and call
aio_wait_kick() unconditionally.  The helper itself loads num_waiters
atomically and only schedules a dummy BH when a waiter exists, so the
change is a no-op on the no-writer path and closes the missed-wakeup
on the writer path.

Signed-off-by: Denis V. Lunev <[email protected]>
Cc: Kevin Wolf <[email protected]>
Cc: Hanna Reitz <[email protected]>
Cc: Stefan Hajnoczi <[email protected]>
Cc: Fiona Ebner <[email protected]>
Message-ID: <[email protected]>
Reviewed-by: Kevin Wolf <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit e3082ab3b3)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-25 20:10:19 +03:00
Kevin Wolf b7a2b41e9e commit: Drain nodes across all of bdrv_commit()
The whole implementation of bdrv_commit() is only correct if no new
writes come in while it's running: It has only a single loop checking
the allocation status for each block and finally calls bdrv_make_empty()
without checking if that throws away any new changes.

We already have to drain while taking the graph write lock. Just extend
the drained section to all of bdrv_commit() to make sure that we don't
get any inconsistencies.

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 f0d9ccd46c)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-20 11:22:34 +03:00
Kevin Wolf c75c1f83b5 block: Add more defaults to DEFAULT_BLOCK_CONF
discard_granularity was missing from this, which means that SCSI disks
created with -drive if=scsi would default to 0 (i.e. disabling discards)
instead of -1, which makes scsi-hd automatically pick a granularity and
is the default of the corresponding qdev property for -device scsi-hd.

This was broken in QEMU 9.0 with commit 3089637.

Also set other fields whose default isn't an obvious 0. These are not
actual bug fixes because ON_OFF_AUTO_AUTO in fact happens to be 0, but
it's better not to rely on the order of enums.

Cc: [email protected]
Fixes: 3089637461 ('scsi: Don't ignore most usb-storage properties')
Reported-by: Lexi Winter <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit f27aea1896)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-20 11:22:33 +03:00
Kevin Wolf 22792c426b block: Create DEFAULT_BLOCK_CONF macro
The property default values from include/hw/block/block.h were
duplicated in scsi_bus_legacy_handle_cmdline(), allowing them to go out
of sync easily. There doesn't seem a good way to avoid the duplication,
but moving them next to each other in the header file should help to
avoid this problem in the future.

Signed-off-by: Kevin Wolf <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit a1310cc628)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-20 11:22:33 +03:00
Kevin Wolf 5a6401e064 ide-test: Test reset during TRIM
This is a regression test for the bug fixed in the previous commits, a
deadlock between the drain issued by an IDE reset and the TRIM state
machine.

Signed-off-by: Kevin Wolf <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit 2fa24e9755)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-20 11:22:28 +03:00
Kevin Wolf 844b940929 ide-test: Factor out wait_dma_completion()
Signed-off-by: Kevin Wolf <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit 92854c9c75)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-20 11:22:27 +03:00
Kevin Wolf 4bae9baf39 ide: Clean up ide_trim_co_entry() to be idiomatic coroutine code
The previous commit did a minimal conversion of the callback based state
machine for TRIM to a coroutine in order to fix a bug. Refactor it to
actually look like normal coroutine based code, which improves its
readability.

Signed-off-by: Kevin Wolf <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit c1c71a7e16)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-20 11:22:27 +03:00
Kevin Wolf 792ce55e29 ide: Minimal fix for deadlock between TRIM and drain
The implementation of TRIM in IDE can chain multiple discard requests
and uses blk_inc/dec_in_flight() to make sure that the whole TRIM
operation has completed when the device needs to be quiescent (e.g. for
the drain when performing an IDE reset, it would be bad if an IDE
request like TRIM were still in flight).

The problem is that each drain request calls blk_wait_while_drained()
and when draining, it waits until the drained section ends. At the same
time, drain_begin can only return if the whole TRIM operation has
completed. This is a classic deadlock.

Use blk_co_start/end_request() and BDRV_REQ_NO_QUEUE to avoid the
problem. This requires moving the TRIM state machine to a coroutine.
This commit does the minimal conversion so that we do have a coroutine
that works for the fix, but it still looks much like a callback-based
implementation. This will be cleaned up in the next patch.

Cc: [email protected]
Fixes: 7e5cdb345f ('ide: Increment BB in-flight counter for TRIM BH')
Buglink: https://redhat.atlassian.net/browse/RHEL-121686
Signed-off-by: Kevin Wolf <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit 095c08a7ba)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-20 11:22:11 +03:00
Kevin Wolf 4e1e50b0f4 block: Add flags parameter to blk_*_pdiscard()
All existing callers pass 0, but we need a way to pass BDRV_REQ_NO_QUEUE
for discard requests.

Signed-off-by: Kevin Wolf <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit 53074ba033)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-20 11:22:08 +03:00
Kevin Wolf 794b70d024 block: Add blk_co_start/end_request() and BDRV_REQ_NO_QUEUE
If a device uses blk_inc/dec_in_flight() in order to build macro
operations that involve multiple requests for the block layer and that
need to be completed as a unit before the BlockBackend can be considered
drained, it sets the stage for a deadlock: When a drain is requested,
the inner request at the BlockBackend level will be queued in
blk_wait_while_drained() and wait until the drained section ends, but at
the same time, drain_begin can only return if the whole macro operation
at the device level has completed.

Introduce a new interface to allow implementing the logic correctly:
Instead of queueing individual requests, blk_co_start_request() calls
blk_wait_while_drained() once at the beginning. The individual requests
must then set BDRV_REQ_NO_QUEUE to avoid being queued and running into
the deadlock; being wrapped in blk_co_start/end_request() makes sure
that drain_begin waits for them and they don't sneak in when the
BlockBackend is supposed to already be quiescent.

Signed-off-by: Kevin Wolf <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit 34a6763776)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-20 11:22:08 +03:00
Kevin Wolf 94880dd3c6 blkdebug: Add 'delay-ns' option
Sometimes reproducing a problem for debugging involves slow I/O, so
let's add something to blkdebug to make I/O slow when we need it. This
can be used either together with an error so that the request fails
after the delay, or with errno=0, which allows the request to succeed
after the delay.

Signed-off-by: Kevin Wolf <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit d5e4090177)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-20 11:22:07 +03:00
Matt Turner a78df9ab50 linux-user/sh4: Fix setup_sigtramp to match Linux kernel trampoline pattern
QEMU used MOVW(2) (0x9300), which loads the syscall number from PC+4,
instead of the kernel's MOVW(7) (0x9305), which loads from PC+14.  The
kernel uses five "or r0,r0" nop pads between TRAP_NOARG and the syscall
number word to reach that offset.  libunwind's unw_is_signal_frame checks
for the exact kernel byte pattern 0xc3109305 at the frame PC, so QEMU's
compact layout was not detected, breaking unwinding through signal frames.

Expand each trampoline from 6 to 16 bytes matching the kernel layout
defined in arch/sh/kernel/signal_32.c:

  #define MOVW(n)    (0x9300|((n)-2))  /* Move mem word at PC+n to R3 */
  #define TRAP_NOARG 0xc310            /* Syscall w/no args (NR in R3) */
  #define OR_R0_R0   0x200b            /* or r0,r0 (insert to avoid hardware bug) */

  __put_user(MOVW(7),          &frame->retcode[0]);  /* 0x9305 */
  __put_user(TRAP_NOARG,       &frame->retcode[1]);  /* 0xc310 */
  __put_user(OR_R0_R0,         &frame->retcode[2]);  /* 0x200b */
  __put_user(OR_R0_R0,         &frame->retcode[3]);  /* 0x200b */
  __put_user(OR_R0_R0,         &frame->retcode[4]);  /* 0x200b */
  __put_user(OR_R0_R0,         &frame->retcode[5]);  /* 0x200b */
  __put_user(OR_R0_R0,         &frame->retcode[6]);  /* 0x200b */
  __put_user((__NR_sigreturn), &frame->retcode[7]);

The first two halfwords (MOVW(7) || TRAP_NOARG = 0xc3109305) form the
32-bit value libunwind checks at the frame PC, followed by two
OR_R0_R0 halfwords (0x200b200b) at PC+4.  The same layout applies to
the rt_sigreturn trampoline (lines 366-373 of signal_32.c).

Neither this fix nor the companion tuc_link fix is independently
sufficient: this fix makes signal frames detectable but register reads
remain garbage without the correct ucontext layout; that fix corrects the
ucontext layout but libunwind still cannot detect the frame without the
correct trampoline pattern.  Together they fix the following libunwind
tests on a 64-bit host:
  Gtest-sig-context, Gtest-trace, Ltest-init-local-signal,
  Ltest-sig-context, Ltest-trace

Signed-off-by: Matt Turner <[email protected]>
Cc: [email protected]
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit 9ac5aa7227)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-19 23:56:02 +03:00
Matt Turner 632f496f17 linux-user/sh4: Fix target_ucontext tuc_link field type
tuc_link is declared as 'struct target_ucontext *', which is a HOST
pointer.  On a 64-bit host running a 32-bit SH4 target, this is 8 bytes
instead of the 4 bytes the target expects, padding pushes tuc_mcontext
8 bytes past its correct offset.

When a signal handler receives ucontext_t *, every field accessed through
uc_mcontext (gregs[], pc, pr, ...) is read from the wrong address.  In
particular the saved PC comes back as a garbage stack value, which breaks
any code that initialises a libunwind cursor from the signal context.

Fix it by using abi_ulong, which is always sized to the target ABI (4
bytes for SH4), matching the layout the kernel and glibc agree on.  This
is the same pattern used by arm/signal.c.

Also remove the (unsigned long *) cast from the __put_user that zeros
tuc_link.  The cast was harmless when tuc_link was pointer-sized (8
bytes matching unsigned long on a 64-bit host), but after the type
change __put_user's sizeof dispatch would select stq_le_p (8-byte write)
for a now-4-byte field, silently overwriting the start of tuc_stack.

Neither this fix nor the companion setup_sigtramp fix is independently
sufficient: this fix corrects register values read from the signal context
but libunwind still cannot detect the frame without the correct trampoline
pattern; that fix makes the frame detectable but register reads remain
garbage without the correct ucontext layout.  Together they fix the
following libunwind tests on a 64-bit host:
  Gtest-sig-context, Gtest-trace, Ltest-init-local-signal,
  Ltest-sig-context, Ltest-trace

Signed-off-by: Matt Turner <[email protected]>
Cc: [email protected]
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit c3176e6457)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-19 23:55:47 +03:00
Helge Deller 552967257a linux-user: Fix AT_EXECFN in AUXV for symlinked programs
The AT_EXECFN entry in AUXV needs to keep the value which was used when
the program was started. Especially for symlinked programs qemu should
not try to resolve the realpath.

Here is a reproducer:
(arm64-chroot)root@p100:/# cd /usr/bin
(arm64-chroot)root@p100:/usr/bin# ln -s echo testprog
(arm64-chroot)root@p100:/usr/bin# LD_SHOW_AUXV=1 ./testprog | grep AT_EXECFN
AT_EXECFN:            ./testprog

In this example, "./testprog" is the correct output, and not "/usr/bin/echo".

This patch fixes parts of commit 258bec39 ("linux-user: Fix access to
/proc/self/exe").

Fixes: 258bec39 ("linux-user: Fix access to /proc/self/exe")
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3379
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit 6b5aef7cac)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-19 23:53:28 +03:00
Klaus Jensen 1058ad0d3c hw/nvme: fix admin cq msix setup
If MSI-X is not enabled when the admin completion queue is created,
msix_vector_use() is not called. But, if MSI-X is subsequently enabled,
msix_notify() will fail to fire the interrupt because the use count for
the vector remains at 0.

msix_vector_use/unuse should be called if MSI-X is *present*, not
*enabled*. Fix this.

Cc: [email protected]
Reported-by: Andreas Hindborg <[email protected]>
Signed-off-by: Klaus Jensen <[email protected]>
(cherry picked from commit 2293d8b4bd)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-19 23:41:13 +03:00
Peter Maydell ec7e6e6562 tests/functional/qemu_test/asset.py: Don't use setxattr when it doesn't exist
The Python os.setxattr() API is Linux-specific, so trying to use
it on other OSes triggers a failure:

  File "/Users/pm215/src/qemu/tests/functional/qemu_test/asset.py",
line 227, in fetch
    os.setxattr(str(tmp_cache_file), "user.qemu-asset-url",
    ^^^^^^^^^^^
AttributeError: module 'os' has no attribute 'setxattr'

Since we only set the attributes here for informational
purposes, skip them when os.setxattr() isn't available.

Cc: [email protected]
Fixes: 9903217a4e ("tests/functional: add a module for handling asset download & caching")
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Daniel P. Berrangé <[email protected]>
Reviewed-by: Alex Bennée <[email protected]>
Reviewed-by: Thomas Huth <[email protected]>
Message-id: [email protected]
(cherry picked from commit 039b057c09)
(Mjt: context fixup for 10.2.x)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-19 23:41:13 +03:00
Peter Maydell 1dd1386955 meson.build: Add -fzero-init-padding-bits=all
The C standard doesn't always guarantee that struct and union padding
bits are zero initialized, even if the code initializes a struct.
For QEMU, this is potentially problematic, because we often have
structs that match data structures in guest memory, where we
initialize them and then bulk copy them into the guest.  If the
compiler didn't zero init the whole of the memory containing the
struct, we could potentially leak random data from the host into the
guest via the padding bytes.

We already use -ftrivial-auto-var-init=zero, which will zero out
padding in many of these cases, but -fzero-init-padding-bits=all
closes some gaps, for example cases where we initialize a
variable with a struct initializer, and cases involving unions.

Follow the Linux kernel in using both options. Compare kernel
commit dce4aab8441 ("kbuild: Use -fzero-init-padding-bits=all").

This option exists in gcc-15 and above; it's not supported
by clang, but clang documents that it guarantees zero init
of these cases always:
https://clang.llvm.org/docs/LanguageExtensions.html#union-and-aggregate-initialization-in-c
Older gcc which don't have the option behave as if it were set.

(These options are passed through the cc.get_supported_arguments()
filter, so we don't need to do anything extra to avoid passing it to
a compiler that doesn't recognize it.)

Cc: [email protected]
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Daniel P. Berrangé <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Reviewed-by: Pierrick Bouvier <[email protected]>
Message-id: [email protected]
(cherry picked from commit a163fc1f86)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-19 23:41:13 +03:00
Peter Maydell 88304ba742 hw/i2c/microbit_i2c: Don't index off end of twi_read_sequence[]
If the guest tries to read more bytes from our fake stub I2C device
than we have provided, we incorrectly read one byte beyond the end of
this array. Avoid this, and instead keep reporting the RXD register
as containing the last byte of the "data transfer".

Cc: [email protected]
Fixes: 9d68bf564e ("arm: Stub out NRF51 TWI magnetometer/accelerometer detection")
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3408
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 a824f3531a)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-19 23:41:13 +03:00
Cédric Le Goater bb28b1d899 aspeed/hace: Prevent total_req_len overflow
In accumulate mode, total_req_len is incremented with plen (hwaddr)
for each hash request. Repeated additions can overflow total_req_len
(uint32_t) and potentially bypass validation checks in has_padding().

Add a helper function to detect overflow before incrementing
total_req_len and reject the request if overflow would occur.

Reported-by: Katherine Leaver <[email protected]>
Cc: [email protected]
Fixes: 5cd7d8564a ("aspeed/hace: Support AST2600 HACE")
Link: https://lore.kernel.org/qemu-devel/[email protected]
Signed-off-by: Cédric Le Goater <[email protected]>
(cherry picked from commit c6aa2d0ac1)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-19 23:41:13 +03:00
Cédric Le Goater 6e146a0eff aspeed/hace: Fix out-of-bounds read in has_padding()
The has_padding() function reads the last 8 bytes of a DMA buffer
without validating req_len. req_len is guest-controlled (via
R_HASH_SRC_LEN register or scatter-gather entries) and values less
than 8 cause integer underflow. This can result in an out-of-bounds
read of QEMU process memory.

Add a check to ensure req_len >= 8 before accessing the buffer.

Reported-by: Katherine Leaver <[email protected]>
Cc: [email protected]
Fixes: 5cd7d8564a ("aspeed/hace: Support AST2600 HACE")
Link: https://lore.kernel.org/qemu-devel/[email protected]
Signed-off-by: Cédric Le Goater <[email protected]>
(cherry picked from commit 534a52755b)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-19 23:41:13 +03:00
Kane Chen 3fa89be81e hw/misc/aspeed_sbc: Add bounds checking for OTP write operations
There is a mismatch between the Aspeed OTP model and the Aspeed SBC
model in how the guest-provided address is handled.
aspeed_sbc_otp_prog() passes a word-indexed address directly
to address_space_write() without converting it to a byte offset,
whereas aspeed_otp_write() expects a byte offset and applies an
additional shift (otp_addr << 2). This double-shift confusion means
that an out-of-range word address can lead to a write beyond the
allocated storage.

Fix this by adding bounds checking on the word offset before
converting to byte offset and passing to address_space_write().
This matches the existing bounds check in aspeed_sbc_otp_read().

Cc: Kane-Chen-AS <[email protected]>
Cc: [email protected]
Fixes: 1a00754ccf15 ("hw/misc: Add Aspeed Secure Boot Controller model")
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3436
Reported-by: Peter Maydell <[email protected]>
Signed-off-by: Kane-Chen-AS <[email protected]>
Reviewed-by: Peter Maydell <[email protected]>
Link: https://lore.kernel.org/qemu-devel/[email protected]
[ clg: Kept otp_addr in event logged in aspeed_sbc_otp_prog() ]
Signed-off-by: Cédric Le Goater <[email protected]>
(cherry picked from commit ff36712da5)
(Mjt: actual Fixes: tag is this one)
Fixes: 9f58dd0a8c ("hw/misc/aspeed_sbc: Connect ASPEED OTP memory device to SBC")
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-19 23:41:13 +03:00
Peter Maydell ee359b5895 hw/display/cirrus_vga: Fix packed-24 color-expansion transparent copies
For the "color expansion" subtype of raster operations, the source
pixel format is a monochrome bitmap, and the destination can be any
of 8, 16, 24 or 32bpp.

For these pattern operations, the GR2F register includes a field
which specifies how much to skip at the start of each scanline.  In
the 8, 16 and 32 bit cases, this field is 3 bits and is a count of
pixels to skip.  We get this case right.  However, for the 24 bit
case, the field is 5 bits and is a count of destination bytes to
skip.

In commit ad81218e40 ("depth=24 write mask fix (Volker Ruppert)")
in 2005, we updated the code to (attempt to) handle the 5-bit mask
case.  However, we don't do the right thing when the 5-bit mask
indicates that we need to skip more than 8 bits of the input bitmap:
we will right-shift the 0x80 constant completely off the right hand
side, and will be off-by-one for all the source bitmap loads.

Fix this by calculating the whole number of input bytes we need to
skip and the residual number of bits.  In the 8/16/32bpp case the
bytes to skip is always zero.

Cc: [email protected]
Fixes: ad81218e40 ("depth=24 write mask fix (Volker Ruppert)")
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Junjie Cao <[email protected]>
Tested-by: Junjie Cao <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit 27d14251b9)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-19 23:41:13 +03:00
Peter Maydell e7c8621547 hw/display/cirrus_vga: Fix packed-24 color-expansion transparent pattern fills
The Cirrus Logic VGA card has "pattern fill" blit modes where it
repeatedly copies an 8x8 source pattern to the display.  For the
"color expansion" subtype of these, the source pixel format is an 8x8
monochrome bitmap, and the destination can be any of 8, 16, 24 or
32bpp.  We implemented these wrong for the 24bpp case, in a way that
results in a complaint from the undefined-behavior sanitizer about a
shift by a negative value.

For these pattern fills, the GR2F register includes a field which
specifies how much to skip at the start of each scanline.  In the 8,
16 and 32 bit cases, this field is 3 bits and is a count of pixels to
skip.  We get this case right.  However, for the 24 bit case, the
field is 5 bits and is a count of destination bytes to skip.  We
tried to add support for 24-bits in commit ad81218e40 ("depth=24
write mask fix (Volker Ruppert)") in 2005.  However we got this
wrong, because when we need to skip, for example, 30 bytes in the
destination, this is 10 input pixels but the whole pattern is only 8
pixels wide, and we ended up with a negative bitpos for the first bit
to use in the pattern.

Fix the bug by masking srcskipleft in the 24-bit case so that it
correctly gives the first pixel to use in the pattern even if we skip
so many pixels that we have wrapped around to what would have been
the second copy of the pattern to the destination.

This patch was produced based on the information in the CL-GD5446
Technical Reference Manual, specifically sections 5.8 "GR2F: BLT
Destination Left-Side Clipping" and 9.4.8 "Pattern Fills".

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3377
Fixes: ad81218e40 ("depth=24 write mask fix (Volker Ruppert)")
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Junjie Cao <[email protected]>
Tested-by: Junjie Cao <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit aefeecb413)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-19 23:41:13 +03:00
Jeuk Kim fbff555944 hw/ufs: Zero reserved bytes in REPORT LUNS response header
ufs_emulate_report_luns() writes the 4-byte LUN list length into
outbuf[0..3] via stl_be_p() but leaves outbuf[4..7], the reserved
field, uninitialized. Those bytes are then DMA'd to guest memory,
leaking uninitialized QEMU stack data.

Fixes: 7708e29818 ("hw/ufs/lu: skip automatic zero-init of large array")
Cc: [email protected]
Signed-off-by: Jeuk Kim <[email protected]>
(cherry picked from commit 042dbcff83)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-19 23:41:13 +03:00
Jeuk Kim 14a88a04e5 hw/ufs: Keep MCQ SQs alive while requests are outstanding
MCQ requests are allocated with their SQ, but can remain in flight on the
CQ list or in the SCSI layer after leaving the SQ free list.

Reject runtime SQ deletion while any request is still outstanding, and
use separate teardown helpers so device exit can still release MCQ
queues after child devices have been unrealized.

Fixes: 5c079578d2 ("hw/ufs: Add support MCQ of UFSHCI 4.0")
Cc: [email protected]
Signed-off-by: Jeuk Kim <[email protected]>
(cherry picked from commit 619c2da19a)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-19 23:41:13 +03:00
Jeuk Kim 504f334394 hw/ufs: Reject zero-depth MCQ queues
Reject SQATTR.SIZE and CQATTR.SIZE values that produce zero-entry MCQ
queues. Such queues can later trigger a divide-by-zero while advancing
queue pointers.

Fixes: 5c079578d2 ("hw/ufs: Add support MCQ of UFSHCI 4.0")
Cc: [email protected]
Signed-off-by: Jeuk Kim <[email protected]>
(cherry picked from commit 4a909c00b9)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-19 23:41:13 +03:00
Jeuk Kim 1b71cb361c hw/ufs: Guard MCQ CQ accesses against missing queues
A guest can ring an MCQ CQ doorbell before the completion queue exists.
The CQ head write path then dereferences a NULL CQ through
ufs_mcq_cq_full().

Ignore CQ head updates for missing CQs, and make ufs_mcq_cq_full()
handle a missing CQ defensively.

Fixes: f78762a3cc ("hw/ufs: Fix mcq completion queue wraparound")
Reported-by: Rayhan Ramdhany Hanaputra <[email protected]>
Cc: [email protected]
Signed-off-by: Jeuk Kim <[email protected]>
(cherry picked from commit 283d921e77)
Fixes: ad5f6ffcd0 ("hw/ufs: Fix mcq completion queue wraparound") in 10.2.x
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-19 23:41:13 +03:00
Jeuk Kim 38e407de9b hw/ufs: Validate MCQ SQ references before use
A guest can program an out-of-range SQATTR.CQID value, or ring an
MCQ SQ doorbell before the submission queue exists.

Reject SQ creation when the referenced CQ is invalid, and ignore SQ
doorbells for queues that have not been created. This prevents a
guest-triggerable out-of-bounds read and NULL pointer dereference.

Fixes: 5c079578d2 ("hw/ufs: Add support MCQ of UFSHCI 4.0")
Reported-by: Rayhan Ramdhany Hanaputra <[email protected]>
Cc: [email protected]
Signed-off-by: Jeuk Kim <[email protected]>
(cherry picked from commit 332ea29787)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-19 23:41:13 +03:00
Gerd Hoffmann 689117427e hw/uefi: check auth.hdr_length minimum size
auth.hdr_length maximum is already checked (against buffer size).  The
header has some fixed fields which are included in the header length, so
there also is a minimum size which must be verified.  Add a check for
that.  Fixes possible integer underflow.

While being at it replace the magic number '24' with sizeof calculations
for better code documentation.

Fixes: CVE-2026-8341
Fixes: f1488fac05 ("hw/uefi: add var-service-auth.c")
Reported-by: Feifan Qian <[email protected]>
Reviewed-by: Daniel P. Berrangé <[email protected]>
Signed-off-by: Gerd Hoffmann <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit b33fd8ab1c)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-19 23:41:13 +03:00
Gerd Hoffmann a9bcab7208 hw/uefi: avoid possibly unaligned variable_auth_2 struct field access
Copy data to stack-allocated struct before accessing it
to make sure it is properly aligned.

Fixes: CVE-2026-41440
Fixes: f1488fac05 ("hw/uefi: add var-service-auth.c")
Reported-by: Katherine Leaver <[email protected]>
Signed-off-by: Gerd Hoffmann <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit b4680c02b8)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:27 +03:00
Gerd Hoffmann 16429eea9a hw/uefi: verify data size before accessing it in wrap_pkcs7
Fixes: CVE-2026-41439
Fixes: 3e33af2cb3 ("hw/uefi: add var-service-pkcs7.c")
Reported-by: Katherine Leaver <[email protected]>
Signed-off-by: Gerd Hoffmann <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit 22b7b222d8)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:27 +03:00
Gerd Hoffmann 35eaa28887 hw/uefi: add name_size check to uefi_vars_mm_lock_variable()
Make sure the total variable_policy_entry size stays below
64k so the (16-bit) size field can not wrap.

Fixes: CVE-2026-41438
Fixes: db1ecfb473 ("hw/uefi: add var-service-vars.c")
Reported-by: Katherine Leaver <[email protected]>
Signed-off-by: Gerd Hoffmann <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit c45b460d16)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:27 +03:00
Gerd Hoffmann 23c38ec6f6 hw/uefi: fix ucs2 string helper functions
The length passed in is in bytes not characters.  Rename the
parameters to make that clear.  Calculate the number of chars
if needed.  Fix length checks to use the number of chars not
bytes to avoid OOB reads.

Fixes: CVE-2026-41437
Fixes: 1ebc319c8c ("hw/uefi: add var-service-utils.c")
Reported-by: Katherine Leaver <[email protected]>
Signed-off-by: Gerd Hoffmann <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit 5247b3034c)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:27 +03:00
Gerd Hoffmann 8bf75ce7af hw/uefi: verify pio_xfer_offset before calculating buffer checksum
Without that it is possible to do trigger OOB reads by first
advancing offset, then making the buffer smaller, finally
asking for a checksum.

Fixes: CVE-2026-41436
Fixes: 90ca4e03c2 ("hw/uefi: add var-service-core.c")
Reported-by: Katherine Leaver <[email protected]>
Signed-off-by: Gerd Hoffmann <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit 94d9a8b2c9)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:27 +03:00
Gerd Hoffmann eee43d91c0 hw/uefi: fix buffer overruns
The buffer size checks do not consider the mm_header size, simliar to
CVE-2026-5744.  Factor out the repeated size check to a small helper
function, fix the check, update all places to use the new helper.

Fixes: CVE-2026-41435
Fixes: db1ecfb473 ("hw/uefi: add var-service-vars.c")
Reported-by: Katherine Leaver <[email protected]>
Signed-off-by: Gerd Hoffmann <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit f252769a23)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:27 +03:00
Peter Maydell baa047808a hw/misc/bcm2835_rng: Specify valid memory access sizes
The BCM2835 RNG has 32-bit registers only; specify this in
the MemoryRegionOps so wrong-sized accesses are rejected rather
than getting to the assertions in the read and write functions,
and for clarity add the matching .impl constraints.

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3394
Fixes: 54a5ba13a9 ("target-arm: Implement BCM2835 hardware RNG")
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Message-id: [email protected]
(cherry picked from commit 18b664c900)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:27 +03:00
Peter Maydell acf81ae6bf target/arm: Report IL=0 for Thumb 16-bit BKPT insn
The Thumb BKPT insn is 16-bit, and the ESR_ELx syndrome register
definition requires that we set the IL bit to 0 for this, and 1 for
the 32-bit A32 and A64 BKPT/BRK.

We used to do this correctly, but accidentally lost it in the
conversion to decodetree, because we converted the A32 BKPT first,
and then when we converted the T16 BKPT we forgot that trans_BKPT()
was unconditionally setting IL=1.

Pass the right value for syn_aa32_bkpt()'s is_16bit argument.

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3474
Fixes: 43f7e42c7d ("target/arm: Convert T16, Miscellaneous 16-bit instructions")
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Alex Bennée <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Message-id: [email protected]
(cherry picked from commit f443b68763)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:27 +03:00
Philippe Mathieu-Daudé f381a79070 target/microblaze: Fix endianness used to disassemble
MicroBlaze CPU model has a "little-endian" property, pointing to
the @endi internal field. Commit c36ec3a965 ("hw/microblaze:
Explicit CPU endianness") took care of having all MicroBlaze
boards with an explicit default endianness (similarly with
commit 91fc6d8101 for linux-user binaries), so later commit
415aae543e ("target/microblaze: Consider endianness while
translating code") could infer the endianness at runtime from
the @endi field, and not a compile time via the TARGET_BIG_ENDIAN
definition. Doing so, we forgot to propagate that runtime change
to the disassemble_info structure. Do it now to display the
opcodes in correct endianness order.

Cc: [email protected]
Fixes: 415aae543e ("target/microblaze: Consider endianness while translating code")
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Reviewed-by: Pierrick Bouvier <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit 41c417290d)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Peter Xu 17ccebbb50 migration: Fix low possibility downtime violation
When QEMU queried the estimated version of pending data and thinks it's
ready to converge, it'll send another accurate query to make sure of it.
It is needed to make sure we collect the latest reports and that equation
still holds true.

However we missed one tiny little difference here on "<" v.s. "<=" when
comparing pending_size (A) to threshold_size (B)..

QEMU src only re-query if A<B, but will kickoff switchover if A<=B.

I think it means it is possible to happen if A (as an estimate only so far)
accidentally equals to B, then re-query won't happen and switchover will
proceed without considering new dirtied data.

It turns out it was an accident in my commit 7aaa1fc072 when refactoring
the code around.  Fix this by using the same equation in both places.

Fixes: 7aaa1fc072 ("migration: Rewrite the migration complete detect logic")
Cc: [email protected]
Reviewed-by: Juraj Marcin <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Peter Xu <[email protected]>
(cherry picked from commit 455a6167f2)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
liugan1 144d98cd16 hw/intc/arm_gicv3: Fix NS write to ICC_AP1Rn_EL1 when prebits < 7
The existing code uses a blanket `regno < 2` check to make
ICC_AP1R0_EL1 and ICC_AP1R1_EL1 writes from Non-secure code WI
(Write Ignore) when EL3 is present. This is intended to prevent
NS code from claiming active interrupts in the Secure priority
range, which could block Secure interrupt delivery.

However, that check assumes prebits=7 (4 APR registers), where the
NS priority range (128..255) maps entirely to AP1R2/AP1R3. Since
commit 39f29e5993 ("hw/intc/arm_gicv3: Use correct number of
priority bits for the CPU", first in 7.1), all QEMU AArch64 CPUs
are initialised with gic_pribits=5 (one APR register), so NS
priorities map to AP1R0 bits [16:31]. Blanket WI of the entire
AP1R0 register prevents NS code from clearing its own NS active
priority bits. Machines using hw_compat_7_0 (e.g. virt-7.0) still
force pribits=8 via force-8-bit-prio and are therefore unaffected.

A concrete consequence observed in virtualisation scenarios: when
a guest VM acknowledges an SPI interrupt but does not perform EOI,
is force-killed and restarted, the new guest's attempt to clear
the residual active state by writing ICC_AP1R0_EL1=0 is silently
ignored. The running priority (RPR) remains stuck at the old
interrupt's priority, preventing all equal-or-lower priority
interrupts (including timer interrupts) from being delivered, and
hanging the guest.

Fix this by computing the exact Secure/NS boundary within the APR
bank based on prebits. For registers entirely in the Secure range,
keep the WI behaviour. For the register that straddles the
boundary, preserve only the Secure bits while allowing NS bits to
be modified. For registers entirely in the NS range, allow full
write access.

The new logic produces identical behaviour to the old code when
prebits=7, preserving existing behaviour for machines that use
force-8-bit-prio.

Fixes: 39f29e5993 ("hw/intc/arm_gicv3: Use correct number of priority bits for the CPU")
Cc: [email protected]
Signed-off-by: liugan1 <[email protected]>
Message-id: [email protected]
Reviewed-by: Peter Maydell <[email protected]>
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit f35f0f1ca1)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
宋文武 b9a80dd25d hw/net/allwinner-sun8i-emac: Flush queued packets when rx is enabled
The RX_CTL_0 register includes the RX_EN receive-enable bit,
which allwinner_sun8i_emac_can_receive() checks. That means that
if the guest sets it we need to call qemu_flush_queued_packets()
as we might now be able to handle them.

This fixes a bug where networking didn't work in u-boot on the
orangepi-pc machine.

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3459
Signed-off-by: 宋文武 <[email protected]>
Message-id: [email protected]
Reviewed-by: Peter Maydell <[email protected]>
[PMM: expanded commit message, removed unneeded RX_EN test]
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit a7f27d6903)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Vivien LEGER 86fa106b40 hw/ppc/e500: fix bus-frequency property hardcoded to zero in CPU FDT node
The bus-frequency property in the CPU FDT node was hardcoded to 0.
This is incorrect - it should reflect the actual platform bus clock
frequency, as firmware and RTOSes use it to derive peripheral clock
rates.

Notably, the RTEMS QorIQ BSP uses bus-frequency to program the MPIC
global timer interval. With bus-frequency=0, the timer interval
overflows to ~85 seconds, preventing any clock interrupts from firing.

Fix by adding a bus_freq field to PPCE500MachineClass and using it in
the FDT generator. Set bus_freq = PLATFORM_CLK_FREQ_HZ (400MHz) for
existing machines, matching the existing clock_freq value.

Signed-off-by: Vivien LEGER <[email protected]>
Reviewed-by: Bernhard Beschow <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit 774e6f5c15)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Cédric Le Goater edceee14b4 tests/rcutorture: Fix build error
Newer gcc compiler (version 16.0.0 20260103 (Red Hat 16.0.0-0) (GCC))
detects an unused variable error:

  ../tests/unit/rcutorture.c: In function ‘rcu_read_stress_test’:
  ../tests/unit/rcutorture.c:251:18: error: variable ‘garbage’ set but not used [-Werror=unused-but-set-variable=]
    251 |     volatile int garbage = 0;
        |                  ^~~~~~~

Since the 'garbage' variable is used to generate memory reads from the
CPU while holding the RCU lock, it can not be removed. Tag it as
((unused)) instead to silence the compiler warnings/errors.

Reviewed-by: Richard Henderson <[email protected]>
Link: https://lore.kernel.org/qemu-devel/[email protected]
Signed-off-by: Cédric Le Goater <[email protected]>
(cherry picked from commit 7a05be8c70)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
kiki bc429dd4c8 hw/intc/xics: Add a check for an invalid server id
A malformed IVE value can result in an invalid server field being
passed to icp_irq(). The function assumes the server id is valid and
may access invalid state otherwise, potentially leading to a crash.

Fix this by validating the server id before using it and ignoring
invalid values.

Reported-by: Zexiang Zhang <[email protected]>
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3324
Signed-off-by: Zexiang Zhang <[email protected]>
Signed-off-by: Gautam Menghani <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Link: https://lore.kernel.org/qemu-devel/[email protected]
Signed-off-by: Harsh Prateek Bora <[email protected]>
(cherry picked from commit 1aee8067fc)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Helge Deller 10703dcfaa linux-user: Translate errno in IP_RECVERR and IPV6_RECVERR
Translate host error codes of IP_RECVERR and IPV6_RECVERR control messages to
target error codes before returning to the caller.
For example, this is important for architectures (e.g. hppa, alpha, sparc,
mips) on which the value of ECONNREFUSED is different to the value on a x86_64
host.

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/602
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit 9667bf3249)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Helge Deller 4130c71eac linux-user: Allow getsockopt() with NULL optval address
Some programs test availability of socket options by asking for the
value with an NULL optval address, which currenrly always trigger an
EFAULT in qemu.  Fix it by allowing a NULL address, in the same manner
as the Linux kernel on physical machines.

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/2390
Signed-off-by: Helge Deller <[email protected]>
Reviewed-by: Pierrick Bouvier <[email protected]>
(cherry picked from commit 08dc3e240f)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Helge Deller be01857b07 linux-user: Flush errors by using exit() instead of _exit() in error path
Similiar to previous patch - ensure that we always flush I/O by using
exit() instead of _exit().

Reported by: Tobias Bergkvist <[email protected]>
Reviewed-by: Warner Losh <[email protected]>
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/2544
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit 9fb681792d)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Helge Deller 3b5d55ece4 linux-user: Add missing CDROM ioctls
Add the missing CDROM ioctls and bring them in same order as
documentation.

Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit dcb6e96257)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Alistair Francis 3aaddc00e1 target/riscv: Use ELEN for Fractional LMUL check
The RISC-V spec states that

"""
For a given supported fractional LMUL setting, implementations
must support SEW settings between SEWMIN and LMUL * ELEN, inclusive.
"""

We were previously checking VLEN, instead of ELEN, so let's update to
check ELEN instead of VLEN for fractional scaling.

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3196
Signed-off-by: Alistair Francis <[email protected]>
Reviewed-by: Daniel Henrique Barboza <[email protected]>
Reviewed-by: LIU Zhiwei <[email protected]>
Reviewed-by: Chao Liu <[email protected]>
Reviewed-by: Max Chou <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit 5dcc64828d)
(Mjt: context fixup)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Alistair Francis 2c1d02069d target/riscv: Don't OR mip.SEIP when mvien is one
The RISC-V spec states that

"""
But when bit 9 of mvien is one, bit SEIP in mip is read-only and does
not include the value of bit 9 of mvip. Rather, the value of mip.SEIP
is simply the supervisor external interrupt signal from the hart’s
external interrupt controller (APLIC or IMSIC).
"""

As such let's mark the mip.SEIP in rmw_mip64().

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/2828
Signed-off-by: Alistair Francis <[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 175afdb0d1)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Alistair Francis c3d2ce5020 target/riscv: Generate access fault if sc comparison fails
The RISC-V spec states:

"For the purposes of memory protection, a failed SC.W may be treated
like a store."

So if the comparison in sc.w fails we should still check for alignment
and do a probe access to check permissions.

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3323
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3136
Signed-off-by: Alistair Francis <[email protected]>
Reviewed-by: Daniel Henrique Barboza <[email protected]>
Reviewed-by: Chao Liu <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit d107b74807)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Munkhbaatar Enkhbaatar 5419da9f50 riscv_htif: reject invalid signature ranges (end <= begin)
Prevents huge allocations and crashes caused by malformed HTIF signature
addresses.

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3205
Signed-off-by: Munkhbaatar Enkhbaatar <[email protected]>
Reviewed-by: Alistair Francis <[email protected]>
Message-ID: <[email protected]>
[ Squashed with following commit to fix build failures
    hw/char/riscv_htif: Fix format specifier for uint64_t

    Message-ID: <[email protected]>
    Signed-off-by: Chao Liu <[email protected]>
]
Tested-by: Tao Tang <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: Chao Liu <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit 14808578cc)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Sebastián Alba Vives 7d4387d996 hw/intc: fix heap OOB in ACLINT MTIMER multi-socket
The MMIO read/write handlers index timecmp[] with the absolute hartid
(hartid_base + offset) but the array is allocated with num_harts
elements. In multi-socket configurations with hartid_base > 0 this
causes heap OOB access in the QEMU process.

Fix by using the relative offset for array indexing.

Cc: [email protected]
Signed-off-by: Sebastián Alba Vives <[email protected]>
Reviewed-by: Alistair Francis <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit d5b33fc180)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Sebastián Alba Vives ef37fe63a5 target/riscv: fix stale ptshift and base on page walk restart
When the atomic compare-and-swap for updating A/D bits in the page
table entry fails due to a concurrent PTE modification by another
vCPU, get_physical_address() jumps to the 'restart' label to re-walk
the page table from the root.

However, neither 'ptshift' nor 'base' are re-initialized before the
restart. After the walk completes, ptshift has been decremented to
its final value and base has been overwritten with an inner PTE PPN.
On goto restart, the for loop resets i=0 but ptshift and base remain
stale, causing the restarted walk to compute incorrect PTE addresses.

In an SMP guest with MTTCG and Svadu active, this can result in
incorrect physical address mappings or guest crashes.

Fix by saving the root base address and re-initializing both ptshift
and base on each restart.

Fixes: 0c3e702aca ("RISC-V CPU Helpers")
Signed-off-by: Sebastián Alba Vives <[email protected]>
Reviewed-by: Alistair Francis <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit b2e874bfec)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Yicong Yang 020e5f3f28 hw/riscv/virt-acpi-build.c: Use kvm timer frequency when kvm enabled
The timer frequency is decided by the host(kvm) rather than a fixed
RISCV_ACLINT_DEFAULT_TIMEBASE_FREQ on kvm accelerated VM. So build
RCHT with KVM provided timer frequency if KVM is enabled, just like
how we build the timer node on DT based VM.

Fixes: ebfd392893 ("hw/riscv/virt: virt-acpi-build.c: Add RHCT Table")
Signed-off-by: Yicong Yang <[email protected]>
Reviewed-by: Andrew Jones <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit 4cb2f91773)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Helge Deller d33c4176d1 linux-user: Flush errors by using exit() instead of _exit() in error path
Qemu user mode does not properly flushes error messages related to bad
arguments when exiting (at least when the output is piped to a file
instead of running on a terminal).
Ensure that we always flush by using exit() instead of _exit().

Reported by: Tobias Bergkvist
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/2544
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit 9e7734ead1)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Helge Deller 60fbf87e6d linux-user: Use abi_int for imr_ifindex in ip_mreqn struct
Peter Hartley noticed, that in the qemu code the imr_ifindex member of
struct target_ip_mreq needs to be of type "int" instead of "long", which
is what the Linux kernel uses on all architectures.

Adjust the type accordingly, and add a QEMU_BUILD_BUG_ON() checker to
prevent such issues in the future.

This change should fix multicast issues when using hosts and guests with
different endianess or bit size.

Reported-by: Peter Hartley <[email protected]>
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/2553
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit e2af3eadc0)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Helge Deller 1c4edb1338 linux-user: Fix CLONE_PARENT_SETTID when using fork-like clone
The CLONE_PARENT_SETTID option requires the implementation to store the
child thread ID at the location pointed to by parent_tid in the parent's
memory.

Fix our implementation and move the code from the client side (where
fork returned 0), to the parent side and store the return value from the
fork call (which is the client TID) in the parent_tid pointer.

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3340
Signed-off-by: Helge Deller <[email protected]>
Reviewed-by: Peter Maydell <[email protected]>
(cherry picked from commit b03a6ac6fa)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Helge Deller 960697c2b5 linux-user: Add getsockopt() for SO_RCVTIMEO_NEW and SO_SNDTIMEO_NEW
Add handlers for both sockopts which use 64-bit time_t from userspace.

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/885
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit 07c7decaa5)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Helge Deller 399d13e92f linux-user: Add setsockopt() for SO_RCVTIMEO_NEW and SO_SNDTIMEO_NEW
Add handlers for both sockopts which use 64-bit time_t from userspace.

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/885
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit edb4588309)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Helge Deller f0ebf0b7c6 linux-user: Define SO_TIMESTAMP*_NEW and SO_RCVTIMEIO_NEW
Define the entries which always use the 64-bit timestamps.

Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit 8b60ed8354)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
James Hilliard 34ffed9518 linux-user/mips: sync k0 TLS for EF_MIPS_MACH_OCTEON userlands
Cavium Octeon userspace is not following a generic MIPS Linux TLS
ABI rule here. Older Octeon glibc uses the k0 register as the fast
thread pointer, while newer Octeon2 and Octeon3 glibc variants use
the normal rdhwr $29 path.

linux-user already updates CP0_UserLocal for cpu_set_tls() and
TARGET_NR_set_thread_area, but it does not keep gpr[26]
synchronized. That leaves EF_MIPS_MACH_OCTEON userlands able to
complete set_thread_area() and still reach pthread startup or
pthread_self() with a stale k0 value.

Use the existing MIPS ELF machine flags from linux-user/elfload.c and
mirror CP0_UserLocal into gpr[26] only for EF_MIPS_MACH_OCTEON.

Signed-off-by: James Hilliard <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit 4c681ba3b8)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Alistair Francis c2a0deae77 linux-user/strace: Use pointer type for read and write values
The stack pointer is being truncated as 32-bits for qemu-riscv64, so
let's use %p to print the syscall pointer argument.

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3238
Signed-off-by: Alistair Francis <[email protected]>
Reviewed-by: Nutty Liu <[email protected]>
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit 1730e6f33f)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Richard Henderson 66c9463cdb linux-user/arm/nwfpe: Use thread-local storage for qemufpa
Fix the thread safety of the emulation by not storing a
pointer in global storage.

Signed-off-by: Richard Henderson <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit 784f1dde90)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Richard Henderson 68045dea8d linux-user/arm/nwfpe: Replace user_registers with current_cpu
Use the thread-local variable current_cpu instead of
a global variable to access the general registers.
This also means we don't need to pass env to EmulateAll.

Signed-off-by: Richard Henderson <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit c8ea175900)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Gyorgy Tamasi 6b073173a2 linux-user: Don't define target_stat64 struct for loongarch64
The kernel defines 'struct stat64' only if
__BITS_PER_LONG != 64 || defined(__ARCH_WANT_STAT64).
loongarch64 doesn't set __ARCH_WANT_STAT64, and it isn't 32-bit,
so it won't get this struct.

QEMU incorrectly does define a target_stat64 struct. However this
isn't causing any guest-visible problems, because defining the
target_stat64 struct and TARGET_HAS_STRUCT_STAT64 affects these
syscalls:
 TARGET_NR_stat64
 TARGET_NR_lstat64
 TARGET_NR_fstat64
 TARGET_NR_fstatat64
 TARGET_NR_newfstatat

For loongarch64 the only one of those we provide is newfstatat,
and that is actually a separate QEMU bug, because the kernel does
not provide that syscall for this architecture. No real guest
code will be using a syscall that doesn't exist in the ABI.

(Some of these syscalls are present in the loongarch64 "ABI1.0",
but that ABI was never accepted in the upstream kernel, and
QEMU does not model that ABI, only the "ABI2.0".)

Stop defining TARGET_HAS_STRUCT_STAT64 anyway, for consistency
with the kernel and to avoid confusion.

Note:
Commit message suggested by Peter Maydell <[email protected]>

Signed-off-by: Gyorgy Tamasi <[email protected]>
Tested-by: Gyorgy Tamasi <[email protected]>
Reviewed-by: Pierrick Bouvier <[email protected]>
Reviewed-by: Peter Maydell <[email protected]>
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit 93484c768f)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Yixin Wei 050805b786 linux-user: fix off-by-one in host_to_target_for_each_rtattr()
host_to_target_for_each_rtattr() uses "len > sizeof(struct rtattr)"
as its loop condition. When the last rtattr in a netlink message has
exactly sizeof(struct rtattr) (4) bytes remaining, the loop exits
without byte-swapping its rta_len and rta_type. A big-endian guest
then reads rta_len in the wrong byte order and fails validation.

The companion function target_to_host_for_each_rtattr() correctly
uses ">=" (added in commit fa2229dbf8). The kernel's RTA_OK macro
also uses ">=". Fix the host_to_target direction to match.

Resolves: https://gitlab.com/qemu-project/qemu/-/issues/2485
Signed-off-by: Yixin Wei <[email protected]>
Fixes: 6c5b5645ae ("linux-user: add rtnetlink(7) support")
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: Helge Deller <[email protected]>
Cc: [email protected]
(cherry picked from commit 029f10e852)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Matt Turner d86794e9d9 linux-user/ppc: Fix ppc64 rt_sigframe stack offset
The kernel's 64-bit signal delivery (signal_64.c) uses:

    newsp = frame - __SIGNAL_FRAMESIZE

while the 32-bit path (signal_32.c) uses:

    newsp = frame - (__SIGNAL_FRAMESIZE + 16)

The extra 16 bytes in the 32-bit case is to place siginfo and ucontext
at the same offsets as older kernels (see the comment in signal_32.c).
The 64-bit rt_sigframe starts with ucontext directly and does not need
this adjustment.

QEMU's setup_rt_frame() unconditionally used (SIGNAL_FRAMESIZE + 16)
for both 32-bit and 64-bit, placing the handler's SP 16 bytes too low
on ppc64. Signal delivery and return still worked because do_rt_sigreturn
had the matching wrong offset, but the vDSO DWARF unwind info encodes
the correct kernel offset. This caused any DWARF unwinder (libunwind,
libgcc, etc.) to compute a CFA that is 16 bytes off, reading garbage
register values from the signal frame.

Define RT_SIGFRAME_ADJUST (0 on ppc64, 16 on ppc32) and use it in both
setup_rt_frame and do_rt_sigreturn to match the kernel.

This was verified by A/B testing with libunwind's test suite:

  ppc64le: Gtest-bt, Ltest-bt, Gtest-concurrent, Ltest-concurrent,
           and Ltest-sig-context all change from FAIL to PASS.
  ppc64be: Gtest-bt, Ltest-bt, and Ltest-sig-context all change
           from FAIL to PASS.

Signed-off-by: Matt Turner <[email protected]>
Reviewed-by: Peter Maydell <[email protected]>
Signed-off-by: Helge Deller <[email protected]>
Cc: [email protected]
(cherry picked from commit 654dce6c52)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Thomas Huth 962bd5ec28 hw/sh4/sh7750: Remove forgotten abort() in the MM_ITLB_DATA handler
QEMU currently aborts when the guest writes to the MM_ITLB_DATA register:

 echo "writel 0xf3000000 0x11223344" | \
  ./qemu-system-sh4 -M r2d -display none -accel qtest -qtest stdio
 [I 0.000000] OPENED
 [R +0.004476] writel 0xf3000000 0x11223344
 Aborted                    (core dumped)

Looking at the history of the code, the abort() here has likely just
been forgotten when the register handler had been implemented (it used
to be a reminder about unimplemented functionality initially):

 https://gitlab.com/qemu-project/qemu/-/commit/9f97309a70f12df5f9104f1f

Thus simply remove the abort() now to get rid of the problem.

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3420
Signed-off-by: Thomas Huth <[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 3ab47a47d7)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Thomas Huth db373da2a7 hw/misc: Fix the valid access size to the avr-power device
Accessing the device with in non-single byte mode currently causes
QEMU to abort:

 $ echo "writew 0x800064 0x4142" | \
   ./qemu-system-avr -M mega2560 -display none -qtest stdio -accel qtest
 [I 0.000000] OPENED
 [R +0.001784] writew 0x800064 0x4142
 qemu-system-avr: ../../devel/qemu/hw/misc/avr_power.c:58: avr_mask_write:
  Assertion `offset == 0' failed.
 Aborted                    (core dumped)

Set the valid max access size to 1 to fix the problem.

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3393
Signed-off-by: Thomas Huth <[email protected]>
Reviewed-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 c0306d2b8f)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Vladimir Sementsov-Ogievskiy c4f78bd036 migration: vmstate_save_state_v: fix double error_setg
We may call error_setg twice on same errp if inner
vmstate_save_state_v() or vmstate_save_state() call fails. Next we will
crash on assertion in error_setv().

Fixes: 848a050342 "migration: Update error description outside migration.c"
Signed-off-by: Vladimir Sementsov-Ogievskiy <[email protected]>
Reviewed-by: Fabiano Rosas <[email protected]>
Reviewed-by: Peter Xu <[email protected]>
Link: https://lore.kernel.org/qemu-devel/[email protected]
Signed-off-by: Fabiano Rosas <[email protected]>
(cherry picked from commit d41ce10d0f)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Alex Bennée 5a44a38332 hw/display: don't accidentally autofree existing virgl resources
While sanity checking a create blob operation the use of the auto
freed res variable could lead to inadvertently freeing an existing
blob.

Avoid this by in-lining the virtio_gpu_virgl_find_resource() check as
the value is not needed anyway.

While at it add a comment to the end and use g_steal_pointer to make
it clearer the object lifetime exceeds the function bounds if we pass
all the checks.

Fixes: CVE-2026-6502
Fixes: 7c092f17cc (virtio-gpu: Handle resource blob commands)
Message-ID: [email protected]
Reviewed-by: Manos Pitsidianakis <[email protected]>
Cc: [email protected]
Message-ID: <[email protected]>
Signed-off-by: Alex Bennée <[email protected]>
Reviewed-by: Dmitry Osipenko <[email protected]>
(cherry picked from commit 30fad722ce)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Stepan Popov d22dd2a689 meson: add missing semicolon in pthread_condattr_setclock test
The test code was missing a semicolon after the pthread_condattr_t
variable declaration.

Signed-off-by: Stepan Popov <[email protected]>
Reviewed-by: Alex Bennée <[email protected]>
Fixes: 657ac98b58 ("thread-posix: use monotonic clock for QemuCond and QemuSemaphore", 2022-02-22)
Reviewed-by: Marc-André Lureau <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 79bc177186)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Paolo Bonzini 30ac69aa67 target/i386/tcg: fix decoding of MOVBE and CRC32 in 16-bit mode
Table A-4 of the SDM shows

                    F0                     F1
--------------------------------------------------------
     NP           MOVBE Gy,My           MOVBE My,Gy
     66           MOVBE Gw,Mw           MOVBW Mw,Gw
     F2           CRC32 Gd,Eb           CRC32 Gd,Ey
  66+F2           CRC32 Gd,Eb           CRC32 Gd,Ew

However, this is incorrect.  Both MOVBE and (for 0xF1) CRC32
take Gv, Ev or Mv operands.  In 16-bit mode therefore the
operand is of 16-bit size without prefix and 32-bit mode
with 0x66 (the data size override).

For example, with NASM you get:

                                 bits 16
   67 0F 38 F0 02                movbe ax, [edx]
   66 67 0F 38 F0 02             movbe eax, [edx]

   67 F2 0F 38 F1 02             crc32 ax, word [edx]
   66 67 F2 0F 38 F1 02          crc32 eax, dword [edx]

versus

                                 bits 32
   66 0F 38 F0 02                movbe ax, [edx]
   0F 38 F0 02                   movbe eax, [edx]

   66 F2 0F 38 F1 02             crc32 eax, word [edx]
   F2 0F 38 F1 02                crc32 eax, dword [edx]

The instruction is listed correctly in the APX documentation
as "SCALABLE" (which means it has v-size operands).

Cc: [email protected]
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 76ad26dd17)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Simon Scherer da5beca9eb target/i386: fix missing PF_INSTR in SIGSEGV context
When running linux-user emulation, the SIGSEGV handler does not
correctly set the 4th bit (PF_INSTR) in the error_code variable of
the context argument (context->uc_mcontext.gregs[REG_ERR]).

Because this bit is never set, guest applications cannot distinguish
if a fault was due to missing executable permissions. This patch
ensures that when a page fault occurs during an instruction fetch,
the PF_INSTR flag is properly populated in the signal context.

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3384
Signed-off-by: Simon Scherer <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 3eae91a8b9)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Marc-André Lureau 5aabe40c38 target/i386: fix strList leak in x86_cpu_get_unavailable_features
The result list built by x86_cpu_list_feature_names() was never freed
after being visited, causing a memory leak detected by ASan.
(the getter visitor is VISITOR_OUTPUT kind and doesn't own data)

Fixes: 506174bf82 ("i386: "unavailable-features" QOM property")
Signed-off-by: Marc-André Lureau <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 87e1226e6f)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Pierrick Bouvier ca77baf544 target/arm/tcg/translate.c: remove MO_TE usage
dc->be_data is already set just above in the same function:
```
    dc->be_data = EX_TBFLAG_ANY(tb_flags, BE_DATA) ? MO_BE : MO_LE;
```

Cc: [email protected]
Fixes: a729a46b05 ("target/arm: Add wrapper macros for accessing tbflags")
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Pierrick Bouvier <[email protected]>
Message-id: [email protected]
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit 027ad866bd)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Marc-André Lureau d631117be8 ui/console-vc: fix off-by-one in CSI J 2 (clear entire screen)
The loop condition used `y <= s->height` instead of `y < s->height`,
causing vc_clear_xy() to be called with y == s->height. This clears
a row in the scrollback buffer beyond the visible screen.

Reviewed-by: Daniel P. Berrangé <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: Marc-André Lureau <[email protected]>
(cherry picked from commit 181fdf8a7e)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
GuoHan Zhao 9a6b1d0b9c ui/spice-app: detect runtime directory creation failures
spice_app_display_early_init() creates the per-VM runtime directory
with g_mkdir_with_parents() before setting up the Spice socket. The
code checks for "< -1", but g_mkdir_with_parents() returns -1 on
failure, so the error path is never taken.

This lets spice-app continue after a directory creation failure and
defers the problem to later setup steps.

Check for "< 0" instead so the failure is reported immediately and
spice-app exits before using an invalid runtime directory.

Fixes: d8aec9d9f1 ("display: add -display spice-app launching a Spice client")
Signed-off-by: GuoHan Zhao <[email protected]>
Reviewed-by: Marc-André Lureau <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit 52cf667ed2)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Werner de Carne 8243d867ce serial COM: windows serial COM PollingFunc don't sleep
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/1802
Signed-off-by: Werner de Carne <[email protected]>
[ Marc-André - indentation fixes ]
Signed-off-by: Marc-André Lureau <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit 7437b3eab6)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Bernhard Beschow 8ad6c43183 util/cutils: Fix heap corruption under Windows
Under Windows, QEMU would only sporadically start successfully. In the
G_OS_WIN32 case, get_relocated_path() first determines a cursor
to the end of the "result" string and then increases its size with
g_string_set_size(). Since g_string_set_size() may reallocate, the
cursor may become dangling. Windows may detect this and crash the QEMU
process with the following message:

  HEAP: Free Heap block 000000000499B640 modified at 000000000499B684 after it was freed

Furthermore, QEMU crashes spontaneously, even long after the guest has
booted. For example, it presumably crashes due to the guest setting a
new cursor icon which may be a result of the heap corruption.

Fix this by determining the cursor on the resized string.

Fixes: cf60ccc330 ("cutils: Introduce bundle mechanism")
Cc: [email protected]
Signed-off-by: Bernhard Beschow <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Akihiko Odaki <[email protected].i.u-tokyo.ac.jp>
Message-id: [email protected]
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit f1b1db98cc)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Stefan Hajnoczi bdf965c067 virtio-blk: fix zone report buffer out-of-memory (CVE-2026-5761)
An internal buffer is used when processing VIRTIO_BLK_T_ZONE_REPORT
requests. The buffer's size is controlled by the guest. A large value
can result in g_malloc() failure and the QEMU process aborts, resulting
in a Denial of Service (DoS) (most likely in cases where an untrusted
guest application or a nested guest with virtio-blk passthrough is able
to abort QEMU).

Modify the zone report implementation to work incrementally with a
bounded buffer size.

This is purely a QEMU implementation issue and no VIRTIO spec changes
are needed.

Mingyuan Luo found this bug and provided a reproducer which I haven't
put into tests/qtest/ because it requires a zoned storage device (e.g.
root and modprobe null_blk):

1) Prepare a zoned nullblk backend (/dev/nullb0):

sudo modprobe -r null_blk || true
sudo modprobe null_blk nr_devices=1 zoned=1
sudo chmod 0666 /dev/nullb0
cat /sys/block/nullb0/queue/zoned

2) Create qtest input:

cat >/tmp/vblk-zone-report-oom.qtest <<'EOF'
outl 0xcf8 0x80002004
outw 0xcfc 0x0007
outl 0xcf8 0x80002010
outl 0xcfc 0x0000c001
outb 0xc012 0x00
outb 0xc012 0x01
outb 0xc012 0x03
outl 0xc004 0x00000000
outw 0xc00e 0x0000
outl 0xc008 0x00000100
outb 0xc012 0x07
writel 0x00020000 0x00000010
writel 0x00020004 0x00000000
writeq 0x00020008 0x0000000000000000
writeq 0x00100000 0x0000000000020000
writel 0x00100008 0x00000010
writew 0x0010000c 0x0001
writew 0x0010000e 0x0001
EOF

for i in $(seq 1 1022); do
d=$((0x00100000 + i * 16))
n=$((i + 1))
printf 'writeq 0x%08x 0x0000000000200000\n' "$d" >> /tmp/vblk-zone-report-oom.qtest
printf 'writel 0x%08x 0x1fe00000\n' $((d + 8)) >> /tmp/vblk-zone-report-oom.qtest
printf 'writew 0x%08x 0x0003\n' $((d + 12)) >> /tmp/vblk-zone-report-oom.qtest
printf 'writew 0x%08x 0x%04x\n' $((d + 14)) "$n" >> /tmp/vblk-zone-report-oom.qtest
done

d=$((0x00100000 + 1023 * 16))
printf 'writeq 0x%08x 0x0000000000200000\n' "$d" >> /tmp/vblk-zone-report-oom.qtest
printf 'writel 0x%08x 0x1fe00000\n' $((d + 8)) >> /tmp/vblk-zone-report-oom.qtest
printf 'writew 0x%08x 0x0002\n' $((d + 12)) >> /tmp/vblk-zone-report-oom.qtest
printf 'writew 0x%08x 0x0000\n' $((d + 14)) >> /tmp/vblk-zone-report-oom.qtest
cat >> /tmp/vblk-zone-report-oom.qtest <<'EOF'
writew 0x00104000 0x0000
writew 0x00104002 0x0001
writew 0x00104004 0x0000
outw 0xc010 0x0000
EOF

3) Run the qtest input with ASAN build (compile qemu with --enable-asan):

build/qemu-system-x86_64 -display none \
-accel qtest -qtest stdio \
-machine pc -nodefaults -m 512M -monitor none -serial none \
-blockdev driver=host_device,node-name=disk0,filename=/dev/nullb0 \
-device virtio-blk-pci-transitional,drive=disk0,addr=04.0,queue-size=1024 \
< /tmp/vblk-zone-report-oom.qtest

Cc: Sam Li <[email protected]>
Cc: Damien Le Moal <[email protected]>
Cc: Dmitry Fomichev <[email protected]>
Fixes: CVE-2026-5761
Fixes: 4f7366506a ("virtio-blk: add zoned storage emulation for zoned devices")
Reported-by: Mingyuan Luo <[email protected]>
Reviewed-by: Damien Le Moal <[email protected]>
Signed-off-by: Stefan Hajnoczi <[email protected]>
(cherry picked from commit 4913ae36f9)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Dietmar Maurer ca0bca5068 qemu-keymap: fix altgr modifier lookup for newer xkeyboard-config
xkeyboard-config 2.37 removed the "AltGr" virtual modifier in favor
of mapping upper groups directly to Mod5. Since then,
xkb_keymap_mod_get_index(map, "AltGr") returns XKB_MOD_INVALID, so
AltGr-based keysyms were never generated.

See: https://gitlab.freedesktop.org/xkeyboard-config/xkeyboard-config/-/commit/473f9bc32f9ba869829cc0d06a75cd1f2560aa60

Try "AltGr" first, and fall back to "Mod5" for compatibility with
both old and new xkeyboard-config versions.

Signed-off-by: Dietmar Maurer <[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 4e6fb62fb0)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Gerd Hoffmann d3c3a7c21b hw/uefi: fix heap overflow (CVE-2026-5744)
When copying the request response into the pio transfer buffer the code
skips the 'struct mm_header' but does not consider that when calculating
transfer size, so it will copy 24 (== sizeof(struct mm_header)) extra
bytes, which can overflow uv->pio_xfer_buffer.

Fix that by copying the complete buffer, including the header, which
also makes the pio code path consistent with the (unaffected) dma code
path.

Fixes: CVE-2026-5744
Fixes: 90ca4e03c2 ("hw/uefi: add var-service-core.c")
Reported-by: Yuma Kurogome <[email protected]>
Signed-off-by: Gerd Hoffmann <[email protected]>
Reviewed-by: Daniel P. Berrangé <[email protected]>
Message-id: [email protected]
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit af74c9e46b)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Paolo Bonzini 4c47362705 virtio-scsi: pass the same cdb_size to virtio_scsi_pop_req and virtio_scsi_handle_cmd_req_prepare
Ensure that there is no allocation/usage mismatch when requests
are processed in virtio_scsi_handle_cmd_vq.  To do this,
retrieve the value once and pass it to both functions.

For other calls to virtio_scsi_pop_req the extra size
can be 0, because control and event requests fit
entirely in VirtIOSCSIReq.

Reported-by: Jihe Wang <[email protected]>
Tested-by: Jihe Wang <[email protected]>
Reviewed-by: Stefan Hajnoczi <[email protected]>
Fixes: CVE-2026-5763
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 7997130293)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Paolo Bonzini 9207e06585 rust: hide panicking default associated constants from rustdoc
Work around rustdoc issue that panics while trying to evaluate
the constants.

Reviewed-by: Zhao Liu <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 34f66fdfd2)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Nguyen Dinh Phi f2b63e289f util/readline: Fix out-of-bounds access in readline_insert_char().
Currently, the readline_insert_char() function is guarded by the cursor
position (cmd_buf_index) rather than the actual buffer fill level(cmd_buf_size).
The current check is:
	if (rs->cmd_buf_index < READLINE_CMD_BUF_SIZE)

This logic is flawed because if the command buffer is full and a user moves the
cursor backward (e.g. by sending left arrow key), cmd_buf_index can be
decreased without descreasing of buffer size.
This allow subsequent insertions to increase cmd_buf_size past its maximum
limit of rs->cmd_buf.

Because in the ReadLineState struct, cmd_buf[READLINE_CMD_BUF_SIZE + 1] is
immediately followed by the cmd_buf_index integer, once the buffer size is
sufficiently inflated, the memmove() operation inside readline_insert_char()
can write past the end of cmd_buf[] and overwrites cmd_buf_index itself.

The subsequent line:
	rs->cmd_buf[rs->cmd_buf_index] = ch;

then writes the input character to an address determined by the now-corrupted
index.

By providing a specifically crafted input sequence via HMP, this flaw can be
used to redirect the write operation to overwrite any field within the
ReadLineState structure, which can lead to unpredictable behavior or
application crashes.

Fix this by adding the guard to check for buffer fullness.

Cc: [email protected]
Signed-off-by: Nguyen Dinh Phi <[email protected]>
Message-id: [email protected]
Reviewed-by: Marc-André Lureau <[email protected]>
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit 4e4832dd72)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Alex Bennée 5d3259da4d target/arm: fix fault_s1ns for stage 2 faults
The computation of s1ns was simply wrong. For Stage 2 faults, it
should indicate whether the faulting IPA is in the Non-Secure IPA
space. Correct the logic to check for ARMSS_NonSecure and drop the
extraneous s2_mmu_idx test.

This is effectively a change in the intended semantics of the
ARMMMUFaultInfo::s1ns field, so that we no longer try to make it
exactly match HPFAR_EL2.NS but instead set it for any stage 2 fault
on an NS IPA, relying on users of the field to check whether the
fault is to be taken to Secure EL2 before propagating the field to
the HPFAR_EL2.NS bit.  Since the actual writing of HPFAR_EL2.NS is
already gated by arm_is_secure_below_el3(env), we only need to update
the comments to document this change of semantics.

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/2568
Signed-off-by: Alex Bennée <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Message-id: [email protected]
[PMM: also update comments about the s1ns field]
Reviewed-by: Peter Maydell <[email protected]>
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit 566594f108)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Peter Maydell 6dea849abc target/arm: do_ats_write(): avoid assertion when ptw failed
In do_ats_write() we try to assert that the cacheattrs from
get_phys_addr_for_at() are in the form we expect:

    /*
     * ATS operations only do S1 or S1+S2 translations, so we never
     * have to deal with the ARMCacheAttrs format for S2 only.
     */
    assert(!res.cacheattrs.is_s2_format);

However, the GetPhysAddrResult struct documents that its fields are
only valid when the page table walk succeeded.  For a two stage page
table walk which fails during stage two, we will return early from
get_phys_addr_twostage() and depending on the fault type the
res.cacheattrs may have been initialized with the stage 2 cache attr
information in stage 2 format.  In this case we will incorrectly
assert here.

Fix the assertion to not look at the res fields if the lookup failed.

Note for stable backports: the do_ats_write() function is in
target/arm/helper.c in older QEMU versions, but the change to the
assert line is the same.

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3328
Fixes: 9f225e607f ("target/arm: Postpone interpretation of stage 2 descriptor attribute bits")
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Message-id: [email protected]
(cherry picked from commit 84771c64a5)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Nicholas Piggin 353efac0f4 bsd-user, linux-user: signal: recursive signal delivery fix
Synchronous signals must accommodate a synchronous signal being
raised during delivery, as asynchronous ones do. For example
badframe errors during delivery will cause SIGSEGV to be raised.

Without this fix, cpu_loop() runs process_pending_signals() which
delivers the first synchronous signal (e.g., SIGILL) which fails
to set the handler and forces SIGSEGV, but that is not picked up.
process_pending_signals() returns. Then cpu_loop() runs cpu_exec()
again, which attempts to execute the same instruction, another
SIGILL.

Signed-off-by: Nicholas Piggin <[email protected]>
Reviewed-by: Warner Losh <[email protected]>
Reviewed-by: Peter Maydell <[email protected]>
Message-id: [email protected]
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit 7e966ef38f)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Sun Haoyu 7b5b46057e linux-user: Make openat2() use -L for absolute paths
openat2() ignored the -L prefix and opened host files directly.
For example, openat2("/tmp/file") opened /tmp/file on the host, not
QEMU_LD_PREFIX/tmp/file like openat() does.

Fix this by using path() to rewrite absolute paths. Skip this
when RESOLVE_BENEATH or RESOLVE_IN_ROOT is set:
- RESOLVE_BENEATH rejects absolute paths anyway
- RESOLVE_IN_ROOT resolves relative to dirfd

Now openat() and openat2() work in the same way.

Link: https://gitlab.com/qemu-project/qemu/-/work_items/3341

Signed-off-by: Sun Haoyu <[email protected]>
Reviewed-by: Peter Maydell <[email protected]>
Message-id: [email protected]
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit fa6dfcc373)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Sun Haoyu 7ef60a5b1b linux-user: update select timeout writeback
The Linux kernel writes back the remaining timeout for select-family
syscalls in poll_select_finish(). If that writeback fails, it keeps
the original return value.

However, QEMU only writes back the timeout on success. If the writeback
fails, QEMU returns -TARGET_EFAULT. This can lose the remaining
timeout and change the return value.

Update do_select(), do_pselect6(), and do_ppoll() to always write back
the timeout to match the Linux kernel's behavior. If the timeout
writeback fails, keep the original return value.

Tested with the issue reproducer.

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3343
Signed-off-by: Sun Haoyu <[email protected]>
Reviewed-by: Peter Maydell <[email protected]>
Message-id: [email protected]
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit 9b7d64686b)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Clayton Craft 3b68c2db23 linux-user: fix name_to_handle_at when AT_HANDLE_MNT_ID_UNIQUE flag is set
Linux 6.12 added AT_HANDLE_MNT_ID_UNIQUE, which indicates that mount_id
is 64-bits. If name_to_handle_at is called with this flag set then qemu
passes a 4 byte int to the kernel, which then tries to store 8 bytes in
a 4 byte variable, causing a SIGSEGV[1][2].

This stores mount_id in a 64-bit var if the flag is set.

1. https://gitlab.postmarketos.org/postmarketOS/pmaports/-/work_items/4431
2. https://github.com/systemd/systemd/issues/41279

Signed-off-by: Clayton Craft <[email protected]>
Reviewed-by: Helge Deller <[email protected]>
Message-id: [email protected]
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit 22966937f4)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Peter Maydell b16930ecb9 include/user/guest-host.h: Provide g2h etc for both abi_ptr and vaddr
In commit 7804c84a ("include/user: Use vaddr in guest-host.h") we
changed all the functions in guest-host.h that took or returned their
guest address argument in type abi_ptr to instead use vaddr.

This introduced regressions for the case of a 32-bit guest and an
address above 2GB for the common situation where the address is a
syscall argument stored in a variable of type 'abi_long'.  With
abi_ptr (which will be an unsigned 32-bit type for 32-bit guests),
the address is cast to unsigned 32-bit, and then zero-extended to
64-bits in g2h_untagged_vaddr().  With the switch to vaddr (which is
always a 64-bit unsigned type), the guest address will instead be
sign-extended to 64 bits, which gives the wrong answer.

Fix this by providing two versions of the affected functions: the
standard names (g2h(), g2h_untagged(), guest_addr_valid_untagged(),
guest_range_valid_untagged(), cpu_untagged_addr()) return to using
the logically-correct abi_ptr type; new versions with a _vaddr()
prefix use the vaddr type.

accel/tcg/user-exec.c must change to use the _vaddr() versions; this
is the only file that uses guest-host.h that we want to compile once.
All the other uses are in linux-user and bsd-user code that
inherently has to know the sizes of target-ABI types.

Cc: [email protected]
Fixes: 7804c84a ("include/user: Use vaddr in guest-host.h")
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3333
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Laurent Vivier <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Message-id: [email protected]
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit 8330da591e)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Peter Maydell 254631b11d include: Don't include guest-host.h in cpu-ldst.h
We currently include user/guest-host.h from accel/tcg/cpu-ldst.h.
However that file doesn't need anything from guest-host.h, since we
removed the uses of g2h() in commit 9b74d403b3 ("accel/tcg: Move
user-only tlb_vaddr_to_host out of line").

Move the include of guest-host.h to where it's actually needed.

Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Laurent Vivier <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Message-id: [email protected]
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit ad7a005d67)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Richard Henderson cf0d771952 accel/tcg: Fix uninitialized hostp in get_page_addr_code_hostp
This uninitialized value violates the contract in the
documentation comment, and may lead to a SEGV during
translaton with -d in_asm.

Change the documentation to disallow hostp NULL.
Pass hostp to probe_access_internal directly.

Reported-by: Panda Jiang <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
(cherry picked from commit 0039e5fd22)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Richard Henderson 35cfa889f3 accel/tcg: Don't pass NULL to get_page_addr_code_hostp
Pass a dummy variable instead to let the value be discarded,
in preparation for making the argument mandatory.

Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
(cherry picked from commit 813dbe869f)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Daniel P. Berrangé 8449013324 util: fix missing aio_wait sym in qemu guest agent only build
Configure QEMU with

 --disable-system --disable-user --disable-tools --enable-guest-agent

and the build with fail with

  FAILED: [code=1] qga/qemu-ga
  ld: libqemuutil.a.p/qapi_qmp-dispatch.c.o: in function `do_qmp_dispatch_bh':
  qapi/qmp-dispatch.c:140:(.text+0x5c): undefined reference to `aio_wait_kick'

This aio_kick() usage was recently introduced in qmp-dispatch.c
without updating the build logic.

Fixes commit fc1a2ec7da
Signed-off-by: Daniel P. Berrangé <[email protected]>
Cc: [email protected]
Reviewed-by: Michael Tokarev <[email protected]>
Signed-off-by: Michael Tokarev <[email protected]>
(cherry picked from commit 17fbf3e18c)
Fixes: 2da5757fba "monitor: Fix deadlock in monitor_cleanup" in 10.2.x
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:27:34 +03:00
hongmianquan 2da5757fba monitor: Fix deadlock in monitor_cleanup
During qemu_cleanup, if a non-coroutine QMP command (e.g.,
query-commands) is concurrently received and processed by the
mon_iothread, it can lead to a deadlock in monitor_cleanup.

The root cause is a race condition between the main thread's shutdown
sequence and the coroutine's dispatching mechanism. When handling a
non-coroutine QMP command, qmp_dispatcher_co schedules the actual
command execution as a bottom half in iohandler_ctx and then yields. At
this suspended point, qmp_dispatcher_co_busy remains true.

Subsequently, the main thread in monitor_cleanup(), sets
qmp_dispatcher_co_shutdown, and calls qmp_dispatcher_co_wake(). Since
qmp_dispatcher_co_busy is already true, the aio_co_wake is skipped. The
main thread then enters the AIO_WAIT_WHILE_UNLOCKED loop, it executes
the scheduled BH (do_qmp_dispatch_bh) via aio_poll(iohandler_ctx,
false), which attempts to wake up the coroutine, aio_co_wake schedules a
new wake-up BH in iohandler_ctx. The main thread then blocks
indefinitely in aio_poll(qemu_aio_context, true), while the coroutine's
wake-up BH is starved in iohandler_ctx, qmp_dispatcher_co never reaches
termination, resulting in a deadlock.

The execution sequence is illustrated below:

 IO Thread                 Main Thread (qemu_aio_context)        qmp_dispatcher_co (iohandler_ctx)
    |                                 |                                        |
    |-- query-commands                |                                        |
    |-- qmp_dispatcher_co_wake()      |                                        |
    |    (sets busy = true)           |                                        |
    |                                 |   <-- Wakes up in iohandler_ctx -->    |
    |                                 |                                        |-- qmp_dispatch()
    |                                 |                                        |-- Schedules BH (do_qmp_dispatch_bh)
    |                                 |                                        |-- qemu_coroutine_yield()
    |                                 |                                            [State: Suspended, busy=true]
    |   [ quit triggered ]            |
    |                                 |-- monitor_cleanup()
    |                                 |-- qmp_dispatcher_co_shutdown = true
    |                                 |-- qmp_dispatcher_co_wake()
    |                                 |    -> Checks busy flag. It's TRUE!
    |                                 |    -> Skips aio_co_wake().
    |                                 |
    |                                 |-- AIO_WAIT_WHILE_UNLOCKED:
    |                                 |   |-- aio_poll(iohandler_ctx, false)
    |                                 |   |    -> Executes do_qmp_dispatch_bh
    |                                 |   |    -> Schedules 'co_schedule_bh' in iohandler_ctx
    |                                 |   |
    |                                 |   |-- aio_poll(qemu_aio_context, true)
    |                                 |   |    -> Blocks indefinitely! (Deadlock)
    |                                 |
    |                                 X (Main thread sleeping)                 X (Waiting for next iohandler_ctx poll)

To fix this, we add an explicit aio_wait_kick() in do_qmp_dispatch_bh()
to break the main loop out of its blocking poll, allowing it to evaluate
the loop condition and poll iohandler_ctx.

Suggested-by: Kevin Wolf <[email protected]>
Signed-off-by: hongmianquan <[email protected]>
Signed-off-by: wubo.bob <[email protected]>
Message-ID: <[email protected]>
Acked-by: Markus Armbruster <[email protected]>
Reviewed-by: Kevin Wolf <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit fc1a2ec7da)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-13 12:18:48 +03:00
Kevin Wolf a0820871f8 scsi: Don't consider LOGICAL UNIT NOT SUPPORTED guest recoverable
When commit bdf9613b introduced scsi_sense_buf_is_guest_recoverable(),
it included LOGICAL UNIT NOT SUPPORTED in the list of guest recoverable
sense codes. It doesn't really explain how the codes to be in the list
were selected.

As the LUN doesn't come from the guest, but from the block backend
(usually the SCSI device on the host that was opened with host_device,
but it could also be the iscsi block driver), there is really no way the
guest could influence this.

It seems that on some storage arrays, LOGICAL UNIT NOT SUPPORTED can
happen during failover operations. When combined with multipath, the
request should be retried on another path instead of being reported to
the guest, which would offline the filesystem in response.

Simply returning false in scsi_sense_buf_is_guest_recoverable() will
enable the retry logic in file-posix, and will also make sure that if
the error persists, the configured error policy is respected so that the
VM can be stopped.

Buglink: https://redhat.atlassian.net/browse/RHEL-158212
Fixes: bdf9613b7f ('scsi: explicitly list guest-recoverable sense codes')
Signed-off-by: Kevin Wolf <[email protected]>
Message-ID: <[email protected]>
Reviewed-by: Paolo Bonzini <[email protected]>
Reviewed-by: Stefan Hajnoczi <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit ccc613f96c)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-13 12:18:48 +03:00
Kevin Wolf 0f2605ef80 ide: Fix potential assertion failure on VM stop for PIO read error
ide_sector_read() as well as its callers neglect to call ide_set_retry()
before starting I/O. If the I/O fails, this means that the retry
information is stale. In particular, ide_handle_rw_error() has an
assertion that s->bus->retry_unit == s->unit, which can fail if either
there was no previous request or it came from another device on the bus.
If the assertion weren't there, a wrong request would be retried after
resuming the VM.

Fix this by adding a ide_set_retry() call to ide_sector_read().

This affects only reads because ide_transfer_start() does call
ide_set_retry(). For writes, the data transfer comes first and the I/O
is only started when the data has been read into s->io_buffer, so by
that time, ide_set_retry() has been called. For reads, however, the I/O
comes first and only then the data is transferred to the guest, so the
call in ide_transfer_start() is too late.

Buglink: https://redhat.atlassian.net/browse/RHEL-153537
Reported-by: Tingting Mao <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit 59c1d31136)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-13 12:18:48 +03:00
Marc-André Lureau ccffe22759 ui/vnc-jobs: fix VncRectEntry leak on job cleanup
When a VncJob is freed, its associated VncRectEntry list must also be
freed. Previously, vnc_job_push() and the disconnected path in
vnc_worker_thread_loop() called g_free(job) directly, leaking all
VncRectEntry allocations.

Introduce vnc_job_free() which iterates and frees the rectangle entries
before freeing the job itself, and use it in both paths.

Also add QLIST_REMOVE() in the worker loop before g_free(entry), so
that entries processed during normal operation are properly unlinked.
Without this, vnc_job_free() would iterate dangling pointers to
already-freed entries, causing use-after-free.

Fixes: bd023f953e ("vnc: threaded VNC server")
Reviewed-by: Daniel P. Berrangé <[email protected]>
Signed-off-by: Marc-André Lureau <[email protected]>
(cherry picked from commit 3cae0b46be)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-13 12:18:48 +03:00
Peter Maydell 4f2e81f0a7 hw/net/rocker: Avoid double-free of l2_flood.group_ids
In of_dpa_cmd_add_l2_flood(), we allocate memory for the
group->l2_flood.group_ids array, freeing any previous array.
However, in the error-exit path we free the group_ids memory but do
not clear the pointer to NULL.  This means that if the guest causes
us to take the error-exit path and then later call the function
again, we will try again to free the memory we already freed.

Fix this by clearing the group_ids pointer in the error exit
path, so we maintain the invariant of "either it points at
allocated memory, or it is NULL" (both being valid to g_free()).

Cc: [email protected]
Fixes: dc488f8880 ("rocker: add new rocker switch device")
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3253
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Message-id: [email protected]
(cherry picked from commit a0721c099b)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-13 12:18:48 +03:00
Zenghui Yu a4ecadcd7b target/arm: Don't skip access flag fault for AccessType_AT
As per the pseudo code from DDI0487 M.a.a (on J1-16021) AArch64.S1Walk():

  // Check descriptor AF bit
  elsif (descriptor<10> == '0' && walkparams.ha == '0' &&
          (!accdesc.acctype IN {AccessType_DC, AccessType_IC} ||
           boolean IMPLEMENTATION_DEFINED "Generate access flag fault on IC/DC operations")) then
      fault.statuscode = Fault_AccessFlag;

an access flag fault should be generated for AccessType_AT, if the AF bit
is 0 and !param.ha.

Besides, we should continue to not raise the access flag fault for
in_debug = true which is what we've been doing previously (before commit
efebeec13d) for LPAE and is what intention of the debugger access
codepath is.

Cc: [email protected]
Fixes: efebeec13d ("target/arm: Skip AF and DB updates for AccessType_AT")
Signed-off-by: Zenghui Yu <[email protected]>
Message-id: [email protected]
Reviewed-by: Peter Maydell <[email protected]>
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit 31b8d287b7)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-13 12:18:48 +03:00
Paolo Bonzini 1b33499c43 lsi53c895a: keep SCSIRequest alive during DMA
Reentrant MMIO can cause the SCSIRequest to be completed, at which
point lsi_request_orphan would drop the last reference.  Anything
that happens afterwards would access freed data.  Keep a reference
to the SCSIRequest and, through req->hba_private, to the lsi_request*
for as long as DMA runs.

Reported-by: Jihe Wang <[email protected]>
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit d459131ff5)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-13 12:18:48 +03:00
Paolo Bonzini 96ef66a733 lsi53c895a: keep lsi_request alive as long as the SCSIRequest
To protect against using the lsi_request after SCSIRequest has been freed,
keep the HBA-private data alive until the last reference to the SCSIRequest
is gone.  Because req->hba_private was used (even if just for an assertion)
to check that the request was still either current or queued, add a boolean
field that is set when the SCSIRequest is cancelled or completed, which
is when the lsi_request would have been unqueued.

Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 7c7aaaa342)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-13 12:18:48 +03:00
Paolo Bonzini 2d69bf45f9 lsi53c895a: keep lsi_request and SCSIRequest in local variables
Protect against changes from reentrant device MMIO during DMA, by always
operating on the same request.

Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 1ca38f84e1)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-13 12:18:48 +03:00
Paolo Bonzini 52ae183c0c lsi53c895a: do not do anything else if a reset is requested by writing ISTAT0
If the device is reset, anything that is done before will not really
be visible.  So do the reset and exit immediately if that is one
of the requests in the value written to ISTAT0.

Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 64807c84e8)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-13 12:18:48 +03:00
Paolo Bonzini 54071d735e lsi53c895a: keep a reference to the device while SCRIPTS execute
SCRIPTS execution can trigger PCI device unplug and consequently
a use-after-free after the unplug returns.  Avoid this by keeping
the device alive.

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3090
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 4862d2c951)
(Mjt: it is CVE-2024-6519, UAF in lsi53c895a)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-13 12:18:43 +03:00
Peter Maydell 4feab33510 scripts/qemu-guest-agent/fsfreeze-hook: Fix syslog-fallback logic
In the fsfreeze script we attempt to implement "log to a file if we
can, and fall back to syslog if we cannot".  We do this with:

  [ ! -w "$LOGFILE" ] && USE_SYSLOG=1
  touch "$LOGFILE" >/dev/null 2>&1 || USE_SYSLOG=1

This has a weird behaviour if it is run in a setup where we have
permissions that would allow us to write to $LOGFILE but it does not
currently exist.  On the first execution, the '-w' fails and so we
set USE_SYSLOG=1.  But since we also do the "touch $LOGFILE" step we
create an empty logfile.  Then on the second time the script is
executed, we see a writeable logfile and will use it.  The effect is
"log to syslog once, then to the logfile thereafter", which is not
likely to be what anybody wants.

Update the condition of the first check to only pick syslog if
the logfile exists but is not writable. This means that:
 * if the logfile doesn't exist but we are able to create it,
   we will create it and use it
 * if the logfile already exists and we can write to it,
   we will use it
 * if the logfile already exists but we can't write to it,
   we will fall back to syslog
 * if the logfile doesn't exist and we can't create it,
   we will fall back to syslog

Cc: [email protected]
Fixes: 85978dfb6b ("qemu-ga: Optimize freeze-hook script logic of logging error")
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Kostiantyn Kostiuk <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Link: https://lore.kernel.org/qemu-devel/[email protected]
Signed-off-by: Kostiantyn Kostiuk <[email protected]>
(cherry picked from commit 08497afcb2)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-31 20:10:04 +03:00
Peter Maydell 976c9167d9 scripts/qemu-guest-agent/fsfreeze-hook: Avoid use of PIPESTATUS
PIPESTATUS is a bash-specific construct, and this script is supposed
to be POSIX shell. We only use it in one place, to capture the exit
status of a command whose output we are piping to 'logger'.

Replace the PIPESTATUS usage with the trick described in
https://unix.stackexchange.com/questions/14270/get-exit-status-of-process-thats-piped-to-another/70675#70675
which uses a command-group to capture the status of the
first process in the pipeline.

Cc: [email protected]
Fixes: 85978dfb6b ("qemu-ga: Optimize freeze-hook script logic of logging error")
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3339
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Kostiantyn Kostiuk <[email protected]>
Link: https://lore.kernel.org/qemu-devel/[email protected]
Signed-off-by: Kostiantyn Kostiuk <[email protected]>
(cherry picked from commit 65b9f4791c)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-31 20:10:04 +03:00
Peter Maydell b223c77aae scripts/qemu-guest-agent/fsfreeze-hook: Avoid bash-isms
The fsfreeze-hook script starts with #!/bin/sh, but it uses
several bash-specific constructs, resulting in misbehaviour
on guest systems where /bin/sh is some other POSIX shell.

Fix the simple ones reported by shellcheck:

In scripts/qemu-guest-agent/fsfreeze-hook line 27:
touch "$LOGFILE" &>/dev/null || USE_SYSLOG=1
                 ^---------^ SC3020 (warning): In POSIX sh, &> is undefined.

In scripts/qemu-guest-agent/fsfreeze-hook line 31:
    local message="$1"
    ^-----------^ SC3043 (warning): In POSIX sh, 'local' is undefined.

In scripts/qemu-guest-agent/fsfreeze-hook line 46:
    log_message "Executing $file $@"
                                 ^-- SC2145 (error): Argument mixes string and array. Use * or separate argument.

In scripts/qemu-guest-agent/fsfreeze-hook line 55:
    if [ $STATUS -ne 0 ]; then
         ^-----^ SC2086 (info): Double quote to prevent globbing and word splitting.

There is also a use of PIPESTATUS that is more complex to fix;
that will be dealt with in a separate commit.

Cc: [email protected]
Fixes: 85978dfb6b ("qemu-ga: Optimize freeze-hook script logic of logging error")
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Kostiantyn Kostiuk <[email protected]>
Link: https://lore.kernel.org/qemu-devel/[email protected]
Signed-off-by: Kostiantyn Kostiuk <[email protected]>
(cherry picked from commit b5abb655fa)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-31 20:10:04 +03:00
Kaixuan Li e78cb08376 hw/nvme: fix heap-buffer-overflow in nvme_abort
In nvme_abort(), the submission queue pointer is dereferenced from the
guest-controlled sqid before validating it with nvme_check_sqid():

    NvmeSQueue *sq = n->sq[sqid];

Since sqid is a 16-bit value (range 0-65535) taken directly from CDW10,
and n->sq[] is typically only max_ioqpairs+1 (65) entries, a malicious
guest can trigger an out-of-bounds heap read by sending an Abort command
with a large sqid.

ASan reports this as heap-buffer-overflow in nvme_abort.

Fix this by moving the array dereference to after the nvme_check_sqid()
bounds validation.

Resolves: https://gitlab.com/qemu-project/qemu/-/issues/3348
Fixes: 75209c071a ("hw/nvme: actually implement abort")
Cc: [email protected]
Signed-off-by: Kaixuan Li <[email protected]>
Signed-off-by: Klaus Jensen <[email protected]>
(cherry picked from commit eb5cc99aff)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-31 20:10:04 +03:00
Pankaj Raghav 64c260df23 hw/nvme: re-enable wzds bit in namespace dlfeat
dlfeat was changed from 0x9 to 0x1 when PI support was added.
It was removed because we can't rely on unmap and have to physically
clear it to get the checksums right but that doesnt mean that we do not
support the bit.

The spec says that if wzds is enabled, then the controller supports
deallocate (DEAC) on write zeroes. But DEAC bit in write zeroes command
is only a hint, the controller might choose to physically write zeroes in
those areas.

As we are sending write zeroes command with BDRV_REQ_MAY_UNMAP to the
underlying block device anyway (if the unmap operation is supported),
change the dlfeat value back to 0x9.

A new flag FALLOC_FL_WRITE_ZEROES has been introduced in linux for
fallocate which will use the wzds bit in dlfeat to quickly zeroout extents
using unmap operation whenever possible[1].

[1] https://lore.kernel.org/linux-fsdevel/[email protected]/

Fixes: 146f720c55 ("hw/block/nvme: end-to-end data protection")
Suggested-by: Klaus Jensen <[email protected]>
Signed-off-by: Pankaj Raghav <[email protected]>
Signed-off-by: Klaus Jensen <[email protected]>
(cherry picked from commit 55720ba97d)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-31 20:10:04 +03:00
Richard Henderson fd10558b42 tcg: Pass host-endian values to plugin_gen_mem_callbacks_*
If the host does not support swapped-endian loads and stores,
then we emulate those within the tcg expanders with explicit
bswap operations.

However, we were passing values to the plugin interface in
the middle of those bswap operations, which meant that we
would pass values of the wrong endianness to plugins when
running on hosts without swapped-endian loads and stores.

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3351
Signed-off-by: Richard Henderson <[email protected]>
Reviewed-by: Pierrick Bouvier <[email protected]>
Tested-by: Pierrick Bouvier <[email protected]>
Link: https://lore.kernel.org/qemu-devel/[email protected]
Signed-off-by: Pierrick Bouvier <[email protected]>
(cherry picked from commit 539421a428)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-31 20:10:04 +03:00
Jenny Guanni Qu 84a8f3ed1d hw/audio/sb16: validate VMState fields in post_load
The SB16 VMState loads in_index and out_data_len as raw INT32
values with no bounds validation. A crafted migration stream or
VM snapshot can set these to values exceeding their respective
buffer sizes (in2_data[10] and out_data[50]), causing heap OOB
write in dsp_write() and heap OOB read in dsp_read().

Add bounds checks in sb16_post_load() to reject invalid values
before they can be used as array indices.

Resolves: https://gitlab.com/qemu-project/qemu/-/issues/3326
Reported-by: Jenny Guanni Qu <[email protected]>
Signed-off-by: Jenny Guanni Qu <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit cb1e8c18df)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-31 20:10:04 +03:00
Paolo Bonzini 11678b9ad7 tdx: fix use-after-free in tdx_fetch_cpuid
This is mostly harmless right now because the "if" is never
hit, but the code as written makes no sense.

Reported-by: Stefan Weil <[email protected]>
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit f093ee7ac3)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-31 20:10:04 +03:00
GuoHan Zhao 6928b79753 block/curl: free s->password in cleanup paths
When password-secret is used, curl_open() resolves it with
qcrypto_secret_lookup_as_utf8() and stores the returned buffer in
s->password.

Unlike s->proxypassword, s->password is not freed either in the open
failure path or in curl_close(), so the resolved secret leaks once it
has been allocated.

Free s->password in both cleanup paths.

Fixes: 1bff960642 ('curl: add support for HTTP authentication parameters')
Signed-off-by: GuoHan Zhao <[email protected]>
Message-ID: <[email protected]>
Reviewed-by: Kevin Wolf <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit 51fc8443c1)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-31 20:10:04 +03:00
Hanna Czenczek c31a6ebade linux-aio: Resubmit tails of short reads/writes
Short reads/writes can happen.  One way to reproduce them is via our
FUSE export, with the following diff applied (%s/escaped // to apply --
if you put plain diffs in commit messages, git-am will apply them, and I
would rather avoid breaking FUSE accidentally via this patch):

escaped diff --git a/block/export/fuse.c b/block/export/fuse.c
escaped index a2a478d293..67dc50a412 100644
escaped --- a/block/export/fuse.c
escaped +++ b/block/export/fuse.c
@@ -828,7 +828,7 @@ static ssize_t coroutine_fn GRAPH_RDLOCK
 fuse_co_init(FuseExport *exp, struct fuse_init_out *out,
              const struct fuse_init_in_compat *in)
 {
-    const uint32_t supported_flags = FUSE_ASYNC_READ | FUSE_ASYNC_DIO;
+    const uint32_t supported_flags = FUSE_ASYNC_READ;

     if (in->major != 7) {
         error_report("FUSE major version mismatch: We have 7, but kernel has %"
@@ -1060,6 +1060,8 @@ fuse_co_read(FuseExport *exp, void **bufptr, uint64_t offset, uint32_t size)
     void *buf;
     int ret;

+    size = MIN(size, 4096);
+
     /* Limited by max_read, should not happen */
     if (size > FUSE_MAX_READ_BYTES) {
         return -EINVAL;
@@ -1110,6 +1112,8 @@ fuse_co_write(FuseExport *exp, struct fuse_write_out *out,
     int64_t blk_len;
     int ret;

+    size = MIN(size, 4096);
+
     QEMU_BUILD_BUG_ON(FUSE_MAX_WRITE_BYTES > BDRV_REQUEST_MAX_BYTES);
     /* Limited by max_write, should not happen */
     if (size > FUSE_MAX_WRITE_BYTES) {

Then:
$ ./qemu-img create -f raw test.raw 8k
Formatting 'test.raw', fmt=raw size=8192
$ ./qemu-io -f raw -c 'write -P 42 0 8k' test.raw
wrote 8192/8192 bytes at offset 0
8 KiB, 1 ops; 00.00 sec (64.804 MiB/sec and 8294.9003 ops/sec)
$ hexdump -C test.raw
00000000  2a 2a 2a 2a 2a 2a 2a 2a  2a 2a 2a 2a 2a 2a 2a 2a  |****************|
*
00002000

With aio=threads, short I/O works:
$ storage-daemon/qemu-storage-daemon \
    --blockdev file,node-name=test,filename=test.raw \
    --export fuse,id=exp,node-name=test,mountpoint=test.raw,writable=true

Other shell:
$ ./qemu-io --image-opts -c 'read -P 42 0 8k' \
    driver=file,filename=test.raw,cache.direct=on,aio=threads
read 8192/8192 bytes at offset 0
8 KiB, 1 ops; 00.00 sec (36.563 MiB/sec and 4680.0923 ops/sec)
$ ./qemu-io --image-opts -c 'write -P 23 0 8k' \
    driver=file,filename=test.raw,cache.direct=on,aio=threads
wrote 8192/8192 bytes at offset 0
8 KiB, 1 ops; 00.00 sec (35.995 MiB/sec and 4607.2970 ops/sec)
$ hexdump -C test.raw
00000000  17 17 17 17 17 17 17 17  17 17 17 17 17 17 17 17  |................|
*
00002000

But with aio=native, it does not:
$ ./qemu-io --image-opts -c 'read -P 23 0 8k' \
    driver=file,filename=test.raw,cache.direct=on,aio=native
Pattern verification failed at offset 0, 8192 bytes
read 8192/8192 bytes at offset 0
8 KiB, 1 ops; 00.00 sec (86.155 MiB/sec and 11027.7900 ops/sec)
$ ./qemu-io --image-opts -c 'write -P 42 0 8k' \
    driver=file,filename=test.raw,cache.direct=on,aio=native
write failed: No space left on device
$ hexdump -C test.raw
00000000  2a 2a 2a 2a 2a 2a 2a 2a  2a 2a 2a 2a 2a 2a 2a 2a  |****************|
*
00001000  17 17 17 17 17 17 17 17  17 17 17 17 17 17 17 17  |................|
*
00002000

This patch fixes that.

Reviewed-by: Kevin Wolf <[email protected]>
Signed-off-by: Hanna Czenczek <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit 7eca3d4883)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-31 20:10:04 +03:00
Hanna Czenczek 7997e9e7fa linux-aio: Put all parameters into qemu_laiocb
Put all request parameters into the qemu_laiocb struct, which will allow
re-submitting the tail of short reads/writes.

Reviewed-by: Kevin Wolf <[email protected]>
Signed-off-by: Hanna Czenczek <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit cc03b62df4)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-31 20:10:04 +03:00
Tao Ding fb16dc31e1 hw/dma/pl080: Fix transfer logic in PL080
The logic in the PL080 for transferring data has multiple bugs:

 * The TransferSize field in the channel control register counts
   in units of the source width; because our loop may do multiple
   source loads if the destination width is greater than the
   source width, we need to decrement it by (xsize / swidth),
   not by 1, each loop

 * It is documented in the TRM that it is a software error to program
   the source and destination width such that SWidth < DWidth and
   TransferSize * SWidth is not a multiple of DWidth. (This would
   mean that there isn't enough data to do a full final destination
   write.) We weren't doing anything sensible with this case.
   The TRM doesn't document what the hardware actually does (though
   it drops some hints that suggest that it probably over-reads
   from the source).

 * In the loop to write to the destination, each loop adds swidth
   to  ch->dest for each loop and also uses (ch->dest + n) as the
   destination address. This moves the destination address on
   further than we should each time round the loop, and also
   is incrementing ch->dest by swidth when it should be dwidth.

This patch fixes these problems:
 * decrement TransferSize by the correct amount
 * log and ignore the transfer size mismatch case
 * correct the loop logic for the destination writes

A repro case which exercises some of this is as follows.  It
configures swidth to 1 byte, dwidth to 4 bytes, and transfer size 4,
for a transfer from 0x00000000 to 0x000010000.  Examining the
destination memory in the QEMU monitor should show that the
source data 0x44332211 has all been copied, but before this
fix it is not:

    ./qemu-system-arm -M versatilepb -m 128M -nographic -S \
    -device loader,addr=0x00000000,data=0x44332211,data-len=4 \
    -device loader,addr=0x00001000,data=0x00000000,data-len=4 \
    -device loader,addr=0x10130030,data=0x00000001,data-len=4 \
    -device loader,addr=0x10130100,data=0x00000000,data-len=4 \
    -device loader,addr=0x10130104,data=0x00001000,data-len=4 \
    -device loader,addr=0x10130108,data=0x00000000,data-len=4 \
    -device loader,addr=0x1013010C,data=0x9e47f004,data-len=4 \
    -device loader,addr=0x10130110,data=0x0000c001,data-len=4

Without this patch the QEMU monitor shows:
    (qemu) xp /1wx 0x00001000
    00001000: 0x00002211

Correct result:
    (qemu) xp /1wx 0x00001000
    00001000: 0x44332211

Cc: [email protected]
Suggested-by: Peter Maydell <[email protected]>
Signed-off-by: Tao Ding <[email protected]>
[PMM: Wrote up what we are fixing in the commit message]
Reviewed-by: Peter Maydell <[email protected]>
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit 5a2fa06b09)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-31 20:10:04 +03:00
Peter Maydell 385d3e593d linux-user/i386/signal.c: Correct definition of target_fpstate_32
Our definition of the target_fpstate_32 struct doesn't match the
kernel's version.  We only use this struct definition in the
definition of 'struct sigframe', where it is used in a field that is
present only for legacy reasons to retain the offset of the following
'extramask' field.  So really all that matters is its length, and we
do get that right; but our previous definition using
X86LegacySaveArea implicitly added an extra alignment constraint
(because X86LegacySaveArea is tagged as 16-aligned) which the real
target_fpstate_32 does not have.  Because we allocate and use a
'struct sigframe' on the guest's stack with the guest's alignment
requirements, this resulted in the undefined-behaviour sanitizer
complaining during 'make check-tcg' for i386-linux-user:

../../linux-user/i386/signal.c:471:35: runtime error: member access within misaligned address 0x1000c07f75ec for type 'struct sigframe', which requires 16 byte alignment
0x1000c07f75ec: note: pointer points here
  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00
              ^

../../linux-user/i386/signal.c:808:5: runtime error: member access within misaligned address 0x1000c07f75f4 for type 'struct target_sigcontext_32', which requires 8 byte alignment
0x1000c07f75f4: note: pointer points here
  0a 00 00 00 33 00 00 00  00 00 00 00 2b 00 00 00  2b 00 00 00 40 05 80 40  f4 7f 10 08 58 05 80 40
              ^

and various similar errors.

Replace the use of X86LegacyXSaveArea with a set of fields that match
the kernel _fpstate_32 struct, and assert that the length is correct.
We could equally have used
   uint8_t legacy_area[512];
but following the kernel is probably less confusing overall.

Since in target/i386/cpu.h we assert that X86LegacySaveArea is 512
bytes, and in linux-user/i386/signal.c we assert that
target_fregs_state is (32 + 80) bytes, the new assertion confirms
that we didn't change the size of target_fpstate_32 here, only its
alignment requirements.

Cc: [email protected]
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Message-id: [email protected]
(cherry picked from commit 0376e9c2dd)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-31 20:10:04 +03:00
Jose Martins 00a49b69c5 target/arm: fix s2prot not set for two-stage PMSA translations
Commit a811c5dafb ("target/arm: Implement get_S2prot_indirect")
changed get_phys_addr_twostage() to combine stage 1 and stage 2
permissions using the new s2prot field:

  result->f.prot = s1_prot & result->s2prot;

The LPAE stage 2 path sets result->s2prot explicitly, but the PMSA
stage 2 path (get_phys_addr_pmsav8) only sets result->f.prot, leaving
s2prot at zero. This causes the combined permission to be zero,
resulting in addr_read being set to -1 in the TLB entry and triggering
an assertion in atomic_mmu_lookup() when the guest executes an atomic
instruction on a two-stage PMSA platform (e.g. Cortex-R52 with EL2).

Set s2prot from f.prot after the PMSA stage 2 lookup, consistent with
what the LPAE path does.

Cc: [email protected]
Fixes: a811c5dafb ("target/arm: Implement get_S2prot_indirect")
Signed-off-by: Jose Martins <[email protected]>
[PMM: refer to the right commit in the commit message]
Reviewed-by: Peter Maydell <[email protected]>
Message-id: [email protected]
Reviewed-by: Gustavo Romero <[email protected]>
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit 32ebd6c09c)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-31 20:10:04 +03:00
Cédric Le Goater 3fd0091d45 hw/ssi/aspeed_smc: Convert mem ops to read/write_with_attrs for error handling
Error conditions (invalid flash mode, unwritable flash) now return
MEMTX_ERROR instead of silently succeeding or returning undefined
values.

This allows the memory subsystem to properly propagate transaction
errors to the guest, improving QEMU reliability.

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3335
Reviewed-by: Jamin Lin <[email protected]>
Link: https://lore.kernel.org/qemu-devel/[email protected]
Signed-off-by: Cédric Le Goater <[email protected]>
(cherry picked from commit 80c5be9458)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-31 20:10:04 +03:00
Cédric Le Goater 53bb480853 hw/net/ftgmac100: Improve DMA error handling
Currently, DMA memory operation errors in the ftgmac100 model are not
all tested and this can lead to a guest-triggerable denial of service
as described in https://gitlab.com/qemu-project/qemu/-/work_items/3335.

To fix this, check the return value of ftgmac100_write_bd() in the TX
path and exit the TX loop on error to prevent further processing. In
the event of a DMA error, also set FTGMAC100_INT_AHB_ERR interrupt
flag as appropriate.

The FTGMAC100_INT_AHB_ERR interrupt status bit only applies to the
AST2400 SoC; on newer Aspeed SoCs, it is a reserved bit.
Nevertheless, since it is supported by the Linux driver and it should
be safe to use in the QEMU implementation across all SoCs.

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3335
Signed-off-by: Cédric Le Goater <[email protected]>
Reviewed-by: Jamin Lin <[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 fa4a759fc1)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-31 20:10:04 +03:00
Davidlohr Bueso 4e5251eed6 hw/cxl: Exclude Discovery from Media Operation Discovery output
Per CXL 4.0 Table 8-331, the Discovery operation "returns a list of
all Media Operations that the device supports, with the exception of
the Discovery operation (Class=0, Subclass=0)."

Filter out Discovery entries when building the output list and adjust
total_supported_operations accordingly.

Fixes: 77a8e9fe0e ("hw/cxl/cxl-mailbox-utils: Add support for Media operations discovery commands cxl r3.2 (8.2.10.9.5.3)")
Reviewed-by: Jonathan Cameron <[email protected]>
Signed-off-by: Davidlohr Bueso <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit 20beec283b)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-31 20:10:04 +03:00
Davidlohr Bueso 207a75123c hw/cxl: Respect Media Operation max ops discovery semantics
The Discovery rejects requests where start_index + num_ops
exceeds the total number of supported operations. Per CXL 4.0
Table 8-332, num_ops is the "Maximum number of Media Operation to
return" - a maximum, not an exact count. The device should return
up to that many entries, not reject the request.

Cap num_ops to the available entries from start_index instead of
erroring the command.

Fixes: 77a8e9fe0e ("hw/cxl/cxl-mailbox-utils: Add support for Media operations discovery commands cxl r3.2 (8.2.10.9.5.3)")
Reviewed-by: Jonathan Cameron <[email protected]>
Signed-off-by: Davidlohr Bueso <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit bc72b2996c)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-31 20:10:04 +03:00
Jenny Guanni Qu 4ac6a8ae82 hw/usb/hcd-ohci: check for MPS=0 to avoid infinite loop
When a guest sets MaxPacketSize to 0 in an OHCI Endpoint Descriptor,
ohci_service_td() transfers 0 bytes per iteration. The Transfer
Descriptor never completes because CBP never advances toward BE,
causing ohci_service_ed_list() to loop indefinitely and hang QEMU.

Add a check for MPS==0 after extracting the field from ED flags.
If MPS is zero, call ohci_die() to reset the controller and return
an error, preventing the infinite loop.

Fixes: CVE-2026-3890
Reported-by: Jenny Guanni Qu <[email protected]>
Signed-off-by: Jenny Guanni Qu <[email protected]>
Reviewed-by: Peter Maydell <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit 129922c2bc)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-31 20:10:04 +03:00
Paolo Bonzini 7ea57b6806 rust: suggest passing --locked to "cargo install"
Without the option, cargo will try using the latest version of the
dependencies of bindgen-cli. While it will obviously respect the
constraints in Cargo.toml, old versions of Cargo do not have
version-constrained resolution and will choke on dependencies
that need Rust 2024.

Cc: Daniel P. Berrangé <[email protected]>
Cc: Peter Maydell <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 6257754bb9)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-31 20:10:04 +03:00
Max Chou 6eb0fabd11 target/riscv: rvv: Fix page probe issues in vext_ldff
Commit 17288e38be ("optimize the memory probing for vector
fault-only-first loads") introduced an optimization that moved from
per-element probing to a fast-path broad probe. Unfortunately it
introduced following bugs in cross-page handling:

- Wrong condition for second page probing: checked "env->vl > elems"
  instead of "env->vl > elems + env->vstart", failing to account for
  the vstart offset.

- Incorrect second page address calculation: used
  "addr + (elems << log2_esz)" instead of "addr + page_split".
  For segment loads (nf > 1), this would probe the wrong address,not
  at the page boundary.

- Wrong second page probe size: used "elems * msize" (the first page
  size) instead of calculating the remaining size as
  "(env->vl - env->vstart) * msize - page_split". This would probe
  too little memory and could miss faults.

This commit fixes these bugs by leveraging the probe_pages helper
which automatically handles cross-page memory accesses correctly.

Fixes: 17288e38be ("optimize the memory probing for vector fault-only-first loads.")

Signed-off-by: Max Chou <[email protected]>
Acked-by: Alistair Francis <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit 0e8ad6a846)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-31 20:10:04 +03:00
Max Chou fa3fd597a1 target/riscv: rvv: Fix missing flags merge in probe_pages for cross-page accesses
When probe_pages probes a memory region that spans two pages, it calls
probe_access_flags twice - once for each page. However, the flags from
the second page probe were overwriting the flags from the first page
instead of being merged together.

Signed-off-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 5568177738)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-31 20:10:04 +03:00
Marc-André Lureau 2a28de12ba virtio-gpu: fix overflow check when allocating 2d image
The calc_image_hostmem() comment says pixman_image_create_bits() checks
for overflow. However, this relied on the facts that "bits" was NULL and
it performed it when it was introduced. Since commit 9462ff4695, the
"bits" argument can be provided and the check is no longer applied.

Promotes the computation to uint64_t and adds an explicit overflow check
to avoid potential later OOB read/write on the image data.

Fixes: CVE-2026-3886
Fixes: ZDI-CAN-27578
Fixes: 9462ff4695 ("virtio-gpu/win32: allocate shareable 2d resources/images")
Reported-by: Zero Day Initiative <[email protected]>
Signed-off-by: Marc-André Lureau <[email protected]>
Reviewed-by: Akihiko Odaki <[email protected].i.u-tokyo.ac.jp>
Message-Id: <[email protected]>
(cherry picked from commit c035d5eadf)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-31 20:10:04 +03:00
Fiona Ebner 8884c7559a ui/vdagent: add migration blocker when machine version < 10.1
In QEMU 10.1, commit 5d56bff11e ("ui/vdagent: add migration support")
added migration support for the vdagent chardev and commit 42000e0013
("ui/vdagent: remove migration blocker") removed the migration
blocker. No compat for older machine versions was added, so migration
with pre-10.1 machine version, from a 10.1 binary to a pre-10.1 binary
will result in a failure when loading the VM state in the target
instance:

> Unknown savevm section or instance 'vdagent' 0. Make sure that your
> current VM setup matches your saved VM setup, including any
> hotplugged devices

Add a compat flag to block migration when the machine version is less
than 10.1 to avoid this.

Cc: [email protected]
Fixes: 42000e0013 ("ui/vdagent: remove migration blocker")
Signed-off-by: Fiona Ebner <[email protected]>
Reviewed-by: Fabiano Rosas <[email protected]>
Reviewed-by: Marc-André Lureau <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit 6f23dde620)
(Mjt: backport to 10.2.x: qdev-properties.h path and vdagent_chr_open return)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-31 20:10:04 +03:00
Fabiano Rosas d9699fd014 io: Fix TLS bye task leak
Recent fixes to TLS tasks memory handling have left the TLS bye task
uncovered. Fix by freeing the task in the same way the handshake task
is freed.

Direct leak of 704 byte(s) in 4 object(s) allocated from:
    #1 0x7f5909b1d6a0 in g_malloc0 ../glib/gmem.c:163
    #2 0x557650496d61 in qio_task_new ../io/task.c:58:12
    #3 0x557650475d7f in qio_channel_tls_bye ../io/channel-tls.c:352:12
    #4 0x55764f7a1bb4 in migration_tls_channel_end ../migration/tls.c:159:5
    #5 0x55764f709750 in migration_ioc_shutdown_gracefully ../migration/multifd.c:462:9
    #6 0x55764f6fcf53 in multifd_send_terminate_threads ../migration/multifd.c:493:13
    #7 0x55764f6fcafb in multifd_send_shutdown ../migration/multifd.c:580:5
    #8 0x55764f6e1b14 in migration_cleanup ../migration/migration.c:1323:9
    #9 0x55764f6f5bac in migration_cleanup_bh ../migration/migration.c:1350:5

Fixes: d39d0f3acd ("io: fix cleanup for TLS I/O source data on cancellation")
Fixes: f8943633a9 ("io: fix cleanup for TLS I/O source data on cancellation") in 10.2.x series
Reviewed-by: Daniel P. Berrangé <[email protected]>
Acked-by: Daniel P. Berrangé <[email protected]>
Link: https://lore.kernel.org/qemu-devel/[email protected]
Signed-off-by: Fabiano Rosas <[email protected]>
(cherry picked from commit c20f143cc9)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-31 20:08:56 +03:00
Shivang Upadhyay 44b84a2d94 ppc/pnv: generate dtb after machine initialization is complete
Currently, the machine dtb is generated in pnv_init(), before all devices
are fully initialized. This can result in an incomplete dtb for the system,
as seen in bug [1].

Fix this by deferring dtb generation until machine initialization is complete,
using the machine_init_done_notifier hook.

[1] https://lore.kernel.org/all/20260323231612.GA2637687@ax162/

Cc: Aditya Gupta <[email protected]>
Cc: Harsh Prateek Bora <[email protected]>
Cc: BALATON Zoltan <[email protected]>
Cc: [email protected]
Reported-by: Nathan Chancellor <[email protected]>
Suggested-by: Peter Maydell <[email protected]>
Fixes: a16d4c2f16 ("ppc/pnv: fix dumpdtb option")
Fixes: 43ed0362d0 ("ppc/pnv: fix dumpdtb option") in 10.2.x series
Signed-off-by: Shivang Upadhyay <[email protected]>
Tested-by: Nathan Chancellor <[email protected]>
Reviewed-by: Aditya Gupta <[email protected]>
Reviewed-by: Peter Maydell <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit ba48bff09f)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-31 20:04:13 +03:00
Shivang Upadhyay 43ed0362d0 ppc/pnv: fix dumpdtb option
The '-machine dumpdtb' command line option stopped working on
PowerPC/pnv systems after recent design change [1].

Fixing this by generating fdt blob in `pnv_init`.

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

Cc: Aditya Gupta <[email protected]>
Cc: Harsh Prateek Bora <[email protected]>
Cc: Peter Maydell <[email protected]>
Cc: BALATON Zoltan <[email protected]>
Cc: [email protected]
Fixes: 8fd2518ef2 ("hw: Centralize handling of -machine dumpdtb option")
Signed-off-by: Shivang Upadhyay <[email protected]>
Reviewed-by: Peter Maydell <[email protected]>
Reviewed-by: Aditya Gupta <[email protected]>
Link: https://lore.kernel.org/qemu-devel/[email protected]
Signed-off-by: Harsh Prateek Bora <[email protected]>
(cherry picked from commit a16d4c2f16)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-18 23:33:21 +03:00
Fiona Ebner fed9f7ac6a block/mirror: fix assertion failure upon duplicate complete for job using 'replaces'
If s->replace_blocker was already set by an earlier invocation of
mirror_complete(), then there will be an assertion failure when
error_setg() is called for it a second time. The bdrv_op_block_all()
and bdrv_ref() operations should only be done a single time too.

Signed-off-by: Fiona Ebner <[email protected]>
Message-Id: <[email protected]>
Reviewed-by: Hanna Czenczek <[email protected]>
Signed-off-by: Hanna Czenczek <[email protected]>
(cherry picked from commit 9ac85f4cc7)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-18 23:28:21 +03:00
Alberto Garcia 444d9054a7 throttle-group: Fix race condition in throttle_group_restart_queue()
When a timer is fired a pending I/O request is restarted and
tg->any_timer_armed is reset so other requests can be scheduled.

However we're resetting any_timer_armed first in timer_cb() before
the request is actually restarted, and there's a window between both
moments in which another thread can arm the same timer, hitting an
assertion in throttle_group_restart_queue().

This can be solved by deferring the reset of tg->any_timer_armed to
the moment when the queue is actually restarted, which is protected by
tg->lock, preventing other threads from arming the timer before that.

In addition to that, throttle_group_restart_tgm() is also updated to
hold tg->lock while the timer is being inspected. Here we consider
three different scenarios:

- If the tgm has a timer set, fire it immediately
- If another tgm has a timer set, restart the queue anyway
- If there is no timer set in this group then simulate a timer that
  fires immediately, by setting tg->any_timer_armed in order to
  prevent other threads from arming a timer in the meantime.

Resolves: https://gitlab.com/qemu-project/qemu/-/issues/3194
Signed-off-by: Alberto Garcia <[email protected]>
Message-Id: <825598ef34ad384d936da19d634eda75598508f7.1773316842.git.berto@igalia.com>
Signed-off-by: Hanna Czenczek <[email protected]>
(cherry picked from commit 9c8430f5d6)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-18 23:28:21 +03:00
Pierrick Bouvier 9f70db93b2 contrib/plugins/uftrace.c: fix depth for exit events
Uftrace plugin was recording wrong depth for exit events, resulting in
incoherent traces, especially for partial ones.

Thanks to Honggyu Kim, one of the original author of uftrace, who
spotted the issue.
https://github.com/namhyung/uftrace/pull/2031#issuecomment-4051762627

Reviewed-by: Pierrick Bouvier <[email protected]>
Link: https://lore.kernel.org/qemu-devel/[email protected]
Signed-off-by: Pierrick Bouvier <[email protected]>
(cherry picked from commit 48221e3716)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-18 08:09:14 +03:00
Sergei Heifetz 982e99a451 target/i386: fix NULL pointer dereference in legacy-cache=off handling
The check that xcc->model is not NULL occurs after it is dereferenced
inside x86_cpu_get_versioned_cache_info(), so something like
`-cpu host,legacy-cache=off` leads to a segfault rather than an error.
This patch fixes that.

Fixes: cca0a000d0 ("target/i386: allow versioned CPUs to specify new cache_info")
Signed-off-by: Sergei Heifetz <[email protected]>
Reviewed-by: Vladimir Sementsov-Ogievskiy <[email protected]>
Reviewed-by: Zhao Liu <[email protected]>
Reviewed-by: Michael Tokarev <[email protected]>
[Mjt: simplify the following condition too]
Signed-off-by: Michael Tokarev <[email protected]>
(cherry picked from commit 2741d2cc39)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-18 08:08:21 +03:00
Tao Ding 61f9a8b128 hw/dma/pl080: Ignore bottom 2 bits of LLI register
The PL080 channel LLI (linked list item) register has bits [31:2] of
the address of the next LLI in bits [31:2], with bit [1] reserved
and bits [0] the AHB master select. We were incorrectly using the
whole register value as the address, which meant that if the guest
programmed something into the AHB master select bit we would use
an incorrect address, and read incorrect data from memory.

The following reproducer creates a setup which has bit 0 set in
an LLI value:

Configuration
    ../configure --target-list=arm-softmmu --enable-debug
Reproducer
    ./qemu-system-arm -M versatilepb -m 128M -nographic -S \
     -device loader,addr=0x00002000,data=0x00000004,data-len=4 \
     -device loader,addr=0x00002004,data=0x00001004,data-len=4 \
     -device loader,addr=0x00002008,data=0x00000000,data-len=4 \
     -device loader,addr=0x0000200c,data=0x9e4bf001,data-len=4 \
     -device loader,addr=0x00000000,data=0x44332211,data-len=4 \
     -device loader,addr=0x00000004,data=0x88776655,data-len=4 \
     -device loader,addr=0x00001000,data=0x00000000,data-len=4 \
     -device loader,addr=0x00001004,data=0x00000000,data-len=4 \
     -device loader,addr=0x10130030,data=0x00000001,data-len=4 \
     -device loader,addr=0x10130100,data=0x00000000,data-len=4 \
     -device loader,addr=0x10130104,data=0x00001000,data-len=4 \
     -device loader,addr=0x10130108,data=0x00002001,data-len=4 \
     -device loader,addr=0x1013010C,data=0x1e4bf001,data-len=4 \
     -device loader,addr=0x10130110,data=0x0000c001,data-len=4

The correct result with this bug fix:
    (qemu) xp /1wx 0x00001000
     00001000: 0x44332211
    (qemu) xp /1wx 0x00001004
     00001004: 0x88776655

Cc: [email protected]
Signed-off-by: Tao Ding <[email protected]>
[PMM: Adjusted commit message]
Reviewed-by: Peter Maydell <[email protected]>
Message-id: cb35c1b622674da7a2b70691402132f691933f2c.1773301927.git.dingtao0430@163.com
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit f9b16f7915)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-18 08:06:17 +03:00
Tao Ding 4244a2d65d hw/dma/pl080: Update interrupts after pl080_run()
In the codepath in pl080_write() where we run the DMA engine
after a change in the channel configuration register, we were
missing a pl080_update() call, which meant that we weren't
raising any interrupts generated by that DMA transfer.

A repro case for this is to program the PL080 and then
check the interrupt status by looking at the PL190 status
register, since the PL080 interrupt output is connected
to input 17 of the PL190. We look at the register value via
the QEMU monitor:

Reproducer
    ./qemu-system-arm -M versatilepb -m 128M -nographic -S \
    -device loader,addr=0x00000000,data=0x11223344,data-len=4 \
    -device loader,addr=0x00001000,data=0x00000000,data-len=4 \
    -device loader,addr=0x10130030,data=0x00000001,data-len=4 \
    -device loader,addr=0x10130100,data=0x00000000,data-len=4 \
    -device loader,addr=0x10130104,data=0x00001000,data-len=4 \
    -device loader,addr=0x10130108,data=0x00000000,data-len=4 \
    -device loader,addr=0x1013010C,data=0x9e4bf001,data-len=4 \
    -device loader,addr=0x10130110,data=0x0000c001,data-len=4

Qemu monitor
    (qemu) xp /1wx 0x10140008
    10140008: 0x00000000

The correct result after this fix:
    (qemu) xp /1wx 0x10140008
    10140008: 0x00020000

Cc: [email protected]
Signed-off-by: Tao Ding <[email protected]>
Message-id: 7584486ba62bc6d767c0d132dc843067f8c5efff.1773301927.git.dingtao0430@163.com
Reviewed-by: Peter Maydell <[email protected]>
[PMM: Adjusted commit message]
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit b6e61d1cc3)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-18 08:05:58 +03:00
Peter Maydell 80d0acaf6c hw/dma/pl080: Handle bogus swidth and dwidth in transfers
The PL080 TRM states that the DWidth and SWidth fields of the channel
control registers can only validly specify widths up to 32 bits (i.e.
values from 0 to 2) and all other values are reserved.

Currently we don't check this, so if the guest specifies an invalid
value we will transfer more data into our local 'buff[]' array than
it can hold.

Check the widths; since the TRM doesn't clearly specify any behaviour
for what to do on invalid values, we choose to log them and then
ignore the channel for transfers.

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/3203
Reviewed-by: Jim MacArthur <[email protected]>
Signed-off-by: Peter Maydell <[email protected]>
Message-id: [email protected]
(cherry picked from commit 37c9f6fce5)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-18 08:05:58 +03:00
Razvan Ghiorghe 23e03a02fd linux-user: fix mremap with old_size=0 for shared mappings
When old_size is zero and old_address refers to a shareable mapping,
mremap() should create a new mapping of the same pages according to the
mremap(2) man page. The MREMAP_MAYMOVE flag must be specified in this case.

Previously, QEMU's target_mremap() rejected this valid case with EFAULT
during the initial validation, before checking for the special
old_size == 0 behaviour.

This patch adds proper handling for old_size == 0:
- Validates that MREMAP_MAYMOVE flag is set (required by man spec)
- Passes the call through to the host mremap()
- Creates a new mapping without invalidating the original, with both
  being valid and sharing the same physical memory frames.
- Ensures the new mapping address falls within the valid guest address
  region before returning it to the guest.

Tested with the reproducer from the issue on qemu-riscv64, qemu-hppa,
and qemu-aarch64.

Resolves: https://gitlab.com/qemu-project/qemu/-/issues/3105
Signed-off-by: Razvan Ghiorghe <[email protected]>
Tested-by: Helge Deller <[email protected]>
Reviewed-by: Helge Deller <[email protected]>
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit 5e5b278d2b)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-18 08:05:36 +03:00
Razvan Ghiorghe ef06d7853c linux-user: Fix zero_bss for RX PT_LOAD segments
zero_bss() incorrectly assumed that any PT_LOAD containing .bss must be
writable, rejecting valid ELF binaries where .bss overlaps the tail of
an RX file-backed page.

Instead of failing, temporarily enable write access on the overlapping
page to zero the fractional bss range, then restore the original page
permissions once initialization is complete.

Resolves: https://gitlab.com/qemu-project/qemu/-/issues/3179
Signed-off-by: Razvan Ghiorghe <[email protected]>
Reviewed-by: Helge Deller <[email protected]>
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit 2ff529c6f6)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-18 08:05:36 +03:00
Peter Maydell 1c1bf4f638 hw/net/rtl8319: Work around GCC sanitizer / -Wstringop-overflow bug
If you compile QEMU with GCC with -fsanitize=address and
-Wstringop-overflow, this causes GCC to produce a false-positive
warning which it does not produce when the sanitizer is not enabled
(and which makes compilation fail if you're using -Werror, as we do
by default for builds from git):

../../hw/net/rtl8139.c: In function ‘rtl8139_io_writeb’:
../../hw/net/rtl8139.c:2264:17: error: writing 8 bytes into a region of size 0 [-Werror=stringop-overflow=]
 2264 |                 memcpy(data_to_checksum, saved_ip_header + 12, 8);
      |                 ^
In file included from ../../hw/net/rtl8139.c:62:
/home/pm215/qemu/include/net/eth.h:50:14: note: at offset [8, 48] into destination object ‘ip_ver_len’ of size 1
   50 |     uint8_t  ip_ver_len;     /* version and header length */
      |              ^~~~~~~~~~
../../hw/net/rtl8139.c:2192:21: error: writing 8 bytes into a region of size 0 [-Werror=stringop-overflow=]
 2192 |                     memcpy(data_to_checksum, saved_ip_header + 12, 8);
      |                     ^
/home/pm215/qemu/include/net/eth.h:50:14: note: at offset [8, 48] into destination object ‘ip_ver_len’ of size 1
   50 |     uint8_t  ip_ver_len;     /* version and header length */
      |              ^~~~~~~~~~
../../hw/net/rtl8139.c:2192:21: error: writing 8 bytes into a region of size 0 [-Werror=stringop-overflow=]
 2192 |                     memcpy(data_to_checksum, saved_ip_header + 12, 8);
      |                     ^
/home/pm215/qemu/include/net/eth.h:50:14: note: at offset [8, 48] into destination object ‘ip_ver_len’ of size 1
   50 |     uint8_t  ip_ver_len;     /* version and header length */
      |              ^~~~~~~~~~
In file included from /home/pm215/qemu/include/system/memory.h:21,
                 from /home/pm215/qemu/include/hw/pci/pci.h:4,
                 from /home/pm215/qemu/include/hw/pci/pci_device.h:4,
                 from ../../hw/net/rtl8139.c:54:
In function ‘stl_he_p’,
    inlined from ‘stl_be_p’ at /home/pm215/qemu/include/qemu/bswap.h:371:5,
    inlined from ‘rtl8139_cplus_transmit_one’ at ../../hw/net/rtl8139.c:2244:21,
    inlined from ‘rtl8139_cplus_transmit’ at ../../hw/net/rtl8139.c:2345:28,
    inlined from ‘rtl8139_io_writeb’ at ../../hw/net/rtl8139.c:2728:17:
/home/pm215/qemu/include/qemu/bswap.h:284:5: error: writing 4 bytes into a region of size 0 [-Werror=stringop-overflow=]
  284 |     __builtin_memcpy(ptr, &v, sizeof(v));
      |     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/pm215/qemu/include/net/eth.h: In function ‘rtl8139_io_writeb’:
/home/pm215/qemu/include/net/eth.h:50:14: note: at offset [24, 64] into destination object ‘ip_ver_len’ of size 1
   50 |     uint8_t  ip_ver_len;     /* version and header length */
      |              ^~~~~~~~~~

This has been triaged as a bug in GCC:
 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=114494
 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=99673
(the sanitizer pass rewrites the IR in a way that conflicts with its
use by the warning pass that runs afterwards).

Since this is the only place in our code where we hit this, work
around it by disabling the -Wstringop-overflow in the part of
the function that hits it. We do this only when using the
address sanitizer on GCC, so that we still get the benefit
of the warning in most compilation scenarios.

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/3006
Suggested-by: Daniel P. Berrangé <[email protected]>
Signed-off-by: Peter Maydell <[email protected]>
Tested-by: Alex Bennée <[email protected]>
Tested-by: Yodel Eldar <[email protected]>
Reviewed-by: Alex Bennée <[email protected]>
Reviewed-by: Thomas Huth <[email protected]>
Message-id: [email protected]
(cherry picked from commit b83a42dc77)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-18 08:04:48 +03:00
211 changed files with 3806 additions and 1070 deletions

No files matched your search

+1
View File
@@ -3939,6 +3939,7 @@ M: Alejandro Jimenez <[email protected]>
R: Sairaj Kodilkar <[email protected]>
S: Supported
F: hw/i386/amd_iommu*
F: tests/qtest/amd-iommu-test.c
OpenSBI Firmware
L: [email protected]
+1 -1
View File
@@ -1 +1 @@
10.2.2
10.2.4
+4 -4
View File
@@ -1544,18 +1544,18 @@ tb_page_addr_t get_page_addr_code_hostp(CPUArchState *env, vaddr addr,
(void)probe_access_internal(env_cpu(env), addr, 1, MMU_INST_FETCH,
cpu_mmu_index(env_cpu(env), true), false,
&p, &full, 0, false);
hostp, &full, 0, false);
p = *hostp;
if (p == NULL) {
return -1;
}
if (full->lg_page_size < TARGET_PAGE_BITS) {
*hostp = NULL;
return -1;
}
if (hostp) {
*hostp = p;
}
return qemu_ram_addr_from_host_nofail(p);
}
+3 -2
View File
@@ -82,7 +82,7 @@ void tb_check_watchpoint(CPUState *cpu, uintptr_t retaddr);
* See get_page_addr_code() (full-system version) for documentation on the
* return value.
*
* Sets *@hostp (when @hostp is non-NULL) as follows.
* Sets *@hostp as follows.
* If the return value is -1, sets *@hostp to NULL. Otherwise, sets *@hostp
* to the host address where @addr's content is kept.
*
@@ -105,7 +105,8 @@ tb_page_addr_t get_page_addr_code_hostp(CPUArchState *env, vaddr addr,
static inline tb_page_addr_t get_page_addr_code(CPUArchState *env,
vaddr addr)
{
return get_page_addr_code_hostp(env, addr, NULL);
void *discard;
return get_page_addr_code_hostp(env, addr, &discard);
}
/*
+13 -15
View File
@@ -647,7 +647,7 @@ void tb_lock_page0(tb_page_addr_t address)
if (prot & PAGE_WRITE) {
pageflags_set_clear(start, last, 0, PAGE_WRITE);
mprotect(g2h_untagged(start), last - start + 1,
mprotect(g2h_untagged_vaddr(start), last - start + 1,
prot & (PAGE_READ | PAGE_EXEC) ? PROT_READ : PROT_NONE);
}
}
@@ -734,7 +734,7 @@ int page_unprotect(CPUState *cpu, tb_page_addr_t address, uintptr_t pc)
if (prot & PAGE_EXEC) {
prot = (prot & ~PAGE_EXEC) | PAGE_READ;
}
mprotect((void *)g2h_untagged(start), len, prot & PAGE_RWX);
mprotect((void *)g2h_untagged_vaddr(start), len, prot & PAGE_RWX);
}
mmap_unlock();
@@ -763,7 +763,7 @@ static int probe_access_internal(CPUArchState *env, vaddr addr,
g_assert_not_reached();
}
if (guest_addr_valid_untagged(addr)) {
if (guest_addr_valid_untagged_vaddr(addr)) {
int page_flags = page_get_flags(addr);
if (page_flags & acc_flag) {
if (access_type != MMU_INST_FETCH
@@ -792,7 +792,7 @@ int probe_access_flags(CPUArchState *env, vaddr addr, int size,
g_assert(-(addr | TARGET_PAGE_MASK) >= size);
flags = probe_access_internal(env, addr, size, access_type, nonfault, ra);
*phost = (flags & TLB_INVALID_MASK) ? NULL : g2h(env_cpu(env), addr);
*phost = (flags & TLB_INVALID_MASK) ? NULL : g2h_vaddr(env_cpu(env), addr);
return flags;
}
@@ -805,13 +805,13 @@ void *probe_access(CPUArchState *env, vaddr addr, int size,
flags = probe_access_internal(env, addr, size, access_type, false, ra);
g_assert((flags & ~TLB_MMIO) == 0);
return size ? g2h(env_cpu(env), addr) : NULL;
return size ? g2h_vaddr(env_cpu(env), addr) : NULL;
}
void *tlb_vaddr_to_host(CPUArchState *env, vaddr addr,
MMUAccessType access_type, int mmu_idx)
{
return g2h(env_cpu(env), addr);
return g2h_vaddr(env_cpu(env), addr);
}
tb_page_addr_t get_page_addr_code_hostp(CPUArchState *env, vaddr addr,
@@ -822,9 +822,7 @@ tb_page_addr_t get_page_addr_code_hostp(CPUArchState *env, vaddr addr,
flags = probe_access_internal(env, addr, 1, MMU_INST_FETCH, false, 0);
g_assert(flags == 0);
if (hostp) {
*hostp = g2h_untagged(addr);
}
*hostp = g2h_untagged_vaddr(addr);
return addr;
}
@@ -940,7 +938,7 @@ static void *cpu_mmu_lookup(CPUState *cpu, vaddr addr,
cpu_loop_exit_sigbus(cpu, addr, type, ra);
}
ret = g2h(cpu, addr);
ret = g2h_vaddr(cpu, addr);
set_helper_retaddr(ra);
return ret;
}
@@ -970,7 +968,7 @@ int cpu_memory_rw_debug(CPUState *cpu, vaddr addr,
}
if (is_write) {
if (flags & PAGE_WRITE) {
memcpy(g2h(cpu, addr), buf, l);
memcpy(g2h_vaddr(cpu, addr), buf, l);
} else {
/* Bypass the host page protection using ptrace. */
if (fd == -1) {
@@ -989,13 +987,13 @@ int cpu_memory_rw_debug(CPUState *cpu, vaddr addr,
*/
tb_invalidate_phys_range(NULL, addr, addr + l - 1);
written = pwrite(fd, buf, l,
(off_t)(uintptr_t)g2h_untagged(addr));
(off_t)(uintptr_t)g2h_untagged_vaddr(addr));
if (written != l) {
goto out_close;
}
}
} else if (flags & PAGE_READ) {
memcpy(buf, g2h(cpu, addr), l);
memcpy(buf, g2h_vaddr(cpu, addr), l);
} else {
/* Bypass the host page protection using ptrace. */
if (fd == -1) {
@@ -1005,7 +1003,7 @@ int cpu_memory_rw_debug(CPUState *cpu, vaddr addr,
}
}
if (pread(fd, buf, l,
(off_t)(uintptr_t)g2h_untagged(addr)) != l) {
(off_t)(uintptr_t)g2h_untagged_vaddr(addr)) != l) {
goto out_close;
}
}
@@ -1233,7 +1231,7 @@ static void *atomic_mmu_lookup(CPUState *cpu, vaddr addr, MemOpIdx oi,
cpu_loop_exit_atomic(cpu, retaddr);
}
ret = g2h(cpu, addr);
ret = g2h_vaddr(cpu, addr);
set_helper_retaddr(retaddr);
return ret;
}
+14 -1
View File
@@ -95,6 +95,7 @@ typedef struct BlkdebugRule {
int immediately;
int once;
int64_t offset;
int64_t delay_ns;
} inject;
struct {
int new_state;
@@ -144,6 +145,10 @@ static QemuOptsList inject_error_opts = {
.name = "immediately",
.type = QEMU_OPT_BOOL,
},
{
.name = "delay-ns",
.type = QEMU_OPT_NUMBER,
},
{ /* end of list */ }
},
};
@@ -216,6 +221,8 @@ static int add_rule(void *opaque, QemuOpts *opts, Error **errp)
rule->options.inject.once = qemu_opt_get_bool(opts, "once", 0);
rule->options.inject.immediately =
qemu_opt_get_bool(opts, "immediately", 0);
rule->options.inject.delay_ns =
qemu_opt_get_number(opts, "delay-ns", 0);
sector = qemu_opt_get_number(opts, "sector", -1);
rule->options.inject.offset =
sector == -1 ? -1 : sector * BDRV_SECTOR_SIZE;
@@ -594,6 +601,7 @@ static int coroutine_fn rule_check(BlockDriverState *bs, uint64_t offset,
BlkdebugRule *rule = NULL;
int error;
bool immediately;
int64_t delay_ns;
qemu_mutex_lock(&s->lock);
QSIMPLEQ_FOREACH(rule, &s->active_rules, active_next) {
@@ -608,13 +616,14 @@ static int coroutine_fn rule_check(BlockDriverState *bs, uint64_t offset,
}
}
if (!rule || !rule->options.inject.error) {
if (!rule) {
qemu_mutex_unlock(&s->lock);
return 0;
}
immediately = rule->options.inject.immediately;
error = rule->options.inject.error;
delay_ns = rule->options.inject.delay_ns;
if (rule->options.inject.once) {
QSIMPLEQ_REMOVE(&s->active_rules, rule, BlkdebugRule, active_next);
@@ -622,6 +631,10 @@ static int coroutine_fn rule_check(BlockDriverState *bs, uint64_t offset,
}
qemu_mutex_unlock(&s->lock);
if (delay_ns) {
qemu_co_sleep_ns(QEMU_CLOCK_REALTIME, delay_ns);
}
if (!immediately) {
aio_co_schedule(qemu_get_current_aio_context(), qemu_coroutine_self());
qemu_coroutine_yield();
+34 -13
View File
@@ -82,6 +82,7 @@ struct BlockBackend {
QemuMutex queued_requests_lock; /* protects queued_requests */
CoQueue queued_requests;
bool disable_request_queuing; /* atomic */
int start_request_count; /* atomic */
VMChangeStateEntry *vmsh;
bool force_allow_inactivate;
@@ -1306,10 +1307,16 @@ bool blk_in_drain(BlockBackend *blk)
}
/* To be called between exactly one pair of blk_inc/dec_in_flight() */
static void coroutine_fn blk_wait_while_drained(BlockBackend *blk)
static void coroutine_fn blk_wait_while_drained(BlockBackend *blk,
BdrvRequestFlags flags)
{
assert(blk->in_flight > 0);
if (flags & BDRV_REQ_NO_QUEUE) {
assert(qatomic_read(&blk->start_request_count));
return;
}
if (qatomic_read(&blk->quiesce_counter) &&
!qatomic_read(&blk->disable_request_queuing)) {
/*
@@ -1335,7 +1342,7 @@ blk_co_do_preadv_part(BlockBackend *blk, int64_t offset, int64_t bytes,
BlockDriverState *bs;
IO_CODE();
blk_wait_while_drained(blk);
blk_wait_while_drained(blk, flags);
GRAPH_RDLOCK_GUARD();
/* Call blk_bs() only after waiting, the graph may have changed */
@@ -1410,7 +1417,7 @@ blk_co_do_pwritev_part(BlockBackend *blk, int64_t offset, int64_t bytes,
BlockDriverState *bs;
IO_CODE();
blk_wait_while_drained(blk);
blk_wait_while_drained(blk, flags);
GRAPH_RDLOCK_GUARD();
/* Call blk_bs() only after waiting, the graph may have changed */
@@ -1523,6 +1530,19 @@ void blk_dec_in_flight(BlockBackend *blk)
aio_wait_kick();
}
void coroutine_fn blk_co_start_request(BlockBackend *blk)
{
blk_inc_in_flight(blk);
blk_wait_while_drained(blk, 0);
qatomic_inc(&blk->start_request_count);
}
void blk_end_request(BlockBackend *blk)
{
qatomic_dec(&blk->start_request_count);
blk_dec_in_flight(blk);
}
static void error_callback_bh(void *opaque)
{
struct BlockBackendAIOCB *acb = opaque;
@@ -1741,7 +1761,7 @@ blk_co_do_ioctl(BlockBackend *blk, unsigned long int req, void *buf)
{
IO_CODE();
blk_wait_while_drained(blk);
blk_wait_while_drained(blk, 0);
GRAPH_RDLOCK_GUARD();
if (!blk_co_is_available(blk)) {
@@ -1783,12 +1803,13 @@ BlockAIOCB *blk_aio_ioctl(BlockBackend *blk, unsigned long int req, void *buf,
/* To be called between exactly one pair of blk_inc/dec_in_flight() */
static int coroutine_fn
blk_co_do_pdiscard(BlockBackend *blk, int64_t offset, int64_t bytes)
blk_co_do_pdiscard(BlockBackend *blk, int64_t offset, int64_t bytes,
BdrvRequestFlags flags)
{
int ret;
IO_CODE();
blk_wait_while_drained(blk);
blk_wait_while_drained(blk, flags);
GRAPH_RDLOCK_GUARD();
ret = blk_check_byte_request(blk, offset, bytes);
@@ -1804,7 +1825,7 @@ static void coroutine_fn blk_aio_pdiscard_entry(void *opaque)
BlkAioEmAIOCB *acb = opaque;
BlkRwCo *rwco = &acb->rwco;
rwco->ret = blk_co_do_pdiscard(rwco->blk, rwco->offset, acb->bytes);
rwco->ret = blk_co_do_pdiscard(rwco->blk, rwco->offset, acb->bytes, 0);
blk_aio_complete(acb);
}
@@ -1818,13 +1839,13 @@ BlockAIOCB *blk_aio_pdiscard(BlockBackend *blk,
}
int coroutine_fn blk_co_pdiscard(BlockBackend *blk, int64_t offset,
int64_t bytes)
int64_t bytes, BdrvRequestFlags flags)
{
int ret;
IO_OR_GS_CODE();
blk_inc_in_flight(blk);
ret = blk_co_do_pdiscard(blk, offset, bytes);
ret = blk_co_do_pdiscard(blk, offset, bytes, flags);
blk_dec_in_flight(blk);
return ret;
@@ -1834,7 +1855,7 @@ int coroutine_fn blk_co_pdiscard(BlockBackend *blk, int64_t offset,
static int coroutine_fn blk_co_do_flush(BlockBackend *blk)
{
IO_CODE();
blk_wait_while_drained(blk);
blk_wait_while_drained(blk, 0);
GRAPH_RDLOCK_GUARD();
if (!blk_co_is_available(blk)) {
@@ -2009,7 +2030,7 @@ int coroutine_fn blk_co_zone_report(BlockBackend *blk, int64_t offset,
IO_CODE();
blk_inc_in_flight(blk); /* increase before waiting */
blk_wait_while_drained(blk);
blk_wait_while_drained(blk, 0);
GRAPH_RDLOCK_GUARD();
if (!blk_is_available(blk)) {
blk_dec_in_flight(blk);
@@ -2034,7 +2055,7 @@ int coroutine_fn blk_co_zone_mgmt(BlockBackend *blk, BlockZoneOp op,
IO_CODE();
blk_inc_in_flight(blk);
blk_wait_while_drained(blk);
blk_wait_while_drained(blk, 0);
GRAPH_RDLOCK_GUARD();
ret = blk_check_byte_request(blk, offset, len);
@@ -2058,7 +2079,7 @@ int coroutine_fn blk_co_zone_append(BlockBackend *blk, int64_t *offset,
IO_CODE();
blk_inc_in_flight(blk);
blk_wait_while_drained(blk);
blk_wait_while_drained(blk, flags);
GRAPH_RDLOCK_GUARD();
if (!blk_is_available(blk)) {
blk_dec_in_flight(blk);
+8 -2
View File
@@ -518,6 +518,7 @@ int bdrv_commit(BlockDriverState *bs)
if (!drv)
return -ENOMEDIUM;
bdrv_drain_all_begin();
bdrv_graph_rdlock_main_loop();
backing_file_bs = bdrv_cow_bs(bs);
@@ -549,6 +550,10 @@ int bdrv_commit(BlockDriverState *bs)
BLK_PERM_ALL);
backing = blk_new(ctx, BLK_PERM_WRITE | BLK_PERM_RESIZE, BLK_PERM_ALL);
/* We drained all nodes, but still make requests through BlockBackends */
blk_set_disable_request_queuing(src, true);
blk_set_disable_request_queuing(backing, true);
ret = blk_insert_bs(src, bs, &local_err);
if (ret < 0) {
error_report_err(local_err);
@@ -565,7 +570,7 @@ int bdrv_commit(BlockDriverState *bs)
bdrv_graph_rdunlock_main_loop();
bdrv_graph_wrlock_drained();
bdrv_graph_wrlock();
bdrv_set_backing_hd(commit_top_bs, backing_file_bs, &error_abort);
bdrv_set_backing_hd(bs, commit_top_bs, &error_abort);
bdrv_graph_wrunlock();
@@ -647,7 +652,7 @@ ro_cleanup:
blk_unref(backing);
bdrv_graph_rdunlock_main_loop();
bdrv_graph_wrlock_drained();
bdrv_graph_wrlock();
if (bdrv_cow_bs(bs) != backing_file_bs) {
bdrv_set_backing_hd(bs, backing_file_bs, &error_abort);
}
@@ -663,6 +668,7 @@ ro_cleanup:
out:
bdrv_graph_rdunlock_main_loop();
bdrv_drain_all_end();
return ret;
}
+2
View File
@@ -865,6 +865,7 @@ out_noclean:
g_free(s->cookie);
g_free(s->url);
g_free(s->username);
g_free(s->password);
g_free(s->proxyusername);
g_free(s->proxypassword);
if (s->sockets) {
@@ -976,6 +977,7 @@ static void curl_close(BlockDriverState *bs)
g_free(s->cookie);
g_free(s->url);
g_free(s->username);
g_free(s->password);
g_free(s->proxyusername);
g_free(s->proxypassword);
}
+1 -1
View File
@@ -121,7 +121,7 @@ virtio_blk_discard_write_zeroes(VirtioBlkHandler *handler, struct iovec *iov,
}
if (blk_co_pdiscard(blk, sector << VIRTIO_BLK_SECTOR_BITS,
bytes) == 0) {
bytes, 0) == 0) {
return VIRTIO_BLK_S_OK;
}
}
+5 -7
View File
@@ -278,14 +278,12 @@ void coroutine_fn bdrv_graph_co_rdunlock(void)
smp_mb();
/*
* has_writer == 0: this means reader will read reader_count decreased
* has_writer == 1: we don't know if writer read reader_count old or
* new. Therefore, kick again so on next iteration
* writer will for sure read the updated value.
* Always kick: bdrv_graph_wrlock() zeroes has_writer while polling (to
* let callbacks take the reader lock via the fast path), so we cannot
* rely on has_writer to detect a waiting writer. aio_wait_kick() is a
* no-op when no one is waiting, so it is cheap in the common case.
*/
if (qatomic_read(&has_writer)) {
aio_wait_kick();
}
aio_wait_kick();
}
void bdrv_graph_rdlock_main_loop(void)
+12 -1
View File
@@ -1917,7 +1917,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;
+93 -17
View File
@@ -36,14 +36,37 @@
/* 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;
struct iocb iocb;
ssize_t ret;
off_t offset;
size_t nbytes;
QEMUIOVector *qiov;
bool is_read;
/* For handling short reads/writes */
size_t total_done;
QEMUIOVector resubmit_qiov;
int fd;
int type;
BdrvRequestFlags flags;
uint64_t dev_max_batch;
QSIMPLEQ_ENTRY(qemu_laiocb) next;
};
@@ -51,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;
@@ -68,28 +92,61 @@ struct LinuxAioState {
};
static void ioq_submit(LinuxAioState *s);
static int laio_do_submit(struct qemu_laiocb *laiocb);
static inline ssize_t io_event_ret(struct io_event *ev)
{
return (ssize_t)(((uint64_t)ev->res2 << 32) | ev->res);
}
/**
* Retry tail of short requests.
*/
static int laio_resubmit_short_io(struct qemu_laiocb *laiocb, size_t done)
{
QEMUIOVector *resubmit_qiov = &laiocb->resubmit_qiov;
laiocb->total_done += done;
if (!resubmit_qiov->iov) {
qemu_iovec_init(resubmit_qiov, laiocb->qiov->niov);
} else {
qemu_iovec_reset(resubmit_qiov);
}
qemu_iovec_concat(resubmit_qiov, laiocb->qiov,
laiocb->total_done, laiocb->nbytes - laiocb->total_done);
return laio_do_submit(laiocb);
}
/*
* Completes an AIO request.
*/
static void qemu_laio_process_completion(struct qemu_laiocb *laiocb)
{
int ret;
ssize_t ret;
ret = laiocb->ret;
if (ret != -ECANCELED) {
if (ret == laiocb->nbytes) {
if (ret == laiocb->nbytes - laiocb->total_done) {
ret = 0;
} else if (ret > 0 && (laiocb->type == QEMU_AIO_READ ||
laiocb->type == QEMU_AIO_WRITE)) {
ret = laio_resubmit_short_io(laiocb, ret);
if (!ret) {
return;
}
} else if (ret >= 0) {
/* Short reads mean EOF, pad with zeros. */
if (laiocb->is_read) {
qemu_iovec_memset(laiocb->qiov, ret, 0,
laiocb->qiov->size - ret);
/*
* For normal reads and writes, we only get here if ret == 0, which
* means EOF for reads and ENOSPC for writes.
* For zone-append, we get here with any ret >= 0, which we just
* treat as ENOSPC, too (safer than resubmitting, probably, but not
* 100 % clear).
*/
if (laiocb->type == QEMU_AIO_READ) {
qemu_iovec_memset(laiocb->qiov, laiocb->total_done, 0,
laiocb->qiov->size - laiocb->total_done);
} else {
ret = -ENOSPC;
}
@@ -97,6 +154,9 @@ static void qemu_laio_process_completion(struct qemu_laiocb *laiocb)
}
laiocb->ret = ret;
if (laiocb->resubmit_qiov.iov) {
qemu_iovec_destroy(&laiocb->resubmit_qiov);
}
/*
* If the coroutine is already entered it must be in ioq_submit() and
@@ -285,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)
@@ -294,6 +355,11 @@ static void ioq_submit(LinuxAioState *s)
QEMU_UNINITIALIZED 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;
@@ -339,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)
@@ -367,23 +435,27 @@ static void laio_deferred_fn(void *opaque)
}
}
static int laio_do_submit(int fd, struct qemu_laiocb *laiocb, off_t offset,
int type, BdrvRequestFlags flags,
uint64_t dev_max_batch)
static int laio_do_submit(struct qemu_laiocb *laiocb)
{
LinuxAioState *s = laiocb->ctx;
struct iocb *iocbs = &laiocb->iocb;
QEMUIOVector *qiov = laiocb->qiov;
int fd = laiocb->fd;
off_t offset = laiocb->offset + laiocb->total_done;
switch (type) {
if (laiocb->resubmit_qiov.iov) {
qiov = &laiocb->resubmit_qiov;
}
switch (laiocb->type) {
case QEMU_AIO_WRITE:
#ifdef HAVE_IO_PREP_PWRITEV2
{
int laio_flags = (flags & BDRV_REQ_FUA) ? RWF_DSYNC : 0;
int laio_flags = (laiocb->flags & BDRV_REQ_FUA) ? RWF_DSYNC : 0;
io_prep_pwritev2(iocbs, fd, qiov->iov, qiov->niov, offset, laio_flags);
}
#else
assert(flags == 0);
assert(laiocb->flags == 0);
io_prep_pwritev(iocbs, fd, qiov->iov, qiov->niov, offset);
#endif
break;
@@ -399,7 +471,7 @@ static int laio_do_submit(int fd, struct qemu_laiocb *laiocb, off_t offset,
/* Currently Linux kernel does not support other operations */
default:
fprintf(stderr, "%s: invalid AIO request type 0x%x.\n",
__func__, type);
__func__, laiocb->type);
return -EIO;
}
io_set_eventfd(&laiocb->iocb, event_notifier_get_fd(&s->e));
@@ -407,7 +479,7 @@ static int laio_do_submit(int fd, struct qemu_laiocb *laiocb, off_t offset,
QSIMPLEQ_INSERT_TAIL(&s->io_q.pending, laiocb, next);
s->io_q.in_queue++;
if (!s->io_q.blocked) {
if (s->io_q.in_queue >= laio_max_batch(s, dev_max_batch)) {
if (s->io_q.in_queue >= laio_max_batch(s, laiocb->dev_max_batch)) {
ioq_submit(s);
} else {
defer_call(laio_deferred_fn, s);
@@ -425,14 +497,18 @@ int coroutine_fn laio_co_submit(int fd, uint64_t offset, QEMUIOVector *qiov,
AioContext *ctx = qemu_get_current_aio_context();
struct qemu_laiocb laiocb = {
.co = qemu_coroutine_self(),
.offset = offset,
.nbytes = qiov ? qiov->size : 0,
.ctx = aio_get_linux_aio(ctx),
.ret = -EINPROGRESS,
.is_read = (type == QEMU_AIO_READ),
.qiov = qiov,
.fd = fd,
.type = type,
.flags = flags,
.dev_max_batch = dev_max_batch,
};
ret = laio_do_submit(fd, &laiocb, offset, type, flags, dev_max_batch);
ret = laio_do_submit(&laiocb);
if (ret < 0) {
return ret;
}
+17 -15
View File
@@ -454,7 +454,7 @@ static void coroutine_fn mirror_co_discard(void *opaque)
*op->bytes_handled = op->bytes;
op->is_in_flight = true;
ret = blk_co_pdiscard(op->s->target, op->offset, op->bytes);
ret = blk_co_pdiscard(op->s->target, op->offset, op->bytes, 0);
mirror_write_complete(op, ret);
}
@@ -1276,23 +1276,25 @@ static void mirror_complete(Job *job, Error **errp)
return;
}
/* block all operations on to_replace bs */
if (s->replaces) {
s->to_replace = bdrv_find_node(s->replaces);
if (!s->to_replace) {
error_setg(errp, "Node name '%s' not found", s->replaces);
return;
if (!s->should_complete) {
/* block all operations on to_replace bs */
if (s->replaces) {
s->to_replace = bdrv_find_node(s->replaces);
if (!s->to_replace) {
error_setg(errp, "Node name '%s' not found", s->replaces);
return;
}
/* TODO Translate this into child freeze system. */
error_setg(&s->replace_blocker,
"block device is in use by block-job-complete");
bdrv_op_block_all(s->to_replace, s->replace_blocker);
bdrv_ref(s->to_replace);
}
/* TODO Translate this into child freeze system. */
error_setg(&s->replace_blocker,
"block device is in use by block-job-complete");
bdrv_op_block_all(s->to_replace, s->replace_blocker);
bdrv_ref(s->to_replace);
s->should_complete = true;
}
s->should_complete = true;
/* If the job is paused, it will be re-entered when it is resumed */
WITH_JOB_LOCK_GUARD() {
if (!job->paused) {
@@ -1530,7 +1532,7 @@ do_sync_target_write(MirrorBlockJob *job, MirrorMethod method,
zero_bitmap_end - zero_bitmap_offset);
}
assert(!qiov);
ret = blk_co_pdiscard(job->target, offset, bytes);
ret = blk_co_pdiscard(job->target, offset, bytes, 0);
break;
default:
+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
@@ -2000,6 +2028,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) ||
@@ -2160,6 +2197,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
@@ -4177,10 +4177,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
@@ -965,6 +965,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);
+60 -19
View File
@@ -391,6 +391,7 @@ void coroutine_fn throttle_group_co_io_limits_intercept(ThrottleGroupMember *tgm
typedef struct {
ThrottleGroupMember *tgm;
ThrottleDirection direction;
bool reset_timer_armed;
} RestartData;
static void coroutine_fn throttle_group_restart_queue_entry(void *opaque)
@@ -403,6 +404,9 @@ static void coroutine_fn throttle_group_restart_queue_entry(void *opaque)
bool empty_queue;
qemu_mutex_lock(&tg->lock);
if (data->reset_timer_armed) {
tg->any_timer_armed[direction] = false;
}
empty_queue = !throttle_group_co_restart_queue(tgm, direction);
/* If the request queue was empty then we have to take care of
@@ -419,18 +423,23 @@ static void coroutine_fn throttle_group_restart_queue_entry(void *opaque)
}
static void throttle_group_restart_queue(ThrottleGroupMember *tgm,
ThrottleDirection direction)
ThrottleDirection direction,
bool reset_timer_armed)
{
Coroutine *co;
RestartData *rd = g_new0(RestartData, 1);
rd->tgm = tgm;
rd->direction = direction;
rd->reset_timer_armed = reset_timer_armed;
/* This function is called when a timer is fired or when
* throttle_group_restart_tgm() is called. Either way, there can
/* If reset_timer_armed is set then this means that this function
* was called when a timer was fired (either from timer_cb() or
* from throttle_group_restart_tgm()). In this case there can
* be no timer pending on this tgm at this point */
assert(!timer_pending(tgm->throttle_timers.timers[direction]));
if (reset_timer_armed) {
assert(!timer_pending(tgm->throttle_timers.timers[direction]));
}
qatomic_inc(&tgm->restart_pending);
@@ -444,15 +453,50 @@ void throttle_group_restart_tgm(ThrottleGroupMember *tgm)
if (tgm->throttle_state) {
for (dir = THROTTLE_READ; dir < THROTTLE_MAX; dir++) {
QEMUTimer *t = tgm->throttle_timers.timers[dir];
QEMUTimer *t;
ThrottleState *ts = tgm->throttle_state;
ThrottleGroup *tg = container_of(ts, ThrottleGroup, ts);
bool reset_timer_armed;
/*
* This function restarts the tgm's queue immediately.
* This is used for example for callers to drain all requests.
* There are three different scenarios depending on whether
* a timer is armed for this tg and which tgm owns the timer.
*/
qemu_mutex_lock(&tg->lock);
t = tgm->throttle_timers.timers[dir];
if (timer_pending(t)) {
/* If there's a pending timer on this tgm, fire it now */
/*
* Case 1: this tgm has a pending timer.
* We can fire the timer immediately.
*/
timer_del(t);
timer_cb(tgm, dir);
reset_timer_armed = true;
} else if (tg->any_timer_armed[dir]) {
/*
* Case 2: another tgm has a pending timer.
* In this case we can still restart the queue but we
* have to leave any_timer_armed untouched so the
* other tgm's timer is not disrupted.
*/
reset_timer_armed = false;
} else {
/* Else run the next request from the queue manually */
throttle_group_restart_queue(tgm, dir);
/*
* Case 3: there is no timer set for this group.
* Here we can simulate a timer that fires immediately,
* so the queue is restarted but no other thread
* can arm a timer in the meantime.
*/
tg->any_timer_armed[dir] = true;
reset_timer_armed = true;
}
qemu_mutex_unlock(&tg->lock);
throttle_group_restart_queue(tgm, dir, reset_timer_armed);
}
}
}
@@ -499,16 +543,13 @@ void throttle_group_get_config(ThrottleGroupMember *tgm, ThrottleConfig *cfg)
*/
static void timer_cb(ThrottleGroupMember *tgm, ThrottleDirection direction)
{
ThrottleState *ts = tgm->throttle_state;
ThrottleGroup *tg = container_of(ts, ThrottleGroup, ts);
/* The timer has just been fired, so we can update the flag */
qemu_mutex_lock(&tg->lock);
tg->any_timer_armed[direction] = false;
qemu_mutex_unlock(&tg->lock);
/* Run the request that was waiting for this timer */
throttle_group_restart_queue(tgm, direction);
/*
* Run the request that was waiting for this timer.
* tg->any_timer_armed needs to be cleared, but we'll do it later
* when the queue is restarted in order to prevent another thread
* from arming the timer before that.
*/
throttle_group_restart_queue(tgm, direction, true);
}
static void read_timer_cb(void *opaque)
+1
View File
@@ -27,6 +27,7 @@
#include "user/abitypes.h"
#include "user/cpu_loop.h"
#include "user/page-protection.h"
#include "user/guest-host.h"
extern char **environ;
+6 -4
View File
@@ -998,7 +998,12 @@ void process_pending_signals(CPUArchState *env)
sigdelset(&ts->signal_mask, target_to_host_signal(sig));
sigact_table[sig - 1]._sa_handler = TARGET_SIG_DFL;
}
/*
* Restart scan from the beginning, as handle_pending_signal
* might have resulted in a new synchronous signal (eg SIGSEGV).
*/
handle_pending_signal(env, sig, &ts->sync_signal);
goto restart_scan;
}
k = ts->sigtab;
@@ -1008,10 +1013,7 @@ void process_pending_signals(CPUArchState *env)
if (k->pending &&
!sigismember(blocked_set, target_to_host_signal(sig))) {
handle_pending_signal(env, sig, k);
/*
* Restart scan from the beginning, as handle_pending_signal
* might have resulted in a new synchronous signal (eg SIGSEGV).
*/
/* Restart scan, explained above. */
goto restart_scan;
}
}
+10 -6
View File
@@ -28,7 +28,7 @@
#include "qapi/error.h"
#include "chardev/char-win.h"
static void win_chr_read(Chardev *chr, DWORD len)
static int win_chr_read(Chardev *chr, DWORD len)
{
WinChardev *s = WIN_CHARDEV(chr);
int max_size = qemu_chr_be_can_write(chr);
@@ -40,7 +40,7 @@ static void win_chr_read(Chardev *chr, DWORD len)
len = max_size;
}
if (len == 0) {
return;
return 0;
}
ZeroMemory(&s->orecv, sizeof(s->orecv));
@@ -56,6 +56,8 @@ static void win_chr_read(Chardev *chr, DWORD len)
if (size > 0) {
qemu_chr_be_write(chr, buf, size);
}
return size > 0 ? 1 : 0;
}
static int win_chr_serial_poll(void *opaque)
@@ -67,8 +69,9 @@ static int win_chr_serial_poll(void *opaque)
ClearCommError(s->file, &comerr, &status);
if (status.cbInQue > 0) {
win_chr_read(chr, status.cbInQue);
return 1;
if (win_chr_read(chr, status.cbInQue)) {
return 1;
}
}
return 0;
}
@@ -147,8 +150,9 @@ int win_chr_pipe_poll(void *opaque)
PeekNamedPipe(s->file, NULL, 0, NULL, &size, NULL);
if (size > 0) {
win_chr_read(chr, size);
return 1;
if (win_chr_read(chr, size)) {
return 1;
}
}
return 0;
}
+2 -1
View File
@@ -705,7 +705,8 @@ static void track_callstack(unsigned int cpu_index, void *udata)
if (fp == caller.frame_pointer) {
/* return */
CallstackEntry e = callstack_pop(cs);
trace_exit_function(t, timestamp, e.pc, callstack_depth(cs));
/* uftrace convention is to use same depth as entry */
trace_exit_function(t, timestamp, e.pc, callstack_depth(cs) + 1);
return;
}
+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 */
+1 -1
View File
@@ -114,7 +114,7 @@ Rust build dependencies
bindgen tool, which is too big to package and distribute. The minimum
supported version of bindgen is 0.60.x. For distributions that do not
include bindgen or have an older version, it is recommended to install
a newer version using ``cargo install bindgen-cli``.
a newer version using ``cargo install --locked bindgen-cli``.
QEMU requires Rust 1.83.0. This is available on all supported platforms
except for the ``mips64el`` architecture on Debian bookworm. For all other
+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
+1 -1
View File
@@ -112,7 +112,7 @@ struct FsContext {
};
struct V9fsPath {
uint16_t size;
size_t size;
char *data;
};
P9ARRAY_DECLARE_TYPE(V9fsPath);
+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"/>
+16 -7
View File
@@ -1256,26 +1256,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;
}
+40 -10
View File
@@ -203,16 +203,24 @@ void v9fs_path_free(V9fsPath *path)
}
void 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)
@@ -241,6 +249,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;
@@ -1406,13 +1417,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)
@@ -3312,12 +3325,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);
@@ -3338,7 +3353,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:
@@ -3435,7 +3453,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:
@@ -3617,6 +3638,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);
+2 -2
View File
@@ -456,8 +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 G_GNUC_PRINTF(2, 3) 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,
+3
View File
@@ -220,13 +220,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;
}
+7
View File
@@ -1286,6 +1286,13 @@ static int sb16_post_load (void *opaque, int version_id)
{
SB16State *s = opaque;
if (s->in_index < 0 || s->in_index > (int)sizeof(s->in2_data)) {
return -1;
}
if (s->out_data_len < 0 || s->out_data_len > (int)sizeof(s->out_data)) {
return -1;
}
if (s->voice) {
AUD_close_out(s->audio_be, s->voice);
s->voice = NULL;
+74 -34
View File
@@ -38,6 +38,9 @@
#include "hw/virtio/virtio-blk-common.h"
#include "qemu/coroutine.h"
/* Internal buffer size limit for zone report */
#define VIRTIO_BLK_MAX_ZONES_PER_BATCH 4096
static void virtio_blk_ioeventfd_attach(VirtIOBlock *s);
static void virtio_blk_init_request(VirtIOBlock *s, VirtQueue *vq,
@@ -196,10 +199,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;
@@ -447,15 +456,22 @@ err:
return err_status;
}
typedef struct {
unsigned int total_nr_zones; /* max zones to fill in this request */
unsigned int nr_zones_done; /* how many zones have been filled in */
int64_t iov_offset; /* current byte position in in_iov[] */
int64_t offset; /* current zone report disk offset */
unsigned int nr_zones; /* for zone report calls */
unsigned int zones_per_batch; /* size of zone report buffer */
BlockZoneDescriptor *zones; /* zone report buffer */
} ZoneReportData;
typedef struct ZoneCmdData {
VirtIOBlockReq *req;
struct iovec *in_iov;
unsigned in_num;
union {
struct {
unsigned int nr_zones;
BlockZoneDescriptor *zones;
} zone_report_data;
ZoneReportData zone_report_data;
struct {
int64_t offset;
} zone_append_data;
@@ -512,16 +528,15 @@ static bool check_zoned_request(VirtIOBlock *s, int64_t offset, int64_t len,
static void virtio_blk_zone_report_complete(void *opaque, int ret)
{
ZoneCmdData *data = opaque;
ZoneReportData *zrd = &data->zone_report_data;
VirtIOBlockReq *req = data->req;
VirtIODevice *vdev = VIRTIO_DEVICE(req->dev);
struct iovec *in_iov = data->in_iov;
unsigned in_num = data->in_num;
int64_t zrp_size, n, j = 0;
int64_t nz = data->zone_report_data.nr_zones;
int64_t n;
unsigned nz = zrd->nr_zones;
int8_t err_status = VIRTIO_BLK_S_OK;
struct virtio_blk_zone_report zrp_hdr = (struct virtio_blk_zone_report) {
.nr_zones = cpu_to_le64(nz),
};
struct virtio_blk_zone_report zrp_hdr = {};
trace_virtio_blk_zone_report_complete(vdev, req, nz, ret);
if (ret) {
@@ -529,28 +544,18 @@ static void virtio_blk_zone_report_complete(void *opaque, int ret)
goto out;
}
zrp_size = sizeof(struct virtio_blk_zone_report)
+ sizeof(struct virtio_blk_zone_descriptor) * nz;
n = iov_from_buf(in_iov, in_num, 0, &zrp_hdr, sizeof(zrp_hdr));
if (n != sizeof(zrp_hdr)) {
virtio_error(vdev, "Driver provided input buffer that is too small!");
err_status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
goto out;
}
for (size_t i = sizeof(zrp_hdr); i < zrp_size;
i += sizeof(struct virtio_blk_zone_descriptor), ++j) {
for (unsigned j = 0; j < nz; j++) {
struct virtio_blk_zone_descriptor desc =
(struct virtio_blk_zone_descriptor) {
.z_start = cpu_to_le64(data->zone_report_data.zones[j].start
.z_start = cpu_to_le64(zrd->zones[j].start
>> BDRV_SECTOR_BITS),
.z_cap = cpu_to_le64(data->zone_report_data.zones[j].cap
.z_cap = cpu_to_le64(zrd->zones[j].cap
>> BDRV_SECTOR_BITS),
.z_wp = cpu_to_le64(data->zone_report_data.zones[j].wp
.z_wp = cpu_to_le64(zrd->zones[j].wp
>> BDRV_SECTOR_BITS),
};
switch (data->zone_report_data.zones[j].type) {
switch (zrd->zones[j].type) {
case BLK_ZT_CONV:
desc.z_type = VIRTIO_BLK_ZT_CONV;
break;
@@ -564,7 +569,7 @@ static void virtio_blk_zone_report_complete(void *opaque, int ret)
g_assert_not_reached();
}
switch (data->zone_report_data.zones[j].state) {
switch (zrd->zones[j].state) {
case BLK_ZS_RDONLY:
desc.z_state = VIRTIO_BLK_ZS_RDONLY;
break;
@@ -594,18 +599,47 @@ static void virtio_blk_zone_report_complete(void *opaque, int ret)
}
/* TODO: it takes O(n^2) time complexity. Optimizations required. */
n = iov_from_buf(in_iov, in_num, i, &desc, sizeof(desc));
n = iov_from_buf(in_iov, in_num, zrd->iov_offset, &desc, sizeof(desc));
if (n != sizeof(desc)) {
virtio_error(vdev, "Driver provided input buffer "
"for descriptors that is too small!");
err_status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
goto out;
}
zrd->iov_offset += sizeof(desc);
}
if (nz > 0) {
BlockZoneDescriptor *zone = &zrd->zones[nz - 1];
zrd->offset = zone->start + zone->length;
}
zrd->nr_zones_done += nz;
/* Call zone report again if the end hasn't been reached yet */
if (nz == zrd->zones_per_batch &&
zrd->nr_zones_done < zrd->total_nr_zones) {
zrd->nr_zones = MIN(zrd->zones_per_batch,
zrd->total_nr_zones - zrd->nr_zones_done);
blk_aio_zone_report(req->dev->blk, zrd->offset, &zrd->nr_zones,
zrd->zones, virtio_blk_zone_report_complete, data);
return;
}
/* Fill in header now that all zones have been reported */
zrp_hdr.nr_zones = cpu_to_le64(zrd->nr_zones_done);
n = iov_from_buf(in_iov, in_num, 0, &zrp_hdr, sizeof(zrp_hdr));
if (n != sizeof(zrp_hdr)) {
virtio_error(vdev, "Driver provided input buffer that is too small!");
err_status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
goto out;
}
out:
virtio_blk_req_complete(req, err_status);
g_free(req);
g_free(data->zone_report_data.zones);
g_free(zrd->zones);
g_free(data);
}
@@ -617,7 +651,8 @@ static void virtio_blk_handle_zone_report(VirtIOBlockReq *req,
VirtIODevice *vdev = VIRTIO_DEVICE(s);
unsigned int nr_zones;
ZoneCmdData *data;
int64_t zone_size, offset;
ZoneReportData *zrd;
int64_t offset;
uint8_t err_status;
if (req->in_len < sizeof(struct virtio_blk_inhdr) +
@@ -639,16 +674,21 @@ static void virtio_blk_handle_zone_report(VirtIOBlockReq *req,
trace_virtio_blk_handle_zone_report(vdev, req,
offset >> BDRV_SECTOR_BITS, nr_zones);
zone_size = sizeof(BlockZoneDescriptor) * nr_zones;
data = g_malloc(sizeof(ZoneCmdData));
data->req = req;
data->in_iov = in_iov;
data->in_num = in_num;
data->zone_report_data.nr_zones = nr_zones;
data->zone_report_data.zones = g_malloc(zone_size),
blk_aio_zone_report(s->blk, offset, &data->zone_report_data.nr_zones,
data->zone_report_data.zones,
zrd = &data->zone_report_data;
zrd->total_nr_zones = nr_zones;
zrd->nr_zones_done = 0;
zrd->iov_offset = sizeof(struct virtio_blk_zone_report);
zrd->offset = offset;
zrd->zones_per_batch = MIN(nr_zones, VIRTIO_BLK_MAX_ZONES_PER_BATCH);
zrd->zones = g_malloc(zrd->zones_per_batch * sizeof(BlockZoneDescriptor));
zrd->nr_zones = zrd->zones_per_batch;
blk_aio_zone_report(s->blk, offset, &zrd->nr_zones, zrd->zones,
virtio_blk_zone_report_complete, data);
return;
out:
+6
View File
@@ -170,6 +170,12 @@ static void htif_handle_tohost_write(HTIFState *s, uint64_t val_written)
* begin/end_signature symbols exist.
*/
if (sig_file && begin_sig_addr && end_sig_addr) {
if (end_sig_addr <= begin_sig_addr) {
error_report("Invalid HTIF signature range:"
" begin=0x%" PRIx64 " end=0x%" PRIx64,
begin_sig_addr, end_sig_addr);
return;
}
uint64_t sig_len = end_sig_addr - begin_sig_addr;
char *sig_data = g_malloc(sig_len);
dma_memory_read(&address_space_memory, begin_sig_addr,
+21 -7
View File
@@ -78,6 +78,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);
@@ -106,11 +111,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.\n");
@@ -124,10 +137,7 @@ static void sifive_uart_write_tx_fifo(SiFiveUARTState *s, const uint8_t *buf,
s->txfifo |= SIFIVE_UART_TXFIFO_FULL;
}
if (!timer_pending(s->fifo_trigger_handle)) {
timer_mod(s->fifo_trigger_handle, current_time +
TX_INTERRUPT_TRIGGER_DELAY_NS);
}
sifive_uart_trigger_tx_fifo(s);
}
static uint64_t
@@ -184,6 +194,10 @@ 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);
}
sifive_uart_update_irq(s);
return;
case SIFIVE_UART_RXCTRL:
s->rxctrl = val64;
@@ -231,7 +245,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)
+1
View File
@@ -52,6 +52,7 @@ GlobalProperty hw_compat_10_0[] = {
{ "vfio-pci", "x-migration-load-config-after-iter", "off" },
{ "ramfb", "use-legacy-x86-rom", "true"},
{ "vfio-pci-nohotplug", "use-legacy-x86-rom", "true" },
{ "chardev-qemu-vdagent", "x-migration-blocked", "true" },
};
const size_t hw_compat_10_0_len = G_N_ELEMENTS(hw_compat_10_0);
+13 -14
View File
@@ -1995,6 +1995,7 @@ static CXLRetCode media_operations_discovery(uint8_t *payload_in,
} QEMU_PACKED *media_op_in_disc_pl = (void *)payload_in;
struct media_op_discovery_out_pl *media_out_pl =
(struct media_op_discovery_out_pl *)payload_out;
int total = ARRAY_SIZE(media_op_matrix) - 1; /* exclude Discovery */
int num_ops, start_index, i;
int count = 0;
@@ -2011,24 +2012,22 @@ static CXLRetCode media_operations_discovery(uint8_t *payload_in,
* sub class command.
*/
if (media_op_in_disc_pl->dpa_range_count ||
start_index + num_ops > ARRAY_SIZE(media_op_matrix)) {
start_index >= total) {
return CXL_MBOX_INVALID_INPUT;
}
media_out_pl->dpa_range_granularity = CXL_CACHE_LINE_SIZE;
media_out_pl->total_supported_operations =
ARRAY_SIZE(media_op_matrix);
if (num_ops > 0) {
for (i = start_index; i < start_index + num_ops; i++) {
media_out_pl->entry[count].media_op_class =
media_op_matrix[i].media_op_class;
media_out_pl->entry[count].media_op_subclass =
media_op_matrix[i].media_op_subclass;
count++;
if (count == num_ops) {
break;
}
}
media_out_pl->total_supported_operations = total;
num_ops = MIN(num_ops, total - start_index);
for (i = 0; i < num_ops; i++) {
int idx = start_index + i + 1; /* skip Discovery (first entry) */
media_out_pl->entry[count].media_op_class =
media_op_matrix[idx].media_op_class;
media_out_pl->entry[count].media_op_subclass =
media_op_matrix[idx].media_op_subclass;
count++;
}
media_out_pl->num_of_supported_operations = count;
+47 -5
View File
@@ -108,12 +108,34 @@ glue(glue(glue(cirrus_colorexpand_transp_, ROP_NAME), _),DEPTH)
unsigned int col;
unsigned bitmask;
unsigned index;
/*
* Raster ops where the source is a monochrome bitmap with
* color expansion to 8/16/24/32bpp destination.
*/
#if DEPTH == 24
/*
* For packed-24 modes, GR2F bits [4:0] are a count of destination
* bytes to be suppressed for each scanline, which we keep in
* dstskipleft. We want to track the number of whole bytes
* to skip in the source (always either 0 or 1) and the number
* of bits within the byte to skip.
*/
int dstskipleft = s->vga.gr[0x2f] & 0x1f;
int srcskipleft = dstskipleft / 3;
int srcskipleftbits = (dstskipleft / 3) & 0x7;
int srcskipleftbytes = (dstskipleft / 3) >> 3;
#else
int srcskipleft = s->vga.gr[0x2f] & 0x07;
int dstskipleft = srcskipleft * (DEPTH / 8);
/*
* In all other modes, GR2F bits [2:0] are a count of how many
* destination pixels to suppress for each scanline, which is our
* srcskipleftbits. We get dstskipleft, the number of bytes to
* skip, by multiplying this by the bytes-per-pixel. In these
* modes we never need to skip an entire source byte.
*/
int srcskipleftbits = s->vga.gr[0x2f] & 0x07;
int srcskipleftbytes = 0;
int dstskipleft = srcskipleftbits * (DEPTH / 8);
#endif
if (s->cirrus_blt_modeext & CIRRUS_BLTMODEEXT_COLOREXPINV) {
@@ -125,7 +147,8 @@ glue(glue(glue(cirrus_colorexpand_transp_, ROP_NAME), _),DEPTH)
}
for(y = 0; y < bltheight; y++) {
bitmask = 0x80 >> srcskipleft;
bitmask = 0x80 >> srcskipleftbits;
srcaddr += srcskipleftbytes;
bits = cirrus_src(s, srcaddr++) ^ bits_xor;
addr = dstaddr + dstskipleft;
for (x = dstskipleft; x < bltwidth; x += (DEPTH / 8)) {
@@ -191,10 +214,29 @@ glue(glue(glue(cirrus_colorexpand_pattern_transp_, ROP_NAME), _),DEPTH)
int x, y, bitpos, pattern_y;
unsigned int bits, bits_xor;
unsigned int col;
/*
* Copy from an 8x8 monochrome pattern with color expansion.
*/
#if DEPTH == 24
/*
* For packed-24 modes, GR2F bits [4:0] are a count of destination
* bytes to be suppressed for each scanline, which we keep in
* dstskipleft. Our srcskipleft is the number of pixels to skip
* within the 8x8 source pattern to match up with that number
* of suppressed bytes. As the pattern repeats every 8 bits we
* take the number of pixels mod 8.
*/
int dstskipleft = s->vga.gr[0x2f] & 0x1f;
int srcskipleft = dstskipleft / 3;
int srcskipleft = (dstskipleft / 3) & 0x7;
#else
/*
* In all other modes, GR2F bits [2:0] are a count of how many
* destination pixels to suppress for each scanline, which is our
* srcskipleft. We get dstskipleft, the number of bytes to skip,
* by multiplying this by the bytes-per-pixel.
*/
int srcskipleft = s->vga.gr[0x2f] & 0x07;
int dstskipleft = srcskipleft * (DEPTH / 8);
#endif
+3 -3
View File
@@ -712,8 +712,7 @@ static void virgl_cmd_resource_create_blob(VirtIOGPU *g,
return;
}
res = virtio_gpu_virgl_find_resource(g, cblob.resource_id);
if (res) {
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;
@@ -766,8 +765,9 @@ static void virgl_cmd_resource_create_blob(VirtIOGPU *g,
res->base.dmabuf_fd = info.fd;
/* Now live, cleaned up in virtio_gpu_virgl_resource_unref */
QTAILQ_INSERT_HEAD(&g->reslist, &res->base, next);
res = NULL;
g_steal_pointer(&res);
}
static void virgl_cmd_resource_map_blob(VirtIOGPU *g,
+25 -11
View File
@@ -227,16 +227,20 @@ void virtio_gpu_get_edid(VirtIOGPU *g,
virtio_gpu_ctrl_response(g, cmd, &edid.hdr, sizeof(edid));
}
static uint32_t calc_image_hostmem(pixman_format_code_t pformat,
uint32_t width, uint32_t height)
static bool calc_image_hostmem(pixman_format_code_t pformat,
uint32_t width, uint32_t height,
uint32_t *hostmem)
{
/* Copied from pixman/pixman-bits-image.c, skip integer overflow check.
* pixman_image_create_bits will fail in case it overflow.
*/
uint64_t bpp = PIXMAN_FORMAT_BPP(pformat);
uint64_t stride = (((uint64_t)width * bpp + 0x1f) >> 5) * sizeof(uint32_t);
uint64_t size = (uint64_t)height * stride;
int bpp = PIXMAN_FORMAT_BPP(pformat);
int stride = ((width * bpp + 0x1f) >> 5) * sizeof(uint32_t);
return height * stride;
if (size > UINT32_MAX) {
return false;
}
*hostmem = size;
return true;
}
static void virtio_gpu_resource_create_2d(VirtIOGPU *g,
@@ -246,6 +250,7 @@ static void virtio_gpu_resource_create_2d(VirtIOGPU *g,
pixman_format_code_t pformat;
struct virtio_gpu_simple_resource *res;
struct virtio_gpu_resource_create_2d c2d;
uint32_t hostmem;
VIRTIO_GPU_FILL_CMD(c2d);
virtio_gpu_bswap_32(&c2d, sizeof(c2d));
@@ -284,7 +289,12 @@ static void virtio_gpu_resource_create_2d(VirtIOGPU *g,
return;
}
res->hostmem = calc_image_hostmem(pformat, c2d.width, c2d.height);
if (!calc_image_hostmem(pformat, c2d.width, c2d.height, &hostmem)) {
qemu_log_mask(LOG_GUEST_ERROR, "%s: image dimensions overflow\n",
__func__);
goto end;
}
res->hostmem = hostmem;
if (res->hostmem + g->hostmem < g->conf_max_hostmem) {
if (!qemu_pixman_image_new_shareable(
&res->image,
@@ -1292,7 +1302,7 @@ static int virtio_gpu_load(QEMUFile *f, void *opaque, size_t size,
VirtIOGPU *g = opaque;
Error *err = NULL;
struct virtio_gpu_simple_resource *res;
uint32_t resource_id, pformat;
uint32_t resource_id, pformat, hostmem;
int i, ret;
g->hostmem = 0;
@@ -1318,7 +1328,11 @@ static int virtio_gpu_load(QEMUFile *f, void *opaque, size_t size,
return -EINVAL;
}
res->hostmem = calc_image_hostmem(pformat, res->width, res->height);
if (!calc_image_hostmem(pformat, res->width, res->height, &hostmem)) {
g_free(res);
return -EINVAL;
}
res->hostmem = hostmem;
if (!qemu_pixman_image_new_shareable(&res->image,
&res->share_handle,
"virtio-gpu res",
+33 -10
View File
@@ -102,6 +102,7 @@ static void pl080_run(PL080State *s)
int size;
uint8_t buff[4];
uint32_t req;
uint32_t next_lli;
s->tc_mask = 0;
for (c = 0; c < s->nchannels; c++) {
@@ -164,40 +165,61 @@ again:
destination widths are different. */
swidth = 1 << ((ch->ctrl >> 18) & 7);
dwidth = 1 << ((ch->ctrl >> 21) & 7);
for (n = 0; n < dwidth; n+= swidth) {
/* Only widths of 1, 2 or 4 are valid */
if (swidth > 4) {
qemu_log_mask(LOG_GUEST_ERROR,
"pl080: channel %d: invalid SWidth %d\n",
c, extract32(ch->ctrl, 18, 3));
continue;
}
if (dwidth > 4) {
qemu_log_mask(LOG_GUEST_ERROR,
"pl080: channel %d: invalid DWidth %d\n",
c, extract32(ch->ctrl, 21, 3));
continue;
}
if ((size * swidth) % dwidth) {
qemu_log_mask(LOG_GUEST_ERROR,
"pl080: channel %d: transfer size mismatch: size=%d swidth=%d dwidth=%d\n",
c, size, swidth, dwidth);
continue;
}
xsize = MAX(swidth, dwidth);
for (n = 0; n < xsize; n += swidth) {
address_space_read(&s->downstream_as, ch->src,
MEMTXATTRS_UNSPECIFIED, buff + n, swidth);
if (ch->ctrl & PL080_CCTRL_SI)
ch->src += swidth;
}
xsize = (dwidth < swidth) ? swidth : dwidth;
/* ??? This may pad the value incorrectly for dwidth < 32. */
for (n = 0; n < xsize; n += dwidth) {
address_space_write(&s->downstream_as, ch->dest + n,
address_space_write(&s->downstream_as, ch->dest,
MEMTXATTRS_UNSPECIFIED, buff + n, dwidth);
if (ch->ctrl & PL080_CCTRL_DI)
ch->dest += swidth;
ch->dest += dwidth;
}
size--;
size -= xsize / swidth;
ch->ctrl = (ch->ctrl & 0xfffff000) | size;
if (size == 0) {
/* Transfer complete. */
if (ch->lli) {
next_lli = (ch->lli & ~3);
if (next_lli) {
ch->src = address_space_ldl_le(&s->downstream_as,
ch->lli,
next_lli,
MEMTXATTRS_UNSPECIFIED,
NULL);
ch->dest = address_space_ldl_le(&s->downstream_as,
ch->lli + 4,
next_lli + 4,
MEMTXATTRS_UNSPECIFIED,
NULL);
ch->ctrl = address_space_ldl_le(&s->downstream_as,
ch->lli + 12,
next_lli + 12,
MEMTXATTRS_UNSPECIFIED,
NULL);
ch->lli = address_space_ldl_le(&s->downstream_as,
ch->lli + 8,
next_lli + 8,
MEMTXATTRS_UNSPECIFIED,
NULL);
} else {
@@ -212,6 +234,7 @@ again:
if (--s->running)
s->running = 1;
}
pl080_update(s);
}
static uint64_t pl080_read(void *opaque, hwaddr offset,
+6 -1
View File
@@ -41,8 +41,13 @@ static uint64_t microbit_i2c_read(void *opaque, hwaddr addr, unsigned int size)
data = 0x01;
break;
case NRF51_TWI_REG_RXD:
/*
* Return the next byte from our fake data sequence. If
* the guest keeps reading the register after that, keep
* returning the same last byte value.
*/
data = twi_read_sequence[s->read_idx];
if (s->read_idx < G_N_ELEMENTS(twi_read_sequence)) {
if (s->read_idx + 1 < G_N_ELEMENTS(twi_read_sequence)) {
s->read_idx++;
}
break;
+102 -44
View File
@@ -648,6 +648,52 @@ static uint64_t large_pte_page_size(uint64_t pte)
return PTE_LARGE_PAGE_SIZE(pte);
}
/*
* Validate DTE fields and extract permissions and top level data required to
* initiate the page table walk.
*
* On success, returns 0 and stores:
* - top_level: highest page-table level encoded in DTE[Mode]
* - dte_perms: effective permissions from the DTE
*
* On failure, returns -AMDVI_FR_PT_ROOT_INV. This includes cases where:
* - DTE permissions disallow read AND write
* - DTE[Mode] is invalid for translation
* - IOVA exceeds the address width supported by DTE[Mode]
* In all such cases a page walk must be aborted.
*/
static uint64_t amdvi_get_top_pt_level_and_perms(hwaddr address, uint64_t dte,
uint8_t *top_level,
IOMMUAccessFlags *dte_perms)
{
*dte_perms = amdvi_get_perms(dte);
if (*dte_perms == IOMMU_NONE) {
return -AMDVI_FR_PT_ROOT_INV;
}
/* Verifying a valid mode is encoded in DTE */
*top_level = get_pte_translation_mode(dte);
/*
* Page Table Root pointer is only valid for GPA->SPA translation on
* supported modes.
*/
if (*top_level == 0 || *top_level > 6) {
return -AMDVI_FR_PT_ROOT_INV;
}
/*
* If IOVA is larger than the max supported by the highest pgtable level,
* there is nothing to do.
*/
if (address > PT_LEVEL_MAX_ADDR(*top_level)) {
/* IOVA too large for the current DTE */
return -AMDVI_FR_PT_ROOT_INV;
}
return 0;
}
/*
* Helper function to fetch a PTE using AMD v1 pgtable format.
* On successful page walk, returns 0 and pte parameter points to a valid PTE.
@@ -662,40 +708,49 @@ static uint64_t large_pte_page_size(uint64_t pte)
static uint64_t fetch_pte(AMDVIAddressSpace *as, hwaddr address, uint64_t dte,
uint64_t *pte, hwaddr *page_size)
{
IOMMUAccessFlags perms = amdvi_get_perms(dte);
uint8_t level, mode;
uint64_t pte_addr;
uint8_t pt_level, next_pt_level;
IOMMUAccessFlags perms;
int ret;
*pte = dte;
*page_size = 0;
if (perms == IOMMU_NONE) {
/*
* Verify the DTE is properly configured before page walk, and extract
* top pagetable level and permissions.
*/
ret = amdvi_get_top_pt_level_and_perms(address, dte, &pt_level, &perms);
if (ret < 0) {
return ret;
}
/*
* Retrieve the top pagetable entry by following the DTE Page Table Root
* Pointer and indexing the top level table using the IOVA from the request.
*/
pte_addr = NEXT_PTE_ADDR(dte, pt_level, address);
*pte = amdvi_get_pte_entry(as->iommu_state, pte_addr, as->devfn);
if (*pte == (uint64_t)-1) {
/*
* A returned PTE of -1 here indicates a failure to read the top level
* page table from guest memory. A page walk is not possible and page
* size must be returned as 0.
*/
return -AMDVI_FR_PT_ROOT_INV;
}
/*
* The Linux kernel driver initializes the default mode to 3, corresponding
* to a 39-bit GPA space, where each entry in the pagetable translates to a
* 1GB (2^30) page size.
* Calculate page size for the top level page table entry.
* This ensures correct results for a single level Page Table setup.
*/
level = mode = get_pte_translation_mode(dte);
assert(mode > 0 && mode < 7);
*page_size = PTE_LEVEL_PAGE_SIZE(pt_level);
/*
* If IOVA is larger than the max supported by the current pgtable level,
* there is nothing to do.
* The root page table entry and its level have been determined. Begin the
* page walk.
*/
if (address > PT_LEVEL_MAX_ADDR(mode - 1)) {
/* IOVA too large for the current DTE */
return -AMDVI_FR_PT_ROOT_INV;
}
do {
level -= 1;
/* Update the page_size */
*page_size = PTE_LEVEL_PAGE_SIZE(level);
while (pt_level > 0) {
/* Permission bits are ANDed at every level, including the DTE */
perms &= amdvi_get_perms(*pte);
@@ -708,37 +763,38 @@ static uint64_t fetch_pte(AMDVIAddressSpace *as, hwaddr address, uint64_t dte,
return 0;
}
next_pt_level = PTE_NEXT_LEVEL(*pte);
/* Large or Leaf PTE found */
if (PTE_NEXT_LEVEL(*pte) == 7 || PTE_NEXT_LEVEL(*pte) == 0) {
if (next_pt_level == 0 || next_pt_level == 7) {
/* Leaf PTE found */
break;
}
/* Next level must always be less than current level */
if (pt_level <= next_pt_level) {
return -AMDVI_FR_PT_ENTRY_INV;
}
pt_level = next_pt_level;
/*
* Index the pgtable using the IOVA bits corresponding to current level
* and walk down to the lower level.
* The current entry is a Page Directory Entry. Descend to the lower
* page table level encoded in current pte, and index the new table
* using the appropriate IOVA bits to retrieve the new entry.
*/
pte_addr = NEXT_PTE_ADDR(*pte, level, address);
*page_size = PTE_LEVEL_PAGE_SIZE(pt_level);
pte_addr = NEXT_PTE_ADDR(*pte, pt_level, address);
*pte = amdvi_get_pte_entry(as->iommu_state, pte_addr, as->devfn);
if (*pte == (uint64_t)-1) {
/*
* A returned PTE of -1 indicates a failure to read the page table
* entry from guest memory.
*/
if (level == mode - 1) {
/* Failure to retrieve the Page Table from Root Pointer */
*page_size = 0;
return -AMDVI_FR_PT_ROOT_INV;
} else {
/* Failure to read PTE. Page walk skips a page_size chunk */
return -AMDVI_FR_PT_ENTRY_INV;
}
/* Failure to read PTE. Page walk skips a page_size chunk */
return -AMDVI_FR_PT_ENTRY_INV;
}
} while (level > 0);
}
assert(PTE_NEXT_LEVEL(*pte) == 0 || PTE_NEXT_LEVEL(*pte) == 7);
assert(PTE_NEXT_LEVEL(*pte) == 0 || PTE_NEXT_LEVEL(*pte) == 7 ||
level == 0);
/*
* Page walk ends when Next Level field on PTE shows that either a leaf PTE
* or a series of large PTEs have been reached. In the latter case, even if
@@ -1475,12 +1531,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);
}
}
@@ -1578,7 +1634,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);
}
@@ -1594,7 +1651,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);
}
+5 -6
View File
@@ -186,17 +186,16 @@
#define IOMMU_PTE_PRESENT(pte) ((pte) & AMDVI_PTE_PR)
/* Using level=0 for leaf PTE at 4K page size */
#define PT_LEVEL_SHIFT(level) (12 + ((level) * 9))
/* Using level=1 for leaf PTE at 4K page size */
#define PT_LEVEL_SHIFT(level) (12 + (((level) - 1) * 9))
/* Return IOVA bit group used to index the Page Table at specific level */
#define PT_LEVEL_INDEX(level, iova) (((iova) >> PT_LEVEL_SHIFT(level)) & \
GENMASK64(8, 0))
/* Return the max address for a specified level i.e. max_oaddr */
#define PT_LEVEL_MAX_ADDR(x) (((x) < 5) ? \
((1ULL << PT_LEVEL_SHIFT((x + 1))) - 1) : \
(~(0ULL)))
/* Return the maximum output address for a specified page table level */
#define PT_LEVEL_MAX_ADDR(level) (((level) > 5) ? (~(0ULL)) : \
((1ULL << PT_LEVEL_SHIFT((level) + 1)) - 1))
/* Extract the NextLevel field from PTE/PDE */
#define PTE_NEXT_LEVEL(pte) (((pte) & AMDVI_PTE_NEXT_LEVEL_MASK) >> 9)
+53 -62
View File
@@ -420,24 +420,15 @@ typedef struct TrimAIOCB {
QEMUBH *bh;
int ret;
QEMUIOVector *qiov;
BlockAIOCB *aiocb;
int i, j;
bool canceled;
} TrimAIOCB;
static void trim_aio_cancel(BlockAIOCB *acb)
{
TrimAIOCB *iocb = container_of(acb, TrimAIOCB, common);
/* Exit the loop so ide_issue_trim_cb will not continue */
iocb->j = iocb->qiov->niov - 1;
iocb->i = (iocb->qiov->iov[iocb->j].iov_len / 8) - 1;
iocb->ret = -ECANCELED;
if (iocb->aiocb) {
blk_aio_cancel_async(iocb->aiocb);
iocb->aiocb = NULL;
}
/* Exit the loop so ide_trim_co_entry will not continue */
iocb->canceled = true;
}
static const AIOCBInfo trim_aiocb_info = {
@@ -456,65 +447,64 @@ static void ide_trim_bh_cb(void *opaque)
iocb->bh = NULL;
qemu_aio_unref(iocb);
/* Paired with an increment in ide_issue_trim() */
blk_dec_in_flight(blk);
/* Paired with blk_co_start_request in ide_trim_co_entry() */
blk_end_request(blk);
}
static void ide_issue_trim_cb(void *opaque, int ret)
static void coroutine_fn ide_trim_co_entry(void *opaque)
{
TrimAIOCB *iocb = opaque;
IDEState *s = iocb->s;
int i, j;
int ret;
if (iocb->i >= 0) {
if (ret >= 0) {
block_acct_done(blk_get_stats(s->blk), &s->acct);
} else {
block_acct_failed(blk_get_stats(s->blk), &s->acct);
}
}
/* Paired with blk_end_request in ide_trim_bh_cb() */
blk_co_start_request(s->blk);
if (ret >= 0) {
while (iocb->j < iocb->qiov->niov) {
int j = iocb->j;
while (++iocb->i < iocb->qiov->iov[j].iov_len / 8) {
int i = iocb->i;
uint64_t *buffer = iocb->qiov->iov[j].iov_base;
for (j = 0; j < iocb->qiov->niov; j++) {
for (i = 0; i < iocb->qiov->iov[j].iov_len / 8; i++) {
uint64_t *buffer = iocb->qiov->iov[j].iov_base;
/* 6-byte LBA + 2-byte range per entry */
uint64_t entry = le64_to_cpu(buffer[i]);
uint64_t sector = entry & 0x0000ffffffffffffULL;
uint16_t count = entry >> 48;
/* 6-byte LBA + 2-byte range per entry */
uint64_t entry = le64_to_cpu(buffer[i]);
uint64_t sector = entry & 0x0000ffffffffffffULL;
uint16_t count = entry >> 48;
if (count == 0) {
continue;
}
if (!ide_sect_range_ok(s, sector, count)) {
block_acct_invalid(blk_get_stats(s->blk), BLOCK_ACCT_UNMAP);
iocb->ret = -EINVAL;
goto done;
}
block_acct_start(blk_get_stats(s->blk), &s->acct,
count << BDRV_SECTOR_BITS, BLOCK_ACCT_UNMAP);
/* Got an entry! Submit and exit. */
iocb->aiocb = blk_aio_pdiscard(s->blk,
sector << BDRV_SECTOR_BITS,
count << BDRV_SECTOR_BITS,
ide_issue_trim_cb, opaque);
return;
if (count == 0) {
continue;
}
iocb->j++;
iocb->i = -1;
if (iocb->canceled) {
iocb->ret = -ECANCELED;
goto done;
}
if (!ide_sect_range_ok(s, sector, count)) {
block_acct_invalid(blk_get_stats(s->blk), BLOCK_ACCT_UNMAP);
iocb->ret = -EINVAL;
goto done;
}
block_acct_start(blk_get_stats(s->blk), &s->acct,
count << BDRV_SECTOR_BITS, BLOCK_ACCT_UNMAP);
/* Got an entry! Submit and exit. */
ret = blk_co_pdiscard(s->blk,
sector << BDRV_SECTOR_BITS,
count << BDRV_SECTOR_BITS,
BDRV_REQ_NO_QUEUE);
if (ret >= 0) {
block_acct_done(blk_get_stats(s->blk), &s->acct);
} else {
iocb->ret = ret;
block_acct_failed(blk_get_stats(s->blk), &s->acct);
goto done;
}
}
} else {
iocb->ret = ret;
}
iocb->ret = 0;
done:
iocb->aiocb = NULL;
if (iocb->bh) {
replay_bh_schedule_event(iocb->bh);
}
@@ -527,9 +517,7 @@ BlockAIOCB *ide_issue_trim(
IDEState *s = opaque;
IDEDevice *dev = s->unit ? s->bus->slave : s->bus->master;
TrimAIOCB *iocb;
/* Paired with a decrement in ide_trim_bh_cb() */
blk_inc_in_flight(s->blk);
Coroutine *co;
iocb = blk_aio_get(&trim_aiocb_info, s->blk, cb, cb_opaque);
iocb->s = s;
@@ -537,9 +525,11 @@ BlockAIOCB *ide_issue_trim(
&DEVICE(dev)->mem_reentrancy_guard);
iocb->ret = 0;
iocb->qiov = qiov;
iocb->i = -1;
iocb->j = 0;
ide_issue_trim_cb(iocb, 0);
iocb->canceled = false;
co = qemu_coroutine_create(ide_trim_co_entry, iocb);
aio_co_enter(qemu_get_current_aio_context(), co);
return &iocb->common;
}
@@ -799,6 +789,7 @@ static void ide_sector_read(IDEState *s)
s->error = 0; /* not needed by IDE spec, but needed by Windows */
sector_num = ide_get_sector(s);
n = s->nsector;
ide_set_retry(s);
if (n == 0) {
ide_transfer_stop(s);
+8 -9
View File
@@ -647,13 +647,6 @@ static void apic_deliver(APICCommonState *s, 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(s)) {
current_apic_id = s->initial_apic_id;
} else {
current_apic_id = s->id;
}
switch (dest_shorthand) {
case 0:
@@ -661,14 +654,20 @@ static void apic_deliver(APICCommonState *s, 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;
}
+33 -2
View File
@@ -1869,9 +1869,40 @@ static void icc_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
* at a priority outside the Non-secure range (128..255), since this
* would otherwise allow malicious NS code to block delivery of S interrupts
* by writing a bad value to these registers.
*
* The NS priority range (128..255) maps to APR bits starting at
* aprbit = 0x80 >> (8 - prebits). Depending on prebits, this boundary
* may fall within AP1R0 or AP1R1, so we cannot simply WI the entire
* register. Instead we calculate which bits within each register
* correspond to the Secure range and preserve those, while allowing
* NS code to modify only the NS range bits.
*
* prebits=4: num_aprs=1, NS starts at AP1R0[8]
* prebits=5: num_aprs=1, NS starts at AP1R0[16]
* prebits=6: num_aprs=2, NS starts at AP1R1[0]
* prebits=7: num_aprs=4, NS starts at AP1R2[0]
*/
if (grp == GICV3_G1NS && regno < 2 && arm_feature(env, ARM_FEATURE_EL3)) {
return;
if (grp == GICV3_G1NS && arm_feature(env, ARM_FEATURE_EL3)) {
int ns_start_bit = 0x80 >> (8 - cs->prebits);
int ns_start_regno = ns_start_bit / 32;
int ns_start_regbit = ns_start_bit % 32;
if (regno < ns_start_regno) {
/* This entire register is in the Secure range: WI */
return;
} else if (regno == ns_start_regno && ns_start_regbit > 0) {
/*
* This register is split: low bits are Secure, high bits are NS.
* Preserve the Secure bits (below ns_start_regbit) from the
* current value, and take the NS bits (at and above
* ns_start_regbit) from the written value.
*/
uint32_t secure_mask = MAKE_64BIT_MASK(0, ns_start_regbit);
value = (cs->icc_apr[grp][regno] & secure_mask) |
(value & ~secure_mask);
}
/* else: regno > ns_start_regno, entire register is NS: allow write */
}
if (cs->nmi_support) {
+6 -4
View File
@@ -131,6 +131,7 @@ static uint64_t riscv_aclint_mtimer_read(void *opaque, hwaddr addr,
addr < (mtimer->timecmp_base + (mtimer->num_harts << 3))) {
size_t hartid = mtimer->hartid_base +
((addr - mtimer->timecmp_base) >> 3);
size_t hartid_offset = hartid - mtimer->hartid_base;
CPUState *cpu = cpu_by_arch_id(hartid);
CPURISCVState *env = cpu ? cpu_env(cpu) : NULL;
if (!env) {
@@ -138,11 +139,11 @@ static uint64_t riscv_aclint_mtimer_read(void *opaque, hwaddr addr,
"aclint-mtimer: invalid hartid: %zu", hartid);
} else if ((addr & 0x7) == 0) {
/* timecmp_lo for RV32/RV64 or timecmp for RV64 */
uint64_t timecmp = mtimer->timecmp[hartid];
uint64_t timecmp = mtimer->timecmp[hartid_offset];
return (size == 4) ? (timecmp & 0xFFFFFFFF) : timecmp;
} else if ((addr & 0x7) == 4) {
/* timecmp_hi */
uint64_t timecmp = mtimer->timecmp[hartid];
uint64_t timecmp = mtimer->timecmp[hartid_offset];
return (timecmp >> 32) & 0xFFFFFFFF;
} else {
qemu_log_mask(LOG_UNIMP,
@@ -174,6 +175,7 @@ static void riscv_aclint_mtimer_write(void *opaque, hwaddr addr,
addr < (mtimer->timecmp_base + (mtimer->num_harts << 3))) {
size_t hartid = mtimer->hartid_base +
((addr - mtimer->timecmp_base) >> 3);
size_t hartid_offset = hartid - mtimer->hartid_base;
CPUState *cpu = cpu_by_arch_id(hartid);
CPURISCVState *env = cpu ? cpu_env(cpu) : NULL;
if (!env) {
@@ -182,7 +184,7 @@ static void riscv_aclint_mtimer_write(void *opaque, hwaddr addr,
} else if ((addr & 0x7) == 0) {
if (size == 4) {
/* timecmp_lo for RV32/RV64 */
uint64_t timecmp_hi = mtimer->timecmp[hartid] >> 32;
uint64_t timecmp_hi = mtimer->timecmp[hartid_offset] >> 32;
riscv_aclint_mtimer_write_timecmp(mtimer, RISCV_CPU(cpu), hartid,
timecmp_hi << 32 | (value & 0xFFFFFFFF));
} else {
@@ -193,7 +195,7 @@ static void riscv_aclint_mtimer_write(void *opaque, hwaddr addr,
} else if ((addr & 0x7) == 4) {
if (size == 4) {
/* timecmp_hi for RV32/RV64 */
uint64_t timecmp_lo = mtimer->timecmp[hartid];
uint64_t timecmp_lo = mtimer->timecmp[hartid_offset];
riscv_aclint_mtimer_write_timecmp(mtimer, RISCV_CPU(cpu), hartid,
value << 32 | (timecmp_lo & 0xFFFFFFFF));
} else {
+8
View File
@@ -26,6 +26,7 @@
*/
#include "qemu/osdep.h"
#include "qemu/log.h"
#include "qapi/error.h"
#include "trace.h"
#include "qemu/timer.h"
@@ -222,6 +223,13 @@ void icp_irq(ICSState *ics, int server, int nr, uint8_t priority)
trace_xics_icp_irq(server, nr, priority);
if (!icp) {
qemu_log_mask(LOG_GUEST_ERROR, "XICS: invalid server %d for IRQ 0x%x\n",
server, nr);
ics_reject(ics, nr);
return;
}
if ((priority >= CPPR(icp))
|| (XISR(icp) && (icp->pending_priority <= priority))) {
ics_reject(ics, nr);
+27 -2
View File
@@ -154,6 +154,14 @@ static bool has_padding(AspeedHACEState *s, struct iovec *iov,
hwaddr req_len, uint32_t *total_msg_len,
uint32_t *pad_offset)
{
/* Need at least 8 bytes to read the total message length field */
if (req_len < 8) {
qemu_log_mask(LOG_GUEST_ERROR,
"%s: invalid request length=0x%" HWADDR_PRIx "\n",
__func__, req_len);
return false;
}
*total_msg_len = (uint32_t)(ldq_be_p(iov->iov_base + req_len - 8) / 8);
/*
* SG_LIST_LEN_LAST asserted in the request length doesn't mean it is the
@@ -197,6 +205,19 @@ static uint64_t hash_get_source_addr(AspeedHACEState *s)
return src_addr;
}
static bool hash_accumulate_len(AspeedHACEState *s, hwaddr plen)
{
if (plen > UINT32_MAX - s->total_req_len) {
qemu_log_mask(LOG_GUEST_ERROR,
"%s: total_req_len overflow, current=0x%x, adding=0x%"
HWADDR_PRIx "\n", __func__, s->total_req_len, plen);
return false;
}
s->total_req_len += plen;
return true;
}
static int hash_prepare_direct_iov(AspeedHACEState *s, struct iovec *iov,
bool acc_mode, bool *acc_final_request)
{
@@ -224,7 +245,9 @@ static int hash_prepare_direct_iov(AspeedHACEState *s, struct iovec *iov,
iov_idx = 1;
if (acc_mode) {
s->total_req_len += plen;
if (!hash_accumulate_len(s, plen)) {
return -1;
}
if (has_padding(s, &iov[0], plen, &total_msg_len,
&pad_offset)) {
@@ -291,7 +314,9 @@ static int hash_prepare_sg_iov(AspeedHACEState *s, struct iovec *iov,
iov[iov_idx].iov_base = haddr;
if (acc_mode) {
s->total_req_len += plen;
if (!hash_accumulate_len(s, plen)) {
return -1;
}
if (has_padding(s, &iov[iov_idx], plen, &total_msg_len,
&pad_offset)) {
+10 -2
View File
@@ -159,9 +159,17 @@ static bool aspeed_sbc_otp_prog(AspeedSBCState *s,
MemTxResult ret;
AspeedOTPState *otp = &s->otp;
uint32_t value = s->regs[R_CAMP1];
uint32_t otp_offset = otp_addr << 2;
ret = address_space_write(&otp->as, otp_addr, MEMTXATTRS_UNSPECIFIED,
&value, sizeof(value));
if (otp_addr >= OTP_TOTAL_DWORD_COUNT) {
qemu_log_mask(LOG_GUEST_ERROR,
"Invalid OTP addr 0x%x\n",
otp_addr);
return false;
}
ret = address_space_write(&otp->as, otp_offset, MEMTXATTRS_UNSPECIFIED,
&value, sizeof(value));
if (ret != MEMTX_OK) {
qemu_log_mask(LOG_GUEST_ERROR,
"Failed to write OTP memory, addr = %x\n",
+3
View File
@@ -73,6 +73,9 @@ static const MemoryRegionOps avr_mask_ops = {
.impl = {
.max_access_size = 1,
},
.valid = {
.max_access_size = 1,
},
};
static void avr_mask_init(Object *dev)
+4
View File
@@ -93,6 +93,10 @@ static const MemoryRegionOps bcm2835_rng_ops = {
.read = bcm2835_rng_read,
.write = bcm2835_rng_write,
.endianness = DEVICE_NATIVE_ENDIAN,
.impl.min_access_size = 4,
.impl.max_access_size = 4,
.valid.min_access_size = 4,
.valid.max_access_size = 4,
};
static const VMStateDescription vmstate_bcm2835_rng = {
+3
View File
@@ -727,6 +727,9 @@ static void allwinner_sun8i_emac_write(void *opaque, hwaddr offset,
break;
case REG_RX_CTL_0: /* Receive Control 0 */
s->rx_ctl0 = value;
if (allwinner_sun8i_emac_can_receive(nc)) {
qemu_flush_queued_packets(nc);
}
break;
case REG_RX_CTL_1: /* Receive Control 1 */
s->rx_ctl1 = value | RX_CTL1_RX_MD;
+8 -2
View File
@@ -624,7 +624,10 @@ static void ftgmac100_do_tx(FTGMAC100State *s, uint64_t tx_ring,
bd.des0 &= ~FTGMAC100_TXDES0_TXDMA_OWN;
/* Write back the modified descriptor. */
ftgmac100_write_bd(&bd, addr);
if (ftgmac100_write_bd(&bd, addr)) {
s->isr |= FTGMAC100_INT_AHB_ERR;
break;
}
/* Advance to the next descriptor. */
if (bd.des0 & s->txdes0_edotr) {
addr = tx_ring;
@@ -1134,7 +1137,10 @@ static ssize_t ftgmac100_receive(NetClientState *nc, const uint8_t *buf,
bd.des0 |= flags | FTGMAC100_RXDES0_LRS;
s->isr |= FTGMAC100_INT_RPKT_BUF;
}
ftgmac100_write_bd(&bd, addr);
if (ftgmac100_write_bd(&bd, addr)) {
s->isr |= FTGMAC100_INT_AHB_ERR;
break;
}
if (bd.des0 & s->rxdes0_edorr) {
addr = s->rx_ring;
} else {
+11 -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;
@@ -299,9 +299,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) {
@@ -2024,6 +2024,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]);
}
@@ -2054,6 +2058,7 @@ static int of_dpa_cmd_add_l2_flood(OfDpa *of_dpa, OfDpaGroup *group,
err_out:
group->l2_flood.group_count = 0;
g_free(group->l2_flood.group_ids);
group->l2_flood.group_ids = NULL;
g_free(tlvs);
return err;
+23
View File
@@ -2132,6 +2132,26 @@ static int rtl8139_cplus_transmit_one(RTL8139State *s)
hlen, ip->ip_sum);
}
/*
* The code in this function triggers a GCC bug where an
* interaction between -fsanitize=address and -Wstringop-overflow
* results in a false-positive stringop-overflow warning that is
* only emitted when the address sanitizer is enabled:
* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=114494
* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=99673
* GCC incorrectly thinks that the eth_payload_data buffer has
* the type and size of the first field in 'struct ip_header', i.e.
* one byte, and then complains about all other attempts to access
* data in the buffer.
*
* Work around this by disabling the warning when building with
* GCC and the address sanitizer is enabled.
*/
#pragma GCC diagnostic push
#if !defined(__clang__) && defined(QEMU_SANITIZE_ADDRESS)
#pragma GCC diagnostic ignored "-Wstringop-overflow"
#endif
if ((txdw0 & CP_TX_LGSEN) && ip_protocol == IP_PROTO_TCP)
{
/* Large enough for the TCP header? */
@@ -2315,6 +2335,9 @@ static int rtl8139_cplus_transmit_one(RTL8139State *s)
/* restore IP header */
memcpy(eth_payload_data, saved_ip_header, hlen);
}
#pragma GCC diagnostic pop
}
skip_offload:
+5 -3
View File
@@ -5517,7 +5517,7 @@ static void nvme_free_cq(NvmeCQueue *cq, NvmeCtrl *n)
event_notifier_set_handler(&cq->notifier, NULL);
event_notifier_cleanup(&cq->notifier);
}
if (msix_enabled(pci) && cq->irq_enabled) {
if (msix_present(pci) && cq->irq_enabled) {
msix_vector_unuse(pci, cq->vector);
}
if (cq->cqid) {
@@ -5558,7 +5558,7 @@ static void nvme_init_cq(NvmeCQueue *cq, NvmeCtrl *n, uint64_t dma_addr,
{
PCIDevice *pci = PCI_DEVICE(n);
if (msix_enabled(pci) && irq_enabled) {
if (msix_present(pci) && irq_enabled) {
msix_vector_use(pci, vector);
}
@@ -6111,7 +6111,7 @@ static uint16_t nvme_abort(NvmeCtrl *n, NvmeRequest *req)
{
uint16_t sqid = le32_to_cpu(req->cmd.cdw10) & 0xffff;
uint16_t cid = (le32_to_cpu(req->cmd.cdw10) >> 16) & 0xffff;
NvmeSQueue *sq = n->sq[sqid];
NvmeSQueue *sq;
NvmeRequest *r, *next;
int i;
@@ -6120,6 +6120,8 @@ static uint16_t nvme_abort(NvmeCtrl *n, NvmeRequest *req)
return NVME_INVALID_FIELD | NVME_DNR;
}
sq = n->sq[sqid];
if (sqid == 0) {
for (i = 0; i < n->outstanding_aers; i++) {
NvmeRequest *re = n->aer_reqs[i];
+1 -1
View File
@@ -75,7 +75,7 @@ static int nvme_ns_init(NvmeNamespace *ns, Error **errp)
ns->csi = NVME_CSI_NVM;
ns->status = 0x0;
ns->id_ns.dlfeat = 0x1;
ns->id_ns.dlfeat = 0x9;
/* support DULBE and I/O optimization fields */
id_ns->nsfeat |= (NVME_ID_NS_NSFEAT_DAE | NVME_ID_NS_NSFEAT_OPTPERF_ALL);
+6 -7
View File
@@ -57,12 +57,12 @@ static bool valid_program_data(uint32_t otp_addr,
return has_programmable_bits != 0;
}
static bool program_otpmem_data(void *opaque, uint32_t otp_addr,
static bool program_otpmem_data(void *opaque, hwaddr otp_offset,
uint32_t prog_bit, uint32_t *value)
{
AspeedOTPState *s = opaque;
uint32_t otp_addr = otp_offset >> 2;
bool is_odd = otp_addr & 1;
uint32_t otp_offset = otp_addr << 2;
memcpy(value, s->storage + otp_offset, sizeof(uint32_t));
@@ -79,26 +79,25 @@ static bool program_otpmem_data(void *opaque, uint32_t otp_addr,
return true;
}
static void aspeed_otp_write(void *opaque, hwaddr otp_addr,
static void aspeed_otp_write(void *opaque, hwaddr otp_offset,
uint64_t val, unsigned size)
{
AspeedOTPState *s = opaque;
uint32_t otp_offset, value;
uint32_t value;
if (!program_otpmem_data(s, otp_addr, val, &value)) {
if (!program_otpmem_data(s, otp_offset, val, &value)) {
qemu_log_mask(LOG_GUEST_ERROR,
"%s: Failed to program data, value = %x, bit = %"PRIx64"\n",
__func__, value, val);
return;
}
otp_offset = otp_addr << 2;
memcpy(s->storage + otp_offset, &value, size);
if (s->blk) {
if (blk_pwrite(s->blk, otp_offset, size, &value, 0) < 0) {
qemu_log_mask(LOG_GUEST_ERROR,
"%s: Failed to write %x to %x\n",
"%s: Failed to write %x to %"HWADDR_PRIx"\n",
__func__, value, otp_offset);
return;
+10
View File
@@ -475,6 +475,11 @@ void pnv_phb3_reg_write(void *opaque, hwaddr off, uint64_t val, unsigned size)
/* Special case configuration data */
if ((off & 0xfffc) == PHB_CONFIG_DATA) {
if (size > 4) {
phb3_error(phb, "Invalid config access, offset: 0x%"PRIx64" size: %d",
off, size);
return;
}
pnv_phb3_config_write(phb, off & 0x3, size, val);
return;
}
@@ -597,6 +602,11 @@ uint64_t pnv_phb3_reg_read(void *opaque, hwaddr off, unsigned size)
uint64_t val;
if ((off & 0xfffc) == PHB_CONFIG_DATA) {
if (size > 4) {
phb3_error(phb, "Invalid config access, offset: 0x%"PRIx64" size: %d",
off, size);
return ~0ull;
}
return pnv_phb3_config_read(phb, off & 0x3, size);
}
+12 -2
View File
@@ -81,7 +81,12 @@ void pci_host_config_write_common(PCIDevice *pci_dev, uint32_t addr,
return;
}
assert(len <= 4);
if (len > 4) {
PCI_DPRINTF("%s: invalid length access: addr " HWADDR_FMT_plx " \
len %d val %"PRIx32"\n", __func__, addr, len, val);
return;
}
/* non-zero functions are only exposed when function 0 is present,
* allowing direct removal of unexposed functions.
*/
@@ -106,7 +111,12 @@ uint32_t pci_host_config_read_common(PCIDevice *pci_dev, uint32_t addr,
return ~0x0;
}
assert(len <= 4);
if (len > 4) {
PCI_DPRINTF("%s: invalid length access: addr " HWADDR_FMT_plx " \
len %d val %"PRIx32"\n", __func__, addr, len, val);
return ~0x0;
}
/* non-zero functions are only exposed when function 0 is present,
* allowing direct removal of unexposed functions.
*/
+1 -1
View File
@@ -517,7 +517,7 @@ static int ppce500_load_device_tree(PPCE500MachineState *pms,
env->icache_line_size);
qemu_fdt_setprop_cell(fdt, cpu_name, "d-cache-size", 0x8000);
qemu_fdt_setprop_cell(fdt, cpu_name, "i-cache-size", 0x8000);
qemu_fdt_setprop_cell(fdt, cpu_name, "bus-frequency", 0);
qemu_fdt_setprop_cell(fdt, cpu_name, "bus-frequency", pmc->bus_freq);
if (cpu->cpu_index) {
qemu_fdt_setprop_string(fdt, cpu_name, "status", "disabled");
qemu_fdt_setprop_string(fdt, cpu_name, "enable-method",
+1
View File
@@ -40,6 +40,7 @@ struct PPCE500MachineClass {
hwaddr pci_mmio_bus_base;
hwaddr spin_base;
uint32_t clock_freq;
uint32_t bus_freq;
uint32_t tb_freq;
};
+1
View File
@@ -94,6 +94,7 @@ static void e500plat_machine_class_init(ObjectClass *oc, const void *data)
pmc->pci_mmio_bus_base = 0xE0000000ULL;
pmc->spin_base = 0xFEF000000ULL;
pmc->clock_freq = PLATFORM_CLK_FREQ_HZ;
pmc->bus_freq = PLATFORM_CLK_FREQ_HZ;
pmc->tb_freq = PLATFORM_CLK_FREQ_HZ;
mc->desc = "generic paravirt e500 platform";
+1
View File
@@ -56,6 +56,7 @@ static void mpc8544ds_machine_class_init(ObjectClass *oc, const void *data)
pmc->pci_pio_base = 0xE1000000ULL;
pmc->spin_base = 0xEF000000ULL;
pmc->clock_freq = PLATFORM_CLK_FREQ_HZ;
pmc->bus_freq = PLATFORM_CLK_FREQ_HZ;
pmc->tb_freq = PLATFORM_CLK_FREQ_HZ;
mc->desc = "mpc8544ds";
+35 -40
View File
@@ -747,51 +747,12 @@ static void pnv_powerdown_notify(Notifier *n, void *opaque)
static void pnv_reset(MachineState *machine, ResetType type)
{
PnvMachineState *pnv = PNV_MACHINE(machine);
IPMIBmc *bmc;
void *fdt;
qemu_devices_reset(type);
/*
* The machine should provide by default an internal BMC simulator.
* If not, try to use the BMC device that was provided on the command
* line.
*/
bmc = pnv_bmc_find(&error_fatal);
if (!pnv->bmc) {
if (!bmc) {
if (!qtest_enabled()) {
warn_report("machine has no BMC device. Use '-device "
"ipmi-bmc-sim,id=bmc0 -device isa-ipmi-bt,bmc=bmc0,irq=10' "
"to define one");
}
} else {
pnv_bmc_set_pnor(bmc, pnv->pnor);
pnv->bmc = bmc;
}
}
if (machine->fdt) {
fdt = machine->fdt;
} else {
fdt = pnv_dt_create(machine);
/* Pack resulting tree */
_FDT((fdt_pack(fdt)));
}
fdt = machine->fdt;
cpu_physical_memory_write(PNV_FDT_ADDR, fdt, fdt_totalsize(fdt));
/* Update machine->fdt with latest fdt */
if (machine->fdt != fdt) {
/*
* Set machine->fdt for 'dumpdtb' QMP/HMP command. Free
* the existing machine->fdt to avoid leaking it during
* a reset.
*/
g_free(machine->fdt);
machine->fdt = fdt;
}
}
static ISABus *pnv_chip_power8_isa_create(PnvChip *chip, Error **errp)
@@ -1001,6 +962,37 @@ static uint64_t pnv_chip_get_ram_size(PnvMachineState *pnv, int chip_id)
return chip_id == 0 ? 1 * GiB : QEMU_ALIGN_DOWN(ram_per_chip, 1 * MiB);
}
static void pnv_machine_init_done(Notifier *notifier, void *data)
{
PnvMachineState *pnv = container_of(notifier, PnvMachineState, machine_init_done);
MachineState *machine = MACHINE(pnv);
IPMIBmc *bmc;
/*
* The machine should provide by default an internal BMC simulator.
* If not, try to use the BMC device that was provided on the command
* line.
*/
bmc = pnv_bmc_find(&error_fatal);
if (!pnv->bmc) {
if (!bmc) {
if (!qtest_enabled()) {
warn_report("machine has no BMC device. Use '-device "
"ipmi-bmc-sim,id=bmc0 -device isa-ipmi-bt,bmc=bmc0,irq=10' "
"to define one");
}
} else {
pnv_bmc_set_pnor(bmc, pnv->pnor);
pnv->bmc = bmc;
}
}
if (!machine->fdt) {
machine->fdt = pnv_dt_create(machine);
_FDT((fdt_pack(machine->fdt)));
}
}
static void pnv_init(MachineState *machine)
{
const char *bios_name = machine->firmware ?: FW_FILE_NAME;
@@ -1260,6 +1252,9 @@ static void pnv_init(MachineState *machine)
if (pmc->i2c_init) {
pmc->i2c_init(pnv);
}
pnv->machine_init_done.notify = pnv_machine_init_done;
qemu_add_machine_init_done_notifier(&pnv->machine_init_done);
}
/*
+40 -4
View File
@@ -237,6 +237,25 @@ static bool riscv_iommu_msi_check(RISCVIOMMUState *s, RISCVIOMMUContext *ctx,
return true;
}
/* Returns the NAPOT page mask, or 0 for reserved encodings. */
static hwaddr riscv_iommu_napot_page_mask(hwaddr ppn, hwaddr addr, hwaddr *out)
{
int napot_bits = ctz64(ppn) + 1;
hwaddr napot_mask, page_mask;
/* The spec only defines 64KB (napot_bits == 4) */
if (napot_bits != 4) {
return 0;
}
napot_mask = (1ULL << napot_bits) - 1;
page_mask = PPN_PHYS(napot_mask) | (TARGET_PAGE_SIZE - 1);
*out = PPN_PHYS(ppn & ~napot_mask) | (addr & page_mask);
return page_mask;
}
/*
* RISCV IOMMU Address Translation Lookup - Page Table Walk
*
@@ -458,9 +477,20 @@ static int riscv_iommu_spa_fetch(RISCVIOMMUState *s, RISCVIOMMUContext *ctx,
} else {
/* Leaf PTE, translation completed. */
sc[pass].step = sc[pass].levels;
base = PPN_PHYS(ppn) | (addr & ((1ULL << va_skip) - 1));
/* Update address mask based on smallest translation granularity */
iotlb->addr_mask &= (1ULL << va_skip) - 1;
if (pte & PTE_N) {
hwaddr mask = riscv_iommu_napot_page_mask(ppn, addr, &base);
if (!mask) {
break;
}
iotlb->addr_mask &= mask;
} else {
base = PPN_PHYS(ppn) | (addr & ((1ULL << va_skip) - 1));
/* Update address mask based on smallest translation granularity */
iotlb->addr_mask &= (1ULL << va_skip) - 1;
}
/* Continue with S-Stage translation? */
if (pass && sc[0].step != sc[0].levels) {
pass = S_STAGE;
@@ -997,7 +1027,13 @@ static MemTxResult pdt_memory_read(RISCVIOMMUState *s,
return MEMTX_ACCESS_ERROR; /* Misaligned PPN */
} else {
/* Leaf PTE, translation completed. */
base = PPN_PHYS(ppn) | (addr & ((1ULL << va_skip) - 1));
if (pte & PTE_N) {
if (!riscv_iommu_napot_page_mask(ppn, addr, &base)) {
return MEMTX_ACCESS_ERROR;
}
} else {
base = PPN_PHYS(ppn) | (addr & ((1ULL << va_skip) - 1));
}
break;
}
+6 -1
View File
@@ -35,9 +35,11 @@
#include "hw/riscv/virt.h"
#include "hw/riscv/numa.h"
#include "hw/virtio/virtio-acpi.h"
#include "kvm/kvm_riscv.h"
#include "migration/vmstate.h"
#include "qapi/error.h"
#include "qemu/error-report.h"
#include "system/kvm.h"
#include "system/reset.h"
#define ACPI_BUILD_TABLE_SIZE 0x20000
@@ -296,7 +298,10 @@ static void build_rhct(GArray *table_data,
/* Time Base Frequency */
build_append_int_noprefix(table_data,
RISCV_ACLINT_DEFAULT_TIMEBASE_FREQ, 8);
kvm_enabled() ?
kvm_riscv_get_timebase_frequency(&s->soc->harts[0]) :
RISCV_ACLINT_DEFAULT_TIMEBASE_FREQ,
8);
/* ISA + N hart info */
num_rhct_nodes = 1 + ms->smp.cpus;
+11 -12
View File
@@ -77,12 +77,13 @@ static inline bool rtc_running(MC146818RtcState *s)
(s->cmos_data[RTC_REG_A] & 0x70) <= 0x20);
}
static uint64_t get_guest_rtc_ns(MC146818RtcState *s)
/*
* Note: get_rtc_ns_since_last_update() does not include the base_rtc seconds
* value. This does not matter if the caller only needs the nanoseconds part.
*/
static uint64_t get_rtc_ns_since_last_update(MC146818RtcState *s)
{
uint64_t guest_clock = qemu_clock_get_ns(rtc_clock);
return s->base_rtc * NANOSECONDS_PER_SECOND +
guest_clock - s->last_update + s->offset;
return qemu_clock_get_ns(rtc_clock) - s->last_update + s->offset;
}
static void rtc_coalesced_timer_update(MC146818RtcState *s)
@@ -258,7 +259,7 @@ static void check_update_timer(MC146818RtcState *s)
return;
}
guest_nsec = get_guest_rtc_ns(s) % NANOSECONDS_PER_SECOND;
guest_nsec = get_rtc_ns_since_last_update(s) % NANOSECONDS_PER_SECOND;
next_update_time = qemu_clock_get_ns(rtc_clock)
+ NANOSECONDS_PER_SECOND - guest_nsec;
@@ -510,7 +511,7 @@ static void cmos_ioport_write(void *opaque, hwaddr addr,
/* if disabling set mode, update the time */
if ((s->cmos_data[RTC_REG_B] & REG_B_SET) &&
(s->cmos_data[RTC_REG_A] & 0x70) <= 0x20) {
s->offset = get_guest_rtc_ns(s) % NANOSECONDS_PER_SECOND;
s->offset = get_rtc_ns_since_last_update(s) % NANOSECONDS_PER_SECOND;
rtc_set_time(s);
}
}
@@ -623,10 +624,8 @@ static void rtc_update_time(MC146818RtcState *s)
{
struct tm ret;
time_t guest_sec;
int64_t guest_nsec;
guest_nsec = get_guest_rtc_ns(s);
guest_sec = guest_nsec / NANOSECONDS_PER_SECOND;
guest_sec = s->base_rtc + get_rtc_ns_since_last_update(s) / NANOSECONDS_PER_SECOND;
gmtime_r(&guest_sec, &ret);
/* Is SET flag of Register B disabled? */
@@ -637,7 +636,7 @@ static void rtc_update_time(MC146818RtcState *s)
static int update_in_progress(MC146818RtcState *s)
{
int64_t guest_nsec;
uint64_t guest_nsec;
if (!rtc_running(s)) {
return 0;
@@ -652,7 +651,7 @@ static int update_in_progress(MC146818RtcState *s)
}
}
guest_nsec = get_guest_rtc_ns(s);
guest_nsec = get_rtc_ns_since_last_update(s);
/* UIP bit will be set at last 244us of every second. */
if ((guest_nsec % NANOSECONDS_PER_SECOND) >=
(NANOSECONDS_PER_SECOND - UIP_HOLD_LENGTH)) {
+1 -1
View File
@@ -1504,7 +1504,7 @@ static void s390_pci_device_reset(DeviceState *dev)
break;
}
if (pbdev->interp && (pbdev->fh & FH_MASK_ENABLE)) {
if (pbdev->interp) {
/* Interpreted devices were using interrupt forwarding */
s390_pci_kvm_aif_disable(pbdev);
} else if (pbdev->summary_ind) {
+53 -30
View File
@@ -197,6 +197,7 @@ typedef struct lsi_request {
uint8_t *dma_buf;
uint32_t pending;
int out;
bool orphan;
QTAILQ_ENTRY(lsi_request) next;
} lsi_request;
@@ -626,6 +627,8 @@ static void lsi_do_dma(LSIState *s, int out)
uint32_t count;
dma_addr_t addr;
SCSIDevice *dev;
SCSIRequest *req;
lsi_request *p;
if (!s->current || !s->current->dma_len) {
/* Wait until data is available. */
@@ -633,12 +636,14 @@ static void lsi_do_dma(LSIState *s, int out)
return;
}
dev = s->current->req->dev;
p = s->current;
req = scsi_req_ref(s->current->req);
dev = req->dev;
assert(dev);
count = s->dbc;
if (count > s->current->dma_len)
count = s->current->dma_len;
if (count > p->dma_len)
count = p->dma_len;
addr = s->dnad;
/* both 40 and Table Indirect 64-bit DMAs store upper bits in dnad64 */
@@ -653,21 +658,27 @@ static void lsi_do_dma(LSIState *s, int out)
s->csbc += count;
s->dnad += count;
s->dbc -= count;
if (s->current->dma_buf == NULL) {
s->current->dma_buf = scsi_req_get_buf(s->current->req);
if (p->dma_buf == NULL) {
p->dma_buf = scsi_req_get_buf(req);
}
/* ??? Set SFBR to first data byte. */
if (out) {
lsi_mem_read(s, addr, s->current->dma_buf, count);
lsi_mem_read(s, addr, p->dma_buf, count);
} else {
lsi_mem_write(s, addr, s->current->dma_buf, count);
lsi_mem_write(s, addr, p->dma_buf, count);
}
s->current->dma_len -= count;
if (s->current->dma_len == 0) {
s->current->dma_buf = NULL;
scsi_req_continue(s->current->req);
if (p->orphan) {
scsi_req_unref(req);
return;
}
scsi_req_unref(req);
p->dma_len -= count;
if (p->dma_len == 0) {
p->dma_buf = NULL;
scsi_req_continue(req);
} else {
s->current->dma_buf += count;
p->dma_buf += count;
lsi_resume_script(s);
}
}
@@ -743,14 +754,20 @@ static lsi_request *lsi_find_by_tag(LSIState *s, uint32_t tag)
return NULL;
}
static void lsi_request_free(LSIState *s, lsi_request *p)
static void lsi_request_orphan(LSIState *s, lsi_request *p)
{
p->orphan = true;
if (p == s->current) {
s->current = NULL;
} else {
QTAILQ_REMOVE(&s->queue, p, next);
}
g_free(p);
scsi_req_unref(p->req);
}
static void lsi_free_request(SCSIBus *bus, void *priv)
{
g_free(priv);
}
static void lsi_request_cancelled(SCSIRequest *req)
@@ -758,9 +775,7 @@ static void lsi_request_cancelled(SCSIRequest *req)
LSIState *s = LSI53C895A(req->bus->qbus.parent);
lsi_request *p = req->hba_private;
req->hba_private = NULL;
lsi_request_free(s, p);
scsi_req_unref(req);
lsi_request_orphan(s, p);
}
/* Record that data is available for a queued command. Returns zero if
@@ -812,9 +827,7 @@ static void lsi_command_complete(SCSIRequest *req, size_t resid)
}
if (req->hba_private == s->current) {
req->hba_private = NULL;
lsi_request_free(s, s->current);
scsi_req_unref(req);
lsi_request_orphan(s, s->current);
}
if (!stop) {
lsi_resume_script(s);
@@ -825,10 +838,11 @@ static void lsi_command_complete(SCSIRequest *req, size_t resid)
static void lsi_transfer_data(SCSIRequest *req, uint32_t len)
{
LSIState *s = LSI53C895A(req->bus->qbus.parent);
lsi_request *p = req->hba_private;
int out;
assert(req->hba_private);
if (s->waiting == LSI_WAIT_RESELECT || req->hba_private != s->current ||
assert(!p->orphan);
if (s->waiting == LSI_WAIT_RESELECT || p != s->current ||
(lsi_irq_on_rsl(s) && !(s->scntl1 & LSI_SCNTL1_CON))) {
if (lsi_queue_req(s, req, len)) {
return;
@@ -986,10 +1000,8 @@ static void lsi_do_msgout(LSIState *s)
if (s->current) {
current_tag = s->current->tag;
current_req = s->current;
} else {
current_tag = s->select_tag;
current_req = lsi_find_by_tag(s, current_tag);
}
trace_lsi_do_msgout(s->dbc);
@@ -1029,24 +1041,31 @@ static void lsi_do_msgout(LSIState *s)
}
break;
case 0x20: /* SIMPLE queue */
s->select_tag &= ~0xff;
s->select_tag |= lsi_get_msgbyte(s) | LSI_TAG_VALID;
trace_lsi_do_msgout_simplequeue(s->select_tag & 0xff);
break;
case 0x21: /* HEAD of queue */
qemu_log_mask(LOG_UNIMP, "lsi_scsi: HEAD queue not implemented\n");
s->select_tag &= ~0xff;
s->select_tag |= lsi_get_msgbyte(s) | LSI_TAG_VALID;
break;
case 0x22: /* ORDERED queue */
qemu_log_mask(LOG_UNIMP,
"lsi_scsi: ORDERED queue not implemented\n");
s->select_tag &= ~0xff;
s->select_tag |= lsi_get_msgbyte(s) | LSI_TAG_VALID;
break;
case 0x0d:
/* The ABORT TAG message clears the current I/O process only. */
trace_lsi_do_msgout_abort(current_tag);
if (s->current) {
current_req = s->current;
} else {
current_req = lsi_find_by_tag(s, current_tag);
}
if (current_req && current_req->req) {
scsi_req_cancel(current_req->req);
current_req = NULL;
}
lsi_disconnect(s);
break;
@@ -1072,7 +1091,6 @@ static void lsi_do_msgout(LSIState *s)
/* clear the current I/O process */
if (s->current) {
scsi_req_cancel(s->current->req);
current_req = NULL;
}
/* As the current implemented devices scsi_disk and scsi_generic
@@ -1163,6 +1181,7 @@ static void lsi_execute_script(LSIState *s)
s->waiting = LSI_NOWAIT;
}
object_ref(s);
reentrancy_level++;
s->istat1 |= LSI_ISTAT1_SRUN;
@@ -1182,6 +1201,7 @@ again:
s->waiting = LSI_WAIT_SCRIPTS;
lsi_scripts_timer_start(s);
reentrancy_level--;
object_unref(s);
return;
}
insn = read_dword(s, s->dsp);
@@ -1630,6 +1650,7 @@ again:
trace_lsi_execute_script_stop();
reentrancy_level--;
object_unref(s);
}
static uint8_t lsi_reg_readb(LSIState *s, int offset)
@@ -1946,6 +1967,10 @@ static void lsi_reg_writeb(LSIState *s, int offset, uint8_t val)
CASE_SET_REG32(dsa, 0x10)
case 0x14: /* ISTAT0 */
s->istat0 = (s->istat0 & 0x0f) | (val & 0xf0);
if (val & LSI_ISTAT0_SRST) {
device_cold_reset(DEVICE(s));
return;
}
if (val & LSI_ISTAT0_ABRT) {
lsi_script_dma_interrupt(s, LSI_DSTAT_ABRT);
}
@@ -1959,9 +1984,6 @@ static void lsi_reg_writeb(LSIState *s, int offset, uint8_t val)
s->dsp = s->dnad;
lsi_execute_script(s);
}
if (val & LSI_ISTAT0_SRST) {
device_cold_reset(DEVICE(s));
}
break;
case 0x16: /* MBOX0 */
s->mbox0 = val;
@@ -2316,7 +2338,8 @@ static const struct SCSIBusInfo lsi_scsi_info = {
.transfer_data = lsi_transfer_data,
.complete = lsi_command_complete,
.cancel = lsi_request_cancelled
.cancel = lsi_request_cancelled,
.free_request = lsi_free_request,
};
static void scripts_timer_cb(void *opaque)
+1 -6
View File
@@ -482,12 +482,7 @@ void scsi_bus_legacy_handle_cmdline(SCSIBus *bus)
Location loc;
DriveInfo *dinfo;
int unit;
BlockConf conf = {
.bootindex = -1,
.share_rw = false,
.rerror = BLOCKDEV_ON_ERROR_AUTO,
.werror = BLOCKDEV_ON_ERROR_AUTO,
};
BlockConf conf = DEFAULT_BLOCK_CONF;
loc_push_none(&loc);
for (unit = 0; unit <= bus->info->max_target; unit++) {
+15 -11
View File
@@ -227,16 +227,16 @@ static int virtio_scsi_parse_req(VirtIOSCSIReq *req,
return 0;
}
static VirtIOSCSIReq *virtio_scsi_pop_req(VirtIOSCSI *s, VirtQueue *vq, QemuMutex *vq_lock)
static VirtIOSCSIReq *virtio_scsi_pop_req(VirtIOSCSI *s, VirtQueue *vq, size_t extra_req_size,
QemuMutex *vq_lock)
{
VirtIOSCSICommon *vs = (VirtIOSCSICommon *)s;
VirtIOSCSIReq *req;
if (vq_lock) {
qemu_mutex_lock(vq_lock);
}
req = virtqueue_pop(vq, sizeof(VirtIOSCSIReq) + vs->cdb_size);
req = virtqueue_pop(vq, sizeof(VirtIOSCSIReq) + extra_req_size);
if (vq_lock) {
qemu_mutex_unlock(vq_lock);
@@ -682,7 +682,7 @@ static void virtio_scsi_handle_ctrl_vq(VirtIOSCSI *s, VirtQueue *vq)
{
VirtIOSCSIReq *req;
while ((req = virtio_scsi_pop_req(s, vq, &s->ctrl_lock))) {
while ((req = virtio_scsi_pop_req(s, vq, 0, &s->ctrl_lock))) {
virtio_scsi_handle_ctrl_req(s, req);
}
}
@@ -850,13 +850,14 @@ static void virtio_scsi_fail_cmd_req(VirtIOSCSIReq *req)
virtio_scsi_complete_cmd_req(req);
}
static int virtio_scsi_handle_cmd_req_prepare(VirtIOSCSI *s, VirtIOSCSIReq *req)
static int virtio_scsi_handle_cmd_req_prepare(VirtIOSCSI *s, VirtIOSCSIReq *req,
size_t cdb_size)
{
VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(s);
SCSIDevice *d;
int rc;
rc = virtio_scsi_parse_req(req, sizeof(VirtIOSCSICmdReq) + vs->cdb_size,
rc = virtio_scsi_parse_req(req, sizeof(VirtIOSCSICmdReq) + cdb_size,
sizeof(VirtIOSCSICmdResp) + vs->sense_size);
if (rc < 0) {
if (rc == -ENOTSUP) {
@@ -878,7 +879,7 @@ static int virtio_scsi_handle_cmd_req_prepare(VirtIOSCSI *s, VirtIOSCSIReq *req)
}
req->sreq = scsi_req_new(d, req->req.cmd.tag,
virtio_scsi_get_lun(req->req.cmd.lun),
req->req.cmd.cdb, vs->cdb_size, req);
req->req.cmd.cdb, cdb_size, req);
if (req->sreq->cmd.mode != SCSI_XFER_NONE
&& (req->sreq->cmd.mode != req->mode ||
@@ -913,12 +914,15 @@ static void virtio_scsi_handle_cmd_vq(VirtIOSCSI *s, VirtQueue *vq)
QTAILQ_HEAD(, VirtIOSCSIReq) reqs = QTAILQ_HEAD_INITIALIZER(reqs);
do {
VirtIOSCSICommon *vs = (VirtIOSCSICommon *)s;
size_t cdb_size = qatomic_read(&vs->cdb_size);
if (suppress_notifications) {
virtio_queue_set_notification(vq, 0);
}
while ((req = virtio_scsi_pop_req(s, vq, NULL))) {
ret = virtio_scsi_handle_cmd_req_prepare(s, req);
while ((req = virtio_scsi_pop_req(s, vq, cdb_size, NULL))) {
ret = virtio_scsi_handle_cmd_req_prepare(s, req, cdb_size);
if (!ret) {
QTAILQ_INSERT_TAIL(&reqs, req, next);
} else if (ret == -EINVAL) {
@@ -989,7 +993,7 @@ static void virtio_scsi_set_config(VirtIODevice *vdev,
}
vs->sense_size = virtio_ldl_p(vdev, &scsiconf->sense_size);
vs->cdb_size = virtio_ldl_p(vdev, &scsiconf->cdb_size);
qatomic_set(&vs->cdb_size, virtio_ldl_p(vdev, &scsiconf->cdb_size));
}
static uint64_t virtio_scsi_get_features(VirtIODevice *vdev,
@@ -1050,7 +1054,7 @@ static void virtio_scsi_push_event(VirtIOSCSI *s,
return;
}
req = virtio_scsi_pop_req(s, vs->event_vq, &s->event_lock);
req = virtio_scsi_pop_req(s, vs->event_vq, 0, &s->event_lock);
WITH_QEMU_LOCK_GUARD(&s->event_lock) {
if (!req) {
s->events_dropped = true;
-1
View File
@@ -687,7 +687,6 @@ static void sh7750_mmct_write(void *opaque, hwaddr addr,
break;
case MM_ITLB_DATA:
cpu_sh4_write_mmaped_itlb_data(&s->cpu->env, addr, mem_value);
abort();
break;
case MM_OCACHE_ADDR:
case MM_OCACHE_DATA:
+28 -21
View File
@@ -493,17 +493,18 @@ static void aspeed_smc_flash_setup(AspeedSMCFlash *fl, uint32_t addr)
}
}
static uint64_t aspeed_smc_flash_read(void *opaque, hwaddr addr, unsigned size)
static MemTxResult aspeed_smc_flash_read(void *opaque, hwaddr addr,
uint64_t *data, unsigned size, MemTxAttrs attrs)
{
AspeedSMCFlash *fl = opaque;
AspeedSMCState *s = fl->controller;
uint64_t ret = 0;
int i;
*data = 0;
switch (aspeed_smc_flash_mode(fl)) {
case CTRL_USERMODE:
for (i = 0; i < size; i++) {
ret |= (uint64_t) ssi_transfer(s->spi, 0x0) << (8 * i);
*data |= (uint64_t) ssi_transfer(s->spi, 0x0) << (8 * i);
}
break;
case CTRL_READMODE:
@@ -512,18 +513,19 @@ static uint64_t aspeed_smc_flash_read(void *opaque, hwaddr addr, unsigned size)
aspeed_smc_flash_setup(fl, addr);
for (i = 0; i < size; i++) {
ret |= (uint64_t) ssi_transfer(s->spi, 0x0) << (8 * i);
*data |= (uint64_t) ssi_transfer(s->spi, 0x0) << (8 * i);
}
aspeed_smc_flash_unselect(fl);
break;
default:
aspeed_smc_error("invalid flash mode %d", aspeed_smc_flash_mode(fl));
return MEMTX_ERROR;
}
trace_aspeed_smc_flash_read(fl->cs, addr, size, ret,
trace_aspeed_smc_flash_read(fl->cs, addr, size, *data,
aspeed_smc_flash_mode(fl));
return ret;
return MEMTX_OK;
}
/*
@@ -624,8 +626,8 @@ static bool aspeed_smc_do_snoop(AspeedSMCFlash *fl, uint64_t data,
return false;
}
static void aspeed_smc_flash_write(void *opaque, hwaddr addr, uint64_t data,
unsigned size)
static MemTxResult aspeed_smc_flash_write(void *opaque, hwaddr addr,
uint64_t data, unsigned size, MemTxAttrs attrs)
{
AspeedSMCFlash *fl = opaque;
AspeedSMCState *s = fl->controller;
@@ -636,7 +638,7 @@ static void aspeed_smc_flash_write(void *opaque, hwaddr addr, uint64_t data,
if (!aspeed_smc_is_writable(fl)) {
aspeed_smc_error("flash is not writable at 0x%" HWADDR_PRIx, addr);
return;
return MEMTX_ERROR;
}
switch (aspeed_smc_flash_mode(fl)) {
@@ -661,12 +663,15 @@ static void aspeed_smc_flash_write(void *opaque, hwaddr addr, uint64_t data,
break;
default:
aspeed_smc_error("invalid flash mode %d", aspeed_smc_flash_mode(fl));
return MEMTX_ERROR;
}
return MEMTX_OK;
}
static const MemoryRegionOps aspeed_smc_flash_ops = {
.read = aspeed_smc_flash_read,
.write = aspeed_smc_flash_write,
.read_with_attrs = aspeed_smc_flash_read,
.write_with_attrs = aspeed_smc_flash_write,
.endianness = DEVICE_LITTLE_ENDIAN,
.valid = {
.min_access_size = 1,
@@ -754,7 +759,8 @@ static void aspeed_smc_reset(DeviceState *d)
s->snoop_dummies = 0;
}
static uint64_t aspeed_smc_read(void *opaque, hwaddr addr, unsigned int size)
static MemTxResult aspeed_smc_read(void *opaque, hwaddr addr, uint64_t *data,
unsigned int size, MemTxAttrs attrs)
{
AspeedSMCState *s = ASPEED_SMC(opaque);
AspeedSMCClass *asc = ASPEED_SMC_GET_CLASS(opaque);
@@ -782,12 +788,13 @@ static uint64_t aspeed_smc_read(void *opaque, hwaddr addr, unsigned int size)
trace_aspeed_smc_read(addr << 2, size, s->regs[addr]);
return s->regs[addr];
*data = s->regs[addr];
} else {
qemu_log_mask(LOG_UNIMP, "%s: not implemented: 0x%" HWADDR_PRIx "\n",
__func__, addr);
return -1;
*data = -1;
}
return MEMTX_OK;
}
static uint8_t aspeed_smc_hclk_divisor(uint8_t hclk_mask)
@@ -1108,8 +1115,8 @@ static void aspeed_2600_smc_dma_ctrl(AspeedSMCState *s, uint32_t dma_ctrl)
s->regs[R_DMA_CTRL] &= ~(DMA_CTRL_REQUEST | DMA_CTRL_GRANT);
}
static void aspeed_smc_write(void *opaque, hwaddr addr, uint64_t data,
unsigned int size)
static MemTxResult aspeed_smc_write(void *opaque, hwaddr addr, uint64_t data,
unsigned int size, MemTxAttrs attrs)
{
AspeedSMCState *s = ASPEED_SMC(opaque);
AspeedSMCClass *asc = ASPEED_SMC_GET_CLASS(s);
@@ -1159,13 +1166,13 @@ static void aspeed_smc_write(void *opaque, hwaddr addr, uint64_t data,
} else {
qemu_log_mask(LOG_UNIMP, "%s: not implemented: 0x%" HWADDR_PRIx "\n",
__func__, addr);
return;
}
return MEMTX_OK;
}
static const MemoryRegionOps aspeed_smc_ops = {
.read = aspeed_smc_read,
.write = aspeed_smc_write,
.read_with_attrs = aspeed_smc_read,
.write_with_attrs = aspeed_smc_write,
.endianness = DEVICE_LITTLE_ENDIAN,
};
@@ -2007,8 +2014,8 @@ static const uint32_t aspeed_2700_fmc_resets[ASPEED_SMC_R_MAX] = {
};
static const MemoryRegionOps aspeed_2700_smc_flash_ops = {
.read = aspeed_smc_flash_read,
.write = aspeed_smc_flash_write,
.read_with_attrs = aspeed_smc_flash_read,
.write_with_attrs = aspeed_smc_flash_write,
.endianness = DEVICE_LITTLE_ENDIAN,
.valid = {
.min_access_size = 1,
+15 -9
View File
@@ -180,9 +180,10 @@ static efi_status uefi_vars_check_auth_2_sb(uefi_vars_state *uv,
void *data,
uint64_t data_offset)
{
variable_auth_2 *auth = data;
variable_auth_2 auth;
uefi_variable *siglist;
memcpy(&auth, data, sizeof(auth));
if (custom_mode_is_active(uv)) {
/* no authentication in custom mode */
return EFI_SUCCESS;
@@ -193,7 +194,7 @@ static efi_status uefi_vars_check_auth_2_sb(uefi_vars_state *uv,
return EFI_SUCCESS;
}
if (auth->hdr_length == 24) {
if (auth.hdr_length == (sizeof(auth) - sizeof(auth.timestamp))) {
/* no signature (auth->cert_data is empty) */
return EFI_SECURITY_VIOLATION;
}
@@ -218,23 +219,28 @@ static efi_status uefi_vars_check_auth_2_sb(uefi_vars_state *uv,
efi_status uefi_vars_check_auth_2(uefi_vars_state *uv, uefi_variable *var,
mm_variable_access *va, void *data)
{
variable_auth_2 *auth = data;
variable_auth_2 auth;
uint64_t data_offset;
efi_status status;
if (va->data_size < sizeof(*auth)) {
if (va->data_size < sizeof(auth)) {
return EFI_SECURITY_VIOLATION;
}
if (uadd64_overflow(sizeof(efi_time), auth->hdr_length, &data_offset)) {
memcpy(&auth, data, sizeof(auth));
if (auth.hdr_length < (sizeof(auth) - sizeof(auth.timestamp))) {
return EFI_SECURITY_VIOLATION;
}
if (uadd64_overflow(sizeof(efi_time), auth.hdr_length, &data_offset)) {
return EFI_SECURITY_VIOLATION;
}
if (va->data_size < data_offset) {
return EFI_SECURITY_VIOLATION;
}
if (auth->hdr_revision != 0x0200 ||
auth->hdr_cert_type != WIN_CERT_TYPE_EFI_GUID ||
!qemu_uuid_is_equal(&auth->guid_cert_type, &EfiCertTypePkcs7Guid)) {
if (auth.hdr_revision != 0x0200 ||
auth.hdr_cert_type != WIN_CERT_TYPE_EFI_GUID ||
!qemu_uuid_is_equal(&auth.guid_cert_type, &EfiCertTypePkcs7Guid)) {
return EFI_UNSUPPORTED;
}
@@ -255,7 +261,7 @@ efi_status uefi_vars_check_auth_2(uefi_vars_state *uv, uefi_variable *var,
}
/* checks passed, set variable data */
var->time = auth->timestamp;
var->time = auth.timestamp;
if (va->data_size - data_offset > 0) {
var->data = g_malloc(va->data_size - data_offset);
memcpy(var->data, data + data_offset, va->data_size - data_offset);
+6 -3
View File
@@ -133,9 +133,8 @@ static uint32_t uefi_vars_cmd_mm(uefi_vars_state *uv, bool dma_mode)
uv->buffer, sizeof(*mhdr) + mhdr->length,
MEMTXATTRS_UNSPECIFIED);
} else {
memcpy(uv->pio_xfer_buffer + sizeof(*mhdr),
uv->buffer + sizeof(*mhdr),
sizeof(*mhdr) + mhdr->length);
memcpy(uv->pio_xfer_buffer,
uv->buffer, sizeof(*mhdr) + mhdr->length);
}
return retval;
@@ -230,6 +229,10 @@ static uint64_t uefi_vars_read(void *opaque, hwaddr addr, unsigned size)
uv->pio_xfer_offset += size;
break;
case UEFI_VARS_REG_PIO_BUFFER_CRC32C:
if (uv->pio_xfer_offset > uv->buf_size) {
retval = 0;
break;
}
retval = crc32c(0xffffffff, uv->pio_xfer_buffer, uv->pio_xfer_offset);
break;
case UEFI_VARS_REG_FLAGS:
+1 -1
View File
@@ -98,7 +98,7 @@ static void parse_hexstr(void *dest, char *src, int len)
uint8_t *data = dest;
size_t i;
for (i = 0; i < len; i += 2) {
for (i = 0; i + 1 < len; i += 2) {
*(data++) =
parse_hexchar(src[i]) << 4 |
parse_hexchar(src[i + 1]);
+14 -9
View File
@@ -21,17 +21,20 @@
*/
static gnutls_datum_t *build_signed_data(mm_variable_access *va, void *data)
{
variable_auth_2 *auth = data;
uint64_t data_offset = sizeof(efi_time) + auth->hdr_length;
variable_auth_2 auth;
uint64_t data_offset;
uint16_t *name = (void *)va + sizeof(mm_variable_access);
gnutls_datum_t *sdata;
uint64_t pos = 0;
memcpy(&auth, data, sizeof(auth));
data_offset = sizeof(efi_time) + auth.hdr_length;
sdata = g_new(gnutls_datum_t, 1);
sdata->size = (va->name_size - 2
+ sizeof(QemuUUID)
+ sizeof(va->attributes)
+ sizeof(auth->timestamp)
+ sizeof(auth.timestamp)
+ va->data_size - data_offset);
sdata->data = g_malloc(sdata->size);
@@ -48,8 +51,8 @@ static gnutls_datum_t *build_signed_data(mm_variable_access *va, void *data)
pos += sizeof(va->attributes);
/* TimeStamp */
memcpy(sdata->data + pos, &auth->timestamp, sizeof(auth->timestamp));
pos += sizeof(auth->timestamp);
memcpy(sdata->data + pos, &auth.timestamp, sizeof(auth.timestamp));
pos += sizeof(auth.timestamp);
/* Variable Content */
memcpy(sdata->data + pos, data + data_offset, va->data_size - data_offset);
@@ -73,7 +76,8 @@ static void wrap_pkcs7(gnutls_datum_t *pkcs7)
};
gnutls_datum_t wrap;
if (pkcs7->data[4] == 0x06 &&
if (pkcs7->size > 16 &&
pkcs7->data[4] == 0x06 &&
pkcs7->data[5] == 0x09 &&
memcmp(pkcs7->data + 6, signed_data_oid, sizeof(signed_data_oid)) == 0 &&
pkcs7->data[15] == 0x0a &&
@@ -104,13 +108,14 @@ static void wrap_pkcs7(gnutls_datum_t *pkcs7)
static gnutls_datum_t *build_pkcs7(void *data)
{
variable_auth_2 *auth = data;
variable_auth_2 auth;
gnutls_datum_t *pkcs7;
memcpy(&auth, data, sizeof(auth));
pkcs7 = g_new(gnutls_datum_t, 1);
pkcs7->size = auth->hdr_length - 24;
pkcs7->size = auth.hdr_length - (sizeof(auth) - sizeof(auth.timestamp));
pkcs7->data = g_malloc(pkcs7->size);
memcpy(pkcs7->data, data + 16 + 24, pkcs7->size);
memcpy(pkcs7->data, data + sizeof(auth), pkcs7->size);
wrap_pkcs7(pkcs7);
+24 -18
View File
@@ -19,13 +19,18 @@
* sometimes when they are not (for example in variable policies).
*/
gboolean uefi_str_is_valid(const uint16_t *str, size_t len,
gboolean uefi_str_is_valid(const uint16_t *str, size_t bytes,
gboolean must_be_null_terminated)
{
size_t chars = bytes / 2;
size_t pos = 0;
if ((bytes % 2) != 0) {
return false;
}
for (;;) {
if (pos == len) {
if (pos == chars) {
if (must_be_null_terminated) {
return false;
} else {
@@ -47,12 +52,13 @@ gboolean uefi_str_is_valid(const uint16_t *str, size_t len,
}
}
size_t uefi_strlen(const uint16_t *str, size_t len)
size_t uefi_strlen(const uint16_t *str, size_t bytes)
{
size_t chars = bytes / 2;
size_t pos = 0;
for (;;) {
if (pos == len) {
if (pos == chars) {
return pos;
}
if (str[pos] == 0) {
@@ -62,25 +68,25 @@ size_t uefi_strlen(const uint16_t *str, size_t len)
}
}
gboolean uefi_str_equal_ex(const uint16_t *a, size_t alen,
const uint16_t *b, size_t blen,
gboolean uefi_str_equal_ex(const uint16_t *a, size_t a_bytes,
const uint16_t *b, size_t b_bytes,
gboolean wildcards_in_a)
{
size_t a_chars = a_bytes / 2;
size_t b_chars = b_bytes / 2;
size_t pos = 0;
alen = alen / 2;
blen = blen / 2;
for (;;) {
if (pos == alen && pos == blen) {
if (pos == a_chars && pos == b_chars) {
return true;
}
if (pos == alen && b[pos] == 0) {
if (pos == a_chars && b[pos] == 0) {
return true;
}
if (pos == blen && a[pos] == 0) {
if (pos == b_chars && a[pos] == 0) {
return true;
}
if (pos == alen || pos == blen) {
if (pos == a_chars || pos == b_chars) {
return false;
}
if (a[pos] == 0 && b[pos] == 0) {
@@ -100,18 +106,18 @@ gboolean uefi_str_equal_ex(const uint16_t *a, size_t alen,
}
}
gboolean uefi_str_equal(const uint16_t *a, size_t alen,
const uint16_t *b, size_t blen)
gboolean uefi_str_equal(const uint16_t *a, size_t a_bytes,
const uint16_t *b, size_t b_bytes)
{
return uefi_str_equal_ex(a, alen, b, blen, false);
return uefi_str_equal_ex(a, a_bytes, b, b_bytes, false);
}
char *uefi_ucs2_to_ascii(const uint16_t *ucs2, uint64_t ucs2_size)
char *uefi_ucs2_to_ascii(const uint16_t *ucs2, uint64_t ucs2_bytes)
{
char *str = g_malloc0(ucs2_size / 2 + 1);
char *str = g_malloc0(ucs2_bytes / 2 + 1);
int i;
for (i = 0; i * 2 < ucs2_size; i++) {
for (i = 0; i * 2 < ucs2_bytes; i++) {
if (ucs2[i] == 0) {
break;
}
+18 -4
View File
@@ -260,6 +260,17 @@ static size_t uefi_vars_mm_error(mm_header *mhdr, mm_variable *mvar,
return sizeof(*mvar);
}
static bool check_buffer_size(uefi_vars_state *uv, uint64_t length)
{
/* uefi_vars_cmd_mm() checks that */
g_assert(uv->buf_size >= sizeof(mm_header));
if (uv->buf_size - sizeof(mm_header) < length) {
return false;
}
return true;
}
static size_t uefi_vars_mm_get_variable(uefi_vars_state *uv, mm_header *mhdr,
mm_variable *mvar, void *func)
{
@@ -307,7 +318,7 @@ static size_t uefi_vars_mm_get_variable(uefi_vars_state *uv, mm_header *mhdr,
if (uadd64_overflow(length, va->data_size, &length)) {
return uefi_vars_mm_error(mhdr, mvar, EFI_BAD_BUFFER_SIZE);
}
if (uv->buf_size < length) {
if (!check_buffer_size(uv, length)) {
return uefi_vars_mm_error(mhdr, mvar, EFI_BAD_BUFFER_SIZE);
}
@@ -377,7 +388,7 @@ uefi_vars_mm_get_next_variable(uefi_vars_state *uv, mm_header *mhdr,
}
length = sizeof(*mvar) + sizeof(*nv) + var->name_size;
if (uv->buf_size < length) {
if (!check_buffer_size(uv, length)) {
return uefi_vars_mm_error(mhdr, mvar, EFI_BAD_BUFFER_SIZE);
}
@@ -567,7 +578,7 @@ static size_t uefi_vars_mm_variable_info(uefi_vars_state *uv, mm_header *mhdr,
uint64_t length;
length = sizeof(*mvar) + sizeof(*vi);
if (uv->buf_size < length) {
if (!check_buffer_size(uv, length)) {
return uefi_vars_mm_error(mhdr, mvar, EFI_BAD_BUFFER_SIZE);
}
@@ -588,7 +599,7 @@ uefi_vars_mm_get_payload_size(uefi_vars_state *uv, mm_header *mhdr,
uint64_t length;
length = sizeof(*mvar) + sizeof(*ps);
if (uv->buf_size < length) {
if (!check_buffer_size(uv, length)) {
return uefi_vars_mm_error(mhdr, mvar, EFI_BAD_BUFFER_SIZE);
}
@@ -618,6 +629,9 @@ uefi_vars_mm_lock_variable(uefi_vars_state *uv, mm_header *mhdr,
if (mhdr->length < length) {
return uefi_vars_mm_error(mhdr, mvar, EFI_BAD_BUFFER_SIZE);
}
if (sizeof(*pe) + lv->name_size > UINT16_MAX) {
return uefi_vars_mm_error(mhdr, mvar, EFI_BAD_BUFFER_SIZE);
}
uefi_trace_variable(__func__, lv->guid, name, lv->name_size);
+4
View File
@@ -101,6 +101,10 @@ static int ufs_emulate_report_luns(UfsRequest *req, uint8_t *outbuf,
return SCSI_COMMAND_FAIL;
}
if (outbuf_len < 8) {
return SCSI_COMMAND_FAIL;
}
memset(outbuf, 0, 8);
len += 8;
for (uint8_t lun = 0; lun < UFS_MAX_LUS; ++lun) {
+3
View File
@@ -40,10 +40,13 @@ ufs_err_mcq_db_wr_invalid_sqid(uint8_t qid) "invalid mcq sqid %"PRIu8""
ufs_err_mcq_db_wr_invalid_db(uint8_t qid, uint32_t db) "invalid mcq doorbell sqid %"PRIu8", db %"PRIu32""
ufs_err_mcq_create_sq_invalid_sqid(uint8_t qid) "invalid mcq sqid %"PRIu8""
ufs_err_mcq_create_sq_invalid_cqid(uint8_t qid) "invalid mcq cqid %"PRIu8""
ufs_err_mcq_create_sq_invalid_size(uint8_t qid) "invalid mcq sq size for sqid %"PRIu8""
ufs_err_mcq_create_sq_already_exists(uint8_t qid) "mcq sqid %"PRIu8 "already exists"
ufs_err_mcq_delete_sq_invalid_sqid(uint8_t qid) "invalid mcq sqid %"PRIu8""
ufs_err_mcq_delete_sq_not_exists(uint8_t qid) "mcq sqid %"PRIu8 "not exists"
ufs_err_mcq_delete_sq_busy(uint8_t qid) "mcq sqid %"PRIu8" has outstanding requests"
ufs_err_mcq_create_cq_invalid_cqid(uint8_t qid) "invalid mcq cqid %"PRIu8""
ufs_err_mcq_create_cq_invalid_size(uint8_t qid) "invalid mcq cq size for cqid %"PRIu8""
ufs_err_mcq_create_cq_already_exists(uint8_t qid) "mcq cqid %"PRIu8 "already exists"
ufs_err_mcq_delete_cq_invalid_cqid(uint8_t qid) "invalid mcq cqid %"PRIu8""
ufs_err_mcq_delete_cq_not_exists(uint8_t qid) "mcq cqid %"PRIu8 "not exists"
+81 -11
View File
@@ -506,6 +506,8 @@ static bool ufs_mcq_create_sq(UfsHc *u, uint8_t qid, uint32_t attr)
UfsMcqReg *reg = &u->mcq_reg[qid];
UfsSq *sq;
uint8_t cqid = FIELD_EX32(attr, SQATTR, CQID);
uint16_t qsize =
((FIELD_EX32(attr, SQATTR, SIZE) + 1) << 2) / sizeof(UfsSqEntry);
if (qid >= u->params.mcq_maxq) {
trace_ufs_err_mcq_create_sq_invalid_sqid(qid);
@@ -517,8 +519,18 @@ static bool ufs_mcq_create_sq(UfsHc *u, uint8_t qid, uint32_t attr)
return false;
}
if (cqid >= u->params.mcq_maxq) {
trace_ufs_err_mcq_create_sq_invalid_cqid(cqid);
return false;
}
if (!u->cq[cqid]) {
trace_ufs_err_mcq_create_sq_invalid_cqid(qid);
trace_ufs_err_mcq_create_sq_invalid_cqid(cqid);
return false;
}
if (!qsize) {
trace_ufs_err_mcq_create_sq_invalid_size(qid);
return false;
}
@@ -527,7 +539,7 @@ static bool ufs_mcq_create_sq(UfsHc *u, uint8_t qid, uint32_t attr)
sq->sqid = qid;
sq->cq = u->cq[cqid];
sq->addr = ((uint64_t)reg->squba << 32) | reg->sqlba;
sq->size = ((FIELD_EX32(attr, SQATTR, SIZE) + 1) << 2) / sizeof(UfsSqEntry);
sq->size = qsize;
sq->bh = qemu_bh_new_guarded(ufs_mcq_process_sq, sq,
&DEVICE(u)->mem_reentrancy_guard);
@@ -544,6 +556,31 @@ static bool ufs_mcq_create_sq(UfsHc *u, uint8_t qid, uint32_t attr)
return true;
}
static bool ufs_mcq_sq_has_outstanding_req(UfsSq *sq)
{
UfsRequest *req;
uint16_t free_reqs = 0;
QTAILQ_FOREACH(req, &sq->req_list, entry)
{
free_reqs++;
}
return free_reqs != sq->size;
}
static void ufs_mcq_free_sq(UfsSq *sq)
{
qemu_bh_delete(sq->bh);
for (int i = 0; i < sq->size; i++) {
ufs_clear_req(&sq->req[i]);
}
g_free(sq->req);
g_free(sq);
}
static bool ufs_mcq_delete_sq(UfsHc *u, uint8_t qid)
{
UfsSq *sq;
@@ -560,9 +597,12 @@ static bool ufs_mcq_delete_sq(UfsHc *u, uint8_t qid)
sq = u->sq[qid];
qemu_bh_delete(sq->bh);
g_free(sq->req);
g_free(sq);
if (ufs_mcq_sq_has_outstanding_req(sq)) {
trace_ufs_err_mcq_delete_sq_busy(qid);
return false;
}
ufs_mcq_free_sq(sq);
u->sq[qid] = NULL;
return true;
}
@@ -571,6 +611,8 @@ static bool ufs_mcq_create_cq(UfsHc *u, uint8_t qid, uint32_t attr)
{
UfsMcqReg *reg = &u->mcq_reg[qid];
UfsCq *cq;
uint16_t qsize =
((FIELD_EX32(attr, CQATTR, SIZE) + 1) << 2) / sizeof(UfsCqEntry);
if (qid >= u->params.mcq_maxq) {
trace_ufs_err_mcq_create_cq_invalid_cqid(qid);
@@ -582,11 +624,16 @@ static bool ufs_mcq_create_cq(UfsHc *u, uint8_t qid, uint32_t attr)
return false;
}
if (!qsize) {
trace_ufs_err_mcq_create_cq_invalid_size(qid);
return false;
}
cq = g_malloc0(sizeof(*cq));
cq->u = u;
cq->cqid = qid;
cq->addr = ((uint64_t)reg->cquba << 32) | reg->cqlba;
cq->size = ((FIELD_EX32(attr, CQATTR, SIZE) + 1) << 2) / sizeof(UfsCqEntry);
cq->size = qsize;
cq->bh = qemu_bh_new_guarded(ufs_mcq_process_cq, cq,
&DEVICE(u)->mem_reentrancy_guard);
@@ -598,6 +645,12 @@ static bool ufs_mcq_create_cq(UfsHc *u, uint8_t qid, uint32_t attr)
return true;
}
static void ufs_mcq_free_cq(UfsCq *cq)
{
qemu_bh_delete(cq->bh);
g_free(cq);
}
static bool ufs_mcq_delete_cq(UfsHc *u, uint8_t qid)
{
UfsCq *cq;
@@ -621,8 +674,7 @@ static bool ufs_mcq_delete_cq(UfsHc *u, uint8_t qid)
cq = u->cq[qid];
qemu_bh_delete(cq->bh);
g_free(cq);
ufs_mcq_free_cq(cq);
u->cq[qid] = NULL;
return true;
}
@@ -775,6 +827,11 @@ static void ufs_mcq_process_db(UfsHc *u, uint8_t qid, uint32_t db)
}
sq = u->sq[qid];
if (!sq) {
trace_ufs_err_mcq_db_wr_invalid_sqid(qid);
return;
}
if (sq->size * sizeof(UfsSqEntry) <= db) {
trace_ufs_err_mcq_db_wr_invalid_db(qid, db);
return;
@@ -788,7 +845,14 @@ static void ufs_write_mcq_op_reg(UfsHc *u, hwaddr offset, uint32_t data,
unsigned size)
{
int qid = offset / sizeof(UfsMcqOpReg);
UfsMcqOpReg *opr = &u->mcq_op_reg[qid];
UfsMcqOpReg *opr;
if (qid >= u->params.mcq_maxq) {
trace_ufs_err_invalid_register_offset(offset);
return;
}
opr = &u->mcq_op_reg[qid];
switch (offset % sizeof(UfsMcqOpReg)) {
case offsetof(UfsMcqOpReg, sq.tp):
@@ -800,6 +864,10 @@ static void ufs_write_mcq_op_reg(UfsHc *u, hwaddr offset, uint32_t data,
case offsetof(UfsMcqOpReg, cq.hp): {
UfsCq *cq = u->cq[qid];
if (!cq) {
break;
}
if (ufs_mcq_cq_full(u, qid) && !QTAILQ_EMPTY(&cq->req_list)) {
/* Enqueueing to CQ was blocked because it was full */
qemu_bh_schedule(cq->bh);
@@ -1849,12 +1917,14 @@ static void ufs_exit(PCIDevice *pci_dev)
for (int i = 0; i < ARRAY_SIZE(u->sq); i++) {
if (u->sq[i]) {
ufs_mcq_delete_sq(u, i);
ufs_mcq_free_sq(u->sq[i]);
u->sq[i] = NULL;
}
}
for (int i = 0; i < ARRAY_SIZE(u->cq); i++) {
if (u->cq[i]) {
ufs_mcq_delete_cq(u, i);
ufs_mcq_free_cq(u->cq[i]);
u->cq[i] = NULL;
}
}
}
+8 -1
View File
@@ -203,7 +203,14 @@ static inline bool ufs_mcq_cq_empty(UfsHc *u, uint32_t qid)
static inline bool ufs_mcq_cq_full(UfsHc *u, uint32_t qid)
{
uint32_t tail = ufs_mcq_cq_tail(u, qid);
uint16_t cq_size = u->cq[qid]->size;
UfsCq *cq = u->cq[qid];
uint16_t cq_size;
if (!cq) {
return false;
}
cq_size = cq->size;
tail = (tail + sizeof(UfsCqEntry)) % (sizeof(UfsCqEntry) * cq_size);
return tail == ufs_mcq_cq_head(u, qid);
+12
View File
@@ -756,6 +756,7 @@ static int ohci_service_iso_td(OHCIState *ohci, struct ohci_ed *ed)
} else {
ret = pkt->status;
}
usb_packet_cleanup(pkt);
g_free(pkt);
trace_usb_ohci_iso_td_so(start_offset, end_offset, start_addr, end_addr,
@@ -956,6 +957,17 @@ static int ohci_service_td(OHCIState *ohci, struct ohci_ed *ed)
if (len && dir != OHCI_TD_DIR_IN) {
/* The endpoint may not allow us to transfer it all now */
pktlen = (ed->flags & OHCI_ED_MPS_MASK) >> OHCI_ED_MPS_SHIFT;
/*
* The OHCI spec does not say what to do if the guest hands us
* an endpoint descriptor which specifies a MaximumPacketSize
* of zero, which would mean we can never actually make forward
* progress transferring data to it. We choose to treat it as
* an error.
*/
if (pktlen == 0) {
ohci_die(ohci);
return 1;
}
if (pktlen > len) {
pktlen = len;
}
+31 -3
View File
@@ -74,15 +74,43 @@ void vfio_address_space_insert(VFIOAddressSpace *space,
bcontainer->space = space;
}
static bool vfio_container_can_dma_map_file(VFIOContainer *bcontainer,
MemoryRegion *mr, int *fd)
{
VFIOIOMMUClass *vioc = VFIO_IOMMU_GET_CLASS(bcontainer);
RAMBlock *rb = mr->ram_block;
if (!vioc->dma_map_file || !rb) {
return false;
}
*fd = qemu_ram_get_fd(rb);
if (*fd < 0) {
return false;
}
/*
* We can use IOMMU DMA mapping (IOMMU_IOAS_MAP_FILE) for :
*
* 1) Guest RAM blocks explicitly configured as shared (MAP_SHARED)
* 2) RAM device sub-regions (MMIO BARs)
*
* Private RAM mappings (MAP_PRIVATE) are strictly excluded. Because
* they are subject to copy-on-write (COW) anomalies, their underlying
* PFNs can permanently diverge from the backing file
*/
return qemu_ram_is_shared(rb) || memory_region_is_ram_device(mr);
}
int vfio_container_dma_map(VFIOContainer *bcontainer,
hwaddr iova, uint64_t size,
void *vaddr, bool readonly, MemoryRegion *mr)
{
VFIOIOMMUClass *vioc = VFIO_IOMMU_GET_CLASS(bcontainer);
RAMBlock *rb = mr->ram_block;
int mfd = rb ? qemu_ram_get_fd(rb) : -1;
int mfd;
if (mfd >= 0 && vioc->dma_map_file) {
if (vfio_container_can_dma_map_file(bcontainer, mr, &mfd)) {
RAMBlock *rb = mr->ram_block;
unsigned long start = vaddr - qemu_ram_get_host_addr(rb);
unsigned long offset = qemu_ram_get_fd_offset(rb);
+1 -1
View File
@@ -963,7 +963,7 @@ static void virtqueue_ordered_fill(VirtQueue *vq, const VirtQueueElement *elem,
* We shouldn't need to increase 'i' by more than or equal to
* the distance between used_idx and last_avail_idx (max_steps).
*/
max_steps = (vq->last_avail_idx - vq->used_idx) % vq->vring.num;
max_steps = MIN(vq->last_avail_idx - vq->used_idx, vq->vring.num);
/* Search for element in vq->used_elems */
while (steps < max_steps) {
-4
View File
@@ -71,10 +71,6 @@
#include "accel/tcg/cpu-mmu-index.h"
#include "exec/abi_ptr.h"
#if defined(CONFIG_USER_ONLY)
#include "user/guest-host.h"
#endif /* CONFIG_USER_ONLY */
static inline uint32_t
cpu_ldub_mmuidx_ra(CPUArchState *env, abi_ptr addr, int mmu_idx, uintptr_t ra)
{
+10 -1
View File
@@ -215,8 +215,17 @@ typedef enum {
*/
BDRV_REQ_NO_WAIT = 0x400,
/*
* Used between blk_co_start_request() and blk_end_request() to avoid
* that the request waits in a drained BlockBackend until the drained
* section ends. Waiting would cause a deadlock because drain waits for
* blk_end_request() to be called, but the request never completes
* because it waits for the drain to end.
*/
BDRV_REQ_NO_QUEUE = 0x800,
/* Mask of valid flags */
BDRV_REQ_MASK = 0x7ff,
BDRV_REQ_MASK = 0xfff,
} BdrvRequestFlags;
#define BDRV_O_NO_SHARE 0x0001 /* don't share permissions */
+12
View File
@@ -51,6 +51,18 @@ static inline unsigned int get_physical_block_exp(BlockConf *conf)
return exp;
}
#define DEFAULT_BLOCK_CONF (BlockConf) { \
.bootindex = -1, \
.backend_defaults = ON_OFF_AUTO_AUTO, \
.discard_granularity = -1, \
.wce = ON_OFF_AUTO_AUTO, \
.share_rw = false, \
.account_invalid = ON_OFF_AUTO_AUTO, \
.account_failed = ON_OFF_AUTO_AUTO, \
.rerror = BLOCKDEV_ON_ERROR_AUTO, \
.werror = BLOCKDEV_ON_ERROR_AUTO, \
}
#define DEFINE_BLOCK_PROPERTIES_BASE(_state, _conf) \
DEFINE_PROP_ON_OFF_AUTO("backend_defaults", _state, \
_conf.backend_defaults, ON_OFF_AUTO_AUTO), \
+2
View File
@@ -51,6 +51,8 @@ enum {
#define SIFIVE_UART_TXFIFO_FULL 0x80000000
#define SIFIVE_UART_TXEN(txctrl) (txctrl & 0x1)
#define SIFIVE_UART_RXEN(rxctrl) (rxctrl & 0x1)
#define SIFIVE_UART_GET_TXCNT(txctrl) ((txctrl >> 16) & 0x7)
#define SIFIVE_UART_GET_RXCNT(rxctrl) ((rxctrl >> 16) & 0x7)
+2
View File
@@ -111,6 +111,8 @@ struct PnvMachineState {
bool big_core;
bool lpar_per_core;
Notifier machine_init_done;
};
PnvChip *pnv_get_chip(PnvMachineState *pnv, uint32_t chip_id);
+4 -2
View File
@@ -71,6 +71,8 @@ BlockAIOCB *blk_aio_ioctl(BlockBackend *blk, unsigned long int req, void *buf,
void blk_inc_in_flight(BlockBackend *blk);
void blk_dec_in_flight(BlockBackend *blk);
void coroutine_fn blk_co_start_request(BlockBackend *blk);
void blk_end_request(BlockBackend *blk);
bool coroutine_fn GRAPH_RDLOCK blk_co_is_inserted(BlockBackend *blk);
bool co_wrapper_mixed_bdrv_rdlock blk_is_inserted(BlockBackend *blk);
@@ -216,9 +218,9 @@ int co_wrapper_mixed blk_zone_append(BlockBackend *blk, int64_t *offset,
BdrvRequestFlags flags);
int co_wrapper_mixed blk_pdiscard(BlockBackend *blk, int64_t offset,
int64_t bytes);
int64_t bytes, BdrvRequestFlags flags);
int coroutine_fn blk_co_pdiscard(BlockBackend *blk, int64_t offset,
int64_t bytes);
int64_t bytes, BdrvRequestFlags flags);
int co_wrapper_mixed blk_flush(BlockBackend *blk);
int coroutine_fn blk_co_flush(BlockBackend *blk);
+56 -6
View File
@@ -29,7 +29,12 @@ extern unsigned long reserved_va;
*/
extern unsigned long guest_addr_max;
static inline vaddr cpu_untagged_addr(CPUState *cs, vaddr x)
/*
* These functions take the guest virtual address as a vaddr,
* and are suitable for use from target-independent code.
*/
static inline vaddr cpu_untagged_addr_vaddr(CPUState *cs, vaddr x)
{
const TCGCPUOps *tcg_ops = cs->cc->tcg_ops;
if (tcg_ops->untagged_addr) {
@@ -39,22 +44,22 @@ static inline vaddr cpu_untagged_addr(CPUState *cs, vaddr x)
}
/* All direct uses of g2h and h2g need to go away for usermode softmmu. */
static inline void *g2h_untagged(vaddr x)
static inline void *g2h_untagged_vaddr(vaddr x)
{
return (void *)((uintptr_t)(x) + guest_base);
}
static inline void *g2h(CPUState *cs, vaddr x)
static inline void *g2h_vaddr(CPUState *cs, vaddr x)
{
return g2h_untagged(cpu_untagged_addr(cs, x));
return g2h_untagged_vaddr(cpu_untagged_addr_vaddr(cs, x));
}
static inline bool guest_addr_valid_untagged(vaddr x)
static inline bool guest_addr_valid_untagged_vaddr(vaddr x)
{
return x <= guest_addr_max;
}
static inline bool guest_range_valid_untagged(vaddr start, vaddr len)
static inline bool guest_range_valid_untagged_vaddr(vaddr start, vaddr len)
{
return len - 1 <= guest_addr_max && start <= guest_addr_max - len + 1;
}
@@ -73,4 +78,49 @@ static inline bool guest_range_valid_untagged(vaddr start, vaddr len)
h2g_nocheck(x); \
})
#ifdef COMPILING_PER_TARGET
/*
* These functions take the guest virtual address as an abi_ptr. This
* is an important difference from a vaddr for the common case where
* the address is a syscall argument in a variable of type abi_long,
* which may be smaller than the vaddr type. If you pass an address in
* an abi_long to these functions then the value will be converted to
* an unsigned type and then zero extended to give the vaddr. If you
* use the g2h_vaddr() and similar functions which take an argument of
* type vaddr, then the value will be sign-extended, giving the wrong
* answer for addresses above the 2GB mark on 32-bit guests.
*
* Providing these functions with their traditional QEMU semantics is
* less bug-prone than requiring many callsites to remember to cast
* their abi_long variable to an abi_ptr before calling.
*/
static inline void *g2h(CPUState *cs, abi_ptr x)
{
return g2h_vaddr(cs, x);
}
static inline void *g2h_untagged(abi_ptr x)
{
return g2h_untagged_vaddr(x);
}
static inline bool guest_addr_valid_untagged(abi_ptr x)
{
return guest_addr_valid_untagged_vaddr(x);
}
static inline bool guest_range_valid_untagged(abi_ptr start, abi_ptr len)
{
return guest_range_valid_untagged_vaddr(start, len);
}
static inline abi_ptr cpu_untagged_addr(CPUState *cs, abi_ptr x)
{
return cpu_untagged_addr_vaddr(cs, x);
}
#endif
#endif
+3 -1
View File
@@ -352,7 +352,9 @@ void qio_channel_tls_bye(QIOChannelTLS *ioc, Error **errp)
task = qio_task_new(OBJECT(ioc), propagate_error, errp, NULL);
trace_qio_channel_tls_bye_start(ioc);
qio_channel_tls_bye_task(ioc, task, NULL);
if (qio_channel_tls_bye_task(ioc, task, NULL)) {
qio_task_free(task);
}
}
static void qio_channel_tls_init(Object *obj G_GNUC_UNUSED)
+7
View File
@@ -75,6 +75,13 @@
/* Instruct lower device to use last 4-bytes of skb data as FCS */
#define TARGET_SO_NOFCS 43
#define TARGET_SO_TIMESTAMP_NEW 63
#define TARGET_SO_TIMESTAMPNS_NEW 64
#define TARGET_SO_TIMESTAMPING_NEW 65
#define TARGET_SO_RCVTIMEO_NEW 66
#define TARGET_SO_SNDTIMEO_NEW 67
/* TARGET_O_NONBLOCK clashes with the bits used for socket types. Therefore we
* have to define SOCK_NONBLOCK to a different value here.
*/
Loaded 100 of 211 files, more files were not shown because too many files have changed in this diff. Show more