Compare commits

...
95 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
91 changed files with 1993 additions and 336 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.3
10.2.4
+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;
+22
View File
@@ -36,6 +36,19 @@
/* Maximum number of requests in a batch. (default value) */
#define DEFAULT_MAX_BATCH 32
/*
* Bound on how deep ioq_submit() may recurse on a single LaioQueue via the
* ioq_submit -> qemu_laio_process_completions -> defer_call_end ->
* laio_deferred_fn -> ioq_submit cycle. The cycle terminates naturally
* when io_submit(2) returns asynchronously (O_DIRECT), but can grow
* without bound when submissions complete synchronously. On overflow
* the caller returns without submitting; the outermost
* qemu_laio_process_completions() has already scheduled s->completion_bh
* (via qemu_bh_schedule() at the top of that function), which resumes
* submission from the next event-loop dispatch.
*/
#define IOQ_SUBMIT_MAX_DEPTH 8
struct qemu_laiocb {
Coroutine *co;
LinuxAioState *ctx;
@@ -61,6 +74,7 @@ typedef struct {
unsigned int in_queue;
unsigned int in_flight;
bool blocked;
unsigned int submit_depth;
QSIMPLEQ_HEAD(, qemu_laiocb) pending;
} LaioQueue;
@@ -331,6 +345,7 @@ static void ioq_init(LaioQueue *io_q)
io_q->in_queue = 0;
io_q->in_flight = 0;
io_q->blocked = false;
io_q->submit_depth = 0;
}
static void ioq_submit(LinuxAioState *s)
@@ -340,6 +355,11 @@ static void ioq_submit(LinuxAioState *s)
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;
@@ -385,6 +405,8 @@ static void ioq_submit(LinuxAioState *s)
* pended requests will be submitted from there.
*/
}
s->io_q.submit_depth--;
}
static uint64_t laio_max_batch(LinuxAioState *s, uint64_t dev_max_batch)
+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);
+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
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 -1
View File
@@ -199,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;
+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)
+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)
+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;
}
+10 -6
View File
@@ -99,13 +99,13 @@ typedef struct of_dpa_flow_key {
} nd;
} ipv6;
};
int width; /* how many uint64_t's in key? */
int width; /* how many uint32_t's in key? */
} OfDpaFlowKey;
/* Width of key which includes field 'f' in u64s, rounded up */
/* Width of key which includes field 'f' in u32s, rounded up */
#define FLOW_KEY_WIDTH(f) \
DIV_ROUND_UP(offsetof(OfDpaFlowKey, f) + sizeof_field(OfDpaFlowKey, f), \
sizeof(uint64_t))
sizeof(uint32_t))
typedef struct of_dpa_flow_action {
uint32_t goto_tbl;
@@ -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]);
}
+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.
*/
+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;
}
+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) {
+8 -4
View File
@@ -1000,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);
@@ -1043,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;
@@ -1086,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
+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]);
+1
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,
+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) {
+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)
+20 -1
View File
@@ -699,7 +699,7 @@ static abi_ulong create_elf_tables(abi_ulong p, int argc, int envc,
/* There must be exactly DLINFO_ITEMS entries here, or the assert
* on info->auxv_len will trigger.
*/
NEW_AUX_ENT(AT_PHDR, (abi_ulong)(info->load_addr + exec->e_phoff));
NEW_AUX_ENT(AT_PHDR, (abi_ulong)(info->phdr_addr));
NEW_AUX_ENT(AT_PHENT, (abi_ulong)(sizeof (struct elf_phdr)));
NEW_AUX_ENT(AT_PHNUM, (abi_ulong)(exec->e_phnum));
NEW_AUX_ENT(AT_PAGESZ, (abi_ulong)(TARGET_PAGE_SIZE));
@@ -1469,6 +1469,12 @@ static void load_elf_image(const char *image_name, const ImageSource *src,
info->data_offset = load_bias;
info->load_addr = load_addr;
info->entry = ehdr->e_entry + load_bias;
/*
* Fallback for AT_PHDR if the program headers do not fall within
* any PT_LOAD segment (see the loop below, which overrides this with
* the correct in-memory address when a containing segment is found).
*/
info->phdr_addr = load_addr + ehdr->e_phoff;
info->start_code = -1;
info->end_code = 0;
info->start_data = -1;
@@ -1523,6 +1529,19 @@ static void load_elf_image(const char *image_name, const ImageSource *src,
vaddr_ef = vaddr + eppnt->p_filesz;
vaddr_em = vaddr + eppnt->p_memsz;
/*
* If this segment contains the program headers, record their
* in-memory address for AT_PHDR. This matches the kernel, which
* locates the headers via the containing PT_LOAD rather than
* assuming load_addr + e_phoff (false when the phdrs are not
* mapped 1:1 from file offset 0, e.g. relocated into their own
* segment by a binary patcher).
*/
if (eppnt->p_offset <= ehdr->e_phoff &&
ehdr->e_phoff < eppnt->p_offset + eppnt->p_filesz) {
info->phdr_addr = vaddr + (ehdr->e_phoff - eppnt->p_offset);
}
/*
* Some segments may be completely empty, with a non-zero p_memsz
* but no backing file segment.
+2
View File
@@ -131,6 +131,7 @@ const char *get_elf_base_platform(CPUState *cs)
#undef MATCH_PLATFORM_INSN
/* See linux kernel: arch/mips/kernel/process.c:elf_dump_regs. */
#ifndef TARGET_MIPS64
void elf_core_copy_regs(target_elf_gregset_t *r, const CPUMIPSState *env)
{
for (int i = 1; i < ARRAY_SIZE(env->active_tc.gpr); i++) {
@@ -146,3 +147,4 @@ void elf_core_copy_regs(target_elf_gregset_t *r, const CPUMIPSState *env)
r->pt.cp0_status = tswapl(env->CP0_Status);
r->pt.cp0_cause = tswapl(env->CP0_Cause);
}
#endif
+7
View File
@@ -134,6 +134,7 @@ static inline void setup_sigcontext(CPUMIPSState *regs,
for (i = 0; i < 32; ++i) {
__put_user(regs->active_fpu.fpr[i].d, &sc->sc_fpregs[i]);
}
__put_user(regs->active_fpu.fcr31, &sc->sc_fpc_csr);
}
static inline void
@@ -165,6 +166,12 @@ restore_sigcontext(CPUMIPSState *regs, struct target_sigcontext *sc)
for (i = 0; i < 32; ++i) {
__get_user(regs->active_fpu.fpr[i].d, &sc->sc_fpregs[i]);
}
{
uint32_t fcr31;
__get_user(fcr31, &sc->sc_fpc_csr);
regs->active_fpu.fcr31 = fcr31 & regs->active_fpu.fcr31_rw_bitmask;
cpu_mips_restore_fp_status(regs);
}
}
/*
+44
View File
@@ -1 +1,45 @@
#include "../mips/elfload.c"
/*
* mips/elfload.c defines elf_core_copy_regs guarded by #ifndef TARGET_MIPS64.
*
* We must provide the mips64 version here. We cannot use r->pt.regs[] because
* when mips/elfload.c is #include'd above its "#include "target_elf.h"" resolves
* to mips/target_elf.h (compiler searches the including file's directory first),
* which pulls in mips/target_ptrace.h. That struct has pad0[6] before regs[],
* so r->pt.regs[i] writes to reserved[6+i] — offset by 6 from what the kernel
* and glibc expect for the N64 ABI (EPC at reserved[34], not reserved[40]).
*
* Write directly to reserved[] using the mips64 N64 index layout:
* R0-R31 at reserved[0..31], LO at [32], HI at [33], EPC at [34].
*/
void elf_core_copy_regs(target_elf_gregset_t *r, const CPUMIPSState *env)
{
/*
* linux-user/elfload.c allocates target_elf_prstatus using the
* definition from mips64/target_elf.h, where target_elf_gregset_t
* has target_ulong reserved[45] (8 bytes each = 360 bytes total).
*
* But in this compilation unit, "#include target_elf.h" resolved to
* mips/target_elf.h (wrong directory), so our local target_elf_gregset_t
* has abi_ulong reserved[45] which is only 4 bytes each for mipsn32.
* Using r->reserved[i] would write to the wrong offsets for mipsn32.
*
* Cast to target_ulong * to always write 8-byte entries at the correct
* positions, matching the layout that elfload.c allocated.
*/
target_ulong *regs = (target_ulong *)r;
/* R0 is always 0; buffer is zero-initialised by the caller */
for (int i = 1; i < 32; i++) {
regs[i] = tswap64(env->active_tc.gpr[i]);
}
regs[26] = 0; /* k0 */
regs[27] = 0; /* k1 */
regs[32] = tswap64(env->active_tc.LO[0]);
regs[33] = tswap64(env->active_tc.HI[0]);
regs[34] = tswap64(env->active_tc.PC);
regs[35] = tswap64(env->CP0_BadVAddr);
regs[36] = tswap64(env->CP0_Status);
regs[37] = tswap64(env->CP0_Cause);
}
+1 -1
View File
@@ -420,7 +420,7 @@ static void restore_user_regs(CPUPPCState *env,
__get_user(*fpr, &frame->mc_fregs[i]);
}
__get_user(fpscr, &frame->mc_fregs[32]);
env->fpscr = (uint32_t) fpscr;
ppc_store_fpscr(env, (uint32_t) fpscr);
}
#if !defined(TARGET_PPC64)
+1
View File
@@ -26,6 +26,7 @@
struct image_info {
abi_ulong load_bias;
abi_ulong load_addr;
abi_ulong phdr_addr;
abi_ulong start_code;
abi_ulong end_code;
abi_ulong start_data;
+5 -1
View File
@@ -332,7 +332,11 @@ static void restore_sigregs(CPUS390XState *env, target_sigregs *sc)
for (i = 0; i < 16; i++) {
__get_user(env->aregs[i], &sc->regs.acrs[i]);
}
__get_user(env->fpc, &sc->fpregs.fpc);
{
uint32_t fpc;
__get_user(fpc, &sc->fpregs.fpc);
cpu_s390x_load_fpc(env, fpc);
}
for (i = 0; i < 16; i++) {
__get_user(*get_freg(env, i), &sc->fpregs.fprs[i]);
}
+16 -3
View File
@@ -131,8 +131,10 @@ static void setup_sigcontext(struct target_sigcontext *sc,
COPY(gregs[14]); COPY(gregs[15]);
COPY(gbr); COPY(mach);
COPY(macl); COPY(pr);
COPY(sr); COPY(pc);
COPY(pc);
#undef COPY
/* The T, M and Q bits live outside env->sr; fold them back in. */
__put_user(cpu_read_sr(regs), &sc->sc_sr);
for (i=0; i<16; i++) {
__put_user(regs->fregs[i], &sc->sc_fpregs[i]);
@@ -159,13 +161,24 @@ static void restore_sigcontext(CPUSH4State *regs, struct target_sigcontext *sc)
COPY(gregs[14]); COPY(gregs[15]);
COPY(gbr); COPY(mach);
COPY(macl); COPY(pr);
COPY(sr); COPY(pc);
COPY(pc);
#undef COPY
/* The T, M and Q bits live outside env->sr; unfold them. */
{
uint32_t sr;
__get_user(sr, &sc->sc_sr);
cpu_write_sr(regs, sr);
}
for (i=0; i<16; i++) {
__get_user(regs->fregs[i], &sc->sc_fpregs[i]);
}
__get_user(regs->fpscr, &sc->sc_fpscr);
/* Resync the derived float_status state, not just env->fpscr. */
{
uint32_t fpscr;
__get_user(fpscr, &sc->sc_fpscr);
cpu_load_fpscr(regs, fpscr);
}
__get_user(regs->fpul, &sc->sc_fpul);
regs->tra = -1; /* disable syscall checks */
+105
View File
@@ -4318,6 +4318,111 @@ print_statx(CPUArchState *cpu_env, const struct syscallname *name,
}
#endif
#if defined(TARGET_NR_fsconfig) && defined(NR_fsconfig)
static void
print_fsconfig_cmd_name(int cmd)
{
switch (cmd) {
case FSCONFIG_SET_FLAG:
qemu_log("%s%s", "FSCONFIG_SET_FLAG", get_comma(0));
break;
case FSCONFIG_SET_STRING:
qemu_log("%s%s", "FSCONFIG_SET_STRING", get_comma(0));
break;
case FSCONFIG_SET_BINARY:
qemu_log("%s%s", "FSCONFIG_SET_BINARY", get_comma(0));
break;
case FSCONFIG_SET_PATH:
qemu_log("%s%s", "FSCONFIG_SET_PATH", get_comma(0));
break;
case FSCONFIG_SET_PATH_EMPTY:
qemu_log("%s%s", "FSCONFIG_SET_PATH_EMPTY", get_comma(0));
break;
case FSCONFIG_SET_FD:
qemu_log("%s%s", "FSCONFIG_SET_FD", get_comma(0));
break;
case FSCONFIG_CMD_CREATE:
qemu_log("%s%s", "FSCONFIG_CMD_CREATE", get_comma(0));
break;
case FSCONFIG_CMD_RECONFIGURE:
qemu_log("%s%s", "FSCONFIG_CMD_RECONFIGURE", get_comma(0));
break;
#ifdef FSCONFIG_CMD_CREATE_EXCL
case FSCONFIG_CMD_CREATE_EXCL:
/* Only available since Linux 6.6. */
qemu_log("%s%s", "FSCONFIG_CMD_CREATE_EXCL", get_comma(0));
break;
#endif
default:
qemu_log("%s (%d)%s", "UNKNOWN_CMD", cmd, get_comma(0));
break;
}
}
static void
print_fsconfig(CPUArchState *cpu_env, const struct syscallname *name,
abi_long arg0, abi_long arg1, abi_long arg2,
abi_long arg3, abi_long arg4, abi_long arg5)
{
/*
* fsconfig(int fd, int cmd, char* key, void* value, int aux)
* Where:
* fd: file descriptor returned by fsopen().
* cmd: integer constant specifying a command.
* key: a string, can be NULL on certain commands.
* value: any data in a buffer, can be NULL, raw buffer or a string.
* aux: axillary values such as flags for FSCONFIG_SET_PATH.
*/
int cmd = (int) arg1;
print_syscall_prologue(name);
print_raw_param("%d", arg0, 0);
print_fsconfig_cmd_name(cmd);
/* Process arg2 (key). */
switch (cmd) {
case FSCONFIG_SET_FLAG:
case FSCONFIG_SET_STRING:
case FSCONFIG_SET_BINARY:
case FSCONFIG_SET_PATH:
case FSCONFIG_SET_PATH_EMPTY:
case FSCONFIG_SET_FD:
print_string(arg2, 0);
break;
default:
print_pointer(arg2, 0);
break;
}
/* Process arg3 (value). */
switch (cmd) {
case FSCONFIG_SET_STRING:
case FSCONFIG_SET_PATH:
case FSCONFIG_SET_PATH_EMPTY:
print_string(arg3, 0);
break;
default:
print_pointer(arg3, 0);
break;
}
/*
* Process arg4 (aux).
* On FSCONFIG_SET_PATH and FSCONFIG_SET_PATH_EMPTY, aux can
* be either 0 or AT_FDCWD.
* On FSCONFIG_SET_BINARY, aux is an integer to state the length
* of the buffer pointed by arg3.
* Otherwise, it must be 0.
*/
switch (cmd) {
case FSCONFIG_SET_PATH:
case FSCONFIG_SET_PATH_EMPTY:
print_at_dirfd(arg4, 1);
break;
default:
print_raw_param("%d", arg4, 1);
break;
}
print_syscall_epilogue(name);
}
#endif
#ifdef TARGET_NR_ioctl
static void
print_ioctl(CPUArchState *cpu_env, const struct syscallname *name,
+15
View File
@@ -1722,3 +1722,18 @@
#ifdef TARGET_NR_rseq
{ TARGET_NR_rseq, "rseq" , "%s(%p,%u,%d,%#x)", NULL, NULL },
#endif
#ifdef TARGET_NR_fsopen
{ TARGET_NR_fsopen, "fsopen", "%s(%s,%d)", NULL, NULL },
#endif
#if defined(TARGET_NR_fsconfig) && defined(NR_fsconfig)
{ TARGET_NR_fsconfig, "fsconfig", NULL, print_fsconfig, NULL },
#endif
#ifdef TARGET_NR_fsmount
{ TARGET_NR_fsmount, "fsmount", "%s(%d,%d,%d)", NULL, NULL },
#endif
#ifdef TARGET_NR_move_mount
{ TARGET_NR_move_mount, "move_mount", "%s(%d,%s,%d,%s,%d)", NULL, NULL },
#endif
#ifdef TARGET_NR_fspick
{ TARGET_NR_fspick, "fspick", "%s(%d,%s,%d)", NULL, NULL },
#endif
+142
View File
@@ -744,6 +744,11 @@ safe_syscall5(ssize_t, preadv, int, fd, const struct iovec *, iov, int, iovcnt,
unsigned long, pos_l, unsigned long, pos_h)
safe_syscall5(ssize_t, pwritev, int, fd, const struct iovec *, iov, int, iovcnt,
unsigned long, pos_l, unsigned long, pos_h)
safe_syscall6(ssize_t, preadv2, int, fd, const struct iovec *, iov, int, iovcnt,
unsigned long, pos_l, unsigned long, pos_h, __kernel_rwf_t, flags)
safe_syscall6(ssize_t, pwritev2, int, fd, const struct iovec *, iov,
int, iovcnt, unsigned long, pos_l, unsigned long, pos_h,
__kernel_rwf_t, flags)
safe_syscall3(int, connect, int, fd, const struct sockaddr *, addr,
socklen_t, addrlen)
safe_syscall6(ssize_t, sendto, int, fd, const void *, buf, size_t, len,
@@ -9658,6 +9663,19 @@ _syscall5(int, sys_move_mount, int, __from_dfd, const char *, __from_pathname,
int, __to_dfd, const char *, __to_pathname, unsigned int, flag)
#endif
#if defined(TARGET_NR_fsopen) && defined(NR_fsopen)
#define __NR_sys_fsopen __NR_fsopen
_syscall2(int, sys_fsopen, const char *, fs_name, unsigned int, flags);
#define __NR_sys_fsconfig __NR_fsconfig
_syscall5(int, sys_fsconfig, int, fs_fd, unsigned int, cmd, const char *, key,
const void *, value, int, aux)
#define __NR_sys_fsmount __NR_fsmount
_syscall3(int, sys_fsmount, int, fs_fd, unsigned int, flags,
unsigned int, ms_flags)
#define __NR_sys_fspick __NR_fspick
_syscall3(int, sys_fspick, int, dfd, const char *, path, unsigned int, flags)
#endif
/* This is an internal helper for do_syscall so that it is easier
* to have a single return point, so that actions, such as logging
* of syscall results, can be performed.
@@ -11839,6 +11857,39 @@ static abi_long do_syscall1(CPUArchState *cpu_env, int num, abi_long arg1,
}
}
return ret;
#endif
#if defined(TARGET_NR_preadv2)
case TARGET_NR_preadv2:
{
struct iovec *vec = lock_iovec(VERIFY_WRITE, arg2, arg3, 0);
if (vec != NULL) {
unsigned long low, high;
target_to_host_low_high(arg4, arg5, &low, &high);
ret = get_errno(safe_preadv2(arg1, vec, arg3, low, high, arg6));
unlock_iovec(vec, arg2, arg3, 1);
} else {
ret = -host_to_target_errno(errno);
}
}
return ret;
#endif
#if defined(TARGET_NR_pwritev2)
case TARGET_NR_pwritev2:
{
struct iovec *vec = lock_iovec(VERIFY_READ, arg2, arg3, 1);
if (vec != NULL) {
unsigned long low, high;
target_to_host_low_high(arg4, arg5, &low, &high);
ret = get_errno(safe_pwritev2(arg1, vec, arg3, low, high,
arg6));
unlock_iovec(vec, arg2, arg3, 0);
} else {
ret = -host_to_target_errno(errno);
}
}
return ret;
#endif
case TARGET_NR_getsid:
return get_errno(getsid(arg1));
@@ -14349,6 +14400,97 @@ static abi_long do_syscall1(CPUArchState *cpu_env, int num, abi_long arg1,
return do_map_shadow_stack(cpu_env, arg1, arg2, arg3);
#endif
#if defined(TARGET_NR_fsopen) && defined(NR_fsopen)
case TARGET_NR_fsopen:
{
p = lock_user_string(arg1);
if (!p) {
return -TARGET_EFAULT;
}
ret = get_errno(sys_fsopen(p, arg2));
unlock_user(p, arg1, 0);
}
return ret;
case TARGET_NR_fsconfig:
{
/*
* fsconfig(int, int, char *, void *, int)
* NOTE: p4 is nullable and its type might not be a string.
*/
void *p3, *p4;
int cmd = (int) arg2;
switch (cmd) {
case FSCONFIG_SET_BINARY:
case FSCONFIG_SET_STRING:
case FSCONFIG_SET_PATH:
case FSCONFIG_SET_PATH_EMPTY:
p3 = lock_user_string(arg3);
if (!p3) {
return -TARGET_EFAULT;
}
if (cmd != FSCONFIG_SET_BINARY) {
/* key and value must be strings. */
p4 = lock_user_string(arg4);
} else {
/*
* Otherwise the value must be a raw buffer with its
* length specified in arg5 (aux).
*/
p4 = lock_user(VERIFY_READ, arg4, arg5, 1);
}
if (!p4) {
unlock_user(p3, arg3, 0);
return -TARGET_EFAULT;
}
ret = get_errno(sys_fsconfig(arg1, arg2, p3, p4, arg5));
unlock_user(p3, arg3, 0);
unlock_user(p4, arg4, 0);
break;
case FSCONFIG_SET_FLAG:
case FSCONFIG_SET_FD:
/* arg4 (value) must be NULL. */
if (arg4) {
return -TARGET_EFAULT;
}
p3 = lock_user_string(arg3);
if (!p3) {
return -TARGET_EFAULT;
}
ret = get_errno(sys_fsconfig(arg1, arg2, p3, NULL, arg5));
unlock_user(p3, arg3, 0);
break;
case FSCONFIG_CMD_CREATE:
case FSCONFIG_CMD_RECONFIGURE:
#ifdef FSCONFIG_CMD_CREATE_EXCL
/*
* FSCONFIG_CMD_CREATE_EXCL is only available since Linux
* 6.6. Guarding it to allow building with pre-6.6 headers.
*/
case FSCONFIG_CMD_CREATE_EXCL:
#endif
/* key and value must be NULL, aux must be 0. */
if (arg3 || arg4 || arg5) {
return -TARGET_EFAULT;
}
ret = get_errno(sys_fsconfig(arg1, arg2, NULL, NULL, 0));
break;
default:
return -TARGET_EFAULT;
}
}
return ret;
case TARGET_NR_fsmount:
ret = get_errno(sys_fsmount(arg1, arg2, arg3));
return ret;
case TARGET_NR_fspick:
{
p = lock_user_string(arg2);
ret = get_errno(sys_fspick(arg1, p, arg3));
unlock_user(p, arg2, 0);
}
return ret;
#endif
default:
qemu_log_mask(LOG_UNIMP, "Unsupported syscall: %d\n", num);
return -TARGET_ENOSYS;
+90 -9
View File
@@ -21,6 +21,7 @@
#include "user-internals.h"
#include "signal-common.h"
#include "linux-user/trace.h"
#include "target/xtensa/cpu.h"
struct target_sigcontext {
abi_ulong sc_pc;
@@ -43,10 +44,25 @@ struct target_ucontext {
target_sigset_t tuc_sigmask;
};
struct target_xtensa_xtregs_fp {
uint32_t f[16];
uint32_t fcr;
uint32_t fsr;
};
struct target_xtensa_xtregs_dfp {
uint64_t f[16];
uint32_t fcr;
uint32_t fsr;
};
struct target_rt_sigframe {
target_siginfo_t info;
struct target_ucontext uc;
/* TODO: xtregs */
union {
struct target_xtensa_xtregs_fp fp;
struct target_xtensa_xtregs_dfp dfp;
} xtregs;
uint8_t retcode[6];
abi_ulong window[4];
};
@@ -107,6 +123,7 @@ static int flush_window_regs(CPUXtensaState *env)
}
static int setup_sigcontext(struct target_rt_sigframe *frame,
abi_ulong frame_addr,
CPUXtensaState *env)
{
struct target_sigcontext *sc = &frame->uc.tuc_mcontext;
@@ -123,8 +140,25 @@ static int setup_sigcontext(struct target_rt_sigframe *frame,
for (i = 0; i < 16; ++i) {
__put_user(env->regs[i], sc->sc_a + i);
}
__put_user(0, &sc->sc_xtregs);
/* TODO: xtregs */
if (xtensa_option_enabled(env->config, XTENSA_OPTION_DFP_COPROCESSOR)) {
for (i = 0; i < 16; ++i) {
__put_user(env->fregs[i].f64, &frame->xtregs.dfp.f[i]);
}
__put_user(env->uregs[FCR], &frame->xtregs.dfp.fcr);
__put_user(cpu_get_fsr(env), &frame->xtregs.dfp.fsr);
__put_user(frame_addr + offsetof(struct target_rt_sigframe, xtregs),
&sc->sc_xtregs);
} else if (xtensa_option_enabled(env->config, XTENSA_OPTION_FP_COPROCESSOR)) {
for (i = 0; i < 16; ++i) {
__put_user(env->fregs[i].f32[FP_F32_LOW], &frame->xtregs.fp.f[i]);
}
__put_user(env->uregs[FCR], &frame->xtregs.fp.fcr);
__put_user(cpu_get_fsr(env), &frame->xtregs.fp.fsr);
__put_user(frame_addr + offsetof(struct target_rt_sigframe, xtregs),
&sc->sc_xtregs);
} else {
__put_user(0, &sc->sc_xtregs);
}
return 1;
}
@@ -190,7 +224,7 @@ void setup_rt_frame(int sig, struct target_sigaction *ka,
__put_user(0, &frame->uc.tuc_flags);
__put_user(0, &frame->uc.tuc_link);
target_save_altstack(&frame->uc.tuc_stack, env);
if (!setup_sigcontext(frame, env)) {
if (!setup_sigcontext(frame, frame_addr, env)) {
unlock_user_struct(frame, frame_addr, 0);
goto give_sigsegv;
}
@@ -243,8 +277,8 @@ give_sigsegv:
force_sigsegv(sig);
}
static void restore_sigcontext(CPUXtensaState *env,
struct target_rt_sigframe *frame)
static int restore_sigcontext(CPUXtensaState *env,
struct target_rt_sigframe *frame)
{
struct target_sigcontext *sc = &frame->uc.tuc_mcontext;
uint32_t ps;
@@ -266,7 +300,51 @@ static void restore_sigcontext(CPUXtensaState *env,
for (i = 0; i < 16; ++i) {
__get_user(env->regs[i], sc->sc_a + i);
}
/* TODO: xtregs */
{
abi_ulong xtregs_addr;
__get_user(xtregs_addr, &sc->sc_xtregs);
if (xtregs_addr) {
if (xtensa_option_enabled(env->config,
XTENSA_OPTION_DFP_COPROCESSOR)) {
struct target_xtensa_xtregs_dfp *xtregs;
uint32_t fcr, fsr;
xtregs = lock_user(VERIFY_READ, xtregs_addr,
sizeof(*xtregs), 1);
if (!xtregs) {
return 0;
}
for (i = 0; i < 16; ++i) {
__get_user(env->fregs[i].f64, &xtregs->f[i]);
}
__get_user(fcr, &xtregs->fcr);
__get_user(fsr, &xtregs->fsr);
unlock_user(xtregs, xtregs_addr, 0);
cpu_set_fcr(env, fcr);
cpu_set_fsr(env, fsr);
} else if (xtensa_option_enabled(env->config,
XTENSA_OPTION_FP_COPROCESSOR)) {
struct target_xtensa_xtregs_fp *xtregs;
uint32_t fcr, fsr;
xtregs = lock_user(VERIFY_READ, xtregs_addr,
sizeof(*xtregs), 1);
if (!xtregs) {
return 0;
}
for (i = 0; i < 16; ++i) {
__get_user(env->fregs[i].f32[FP_F32_LOW], &xtregs->f[i]);
}
__get_user(fcr, &xtregs->fcr);
__get_user(fsr, &xtregs->fsr);
unlock_user(xtregs, xtregs_addr, 0);
cpu_set_fcr(env, fcr);
cpu_set_fsr(env, fsr);
}
}
}
return 1;
}
long do_rt_sigreturn(CPUXtensaState *env)
@@ -277,12 +355,15 @@ long do_rt_sigreturn(CPUXtensaState *env)
trace_user_do_rt_sigreturn(env, frame_addr);
if (!lock_user_struct(VERIFY_READ, frame, frame_addr, 1)) {
goto badframe;
force_sig(TARGET_SIGSEGV);
return -QEMU_ESIGRETURN;
}
target_to_host_sigset(&set, &frame->uc.tuc_sigmask);
set_sigmask(&set);
restore_sigcontext(env, frame);
if (!restore_sigcontext(env, frame)) {
goto badframe;
}
target_restore_altstack(&frame->uc.tuc_stack, env);
unlock_user_struct(frame, frame_addr, 0);
+115
View File
@@ -2218,6 +2218,120 @@ static int discard_f(BlockBackend *blk, int argc, char **argv)
return 0;
}
static void aio_discard_help(void)
{
printf(
"\n"
" asynchronously discards a range of bytes from the given offset\n"
"\n"
" Example:\n"
" 'aio_discard 512 1k' - discards 1 kilobyte from 512 bytes into the file\n"
"\n"
" Discards a segment of the currently open file.\n"
" -C, -- report statistics in a machine parsable format\n"
" -q, -- quiet mode, do not show I/O statistics\n"
" The discard is performed asynchronously and the aio_flush command must be\n"
" used to ensure all outstanding aio requests have been completed.\n"
" Note that due to its asynchronous nature, this command will be\n"
" considered successful once the request is submitted, independently\n"
" of potential I/O errors.\n"
"\n");
}
static int aio_discard_f(BlockBackend *blk, int argc, char **argv);
static const cmdinfo_t aio_discard_cmd = {
.name = "aio_discard",
.cfunc = aio_discard_f,
.perm = BLK_PERM_WRITE,
.argmin = 2,
.argmax = -1,
.args = "[-Cq] off len",
.oneline = "asynchronously discards a number of bytes",
.help = aio_discard_help,
};
static void aio_discard_done(void *opaque, int ret)
{
struct aio_ctx *ctx = opaque;
struct timespec t2;
clock_gettime(CLOCK_MONOTONIC, &t2);
if (ret < 0) {
printf("aio_discard failed: %s\n", strerror(-ret));
block_acct_failed(blk_get_stats(ctx->blk), &ctx->acct);
goto out;
}
block_acct_done(blk_get_stats(ctx->blk), &ctx->acct);
if (ctx->qflag) {
goto out;
}
/* Finally, report back -- -C gives a parsable format */
t2 = tsub(t2, ctx->t1);
print_report("discarded ", &t2, ctx->offset, ctx->qiov.size,
ctx->qiov.size, 1, ctx->Cflag);
out:
g_free(ctx);
}
static int aio_discard_f(BlockBackend *blk, int argc, char **argv)
{
int c, ret;
int64_t count;
struct aio_ctx *ctx = g_new0(struct aio_ctx, 1);
ctx->blk = blk;
while ((c = getopt(argc, argv, "Cq")) != -1) {
switch (c) {
case 'C':
ctx->Cflag = true;
break;
case 'q':
ctx->qflag = true;
break;
default:
g_free(ctx);
qemuio_command_usage(&aio_discard_cmd);
return -EINVAL;
}
}
if (optind != argc - 2) {
g_free(ctx);
qemuio_command_usage(&aio_discard_cmd);
return -EINVAL;
}
ctx->offset = cvtnum(argv[optind]);
if (ctx->offset < 0) {
ret = ctx->offset;
print_cvtnum_err(ret, argv[optind]);
g_free(ctx);
return ret;
}
optind++;
count = cvtnum(argv[optind]);
if (count < 0) {
print_cvtnum_err(count, argv[optind]);
g_free(ctx);
return count;
}
clock_gettime(CLOCK_MONOTONIC, &ctx->t1);
ctx->qiov.size = count;
block_acct_start(blk_get_stats(blk), &ctx->acct, ctx->qiov.size,
BLOCK_ACCT_UNMAP);
blk_aio_pdiscard(blk, ctx->offset, count, aio_discard_done, ctx);
return 0;
}
static int alloc_f(BlockBackend *blk, int argc, char **argv)
{
BlockDriverState *bs = blk_bs(blk);
@@ -2800,6 +2914,7 @@ static void __attribute((constructor)) init_qemuio_commands(void)
qemuio_add_command(&length_cmd);
qemuio_add_command(&info_cmd);
qemuio_add_command(&discard_cmd);
qemuio_add_command(&aio_discard_cmd);
qemuio_add_command(&alloc_cmd);
qemuio_add_command(&map_cmd);
qemuio_add_command(&reopen_cmd);
+4 -3
View File
@@ -465,8 +465,9 @@ static int
vduse_queue_read_indirect_desc(VduseDev *dev, struct vring_desc *desc,
uint64_t addr, size_t len)
{
struct vring_desc *ori_desc;
char *dst_desc = (char *)desc;
uint64_t read_len;
void *ori_desc;
if (len > (VIRTQUEUE_MAX_SIZE * sizeof(struct vring_desc))) {
return -1;
@@ -483,10 +484,10 @@ vduse_queue_read_indirect_desc(VduseDev *dev, struct vring_desc *desc,
return -1;
}
memcpy(desc, ori_desc, read_len);
memcpy(dst_desc, ori_desc, read_len);
len -= read_len;
addr += read_len;
desc += read_len;
dst_desc += read_len;
}
return 0;
+4 -3
View File
@@ -2391,8 +2391,9 @@ static int
virtqueue_read_indirect_desc(VuDev *dev, struct vring_desc *desc,
uint64_t addr, size_t len)
{
struct vring_desc *ori_desc;
char *dst_desc = (char *)desc;
uint64_t read_len;
void *ori_desc;
if (len > (VIRTQUEUE_MAX_SIZE * sizeof(struct vring_desc))) {
return -1;
@@ -2409,10 +2410,10 @@ virtqueue_read_indirect_desc(VuDev *dev, struct vring_desc *desc,
return -1;
}
memcpy(desc, ori_desc, read_len);
memcpy(dst_desc, ori_desc, read_len);
len -= read_len;
addr += read_len;
desc += read_len;
dst_desc += read_len;
}
return 0;
+2 -2
View File
@@ -40,8 +40,8 @@ static enum {
RTC_BASE_DATETIME,
} rtc_base_type = RTC_BASE_UTC;
static time_t rtc_ref_start_datetime;
static int rtc_realtime_clock_offset; /* used only with QEMU_CLOCK_REALTIME */
static int rtc_host_datetime_offset = -1; /* valid & used only with
static time_t rtc_realtime_clock_offset; /* used only with QEMU_CLOCK_REALTIME */
static time_t rtc_host_datetime_offset = -1; /* valid & used only with
RTC_BASE_DATETIME */
QEMUClockType rtc_clock;
/***********************************************************/
+10
View File
@@ -871,6 +871,16 @@ static inline uint32_t arm_fi_to_lfsc(ARMMMUFaultInfo *fi)
assert(fi->level >= 0 && fi->level <= 3);
fsc = 0b001100 | fi->level;
break;
case ARMFault_Domain:
/*
* This can only happen when doing an AT insn at EL2 for an AArch32
* stage 1 EL1&0 translation regime using short-descriptors, and
* the translation hits a Domain fault. This needs to be reported in
* the long-format PAR. Compare pseudocode AArch64_PARFaultStatus().
*/
assert(fi->level == 1 || fi->level == 2);
fsc = 0b111100 | fi->level;
break;
case ARMFault_Translation:
assert(fi->level >= -1 && fi->level <= 3);
if (fi->level < 0) {
+14
View File
@@ -2914,6 +2914,20 @@ DEF_HELPER_FLAGS_6(sve2_fminp_zpzz_s, TCG_CALL_NO_RWG,
DEF_HELPER_FLAGS_6(sve2_fminp_zpzz_d, TCG_CALL_NO_RWG,
void, ptr, ptr, ptr, ptr, fpst, i32)
DEF_HELPER_FLAGS_6(sve2_ah_fmaxp_zpzz_h, TCG_CALL_NO_RWG,
void, ptr, ptr, ptr, ptr, fpst, i32)
DEF_HELPER_FLAGS_6(sve2_ah_fmaxp_zpzz_s, TCG_CALL_NO_RWG,
void, ptr, ptr, ptr, ptr, fpst, i32)
DEF_HELPER_FLAGS_6(sve2_ah_fmaxp_zpzz_d, TCG_CALL_NO_RWG,
void, ptr, ptr, ptr, ptr, fpst, i32)
DEF_HELPER_FLAGS_6(sve2_ah_fminp_zpzz_h, TCG_CALL_NO_RWG,
void, ptr, ptr, ptr, ptr, fpst, i32)
DEF_HELPER_FLAGS_6(sve2_ah_fminp_zpzz_s, TCG_CALL_NO_RWG,
void, ptr, ptr, ptr, ptr, fpst, i32)
DEF_HELPER_FLAGS_6(sve2_ah_fminp_zpzz_d, TCG_CALL_NO_RWG,
void, ptr, ptr, ptr, ptr, fpst, i32)
DEF_HELPER_FLAGS_5(sve2_eor3, TCG_CALL_NO_RWG, void, ptr, ptr, ptr, ptr, i32)
DEF_HELPER_FLAGS_5(sve2_bcax, TCG_CALL_NO_RWG, void, ptr, ptr, ptr, ptr, i32)
DEF_HELPER_FLAGS_5(sve2_bsl1n, TCG_CALL_NO_RWG, void, ptr, ptr, ptr, ptr, i32)
+11
View File
@@ -774,6 +774,14 @@ DO_ZPZZ_PAIR_FP(sve2_fminp_zpzz_h, float16, H1_2, float16_min)
DO_ZPZZ_PAIR_FP(sve2_fminp_zpzz_s, float32, H1_4, float32_min)
DO_ZPZZ_PAIR_FP(sve2_fminp_zpzz_d, float64, H1_8, float64_min)
DO_ZPZZ_PAIR_FP(sve2_ah_fmaxp_zpzz_h, float16, H1_2, helper_vfp_ah_maxh)
DO_ZPZZ_PAIR_FP(sve2_ah_fmaxp_zpzz_s, float32, H1_4, helper_vfp_ah_maxs)
DO_ZPZZ_PAIR_FP(sve2_ah_fmaxp_zpzz_d, float64, H1_8, helper_vfp_ah_maxd)
DO_ZPZZ_PAIR_FP(sve2_ah_fminp_zpzz_h, float16, H1_2, helper_vfp_ah_minh)
DO_ZPZZ_PAIR_FP(sve2_ah_fminp_zpzz_s, float32, H1_4, helper_vfp_ah_mins)
DO_ZPZZ_PAIR_FP(sve2_ah_fminp_zpzz_d, float64, H1_8, helper_vfp_ah_mind)
#undef DO_ZPZZ_PAIR_FP
/* Three-operand expander, controlled by a predicate, in which the
@@ -5024,6 +5032,7 @@ static int16_t do_float16_logb_as_int(float16 a, float_status *s)
if (frac != 0) {
if (!get_flush_inputs_to_zero(s)) {
/* denormal: bias - fractional_zeros */
float_raise(float_flag_input_denormal_used, s);
return -15 - clz32(frac);
}
/* flush to zero */
@@ -5052,6 +5061,7 @@ static int32_t do_float32_logb_as_int(float32 a, float_status *s)
if (frac != 0) {
if (!get_flush_inputs_to_zero(s)) {
/* denormal: bias - fractional_zeros */
float_raise(float_flag_input_denormal_used, s);
return -127 - clz32(frac);
}
/* flush to zero */
@@ -5080,6 +5090,7 @@ static int64_t do_float64_logb_as_int(float64 a, float_status *s)
if (frac != 0) {
if (!get_flush_inputs_to_zero(s)) {
/* denormal: bias - fractional_zeros */
float_raise(float_flag_input_denormal_used, s);
return -1023 - clz64(frac);
}
/* flush to zero */
+2 -2
View File
@@ -1415,9 +1415,9 @@ static bool do_zz_fpst(DisasContext *s, arg_zz_n *a, int data,
}
TRANS_FEAT(BFCVT, aa64_sme2, do_zz_fpst, a, 0,
FPST_A64, gen_helper_sme2_bfcvt)
s->fpcr_ah ? FPST_AH : FPST_A64, gen_helper_sme2_bfcvt)
TRANS_FEAT(BFCVTN, aa64_sme2, do_zz_fpst, a, 0,
FPST_A64, gen_helper_sme2_bfcvtn)
s->fpcr_ah ? FPST_AH : FPST_A64, gen_helper_sme2_bfcvtn)
TRANS_FEAT(FCVT_n, aa64_sme2, do_zz_fpst, a, 0,
FPST_A64, gen_helper_sme2_fcvt_n)
TRANS_FEAT(FCVTN, aa64_sme2, do_zz_fpst, a, 0,
+5 -4
View File
@@ -2989,7 +2989,8 @@ TRANS_FEAT(REVH, aa64_sve, gen_gvec_ool_arg_zpz, revh_fns[a->esz], a, 0)
TRANS_FEAT(REVW, aa64_sve, gen_gvec_ool_arg_zpz,
a->esz == 3 ? gen_helper_sve_revw_d : NULL, a, 0)
TRANS_FEAT(REVD, aa64_sme, gen_gvec_ool_arg_zpz, gen_helper_sme_revd_q, a, 0)
TRANS_FEAT(REVD, aa64_sme_or_sve2p1, gen_gvec_ool_arg_zpz,
gen_helper_sme_revd_q, a, 0)
TRANS_FEAT(SPLICE, aa64_sve, gen_gvec_ool_arg_zpzz,
gen_helper_sve_splice, a, a->esz)
@@ -7665,8 +7666,8 @@ TRANS_FEAT_NONSTREAMING(HISTSEG, aa64_sve2, gen_gvec_ool_arg_zzz,
DO_ZPZZ_FP(FADDP, aa64_sve2, sve2_faddp_zpzz)
DO_ZPZZ_FP(FMAXNMP, aa64_sve2, sve2_fmaxnmp_zpzz)
DO_ZPZZ_FP(FMINNMP, aa64_sve2, sve2_fminnmp_zpzz)
DO_ZPZZ_FP(FMAXP, aa64_sve2, sve2_fmaxp_zpzz)
DO_ZPZZ_FP(FMINP, aa64_sve2, sve2_fminp_zpzz)
DO_ZPZZ_AH_FP(FMAXP, aa64_sve2, sve2_fmaxp_zpzz, sve2_ah_fmaxp_zpzz)
DO_ZPZZ_AH_FP(FMINP, aa64_sve2, sve2_fminp_zpzz, sve2_ah_fminp_zpzz)
static bool do_fmmla(DisasContext *s, arg_rrrr_esz *a,
gen_helper_gvec_4_ptr *fn)
@@ -7825,7 +7826,7 @@ TRANS_FEAT(BFCVTNT, aa64_sve_bf16, gen_gvec_fpst_arg_zpz,
s->fpcr_ah ? FPST_AH : FPST_A64)
TRANS_FEAT(FCVTLT_hs, aa64_sve2, gen_gvec_fpst_arg_zpz,
gen_helper_sve2_fcvtlt_hs, a, 0, FPST_A64)
gen_helper_sve2_fcvtlt_hs, a, 0, FPST_A64_F16)
TRANS_FEAT(FCVTLT_sd, aa64_sve2, gen_gvec_fpst_arg_zpz,
gen_helper_sve2_fcvtlt_sd, a, 0, FPST_A64)
+35 -29
View File
@@ -3253,8 +3253,9 @@ static void gen_PUSHF(DisasContext *s, X86DecodedInsn *decode)
gen_push_v(s, s->T0);
}
static MemOp gen_shift_count(DisasContext *s, X86DecodedInsn *decode,
bool *can_be_zero, TCGv *count, int unit)
static MemOp gen_shift_count_1(DisasContext *s, X86DecodedInsn *decode,
bool *can_be_zero, TCGv *count, int unit,
int mod)
{
MemOp ot = decode->op[0].ot;
int mask = (ot <= MO_32 ? 0x1f : 0x3f);
@@ -3264,16 +3265,31 @@ static MemOp gen_shift_count(DisasContext *s, X86DecodedInsn *decode,
case X86_OP_INT:
*count = tcg_temp_new();
tcg_gen_andi_tl(*count, cpu_regs[R_ECX], mask);
if (mod < mask) {
TCGv temp = tcg_temp_new();
assert(mod * 4 >= mask);
if (mod * 2 < mask) {
tcg_gen_subi_tl(temp, *count, mod * 2);
tcg_gen_movcond_tl(TCG_COND_GE, *count, temp, tcg_constant_tl(0), temp, *count);
}
tcg_gen_subi_tl(temp, *count, mod);
tcg_gen_movcond_tl(TCG_COND_GE, *count, temp, tcg_constant_tl(0), temp, *count);
}
*can_be_zero = true;
break;
case X86_OP_IMM:
if ((decode->immediate & mask) == 0) {
decode->immediate &= mask;
if (mod < mask) {
decode->immediate %= mod;
}
if (decode->immediate == 0) {
*count = NULL;
break;
}
*count = tcg_temp_new();
tcg_gen_movi_tl(*count, decode->immediate & mask);
tcg_gen_movi_tl(*count, decode->immediate);
break;
case X86_OP_SKIP:
@@ -3288,6 +3304,13 @@ static MemOp gen_shift_count(DisasContext *s, X86DecodedInsn *decode,
return ot;
}
static MemOp gen_shift_count(DisasContext *s, X86DecodedInsn *decode,
bool *can_be_zero, TCGv *count, int unit)
{
return gen_shift_count_1(s, decode, can_be_zero, count, unit,
INT_MAX);
}
/*
* Compute existing flags in decode->cc_src, for gen_* functions that wants
* to set the cc_op set to CC_OP_ADCOX. In particular, this allows rotate
@@ -3406,29 +3429,14 @@ static void gen_rot_overflow(X86DecodedInsn *decode, TCGv result, TCGv old,
/*
* RCx operations are invariant modulo 8*operand_size+1. For 8 and 16-bit operands,
* this is less than 0x1f (the mask applied by gen_shift_count) so reduce further.
* FIXME: are flags updated if the count is nonzero, but a multiple of (8 << op) + 1?
*/
static void gen_rotc_mod(MemOp ot, TCGv count)
static MemOp gen_rotc_count(DisasContext *s, X86DecodedInsn *decode,
bool *can_be_zero, TCGv *count, int unit)
{
TCGv temp;
switch (ot) {
case MO_8:
temp = tcg_temp_new();
tcg_gen_subi_tl(temp, count, 18);
tcg_gen_movcond_tl(TCG_COND_GE, count, temp, tcg_constant_tl(0), temp, count);
tcg_gen_subi_tl(temp, count, 9);
tcg_gen_movcond_tl(TCG_COND_GE, count, temp, tcg_constant_tl(0), temp, count);
break;
case MO_16:
temp = tcg_temp_new();
tcg_gen_subi_tl(temp, count, 17);
tcg_gen_movcond_tl(TCG_COND_GE, count, temp, tcg_constant_tl(0), temp, count);
break;
default:
break;
}
MemOp ot = decode->op[0].ot;
return gen_shift_count_1(s, decode, can_be_zero, count, unit,
(8 << ot) + 1);
}
/*
@@ -3449,7 +3457,7 @@ static void gen_RCL(DisasContext *s, X86DecodedInsn *decode)
bool have_1bit_cin, can_be_zero;
TCGv count;
TCGLabel *zero_label = NULL;
MemOp ot = gen_shift_count(s, decode, &can_be_zero, &count, decode->op[2].unit);
MemOp ot = gen_rotc_count(s, decode, &can_be_zero, &count, decode->op[2].unit);
TCGv low, high, low_count;
if (!count) {
@@ -3460,7 +3468,6 @@ static void gen_RCL(DisasContext *s, X86DecodedInsn *decode)
high = tcg_temp_new();
low_count = tcg_temp_new();
gen_rotc_mod(ot, count);
have_1bit_cin = gen_eflags_adcox(s, decode, true, can_be_zero);
if (can_be_zero) {
zero_label = gen_new_label();
@@ -3501,7 +3508,7 @@ static void gen_RCR(DisasContext *s, X86DecodedInsn *decode)
bool have_1bit_cin, can_be_zero;
TCGv count;
TCGLabel *zero_label = NULL;
MemOp ot = gen_shift_count(s, decode, &can_be_zero, &count, decode->op[2].unit);
MemOp ot = gen_rotc_count(s, decode, &can_be_zero, &count, decode->op[2].unit);
TCGv low, high, high_count;
if (!count) {
@@ -3512,7 +3519,6 @@ static void gen_RCR(DisasContext *s, X86DecodedInsn *decode)
high = tcg_temp_new();
high_count = tcg_temp_new();
gen_rotc_mod(ot, count);
have_1bit_cin = gen_eflags_adcox(s, decode, true, can_be_zero);
if (can_be_zero) {
zero_label = gen_new_label();
+3
View File
@@ -1366,6 +1366,9 @@ void cpu_mips_clock_init(MIPSCPU *cpu);
/* helper.c */
target_ulong exception_resume_pc(CPUMIPSState *env);
/* fpu.c */
void cpu_mips_restore_fp_status(CPUMIPSState *env);
/**
* mips_cpu_create_with_clock:
* @typename: a MIPS CPU type.
+5
View File
@@ -17,6 +17,11 @@ const FloatRoundMode ieee_rm[4] = {
float_round_down
};
void cpu_mips_restore_fp_status(CPUMIPSState *env)
{
restore_fp_status(env);
}
const char fregnames[32][4] = {
"f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7",
"f8", "f9", "f10", "f11", "f12", "f13", "f14", "f15",
+7 -3
View File
@@ -755,10 +755,14 @@ static void riscv_cpu_reset_hold(Object *obj, ResetType type)
/*
* Clear mseccfg and unlock all the PMP entries upon reset.
* This is allowed as per the priv and smepmp specifications
* and is needed to clear stale entries across reboots.
* This is required as per the priv, smepmp, and other security
* extension specifications that share this CSR, and is needed
* to clear stale entries across reboots.
*/
if (riscv_cpu_cfg(env)->ext_smepmp) {
if (riscv_cpu_cfg(env)->ext_smepmp ||
riscv_cpu_cfg(env)->ext_zkr ||
riscv_cpu_cfg(env)->ext_smmpm ||
riscv_cpu_cfg(env)->ext_zicfilp) {
env->mseccfg = 0;
}
+3 -1
View File
@@ -69,6 +69,7 @@ typedef struct CPUArchState CPURISCVState;
#define RVH RV('H')
#define RVG RV('G')
#define RVB RV('B')
#define RVX RV('X')
extern const uint32_t misa_bits[];
const char *riscv_get_misa_ext_name(uint32_t bit);
@@ -130,7 +131,8 @@ enum {
TRANSLATE_SUCCESS,
TRANSLATE_FAIL,
TRANSLATE_PMP_FAIL,
TRANSLATE_G_STAGE_FAIL
TRANSLATE_G_STAGE_FAIL,
TRANSLATE_PMA_FAIL,
};
/* Extension context status */
+64 -9
View File
@@ -1374,7 +1374,22 @@ static int get_physical_address(CPURISCVState *env, hwaddr *physical,
}
if (res != MEMTX_OK) {
return TRANSLATE_FAIL;
/*
* The result of address_space_* APIs above does not take into
* consideration reject reads, putting all errors in the same
* cathegory (DECODE_ERROR), although there's a clear
* distinction between a rejected read versus other errors
* (see memory_region_dispatch_read() ->
* memory_region_access_valid()). This is something that
* we might have to deal with core QEMU logic some other
* day.
*
* For this particular error path, given that we made checks
* w.r.t legal PTE address before calling those APIs, we'll
* assume that anything != MEMTX_OK means a rejected read,
* i.e. a PMA error.
*/
return TRANSLATE_PMA_FAIL;
}
if (riscv_cpu_sxl(env) == MXL_RV32) {
@@ -1396,6 +1411,25 @@ static int get_physical_address(CPURISCVState *env, hwaddr *physical,
return TRANSLATE_FAIL;
}
/*
* priv spec, "Svpbmt" chapter:
* "For non-leaf PTEs, bits 62-61 are reserved for future
* standard use. Until their use is defined by a standard
* extension, they must be cleared by software for forward
* compatibility, or else a page-fault exception is raised."
*
* For leaf PTEs the same bits are also reserved but in that
* case the page-fault is mandatory. Make both cases consistent
* by also page faulting here.
*/
if ((pte & PTE_PBMT) == PTE_PBMT) {
qemu_log_mask(LOG_GUEST_ERROR, "%s: PBMT bits 62 and 61 are "
"reserved but are set in PTE: "
"addr: 0x%" HWADDR_PRIx " pte: 0x" TARGET_FMT_lx "\n",
__func__, pte_addr, pte);
return TRANSLATE_FAIL;
}
if (!riscv_cpu_cfg(env)->ext_svnapot && (pte & PTE_N)) {
/* Reserved without Svnapot extension */
qemu_log_mask(LOG_GUEST_ERROR, "%s: N bit set in PTE, "
@@ -1448,6 +1482,23 @@ static int get_physical_address(CPURISCVState *env, hwaddr *physical,
return TRANSLATE_FAIL;
}
/*
* priv spec, "Svpbmt" chapter:
* "For leaf PTEs, setting bits 62-61 to the value 3 is reserved
* for future standard use. Until this value is defined by a
* standard extension, using this reserved value in a leaf PTE
* raises a page-fault exception. "
*
* Raise a fault if 62-61 (i.e. PTE_PBMT) are set.
*/
if ((pte & PTE_PBMT) == PTE_PBMT) {
qemu_log_mask(LOG_GUEST_ERROR, "%s: PBMT bits 62 and 61 are "
"reserved but are set in leaf PTE: "
"addr: 0x%" HWADDR_PRIx " pte: 0x" TARGET_FMT_lx "\n",
__func__, pte_addr, pte);
return TRANSLATE_FAIL;
}
target_ulong rwx = pte & (PTE_R | PTE_W | PTE_X);
/* Check for reserved combinations of RWX flags. */
switch (rwx) {
@@ -1618,7 +1669,8 @@ static int get_physical_address(CPURISCVState *env, hwaddr *physical,
}
static void raise_mmu_exception(CPURISCVState *env, target_ulong address,
MMUAccessType access_type, bool pmp_violation,
MMUAccessType access_type,
bool pmp_pma_violation,
bool first_stage, bool two_stage,
bool two_stage_indirect)
{
@@ -1626,7 +1678,7 @@ static void raise_mmu_exception(CPURISCVState *env, target_ulong address,
switch (access_type) {
case MMU_INST_FETCH:
if (pmp_violation) {
if (pmp_pma_violation) {
cs->exception_index = RISCV_EXCP_INST_ACCESS_FAULT;
} else if (env->virt_enabled && !first_stage) {
cs->exception_index = RISCV_EXCP_INST_GUEST_PAGE_FAULT;
@@ -1635,7 +1687,7 @@ static void raise_mmu_exception(CPURISCVState *env, target_ulong address,
}
break;
case MMU_DATA_LOAD:
if (pmp_violation) {
if (pmp_pma_violation) {
cs->exception_index = RISCV_EXCP_LOAD_ACCESS_FAULT;
} else if (two_stage && !first_stage) {
cs->exception_index = RISCV_EXCP_LOAD_GUEST_ACCESS_FAULT;
@@ -1644,7 +1696,7 @@ static void raise_mmu_exception(CPURISCVState *env, target_ulong address,
}
break;
case MMU_DATA_STORE:
if (pmp_violation) {
if (pmp_pma_violation) {
cs->exception_index = RISCV_EXCP_STORE_AMO_ACCESS_FAULT;
} else if (two_stage && !first_stage) {
cs->exception_index = RISCV_EXCP_STORE_GUEST_AMO_ACCESS_FAULT;
@@ -1770,7 +1822,7 @@ bool riscv_cpu_tlb_fill(CPUState *cs, vaddr address, int size,
vaddr im_address;
hwaddr pa = 0;
int prot, prot2, prot_pmp;
bool pmp_violation = false;
bool pmp_pma_violation = false;
bool first_stage_error = true;
bool two_stage_lookup = mmuidx_2stage(mmu_idx);
bool two_stage_indirect_error = false;
@@ -1871,8 +1923,8 @@ bool riscv_cpu_tlb_fill(CPUState *cs, vaddr address, int size,
}
}
if (ret == TRANSLATE_PMP_FAIL) {
pmp_violation = true;
if (ret == TRANSLATE_PMP_FAIL || ret == TRANSLATE_PMA_FAIL) {
pmp_pma_violation = true;
}
if (ret == TRANSLATE_SUCCESS) {
@@ -1899,7 +1951,7 @@ bool riscv_cpu_tlb_fill(CPUState *cs, vaddr address, int size,
cpu_check_watchpoint(cs, address, size, MEMTXATTRS_UNSPECIFIED,
wp_access, retaddr);
raise_mmu_exception(env, address, access_type, pmp_violation,
raise_mmu_exception(env, address, access_type, pmp_pma_violation,
first_stage_error, two_stage_lookup,
two_stage_indirect_error);
cpu_loop_exit_restore(cs, retaddr);
@@ -2124,6 +2176,9 @@ static target_ulong promote_load_fault(target_ulong orig_cause)
case RISCV_EXCP_LOAD_PAGE_FAULT:
return RISCV_EXCP_STORE_PAGE_FAULT;
case RISCV_EXCP_LOAD_ADDR_MIS:
return RISCV_EXCP_STORE_AMO_ADDR_MIS;
}
/* if no promotion, return original cause */
+34 -8
View File
@@ -771,6 +771,9 @@ static RISCVException have_mseccfg(CPURISCVState *env, int csrno)
if (riscv_cpu_cfg(env)->ext_smmpm) {
return RISCV_EXCP_NONE;
}
if (riscv_cpu_cfg(env)->ext_zicfilp) {
return RISCV_EXCP_NONE;
}
return RISCV_EXCP_ILLEGAL_INST;
}
@@ -958,7 +961,7 @@ static RISCVException write_vxrm(CPURISCVState *env, int csrno,
#if !defined(CONFIG_USER_ONLY)
env->mstatus |= MSTATUS_VS;
#endif
env->vxrm = val;
env->vxrm = val & (VCSR_VXRM >> VCSR_VXRM_SHIFT);
return RISCV_EXCP_NONE;
}
@@ -1762,13 +1765,13 @@ static RISCVException write_stimecmph(CPURISCVState *env, int csrno,
#define VSTOPI_NUM_SRCS 5
/*
* All core local interrupts except the fixed ones 0:12. This macro is for
* All core local interrupts except the fixed ones 0:15. This macro is for
* virtual interrupts logic so please don't change this to avoid messing up
* the whole support, For reference see AIA spec: `5.3 Interrupt filtering and
* virtual interrupts for supervisor level` and `6.3.2 Virtual interrupts for
* VS level`.
*/
#define LOCAL_INTERRUPTS (~0x1FFFULL)
#define LOCAL_INTERRUPTS (~0xFFFFULL)
static const uint64_t delegable_ints =
S_MODE_INTERRUPTS | VS_MODE_INTERRUPTS | MIP_LCOFIP;
@@ -1787,7 +1790,6 @@ static const uint64_t all_ints = M_MODE_INTERRUPTS | S_MODE_INTERRUPTS |
(1ULL << (RISCV_EXCP_U_ECALL)) | \
(1ULL << (RISCV_EXCP_S_ECALL)) | \
(1ULL << (RISCV_EXCP_VS_ECALL)) | \
(1ULL << (RISCV_EXCP_M_ECALL)) | \
(1ULL << (RISCV_EXCP_INST_PAGE_FAULT)) | \
(1ULL << (RISCV_EXCP_LOAD_PAGE_FAULT)) | \
(1ULL << (RISCV_EXCP_STORE_PAGE_FAULT)) | \
@@ -2025,11 +2027,18 @@ static RISCVException write_mstatus(CPURISCVState *env, int csrno,
}
if (xl != MXL_RV32 || env->debugger) {
if (riscv_has_ext(env, RVH)) {
mask |= MSTATUS_MPV | MSTATUS_GVA;
}
if ((val & MSTATUS64_UXL) != 0) {
uint64_t uxl = val & MSTATUS64_UXL >> 32;
mask |= MSTATUS64_UXL;
/*
* uxl = 3 is reserved so write the current xl instead.
* In case xl = MXL_RV128 (3) write MXL_RV64.
*/
if (uxl == 3) {
uxl = xl == MXL_RV128 ? MXL_RV64 : xl;
val = deposit64(val, 32, 2, uxl);
}
}
}
@@ -2064,7 +2073,7 @@ static RISCVException write_mstatush(CPURISCVState *env, int csrno,
target_ulong val, uintptr_t ra)
{
uint64_t valh = (uint64_t)val << 32;
uint64_t mask = riscv_has_ext(env, RVH) ? MSTATUS_MPV | MSTATUS_GVA : 0;
uint64_t mask = 0;
if (riscv_cpu_cfg(env)->ext_smdbltrp) {
mask |= MSTATUS_MDT;
@@ -5326,6 +5335,23 @@ static RISCVException read_pmpaddr(CPURISCVState *env, int csrno,
target_ulong *val)
{
*val = pmpaddr_csr_read(env, csrno - CSR_PMPADDR0);
/*
* For RV64, bits 54-63 of the address registers
* PMPAADDR(0-63) is a WARL zero field (priv spec,
* section "Physical Memory Protection CSRs").
*
* We'll have to add an annoying TARGET_RISCV64 gate
* here to avoid complaints about masking bits 0-53
* of a potential 32 bit target_ulong '*var'.
*/
#ifdef TARGET_RISCV64
if (env->misa_mxl == MXL_RV64
&& csrno >= CSR_PMPADDR0 && csrno <= CSR_PMPADDR63) {
target_ulong read_mask = MAKE_64BIT_MASK(0, 54);
*val &= read_mask;
}
#endif
return RISCV_EXCP_NONE;
}
+1 -1
View File
@@ -199,9 +199,9 @@ ldu ............ ..... 111 ..... 0000011 @i
{
[
# *** RV32 Zicbom Standard Extension ***
cbo_inval 0000000 00000 ..... 010 00000 0001111 @sfence_vm
cbo_clean 0000000 00001 ..... 010 00000 0001111 @sfence_vm
cbo_flush 0000000 00010 ..... 010 00000 0001111 @sfence_vm
cbo_inval 0000000 00000 ..... 010 00000 0001111 @sfence_vm
# *** RV32 Zicboz Standard Extension ***
cbo_zero 0000000 00100 ..... 010 00000 0001111 @sfence_vm
+1
View File
@@ -3090,6 +3090,7 @@ GEN_OPIVV_TRANS(vredxor_vs, reduction_check)
static bool reduction_widen_check(DisasContext *s, arg_rmrr *a)
{
return reduction_check(s, a) && (s->sew < MO_64) &&
!is_overlapped(a->rs1, 1, a->rs2, 1 << MAX(s->lmul, 0)) &&
((s->sew + 1) <= (s->cfg_ptr->elen >> 4));
}
@@ -33,6 +33,8 @@ static bool trans_cbo_clean(DisasContext *ctx, arg_cbo_clean *a)
REQUIRE_ZICBOM(ctx);
TCGv src = get_address(ctx, a->rs1, 0);
/* The helper may raise ILLEGAL_INSN -- record binv for unwind. */
decode_save_opc(ctx, 0);
gen_helper_cbo_clean_flush(tcg_env, src);
return true;
}
@@ -42,6 +44,8 @@ static bool trans_cbo_flush(DisasContext *ctx, arg_cbo_flush *a)
REQUIRE_ZICBOM(ctx);
TCGv src = get_address(ctx, a->rs1, 0);
/* The helper may raise ILLEGAL_INSN -- record binv for unwind. */
decode_save_opc(ctx, 0);
gen_helper_cbo_clean_flush(tcg_env, src);
return true;
}
@@ -51,6 +55,8 @@ static bool trans_cbo_inval(DisasContext *ctx, arg_cbo_inval *a)
REQUIRE_ZICBOM(ctx);
TCGv src = get_address(ctx, a->rs1, 0);
/* The helper may raise ILLEGAL_INSN -- record binv for unwind. */
decode_save_opc(ctx, 0);
gen_helper_cbo_inval(tcg_env, src);
return true;
}
@@ -60,6 +66,8 @@ static bool trans_cbo_zero(DisasContext *ctx, arg_cbo_zero *a)
REQUIRE_ZICBOZ(ctx);
TCGv src = get_address(ctx, a->rs1, 0);
/* The helper may raise ILLEGAL_INSN -- record binv for unwind. */
decode_save_opc(ctx, 0);
gen_helper_cbo_zero(tcg_env, src);
return true;
}
+20
View File
@@ -425,6 +425,25 @@ static const VMStateDescription vmstate_sstc = {
}
};
static bool mseccfg_needed(void *opaque)
{
RISCVCPU *cpu = opaque;
return cpu->cfg.ext_smepmp || cpu->cfg.ext_zkr
|| cpu->cfg.ext_smmpm || cpu->cfg.ext_zicfilp;
}
static const VMStateDescription vmstate_mseccfg = {
.name = "cpu/mseccfg",
.version_id = 1,
.minimum_version_id = 1,
.needed = mseccfg_needed,
.fields = (const VMStateField[]) {
VMSTATE_UINTTL(env.mseccfg, RISCVCPU),
VMSTATE_END_OF_LIST()
}
};
const VMStateDescription vmstate_riscv_cpu = {
.name = "cpu",
.version_id = 10,
@@ -502,6 +521,7 @@ const VMStateDescription vmstate_riscv_cpu = {
&vmstate_ssp,
&vmstate_ctr,
&vmstate_sstc,
&vmstate_mseccfg,
NULL
}
};
+2 -2
View File
@@ -215,8 +215,8 @@ static void pmp_decode_napot(hwaddr a, hwaddr *sa, hwaddr *ea)
void pmp_update_rule_addr(CPURISCVState *env, uint32_t pmp_index)
{
uint8_t this_cfg = env->pmp_state.pmp[pmp_index].cfg_reg;
target_ulong this_addr = env->pmp_state.pmp[pmp_index].addr_reg;
target_ulong prev_addr = 0u;
hwaddr this_addr = env->pmp_state.pmp[pmp_index].addr_reg;
hwaddr prev_addr = 0u;
hwaddr sa = 0u;
hwaddr ea = 0u;
int g = pmp_get_granularity_g(env);
+75
View File
@@ -861,6 +861,27 @@ void riscv_cpu_validate_set_extensions(RISCVCPU *cpu, Error **errp)
return;
}
#ifndef CONFIG_USER_ONLY
if (cpu->cfg.ext_svpbmt && cpu->cfg.max_satp_mode < VM_1_10_SV39) {
cpu->cfg.ext_svpbmt = false;
if (cpu_cfg_ext_is_user_set(CPU_CFG_OFFSET(ext_svpbmt))) {
warn_report("svpbmt requires at least satp sv39, "
"current satp mode: %s",
satp_mode_str(cpu->cfg.max_satp_mode,
riscv_cpu_is_32bit(cpu)));
}
}
if (cpu->cfg.ext_svnapot && cpu->cfg.max_satp_mode < VM_1_10_SV39) {
cpu->cfg.ext_svnapot = false;
if (cpu_cfg_ext_is_user_set(CPU_CFG_OFFSET(ext_svnapot))) {
warn_report("svnapot requires at least satp sv39, "
"current satp mode: %s",
satp_mode_str(cpu->cfg.max_satp_mode,
riscv_cpu_is_32bit(cpu)));
}
}
#endif
/*
* Disable isa extensions based on priv spec after we
* validated and set everything we need.
@@ -1120,6 +1141,58 @@ static void riscv_cpu_enable_implied_rules(RISCVCPU *cpu)
}
}
/*
* MISA.C is set if the following extensions are selected:
* - Zca and not F.
* - Zca, Zcf and F (but not D) is specified on RV32.
* - Zca, Zcf and Zcd if D is specified on RV32.
* - Zca, Zcd if D is specified on RV64.
*/
static void riscv_cpu_update_misa_c(RISCVCPU *cpu)
{
CPURISCVState *env = &cpu->env;
bool set_misa_c = false;
if (riscv_has_ext(env, RVC)) {
return;
}
if (cpu->cfg.ext_zca && !riscv_has_ext(env, RVF)) {
set_misa_c = true;
} else if (riscv_cpu_mxl(env) == MXL_RV32 &&
cpu->cfg.ext_zca && cpu->cfg.ext_zcf &&
(riscv_has_ext(env, RVD) ? cpu->cfg.ext_zcd :
riscv_has_ext(env, RVF))) {
set_misa_c = true;
} else if (riscv_cpu_mxl(env) == MXL_RV64 &&
cpu->cfg.ext_zca && cpu->cfg.ext_zcd) {
set_misa_c = true;
}
if (set_misa_c) {
if (cpu_misa_ext_is_user_set(RVC)) {
warn_report("RVC mandated by Zca/Zcf/Zcd extensions");
return;
}
riscv_cpu_set_misa_ext(env, env->misa_ext | RVC);
}
}
/* MISA.X is set when any of the non-standard extensions is enabled. */
static void riscv_cpu_update_misa_x(RISCVCPU *cpu)
{
CPURISCVState *env = &cpu->env;
const RISCVCPUMultiExtConfig *arr = riscv_cpu_vendor_exts;
for (int i = 0; arr[i].name != NULL; i++) {
if (isa_ext_is_enabled(cpu, arr[i].offset)) {
riscv_cpu_set_misa_ext(env, env->misa_ext | RVX);
break;
}
}
}
void riscv_tcg_cpu_finalize_features(RISCVCPU *cpu, Error **errp)
{
CPURISCVState *env = &cpu->env;
@@ -1127,6 +1200,8 @@ void riscv_tcg_cpu_finalize_features(RISCVCPU *cpu, Error **errp)
riscv_cpu_init_implied_exts_rules();
riscv_cpu_enable_implied_rules(cpu);
riscv_cpu_update_misa_c(cpu);
riscv_cpu_update_misa_x(cpu);
riscv_cpu_validate_misa_priv(env, &local_err);
if (local_err != NULL) {
+1
View File
@@ -924,6 +924,7 @@ void s390_init_sigp(void);
/* helper.c */
void s390_cpu_set_psw(CPUS390XState *env, uint64_t mask, uint64_t addr);
uint64_t s390_cpu_get_psw_mask(CPUS390XState *env);
void cpu_s390x_load_fpc(CPUS390XState *env, uint32_t fpc);
/* outside of target/s390x/ */
S390CPU *s390_cpu_addr2state(uint16_t cpu_addr);
+5 -5
View File
@@ -90,9 +90,9 @@ static int stsi_topology_fill_sysib(S390TopologyList *topology_list,
int last_drawer = -1;
int last_book = -1;
int last_socket = -1;
int drawer_id = 0;
int book_id = 0;
int socket_id = 0;
int drawer_id = 1;
int book_id = 1;
int socket_id = 1;
int n = sizeof(SysIB_151x);
QTAILQ_FOREACH(entry, topology_list, next) {
@@ -103,12 +103,12 @@ static int stsi_topology_fill_sysib(S390TopologyList *topology_list,
if (level > 3 && drawer_change) {
SYSIB_GUARD(n, sizeof(SYSIBContainerListEntry));
p = fill_container(p, 3, drawer_id++);
book_id = 0;
book_id = 1;
}
if (level > 2 && book_change) {
SYSIB_GUARD(n, sizeof(SYSIBContainerListEntry));
p = fill_container(p, 2, book_id++);
socket_id = 0;
socket_id = 1;
}
if (socket_change) {
SYSIB_GUARD(n, sizeof(SYSIBContainerListEntry));
+14 -6
View File
@@ -896,6 +896,19 @@ static const int fpc_to_rnd[8] = {
float_round_to_odd,
};
void cpu_s390x_load_fpc(CPUS390XState *env, uint32_t fpc)
{
/*
* Mimic kernel fpu_lfpc_safe(): a corrupt signal frame value that would
* trigger a specification exception instead results in FPC being set to 0.
*/
if (fpc_to_rnd[fpc & 0x7] == -1 || fpc & 0x03030088u) {
fpc = 0;
}
env->fpc = fpc;
set_float_rounding_mode(fpc_to_rnd[fpc & 0x7], &env->fpu_status);
}
/* set fpc */
void HELPER(sfpc)(CPUS390XState *env, uint64_t fpc)
{
@@ -903,12 +916,7 @@ void HELPER(sfpc)(CPUS390XState *env, uint64_t fpc)
(!s390_has_feat(S390_FEAT_FLOATING_POINT_EXT) && fpc & 0x4)) {
tcg_s390_program_interrupt(env, PGM_SPECIFICATION, GETPC());
}
/* Install everything in the main FPC. */
env->fpc = fpc;
/* Install the rounding mode in the shadow fpu_status. */
set_float_rounding_mode(fpc_to_rnd[fpc & 0x7], &env->fpu_status);
cpu_s390x_load_fpc(env, fpc);
}
/* set fpc and signal */
+3
View File
@@ -380,4 +380,7 @@ static inline void cpu_write_sr(CPUSH4State *env, uint32_t sr)
env->sr = sr & ~((1u << SR_M) | (1u << SR_Q) | (1u << SR_T));
}
/* Set FPSCR and the derived float_status rounding/flush-to-zero state. */
void cpu_load_fpscr(CPUSH4State *env, uint32_t val);
#endif /* SH4_CPU_H */
+6 -1
View File
@@ -201,7 +201,7 @@ void helper_macw(CPUSH4State *env, int32_t arg0, int32_t arg1)
}
}
void helper_ld_fpscr(CPUSH4State *env, uint32_t val)
void cpu_load_fpscr(CPUSH4State *env, uint32_t val)
{
env->fpscr = val & FPSCR_MASK;
if ((val & FPSCR_RM_MASK) == FPSCR_RM_ZERO) {
@@ -212,6 +212,11 @@ void helper_ld_fpscr(CPUSH4State *env, uint32_t val)
set_flush_to_zero((val & FPSCR_DN) != 0, &env->fp_status);
}
void helper_ld_fpscr(CPUSH4State *env, uint32_t val)
{
cpu_load_fpscr(env, val);
}
static void update_fpscr(CPUSH4State *env, uintptr_t retaddr)
{
int xcpt, cause, enable;
+4
View File
@@ -643,6 +643,10 @@ static inline void xtensa_select_static_vectors(CPUXtensaState *env,
}
void xtensa_runstall(CPUXtensaState *env, bool runstall);
uint32_t cpu_get_fsr(CPUXtensaState *env);
void cpu_set_fcr(CPUXtensaState *env, uint32_t v);
void cpu_set_fsr(CPUXtensaState *env, uint32_t v);
#define XTENSA_OPTION_BIT(opt) (((uint64_t)1) << (opt))
#define XTENSA_OPTION_ALL (~(uint64_t)0)
+60 -51
View File
@@ -64,56 +64,7 @@ void xtensa_use_first_nan(CPUXtensaState *env, bool use_first)
&env->fp_status);
}
void HELPER(wur_fpu2k_fcr)(CPUXtensaState *env, uint32_t v)
{
static const int rounding_mode[] = {
float_round_nearest_even,
float_round_to_zero,
float_round_up,
float_round_down,
};
env->uregs[FCR] = v & 0xfffff07f;
set_float_rounding_mode(rounding_mode[v & 3], &env->fp_status);
}
void HELPER(wur_fpu_fcr)(CPUXtensaState *env, uint32_t v)
{
static const int rounding_mode[] = {
float_round_nearest_even,
float_round_to_zero,
float_round_up,
float_round_down,
};
if (v & 0xfffff000) {
qemu_log_mask(LOG_GUEST_ERROR,
"MBZ field of FCR is written non-zero: %08x\n", v);
}
env->uregs[FCR] = v & 0x0000007f;
set_float_rounding_mode(rounding_mode[v & 3], &env->fp_status);
}
void HELPER(wur_fpu_fsr)(CPUXtensaState *env, uint32_t v)
{
uint32_t flags = v >> XTENSA_FSR_FLAGS_SHIFT;
int fef = 0;
unsigned i;
if (v & 0xfffff000) {
qemu_log_mask(LOG_GUEST_ERROR,
"MBZ field of FSR is written non-zero: %08x\n", v);
}
env->uregs[FSR] = v & 0x00000f80;
for (i = 0; i < ARRAY_SIZE(xtensa_fp_flag_map); ++i) {
if (flags & xtensa_fp_flag_map[i].xtensa_fp_flag) {
fef |= xtensa_fp_flag_map[i].softfloat_fp_flag;
}
}
set_float_exception_flags(fef, &env->fp_status);
}
uint32_t HELPER(rur_fpu_fsr)(CPUXtensaState *env)
uint32_t cpu_get_fsr(CPUXtensaState *env)
{
uint32_t flags = 0;
int fef = get_float_exception_flags(&env->fp_status);
@@ -124,10 +75,68 @@ uint32_t HELPER(rur_fpu_fsr)(CPUXtensaState *env)
flags |= xtensa_fp_flag_map[i].xtensa_fp_flag;
}
}
env->uregs[FSR] = flags << XTENSA_FSR_FLAGS_SHIFT;
return flags << XTENSA_FSR_FLAGS_SHIFT;
}
void cpu_set_fcr(CPUXtensaState *env, uint32_t v)
{
static const FloatRoundMode rounding_mode[] = {
float_round_nearest_even,
float_round_to_zero,
float_round_up,
float_round_down,
};
env->uregs[FCR] = v & 0xfffff07f;
set_float_rounding_mode(rounding_mode[v & 3], &env->fp_status);
}
void cpu_set_fsr(CPUXtensaState *env, uint32_t v)
{
uint32_t flags = v >> XTENSA_FSR_FLAGS_SHIFT;
int fef = 0;
unsigned i;
env->uregs[FSR] = v & 0x00000f80;
for (i = 0; i < ARRAY_SIZE(xtensa_fp_flag_map); ++i) {
if (flags & xtensa_fp_flag_map[i].xtensa_fp_flag) {
fef |= xtensa_fp_flag_map[i].softfloat_fp_flag;
}
}
set_float_exception_flags(fef, &env->fp_status);
}
void HELPER(wur_fpu2k_fcr)(CPUXtensaState *env, uint32_t v)
{
cpu_set_fcr(env, v);
}
void HELPER(wur_fpu_fcr)(CPUXtensaState *env, uint32_t v)
{
if (v & 0xfffff000) {
qemu_log_mask(LOG_GUEST_ERROR,
"MBZ field of FCR is written non-zero: %08x\n", v);
}
cpu_set_fcr(env, v & 0x0000007f);
}
void HELPER(wur_fpu_fsr)(CPUXtensaState *env, uint32_t v)
{
if (v & 0xfffff000) {
qemu_log_mask(LOG_GUEST_ERROR,
"MBZ field of FSR is written non-zero: %08x\n", v);
}
cpu_set_fsr(env, v);
}
uint32_t HELPER(rur_fpu_fsr)(CPUXtensaState *env)
{
uint32_t fsr = cpu_get_fsr(env);
env->uregs[FSR] = fsr;
return fsr;
}
float64 HELPER(abs_d)(float64 v)
{
return float64_abs(v);
+69
View File
@@ -184,6 +184,68 @@ aio_write -P 160 0x104000 0x18000
resume A
aio_flush
EOF
# Create a pre-allocated zero cluster, then start a write on it and discard it
# before the L2 update is made
cat <<EOF
write -P 181 0x120000 0x10000
write -z 0x120000 0x10000
break write_aio A
aio_write -P 180 0x120000 0x10000
wait_break A
aio_discard 0x120000 0x10000
resume A
aio_flush
EOF
# Create a pre-allocated zero cluster, then start a write on it and a
# concurrent zero write with MAY_UNMAP before the L2 update is made
cat <<EOF
write -P 181 0x130000 0x10000
write -z 0x130000 0x10000
break write_aio A
aio_write -P 180 0x130000 0x10000
wait_break A
aio_write -z -u 0x130000 0x10000
resume A
aio_flush
EOF
# Create a pre-allocated zero cluster, then start a write on it and a
# concurrent zero write without MAY_UNMAP before the L2 update is made
cat <<EOF
write -P 181 0x140000 0x10000
write -z 0x140000 0x10000
break write_aio A
aio_write -P 180 0x140000 0x10000
wait_break A
aio_write -z 0x140000 0x10000
resume A
aio_flush
EOF
# Start an allocating write to a previously unallocated cluster and, before
# its L2 update is linked, issue a concurrent sub-cluster zero write with
# MAY_UNMAP that targets a disjoint range within the same cluster. The zero
# write's head/tail are zero (cluster is unallocated), so qcow2_co_pwrite_zeroes
# would expand it to the full subcluster. Without waiting for dependencies
# before the zero write's "unallocated" type check, that check passes,
# qcow2_subcluster_zeroize then yields in wait_for_dependencies, the allocating
# write links its L2 entry, and the resumed zeroize unmaps the cluster -
# silently discarding the just-written data. Waiting first makes the zero write
# fall back to a bounce-buffered real write, which only touches its own
# subrange.
cat <<EOF
break write_aio A
aio_write -P 180 0x200000 0x4000
wait_break A
aio_write -z -u 0x204000 0x4000
resume A
aio_flush
EOF
}
overlay_io | $QEMU_IO blkdebug::"$TEST_IMG" | _filter_qemu_io |\
@@ -264,6 +326,13 @@ verify_io()
# Undefined content for 0x10c000 0x8000
echo read -P 160 0x114000 0x8000
echo read -P 17 0x11c000 0x4000
echo read -P 0 0x120000 0x10000
echo read -P 0 0x130000 0x10000
echo read -P 0 0x140000 0x10000
echo read -P 180 0x200000 0x4000
echo read -P 0 0x204000 0xc000
}
verify_io | $QEMU_IO "$TEST_IMG" | _filter_qemu_io
+46
View File
@@ -139,6 +139,42 @@ wrote XXX/XXX bytes at offset XXX
XXX KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
wrote XXX/XXX bytes at offset XXX
XXX KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
wrote XXX/XXX bytes at offset XXX
XXX KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
wrote XXX/XXX bytes at offset XXX
XXX KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
blkdebug: Suspended request 'A'
blkdebug: Resuming request 'A'
wrote XXX/XXX bytes at offset XXX
XXX KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
discarded XXX/XXX bytes at offset XXX
XXX KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
wrote XXX/XXX bytes at offset XXX
XXX KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
wrote XXX/XXX bytes at offset XXX
XXX KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
blkdebug: Suspended request 'A'
blkdebug: Resuming request 'A'
wrote XXX/XXX bytes at offset XXX
XXX KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
wrote XXX/XXX bytes at offset XXX
XXX KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
wrote XXX/XXX bytes at offset XXX
XXX KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
wrote XXX/XXX bytes at offset XXX
XXX KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
blkdebug: Suspended request 'A'
blkdebug: Resuming request 'A'
wrote XXX/XXX bytes at offset XXX
XXX KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
wrote XXX/XXX bytes at offset XXX
XXX KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
blkdebug: Suspended request 'A'
blkdebug: Resuming request 'A'
wrote XXX/XXX bytes at offset XXX
XXX KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
wrote XXX/XXX bytes at offset XXX
XXX KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
== Verify image content ==
read 65536/65536 bytes at offset 0
@@ -239,5 +275,15 @@ read 32768/32768 bytes at offset 1130496
32 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
read 16384/16384 bytes at offset 1163264
16 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
read 65536/65536 bytes at offset 1179648
64 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
read 65536/65536 bytes at offset 1245184
64 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
read 65536/65536 bytes at offset 1310720
64 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
read 16384/16384 bytes at offset 2097152
16 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
read 49152/49152 bytes at offset 2113536
48 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
No errors were found on the image.
*** done
+76
View File
@@ -0,0 +1,76 @@
/*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "qemu/osdep.h"
#include "libqtest.h"
#include "hw/i386/amd_iommu.h"
#define CMDBUF_ADDR 0x200000
#define CMDBUF_LEN_FIELD 8
#define CMDBUF_ENTRIES (1U << CMDBUF_LEN_FIELD)
static inline uint64_t amdvi_reg_readq(QTestState *s, uint64_t offset)
{
return qtest_readq(s, AMDVI_BASE_ADDR + offset);
}
static inline void amdvi_reg_writeq(QTestState *s, uint64_t offset,
uint64_t val)
{
qtest_writeq(s, AMDVI_BASE_ADDR + offset, val);
}
static void test_cmdbuf_head_wrap(void)
{
QTestState *s;
uint64_t head;
int i;
/* 16 bytes per command */
struct {
uint64_t qw0;
uint64_t qw1;
} cmdbuf[CMDBUF_ENTRIES];
if (!qtest_has_machine("q35")) {
g_test_skip("q35 machine not available");
return;
}
s = qtest_init("-M q35 -device amd-iommu");
/* fill the command buffer with COMPLETION_WAIT (no-op) commands */
for (i = 0; i < CMDBUF_ENTRIES; i++) {
cmdbuf[i].qw0 = (uint64_t)AMDVI_CMD_COMPLETION_WAIT << 60;
cmdbuf[i].qw1 = 0;
}
qtest_memwrite(s, CMDBUF_ADDR, cmdbuf, sizeof(cmdbuf));
/* point the IOMMU at the command buffer and set its length */
amdvi_reg_writeq(s, AMDVI_MMIO_COMMAND_BASE,
CMDBUF_ADDR | ((uint64_t)CMDBUF_LEN_FIELD << 56));
/* enable the IOMMU and its command buffer processor */
amdvi_reg_writeq(s, AMDVI_MMIO_CONTROL,
AMDVI_MMIO_CONTROL_AMDVIEN | AMDVI_MMIO_CONTROL_CMDBUFLEN);
/* advance tail to the last entry, consuming all but the final entry */
amdvi_reg_writeq(s, AMDVI_MMIO_COMMAND_TAIL,
(CMDBUF_ENTRIES - 1) * AMDVI_COMMAND_SIZE);
/* wrap tail to 0, consuming the final entry and completing the buffer */
amdvi_reg_writeq(s, AMDVI_MMIO_COMMAND_TAIL, 0);
/* after consuming all entries the IOMMU must wrap CmdHeadPtr to 0 */
head = amdvi_reg_readq(s, AMDVI_MMIO_COMMAND_HEAD);
g_assert((head & AMDVI_MMIO_CMDBUF_HEAD_MASK) == 0);
qtest_quit(s);
}
int main(int argc, char **argv)
{
g_test_init(&argc, &argv, NULL);
qtest_add_func("/q35/amd-iommu/cmdbuf-head-wrap", test_cmdbuf_head_wrap);
return g_test_run();
}
+23
View File
@@ -464,6 +464,29 @@ bool qvirtqueue_get_buf(QTestState *qts, QVirtQueue *vq, uint32_t *desc_idx,
return true;
}
/*
* qvirtqueue_reset_pool:
* @vq: The virtqueue to reset
*
* Reset the 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.
*
* This is only safe for synchronous test code where requests are
* sent and completed before the next request is issued. Do not use
* with asynchronous code where multiple requests may be in-flight.
*
* Note: This only resets the available descriptor pool (free_head,
* num_free). The used ring position (last_used_idx) is NOT reset
* and should continue to track consumed responses across iterations.
*/
void qvirtqueue_reset_pool(QVirtQueue *vq)
{
vq->free_head = 0;
vq->num_free = vq->size;
}
void qvirtqueue_set_used_event(QTestState *qts, QVirtQueue *vq, uint16_t idx)
{
g_assert(vq->event);
+2
View File
@@ -150,6 +150,8 @@ void qvirtqueue_kick(QTestState *qts, QVirtioDevice *d, QVirtQueue *vq,
bool qvirtqueue_get_buf(QTestState *qts, QVirtQueue *vq, uint32_t *desc_idx,
uint32_t *len);
void qvirtqueue_reset_pool(QVirtQueue *vq);
void qvirtqueue_set_used_event(QTestState *qts, QVirtQueue *vq, uint16_t idx);
void qvirtio_start_device(QVirtioDevice *vdev);
+1
View File
@@ -94,6 +94,7 @@ qtests_i386 = \
(config_all_devices.has_key('CONFIG_SB16') ? ['fuzz-sb16-test'] : []) + \
(config_all_devices.has_key('CONFIG_SDHCI_PCI') ? ['fuzz-sdcard-test'] : []) + \
(config_all_devices.has_key('CONFIG_ESP_PCI') ? ['am53c974-test'] : []) + \
(config_all_devices.has_key('CONFIG_AMD_IOMMU') ? ['amd-iommu-test'] : []) + \
(config_all_devices.has_key('CONFIG_VTD') ? ['intel-iommu-test'] : []) + \
(host_os != 'windows' and \
config_all_devices.has_key('CONFIG_ACPI_ERST') ? ['erst-test'] : []) + \
+69
View File
@@ -14,6 +14,7 @@
#include "qemu/osdep.h"
#include "qemu/module.h"
#include "libqos/virtio.h"
#include "libqos/virtio-9p-client.h"
#define twalk(...) v9fs_twalk((TWalkOpt) __VA_ARGS__)
@@ -752,6 +753,72 @@ static void fs_use_after_unlink(void *obj, void *data,
g_assert_cmpint(attr.size, ==, 2001);
}
/* https://gitlab.com/qemu-project/qemu/-/issues/3358 */
static void fs_deep_absolute_path(void *obj, void *data,
QGuestAllocator *t_alloc)
{
QVirtio9P *v9p = obj;
v9fs_set_allocator(t_alloc);
if (!g_test_slow()) {
g_test_skip("This is a slow test, run with -m slow");
return;
}
GString *path = g_string_new("/");
char name[256];
uint32_t current_fid = 0;
tattach({ .client = v9p });
/* Create deep directory structure until absolute path length
* exceeds 16-bit range.
*/
while (path->len <= 65536) {
/* use 255-byte name (NAME_MAX) to reduce iterations to ~257 */
memset(name, 'A', 255);
name[255] = '\0';
/* create the directory relative to current FID */
tmkdir({
.client = v9p,
.dfid = current_fid,
.name = name
});
/* just for locally tracking the current path length */
g_string_append(path, name);
g_string_append(path, "/");
/* acquire new FID for the newly created directory */
char *wnames[] = { name };
current_fid = twalk({
.client = v9p,
.fid = current_fid,
.nwname = 1,
.wnames = wnames
}).newfid;
/* Reset descriptor pool to avoid exhaustion. The simplified
* virtio test driver does never free descriptors back to the pool
* after use, so we must manually reset it for the required high
* amount of 9p requests here.
*/
qvirtqueue_reset_pool(v9p->vq);
}
/* check if the deepest directory is accessible */
v9fs_attr attr = {};
tgetattr({
.client = v9p,
.fid = current_fid,
.request_mask = P9_GETATTR_BASIC,
.rgetattr.attr = &attr
});
g_string_free(path, TRUE);
}
static void cleanup_9p_local_driver(void *data)
{
/* remove previously created test dir when test is completed */
@@ -819,6 +886,8 @@ static void register_virtio_9p_test(void)
&opts);
qos_add_test("local/use_after_unlink", "virtio-9p", fs_use_after_unlink,
&opts);
qos_add_test("local/deep_absolute_path", "virtio-9p",
fs_deep_absolute_path, &opts);
}
libqos_init(register_virtio_9p_test);
-7
View File
@@ -3,13 +3,6 @@
# SuperH specific tweaks
#
# This triggers failures for sh4-linux about 10% of the time.
# Random SIGSEGV at unpredictable guest address, cause unknown.
run-signals: signals
$(call skip-test, $<, "BROKEN")
run-plugin-signals-with-%:
$(call skip-test, $<, "BROKEN")
VPATH += $(SRC_PATH)/tests/tcg/sh4
test-macl: CFLAGS += -O -g
+1
View File
@@ -48,6 +48,7 @@ tests = {
'test-qapi-util': [],
'test-interval-tree': [],
'test-fifo': [],
'test-envlist': [],
}
if have_system or have_tools
+196
View File
@@ -0,0 +1,196 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
/*
* envlist tests
*
* Copyright 2026 Virtuozzo International GmbH
*
* Authors:
* Denis V. Lunev <den@openvz.org>
*/
#include "qemu/osdep.h"
#include "qemu/envlist.h"
static void free_environ(char **env)
{
char **p;
for (p = env; *p != NULL; p++) {
g_free(*p);
}
g_free(env);
}
static const char *find_env(char **env, const char *name)
{
size_t name_len = strlen(name);
char **p;
for (p = env; *p != NULL; p++) {
if (strncmp(*p, name, name_len) == 0 && (*p)[name_len] == '=') {
return *p + name_len + 1;
}
}
return NULL;
}
static void test_envlist_basic(void)
{
envlist_t *el = envlist_create();
char **env;
size_t count;
/* empty list */
env = envlist_to_environ(el, &count);
g_assert_cmpuint(count, ==, 0);
g_assert_null(env[0]);
free_environ(env);
/* add */
g_assert_cmpint(envlist_setenv(el, "A=1"), ==, 0);
g_assert_cmpint(envlist_setenv(el, "B=2"), ==, 0);
env = envlist_to_environ(el, &count);
g_assert_cmpuint(count, ==, 2);
g_assert_cmpstr(find_env(env, "A"), ==, "1");
g_assert_cmpstr(find_env(env, "B"), ==, "2");
free_environ(env);
/* replace */
g_assert_cmpint(envlist_setenv(el, "A=42"), ==, 0);
env = envlist_to_environ(el, &count);
g_assert_cmpuint(count, ==, 2);
g_assert_cmpstr(find_env(env, "A"), ==, "42");
g_assert_cmpstr(find_env(env, "B"), ==, "2");
free_environ(env);
/* unset existing */
g_assert_cmpint(envlist_unsetenv(el, "A"), ==, 0);
env = envlist_to_environ(el, &count);
g_assert_cmpuint(count, ==, 1);
g_assert_null(find_env(env, "A"));
g_assert_cmpstr(find_env(env, "B"), ==, "2");
free_environ(env);
/* unset non-existing is a no-op success */
g_assert_cmpint(envlist_unsetenv(el, "NOPE"), ==, 0);
env = envlist_to_environ(el, &count);
g_assert_cmpuint(count, ==, 1);
free_environ(env);
envlist_free(el);
}
/*
* envlist_setenv() inserts at the head; envlist_to_environ() walks
* head-to-tail, so the last setenv comes out first.
*/
static void test_envlist_head_insertion_order(void)
{
envlist_t *el = envlist_create();
char **env;
size_t count;
g_assert_cmpint(envlist_setenv(el, "A=1"), ==, 0);
g_assert_cmpint(envlist_setenv(el, "B=2"), ==, 0);
g_assert_cmpint(envlist_setenv(el, "C=3"), ==, 0);
env = envlist_to_environ(el, &count);
g_assert_cmpuint(count, ==, 3);
g_assert_cmpstr(env[0], ==, "C=3");
g_assert_cmpstr(env[1], ==, "B=2");
g_assert_cmpstr(env[2], ==, "A=1");
g_assert_null(env[3]);
free_environ(env);
envlist_free(el);
}
static void test_envlist_einval(void)
{
envlist_t *el = envlist_create();
/* NULL list */
g_assert_cmpint(envlist_setenv(NULL, "A=1"), ==, EINVAL);
g_assert_cmpint(envlist_unsetenv(NULL, "A"), ==, EINVAL);
/* NULL string */
g_assert_cmpint(envlist_setenv(el, NULL), ==, EINVAL);
g_assert_cmpint(envlist_unsetenv(el, NULL), ==, EINVAL);
/* setenv: missing '=' */
g_assert_cmpint(envlist_setenv(el, "NOEQ"), ==, EINVAL);
/* unsetenv: name must not contain '=' */
g_assert_cmpint(envlist_unsetenv(el, "A=B"), ==, EINVAL);
envlist_free(el);
}
/*
* Regression: envlist_unsetenv("FOO") must not remove an entry named
* "FOOBAR" -- the previous strncmp(entry, name, strlen(name)) lookup
* prefix-matched. To trigger the bug, the longer-named entry has to
* be ahead of the target in the list: envlist_setenv() inserts at
* the head, so we add FOO first and FOOBAR last.
*/
static void test_envlist_unsetenv_no_prefix_match(void)
{
envlist_t *el = envlist_create();
char **env;
size_t count;
g_assert_cmpint(envlist_setenv(el, "FOO=y"), ==, 0);
g_assert_cmpint(envlist_setenv(el, "FOOBAR=x"), ==, 0);
g_assert_cmpint(envlist_unsetenv(el, "FOO"), ==, 0);
env = envlist_to_environ(el, &count);
g_assert_cmpuint(count, ==, 1);
g_assert_cmpstr(find_env(env, "FOOBAR"), ==, "x");
g_assert_null(find_env(env, "FOO"));
free_environ(env);
envlist_free(el);
}
/*
* envlist_setenv() must not replace a prior FOOBAR=... entry when
* setting FOO=... The pre-fix code happened to be safe here only
* because it included the trailing '=' byte in its strncmp length;
* this test pins down the post-fix contract that the name boundary
* is a property of the entry, not of the encoded form.
*/
static void test_envlist_setenv_no_prefix_match(void)
{
envlist_t *el = envlist_create();
char **env;
size_t count;
g_assert_cmpint(envlist_setenv(el, "FOOBAR=x"), ==, 0);
g_assert_cmpint(envlist_setenv(el, "FOO=y"), ==, 0);
env = envlist_to_environ(el, &count);
g_assert_cmpuint(count, ==, 2);
g_assert_cmpstr(find_env(env, "FOOBAR"), ==, "x");
g_assert_cmpstr(find_env(env, "FOO"), ==, "y");
free_environ(env);
envlist_free(el);
}
int main(int argc, char *argv[])
{
g_test_init(&argc, &argv, NULL);
g_test_add_func("/envlist/basic", test_envlist_basic);
g_test_add_func("/envlist/head_insertion_order",
test_envlist_head_insertion_order);
g_test_add_func("/envlist/einval", test_envlist_einval);
g_test_add_func("/envlist/unsetenv_no_prefix_match",
test_envlist_unsetenv_no_prefix_match);
g_test_add_func("/envlist/setenv_no_prefix_match",
test_envlist_setenv_no_prefix_match);
return g_test_run();
}
+2
View File
@@ -109,6 +109,8 @@ void sdl2_window_create(struct sdl2_console *scon)
if (scon->opts->gl == DISPLAY_GL_MODE_ES) {
driver = "opengles2";
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK,
SDL_GL_CONTEXT_PROFILE_ES);
}
SDL_SetHint(SDL_HINT_RENDER_DRIVER, driver);
+2
View File
@@ -490,6 +490,8 @@ static int protocol_client_auth_sasl_mechname(VncState *vs, uint8_t *data, size_
char *mechname = g_strndup((const char *) data, len);
trace_vnc_auth_sasl_mech_choose(vs, mechname);
/* If 'data' had embedded NUL the dup'd string might now be shorter */
len = strlen(mechname);
if (strncmp(vs->sasl.mechlist, mechname, len) == 0) {
if (vs->sasl.mechlist[len] != '\0' &&
vs->sasl.mechlist[len] != ',') {
+8 -1
View File
@@ -23,6 +23,7 @@
*/
#include "qemu/osdep.h"
#include "qemu/error-report.h"
#include "vnc.h"
#include "vnc-jobs.h"
@@ -282,10 +283,16 @@ void vnc_client_cut_text_ext(VncState *vs, int32_t len, uint32_t flags, uint8_t
buf && size >= 4) {
uint32_t tsize = read_u32(buf, 0);
uint8_t *tbuf = buf + 4;
if (tsize < size) {
if (tsize <= size - 4) {
qemu_clipboard_set_data(&vs->cbpeer, vs->cbinfo,
QEMU_CLIPBOARD_TYPE_TEXT,
tsize, tbuf, true);
} else {
error_report("vnc: malformed extended clipboard payload "
"with text length %u exceeding available %u",
tsize, size - 4);
vnc_client_error(vs);
return;
}
}
}
+10 -6
View File
@@ -3009,13 +3009,15 @@ void vnc_sent_lossy_rect(VncWorker *worker, int x, int y, int w, int h)
{
int i, j;
w = (x + w) / VNC_STAT_RECT;
h = (y + h) / VNC_STAT_RECT;
w = DIV_ROUND_UP((x + w), VNC_STAT_RECT);
h = DIV_ROUND_UP((y + h), VNC_STAT_RECT);
assert(h <= VNC_STAT_ROWS);
assert(w <= VNC_STAT_COLS);
x /= VNC_STAT_RECT;
y /= VNC_STAT_RECT;
for (j = y; j <= h; j++) {
for (i = x; i <= w; i++) {
for (j = y; j < h; j++) {
for (i = x; i < w; i++) {
worker->lossy_rect[j][i] = 1;
}
}
@@ -3118,12 +3120,14 @@ double vnc_update_freq(VncState *vs, int x, int y, int w, int h)
int i, j;
double total = 0;
int num = 0;
int x_end = x + w;
int y_end = y + h;
x = QEMU_ALIGN_DOWN(x, VNC_STAT_RECT);
y = QEMU_ALIGN_DOWN(y, VNC_STAT_RECT);
for (j = y; j <= y + h; j += VNC_STAT_RECT) {
for (i = x; i <= x + w; i += VNC_STAT_RECT) {
for (j = y; j < y_end; j += VNC_STAT_RECT) {
for (i = x; i < x_end; i += VNC_STAT_RECT) {
total += vnc_stat_rect(vs->vd, i, j)->freq;
num++;
}
+2 -2
View File
@@ -92,8 +92,8 @@ typedef void VncSendHextileTile(VncState *vs,
#define VNC_DIRTY_BPL(x) (sizeof((x)->dirty) / VNC_MAX_HEIGHT * BITS_PER_BYTE)
#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)
#define VNC_STAT_COLS DIV_ROUND_UP(VNC_MAX_WIDTH, VNC_STAT_RECT)
#define VNC_STAT_ROWS DIV_ROUND_UP(VNC_MAX_HEIGHT, VNC_STAT_RECT)
#define VNC_AUTH_CHALLENGE_SIZE 16
+15 -4
View File
@@ -3,7 +3,8 @@
#include "qemu/envlist.h"
struct envlist_entry {
const char *ev_var; /* actual env value */
const char *ev_var; /* actual env value: "NAME=VALUE" */
size_t ev_name_len; /* length of NAME (offset of '=') */
QLIST_ENTRY(envlist_entry) ev_link;
};
@@ -12,6 +13,13 @@ struct envlist {
size_t el_count; /* number of entries */
};
static inline bool envlist_name_eq(const struct envlist_entry *entry,
const char *name, size_t name_len)
{
return entry->ev_name_len == name_len &&
memcmp(entry->ev_var, name, name_len) == 0;
}
/*
* Allocates new envlist and returns pointer to it.
*/
@@ -67,7 +75,7 @@ envlist_setenv(envlist_t *envlist, const char *env)
/* find out first equals sign in given env */
if ((eq_sign = strchr(env, '=')) == NULL)
return (EINVAL);
envname_len = eq_sign - env + 1;
envname_len = eq_sign - env;
/*
* If there already exists variable with given name
@@ -76,8 +84,9 @@ envlist_setenv(envlist_t *envlist, const char *env)
*/
for (entry = envlist->el_entries.lh_first; entry != NULL;
entry = entry->ev_link.le_next) {
if (strncmp(entry->ev_var, env, envname_len) == 0)
if (envlist_name_eq(entry, env, envname_len)) {
break;
}
}
if (entry != NULL) {
@@ -90,6 +99,7 @@ envlist_setenv(envlist_t *envlist, const char *env)
entry = g_malloc(sizeof(*entry));
entry->ev_var = g_strdup(env);
entry->ev_name_len = envname_len;
QLIST_INSERT_HEAD(&envlist->el_entries, entry, ev_link);
return (0);
@@ -119,8 +129,9 @@ envlist_unsetenv(envlist_t *envlist, const char *env)
envname_len = strlen(env);
for (entry = envlist->el_entries.lh_first; entry != NULL;
entry = entry->ev_link.le_next) {
if (strncmp(entry->ev_var, env, envname_len) == 0)
if (envlist_name_eq(entry, env, envname_len)) {
break;
}
}
if (entry != NULL) {
QLIST_REMOVE(entry, ev_link);