Compare commits

...
147 Commits
Author SHA1 Message Date
Michael Tokarev 2e7e8b7eae Update version for 10.2.3 release
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-25 20:13:18 +03:00
Denis V. Lunev 9972a3f283 block/graph-lock: fix missed wakeup in bdrv_graph_co_rdunlock()
tests/qemu-iotests/tests/iothreads-create reproduces the hang on
master under `stress-ng --cpu $(nproc) --timeout 0`.  The iotest's
vm.run_job() times out and qemu stays permanently stuck in
ppoll(timeout=-1) inside bdrv_graph_wrlock_drained -> blk_remove_bs
during qemu_cleanup().  The timing window is narrow on modern
bare-metal hardware and much wider in a VM guest; downstream trees
that still use plain bdrv_graph_wrlock() in blk_remove_bs() hit it
on the first iteration under the same stress.

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

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

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

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

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

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

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

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

This was broken in QEMU 9.0 with commit 3089637.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/2828
Signed-off-by: Alistair Francis <[email protected]>
Reviewed-by: Chao Liu <[email protected]>
Reviewed-by: Nutty Liu <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alistair Francis <[email protected]>
(cherry picked from commit 175afdb0d1)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Alistair Francis c3d2ce5020 target/riscv: Generate access fault if sc comparison fails
The RISC-V spec states:

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

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

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

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

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

Fix by using the relative offset for array indexing.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    newsp = frame - __SIGNAL_FRAMESIZE

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

    newsp = frame - (__SIGNAL_FRAMESIZE + 16)

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

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

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

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

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

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

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

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

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

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

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3420
Signed-off-by: Thomas Huth <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit 3ab47a47d7)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Thomas Huth db373da2a7 hw/misc: Fix the valid access size to the avr-power device
Accessing the device with in non-single byte mode currently causes
QEMU to abort:

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

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

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3393
Signed-off-by: Thomas Huth <[email protected]>
Reviewed-by: Peter Maydell <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit c0306d2b8f)
Signed-off-by: Michael Tokarev <[email protected]>
2026-05-14 22:28:26 +03:00
Vladimir Sementsov-Ogievskiy c4f78bd036 migration: vmstate_save_state_v: fix double error_setg
We may call error_setg twice on same errp if inner
vmstate_save_state_v() or vmstate_save_state() call fails. Next we will
crash on assertion in error_setv().

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

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

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

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

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

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

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

For example, with NASM you get:

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

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

versus

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Fix this by determining the cursor on the resized string.

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

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

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

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

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

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

2) Create qtest input:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Tested with the issue reproducer.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

and the build with fail with

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

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

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

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

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

The execution sequence is illustrated below:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Fix the simple ones reported by shellcheck:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Free s->password in both cleanup paths.

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

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

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

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

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

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

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

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

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

This patch fixes that.

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

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

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

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

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

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

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

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

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

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

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

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

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

and various similar errors.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Fixing this by generating fdt blob in `pnv_init`.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

No files matched your search

+1 -1
View File
@@ -1 +1 @@
10.2.2
10.2.3
+4 -4
View File
@@ -1544,18 +1544,18 @@ tb_page_addr_t get_page_addr_code_hostp(CPUArchState *env, vaddr addr,
(void)probe_access_internal(env_cpu(env), addr, 1, MMU_INST_FETCH,
cpu_mmu_index(env_cpu(env), true), false,
&p, &full, 0, false);
hostp, &full, 0, false);
p = *hostp;
if (p == NULL) {
return -1;
}
if (full->lg_page_size < TARGET_PAGE_BITS) {
*hostp = NULL;
return -1;
}
if (hostp) {
*hostp = p;
}
return qemu_ram_addr_from_host_nofail(p);
}
+3 -2
View File
@@ -82,7 +82,7 @@ void tb_check_watchpoint(CPUState *cpu, uintptr_t retaddr);
* See get_page_addr_code() (full-system version) for documentation on the
* return value.
*
* Sets *@hostp (when @hostp is non-NULL) as follows.
* Sets *@hostp as follows.
* If the return value is -1, sets *@hostp to NULL. Otherwise, sets *@hostp
* to the host address where @addr's content is kept.
*
@@ -105,7 +105,8 @@ tb_page_addr_t get_page_addr_code_hostp(CPUArchState *env, vaddr addr,
static inline tb_page_addr_t get_page_addr_code(CPUArchState *env,
vaddr addr)
{
return get_page_addr_code_hostp(env, addr, NULL);
void *discard;
return get_page_addr_code_hostp(env, addr, &discard);
}
/*
+13 -15
View File
@@ -647,7 +647,7 @@ void tb_lock_page0(tb_page_addr_t address)
if (prot & PAGE_WRITE) {
pageflags_set_clear(start, last, 0, PAGE_WRITE);
mprotect(g2h_untagged(start), last - start + 1,
mprotect(g2h_untagged_vaddr(start), last - start + 1,
prot & (PAGE_READ | PAGE_EXEC) ? PROT_READ : PROT_NONE);
}
}
@@ -734,7 +734,7 @@ int page_unprotect(CPUState *cpu, tb_page_addr_t address, uintptr_t pc)
if (prot & PAGE_EXEC) {
prot = (prot & ~PAGE_EXEC) | PAGE_READ;
}
mprotect((void *)g2h_untagged(start), len, prot & PAGE_RWX);
mprotect((void *)g2h_untagged_vaddr(start), len, prot & PAGE_RWX);
}
mmap_unlock();
@@ -763,7 +763,7 @@ static int probe_access_internal(CPUArchState *env, vaddr addr,
g_assert_not_reached();
}
if (guest_addr_valid_untagged(addr)) {
if (guest_addr_valid_untagged_vaddr(addr)) {
int page_flags = page_get_flags(addr);
if (page_flags & acc_flag) {
if (access_type != MMU_INST_FETCH
@@ -792,7 +792,7 @@ int probe_access_flags(CPUArchState *env, vaddr addr, int size,
g_assert(-(addr | TARGET_PAGE_MASK) >= size);
flags = probe_access_internal(env, addr, size, access_type, nonfault, ra);
*phost = (flags & TLB_INVALID_MASK) ? NULL : g2h(env_cpu(env), addr);
*phost = (flags & TLB_INVALID_MASK) ? NULL : g2h_vaddr(env_cpu(env), addr);
return flags;
}
@@ -805,13 +805,13 @@ void *probe_access(CPUArchState *env, vaddr addr, int size,
flags = probe_access_internal(env, addr, size, access_type, false, ra);
g_assert((flags & ~TLB_MMIO) == 0);
return size ? g2h(env_cpu(env), addr) : NULL;
return size ? g2h_vaddr(env_cpu(env), addr) : NULL;
}
void *tlb_vaddr_to_host(CPUArchState *env, vaddr addr,
MMUAccessType access_type, int mmu_idx)
{
return g2h(env_cpu(env), addr);
return g2h_vaddr(env_cpu(env), addr);
}
tb_page_addr_t get_page_addr_code_hostp(CPUArchState *env, vaddr addr,
@@ -822,9 +822,7 @@ tb_page_addr_t get_page_addr_code_hostp(CPUArchState *env, vaddr addr,
flags = probe_access_internal(env, addr, 1, MMU_INST_FETCH, false, 0);
g_assert(flags == 0);
if (hostp) {
*hostp = g2h_untagged(addr);
}
*hostp = g2h_untagged_vaddr(addr);
return addr;
}
@@ -940,7 +938,7 @@ static void *cpu_mmu_lookup(CPUState *cpu, vaddr addr,
cpu_loop_exit_sigbus(cpu, addr, type, ra);
}
ret = g2h(cpu, addr);
ret = g2h_vaddr(cpu, addr);
set_helper_retaddr(ra);
return ret;
}
@@ -970,7 +968,7 @@ int cpu_memory_rw_debug(CPUState *cpu, vaddr addr,
}
if (is_write) {
if (flags & PAGE_WRITE) {
memcpy(g2h(cpu, addr), buf, l);
memcpy(g2h_vaddr(cpu, addr), buf, l);
} else {
/* Bypass the host page protection using ptrace. */
if (fd == -1) {
@@ -989,13 +987,13 @@ int cpu_memory_rw_debug(CPUState *cpu, vaddr addr,
*/
tb_invalidate_phys_range(NULL, addr, addr + l - 1);
written = pwrite(fd, buf, l,
(off_t)(uintptr_t)g2h_untagged(addr));
(off_t)(uintptr_t)g2h_untagged_vaddr(addr));
if (written != l) {
goto out_close;
}
}
} else if (flags & PAGE_READ) {
memcpy(buf, g2h(cpu, addr), l);
memcpy(buf, g2h_vaddr(cpu, addr), l);
} else {
/* Bypass the host page protection using ptrace. */
if (fd == -1) {
@@ -1005,7 +1003,7 @@ int cpu_memory_rw_debug(CPUState *cpu, vaddr addr,
}
}
if (pread(fd, buf, l,
(off_t)(uintptr_t)g2h_untagged(addr)) != l) {
(off_t)(uintptr_t)g2h_untagged_vaddr(addr)) != l) {
goto out_close;
}
}
@@ -1233,7 +1231,7 @@ static void *atomic_mmu_lookup(CPUState *cpu, vaddr addr, MemOpIdx oi,
cpu_loop_exit_atomic(cpu, retaddr);
}
ret = g2h(cpu, addr);
ret = g2h_vaddr(cpu, addr);
set_helper_retaddr(retaddr);
return ret;
}
+14 -1
View File
@@ -95,6 +95,7 @@ typedef struct BlkdebugRule {
int immediately;
int once;
int64_t offset;
int64_t delay_ns;
} inject;
struct {
int new_state;
@@ -144,6 +145,10 @@ static QemuOptsList inject_error_opts = {
.name = "immediately",
.type = QEMU_OPT_BOOL,
},
{
.name = "delay-ns",
.type = QEMU_OPT_NUMBER,
},
{ /* end of list */ }
},
};
@@ -216,6 +221,8 @@ static int add_rule(void *opaque, QemuOpts *opts, Error **errp)
rule->options.inject.once = qemu_opt_get_bool(opts, "once", 0);
rule->options.inject.immediately =
qemu_opt_get_bool(opts, "immediately", 0);
rule->options.inject.delay_ns =
qemu_opt_get_number(opts, "delay-ns", 0);
sector = qemu_opt_get_number(opts, "sector", -1);
rule->options.inject.offset =
sector == -1 ? -1 : sector * BDRV_SECTOR_SIZE;
@@ -594,6 +601,7 @@ static int coroutine_fn rule_check(BlockDriverState *bs, uint64_t offset,
BlkdebugRule *rule = NULL;
int error;
bool immediately;
int64_t delay_ns;
qemu_mutex_lock(&s->lock);
QSIMPLEQ_FOREACH(rule, &s->active_rules, active_next) {
@@ -608,13 +616,14 @@ static int coroutine_fn rule_check(BlockDriverState *bs, uint64_t offset,
}
}
if (!rule || !rule->options.inject.error) {
if (!rule) {
qemu_mutex_unlock(&s->lock);
return 0;
}
immediately = rule->options.inject.immediately;
error = rule->options.inject.error;
delay_ns = rule->options.inject.delay_ns;
if (rule->options.inject.once) {
QSIMPLEQ_REMOVE(&s->active_rules, rule, BlkdebugRule, active_next);
@@ -622,6 +631,10 @@ static int coroutine_fn rule_check(BlockDriverState *bs, uint64_t offset,
}
qemu_mutex_unlock(&s->lock);
if (delay_ns) {
qemu_co_sleep_ns(QEMU_CLOCK_REALTIME, delay_ns);
}
if (!immediately) {
aio_co_schedule(qemu_get_current_aio_context(), qemu_coroutine_self());
qemu_coroutine_yield();
+34 -13
View File
@@ -82,6 +82,7 @@ struct BlockBackend {
QemuMutex queued_requests_lock; /* protects queued_requests */
CoQueue queued_requests;
bool disable_request_queuing; /* atomic */
int start_request_count; /* atomic */
VMChangeStateEntry *vmsh;
bool force_allow_inactivate;
@@ -1306,10 +1307,16 @@ bool blk_in_drain(BlockBackend *blk)
}
/* To be called between exactly one pair of blk_inc/dec_in_flight() */
static void coroutine_fn blk_wait_while_drained(BlockBackend *blk)
static void coroutine_fn blk_wait_while_drained(BlockBackend *blk,
BdrvRequestFlags flags)
{
assert(blk->in_flight > 0);
if (flags & BDRV_REQ_NO_QUEUE) {
assert(qatomic_read(&blk->start_request_count));
return;
}
if (qatomic_read(&blk->quiesce_counter) &&
!qatomic_read(&blk->disable_request_queuing)) {
/*
@@ -1335,7 +1342,7 @@ blk_co_do_preadv_part(BlockBackend *blk, int64_t offset, int64_t bytes,
BlockDriverState *bs;
IO_CODE();
blk_wait_while_drained(blk);
blk_wait_while_drained(blk, flags);
GRAPH_RDLOCK_GUARD();
/* Call blk_bs() only after waiting, the graph may have changed */
@@ -1410,7 +1417,7 @@ blk_co_do_pwritev_part(BlockBackend *blk, int64_t offset, int64_t bytes,
BlockDriverState *bs;
IO_CODE();
blk_wait_while_drained(blk);
blk_wait_while_drained(blk, flags);
GRAPH_RDLOCK_GUARD();
/* Call blk_bs() only after waiting, the graph may have changed */
@@ -1523,6 +1530,19 @@ void blk_dec_in_flight(BlockBackend *blk)
aio_wait_kick();
}
void coroutine_fn blk_co_start_request(BlockBackend *blk)
{
blk_inc_in_flight(blk);
blk_wait_while_drained(blk, 0);
qatomic_inc(&blk->start_request_count);
}
void blk_end_request(BlockBackend *blk)
{
qatomic_dec(&blk->start_request_count);
blk_dec_in_flight(blk);
}
static void error_callback_bh(void *opaque)
{
struct BlockBackendAIOCB *acb = opaque;
@@ -1741,7 +1761,7 @@ blk_co_do_ioctl(BlockBackend *blk, unsigned long int req, void *buf)
{
IO_CODE();
blk_wait_while_drained(blk);
blk_wait_while_drained(blk, 0);
GRAPH_RDLOCK_GUARD();
if (!blk_co_is_available(blk)) {
@@ -1783,12 +1803,13 @@ BlockAIOCB *blk_aio_ioctl(BlockBackend *blk, unsigned long int req, void *buf,
/* To be called between exactly one pair of blk_inc/dec_in_flight() */
static int coroutine_fn
blk_co_do_pdiscard(BlockBackend *blk, int64_t offset, int64_t bytes)
blk_co_do_pdiscard(BlockBackend *blk, int64_t offset, int64_t bytes,
BdrvRequestFlags flags)
{
int ret;
IO_CODE();
blk_wait_while_drained(blk);
blk_wait_while_drained(blk, flags);
GRAPH_RDLOCK_GUARD();
ret = blk_check_byte_request(blk, offset, bytes);
@@ -1804,7 +1825,7 @@ static void coroutine_fn blk_aio_pdiscard_entry(void *opaque)
BlkAioEmAIOCB *acb = opaque;
BlkRwCo *rwco = &acb->rwco;
rwco->ret = blk_co_do_pdiscard(rwco->blk, rwco->offset, acb->bytes);
rwco->ret = blk_co_do_pdiscard(rwco->blk, rwco->offset, acb->bytes, 0);
blk_aio_complete(acb);
}
@@ -1818,13 +1839,13 @@ BlockAIOCB *blk_aio_pdiscard(BlockBackend *blk,
}
int coroutine_fn blk_co_pdiscard(BlockBackend *blk, int64_t offset,
int64_t bytes)
int64_t bytes, BdrvRequestFlags flags)
{
int ret;
IO_OR_GS_CODE();
blk_inc_in_flight(blk);
ret = blk_co_do_pdiscard(blk, offset, bytes);
ret = blk_co_do_pdiscard(blk, offset, bytes, flags);
blk_dec_in_flight(blk);
return ret;
@@ -1834,7 +1855,7 @@ int coroutine_fn blk_co_pdiscard(BlockBackend *blk, int64_t offset,
static int coroutine_fn blk_co_do_flush(BlockBackend *blk)
{
IO_CODE();
blk_wait_while_drained(blk);
blk_wait_while_drained(blk, 0);
GRAPH_RDLOCK_GUARD();
if (!blk_co_is_available(blk)) {
@@ -2009,7 +2030,7 @@ int coroutine_fn blk_co_zone_report(BlockBackend *blk, int64_t offset,
IO_CODE();
blk_inc_in_flight(blk); /* increase before waiting */
blk_wait_while_drained(blk);
blk_wait_while_drained(blk, 0);
GRAPH_RDLOCK_GUARD();
if (!blk_is_available(blk)) {
blk_dec_in_flight(blk);
@@ -2034,7 +2055,7 @@ int coroutine_fn blk_co_zone_mgmt(BlockBackend *blk, BlockZoneOp op,
IO_CODE();
blk_inc_in_flight(blk);
blk_wait_while_drained(blk);
blk_wait_while_drained(blk, 0);
GRAPH_RDLOCK_GUARD();
ret = blk_check_byte_request(blk, offset, len);
@@ -2058,7 +2079,7 @@ int coroutine_fn blk_co_zone_append(BlockBackend *blk, int64_t *offset,
IO_CODE();
blk_inc_in_flight(blk);
blk_wait_while_drained(blk);
blk_wait_while_drained(blk, flags);
GRAPH_RDLOCK_GUARD();
if (!blk_is_available(blk)) {
blk_dec_in_flight(blk);
+8 -2
View File
@@ -518,6 +518,7 @@ int bdrv_commit(BlockDriverState *bs)
if (!drv)
return -ENOMEDIUM;
bdrv_drain_all_begin();
bdrv_graph_rdlock_main_loop();
backing_file_bs = bdrv_cow_bs(bs);
@@ -549,6 +550,10 @@ int bdrv_commit(BlockDriverState *bs)
BLK_PERM_ALL);
backing = blk_new(ctx, BLK_PERM_WRITE | BLK_PERM_RESIZE, BLK_PERM_ALL);
/* We drained all nodes, but still make requests through BlockBackends */
blk_set_disable_request_queuing(src, true);
blk_set_disable_request_queuing(backing, true);
ret = blk_insert_bs(src, bs, &local_err);
if (ret < 0) {
error_report_err(local_err);
@@ -565,7 +570,7 @@ int bdrv_commit(BlockDriverState *bs)
bdrv_graph_rdunlock_main_loop();
bdrv_graph_wrlock_drained();
bdrv_graph_wrlock();
bdrv_set_backing_hd(commit_top_bs, backing_file_bs, &error_abort);
bdrv_set_backing_hd(bs, commit_top_bs, &error_abort);
bdrv_graph_wrunlock();
@@ -647,7 +652,7 @@ ro_cleanup:
blk_unref(backing);
bdrv_graph_rdunlock_main_loop();
bdrv_graph_wrlock_drained();
bdrv_graph_wrlock();
if (bdrv_cow_bs(bs) != backing_file_bs) {
bdrv_set_backing_hd(bs, backing_file_bs, &error_abort);
}
@@ -663,6 +668,7 @@ ro_cleanup:
out:
bdrv_graph_rdunlock_main_loop();
bdrv_drain_all_end();
return ret;
}
+2
View File
@@ -865,6 +865,7 @@ out_noclean:
g_free(s->cookie);
g_free(s->url);
g_free(s->username);
g_free(s->password);
g_free(s->proxyusername);
g_free(s->proxypassword);
if (s->sockets) {
@@ -976,6 +977,7 @@ static void curl_close(BlockDriverState *bs)
g_free(s->cookie);
g_free(s->url);
g_free(s->username);
g_free(s->password);
g_free(s->proxyusername);
g_free(s->proxypassword);
}
+1 -1
View File
@@ -121,7 +121,7 @@ virtio_blk_discard_write_zeroes(VirtioBlkHandler *handler, struct iovec *iov,
}
if (blk_co_pdiscard(blk, sector << VIRTIO_BLK_SECTOR_BITS,
bytes) == 0) {
bytes, 0) == 0) {
return VIRTIO_BLK_S_OK;
}
}
+5 -7
View File
@@ -278,14 +278,12 @@ void coroutine_fn bdrv_graph_co_rdunlock(void)
smp_mb();
/*
* has_writer == 0: this means reader will read reader_count decreased
* has_writer == 1: we don't know if writer read reader_count old or
* new. Therefore, kick again so on next iteration
* writer will for sure read the updated value.
* Always kick: bdrv_graph_wrlock() zeroes has_writer while polling (to
* let callbacks take the reader lock via the fast path), so we cannot
* rely on has_writer to detect a waiting writer. aio_wait_kick() is a
* no-op when no one is waiting, so it is cheap in the common case.
*/
if (qatomic_read(&has_writer)) {
aio_wait_kick();
}
aio_wait_kick();
}
void bdrv_graph_rdlock_main_loop(void)
+71 -17
View File
@@ -41,9 +41,19 @@ struct qemu_laiocb {
LinuxAioState *ctx;
struct iocb iocb;
ssize_t ret;
off_t offset;
size_t nbytes;
QEMUIOVector *qiov;
bool is_read;
/* For handling short reads/writes */
size_t total_done;
QEMUIOVector resubmit_qiov;
int fd;
int type;
BdrvRequestFlags flags;
uint64_t dev_max_batch;
QSIMPLEQ_ENTRY(qemu_laiocb) next;
};
@@ -68,28 +78,61 @@ struct LinuxAioState {
};
static void ioq_submit(LinuxAioState *s);
static int laio_do_submit(struct qemu_laiocb *laiocb);
static inline ssize_t io_event_ret(struct io_event *ev)
{
return (ssize_t)(((uint64_t)ev->res2 << 32) | ev->res);
}
/**
* Retry tail of short requests.
*/
static int laio_resubmit_short_io(struct qemu_laiocb *laiocb, size_t done)
{
QEMUIOVector *resubmit_qiov = &laiocb->resubmit_qiov;
laiocb->total_done += done;
if (!resubmit_qiov->iov) {
qemu_iovec_init(resubmit_qiov, laiocb->qiov->niov);
} else {
qemu_iovec_reset(resubmit_qiov);
}
qemu_iovec_concat(resubmit_qiov, laiocb->qiov,
laiocb->total_done, laiocb->nbytes - laiocb->total_done);
return laio_do_submit(laiocb);
}
/*
* Completes an AIO request.
*/
static void qemu_laio_process_completion(struct qemu_laiocb *laiocb)
{
int ret;
ssize_t ret;
ret = laiocb->ret;
if (ret != -ECANCELED) {
if (ret == laiocb->nbytes) {
if (ret == laiocb->nbytes - laiocb->total_done) {
ret = 0;
} else if (ret > 0 && (laiocb->type == QEMU_AIO_READ ||
laiocb->type == QEMU_AIO_WRITE)) {
ret = laio_resubmit_short_io(laiocb, ret);
if (!ret) {
return;
}
} else if (ret >= 0) {
/* Short reads mean EOF, pad with zeros. */
if (laiocb->is_read) {
qemu_iovec_memset(laiocb->qiov, ret, 0,
laiocb->qiov->size - ret);
/*
* For normal reads and writes, we only get here if ret == 0, which
* means EOF for reads and ENOSPC for writes.
* For zone-append, we get here with any ret >= 0, which we just
* treat as ENOSPC, too (safer than resubmitting, probably, but not
* 100 % clear).
*/
if (laiocb->type == QEMU_AIO_READ) {
qemu_iovec_memset(laiocb->qiov, laiocb->total_done, 0,
laiocb->qiov->size - laiocb->total_done);
} else {
ret = -ENOSPC;
}
@@ -97,6 +140,9 @@ static void qemu_laio_process_completion(struct qemu_laiocb *laiocb)
}
laiocb->ret = ret;
if (laiocb->resubmit_qiov.iov) {
qemu_iovec_destroy(&laiocb->resubmit_qiov);
}
/*
* If the coroutine is already entered it must be in ioq_submit() and
@@ -367,23 +413,27 @@ static void laio_deferred_fn(void *opaque)
}
}
static int laio_do_submit(int fd, struct qemu_laiocb *laiocb, off_t offset,
int type, BdrvRequestFlags flags,
uint64_t dev_max_batch)
static int laio_do_submit(struct qemu_laiocb *laiocb)
{
LinuxAioState *s = laiocb->ctx;
struct iocb *iocbs = &laiocb->iocb;
QEMUIOVector *qiov = laiocb->qiov;
int fd = laiocb->fd;
off_t offset = laiocb->offset + laiocb->total_done;
switch (type) {
if (laiocb->resubmit_qiov.iov) {
qiov = &laiocb->resubmit_qiov;
}
switch (laiocb->type) {
case QEMU_AIO_WRITE:
#ifdef HAVE_IO_PREP_PWRITEV2
{
int laio_flags = (flags & BDRV_REQ_FUA) ? RWF_DSYNC : 0;
int laio_flags = (laiocb->flags & BDRV_REQ_FUA) ? RWF_DSYNC : 0;
io_prep_pwritev2(iocbs, fd, qiov->iov, qiov->niov, offset, laio_flags);
}
#else
assert(flags == 0);
assert(laiocb->flags == 0);
io_prep_pwritev(iocbs, fd, qiov->iov, qiov->niov, offset);
#endif
break;
@@ -399,7 +449,7 @@ static int laio_do_submit(int fd, struct qemu_laiocb *laiocb, off_t offset,
/* Currently Linux kernel does not support other operations */
default:
fprintf(stderr, "%s: invalid AIO request type 0x%x.\n",
__func__, type);
__func__, laiocb->type);
return -EIO;
}
io_set_eventfd(&laiocb->iocb, event_notifier_get_fd(&s->e));
@@ -407,7 +457,7 @@ static int laio_do_submit(int fd, struct qemu_laiocb *laiocb, off_t offset,
QSIMPLEQ_INSERT_TAIL(&s->io_q.pending, laiocb, next);
s->io_q.in_queue++;
if (!s->io_q.blocked) {
if (s->io_q.in_queue >= laio_max_batch(s, dev_max_batch)) {
if (s->io_q.in_queue >= laio_max_batch(s, laiocb->dev_max_batch)) {
ioq_submit(s);
} else {
defer_call(laio_deferred_fn, s);
@@ -425,14 +475,18 @@ int coroutine_fn laio_co_submit(int fd, uint64_t offset, QEMUIOVector *qiov,
AioContext *ctx = qemu_get_current_aio_context();
struct qemu_laiocb laiocb = {
.co = qemu_coroutine_self(),
.offset = offset,
.nbytes = qiov ? qiov->size : 0,
.ctx = aio_get_linux_aio(ctx),
.ret = -EINPROGRESS,
.is_read = (type == QEMU_AIO_READ),
.qiov = qiov,
.fd = fd,
.type = type,
.flags = flags,
.dev_max_batch = dev_max_batch,
};
ret = laio_do_submit(fd, &laiocb, offset, type, flags, dev_max_batch);
ret = laio_do_submit(&laiocb);
if (ret < 0) {
return ret;
}
+17 -15
View File
@@ -454,7 +454,7 @@ static void coroutine_fn mirror_co_discard(void *opaque)
*op->bytes_handled = op->bytes;
op->is_in_flight = true;
ret = blk_co_pdiscard(op->s->target, op->offset, op->bytes);
ret = blk_co_pdiscard(op->s->target, op->offset, op->bytes, 0);
mirror_write_complete(op, ret);
}
@@ -1276,23 +1276,25 @@ static void mirror_complete(Job *job, Error **errp)
return;
}
/* block all operations on to_replace bs */
if (s->replaces) {
s->to_replace = bdrv_find_node(s->replaces);
if (!s->to_replace) {
error_setg(errp, "Node name '%s' not found", s->replaces);
return;
if (!s->should_complete) {
/* block all operations on to_replace bs */
if (s->replaces) {
s->to_replace = bdrv_find_node(s->replaces);
if (!s->to_replace) {
error_setg(errp, "Node name '%s' not found", s->replaces);
return;
}
/* TODO Translate this into child freeze system. */
error_setg(&s->replace_blocker,
"block device is in use by block-job-complete");
bdrv_op_block_all(s->to_replace, s->replace_blocker);
bdrv_ref(s->to_replace);
}
/* TODO Translate this into child freeze system. */
error_setg(&s->replace_blocker,
"block device is in use by block-job-complete");
bdrv_op_block_all(s->to_replace, s->replace_blocker);
bdrv_ref(s->to_replace);
s->should_complete = true;
}
s->should_complete = true;
/* If the job is paused, it will be re-entered when it is resumed */
WITH_JOB_LOCK_GUARD() {
if (!job->paused) {
@@ -1530,7 +1532,7 @@ do_sync_target_write(MirrorBlockJob *job, MirrorMethod method,
zero_bitmap_end - zero_bitmap_offset);
}
assert(!qiov);
ret = blk_co_pdiscard(job->target, offset, bytes);
ret = blk_co_pdiscard(job->target, offset, bytes, 0);
break;
default:
+60 -19
View File
@@ -391,6 +391,7 @@ void coroutine_fn throttle_group_co_io_limits_intercept(ThrottleGroupMember *tgm
typedef struct {
ThrottleGroupMember *tgm;
ThrottleDirection direction;
bool reset_timer_armed;
} RestartData;
static void coroutine_fn throttle_group_restart_queue_entry(void *opaque)
@@ -403,6 +404,9 @@ static void coroutine_fn throttle_group_restart_queue_entry(void *opaque)
bool empty_queue;
qemu_mutex_lock(&tg->lock);
if (data->reset_timer_armed) {
tg->any_timer_armed[direction] = false;
}
empty_queue = !throttle_group_co_restart_queue(tgm, direction);
/* If the request queue was empty then we have to take care of
@@ -419,18 +423,23 @@ static void coroutine_fn throttle_group_restart_queue_entry(void *opaque)
}
static void throttle_group_restart_queue(ThrottleGroupMember *tgm,
ThrottleDirection direction)
ThrottleDirection direction,
bool reset_timer_armed)
{
Coroutine *co;
RestartData *rd = g_new0(RestartData, 1);
rd->tgm = tgm;
rd->direction = direction;
rd->reset_timer_armed = reset_timer_armed;
/* This function is called when a timer is fired or when
* throttle_group_restart_tgm() is called. Either way, there can
/* If reset_timer_armed is set then this means that this function
* was called when a timer was fired (either from timer_cb() or
* from throttle_group_restart_tgm()). In this case there can
* be no timer pending on this tgm at this point */
assert(!timer_pending(tgm->throttle_timers.timers[direction]));
if (reset_timer_armed) {
assert(!timer_pending(tgm->throttle_timers.timers[direction]));
}
qatomic_inc(&tgm->restart_pending);
@@ -444,15 +453,50 @@ void throttle_group_restart_tgm(ThrottleGroupMember *tgm)
if (tgm->throttle_state) {
for (dir = THROTTLE_READ; dir < THROTTLE_MAX; dir++) {
QEMUTimer *t = tgm->throttle_timers.timers[dir];
QEMUTimer *t;
ThrottleState *ts = tgm->throttle_state;
ThrottleGroup *tg = container_of(ts, ThrottleGroup, ts);
bool reset_timer_armed;
/*
* This function restarts the tgm's queue immediately.
* This is used for example for callers to drain all requests.
* There are three different scenarios depending on whether
* a timer is armed for this tg and which tgm owns the timer.
*/
qemu_mutex_lock(&tg->lock);
t = tgm->throttle_timers.timers[dir];
if (timer_pending(t)) {
/* If there's a pending timer on this tgm, fire it now */
/*
* Case 1: this tgm has a pending timer.
* We can fire the timer immediately.
*/
timer_del(t);
timer_cb(tgm, dir);
reset_timer_armed = true;
} else if (tg->any_timer_armed[dir]) {
/*
* Case 2: another tgm has a pending timer.
* In this case we can still restart the queue but we
* have to leave any_timer_armed untouched so the
* other tgm's timer is not disrupted.
*/
reset_timer_armed = false;
} else {
/* Else run the next request from the queue manually */
throttle_group_restart_queue(tgm, dir);
/*
* Case 3: there is no timer set for this group.
* Here we can simulate a timer that fires immediately,
* so the queue is restarted but no other thread
* can arm a timer in the meantime.
*/
tg->any_timer_armed[dir] = true;
reset_timer_armed = true;
}
qemu_mutex_unlock(&tg->lock);
throttle_group_restart_queue(tgm, dir, reset_timer_armed);
}
}
}
@@ -499,16 +543,13 @@ void throttle_group_get_config(ThrottleGroupMember *tgm, ThrottleConfig *cfg)
*/
static void timer_cb(ThrottleGroupMember *tgm, ThrottleDirection direction)
{
ThrottleState *ts = tgm->throttle_state;
ThrottleGroup *tg = container_of(ts, ThrottleGroup, ts);
/* The timer has just been fired, so we can update the flag */
qemu_mutex_lock(&tg->lock);
tg->any_timer_armed[direction] = false;
qemu_mutex_unlock(&tg->lock);
/* Run the request that was waiting for this timer */
throttle_group_restart_queue(tgm, direction);
/*
* Run the request that was waiting for this timer.
* tg->any_timer_armed needs to be cleared, but we'll do it later
* when the queue is restarted in order to prevent another thread
* from arming the timer before that.
*/
throttle_group_restart_queue(tgm, direction, true);
}
static void read_timer_cb(void *opaque)
+1
View File
@@ -27,6 +27,7 @@
#include "user/abitypes.h"
#include "user/cpu_loop.h"
#include "user/page-protection.h"
#include "user/guest-host.h"
extern char **environ;
+6 -4
View File
@@ -998,7 +998,12 @@ void process_pending_signals(CPUArchState *env)
sigdelset(&ts->signal_mask, target_to_host_signal(sig));
sigact_table[sig - 1]._sa_handler = TARGET_SIG_DFL;
}
/*
* Restart scan from the beginning, as handle_pending_signal
* might have resulted in a new synchronous signal (eg SIGSEGV).
*/
handle_pending_signal(env, sig, &ts->sync_signal);
goto restart_scan;
}
k = ts->sigtab;
@@ -1008,10 +1013,7 @@ void process_pending_signals(CPUArchState *env)
if (k->pending &&
!sigismember(blocked_set, target_to_host_signal(sig))) {
handle_pending_signal(env, sig, k);
/*
* Restart scan from the beginning, as handle_pending_signal
* might have resulted in a new synchronous signal (eg SIGSEGV).
*/
/* Restart scan, explained above. */
goto restart_scan;
}
}
+10 -6
View File
@@ -28,7 +28,7 @@
#include "qapi/error.h"
#include "chardev/char-win.h"
static void win_chr_read(Chardev *chr, DWORD len)
static int win_chr_read(Chardev *chr, DWORD len)
{
WinChardev *s = WIN_CHARDEV(chr);
int max_size = qemu_chr_be_can_write(chr);
@@ -40,7 +40,7 @@ static void win_chr_read(Chardev *chr, DWORD len)
len = max_size;
}
if (len == 0) {
return;
return 0;
}
ZeroMemory(&s->orecv, sizeof(s->orecv));
@@ -56,6 +56,8 @@ static void win_chr_read(Chardev *chr, DWORD len)
if (size > 0) {
qemu_chr_be_write(chr, buf, size);
}
return size > 0 ? 1 : 0;
}
static int win_chr_serial_poll(void *opaque)
@@ -67,8 +69,9 @@ static int win_chr_serial_poll(void *opaque)
ClearCommError(s->file, &comerr, &status);
if (status.cbInQue > 0) {
win_chr_read(chr, status.cbInQue);
return 1;
if (win_chr_read(chr, status.cbInQue)) {
return 1;
}
}
return 0;
}
@@ -147,8 +150,9 @@ int win_chr_pipe_poll(void *opaque)
PeekNamedPipe(s->file, NULL, 0, NULL, &size, NULL);
if (size > 0) {
win_chr_read(chr, size);
return 1;
if (win_chr_read(chr, size)) {
return 1;
}
}
return 0;
}
+2 -1
View File
@@ -705,7 +705,8 @@ static void track_callstack(unsigned int cpu_index, void *udata)
if (fp == caller.frame_pointer) {
/* return */
CallstackEntry e = callstack_pop(cs);
trace_exit_function(t, timestamp, e.pc, callstack_depth(cs));
/* uftrace convention is to use same depth as entry */
trace_exit_function(t, timestamp, e.pc, callstack_depth(cs) + 1);
return;
}
+1 -1
View File
@@ -114,7 +114,7 @@ Rust build dependencies
bindgen tool, which is too big to package and distribute. The minimum
supported version of bindgen is 0.60.x. For distributions that do not
include bindgen or have an older version, it is recommended to install
a newer version using ``cargo install bindgen-cli``.
a newer version using ``cargo install --locked bindgen-cli``.
QEMU requires Rust 1.83.0. This is available on all supported platforms
except for the ``mips64el`` architecture on Debian bookworm. For all other
+7
View File
@@ -1286,6 +1286,13 @@ static int sb16_post_load (void *opaque, int version_id)
{
SB16State *s = opaque;
if (s->in_index < 0 || s->in_index > (int)sizeof(s->in2_data)) {
return -1;
}
if (s->out_data_len < 0 || s->out_data_len > (int)sizeof(s->out_data)) {
return -1;
}
if (s->voice) {
AUD_close_out(s->audio_be, s->voice);
s->voice = NULL;
+67 -33
View File
@@ -38,6 +38,9 @@
#include "hw/virtio/virtio-blk-common.h"
#include "qemu/coroutine.h"
/* Internal buffer size limit for zone report */
#define VIRTIO_BLK_MAX_ZONES_PER_BATCH 4096
static void virtio_blk_ioeventfd_attach(VirtIOBlock *s);
static void virtio_blk_init_request(VirtIOBlock *s, VirtQueue *vq,
@@ -447,15 +450,22 @@ err:
return err_status;
}
typedef struct {
unsigned int total_nr_zones; /* max zones to fill in this request */
unsigned int nr_zones_done; /* how many zones have been filled in */
int64_t iov_offset; /* current byte position in in_iov[] */
int64_t offset; /* current zone report disk offset */
unsigned int nr_zones; /* for zone report calls */
unsigned int zones_per_batch; /* size of zone report buffer */
BlockZoneDescriptor *zones; /* zone report buffer */
} ZoneReportData;
typedef struct ZoneCmdData {
VirtIOBlockReq *req;
struct iovec *in_iov;
unsigned in_num;
union {
struct {
unsigned int nr_zones;
BlockZoneDescriptor *zones;
} zone_report_data;
ZoneReportData zone_report_data;
struct {
int64_t offset;
} zone_append_data;
@@ -512,16 +522,15 @@ static bool check_zoned_request(VirtIOBlock *s, int64_t offset, int64_t len,
static void virtio_blk_zone_report_complete(void *opaque, int ret)
{
ZoneCmdData *data = opaque;
ZoneReportData *zrd = &data->zone_report_data;
VirtIOBlockReq *req = data->req;
VirtIODevice *vdev = VIRTIO_DEVICE(req->dev);
struct iovec *in_iov = data->in_iov;
unsigned in_num = data->in_num;
int64_t zrp_size, n, j = 0;
int64_t nz = data->zone_report_data.nr_zones;
int64_t n;
unsigned nz = zrd->nr_zones;
int8_t err_status = VIRTIO_BLK_S_OK;
struct virtio_blk_zone_report zrp_hdr = (struct virtio_blk_zone_report) {
.nr_zones = cpu_to_le64(nz),
};
struct virtio_blk_zone_report zrp_hdr = {};
trace_virtio_blk_zone_report_complete(vdev, req, nz, ret);
if (ret) {
@@ -529,28 +538,18 @@ static void virtio_blk_zone_report_complete(void *opaque, int ret)
goto out;
}
zrp_size = sizeof(struct virtio_blk_zone_report)
+ sizeof(struct virtio_blk_zone_descriptor) * nz;
n = iov_from_buf(in_iov, in_num, 0, &zrp_hdr, sizeof(zrp_hdr));
if (n != sizeof(zrp_hdr)) {
virtio_error(vdev, "Driver provided input buffer that is too small!");
err_status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
goto out;
}
for (size_t i = sizeof(zrp_hdr); i < zrp_size;
i += sizeof(struct virtio_blk_zone_descriptor), ++j) {
for (unsigned j = 0; j < nz; j++) {
struct virtio_blk_zone_descriptor desc =
(struct virtio_blk_zone_descriptor) {
.z_start = cpu_to_le64(data->zone_report_data.zones[j].start
.z_start = cpu_to_le64(zrd->zones[j].start
>> BDRV_SECTOR_BITS),
.z_cap = cpu_to_le64(data->zone_report_data.zones[j].cap
.z_cap = cpu_to_le64(zrd->zones[j].cap
>> BDRV_SECTOR_BITS),
.z_wp = cpu_to_le64(data->zone_report_data.zones[j].wp
.z_wp = cpu_to_le64(zrd->zones[j].wp
>> BDRV_SECTOR_BITS),
};
switch (data->zone_report_data.zones[j].type) {
switch (zrd->zones[j].type) {
case BLK_ZT_CONV:
desc.z_type = VIRTIO_BLK_ZT_CONV;
break;
@@ -564,7 +563,7 @@ static void virtio_blk_zone_report_complete(void *opaque, int ret)
g_assert_not_reached();
}
switch (data->zone_report_data.zones[j].state) {
switch (zrd->zones[j].state) {
case BLK_ZS_RDONLY:
desc.z_state = VIRTIO_BLK_ZS_RDONLY;
break;
@@ -594,18 +593,47 @@ static void virtio_blk_zone_report_complete(void *opaque, int ret)
}
/* TODO: it takes O(n^2) time complexity. Optimizations required. */
n = iov_from_buf(in_iov, in_num, i, &desc, sizeof(desc));
n = iov_from_buf(in_iov, in_num, zrd->iov_offset, &desc, sizeof(desc));
if (n != sizeof(desc)) {
virtio_error(vdev, "Driver provided input buffer "
"for descriptors that is too small!");
err_status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
goto out;
}
zrd->iov_offset += sizeof(desc);
}
if (nz > 0) {
BlockZoneDescriptor *zone = &zrd->zones[nz - 1];
zrd->offset = zone->start + zone->length;
}
zrd->nr_zones_done += nz;
/* Call zone report again if the end hasn't been reached yet */
if (nz == zrd->zones_per_batch &&
zrd->nr_zones_done < zrd->total_nr_zones) {
zrd->nr_zones = MIN(zrd->zones_per_batch,
zrd->total_nr_zones - zrd->nr_zones_done);
blk_aio_zone_report(req->dev->blk, zrd->offset, &zrd->nr_zones,
zrd->zones, virtio_blk_zone_report_complete, data);
return;
}
/* Fill in header now that all zones have been reported */
zrp_hdr.nr_zones = cpu_to_le64(zrd->nr_zones_done);
n = iov_from_buf(in_iov, in_num, 0, &zrp_hdr, sizeof(zrp_hdr));
if (n != sizeof(zrp_hdr)) {
virtio_error(vdev, "Driver provided input buffer that is too small!");
err_status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
goto out;
}
out:
virtio_blk_req_complete(req, err_status);
g_free(req);
g_free(data->zone_report_data.zones);
g_free(zrd->zones);
g_free(data);
}
@@ -617,7 +645,8 @@ static void virtio_blk_handle_zone_report(VirtIOBlockReq *req,
VirtIODevice *vdev = VIRTIO_DEVICE(s);
unsigned int nr_zones;
ZoneCmdData *data;
int64_t zone_size, offset;
ZoneReportData *zrd;
int64_t offset;
uint8_t err_status;
if (req->in_len < sizeof(struct virtio_blk_inhdr) +
@@ -639,16 +668,21 @@ static void virtio_blk_handle_zone_report(VirtIOBlockReq *req,
trace_virtio_blk_handle_zone_report(vdev, req,
offset >> BDRV_SECTOR_BITS, nr_zones);
zone_size = sizeof(BlockZoneDescriptor) * nr_zones;
data = g_malloc(sizeof(ZoneCmdData));
data->req = req;
data->in_iov = in_iov;
data->in_num = in_num;
data->zone_report_data.nr_zones = nr_zones;
data->zone_report_data.zones = g_malloc(zone_size),
blk_aio_zone_report(s->blk, offset, &data->zone_report_data.nr_zones,
data->zone_report_data.zones,
zrd = &data->zone_report_data;
zrd->total_nr_zones = nr_zones;
zrd->nr_zones_done = 0;
zrd->iov_offset = sizeof(struct virtio_blk_zone_report);
zrd->offset = offset;
zrd->zones_per_batch = MIN(nr_zones, VIRTIO_BLK_MAX_ZONES_PER_BATCH);
zrd->zones = g_malloc(zrd->zones_per_batch * sizeof(BlockZoneDescriptor));
zrd->nr_zones = zrd->zones_per_batch;
blk_aio_zone_report(s->blk, offset, &zrd->nr_zones, zrd->zones,
virtio_blk_zone_report_complete, data);
return;
out:
+6
View File
@@ -170,6 +170,12 @@ static void htif_handle_tohost_write(HTIFState *s, uint64_t val_written)
* begin/end_signature symbols exist.
*/
if (sig_file && begin_sig_addr && end_sig_addr) {
if (end_sig_addr <= begin_sig_addr) {
error_report("Invalid HTIF signature range:"
" begin=0x%" PRIx64 " end=0x%" PRIx64,
begin_sig_addr, end_sig_addr);
return;
}
uint64_t sig_len = end_sig_addr - begin_sig_addr;
char *sig_data = g_malloc(sig_len);
dma_memory_read(&address_space_memory, begin_sig_addr,
+1
View File
@@ -52,6 +52,7 @@ GlobalProperty hw_compat_10_0[] = {
{ "vfio-pci", "x-migration-load-config-after-iter", "off" },
{ "ramfb", "use-legacy-x86-rom", "true"},
{ "vfio-pci-nohotplug", "use-legacy-x86-rom", "true" },
{ "chardev-qemu-vdagent", "x-migration-blocked", "true" },
};
const size_t hw_compat_10_0_len = G_N_ELEMENTS(hw_compat_10_0);
+13 -14
View File
@@ -1995,6 +1995,7 @@ static CXLRetCode media_operations_discovery(uint8_t *payload_in,
} QEMU_PACKED *media_op_in_disc_pl = (void *)payload_in;
struct media_op_discovery_out_pl *media_out_pl =
(struct media_op_discovery_out_pl *)payload_out;
int total = ARRAY_SIZE(media_op_matrix) - 1; /* exclude Discovery */
int num_ops, start_index, i;
int count = 0;
@@ -2011,24 +2012,22 @@ static CXLRetCode media_operations_discovery(uint8_t *payload_in,
* sub class command.
*/
if (media_op_in_disc_pl->dpa_range_count ||
start_index + num_ops > ARRAY_SIZE(media_op_matrix)) {
start_index >= total) {
return CXL_MBOX_INVALID_INPUT;
}
media_out_pl->dpa_range_granularity = CXL_CACHE_LINE_SIZE;
media_out_pl->total_supported_operations =
ARRAY_SIZE(media_op_matrix);
if (num_ops > 0) {
for (i = start_index; i < start_index + num_ops; i++) {
media_out_pl->entry[count].media_op_class =
media_op_matrix[i].media_op_class;
media_out_pl->entry[count].media_op_subclass =
media_op_matrix[i].media_op_subclass;
count++;
if (count == num_ops) {
break;
}
}
media_out_pl->total_supported_operations = total;
num_ops = MIN(num_ops, total - start_index);
for (i = 0; i < num_ops; i++) {
int idx = start_index + i + 1; /* skip Discovery (first entry) */
media_out_pl->entry[count].media_op_class =
media_op_matrix[idx].media_op_class;
media_out_pl->entry[count].media_op_subclass =
media_op_matrix[idx].media_op_subclass;
count++;
}
media_out_pl->num_of_supported_operations = count;
+47 -5
View File
@@ -108,12 +108,34 @@ glue(glue(glue(cirrus_colorexpand_transp_, ROP_NAME), _),DEPTH)
unsigned int col;
unsigned bitmask;
unsigned index;
/*
* Raster ops where the source is a monochrome bitmap with
* color expansion to 8/16/24/32bpp destination.
*/
#if DEPTH == 24
/*
* For packed-24 modes, GR2F bits [4:0] are a count of destination
* bytes to be suppressed for each scanline, which we keep in
* dstskipleft. We want to track the number of whole bytes
* to skip in the source (always either 0 or 1) and the number
* of bits within the byte to skip.
*/
int dstskipleft = s->vga.gr[0x2f] & 0x1f;
int srcskipleft = dstskipleft / 3;
int srcskipleftbits = (dstskipleft / 3) & 0x7;
int srcskipleftbytes = (dstskipleft / 3) >> 3;
#else
int srcskipleft = s->vga.gr[0x2f] & 0x07;
int dstskipleft = srcskipleft * (DEPTH / 8);
/*
* In all other modes, GR2F bits [2:0] are a count of how many
* destination pixels to suppress for each scanline, which is our
* srcskipleftbits. We get dstskipleft, the number of bytes to
* skip, by multiplying this by the bytes-per-pixel. In these
* modes we never need to skip an entire source byte.
*/
int srcskipleftbits = s->vga.gr[0x2f] & 0x07;
int srcskipleftbytes = 0;
int dstskipleft = srcskipleftbits * (DEPTH / 8);
#endif
if (s->cirrus_blt_modeext & CIRRUS_BLTMODEEXT_COLOREXPINV) {
@@ -125,7 +147,8 @@ glue(glue(glue(cirrus_colorexpand_transp_, ROP_NAME), _),DEPTH)
}
for(y = 0; y < bltheight; y++) {
bitmask = 0x80 >> srcskipleft;
bitmask = 0x80 >> srcskipleftbits;
srcaddr += srcskipleftbytes;
bits = cirrus_src(s, srcaddr++) ^ bits_xor;
addr = dstaddr + dstskipleft;
for (x = dstskipleft; x < bltwidth; x += (DEPTH / 8)) {
@@ -191,10 +214,29 @@ glue(glue(glue(cirrus_colorexpand_pattern_transp_, ROP_NAME), _),DEPTH)
int x, y, bitpos, pattern_y;
unsigned int bits, bits_xor;
unsigned int col;
/*
* Copy from an 8x8 monochrome pattern with color expansion.
*/
#if DEPTH == 24
/*
* For packed-24 modes, GR2F bits [4:0] are a count of destination
* bytes to be suppressed for each scanline, which we keep in
* dstskipleft. Our srcskipleft is the number of pixels to skip
* within the 8x8 source pattern to match up with that number
* of suppressed bytes. As the pattern repeats every 8 bits we
* take the number of pixels mod 8.
*/
int dstskipleft = s->vga.gr[0x2f] & 0x1f;
int srcskipleft = dstskipleft / 3;
int srcskipleft = (dstskipleft / 3) & 0x7;
#else
/*
* In all other modes, GR2F bits [2:0] are a count of how many
* destination pixels to suppress for each scanline, which is our
* srcskipleft. We get dstskipleft, the number of bytes to skip,
* by multiplying this by the bytes-per-pixel.
*/
int srcskipleft = s->vga.gr[0x2f] & 0x07;
int dstskipleft = srcskipleft * (DEPTH / 8);
#endif
+3 -3
View File
@@ -712,8 +712,7 @@ static void virgl_cmd_resource_create_blob(VirtIOGPU *g,
return;
}
res = virtio_gpu_virgl_find_resource(g, cblob.resource_id);
if (res) {
if (virtio_gpu_virgl_find_resource(g, cblob.resource_id)) {
qemu_log_mask(LOG_GUEST_ERROR, "%s: resource already exists %d\n",
__func__, cblob.resource_id);
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_RESOURCE_ID;
@@ -766,8 +765,9 @@ static void virgl_cmd_resource_create_blob(VirtIOGPU *g,
res->base.dmabuf_fd = info.fd;
/* Now live, cleaned up in virtio_gpu_virgl_resource_unref */
QTAILQ_INSERT_HEAD(&g->reslist, &res->base, next);
res = NULL;
g_steal_pointer(&res);
}
static void virgl_cmd_resource_map_blob(VirtIOGPU *g,
+25 -11
View File
@@ -227,16 +227,20 @@ void virtio_gpu_get_edid(VirtIOGPU *g,
virtio_gpu_ctrl_response(g, cmd, &edid.hdr, sizeof(edid));
}
static uint32_t calc_image_hostmem(pixman_format_code_t pformat,
uint32_t width, uint32_t height)
static bool calc_image_hostmem(pixman_format_code_t pformat,
uint32_t width, uint32_t height,
uint32_t *hostmem)
{
/* Copied from pixman/pixman-bits-image.c, skip integer overflow check.
* pixman_image_create_bits will fail in case it overflow.
*/
uint64_t bpp = PIXMAN_FORMAT_BPP(pformat);
uint64_t stride = (((uint64_t)width * bpp + 0x1f) >> 5) * sizeof(uint32_t);
uint64_t size = (uint64_t)height * stride;
int bpp = PIXMAN_FORMAT_BPP(pformat);
int stride = ((width * bpp + 0x1f) >> 5) * sizeof(uint32_t);
return height * stride;
if (size > UINT32_MAX) {
return false;
}
*hostmem = size;
return true;
}
static void virtio_gpu_resource_create_2d(VirtIOGPU *g,
@@ -246,6 +250,7 @@ static void virtio_gpu_resource_create_2d(VirtIOGPU *g,
pixman_format_code_t pformat;
struct virtio_gpu_simple_resource *res;
struct virtio_gpu_resource_create_2d c2d;
uint32_t hostmem;
VIRTIO_GPU_FILL_CMD(c2d);
virtio_gpu_bswap_32(&c2d, sizeof(c2d));
@@ -284,7 +289,12 @@ static void virtio_gpu_resource_create_2d(VirtIOGPU *g,
return;
}
res->hostmem = calc_image_hostmem(pformat, c2d.width, c2d.height);
if (!calc_image_hostmem(pformat, c2d.width, c2d.height, &hostmem)) {
qemu_log_mask(LOG_GUEST_ERROR, "%s: image dimensions overflow\n",
__func__);
goto end;
}
res->hostmem = hostmem;
if (res->hostmem + g->hostmem < g->conf_max_hostmem) {
if (!qemu_pixman_image_new_shareable(
&res->image,
@@ -1292,7 +1302,7 @@ static int virtio_gpu_load(QEMUFile *f, void *opaque, size_t size,
VirtIOGPU *g = opaque;
Error *err = NULL;
struct virtio_gpu_simple_resource *res;
uint32_t resource_id, pformat;
uint32_t resource_id, pformat, hostmem;
int i, ret;
g->hostmem = 0;
@@ -1318,7 +1328,11 @@ static int virtio_gpu_load(QEMUFile *f, void *opaque, size_t size,
return -EINVAL;
}
res->hostmem = calc_image_hostmem(pformat, res->width, res->height);
if (!calc_image_hostmem(pformat, res->width, res->height, &hostmem)) {
g_free(res);
return -EINVAL;
}
res->hostmem = hostmem;
if (!qemu_pixman_image_new_shareable(&res->image,
&res->share_handle,
"virtio-gpu res",
+33 -10
View File
@@ -102,6 +102,7 @@ static void pl080_run(PL080State *s)
int size;
uint8_t buff[4];
uint32_t req;
uint32_t next_lli;
s->tc_mask = 0;
for (c = 0; c < s->nchannels; c++) {
@@ -164,40 +165,61 @@ again:
destination widths are different. */
swidth = 1 << ((ch->ctrl >> 18) & 7);
dwidth = 1 << ((ch->ctrl >> 21) & 7);
for (n = 0; n < dwidth; n+= swidth) {
/* Only widths of 1, 2 or 4 are valid */
if (swidth > 4) {
qemu_log_mask(LOG_GUEST_ERROR,
"pl080: channel %d: invalid SWidth %d\n",
c, extract32(ch->ctrl, 18, 3));
continue;
}
if (dwidth > 4) {
qemu_log_mask(LOG_GUEST_ERROR,
"pl080: channel %d: invalid DWidth %d\n",
c, extract32(ch->ctrl, 21, 3));
continue;
}
if ((size * swidth) % dwidth) {
qemu_log_mask(LOG_GUEST_ERROR,
"pl080: channel %d: transfer size mismatch: size=%d swidth=%d dwidth=%d\n",
c, size, swidth, dwidth);
continue;
}
xsize = MAX(swidth, dwidth);
for (n = 0; n < xsize; n += swidth) {
address_space_read(&s->downstream_as, ch->src,
MEMTXATTRS_UNSPECIFIED, buff + n, swidth);
if (ch->ctrl & PL080_CCTRL_SI)
ch->src += swidth;
}
xsize = (dwidth < swidth) ? swidth : dwidth;
/* ??? This may pad the value incorrectly for dwidth < 32. */
for (n = 0; n < xsize; n += dwidth) {
address_space_write(&s->downstream_as, ch->dest + n,
address_space_write(&s->downstream_as, ch->dest,
MEMTXATTRS_UNSPECIFIED, buff + n, dwidth);
if (ch->ctrl & PL080_CCTRL_DI)
ch->dest += swidth;
ch->dest += dwidth;
}
size--;
size -= xsize / swidth;
ch->ctrl = (ch->ctrl & 0xfffff000) | size;
if (size == 0) {
/* Transfer complete. */
if (ch->lli) {
next_lli = (ch->lli & ~3);
if (next_lli) {
ch->src = address_space_ldl_le(&s->downstream_as,
ch->lli,
next_lli,
MEMTXATTRS_UNSPECIFIED,
NULL);
ch->dest = address_space_ldl_le(&s->downstream_as,
ch->lli + 4,
next_lli + 4,
MEMTXATTRS_UNSPECIFIED,
NULL);
ch->ctrl = address_space_ldl_le(&s->downstream_as,
ch->lli + 12,
next_lli + 12,
MEMTXATTRS_UNSPECIFIED,
NULL);
ch->lli = address_space_ldl_le(&s->downstream_as,
ch->lli + 8,
next_lli + 8,
MEMTXATTRS_UNSPECIFIED,
NULL);
} else {
@@ -212,6 +234,7 @@ again:
if (--s->running)
s->running = 1;
}
pl080_update(s);
}
static uint64_t pl080_read(void *opaque, hwaddr offset,
+6 -1
View File
@@ -41,8 +41,13 @@ static uint64_t microbit_i2c_read(void *opaque, hwaddr addr, unsigned int size)
data = 0x01;
break;
case NRF51_TWI_REG_RXD:
/*
* Return the next byte from our fake data sequence. If
* the guest keeps reading the register after that, keep
* returning the same last byte value.
*/
data = twi_read_sequence[s->read_idx];
if (s->read_idx < G_N_ELEMENTS(twi_read_sequence)) {
if (s->read_idx + 1 < G_N_ELEMENTS(twi_read_sequence)) {
s->read_idx++;
}
break;
+53 -62
View File
@@ -420,24 +420,15 @@ typedef struct TrimAIOCB {
QEMUBH *bh;
int ret;
QEMUIOVector *qiov;
BlockAIOCB *aiocb;
int i, j;
bool canceled;
} TrimAIOCB;
static void trim_aio_cancel(BlockAIOCB *acb)
{
TrimAIOCB *iocb = container_of(acb, TrimAIOCB, common);
/* Exit the loop so ide_issue_trim_cb will not continue */
iocb->j = iocb->qiov->niov - 1;
iocb->i = (iocb->qiov->iov[iocb->j].iov_len / 8) - 1;
iocb->ret = -ECANCELED;
if (iocb->aiocb) {
blk_aio_cancel_async(iocb->aiocb);
iocb->aiocb = NULL;
}
/* Exit the loop so ide_trim_co_entry will not continue */
iocb->canceled = true;
}
static const AIOCBInfo trim_aiocb_info = {
@@ -456,65 +447,64 @@ static void ide_trim_bh_cb(void *opaque)
iocb->bh = NULL;
qemu_aio_unref(iocb);
/* Paired with an increment in ide_issue_trim() */
blk_dec_in_flight(blk);
/* Paired with blk_co_start_request in ide_trim_co_entry() */
blk_end_request(blk);
}
static void ide_issue_trim_cb(void *opaque, int ret)
static void coroutine_fn ide_trim_co_entry(void *opaque)
{
TrimAIOCB *iocb = opaque;
IDEState *s = iocb->s;
int i, j;
int ret;
if (iocb->i >= 0) {
if (ret >= 0) {
block_acct_done(blk_get_stats(s->blk), &s->acct);
} else {
block_acct_failed(blk_get_stats(s->blk), &s->acct);
}
}
/* Paired with blk_end_request in ide_trim_bh_cb() */
blk_co_start_request(s->blk);
if (ret >= 0) {
while (iocb->j < iocb->qiov->niov) {
int j = iocb->j;
while (++iocb->i < iocb->qiov->iov[j].iov_len / 8) {
int i = iocb->i;
uint64_t *buffer = iocb->qiov->iov[j].iov_base;
for (j = 0; j < iocb->qiov->niov; j++) {
for (i = 0; i < iocb->qiov->iov[j].iov_len / 8; i++) {
uint64_t *buffer = iocb->qiov->iov[j].iov_base;
/* 6-byte LBA + 2-byte range per entry */
uint64_t entry = le64_to_cpu(buffer[i]);
uint64_t sector = entry & 0x0000ffffffffffffULL;
uint16_t count = entry >> 48;
/* 6-byte LBA + 2-byte range per entry */
uint64_t entry = le64_to_cpu(buffer[i]);
uint64_t sector = entry & 0x0000ffffffffffffULL;
uint16_t count = entry >> 48;
if (count == 0) {
continue;
}
if (!ide_sect_range_ok(s, sector, count)) {
block_acct_invalid(blk_get_stats(s->blk), BLOCK_ACCT_UNMAP);
iocb->ret = -EINVAL;
goto done;
}
block_acct_start(blk_get_stats(s->blk), &s->acct,
count << BDRV_SECTOR_BITS, BLOCK_ACCT_UNMAP);
/* Got an entry! Submit and exit. */
iocb->aiocb = blk_aio_pdiscard(s->blk,
sector << BDRV_SECTOR_BITS,
count << BDRV_SECTOR_BITS,
ide_issue_trim_cb, opaque);
return;
if (count == 0) {
continue;
}
iocb->j++;
iocb->i = -1;
if (iocb->canceled) {
iocb->ret = -ECANCELED;
goto done;
}
if (!ide_sect_range_ok(s, sector, count)) {
block_acct_invalid(blk_get_stats(s->blk), BLOCK_ACCT_UNMAP);
iocb->ret = -EINVAL;
goto done;
}
block_acct_start(blk_get_stats(s->blk), &s->acct,
count << BDRV_SECTOR_BITS, BLOCK_ACCT_UNMAP);
/* Got an entry! Submit and exit. */
ret = blk_co_pdiscard(s->blk,
sector << BDRV_SECTOR_BITS,
count << BDRV_SECTOR_BITS,
BDRV_REQ_NO_QUEUE);
if (ret >= 0) {
block_acct_done(blk_get_stats(s->blk), &s->acct);
} else {
iocb->ret = ret;
block_acct_failed(blk_get_stats(s->blk), &s->acct);
goto done;
}
}
} else {
iocb->ret = ret;
}
iocb->ret = 0;
done:
iocb->aiocb = NULL;
if (iocb->bh) {
replay_bh_schedule_event(iocb->bh);
}
@@ -527,9 +517,7 @@ BlockAIOCB *ide_issue_trim(
IDEState *s = opaque;
IDEDevice *dev = s->unit ? s->bus->slave : s->bus->master;
TrimAIOCB *iocb;
/* Paired with a decrement in ide_trim_bh_cb() */
blk_inc_in_flight(s->blk);
Coroutine *co;
iocb = blk_aio_get(&trim_aiocb_info, s->blk, cb, cb_opaque);
iocb->s = s;
@@ -537,9 +525,11 @@ BlockAIOCB *ide_issue_trim(
&DEVICE(dev)->mem_reentrancy_guard);
iocb->ret = 0;
iocb->qiov = qiov;
iocb->i = -1;
iocb->j = 0;
ide_issue_trim_cb(iocb, 0);
iocb->canceled = false;
co = qemu_coroutine_create(ide_trim_co_entry, iocb);
aio_co_enter(qemu_get_current_aio_context(), co);
return &iocb->common;
}
@@ -799,6 +789,7 @@ static void ide_sector_read(IDEState *s)
s->error = 0; /* not needed by IDE spec, but needed by Windows */
sector_num = ide_get_sector(s);
n = s->nsector;
ide_set_retry(s);
if (n == 0) {
ide_transfer_stop(s);
+33 -2
View File
@@ -1869,9 +1869,40 @@ static void icc_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
* at a priority outside the Non-secure range (128..255), since this
* would otherwise allow malicious NS code to block delivery of S interrupts
* by writing a bad value to these registers.
*
* The NS priority range (128..255) maps to APR bits starting at
* aprbit = 0x80 >> (8 - prebits). Depending on prebits, this boundary
* may fall within AP1R0 or AP1R1, so we cannot simply WI the entire
* register. Instead we calculate which bits within each register
* correspond to the Secure range and preserve those, while allowing
* NS code to modify only the NS range bits.
*
* prebits=4: num_aprs=1, NS starts at AP1R0[8]
* prebits=5: num_aprs=1, NS starts at AP1R0[16]
* prebits=6: num_aprs=2, NS starts at AP1R1[0]
* prebits=7: num_aprs=4, NS starts at AP1R2[0]
*/
if (grp == GICV3_G1NS && regno < 2 && arm_feature(env, ARM_FEATURE_EL3)) {
return;
if (grp == GICV3_G1NS && arm_feature(env, ARM_FEATURE_EL3)) {
int ns_start_bit = 0x80 >> (8 - cs->prebits);
int ns_start_regno = ns_start_bit / 32;
int ns_start_regbit = ns_start_bit % 32;
if (regno < ns_start_regno) {
/* This entire register is in the Secure range: WI */
return;
} else if (regno == ns_start_regno && ns_start_regbit > 0) {
/*
* This register is split: low bits are Secure, high bits are NS.
* Preserve the Secure bits (below ns_start_regbit) from the
* current value, and take the NS bits (at and above
* ns_start_regbit) from the written value.
*/
uint32_t secure_mask = MAKE_64BIT_MASK(0, ns_start_regbit);
value = (cs->icc_apr[grp][regno] & secure_mask) |
(value & ~secure_mask);
}
/* else: regno > ns_start_regno, entire register is NS: allow write */
}
if (cs->nmi_support) {
+6 -4
View File
@@ -131,6 +131,7 @@ static uint64_t riscv_aclint_mtimer_read(void *opaque, hwaddr addr,
addr < (mtimer->timecmp_base + (mtimer->num_harts << 3))) {
size_t hartid = mtimer->hartid_base +
((addr - mtimer->timecmp_base) >> 3);
size_t hartid_offset = hartid - mtimer->hartid_base;
CPUState *cpu = cpu_by_arch_id(hartid);
CPURISCVState *env = cpu ? cpu_env(cpu) : NULL;
if (!env) {
@@ -138,11 +139,11 @@ static uint64_t riscv_aclint_mtimer_read(void *opaque, hwaddr addr,
"aclint-mtimer: invalid hartid: %zu", hartid);
} else if ((addr & 0x7) == 0) {
/* timecmp_lo for RV32/RV64 or timecmp for RV64 */
uint64_t timecmp = mtimer->timecmp[hartid];
uint64_t timecmp = mtimer->timecmp[hartid_offset];
return (size == 4) ? (timecmp & 0xFFFFFFFF) : timecmp;
} else if ((addr & 0x7) == 4) {
/* timecmp_hi */
uint64_t timecmp = mtimer->timecmp[hartid];
uint64_t timecmp = mtimer->timecmp[hartid_offset];
return (timecmp >> 32) & 0xFFFFFFFF;
} else {
qemu_log_mask(LOG_UNIMP,
@@ -174,6 +175,7 @@ static void riscv_aclint_mtimer_write(void *opaque, hwaddr addr,
addr < (mtimer->timecmp_base + (mtimer->num_harts << 3))) {
size_t hartid = mtimer->hartid_base +
((addr - mtimer->timecmp_base) >> 3);
size_t hartid_offset = hartid - mtimer->hartid_base;
CPUState *cpu = cpu_by_arch_id(hartid);
CPURISCVState *env = cpu ? cpu_env(cpu) : NULL;
if (!env) {
@@ -182,7 +184,7 @@ static void riscv_aclint_mtimer_write(void *opaque, hwaddr addr,
} else if ((addr & 0x7) == 0) {
if (size == 4) {
/* timecmp_lo for RV32/RV64 */
uint64_t timecmp_hi = mtimer->timecmp[hartid] >> 32;
uint64_t timecmp_hi = mtimer->timecmp[hartid_offset] >> 32;
riscv_aclint_mtimer_write_timecmp(mtimer, RISCV_CPU(cpu), hartid,
timecmp_hi << 32 | (value & 0xFFFFFFFF));
} else {
@@ -193,7 +195,7 @@ static void riscv_aclint_mtimer_write(void *opaque, hwaddr addr,
} else if ((addr & 0x7) == 4) {
if (size == 4) {
/* timecmp_hi for RV32/RV64 */
uint64_t timecmp_lo = mtimer->timecmp[hartid];
uint64_t timecmp_lo = mtimer->timecmp[hartid_offset];
riscv_aclint_mtimer_write_timecmp(mtimer, RISCV_CPU(cpu), hartid,
value << 32 | (timecmp_lo & 0xFFFFFFFF));
} else {
+8
View File
@@ -26,6 +26,7 @@
*/
#include "qemu/osdep.h"
#include "qemu/log.h"
#include "qapi/error.h"
#include "trace.h"
#include "qemu/timer.h"
@@ -222,6 +223,13 @@ void icp_irq(ICSState *ics, int server, int nr, uint8_t priority)
trace_xics_icp_irq(server, nr, priority);
if (!icp) {
qemu_log_mask(LOG_GUEST_ERROR, "XICS: invalid server %d for IRQ 0x%x\n",
server, nr);
ics_reject(ics, nr);
return;
}
if ((priority >= CPPR(icp))
|| (XISR(icp) && (icp->pending_priority <= priority))) {
ics_reject(ics, nr);
+27 -2
View File
@@ -154,6 +154,14 @@ static bool has_padding(AspeedHACEState *s, struct iovec *iov,
hwaddr req_len, uint32_t *total_msg_len,
uint32_t *pad_offset)
{
/* Need at least 8 bytes to read the total message length field */
if (req_len < 8) {
qemu_log_mask(LOG_GUEST_ERROR,
"%s: invalid request length=0x%" HWADDR_PRIx "\n",
__func__, req_len);
return false;
}
*total_msg_len = (uint32_t)(ldq_be_p(iov->iov_base + req_len - 8) / 8);
/*
* SG_LIST_LEN_LAST asserted in the request length doesn't mean it is the
@@ -197,6 +205,19 @@ static uint64_t hash_get_source_addr(AspeedHACEState *s)
return src_addr;
}
static bool hash_accumulate_len(AspeedHACEState *s, hwaddr plen)
{
if (plen > UINT32_MAX - s->total_req_len) {
qemu_log_mask(LOG_GUEST_ERROR,
"%s: total_req_len overflow, current=0x%x, adding=0x%"
HWADDR_PRIx "\n", __func__, s->total_req_len, plen);
return false;
}
s->total_req_len += plen;
return true;
}
static int hash_prepare_direct_iov(AspeedHACEState *s, struct iovec *iov,
bool acc_mode, bool *acc_final_request)
{
@@ -224,7 +245,9 @@ static int hash_prepare_direct_iov(AspeedHACEState *s, struct iovec *iov,
iov_idx = 1;
if (acc_mode) {
s->total_req_len += plen;
if (!hash_accumulate_len(s, plen)) {
return -1;
}
if (has_padding(s, &iov[0], plen, &total_msg_len,
&pad_offset)) {
@@ -291,7 +314,9 @@ static int hash_prepare_sg_iov(AspeedHACEState *s, struct iovec *iov,
iov[iov_idx].iov_base = haddr;
if (acc_mode) {
s->total_req_len += plen;
if (!hash_accumulate_len(s, plen)) {
return -1;
}
if (has_padding(s, &iov[iov_idx], plen, &total_msg_len,
&pad_offset)) {
+10 -2
View File
@@ -159,9 +159,17 @@ static bool aspeed_sbc_otp_prog(AspeedSBCState *s,
MemTxResult ret;
AspeedOTPState *otp = &s->otp;
uint32_t value = s->regs[R_CAMP1];
uint32_t otp_offset = otp_addr << 2;
ret = address_space_write(&otp->as, otp_addr, MEMTXATTRS_UNSPECIFIED,
&value, sizeof(value));
if (otp_addr >= OTP_TOTAL_DWORD_COUNT) {
qemu_log_mask(LOG_GUEST_ERROR,
"Invalid OTP addr 0x%x\n",
otp_addr);
return false;
}
ret = address_space_write(&otp->as, otp_offset, MEMTXATTRS_UNSPECIFIED,
&value, sizeof(value));
if (ret != MEMTX_OK) {
qemu_log_mask(LOG_GUEST_ERROR,
"Failed to write OTP memory, addr = %x\n",
+3
View File
@@ -73,6 +73,9 @@ static const MemoryRegionOps avr_mask_ops = {
.impl = {
.max_access_size = 1,
},
.valid = {
.max_access_size = 1,
},
};
static void avr_mask_init(Object *dev)
+4
View File
@@ -93,6 +93,10 @@ static const MemoryRegionOps bcm2835_rng_ops = {
.read = bcm2835_rng_read,
.write = bcm2835_rng_write,
.endianness = DEVICE_NATIVE_ENDIAN,
.impl.min_access_size = 4,
.impl.max_access_size = 4,
.valid.min_access_size = 4,
.valid.max_access_size = 4,
};
static const VMStateDescription vmstate_bcm2835_rng = {
+3
View File
@@ -727,6 +727,9 @@ static void allwinner_sun8i_emac_write(void *opaque, hwaddr offset,
break;
case REG_RX_CTL_0: /* Receive Control 0 */
s->rx_ctl0 = value;
if (allwinner_sun8i_emac_can_receive(nc)) {
qemu_flush_queued_packets(nc);
}
break;
case REG_RX_CTL_1: /* Receive Control 1 */
s->rx_ctl1 = value | RX_CTL1_RX_MD;
+8 -2
View File
@@ -624,7 +624,10 @@ static void ftgmac100_do_tx(FTGMAC100State *s, uint64_t tx_ring,
bd.des0 &= ~FTGMAC100_TXDES0_TXDMA_OWN;
/* Write back the modified descriptor. */
ftgmac100_write_bd(&bd, addr);
if (ftgmac100_write_bd(&bd, addr)) {
s->isr |= FTGMAC100_INT_AHB_ERR;
break;
}
/* Advance to the next descriptor. */
if (bd.des0 & s->txdes0_edotr) {
addr = tx_ring;
@@ -1134,7 +1137,10 @@ static ssize_t ftgmac100_receive(NetClientState *nc, const uint8_t *buf,
bd.des0 |= flags | FTGMAC100_RXDES0_LRS;
s->isr |= FTGMAC100_INT_RPKT_BUF;
}
ftgmac100_write_bd(&bd, addr);
if (ftgmac100_write_bd(&bd, addr)) {
s->isr |= FTGMAC100_INT_AHB_ERR;
break;
}
if (bd.des0 & s->rxdes0_edorr) {
addr = s->rx_ring;
} else {
+1
View File
@@ -2054,6 +2054,7 @@ static int of_dpa_cmd_add_l2_flood(OfDpa *of_dpa, OfDpaGroup *group,
err_out:
group->l2_flood.group_count = 0;
g_free(group->l2_flood.group_ids);
group->l2_flood.group_ids = NULL;
g_free(tlvs);
return err;
+23
View File
@@ -2132,6 +2132,26 @@ static int rtl8139_cplus_transmit_one(RTL8139State *s)
hlen, ip->ip_sum);
}
/*
* The code in this function triggers a GCC bug where an
* interaction between -fsanitize=address and -Wstringop-overflow
* results in a false-positive stringop-overflow warning that is
* only emitted when the address sanitizer is enabled:
* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=114494
* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=99673
* GCC incorrectly thinks that the eth_payload_data buffer has
* the type and size of the first field in 'struct ip_header', i.e.
* one byte, and then complains about all other attempts to access
* data in the buffer.
*
* Work around this by disabling the warning when building with
* GCC and the address sanitizer is enabled.
*/
#pragma GCC diagnostic push
#if !defined(__clang__) && defined(QEMU_SANITIZE_ADDRESS)
#pragma GCC diagnostic ignored "-Wstringop-overflow"
#endif
if ((txdw0 & CP_TX_LGSEN) && ip_protocol == IP_PROTO_TCP)
{
/* Large enough for the TCP header? */
@@ -2315,6 +2335,9 @@ static int rtl8139_cplus_transmit_one(RTL8139State *s)
/* restore IP header */
memcpy(eth_payload_data, saved_ip_header, hlen);
}
#pragma GCC diagnostic pop
}
skip_offload:
+5 -3
View File
@@ -5517,7 +5517,7 @@ static void nvme_free_cq(NvmeCQueue *cq, NvmeCtrl *n)
event_notifier_set_handler(&cq->notifier, NULL);
event_notifier_cleanup(&cq->notifier);
}
if (msix_enabled(pci) && cq->irq_enabled) {
if (msix_present(pci) && cq->irq_enabled) {
msix_vector_unuse(pci, cq->vector);
}
if (cq->cqid) {
@@ -5558,7 +5558,7 @@ static void nvme_init_cq(NvmeCQueue *cq, NvmeCtrl *n, uint64_t dma_addr,
{
PCIDevice *pci = PCI_DEVICE(n);
if (msix_enabled(pci) && irq_enabled) {
if (msix_present(pci) && irq_enabled) {
msix_vector_use(pci, vector);
}
@@ -6111,7 +6111,7 @@ static uint16_t nvme_abort(NvmeCtrl *n, NvmeRequest *req)
{
uint16_t sqid = le32_to_cpu(req->cmd.cdw10) & 0xffff;
uint16_t cid = (le32_to_cpu(req->cmd.cdw10) >> 16) & 0xffff;
NvmeSQueue *sq = n->sq[sqid];
NvmeSQueue *sq;
NvmeRequest *r, *next;
int i;
@@ -6120,6 +6120,8 @@ static uint16_t nvme_abort(NvmeCtrl *n, NvmeRequest *req)
return NVME_INVALID_FIELD | NVME_DNR;
}
sq = n->sq[sqid];
if (sqid == 0) {
for (i = 0; i < n->outstanding_aers; i++) {
NvmeRequest *re = n->aer_reqs[i];
+1 -1
View File
@@ -75,7 +75,7 @@ static int nvme_ns_init(NvmeNamespace *ns, Error **errp)
ns->csi = NVME_CSI_NVM;
ns->status = 0x0;
ns->id_ns.dlfeat = 0x1;
ns->id_ns.dlfeat = 0x9;
/* support DULBE and I/O optimization fields */
id_ns->nsfeat |= (NVME_ID_NS_NSFEAT_DAE | NVME_ID_NS_NSFEAT_OPTPERF_ALL);
+6 -7
View File
@@ -57,12 +57,12 @@ static bool valid_program_data(uint32_t otp_addr,
return has_programmable_bits != 0;
}
static bool program_otpmem_data(void *opaque, uint32_t otp_addr,
static bool program_otpmem_data(void *opaque, hwaddr otp_offset,
uint32_t prog_bit, uint32_t *value)
{
AspeedOTPState *s = opaque;
uint32_t otp_addr = otp_offset >> 2;
bool is_odd = otp_addr & 1;
uint32_t otp_offset = otp_addr << 2;
memcpy(value, s->storage + otp_offset, sizeof(uint32_t));
@@ -79,26 +79,25 @@ static bool program_otpmem_data(void *opaque, uint32_t otp_addr,
return true;
}
static void aspeed_otp_write(void *opaque, hwaddr otp_addr,
static void aspeed_otp_write(void *opaque, hwaddr otp_offset,
uint64_t val, unsigned size)
{
AspeedOTPState *s = opaque;
uint32_t otp_offset, value;
uint32_t value;
if (!program_otpmem_data(s, otp_addr, val, &value)) {
if (!program_otpmem_data(s, otp_offset, val, &value)) {
qemu_log_mask(LOG_GUEST_ERROR,
"%s: Failed to program data, value = %x, bit = %"PRIx64"\n",
__func__, value, val);
return;
}
otp_offset = otp_addr << 2;
memcpy(s->storage + otp_offset, &value, size);
if (s->blk) {
if (blk_pwrite(s->blk, otp_offset, size, &value, 0) < 0) {
qemu_log_mask(LOG_GUEST_ERROR,
"%s: Failed to write %x to %x\n",
"%s: Failed to write %x to %"HWADDR_PRIx"\n",
__func__, value, otp_offset);
return;
+1 -1
View File
@@ -517,7 +517,7 @@ static int ppce500_load_device_tree(PPCE500MachineState *pms,
env->icache_line_size);
qemu_fdt_setprop_cell(fdt, cpu_name, "d-cache-size", 0x8000);
qemu_fdt_setprop_cell(fdt, cpu_name, "i-cache-size", 0x8000);
qemu_fdt_setprop_cell(fdt, cpu_name, "bus-frequency", 0);
qemu_fdt_setprop_cell(fdt, cpu_name, "bus-frequency", pmc->bus_freq);
if (cpu->cpu_index) {
qemu_fdt_setprop_string(fdt, cpu_name, "status", "disabled");
qemu_fdt_setprop_string(fdt, cpu_name, "enable-method",
+1
View File
@@ -40,6 +40,7 @@ struct PPCE500MachineClass {
hwaddr pci_mmio_bus_base;
hwaddr spin_base;
uint32_t clock_freq;
uint32_t bus_freq;
uint32_t tb_freq;
};
+1
View File
@@ -94,6 +94,7 @@ static void e500plat_machine_class_init(ObjectClass *oc, const void *data)
pmc->pci_mmio_bus_base = 0xE0000000ULL;
pmc->spin_base = 0xFEF000000ULL;
pmc->clock_freq = PLATFORM_CLK_FREQ_HZ;
pmc->bus_freq = PLATFORM_CLK_FREQ_HZ;
pmc->tb_freq = PLATFORM_CLK_FREQ_HZ;
mc->desc = "generic paravirt e500 platform";
+1
View File
@@ -56,6 +56,7 @@ static void mpc8544ds_machine_class_init(ObjectClass *oc, const void *data)
pmc->pci_pio_base = 0xE1000000ULL;
pmc->spin_base = 0xEF000000ULL;
pmc->clock_freq = PLATFORM_CLK_FREQ_HZ;
pmc->bus_freq = PLATFORM_CLK_FREQ_HZ;
pmc->tb_freq = PLATFORM_CLK_FREQ_HZ;
mc->desc = "mpc8544ds";
+35 -40
View File
@@ -747,51 +747,12 @@ static void pnv_powerdown_notify(Notifier *n, void *opaque)
static void pnv_reset(MachineState *machine, ResetType type)
{
PnvMachineState *pnv = PNV_MACHINE(machine);
IPMIBmc *bmc;
void *fdt;
qemu_devices_reset(type);
/*
* The machine should provide by default an internal BMC simulator.
* If not, try to use the BMC device that was provided on the command
* line.
*/
bmc = pnv_bmc_find(&error_fatal);
if (!pnv->bmc) {
if (!bmc) {
if (!qtest_enabled()) {
warn_report("machine has no BMC device. Use '-device "
"ipmi-bmc-sim,id=bmc0 -device isa-ipmi-bt,bmc=bmc0,irq=10' "
"to define one");
}
} else {
pnv_bmc_set_pnor(bmc, pnv->pnor);
pnv->bmc = bmc;
}
}
if (machine->fdt) {
fdt = machine->fdt;
} else {
fdt = pnv_dt_create(machine);
/* Pack resulting tree */
_FDT((fdt_pack(fdt)));
}
fdt = machine->fdt;
cpu_physical_memory_write(PNV_FDT_ADDR, fdt, fdt_totalsize(fdt));
/* Update machine->fdt with latest fdt */
if (machine->fdt != fdt) {
/*
* Set machine->fdt for 'dumpdtb' QMP/HMP command. Free
* the existing machine->fdt to avoid leaking it during
* a reset.
*/
g_free(machine->fdt);
machine->fdt = fdt;
}
}
static ISABus *pnv_chip_power8_isa_create(PnvChip *chip, Error **errp)
@@ -1001,6 +962,37 @@ static uint64_t pnv_chip_get_ram_size(PnvMachineState *pnv, int chip_id)
return chip_id == 0 ? 1 * GiB : QEMU_ALIGN_DOWN(ram_per_chip, 1 * MiB);
}
static void pnv_machine_init_done(Notifier *notifier, void *data)
{
PnvMachineState *pnv = container_of(notifier, PnvMachineState, machine_init_done);
MachineState *machine = MACHINE(pnv);
IPMIBmc *bmc;
/*
* The machine should provide by default an internal BMC simulator.
* If not, try to use the BMC device that was provided on the command
* line.
*/
bmc = pnv_bmc_find(&error_fatal);
if (!pnv->bmc) {
if (!bmc) {
if (!qtest_enabled()) {
warn_report("machine has no BMC device. Use '-device "
"ipmi-bmc-sim,id=bmc0 -device isa-ipmi-bt,bmc=bmc0,irq=10' "
"to define one");
}
} else {
pnv_bmc_set_pnor(bmc, pnv->pnor);
pnv->bmc = bmc;
}
}
if (!machine->fdt) {
machine->fdt = pnv_dt_create(machine);
_FDT((fdt_pack(machine->fdt)));
}
}
static void pnv_init(MachineState *machine)
{
const char *bios_name = machine->firmware ?: FW_FILE_NAME;
@@ -1260,6 +1252,9 @@ static void pnv_init(MachineState *machine)
if (pmc->i2c_init) {
pmc->i2c_init(pnv);
}
pnv->machine_init_done.notify = pnv_machine_init_done;
qemu_add_machine_init_done_notifier(&pnv->machine_init_done);
}
/*
+6 -1
View File
@@ -35,9 +35,11 @@
#include "hw/riscv/virt.h"
#include "hw/riscv/numa.h"
#include "hw/virtio/virtio-acpi.h"
#include "kvm/kvm_riscv.h"
#include "migration/vmstate.h"
#include "qapi/error.h"
#include "qemu/error-report.h"
#include "system/kvm.h"
#include "system/reset.h"
#define ACPI_BUILD_TABLE_SIZE 0x20000
@@ -296,7 +298,10 @@ static void build_rhct(GArray *table_data,
/* Time Base Frequency */
build_append_int_noprefix(table_data,
RISCV_ACLINT_DEFAULT_TIMEBASE_FREQ, 8);
kvm_enabled() ?
kvm_riscv_get_timebase_frequency(&s->soc->harts[0]) :
RISCV_ACLINT_DEFAULT_TIMEBASE_FREQ,
8);
/* ISA + N hart info */
num_rhct_nodes = 1 + ms->smp.cpus;
+45 -26
View File
@@ -197,6 +197,7 @@ typedef struct lsi_request {
uint8_t *dma_buf;
uint32_t pending;
int out;
bool orphan;
QTAILQ_ENTRY(lsi_request) next;
} lsi_request;
@@ -626,6 +627,8 @@ static void lsi_do_dma(LSIState *s, int out)
uint32_t count;
dma_addr_t addr;
SCSIDevice *dev;
SCSIRequest *req;
lsi_request *p;
if (!s->current || !s->current->dma_len) {
/* Wait until data is available. */
@@ -633,12 +636,14 @@ static void lsi_do_dma(LSIState *s, int out)
return;
}
dev = s->current->req->dev;
p = s->current;
req = scsi_req_ref(s->current->req);
dev = req->dev;
assert(dev);
count = s->dbc;
if (count > s->current->dma_len)
count = s->current->dma_len;
if (count > p->dma_len)
count = p->dma_len;
addr = s->dnad;
/* both 40 and Table Indirect 64-bit DMAs store upper bits in dnad64 */
@@ -653,21 +658,27 @@ static void lsi_do_dma(LSIState *s, int out)
s->csbc += count;
s->dnad += count;
s->dbc -= count;
if (s->current->dma_buf == NULL) {
s->current->dma_buf = scsi_req_get_buf(s->current->req);
if (p->dma_buf == NULL) {
p->dma_buf = scsi_req_get_buf(req);
}
/* ??? Set SFBR to first data byte. */
if (out) {
lsi_mem_read(s, addr, s->current->dma_buf, count);
lsi_mem_read(s, addr, p->dma_buf, count);
} else {
lsi_mem_write(s, addr, s->current->dma_buf, count);
lsi_mem_write(s, addr, p->dma_buf, count);
}
s->current->dma_len -= count;
if (s->current->dma_len == 0) {
s->current->dma_buf = NULL;
scsi_req_continue(s->current->req);
if (p->orphan) {
scsi_req_unref(req);
return;
}
scsi_req_unref(req);
p->dma_len -= count;
if (p->dma_len == 0) {
p->dma_buf = NULL;
scsi_req_continue(req);
} else {
s->current->dma_buf += count;
p->dma_buf += count;
lsi_resume_script(s);
}
}
@@ -743,14 +754,20 @@ static lsi_request *lsi_find_by_tag(LSIState *s, uint32_t tag)
return NULL;
}
static void lsi_request_free(LSIState *s, lsi_request *p)
static void lsi_request_orphan(LSIState *s, lsi_request *p)
{
p->orphan = true;
if (p == s->current) {
s->current = NULL;
} else {
QTAILQ_REMOVE(&s->queue, p, next);
}
g_free(p);
scsi_req_unref(p->req);
}
static void lsi_free_request(SCSIBus *bus, void *priv)
{
g_free(priv);
}
static void lsi_request_cancelled(SCSIRequest *req)
@@ -758,9 +775,7 @@ static void lsi_request_cancelled(SCSIRequest *req)
LSIState *s = LSI53C895A(req->bus->qbus.parent);
lsi_request *p = req->hba_private;
req->hba_private = NULL;
lsi_request_free(s, p);
scsi_req_unref(req);
lsi_request_orphan(s, p);
}
/* Record that data is available for a queued command. Returns zero if
@@ -812,9 +827,7 @@ static void lsi_command_complete(SCSIRequest *req, size_t resid)
}
if (req->hba_private == s->current) {
req->hba_private = NULL;
lsi_request_free(s, s->current);
scsi_req_unref(req);
lsi_request_orphan(s, s->current);
}
if (!stop) {
lsi_resume_script(s);
@@ -825,10 +838,11 @@ static void lsi_command_complete(SCSIRequest *req, size_t resid)
static void lsi_transfer_data(SCSIRequest *req, uint32_t len)
{
LSIState *s = LSI53C895A(req->bus->qbus.parent);
lsi_request *p = req->hba_private;
int out;
assert(req->hba_private);
if (s->waiting == LSI_WAIT_RESELECT || req->hba_private != s->current ||
assert(!p->orphan);
if (s->waiting == LSI_WAIT_RESELECT || p != s->current ||
(lsi_irq_on_rsl(s) && !(s->scntl1 & LSI_SCNTL1_CON))) {
if (lsi_queue_req(s, req, len)) {
return;
@@ -1163,6 +1177,7 @@ static void lsi_execute_script(LSIState *s)
s->waiting = LSI_NOWAIT;
}
object_ref(s);
reentrancy_level++;
s->istat1 |= LSI_ISTAT1_SRUN;
@@ -1182,6 +1197,7 @@ again:
s->waiting = LSI_WAIT_SCRIPTS;
lsi_scripts_timer_start(s);
reentrancy_level--;
object_unref(s);
return;
}
insn = read_dword(s, s->dsp);
@@ -1630,6 +1646,7 @@ again:
trace_lsi_execute_script_stop();
reentrancy_level--;
object_unref(s);
}
static uint8_t lsi_reg_readb(LSIState *s, int offset)
@@ -1946,6 +1963,10 @@ static void lsi_reg_writeb(LSIState *s, int offset, uint8_t val)
CASE_SET_REG32(dsa, 0x10)
case 0x14: /* ISTAT0 */
s->istat0 = (s->istat0 & 0x0f) | (val & 0xf0);
if (val & LSI_ISTAT0_SRST) {
device_cold_reset(DEVICE(s));
return;
}
if (val & LSI_ISTAT0_ABRT) {
lsi_script_dma_interrupt(s, LSI_DSTAT_ABRT);
}
@@ -1959,9 +1980,6 @@ static void lsi_reg_writeb(LSIState *s, int offset, uint8_t val)
s->dsp = s->dnad;
lsi_execute_script(s);
}
if (val & LSI_ISTAT0_SRST) {
device_cold_reset(DEVICE(s));
}
break;
case 0x16: /* MBOX0 */
s->mbox0 = val;
@@ -2316,7 +2334,8 @@ static const struct SCSIBusInfo lsi_scsi_info = {
.transfer_data = lsi_transfer_data,
.complete = lsi_command_complete,
.cancel = lsi_request_cancelled
.cancel = lsi_request_cancelled,
.free_request = lsi_free_request,
};
static void scripts_timer_cb(void *opaque)
+1 -6
View File
@@ -482,12 +482,7 @@ void scsi_bus_legacy_handle_cmdline(SCSIBus *bus)
Location loc;
DriveInfo *dinfo;
int unit;
BlockConf conf = {
.bootindex = -1,
.share_rw = false,
.rerror = BLOCKDEV_ON_ERROR_AUTO,
.werror = BLOCKDEV_ON_ERROR_AUTO,
};
BlockConf conf = DEFAULT_BLOCK_CONF;
loc_push_none(&loc);
for (unit = 0; unit <= bus->info->max_target; unit++) {
+15 -11
View File
@@ -227,16 +227,16 @@ static int virtio_scsi_parse_req(VirtIOSCSIReq *req,
return 0;
}
static VirtIOSCSIReq *virtio_scsi_pop_req(VirtIOSCSI *s, VirtQueue *vq, QemuMutex *vq_lock)
static VirtIOSCSIReq *virtio_scsi_pop_req(VirtIOSCSI *s, VirtQueue *vq, size_t extra_req_size,
QemuMutex *vq_lock)
{
VirtIOSCSICommon *vs = (VirtIOSCSICommon *)s;
VirtIOSCSIReq *req;
if (vq_lock) {
qemu_mutex_lock(vq_lock);
}
req = virtqueue_pop(vq, sizeof(VirtIOSCSIReq) + vs->cdb_size);
req = virtqueue_pop(vq, sizeof(VirtIOSCSIReq) + extra_req_size);
if (vq_lock) {
qemu_mutex_unlock(vq_lock);
@@ -682,7 +682,7 @@ static void virtio_scsi_handle_ctrl_vq(VirtIOSCSI *s, VirtQueue *vq)
{
VirtIOSCSIReq *req;
while ((req = virtio_scsi_pop_req(s, vq, &s->ctrl_lock))) {
while ((req = virtio_scsi_pop_req(s, vq, 0, &s->ctrl_lock))) {
virtio_scsi_handle_ctrl_req(s, req);
}
}
@@ -850,13 +850,14 @@ static void virtio_scsi_fail_cmd_req(VirtIOSCSIReq *req)
virtio_scsi_complete_cmd_req(req);
}
static int virtio_scsi_handle_cmd_req_prepare(VirtIOSCSI *s, VirtIOSCSIReq *req)
static int virtio_scsi_handle_cmd_req_prepare(VirtIOSCSI *s, VirtIOSCSIReq *req,
size_t cdb_size)
{
VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(s);
SCSIDevice *d;
int rc;
rc = virtio_scsi_parse_req(req, sizeof(VirtIOSCSICmdReq) + vs->cdb_size,
rc = virtio_scsi_parse_req(req, sizeof(VirtIOSCSICmdReq) + cdb_size,
sizeof(VirtIOSCSICmdResp) + vs->sense_size);
if (rc < 0) {
if (rc == -ENOTSUP) {
@@ -878,7 +879,7 @@ static int virtio_scsi_handle_cmd_req_prepare(VirtIOSCSI *s, VirtIOSCSIReq *req)
}
req->sreq = scsi_req_new(d, req->req.cmd.tag,
virtio_scsi_get_lun(req->req.cmd.lun),
req->req.cmd.cdb, vs->cdb_size, req);
req->req.cmd.cdb, cdb_size, req);
if (req->sreq->cmd.mode != SCSI_XFER_NONE
&& (req->sreq->cmd.mode != req->mode ||
@@ -913,12 +914,15 @@ static void virtio_scsi_handle_cmd_vq(VirtIOSCSI *s, VirtQueue *vq)
QTAILQ_HEAD(, VirtIOSCSIReq) reqs = QTAILQ_HEAD_INITIALIZER(reqs);
do {
VirtIOSCSICommon *vs = (VirtIOSCSICommon *)s;
size_t cdb_size = qatomic_read(&vs->cdb_size);
if (suppress_notifications) {
virtio_queue_set_notification(vq, 0);
}
while ((req = virtio_scsi_pop_req(s, vq, NULL))) {
ret = virtio_scsi_handle_cmd_req_prepare(s, req);
while ((req = virtio_scsi_pop_req(s, vq, cdb_size, NULL))) {
ret = virtio_scsi_handle_cmd_req_prepare(s, req, cdb_size);
if (!ret) {
QTAILQ_INSERT_TAIL(&reqs, req, next);
} else if (ret == -EINVAL) {
@@ -989,7 +993,7 @@ static void virtio_scsi_set_config(VirtIODevice *vdev,
}
vs->sense_size = virtio_ldl_p(vdev, &scsiconf->sense_size);
vs->cdb_size = virtio_ldl_p(vdev, &scsiconf->cdb_size);
qatomic_set(&vs->cdb_size, virtio_ldl_p(vdev, &scsiconf->cdb_size));
}
static uint64_t virtio_scsi_get_features(VirtIODevice *vdev,
@@ -1050,7 +1054,7 @@ static void virtio_scsi_push_event(VirtIOSCSI *s,
return;
}
req = virtio_scsi_pop_req(s, vs->event_vq, &s->event_lock);
req = virtio_scsi_pop_req(s, vs->event_vq, 0, &s->event_lock);
WITH_QEMU_LOCK_GUARD(&s->event_lock) {
if (!req) {
s->events_dropped = true;
-1
View File
@@ -687,7 +687,6 @@ static void sh7750_mmct_write(void *opaque, hwaddr addr,
break;
case MM_ITLB_DATA:
cpu_sh4_write_mmaped_itlb_data(&s->cpu->env, addr, mem_value);
abort();
break;
case MM_OCACHE_ADDR:
case MM_OCACHE_DATA:
+28 -21
View File
@@ -493,17 +493,18 @@ static void aspeed_smc_flash_setup(AspeedSMCFlash *fl, uint32_t addr)
}
}
static uint64_t aspeed_smc_flash_read(void *opaque, hwaddr addr, unsigned size)
static MemTxResult aspeed_smc_flash_read(void *opaque, hwaddr addr,
uint64_t *data, unsigned size, MemTxAttrs attrs)
{
AspeedSMCFlash *fl = opaque;
AspeedSMCState *s = fl->controller;
uint64_t ret = 0;
int i;
*data = 0;
switch (aspeed_smc_flash_mode(fl)) {
case CTRL_USERMODE:
for (i = 0; i < size; i++) {
ret |= (uint64_t) ssi_transfer(s->spi, 0x0) << (8 * i);
*data |= (uint64_t) ssi_transfer(s->spi, 0x0) << (8 * i);
}
break;
case CTRL_READMODE:
@@ -512,18 +513,19 @@ static uint64_t aspeed_smc_flash_read(void *opaque, hwaddr addr, unsigned size)
aspeed_smc_flash_setup(fl, addr);
for (i = 0; i < size; i++) {
ret |= (uint64_t) ssi_transfer(s->spi, 0x0) << (8 * i);
*data |= (uint64_t) ssi_transfer(s->spi, 0x0) << (8 * i);
}
aspeed_smc_flash_unselect(fl);
break;
default:
aspeed_smc_error("invalid flash mode %d", aspeed_smc_flash_mode(fl));
return MEMTX_ERROR;
}
trace_aspeed_smc_flash_read(fl->cs, addr, size, ret,
trace_aspeed_smc_flash_read(fl->cs, addr, size, *data,
aspeed_smc_flash_mode(fl));
return ret;
return MEMTX_OK;
}
/*
@@ -624,8 +626,8 @@ static bool aspeed_smc_do_snoop(AspeedSMCFlash *fl, uint64_t data,
return false;
}
static void aspeed_smc_flash_write(void *opaque, hwaddr addr, uint64_t data,
unsigned size)
static MemTxResult aspeed_smc_flash_write(void *opaque, hwaddr addr,
uint64_t data, unsigned size, MemTxAttrs attrs)
{
AspeedSMCFlash *fl = opaque;
AspeedSMCState *s = fl->controller;
@@ -636,7 +638,7 @@ static void aspeed_smc_flash_write(void *opaque, hwaddr addr, uint64_t data,
if (!aspeed_smc_is_writable(fl)) {
aspeed_smc_error("flash is not writable at 0x%" HWADDR_PRIx, addr);
return;
return MEMTX_ERROR;
}
switch (aspeed_smc_flash_mode(fl)) {
@@ -661,12 +663,15 @@ static void aspeed_smc_flash_write(void *opaque, hwaddr addr, uint64_t data,
break;
default:
aspeed_smc_error("invalid flash mode %d", aspeed_smc_flash_mode(fl));
return MEMTX_ERROR;
}
return MEMTX_OK;
}
static const MemoryRegionOps aspeed_smc_flash_ops = {
.read = aspeed_smc_flash_read,
.write = aspeed_smc_flash_write,
.read_with_attrs = aspeed_smc_flash_read,
.write_with_attrs = aspeed_smc_flash_write,
.endianness = DEVICE_LITTLE_ENDIAN,
.valid = {
.min_access_size = 1,
@@ -754,7 +759,8 @@ static void aspeed_smc_reset(DeviceState *d)
s->snoop_dummies = 0;
}
static uint64_t aspeed_smc_read(void *opaque, hwaddr addr, unsigned int size)
static MemTxResult aspeed_smc_read(void *opaque, hwaddr addr, uint64_t *data,
unsigned int size, MemTxAttrs attrs)
{
AspeedSMCState *s = ASPEED_SMC(opaque);
AspeedSMCClass *asc = ASPEED_SMC_GET_CLASS(opaque);
@@ -782,12 +788,13 @@ static uint64_t aspeed_smc_read(void *opaque, hwaddr addr, unsigned int size)
trace_aspeed_smc_read(addr << 2, size, s->regs[addr]);
return s->regs[addr];
*data = s->regs[addr];
} else {
qemu_log_mask(LOG_UNIMP, "%s: not implemented: 0x%" HWADDR_PRIx "\n",
__func__, addr);
return -1;
*data = -1;
}
return MEMTX_OK;
}
static uint8_t aspeed_smc_hclk_divisor(uint8_t hclk_mask)
@@ -1108,8 +1115,8 @@ static void aspeed_2600_smc_dma_ctrl(AspeedSMCState *s, uint32_t dma_ctrl)
s->regs[R_DMA_CTRL] &= ~(DMA_CTRL_REQUEST | DMA_CTRL_GRANT);
}
static void aspeed_smc_write(void *opaque, hwaddr addr, uint64_t data,
unsigned int size)
static MemTxResult aspeed_smc_write(void *opaque, hwaddr addr, uint64_t data,
unsigned int size, MemTxAttrs attrs)
{
AspeedSMCState *s = ASPEED_SMC(opaque);
AspeedSMCClass *asc = ASPEED_SMC_GET_CLASS(s);
@@ -1159,13 +1166,13 @@ static void aspeed_smc_write(void *opaque, hwaddr addr, uint64_t data,
} else {
qemu_log_mask(LOG_UNIMP, "%s: not implemented: 0x%" HWADDR_PRIx "\n",
__func__, addr);
return;
}
return MEMTX_OK;
}
static const MemoryRegionOps aspeed_smc_ops = {
.read = aspeed_smc_read,
.write = aspeed_smc_write,
.read_with_attrs = aspeed_smc_read,
.write_with_attrs = aspeed_smc_write,
.endianness = DEVICE_LITTLE_ENDIAN,
};
@@ -2007,8 +2014,8 @@ static const uint32_t aspeed_2700_fmc_resets[ASPEED_SMC_R_MAX] = {
};
static const MemoryRegionOps aspeed_2700_smc_flash_ops = {
.read = aspeed_smc_flash_read,
.write = aspeed_smc_flash_write,
.read_with_attrs = aspeed_smc_flash_read,
.write_with_attrs = aspeed_smc_flash_write,
.endianness = DEVICE_LITTLE_ENDIAN,
.valid = {
.min_access_size = 1,
+15 -9
View File
@@ -180,9 +180,10 @@ static efi_status uefi_vars_check_auth_2_sb(uefi_vars_state *uv,
void *data,
uint64_t data_offset)
{
variable_auth_2 *auth = data;
variable_auth_2 auth;
uefi_variable *siglist;
memcpy(&auth, data, sizeof(auth));
if (custom_mode_is_active(uv)) {
/* no authentication in custom mode */
return EFI_SUCCESS;
@@ -193,7 +194,7 @@ static efi_status uefi_vars_check_auth_2_sb(uefi_vars_state *uv,
return EFI_SUCCESS;
}
if (auth->hdr_length == 24) {
if (auth.hdr_length == (sizeof(auth) - sizeof(auth.timestamp))) {
/* no signature (auth->cert_data is empty) */
return EFI_SECURITY_VIOLATION;
}
@@ -218,23 +219,28 @@ static efi_status uefi_vars_check_auth_2_sb(uefi_vars_state *uv,
efi_status uefi_vars_check_auth_2(uefi_vars_state *uv, uefi_variable *var,
mm_variable_access *va, void *data)
{
variable_auth_2 *auth = data;
variable_auth_2 auth;
uint64_t data_offset;
efi_status status;
if (va->data_size < sizeof(*auth)) {
if (va->data_size < sizeof(auth)) {
return EFI_SECURITY_VIOLATION;
}
if (uadd64_overflow(sizeof(efi_time), auth->hdr_length, &data_offset)) {
memcpy(&auth, data, sizeof(auth));
if (auth.hdr_length < (sizeof(auth) - sizeof(auth.timestamp))) {
return EFI_SECURITY_VIOLATION;
}
if (uadd64_overflow(sizeof(efi_time), auth.hdr_length, &data_offset)) {
return EFI_SECURITY_VIOLATION;
}
if (va->data_size < data_offset) {
return EFI_SECURITY_VIOLATION;
}
if (auth->hdr_revision != 0x0200 ||
auth->hdr_cert_type != WIN_CERT_TYPE_EFI_GUID ||
!qemu_uuid_is_equal(&auth->guid_cert_type, &EfiCertTypePkcs7Guid)) {
if (auth.hdr_revision != 0x0200 ||
auth.hdr_cert_type != WIN_CERT_TYPE_EFI_GUID ||
!qemu_uuid_is_equal(&auth.guid_cert_type, &EfiCertTypePkcs7Guid)) {
return EFI_UNSUPPORTED;
}
@@ -255,7 +261,7 @@ efi_status uefi_vars_check_auth_2(uefi_vars_state *uv, uefi_variable *var,
}
/* checks passed, set variable data */
var->time = auth->timestamp;
var->time = auth.timestamp;
if (va->data_size - data_offset > 0) {
var->data = g_malloc(va->data_size - data_offset);
memcpy(var->data, data + data_offset, va->data_size - data_offset);
+6 -3
View File
@@ -133,9 +133,8 @@ static uint32_t uefi_vars_cmd_mm(uefi_vars_state *uv, bool dma_mode)
uv->buffer, sizeof(*mhdr) + mhdr->length,
MEMTXATTRS_UNSPECIFIED);
} else {
memcpy(uv->pio_xfer_buffer + sizeof(*mhdr),
uv->buffer + sizeof(*mhdr),
sizeof(*mhdr) + mhdr->length);
memcpy(uv->pio_xfer_buffer,
uv->buffer, sizeof(*mhdr) + mhdr->length);
}
return retval;
@@ -230,6 +229,10 @@ static uint64_t uefi_vars_read(void *opaque, hwaddr addr, unsigned size)
uv->pio_xfer_offset += size;
break;
case UEFI_VARS_REG_PIO_BUFFER_CRC32C:
if (uv->pio_xfer_offset > uv->buf_size) {
retval = 0;
break;
}
retval = crc32c(0xffffffff, uv->pio_xfer_buffer, uv->pio_xfer_offset);
break;
case UEFI_VARS_REG_FLAGS:
+14 -9
View File
@@ -21,17 +21,20 @@
*/
static gnutls_datum_t *build_signed_data(mm_variable_access *va, void *data)
{
variable_auth_2 *auth = data;
uint64_t data_offset = sizeof(efi_time) + auth->hdr_length;
variable_auth_2 auth;
uint64_t data_offset;
uint16_t *name = (void *)va + sizeof(mm_variable_access);
gnutls_datum_t *sdata;
uint64_t pos = 0;
memcpy(&auth, data, sizeof(auth));
data_offset = sizeof(efi_time) + auth.hdr_length;
sdata = g_new(gnutls_datum_t, 1);
sdata->size = (va->name_size - 2
+ sizeof(QemuUUID)
+ sizeof(va->attributes)
+ sizeof(auth->timestamp)
+ sizeof(auth.timestamp)
+ va->data_size - data_offset);
sdata->data = g_malloc(sdata->size);
@@ -48,8 +51,8 @@ static gnutls_datum_t *build_signed_data(mm_variable_access *va, void *data)
pos += sizeof(va->attributes);
/* TimeStamp */
memcpy(sdata->data + pos, &auth->timestamp, sizeof(auth->timestamp));
pos += sizeof(auth->timestamp);
memcpy(sdata->data + pos, &auth.timestamp, sizeof(auth.timestamp));
pos += sizeof(auth.timestamp);
/* Variable Content */
memcpy(sdata->data + pos, data + data_offset, va->data_size - data_offset);
@@ -73,7 +76,8 @@ static void wrap_pkcs7(gnutls_datum_t *pkcs7)
};
gnutls_datum_t wrap;
if (pkcs7->data[4] == 0x06 &&
if (pkcs7->size > 16 &&
pkcs7->data[4] == 0x06 &&
pkcs7->data[5] == 0x09 &&
memcmp(pkcs7->data + 6, signed_data_oid, sizeof(signed_data_oid)) == 0 &&
pkcs7->data[15] == 0x0a &&
@@ -104,13 +108,14 @@ static void wrap_pkcs7(gnutls_datum_t *pkcs7)
static gnutls_datum_t *build_pkcs7(void *data)
{
variable_auth_2 *auth = data;
variable_auth_2 auth;
gnutls_datum_t *pkcs7;
memcpy(&auth, data, sizeof(auth));
pkcs7 = g_new(gnutls_datum_t, 1);
pkcs7->size = auth->hdr_length - 24;
pkcs7->size = auth.hdr_length - (sizeof(auth) - sizeof(auth.timestamp));
pkcs7->data = g_malloc(pkcs7->size);
memcpy(pkcs7->data, data + 16 + 24, pkcs7->size);
memcpy(pkcs7->data, data + sizeof(auth), pkcs7->size);
wrap_pkcs7(pkcs7);
+24 -18
View File
@@ -19,13 +19,18 @@
* sometimes when they are not (for example in variable policies).
*/
gboolean uefi_str_is_valid(const uint16_t *str, size_t len,
gboolean uefi_str_is_valid(const uint16_t *str, size_t bytes,
gboolean must_be_null_terminated)
{
size_t chars = bytes / 2;
size_t pos = 0;
if ((bytes % 2) != 0) {
return false;
}
for (;;) {
if (pos == len) {
if (pos == chars) {
if (must_be_null_terminated) {
return false;
} else {
@@ -47,12 +52,13 @@ gboolean uefi_str_is_valid(const uint16_t *str, size_t len,
}
}
size_t uefi_strlen(const uint16_t *str, size_t len)
size_t uefi_strlen(const uint16_t *str, size_t bytes)
{
size_t chars = bytes / 2;
size_t pos = 0;
for (;;) {
if (pos == len) {
if (pos == chars) {
return pos;
}
if (str[pos] == 0) {
@@ -62,25 +68,25 @@ size_t uefi_strlen(const uint16_t *str, size_t len)
}
}
gboolean uefi_str_equal_ex(const uint16_t *a, size_t alen,
const uint16_t *b, size_t blen,
gboolean uefi_str_equal_ex(const uint16_t *a, size_t a_bytes,
const uint16_t *b, size_t b_bytes,
gboolean wildcards_in_a)
{
size_t a_chars = a_bytes / 2;
size_t b_chars = b_bytes / 2;
size_t pos = 0;
alen = alen / 2;
blen = blen / 2;
for (;;) {
if (pos == alen && pos == blen) {
if (pos == a_chars && pos == b_chars) {
return true;
}
if (pos == alen && b[pos] == 0) {
if (pos == a_chars && b[pos] == 0) {
return true;
}
if (pos == blen && a[pos] == 0) {
if (pos == b_chars && a[pos] == 0) {
return true;
}
if (pos == alen || pos == blen) {
if (pos == a_chars || pos == b_chars) {
return false;
}
if (a[pos] == 0 && b[pos] == 0) {
@@ -100,18 +106,18 @@ gboolean uefi_str_equal_ex(const uint16_t *a, size_t alen,
}
}
gboolean uefi_str_equal(const uint16_t *a, size_t alen,
const uint16_t *b, size_t blen)
gboolean uefi_str_equal(const uint16_t *a, size_t a_bytes,
const uint16_t *b, size_t b_bytes)
{
return uefi_str_equal_ex(a, alen, b, blen, false);
return uefi_str_equal_ex(a, a_bytes, b, b_bytes, false);
}
char *uefi_ucs2_to_ascii(const uint16_t *ucs2, uint64_t ucs2_size)
char *uefi_ucs2_to_ascii(const uint16_t *ucs2, uint64_t ucs2_bytes)
{
char *str = g_malloc0(ucs2_size / 2 + 1);
char *str = g_malloc0(ucs2_bytes / 2 + 1);
int i;
for (i = 0; i * 2 < ucs2_size; i++) {
for (i = 0; i * 2 < ucs2_bytes; i++) {
if (ucs2[i] == 0) {
break;
}
+18 -4
View File
@@ -260,6 +260,17 @@ static size_t uefi_vars_mm_error(mm_header *mhdr, mm_variable *mvar,
return sizeof(*mvar);
}
static bool check_buffer_size(uefi_vars_state *uv, uint64_t length)
{
/* uefi_vars_cmd_mm() checks that */
g_assert(uv->buf_size >= sizeof(mm_header));
if (uv->buf_size - sizeof(mm_header) < length) {
return false;
}
return true;
}
static size_t uefi_vars_mm_get_variable(uefi_vars_state *uv, mm_header *mhdr,
mm_variable *mvar, void *func)
{
@@ -307,7 +318,7 @@ static size_t uefi_vars_mm_get_variable(uefi_vars_state *uv, mm_header *mhdr,
if (uadd64_overflow(length, va->data_size, &length)) {
return uefi_vars_mm_error(mhdr, mvar, EFI_BAD_BUFFER_SIZE);
}
if (uv->buf_size < length) {
if (!check_buffer_size(uv, length)) {
return uefi_vars_mm_error(mhdr, mvar, EFI_BAD_BUFFER_SIZE);
}
@@ -377,7 +388,7 @@ uefi_vars_mm_get_next_variable(uefi_vars_state *uv, mm_header *mhdr,
}
length = sizeof(*mvar) + sizeof(*nv) + var->name_size;
if (uv->buf_size < length) {
if (!check_buffer_size(uv, length)) {
return uefi_vars_mm_error(mhdr, mvar, EFI_BAD_BUFFER_SIZE);
}
@@ -567,7 +578,7 @@ static size_t uefi_vars_mm_variable_info(uefi_vars_state *uv, mm_header *mhdr,
uint64_t length;
length = sizeof(*mvar) + sizeof(*vi);
if (uv->buf_size < length) {
if (!check_buffer_size(uv, length)) {
return uefi_vars_mm_error(mhdr, mvar, EFI_BAD_BUFFER_SIZE);
}
@@ -588,7 +599,7 @@ uefi_vars_mm_get_payload_size(uefi_vars_state *uv, mm_header *mhdr,
uint64_t length;
length = sizeof(*mvar) + sizeof(*ps);
if (uv->buf_size < length) {
if (!check_buffer_size(uv, length)) {
return uefi_vars_mm_error(mhdr, mvar, EFI_BAD_BUFFER_SIZE);
}
@@ -618,6 +629,9 @@ uefi_vars_mm_lock_variable(uefi_vars_state *uv, mm_header *mhdr,
if (mhdr->length < length) {
return uefi_vars_mm_error(mhdr, mvar, EFI_BAD_BUFFER_SIZE);
}
if (sizeof(*pe) + lv->name_size > UINT16_MAX) {
return uefi_vars_mm_error(mhdr, mvar, EFI_BAD_BUFFER_SIZE);
}
uefi_trace_variable(__func__, lv->guid, name, lv->name_size);
+4
View File
@@ -101,6 +101,10 @@ static int ufs_emulate_report_luns(UfsRequest *req, uint8_t *outbuf,
return SCSI_COMMAND_FAIL;
}
if (outbuf_len < 8) {
return SCSI_COMMAND_FAIL;
}
memset(outbuf, 0, 8);
len += 8;
for (uint8_t lun = 0; lun < UFS_MAX_LUS; ++lun) {
+3
View File
@@ -40,10 +40,13 @@ ufs_err_mcq_db_wr_invalid_sqid(uint8_t qid) "invalid mcq sqid %"PRIu8""
ufs_err_mcq_db_wr_invalid_db(uint8_t qid, uint32_t db) "invalid mcq doorbell sqid %"PRIu8", db %"PRIu32""
ufs_err_mcq_create_sq_invalid_sqid(uint8_t qid) "invalid mcq sqid %"PRIu8""
ufs_err_mcq_create_sq_invalid_cqid(uint8_t qid) "invalid mcq cqid %"PRIu8""
ufs_err_mcq_create_sq_invalid_size(uint8_t qid) "invalid mcq sq size for sqid %"PRIu8""
ufs_err_mcq_create_sq_already_exists(uint8_t qid) "mcq sqid %"PRIu8 "already exists"
ufs_err_mcq_delete_sq_invalid_sqid(uint8_t qid) "invalid mcq sqid %"PRIu8""
ufs_err_mcq_delete_sq_not_exists(uint8_t qid) "mcq sqid %"PRIu8 "not exists"
ufs_err_mcq_delete_sq_busy(uint8_t qid) "mcq sqid %"PRIu8" has outstanding requests"
ufs_err_mcq_create_cq_invalid_cqid(uint8_t qid) "invalid mcq cqid %"PRIu8""
ufs_err_mcq_create_cq_invalid_size(uint8_t qid) "invalid mcq cq size for cqid %"PRIu8""
ufs_err_mcq_create_cq_already_exists(uint8_t qid) "mcq cqid %"PRIu8 "already exists"
ufs_err_mcq_delete_cq_invalid_cqid(uint8_t qid) "invalid mcq cqid %"PRIu8""
ufs_err_mcq_delete_cq_not_exists(uint8_t qid) "mcq cqid %"PRIu8 "not exists"
+81 -11
View File
@@ -506,6 +506,8 @@ static bool ufs_mcq_create_sq(UfsHc *u, uint8_t qid, uint32_t attr)
UfsMcqReg *reg = &u->mcq_reg[qid];
UfsSq *sq;
uint8_t cqid = FIELD_EX32(attr, SQATTR, CQID);
uint16_t qsize =
((FIELD_EX32(attr, SQATTR, SIZE) + 1) << 2) / sizeof(UfsSqEntry);
if (qid >= u->params.mcq_maxq) {
trace_ufs_err_mcq_create_sq_invalid_sqid(qid);
@@ -517,8 +519,18 @@ static bool ufs_mcq_create_sq(UfsHc *u, uint8_t qid, uint32_t attr)
return false;
}
if (cqid >= u->params.mcq_maxq) {
trace_ufs_err_mcq_create_sq_invalid_cqid(cqid);
return false;
}
if (!u->cq[cqid]) {
trace_ufs_err_mcq_create_sq_invalid_cqid(qid);
trace_ufs_err_mcq_create_sq_invalid_cqid(cqid);
return false;
}
if (!qsize) {
trace_ufs_err_mcq_create_sq_invalid_size(qid);
return false;
}
@@ -527,7 +539,7 @@ static bool ufs_mcq_create_sq(UfsHc *u, uint8_t qid, uint32_t attr)
sq->sqid = qid;
sq->cq = u->cq[cqid];
sq->addr = ((uint64_t)reg->squba << 32) | reg->sqlba;
sq->size = ((FIELD_EX32(attr, SQATTR, SIZE) + 1) << 2) / sizeof(UfsSqEntry);
sq->size = qsize;
sq->bh = qemu_bh_new_guarded(ufs_mcq_process_sq, sq,
&DEVICE(u)->mem_reentrancy_guard);
@@ -544,6 +556,31 @@ static bool ufs_mcq_create_sq(UfsHc *u, uint8_t qid, uint32_t attr)
return true;
}
static bool ufs_mcq_sq_has_outstanding_req(UfsSq *sq)
{
UfsRequest *req;
uint16_t free_reqs = 0;
QTAILQ_FOREACH(req, &sq->req_list, entry)
{
free_reqs++;
}
return free_reqs != sq->size;
}
static void ufs_mcq_free_sq(UfsSq *sq)
{
qemu_bh_delete(sq->bh);
for (int i = 0; i < sq->size; i++) {
ufs_clear_req(&sq->req[i]);
}
g_free(sq->req);
g_free(sq);
}
static bool ufs_mcq_delete_sq(UfsHc *u, uint8_t qid)
{
UfsSq *sq;
@@ -560,9 +597,12 @@ static bool ufs_mcq_delete_sq(UfsHc *u, uint8_t qid)
sq = u->sq[qid];
qemu_bh_delete(sq->bh);
g_free(sq->req);
g_free(sq);
if (ufs_mcq_sq_has_outstanding_req(sq)) {
trace_ufs_err_mcq_delete_sq_busy(qid);
return false;
}
ufs_mcq_free_sq(sq);
u->sq[qid] = NULL;
return true;
}
@@ -571,6 +611,8 @@ static bool ufs_mcq_create_cq(UfsHc *u, uint8_t qid, uint32_t attr)
{
UfsMcqReg *reg = &u->mcq_reg[qid];
UfsCq *cq;
uint16_t qsize =
((FIELD_EX32(attr, CQATTR, SIZE) + 1) << 2) / sizeof(UfsCqEntry);
if (qid >= u->params.mcq_maxq) {
trace_ufs_err_mcq_create_cq_invalid_cqid(qid);
@@ -582,11 +624,16 @@ static bool ufs_mcq_create_cq(UfsHc *u, uint8_t qid, uint32_t attr)
return false;
}
if (!qsize) {
trace_ufs_err_mcq_create_cq_invalid_size(qid);
return false;
}
cq = g_malloc0(sizeof(*cq));
cq->u = u;
cq->cqid = qid;
cq->addr = ((uint64_t)reg->cquba << 32) | reg->cqlba;
cq->size = ((FIELD_EX32(attr, CQATTR, SIZE) + 1) << 2) / sizeof(UfsCqEntry);
cq->size = qsize;
cq->bh = qemu_bh_new_guarded(ufs_mcq_process_cq, cq,
&DEVICE(u)->mem_reentrancy_guard);
@@ -598,6 +645,12 @@ static bool ufs_mcq_create_cq(UfsHc *u, uint8_t qid, uint32_t attr)
return true;
}
static void ufs_mcq_free_cq(UfsCq *cq)
{
qemu_bh_delete(cq->bh);
g_free(cq);
}
static bool ufs_mcq_delete_cq(UfsHc *u, uint8_t qid)
{
UfsCq *cq;
@@ -621,8 +674,7 @@ static bool ufs_mcq_delete_cq(UfsHc *u, uint8_t qid)
cq = u->cq[qid];
qemu_bh_delete(cq->bh);
g_free(cq);
ufs_mcq_free_cq(cq);
u->cq[qid] = NULL;
return true;
}
@@ -775,6 +827,11 @@ static void ufs_mcq_process_db(UfsHc *u, uint8_t qid, uint32_t db)
}
sq = u->sq[qid];
if (!sq) {
trace_ufs_err_mcq_db_wr_invalid_sqid(qid);
return;
}
if (sq->size * sizeof(UfsSqEntry) <= db) {
trace_ufs_err_mcq_db_wr_invalid_db(qid, db);
return;
@@ -788,7 +845,14 @@ static void ufs_write_mcq_op_reg(UfsHc *u, hwaddr offset, uint32_t data,
unsigned size)
{
int qid = offset / sizeof(UfsMcqOpReg);
UfsMcqOpReg *opr = &u->mcq_op_reg[qid];
UfsMcqOpReg *opr;
if (qid >= u->params.mcq_maxq) {
trace_ufs_err_invalid_register_offset(offset);
return;
}
opr = &u->mcq_op_reg[qid];
switch (offset % sizeof(UfsMcqOpReg)) {
case offsetof(UfsMcqOpReg, sq.tp):
@@ -800,6 +864,10 @@ static void ufs_write_mcq_op_reg(UfsHc *u, hwaddr offset, uint32_t data,
case offsetof(UfsMcqOpReg, cq.hp): {
UfsCq *cq = u->cq[qid];
if (!cq) {
break;
}
if (ufs_mcq_cq_full(u, qid) && !QTAILQ_EMPTY(&cq->req_list)) {
/* Enqueueing to CQ was blocked because it was full */
qemu_bh_schedule(cq->bh);
@@ -1849,12 +1917,14 @@ static void ufs_exit(PCIDevice *pci_dev)
for (int i = 0; i < ARRAY_SIZE(u->sq); i++) {
if (u->sq[i]) {
ufs_mcq_delete_sq(u, i);
ufs_mcq_free_sq(u->sq[i]);
u->sq[i] = NULL;
}
}
for (int i = 0; i < ARRAY_SIZE(u->cq); i++) {
if (u->cq[i]) {
ufs_mcq_delete_cq(u, i);
ufs_mcq_free_cq(u->cq[i]);
u->cq[i] = NULL;
}
}
}
+8 -1
View File
@@ -203,7 +203,14 @@ static inline bool ufs_mcq_cq_empty(UfsHc *u, uint32_t qid)
static inline bool ufs_mcq_cq_full(UfsHc *u, uint32_t qid)
{
uint32_t tail = ufs_mcq_cq_tail(u, qid);
uint16_t cq_size = u->cq[qid]->size;
UfsCq *cq = u->cq[qid];
uint16_t cq_size;
if (!cq) {
return false;
}
cq_size = cq->size;
tail = (tail + sizeof(UfsCqEntry)) % (sizeof(UfsCqEntry) * cq_size);
return tail == ufs_mcq_cq_head(u, qid);
+11
View File
@@ -956,6 +956,17 @@ static int ohci_service_td(OHCIState *ohci, struct ohci_ed *ed)
if (len && dir != OHCI_TD_DIR_IN) {
/* The endpoint may not allow us to transfer it all now */
pktlen = (ed->flags & OHCI_ED_MPS_MASK) >> OHCI_ED_MPS_SHIFT;
/*
* The OHCI spec does not say what to do if the guest hands us
* an endpoint descriptor which specifies a MaximumPacketSize
* of zero, which would mean we can never actually make forward
* progress transferring data to it. We choose to treat it as
* an error.
*/
if (pktlen == 0) {
ohci_die(ohci);
return 1;
}
if (pktlen > len) {
pktlen = len;
}
-4
View File
@@ -71,10 +71,6 @@
#include "accel/tcg/cpu-mmu-index.h"
#include "exec/abi_ptr.h"
#if defined(CONFIG_USER_ONLY)
#include "user/guest-host.h"
#endif /* CONFIG_USER_ONLY */
static inline uint32_t
cpu_ldub_mmuidx_ra(CPUArchState *env, abi_ptr addr, int mmu_idx, uintptr_t ra)
{
+10 -1
View File
@@ -215,8 +215,17 @@ typedef enum {
*/
BDRV_REQ_NO_WAIT = 0x400,
/*
* Used between blk_co_start_request() and blk_end_request() to avoid
* that the request waits in a drained BlockBackend until the drained
* section ends. Waiting would cause a deadlock because drain waits for
* blk_end_request() to be called, but the request never completes
* because it waits for the drain to end.
*/
BDRV_REQ_NO_QUEUE = 0x800,
/* Mask of valid flags */
BDRV_REQ_MASK = 0x7ff,
BDRV_REQ_MASK = 0xfff,
} BdrvRequestFlags;
#define BDRV_O_NO_SHARE 0x0001 /* don't share permissions */
+12
View File
@@ -51,6 +51,18 @@ static inline unsigned int get_physical_block_exp(BlockConf *conf)
return exp;
}
#define DEFAULT_BLOCK_CONF (BlockConf) { \
.bootindex = -1, \
.backend_defaults = ON_OFF_AUTO_AUTO, \
.discard_granularity = -1, \
.wce = ON_OFF_AUTO_AUTO, \
.share_rw = false, \
.account_invalid = ON_OFF_AUTO_AUTO, \
.account_failed = ON_OFF_AUTO_AUTO, \
.rerror = BLOCKDEV_ON_ERROR_AUTO, \
.werror = BLOCKDEV_ON_ERROR_AUTO, \
}
#define DEFINE_BLOCK_PROPERTIES_BASE(_state, _conf) \
DEFINE_PROP_ON_OFF_AUTO("backend_defaults", _state, \
_conf.backend_defaults, ON_OFF_AUTO_AUTO), \
+2
View File
@@ -111,6 +111,8 @@ struct PnvMachineState {
bool big_core;
bool lpar_per_core;
Notifier machine_init_done;
};
PnvChip *pnv_get_chip(PnvMachineState *pnv, uint32_t chip_id);
+4 -2
View File
@@ -71,6 +71,8 @@ BlockAIOCB *blk_aio_ioctl(BlockBackend *blk, unsigned long int req, void *buf,
void blk_inc_in_flight(BlockBackend *blk);
void blk_dec_in_flight(BlockBackend *blk);
void coroutine_fn blk_co_start_request(BlockBackend *blk);
void blk_end_request(BlockBackend *blk);
bool coroutine_fn GRAPH_RDLOCK blk_co_is_inserted(BlockBackend *blk);
bool co_wrapper_mixed_bdrv_rdlock blk_is_inserted(BlockBackend *blk);
@@ -216,9 +218,9 @@ int co_wrapper_mixed blk_zone_append(BlockBackend *blk, int64_t *offset,
BdrvRequestFlags flags);
int co_wrapper_mixed blk_pdiscard(BlockBackend *blk, int64_t offset,
int64_t bytes);
int64_t bytes, BdrvRequestFlags flags);
int coroutine_fn blk_co_pdiscard(BlockBackend *blk, int64_t offset,
int64_t bytes);
int64_t bytes, BdrvRequestFlags flags);
int co_wrapper_mixed blk_flush(BlockBackend *blk);
int coroutine_fn blk_co_flush(BlockBackend *blk);
+56 -6
View File
@@ -29,7 +29,12 @@ extern unsigned long reserved_va;
*/
extern unsigned long guest_addr_max;
static inline vaddr cpu_untagged_addr(CPUState *cs, vaddr x)
/*
* These functions take the guest virtual address as a vaddr,
* and are suitable for use from target-independent code.
*/
static inline vaddr cpu_untagged_addr_vaddr(CPUState *cs, vaddr x)
{
const TCGCPUOps *tcg_ops = cs->cc->tcg_ops;
if (tcg_ops->untagged_addr) {
@@ -39,22 +44,22 @@ static inline vaddr cpu_untagged_addr(CPUState *cs, vaddr x)
}
/* All direct uses of g2h and h2g need to go away for usermode softmmu. */
static inline void *g2h_untagged(vaddr x)
static inline void *g2h_untagged_vaddr(vaddr x)
{
return (void *)((uintptr_t)(x) + guest_base);
}
static inline void *g2h(CPUState *cs, vaddr x)
static inline void *g2h_vaddr(CPUState *cs, vaddr x)
{
return g2h_untagged(cpu_untagged_addr(cs, x));
return g2h_untagged_vaddr(cpu_untagged_addr_vaddr(cs, x));
}
static inline bool guest_addr_valid_untagged(vaddr x)
static inline bool guest_addr_valid_untagged_vaddr(vaddr x)
{
return x <= guest_addr_max;
}
static inline bool guest_range_valid_untagged(vaddr start, vaddr len)
static inline bool guest_range_valid_untagged_vaddr(vaddr start, vaddr len)
{
return len - 1 <= guest_addr_max && start <= guest_addr_max - len + 1;
}
@@ -73,4 +78,49 @@ static inline bool guest_range_valid_untagged(vaddr start, vaddr len)
h2g_nocheck(x); \
})
#ifdef COMPILING_PER_TARGET
/*
* These functions take the guest virtual address as an abi_ptr. This
* is an important difference from a vaddr for the common case where
* the address is a syscall argument in a variable of type abi_long,
* which may be smaller than the vaddr type. If you pass an address in
* an abi_long to these functions then the value will be converted to
* an unsigned type and then zero extended to give the vaddr. If you
* use the g2h_vaddr() and similar functions which take an argument of
* type vaddr, then the value will be sign-extended, giving the wrong
* answer for addresses above the 2GB mark on 32-bit guests.
*
* Providing these functions with their traditional QEMU semantics is
* less bug-prone than requiring many callsites to remember to cast
* their abi_long variable to an abi_ptr before calling.
*/
static inline void *g2h(CPUState *cs, abi_ptr x)
{
return g2h_vaddr(cs, x);
}
static inline void *g2h_untagged(abi_ptr x)
{
return g2h_untagged_vaddr(x);
}
static inline bool guest_addr_valid_untagged(abi_ptr x)
{
return guest_addr_valid_untagged_vaddr(x);
}
static inline bool guest_range_valid_untagged(abi_ptr start, abi_ptr len)
{
return guest_range_valid_untagged_vaddr(start, len);
}
static inline abi_ptr cpu_untagged_addr(CPUState *cs, abi_ptr x)
{
return cpu_untagged_addr_vaddr(cs, x);
}
#endif
#endif
+3 -1
View File
@@ -352,7 +352,9 @@ void qio_channel_tls_bye(QIOChannelTLS *ioc, Error **errp)
task = qio_task_new(OBJECT(ioc), propagate_error, errp, NULL);
trace_qio_channel_tls_bye_start(ioc);
qio_channel_tls_bye_task(ioc, task, NULL);
if (qio_channel_tls_bye_task(ioc, task, NULL)) {
qio_task_free(task);
}
}
static void qio_channel_tls_init(Object *obj G_GNUC_UNUSED)
+7
View File
@@ -75,6 +75,13 @@
/* Instruct lower device to use last 4-bytes of skb data as FCS */
#define TARGET_SO_NOFCS 43
#define TARGET_SO_TIMESTAMP_NEW 63
#define TARGET_SO_TIMESTAMPNS_NEW 64
#define TARGET_SO_TIMESTAMPING_NEW 65
#define TARGET_SO_RCVTIMEO_NEW 66
#define TARGET_SO_SNDTIMEO_NEW 67
/* TARGET_O_NONBLOCK clashes with the bits used for socket types. Therefore we
* have to define SOCK_NONBLOCK to a different value here.
*/
+1 -1
View File
@@ -232,7 +232,7 @@ static bool insn_is_linux_bkpt(uint32_t opcode, bool is_thumb)
static bool emulate_arm_fpa11(CPUARMState *env, uint32_t opcode)
{
TaskState *ts = get_task_state(env_cpu(env));
int rc = EmulateAll(opcode, &ts->fpa, env);
int rc = EmulateAll(opcode, &ts->fpa);
int raise, enabled;
if (rc == 0) {
+2 -10
View File
@@ -29,8 +29,7 @@
//#include <asm/system.h>
FPA11* qemufpa = NULL;
CPUARMState* user_registers;
__thread FPA11* qemufpa = NULL;
/* Reset the FPA11 chip. Called to initialize and reset the emulator. */
void resetFPA11(void)
@@ -155,8 +154,7 @@ void SetRoundingPrecision(const unsigned int opcode)
}
/* Emulate the instruction in the opcode. */
/* ??? This is not thread safe. */
unsigned int EmulateAll(unsigned int opcode, FPA11* qfpa, CPUARMState* qregs)
unsigned int EmulateAll(unsigned int opcode, FPA11* qfpa)
{
unsigned int nRc = 0;
// unsigned long flags;
@@ -173,12 +171,6 @@ unsigned int EmulateAll(unsigned int opcode, FPA11* qfpa, CPUARMState* qregs)
}
qemufpa=qfpa;
user_registers=qregs;
#if 0
fprintf(stderr,"emulating FP insn 0x%08x, PC=0x%08x\n",
opcode, qregs[ARM_REG_PC]);
#endif
fpa11 = GET_FPA11();
if (fpa11->initflag == 0) /* good place for __builtin_expect */
+8 -17
View File
@@ -25,15 +25,6 @@
#define GET_FPA11() (qemufpa)
/*
* The processes registers are always at the very top of the 8K
* stack+task struct. Use the same method as 'current' uses to
* reach them.
*/
extern CPUARMState *user_registers;
#define GET_USERREG() (user_registers)
/* Need task_struct */
//#include <linux/sched.h>
@@ -83,7 +74,7 @@ typedef struct tagFPA11 {
float_status fp_status; /* QEMU float emulator status */
} FPA11;
extern FPA11* qemufpa;
extern __thread FPA11* qemufpa;
void resetFPA11(void);
void SetRoundingMode(const unsigned int);
@@ -91,25 +82,25 @@ void SetRoundingPrecision(const unsigned int);
static inline unsigned int readRegister(unsigned int reg)
{
return (user_registers->regs[(reg)]);
CPUARMState *env = cpu_env(current_cpu);
return env->regs[reg];
}
static inline void writeRegister(unsigned int x, unsigned int y)
{
#if 0
printf("writing %d to r%d\n",y,x);
#endif
user_registers->regs[(x)]=(y);
CPUARMState *env = cpu_env(current_cpu);
env->regs[x] = y;
}
static inline void writeConditionCodes(unsigned int x)
{
cpsr_write(user_registers, x, CPSR_NZCV, CPSRWriteByInstr);
CPUARMState *env = cpu_env(current_cpu);
cpsr_write(env, x, CPSR_NZCV, CPSRWriteByInstr);
}
#define ARM_REG_PC 15
unsigned int EmulateAll(unsigned int opcode, FPA11* qfpa, CPUARMState* qregs);
unsigned int EmulateAll(unsigned int opcode, FPA11* qfpa);
unsigned int EmulateCPDO(const unsigned int);
unsigned int EmulateCPDT(const unsigned int);
+26 -14
View File
@@ -449,12 +449,6 @@ static bool zero_bss(abi_ulong start_bss, abi_ulong end_bss,
{
abi_ulong align_bss;
/* We only expect writable bss; the code segment shouldn't need this. */
if (!(prot & PROT_WRITE)) {
error_setg(errp, "PT_LOAD with non-writable bss");
return false;
}
align_bss = TARGET_PAGE_ALIGN(start_bss);
end_bss = TARGET_PAGE_ALIGN(end_bss);
@@ -472,20 +466,35 @@ static bool zero_bss(abi_ulong start_bss, abi_ulong end_bss,
*/
align_bss -= TARGET_PAGE_SIZE;
} else {
abi_ulong start_page_aligned = start_bss & TARGET_PAGE_MASK;
/*
* The start of the bss shares a page with something.
* The only thing that we expect is the data section,
* which would already be marked writable.
* Overlapping the RX code segment seems malformed.
* The logical OR between flags and PAGE_WRITE works because
* in include/exec/page-protection.h they are defined as PROT_*
* values, matching mprotect().
* Temporarily enable write access to zero the fractional bss.
* target_mprotect() handles TB invalidation if needed.
*/
if (!(flags & PAGE_WRITE)) {
error_setg(errp, "PT_LOAD with bss overlapping "
"non-writable page");
return false;
if (target_mprotect(start_page_aligned,
TARGET_PAGE_SIZE,
prot | PAGE_WRITE) == -1) {
error_setg_errno(errp, errno,
"Error enabling write access for bss");
return false;
}
}
/* The page is already mapped and writable. */
/* The page is already mapped and now guaranteed writable. */
memset(g2h_untagged(start_bss), 0, align_bss - start_bss);
if (!(flags & PAGE_WRITE)) {
if (target_mprotect(start_page_aligned,
TARGET_PAGE_SIZE, prot) == -1) {
error_setg_errno(errp, errno,
"Error restoring bss first permissions");
return false;
}
}
}
}
@@ -1467,6 +1476,9 @@ static void load_elf_image(const char *image_name, const ImageSource *src,
/* Usual start for brk is after all sections of the main executable. */
info->brk = TARGET_PAGE_ALIGN(hiaddr + load_bias);
info->elf_flags = ehdr->e_flags;
#ifdef TARGET_MIPS
info->use_k0_tls = (ehdr->e_flags & EF_MIPS_MACH) == EF_MIPS_MACH_OCTEON;
#endif
prot_exec = PROT_EXEC;
#ifdef TARGET_AARCH64
+1 -1
View File
@@ -482,7 +482,7 @@ static abi_long host_to_target_for_each_rtattr(struct rtattr *rtattr,
unsigned short aligned_rta_len;
abi_long ret;
while (len > sizeof(struct rtattr)) {
while (len >= sizeof(struct rtattr)) {
rta_len = rtattr->rta_len;
if (rta_len < sizeof(struct rtattr) ||
rta_len > len) {
+8
View File
@@ -58,4 +58,12 @@
#define TARGET_SO_PROTOCOL 38
#define TARGET_SO_DOMAIN 39
#define TARGET_SO_TIMESTAMP_NEW 63
#define TARGET_SO_TIMESTAMPNS_NEW 64
#define TARGET_SO_TIMESTAMPING_NEW 65
#define TARGET_SO_RCVTIMEO_NEW 66
#define TARGET_SO_SNDTIMEO_NEW 67
#endif
+7
View File
@@ -67,6 +67,13 @@
#define TARGET_SO_CNX_ADVICE 0x402E
#define TARGET_SO_TIMESTAMP_NEW 0x4038
#define TARGET_SO_TIMESTAMPNS_NEW 0x4039
#define TARGET_SO_TIMESTAMPING_NEW 0x403A
#define TARGET_SO_RCVTIMEO_NEW 0x4040
#define TARGET_SO_SNDTIMEO_NEW 0x4041
/* TARGET_O_NONBLOCK clashes with the bits used for socket types. Therefore we
* have to define SOCK_NONBLOCK to a different value here.
*/
+24 -1
View File
@@ -60,10 +60,33 @@ struct target_fpx_sw_bytes {
};
QEMU_BUILD_BUG_ON(sizeof(struct target_fpx_sw_bytes) != 12*4);
struct fpxreg {
uint16_t significand[4];
uint16_t exponent;
uint16_t padding[3];
};
struct xmmreg {
uint32_t element[4];
};
/*
* This corresponds to the kernel's _fpstate_32. Since we
* only use it for the fpstate_unused padding section in
* the target sigcontext, it doesn't actually matter what fields
* we define here as long as we get the size right.
*/
struct target_fpstate_32 {
struct target_fregs_state fpstate;
X86LegacyXSaveArea fxstate;
uint32_t fxsr_env[6];
uint32_t mxcsr;
uint32_t reserved;
struct fpxreg fxsr_st[8];
struct xmmreg xmm[8];
uint32_t padding1[44];
uint32_t padding2[12]; /* aka sw_reserved */
};
QEMU_BUILD_BUG_ON(sizeof(struct target_fpstate_32) != 32 + 80 + 512);
struct target_sigcontext_32 {
uint16_t gs, __gsh;
+17 -12
View File
@@ -416,19 +416,18 @@
#endif
IOCTL(CDROMPAUSE, 0, TYPE_NULL)
IOCTL(CDROMSTART, 0, TYPE_NULL)
IOCTL(CDROMSTOP, 0, TYPE_NULL)
IOCTL(CDROMRESUME, 0, TYPE_NULL)
IOCTL(CDROMEJECT, 0, TYPE_NULL)
IOCTL(CDROMEJECT_SW, 0, TYPE_INT)
IOCTL(CDROMCLOSETRAY, 0, TYPE_NULL)
IOCTL(CDROMRESET, 0, TYPE_NULL)
IOCTL(CDROMPLAYMSF, IOC_W, MK_PTR(TYPE_INT))
IOCTL(CDROMPLAYTRKIND, IOC_W, MK_PTR(TYPE_INT))
IOCTL(CDROMREADTOCHDR, IOC_R, MK_PTR(TYPE_INT))
IOCTL(CDROMREADTOCENTRY, IOC_RW, MK_PTR(TYPE_INT))
IOCTL(CDROMSTOP, 0, TYPE_NULL)
IOCTL(CDROMSTART, 0, TYPE_NULL)
IOCTL(CDROMEJECT, 0, TYPE_NULL)
IOCTL(CDROMVOLCTRL, IOC_W, MK_PTR(TYPE_INT))
IOCTL(CDROMSUBCHNL, IOC_RW, MK_PTR(TYPE_INT))
IOCTL(CDROMEJECT_SW, IOC_W, TYPE_INT)
IOCTL(CDROMRESET, 0, TYPE_NULL)
/* XXX: incorrect (need specific handling) */
IOCTL(CDROMREADAUDIO, IOC_W, MK_PTR(MK_STRUCT(STRUCT_cdrom_read_audio)))
IOCTL(CDROMREADCOOKED, IOC_RW, MK_PTR(TYPE_INT))
@@ -438,16 +437,22 @@
IOCTL(CDROMREADALL, IOC_RW, MK_PTR(TYPE_INT))
IOCTL(CDROMMULTISESSION, IOC_RW, MK_PTR(TYPE_INT))
IOCTL(CDROM_GET_UPC, IOC_R, MK_PTR(TYPE_INT))
IOCTL(CDROM_LAST_WRITTEN, IOC_R, MK_PTR(TYPE_LONG))
IOCTL(CDROMVOLREAD, IOC_R, MK_PTR(TYPE_INT))
IOCTL(CDROMSEEK, IOC_W, MK_PTR(TYPE_INT))
IOCTL(CDROMPLAYBLK, IOC_W, MK_PTR(TYPE_INT))
IOCTL(CDROM_MEDIA_CHANGED, 0, TYPE_NULL)
IOCTL(CDROM_SET_OPTIONS, 0, TYPE_INT)
IOCTL(CDROM_CLEAR_OPTIONS, 0, TYPE_INT)
IOCTL(CDROM_SELECT_SPEED, 0, TYPE_INT)
IOCTL(CDROM_SELECT_DISC, 0, TYPE_INT)
IOCTL(CDROM_DRIVE_STATUS, 0, TYPE_NULL)
IOCTL(CDROMCLOSETRAY, 0, TYPE_NULL)
IOCTL(CDROM_SET_OPTIONS, IOC_W, TYPE_INT)
IOCTL(CDROM_CLEAR_OPTIONS, IOC_W, TYPE_INT)
IOCTL(CDROM_SELECT_SPEED, IOC_W, TYPE_INT)
IOCTL(CDROM_SELECT_DISC, IOC_W, TYPE_INT)
IOCTL(CDROM_MEDIA_CHANGED, IOC_W, TYPE_INT)
IOCTL(CDROM_DRIVE_STATUS, IOC_W, TYPE_INT)
IOCTL(CDROM_DISC_STATUS, 0, TYPE_NULL)
IOCTL(CDROM_CHANGER_NSLOTS, 0, TYPE_NULL)
IOCTL(CDROM_LOCKDOOR, IOC_W, TYPE_INT)
IOCTL(CDROM_DEBUG, IOC_W, TYPE_INT)
IOCTL(CDROM_GET_CAPABILITY, 0, TYPE_NULL)
IOCTL(CDROMAUDIOBUFSIZ, 0, TYPE_INT)
#if 0
+6 -4
View File
@@ -767,13 +767,15 @@ int main(int argc, char **argv, char **envp)
execfd = open(exec_path, O_RDONLY);
if (execfd < 0) {
printf("Error while loading %s: %s\n", exec_path, strerror(errno));
_exit(EXIT_FAILURE);
exit(EXIT_FAILURE);
}
}
/* Resolve executable file name to full path name */
if (realpath(exec_path, real_exec_path)) {
exec_path = real_exec_path;
/* Keep how we started the program in exec_path, e.g. "./my_program" */
/* Store real path in real_exec_path, e.g. "/usr/local/bin/my_program" */
if (!realpath(exec_path, real_exec_path)) {
printf("Could not resolve %s\n", exec_path);
}
/*
@@ -975,7 +977,7 @@ int main(int argc, char **argv, char **envp)
info, &bprm);
if (ret != 0) {
printf("Error while loading %s: %s\n", exec_path, strerror(-ret));
_exit(EXIT_FAILURE);
exit(EXIT_FAILURE);
}
for (wrk = target_environ; *wrk; wrk++) {
+7
View File
@@ -71,6 +71,13 @@
#define TARGET_SO_RCVBUFFORCE 33
#define TARGET_SO_PASSSEC 34
#define TARGET_SO_TIMESTAMP_NEW 63
#define TARGET_SO_TIMESTAMPNS_NEW 64
#define TARGET_SO_TIMESTAMPING_NEW 65
#define TARGET_SO_RCVTIMEO_NEW 66
#define TARGET_SO_SNDTIMEO_NEW 67
/** sock_type - Socket types
*
* Please notice that for binary compat reasons MIPS has to
+5
View File
@@ -35,7 +35,12 @@ static inline void cpu_clone_regs_parent(CPUMIPSState *env, unsigned flags)
static inline void cpu_set_tls(CPUMIPSState *env, target_ulong newtls)
{
TaskState *ts = get_task_state(env_cpu(env));
env->active_tc.CP0_UserLocal = newtls;
if (ts->info->use_k0_tls) {
env->active_tc.gpr[26] = newtls;
}
}
static inline abi_ulong get_sp_from_cpustate(CPUMIPSState *state)
+52
View File
@@ -1120,6 +1120,58 @@ abi_long target_mremap(abi_ulong old_addr, abi_ulong old_size,
errno = EINVAL;
return -1;
}
if (!old_size) {
if (!(flags & MREMAP_MAYMOVE)) {
errno = EINVAL;
return -1;
}
mmap_lock();
if (flags & MREMAP_FIXED) {
host_addr = mremap(g2h_untagged(old_addr), old_size, new_size,
flags, g2h_untagged(new_addr));
} else {
/*
* We ensure that the new mapping stands in the
* region of guest mappable addresses.
*/
abi_ulong mmap_start;
mmap_start = mmap_find_vma(0, new_size, TARGET_PAGE_SIZE);
if (mmap_start == -1) {
errno = ENOMEM;
mmap_unlock();
return -1;
}
host_addr = mremap(g2h_untagged(old_addr), old_size, new_size,
flags | MREMAP_FIXED, g2h_untagged(mmap_start));
new_addr = mmap_start;
}
if (host_addr == MAP_FAILED) {
mmap_unlock();
return -1;
}
if (flags & MREMAP_FIXED) {
new_addr = h2g(host_addr);
}
prot = page_get_flags(old_addr);
/*
* For old_size zero, there is nothing to clear at old_addr.
* Only set the flags for the new mapping. They both are valid.
*/
page_set_flags(new_addr, new_addr + new_size - 1,
prot | PAGE_VALID, PAGE_VALID);
shm_region_rm_complete(new_addr, new_addr + new_size - 1);
mmap_unlock();
return new_addr;
}
if (!guest_range_valid_untagged(old_addr, old_size)) {
errno = EFAULT;
return -1;
+14 -2
View File
@@ -210,6 +210,18 @@ QEMU_BUILD_BUG_ON(offsetof(struct target_rt_sigframe, uc.tuc_mcontext)
#endif
#ifdef TARGET_PPC64
#define RT_SIGFRAME_ADJUST 0
#else
/*
* For 32-bit rt sigframes we have an extra 16 bytes of gap
* on top of __SIGNAL_FRAMESIZE; this is to get the siginfo
* and ucontext in the same positions as in older kernels.
* See Linux's arch/powerpc/kernel/signal_32.c.
*/
#define RT_SIGFRAME_ADJUST 16
#endif
#if defined(TARGET_PPC64)
struct target_func_ptr {
@@ -525,7 +537,7 @@ void setup_rt_frame(int sig, struct target_sigaction *ka,
env->fpscr = 0;
/* Create a stack frame for the caller of the handler. */
newsp = rt_sf_addr - (SIGNAL_FRAMESIZE + 16);
newsp = rt_sf_addr - (SIGNAL_FRAMESIZE + RT_SIGFRAME_ADJUST);
err |= put_user(env->gpr[1], newsp, target_ulong);
if (err)
@@ -641,7 +653,7 @@ long do_rt_sigreturn(CPUPPCState *env)
struct target_rt_sigframe *rt_sf = NULL;
target_ulong rt_sf_addr;
rt_sf_addr = env->gpr[1] + SIGNAL_FRAMESIZE + 16;
rt_sf_addr = env->gpr[1] + SIGNAL_FRAMESIZE + RT_SIGFRAME_ADJUST;
if (!lock_user_struct(VERIFY_READ, rt_sf, rt_sf_addr, 1))
goto sigsegv;
+2
View File
@@ -10,6 +10,7 @@
#include "syscall_defs.h"
#include "target_syscall.h"
#include "accel/tcg/vcpu-state.h"
#include "user/guest-host.h"
/*
* This is the size of the host kernel's sigset_t, needed where we make
@@ -64,6 +65,7 @@ struct image_info {
uint32_t note_flags;
#ifdef TARGET_MIPS
bool use_k0_tls;
int fp_abi;
int interp_fp_abi;
#endif
+32 -10
View File
@@ -57,7 +57,7 @@ struct target_sigframe
struct target_ucontext {
target_ulong tuc_flags;
struct target_ucontext *tuc_link;
abi_ulong tuc_link;
target_stack_t tuc_stack;
struct target_sigcontext tuc_mcontext;
target_sigset_t tuc_sigmask; /* mask last for extensibility */
@@ -237,7 +237,7 @@ void setup_rt_frame(int sig, struct target_sigaction *ka,
/* Create the ucontext. */
__put_user(0, &frame->uc.tuc_flags);
__put_user(0, (unsigned long *)&frame->uc.tuc_link);
__put_user(0, &frame->uc.tuc_link);
target_save_altstack(&frame->uc.tuc_stack, regs);
setup_sigcontext(&frame->uc.tuc_mcontext,
regs, set->sig[0]);
@@ -329,20 +329,42 @@ badframe:
return -QEMU_ESIGRETURN;
}
/*
* "or r0,r0" nop used by the Linux kernel inline sigreturn trampolines to
* avoid a hardware bug (OR_R0_R0 in arch/sh/kernel/signal_32.c). Five of
* these nops follow TRAP_NOARG, placing the syscall number word 14 bytes
* past the MOVW(7) instruction (at MOVW(7)'s load offset). This yields the
* fixed 16-byte layout that libunwind's unw_is_signal_frame detects:
* [MOVW(7), TRAP_NOARG, 5x NOP_OR, .word syscall_nr]
*/
#define NOP_OR 0x200b
void setup_sigtramp(abi_ulong sigtramp_page)
{
uint16_t *tramp = lock_user(VERIFY_WRITE, sigtramp_page, 2 * 6, 0);
uint16_t *tramp = lock_user(VERIFY_WRITE, sigtramp_page, 2 * 16, 0);
assert(tramp != NULL);
/* sigreturn trampoline (non-RT) at offset 0 */
default_sigreturn = sigtramp_page;
__put_user(MOVW(2), &tramp[0]);
__put_user(MOVW(7), &tramp[0]);
__put_user(TRAP_NOARG, &tramp[1]);
__put_user(TARGET_NR_sigreturn, &tramp[2]);
__put_user(NOP_OR, &tramp[2]);
__put_user(NOP_OR, &tramp[3]);
__put_user(NOP_OR, &tramp[4]);
__put_user(NOP_OR, &tramp[5]);
__put_user(NOP_OR, &tramp[6]);
__put_user(TARGET_NR_sigreturn, &tramp[7]);
default_rt_sigreturn = sigtramp_page + 6;
__put_user(MOVW(2), &tramp[3]);
__put_user(TRAP_NOARG, &tramp[4]);
__put_user(TARGET_NR_rt_sigreturn, &tramp[5]);
/* rt_sigreturn trampoline at offset 16 */
default_rt_sigreturn = sigtramp_page + 16;
__put_user(MOVW(7), &tramp[8]);
__put_user(TRAP_NOARG, &tramp[9]);
__put_user(NOP_OR, &tramp[10]);
__put_user(NOP_OR, &tramp[11]);
__put_user(NOP_OR, &tramp[12]);
__put_user(NOP_OR, &tramp[13]);
__put_user(NOP_OR, &tramp[14]);
__put_user(TARGET_NR_rt_sigreturn, &tramp[15]);
unlock_user(tramp, sigtramp_page, 2 * 6);
unlock_user(tramp, sigtramp_page, 2 * 16);
}
+6 -3
View File
@@ -1384,6 +1384,11 @@ void process_pending_signals(CPUArchState *cpu_env)
}
handle_pending_signal(cpu_env, sig, &ts->sync_signal);
/*
* Restart scan from the beginning, as handle_pending_signal
* might have resulted in a new synchronous signal (eg SIGSEGV).
*/
goto restart_scan;
}
for (sig = 1; sig <= TARGET_NSIG; sig++) {
@@ -1394,9 +1399,7 @@ void process_pending_signals(CPUArchState *cpu_env)
(!sigismember(blocked_set,
target_to_host_signal_table[sig]))) {
handle_pending_signal(cpu_env, sig, &ts->sigtab[sig - 1]);
/* Restart scan from the beginning, as handle_pending_signal
* might have resulted in a new synchronous signal (eg SIGSEGV).
*/
/* Restart scan, explained above. */
goto restart_scan;
}
}
+7
View File
@@ -61,6 +61,13 @@
#define TARGET_SO_TIMESTAMPING 0x0023
#define TARGET_SCM_TIMESTAMPING TARGET_SO_TIMESTAMPING
#define TARGET_SO_TIMESTAMP_NEW 0x0046
#define TARGET_SO_TIMESTAMPNS_NEW 0x0042
#define TARGET_SO_TIMESTAMPING_NEW 0x0043
#define TARGET_SO_RCVTIMEO_NEW 0x0044
#define TARGET_SO_SNDTIMEO_NEW 0x0045
#define TARGET_SO_RXQ_OVFL 0x0024
#define TARGET_SO_WIFI_STATUS 0x0025
+2 -2
View File
@@ -1114,7 +1114,7 @@
{ TARGET_NR_quotactl, "quotactl" , NULL, NULL, NULL },
#endif
#ifdef TARGET_NR_read
{ TARGET_NR_read, "read" , "%s(%d,%#x,%d)", NULL, NULL },
{ TARGET_NR_read, "read" , "%s(%d,%p,%d)", NULL, NULL },
#endif
#ifdef TARGET_NR_readahead
{ TARGET_NR_readahead, "readahead" , NULL, NULL, NULL },
@@ -1674,7 +1674,7 @@
print_syscall_ret_waitpid },
#endif
#ifdef TARGET_NR_write
{ TARGET_NR_write, "write" , "%s(%d,%#x,%d)", NULL, NULL },
{ TARGET_NR_write, "write" , "%s(%d,%p,%d)", NULL, NULL },
#endif
#ifdef TARGET_NR_writev
{ TARGET_NR_writev, "writev" , "%s(%d,%p,%#x)", NULL, NULL },
+128 -66
View File
@@ -1146,7 +1146,6 @@ static inline abi_long copy_to_user_timeval(abi_ulong target_tv_addr,
return 0;
}
#if defined(TARGET_NR_clock_adjtime64) && defined(CONFIG_CLOCK_ADJTIME)
static inline abi_long copy_from_user_timeval64(struct timeval *tv,
abi_ulong target_tv_addr)
{
@@ -1163,7 +1162,6 @@ static inline abi_long copy_from_user_timeval64(struct timeval *tv,
return 0;
}
#endif
static inline abi_long copy_to_user_timeval64(abi_ulong target_tv_addr,
const struct timeval *tv)
@@ -1387,14 +1385,15 @@ static abi_long do_select(int n,
return -TARGET_EFAULT;
if (efd_addr && copy_to_user_fdset(efd_addr, &efds, n))
return -TARGET_EFAULT;
if (target_tv_addr) {
tv.tv_sec = ts.tv_sec;
tv.tv_usec = ts.tv_nsec / 1000;
if (copy_to_user_timeval(target_tv_addr, &tv)) {
return -TARGET_EFAULT;
}
}
}
if (target_tv_addr) {
tv.tv_sec = ts.tv_sec;
tv.tv_usec = ts.tv_nsec / 1000;
/*
* Like the kernel, we deliberately ignore possible
* failures writing back to the timeout struct.
*/
copy_to_user_timeval(target_tv_addr, &tv);
}
return ret;
@@ -1522,14 +1521,16 @@ static abi_long do_pselect6(abi_long arg1, abi_long arg2, abi_long arg3,
if (efd_addr && copy_to_user_fdset(efd_addr, &efds, n)) {
return -TARGET_EFAULT;
}
}
if (ts_addr) {
/*
* Like the kernel, we deliberately ignore possible
* failures writing back to the timeout struct.
*/
if (time64) {
if (ts_addr && host_to_target_timespec64(ts_addr, &ts)) {
return -TARGET_EFAULT;
}
host_to_target_timespec64(ts_addr, &ts);
} else {
if (ts_addr && host_to_target_timespec(ts_addr, &ts)) {
return -TARGET_EFAULT;
}
host_to_target_timespec(ts_addr, &ts);
}
}
return ret;
@@ -1599,15 +1600,15 @@ static abi_long do_ppoll(abi_long arg1, abi_long arg2, abi_long arg3,
if (set) {
finish_sigsuspend_mask(ret);
}
if (!is_error(ret) && arg3) {
if (arg3) {
/*
* Like the kernel, we deliberately ignore possible
* failures writing back to the timeout struct.
*/
if (time64) {
if (host_to_target_timespec64(arg3, timeout_ts)) {
return -TARGET_EFAULT;
}
host_to_target_timespec64(arg3, timeout_ts);
} else {
if (host_to_target_timespec(arg3, timeout_ts)) {
return -TARGET_EFAULT;
}
host_to_target_timespec(arg3, timeout_ts);
}
}
} else {
@@ -2010,7 +2011,8 @@ static inline abi_long host_to_target_cmsg(struct target_msghdr *target_msgh,
tgt_len != sizeof(struct errhdr_t)) {
goto unimplemented;
}
__put_user(errh->ee.ee_errno, &target_errh->ee.ee_errno);
__put_user(host_to_target_errno(errh->ee.ee_errno),
&target_errh->ee.ee_errno);
__put_user(errh->ee.ee_origin, &target_errh->ee.ee_origin);
__put_user(errh->ee.ee_type, &target_errh->ee.ee_type);
__put_user(errh->ee.ee_code, &target_errh->ee.ee_code);
@@ -2064,7 +2066,8 @@ static inline abi_long host_to_target_cmsg(struct target_msghdr *target_msgh,
tgt_len != sizeof(struct errhdr6_t)) {
goto unimplemented;
}
__put_user(errh->ee.ee_errno, &target_errh->ee.ee_errno);
__put_user(host_to_target_errno(errh->ee.ee_errno),
&target_errh->ee.ee_errno);
__put_user(errh->ee.ee_origin, &target_errh->ee.ee_origin);
__put_user(errh->ee.ee_type, &target_errh->ee.ee_type);
__put_user(errh->ee.ee_code, &target_errh->ee.ee_code);
@@ -2163,6 +2166,8 @@ static abi_long do_setsockopt(int sockfd, int level, int optname,
QEMU_BUILD_BUG_ON(sizeof(struct ip_mreq) !=
sizeof(struct target_ip_mreq));
QEMU_BUILD_BUG_ON(sizeof(struct ip_mreqn) !=
sizeof(struct target_ip_mreqn));
if (optname == IP_MULTICAST_IF) {
min_size = sizeof(struct in_addr);
@@ -2391,6 +2396,25 @@ static abi_long do_setsockopt(int sockfd, int level, int optname,
&tv, sizeof(tv)));
return ret;
}
case TARGET_SO_RCVTIMEO_NEW:
case TARGET_SO_SNDTIMEO_NEW:
{
struct timeval tv;
if (optlen != sizeof(struct target__kernel_sock_timeval)) {
return -TARGET_EINVAL;
}
if (copy_from_user_timeval64(&tv, optval_addr)) {
return -TARGET_EFAULT;
}
ret = get_errno(setsockopt(sockfd, SOL_SOCKET,
optname == TARGET_SO_RCVTIMEO_NEW ?
SO_RCVTIMEO : SO_SNDTIMEO,
&tv, sizeof(tv)));
return ret;
}
case TARGET_SO_ATTACH_FILTER:
{
struct target_sock_fprog *tfprog;
@@ -2604,7 +2628,8 @@ static abi_long do_getsockopt(int sockfd, int level, int optname,
/* These don't just return a single integer */
case TARGET_SO_PEERNAME:
goto unimplemented;
case TARGET_SO_RCVTIMEO: {
case TARGET_SO_RCVTIMEO:
case TARGET_SO_RCVTIMEO_NEW: {
struct timeval tv;
socklen_t tvlen;
@@ -2624,11 +2649,21 @@ get_timeout:
if (ret < 0) {
return ret;
}
if (len > sizeof(struct target_timeval)) {
len = sizeof(struct target_timeval);
/* special case: destination address is NULL, return 0 */
if (optval_addr) {
len = 0;
}
if (copy_to_user_timeval(optval_addr, &tv)) {
return -TARGET_EFAULT;
if (len == sizeof(struct target__kernel_sock_timeval)) {
if (copy_to_user_timeval64(optval_addr, &tv)) {
return -TARGET_EFAULT;
}
} else {
if (len >= sizeof(struct target_timeval)) {
len = sizeof(struct target_timeval);
if (copy_to_user_timeval(optval_addr, &tv)) {
return -TARGET_EFAULT;
}
}
}
if (put_user_u32(len, optlen)) {
return -TARGET_EFAULT;
@@ -2636,6 +2671,7 @@ get_timeout:
break;
}
case TARGET_SO_SNDTIMEO:
case TARGET_SO_SNDTIMEO_NEW:
optname = SO_SNDTIMEO;
goto get_timeout;
case TARGET_SO_PEERCRED: {
@@ -2817,7 +2853,10 @@ get_timeout:
}
if (len > lv)
len = lv;
if (len == 4) {
if (!optval_addr) {
/* writing to NULL does not give error */
len = 0;
} else if (len == 4) {
if (put_user_u32(val, optval_addr))
return -TARGET_EFAULT;
} else {
@@ -2850,18 +2889,24 @@ get_timeout:
return -TARGET_EINVAL;
lv = sizeof(lv);
ret = get_errno(getsockopt(sockfd, level, optname, &val, &lv));
write_ret:
if (ret < 0)
return ret;
if (len < sizeof(int) && len > 0 && val >= 0 && val < 255) {
if (!optval_addr) {
len = 0;
} else if (len < sizeof(int) && len > 0 && val >= 0 && val < 255) {
len = 1;
if (put_user_u32(len, optlen)
|| put_user_u8(val, optval_addr))
if (put_user_u8(val, optval_addr)) {
return -TARGET_EFAULT;
}
} else {
if (len > sizeof(int))
len = sizeof(int);
if (put_user_u32(len, optlen)
|| put_user_u32(val, optval_addr))
if (put_user_u32(val, optval_addr)) {
return -TARGET_EFAULT;
}
}
if (put_user_u32(len, optlen)) {
return -TARGET_EFAULT;
}
break;
@@ -2912,20 +2957,7 @@ get_timeout:
return -TARGET_EINVAL;
lv = sizeof(lv);
ret = get_errno(getsockopt(sockfd, level, optname, &val, &lv));
if (ret < 0)
return ret;
if (len < sizeof(int) && len > 0 && val >= 0 && val < 255) {
len = 1;
if (put_user_u32(len, optlen)
|| put_user_u8(val, optval_addr))
return -TARGET_EFAULT;
} else {
if (len > sizeof(int))
len = sizeof(int);
if (put_user_u32(len, optlen)
|| put_user_u32(val, optval_addr))
return -TARGET_EFAULT;
}
goto write_ret;
break;
default:
ret = -TARGET_ENOPROTOOPT;
@@ -2959,8 +2991,14 @@ get_timeout:
if (ret < 0) {
return ret;
}
if (put_user_u32(lv, optlen)
|| put_user_u32(val, optval_addr)) {
if (optval_addr) {
if (put_user_u32(val, optval_addr)) {
return -TARGET_EFAULT;
}
} else {
lv = 0;
}
if (put_user_u32(lv, optlen)) {
return -TARGET_EFAULT;
}
break;
@@ -7025,8 +7063,6 @@ static int do_fork(CPUArchState *env, unsigned int flags, abi_ulong newsp,
the child process gets its own copy of the lock. */
if (flags & CLONE_CHILD_SETTID)
put_user_u32(sys_gettid(), child_tidptr);
if (flags & CLONE_PARENT_SETTID)
put_user_u32(sys_gettid(), parent_tidptr);
ts = get_task_state(cpu);
if (flags & CLONE_SETTLS)
cpu_set_tls (env, newtls);
@@ -7034,6 +7070,8 @@ static int do_fork(CPUArchState *env, unsigned int flags, abi_ulong newsp,
ts->child_tidptr = child_tidptr;
} else {
cpu_clone_regs_parent(env, flags);
if (flags & CLONE_PARENT_SETTID)
put_user_u32(ret, parent_tidptr);
if (flags & CLONE_PIDFD) {
int pid_fd = 0;
#if defined(__NR_pidfd_open) && defined(TARGET_NR_pidfd_open)
@@ -8175,6 +8213,9 @@ static int do_futex(CPUState *cpu, bool time64, target_ulong uaddr,
#endif
#if defined(TARGET_NR_name_to_handle_at) && defined(CONFIG_OPEN_BY_HANDLE)
#ifndef AT_HANDLE_MNT_ID_UNIQUE
#define AT_HANDLE_MNT_ID_UNIQUE 0x001
#endif
static abi_long do_name_to_handle_at(abi_long dirfd, abi_long pathname,
abi_long handle, abi_long mount_id,
abi_long flags)
@@ -8182,6 +8223,7 @@ static abi_long do_name_to_handle_at(abi_long dirfd, abi_long pathname,
struct file_handle *target_fh;
struct file_handle *fh;
int mid = 0;
uint64_t mid64 = 0;
abi_long ret;
char *name;
unsigned int size, total_size;
@@ -8205,7 +8247,12 @@ static abi_long do_name_to_handle_at(abi_long dirfd, abi_long pathname,
fh = g_malloc0(total_size);
fh->handle_bytes = size;
ret = get_errno(name_to_handle_at(dirfd, path(name), fh, &mid, flags));
if (flags & AT_HANDLE_MNT_ID_UNIQUE) {
ret = get_errno(name_to_handle_at(dirfd, path(name), fh,
(int *)&mid64, flags));
} else {
ret = get_errno(name_to_handle_at(dirfd, path(name), fh, &mid, flags));
}
unlock_user(name, pathname, 0);
/* man name_to_handle_at(2):
@@ -8219,8 +8266,14 @@ static abi_long do_name_to_handle_at(abi_long dirfd, abi_long pathname,
g_free(fh);
unlock_user(target_fh, handle, total_size);
if (put_user_s32(mid, mount_id)) {
return -TARGET_EFAULT;
if (flags & AT_HANDLE_MNT_ID_UNIQUE) {
if (put_user_u64(mid64, mount_id)) {
return -TARGET_EFAULT;
}
} else {
if (put_user_s32(mid, mount_id)) {
return -TARGET_EFAULT;
}
}
return ret;
@@ -8746,9 +8799,9 @@ static int maybe_do_fake_open(CPUArchState *cpu_env, int dirfd,
return -1;
}
if (safe) {
return safe_openat(dirfd, exec_path, flags, mode);
return safe_openat(dirfd, real_exec_path, flags, mode);
} else {
return openat(dirfd, exec_path, flags, mode);
return openat(dirfd, real_exec_path, flags, mode);
}
}
@@ -8843,7 +8896,16 @@ static int do_openat2(CPUArchState *cpu_env, abi_long dirfd,
if (fd > -2) {
ret = get_errno(fd);
} else {
ret = get_errno(safe_openat2(dirfd, pathname, &how,
const char *host_pathname = pathname;
if (pathname[0] == '/' &&
!(how.resolve & (RESOLVE_IN_ROOT | RESOLVE_BENEATH))) {
/*
* RESOLVE_BENEATH rejects absolute paths; RESOLVE_IN_ROOT
* resolves them relative to dirfd.
*/
host_pathname = path(pathname);
}
ret = get_errno(safe_openat2(dirfd, host_pathname, &how,
sizeof(struct open_how_ver0)));
}
@@ -8872,9 +8934,9 @@ ssize_t do_guest_readlink(const char *pathname, char *buf, size_t bufsiz)
* Don't worry about sign mismatch as earlier mapping
* logic would have thrown a bad address error.
*/
ret = MIN(strlen(exec_path), bufsiz);
ret = MIN(strlen(real_exec_path), bufsiz);
/* We cannot NUL terminate the string. */
memcpy(buf, exec_path, ret);
memcpy(buf, real_exec_path, ret);
} else {
ret = readlink(path(pathname), buf, bufsiz);
}
@@ -8965,7 +9027,7 @@ static int do_execv(CPUArchState *cpu_env, int dirfd,
const char *exe = p;
if (is_proc_myself(p, "exe")) {
exe = exec_path;
exe = real_exec_path;
}
ret = is_execveat
? safe_execveat(dirfd, exe, argp, envp, flags)
@@ -10976,9 +11038,9 @@ static abi_long do_syscall1(CPUArchState *cpu_env, int num, abi_long arg1,
* Don't worry about sign mismatch as earlier mapping
* logic would have thrown a bad address error.
*/
ret = MIN(strlen(exec_path), arg4);
ret = MIN(strlen(real_exec_path), arg4);
/* We cannot NUL terminate the string. */
memcpy(p2, exec_path, ret);
memcpy(p2, real_exec_path, ret);
} else {
ret = get_errno(readlinkat(arg1, path(p), p2, arg4));
}
@@ -13178,7 +13240,7 @@ static abi_long do_syscall1(CPUArchState *cpu_env, int num, abi_long arg1,
#ifdef TARGET_NR_set_thread_area
case TARGET_NR_set_thread_area:
#if defined(TARGET_MIPS)
cpu_env->active_tc.CP0_UserLocal = arg1;
cpu_set_tls(cpu_env, arg1);
return 0;
#elif defined(TARGET_I386) && defined(TARGET_ABI32)
return do_set_thread_area(cpu_env, arg1);
+8 -3
View File
@@ -210,7 +210,7 @@ struct target_ip_mreq {
struct target_ip_mreqn {
struct target_in_addr imr_multiaddr;
struct target_in_addr imr_address;
abi_long imr_ifindex;
abi_int imr_ifindex;
};
struct target_ip_mreq_source {
@@ -2005,7 +2005,7 @@ struct target_stat {
abi_uint __unused5;
};
#if !defined(TARGET_RISCV64)
#if !defined(TARGET_RISCV64) && !defined(TARGET_LOONGARCH64)
#define TARGET_HAS_STRUCT_STAT64
struct target_stat64 {
abi_ullong st_dev;
@@ -2773,7 +2773,12 @@ struct target_open_how_ver0 {
#ifndef RESOLVE_NO_SYMLINKS
#define RESOLVE_NO_SYMLINKS 0x04
#endif
#ifndef RESOLVE_BENEATH
#define RESOLVE_BENEATH 0x08
#endif
#ifndef RESOLVE_IN_ROOT
#define RESOLVE_IN_ROOT 0x10
#endif
#if (defined(TARGET_I386) && defined(TARGET_ABI32)) || \
(defined(TARGET_ARM) && defined(TARGET_ABI32)) || \
defined(TARGET_M68K) || defined(TARGET_MICROBLAZE) || \
+1
View File
@@ -24,6 +24,7 @@
#include "exec/translation-block.h"
extern char *exec_path;
extern char real_exec_path[PATH_MAX];
void init_task_state(TaskState *ts);
void task_settid(TaskState *);
void stop_all_tasks(void);
+8 -2
View File
@@ -110,7 +110,7 @@ if have_rust
bindgen = find_program('bindgen', required: get_option('rust'))
if not bindgen.found() or bindgen.version().version_compare('<0.60.0')
if get_option('rust').enabled()
error('bindgen version ' + bindgen.version() + ' is unsupported. You can install a new version with "cargo install bindgen-cli"')
error('bindgen version ' + bindgen.version() + ' is unsupported. You can install a new version with "cargo install --locked bindgen-cli"')
else
if bindgen.found()
warning('bindgen version ' + bindgen.version() + ' is unsupported, disabling Rust compilation.')
@@ -703,6 +703,12 @@ hardening_flags = [
# it harder to take advantage of uninitialized stack
# data to drive exploits
'-ftrivial-auto-var-init=zero',
# Ensure GCC zero-initializes padding bits and trailing fields in
# unions. This avoids potentially leaking host data into the guest
# when we init a struct and copy it into guest memory. GCC prior
# to GCC 15 and clang don't have this, but they zero the padding
# and trailing portions of a union by default.
'-fzero-init-padding-bits=all',
]
# Zero out registers used during a function call
@@ -2887,7 +2893,7 @@ config_host_data.set('CONFIG_PTHREAD_CONDATTR_SETCLOCK', cc.links(osdep_prefix +
int main(void)
{
pthread_condattr_t attr
pthread_condattr_t attr;
pthread_condattr_init(&attr);
pthread_condattr_setclock(&attr, CLOCK_MONOTONIC);
return 0;
+1 -1
View File
@@ -3510,7 +3510,7 @@ static MigIterateState migration_iteration_run(MigrationState *s)
* postcopy started, so ESTIMATE should always match with EXACT
* during postcopy phase.
*/
if (pending_size < s->threshold_size) {
if (pending_size <= s->threshold_size) {
qemu_savevm_state_pending_exact(&must_precopy, &can_postcopy);
pending_size = must_precopy + can_postcopy;
trace_migrate_pending_exact(pending_size, must_precopy,
+5 -2
View File
@@ -539,6 +539,9 @@ int vmstate_save_state_v(QEMUFile *f, const VMStateDescription *vmsd,
} else {
ret = inner_field->info->put(f, curr_elem, size,
inner_field, vmdesc_loop);
if (ret < 0) {
error_setg(errp, "put failed");
}
}
written_bytes = qemu_file_transferred(f) - old_offset;
@@ -551,8 +554,8 @@ int vmstate_save_state_v(QEMUFile *f, const VMStateDescription *vmsd,
}
if (ret) {
error_setg(errp, "Save of field %s/%s failed",
vmsd->name, field->name);
error_prepend(errp, "Save of field %s/%s failed: ",
vmsd->name, field->name);
if (vmsd->post_save) {
vmsd->post_save(opaque);
}
+1 -1
View File
@@ -2984,7 +2984,7 @@ static coroutine_fn int nbd_handle_request(NBDClient *client,
"flush failed", errp);
case NBD_CMD_TRIM:
ret = blk_co_pdiscard(exp->common.blk, request->from, request->len);
ret = blk_co_pdiscard(exp->common.blk, request->from, request->len, 0);
if (ret >= 0 && request->flags & NBD_CMD_FLAG_FUA) {
ret = blk_co_flush(exp->common.blk);
}
+4
View File
@@ -3914,6 +3914,9 @@
#
# @errno: error identifier (errno) to be returned; defaults to EIO
#
# @delay-ns: request delay before completion in nanoseconds
# (default: 0, since: 11.1)
#
# @sector: specifies the sector index which has to be affected in
# order to actually trigger the event; defaults to "any sector"
#
@@ -3929,6 +3932,7 @@
'*state': 'int',
'*iotype': 'BlkdebugIOType',
'*errno': 'int',
'*delay-ns': 'int',
'*sector': 'int',
'*once': 'bool',
'*immediately': 'bool' } }
+10
View File
@@ -128,6 +128,16 @@ static void do_qmp_dispatch_bh(void *opaque)
data->cmd->fn(data->args, data->ret, data->errp);
monitor_set_cur(qemu_coroutine_self(), NULL);
aio_co_wake(data->co);
/*
* If the QMP dispatcher coroutine is waiting to be scheduled
* in iohandler_ctx, we must kick the main loop. This ensures
* that AIO_WAIT_WHILE_UNLOCKED() in monitor_cleanup() doesn't
* block indefinitely waiting for an event in qemu_aio_context,
* but actually gets the chance to poll iohandler_ctx and resume
* the coroutine.
*/
aio_wait_kick();
}
/*
Loaded 100 of 136 files, more files were not shown because too many files have changed in this diff. Show more