Compare commits

..
135 Commits
Author SHA1 Message Date
Michael Tokarev f8ed81651e Update version for 10.2.2 release
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-17 11:33:17 +03:00
Fiona Ebner 0103b23cb7 target/i386: add compat for migrating error code
If cpu->env.has_error_code is true, backwards migration of a VM from
a QEMU binary with commit 27535e9cca to a QEMU binary without commit
27535e9cca will fail:

> kvm: error while loading state for instance 0x0 of device 'cpu'

In practice, wrongly setting the error code to 0 on the target is
often unproblematic, so additionally checking error_code != 0 in
cpu_errcode_needed() is not enough to mitigate the issue. Instead, add
proper machine version compat handling.

Cc: [email protected]
Fixes: 27535e9cca ("target/i386: Add support for save/load of exception error code")
Signed-off-by: Fiona Ebner <[email protected]>
Reviewed-by: Zhao Liu <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 1b80f1009d)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-13 10:14:49 +03:00
Paolo Bonzini 85af4e9370 hyperv/syndbg: check length returned by cpu_physical_memory_map()
If cpu_physical_memory_map() returns a length shorter than the one
that was passed into the function, writing the full out_len bytes
causes an access beyond the memory allocated to the guest; or in
the case of the MMIO bounce buffer, an out-of-bounds access in a
heap-allocated object.

Add a check similar to the one already in handle_send_msg(),
and take the occasion to remove repeated computations of
recv_byte_count + UDP_PKT_HEADER_SIZE and clarify that the
code does not write past out_len bytes.

Reported-by: Oleh Konko <https://github.com/1seal>
Reviewed-by: Daniel P. Berrangé <[email protected]>
Fixes: CVE-2026-3842
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 4f28b87fdd)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-13 10:14:49 +03:00
Hanna Czenczek 3e7e7cf05a fuse: Copy write buffer content before polling
aio_poll() in I/O functions can lead to nested read_from_fuse_export()
calls, overwriting the request buffer's content.  The only function
affected by this is fuse_write(), which therefore must use a bounce
buffer or corruption may occur.

Note that in addition we do not know whether libfuse-internal structures
can cope with this nesting, and even if we did, we probably cannot rely
on it in the future.  This is the main reason why we want to remove
libfuse from the I/O path.

I do not have a good reproducer for this other than:

$ dd if=/dev/urandom of=image bs=1M count=4096
$ dd if=/dev/zero of=copy bs=1M count=4096
$ touch fuse-export
$ qemu-storage-daemon \
    --blockdev file,node-name=file,filename=copy \
    --export \
    fuse,id=exp,node-name=file,mountpoint=fuse-export,writable=true \
    &

Other shell:
$ qemu-img convert -p -n -f raw -O raw -t none image fuse-export
$ killall -SIGINT qemu-storage-daemon
$ qemu-img compare image copy
Content mismatch at offset 0!

(The -t none in qemu-img convert is important.)

I tried reproducing this with throttle and small aio_write requests from
another qemu-io instance, but for some reason all requests are perfectly
serialized then.

I think in theory we should get parallel writes only if we set
fi->parallel_direct_writes in fuse_open().  In fact, I can confirm that
if we do that, that throttle-based reproducer works (i.e. does get
parallel (nested) write requests).  I have no idea why we still get
parallel requests with qemu-img convert anyway.

Also, a later patch in this series will set fi->parallel_direct_writes
and note that it makes basically no difference when running fio on the
current libfuse-based version of our code.  It does make a difference
without libfuse.  So something quite fishy is going on.

I will try to investigate further what the root cause is, but I think
for now let's assume that calling blk_pwrite() can invalidate the buffer
contents through nested polling.

Cc: [email protected]
Reviewed-by: Kevin Wolf <[email protected]>
Signed-off-by: Hanna Czenczek <[email protected]>
Message-ID: <[email protected]>
Reviewed-by: Kevin Wolf <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit a3fcbca0ef)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-13 10:14:49 +03:00
rail5 8b3b97dae5 target/loongarch: Preserve PTE permission bits in LDPTE
The LDPTE helper loads a page table entry (or huge page entry) from guest
memory and currently applies the PALEN mask to the whole 64-bit value.

That mask is intended to constrain the physical address bits, but masking
the full entry also clears upper permission bits in the PTE, including NX
(bit 62). As a result, LoongArch TCG can incorrectly allow instruction
fetches from NX mappings when translation is driven through software
page-walk.

Fix this by masking only the PPN/address field with PALEN while preserving
permission bits, and by clearing any non-architectural (software) bits
using a hardware PTE mask. LDDIR is unchanged since it returns the base
address of the next page table level.

Reported at: https://gitlab.com/qemu-project/qemu/-/issues/3319

-Fixes: 56599a705f ("target/loongarch: Introduce loongarch_palen_mask()")
Fixes: d2cba6f7ce ("target/loongarch: Add other core instructions support")
Cc: [email protected]
Signed-off-by: rail5 (Andrew S. Rightenburg) <[email protected]>
Reviewed-by: Bibo Mao <[email protected]>
Reviewed-by: Song Gao <[email protected]>
Signed-off-by: Song Gao <[email protected]>
(cherry picked from commit 2d877bc02a)
(Mjt: backport to 10.2.x which lacks v10.2.0-1568-g56599a705f
 "target/loongarch: Introduce loongarch_palen_mask()")
(fixing the Fixes: tag)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-13 10:13:05 +03:00
rail5 477d1f3c59 target/loongarch: Avoid recursive PNX exception on CSR_BADI fetch
loongarch_cpu_do_interrupt() updates CSR_BADI by fetching the faulting
instruction with cpu_ldl_code_mmu().

For a PNX exception (instruction fetch prohibited by NX), fetching the
instruction at env->pc will fault with PNX again. This can lead to an
infinite exception loop.

Treat PNX like other instruction-fetch exceptions (PIF/ADEF) and do not
update CSR_BADI for it.

-Fixes: 410dfbf620 ("target/loongarch: Move TCG specified functions to tcg_cpu.c")
Fixes: f757a2cd69 ("target/loongarch: Add LoongArch interrupt and exception handler")
Cc: [email protected]
Signed-off-by: rail5 (Andrew S. Rightenburg) <[email protected]>
Reviewed-by: Bibo Mao <[email protected]>
Reviewed-by: Song Gao <[email protected]>
Signed-off-by: Song Gao <[email protected]>
(cherry picked from commit db2325f794)
(fixing the Fixes: tag)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-13 10:10:26 +03:00
Peter Maydell f07f64c3d8 hw: Make qdev_get_printable_name() consistently return freeable string
The current implementation of qdev_get_printable_name() sometimes
returns a string that must not be freed (vdev->id or the fixed
fallback string "<unknown device>" and sometimes returns a string
that must be freed (the return value of qdev_get_dev_path()). This
forces callers to leak the string in the "must be freed" case.

Make the function consistent that it always returns a string that
the caller must free, and make the three callsites free it.

This fixes leaks like this that show up when running "make check"
with the address sanitizer enabled:

Direct leak of 13 byte(s) in 1 object(s) allocated from:
    #0 0x5561de21f293 in malloc (/home/pm215/qemu/build/san/qemu-system-i386+0x1a2d293) (BuildId: 6d6fad7130fd5c8dbbc03401df554f68b8034936)
    #1 0x767ad7a82ac9 in g_malloc (/lib/x86_64-linux-gnu/libglib-2.0.so.0+0x62ac9) (BuildId: 116e142b9b52c8a4dfd403e759e71ab8f95d8bb3)
    #2 0x5561deaf34f2 in pcibus_get_dev_path /home/pm215/qemu/build/san/../../hw/pci/pci.c:2792:12
    #3 0x5561df9d8830 in qdev_get_printable_name /home/pm215/qemu/build/san/../../hw/core/qdev.c:431:24
    #4 0x5561deebdca2 in virtio_init_region_cache /home/pm215/qemu/build/san/../../hw/virtio/virtio.c:298:17
    #5 0x5561df05f842 in memory_region_write_accessor /home/pm215/qemu/build/san/../../system/memory.c:491:5
    #6 0x5561df05ed1b in access_with_adjusted_size /home/pm215/qemu/build/san/../../system/memory.c:567:18
    #7 0x5561df05e3fa in memory_region_dispatch_write /home/pm215/qemu/build/san/../../system/memory.c
    #8 0x5561df0aa805 in address_space_stm_internal /home/pm215/qemu/build/san/../../system/memory_ldst.c.inc:85:13
    #9 0x5561df0bcad3 in qtest_process_command /home/pm215/qemu/build/san/../../system/qtest.c:480:13

Cc: [email protected]
Fixes: e209d4d7a3 ("virtio: improve virtqueue mapping error messages")
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 1e3e1d51e2)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-11 16:42:39 +03:00
Peter Maydell a69152d257 hw/net/npcm_gmac: Catch accesses off the end of the register array
In the npcm_gmac device, we create the iomem MemoryRegion with
a size of 8KB, but NPCM_GMAC_NR_REGS is only 0x1060 / 4. This
means there's a range of offsets that the guest can access
that don't have gmac->regs[] entries. We weren't catching this,
so the guest could get us to index off the end of the regs array.

Catch and log these invalid accesses.

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/3316
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 550391c713)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-11 16:42:39 +03:00
Andreas Schwab 6f6bdf3763 linux-user: fix TIOCGSID ioctl
TIOCGSID is IOC_R, not IOC_W.

Signed-off-by: Andreas Schwab <[email protected]>
Reviewed-by: Helge Deller <[email protected]>
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit 6a1221614f)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-11 16:42:39 +03:00
Bingwu Zhang 2481744d96 tests/tcg/multiarch/test-mmap: Check mmaps beyond reserved_va
Unfixed mmap calls where start > reserved_va or the max guest addr
should have a valid result.

Signed-off-by: Bingwu Zhang <[email protected]>
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit c865b6bce5)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-11 16:42:39 +03:00
Bingwu Zhang ed18bbbc11 bsd-user: Deal with mmap where start > reserved_va
Fixes: f12294b5bd ("bsd-user: Use page_find_range_empty for mmap_find_vma_reserved")
Signed-off-by: Bingwu Zhang <[email protected]>
Reviewed-by: Helge Deller <[email protected]>
Reviewed-by: Warner Losh <[email protected]>
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit e8e7d1f977)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-11 16:42:39 +03:00
Bingwu Zhang 82d83d29bd linux-user: Deal with mmap where start > reserved_va
Fixes: 4c13048e02 ("linux-user: Use page_find_range_empty for mmap_find_vma_reserved")
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/3310
Signed-off-by: Bingwu Zhang <[email protected]>
Reviewed-by: Helge Deller <[email protected]>
Signed-off-by: Helge Deller <[email protected]>
(cherry picked from commit f2813e13fe)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-11 16:42:39 +03:00
Peter Maydell d9dfd5f425 hw/net/xilinx_ethlite: Check for oversized TX packets
The xilinx_ethlite network device wasn't checking that the TX packet
size set by the guest was within the size of its dual port RAM, with
the effect that the guest could get it to read off the end of the RAM
block.

Check the length.  There is no provision in this very simple device
for reporting errors, so as with various RX errors we just report via
tracepoint.

This lack of length check has been present since the device was first
introduced, though the code implementing the tx path has changed
somewhat since then.

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/3317
Fixes: b43848a100 ("xilinx: Add ethlite emulation")
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Alistair Francis <[email protected]>
Reviewed-by: Edgar E. Iglesias <[email protected]>
Message-ID: <[email protected]>
[PMD: renamed size -> tx_size to avoid shadow=compatible-local error]
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit 6595a8d5d1)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-11 16:42:39 +03:00
Dmitry Osipenko 0c5199e52b virtio-gpu: Ensure BHs are invoked only from main-loop thread
QEMU's display GL core is tied to main-loop thread and virtio-gpu
interacts with display while processing GPU commands. Virtio-gpu BHs
work in generic AIO context that can be invoked on vCPU thread, while
GL and UI toolkits are bound to the main-loop thread.

Make virtio-gpu BHs use iohandler AIO context that is handled in a
main-loop thread only.

 0  SDL_GL_MakeCurrent() (libSDL3)
 1  SDL_GL_MakeCurrent_REAL() (libSDL2)
 2  sdl2_gl_make_context_current() (ui/sdl2-gl.c:201)
 3  make_current() (virglrenderer.c:639)
 4  vrend_finish_context_switch() (vrend_renderer.c:11630)
 5  vrend_hw_switch_context() (vrend_renderer.c:11613)
 6  vrend_renderer_force_ctx_0() (vrend_renderer.c:12986)
 7  virgl_renderer_force_ctx_0() (virglrenderer.c:460)
 8  virtio_gpu_virgl_process_cmd() (virtio-gpu-virgl.c:1013)
 9  virtio_gpu_process_cmdq() (virtio-gpu.c:1050)
 10 virtio_gpu_gl_handle_ctrl() (virtio-gpu-gl.c:86)
 11 aio_bh_poll() (util/async.c)
 12 aio_poll() (util/aio-posix.c)
 13 blk_pwrite() (block/block-gen.c:1985)
 14 pflash_update() (pflash_cfi01.c:396)
 15 pflash_write() (pflash_cfi01.c:541)
 16 memory_region_dispatch_write() (system/memory.c:1554)
 17 flatview_write() (system/physmem.c:3333)
 18 address_space_write() (system/physmem.c:3453)
 19 kvm_cpu_exec() (accel/kvm/kall-all.c:3248)
 20 kvm_vcpu_thread_fn() (accel/kvm/kaccel-ops.c:53)

Cc: [email protected]
Signed-off-by: Dmitry Osipenko <[email protected]>
Message-ID: <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alex Bennée <[email protected]>
(cherry picked from commit 235f9b3638)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-11 16:42:39 +03:00
Jens Axboe a40b3f664c fdmon-io_uring: check CQ ring directly in gsource_check
gsource_check() only looks at the ppoll revents for the io_uring fd,
but CQEs can be posted during gsource_prepare()'s io_uring_submit()
call via kernel task_work processing on syscall exit. These completions
are already sitting in the CQ ring but the ring fd may not be signaled
yet, causing gsource_check() to return false.

Add a fallback io_uring_cq_ready() check so completions that arrive
during submission are dispatched immediately rather than waiting for
the next ppoll() cycle.

Signed-off-by: Jens Axboe <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Stefan Hajnoczi <[email protected]>
(cherry picked from commit 961fcc0f22)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-11 16:42:39 +03:00
Jens Axboe f9b1537744 aio-posix: notify main loop when SQEs are queued
When a vCPU thread handles MMIO (holding BQL), aio_co_enter() runs the
block I/O coroutine inline on the vCPU thread because
qemu_get_current_aio_context() returns the main AioContext when BQL is
held. The coroutine calls luring_co_submit() which queues an SQE via
fdmon_io_uring_add_sqe(), but the actual io_uring_submit() only happens
in gsource_prepare() on the main loop thread.

Since the coroutine ran inline (not via aio_co_schedule()), no BH is
scheduled and aio_notify() is never called. The main loop remains asleep
in ppoll() with up to a 499ms timeout, leaving the SQE unsubmitted until
the next timer fires.

Fix this by calling aio_notify() after queuing the SQE. This wakes the
main loop via the eventfd so it can run gsource_prepare() and submit the
pending SQE promptly.

This is a generic fix that benefits all devices using aio=io_uring.
Without it, AHCI/SATA devices see MUCH worse I/O latency since they use
MMIO (not ioeventfd like virtio) and have no other mechanism to wake the
main loop after queuing block I/O.

This is usually a bit hard to detect, as it also relies on the ppoll
loop not waking up for other activity, and micro benchmarks tend not to
see it because they don't have any real processing time. With a
synthetic test case that has a few usleep() to simulate processing of
read data, it's very noticeable. The below example reads 128MB with
O_DIRECT in 128KB chunks in batches of 16, and has a 1ms delay before
each batch submit, and a 1ms delay after processing each completion.
Running it on /dev/sda yields:

time sudo ./iotest /dev/sda

________________________________________________________
Executed in   25.76 secs	  fish           external
   usr time    6.19 millis  783.00 micros    5.41 millis
   sys time   12.43 millis  642.00 micros   11.79 millis

while on a virtio-blk or NVMe device we get:

time sudo ./iotest /dev/vdb

________________________________________________________
Executed in    1.25 secs      fish           external
   usr time    1.40 millis    0.30 millis    1.10 millis
   sys time   17.61 millis    1.43 millis   16.18 millis

time sudo ./iotest /dev/nvme0n1

________________________________________________________
Executed in    1.26 secs      fish           external
   usr time    6.11 millis    0.52 millis    5.59 millis
   sys time   13.94 millis    1.50 millis   12.43 millis

where the latter are consistent. If we run the same test but keep the
socket for the ssh connection active by having activity there, then
the sda test looks as follows:

time sudo ./iotest /dev/sda

________________________________________________________
Executed in    1.23 secs      fish           external
   usr time    2.70 millis   39.00 micros    2.66 millis
   sys time    4.97 millis  977.00 micros    3.99 millis

as now the ppoll loop is woken all the time anyway.

After this fix, on an idle system:

time sudo ./iotest /dev/sda

________________________________________________________
Executed in    1.30 secs      fish           external
   usr time    2.14 millis    0.14 millis    2.00 millis
   sys time   16.93 millis    1.16 millis   15.76 millis

Signed-off-by: Jens Axboe <[email protected]>
Message-Id: <[email protected]>
Reviewed-by: Kevin Wolf <[email protected]>
[Generalize the comment since this applies to all vCPU thread activity,
not just coroutines, as suggested by Kevin Wolf <[email protected]>.
--Stefan]
Signed-off-by: Stefan Hajnoczi <[email protected]>
(cherry picked from commit 2ae361ef1d)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-11 16:42:39 +03:00
Hanna Czenczek 8b851e5bb1 block/nfs: Do not enter coroutine from CB
The reasoning I gave for why it would be safe to call aio_co_wake()
despite holding the mutex was wrong: It is true that the current request
will not re-acquire the mutex, but a subsequent request in the same
coroutine can.  Because the mutex is a non-coroutine mutex, this will
result in a deadlock.

Therefore, we must either not enter the coroutine here (only scheduling
it), or release the mutex around aio_co_wake().  I opt for the former,
as it is the behavior prior to the offending commit, and so seems safe
to do.

Fixes: deb35c129b
       ("nfs: Run co BH CB in the coroutine’s AioContext")
Buglink: https://gitlab.com/qemu-project/qemu/-/issues/2622#note_2965097035
Cc: [email protected]
Signed-off-by: Hanna Czenczek <[email protected]>
Message-ID: <[email protected]>
Reviewed-by: Kevin Wolf <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit 1d6610099b)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-11 16:42:39 +03:00
Kevin Wolf ca8b13eb04 block: Never drop BLOCK_IO_ERROR with action=stop for rate limiting
Commit 2155d2dd introduced rate limiting for BLOCK_IO_ERROR to emit an
event only once a second. This makes sense for cases in which the guest
keeps running and can submit more requests that would possibly also fail
because there is a problem with the backend.

However, if the error policy is configured so that the VM is stopped on
errors, this is both unnecessary because stopping the VM means that the
guest can't issue more requests and in fact harmful because stopping the
VM is an important state change that management tools need to keep track
of even if it happens more than once in a given second. If an event is
dropped, the management tool would see a VM randomly going to paused
state without an associated error, so it has a hard time deciding how to
handle the situation.

This patch disables rate limiting for action=stop by not relying on the
event type alone any more in monitor_qapi_event_queue_no_reenter(), but
checking action for BLOCK_IO_ERROR, too. If the error is reported to the
guest or ignored, the rate limiting stays in place.

Fixes: 2155d2dd7f ('block-backend: per-device throttling of BLOCK_IO_ERROR reports')
Signed-off-by: Kevin Wolf <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit 544ddbb637)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-11 16:42:39 +03:00
Dmitry Guryanov 43e60c88f1 block/throttle-groups: fix deadlock with iolimits and muliple iothreads
Details: https://gitlab.com/qemu-project/qemu/-/issues/3144

The function schedule_next_request is called with tg->lock held and
it may call throttle_group_co_restart_queue, which takes
tgm->throttled_reqs_lock, qemu_co_mutex_lock may leave current
coroutine if other iothread has taken the lock. If the next
coroutine will call throttle_group_co_io_limits_intercept - it
will try to take the mutex tg->lock which will never be released.

Here is the backtrace of the iothread:
Thread 30 (Thread 0x7f8aad1fd6c0 (LWP 24240) "IO iothread2"):
 #0  futex_wait (futex_word=0x5611adb7d828, expected=2, private=0) at ../sysdeps/nptl/futex-internal.h:146
 #1  __GI___lll_lock_wait (futex=futex@entry=0x5611adb7d828, private=0) at lowlevellock.c:49
 #2  0x00007f8ab5a97501 in lll_mutex_lock_optimized (mutex=0x5611adb7d828) at pthread_mutex_lock.c:48
 #3  ___pthread_mutex_lock (mutex=0x5611adb7d828) at pthread_mutex_lock.c:93
 #4  0x00005611823f5482 in qemu_mutex_lock_impl (mutex=0x5611adb7d828, file=0x56118289daca "../block/throttle-groups.c", line=372) at ../util/qemu-thread-posix.c:94
 #5  0x00005611822b0b39 in throttle_group_co_io_limits_intercept (tgm=0x5611af1bb4d8, bytes=4096, direction=THROTTLE_READ) at ../block/throttle-groups.c:372
 #6  0x00005611822473b1 in blk_co_do_preadv_part (blk=0x5611af1bb490, offset=15972311040, bytes=4096, qiov=0x7f8aa4000f98, qiov_offset=0, flags=BDRV_REQ_REGISTERED_BUF) at ../block/block-backend.c:1354
 #7  0x0000561182247fa0 in blk_aio_read_entry (opaque=0x7f8aa4005910) at ../block/block-backend.c:1619
 #8  0x000056118241952e in coroutine_trampoline (i0=-1543497424, i1=32650) at ../util/coroutine-ucontext.c:175
 #9  0x00007f8ab5a56f70 in ?? () at ../sysdeps/unix/sysv/linux/x86_64/__start_context.S:66 from target:/lib64/libc.so.6
 #10 0x00007f8aad1ef190 in ?? ()
 #11 0x0000000000000000 in ?? ()

The lock is taken in line 386:
(gdb) p tg.lock
$1 = {lock = {__data = {__lock = 2, __count = 0, __owner = 24240, __nusers = 1, __kind = 0, __spins = 0, __elision = 0, __list = {__prev = 0x0, __next = 0x0}},
    __size = "\002\000\000\000\000\000\000\000\260^\000\000\001", '\000' <repeats 26 times>, __align = 2}, file = 0x56118289daca "../block/throttle-groups.c",
  line = 386, initialized = true}

The solution is to use tg->lock to protect both ThreadGroup fields and
ThrottleGroupMember.throttled_reqs. It doesn't seem to be possible
to use separate locks because we need to first manipulate ThrottleGroup
fields, then schedule next coroutine using throttled_reqs and after than
update token field from ThrottleGroup depending on the throttled_reqs
state.

Signed-off-by: Dmitry Guryanov <[email protected]>
Message-ID: <[email protected]>
Reviewed-by: Hanna Czenczek <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit d481617765)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-11 16:42:39 +03:00
Kevin Wolf 61f14858c1 mirror: Fix missed dirty bitmap writes during startup
Currently, mirror disables the block layer's dirty bitmap before its own
replacement is working. This means that during startup, there is a
window in which the allocation status of blocks in the source has
already been checked, but new writes coming in aren't tracked yet,
resulting in a corrupted copy:

1. Dirty bitmap is disabled in mirror_start_job()
2. Some request are started in mirror_top_bs while s->job == NULL
3. mirror_dirty_init() -> bdrv_co_is_allocated_above() runs and because
   the request hasn't completed yet, the block isn't allocated
4. The request completes, still sees s->job == NULL and skips the
   bitmap, and nothing else will mark it dirty either

One ingredient is that mirror_top_opaque->job is only set after the
job is fully initialized. For the rationale, see commit 32125b1460
("mirror: Fix access of uninitialised fields during start").

Fix this by giving mirror_top_bs access to dirty_bitmap and enabling it
to track writes from the beginning. Disabling the block layer's tracking
and enabling the mirror_top_bs one happens in a drained section, so
there is no danger of races with in-flight requests any more. All of
this happens well before the block allocation status is checked, so we
can be sure that no writes will be missed.

Cc: [email protected]
Closes: https://gitlab.com/qemu-project/qemu/-/issues/3273
Fixes: 32125b1460 ('mirror: Fix access of uninitialised fields during start')
Signed-off-by: Kevin Wolf <[email protected]>
Message-ID: <[email protected]>
Reviewed-by: Fiona Ebner <[email protected]>
Tested-by: Jean-Louis Dupond <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit 0f51f9c342)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-11 16:42:39 +03:00
Antoine Damhet 11589707ec block/curl: fix concurrent completion handling
curl_multi_check_completion would bail upon the first completed
transfer even if more completion messages were available thus leaving
some in flight IOs stuck.

Rework a bit the loop to make the iterations clearer and drop the breaks.

The original hang can be somewhat reproduced with the following command:

$ qemu-img convert -p -m 16 -O qcow2 -c --image-opts \
  'file.driver=https,file.url=https://scaleway.testdebit.info/10G.iso,file.readahead=1M' \
  /tmp/test.qcow2

Fixes: 1f2cead324 ("curl: Ensure all informationals are checked for completion")
Cc: [email protected]
Signed-off-by: Antoine Damhet <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit 6f7b0a23a6)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-11 16:42:39 +03:00
Halil Oktay (oblivionsage) 86b5130fef block/vmdk: fix OOB read in vmdk_read_extent()
Bounds check for marker.size doesn't account for the 12-byte marker
header, allowing zlib to read past the allocated buffer.

Move the check inside the has_marker block and subtract the marker size.

Fixes: CVE-2026-2243
Reported-by: Halil Oktay (oblivionsage) <[email protected]>
Signed-off-by: Halil Oktay (oblivionsage) <[email protected]>
Reviewed-by: Kevin Wolf <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
(cherry picked from commit cfda94eddb)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-11 16:42:39 +03:00
Peter Maydell 52cb65f9a6 hw/net/smc91c111: Don't allow negative-length packets
The smc91c111 data frame format in memory (figure 8-1 in the
datasheet) includes a "byte count" field which is intended to be the
total size of the data frame, including not just the packet data but
also the leading and trailing information like the status word and
the byte count field itself.  It is therefore possible for the guest
to set this to a value so small that the leading and trailing fields
won't fit and the packet has effectively a negative area.

We weren't checking for this, with the result that when we subtract 6
from the length to get the length of the packet proper we end up with
a negative length, which is then inconsistently handled in the
qemu_send_packet() code such that we can try to transmit a very large
amount of data and read off the end of the device's data array.

Treat excessively small length values the same way we do excessively
large values.  As with the oversized case, the datasheet does not
describe what happens for this software error case, and there is no
relevant tx error condition for this, so we just log and drop the
packet.

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/3304
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Message-id: [email protected]
(cherry picked from commit d8e19f8042)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-11 16:42:39 +03:00
Daniel P. Berrangé e944f36993 io: fix cleanup for websock I/O source data on cancellation
The websock code will create a GSource for tracking completion of the
handshake process, passing a QIOTask which is freed by the callback
when it completes, which means when a source is cancelled, nothing is
free'ing the task.

Switch to provide a data free callback to the GSource, which ensures
the QIOTask is always freed even when the main event callback never
fires.

Fixes: https://gitlab.com/qemu-project/qemu/-/issues/3114
Signed-off-by: Daniel P. Berrangé <[email protected]>
(cherry picked from commit 9545c059f7)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-11 16:42:36 +03:00
Daniel P. Berrangé f8943633a9 io: fix cleanup for TLS I/O source data on cancellation
The TLS code will create a GSource for tracking completion of the
handshake process, passing a QIOChannelTLSData struct that contains
various data items. The data struct is freed by the callback when
it completes, which means when a source is cancelled, nothing is
free'ing the data struct or its contents.

Switch to provide a data free callback to the GSource, which ensures
the QIOChannelTLSData struct is always freed even when the main event
callback never fires.

Fixes: https://gitlab.com/qemu-project/qemu/-/issues/3114
Reviewed-by: Marc-André Lureau <[email protected]>
Signed-off-by: Daniel P. Berrangé <[email protected]>
(cherry picked from commit d39d0f3acd)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-11 16:42:36 +03:00
Daniel P. Berrangé 68e031345a io: separate freeing of tasks from marking them as complete
The original design of QIOTask was intended to simplify lifecycle
management by automatically freeing it when the task was marked as
complete. This overlooked the fact that when a QIOTask is used in
combination with a GSource, there may be times when the source
callback is never invoked. This is typically when a GSource is
released before any I/O event arrives. In such cases it is not
desirable to mark a QIOTask as complete, but it still needs to be
freed. To satisfy this, the task must be released manually.

Reviewed-by: Marc-André Lureau <[email protected]>
Signed-off-by: Daniel P. Berrangé <[email protected]>
(cherry picked from commit 163cd0ae11)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-11 16:42:36 +03:00
Peter Maydell 0deef85292 target/ppc/translate: Fix TCG debug assert translating CLRBWIBC
The test case in the ppe42 functional test triggers a TCG debug
assertion, which causes the test to fail in an --enable-debug
build or when the sanitizers are enabled:

#6  0x00007ffff4a3b517 in __assert_fail
    (assertion=0x5555562e7589 "!temp_readonly(ots)", file=0x5555562e5b23 "../../tcg/tcg.c", line=4928, function=0x5555562e8900 <__PRETTY_FUNCTION__.23> "tcg_reg_alloc_mov") at ./assert/assert.c:105
#7  0x0000555555cc2189 in tcg_reg_alloc_mov (s=0x7fff60000b70, op=0x7fff600126f8) at ../../tcg/tcg.c:4928
#8  0x0000555555cc74e0 in tcg_gen_code (s=0x7fff60000b70, tb=0x7fffa802f540, pc_start=4294446080) at ../../tcg/tcg.c:6667
#9  0x0000555555d02abe in setjmp_gen_code
    (env=0x555556cbe610, tb=0x7fffa802f540, pc=4294446080, host_pc=0x7fffeea00c00, max_insns=0x7fffee9f9d74, ti=0x7fffee9f9d90)
    at ../../accel/tcg/translate-all.c:257
#10 0x0000555555d02d75 in tb_gen_code (cpu=0x555556cba590, s=...) at ../../accel/tcg/translate-all.c:325
#11 0x0000555555cf5922 in cpu_exec_loop (cpu=0x555556cba590, sc=0x7fffee9f9ee0) at ../../accel/tcg/cpu-exec.c:970
#12 0x0000555555cf5aae in cpu_exec_setjmp (cpu=0x555556cba590, sc=0x7fffee9f9ee0) at ../../accel/tcg/cpu-exec.c:1016
#13 0x0000555555cf5b4b in cpu_exec (cpu=0x555556cba590) at ../../accel/tcg/cpu-exec.c:1042
#14 0x0000555555d1e7ab in tcg_cpu_exec (cpu=0x555556cba590) at ../../accel/tcg/tcg-accel-ops.c:82
#15 0x0000555555d1ff97 in rr_cpu_thread_fn (arg=0x555556cba590) at ../../accel/tcg/tcg-accel-ops-rr.c:285
#16 0x00005555561586c9 in qemu_thread_start (args=0x555556ee3c90) at ../../util/qemu-thread-posix.c:393
#17 0x00007ffff4a9caa4 in start_thread (arg=<optimized out>) at ./nptl/pthread_create.c:447
#18 0x00007ffff4b29c6c in clone3 () at ../sysdeps/unix/sysv/linux/x86_64/clone3.S:78

This can be reproduced "by hand":

 ./build/clang/qemu-system-ppc -display none -vga none \
    -machine ppe42_machine -serial stdio \
    -device loader,file=$HOME/.cache/qemu/download/03c1ac0fb7f6c025102a02776a93b35101dae7c14b75e4eab36a337e39042ea8 \
    -device loader,addr=0xfff80040,cpu-num=0

(assuming you have the image file from the functional test
in your local cache).

This happens for this input:

IN:
0xfff80c00:  07436004  .byte    0x07, 0x43, 0x60, 0x04

which generates (among other things):

 not_i32 $0x80000,$0x80000

which the TCG optimization pass turns into:

 mov_i32 $0x80000,$0xfff7ffff             dead: 1  pref=0xffff

and where we then assert because we tried to write to a constant.

This happens for the CLRBWIBC instruction which ends up in
do_mask_branch() with rb_is_gpr false and invert true.  In this case
we will generate code that sets mask to a tcg_constant_tl() but then
uses it as the LHS in tcg_gen_not_tl().

Fix the assertion by doing the invert in the translate time C code
for the "mask is constant" case.

Cc: [email protected]
Fixes: f7ec91c239 ("target/ppc: Add IBM PPE42 special instructions")
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Glenn Miles <[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 78c6b6010c)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-02 17:44:09 +03:00
Bernhard Beschow 438b752c76 target/i386/emulate/x86_decode: Actually use stream in decode_instruction_stream()
Compared to decode_instruction(), decode_instruction_stream() has an additional
stream parameter which avoids some guest memory accesses during instruction
decoding. Both functions defer the actual work to decode_opcode() which would
set the stream pointer to zero such that decode_instruction_stream() essentially
behaved like decode_instruction(). Given that all callers of
decode_instruction_stream() properly zero-initialize the decode parameter, the
memset() call can be moved into decode_instruction() which is the only other
user of decode_opcode(). This preserves the non-zero stream pointer which
avoids extra guest memory accesses.

Fixes: 1e25327b24 ("target/i386/emulate: Allow instruction decoding from stream")
cc: qemu-stable
Signed-off-by: Bernhard Beschow <[email protected]>
Reviewed-by: Mohamed Mediouni <[email protected]>
Reviewed-by: Wei Liu (Microsoft) <[email protected]>
Tested-by: Magnus Kulke <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 1b93832f55)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-02 17:38:38 +03:00
Bernhard Beschow 32c1fc948e target/i386/hvf/x86_mmu: Fix compiler warning
When reusing the code in WHPX, GCC emits the following warning when compiling
for i386-softmmu under MSYS2:

  In file included from ../src/target/i386/emulate/x86_mmu.c:20:
  ../src/target/i386/emulate/x86_mmu.c: In function 'vmx_write_mem':
  ../src/target/i386/emulate/x86_mmu.c:251:25: error: format '%llx' expects argument of type 'long long unsigned int', but argument 3 has type 'target_ulong' {aka 'unsigned int'} [-Werror=format=]
    251 |             VM_PANIC_EX("%s: mmu_gva_to_gpa %llx failed\n", __func__, gva);
        |                         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~            ~~~
        |                                                                       |
        |                                                                       target_ulong {aka unsigned int}
  ../src/target/i386/emulate/panic.h:34:12: note: in definition of macro 'VM_PANIC_EX'
     34 |     printf(__VA_ARGS__); \
        |            ^~~~~~~~~~~
  ../src/target/i386/emulate/x86_mmu.c:251:48: note: format string is defined here
    251 |             VM_PANIC_EX("%s: mmu_gva_to_gpa %llx failed\n", __func__, gva);
        |                                             ~~~^
        |                                                |
        |                                                long long unsigned int
        |                                             %x

Fix the warning by reusing the target-specific macro TARGET_FMT_lx which exists
for this exact purpose.

Fixes: c97d6d2cdf ("i386: hvf: add code base from Google's QEMU repository")
cc: qemu-stable
Signed-off-by: Bernhard Beschow <[email protected]>
Reviewed-by: Mohamed Mediouni <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Wei Liu (Microsoft) <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 529e5e7643)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-02 17:37:52 +03:00
Bernhard Beschow 17ec370a79 target/i386/emulate/x86_decode: Fix compiler warning
When compiling for i386-softmmu under MSYS2, GCC emits the following warning:

  In function 'get_reg_val',
      inlined from 'calc_modrm_operand64' at ../src/target/i386/emulate/x86_decode.c:1796:15:
  ../src/target/i386/emulate/x86_decode.c:1703:5: error: 'memcpy' forming offset [4, 7] is out of the bounds [0, 4] of object 'val' with type 'target_ulong' {aka 'unsigned int'} [-Werror=array-bounds=]
   1703 |     memcpy(&val,
        |     ^~~~~~~~~~~~
   1704 |            get_reg_ref(env, reg, rex_present, is_extended, size),
        |            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   1705 |            size);
        |            ~~~~~
  ../src/target/i386/emulate/x86_decode.c: In function 'calc_modrm_operand64':
  ../src/target/i386/emulate/x86_decode.c:1702:18: note: 'val' declared here
   1702 |     target_ulong val = 0;
        |                  ^~~

In the calc_modrm_operand64() case the compiler sees size == 8 to be mem-copied
to a target_ulong variable which is only 4 bytes wide in case of i386-softmmu.
Note that when size != 1, get_reg_ref() always returns a pointer to an 8 byte
register, regardless of the target_ulong size. Fix the compiler warning by
always providing 8 bytes of storage by means of uint64_t.

Fixes: 77a2dba45c ("target/i386/emulate: stop overloading decode->op[N].ptr")
cc: qemu-stable
Signed-off-by: Bernhard Beschow <[email protected]>
Reviewed-by: Mohamed Mediouni <[email protected]>
Reviewed-by: Wei Liu (Microsoft) <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit c86bca1671)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-02 17:37:29 +03:00
Josh Poimboeuf 7426a375bc hw/i386/vmmouse: Fix hypercall clobbers
Fedora QA reported the following kernel panic:

  BUG: unable to handle page fault for address: 0000000040003e54
  #PF: supervisor write access in kernel mode
  #PF: error_code(0x0002) - not-present page
  PGD 1082ec067 P4D 0
  Oops: Oops: 0002 [#1] SMP NOPTI
  CPU: 0 UID: 0 PID: 0 Comm: swapper/0 Not tainted 6.19.0-0.rc4.260108gf0b9d8eb98df.34.fc43.x86_64 #1 PREEMPT(lazy)
  Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS edk2-20251119-3.fc43 11/19/2025
  RIP: 0010:vmware_hypercall4.constprop.0+0x52/0x90
  Code: 48 83 c4 20 5b e9 69 f0 fc fe 8b 05 a0 c1 b2 01 85 c0 74 23 b8 68 58 4d 56 b9 27 00 00 00 31 d2 bb 04 00 00 00 66 ba 58 56 ed <89> 1f 89 0e 41 89 10 5b e9 3c f0 fc fe 6a 00 49 89 f9 45 31 c0 31
  RSP: 0018:ff5eeb3240003e40 EFLAGS: 00010046
  RAX: 0000000000000000 RBX: 000000000000ffca RCX: 000000000000ffac
  RDX: 0000000000000000 RSI: 0000000040003e58 RDI: 0000000040003e54
  RBP: ff1e05f3c1204800 R08: ff5eeb3240003e5c R09: 000000009d899c41
  R10: 000000000000003d R11: ff5eeb3240003ff8 R12: 0000000000000000
  R13: 00000000000000ff R14: ff1e05f3c02f9e00 R15: 000000000000000c
  FS:  0000000000000000(0000) GS:ff1e05f489e40000(0000) knlGS:0000000000000000
  CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
  CR2: 0000000040003e54 CR3: 000000010841d002 CR4: 0000000000771ef0
  PKRU: 55555554
  Call Trace:
   <IRQ>
   vmmouse_report_events+0x13e/0x1b0
   psmouse_handle_byte+0x15/0x60
   ps2_interrupt+0x8a/0xd0
   ...

It was triggered by dereferencing a bad pointer (RDI) immediately after
a VMware hypercall for VMWARE_CMD_ABSPOINTER_DATA in the vmmouse driver:

  ffffffff82135070 <vmware_hypercall4.constprop.0>:
  ...
  ffffffff821350ac:       b8 68 58 4d 56          mov    $0x564d5868,%eax
  ffffffff821350b1:       b9 27 00 00 00          mov    $0x27,%ecx
  ffffffff821350b6:       31 d2                   xor    %edx,%edx
  ffffffff821350b8:       bb 04 00 00 00          mov    $0x4,%ebx
  ffffffff821350bd:       66 ba 58 56             mov    $0x5658,%dx
  ffffffff821350c1:       ed                      in     (%dx),%eax	<-- hypercall
  ffffffff821350c2:       89 1f                   mov    %ebx,(%rdi)	<-- crash

Reading the kernel disassembly shows that RDI should contain the value
of a valid kernel stack address here (0xff5eeb3240003e54).  Instead it
contains 0x40003e54, suggesting the hypervisor cleared the upper 32
bits.

And indeed, Alexey discovered that QEMU's vmmouse_get_data() and
vmmouse_set_data() are only saving/restoring the lower 32 bits, while
clearing the upper 32.  Fix that by changing the type of the saved data
array from uint32_t to uint64_t.

Fixes: 548df2acc6 ("VMMouse Emulation, by Anthony Liguori.")
Reported-by: Justin Forbes <[email protected]>
Debugged-by: Alexey Makhalov <[email protected]>
Signed-off-by: Josh Poimboeuf <[email protected]>
Link: https://lore.kernel.org/r/c508fc1d4a4ccd8c9fb1e51b71df089e31115a53.1770309998.git.jpoimboe@kernel.org
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/3293
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 48c8916aec)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-02 17:35:59 +03:00
Christian Schoenebeck f577bc677f hw/9pfs: fix missing EOPNOTSUPP on Twstat and Trenameat for fs synth driver
Renaming files/dirs is only supported by path-based fs drivers. EOPNOTSUPP
should be returned on any renaming attempt for not path-based fs drivers.
This was already the case for 9p "Trename" request type. However for 9p
request types "Trenameat" and "Twstat" this was yet missing.

So fix this by checking in Twstat and Trenameat request handlers whether
the fs driver in use is really path based, if not return EOPNOTSUPP and
abort further handling of the request.

This fixes a crash with the 9p "synth" fs driver which is not path-based.

The crash happened because the synth driver stores and expects a raw
V9fsSynthNode pointer instead of a C-string on V9fsPath.data. So the
C-string delivered by 9p server to synth fs driver was incorrectly
casted to a V9fsSynthNode pointer, eventually causing a segfault.

Reported-by: Oliver Chang <[email protected]>
Fixes: https://issues.oss-fuzz.com/issues/477990727
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/3298
Signed-off-by: Christian Schoenebeck <[email protected]>
Reviewed-by: Greg Kurz <[email protected]>
Link: https://lore.kernel.org/qemu-devel/[email protected]/
(cherry picked from commit b72d15f47c)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-01 09:23:29 +03:00
Richie Buturla cdafefe5ae hw/9pfs: fix data race in v9fs_mark_fids_unreclaim()
A data race between v9fs_mark_fids_unreclaim() and v9fs_path_copy()
causes an inconsistent read of fidp->path. In v9fs_path_copy(), the
path size is set before the data pointer is allocated, creating a
window where size is non-zero but data is NULL.

v9fs_co_open2() holds a write lock during path modifications,
but v9fs_mark_fids_unreclaim() was not acquiring a read
lock, allowing it to race.

Fix by holding the path read lock during FID table iteration.

Resolves: https://gitlab.com/qemu-project/qemu/-/issues/3300
Signed-off-by: Richie Buturla <[email protected]>
Link: https://lore.kernel.org/qemu-devel/[email protected]/
Fixes: 7a46274529 ("hw/9pfs: Add file descriptor reclaim support")
Signed-off-by: Christian Schoenebeck <[email protected]>
(cherry picked from commit c96f6d2398)
Signed-off-by: Michael Tokarev <[email protected]>
2026-03-01 09:23:29 +03:00
Alex Bennée b0560afef6 target/arm: set the correct TI bits for WFIT traps
The WFIT trap should be reported as 0b10.

Cc: [email protected]
Signed-off-by: Alex Bennée <[email protected]>
Reviewed-by: Gustavo Romero <[email protected]>
Message-id: [email protected]
Reviewed-by: Peter Maydell <[email protected]>
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit 662fd548a0)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-26 23:14:13 +03:00
Weixie Cui 7e64af6463 hw/ssi/xilinx_spips: Reset TX FIFO in reset
In xilinx_spips_reset() and xlnx_zynqmp_qspips_reset() a cut and
paste error meant we reset the RX FIFO twice and the TX FIFO not at
all.  Correct this to reset both FIFOs.

Cc: [email protected]
Signed-off-by: Weixie Cui <[email protected]>
Reviewed-by: Thomas Huth <[email protected]>
Reviewed-by: Alistair Francis <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Message-id: [email protected]
[Rewrote commit message]
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit 669683cf14)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-26 23:13:30 +03:00
Kuan-Wei Chiu dc9f0565a2 hw/misc/virt_ctrl: Fix incorrect trace event in read operation
The virt_ctrl_read() function currently invokes trace_virt_ctrl_write()
instead of trace_virt_ctrl_read(). This results in read operations
appearing as write operations in the trace output, which is misleading
during debugging and analysis.

Replace the incorrect trace call with the proper read-specific trace
event to accurately reflect the hardware behavior.

Fixes: 0791bc02b8 ("m68k: add a system controller")
Signed-off-by: Kuan-Wei Chiu <[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 8608ed356e)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-23 21:57:21 +03:00
Manos Pitsidianakis 2989865251 virtio-snd: tighten read amount in in_cb
The amount of bytes to read passed to AUD_read() should never surpass
the maximum available buffer length. Tighten the current amount by
MIN(<amount>, max_size - <existing size>).

Cc: [email protected]
Fixes: 98e77e3dd8 ("virtio-snd: add max size bounds check in input cb")
Reported-by: DARKNAVY <[email protected]>
Signed-off-by: Manos Pitsidianakis <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit 7994203bb1)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-23 21:55:43 +03:00
Manos Pitsidianakis a730f98a7a virtio-snd: fix max_size bounds check in input cb
In 98e77e3d we calculated the max size and checked that each buffer is smaller than it.

We neglected to subtract the size of the virtio_snd_pcm_status header
from the max size, and max_size was thus larger than the correct value,
leading to potential OOB writes.

If the buffer cannot fit the header or can fit only the header, return
the buffer immediately.

Cc: [email protected]
Fixes: 98e77e3dd8 ("virtio-snd: add max size bounds check in input cb")
Reported-by: DARKNAVY <[email protected]>
Signed-off-by: Manos Pitsidianakis <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit bcb53328aa)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-23 21:55:24 +03:00
Manos Pitsidianakis d84fbf241d virtio-snd: handle 5.14.6.2 for PCM_INFO properly
The section 5.14.6.2 of the VIRTIO spec says:

  5.14.6.2 Driver Requirements: Item Information Request

  - The driver MUST NOT set start_id and count such that start_id +
    count is greater than the total number of particular items that is
    indicated in the device configuration space.

  - The driver MUST provide a buffer of sizeof(struct virtio_snd_hdr) +
    count * size bytes for the response.

While we performed some check for the second requirement, it failed to
check for integer overflow.

Add also a check for the first requirement, which should limit exposure
to any overflow, since realistically the number of streams will be low
enough in value such that overflow is improbable.

Cc: [email protected]
Reported-by: 罗铭源 <[email protected]>
Signed-off-by: Manos Pitsidianakis <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit 61679d7dcf)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-23 21:54:36 +03:00
Manos Pitsidianakis 421123a691 virtio-snd: remove TODO comments
Replying with a VIRTIO_SND_S_BAD_MSG error does not warrant a device
reset. Instead, a device reset happens when the driver requests it from the
transport.

Signed-off-by: Manos Pitsidianakis <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit 34238f078a)
(Mjt: pick this one up so the next commit applies cleanly)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-23 21:54:31 +03:00
Akihiko Odaki f402cbe224 virtio-gpu-virgl: Add virtio-gpu-virgl-hostmem-region type
Commit e27194e087 ("virtio-gpu-virgl: correct parent for blob memory
region") made the name member of MemoryRegion unset, causing a NULL
pointer dereference[1]:
> Thread 2 "qemu-system-x86" received signal SIGSEGV, Segmentation fault.
> (gdb) bt
> #0  0x00007ffff56565e2 in __strcmp_evex () at /lib64/libc.so.6
> #1  0x0000555555841bdb in find_fd (head=0x5555572337d0 <cpr_state>,
> name=0x0, id=0) at ../migration/cpr.c:68
> #2  cpr_delete_fd (name=name@entry=0x0, id=id@entry=0) at
> ../migration/cpr.c:77
> #3  0x000055555582290a in qemu_ram_free (block=0x7ff7e93aa7f0) at
> ../system/physmem.c:2615
> #4  0x000055555581ae02 in memory_region_finalize (obj=<optimized out>)
> at ../system/memory.c:1816
> #5  0x0000555555a70ab9 in object_deinit (obj=<optimized out>,
> type=<optimized out>) at ../qom/object.c:715
> #6  object_finalize (data=0x7ff7e936eff0) at ../qom/object.c:729
> #7  object_unref (objptr=0x7ff7e936eff0) at ../qom/object.c:1232
> #8  0x0000555555814fae in memory_region_unref (mr=<optimized out>) at
> ../system/memory.c:1848
> #9  flatview_destroy (view=0x555559ed6c40) at ../system/memory.c:301
> #10 0x0000555555bfc122 in call_rcu_thread (opaque=<optimized out>) at
> ../util/rcu.c:324
> #11 0x0000555555bf17a7 in qemu_thread_start (args=0x555557b99520) at
> ../util/qemu-thread-posix.c:393
> #12 0x00007ffff556f464 in start_thread () at /lib64/libc.so.6
> #13 0x00007ffff55f25ac in __clone3 () at /lib64/libc.so.6

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

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

Cc: [email protected]
Fixes: e27194e087 ("virtio-gpu-virgl: correct parent for blob memory region")
Fixes: be88ad424c ("virtio-gpu-virgl: correct parent for blob memory region") for 10.2.x
Signed-off-by: Akihiko Odaki <[email protected].i.u-tokyo.ac.jp>
Tested-by: Dmitry Osipenko <[email protected]>
Tested-by: Joelle van Dyne <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Message-Id: <[email protected].i.u-tokyo.ac.jp>
(cherry picked from commit b2a279094c)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-23 21:51:15 +03:00
Helge Deller 22687ae317 hw/hppa: Add BMC on 64-bit machines only
Prevent adding the BMC with it's serial ports on 32-bit machines, even
if they have a PCI bus like the B160L. This fixes boot problems with
HP-UX on B160L.

Signed-off-by: Helge Deller <[email protected]>
Fixes: 557bc5260c ("hw/hppa: PCI devices depend on availability of PCI bus")
Cc: [email protected]
Reviewed-by: Anton Johansson <[email protected]>
(cherry picked from commit 16786eb7bf)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-23 21:46:20 +03:00
Peter Maydell 5fc003f542 target/arm: Don't let 'sme=on' downgrade SME
In our handling of the boolean 'sme' CPU property, we write this 0/1
value directly to ID_AA64PFR1_EL1.SME.  This worked when the only
valid values in that field were 0 (for no SME) and 1 (for SME1).
However, with the addition of SME2 the SME field can now also read 2.
This means that "-cpu max,sme=on" will result in an inconsistent set
of ID registers, where ID_AA64PFR1_EL1.SME claims SME1 but
ID_AA64SMFR0_EL1.SMEver claims SME2p1.  This isn't a valid thing to
report, and confuses Linux into reporting SME2 to userspace but not
actually enabling userspace access for it.

Fix this bug by having arm_cpu_sme_finalize() fix up the
ID_AA64PFR1_EL1.SME field to match ID_AA64SMFR0.SMEver.  This means
the "sme" property's semantics are "off" for "no SME" and "on" for
"enable at whatever the default SME version this CPU provides is".

Update the documentation to clarify what 'sve=on' and 'sme=on' do.
(We don't have the equivalent bug for 'sve=on' because
ID_AA64PFR0_EL1.SVE only has 0 and 1 as valid values, but the
semantics of the property are the same.)

Cc: [email protected]
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Reviewed-by: Manos Pitsidianakis <[email protected]>
Message-id: [email protected]
(cherry picked from commit aeb3c147fc)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-19 22:27:21 +03:00
Peter Maydell aeaff51f58 target/arm/tcg: Allow SVE RAX1 in SME2p1 streaming mode
The SVE RAX1 instruction is permitted in SME streaming mode starting
from SME2p1.  We forgot to allow this relaxation when we implemented
SME2p1.

Cc: [email protected]
Fixes: 7b1613a102 ("target/arm: Enable FEAT_SME2p1 on -cpu max")
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Message-id: [email protected]
(cherry picked from commit 433097a224)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-19 22:25:59 +03:00
Peter Maydell aa9c49d19e target/arm: Fix feature check in DO_SVE2_RRX, DO_SVE2_RRX_TB
In the macros DO_SVE2_RRX and DO_SVE2_RRX_TB we use the
feature check aa64_sve, thus exposing this set of instructions
in SVE as well as SVE2. Use aa64_sve2 instead, so they UNDEF
on an SVE1-only CPU as they should.

Strictly, the condition here should be "SVE2 or SME"; but we
will correct that in a following commit with all the other
missing "or SME" checks.

Cc: [email protected]
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Reviewed-by: Manos Pitsidianakis <[email protected]>
Message-id: [email protected]
(cherry picked from commit ee5bf0962e)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-19 22:25:32 +03:00
Peter Maydell 188b8070ce target/arm: Account for SME in aarch64_sve_narrow_vq() assertion
In aarch64_sve_narrow_vq() we assert that the new VQ is within
the maximum supported range for the CPU. We forgot to update
this to account for SME, which might have a different maximum.

Update the assert to permit any VQ which is valid for either
SVE or SME.

Cc: [email protected]
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Alex Bennée <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Message-id: [email protected]
(cherry picked from commit 42eab40a12)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-19 20:49:14 +03:00
Jamin Lin 0e311e683f hw/i2c/aspeed_i2c: Fix out-of-bounds read in I2C MMIO handlers
The ASPEED I2C controller exposes a per-bus MMIO window of 0x80 bytes on
AST2600/AST1030/AST2700, but the backing regs[] array was sized for only
28 dwords (0x70 bytes). This allows guest reads in the range [0x70..0x7f]
to index past the end of regs[].

Fix this by:
- Sizing ASPEED_I2C_NEW_NUM_REG to match the 0x80-byte window
  (0x80 >> 2 = 32 dwords).
- Avoiding an unconditional pre-read from regs[] in the legacy/new read
  handlers. Initialize the return value to -1 and only read regs[] for
  offsets that are explicitly handled/valid, leaving invalid offsets to
  return -1 with a guest error log.

Signed-off-by: Jamin Lin <[email protected]>
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/3290
Reviewed-by: Cédric Le Goater <[email protected]>
Link: https://lore.kernel.org/qemu-devel/[email protected]
Signed-off-by: Cédric Le Goater <[email protected]>
(cherry picked from commit c2c5beec42)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-17 15:00:32 +03:00
Alex Bradbury 713e807357 docs/about/emulation: Add documentation for hotblocks plugin arguments
Currently just 'inline'.

Signed-off-by: Alex Bradbury <[email protected]>
Reviewed-by: Pierrick Bouvier <[email protected]>
Link: https://lore.kernel.org/qemu-devel/35128cc5a86a0c18418f9d3150fb8771c54ef7d8.1753857212.git.asb@igalia.com
Signed-off-by: Pierrick Bouvier <[email protected]>
(cherry picked from commit e4ed74c9ae)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-17 15:00:32 +03:00
Alex Bradbury cb327d638f contrib/plugins/hotblocks: Print uint64_t with PRIu64 rather than PRId64
qemu_plugin_u64_sum returns a uint64_t, so PRIu64 is the correct format
specifier.

Signed-off-by: Alex Bradbury <[email protected]>
Reviewed-by: Manos Pitsidianakis <[email protected]>
Reviewed-by: Pierrick Bouvier <[email protected]>
Link: https://lore.kernel.org/qemu-devel/5d26c9d99ee87ac4a4034ff64e3d8881253eedf3.1753857212.git.asb@igalia.com
Signed-off-by: Pierrick Bouvier <[email protected]>
(cherry picked from commit e777f6ab91)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-17 15:00:32 +03:00
Alex Bradbury 8532740333 contrib/plugins/hotblocks: Fix off by one error in iteration of sorted blocks
The logic to iterate over the hottest blocks will never reach the last
item in the list, as it checks `it->next != NULL` before entering the
loop. It's hard to trigger this off-by-one error with the default
limit=20, but it is a bug and is problematic if that default is changed
to something larger.

Signed-off-by: Alex Bradbury <[email protected]>
Reviewed-by: Pierrick Bouvier <[email protected]>
Link: https://lore.kernel.org/qemu-devel/f1ba2e57c6126472c0c8310774009f2455efc370.1753857212.git.asb@igalia.com
Signed-off-by: Pierrick Bouvier <[email protected]>
(cherry picked from commit 1c1e45fcd6)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-17 15:00:32 +03:00
Alex Bradbury 2729113a79 contrib/plugins/hotblocks: Correctly free sorted counts list
g_list_free should be passed the head of the list.

Signed-off-by: Alex Bradbury <[email protected]>
Reviewed-by: Manos Pitsidianakis <[email protected]>
Reviewed-by: Pierrick Bouvier <[email protected]>
Link: https://lore.kernel.org/qemu-devel/cf5a00136738b981a12270b76572e8d502daf208.1753857212.git.asb@igalia.com
Signed-off-by: Pierrick Bouvier <[email protected]>
(cherry picked from commit 90fabd5dda)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-17 15:00:32 +03:00
John Snow 6500ee3d5a python: drop uses of pkg_resources
pkg_resources has been fully dropped from modern pip/setuptools
distributions and we should phase out its use. This patch is enough to,
by itself, repair most GitLab CI tests upstream; with the exception of
tox tests which are still making use of avocado - which will be dropped
in a separate series to restore functionality there.

Signed-off-by: John Snow <[email protected]>
Suggested-by: Peter Maydell <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Thomas Huth <[email protected]>
(cherry picked from commit e44a26ba94)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-17 15:00:32 +03:00
Fiona Ebner 641cb36c07 iotests: test active mirror with unaligned, small write zeroes op
This tests the scenario fixed by "block/mirror: check range
when setting zero bitmap for sync write" [0].

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

Signed-off-by: Fiona Ebner <[email protected]>
Message-ID: <[email protected]>
Reviewed-by: Vladimir Sementsov-Ogievskiy <[email protected]>
Tested-by: Vladimir Sementsov-Ogievskiy <[email protected]>
Signed-off-by: Vladimir Sementsov-Ogievskiy <[email protected]>
(cherry picked from commit 267d7ae99a)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-17 15:00:32 +03:00
Fiona Ebner 8d2f7ef7c0 block/mirror: check range when setting zero bitmap for sync write
Some Proxmox users reported an occasional assertion failure [0][1] in
busy VMs when using drive mirror with active mode. In particular, the
failure may occur for zero writes shorter than the job granularity:

> #0  0x00007b421154b507 in abort ()
> #1  0x00007b421154b420 in ?? ()
> #2  0x0000641c582e061f in bitmap_set (map=0x7b4204014e00, start=14, nr=-1)
> #3  0x0000641c58062824 in do_sync_target_write (job=0x641c7e73d1e0,
>       method=MIRROR_METHOD_ZERO, offset=852480, bytes=4096, qiov=0x0, flags=0)
> #4  0x0000641c58062250 in bdrv_mirror_top_do_write (bs=0x641c7e62e1f0,
        method=MIRROR_METHOD_ZERO, copy_to_target=true, offset=852480,
        bytes=4096, qiov=0x0, flags=0)
> #5  0x0000641c58061f31 in bdrv_mirror_top_pwrite_zeroes (bs=0x641c7e62e1f0,
        offset=852480, bytes=4096, flags=0)

The range for the dirty bitmap described by dirty_bitmap_offset and
dirty_bitmap_end is narrower than the original range and in fact,
dirty_bitmap_end might be smaller than dirty_bitmap_offset. There
already is a check for 'dirty_bitmap_offset < dirty_bitmap_end' before
resetting the dirty bitmap. Add such a check for setting the zero
bitmap too, which uses the same narrower range.

[0]: https://forum.proxmox.com/threads/177981/
[1]: https://bugzilla.proxmox.com/show_bug.cgi?id=7222

Cc: [email protected]
Fixes: 7e277545b9 ("mirror: Skip writing zeroes when target is already zero")
Signed-off-by: Fiona Ebner <[email protected]>
Message-ID: <[email protected]>
Reviewed-by: Vladimir Sementsov-Ogievskiy <[email protected]>
Signed-off-by: Vladimir Sementsov-Ogievskiy <[email protected]>
(cherry picked from commit 4a7b1bd18d)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-17 15:00:32 +03:00
Mohamed Mediouni 24690bf836 plugins: fix cross-build using LLVM for Windows targets
llvm-dlltool assumes that it's by default targeting the host architecture
it's running on. That assumption doesn't hold true when cross-compiling.

Signed-off-by: Mohamed Mediouni <[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 b0353beebb)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-17 15:00:32 +03:00
Jaehoon Kim 2cfc92842a s390x/pci: Fix endianness for zPCI BAR values.
During zPCI scan, BAR configuration data retrieved via CLP Query was
misinterpreted due to an endianness mismatch between QEMU and the guest
kernel.

The guest kernel's clp_store_query_pci_fn() expects BAR values in
little-endian format and converts them with le32_to_cpu(). However, QEMU
was incorrectly sending them in big-endian format, not following the
architecture specification. This caused incorrect bit-swapping in the
kernel, leading zpci_setup_bus_resources() to perform registration checks
against invalid flags, making the process ineffective.

Observation values for zPCI device (NVMe passthrough):
LPAR from real CLP:
[    0.865595] Resource: PCI Bus 0000:00 -> zdev->bar[0].val: 0x4
[    0.865597]  start: 0x4000000000000000
[    0.865598]  end:   0x4000000000003fff
[    0.865600]  flags: 0x100200

QEMU before fix (wrong):
[    0.601083] Resource: PCI Bus 0001:00 -> zdev->bar[0].val: 0x4000000
[    0.601085]  start: 0x4003000000000000
[    0.601086]  end:   0x4003000000003fff
[    0.601087]  flags: 0x200

QEMU after fix (correct):
[    0.601116] Resource: PCI Bus 0001:00 -> zdev->bar[0].val: 0x4
[    0.601117]  start: 0x4003000000000000
[    0.601118]  end:   0x4003000000003fff
[    0.601119]  flags: 0x100200

Signed-off-by: Jaehoon Kim <[email protected]>
Reviewed-by: Matthew Rosato <[email protected]>
Reviewed-by: Farhan Ali <[email protected]>
Reviewed-by: Eric Farman <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Thomas Huth <[email protected]>
(cherry picked from commit 00ebc44514)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-12 15:20:05 +03:00
Michael Tokarev 2d3df8abca Update version for 10.2.1 release
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-12 15:15:05 +03:00
Andrey Drobyshev 63a76e0123 scripts/qemugdb: timers: Fix KeyError in 'qemu timers' command
Currently invoking 'qemu timers' command results into: "gdb.error: There
is no member named last".  Let's remove the legacy 'last' field from
QEMUClock, as it was removed in v4.2.0 by the commit 3c2d4c8aa6
("timer: last, remove last bits of last").

Signed-off-by: Andrey Drobyshev <[email protected]>
Reviewed-by: Stefan Hajnoczi <[email protected]>
Message-id: [email protected]
Signed-off-by: Stefan Hajnoczi <[email protected]>
(cherry picked from commit 80c97930a9)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-10 12:46:22 +03:00
Paolo Bonzini b5ce6809b4 Revert "tcg/user: do not set exit_request gratuitously"
This reverts commit b422a7bff6.

The reporter says "The commit breaks go; if you run go build in a loop,
it eventually hangs uninterruptible (except -9) with a couple of zombie
children left over".

Reported-by: Andreas Schwab <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit 251a3d4ca3)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-10 12:44:50 +03:00
Aleksandr Sergeev 1af5215667 linux-user/syscall.c: Prevent acquiring clone_lock while fork()
By the spec, fork() copies only the thread which executes it.
So it may happen, what while one thread is doing a fork,
another thread is holding `clone_lock` mutex
(e.g. doing a `fork()` or `exit()`).
So the child process is born with the mutex being held,
and there are nobody to release it.

As the thread executing do_syscall() is not considered running,
start_exclusive() does not protect us from the case.

Resolves: https://gitlab.com/qemu-project/qemu/-/issues/3226
Signed-off-by: Aleksandr Sergeev <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit d22e9aec57)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-10 12:42:54 +03:00
Jonathan Cameron ba31a6fca7 hw/cxl: Take into account how many media operations are requested for param check
Whilst the spec doesn't speak to it directly my assumption is that
a request for more operations than exist should result in an invalid
input error return.

Fixes: 77a8e9fe0e ("hw/cxl/cxl-mailbox-utils: Add support for Media operations discovery commands cxl r3.2 (8.2.10.9.5.3)")
Closes: https://lore.kernel.org/qemu-devel/CAFEAcA-p5wZkNxK7wNVq_3PAzEE-muOd1Def-0O-FSpck4DrBQ@mail.gmail.com/
Reported-by: Peter Maydell <[email protected]>
Signed-off-by: Jonathan Cameron <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit 25465c0e1f)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-06 01:12:25 +03:00
Jonathan Cameron fd0abbb386 hw/cxl: Check for overflow on santize media as both base and offset 64bit.
The both the size and base of a media sanitize operation are both provided
by the VM, an overflow is possible which may result in checks on valid
range passing when they should not.  Close that by checking for overflow
on the addition.

Fixes: 40ab4ed107 ("hw/cxl/cxl-mailbox-utils: Media operations Sanitize and Write Zeros commands CXL r3.2(8.2.10.9.5.3)")
Closes: https://lore.kernel.org/qemu-devel/CAFEAcA8Rqop+ju0fuxN+0T57NBG+bep80z45f6pY0ci2fz_G3A@mail.gmail.com/
Reported-by: Peter Maydell <[email protected]>
Signed-off-by: Jonathan Cameron <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit 87f8e5a71d)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-06 01:12:25 +03:00
Honglei Huang e5628119e1 virtio-gpu: fix error handling in virgl_cmd_resource_create_blob
Fix inverted error check in virgl_cmd_resource_create_blob() that causes
the function to return error when virtio_gpu_create_mapping_iov() succeeds.

virtio_gpu_create_mapping_iov() returns 0 on success and negative values
on error. The check 'if (!ret)' incorrectly treats success (ret=0) as an
error condition, causing the function to fail when it should succeed.

Change the condition to 'if (ret != 0)' to properly detect errors.

Fixes: 7c092f17cc ("virtio-gpu: Handle resource blob commands")
Signed-off-by: Honglei Huang <[email protected]>
Reviewed-by: Akihiko Odaki <[email protected].i.u-tokyo.ac.jp>
Reviewed-by: Dmitry Osipenko <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit 3560b51979)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-06 01:07:26 +03:00
Li Chen cfc706b38e virtio-pmem: ignore empty queue notifications
virtio_pmem_flush() treats a NULL return from virtqueue_pop() as a fatal
error and calls virtio_error(), which puts the device into NEEDS_RESET.

However, virtqueue handlers can be invoked when no element is available,
so an empty queue should be handled as a benign no-op.

With a Linux guest this avoids spurious NEEDS_RESET and the resulting
-EIO propagation (e.g. EXT4 journal abort and remount-ro).

Signed-off-by: Li Chen <[email protected]>
Acked-by: Michael S. Tsirkin <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit efd581a8cd)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-06 01:00:27 +03:00
Joelle van Dyne be88ad424c virtio-gpu-virgl: correct parent for blob memory region
When `owner` == `mr`, `object_unparent` will crash:

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

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

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

Signed-off-by: Joelle van Dyne <[email protected]>
Reviewed-by: Akihiko Odaki <[email protected].i.u-tokyo.ac.jp>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit e27194e087)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-06 00:49:47 +03:00
zhenwei pi 51514aa3c2 cryptodev-builtin: Limit the maximum size
This backend driver is used for demonstration purposes only, unlimited
size leads QEMU OOM.

Fixes: CVE-2025-14876
Fixes: 1653a5f3fc ("cryptodev: introduce a new cryptodev backend")
Reported-by: 이재영 <[email protected]>
Signed-off-by: zhenwei pi <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit 7b913094c7)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-06 00:47:21 +03:00
zhenwei pi 2ac11c1d93 hw/virtio/virtio-crypto: verify asym request size
The total lenght of request is limited by cryptodev config, verify it
to avoid unexpected request from guest.

Fixes: CVE-2025-14876
Fixes: 0e660a6f90 ("crypto: Introduce RSA algorithm")
Reported-by: 이재영 <[email protected]>
Signed-off-by: zhenwei pi <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit 91c6438caf)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-06 00:46:52 +03:00
Igor Mammedov 080b623ed4 q35: Fix migration of SMRAM state
When migrating, dst QEMU by default has SMRAM unlocked,
and since wmask is not migrated, the migrated value of
MCH_HOST_BRIDGE_F_SMBASE in config space fall to prey of

  mch_update_smbase_smram()
    ...
    if (pd->wmask[MCH_HOST_BRIDGE_F_SMBASE] == 0xff) {
        *reg = 0x00;

and is getting cleared and leads to unlocked smram
on dst even if on source it's been locked.

As Andrey has pointed out [1], we should derive wmask
from config and not other way around.

Drop offending chunk and resync wmask based on MCH_HOST_BRIDGE_F_SMBASE
register value. That would preserve the register during
migration and set smram regions into corresponding state.

What that changes is:
that it would let guest write junk values in register
(with no apparent effect) until it's stumbles upon
reserved 0x1 [|] 0x2 values, at which point it
would be only possible to lock register and trigger
switch to SMRAM blackhole in CPU AS.

While at it, fix up test by removing junk discard before negotiation hunk.

PS2:
Instead of adding a dedicated post_load handler for it,
reuse mch_update->mch_update_smbase_smram call chain
that is called on write/reset/post_load to be consistent
with how we handle mch registers.

PS3:
for prosterity here is erro message Andrey got due to this bug:
    qemu: vfio_container_dma_map(0x..., 0x0, 0xa0000, 0x....) = -22 (Invalid argument)
    qemu: hardware error: vfio: DMA mapping failed, unable to continue

1) https://patchew.org/QEMU/[email protected]/

Fixes: f404220e27 ("q35: implement 128K SMRAM at default SMBASE address")
Reported-by: Andrey Ryabinin <[email protected]>
Signed-off-by: Igor Mammedov <[email protected]>
Reviewed-by: Andrey Ryabinin <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit 66cf169e29)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-06 00:46:09 +03:00
Kevin Wolf 8c65f73b31 pcie_sriov: Fix PCI_SRIOV_* accesses in pcie_sriov_pf_exit()
PCI_SRIOV_* are offsets into the SR-IOV capability, not into the PCI
config space. pcie_sriov_pf_exit() erroneously takes them as the latter,
which makes it read PCI_HEADER_TYPE and PCI_BIST when it tries to read
PCI_SRIOV_TOTAL_VF.

In many cases we're lucky enough that the PCI config space will be 0
there, so we just skip the whole for loop, but this isn't guaranteed.
For example, setting the multifunction bit on the PF and then doing a
'device_del' on it will get a larger number and cause a segfault.

Fix this and access the real PCI_SRIOV_* fields in the capability.

Cc: [email protected]
Fixes: 19e55471d4 ('pcie_sriov: Allow user to create SR-IOV device')
Signed-off-by: Kevin Wolf <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit f73e5ed9bc)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-06 00:45:06 +03:00
Kevin Wolf a440980876 virtio: Fix crash when sriov-pf is set for non-PCI-Express device
Setting the sriov-pf property on devices that aren't PCI Express causes
an assertion failure:

    $ qemu-system-x86_64 \
        -blockdev null-co,node-name=null \
        -blockdev null-co,node-name=null2 \
        -device virtio-blk,drive=null,id=pf \
        -device virtio-blk,sriov-pf=pf,drive=null2
    qemu-system-x86_64: ../hw/pci/pcie.c:1062: void pcie_add_capability(PCIDevice *, uint16_t, uint8_t, uint16_t, uint16_t): Assertion `offset >= PCI_CONFIG_SPACE_SIZE' failed.

This is because proxy->last_pcie_cap_offset is only initialised to a
non-zero value in virtio_pci_realize() if it's a PCI Express device, and
then virtio_pci_device_plugged() still tries to use it.

To fix this, just skip the SR-IOV code for !pci_is_express(). Then the
next thing pci_qdev_realize() does is call pcie_sriov_register_device(),
which returns the appropriate error.

Cc: [email protected]
Fixes: d0c280d3fa ('pcie_sriov: Make a PCI device with user-created VF ARI-capable')
Signed-off-by: Kevin Wolf <[email protected]>
Reviewed-by: Stefan Hajnoczi <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit 623db85647)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-06 00:44:47 +03:00
Dorinda Bassey ab67c542a9 virtio-dmabuf: Ensure UUID persistence for hash table insertion
In `virtio_add_resource` function, the UUID used as a key for
`g_hash_table_insert` was temporary, which could lead to
invalid lookups when accessed later. This patch ensures that
the UUID remains valid by duplicating it into a newly allocated
memory space. The value is then inserted into the hash table
with this persistent UUID key to ensure that the key stored in
the hash table remains valid as long as the hash table entry
exists.

Fixes: faefdba847 ("hw/display: introduce virtio-dmabuf")
Signed-off-by: Dorinda Bassey <[email protected]>
Reviewed-by: Stefano Garzarella <[email protected]>
Reviewed-by: Albert Esteve <[email protected]>
Reviewed-by: Marc-André Lureau <[email protected]>
Reviewed-by: Jim MacArthur <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit fff77cfb84)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-06 00:42:22 +03:00
Wafer Xie ad2c2ef5e5 vdpa: fix vhost-vdpa suspended state not be shared
When stopping a vhost-vdpa device, only the first queue pair is marked as suspended,
while the remaining queues are not updated to the suspended state.
As a result, when stopping a multi-queue vhost-vdpa device,
the following error message will be printed.

qemu-system-x86_64:vhost VQ 2 ring restore failed: -1: Operation not permitted (1)

qemu-system-x86_64:vhost VQ 3 ring restore failed: -1: Operation not permitted (1)

So move v->suspended to v->shared, and then all the vhost_vdpa devices cannot
have different suspended states.

Fixes: 0bb302a996 ("vdpa: add vhost_vdpa_suspend")
Suggested-by: Eugenio Pérez <[email protected]>
Acked-by: Eugenio Pérez <[email protected]>
Acked-by: Jason Wang <[email protected]>
Signed-off-by: Wafer Xie <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Acked-by: Jason Wang <[email protected]>
Message-Id: <[email protected]>
(cherry picked from commit fd3a2c601a)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-06 00:31:38 +03:00
Jamin Lin 0b1ddf19d0 hw/i2c/aspeed_i2c: Fix DMA moving data into incorrect address
In the previous design, the I2C model updated dma_dram_offset only when
firmware programmed the RX/TX DMA buffer address registers. The firmware
used to rewrite these registers before issuing each DMA command.

The firmware driver behavior has changed to program the DMA address
registers only once during I2C initialization. As a result, the I2C model
no longer refreshes dma_dram_offset, causing DMA to move data into an
incorrect DRAM address.

Fix this by introducing helper functions to update dma_dram_offset from
the DMA address registers, and invoke them right before handling TX/RX
DMA operations. This guarantees DMA always uses the correct buffer
address even if the registers are programmed only once.

Signed-off-by: Jamin Lin <[email protected]>
Fixes: c400c38854 ("hw/i2c/aspeed: Introduce a new dma_dram_offset attribute in AspeedI2Cbus")
Reviewed-by: Cédric Le Goater <[email protected]>
Link: https://lore.kernel.org/qemu-devel/[email protected]
Signed-off-by: Cédric Le Goater <[email protected]>
(cherry picked from commit efea7ddb46)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-06 00:13:25 +03:00
Jamin Lin a66c02ea9d hw/i2c/aspeed: Fix wrong I2CC_DMA_LEN when I2CM_DMA_TX/RX_ADDR set first
In the previous design, the I2C model would update I2CC_DMA_LEN (0x54) based on
the value of I2CM_DMA_LEN (0x1C) when the firmware set either I2CM_DMA_TX_ADDR
(0x30) or I2CM_DMA_RX_ADDR (0x34). However, this only worked correctly if the
firmware set I2CM_DMA_LEN before setting I2CM_DMA_TX_ADDR or I2CM_DMA_RX_ADDR.

If the firmware instead set I2CM_DMA_TX_ADDR or I2CM_DMA_RX_ADDR before setting
I2CM_DMA_LEN, the value written to I2CC_DMA_LEN would be incorrect.

To fix this issue, the model should be updated to set I2CC_DMA_LEN when the
firmware writes to the I2CM_DMA_LEN register, rather than when it writes to the
I2CM_DMA_RX_ADDR and I2CM_DMA_TX_ADDR registers.

Signed-off-by: Jamin Lin <[email protected]>
Fixes: ba2cccd64e ("aspeed: i2c: Add new mode support")
Reviewed-by: Cédric Le Goater <[email protected]>
Link: https://lore.kernel.org/qemu-devel/[email protected]
Signed-off-by: Cédric Le Goater <[email protected]>
(cherry picked from commit 9cbd8ee7f6)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-06 00:13:25 +03:00
Jamin Lin 146214796c hw/arm/aspeed_ast27x0: Fix EHCI3/4 IRQ routing to GIC
EHCI3 and EHCI4 were missing entries in aspeed_soc_ast2700a1_irqmap,
so their source IRQs were never routed through the INTC OR-gates.

As a result, EHCI3/4 interrupts were not propagated to the GIC,
causing incorrect interrupt behavior for these controllers.

Add EHCI3 and EHCI4 to the IRQ map and route them to the same INTC
group as other shared peripherals, ensuring their interrupts are
properly connected to the GIC.

Signed-off-by: Jamin Lin <[email protected]>
Fixes: ba27ba302a ("hw/arm: ast27x0: Wire up EHCI controllers")
Reviewed-by: Cédric Le Goater <[email protected]>
Link: https://lore.kernel.org/qemu-devel/[email protected]
Signed-off-by: Cédric Le Goater <[email protected]>
(cherry picked from commit 7d64f04863)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-06 00:07:28 +03:00
Nabih Estefan 2f46d99451 hw/i2c/aspeed_i2c.c: Add a check for dma_read
If aspeed_i2c_dma_read fails in aspeed_i2c_bus_send currently, we get
stuck in an infinite retry loop. Add a check for the return value of
aspeed_i2c_dma_read that will break us out of said loop.

Signed-off-by: Nabih Estefan <[email protected]>
Reviewed-by: Cédric Le Goater <[email protected]>
Fixes: 545d6bef70 ("aspeed/i2c: Add support for DMA transfers")
Link: https://lore.kernel.org/qemu-devel/[email protected]
Signed-off-by: Cédric Le Goater <[email protected]>
(cherry picked from commit 0a1d477067)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-06 00:04:10 +03:00
Cédric Le Goater d4c6c60993 hw/adc: Fix out-of-bounds write in Aspeed ADC model
The 'regs' array has ASPEED_ADC_NR_REGS (52) elements, while the
memory region covers offsets 0x00-0xFC. The aspeed_adc_engine_write()
function has an out-of-bounds write vulnerability when accessing
unimplemented registers.

Fix this by using 'return' instead of 'break' in the default case,
which prevents execution from reaching the s->regs[reg] assignment for
unimplemented registers.

Reported-by: Elhrj Saad <[email protected]>
Fixes: 5857974d5d ("hw/adc: Add basic Aspeed ADC model")
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Link: https://lore.kernel.org/qemu-devel/[email protected]
Signed-off-by: Cédric Le Goater <[email protected]>
(cherry picked from commit 4c6521296d)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-06 00:02:27 +03:00
Gerd Hoffmann 8bf4744182 hw/uefi: fix size negotiation
Payload size is the variable request size, not the total buffer size.
Take that into account and subtract header sizes.

Fixes: db1ecfb473 ("hw/uefi: add var-service-vars.c")
Signed-off-by: Gerd Hoffmann <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit 46dee71a94)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-04 11:00:23 +03:00
Akihiko Odaki 89f7d4fb13 hw/nvme: Fix bootindex suffix use-after-free
The bootindex suffix can be used as long as the property is alive.

Signed-off-by: Akihiko Odaki <[email protected].i.u-tokyo.ac.jp>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Message-ID: <[email protected].i.u-tokyo.ac.jp>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit eda9baa17a)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-03 10:59:53 +03:00
John Snow a2fbfefbb7 python: fix msys64 wheel directory specification
In python3.14, fixes were made to the file URI parsing [1] such that
file URIs that used to work but were technically out of spec are now
broken.

As a result, our msys2 GitLab CI tests began failing.

Stop using "file://" URI links in favor of simple paths (Thanks pbo) to
fix parsing errors under Python 3.14 and fix the msys2 GitLab CI tests.

[1] https://docs.python.org/3/whatsnew/3.14.html#urllib

Reported-by: Pierrick Bouvier <[email protected]>
Suggested-by: Pierrick Bouvier <[email protected]>
Signed-off-by: John Snow <[email protected]>
Reviewed-by: Pierrick Bouvier <[email protected]>
Tested-by: Pierrick Bouvier <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit 587f4a1805)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-02 16:50:52 +03:00
Ilia Levi 0c2fd08dc8 tests/qtest/ufs-test: Add test for mcq completion queue wraparound
Added a test that sends 32 NOP Out commands asynchronously. Since the CQ
has 31 entries by default, this tests the scenario where CQ processing
needs to wait for space to become available.

Additionally, added two minor fixes to existing tests:
* advance CQ head after reading from CQ
* initialize command descriptor slots bitmap in ufs_init()

Signed-off-by: Ilia Levi <[email protected]>
Acked-by: Fabiano Rosas <[email protected]>
Reviewed-by: Jeuk Kim <[email protected]>
Signed-off-by: Jeuk Kim <[email protected]>
(cherry picked from commit 94e72135d4)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-02 16:21:37 +03:00
Ilia Levi ad5f6ffcd0 hw/ufs: Fix mcq completion queue wraparound
Currently, ufs_mcq_process_cq() writes to the CQ without checking whether
there is available space. This can cause CQ entries to be discarded and
overwritten. The solution is to stop writing when CQ is full and exert
backpressure on the affected SQs. This is similar to how NVMe CQs operate.

Signed-off-by: Ilia Levi <[email protected]>
Reviewed-by: Jeuk Kim <[email protected]>
Signed-off-by: Jeuk Kim <[email protected]>
(cherry picked from commit f78762a3cc)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-02 16:21:37 +03:00
Jeuk Kim 88ef8726ff hw/ufs: fix CQE endianness and UPIU length
Round-trip UTRD fields through cpu_to_le/ le_to_cpu when building MCQ CQEs to
keep BE hosts correct. Also avoid double BE conversion of response
data_segment_length and document the LE round-trip.

Signed-off-by: Jeuk Kim <[email protected]>
(cherry picked from commit ed621cc8e2)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-02 16:21:37 +03:00
Jeuk Kim cce96e6052 hw/ufs: Ensure DBC of PRDT uses only lower 18 bits
The UFS spec defines the PRDT data byte count as an 18-bit field. This
commit masks the value to the lower 18 bits to prevent incorrect
transfer lengths and ensure compliance.

Signed-off-by: Jeuk Kim <[email protected]>
(cherry picked from commit 289e6a3edf)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-02 16:21:37 +03:00
Alex Bennée 92e6f27829 tests/functional: migrate sbsa_ref test images
As the builds in codelinaro.org are going away migrate the binaries to
share.linaro.org. As the hotlinks don't encode the filename we need to
explicitly tell uncompress how to handle the files.

Tested-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Pierrick Bouvier <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Alex Bennée <[email protected]>
(cherry picked from commit d9ca273f8f)
Signed-off-by: Michael Tokarev <[email protected]>
2026-02-02 16:18:57 +03:00
Thomas Huth 49d3f1381d pc-bios/optionrom: Use 32-bit linker emulation for the optionroms
Without this linker flag, the linking fails on NetBSD v10.1 with:

 ld: i386 architecture of input file `multiboot.o' is incompatible with i386:x86-64 output
 ld: i386 architecture of input file `multiboot_dma.o' is incompatible with i386:x86-64 output

Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Thomas Huth <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit e4f1a9b1da)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-28 12:06:55 +03:00
Daniel P. Berrangé 8aee37581e gitlab: preserve base rules for container template
When extending the container template to allow scheduled pipelines in
upstream context, we must ensure that all the existing rules defined
by .base_job_template are preserved.

Fortunately since the new rule for scheduled pipelines can come at
the head of all other rules, not in the middle, we can just the obscure
'!reference' syntax to pull in all the pre-existing rules as a single
block.

This fixes

 * stable branches using the wrong tag name in container images
 * pushes to forks unconditionally running container builds

Fixes: 8bec7b9874
Signed-off-by: Daniel P. Berrangé <[email protected]>
Tested-by: Michael Tokarev <[email protected]>
Fixes: 8bec7b9874 ("gitlab: add a weekly container building job")
Message-ID: <[email protected]>
Signed-off-by: Thomas Huth <[email protected]>
(cherry picked from commit 815567b4ea)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-28 12:05:14 +03:00
Paolo Bonzini f48aaf926e target/i386/tcg: fix a few instructions that do not support VEX.L=1
Match the contents of table 2-17 ("#UD Exception and VEX.L Field Encoding")
in the SDM, for instruction in exception class 5.  They were incorrectly
accepting 256-bit versions that do not exist.

Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 2eb8d97343)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-28 12:01:22 +03:00
Icenowy Zheng d0be1b581c linux-user: fixup termios2 related things on PowerPC
The termios things on PowerPC equal to termios2 things otherwhere.

Use some simple #define's to allow both termios and termios2 to map to
termios on PowerPC.

Signed-off-by: Icenowy Zheng <[email protected]>
Link: https://github.com/AOSC-Dev/aosc-os-abbs/blob/8d77eeaa76e9b159c3f35adaf73c875751aa7d17/app-virtualization/qemu/01-shared/patches/0005-AOSCOS-linux-user-fixup-termios2-related-things-on-P.patch
Link: https://lore.kernel.org/qemu-devel/[email protected]
Reviewed-by: Helge Deller <[email protected]>
(cherry picked from commit d68f0e2e90)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-24 23:47:45 +03:00
Vivian Wang 1e762859ce linux-user: Add missing termios baud rates
Add several missing baud rates and inputs baud rates in cflag_tbl.

Add these missing definitions in termbits.h:

- TARGET_BOTHER for alpha, hppa, ppc, sh4, sparc
- TARGET_IBSHIFT for hppa, mips, ppc, sh4, sparc
- Missing standard baud rates for hppa

These are required for the glibc test tst-termios-linux.

Link: https://lore.kernel.org/qemu-devel/20251203-linux-user-higher-baud-rates-v2-1-e45b35224437@iscas.ac.cn
Signed-off-by: Vivian Wang <[email protected]>
Reviewed-by: Helge Deller <[email protected]>
(cherry picked from commit 4f22fcb5c6)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-24 23:47:45 +03:00
Luca Bonissi 22a55fc7df linux-user: Add termios2 support to sparc target
Signed-off-by: Luca Bonissi <[email protected]>
Link: https://lore.kernel.org/qemu-devel/[email protected]
Reviewed-by: Helge Deller <[email protected]>
(cherry picked from commit 947b971cad)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-24 23:47:45 +03:00
Luca Bonissi c1fac5fbfe linux-user: Add termios2 support to sh4 target
Signed-off-by: Luca Bonissi <[email protected]>
Link: https://lore.kernel.org/qemu-devel/[email protected]
Reviewed-by: Helge Deller <[email protected]>
(cherry picked from commit afbe0ff81c)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-24 23:47:45 +03:00
Luca Bonissi ce78d40265 linux-user: Add termios2 support to mips target
Signed-off-by: Luca Bonissi <[email protected]>
Link: https://lore.kernel.org/qemu-devel/[email protected]
Reviewed-by: Helge Deller <[email protected]>
(cherry picked from commit edf9184f4f)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-24 23:47:45 +03:00
Luca Bonissi 06cfe78536 linux-user: Add termios2 support to hppa target
Signed-off-by: Luca Bonissi <[email protected]>
Link: https://lore.kernel.org/qemu-devel/[email protected]
Reviewed-by: Helge Deller <[email protected]>
(cherry picked from commit edc741710a)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-24 23:47:45 +03:00
Luca Bonissi 20b93df8d7 linux-user: Add termios2 support to alpha target
Signed-off-by: Luca Bonissi <[email protected]>
Link: https://lore.kernel.org/qemu-devel/[email protected]
Reviewed-by: Helge Deller <[email protected]>
(cherry picked from commit 8d8c6aeee8)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-24 23:47:45 +03:00
Luca Bonissi 5380228f7f linux-user: Add termios2 support
Signed-off-by: Luca Bonissi <[email protected]>
Link: https://lore.kernel.org/qemu-devel/[email protected]
Reviewed-by: Helge Deller <[email protected]>
Tested-by: Heinrich Schuchardt <[email protected]>
(cherry picked from commit e9a8a10e84)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-24 23:47:45 +03:00
Alex Bennée ba3581de79 hw/intc: avoid byte swap fiddling in gicv3 its path
This allows us to keep the MSI data in plain host order all the way
from the MemoryRegionOps write method to the final KVM_SIGNAL_MSI
ioctl. This fixes a theoretical bug on big-endian hosts because we
were using different size byte swaps which would have truncated the data.

Signed-off-by: Alex Bennée <[email protected]>
Reviewed-by: Peter Maydell <[email protected]>
Message-id: [email protected]
Cc: [email protected]
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit cf10273aff)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-24 09:20:18 +03:00
Pierrick Bouvier 9707eaa47b bsd-user/syscall_defs.h: define STAT_TIME_T_EXT only for 32 bits
Commit 369c1ba2b changed the wrong conditional "#if defined(__i386__)" to
"#if defined(TARGET_I386)".
However, TARGET_I386 is defined for target x86_64 also.

This commit fixes it by identifying correctly 32 bits target.

Found with:
$ ./build/qemu-x86_64 \
  -plugin ./build/contrib/plugins/libstoptrigger,icount=1000000 \
  -plugin ./build/tests/tcg/plugins/libinsn \
  -d plugin \
  ./build/qemu-system-x86_64 --version
ld-elf.so.1: /lib/libz.so.6: invalid file format
cpu 0 insns: 59746
total insns: 59746

Fixes: 369c1ba2b ("Fix __i386__ test for TARGET_HAS_STAT_TIME_T_EXT")
Fixes: dba028d1b ("Fix __i386__ test for TARGET_HAS_STAT_TIME_T_EXT" in 10.2.x)
Signed-off-by: Pierrick Bouvier <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Warner Losh <[email protected]>
Reviewed-by: Michael Tokarev <[email protected]>
Signed-off-by: Michael Tokarev <[email protected]>
(cherry picked from commit f0de58ccf6)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-21 10:25:42 +03:00
Richard Henderson ff338c6f78 bsd-user: Fix __i386__ test for TARGET_HAS_STAT_TIME_T_EXT
The target test is TARGET_I386, not __i386__.

Cc: Kyle Evans <[email protected]>
Reviewed-by: Warner Losh <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Pierrick Bouvier <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
(cherry picked from commit 369c1ba2b7)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-21 10:23:05 +03:00
Bernhard Beschow 769d19221e hw/sd/sdhci: Fix TYPE_IMX_USDHC to implement sd-spec-version 3 by default
Fixes TYPE_FSL_IMX6UL, TYPE_FSL_IMX7, and TYPE_FSL_IMX8MP to implement
version 3 of the SD specification.

Note that TYPE_FSL_IMX6 already had "sd-spec-version" set accordingly and
that TYPE_FSL_IMX25 correctly sets the same property to version 2 since the
real hardware is an eSDHC which is the uSDHC's predecessor.

Fixes: fd1e5c8179 ("sdhci: Add i.MX specific subtype of SDHCI")
cc: qemu-stable
Signed-off-by: Bernhard Beschow <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Tested-by: BALATON Zoltan <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit 214f79fdfb)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-21 10:23:05 +03:00
Pierrick Bouvier 6f54455c10 linux-user/aarch64/target_fcntl.h: add missing TARGET_O_LARGEFILE definition
This caused a failure with program using openat2, where O_LARGEFILE was
replaced by O_NOFOLLOW.
This issue is only visible when QEMU is compiled with musl libc, where
O_LARGEFILE is different from 0 (vs glibc).

Resolves: https://gitlab.com/qemu-project/qemu/-/issues/3262
Cc: [email protected]
Signed-off-by: Pierrick Bouvier <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Michael Tokarev <[email protected]>
Signed-off-by: Michael Tokarev <[email protected]>
(cherry picked from commit 83017c4aaa)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-21 10:23:05 +03:00
Philippe Mathieu-Daudé 4131a1d83c accel/nvmm: Fix 'cpu' typo in nvmm_init_vcpu()
Fix typo to avoid the following build failure:

  target/i386/nvmm/nvmm-all.c: In function 'nvmm_init_vcpu':
  target/i386/nvmm/nvmm-all.c:988:9: error: 'AccelCPUState' has no member named 'vcpu_dirty'
    988 |     qcpu->vcpu_dirty = true;
        |         ^~

Cc: [email protected]
Reported-by: Thomas Huth <[email protected]>
Fixes: 2098164a6b ("accel/nvmm: Replace @dirty field by generic CPUState::vcpu_dirty field")
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
Tested-by: Thomas Huth <[email protected]>
Reviewed-by: Pierrick Bouvier <[email protected]>
Tested-by: Pierrick Bouvier <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit 7be4256281)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-18 20:29:45 +03:00
Peter Maydell 6bcd958030 target/arm: Correctly trap HCR.TID1 registers in v7A
In v7A HCR.TID1 is defined to trap for TCMTR, TLBTR, REVIDR and AIDR.
We incorrectly use an accessfn for REVIDR and AIDR that only traps on
v8A cores.  Fix this by collapsing access_aa64_tid1() and
access_aa32_tid1() together and never doing a check for v8 vs v7.

The accessfn is also used for SMIDR_EL1, which is fine as this
register is AArch64 only.

Cc: [email protected]
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Alex Bennée <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Message-id: [email protected]
(cherry picked from commit b67a35622f)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-18 20:29:45 +03:00
Peter Maydell 5ead00ce11 target/arm: Correctly honour HCR.TID3 for v7A cores
The HCR.TID3 bit defines that we should trap to the hypervisor for
reads to a collection of ID registers. Different architecture versions
have defined this differently:

 * v7A has a set of ID regs that definitely must trap:
    - ID_PFR{0,1}, ID_DFR0, ID_AFR0, ID_MMFR{0,1,2,3},
      ID_ISAR{0,1,2,3,4,5}, MVFR{0,1}
   and somewhat vaguely says that "there is no requirement"
   to trap for registers that are reserved in the ID reg space
   (i.e. which RAZ and might be used for new ID regs in future)
 * v8A adds to this list:
    - ID_PFR2 and MVFR2 must trap
    - ID_MMFR4, ID_MMFR5, ID_ISAR6, ID_DFR1 and reserved registers
      in the ID reg space must trap if FEAT_FGT is implemented,
      and it is IMPDEF if they trap if FEAT_FGT is not implemented

In QEMU we seem to have attempted to implement this distinction
(taking the "we do trap" IMPDEF choice if no FEAT_FGT), with
access_aa64_tid3() always trapping on TID3 and access_aa32_tid3()
trapping only if ARM_FEATURE_V8 is set.  However, we didn't apply
these to the right set of registers: we use access_aa32_tid3() on all
the 32-bit ID registers *except* ID_PFR2, ID_DFR1, ID_MMFR5 and the
RES0 space, which means that for a v7 CPU we don't trap on a lot of
registers that we should trap on, and we do trap on various things
that the v7A Arm ARM says there is "no requirement" to trap on.

Straighten this out by naming the access functions more clearly for
their purpose, and documenting this: access_v7_tid3() is only for the
fixed set of ID registers that v7A traps on HCR.TID3, and
access_tid3() is for any others, including the reserved encoding
spaces and any new registers we add in future.

AArch32 MVFR2 access is handled differently, in check_hcr_el2_trap;
there we already do not trap on TID3 on v7A cores (where MVFR2
doesn't exist), because we in the code-generation function we UNDEF
if ARM_FEATURE_V8 is not set, without generating code to call
check_hcr_el2_trap.

This bug was causing a problem for Xen which (after a recent change
to Xen) expects to be able to trap ID_PFR0 on a Cortex-A15.

The result of these changes is that our v8A behaviour remains
the same, and on v7A we now trap the registers the Arm ARM definitely
requires us to trap, and don't trap the reserved space that "there is
no requirement" to trap.

Cc: [email protected]
Fixes: 6a4ef4e5d1 ("target/arm: Honor HCR_EL2.TID3 trapping requirements")
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Alex Bennée <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Message-id: [email protected]
(cherry picked from commit 205ca535ab)
(Mjt: trivial context fix around AA64MMFR4_EL1 definition)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-18 20:29:05 +03:00
Peter Maydell bcc7fc8f81 target/arm: Don't specify ID_PFR1 accessfn twice
In the definition of ID_PFR1 we have an ifdef block; we specify the
accessfn once in the common part of the ifdef and once in the
not-user-only part, which is redundant but harmless.

The accessfn will always return success in user-only mode (because
we won't trap to EL2), so specify it only in the not-user-only
half of the ifdef, as was probably the intention.

This is only cc'd to stable to avoid a textual conflict with
the following patch, which is a bug fix.

Cc: [email protected]
Fixes: 0f150c8499 ("target/arm: Constify ID_PFR1 on user emulation")
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Alex Bennée <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Message-id: [email protected]
(cherry picked from commit 8da52b8401)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-18 19:35:21 +03:00
Alex Bennée 35abae4511 tests/functional: migrate aspeed_rainier image
Cedric has a host for the file which allows us to keep the name.

Cc: [email protected]
Signed-off-by: Alex Bennée <[email protected]>
Reviewed-by: Cédric Le Goater <[email protected]>
Message-id: [email protected]
Cc: Cédric Le Goater <[email protected]>
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit 7cf096d609)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-18 19:35:21 +03:00
Philippe Mathieu-Daudé d9dd5dad31 hw/arm: Re-enable the MAX78000FTHR machine in qemu-system-arm/aarch64
Unfortunately while rebasing the series registering the
ARM/Aarch64 machine interfaces and getting it merged as
commit 38c5ab4003 ("hw/arm: Filter machine types for
qemu-system-arm/aarch64 binaries") we missed the recent
addition of the MAX78000FTHR machine in commit 51eb283dd0.
Correct that.

The effect is that the machine was accidentally disabled.

Cc: [email protected]
Reported-by: Thomas Huth <[email protected]>
Tested-by: Thomas Huth <[email protected]>
Tested-by: Markus Armbruster <[email protected]>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
Message-id: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/3248
Fixes: 38c5ab4003 ("hw/arm: Filter machine types for single binary")
Signed-off-by: Peter Maydell <[email protected]>
(cherry picked from commit c5712ad83f)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-18 19:35:21 +03:00
Yao Zi 1a1ebc90cd hw/loongarch/virt: Don't abort on access to unimplemented IOCSR
Since commit f2e61edb29 ("hw/loongarch/virt: Use MemTxAttrs interface
for misc ops") which adds a call to g_assert_not_reached() in the path
of handling unimplemented IOCSRs, QEMU would abort when the guest
accesses unimplemented IOCSRs.

This is too serious since there's nothing fatal happening in QEMU
itself, and the guest could probably continue running if we give zero as
result for these reads, which also matches the behavior observed on
3A5000M real machine.

Replace the assertion with qemu_log_mask(LOG_UNIMP, ...), it's still
possible to examine unimplemented IOCSR access through "-d unimp"
command line arguments.

Fixes: f2e61edb29 ("hw/loongarch/virt: Use MemTxAttrs interface for misc ops")
Signed-off-by: Yao Zi <[email protected]>
Signed-off-by: Bibo Mao <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Reviewed-by: Bibo Mao <[email protected]>
(cherry picked from commit 49ee001a5b)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-18 19:35:21 +03:00
Song Gao 0b92a8a130 target/loongarch: Fix exception ADEF/ADEM missing to update CSR_BADV
Exception ADEM/ADEF need update CSR_BADV, the value from the virtual
address.

Signed-off-by: Song Gao <[email protected]>
Signed-off-by: Bibo Mao <[email protected]>
Reviewed-by: Bibo Mao <[email protected]>
(cherry picked from commit a7be2e0a3f)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-18 19:35:21 +03:00
Song Gao 7d662d328d target/loongarch: Fix exception BCE missing to update CSR_BADV
Exception BCE need update CSR_BADV, and the value is env->pc.

Signed-off-by: Song Gao <[email protected]>
Signed-off-by: Bibo Mao <[email protected]>
Reviewed-by: Bibo Mao <[email protected]>
(cherry picked from commit e4f0ef58d5)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-18 19:35:21 +03:00
Song Gao b8456254d0 target/loongach: Fix some exceptions failure in updating CSR_BADV
According to Volume 1 Manual 7.4.8 ,exception,SYS,BRK,INE,IPE,PPD
FPE,SXD,ASXD are need't update CSR_BADV, this patch correct it.

Signed-off-by: Song Gao <[email protected]>
Signed-off-by: Bibo Mao <[email protected]>
Reviewed-by: Bibo Mao <[email protected]>
(cherry picked from commit 70cf9b7bf7)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-18 19:35:21 +03:00
Xianglai Li 21af0baf9a hw/loongarch/virt: Fix irq allocation failure with pci device from fdt
When we use the -kernel parameter to start an elf format kernel relying on
fdt, we get the following error:

pcieport 0000:00:01.0: of_irq_parse_pci: failed with rc=-22
pcieport 0000:00:01.0: enabling device (0000 -> 0003)
pcieport 0000:00:01.0: PME: Signaling with IRQ 19
pcieport 0000:00:01.0: AER: enabled with IRQ 19
pcieport 0000:00:01.1: of_irq_parse_pci: failed with rc=-22
pcieport 0000:00:01.1: enabling device (0000 -> 0003)
pcieport 0000:00:01.1: PME: Signaling with IRQ 20
pcieport 0000:00:01.1: AER: enabled with IRQ 20
pcieport 0000:00:01.2: of_irq_parse_pci: failed with rc=-22
pcieport 0000:00:01.2: enabling device (0000 -> 0003)
pcieport 0000:00:01.2: PME: Signaling with IRQ 21
pcieport 0000:00:01.2: AER: enabled with IRQ 21
pcieport 0000:00:01.3: of_irq_parse_pci: failed with rc=-22
pcieport 0000:00:01.3: enabling device (0000 -> 0003)
pcieport 0000:00:01.3: PME: Signaling with IRQ 22
pcieport 0000:00:01.3: AER: enabled with IRQ 22
pcieport 0000:00:01.4: of_irq_parse_pci: failed with rc=-22

This is because  the description of interrupt-cell is missing in the pcie
irq map.  And there is a lack of a description of the interrupt trigger
type.  Now it is corrected and the correct interrupt-cell is added in the
pcie irq map.

Refer to the implementation in arm and add some comments.

Signed-off-by: Xianglai Li <[email protected]>
Signed-off-by: Bibo Mao <[email protected]>
Reviewed-by: Bibo Mao <[email protected]>
(cherry picked from commit ff54394eed)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-18 19:35:21 +03:00
Xianglai Li e12259821c hw/loongarch/virt: Modify the interrupt trigger type in fdt table
In the loongarch virt fdt file, the interrupt trigger type directly
uses magic numbers. Now, refer to the definitions in the linux kernel and
use macro definitions.

Signed-off-by: Xianglai Li <[email protected]>
Signed-off-by: Bibo Mao <[email protected]>
Reviewed-by: Bibo Mao <[email protected]>
(cherry picked from commit 47de28a0b7)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-18 19:35:18 +03:00
Vulnerability Report 058e1774d6 hw/i386/kvm: fix PIRQ bounds check in xen_physdev_map_pirq()
Reject pirq == s->nr_pirqs in xen_physdev_map_pirq().

Fixes: aa98ee38a5 ("hw/xen: Implement emulated PIRQ hypercall support")
Fixes: CVE-2026-0665
Reported-by: DARKNAVY (@DarkNavyOrg) <[email protected]>
Reviewed-by: David Woodhouse <[email protected]>
Signed-off-by: Vulnerability Report <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit c7504ba2a5)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-16 14:29:24 +03:00
Paolo Bonzini 11e286fb93 target/i386/tcg: allow VEX in 16-bit protected mode
VEX is only forbidden in real and vm86 mode; 16-bit protected mode supports
it for some unfathomable reason.

Cc: [email protected]
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit ed88bdcfbd)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-16 14:29:07 +03:00
Paolo Bonzini 6594e50e7e target/i386/tcg: mask addresses for VSIB
VSIB can have either 32-bit or 64-bit addresses, pass a constant mask to
the helper and apply it before the load.

Cc: [email protected]
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 5e3572ef2e)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-16 14:28:56 +03:00
Paolo Bonzini 51bc24d427 target/i386/tcg: do not mark all SSE instructions as unaligned
If the vex_special field was not initialized, it was considered to be
X86_VEX_SSEUnaligned (whose value was zero).  Add a new value to
fix that.

Cc: [email protected]
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 73dd6e4a36)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-16 14:28:45 +03:00
Laurent Vivier 359076c8a0 m68k: fix CAS2 writeback when Dc1==Dc2
According to Programmer's Reference Manual, if Dc1 and Dc2 specify the
same data register and the comparison fails, memory operand 1 is stored
in the data register.

The current helpers wrote Dc1 then Dc2, leaving operand 2 in the shared
register.

Swap the writeback order for cas2w/cas2l so memory operand 1 wins.

Signed-off-by: Laurent Vivier <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit 11dac41f2e)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-16 14:26:44 +03:00
Paolo Bonzini 920634e411 configs: use default prefix for Windows compilation
The update to Python 3.13 causes meson configuration to fail, see e.g.:

   https://gitlab.com/qemu-project/qemu/-/jobs/12672816538#L397

   meson.build:1:0: ERROR: prefix value '/qemu' must be an absolute path

This is https://github.com/mesonbuild/meson/issues/14303.  Remove the
prefix='/qemu' line in configs/meson/windows.txt, since commit d17f305a26
("configure: use a platform-neutral prefix", 2020-09-30) says that the
NSIS installer doesn't care.

Cc: [email protected]
Cc: Thomas Huth <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
Reviewed-by: Thomas Huth <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit 894c8bd56f)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-13 11:11:15 +03:00
Fabiano Rosas 639ffcbd64 target/ppc: Fix env->quiesced migration
The commit referenced (from QEMU 10.0) has changed the way the pseries
machine marks a cpu as quiesced. Previously, the cpu->halted value
from QEMU common cpu code was (incorrectly) used. With the fix, the
env->quiesced variable starts being used, which improves on the
original situation, but also causes a side effect after migration:

The env->quiesced is set at reset and never migrated, which causes the
destination QEMU to stop delivering interrupts and hang the machine.

To fix the issue from this point on, start migrating the env->quiesced
value.

For QEMU versions < 10.0, sending the new element on the stream would
cause migration to be aborted, so add the appropriate compatibility
property to omit the new subsection.

Independently of this patch, all migrations from QEMU versions < 10.0
would result in a hang since the older QEMU never migrates
env->quiesced. This is bad because it leaves machines already running
on the old QEMU without a migration path into newer versions.

As a workaround, use a few heuristics to infer the new value of
env->quiesced based on cpu->halted, LPCR and PSSCR bits that are
usually set/cleared along with quiesced.

Note that this was tested with -cpu power9 and -machine ic-mode=xive
due to another bug affecting migration of XICS guests. Tested both
forward and backward migration and savevm/loadvm from 9.2 and 10.0.

Also tested loadvm of a savevm image that contains a mix of cpus both
halted and not halted.

Reported-by: Fabian Vogt <[email protected]>
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/3079
Fixes: fb802acdc8 ("ppc/spapr: Fix RTAS stopped state")
Acked-by: Chinmay Rath <[email protected]>
Reviewed-by: Harsh Prateek Bora <[email protected]>
Signed-off-by: Fabiano Rosas <[email protected]>
Link: https://lore.kernel.org/qemu-devel/[email protected]
Signed-off-by: Harsh Prateek Bora <[email protected]>
(cherry picked from commit 628bda1ab7)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-13 11:07:34 +03:00
Matthew Lugg 4cc64bd6c4 tests: add tcg coverage for fixed mremap bugs
These tests cover the first two fixes in this patch series. The final
patch is not covered because the bug it fixes is not easily observable
by the guest.

Signed-off-by: Matthew Lugg <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit 9290c10ae9)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-13 00:33:05 +03:00
Matthew Lugg 860f8f3f53 linux-user: fix reserved_va page leak in do_munmap
The old logic had an off-by-one bug. For instance, assuming 4k pages on
host and guest, if 'len' is '4097' (indicating to unmap 2 pages), then
'last = start + 4096', so 'real_last = start + 4095', so ultimately
'real_len = 4096'. I do not believe this could cause any observable bugs
in guests, because `target_munmap` page-aligns the length it passes in.
However, calls to this function in `target_mremap` do not page-align the
length, so those calls could "drop" pages, leading to a part of the
reserved region becoming unmapped. At worst, a host allocation could get
mapped into that hole, then clobbered by a new guest mapping.

Signed-off-by: Matthew Lugg <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit 81ceab3049)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-13 00:33:01 +03:00
Matthew Lugg 5ac0811f40 linux-user: fix mremap errors for invalid ranges
If an address range given to `mremap` is invalid (exceeds addressing
bounds on the guest), we were previously returning `ENOMEM`, which is
not correct. The manpage and the Linux kernel implementation both agree
that if `old_addr`/`old_size` refer to an invalid address, `EFAULT` is
returned, and if `new_addr`/`new_size` refer to an invalid address,
`EINVAL` is returned.

Signed-off-by: Matthew Lugg <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit 2422884ec5)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-13 00:33:01 +03:00
Matthew Lugg a8adf882fd linux-user: fix mremap unmapping adjacent region
This typo meant that calls to `mremap` which shrink a mapping by some N
bytes would, when the virtual address space was pre-reserved (e.g.
32-bit guest on 64-bit host), unmap the N bytes following the *original*
mapping.

Signed-off-by: Matthew Lugg <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit aaed9ca179)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-13 00:33:00 +03:00
Jim MacArthur 86ce6e0773 linux-user/elfload.c: Correction to HWCAP2 accessor
get_elf_hwcap was used when get_elf_hwcap2 should have been.

Cc: [email protected]
Fixes: fcac98d0ba ("linux-user: Remove ELF_HWCAP2")
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/3259
Signed-off-by: Jim MacArthur <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit c333f9c4ee)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-13 00:32:10 +03:00
Jean-Christian CÎRSTEA e71e02caa7 linux-user: allow null pathname for statx()/fstatat()
Since Linux 6.11, the path argument may be NULL.

Before this patch, qemu-*-linux-user failed with EFAULT when `pathname` was
specified as NULL, even for Linux kernel hosts > 6.10. This patch fixes this
issue by checking whether `arg2` is 0. If so, don't return EFAULT, but instead
perform the appropiate syscall and let the host's kernel handle null `pathname`.

Cc: [email protected]
Signed-off-by: Jean-Christian CÎRSTEA <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit 82ae60c8b5)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-13 00:31:40 +03:00
Richard Henderson f34c0eb054 tcg/riscv: Fix TCG_REG_TMP0 clobber in tcg_gen_dup{m,i}
TCG_REG_TMP0 may be used by set_vtype* to load the vtype
parameter, so delay any other use of TCG_REG_TMP0 until
the correct vtype has been installed.

Cc: [email protected]
Fixes: d4be6ee111 ("tcg/riscv: Implement vector mov/dup{m/i}")
Reported-by: Zhijin Zeng <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
(cherry picked from commit af6db3b713)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-13 00:31:22 +03:00
Paolo Bonzini a53ba65fff tcg/optimize: Do use affected bits
We inadvertently disabled affected bits optimizations on operations
that use fold_masks_zosa.  These happen relatively often in x86 code
for extract/sextract; for example given the following:

   mov %esi, %ebp
   xor $0x1, %ebp

the optimizer is able to simplify the "extract_i64 rbp,tmp0,$0x0,$0x20"
produced by the second instruction to a move.

Cc: [email protected]
Fixes: 932522a9dd ("tcg/optimize: Fold and to extract during optimize")
Signed-off-by: Paolo Bonzini <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit 23b53ec3a8)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-13 00:30:58 +03:00
Richard Henderson b276b2ca22 tcg/optimize: Fix a_mask computation for orc
In computing a_mask, for or, we remove the bits from t1->o_mask
which are known to be zero.  For orc, the bits known to be zero
are the inverse of those known to be one.

Cc: [email protected]
Fixes: cc4033ee47 ("tcg/optimize: Build and use zero, one and affected bits in fold_orc")
Reviewed-by: Pierrick Bouvier <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
(cherry picked from commit 08b12bfb8f)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-13 00:30:37 +03:00
Richard Henderson 682e043b17 tcg/optimize: Save o_mask in fold_masks_zosa_int
When adding o_mask to this function, we used it in a
couple of places but failed to save it for future use.
Also, update a related comment.

Cc: [email protected]
Fixes: 56f15f67ea ("tcg/optimize: Add one's mask to TempOptInfo")
Reported-by: Manos Pitsidianakis <[email protected]>
Reviewed-by: Pierrick Bouvier <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: Richard Henderson <[email protected]>
(cherry picked from commit 7d2d577de0)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-13 00:29:57 +03:00
Jie Song d6b9de8f9e monitor/qmp: cleanup SocketChardev listener sources early to avoid fd handling race
When starting a dummy QEMU process with virsh version, monitor_init_qmp()
enables IOThread monitoring of the QMP fd by default. However, a race
condition exists during the initialization phase: the IOThread only removes
the main thread's fd watch when it reaches qio_net_listener_set_client_func_full(),
which may be delayed under high system load.

This creates a window between monitor_qmp_setup_handlers_bh() and
qio_net_listener_set_client_func_full() where both the main thread and
IOThread are simultaneously monitoring the same fd and processing events.
This race can cause either the main thread or the IOThread to hang and
become unresponsive.

Fix this by proactively cleaning up the listener's IO sources in
monitor_init_qmp() before the IOThread initializes QMP monitoring,
ensuring exclusive fd ownership and eliminating the race condition.

Signed-off-by: Jie Song <[email protected]>
Reviewed-by: Marc-André Lureau <[email protected]>
Message-ID: <[email protected]>
(cherry picked from commit e714f1a3d4)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-08 17:44:39 +03:00
Cédric Le Goater a7383751c2 tests/functional: Fix URL of gb200nvl-bmc image
Commit [1] moved the FW image of the gb200nvl-bmc machine and broke
the associated functional test. Fix that.

[1] https://github.com/legoater/qemu-aspeed-boot/commit/52451b2472eeb40aa97e131aeea327e9d4a8a78a

Cc: Ed Tanous <[email protected]>
Cc: Patrick Williams <[email protected]>
Tested-by: Philippe Mathieu-Daudé <[email protected]>
Link: https://lore.kernel.org/qemu-devel/[email protected]
Signed-off-by: Cédric Le Goater <[email protected]>
(cherry picked from commit 75bcfb98a1)
Signed-off-by: Michael Tokarev <[email protected]>
2026-01-06 11:38:00 +03:00
Alano Song 2af81f1251 hw/i2c/imx: Fix trace func name error
Signed-off-by: Alano Song <[email protected]>
Fixes: e589c0ea9c ("hw/i2c/imx_i2c: Convert DPRINTF() to trace events")
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Message-ID: <[email protected]>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
(cherry picked from commit 3fbadbb392)
Signed-off-by: Michael Tokarev <[email protected]>
2025-12-31 18:02:43 +03:00
Paolo Bonzini 59c9137156 target/i386/tcg: ignore V3 in 32-bit mode
From the manual: "In 64-bit mode all 4 bits may be used. [...]
In 32-bit and 16-bit modes bit 6 must be 1 (if bit 6 is not 1, the
2-byte VEX version will generate LDS instruction and the 3-byte VEX
version will ignore this bit)."

Cc: [email protected]
Reviewed-by: Richard Henderson <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 0db1b556e4)
Signed-off-by: Michael Tokarev <[email protected]>
2025-12-29 10:44:56 +03:00
Andrew Cooper b33a563281 target/i386: Fix #GP error code for INT instructions
While the (intno << shift) expression is correct for indexing the IDT based on
whether Long Mode is active, the error code itself was unchanged with AMD64,
and is still the index with 3 bits of metadata in the bottom.

Found when running a Xen unit test, all under QEMU.  The unit test objected to
being told there was an error with IDT index 256 when INT $0x80 (128) was the
problem instruction:

  ...
  Error: Unexpected fault 0x800d0802, #GP[IDT[256]]
  ...

Fixes: d2fd1af767 ("x86_64 linux user emulation")
Signed-off-by: Andrew Cooper <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/issues/3160
Signed-off-by: Paolo Bonzini <[email protected]>
(cherry picked from commit 60efba3c1b)
Signed-off-by: Michael Tokarev <[email protected]>
2025-12-29 10:44:47 +03:00
3747 changed files with 53651 additions and 77209 deletions

No files matched your search

+4 -3
View File
@@ -28,9 +28,6 @@ variables:
# we don't need. The --filter options avoid blobs and tree references we aren't going to use
# and we also avoid fetching tags.
GIT_FETCH_EXTRA_FLAGS: --filter=blob:none --filter=tree:0 --no-tags --prune --quiet
# Ensure docker.py / tests/docker/Makefile.include always displays stdout
# from any docker commands to aid debugging of failures
DOCKER_V: 1
interruptible: true
@@ -52,6 +49,10 @@ variables:
- if: '$CI_PIPELINE_SOURCE == "schedule"'
when: never
# Cirrus jobs can't run unless the creds / target repo are set
- if: '$QEMU_JOB_CIRRUS && ($CIRRUS_GITHUB_REPO == null || $CIRRUS_API_TOKEN == null)'
when: never
# Publishing jobs should only run on the default branch in upstream
- if: '$QEMU_JOB_PUBLISH == "1" && $CI_PROJECT_NAMESPACE == $QEMU_CI_UPSTREAM && $CI_COMMIT_BRANCH != $CI_DEFAULT_BRANCH'
when: never
+34 -29
View File
@@ -40,7 +40,7 @@ build-system-ubuntu:
variables:
IMAGE: ubuntu2204
CONFIGURE_ARGS: --enable-docs --enable-rust
TARGETS: alpha-softmmu microblaze-softmmu mips64el-softmmu
TARGETS: alpha-softmmu microblazeel-softmmu mips64el-softmmu
MAKE_CHECK_ARGS: check-build
check-system-ubuntu:
@@ -101,7 +101,8 @@ crash-test-debian:
IMAGE: debian
script:
- cd build
- ./run scripts/device-crash-test -q --tcg-only ./qemu-system-i386
- make NINJA=":" check-venv
- pyvenv/bin/python3 scripts/device-crash-test -q --tcg-only ./qemu-system-i386
build-system-fedora:
extends:
@@ -112,7 +113,7 @@ build-system-fedora:
variables:
IMAGE: fedora
CONFIGURE_ARGS: --disable-gcrypt --enable-nettle --enable-docs --enable-crypto-afalg --enable-rust
TARGETS: mips-softmmu
TARGETS: microblaze-softmmu mips-softmmu
xtensa-softmmu m68k-softmmu riscv32-softmmu ppc-softmmu sparc64-softmmu
MAKE_CHECK_ARGS: check-build check-doc
@@ -157,8 +158,9 @@ crash-test-fedora:
IMAGE: fedora
script:
- cd build
- ./run scripts/device-crash-test -q ./qemu-system-ppc
- ./run scripts/device-crash-test -q ./qemu-system-riscv32
- make NINJA=":" check-venv
- pyvenv/bin/python3 scripts/device-crash-test -q ./qemu-system-ppc
- pyvenv/bin/python3 scripts/device-crash-test -q ./qemu-system-riscv32
build-system-centos:
extends:
@@ -348,15 +350,15 @@ build-tcg-disabled:
- make -j"$JOBS"
- make check-unit
- make check-qapi-schema
- ./run tests/qemu-iotests/check -raw 001 002 003 004 005 008 009
010 011 012 021 025 032 033 048 052 063 077 086 101 104 106
113 148 150 151 152 157 159 160 163 170 171 184 192 194 208
221 226 227 236 253 277 image-fleecing
- ./run tests/qemu-iotests/check -qcow2 028 051 056 057 058 065 068
082 085 091 095 096 102 122 124 132 139 142 144 145 151 152
155 157 165 194 196 200 202 208 209 216 218 227 234 246 247
248 250 254 255 257 258 260 261 262 263 264 270 272 273 277
279 image-fleecing
- cd tests/qemu-iotests/
- ./check -raw 001 002 003 004 005 008 009 010 011 012 021 025 032 033 048
052 063 077 086 101 104 106 113 148 150 151 152 157 159 160 163
170 171 184 192 194 208 221 226 227 236 253 277 image-fleecing
- ./check -qcow2 028 051 056 057 058 065 068 082 085 091 095 096 102 122
124 132 139 142 144 145 151 152 155 157 165 194 196 200 202
208 209 216 218 227 234 246 247 248 250 254 255 257 258
260 261 262 263 264 270 272 273 277 279 image-fleecing
- cd ../..
- make distclean
build-user:
@@ -376,6 +378,18 @@ build-user-static:
variables:
IMAGE: debian-all-test-cross
CONFIGURE_ARGS: --disable-tools --disable-system --static
--target-list-exclude=alpha-linux-user,sh4-linux-user
MAKE_CHECK_ARGS: check-tcg
# targets stuck on older compilers
build-legacy:
extends: .native_build_job_template
needs:
- job: amd64-debian-legacy-cross-container
variables:
IMAGE: debian-legacy-test-cross
TARGETS: alpha-linux-user alpha-softmmu sh4-linux-user
CONFIGURE_ARGS: --disable-tools
MAKE_CHECK_ARGS: check-tcg
build-user-hexagon:
@@ -614,7 +628,7 @@ build-oss-fuzz:
IMAGE: fedora
script:
- mkdir build-oss-fuzz
- export LSAN_OPTIONS=suppressions=scripts/lsan_suppressions.txt
- export LSAN_OPTIONS=suppressions=scripts/oss-fuzz/lsan_suppressions.txt
- CC="clang" CXX="clang++" CFLAGS="-fsanitize=address"
./scripts/oss-fuzz/build.sh
- export ASAN_OPTIONS="fast_unwind_on_malloc=0"
@@ -664,7 +678,7 @@ build-without-defaults:
--disable-pie
--disable-qom-cast-debug
--disable-strip
--target-list-exclude=aarch64-softmmu,mips64-softmmu,mipsel-softmmu,ppc64-softmmu,sh4el-softmmu,xtensa-softmmu,x86_64-softmmu
--target-list-exclude=aarch64-softmmu,microblaze-softmmu,mips64-softmmu,mipsel-softmmu,ppc64-softmmu,sh4el-softmmu,xtensa-softmmu,x86_64-softmmu
MAKE_CHECK_ARGS: check
build-libvhost-user:
@@ -771,20 +785,11 @@ coverity:
# Always manual on forks even if $QEMU_CI == "2"
- when: manual
build-wasm64-64bit:
build-wasm:
extends: .wasm_build_job_template
timeout: 2h
needs:
- job: wasm64-emsdk-cross-container
- job: wasm-emsdk-cross-container
variables:
IMAGE: emsdk-wasm64-cross
CONFIGURE_ARGS: --static --cpu=wasm64 --disable-tools --enable-debug --enable-tcg-interpreter
build-wasm64-32bit:
extends: .wasm_build_job_template
timeout: 2h
needs:
- job: wasm64-emsdk-cross-container
variables:
IMAGE: emsdk-wasm64-cross
CONFIGURE_ARGS: --static --cpu=wasm64 --wasm64-32bit-address-limit --disable-tools --enable-debug --enable-tcg-interpreter
IMAGE: emsdk-wasm32-cross
CONFIGURE_ARGS: --static --disable-tools --enable-debug --enable-tcg-interpreter
+60
View File
@@ -0,0 +1,60 @@
# Jobs that we delegate to Cirrus CI because they require an operating
# system other than Linux. These jobs will only run if the required
# setup has been performed on the GitLab account.
#
# The Cirrus CI configuration is generated by replacing target-specific
# variables in a generic template: some of these variables are provided
# when the GitLab CI job is defined, others are taken from a shell
# snippet generated using lcitool.
#
# Note that the $PATH environment variable has to be treated with
# special care, because we can't just override it at the GitLab CI job
# definition level or we risk breaking it completely.
.cirrus_build_job:
extends: .base_job_template
stage: build
image: registry.gitlab.com/libvirt/libvirt-ci/cirrus-run:latest
needs: []
allow_failure:
exit_codes: 3
# 20 mins larger than "timeout_in" in cirrus/build.yml
# as there's often a 5-10 minute delay before Cirrus CI
# actually starts the task
timeout: 80m
script:
- set -o allexport
- source .gitlab-ci.d/cirrus/$NAME.vars
- set +o allexport
- cirrus-vars <.gitlab-ci.d/cirrus/build.yml >.gitlab-ci.d/cirrus/$NAME.yml
- cat .gitlab-ci.d/cirrus/$NAME.yml
- cirrus-run -v --show-build-log always .gitlab-ci.d/cirrus/$NAME.yml
variables:
QEMU_JOB_CIRRUS: 1
x64-freebsd-14-build:
extends: .cirrus_build_job
variables:
NAME: freebsd-14
CIRRUS_VM_INSTANCE_TYPE: freebsd_instance
CIRRUS_VM_IMAGE_SELECTOR: image_family
CIRRUS_VM_IMAGE_NAME: freebsd-14-3
CIRRUS_VM_CPUS: 8
CIRRUS_VM_RAM: 8G
UPDATE_COMMAND: pkg update; pkg upgrade -y
INSTALL_COMMAND: pkg install -y
CONFIGURE_ARGS: --target-list-exclude=arm-softmmu,i386-softmmu,microblaze-softmmu,mips64el-softmmu,mipsel-softmmu,mips-softmmu,ppc-softmmu,sh4eb-softmmu,xtensa-softmmu --enable-rust
TEST_TARGETS: check
aarch64-macos-build:
extends: .cirrus_build_job
variables:
NAME: macos-14
CIRRUS_VM_INSTANCE_TYPE: macos_instance
CIRRUS_VM_IMAGE_SELECTOR: image
CIRRUS_VM_IMAGE_NAME: ghcr.io/cirruslabs/macos-runner:sonoma
UPDATE_COMMAND: brew update
INSTALL_COMMAND: brew install
PATH_EXTRA: /opt/homebrew/ccache/libexec:/opt/homebrew/gettext/bin
PKG_CONFIG_PATH: /opt/homebrew/curl/lib/pkgconfig:/opt/homebrew/ncurses/lib/pkgconfig:/opt/homebrew/readline/lib/pkgconfig
CONFIGURE_ARGS: --target-list-exclude=arm-softmmu,i386-softmmu,microblazeel-softmmu,mips64-softmmu,mipsel-softmmu,mips-softmmu,ppc-softmmu,sh4-softmmu,xtensaeb-softmmu
TEST_TARGETS: check-unit check-block check-qapi-schema check-softfloat check-qtest-x86_64
+54
View File
@@ -0,0 +1,54 @@
Cirrus CI integration
=====================
GitLab CI shared runners only provide a docker environment running on Linux.
While it is possible to provide private runners for non-Linux platforms this
is not something most contributors/maintainers will wish to do.
To work around this limitation, we take advantage of `Cirrus CI`_'s free
offering: more specifically, we use the `cirrus-run`_ script to trigger Cirrus
CI jobs from GitLab CI jobs so that Cirrus CI job output is integrated into
the main GitLab CI pipeline dashboard.
There is, however, some one-time setup required. If you want FreeBSD and macOS
builds to happen when you push to your GitLab repository, you need to
* set up a GitHub repository for the project, eg. ``yourusername/qemu``.
This repository needs to exist for cirrus-run to work, but it doesn't need to
be kept up to date, so you can create it and then forget about it;
* enable the `Cirrus CI GitHub app`_ for your GitHub account;
* sign up for Cirrus CI. It's enough to log into the website using your GitHub
account;
* grab an API token from the `Cirrus CI settings`_ page;
* it may be necessary to push an empty ``.cirrus.yml`` file to your github fork
for Cirrus CI to properly recognize the project. You can check whether
Cirrus CI knows about your project by navigating to:
``https://cirrus-ci.com/yourusername/qemu``
* in the *CI/CD / Variables* section of the settings page for your GitLab
repository, create two new variables:
* ``CIRRUS_GITHUB_REPO``, containing the name of the GitHub repository
created earlier, eg. ``yourusername/qemu``;
* ``CIRRUS_API_TOKEN``, containing the Cirrus CI API token generated earlier.
This variable **must** be marked as *Masked*, because anyone with knowledge
of it can impersonate you as far as Cirrus CI is concerned.
Neither of these variables should be marked as *Protected*, because in
general you'll want to be able to trigger Cirrus CI builds from non-protected
branches.
Once this one-time setup is complete, you can just keep pushing to your GitLab
repository as usual and you'll automatically get the additional CI coverage.
.. _Cirrus CI GitHub app: https://github.com/marketplace/cirrus-ci
.. _Cirrus CI settings: https://cirrus-ci.com/settings/profile/
.. _Cirrus CI: https://cirrus-ci.com/
.. _cirrus-run: https://github.com/sio/cirrus-run/
+42
View File
@@ -0,0 +1,42 @@
@CIRRUS_VM_INSTANCE_TYPE@:
@CIRRUS_VM_IMAGE_SELECTOR@: @CIRRUS_VM_IMAGE_NAME@
cpu: @CIRRUS_VM_CPUS@
memory: @CIRRUS_VM_RAM@
env:
CIRRUS_CLONE_DEPTH: 1
CI_REPOSITORY_URL: "@CI_REPOSITORY_URL@"
CI_COMMIT_REF_NAME: "@CI_COMMIT_REF_NAME@"
CI_COMMIT_SHA: "@CI_COMMIT_SHA@"
PATH: "@PATH_EXTRA@:$PATH"
PKG_CONFIG_PATH: "@PKG_CONFIG_PATH@"
PYTHON: "@PYTHON@"
MAKE: "@MAKE@"
CONFIGURE_ARGS: "@CONFIGURE_ARGS@"
TEST_TARGETS: "@TEST_TARGETS@"
build_task:
# A little shorter than GitLab timeout in ../cirrus.yml
timeout_in: 60m
install_script:
- @UPDATE_COMMAND@
- @INSTALL_COMMAND@ @PKGS@
- if test -n "@PYPI_PKGS@" ; then PYLIB=$(@PYTHON@ -c 'import sysconfig; print(sysconfig.get_path("stdlib"))'); rm -f $PYLIB/EXTERNALLY-MANAGED; @PIP3@ install @PYPI_PKGS@ ; fi
clone_script:
- git clone --depth 100 "$CI_REPOSITORY_URL" .
- git fetch origin "$CI_COMMIT_REF_NAME"
- git reset --hard "$CI_COMMIT_SHA"
step_script:
- mkdir build
- cd build
- ../configure --enable-werror $CONFIGURE_ARGS
|| { cat config.log meson-logs/meson-log.txt; exit 1; }
- $MAKE -j$(sysctl -n hw.ncpu)
- for TARGET in $TEST_TARGETS ;
do
$MAKE -j$(sysctl -n hw.ncpu) $TARGET V=1 ;
done
always:
build_result_artifacts:
path: build/meson-logs/*log.txt
type: text/plain
+16
View File
@@ -0,0 +1,16 @@
# THIS FILE WAS AUTO-GENERATED
#
# $ lcitool variables freebsd-14 qemu
#
# https://gitlab.com/libvirt/libvirt-ci
CCACHE='/usr/local/bin/ccache'
CPAN_PKGS=''
CROSS_PKGS=''
MAKE='/usr/local/bin/gmake'
NINJA='/usr/local/bin/ninja'
PACKAGING_COMMAND='pkg'
PIP3='/usr/local/bin/pip'
PKGS='alsa-lib bash bison bzip2 ca_root_nss capstone4 ccache4 cmocka coreutils ctags curl cyrus-sasl dbus diffutils dtc flex fusefs-libs3 gettext git glib gmake gnutls gsed gtk-vnc gtk3 json-c libepoxy libffi libgcrypt libjpeg-turbo libnfs libslirp libspice-server libssh libtasn1 llvm lzo2 meson mtools ncurses nettle ninja opencv pixman pkgconf png py311-numpy py311-pillow py311-pip py311-pyyaml py311-sphinx py311-sphinx_rtd_theme py311-tomli python3 rpm2cpio rust rust-bindgen-cli sdl2 sdl2_image snappy sndio socat spice-protocol tesseract usbredir virglrenderer vte3 vulkan-tools xorriso zstd'
PYPI_PKGS=''
PYTHON='/usr/local/bin/python3'
@@ -11,6 +11,6 @@ MAKE='/opt/homebrew/bin/gmake'
NINJA='/opt/homebrew/bin/ninja'
PACKAGING_COMMAND='brew'
PIP3='/opt/homebrew/bin/pip3'
PKGS='bash bc bindgen bison bzip2 capstone ccache cmocka coreutils ctags curl dbus diffutils dtc flex gcovr gettext git glib gnu-sed gnutls gtk+3 gtk-vnc jemalloc jpeg-turbo json-c libcbor libepoxy libffi libgcrypt libiscsi libnfs libpng libslirp libssh libtasn1 libusb llvm lzo make meson mtools ncurses nettle ninja pixman pkg-config python-setuptools python3 rpm2cpio rust sdl2 sdl2_image snappy socat sparse spice-protocol swtpm tesseract usbredir vde vte3 vulkan-tools xorriso zlib zstd'
PKGS='bash bc bindgen bison bzip2 capstone ccache cmocka coreutils ctags curl dbus diffutils dtc flex gcovr gettext git glib gnu-sed gnutls gtk+3 gtk-vnc jemalloc jpeg-turbo json-c libcbor libepoxy libffi libgcrypt libiscsi libnfs libpng libslirp libssh libtasn1 libusb llvm lzo make meson mtools ncurses nettle ninja pixman pkg-config python3 rpm2cpio rust sdl2 sdl2_image snappy socat sparse spice-protocol swtpm tesseract usbredir vde vte3 vulkan-tools xorriso zlib zstd'
PYPI_PKGS='PyYAML numpy pillow sphinx sphinx-rtd-theme tomli'
PYTHON='/opt/homebrew/bin/python3'
+20 -2
View File
@@ -10,12 +10,24 @@ amd64-debian-user-cross-container:
variables:
NAME: debian-all-test-cross
amd64-debian-legacy-cross-container:
extends: .container_job_template
stage: containers
variables:
NAME: debian-legacy-test-cross
arm64-debian-cross-container:
extends: .container_job_template
stage: containers
variables:
NAME: debian-arm64-cross
armhf-debian-cross-container:
extends: .container_job_template
stage: containers
variables:
NAME: debian-armhf-cross
hexagon-cross-container:
extends: .container_job_template
stage: containers
@@ -28,6 +40,12 @@ loongarch-debian-cross-container:
variables:
NAME: debian-loongarch-cross
i686-debian-cross-container:
extends: .container_job_template
stage: containers
variables:
NAME: debian-i686-cross
mips64el-debian-cross-container:
extends: .container_job_template
stage: containers
@@ -68,7 +86,7 @@ win64-fedora-cross-container:
variables:
NAME: fedora-win64-cross
wasm64-emsdk-cross-container:
wasm-emsdk-cross-container:
extends: .container_job_template
variables:
NAME: emsdk-wasm64-cross
NAME: emsdk-wasm32-cross
+4 -1
View File
@@ -45,9 +45,12 @@ weekly-container-builds:
# cross
- amd64-debian-cross-container
- amd64-debian-user-cross-container
- amd64-debian-legacy-cross-container
- arm64-debian-cross-container
- armhf-debian-cross-container
- hexagon-cross-container
- loongarch-debian-cross-container
- i686-debian-cross-container
- mips64el-debian-cross-container
- ppc64el-debian-cross-container
- riscv64-debian-cross-container
@@ -55,7 +58,7 @@ weekly-container-builds:
- tricore-debian-cross-container
- xtensa-debian-cross-container
- win64-fedora-cross-container
- wasm64-emsdk-cross-container
- wasm-emsdk-cross-container
# containers
- amd64-alpine-container
- amd64-debian-container
+46 -1
View File
@@ -1,6 +1,13 @@
include:
- local: '/.gitlab-ci.d/crossbuild-template.yml'
cross-armhf-user:
extends: .cross_user_build_job
needs:
- job: armhf-debian-cross-container
variables:
IMAGE: debian-armhf-cross
cross-arm64-system:
extends: .cross_system_build_job
needs:
@@ -23,6 +30,44 @@ cross-arm64-kvm-only:
IMAGE: debian-arm64-cross
EXTRA_CONFIGURE_OPTS: --disable-tcg --without-default-features
cross-i686-system:
extends:
- .cross_system_build_job
- .cross_test_artifacts
needs:
- job: i686-debian-cross-container
variables:
IMAGE: debian-i686-cross
EXTRA_CONFIGURE_OPTS: --disable-kvm
MAKE_CHECK_ARGS: check-qtest
cross-i686-user:
extends:
- .cross_user_build_job
- .cross_test_artifacts
needs:
- job: i686-debian-cross-container
variables:
IMAGE: debian-i686-cross
MAKE_CHECK_ARGS: check
cross-i686-tci:
extends:
- .cross_accel_build_job
- .cross_test_artifacts
timeout: 60m
needs:
- job: i686-debian-cross-container
variables:
IMAGE: debian-i686-cross
ACCEL: tcg-interpreter
EXTRA_CONFIGURE_OPTS: --target-list=i386-softmmu,i386-linux-user,arm-softmmu,arm-linux-user,ppc-softmmu,ppc-linux-user --disable-plugins --disable-kvm
# Force tests to run with reduced parallelism, to see whether this
# reduces the flakiness of this CI job. The CI
# environment by default shows us 8 CPUs and so we
# would otherwise be using a parallelism of 9.
MAKE_CHECK_ARGS: check check-tcg -j2
cross-mips64el-system:
extends: .cross_system_build_job
needs:
@@ -111,7 +156,7 @@ cross-win64-system:
IMAGE: fedora-win64-cross
EXTRA_CONFIGURE_OPTS: --enable-fdt=internal --disable-plugins
CROSS_SKIP_TARGETS: alpha-softmmu avr-softmmu hppa-softmmu
m68k-softmmu microblaze-softmmu
m68k-softmmu microblazeel-softmmu
or1k-softmmu rx-softmmu sh4eb-softmmu sparc64-softmmu
tricore-softmmu xtensaeb-softmmu
artifacts:
-47
View File
@@ -1,47 +0,0 @@
.macos_job_template:
extends: .base_job_template
stage: build
tags:
- saas-macos-large-m2pro
needs: []
timeout: 80m
artifacts:
name: "$CI_JOB_NAME-$CI_COMMIT_REF_SLUG"
expire_in: 7 days
paths:
- build/meson-logs/
- build/tests/tcg/
reports:
junit: build/meson-logs/*.junit.xml
when: always
before_script:
- set -o allexport
- source .gitlab-ci.d/macos-14.vars
- set +o allexport
- export PATH="$PATH_EXTRA:$PATH"
- export PKG_CONFIG_PATH="$PKG_CONFIG_PATH"
- brew update
- brew install $PKGS
- brew install gdb aarch64-elf-gcc i686-elf-gcc x86_64-elf-gcc
- if test -n "$PYPI_PKGS" ; then PYLIB=$($PYTHON -c 'import sysconfig; print(sysconfig.get_path("stdlib"))'); rm -f $PYLIB/EXTERNALLY-MANAGED; $PIP3 install --break-system-packages $PYPI_PKGS ; fi
script:
- mkdir build
- cd build
- ../configure --enable-werror $CONFIGURE_ARGS || { cat config.log meson-logs/meson-log.txt; exit 1; }
- $MAKE -j$(sysctl -n hw.ncpu)
- for TARGET in $TEST_TARGETS ; do $MAKE $TARGET ; done
aarch64-macos-15-build:
extends: .macos_job_template
image: macos-15-xcode-16
variables:
NAME: macos-15
PATH_EXTRA: /opt/homebrew/gettext/bin
PKG_CONFIG_PATH: /opt/homebrew/curl/lib/pkgconfig:/opt/homebrew/ncurses/lib/pkgconfig:/opt/homebrew/readline/lib/pkgconfig
CONFIGURE_ARGS:
--target-list=aarch64-softmmu,i386-softmmu,x86_64-softmmu
--cross-prefix-aarch64=aarch64-elf-
--cross-prefix-i386=i686-elf-
--cross-prefix-x86_64=x86_64-elf-
--disable-plugins
TEST_TARGETS: check-unit run-tcg-tests-aarch64-softmmu run-tcg-tests-i386-softmmu run-tcg-tests-x86_64-softmmu
+1 -1
View File
@@ -17,5 +17,5 @@ include:
- local: '/.gitlab-ci.d/buildtest.yml'
- local: '/.gitlab-ci.d/static_checks.yml'
- local: '/.gitlab-ci.d/custom-runners.yml'
- local: '/.gitlab-ci.d/cirrus.yml'
- local: '/.gitlab-ci.d/windows.yml'
- local: '/.gitlab-ci.d/macos.yml'
+1 -8
View File
@@ -17,7 +17,7 @@ msys2-64bit:
# This feature doesn't (currently) work with PowerShell, it stops
# the echo'ing of commands being run and doesn't show any timing
FF_SCRIPT_SECTIONS: 0
CONFIGURE_ARGS: --disable-system --enable-tools -Ddebug=false -Doptimization=0 --enable-rust
CONFIGURE_ARGS: --disable-system --enable-tools -Ddebug=false -Doptimization=0
# The Windows git is a bit older so override the default
GIT_FETCH_EXTRA_FLAGS: --no-tags --prune --quiet
artifacts:
@@ -77,7 +77,6 @@ msys2-64bit:
bison diffutils flex
git grep make sed
mingw-w64-x86_64-binutils
mingw-w64-x86_64-ca-certificates
mingw-w64-x86_64-ccache
mingw-w64-x86_64-curl-winssl
mingw-w64-x86_64-gcc
@@ -88,11 +87,6 @@ msys2-64bit:
mingw-w64-x86_64-pixman
mingw-w64-x86_64-pkgconf
mingw-w64-x86_64-python
mingw-w64-x86_64-python-certifi
mingw-w64-x86_64-python-setuptools
mingw-w64-x86_64-python-wheel
mingw-w64-x86_64-rust
mingw-w64-x86_64-rust-bindgen
mingw-w64-x86_64-zstd"
- .\msys64\usr\bin\bash -lc "pacman -Sc --noconfirm"
- Write-Output "Running build at $(Get-Date -Format u)"
@@ -104,7 +98,6 @@ msys2-64bit:
- $env:CCACHE_MAXSIZE = "180M"
- $env:CCACHE_DEPEND = 1 # cache misses are too expensive with preprocessor mode
- $env:CC = "ccache gcc"
- $env:LIBCLANG_PATH = Join-Path -Path $PWD.Path -ChildPath "msys64/mingw64/bin"
- mkdir build
- cd build
- ..\msys64\usr\bin\bash -lc "ccache --zero-stats"
-1
View File
-1
View File
@@ -1,7 +1,6 @@
source Kconfig.host
source backends/Kconfig
source accel/Kconfig
source dump/Kconfig
source target/Kconfig
source hw/Kconfig
source semihosting/Kconfig
+125 -215
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -130,7 +130,7 @@ Makefile.mtest: build.ninja scripts/mtest2make.py
.PHONY: update-buildoptions
all update-buildoptions: $(SRC_PATH)/scripts/meson-buildoptions.sh
$(SRC_PATH)/scripts/meson-buildoptions.sh: $(SRC_PATH)/meson_options.txt $(SRC_PATH)/scripts/meson-buildoptions.py
$(SRC_PATH)/scripts/meson-buildoptions.sh: $(SRC_PATH)/meson_options.txt
$(MESON) introspect --buildoptions $(SRC_PATH)/meson.build | $(PYTHON) \
scripts/meson-buildoptions.py > $@.tmp && mv $@.tmp $@
endif
+1 -1
View File
@@ -1 +1 @@
11.0.2
10.2.2
-3
View File
@@ -16,9 +16,6 @@ config KVM
config MSHV
bool
config NITRO
bool
config XEN
bool
select FSDEV_9P if VIRTFS
-5
View File
@@ -106,11 +106,6 @@ bool accel_cpu_common_realize(CPUState *cpu, Error **errp)
if (acc->cpu_common_realize && !acc->cpu_common_realize(cpu, errp)) {
return false;
}
if (acc->ops
&& acc->ops->cpu_target_realize
&& !acc->ops->cpu_target_realize(cpu, errp)) {
return false;
}
return true;
}
+1 -1
View File
@@ -27,7 +27,7 @@
#include "qemu/accel.h"
#include "qapi/qapi-commands-accelerator.h"
#include "monitor/monitor.h"
#include "hw/core/boards.h"
#include "hw/boards.h"
#include "hw/core/cpu.h"
#include "accel/accel-ops.h"
#include "accel/accel-cpu-ops.h"
+16 -2
View File
@@ -64,6 +64,20 @@ HVFState *hvf_state;
/* Memory slots */
hvf_slot *hvf_find_overlap_slot(uint64_t start, uint64_t size)
{
hvf_slot *slot;
int x;
for (x = 0; x < hvf_state->num_slots; ++x) {
slot = &hvf_state->slots[x];
if (slot->size && start < (slot->start + slot->size) &&
(start + size) > slot->start) {
return slot;
}
}
return NULL;
}
static void do_hvf_cpu_synchronize_state(CPUState *cpu, run_on_cpu_data arg)
{
if (!cpu->vcpu_dirty) {
@@ -135,6 +149,8 @@ static int hvf_init_vcpu(CPUState *cpu)
sigaction(SIG_IPI, &sigact, NULL);
#ifdef __aarch64__
pthread_sigmask(SIG_BLOCK, NULL, &cpu->accel->unblock_ipi_mask);
sigdelset(&cpu->accel->unblock_ipi_mask, SIG_IPI);
cpu->accel->guest_debug_enabled = false;
r = hv_vcpu_create(&cpu->accel->fd,
@@ -356,8 +372,6 @@ static void hvf_accel_ops_class_init(ObjectClass *oc, const void *data)
{
AccelOpsClass *ops = ACCEL_OPS_CLASS(oc);
ops->cpu_target_realize = hvf_arch_cpu_realize;
ops->create_vcpu_thread = hvf_start_vcpu_thread;
ops->kick_vcpu_thread = hvf_kick_vcpu_thread;
ops->handle_interrupt = generic_handle_interrupt;
+134 -60
View File
@@ -11,17 +11,25 @@
#include "qemu/osdep.h"
#include "qemu/error-report.h"
#include "accel/accel-ops.h"
#include "exec/cpu-common.h"
#include "system/address-spaces.h"
#include "system/memory.h"
#include "system/hvf.h"
#include "system/hvf_int.h"
#include "hw/core/cpu.h"
#include "hw/core/boards.h"
#include "hw/boards.h"
#include "trace.h"
bool hvf_allowed;
struct mac_slot {
int present;
uint64_t size;
uint64_t gpa_start;
uint64_t gva;
};
struct mac_slot mac_slots[32];
const char *hvf_return_string(hv_return_t ret)
{
switch (ret) {
@@ -50,44 +58,45 @@ void assert_hvf_ok_impl(hv_return_t ret, const char *file, unsigned int line,
abort();
}
static void do_hv_vm_protect(hwaddr start, size_t size,
hv_memory_flags_t flags)
static int do_hvf_set_memory(hvf_slot *slot, hv_memory_flags_t flags)
{
intptr_t page_mask = qemu_real_host_page_mask();
struct mac_slot *macslot;
hv_return_t ret;
trace_hvf_vm_protect(start, size, flags,
flags & HV_MEMORY_READ ? 'R' : '-',
flags & HV_MEMORY_WRITE ? 'W' : '-',
flags & HV_MEMORY_EXEC ? 'X' : '-');
g_assert(!((uintptr_t)start & ~page_mask));
g_assert(!(size & ~page_mask));
macslot = &mac_slots[slot->slot_id];
ret = hv_vm_protect(start, size, flags);
if (macslot->present) {
if (macslot->size != slot->size) {
macslot->present = 0;
trace_hvf_vm_unmap(macslot->gpa_start, macslot->size);
ret = hv_vm_unmap(macslot->gpa_start, macslot->size);
assert_hvf_ok(ret);
}
}
if (!slot->size) {
return 0;
}
macslot->present = 1;
macslot->gpa_start = slot->start;
macslot->size = slot->size;
trace_hvf_vm_map(slot->start, slot->size, slot->mem, flags,
flags & HV_MEMORY_READ ? 'R' : '-',
flags & HV_MEMORY_WRITE ? 'W' : '-',
flags & HV_MEMORY_EXEC ? 'X' : '-');
ret = hv_vm_map(slot->mem, slot->start, slot->size, flags);
assert_hvf_ok(ret);
}
void hvf_protect_clean_range(hwaddr addr, size_t size)
{
do_hv_vm_protect(addr, size, HV_MEMORY_READ | HV_MEMORY_EXEC);
}
void hvf_unprotect_dirty_range(hwaddr addr, size_t size)
{
do_hv_vm_protect(addr, size,
HV_MEMORY_READ | HV_MEMORY_WRITE | HV_MEMORY_EXEC);
return 0;
}
static void hvf_set_phys_mem(MemoryRegionSection *section, bool add)
{
hvf_slot *mem;
MemoryRegion *area = section->mr;
bool writable = !area->readonly && !area->rom_device;
hv_memory_flags_t flags;
uint64_t page_size = qemu_real_host_page_size();
uint64_t gpa = section->offset_within_address_space;
uint64_t size = int128_get64(section->size);
hv_return_t ret;
void *mem;
if (!memory_region_is_ram(area)) {
if (writable) {
@@ -101,60 +110,120 @@ static void hvf_set_phys_mem(MemoryRegionSection *section, bool add)
}
}
if (!QEMU_IS_ALIGNED(size, page_size) ||
!QEMU_IS_ALIGNED(gpa, page_size)) {
if (!QEMU_IS_ALIGNED(int128_get64(section->size), page_size) ||
!QEMU_IS_ALIGNED(section->offset_within_address_space, page_size)) {
/* Not page aligned, so we can not map as RAM */
add = false;
}
mem = hvf_find_overlap_slot(
section->offset_within_address_space,
int128_get64(section->size));
if (mem && add) {
if (mem->size == int128_get64(section->size) &&
mem->start == section->offset_within_address_space &&
mem->mem == (memory_region_get_ram_ptr(area) +
section->offset_within_region)) {
return; /* Same region was attempted to register, go away. */
}
}
/* Region needs to be reset. set the size to 0 and remap it. */
if (mem) {
mem->size = 0;
if (do_hvf_set_memory(mem, 0)) {
error_report("Failed to reset overlapping slot");
abort();
}
}
if (!add) {
trace_hvf_vm_unmap(gpa, size);
ret = hv_vm_unmap(gpa, size);
assert_hvf_ok(ret);
return;
}
flags = HV_MEMORY_READ | HV_MEMORY_EXEC | (writable ? HV_MEMORY_WRITE : 0);
mem = memory_region_get_ram_ptr(area) + section->offset_within_region;
if (area->readonly ||
(!memory_region_is_ram(area) && memory_region_is_romd(area))) {
flags = HV_MEMORY_READ | HV_MEMORY_EXEC;
} else {
flags = HV_MEMORY_READ | HV_MEMORY_WRITE | HV_MEMORY_EXEC;
}
trace_hvf_vm_map(gpa, size, mem, flags,
flags & HV_MEMORY_READ ? 'R' : '-',
flags & HV_MEMORY_WRITE ? 'W' : '-',
flags & HV_MEMORY_EXEC ? 'X' : '-');
ret = hv_vm_map(mem, gpa, size, flags);
assert_hvf_ok(ret);
/* Now make a new slot. */
int x;
for (x = 0; x < hvf_state->num_slots; ++x) {
mem = &hvf_state->slots[x];
if (!mem->size) {
break;
}
}
if (x == hvf_state->num_slots) {
error_report("No free slots");
abort();
}
mem->size = int128_get64(section->size);
mem->mem = memory_region_get_ram_ptr(area) + section->offset_within_region;
mem->start = section->offset_within_address_space;
mem->region = area;
if (do_hvf_set_memory(mem, flags)) {
error_report("Error registering new memory slot");
abort();
}
}
static void hvf_set_dirty_tracking(MemoryRegionSection *section, bool on)
{
hvf_slot *slot;
slot = hvf_find_overlap_slot(
section->offset_within_address_space,
int128_get64(section->size));
/* protect region against writes; begin tracking it */
if (on) {
slot->flags |= HVF_SLOT_LOG;
hv_vm_protect((uintptr_t)slot->start, (size_t)slot->size,
HV_MEMORY_READ | HV_MEMORY_EXEC);
/* stop tracking region*/
} else {
slot->flags &= ~HVF_SLOT_LOG;
hv_vm_protect((uintptr_t)slot->start, (size_t)slot->size,
HV_MEMORY_READ | HV_MEMORY_WRITE | HV_MEMORY_EXEC);
}
}
static void hvf_log_start(MemoryListener *listener,
MemoryRegionSection *section, int old, int new)
{
assert(new != 0);
if (old == 0) {
hvf_protect_clean_range(section->offset_within_address_space,
int128_get64(section->size));
if (old != 0) {
return;
}
hvf_set_dirty_tracking(section, 1);
}
static void hvf_log_stop(MemoryListener *listener,
MemoryRegionSection *section, int old, int new)
{
assert(old != 0);
if (new == 0) {
hvf_unprotect_dirty_range(section->offset_within_address_space,
int128_get64(section->size));
if (new != 0) {
return;
}
hvf_set_dirty_tracking(section, 0);
}
static void hvf_log_clear(MemoryListener *listener,
MemoryRegionSection *section)
static void hvf_log_sync(MemoryListener *listener,
MemoryRegionSection *section)
{
/*
* The dirty page bits within section are being cleared.
* Some number of those pages may have been dirtied and
* the write permission enabled. Reset the range read-only.
* sync of dirty pages is handled elsewhere; just make sure we keep
* tracking the region.
*/
hvf_protect_clean_range(section->offset_within_address_space,
int128_get64(section->size));
hvf_set_dirty_tracking(section, 1);
}
static void hvf_region_add(MemoryListener *listener,
@@ -176,20 +245,19 @@ static MemoryListener hvf_memory_listener = {
.region_del = hvf_region_del,
.log_start = hvf_log_start,
.log_stop = hvf_log_stop,
.log_clear = hvf_log_clear,
.log_sync = hvf_log_sync,
};
static int hvf_accel_init(AccelState *as, MachineState *ms)
{
int x;
hv_return_t ret;
HVFState *s = HVF_STATE(as);
int pa_range = 36;
MachineClass *mc = MACHINE_GET_CLASS(ms);
if (mc->get_physical_address_range) {
pa_range = mc->get_physical_address_range(ms,
hvf_arch_get_default_ipa_bit_size(), hvf_arch_get_max_ipa_bit_size());
if (mc->hvf_get_physical_address_range) {
pa_range = mc->hvf_get_physical_address_range(ms);
if (pa_range < 0) {
return -EINVAL;
}
@@ -203,6 +271,12 @@ static int hvf_accel_init(AccelState *as, MachineState *ms)
}
assert_hvf_ok(ret);
s->num_slots = ARRAY_SIZE(s->slots);
for (x = 0; x < s->num_slots; ++x) {
s->slots[x].size = 0;
s->slots[x].slot_id = x;
}
QTAILQ_INIT(&s->hvf_sw_breakpoints);
hvf_state = s;
+4 -1
View File
@@ -1,4 +1,7 @@
system_ss.add(when: 'CONFIG_HVF', if_true: files(
hvf_ss = ss.source_set()
hvf_ss.add(files(
'hvf-all.c',
'hvf-accel-ops.c',
))
specific_ss.add_all(when: 'CONFIG_HVF', if_true: hvf_ss)
-1
View File
@@ -5,4 +5,3 @@
# hvf-accel-ops.c
hvf_vm_map(uint64_t paddr, uint64_t size, void *vaddr, uint8_t flags, const char r, const char w, const char e) "paddr:0x%016"PRIx64" size:0x%08"PRIx64" vaddr:%p flags:0x%02x/%c%c%c"
hvf_vm_unmap(uint64_t paddr, uint64_t size) "paddr:0x%016"PRIx64" size:0x%08"PRIx64
hvf_vm_protect(uint64_t paddr, size_t size, uint8_t flags, const char r, const char w, const char e) "paddr:0x%016"PRIx64" size:0x%08zx flags:0x%02x/%c%c%c"
-1
View File
@@ -16,7 +16,6 @@
#include "qemu/osdep.h"
#include "qemu/error-report.h"
#include "qemu/main-loop.h"
#include "exec/cpu-common.h"
#include "accel/accel-cpu-ops.h"
#include "system/kvm.h"
#include "system/kvm_int.h"
+52 -340
View File
@@ -42,7 +42,7 @@
#include "qemu/event_notifier.h"
#include "qemu/main-loop.h"
#include "trace.h"
#include "hw/core/irq.h"
#include "hw/irq.h"
#include "qapi/visitor.h"
#include "qapi/qapi-types-common.h"
#include "qapi/qapi-visit-common.h"
@@ -53,7 +53,7 @@
#include "system/dirtylimit.h"
#include "qemu/range.h"
#include "hw/core/boards.h"
#include "hw/boards.h"
#include "system/stats.h"
/* This check must be after config-host.h is included */
@@ -61,7 +61,7 @@
#include <sys/eventfd.h>
#endif
#if defined(__x86_64__) || defined(__aarch64__)
#if defined(__i386__) || defined(__x86_64__) || defined(__aarch64__)
# define KVM_HAVE_MCE_INJECTION 1
#endif
@@ -90,7 +90,6 @@ struct KVMParkedVcpu {
};
KVMState *kvm_state;
VmfdChangeNotifier vmfd_notifier;
bool kvm_kernel_irqchip;
bool kvm_split_irqchip;
bool kvm_async_interrupts_allowed;
@@ -111,7 +110,7 @@ static uint64_t kvm_supported_memory_attributes;
static bool kvm_guest_memfd_supported;
static hwaddr kvm_max_slot_size = ~0;
static const KVMCapabilityInfo kvm_required_capabilities[] = {
static const KVMCapabilityInfo kvm_required_capabilites[] = {
KVM_CAP_INFO(USER_MEMORY),
KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS),
KVM_CAP_INFO(JOIN_MEMORY_REGIONS_WORKS),
@@ -124,16 +123,6 @@ static const KVMCapabilityInfo kvm_required_capabilities[] = {
static NotifierList kvm_irqchip_change_notifiers =
NOTIFIER_LIST_INITIALIZER(kvm_irqchip_change_notifiers);
static NotifierWithReturnList register_vmfd_changed_notifiers =
NOTIFIER_WITH_RETURN_LIST_INITIALIZER(register_vmfd_changed_notifiers);
static NotifierWithReturnList register_vcpufd_changed_notifiers =
NOTIFIER_WITH_RETURN_LIST_INITIALIZER(register_vcpufd_changed_notifiers);
static int map_kvm_run(KVMState *s, CPUState *cpu, Error **errp);
static int map_kvm_dirty_gfns(KVMState *s, CPUState *cpu, Error **errp);
static int vcpu_unmap_regions(KVMState *s, CPUState *cpu);
struct KVMResampleFd {
int gsi;
EventNotifier *resample_event;
@@ -427,90 +416,6 @@ err:
return ret;
}
static void kvm_create_vcpu_internal(CPUState *cpu, KVMState *s, int kvm_fd)
{
cpu->kvm_fd = kvm_fd;
cpu->kvm_state = s;
if (!s->guest_state_protected) {
cpu->vcpu_dirty = true;
}
cpu->dirty_pages = 0;
cpu->throttle_us_per_full = 0;
return;
}
static int kvm_rebind_vcpus(Error **errp)
{
CPUState *cpu;
unsigned long vcpu_id;
KVMState *s = kvm_state;
int kvm_fd, ret = 0;
CPU_FOREACH(cpu) {
vcpu_id = kvm_arch_vcpu_id(cpu);
if (cpu->kvm_fd) {
close(cpu->kvm_fd);
}
ret = kvm_arch_destroy_vcpu(cpu);
if (ret < 0) {
goto err;
}
if (s->coalesced_mmio_ring == (void *)cpu->kvm_run + PAGE_SIZE) {
s->coalesced_mmio_ring = NULL;
}
ret = vcpu_unmap_regions(s, cpu);
if (ret < 0) {
goto err;
}
ret = kvm_arch_pre_create_vcpu(cpu, errp);
if (ret < 0) {
goto err;
}
kvm_fd = kvm_vm_ioctl(s, KVM_CREATE_VCPU, vcpu_id);
if (kvm_fd < 0) {
error_report("KVM_CREATE_VCPU IOCTL failed for vCPU %lu (%s)",
vcpu_id, strerror(kvm_fd));
return kvm_fd;
}
kvm_create_vcpu_internal(cpu, s, kvm_fd);
ret = map_kvm_run(s, cpu, errp);
if (ret < 0) {
goto err;
}
if (s->kvm_dirty_ring_size) {
ret = map_kvm_dirty_gfns(s, cpu, errp);
if (ret < 0) {
goto err;
}
}
ret = kvm_arch_init_vcpu(cpu);
if (ret < 0) {
error_setg_errno(errp, -ret,
"kvm_init_vcpu: kvm_arch_init_vcpu failed (%lu)",
vcpu_id);
}
close(cpu->kvm_vcpu_stats_fd);
cpu->kvm_vcpu_stats_fd = kvm_vcpu_ioctl(cpu, KVM_GET_STATS_FD, NULL);
kvm_init_cpu_signals(cpu);
}
trace_kvm_rebind_vcpus();
err:
return ret;
}
static void kvm_park_vcpu(CPUState *cpu)
{
struct KVMParkedVcpu *vcpu;
@@ -574,7 +479,13 @@ static int kvm_create_vcpu(CPUState *cpu)
}
}
kvm_create_vcpu_internal(cpu, s, kvm_fd);
cpu->kvm_fd = kvm_fd;
cpu->kvm_state = s;
if (!s->guest_state_protected) {
cpu->vcpu_dirty = true;
}
cpu->dirty_pages = 0;
cpu->throttle_us_per_full = 0;
trace_kvm_create_vcpu(cpu->cpu_index, vcpu_id, kvm_fd);
@@ -593,11 +504,19 @@ int kvm_create_and_park_vcpu(CPUState *cpu)
return ret;
}
static int vcpu_unmap_regions(KVMState *s, CPUState *cpu)
static int do_kvm_destroy_vcpu(CPUState *cpu)
{
KVMState *s = kvm_state;
int mmap_size;
int ret = 0;
trace_kvm_destroy_vcpu(cpu->cpu_index, kvm_arch_vcpu_id(cpu));
ret = kvm_arch_destroy_vcpu(cpu);
if (ret < 0) {
goto err;
}
mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
if (mmap_size < 0) {
ret = mmap_size;
@@ -625,31 +544,6 @@ static int vcpu_unmap_regions(KVMState *s, CPUState *cpu)
cpu->kvm_dirty_gfns = NULL;
}
err:
return ret;
}
static int do_kvm_destroy_vcpu(CPUState *cpu)
{
KVMState *s = kvm_state;
int ret = 0;
trace_kvm_destroy_vcpu(cpu->cpu_index, kvm_arch_vcpu_id(cpu));
ret = kvm_arch_destroy_vcpu(cpu);
if (ret < 0) {
goto err;
}
/* If I am the CPU that created coalesced_mmio_ring, then discard it */
if (s->coalesced_mmio_ring == (void *)cpu->kvm_run + PAGE_SIZE) {
s->coalesced_mmio_ring = NULL;
}
ret = vcpu_unmap_regions(s, cpu);
if (ret < 0) {
goto err;
}
kvm_park_vcpu(cpu);
err:
return ret;
@@ -663,9 +557,26 @@ void kvm_destroy_vcpu(CPUState *cpu)
}
}
static int map_kvm_run(KVMState *s, CPUState *cpu, Error **errp)
int kvm_init_vcpu(CPUState *cpu, Error **errp)
{
int mmap_size, ret = 0;
KVMState *s = kvm_state;
int mmap_size;
int ret;
trace_kvm_init_vcpu(cpu->cpu_index, kvm_arch_vcpu_id(cpu));
ret = kvm_arch_pre_create_vcpu(cpu, errp);
if (ret < 0) {
goto err;
}
ret = kvm_create_vcpu(cpu);
if (ret < 0) {
error_setg_errno(errp, -ret,
"kvm_init_vcpu: kvm_create_vcpu failed (%lu)",
kvm_arch_vcpu_id(cpu));
goto err;
}
mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
if (mmap_size < 0) {
@@ -690,53 +601,14 @@ static int map_kvm_run(KVMState *s, CPUState *cpu, Error **errp)
(void *)cpu->kvm_run + s->coalesced_mmio * PAGE_SIZE;
}
err:
return ret;
}
static int map_kvm_dirty_gfns(KVMState *s, CPUState *cpu, Error **errp)
{
int ret = 0;
/* Use MAP_SHARED to share pages with the kernel */
cpu->kvm_dirty_gfns = mmap(NULL, s->kvm_dirty_ring_bytes,
PROT_READ | PROT_WRITE, MAP_SHARED,
cpu->kvm_fd,
PAGE_SIZE * KVM_DIRTY_LOG_PAGE_OFFSET);
if (cpu->kvm_dirty_gfns == MAP_FAILED) {
ret = -errno;
}
return ret;
}
int kvm_init_vcpu(CPUState *cpu, Error **errp)
{
KVMState *s = kvm_state;
int ret;
trace_kvm_init_vcpu(cpu->cpu_index, kvm_arch_vcpu_id(cpu));
ret = kvm_arch_pre_create_vcpu(cpu, errp);
if (ret < 0) {
goto err;
}
ret = kvm_create_vcpu(cpu);
if (ret < 0) {
error_setg_errno(errp, -ret,
"kvm_init_vcpu: kvm_create_vcpu failed (%lu)",
kvm_arch_vcpu_id(cpu));
goto err;
}
ret = map_kvm_run(s, cpu, errp);
if (ret < 0) {
goto err;
}
if (s->kvm_dirty_ring_size) {
ret = map_kvm_dirty_gfns(s, cpu, errp);
if (ret < 0) {
/* Use MAP_SHARED to share pages with the kernel */
cpu->kvm_dirty_gfns = mmap(NULL, s->kvm_dirty_ring_bytes,
PROT_READ | PROT_WRITE, MAP_SHARED,
cpu->kvm_fd,
PAGE_SIZE * KVM_DIRTY_LOG_PAGE_OFFSET);
if (cpu->kvm_dirty_gfns == MAP_FAILED) {
ret = -errno;
goto err;
}
}
@@ -2301,38 +2173,6 @@ void kvm_irqchip_change_notify(void)
notifier_list_notify(&kvm_irqchip_change_notifiers, NULL);
}
void kvm_vmfd_add_change_notifier(NotifierWithReturn *n)
{
notifier_with_return_list_add(&register_vmfd_changed_notifiers, n);
}
void kvm_vmfd_remove_change_notifier(NotifierWithReturn *n)
{
notifier_with_return_remove(n);
}
static int kvm_vmfd_change_notify(Error **errp)
{
return notifier_with_return_list_notify(&register_vmfd_changed_notifiers,
&vmfd_notifier, errp);
}
void kvm_vcpufd_add_change_notifier(NotifierWithReturn *n)
{
notifier_with_return_list_add(&register_vcpufd_changed_notifiers, n);
}
void kvm_vcpufd_remove_change_notifier(NotifierWithReturn *n)
{
notifier_with_return_remove(n);
}
static int kvm_vcpufd_change_notify(Error **errp)
{
return notifier_with_return_list_notify(&register_vcpufd_changed_notifiers,
&vmfd_notifier, errp);
}
int kvm_irqchip_get_virq(KVMState *s)
{
int next_virq;
@@ -2575,9 +2415,11 @@ void kvm_irqchip_set_qemuirq_gsi(KVMState *s, qemu_irq irq, int gsi)
g_hash_table_insert(s->gsimap, irq, GINT_TO_POINTER(gsi));
}
static int do_kvm_irqchip_create(KVMState *s)
static void kvm_irqchip_create(KVMState *s)
{
int ret;
assert(s->kernel_irqchip_split != ON_OFF_AUTO_AUTO);
if (kvm_check_extension(s, KVM_CAP_IRQCHIP)) {
;
} else if (kvm_check_extension(s, KVM_CAP_S390_IRQCHIP)) {
@@ -2587,7 +2429,7 @@ static int do_kvm_irqchip_create(KVMState *s)
exit(1);
}
} else {
return -EOPNOTSUPP;
return;
}
if (kvm_check_extension(s, KVM_CAP_IRQFD) <= 0) {
@@ -2611,16 +2453,6 @@ static int do_kvm_irqchip_create(KVMState *s)
exit(1);
}
return 0;
}
static void kvm_irqchip_create(KVMState *s)
{
assert(s->kernel_irqchip_split != ON_OFF_AUTO_AUTO);
if (do_kvm_irqchip_create(s) < 0) {
return;
}
kvm_kernel_irqchip = true;
/* If we have an in-kernel IRQ chip then we must have asynchronous
* interrupt delivery (though the reverse is not necessarily true)
@@ -2775,123 +2607,6 @@ static int kvm_setup_dirty_ring(KVMState *s)
return 0;
}
static int kvm_reset_vmfd(MachineState *ms)
{
KVMState *s;
KVMMemoryListener *kml;
int ret = 0, type;
Error *err = NULL;
/*
* bail if the current architecture does not support VM file
* descriptor change.
*/
if (!kvm_arch_supports_vmfd_change()) {
error_report("This target architecture does not support KVM VM "
"file descriptor change.");
return -EOPNOTSUPP;
}
s = KVM_STATE(ms->accelerator);
kml = &s->memory_listener;
memory_listener_unregister(&kml->listener);
memory_listener_unregister(&kvm_io_listener);
vmfd_notifier.pre = true;
ret = kvm_vmfd_change_notify(&err);
if (ret < 0) {
return ret;
}
assert(!err);
if (s->vmfd >= 0) {
close(s->vmfd);
}
type = find_kvm_machine_type(ms);
if (type < 0) {
return -EINVAL;
}
ret = do_kvm_create_vm(s, type);
if (ret < 0) {
return ret;
}
s->vmfd = ret;
/* guest state is now unprotected again */
kvm_state->guest_state_protected = false;
kvm_setup_dirty_ring(s);
/* rebind memory to new vm fd */
ret = ram_block_rebind(&err);
if (ret < 0) {
return ret;
}
assert(!err);
ret = kvm_arch_on_vmfd_change(ms, s);
if (ret < 0) {
return ret;
}
if (s->kernel_irqchip_allowed) {
/* ignore return from this function */
do_kvm_irqchip_create(s);
}
/*
* notify everyone that vmfd has changed.
*/
vmfd_notifier.vmfd = s->vmfd;
vmfd_notifier.pre = false;
ret = kvm_vmfd_change_notify(&err);
if (ret < 0) {
return ret;
}
assert(!err);
/*
* rebind new vcpu fds with the new kvm fds
* These can only be called after kvm_arch_on_vmfd_change()
*/
ret = kvm_rebind_vcpus(&err);
if (ret < 0) {
return ret;
}
assert(!err);
/* notify everyone that vcpu fd has changed. */
ret = kvm_vcpufd_change_notify(&err);
if (ret < 0) {
return ret;
}
assert(!err);
/* these can be only called after ram_block_rebind() */
memory_listener_register(&kml->listener, &address_space_memory);
memory_listener_register(&kvm_io_listener, &address_space_io);
/*
* kvm fd has changed. Commit the irq routes to KVM once more.
*/
kvm_irqchip_commit_routes(s);
/*
* for confidential guest, this is the last possible place where we
* can call synchronize_all_post_init() to sync all vcpu states to
* kvm.
*/
if (ms->cgs) {
cpu_synchronize_all_post_init();
}
trace_kvm_reset_vmfd();
return ret;
}
static int kvm_init(AccelState *as, MachineState *ms)
{
MachineClass *mc = MACHINE_GET_CLASS(ms);
@@ -2997,7 +2712,7 @@ static int kvm_init(AccelState *as, MachineState *ms)
nc++;
}
missing_cap = kvm_check_extension_list(s, kvm_required_capabilities);
missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);
if (!missing_cap) {
missing_cap =
kvm_check_extension_list(s, kvm_arch_required_capabilities);
@@ -3409,7 +3124,7 @@ int kvm_convert_memory(hwaddr start, hwaddr size, bool to_private)
addr = memory_region_get_ram_ptr(mr) + section.offset_within_region;
rb = qemu_ram_block_from_host(addr, false, &offset);
ret = ram_block_attributes_state_change(rb->attributes,
ret = ram_block_attributes_state_change(RAM_BLOCK_ATTRIBUTES(mr->rdm),
offset, size, to_private);
if (ret) {
error_report("Failed to notify the listener the state change of "
@@ -3585,7 +3300,6 @@ int kvm_cpu_exec(CPUState *cpu)
qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
ret = EXCP_INTERRUPT;
break;
case KVM_SYSTEM_EVENT_SEV_TERM:
case KVM_SYSTEM_EVENT_CRASH:
kvm_cpu_synchronize_state(cpu);
bql_lock();
@@ -4282,7 +3996,6 @@ static void kvm_accel_instance_init(Object *obj)
s->xen_evtchn_max_pirq = 256;
s->device = NULL;
s->msr_energy.enable = false;
s->honor_guest_pat = ON_OFF_AUTO_OFF;
}
/**
@@ -4301,7 +4014,6 @@ static void kvm_accel_class_init(ObjectClass *oc, const void *data)
AccelClass *ac = ACCEL_CLASS(oc);
ac->name = "KVM";
ac->init_machine = kvm_init;
ac->rebuild_guest = kvm_reset_vmfd;
ac->has_memory = kvm_accel_has_memory;
ac->allowed = &kvm_allowed;
ac->gdbstub_supported_sstep_flags = kvm_gdbstub_sstep_flags;
-2
View File
@@ -14,8 +14,6 @@ kvm_destroy_vcpu(int cpu_index, unsigned long arch_cpu_id) "index: %d id: %lu"
kvm_park_vcpu(int cpu_index, unsigned long arch_cpu_id) "index: %d id: %lu"
kvm_unpark_vcpu(unsigned long arch_cpu_id, const char *msg) "id: %lu %s"
kvm_irqchip_commit_routes(void) ""
kvm_reset_vmfd(void) ""
kvm_rebind_vcpus(void) ""
kvm_irqchip_add_msi_route(char *name, int vector, int virq) "dev %s vector %d virq %d"
kvm_irqchip_update_msi_route(int virq) "Updating MSI route virq=%d"
kvm_irqchip_release_virq(int virq) "virq %d"
-2
View File
@@ -6,13 +6,11 @@ user_ss.add(files('accel-user.c'))
subdir('tcg')
if have_system
subdir('hvf')
subdir('whpx')
subdir('qtest')
subdir('kvm')
subdir('xen')
subdir('stubs')
subdir('mshv')
subdir('nitro')
endif
# qtest
+2 -1
View File
@@ -10,8 +10,8 @@
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "qemu/osdep.h"
#include "linux/mshv.h"
#include "qemu/osdep.h"
#include "qemu/error-report.h"
#include "hw/hyperv/hvhdk_mini.h"
#include "hw/hyperv/hvgdk_mini.h"
@@ -20,6 +20,7 @@
#include "system/mshv.h"
#include "system/mshv_int.h"
#include "trace.h"
#include <stdint.h>
#include <sys/ioctl.h>
#define MSHV_IRQFD_RESAMPLE_FLAG (1 << MSHV_IRQFD_BIT_RESAMPLE)
+378 -28
View File
@@ -11,7 +11,9 @@
*/
#include "qemu/osdep.h"
#include "qemu/lockable.h"
#include "qemu/error-report.h"
#include "qemu/rcu.h"
#include "linux/mshv.h"
#include "system/address-spaces.h"
#include "system/mshv.h"
@@ -20,6 +22,137 @@
#include <sys/ioctl.h>
#include "trace.h"
typedef struct SlotsRCUReclaim {
struct rcu_head rcu;
GList *old_head;
MshvMemorySlot *removed_slot;
} SlotsRCUReclaim;
static void rcu_reclaim_slotlist(struct rcu_head *rcu)
{
SlotsRCUReclaim *r = container_of(rcu, SlotsRCUReclaim, rcu);
g_list_free(r->old_head);
g_free(r->removed_slot);
g_free(r);
}
static void publish_slots(GList *new_head, GList *old_head,
MshvMemorySlot *removed_slot)
{
MshvMemorySlotManager *manager = &mshv_state->msm;
assert(manager);
qatomic_store_release(&manager->slots, new_head);
SlotsRCUReclaim *r = g_new(SlotsRCUReclaim, 1);
r->old_head = old_head;
r->removed_slot = removed_slot;
call_rcu1(&r->rcu, rcu_reclaim_slotlist);
}
/* Needs to be called with mshv_state->msm.mutex held */
static int remove_slot(MshvMemorySlot *slot)
{
GList *old_head, *new_head;
MshvMemorySlotManager *manager = &mshv_state->msm;
assert(manager);
old_head = qatomic_load_acquire(&manager->slots);
if (!g_list_find(old_head, slot)) {
error_report("slot requested for removal not found");
return -1;
}
new_head = g_list_copy(old_head);
new_head = g_list_remove(new_head, slot);
manager->n_slots--;
publish_slots(new_head, old_head, slot);
return 0;
}
/* Needs to be called with mshv_state->msm.mutex held */
static MshvMemorySlot *append_slot(uint64_t gpa, uint64_t userspace_addr,
uint64_t size, bool readonly)
{
GList *old_head, *new_head;
MshvMemorySlot *slot;
MshvMemorySlotManager *manager = &mshv_state->msm;
assert(manager);
old_head = qatomic_load_acquire(&manager->slots);
if (manager->n_slots >= MSHV_MAX_MEM_SLOTS) {
error_report("no free memory slots available");
return NULL;
}
slot = g_new0(MshvMemorySlot, 1);
slot->guest_phys_addr = gpa;
slot->userspace_addr = userspace_addr;
slot->memory_size = size;
slot->readonly = readonly;
new_head = g_list_copy(old_head);
new_head = g_list_append(new_head, slot);
manager->n_slots++;
publish_slots(new_head, old_head, NULL);
return slot;
}
static int slot_overlaps(const MshvMemorySlot *slot1,
const MshvMemorySlot *slot2)
{
uint64_t start_1 = slot1->userspace_addr,
start_2 = slot2->userspace_addr;
size_t len_1 = slot1->memory_size,
len_2 = slot2->memory_size;
if (slot1 == slot2) {
return -1;
}
return ranges_overlap(start_1, len_1, start_2, len_2) ? 0 : -1;
}
static bool is_mapped(MshvMemorySlot *slot)
{
/* Subsequent reads of mapped field see a fully-initialized slot */
return qatomic_load_acquire(&slot->mapped);
}
/*
* Find slot that is:
* - overlapping in userspace
* - currently mapped in the guest
*
* Needs to be called with mshv_state->msm.mutex or RCU read lock held.
*/
static MshvMemorySlot *find_overlap_mem_slot(GList *head, MshvMemorySlot *slot)
{
GList *found;
MshvMemorySlot *overlap_slot;
found = g_list_find_custom(head, slot, (GCompareFunc) slot_overlaps);
if (!found) {
return NULL;
}
overlap_slot = found->data;
if (!overlap_slot || !is_mapped(overlap_slot)) {
return NULL;
}
return overlap_slot;
}
static int set_guest_memory(int vm_fd,
const struct mshv_user_mem_region *region)
{
@@ -27,38 +160,169 @@ static int set_guest_memory(int vm_fd,
ret = ioctl(vm_fd, MSHV_SET_GUEST_MEMORY, region);
if (ret < 0) {
error_report("failed to set guest memory");
return -errno;
error_report("failed to set guest memory: %s", strerror(errno));
return -1;
}
return 0;
}
static int map_or_unmap(int vm_fd, const MshvMemoryRegion *mr, bool map)
static int map_or_unmap(int vm_fd, const MshvMemorySlot *slot, bool map)
{
struct mshv_user_mem_region region = {0};
region.guest_pfn = mr->guest_phys_addr >> MSHV_PAGE_SHIFT;
region.size = mr->memory_size;
region.userspace_addr = mr->userspace_addr;
region.guest_pfn = slot->guest_phys_addr >> MSHV_PAGE_SHIFT;
region.size = slot->memory_size;
region.userspace_addr = slot->userspace_addr;
if (!map) {
region.flags |= (1 << MSHV_SET_MEM_BIT_UNMAP);
trace_mshv_unmap_memory(mr->userspace_addr, mr->guest_phys_addr,
mr->memory_size);
trace_mshv_unmap_memory(slot->userspace_addr, slot->guest_phys_addr,
slot->memory_size);
return set_guest_memory(vm_fd, &region);
}
region.flags = BIT(MSHV_SET_MEM_BIT_EXECUTABLE);
if (!mr->readonly) {
if (!slot->readonly) {
region.flags |= BIT(MSHV_SET_MEM_BIT_WRITABLE);
}
trace_mshv_map_memory(mr->userspace_addr, mr->guest_phys_addr,
mr->memory_size);
trace_mshv_map_memory(slot->userspace_addr, slot->guest_phys_addr,
slot->memory_size);
return set_guest_memory(vm_fd, &region);
}
static int slot_matches_region(const MshvMemorySlot *slot1,
const MshvMemorySlot *slot2)
{
return (slot1->guest_phys_addr == slot2->guest_phys_addr &&
slot1->userspace_addr == slot2->userspace_addr &&
slot1->memory_size == slot2->memory_size) ? 0 : -1;
}
/* Needs to be called with mshv_state->msm.mutex held */
static MshvMemorySlot *find_mem_slot_by_region(uint64_t gpa, uint64_t size,
uint64_t userspace_addr)
{
MshvMemorySlot ref_slot = {
.guest_phys_addr = gpa,
.userspace_addr = userspace_addr,
.memory_size = size,
};
GList *found;
MshvMemorySlotManager *manager = &mshv_state->msm;
assert(manager);
found = g_list_find_custom(manager->slots, &ref_slot,
(GCompareFunc) slot_matches_region);
return found ? found->data : NULL;
}
static int slot_covers_gpa(const MshvMemorySlot *slot, uint64_t *gpa_p)
{
uint64_t gpa_offset, gpa = *gpa_p;
gpa_offset = gpa - slot->guest_phys_addr;
return (slot->guest_phys_addr <= gpa && gpa_offset < slot->memory_size)
? 0 : -1;
}
/* Needs to be called with mshv_state->msm.mutex or RCU read lock held */
static MshvMemorySlot *find_mem_slot_by_gpa(GList *head, uint64_t gpa)
{
GList *found;
MshvMemorySlot *slot;
trace_mshv_find_slot_by_gpa(gpa);
found = g_list_find_custom(head, &gpa, (GCompareFunc) slot_covers_gpa);
if (found) {
slot = found->data;
trace_mshv_found_slot(slot->userspace_addr, slot->guest_phys_addr,
slot->memory_size);
return slot;
}
return NULL;
}
/* Needs to be called with mshv_state->msm.mutex held */
static void set_mapped(MshvMemorySlot *slot, bool mapped)
{
/* prior writes to mapped field becomes visible before readers see slot */
qatomic_store_release(&slot->mapped, mapped);
}
MshvRemapResult mshv_remap_overlap_region(int vm_fd, uint64_t gpa)
{
MshvMemorySlot *gpa_slot, *overlap_slot;
GList *head;
int ret;
MshvMemorySlotManager *manager = &mshv_state->msm;
/* fast path, called often by unmapped_gpa vm exit */
WITH_RCU_READ_LOCK_GUARD() {
assert(manager);
head = qatomic_load_acquire(&manager->slots);
/* return early if no slot is found */
gpa_slot = find_mem_slot_by_gpa(head, gpa);
if (gpa_slot == NULL) {
return MshvRemapNoMapping;
}
/* return early if no overlapping slot is found */
overlap_slot = find_overlap_mem_slot(head, gpa_slot);
if (overlap_slot == NULL) {
return MshvRemapNoOverlap;
}
}
/*
* We'll modify the mapping list, so we need to upgrade to mutex and
* recheck.
*/
assert(manager);
QEMU_LOCK_GUARD(&manager->mutex);
/* return early if no slot is found */
gpa_slot = find_mem_slot_by_gpa(manager->slots, gpa);
if (gpa_slot == NULL) {
return MshvRemapNoMapping;
}
/* return early if no overlapping slot is found */
overlap_slot = find_overlap_mem_slot(manager->slots, gpa_slot);
if (overlap_slot == NULL) {
return MshvRemapNoOverlap;
}
/* unmap overlapping slot */
ret = map_or_unmap(vm_fd, overlap_slot, false);
if (ret < 0) {
error_report("failed to unmap overlap region");
abort();
}
set_mapped(overlap_slot, false);
warn_report("mapped out userspace_addr=0x%016lx gpa=0x%010lx size=0x%lx",
overlap_slot->userspace_addr,
overlap_slot->guest_phys_addr,
overlap_slot->memory_size);
/* map region for gpa */
ret = map_or_unmap(vm_fd, gpa_slot, true);
if (ret < 0) {
error_report("failed to map new region");
abort();
}
set_mapped(gpa_slot, true);
warn_report("mapped in userspace_addr=0x%016lx gpa=0x%010lx size=0x%lx",
gpa_slot->userspace_addr, gpa_slot->guest_phys_addr,
gpa_slot->memory_size);
return MshvRemapOk;
}
static int handle_unmapped_mmio_region_read(uint64_t gpa, uint64_t size,
uint8_t *data)
{
@@ -124,20 +388,97 @@ int mshv_guest_mem_write(uint64_t gpa, const uint8_t *data, uintptr_t size,
return -1;
}
static int set_memory(const MshvMemoryRegion *mshv_mr, bool add)
static int tracked_unmap(int vm_fd, uint64_t gpa, uint64_t size,
uint64_t userspace_addr)
{
int ret = 0;
int ret;
MshvMemorySlot *slot;
MshvMemorySlotManager *manager = &mshv_state->msm;
if (!mshv_mr) {
error_report("Invalid mshv_mr");
assert(manager);
QEMU_LOCK_GUARD(&manager->mutex);
slot = find_mem_slot_by_region(gpa, size, userspace_addr);
if (!slot) {
trace_mshv_skip_unset_mem(userspace_addr, gpa, size);
/* no work to do */
return 0;
}
if (!is_mapped(slot)) {
/* remove slot, no need to unmap */
return remove_slot(slot);
}
ret = map_or_unmap(vm_fd, slot, false);
if (ret < 0) {
error_report("failed to unmap memory region");
return ret;
}
return remove_slot(slot);
}
static int tracked_map(int vm_fd, uint64_t gpa, uint64_t size, bool readonly,
uint64_t userspace_addr)
{
MshvMemorySlot *slot, *overlap_slot;
int ret;
MshvMemorySlotManager *manager = &mshv_state->msm;
assert(manager);
QEMU_LOCK_GUARD(&manager->mutex);
slot = find_mem_slot_by_region(gpa, size, userspace_addr);
if (slot) {
error_report("memory region already mapped at gpa=0x%lx, "
"userspace_addr=0x%lx, size=0x%lx",
slot->guest_phys_addr, slot->userspace_addr,
slot->memory_size);
return -1;
}
trace_mshv_set_memory(add, mshv_mr->guest_phys_addr,
mshv_mr->memory_size,
mshv_mr->userspace_addr, mshv_mr->readonly,
ret);
return map_or_unmap(mshv_state->vm, mshv_mr, add);
slot = append_slot(gpa, userspace_addr, size, readonly);
overlap_slot = find_overlap_mem_slot(manager->slots, slot);
if (overlap_slot) {
trace_mshv_remap_attempt(slot->userspace_addr,
slot->guest_phys_addr,
slot->memory_size);
warn_report("attempt to map region [0x%lx-0x%lx], while "
"[0x%lx-0x%lx] is already mapped in the guest",
userspace_addr, userspace_addr + size - 1,
overlap_slot->userspace_addr,
overlap_slot->userspace_addr +
overlap_slot->memory_size - 1);
/* do not register mem slot in hv, but record for later swap-in */
set_mapped(slot, false);
return 0;
}
ret = map_or_unmap(vm_fd, slot, true);
if (ret < 0) {
error_report("failed to map memory region");
return -1;
}
set_mapped(slot, true);
return 0;
}
static int set_memory(uint64_t gpa, uint64_t size, bool readonly,
uint64_t userspace_addr, bool add)
{
int vm_fd = mshv_state->vm;
if (add) {
return tracked_map(vm_fd, gpa, size, readonly, userspace_addr);
}
return tracked_unmap(vm_fd, gpa, size, userspace_addr);
}
/*
@@ -173,7 +514,9 @@ void mshv_set_phys_mem(MshvMemoryListener *mml, MemoryRegionSection *section,
bool writable = !area->readonly && !area->rom_device;
hwaddr start_addr, mr_offset, size;
void *ram;
MshvMemoryRegion mshv_mr = {0};
size = align_section(section, &start_addr);
trace_mshv_set_phys_mem(add, section->mr->name, start_addr);
size = align_section(section, &start_addr);
trace_mshv_set_phys_mem(add, section->mr->name, start_addr);
@@ -200,14 +543,21 @@ void mshv_set_phys_mem(MshvMemoryListener *mml, MemoryRegionSection *section,
ram = memory_region_get_ram_ptr(area) + mr_offset;
mshv_mr.guest_phys_addr = start_addr;
mshv_mr.memory_size = size;
mshv_mr.readonly = !writable;
mshv_mr.userspace_addr = (uint64_t)ram;
ret = set_memory(&mshv_mr, add);
ret = set_memory(start_addr, size, !writable, (uint64_t)ram, add);
if (ret < 0) {
error_report("Failed to set memory region");
error_report("failed to set memory region");
abort();
}
}
void mshv_init_memory_slot_manager(MshvState *mshv_state)
{
MshvMemorySlotManager *manager;
assert(mshv_state);
manager = &mshv_state->msm;
manager->n_slots = 0;
manager->slots = NULL;
qemu_mutex_init(&manager->mutex);
}
+4 -1
View File
@@ -1,6 +1,9 @@
system_ss.add(when: 'CONFIG_MSHV', if_true: files(
mshv_ss = ss.source_set()
mshv_ss.add(if_true: files(
'irq.c',
'mem.c',
'msr.c',
'mshv-all.c'
))
specific_ss.add_all(when: 'CONFIG_MSHV', if_true: mshv_ss)
+5 -3
View File
@@ -19,7 +19,7 @@
#include "qemu/event_notifier.h"
#include "qemu/module.h"
#include "qemu/main-loop.h"
#include "hw/core/boards.h"
#include "hw/boards.h"
#include "hw/hyperv/hvhdk.h"
#include "hw/hyperv/hvhdk_mini.h"
@@ -31,7 +31,6 @@
#include "qemu/guest-random.h"
#include "accel/accel-ops.h"
#include "accel/accel-cpu-ops.h"
#include "exec/cpu-common.h"
#include "system/cpus.h"
#include "system/runstate.h"
#include "system/accel-blocker.h"
@@ -41,6 +40,7 @@
#include "system/reset.h"
#include "trace.h"
#include <err.h>
#include <stdint.h>
#include <sys/ioctl.h>
#define TYPE_MSHV_ACCEL ACCEL_CLASS_NAME("mshv")
@@ -381,7 +381,7 @@ static void register_mshv_memory_listener(MshvState *s, MshvMemoryListener *mml,
}
}
int mshv_hvcall(int fd, const mshv_root_hvcall *args)
int mshv_hvcall(int fd, const struct mshv_root_hvcall *args)
{
int ret = 0;
@@ -437,6 +437,8 @@ static int mshv_init(AccelState *as, MachineState *ms)
mshv_init_msicontrol();
mshv_init_memory_slot_manager(s);
ret = create_vm(mshv_fd, &vm_fd);
if (ret < 0) {
close(mshv_fd);
+5
View File
@@ -26,3 +26,8 @@ mshv_map_memory(uint64_t userspace_addr, uint64_t gpa, uint64_t size) "\tu_a=0x%
mshv_unmap_memory(uint64_t userspace_addr, uint64_t gpa, uint64_t size) "\tu_a=0x%" PRIx64 " gpa=0x%010" PRIx64 " size=0x%08" PRIx64
mshv_set_phys_mem(bool add, const char *name, uint64_t gpa) "\tadd=%d name=%s gpa=0x%010" PRIx64
mshv_handle_mmio(uint64_t gva, uint64_t gpa, uint64_t size, uint8_t access_type) "\tgva=0x%" PRIx64 " gpa=0x%010" PRIx64 " size=0x%" PRIx64 " access_type=%d"
mshv_found_slot(uint64_t userspace_addr, uint64_t gpa, uint64_t size) "\tu_a=0x%" PRIx64 " gpa=0x%010" PRIx64 " size=0x%08" PRIx64
mshv_skip_unset_mem(uint64_t userspace_addr, uint64_t gpa, uint64_t size) "\tu_a=0x%" PRIx64 " gpa=0x%010" PRIx64 " size=0x%08" PRIx64
mshv_remap_attempt(uint64_t userspace_addr, uint64_t gpa, uint64_t size) "\tu_a=0x%" PRIx64 " gpa=0x%010" PRIx64 " size=0x%08" PRIx64
mshv_find_slot_by_gpa(uint64_t gpa) "\tgpa=0x%010" PRIx64
-3
View File
@@ -1,3 +0,0 @@
nitro_ss = ss.source_set()
nitro_ss.add(files('nitro-accel.c'))
system_ss.add_all(when: 'CONFIG_NITRO', if_true: nitro_ss)
-284
View File
@@ -1,284 +0,0 @@
/*
* Nitro Enclaves accelerator
*
* Copyright © 2026 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Authors:
* Alexander Graf <[email protected]>
*
* Nitro Enclaves are a confidential compute technology which
* allows a parent instance to carve out resources from itself
* and spawn a confidential sibling VM next to itself. Similar
* to other confidential compute solutions, this sibling is
* controlled by an underlying vmm, but still has a higher level
* vmm (QEMU) to implement some of its I/O functionality and
* lifecycle.
*
* This accelerator drives /dev/nitro_enclaves to spawn a Nitro
* Enclave. It works in tandem with the nitro_enclaves machine
* which ensures the correct backend devices are available and
* that the initial seed (an EIF file) is loaded at the correct
* offset in memory.
*
* The accel starts the enclave when the machine starts, after
* all device setup is finished.
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "qemu/osdep.h"
#include "qemu/error-report.h"
#include "qapi/error.h"
#include "qapi/visitor.h"
#include "qemu/module.h"
#include "qemu/rcu.h"
#include "qemu/accel.h"
#include "qemu/guest-random.h"
#include "qemu/main-loop.h"
#include "accel/accel-ops.h"
#include "accel/accel-cpu-ops.h"
#include "accel/dummy-cpus.h"
#include "system/cpus.h"
#include "hw/core/cpu.h"
#include "hw/core/boards.h"
#include "hw/nitro/nitro-vsock-bus.h"
#include "system/ramblock.h"
#include "system/nitro-accel.h"
#include "trace.h"
#include <sys/ioctl.h>
#include "standard-headers/linux/nitro_enclaves.h"
bool nitro_allowed;
typedef struct NitroAccelState {
AccelState parent_obj;
int ne_fd;
int enclave_fd;
uint64_t slot_uid;
uint64_t enclave_cid;
bool debug_mode;
} NitroAccelState;
static int nitro_init_machine(AccelState *as, MachineState *ms)
{
NitroAccelState *s = NITRO_ACCEL(as);
uint64_t slot_uid = 0;
int ret;
s->ne_fd = open("/dev/nitro_enclaves", O_RDWR | O_CLOEXEC);
if (s->ne_fd < 0) {
error_report("nitro: failed to open /dev/nitro_enclaves: %s",
strerror(errno));
return -errno;
}
ret = ioctl(s->ne_fd, NE_CREATE_VM, &slot_uid);
if (ret < 0) {
error_report("nitro: NE_CREATE_VM failed: %s", strerror(errno));
close(s->ne_fd);
return -errno;
}
s->enclave_fd = ret;
s->slot_uid = slot_uid;
return 0;
}
static int nitro_donate_ram_block(RAMBlock *rb, void *opaque)
{
NitroAccelState *s = opaque;
struct ne_user_memory_region region = {
.flags = 0,
.memory_size = rb->used_length,
.userspace_addr = (uint64_t)(uintptr_t)rb->host,
};
if (!rb->used_length) {
return 0;
}
if (ioctl(s->enclave_fd, NE_SET_USER_MEMORY_REGION, &region) < 0) {
error_report("nitro: NE_SET_USER_MEMORY_REGION failed for %s "
"(%" PRIu64 " bytes): %s", rb->idstr, rb->used_length,
strerror(errno));
return -errno;
}
return 0;
}
/*
* Start the Enclave. At this point memory is set up and the EIF is loaded.
* This function donates memory, adds vCPUs, and starts the enclave.
*/
static void nitro_setup_post(AccelState *as)
{
MachineState *ms = MACHINE(qdev_get_machine());
NitroAccelState *s = NITRO_ACCEL(as);
int nr_cpus = ms->smp.cpus;
int i, ret;
struct ne_enclave_start_info start_info = {
.flags = s->debug_mode ? NE_ENCLAVE_DEBUG_MODE : 0,
.enclave_cid = s->enclave_cid,
};
ret = qemu_ram_foreach_block(nitro_donate_ram_block, s);
if (ret < 0) {
error_report("nitro: failed to donate memory");
exit(1);
}
for (i = 0; i < nr_cpus; i++) {
uint32_t cpu_id = 0;
if (ioctl(s->enclave_fd, NE_ADD_VCPU, &cpu_id) < 0) {
error_report("nitro: NE_ADD_VCPU failed: %s", strerror(errno));
exit(1);
}
}
ret = ioctl(s->enclave_fd, NE_START_ENCLAVE, &start_info);
if (ret < 0) {
switch (errno) {
case NE_ERR_NO_MEM_REGIONS_ADDED:
error_report("nitro: no memory regions added");
break;
case NE_ERR_NO_VCPUS_ADDED:
error_report("nitro: no vCPUs added");
break;
case NE_ERR_ENCLAVE_MEM_MIN_SIZE:
error_report("nitro: memory is below the minimum "
"required size. Try increasing -m");
break;
case NE_ERR_FULL_CORES_NOT_USED:
error_report("nitro: requires full CPU cores. "
"Try increasing -smp to a multiple of threads "
"per core on this host (e.g. -smp 2)");
break;
case NE_ERR_NOT_IN_INIT_STATE:
error_report("nitro: not in init state");
break;
case NE_ERR_INVALID_FLAG_VALUE:
error_report("nitro: invalid flag value for NE_START_ENCLAVE");
break;
case NE_ERR_INVALID_ENCLAVE_CID:
error_report("nitro: invalid enclave CID");
break;
default:
error_report("nitro: NE_START_ENCLAVE failed: %s (errno %d)",
strerror(errno), errno);
break;
}
exit(1);
}
s->enclave_cid = start_info.enclave_cid;
trace_nitro_enclave_started(s->enclave_cid);
/*
* Notify all Nitro vsock bus devices that the enclave has started
* and provide them with the CID for vsock connections.
*/
{
NitroVsockBridge *bridge = nitro_vsock_bridge_find();
Error *err = NULL;
if (bridge) {
nitro_vsock_bridge_start_enclave(bridge,
(uint32_t)s->enclave_cid, &err);
if (err) {
error_report_err(err);
exit(1);
}
}
}
}
/* QOM properties */
static bool nitro_get_debug_mode(Object *obj, Error **errp)
{
return NITRO_ACCEL(obj)->debug_mode;
}
static void nitro_set_debug_mode(Object *obj, bool value, Error **errp)
{
NITRO_ACCEL(obj)->debug_mode = value;
}
static void nitro_get_enclave_cid(Object *obj, Visitor *v,
const char *name, void *opaque,
Error **errp)
{
uint64_t val = NITRO_ACCEL(obj)->enclave_cid;
visit_type_uint64(v, name, &val, errp);
}
static void nitro_set_enclave_cid(Object *obj, Visitor *v,
const char *name, void *opaque,
Error **errp)
{
uint64_t val;
if (visit_type_uint64(v, name, &val, errp)) {
NITRO_ACCEL(obj)->enclave_cid = val;
}
}
static void nitro_accel_class_init(ObjectClass *oc, const void *data)
{
AccelClass *ac = ACCEL_CLASS(oc);
ac->name = "Nitro";
ac->init_machine = nitro_init_machine;
ac->setup_post = nitro_setup_post;
ac->allowed = &nitro_allowed;
object_class_property_add_bool(oc, "debug-mode",
nitro_get_debug_mode,
nitro_set_debug_mode);
object_class_property_set_description(oc, "debug-mode",
"Start enclave in debug mode (enables console output)");
object_class_property_add(oc, "enclave-cid", "uint64",
nitro_get_enclave_cid,
nitro_set_enclave_cid,
NULL, NULL);
object_class_property_set_description(oc, "enclave-cid",
"Enclave CID (0 = auto-assigned by Nitro)");
}
static const TypeInfo nitro_accel_type = {
.name = TYPE_NITRO_ACCEL,
.parent = TYPE_ACCEL,
.instance_size = sizeof(NitroAccelState),
.class_init = nitro_accel_class_init,
};
module_obj(TYPE_NITRO_ACCEL);
static bool nitro_cpus_are_resettable(void)
{
return false;
}
static void nitro_accel_ops_class_init(ObjectClass *oc, const void *data)
{
AccelOpsClass *ops = ACCEL_OPS_CLASS(oc);
ops->create_vcpu_thread = dummy_start_vcpu_thread;
ops->handle_interrupt = generic_handle_interrupt;
ops->cpus_are_resettable = nitro_cpus_are_resettable;
}
static const TypeInfo nitro_accel_ops_type = {
.name = ACCEL_OPS_NAME("nitro"),
.parent = TYPE_ACCEL_OPS,
.class_init = nitro_accel_ops_class_init,
.abstract = true,
};
module_obj(ACCEL_OPS_NAME("nitro"));
static void nitro_type_init(void)
{
type_register_static(&nitro_accel_type);
type_register_static(&nitro_accel_ops_type);
}
type_init(nitro_type_init);
-6
View File
@@ -1,6 +0,0 @@
# SPDX-License-Identifier: GPL-2.0-or-later
#
# See docs/devel/tracing.rst for syntax documentation.
# nitro-accel.c
nitro_enclave_started(uint64_t cid) "nitro: enclave started, CID=%"PRIu64
-2
View File
@@ -1,2 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
#include "trace/trace-accel_nitro.h"
+1 -4
View File
@@ -1,4 +1 @@
qtest_module_ss = ss.source_set()
qtest_module_ss.add(files('qtest.c'))
modules += {'accel': {'qtest': qtest_module_ss}}
qtest_module_ss.add(when: ['CONFIG_SYSTEM_ONLY'], if_true: files('qtest.c'))
+2 -2
View File
@@ -31,12 +31,12 @@ static int64_t qtest_clock_counter;
static int64_t qtest_get_virtual_clock(void)
{
return qatomic_read(&qtest_clock_counter);
return qatomic_read_i64(&qtest_clock_counter);
}
static void qtest_set_virtual_clock(int64_t count)
{
qatomic_set(&qtest_clock_counter, count);
qatomic_set_i64(&qtest_clock_counter, count);
}
static int qtest_init_accel(AccelState *as, MachineState *ms)
-18
View File
@@ -79,24 +79,6 @@ void kvm_irqchip_change_notify(void)
{
}
void kvm_vmfd_add_change_notifier(NotifierWithReturn *n)
{
}
void kvm_vmfd_remove_change_notifier(NotifierWithReturn *n)
{
}
void kvm_vcpufd_add_change_notifier(NotifierWithReturn *n)
{
return;
}
void kvm_vcpufd_remove_change_notifier(NotifierWithReturn *n)
{
return;
}
int kvm_irqchip_add_irqfd_notifier_gsi(KVMState *s, EventNotifier *n,
EventNotifier *rn, int virq)
{
+10 -10
View File
@@ -1,10 +1,10 @@
stub_ss.add(files(
'hvf-stub.c',
'kvm-stub.c',
'nitro-stub.c',
'mshv-stub.c',
'nvmm-stub.c',
'tcg-stub.c',
'whpx-stub.c',
'xen-stub.c',
))
system_stubs_ss = ss.source_set()
system_stubs_ss.add(when: 'CONFIG_XEN', if_false: files('xen-stub.c'))
system_stubs_ss.add(when: 'CONFIG_KVM', if_false: files('kvm-stub.c'))
system_stubs_ss.add(when: 'CONFIG_TCG', if_false: files('tcg-stub.c'))
system_stubs_ss.add(when: 'CONFIG_HVF', if_false: files('hvf-stub.c'))
system_stubs_ss.add(when: 'CONFIG_NVMM', if_false: files('nvmm-stub.c'))
system_stubs_ss.add(when: 'CONFIG_WHPX', if_false: files('whpx-stub.c'))
system_stubs_ss.add(when: 'CONFIG_MSHV', if_false: files('mshv-stub.c'))
specific_ss.add_all(when: ['CONFIG_SYSTEM_ONLY'], if_true: system_stubs_ss)
-11
View File
@@ -1,11 +0,0 @@
/*
* Nitro accel stubs for QEMU
*
* Copyright © 2026 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "qemu/osdep.h"
bool nitro_allowed;
-1
View File
@@ -10,4 +10,3 @@
#include "system/whpx.h"
bool whpx_allowed;
bool whpx_irqchip_in_kernel;
+32
View File
@@ -46,8 +46,11 @@ CMPXCHG_HELPER(cmpxchgw_be, uint32_t)
CMPXCHG_HELPER(cmpxchgw_le, uint32_t)
CMPXCHG_HELPER(cmpxchgl_be, uint32_t)
CMPXCHG_HELPER(cmpxchgl_le, uint32_t)
#ifdef CONFIG_ATOMIC64
CMPXCHG_HELPER(cmpxchgq_be, uint64_t)
CMPXCHG_HELPER(cmpxchgq_le, uint64_t)
#endif
#if HAVE_CMPXCHG128
CMPXCHG_HELPER(cmpxchgo_be, Int128)
@@ -56,11 +59,32 @@ CMPXCHG_HELPER(cmpxchgo_le, Int128)
#undef CMPXCHG_HELPER
Int128 HELPER(nonatomic_cmpxchgo)(CPUArchState *env, uint64_t addr,
Int128 cmpv, Int128 newv, uint32_t oi)
{
#if TCG_TARGET_REG_BITS == 32
uintptr_t ra = GETPC();
Int128 oldv;
oldv = cpu_ld16_mmu(env, addr, oi, ra);
if (int128_eq(oldv, cmpv)) {
cpu_st16_mmu(env, addr, newv, oi, ra);
} else {
/* Even with comparison failure, still need a write cycle. */
probe_write(env, addr, 16, get_mmuidx(oi), ra);
}
return oldv;
#else
g_assert_not_reached();
#endif
}
#define ATOMIC_HELPER(OP, TYPE) \
TYPE HELPER(glue(atomic_,OP))(CPUArchState *env, uint64_t addr, \
TYPE val, uint32_t oi) \
{ return glue(glue(cpu_atomic_,OP),_mmu)(env, addr, val, oi, GETPC()); }
#ifdef CONFIG_ATOMIC64
#define GEN_ATOMIC_HELPERS(OP) \
ATOMIC_HELPER(glue(OP,b), uint32_t) \
ATOMIC_HELPER(glue(OP,w_be), uint32_t) \
@@ -69,6 +93,14 @@ CMPXCHG_HELPER(cmpxchgo_le, Int128)
ATOMIC_HELPER(glue(OP,l_le), uint32_t) \
ATOMIC_HELPER(glue(OP,q_be), uint64_t) \
ATOMIC_HELPER(glue(OP,q_le), uint64_t)
#else
#define GEN_ATOMIC_HELPERS(OP) \
ATOMIC_HELPER(glue(OP,b), uint32_t) \
ATOMIC_HELPER(glue(OP,w_be), uint32_t) \
ATOMIC_HELPER(glue(OP,w_le), uint32_t) \
ATOMIC_HELPER(glue(OP,l_be), uint32_t) \
ATOMIC_HELPER(glue(OP,l_le), uint32_t)
#endif
GEN_ATOMIC_HELPERS(fetch_add)
GEN_ATOMIC_HELPERS(fetch_and)
+2 -2
View File
@@ -27,8 +27,8 @@
# define SHIFT 4
#elif DATA_SIZE == 8
# define SUFFIX q
# define DATA_TYPE uint64_t
# define SDATA_TYPE int64_t
# define DATA_TYPE aligned_uint64_t
# define SDATA_TYPE aligned_int64_t
# define BSWAP bswap64
# define SHIFT 3
#elif DATA_SIZE == 4
+67 -27
View File
@@ -30,7 +30,7 @@
#include "accel/tcg/cpu-mmu-index.h"
#include "exec/cputlb.h"
#include "exec/tb-flush.h"
#include "system/ramblock.h"
#include "system/ram_addr.h"
#include "exec/mmu-access-type.h"
#include "exec/tlb-common.h"
#include "exec/vaddr.h"
@@ -857,9 +857,8 @@ void tlb_flush_page_bits_by_mmuidx_all_cpus_synced(CPUState *src_cpu,
void tlb_protect_code(ram_addr_t ram_addr)
{
physical_memory_test_and_clear_dirty(ram_addr & TARGET_PAGE_MASK,
TARGET_PAGE_SIZE,
DIRTY_MEMORY_CODE,
NULL);
TARGET_PAGE_SIZE,
DIRTY_MEMORY_CODE);
}
/* update the TLB so that writes in physical page 'phys_addr' are no longer
@@ -1090,7 +1089,7 @@ void tlb_set_page_full(CPUState *cpu, int mmu_idx,
}
} else {
/* I/O or ROMD */
iotlb = xlat;
iotlb = memory_region_section_get_iotlb(cpu, section) + xlat;
/*
* Writes to romd devices must go through MMIO to enable write.
* Reads to romd devices go through the ram_ptr found above,
@@ -1141,9 +1140,10 @@ void tlb_set_page_full(CPUState *cpu, int mmu_idx,
/*
* When memory region is ram, iotlb contains a TARGET_PAGE_BITS
* aligned ram_addr_t of the page base of the target RAM.
* Otherwise, iotlb contains a TARGET_PAGE_BITS aligned
* offset within section->mr of the page base (I/O, ROMD)
*
* Otherwise, iotlb contains
* - a physical section number in the lower TARGET_PAGE_BITS
* - the offset within section->mr of the page base (I/O, ROMD) with the
* TARGET_PAGE_BITS masked off.
* We subtract addr_page (which is page aligned and thus won't
* disturb the low bits) to give an offset which can be added to the
* (non-page-aligned) vaddr of the eventual memory access to get
@@ -1153,8 +1153,7 @@ void tlb_set_page_full(CPUState *cpu, int mmu_idx,
*/
desc->fulltlb[index] = *full;
full = &desc->fulltlb[index];
full->xlat_offset = iotlb - addr_page;
full->section = section;
full->xlat_section = iotlb - addr_page;
full->phys_addr = paddr_page;
/* Now calculate the new entry */
@@ -1270,14 +1269,14 @@ static inline void cpu_unaligned_access(CPUState *cpu, vaddr addr,
}
static MemoryRegionSection *
io_prepare(hwaddr *out_offset, CPUState *cpu, CPUTLBEntryFull *full,
vaddr addr, uintptr_t retaddr)
io_prepare(hwaddr *out_offset, CPUState *cpu, hwaddr xlat,
MemTxAttrs attrs, vaddr addr, uintptr_t retaddr)
{
MemoryRegionSection *section;
hwaddr mr_offset;
section = full->section;
mr_offset = full->xlat_offset + addr;
section = iotlb_to_section(cpu, xlat, attrs);
mr_offset = (xlat & TARGET_PAGE_MASK) + addr;
cpu->mem_io_pc = retaddr;
if (!cpu->neg.can_do_io) {
cpu_io_recompile(cpu, retaddr);
@@ -1336,7 +1335,7 @@ static bool victim_tlb_hit(CPUState *cpu, size_t mmu_idx, size_t index,
static void notdirty_write(CPUState *cpu, vaddr mem_vaddr, unsigned size,
CPUTLBEntryFull *full, uintptr_t retaddr)
{
ram_addr_t ram_addr = mem_vaddr + full->xlat_offset;
ram_addr_t ram_addr = mem_vaddr + full->xlat_section;
trace_memory_notdirty_write_access(mem_vaddr, ram_addr, size);
@@ -1545,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,
hostp, &full, 0, false);
p = *hostp;
&p, &full, 0, false);
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);
}
@@ -1593,7 +1592,9 @@ bool tlb_plugin_lookup(CPUState *cpu, vaddr addr, int mmu_idx,
/* We must have an iotlb entry for MMIO */
if (tlb_addr & TLB_MMIO) {
MemoryRegionSection *section = full->section;
MemoryRegionSection *section =
iotlb_to_section(cpu, full->xlat_section & ~TARGET_PAGE_MASK,
full->attrs);
data->is_io = true;
data->mr = section->mr;
} else {
@@ -1974,10 +1975,12 @@ static uint64_t do_ld_mmio_beN(CPUState *cpu, CPUTLBEntryFull *full,
MemoryRegionSection *section;
MemoryRegion *mr;
hwaddr mr_offset;
MemTxAttrs attrs;
tcg_debug_assert(size > 0 && size <= 8);
section = io_prepare(&mr_offset, cpu, full, addr, ra);
attrs = full->attrs;
section = io_prepare(&mr_offset, cpu, full->xlat_section, attrs, addr, ra);
mr = section->mr;
BQL_LOCK_GUARD();
@@ -1992,11 +1995,13 @@ static Int128 do_ld16_mmio_beN(CPUState *cpu, CPUTLBEntryFull *full,
MemoryRegionSection *section;
MemoryRegion *mr;
hwaddr mr_offset;
MemTxAttrs attrs;
uint64_t a, b;
tcg_debug_assert(size > 8 && size <= 16);
section = io_prepare(&mr_offset, cpu, full, addr, ra);
attrs = full->attrs;
section = io_prepare(&mr_offset, cpu, full->xlat_section, attrs, addr, ra);
mr = section->mr;
BQL_LOCK_GUARD();
@@ -2074,6 +2079,25 @@ static uint64_t do_ld_parts_beN(MMULookupPageData *p, uint64_t ret_be)
return ret_be;
}
/**
* do_ld_parts_be4
* @p: translation parameters
* @ret_be: accumulated data
*
* As do_ld_bytes_beN, but with one atomic load.
* Four aligned bytes are guaranteed to cover the load.
*/
static uint64_t do_ld_whole_be4(MMULookupPageData *p, uint64_t ret_be)
{
int o = p->addr & 3;
uint32_t x = load_atomic4(p->haddr - o);
x = cpu_to_be32(x);
x <<= o * 8;
x >>= (4 - p->size) * 8;
return (ret_be << (p->size * 8)) | x;
}
/**
* do_ld_parts_be8
* @p: translation parameters
@@ -2086,7 +2110,7 @@ static uint64_t do_ld_whole_be8(CPUState *cpu, uintptr_t ra,
MMULookupPageData *p, uint64_t ret_be)
{
int o = p->addr & 7;
uint64_t x = load_atomic8(p->haddr - o);
uint64_t x = load_atomic8_or_exit(cpu, ra, p->haddr - o);
x = cpu_to_be64(x);
x <<= o * 8;
@@ -2151,7 +2175,11 @@ static uint64_t do_ld_beN(CPUState *cpu, MMULookupPageData *p,
if (atom == MO_ATOM_IFALIGN_PAIR
? p->size == half_size
: p->size >= half_size) {
return do_ld_whole_be8(cpu, ra, p, ret_be);
if (!HAVE_al8_fast && p->size < 4) {
return do_ld_whole_be4(p, ret_be);
} else {
return do_ld_whole_be8(cpu, ra, p, ret_be);
}
}
/* fall through */
@@ -2488,10 +2516,12 @@ static uint64_t do_st_mmio_leN(CPUState *cpu, CPUTLBEntryFull *full,
MemoryRegionSection *section;
hwaddr mr_offset;
MemoryRegion *mr;
MemTxAttrs attrs;
tcg_debug_assert(size > 0 && size <= 8);
section = io_prepare(&mr_offset, cpu, full, addr, ra);
attrs = full->attrs;
section = io_prepare(&mr_offset, cpu, full->xlat_section, attrs, addr, ra);
mr = section->mr;
BQL_LOCK_GUARD();
@@ -2506,10 +2536,12 @@ static uint64_t do_st16_mmio_leN(CPUState *cpu, CPUTLBEntryFull *full,
MemoryRegionSection *section;
MemoryRegion *mr;
hwaddr mr_offset;
MemTxAttrs attrs;
tcg_debug_assert(size > 8 && size <= 16);
section = io_prepare(&mr_offset, cpu, full, addr, ra);
attrs = full->attrs;
section = io_prepare(&mr_offset, cpu, full->xlat_section, attrs, addr, ra);
mr = section->mr;
BQL_LOCK_GUARD();
@@ -2553,7 +2585,13 @@ static uint64_t do_st_leN(CPUState *cpu, MMULookupPageData *p,
if (atom == MO_ATOM_IFALIGN_PAIR
? p->size == half_size
: p->size >= half_size) {
return store_whole_le8(p->haddr, p->size, val_le);
if (!HAVE_al8_fast && p->size <= 4) {
return store_whole_le4(p->haddr, p->size, val_le);
} else if (HAVE_al8) {
return store_whole_le8(p->haddr, p->size, val_le);
} else {
cpu_loop_exit_atomic(cpu, ra);
}
}
/* fall through */
@@ -2847,8 +2885,10 @@ static void do_st16_mmu(CPUState *cpu, vaddr addr, Int128 val,
#define DATA_SIZE 4
#include "atomic_template.h"
#ifdef CONFIG_ATOMIC64
#define DATA_SIZE 8
#include "atomic_template.h"
#endif
#if defined(CONFIG_ATOMIC128) || HAVE_CMPXCHG128
#define DATA_SIZE 16
+13 -12
View File
@@ -86,8 +86,8 @@ static void icount_update_locked(CPUState *cpu)
int64_t executed = icount_get_executed(cpu);
cpu->icount_budget -= executed;
qatomic_set(&timers_state.qemu_icount,
timers_state.qemu_icount + executed);
qatomic_set_i64(&timers_state.qemu_icount,
timers_state.qemu_icount + executed);
}
/*
@@ -116,14 +116,15 @@ static int64_t icount_get_raw_locked(void)
/* Take into account what has run */
icount_update_locked(cpu);
}
/* The read is protected by the seqlock, but needs atomic to avoid UB */
return qatomic_read(&timers_state.qemu_icount);
/* The read is protected by the seqlock, but needs atomic64 to avoid UB */
return qatomic_read_i64(&timers_state.qemu_icount);
}
static int64_t icount_get_locked(void)
{
int64_t icount = icount_get_raw_locked();
return qatomic_read(&timers_state.qemu_icount_bias) + icount_to_ns(icount);
return qatomic_read_i64(&timers_state.qemu_icount_bias) +
icount_to_ns(icount);
}
int64_t icount_get_raw(void)
@@ -200,9 +201,9 @@ static void icount_adjust(void)
timers_state.icount_time_shift + 1);
}
timers_state.last_delta = delta;
qatomic_set(&timers_state.qemu_icount_bias,
cur_icount - (timers_state.qemu_icount
<< timers_state.icount_time_shift));
qatomic_set_i64(&timers_state.qemu_icount_bias,
cur_icount - (timers_state.qemu_icount
<< timers_state.icount_time_shift));
seqlock_write_unlock(&timers_state.vm_clock_seqlock,
&timers_state.vm_clock_lock);
}
@@ -268,8 +269,8 @@ static void icount_warp_rt(void)
}
warp_delta = MIN(warp_delta, delta);
}
qatomic_set(&timers_state.qemu_icount_bias,
timers_state.qemu_icount_bias + warp_delta);
qatomic_set_i64(&timers_state.qemu_icount_bias,
timers_state.qemu_icount_bias + warp_delta);
}
timers_state.vm_clock_warp_start = -1;
seqlock_write_unlock(&timers_state.vm_clock_seqlock,
@@ -360,8 +361,8 @@ void icount_start_warp_timer(void)
*/
seqlock_write_lock(&timers_state.vm_clock_seqlock,
&timers_state.vm_clock_lock);
qatomic_set(&timers_state.qemu_icount_bias,
timers_state.qemu_icount_bias + deadline);
qatomic_set_i64(&timers_state.qemu_icount_bias,
timers_state.qemu_icount_bias + deadline);
seqlock_write_unlock(&timers_state.vm_clock_seqlock,
&timers_state.vm_clock_lock);
qemu_clock_notify(QEMU_CLOCK_VIRTUAL);
+2 -3
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 as follows.
* Sets *@hostp (when @hostp is non-NULL) 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,8 +105,7 @@ 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)
{
void *discard;
return get_page_addr_code_hostp(env, addr, &discard);
return get_page_addr_code_hostp(env, addr, NULL);
}
/*
+128 -21
View File
@@ -12,6 +12,13 @@
#include "host/load-extract-al16-al8.h.inc"
#include "host/store-insert-al16.h.inc"
#ifdef CONFIG_ATOMIC64
# define HAVE_al8 true
#else
# define HAVE_al8 false
#endif
#define HAVE_al8_fast (ATOMIC_REG_SIZE >= 8)
/**
* required_atomicity:
*
@@ -125,7 +132,44 @@ static inline uint32_t load_atomic4(void *pv)
static inline uint64_t load_atomic8(void *pv)
{
uint64_t *p = __builtin_assume_aligned(pv, 8);
return qatomic_read(p);
qemu_build_assert(HAVE_al8);
return qatomic_read__nocheck(p);
}
/**
* load_atomic8_or_exit:
* @cpu: generic cpu state
* @ra: host unwind address
* @pv: host address
*
* Atomically load 8 aligned bytes from @pv.
* If this is not possible, longjmp out to restart serially.
*/
static uint64_t load_atomic8_or_exit(CPUState *cpu, uintptr_t ra, void *pv)
{
if (HAVE_al8) {
return load_atomic8(pv);
}
#ifdef CONFIG_USER_ONLY
/*
* If the page is not writable, then assume the value is immutable
* and requires no locking. This ignores the case of MAP_SHARED with
* another process, because the fallback start_exclusive solution
* provides no protection across processes.
*/
WITH_MMAP_LOCK_GUARD() {
if (!page_check_range(h2g(pv), 8, PAGE_WRITE_ORG)) {
uint64_t *p = __builtin_assume_aligned(pv, 8);
return *p;
}
}
#endif
/* Ultimate fallback: re-execute in serial context. */
trace_load_atom8_or_exit_fallback(ra);
cpu_loop_exit_atomic(cpu, ra);
}
/**
@@ -220,7 +264,9 @@ static uint64_t load_atom_extract_al8x2(void *pv)
}
/**
* load_atom_extract_al8
* load_atom_extract_al8_or_exit:
* @cpu: generic cpu state
* @ra: host unwind address
* @pv: host address
* @s: object size in bytes, @s <= 4.
*
@@ -229,14 +275,15 @@ static uint64_t load_atom_extract_al8x2(void *pv)
* 8-byte load and extract.
* The value is returned in the low bits of a uint32_t.
*/
static uint32_t load_atom_extract_al8(void *pv, int s)
static uint32_t load_atom_extract_al8_or_exit(CPUState *cpu, uintptr_t ra,
void *pv, int s)
{
uintptr_t pi = (uintptr_t)pv;
int o = pi & 7;
int shr = (HOST_BIG_ENDIAN ? 8 - s - o : o) * 8;
pv = (void *)(pi & ~7);
return load_atomic8(pv) >> shr;
return load_atomic8_or_exit(cpu, ra, pv) >> shr;
}
/**
@@ -250,7 +297,7 @@ static uint32_t load_atom_extract_al8(void *pv, int s)
* and p % 16 + s > 8. I.e. does not cross a 16-byte
* boundary, but *does* cross an 8-byte boundary.
* This is the slow version, so we must have eliminated
* any faster load_atom_extract_al8 case.
* any faster load_atom_extract_al8_or_exit case.
*
* If this is not possible, longjmp out to restart serially.
*/
@@ -327,6 +374,21 @@ static inline uint64_t load_atom_8_by_4(void *pv)
}
}
/**
* load_atom_8_by_8_or_4:
* @pv: host address
*
* Load 8 bytes from aligned @pv, with at least 4-byte atomicity.
*/
static inline uint64_t load_atom_8_by_8_or_4(void *pv)
{
if (HAVE_al8_fast) {
return load_atomic8(pv);
} else {
return load_atom_8_by_4(pv);
}
}
/**
* load_atom_2:
* @p: host address
@@ -356,8 +418,12 @@ static uint16_t load_atom_2(CPUState *cpu, uintptr_t ra,
return lduw_he_p(pv);
case MO_16:
/* The only case remaining is MO_ATOM_WITHIN16. */
if (!HAVE_al8_fast && (pi & 3) == 1) {
/* Big or little endian, we want the middle two bytes. */
return load_atomic4(pv - 1) >> 8;
}
if ((pi & 15) != 7) {
return load_atom_extract_al8(pv, 2);
return load_atom_extract_al8_or_exit(cpu, ra, pv, 2);
}
return load_atom_extract_al16_or_exit(cpu, ra, pv, 2);
default:
@@ -402,7 +468,7 @@ static uint32_t load_atom_4(CPUState *cpu, uintptr_t ra,
return load_atom_extract_al4x2(pv);
case MO_32:
if (!(pi & 4)) {
return load_atom_extract_al8(pv, 4);
return load_atom_extract_al8_or_exit(cpu, ra, pv, 4);
}
return load_atom_extract_al16_or_exit(cpu, ra, pv, 4);
default:
@@ -427,7 +493,7 @@ static uint64_t load_atom_8(CPUState *cpu, uintptr_t ra,
* If the host does not support 8-byte atomics, wait until we have
* examined the atomicity parameters below.
*/
if (likely((pi & 7) == 0)) {
if (HAVE_al8 && likely((pi & 7) == 0)) {
return load_atomic8(pv);
}
if (HAVE_ATOMIC128_RO) {
@@ -436,9 +502,30 @@ static uint64_t load_atom_8(CPUState *cpu, uintptr_t ra,
atmax = required_atomicity(cpu, pi, memop);
if (atmax == MO_64) {
if (!HAVE_al8 && (pi & 7) == 0) {
load_atomic8_or_exit(cpu, ra, pv);
}
return load_atom_extract_al16_or_exit(cpu, ra, pv, 8);
}
return load_atom_extract_al8x2(pv);
if (HAVE_al8_fast) {
return load_atom_extract_al8x2(pv);
}
switch (atmax) {
case MO_8:
return ldq_he_p(pv);
case MO_16:
return load_atom_8_by_2(pv);
case MO_32:
return load_atom_8_by_4(pv);
case -MO_32:
if (HAVE_al8) {
return load_atom_extract_al8x2(pv);
}
trace_load_atom8_fallback(memop, ra);
cpu_loop_exit_atomic(cpu, ra);
default:
g_assert_not_reached();
}
}
/**
@@ -478,10 +565,18 @@ static Int128 load_atom_16(CPUState *cpu, uintptr_t ra,
b = load_atom_8_by_4(pv + 8);
break;
case MO_64:
if (!HAVE_al8) {
trace_load_atom16_fallback(memop, ra);
cpu_loop_exit_atomic(cpu, ra);
}
a = load_atomic8(pv);
b = load_atomic8(pv + 8);
break;
case -MO_64:
if (!HAVE_al8) {
trace_load_atom16_fallback(memop, ra);
cpu_loop_exit_atomic(cpu, ra);
}
a = load_atom_extract_al8x2(pv);
b = load_atom_extract_al8x2(pv + 8);
break;
@@ -529,7 +624,9 @@ static inline void store_atomic4(void *pv, uint32_t val)
static inline void store_atomic8(void *pv, uint64_t val)
{
uint64_t *p = __builtin_assume_aligned(pv, 8);
qatomic_set(p, val);
qemu_build_assert(HAVE_al8);
qatomic_set__nocheck(p, val);
}
/**
@@ -591,8 +688,9 @@ static void store_atom_insert_al8(uint64_t *p, uint64_t val, uint64_t msk)
{
uint64_t old, new;
qemu_build_assert(HAVE_al8);
p = __builtin_assume_aligned(p, 8);
old = qatomic_read(p);
old = qatomic_read__nocheck(p);
do {
new = (old & ~msk) | val;
} while (!__atomic_compare_exchange_n(p, &old, new, true,
@@ -704,6 +802,7 @@ static uint64_t store_whole_le8(void *pv, int size, uint64_t val_le)
uint64_t m = MAKE_64BIT_MASK(0, sz);
uint64_t v;
qemu_build_assert(HAVE_al8);
if (HOST_BIG_ENDIAN) {
v = bswap64(val_le) >> sh;
m = bswap64(m) >> sh;
@@ -788,8 +887,10 @@ static void store_atom_2(CPUState *cpu, uintptr_t ra,
store_atom_insert_al4(pv - 1, (uint32_t)val << 8, MAKE_64BIT_MASK(8, 16));
return;
} else if ((pi & 7) == 3) {
store_atom_insert_al8(pv - 3, (uint64_t)val << 24, MAKE_64BIT_MASK(24, 16));
return;
if (HAVE_al8) {
store_atom_insert_al8(pv - 3, (uint64_t)val << 24, MAKE_64BIT_MASK(24, 16));
return;
}
} else if ((pi & 15) == 7) {
if (HAVE_CMPXCHG128) {
Int128 v = int128_lshift(int128_make64(val), 56);
@@ -856,8 +957,10 @@ static void store_atom_4(CPUState *cpu, uintptr_t ra,
return;
case MO_32:
if ((pi & 7) < 4) {
store_whole_le8(pv, 4, cpu_to_le32(val));
return;
if (HAVE_al8) {
store_whole_le8(pv, 4, cpu_to_le32(val));
return;
}
} else {
if (HAVE_CMPXCHG128) {
store_whole_le16(pv, 4, int128_make64(cpu_to_le32(val)));
@@ -885,7 +988,7 @@ static void store_atom_8(CPUState *cpu, uintptr_t ra,
uintptr_t pi = (uintptr_t)pv;
int atmax;
if (likely((pi & 7) == 0)) {
if (HAVE_al8 && likely((pi & 7) == 0)) {
store_atomic8(pv, val);
return;
}
@@ -902,7 +1005,7 @@ static void store_atom_8(CPUState *cpu, uintptr_t ra,
store_atom_8_by_4(pv, val);
return;
case -MO_32:
{
if (HAVE_al8) {
uint64_t val_le = cpu_to_le64(val);
int s2 = pi & 7;
int s1 = 8 - s2;
@@ -921,8 +1024,9 @@ static void store_atom_8(CPUState *cpu, uintptr_t ra,
default:
g_assert_not_reached();
}
return;
}
return;
break;
case MO_64:
if (HAVE_CMPXCHG128) {
store_whole_le16(pv, 8, int128_make64(cpu_to_le64(val)));
@@ -973,9 +1077,12 @@ static void store_atom_16(CPUState *cpu, uintptr_t ra,
store_atom_8_by_4(pv + 8, b);
return;
case MO_64:
store_atomic8(pv, a);
store_atomic8(pv + 8, b);
return;
if (HAVE_al8) {
store_atomic8(pv, a);
store_atomic8(pv + 8, b);
return;
}
break;
case -MO_64:
if (HAVE_CMPXCHG128) {
uint64_t val_le;
+1 -2
View File
@@ -24,14 +24,13 @@
*/
#include "qemu/osdep.h"
#include "exec/cpu-common.h"
#include "system/tcg.h"
#include "system/replay.h"
#include "exec/icount.h"
#include "qemu/main-loop.h"
#include "qemu/notify.h"
#include "qemu/guest-random.h"
#include "hw/core/boards.h"
#include "hw/boards.h"
#include "tcg/startup.h"
#include "tcg-accel-ops.h"
#include "tcg-accel-ops-mttcg.h"
+1 -1
View File
@@ -37,7 +37,7 @@
#include "qemu/units.h"
#include "qemu/target-info.h"
#ifndef CONFIG_USER_ONLY
#include "hw/core/boards.h"
#include "hw/boards.h"
#include "exec/tb-flush.h"
#include "system/runstate.h"
#endif
+15
View File
@@ -55,6 +55,21 @@ uint32_t HELPER(remu_i32)(uint32_t arg1, uint32_t arg2)
/* 64-bit helpers */
uint64_t HELPER(shl_i64)(uint64_t arg1, uint64_t arg2)
{
return arg1 << arg2;
}
uint64_t HELPER(shr_i64)(uint64_t arg1, uint64_t arg2)
{
return arg1 >> arg2;
}
int64_t HELPER(sar_i64)(int64_t arg1, int64_t arg2)
{
return arg1 >> arg2;
}
int64_t HELPER(div_i64)(int64_t arg1, int64_t arg2)
{
return arg1 / arg2;
+23
View File
@@ -8,6 +8,10 @@ DEF_HELPER_FLAGS_2(rem_i64, TCG_CALL_NO_RWG_SE, s64, s64, s64)
DEF_HELPER_FLAGS_2(divu_i64, TCG_CALL_NO_RWG_SE, i64, i64, i64)
DEF_HELPER_FLAGS_2(remu_i64, TCG_CALL_NO_RWG_SE, i64, i64, i64)
DEF_HELPER_FLAGS_2(shl_i64, TCG_CALL_NO_RWG_SE, i64, i64, i64)
DEF_HELPER_FLAGS_2(shr_i64, TCG_CALL_NO_RWG_SE, i64, i64, i64)
DEF_HELPER_FLAGS_2(sar_i64, TCG_CALL_NO_RWG_SE, s64, s64, s64)
DEF_HELPER_FLAGS_2(mulsh_i64, TCG_CALL_NO_RWG_SE, s64, s64, s64)
DEF_HELPER_FLAGS_2(muluh_i64, TCG_CALL_NO_RWG_SE, i64, i64, i64)
@@ -48,10 +52,12 @@ DEF_HELPER_FLAGS_5(atomic_cmpxchgl_be, TCG_CALL_NO_WG,
i32, env, i64, i32, i32, i32)
DEF_HELPER_FLAGS_5(atomic_cmpxchgl_le, TCG_CALL_NO_WG,
i32, env, i64, i32, i32, i32)
#ifdef CONFIG_ATOMIC64
DEF_HELPER_FLAGS_5(atomic_cmpxchgq_be, TCG_CALL_NO_WG,
i64, env, i64, i64, i64, i32)
DEF_HELPER_FLAGS_5(atomic_cmpxchgq_le, TCG_CALL_NO_WG,
i64, env, i64, i64, i64, i32)
#endif
#if HAVE_CMPXCHG128
DEF_HELPER_FLAGS_5(atomic_cmpxchgo_be, TCG_CALL_NO_WG,
i128, env, i64, i128, i128, i32)
@@ -71,6 +77,10 @@ DEF_HELPER_FLAGS_4(atomic_fetch_oro_le, TCG_CALL_NO_WG,
i128, env, i64, i128, i32)
#endif
DEF_HELPER_FLAGS_5(nonatomic_cmpxchgo, TCG_CALL_NO_WG,
i128, env, i64, i128, i128, i32)
#ifdef CONFIG_ATOMIC64
#define GEN_ATOMIC_HELPERS(NAME) \
DEF_HELPER_FLAGS_4(glue(glue(atomic_, NAME), b), \
TCG_CALL_NO_WG, i32, env, i64, i32, i32) \
@@ -86,6 +96,19 @@ DEF_HELPER_FLAGS_4(atomic_fetch_oro_le, TCG_CALL_NO_WG,
TCG_CALL_NO_WG, i64, env, i64, i64, i32) \
DEF_HELPER_FLAGS_4(glue(glue(atomic_, NAME), q_be), \
TCG_CALL_NO_WG, i64, env, i64, i64, i32)
#else
#define GEN_ATOMIC_HELPERS(NAME) \
DEF_HELPER_FLAGS_4(glue(glue(atomic_, NAME), b), \
TCG_CALL_NO_WG, i32, env, i64, i32, i32) \
DEF_HELPER_FLAGS_4(glue(glue(atomic_, NAME), w_le), \
TCG_CALL_NO_WG, i32, env, i64, i32, i32) \
DEF_HELPER_FLAGS_4(glue(glue(atomic_, NAME), w_be), \
TCG_CALL_NO_WG, i32, env, i64, i32, i32) \
DEF_HELPER_FLAGS_4(glue(glue(atomic_, NAME), l_le), \
TCG_CALL_NO_WG, i32, env, i64, i32, i32) \
DEF_HELPER_FLAGS_4(glue(glue(atomic_, NAME), l_be), \
TCG_CALL_NO_WG, i32, env, i64, i32, i32)
#endif /* CONFIG_ATOMIC64 */
GEN_ATOMIC_HELPERS(fetch_add)
GEN_ATOMIC_HELPERS(fetch_and)
+3 -1
View File
@@ -352,13 +352,15 @@ static bool translator_ld(CPUArchState *env, DisasContextBase *db,
return true;
}
break;
#ifdef CONFIG_ATOMIC64
case 8:
if (QEMU_IS_ALIGNED(pc, 8)) {
uint64_t t = qatomic_read((uint64_t *)host);
uint64_t t = qatomic_read__nocheck((uint64_t *)host);
stq_he_p(dest, t);
return true;
}
break;
#endif
}
/* Unaligned or partial read from the second page is not atomic. */
memcpy(dest, host, len);
-33
View File
@@ -1,8 +1,6 @@
#include "qemu/osdep.h"
#include "hw/core/cpu.h"
#include "accel/tcg/cpu-ops.h"
#include "exec/replay-core.h"
#include "exec/watchpoint.h"
#include "internal-common.h"
void cpu_resume(CPUState *cpu)
@@ -21,37 +19,6 @@ void cpu_exec_reset_hold(CPUState *cpu)
{
}
int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
int flags, CPUWatchpoint **watchpoint)
{
return -ENOSYS;
}
int cpu_watchpoint_remove(CPUState *cpu, vaddr addr,
vaddr len, int flags)
{
return -ENOSYS;
}
void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *wp)
{
}
void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
{
}
int cpu_watchpoint_address_matches(CPUState *cpu, vaddr addr, vaddr len)
{
return 0;
}
void cpu_check_watchpoint(CPUState *cpu, vaddr addr, vaddr len,
MemTxAttrs atr, int fl, uintptr_t ra)
{
}
/* User mode emulation does not support softmmu yet. */
void tlb_init(CPUState *cpu)
+17 -13
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_vaddr(start), last - start + 1,
mprotect(g2h_untagged(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_vaddr(start), len, prot & PAGE_RWX);
mprotect((void *)g2h_untagged(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_vaddr(addr)) {
if (guest_addr_valid_untagged(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_vaddr(env_cpu(env), addr);
*phost = (flags & TLB_INVALID_MASK) ? NULL : g2h(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_vaddr(env_cpu(env), addr) : NULL;
return size ? g2h(env_cpu(env), addr) : NULL;
}
void *tlb_vaddr_to_host(CPUArchState *env, vaddr addr,
MMUAccessType access_type, int mmu_idx)
{
return g2h_vaddr(env_cpu(env), addr);
return g2h(env_cpu(env), addr);
}
tb_page_addr_t get_page_addr_code_hostp(CPUArchState *env, vaddr addr,
@@ -822,7 +822,9 @@ 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);
*hostp = g2h_untagged_vaddr(addr);
if (hostp) {
*hostp = g2h_untagged(addr);
}
return addr;
}
@@ -938,7 +940,7 @@ static void *cpu_mmu_lookup(CPUState *cpu, vaddr addr,
cpu_loop_exit_sigbus(cpu, addr, type, ra);
}
ret = g2h_vaddr(cpu, addr);
ret = g2h(cpu, addr);
set_helper_retaddr(ra);
return ret;
}
@@ -968,7 +970,7 @@ int cpu_memory_rw_debug(CPUState *cpu, vaddr addr,
}
if (is_write) {
if (flags & PAGE_WRITE) {
memcpy(g2h_vaddr(cpu, addr), buf, l);
memcpy(g2h(cpu, addr), buf, l);
} else {
/* Bypass the host page protection using ptrace. */
if (fd == -1) {
@@ -987,13 +989,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_vaddr(addr));
(off_t)(uintptr_t)g2h_untagged(addr));
if (written != l) {
goto out_close;
}
}
} else if (flags & PAGE_READ) {
memcpy(buf, g2h_vaddr(cpu, addr), l);
memcpy(buf, g2h(cpu, addr), l);
} else {
/* Bypass the host page protection using ptrace. */
if (fd == -1) {
@@ -1003,7 +1005,7 @@ int cpu_memory_rw_debug(CPUState *cpu, vaddr addr,
}
}
if (pread(fd, buf, l,
(off_t)(uintptr_t)g2h_untagged_vaddr(addr)) != l) {
(off_t)(uintptr_t)g2h_untagged(addr)) != l) {
goto out_close;
}
}
@@ -1231,7 +1233,7 @@ static void *atomic_mmu_lookup(CPUState *cpu, vaddr addr, MemOpIdx oi,
cpu_loop_exit_atomic(cpu, retaddr);
}
ret = g2h_vaddr(cpu, addr);
ret = g2h(cpu, addr);
set_helper_retaddr(retaddr);
return ret;
}
@@ -1256,8 +1258,10 @@ static void *atomic_mmu_lookup(CPUState *cpu, vaddr addr, MemOpIdx oi,
#define DATA_SIZE 4
#include "atomic_template.h"
#ifdef CONFIG_ATOMIC64
#define DATA_SIZE 8
#include "atomic_template.h"
#endif
#if defined(CONFIG_ATOMIC128) || HAVE_CMPXCHG128
#define DATA_SIZE 16
-7
View File
@@ -1,7 +0,0 @@
whpx_ss = ss.source_set()
whpx_ss.add(files(
'whpx-accel-ops.c',
'whpx-common.c'
))
specific_ss.add_all(when: 'CONFIG_WHPX', if_true: whpx_ss)
-589
View File
@@ -1,589 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
/*
* QEMU Windows Hypervisor Platform accelerator (WHPX)
*
* Copyright Microsoft Corp. 2017
*/
#include "qemu/osdep.h"
#include "cpu.h"
#include "system/address-spaces.h"
#include "system/ioport.h"
#include "gdbstub/helpers.h"
#include "qemu/accel.h"
#include "accel/accel-ops.h"
#include "system/memory.h"
#include "system/whpx.h"
#include "system/cpus.h"
#include "system/runstate.h"
#include "qemu/main-loop.h"
#include "hw/core/boards.h"
#include "hw/intc/ioapic.h"
#include "qemu/error-report.h"
#include "qapi/error.h"
#include "qapi/qapi-types-common.h"
#include "qapi/qapi-visit-common.h"
#include "migration/blocker.h"
#include "accel/accel-cpu-target.h"
#include <winerror.h>
#include "system/whpx-internal.h"
#include "system/whpx-accel-ops.h"
#include "system/whpx-common.h"
#include "system/whpx-all.h"
#include <winhvplatform.h>
#include <winhvplatformdefs.h>
bool whpx_allowed;
bool whpx_irqchip_in_kernel;
static bool whp_dispatch_initialized;
static HMODULE hWinHvPlatform;
struct whpx_state whpx_global;
struct WHPDispatch whp_dispatch;
void whpx_flush_cpu_state(CPUState *cpu)
{
if (cpu->vcpu_dirty) {
whpx_set_registers(cpu, WHPX_LEVEL_RUNTIME_STATE);
cpu->vcpu_dirty = false;
}
}
void whpx_get_reg(CPUState *cpu, WHV_REGISTER_NAME reg, WHV_REGISTER_VALUE* val)
{
struct whpx_state *whpx = &whpx_global;
HRESULT hr;
whpx_flush_cpu_state(cpu);
hr = whp_dispatch.WHvGetVirtualProcessorRegisters(whpx->partition, cpu->cpu_index,
&reg, 1, val);
if (FAILED(hr)) {
error_report("WHPX: Failed to get register %08x, hr=%08lx", reg, hr);
}
}
void whpx_set_reg(CPUState *cpu, WHV_REGISTER_NAME reg, WHV_REGISTER_VALUE val)
{
struct whpx_state *whpx = &whpx_global;
HRESULT hr;
hr = whp_dispatch.WHvSetVirtualProcessorRegisters(whpx->partition, cpu->cpu_index,
&reg, 1, &val);
if (FAILED(hr)) {
error_report("WHPX: Failed to set register %08x, hr=%08lx", reg, hr);
}
}
/* Tries to find a breakpoint at the specified address. */
struct whpx_breakpoint *whpx_lookup_breakpoint_by_addr(uint64_t address)
{
struct whpx_state *whpx = &whpx_global;
int i;
if (whpx->breakpoints.breakpoints) {
for (i = 0; i < whpx->breakpoints.breakpoints->used; i++) {
if (address == whpx->breakpoints.breakpoints->data[i].address) {
return &whpx->breakpoints.breakpoints->data[i];
}
}
}
return NULL;
}
/*
* This function is called when the a VCPU is about to start and no other
* VCPUs have been started so far. Since the VCPU start order could be
* arbitrary, it doesn't have to be VCPU#0.
*
* It is used to commit the breakpoints into memory, and configure WHPX
* to intercept debug exceptions.
*
* Note that whpx_set_exception_exit_bitmap() cannot be called if one or
* more VCPUs are already running, so this is the best place to do it.
*/
int whpx_first_vcpu_starting(CPUState *cpu)
{
struct whpx_state *whpx = &whpx_global;
g_assert(bql_locked());
if (!QTAILQ_EMPTY(&cpu->breakpoints) ||
(whpx->breakpoints.breakpoints &&
whpx->breakpoints.breakpoints->used)) {
CPUBreakpoint *bp;
int i = 0;
bool update_pending = false;
QTAILQ_FOREACH(bp, &cpu->breakpoints, entry) {
if (i >= whpx->breakpoints.original_address_count ||
bp->pc != whpx->breakpoints.original_addresses[i]) {
update_pending = true;
}
i++;
}
if (i != whpx->breakpoints.original_address_count) {
update_pending = true;
}
if (update_pending) {
/*
* The CPU breakpoints have changed since the last call to
* whpx_translate_cpu_breakpoints(). WHPX breakpoints must
* now be recomputed.
*/
whpx_translate_cpu_breakpoints(&whpx->breakpoints, cpu, i);
}
/* Actually insert the breakpoints into the memory. */
whpx_apply_breakpoints(whpx->breakpoints.breakpoints, cpu, true);
}
HRESULT hr;
uint64_t exception_mask;
if (whpx->step_pending ||
(whpx->breakpoints.breakpoints &&
whpx->breakpoints.breakpoints->used)) {
/*
* We are either attempting to single-step one or more CPUs, or
* have one or more breakpoints enabled. Both require intercepting
* the WHvX64ExceptionTypeBreakpointTrap exception.
*/
exception_mask = 1UL << WHPX_INTERCEPT_DEBUG_TRAPS;
} else {
/* Let the guest handle all exceptions. */
exception_mask = 0;
}
hr = whpx_set_exception_exit_bitmap(exception_mask);
if (!SUCCEEDED(hr)) {
error_report("WHPX: Failed to update exception exit mask,"
"hr=%08lx.", hr);
return 1;
}
return 0;
}
/*
* This function is called when the last VCPU has finished running.
* It is used to remove any previously set breakpoints from memory.
*/
int whpx_last_vcpu_stopping(CPUState *cpu)
{
whpx_apply_breakpoints(whpx_global.breakpoints.breakpoints, cpu, false);
return 0;
}
static void do_whpx_cpu_synchronize_state(CPUState *cpu, run_on_cpu_data arg)
{
if (!cpu->vcpu_dirty) {
whpx_get_registers(cpu, WHPX_LEVEL_FULL_STATE);
cpu->vcpu_dirty = true;
}
}
static void do_whpx_cpu_synchronize_post_reset(CPUState *cpu,
run_on_cpu_data arg)
{
whpx_set_registers(cpu, WHPX_LEVEL_RESET_STATE);
cpu->vcpu_dirty = false;
}
static void do_whpx_cpu_synchronize_post_init(CPUState *cpu,
run_on_cpu_data arg)
{
whpx_set_registers(cpu, WHPX_LEVEL_FULL_STATE);
cpu->vcpu_dirty = false;
}
static void do_whpx_cpu_synchronize_pre_loadvm(CPUState *cpu,
run_on_cpu_data arg)
{
cpu->vcpu_dirty = true;
}
/*
* CPU support.
*/
void whpx_cpu_synchronize_state(CPUState *cpu)
{
if (!cpu->vcpu_dirty) {
run_on_cpu(cpu, do_whpx_cpu_synchronize_state, RUN_ON_CPU_NULL);
}
}
void whpx_cpu_synchronize_post_reset(CPUState *cpu)
{
run_on_cpu(cpu, do_whpx_cpu_synchronize_post_reset, RUN_ON_CPU_NULL);
}
void whpx_cpu_synchronize_post_init(CPUState *cpu)
{
run_on_cpu(cpu, do_whpx_cpu_synchronize_post_init, RUN_ON_CPU_NULL);
}
void whpx_cpu_synchronize_pre_loadvm(CPUState *cpu)
{
run_on_cpu(cpu, do_whpx_cpu_synchronize_pre_loadvm, RUN_ON_CPU_NULL);
}
static void whpx_pre_resume_vm(AccelState *as, bool step_pending)
{
whpx_global.step_pending = step_pending;
}
/*
* Vcpu support.
*/
int whpx_vcpu_exec(CPUState *cpu)
{
int ret;
int fatal;
for (;;) {
if (cpu->exception_index >= EXCP_INTERRUPT) {
ret = cpu->exception_index;
cpu->exception_index = -1;
break;
}
fatal = whpx_vcpu_run(cpu);
if (fatal) {
error_report("WHPX: Failed to exec a virtual processor");
abort();
}
}
return ret;
}
void whpx_destroy_vcpu(CPUState *cpu)
{
struct whpx_state *whpx = &whpx_global;
whp_dispatch.WHvDeleteVirtualProcessor(whpx->partition, cpu->cpu_index);
whpx_arch_destroy_vcpu(cpu);
g_free(cpu->accel);
}
void whpx_vcpu_kick(CPUState *cpu)
{
struct whpx_state *whpx = &whpx_global;
whp_dispatch.WHvCancelRunVirtualProcessor(
whpx->partition, cpu->cpu_index, 0);
}
/*
* Memory support.
*/
static void whpx_set_phys_mem(MemoryRegionSection *section, bool add)
{
struct whpx_state *whpx = &whpx_global;
MemoryRegion *area = section->mr;
bool writable = !area->readonly && !area->rom_device;
WHV_MAP_GPA_RANGE_FLAGS flags;
uint64_t page_size = qemu_real_host_page_size();
uint64_t gva = section->offset_within_address_space;
uint64_t size = int128_get64(section->size);
HRESULT hr;
void *mem;
if (!memory_region_is_ram(area)) {
if (writable) {
return;
} else if (!memory_region_is_romd(area)) {
add = false;
}
}
if (!QEMU_IS_ALIGNED(size, page_size) ||
!QEMU_IS_ALIGNED(gva, page_size)) {
/* Not page aligned, so we can not map as RAM */
add = false;
}
if (!add) {
hr = whp_dispatch.WHvUnmapGpaRange(whpx->partition,
gva, size);
if (FAILED(hr)) {
error_report("WHPX: failed to unmap GPA range");
abort();
}
return;
}
flags = WHvMapGpaRangeFlagRead | WHvMapGpaRangeFlagExecute
| (writable ? WHvMapGpaRangeFlagWrite : 0);
mem = memory_region_get_ram_ptr(area) + section->offset_within_region;
hr = whp_dispatch.WHvMapGpaRange(whpx->partition,
mem, gva, size, flags);
if (FAILED(hr)) {
error_report("WHPX: failed to map GPA range");
abort();
}
}
static void whpx_region_add(MemoryListener *listener,
MemoryRegionSection *section)
{
whpx_set_phys_mem(section, true);
}
static void whpx_region_del(MemoryListener *listener,
MemoryRegionSection *section)
{
whpx_set_phys_mem(section, false);
}
static void whpx_transaction_begin(MemoryListener *listener)
{
}
static void whpx_transaction_commit(MemoryListener *listener)
{
}
static void whpx_log_sync(MemoryListener *listener,
MemoryRegionSection *section)
{
MemoryRegion *mr = section->mr;
if (!memory_region_is_ram(mr)) {
return;
}
memory_region_set_dirty(mr, 0, int128_get64(section->size));
}
static MemoryListener whpx_memory_listener = {
.name = "whpx",
.begin = whpx_transaction_begin,
.commit = whpx_transaction_commit,
.region_add = whpx_region_add,
.region_del = whpx_region_del,
.log_sync = whpx_log_sync,
.priority = MEMORY_LISTENER_PRIORITY_ACCEL,
};
void whpx_memory_init(void)
{
memory_listener_register(&whpx_memory_listener, &address_space_memory);
}
/*
* Load the functions from the given library, using the given handle. If a
* handle is provided, it is used, otherwise the library is opened. The
* handle will be updated on return with the opened one.
*/
static bool load_whp_dispatch_fns(HMODULE *handle,
WHPFunctionList function_list)
{
HMODULE hLib = *handle;
#define WINHV_PLATFORM_DLL "WinHvPlatform.dll"
#define WHP_LOAD_FIELD_OPTIONAL(return_type, function_name, signature) \
whp_dispatch.function_name = \
(function_name ## _t)GetProcAddress(hLib, #function_name); \
#define WHP_LOAD_FIELD(return_type, function_name, signature) \
whp_dispatch.function_name = \
(function_name ## _t)GetProcAddress(hLib, #function_name); \
if (!whp_dispatch.function_name) { \
error_report("Could not load function %s", #function_name); \
goto error; \
} \
#define WHP_LOAD_LIB(lib_name, handle_lib) \
if (!handle_lib) { \
handle_lib = LoadLibrary(lib_name); \
if (!handle_lib) { \
error_report("Could not load library %s.", lib_name); \
goto error; \
} \
} \
switch (function_list) {
case WINHV_PLATFORM_FNS_DEFAULT:
WHP_LOAD_LIB(WINHV_PLATFORM_DLL, hLib)
LIST_WINHVPLATFORM_FUNCTIONS(WHP_LOAD_FIELD)
break;
case WINHV_PLATFORM_FNS_SUPPLEMENTAL:
WHP_LOAD_LIB(WINHV_PLATFORM_DLL, hLib)
LIST_WINHVPLATFORM_FUNCTIONS_SUPPLEMENTAL(WHP_LOAD_FIELD_OPTIONAL)
break;
}
*handle = hLib;
return true;
error:
if (hLib) {
FreeLibrary(hLib);
}
return false;
}
static void whpx_set_kernel_irqchip(Object *obj, Visitor *v,
const char *name, void *opaque,
Error **errp)
{
struct whpx_state *whpx = &whpx_global;
OnOffSplit mode;
if (!visit_type_OnOffSplit(v, name, &mode, errp)) {
return;
}
switch (mode) {
case ON_OFF_SPLIT_ON:
whpx->kernel_irqchip_allowed = true;
whpx->kernel_irqchip_required = true;
break;
case ON_OFF_SPLIT_OFF:
whpx->kernel_irqchip_allowed = false;
whpx->kernel_irqchip_required = false;
break;
case ON_OFF_SPLIT_SPLIT:
error_setg(errp, "WHPX: split irqchip currently not supported");
error_append_hint(errp,
"Try without kernel-irqchip or with kernel-irqchip=on|off");
break;
default:
/*
* The value was checked in visit_type_OnOffSplit() above. If
* we get here, then something is wrong in QEMU.
*/
abort();
}
}
static void whpx_set_hyperv(Object *obj, Visitor *v,
const char *name, void *opaque,
Error **errp)
{
struct whpx_state *whpx = &whpx_global;
OnOffAuto mode;
if (!visit_type_OnOffAuto(v, name, &mode, errp)) {
return;
}
switch (mode) {
case ON_OFF_AUTO_ON:
whpx->hyperv_enlightenments_allowed = true;
whpx->hyperv_enlightenments_required = true;
break;
case ON_OFF_AUTO_OFF:
whpx->hyperv_enlightenments_allowed = false;
whpx->hyperv_enlightenments_required = false;
break;
case ON_OFF_AUTO_AUTO:
whpx->hyperv_enlightenments_allowed = true;
whpx->hyperv_enlightenments_required = false;
break;
default:
/*
* The value was checked in visit_type_OnOffAuto() above. If
* we get here, then something is wrong in QEMU.
*/
abort();
}
}
static void whpx_cpu_accel_class_init(ObjectClass *oc, const void *data)
{
AccelCPUClass *acc = ACCEL_CPU_CLASS(oc);
acc->cpu_instance_init = whpx_cpu_instance_init;
}
static const TypeInfo whpx_cpu_accel_type = {
.name = ACCEL_CPU_NAME("whpx"),
.parent = TYPE_ACCEL_CPU,
.class_init = whpx_cpu_accel_class_init,
.abstract = true,
};
static void whpx_accel_class_init(ObjectClass *oc, const void *data)
{
AccelClass *ac = ACCEL_CLASS(oc);
ac->name = "WHPX";
ac->init_machine = whpx_accel_init;
ac->pre_resume_vm = whpx_pre_resume_vm;
ac->allowed = &whpx_allowed;
object_class_property_add(oc, "kernel-irqchip", "on|off|split",
NULL, whpx_set_kernel_irqchip,
NULL, NULL);
object_class_property_set_description(oc, "kernel-irqchip",
"Configure WHPX in-kernel irqchip");
object_class_property_add(oc, "hyperv", "OnOffAuto",
NULL, whpx_set_hyperv,
NULL, NULL);
object_class_property_set_description(oc, "hyperv",
"Configure Hyper-V enlightenments");
}
static void whpx_accel_instance_init(Object *obj)
{
struct whpx_state *whpx = &whpx_global;
memset(whpx, 0, sizeof(struct whpx_state));
/* Turn on kernel-irqchip, by default */
whpx->kernel_irqchip_allowed = true;
whpx->hyperv_enlightenments_allowed = true;
whpx->hyperv_enlightenments_required = false;
}
static const TypeInfo whpx_accel_type = {
.name = ACCEL_CLASS_NAME("whpx"),
.parent = TYPE_ACCEL,
.instance_init = whpx_accel_instance_init,
.class_init = whpx_accel_class_init,
};
static void whpx_type_init(void)
{
type_register_static(&whpx_accel_type);
type_register_static(&whpx_cpu_accel_type);
}
bool init_whp_dispatch(void)
{
if (whp_dispatch_initialized) {
return true;
}
if (!load_whp_dispatch_fns(&hWinHvPlatform, WINHV_PLATFORM_FNS_DEFAULT)) {
goto error;
}
assert(load_whp_dispatch_fns(&hWinHvPlatform,
WINHV_PLATFORM_FNS_SUPPLEMENTAL));
whp_dispatch_initialized = true;
return true;
error:
if (hWinHvPlatform) {
FreeLibrary(hWinHvPlatform);
}
return false;
}
type_init(whpx_type_init);
+1 -1
View File
@@ -1 +1 @@
system_ss.add(when: 'CONFIG_XEN', if_true: files('xen-all.c'))
specific_ss.add(when: 'CONFIG_XEN', if_true: files('xen-all.c'))
+1 -1
View File
@@ -26,7 +26,7 @@
#include "system/runstate.h"
#include "migration/misc.h"
#include "migration/global_state.h"
#include "hw/core/boards.h"
#include "hw/boards.h"
bool xen_allowed;
+149 -124
View File
@@ -26,43 +26,36 @@
#include <alsa/asoundlib.h>
#include "qemu/main-loop.h"
#include "qemu/module.h"
#include "qemu/error-report.h"
#include "qemu/audio.h"
#include "qom/object.h"
#include "trace.h"
#pragma GCC diagnostic ignored "-Waddress"
#define AUDIO_CAP "alsa"
#include "audio_int.h"
#define TYPE_AUDIO_ALSA "audio-alsa"
OBJECT_DECLARE_SIMPLE_TYPE(AudioALSA, AUDIO_ALSA)
static AudioBackendClass *audio_alsa_parent_class;
struct AudioALSA {
AudioMixengBackend parent_obj;
};
#define DEBUG_ALSA 0
struct pollhlp {
snd_pcm_t *handle;
struct pollfd *pfds;
int count;
int mask;
AudioMixengBackend *s;
AudioBackend *s;
};
typedef struct ALSAVoiceOut {
HWVoiceOut hw;
snd_pcm_t *handle;
struct pollhlp pollhlp;
Audiodev *dev;
} ALSAVoiceOut;
typedef struct ALSAVoiceIn {
HWVoiceIn hw;
snd_pcm_t *handle;
struct pollhlp pollhlp;
Audiodev *dev;
} ALSAVoiceIn;
struct alsa_params_req {
@@ -79,29 +72,33 @@ struct alsa_params_obt {
snd_pcm_uframes_t samples;
};
static void G_GNUC_PRINTF(2, 3) alsa_logerr(int err, const char *fmt, ...)
static void G_GNUC_PRINTF (2, 3) alsa_logerr (int err, const char *fmt, ...)
{
va_list ap;
error_printf("alsa: ");
va_start(ap, fmt);
error_vprintf(fmt, ap);
va_end(ap);
error_printf(" Reason: %s", snd_strerror(err));
error_printf("\n");
va_start (ap, fmt);
AUD_vlog (AUDIO_CAP, fmt, ap);
va_end (ap);
AUD_log (AUDIO_CAP, "Reason: %s\n", snd_strerror (err));
}
static void G_GNUC_PRINTF(3, 4) alsa_logerr2(int err, const char *typ,
const char *fmt, ...)
static void G_GNUC_PRINTF (3, 4) alsa_logerr2 (
int err,
const char *typ,
const char *fmt,
...
)
{
va_list ap;
error_printf("alsa: Could not initialize %s:", typ);
va_start(ap, fmt);
error_vprintf(fmt, ap);
va_end(ap);
error_printf(" Reason: %s", snd_strerror(err));
error_printf("\n");
AUD_log (AUDIO_CAP, "Could not initialize %s\n", typ);
va_start (ap, fmt);
AUD_vlog (AUDIO_CAP, fmt, ap);
va_end (ap);
AUD_log (AUDIO_CAP, "Reason: %s\n", snd_strerror (err));
}
static void alsa_fini_poll (struct pollhlp *hlp)
@@ -124,7 +121,7 @@ static void alsa_anal_close1 (snd_pcm_t **handlep)
{
int err = snd_pcm_close (*handlep);
if (err) {
alsa_logerr(err, "Failed to close PCM handle %p", *handlep);
alsa_logerr (err, "Failed to close PCM handle %p\n", *handlep);
}
*handlep = NULL;
}
@@ -139,7 +136,7 @@ static int alsa_recover (snd_pcm_t *handle)
{
int err = snd_pcm_prepare (handle);
if (err < 0) {
alsa_logerr(err, "Failed to prepare handle %p", handle);
alsa_logerr (err, "Failed to prepare handle %p\n", handle);
return -1;
}
return 0;
@@ -149,7 +146,7 @@ static int alsa_resume (snd_pcm_t *handle)
{
int err = snd_pcm_resume (handle);
if (err < 0) {
alsa_logerr(err, "Failed to resume handle %p", handle);
alsa_logerr (err, "Failed to resume handle %p\n", handle);
return -1;
}
return 0;
@@ -164,7 +161,7 @@ static void alsa_poll_handler (void *opaque)
count = poll (hlp->pfds, hlp->count, 0);
if (count < 0) {
warn_report("alsa_poll_handler: poll %s", strerror(errno));
dolog ("alsa_poll_handler: poll %s\n", strerror (errno));
return;
}
@@ -177,7 +174,7 @@ static void alsa_poll_handler (void *opaque)
err = snd_pcm_poll_descriptors_revents (hlp->handle, hlp->pfds,
hlp->count, &revents);
if (err < 0) {
alsa_logerr(err, "snd_pcm_poll_descriptors_revents");
alsa_logerr (err, "snd_pcm_poll_descriptors_revents");
return;
}
@@ -209,7 +206,7 @@ static void alsa_poll_handler (void *opaque)
break;
default:
warn_report("alsa: Unexpected state %d", state);
dolog ("Unexpected state %d\n", state);
}
}
@@ -220,8 +217,8 @@ static int alsa_poll_helper (snd_pcm_t *handle, struct pollhlp *hlp, int mask)
count = snd_pcm_poll_descriptors_count (handle);
if (count <= 0) {
warn_report("alsa: Could not initialize poll mode: "
"Invalid number of poll descriptors %d", count);
dolog ("Could not initialize poll mode\n"
"Invalid number of poll descriptors %d\n", count);
return -1;
}
@@ -229,7 +226,8 @@ static int alsa_poll_helper (snd_pcm_t *handle, struct pollhlp *hlp, int mask)
err = snd_pcm_poll_descriptors (handle, pfds, count);
if (err < 0) {
alsa_logerr(err, "Could not initialize poll mode: Could not obtain poll descriptors");
alsa_logerr (err, "Could not initialize poll mode\n"
"Could not obtain poll descriptors\n");
g_free (pfds);
return -1;
}
@@ -291,7 +289,10 @@ static snd_pcm_format_t aud_to_alsafmt(AudioFormat fmt, bool big_endian)
return big_endian ? SND_PCM_FORMAT_FLOAT_BE : SND_PCM_FORMAT_FLOAT_LE;
default:
warn_report("alsa: Internal logic error: Bad audio format %d", fmt);
dolog ("Internal logic error: Bad audio format %d\n", fmt);
#ifdef DEBUG_AUDIO
abort ();
#endif
return SND_PCM_FORMAT_U8;
}
}
@@ -361,13 +362,29 @@ static int alsa_to_audfmt (snd_pcm_format_t alsafmt, AudioFormat *fmt,
break;
default:
warn_report("alsa: Unrecognized audio format %d", alsafmt);
dolog ("Unrecognized audio format %d\n", alsafmt);
return -1;
}
return 0;
}
static void alsa_dump_info (struct alsa_params_req *req,
struct alsa_params_obt *obt,
snd_pcm_format_t obtfmt,
AudiodevAlsaPerDirectionOptions *apdo)
{
dolog("parameter | requested value | obtained value\n");
dolog("format | %10d | %10d\n", req->fmt, obtfmt);
dolog("channels | %10d | %10d\n",
req->nchannels, obt->nchannels);
dolog("frequency | %10d | %10d\n", req->freq, obt->freq);
dolog("============================================\n");
dolog("requested: buffer len %" PRId32 " period len %" PRId32 "\n",
apdo->buffer_length, apdo->period_length);
dolog("obtained: samples %ld\n", obt->samples);
}
static void alsa_set_threshold (snd_pcm_t *handle, snd_pcm_uframes_t threshold)
{
int err;
@@ -377,22 +394,23 @@ static void alsa_set_threshold (snd_pcm_t *handle, snd_pcm_uframes_t threshold)
err = snd_pcm_sw_params_current (handle, sw_params);
if (err < 0) {
error_report("alsa: Could not fully initialize DAC");
alsa_logerr(err, "Failed to get current software parameters");
dolog ("Could not fully initialize DAC\n");
alsa_logerr (err, "Failed to get current software parameters\n");
return;
}
err = snd_pcm_sw_params_set_start_threshold (handle, sw_params, threshold);
if (err < 0) {
error_report("alsa: Could not fully initialize DAC");
alsa_logerr(err, "Failed to set software threshold to %ld", threshold);
dolog ("Could not fully initialize DAC\n");
alsa_logerr (err, "Failed to set software threshold to %ld\n",
threshold);
return;
}
err = snd_pcm_sw_params (handle, sw_params);
if (err < 0) {
error_report("alsa: Could not fully initialize DAC");
alsa_logerr(err, "Failed to set software parameters");
dolog ("Could not fully initialize DAC\n");
alsa_logerr (err, "Failed to set software parameters\n");
return;
}
}
@@ -424,13 +442,13 @@ static int alsa_open(bool in, struct alsa_params_req *req,
SND_PCM_NONBLOCK
);
if (err < 0) {
alsa_logerr2(err, typ, "Failed to open `%s'", pcm_name);
alsa_logerr2 (err, typ, "Failed to open `%s':\n", pcm_name);
return -1;
}
err = snd_pcm_hw_params_any (handle, hw_params);
if (err < 0) {
alsa_logerr2(err, typ, "Failed to initialize hardware parameters");
alsa_logerr2 (err, typ, "Failed to initialize hardware parameters\n");
goto err;
}
@@ -440,18 +458,18 @@ static int alsa_open(bool in, struct alsa_params_req *req,
SND_PCM_ACCESS_RW_INTERLEAVED
);
if (err < 0) {
alsa_logerr2(err, typ, "Failed to set access type");
alsa_logerr2 (err, typ, "Failed to set access type\n");
goto err;
}
err = snd_pcm_hw_params_set_format (handle, hw_params, req->fmt);
if (err < 0) {
alsa_logerr2(err, typ, "Failed to set format %d", req->fmt);
alsa_logerr2 (err, typ, "Failed to set format %d\n", req->fmt);
}
err = snd_pcm_hw_params_set_rate_near (handle, hw_params, &freq, 0);
if (err < 0) {
alsa_logerr2(err, typ, "Failed to set frequency %d", req->freq);
alsa_logerr2 (err, typ, "Failed to set frequency %d\n", req->freq);
goto err;
}
@@ -461,7 +479,8 @@ static int alsa_open(bool in, struct alsa_params_req *req,
&nchannels
);
if (err < 0) {
alsa_logerr2(err, typ, "Failed to set number of channels %d", req->nchannels);
alsa_logerr2 (err, typ, "Failed to set number of channels %d\n",
req->nchannels);
goto err;
}
@@ -473,14 +492,14 @@ static int alsa_open(bool in, struct alsa_params_req *req,
handle, hw_params, &btime, &dir);
if (err < 0) {
alsa_logerr2(err, typ, "Failed to set buffer time to %" PRId32,
alsa_logerr2(err, typ, "Failed to set buffer time to %" PRId32 "\n",
apdo->buffer_length);
goto err;
}
if (apdo->has_buffer_length && btime != apdo->buffer_length) {
warn_report("alsa: Requested buffer time %" PRId32 " was rejected, using %u",
apdo->buffer_length, btime);
dolog("Requested buffer time %" PRId32
" was rejected, using %u\n", apdo->buffer_length, btime);
}
}
@@ -492,43 +511,43 @@ static int alsa_open(bool in, struct alsa_params_req *req,
&dir);
if (err < 0) {
alsa_logerr2(err, typ, "Failed to set period time to %" PRId32,
alsa_logerr2(err, typ, "Failed to set period time to %" PRId32 "\n",
apdo->period_length);
goto err;
}
if (apdo->has_period_length && ptime != apdo->period_length) {
warn_report("alsa: Requested period time %" PRId32 " was rejected, using %d",
apdo->period_length, ptime);
dolog("Requested period time %" PRId32 " was rejected, using %d\n",
apdo->period_length, ptime);
}
}
err = snd_pcm_hw_params (handle, hw_params);
if (err < 0) {
alsa_logerr2(err, typ, "Failed to apply audio parameters");
alsa_logerr2 (err, typ, "Failed to apply audio parameters\n");
goto err;
}
err = snd_pcm_hw_params_get_buffer_size (hw_params, &obt_buffer_size);
if (err < 0) {
alsa_logerr2(err, typ, "Failed to get buffer size");
alsa_logerr2 (err, typ, "Failed to get buffer size\n");
goto err;
}
err = snd_pcm_hw_params_get_format (hw_params, &obtfmt);
if (err < 0) {
alsa_logerr2(err, typ, "Failed to get format");
alsa_logerr2 (err, typ, "Failed to get format\n");
goto err;
}
if (alsa_to_audfmt (obtfmt, &obt->fmt, &obt->endianness)) {
error_report("alsa: Invalid format was returned %d", obtfmt);
dolog ("Invalid format was returned %d\n", obtfmt);
goto err;
}
err = snd_pcm_prepare (handle);
if (err < 0) {
alsa_logerr2(err, typ, "Could not prepare handle %p", handle);
alsa_logerr2 (err, typ, "Could not prepare handle %p\n", handle);
goto err;
}
@@ -546,9 +565,11 @@ static int alsa_open(bool in, struct alsa_params_req *req,
*handlep = handle;
trace_alsa_info_params(req->fmt, obtfmt, req->nchannels, obt->nchannels,
req->freq, obt->freq);
trace_alsa_info_samples(apdo->buffer_length, apdo->period_length, obt->samples);
if (DEBUG_ALSA || obtfmt != req->fmt ||
obt->nchannels != req->nchannels || obt->freq != req->freq) {
dolog ("Audio parameters for %s\n", typ);
alsa_dump_info(req, obt, obtfmt, apdo);
}
return 0;
@@ -571,7 +592,8 @@ static size_t alsa_buffer_get_free(HWVoiceOut *hw)
}
}
if (avail < 0) {
alsa_logerr(avail, "Could not obtain number of available frames");
alsa_logerr(avail,
"Could not obtain number of available frames\n");
avail = 0;
}
}
@@ -612,7 +634,8 @@ static size_t alsa_write(HWVoiceOut *hw, void *buf, size_t len)
case -EPIPE:
if (alsa_recover(alsa->handle)) {
alsa_logerr(written, "Failed to write %zu frames", len_frames);
alsa_logerr(written, "Failed to write %zu frames\n",
len_frames);
return pos;
}
trace_alsa_xrun_out();
@@ -624,7 +647,8 @@ static size_t alsa_write(HWVoiceOut *hw, void *buf, size_t len)
* recovery
*/
if (alsa_resume(alsa->handle)) {
alsa_logerr(written, "Failed to write %zu frames", len_frames);
alsa_logerr(written, "Failed to write %zu frames\n",
len_frames);
return pos;
}
trace_alsa_resume_out();
@@ -634,7 +658,8 @@ static size_t alsa_write(HWVoiceOut *hw, void *buf, size_t len)
return pos;
default:
alsa_logerr(written, "Failed to write %zu frames from %p", len_frames, src);
alsa_logerr(written, "Failed to write %zu frames from %p\n",
len, src);
return pos;
}
}
@@ -653,20 +678,21 @@ static void alsa_fini_out (HWVoiceOut *hw)
{
ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
trace_alsa_fini_out();
ldebug ("alsa_fini\n");
alsa_anal_close (&alsa->handle, &alsa->pollhlp);
}
static int alsa_init_out(HWVoiceOut *hw, struct audsettings *as)
static int alsa_init_out(HWVoiceOut *hw, struct audsettings *as,
void *drv_opaque)
{
ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
struct alsa_params_req req;
struct alsa_params_obt obt;
snd_pcm_t *handle;
struct audsettings obt_as;
Audiodev *dev = hw->s->dev;
Audiodev *dev = drv_opaque;
req.fmt = aud_to_alsafmt (as->fmt, as->big_endian);
req.fmt = aud_to_alsafmt (as->fmt, as->endianness);
req.freq = as->freq;
req.nchannels = as->nchannels;
@@ -677,13 +703,14 @@ static int alsa_init_out(HWVoiceOut *hw, struct audsettings *as)
obt_as.freq = obt.freq;
obt_as.nchannels = obt.nchannels;
obt_as.fmt = obt.fmt;
obt_as.big_endian = obt.endianness;
obt_as.endianness = obt.endianness;
audio_pcm_init_info (&hw->info, &obt_as);
hw->samples = obt.samples;
alsa->pollhlp.s = hw->s;
alsa->handle = handle;
alsa->dev = dev;
return 0;
}
@@ -698,19 +725,19 @@ static int alsa_voice_ctl (snd_pcm_t *handle, const char *typ, int ctl)
if (ctl == VOICE_CTL_PAUSE) {
err = snd_pcm_drop (handle);
if (err < 0) {
alsa_logerr(err, "Could not stop %s", typ);
alsa_logerr (err, "Could not stop %s\n", typ);
return -1;
}
} else {
err = snd_pcm_prepare (handle);
if (err < 0) {
alsa_logerr(err, "Could not prepare handle for %s", typ);
alsa_logerr (err, "Could not prepare handle for %s\n", typ);
return -1;
}
if (ctl == VOICE_CTL_START) {
err = snd_pcm_start(handle);
if (err < 0) {
alsa_logerr(err, "Could not start handle for %s", typ);
alsa_logerr (err, "Could not start handle for %s\n", typ);
return -1;
}
}
@@ -722,19 +749,19 @@ static int alsa_voice_ctl (snd_pcm_t *handle, const char *typ, int ctl)
static void alsa_enable_out(HWVoiceOut *hw, bool enable)
{
ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;
AudiodevAlsaPerDirectionOptions *apdo = hw->s->dev->u.alsa.out;
trace_alsa_enable_out(enable);
AudiodevAlsaPerDirectionOptions *apdo = alsa->dev->u.alsa.out;
if (enable) {
bool poll_mode = apdo->try_poll;
ldebug("enabling voice\n");
if (poll_mode && alsa_poll_out(hw)) {
poll_mode = 0;
}
hw->poll_mode = poll_mode;
alsa_voice_ctl(alsa->handle, "playback", VOICE_CTL_PREPARE);
} else {
ldebug("disabling voice\n");
if (hw->poll_mode) {
hw->poll_mode = 0;
alsa_fini_poll(&alsa->pollhlp);
@@ -743,16 +770,16 @@ static void alsa_enable_out(HWVoiceOut *hw, bool enable)
}
}
static int alsa_init_in(HWVoiceIn *hw, struct audsettings *as)
static int alsa_init_in(HWVoiceIn *hw, struct audsettings *as, void *drv_opaque)
{
ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
struct alsa_params_req req;
struct alsa_params_obt obt;
snd_pcm_t *handle;
struct audsettings obt_as;
Audiodev *dev = hw->s->dev;
Audiodev *dev = drv_opaque;
req.fmt = aud_to_alsafmt (as->fmt, as->big_endian);
req.fmt = aud_to_alsafmt (as->fmt, as->endianness);
req.freq = as->freq;
req.nchannels = as->nchannels;
@@ -763,13 +790,14 @@ static int alsa_init_in(HWVoiceIn *hw, struct audsettings *as)
obt_as.freq = obt.freq;
obt_as.nchannels = obt.nchannels;
obt_as.fmt = obt.fmt;
obt_as.big_endian = obt.endianness;
obt_as.endianness = obt.endianness;
audio_pcm_init_info (&hw->info, &obt_as);
hw->samples = obt.samples;
alsa->pollhlp.s = hw->s;
alsa->handle = handle;
alsa->dev = dev;
return 0;
}
@@ -800,7 +828,7 @@ static size_t alsa_read(HWVoiceIn *hw, void *buf, size_t len)
case -EPIPE:
if (alsa_recover(alsa->handle)) {
alsa_logerr(nread, "Failed to read %zu frames", len);
alsa_logerr(nread, "Failed to read %zu frames\n", len);
return pos;
}
trace_alsa_xrun_in();
@@ -810,7 +838,8 @@ static size_t alsa_read(HWVoiceIn *hw, void *buf, size_t len)
return pos;
default:
alsa_logerr(nread, "Failed to read %zu frames to %p", len, dst);
alsa_logerr(nread, "Failed to read %zu frames to %p\n",
len, dst);
return pos;
}
}
@@ -825,13 +854,12 @@ static size_t alsa_read(HWVoiceIn *hw, void *buf, size_t len)
static void alsa_enable_in(HWVoiceIn *hw, bool enable)
{
ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;
AudiodevAlsaPerDirectionOptions *apdo = hw->s->dev->u.alsa.in;
trace_alsa_enable_in(enable);
AudiodevAlsaPerDirectionOptions *apdo = alsa->dev->u.alsa.in;
if (enable) {
bool poll_mode = apdo->try_poll;
ldebug("enabling voice\n");
if (poll_mode && alsa_poll_in(hw)) {
poll_mode = 0;
}
@@ -839,6 +867,7 @@ static void alsa_enable_in(HWVoiceIn *hw, bool enable)
alsa_voice_ctl(alsa->handle, "capture", VOICE_CTL_START);
} else {
ldebug ("disabling voice\n");
if (hw->poll_mode) {
hw->poll_mode = 0;
alsa_fini_poll(&alsa->pollhlp);
@@ -855,8 +884,7 @@ static void alsa_init_per_direction(AudiodevAlsaPerDirectionOptions *apdo)
}
}
static bool
audio_alsa_realize(AudioBackend *abe, Audiodev *dev, Error **errp)
static void *alsa_audio_init(Audiodev *dev, Error **errp)
{
AudiodevAlsaOptions *aopts;
assert(dev->driver == AUDIODEV_DRIVER_ALSA);
@@ -884,44 +912,41 @@ audio_alsa_realize(AudioBackend *abe, Audiodev *dev, Error **errp)
dev->u.alsa.in->buffer_length = 92880;
}
return audio_alsa_parent_class->realize(abe, dev, errp);
return dev;
}
static void audio_alsa_class_init(ObjectClass *klass, const void *data)
static void alsa_audio_fini (void *opaque)
{
AudioBackendClass *b = AUDIO_BACKEND_CLASS(klass);
AudioMixengBackendClass *k = AUDIO_MIXENG_BACKEND_CLASS(klass);
audio_alsa_parent_class = AUDIO_BACKEND_CLASS(object_class_get_parent(klass));
b->realize = audio_alsa_realize;
k->max_voices_out = INT_MAX;
k->max_voices_in = INT_MAX;
k->voice_size_out = sizeof(ALSAVoiceOut);
k->voice_size_in = sizeof(ALSAVoiceIn);
k->init_out = alsa_init_out;
k->fini_out = alsa_fini_out;
k->write = alsa_write;
k->buffer_get_free = alsa_buffer_get_free;
k->run_buffer_out = audio_generic_run_buffer_out;
k->enable_out = alsa_enable_out;
k->init_in = alsa_init_in;
k->fini_in = alsa_fini_in;
k->read = alsa_read;
k->run_buffer_in = audio_generic_run_buffer_in;
k->enable_in = alsa_enable_in;
}
static const TypeInfo audio_types[] = {
{
.name = TYPE_AUDIO_ALSA,
.parent = TYPE_AUDIO_MIXENG_BACKEND,
.instance_size = sizeof(AudioALSA),
.class_init = audio_alsa_class_init,
},
static struct audio_pcm_ops alsa_pcm_ops = {
.init_out = alsa_init_out,
.fini_out = alsa_fini_out,
.write = alsa_write,
.buffer_get_free = alsa_buffer_get_free,
.run_buffer_out = audio_generic_run_buffer_out,
.enable_out = alsa_enable_out,
.init_in = alsa_init_in,
.fini_in = alsa_fini_in,
.read = alsa_read,
.run_buffer_in = audio_generic_run_buffer_in,
.enable_in = alsa_enable_in,
};
DEFINE_TYPES(audio_types)
module_obj(TYPE_AUDIO_ALSA);
static struct audio_driver alsa_audio_driver = {
.name = "alsa",
.init = alsa_audio_init,
.fini = alsa_audio_fini,
.pcm_ops = &alsa_pcm_ops,
.max_voices_out = INT_MAX,
.max_voices_in = INT_MAX,
.voice_size_out = sizeof (ALSAVoiceOut),
.voice_size_in = sizeof (ALSAVoiceIn)
};
static void register_audio_alsa(void)
{
audio_driver_register(&alsa_audio_driver);
}
type_init(register_audio_alsa);
-274
View File
@@ -1,274 +0,0 @@
/* SPDX-License-Identifier: MIT */
#include "qemu/osdep.h"
#include "qemu/audio.h"
#include "qemu/audio-capture.h"
#include "qapi/error.h"
#include "trace.h"
#include "qapi-types-audio.h"
bool audio_be_check(AudioBackend **be, Error **errp)
{
assert(be != NULL);
if (!*be) {
*be = audio_get_default_audio_be(errp);
if (!*be) {
return false;
}
}
return true;
}
SWVoiceIn *audio_be_open_in(
AudioBackend *be,
SWVoiceIn *sw,
const char *name,
void *callback_opaque,
audio_callback_fn callback_fn,
const struct audsettings *as)
{
AudioBackendClass *klass = AUDIO_BACKEND_GET_CLASS(be);
assert(name != NULL);
assert(callback_fn != NULL);
assert(as != NULL);
return klass->open_in(be, sw, name, callback_opaque, callback_fn, as);
}
SWVoiceOut *audio_be_open_out(
AudioBackend *be,
SWVoiceOut *sw,
const char *name,
void *callback_opaque,
audio_callback_fn callback_fn,
const struct audsettings *as)
{
AudioBackendClass *klass = AUDIO_BACKEND_GET_CLASS(be);
assert(name != NULL);
assert(callback_fn != NULL);
assert(as != NULL);
return klass->open_out(be, sw, name, callback_opaque, callback_fn, as);
}
void audio_be_close_out(AudioBackend *be, SWVoiceOut *sw)
{
AudioBackendClass *klass = AUDIO_BACKEND_GET_CLASS(be);
if (!sw) {
return;
}
return klass->close_out(be, sw);
}
void audio_be_close_in(AudioBackend *be, SWVoiceIn *sw)
{
AudioBackendClass *klass = AUDIO_BACKEND_GET_CLASS(be);
if (!sw) {
return;
}
return klass->close_in(be, sw);
}
bool audio_be_is_active_out(AudioBackend *be, SWVoiceOut *sw)
{
AudioBackendClass *klass = AUDIO_BACKEND_GET_CLASS(be);
if (!sw) {
return false;
}
return klass->is_active_out(be, sw);
}
bool audio_be_is_active_in(AudioBackend *be, SWVoiceIn *sw)
{
AudioBackendClass *klass = AUDIO_BACKEND_GET_CLASS(be);
if (!sw) {
return false;
}
return klass->is_active_in(be, sw);
}
size_t audio_be_write(AudioBackend *be, SWVoiceOut *sw, void *buf, size_t size)
{
AudioBackendClass *klass = AUDIO_BACKEND_GET_CLASS(be);
if (!sw) {
return 0;
}
return klass->write(be, sw, buf, size);
}
size_t audio_be_read(AudioBackend *be, SWVoiceIn *sw, void *buf, size_t size)
{
AudioBackendClass *klass = AUDIO_BACKEND_GET_CLASS(be);
if (!sw) {
return 0;
}
return klass->read(be, sw, buf, size);
}
int audio_be_get_buffer_size_out(AudioBackend *be, SWVoiceOut *sw)
{
AudioBackendClass *klass = AUDIO_BACKEND_GET_CLASS(be);
if (!sw) {
return 0;
}
return klass->get_buffer_size_out(be, sw);
}
void audio_be_set_active_out(AudioBackend *be, SWVoiceOut *sw, bool on)
{
AudioBackendClass *klass = AUDIO_BACKEND_GET_CLASS(be);
trace_audio_be_set_active_out(sw, on);
if (!sw) {
return;
}
return klass->set_active_out(be, sw, on);
}
void audio_be_set_active_in(AudioBackend *be, SWVoiceIn *sw, bool on)
{
AudioBackendClass *klass = AUDIO_BACKEND_GET_CLASS(be);
trace_audio_be_set_active_in(sw, on);
if (!sw) {
return;
}
return klass->set_active_in(be, sw, on);
}
void audio_be_set_volume_out(AudioBackend *be, SWVoiceOut *sw, Volume *vol)
{
AudioBackendClass *klass = AUDIO_BACKEND_GET_CLASS(be);
if (!sw) {
return;
}
klass->set_volume_out(be, sw, vol);
}
void audio_be_set_volume_in(AudioBackend *be, SWVoiceIn *sw, Volume *vol)
{
AudioBackendClass *klass = AUDIO_BACKEND_GET_CLASS(be);
if (!sw) {
return;
}
klass->set_volume_in(be, sw, vol);
}
CaptureVoiceOut *audio_be_add_capture(
AudioBackend *be,
const struct audsettings *as,
const struct audio_capture_ops *ops,
void *cb_opaque)
{
AudioBackendClass *klass = AUDIO_BACKEND_GET_CLASS(be);
assert(as != NULL);
assert(ops != NULL);
return klass->add_capture(be, as, ops, cb_opaque);
}
void audio_be_del_capture(AudioBackend *be, CaptureVoiceOut *cap, void *cb_opaque)
{
AudioBackendClass *klass = AUDIO_BACKEND_GET_CLASS(be);
if (!cap) {
return;
}
klass->del_capture(be, cap, cb_opaque);
}
#ifdef CONFIG_GIO
bool audio_be_can_set_dbus_server(AudioBackend *be)
{
AudioBackendClass *klass = AUDIO_BACKEND_GET_CLASS(be);
return klass->set_dbus_server != NULL;
}
bool audio_be_set_dbus_server(AudioBackend *be,
GDBusObjectManagerServer *server,
bool p2p,
Error **errp)
{
AudioBackendClass *klass = AUDIO_BACKEND_GET_CLASS(be);
assert(server != NULL);
if (!audio_be_can_set_dbus_server(be)) {
error_setg(errp, "Audiodev '%s' is not compatible with DBus",
audio_be_get_id(be));
return false;
}
return klass->set_dbus_server(be, server, p2p, errp);
}
#endif
const char *audio_be_get_id(AudioBackend *be)
{
if (be) {
return AUDIO_BACKEND_GET_CLASS(be)->get_id(be);
} else {
return "";
}
}
AudioBackend *audio_be_new(Audiodev *dev, Error **errp)
{
const char *drvname = AudiodevDriver_str(dev->driver);
g_autofree char *type = g_strconcat("audio-", drvname, NULL);
AudioBackend *be = AUDIO_BACKEND(object_new(type));
if (!be) {
error_setg(errp, "Unknown audio driver `%s'", drvname);
qapi_free_Audiodev(dev);
return NULL;
}
if (!AUDIO_BACKEND_GET_CLASS(be)->realize(be, dev, errp)) {
object_unref(OBJECT(be));
return NULL;
}
return be;
}
static const TypeInfo audio_types[] = {
{
.name = TYPE_AUDIO_BACKEND,
.parent = TYPE_OBJECT,
.instance_size = sizeof(AudioBackend),
.abstract = true,
.class_size = sizeof(AudioBackendClass),
},
};
DEFINE_TYPES(audio_types)
File diff suppressed because it is too large. Load diff
+2032 -171
View File
File diff suppressed because it is too large. Load diff
+107 -63
View File
@@ -33,13 +33,27 @@
#include "qemu/audio-capture.h"
#include "mixeng.h"
#ifdef CONFIG_GIO
#include <gio/gio.h>
#endif
void G_GNUC_PRINTF(2, 0)
AUD_vlog(const char *cap, const char *fmt, va_list ap);
void G_GNUC_PRINTF(2, 3)
AUD_log(const char *cap, const char *fmt, ...);
struct audio_pcm_ops;
struct audio_callback {
void *opaque;
audio_callback_fn fn;
};
struct audio_pcm_info {
AudioFormat af;
int bits;
bool is_signed;
bool is_float;
int freq;
int nchannels;
int bytes_per_frame;
@@ -47,7 +61,7 @@ struct audio_pcm_info {
int swap_endianness;
};
typedef struct AudioMixengBackend AudioMixengBackend;
typedef struct AudioBackend AudioBackend;
typedef struct SWVoiceCap SWVoiceCap;
typedef struct STSampleBuffer {
@@ -56,13 +70,14 @@ typedef struct STSampleBuffer {
} STSampleBuffer;
typedef struct HWVoiceOut {
AudioMixengBackend *s;
AudioBackend *s;
bool enabled;
int poll_mode;
bool pending_disable;
struct audio_pcm_info info;
f_sample *clip;
uint64_t ts_helper;
STSampleBuffer mix_buf;
void *buf_emul;
@@ -71,11 +86,12 @@ typedef struct HWVoiceOut {
size_t samples;
QLIST_HEAD (sw_out_listhead, SWVoiceOut) sw_head;
QLIST_HEAD (sw_cap_listhead, SWVoiceCap) cap_head;
struct audio_pcm_ops *pcm_ops;
QLIST_ENTRY (HWVoiceOut) entries;
} HWVoiceOut;
typedef struct HWVoiceIn {
AudioMixengBackend *s;
AudioBackend *s;
bool enabled;
int poll_mode;
struct audio_pcm_info info;
@@ -83,6 +99,7 @@ typedef struct HWVoiceIn {
t_sample *conv;
size_t total_samples_captured;
uint64_t ts_helper;
STSampleBuffer conv_buf;
void *buf_emul;
@@ -90,11 +107,12 @@ typedef struct HWVoiceIn {
size_t samples;
QLIST_HEAD (sw_in_listhead, SWVoiceIn) sw_head;
struct audio_pcm_ops *pcm_ops;
QLIST_ENTRY (HWVoiceIn) entries;
} HWVoiceIn;
struct SWVoiceOut {
AudioMixengBackend *s;
AudioBackend *s;
struct audio_pcm_info info;
t_sample *conv;
STSampleBuffer resample_buf;
@@ -110,7 +128,7 @@ struct SWVoiceOut {
};
struct SWVoiceIn {
AudioMixengBackend *s;
AudioBackend *s;
bool active;
struct audio_pcm_info info;
void *rate;
@@ -124,6 +142,59 @@ struct SWVoiceIn {
QLIST_ENTRY (SWVoiceIn) entries;
};
typedef struct audio_driver audio_driver;
struct audio_driver {
const char *name;
void *(*init) (Audiodev *, Error **);
void (*fini) (void *);
#ifdef CONFIG_GIO
bool (*set_dbus_server)(AudioBackend *be,
GDBusObjectManagerServer *manager,
bool p2p,
Error **errp);
#endif
struct audio_pcm_ops *pcm_ops;
int max_voices_out;
int max_voices_in;
size_t voice_size_out;
size_t voice_size_in;
QLIST_ENTRY(audio_driver) next;
};
struct audio_pcm_ops {
int (*init_out)(HWVoiceOut *hw, audsettings *as, void *drv_opaque);
void (*fini_out)(HWVoiceOut *hw);
size_t (*write) (HWVoiceOut *hw, void *buf, size_t size);
void (*run_buffer_out)(HWVoiceOut *hw);
/*
* Get the free output buffer size. This is an upper limit. The size
* returned by function get_buffer_out may be smaller.
*/
size_t (*buffer_get_free)(HWVoiceOut *hw);
/*
* get a buffer that after later can be passed to put_buffer_out; optional
* returns the buffer, and writes it's size to size (in bytes)
*/
void *(*get_buffer_out)(HWVoiceOut *hw, size_t *size);
/*
* put back the buffer returned by get_buffer_out; optional
* buf must be equal the pointer returned by get_buffer_out,
* size may be smaller
*/
size_t (*put_buffer_out)(HWVoiceOut *hw, void *buf, size_t size);
void (*enable_out)(HWVoiceOut *hw, bool enable);
void (*volume_out)(HWVoiceOut *hw, Volume *vol);
int (*init_in) (HWVoiceIn *hw, audsettings *as, void *drv_opaque);
void (*fini_in) (HWVoiceIn *hw);
size_t (*read) (HWVoiceIn *hw, void *buf, size_t size);
void (*run_buffer_in)(HWVoiceIn *hw);
void *(*get_buffer_in)(HWVoiceIn *hw, size_t *size);
void (*put_buffer_in)(HWVoiceIn *hw, void *buf, size_t size);
void (*enable_in)(HWVoiceIn *hw, bool enable);
void (*volume_in)(HWVoiceIn *hw, Volume *vol);
};
audsettings audiodev_to_audsettings(AudiodevPerDirectionOptions *pdo);
int audioformat_bytes_per_sample(AudioFormat fmt);
int audio_buffer_frames(AudiodevPerDirectionOptions *pdo,
@@ -141,11 +212,9 @@ static inline void *advance(void *p, size_t incr)
int wav_start_capture(AudioBackend *state, CaptureState *s, const char *path,
int freq, int bits, int nchannels);
void audio_generic_initialize_buffer_in(HWVoiceIn *hw);
void audio_generic_run_buffer_in(HWVoiceIn *hw);
void *audio_generic_get_buffer_in(HWVoiceIn *hw, size_t *size);
void audio_generic_put_buffer_in(HWVoiceIn *hw, void *buf, size_t size);
void audio_generic_initialize_buffer_out(HWVoiceOut *hw);
void audio_generic_run_buffer_out(HWVoiceOut *hw);
size_t audio_generic_buffer_get_free(HWVoiceOut *hw);
void *audio_generic_get_buffer_out(HWVoiceOut *hw, size_t *size);
@@ -172,74 +241,41 @@ struct SWVoiceCap {
QLIST_ENTRY (SWVoiceCap) entries;
};
struct AudioMixengBackendClass {
AudioBackendClass parent_class;
int max_voices_out;
int max_voices_in;
size_t voice_size_out;
size_t voice_size_in;
int (*init_out)(HWVoiceOut *hw, audsettings *as);
void (*fini_out)(HWVoiceOut *hw);
size_t (*write) (HWVoiceOut *hw, void *buf, size_t size);
void (*run_buffer_out)(HWVoiceOut *hw);
/*
* Get the free output buffer size. This is an upper limit. The size
* returned by function get_buffer_out may be smaller.
*/
size_t (*buffer_get_free)(HWVoiceOut *hw);
/*
* get a buffer that after later can be passed to put_buffer_out; optional
* returns the buffer, and writes it's size to size (in bytes)
*/
void *(*get_buffer_out)(HWVoiceOut *hw, size_t *size);
/*
* put back the buffer returned by get_buffer_out; optional
* buf must be equal the pointer returned by get_buffer_out,
* size may be smaller
*/
size_t (*put_buffer_out)(HWVoiceOut *hw, void *buf, size_t size);
void (*enable_out)(HWVoiceOut *hw, bool enable);
void (*volume_out)(HWVoiceOut *hw, Volume *vol);
int (*init_in) (HWVoiceIn *hw, audsettings *as);
void (*fini_in) (HWVoiceIn *hw);
size_t (*read) (HWVoiceIn *hw, void *buf, size_t size);
void (*run_buffer_in)(HWVoiceIn *hw);
void *(*get_buffer_in)(HWVoiceIn *hw, size_t *size);
void (*put_buffer_in)(HWVoiceIn *hw, void *buf, size_t size);
void (*enable_in)(HWVoiceIn *hw, bool enable);
void (*volume_in)(HWVoiceIn *hw, Volume *vol);
};
struct AudioMixengBackend {
AudioBackend parent_obj;
typedef struct AudioBackend {
Object parent;
struct audio_driver *drv;
Audiodev *dev;
void *drv_opaque;
QEMUTimer *ts;
GTimer *run_timer;
QLIST_HEAD (hw_in_listhead, HWVoiceIn) hw_head_in;
QLIST_HEAD (hw_out_listhead, HWVoiceOut) hw_head_out;
QLIST_HEAD (cap_listhead, CaptureVoiceOut) cap_head;
int nb_hw_voices_out;
int nb_hw_voices_in;
int vm_running;
int64_t period_ticks;
bool timer_running;
uint64_t timer_last;
VMChangeStateEntry *vmse;
};
} AudioBackend;
extern const struct mixeng_volume nominal_volume;
extern const char *audio_prio_list[];
void audio_pcm_init_info (struct audio_pcm_info *info, const struct audsettings *as);
void audio_driver_register(audio_driver *drv);
void audio_pcm_init_info (struct audio_pcm_info *info, struct audsettings *as);
void audio_pcm_info_clear_buf (struct audio_pcm_info *info, void *buf, int len);
void audio_run(AudioMixengBackend *s, const char *msg);
int audio_bug (const char *funcname, int cond);
void audio_run(AudioBackend *s, const char *msg);
const char *audio_application_name(void);
typedef struct RateCtl {
int64_t start_ticks;
@@ -271,15 +307,23 @@ static inline size_t audio_ring_posb(size_t pos, size_t dist, size_t len)
return pos >= dist ? pos - dist : len - dist + pos;
}
#define dolog(fmt, ...) AUD_log(AUDIO_CAP, fmt, ## __VA_ARGS__)
#ifdef DEBUG
#define ldebug(fmt, ...) AUD_log(AUDIO_CAP, fmt, ## __VA_ARGS__)
#else
#define ldebug(fmt, ...) (void)0
#endif
typedef struct AudiodevListEntry {
Audiodev *dev;
QSIMPLEQ_ENTRY(AudiodevListEntry) next;
} AudiodevListEntry;
typedef QSIMPLEQ_HEAD(, AudiodevListEntry) AudiodevListHead;
void audio_create_pdos(Audiodev *dev);
AudiodevPerDirectionOptions *audio_get_pdo_in(Audiodev *dev);
AudiodevPerDirectionOptions *audio_get_pdo_out(Audiodev *dev);
void audio_sample_to_uint64(const st_sample *sample, int pos,
uint64_t *left, uint64_t *right);
void audio_sample_from_uint64(st_sample *sample, int pos,
uint64_t left, uint64_t right);
#define TYPE_AUDIO_MIXENG_BACKEND "audio-mixeng-backend"
OBJECT_DECLARE_TYPE(AudioMixengBackend, AudioMixengBackendClass, AUDIO_MIXENG_BACKEND)
#endif /* QEMU_AUDIO_INT_H */
+127 -91
View File
@@ -36,42 +36,42 @@
#define HWBUF hw->conv_buf
#endif
static void glue(audio_init_nb_voices_, TYPE)(AudioMixengBackend *s,
AudioMixengBackendClass *k,
int min_voices)
static void glue(audio_init_nb_voices_, TYPE)(AudioBackend *s,
struct audio_driver *drv, int min_voices)
{
const char *be_name = object_class_get_name(OBJECT_CLASS(k));
int max_voices = glue(k->max_voices_, TYPE);
size_t voice_size = glue(k->voice_size_, TYPE);
int max_voices = glue (drv->max_voices_, TYPE);
size_t voice_size = glue(drv->voice_size_, TYPE);
glue(s->nb_hw_voices_, TYPE) = glue(audio_get_pdo_, TYPE)(s->dev)->voices;
if (glue(s->nb_hw_voices_, TYPE) > max_voices) {
glue (s->nb_hw_voices_, TYPE) = glue(audio_get_pdo_, TYPE)(s->dev)->voices;
if (glue (s->nb_hw_voices_, TYPE) > max_voices) {
if (!max_voices) {
#ifdef DAC
warn_report("audio: '%s' backend does not support " NAME, be_name);
dolog ("Driver `%s' does not support " NAME "\n", drv->name);
#endif
} else {
warn_report("audio: '%s' backend does not support %d " NAME " voices, max %d",
be_name, glue(s->nb_hw_voices_, TYPE), max_voices);
dolog ("Driver `%s' does not support %d " NAME " voices, max %d\n",
drv->name,
glue (s->nb_hw_voices_, TYPE),
max_voices);
}
glue(s->nb_hw_voices_, TYPE) = max_voices;
glue (s->nb_hw_voices_, TYPE) = max_voices;
}
if (glue(s->nb_hw_voices_, TYPE) < min_voices) {
warn_report("audio: Bogus number of " NAME " voices %d, setting to %d",
glue(s->nb_hw_voices_, TYPE),
min_voices);
if (glue (s->nb_hw_voices_, TYPE) < min_voices) {
dolog ("Bogus number of " NAME " voices %d, setting to %d\n",
glue (s->nb_hw_voices_, TYPE),
min_voices);
}
if (!voice_size && max_voices) {
audio_bug("backend=`%s' voice_size=0 max_voices=%d",
be_name, max_voices);
glue(s->nb_hw_voices_, TYPE) = 0;
if (audio_bug(__func__, !voice_size && max_voices)) {
dolog ("drv=`%s' voice_size=0 max_voices=%d\n",
drv->name, max_voices);
glue (s->nb_hw_voices_, TYPE) = 0;
}
if (voice_size && !max_voices) {
audio_bug("backend=`%s' voice_size=%zu max_voices=0",
be_name, voice_size);
if (audio_bug(__func__, voice_size && !max_voices)) {
dolog("drv=`%s' voice_size=%zu max_voices=0\n",
drv->name, voice_size);
}
}
@@ -87,8 +87,8 @@ static void glue(audio_pcm_hw_alloc_resources_, TYPE)(HW *hw)
{
if (glue(audio_get_pdo_, TYPE)(hw->s->dev)->mixing_engine) {
size_t samples = hw->samples;
if (samples == 0) {
audio_bug("Attempted to allocate empty buffer");
if (audio_bug(__func__, samples == 0)) {
dolog("Attempted to allocate empty buffer\n");
}
HWBUF.buffer = g_new0(st_sample, samples);
@@ -129,7 +129,7 @@ static int glue (audio_pcm_sw_alloc_resources_, TYPE) (SW *sw)
/* f_fe_min = ceil(1 [frames] * f_be [Hz] / size_be [frames]) */
f_fe_min = (f_be + HWBUF.size - 1) / HWBUF.size;
qemu_log_mask(LOG_UNIMP,
"audio: The guest selected a " NAME " sample rate"
AUDIO_CAP ": The guest selected a " NAME " sample rate"
" of %d Hz for %s. Only sample rates >= %" PRIu64 " Hz"
" are supported.\n",
sw->info.freq, sw->name, f_fe_min);
@@ -159,7 +159,7 @@ static int glue (audio_pcm_sw_init_, TYPE) (
SW *sw,
HW *hw,
const char *name,
const struct audsettings *as
struct audsettings *as
)
{
int err;
@@ -172,7 +172,7 @@ static int glue (audio_pcm_sw_init_, TYPE) (
sw->empty = true;
#endif
if (audio_format_is_float(sw->info.af)) {
if (sw->info.is_float) {
#ifdef DAC
sw->conv = mixeng_conv_float[sw->info.nchannels == 2]
[sw->info.swap_endianness];
@@ -187,9 +187,9 @@ static int glue (audio_pcm_sw_init_, TYPE) (
sw->clip = mixeng_clip
#endif
[sw->info.nchannels == 2]
[audio_format_is_signed(sw->info.af)]
[sw->info.is_signed]
[sw->info.swap_endianness]
[audio_format_to_index(sw->info.af)];
[audio_bits_to_index(sw->info.bits)];
}
sw->name = g_strdup (name);
@@ -221,29 +221,27 @@ static void glue (audio_pcm_hw_del_sw_, TYPE) (SW *sw)
static void glue (audio_pcm_hw_gc_, TYPE) (HW **hwp)
{
HW *hw = *hwp;
AudioMixengBackend *s = hw->s;
AudioMixengBackendClass *k = AUDIO_MIXENG_BACKEND_GET_CLASS(s);
AudioBackend *s = hw->s;
if (!hw->sw_head.lh_first) {
#ifdef DAC
audio_detach_capture(hw);
#endif
QLIST_REMOVE(hw, entries);
glue(k->fini_, TYPE)(hw);
glue(hw->pcm_ops->fini_, TYPE) (hw);
glue(s->nb_hw_voices_, TYPE) += 1;
glue(audio_pcm_hw_free_resources_ , TYPE) (hw);
object_unref(hw->s);
g_free(hw);
*hwp = NULL;
}
}
static HW *glue(audio_pcm_hw_find_any_, TYPE)(AudioMixengBackend *s, HW *hw)
static HW *glue(audio_pcm_hw_find_any_, TYPE)(AudioBackend *s, HW *hw)
{
return hw ? hw->entries.le_next : glue (s->hw_head_, TYPE).lh_first;
}
static HW *glue(audio_pcm_hw_find_any_enabled_, TYPE)(AudioMixengBackend *s, HW *hw)
static HW *glue(audio_pcm_hw_find_any_enabled_, TYPE)(AudioBackend *s, HW *hw)
{
while ((hw = glue(audio_pcm_hw_find_any_, TYPE)(s, hw))) {
if (hw->enabled) {
@@ -253,7 +251,7 @@ static HW *glue(audio_pcm_hw_find_any_enabled_, TYPE)(AudioMixengBackend *s, HW
return NULL;
}
static HW *glue(audio_pcm_hw_find_specific_, TYPE)(AudioMixengBackend *s, HW *hw,
static HW *glue(audio_pcm_hw_find_specific_, TYPE)(AudioBackend *s, HW *hw,
struct audsettings *as)
{
while ((hw = glue(audio_pcm_hw_find_any_, TYPE)(s, hw))) {
@@ -264,42 +262,48 @@ static HW *glue(audio_pcm_hw_find_specific_, TYPE)(AudioMixengBackend *s, HW *hw
return NULL;
}
static HW *glue(audio_pcm_hw_add_new_, TYPE)(AudioMixengBackend *s,
static HW *glue(audio_pcm_hw_add_new_, TYPE)(AudioBackend *s,
struct audsettings *as)
{
HW *hw;
AudioMixengBackendClass *k = AUDIO_MIXENG_BACKEND_GET_CLASS(s);
struct audio_driver *drv = s->drv;
if (!glue(s->nb_hw_voices_, TYPE)) {
if (!glue (s->nb_hw_voices_, TYPE)) {
return NULL;
}
if (!glue(k->init_, TYPE)) {
audio_bug("No host audio driver or missing init_%s", NAME);
if (audio_bug(__func__, !drv)) {
dolog ("No host audio driver\n");
return NULL;
}
if (audio_bug(__func__, !drv->pcm_ops)) {
dolog ("Host audio driver without pcm_ops\n");
return NULL;
}
/*
* Since glue(s->nb_hw_voices_, TYPE) is != 0, glue(k->voice_size_, TYPE)
* Since glue(s->nb_hw_voices_, TYPE) is != 0, glue(drv->voice_size_, TYPE)
* is guaranteed to be != 0. See the audio_init_nb_voices_* functions.
*/
hw = g_malloc0(glue(k->voice_size_, TYPE));
hw->s = AUDIO_MIXENG_BACKEND(object_ref(s));
hw = g_malloc0(glue(drv->voice_size_, TYPE));
hw->s = s;
hw->pcm_ops = drv->pcm_ops;
QLIST_INIT (&hw->sw_head);
#ifdef DAC
QLIST_INIT (&hw->cap_head);
#endif
if (glue(k->init_, TYPE)(hw, as)) {
if (glue (hw->pcm_ops->init_, TYPE) (hw, as, s->drv_opaque)) {
goto err0;
}
if (hw->samples <= 0) {
audio_bug("hw->samples=%zd", hw->samples);
if (audio_bug(__func__, hw->samples <= 0)) {
dolog("hw->samples=%zd\n", hw->samples);
goto err1;
}
if (audio_format_is_float(hw->info.af)) {
if (hw->info.is_float) {
#ifdef DAC
hw->clip = mixeng_clip_float[hw->info.nchannels == 2]
[hw->info.swap_endianness];
@@ -314,9 +318,9 @@ static HW *glue(audio_pcm_hw_add_new_, TYPE)(AudioMixengBackend *s,
hw->conv = mixeng_conv
#endif
[hw->info.nchannels == 2]
[audio_format_is_signed(hw->info.af)]
[hw->info.is_signed]
[hw->info.swap_endianness]
[audio_format_to_index(hw->info.af)];
[audio_bits_to_index(hw->info.bits)];
}
glue(audio_pcm_hw_alloc_resources_, TYPE)(hw);
@@ -329,9 +333,8 @@ static HW *glue(audio_pcm_hw_add_new_, TYPE)(AudioMixengBackend *s,
return hw;
err1:
glue(k->fini_, TYPE)(hw);
glue (hw->pcm_ops->fini_, TYPE) (hw);
err0:
object_unref(hw->s);
g_free (hw);
return NULL;
}
@@ -395,7 +398,7 @@ AudiodevPerDirectionOptions *glue(audio_get_pdo_, TYPE)(Audiodev *dev)
abort();
}
static HW *glue(audio_pcm_hw_add_, TYPE)(AudioMixengBackend *s, struct audsettings *as)
static HW *glue(audio_pcm_hw_add_, TYPE)(AudioBackend *s, struct audsettings *as)
{
HW *hw;
AudiodevPerDirectionOptions *pdo = glue(audio_get_pdo_, TYPE)(s->dev);
@@ -421,9 +424,9 @@ static HW *glue(audio_pcm_hw_add_, TYPE)(AudioMixengBackend *s, struct audsettin
}
static SW *glue(audio_pcm_create_voice_pair_, TYPE)(
AudioMixengBackend *s,
AudioBackend *s,
const char *sw_name,
const struct audsettings *as
struct audsettings *as
)
{
SW *sw;
@@ -438,11 +441,11 @@ static SW *glue(audio_pcm_create_voice_pair_, TYPE)(
}
sw = g_new0(SW, 1);
sw->s = AUDIO_MIXENG_BACKEND(object_ref(s));
sw->s = s;
hw = glue(audio_pcm_hw_add_, TYPE)(s, &hw_as);
if (!hw) {
error_report("audio: Could not create a backend for voice '%s'", sw_name);
dolog("Could not create a backend for voice `%s'\n", sw_name);
goto err1;
}
@@ -458,7 +461,6 @@ err2:
glue (audio_pcm_hw_del_sw_, TYPE) (sw);
glue (audio_pcm_hw_gc_, TYPE) (&hw);
err1:
object_unref(sw->s);
g_free(sw);
return NULL;
}
@@ -468,16 +470,14 @@ static void glue (audio_close_, TYPE) (SW *sw)
glue (audio_pcm_sw_fini_, TYPE) (sw);
glue (audio_pcm_hw_del_sw_, TYPE) (sw);
glue (audio_pcm_hw_gc_, TYPE) (&sw->hw);
object_unref(sw->s);
g_free (sw);
}
static void glue(audio_mixeng_backend_close_, TYPE)(AudioBackend *be, SW *sw)
void glue(AUD_close_, TYPE)(AudioBackend *be, SW *sw)
{
if (sw) {
if (!be) {
audio_bug("backend=%p", be);
if (audio_bug(__func__, !be)) {
dolog("backend=%p\n", be);
return;
}
@@ -485,35 +485,36 @@ static void glue(audio_mixeng_backend_close_, TYPE)(AudioBackend *be, SW *sw)
}
}
static SW *glue(audio_mixeng_backend_open_, TYPE) (
SW *glue (AUD_open_, TYPE) (
AudioBackend *be,
SW *sw,
const char *name,
void *callback_opaque ,
audio_callback_fn callback_fn,
const struct audsettings *as)
struct audsettings *as
)
{
AudioMixengBackend *s = AUDIO_MIXENG_BACKEND(be);
AudioMixengBackendClass *k;
AudioBackend *s = be;
AudiodevPerDirectionOptions *pdo;
k = AUDIO_MIXENG_BACKEND_GET_CLASS(s);
pdo = glue(audio_get_pdo_, TYPE)(s->dev);
#ifdef DAC
trace_audio_open_out(name, as->freq, as->nchannels, as->fmt);
#else
trace_audio_open_in(name, as->freq, as->nchannels, as->fmt);
#endif
if (audio_validate_settings(as)) {
g_autofree char *str = audsettings_to_string(as);
error_report("audio: Invalid audio settings: %s", str);
if (audio_bug(__func__, !be || !name || !callback_fn || !as)) {
dolog("backend=%p name=%p callback_fn=%p as=%p\n",
be, name, callback_fn, as);
goto fail;
}
if (!glue(k->init_, TYPE)) {
error_report("audio: Can not open `%s' (no host audio driver)", name);
pdo = glue(audio_get_pdo_, TYPE)(s->dev);
ldebug ("open %s, freq %d, nchannels %d, fmt %d\n",
name, as->freq, as->nchannels, as->fmt);
if (audio_bug(__func__, audio_validate_settings(as))) {
audio_print_settings (as);
goto fail;
}
if (audio_bug(__func__, !s->drv)) {
dolog ("Can not open `%s' (no host audio driver)\n", name);
goto fail;
}
@@ -522,7 +523,7 @@ static SW *glue(audio_mixeng_backend_open_, TYPE) (
}
if (!pdo->fixed_settings && sw) {
glue(audio_be_close_, TYPE)(be, sw);
glue(AUD_close_, TYPE)(be, sw);
sw = NULL;
}
@@ -530,7 +531,8 @@ static SW *glue(audio_mixeng_backend_open_, TYPE) (
HW *hw = sw->hw;
if (!hw) {
audio_bug("Internal logic error: voice '%s' has no backend", SW_NAME(sw));
dolog("Internal logic error: voice `%s' has no backend\n",
SW_NAME(sw));
goto fail;
}
@@ -549,24 +551,58 @@ static SW *glue(audio_mixeng_backend_open_, TYPE) (
sw->callback.fn = callback_fn;
sw->callback.opaque = callback_opaque;
trace_audio_voice_pair(G_STRINGIFY(TYPE), name,
AudioFormat_str(sw->hw->info.af),
sw->hw->info.freq, sw->hw->info.nchannels,
AudioFormat_str(sw->info.af),
sw->info.freq, sw->info.nchannels);
#ifdef DEBUG_AUDIO
dolog ("%s\n", name);
audio_pcm_print_info ("hw", &sw->hw->info);
audio_pcm_print_info ("sw", &sw->info);
#endif
return sw;
fail:
glue(audio_be_close_, TYPE)(be, sw);
glue(AUD_close_, TYPE)(be, sw);
return NULL;
}
static bool glue(audio_mixeng_backend_is_active_, TYPE)(AudioBackend *be, SW *sw)
bool glue(AUD_is_active_, TYPE)(SW *sw)
{
return sw ? sw->active : 0;
}
void glue (AUD_init_time_stamp_, TYPE) (SW *sw, QEMUAudioTimeStamp *ts)
{
if (!sw) {
return;
}
ts->old_ts = sw->hw->ts_helper;
}
uint64_t glue (AUD_get_elapsed_usec_, TYPE) (SW *sw, QEMUAudioTimeStamp *ts)
{
uint64_t delta, cur_ts, old_ts;
if (!sw) {
return 0;
}
cur_ts = sw->hw->ts_helper;
old_ts = ts->old_ts;
/* dolog ("cur %" PRId64 " old %" PRId64 "\n", cur_ts, old_ts); */
if (cur_ts >= old_ts) {
delta = cur_ts - old_ts;
} else {
delta = UINT64_MAX - old_ts + cur_ts;
}
if (!delta) {
return 0;
}
return muldiv64 (delta, sw->hw->info.freq, 1000000);
}
#undef TYPE
#undef HW
#undef SW
+16 -15
View File
@@ -2,12 +2,12 @@
#include "qemu/osdep.h"
#define AUDIO_CAP "win-int"
#include <windows.h>
#include <mmreg.h>
#include <mmsystem.h>
#include "qemu/audio.h"
#include "qemu/error-report.h"
#include "audio_int.h"
#include "audio_win_int.h"
@@ -53,7 +53,7 @@ int waveformat_from_audio_settings (WAVEFORMATEX *wfx,
break;
default:
error_report("dsound: Internal logic error: Bad audio format %d", as->fmt);
dolog("Internal logic error: Bad audio format %d\n", as->fmt);
return -1;
}
@@ -64,7 +64,7 @@ int waveformat_to_audio_settings (WAVEFORMATEX *wfx,
struct audsettings *as)
{
if (!wfx->nSamplesPerSec) {
error_report("dsound: Invalid wave format, frequency is zero");
dolog ("Invalid wave format, frequency is zero\n");
return -1;
}
as->freq = wfx->nSamplesPerSec;
@@ -79,9 +79,10 @@ int waveformat_to_audio_settings (WAVEFORMATEX *wfx,
break;
default:
error_report("dsound: Invalid wave format, "
"number of channels is not 1 or 2, but %d",
wfx->nChannels);
dolog (
"Invalid wave format, number of channels is not 1 or 2, but %d\n",
wfx->nChannels
);
return -1;
}
@@ -100,9 +101,9 @@ int waveformat_to_audio_settings (WAVEFORMATEX *wfx,
break;
default:
error_report("dsound: Invalid PCM wave format, bits per sample is not "
"8, 16 or 32, but %d",
wfx->wBitsPerSample);
dolog("Invalid PCM wave format, bits per sample is not "
"8, 16 or 32, but %d\n",
wfx->wBitsPerSample);
return -1;
}
} else if (wfx->wFormatTag == WAVE_FORMAT_IEEE_FLOAT) {
@@ -112,15 +113,15 @@ int waveformat_to_audio_settings (WAVEFORMATEX *wfx,
break;
default:
error_report("dsound: Invalid IEEE_FLOAT wave format, "
"bits per sample is not 32, but %d",
wfx->wBitsPerSample);
dolog("Invalid IEEE_FLOAT wave format, bits per sample is not "
"32, but %d\n",
wfx->wBitsPerSample);
return -1;
}
} else {
error_report("dsound: Invalid wave format, "
"tag is not PCM and not IEEE_FLOAT, but %d",
wfx->wFormatTag);
dolog("Invalid wave format, tag is not PCM and not IEEE_FLOAT, "
"but %d\n",
wfx->wFormatTag);
return -1;
}
+194 -199
View File
@@ -28,49 +28,42 @@
#include "qemu/main-loop.h"
#include "qemu/module.h"
#include "qemu/error-report.h"
#include "qemu/audio.h"
#include "qom/object.h"
#define AUDIO_CAP "coreaudio"
#include "audio_int.h"
#define TYPE_AUDIO_COREAUDIO "audio-coreaudio"
OBJECT_DECLARE_SIMPLE_TYPE(AudioCoreaudio, AUDIO_COREAUDIO)
struct AudioCoreaudio {
AudioMixengBackend parent_obj;
};
typedef struct coreaudioVoiceOut {
HWVoiceOut hw;
pthread_mutex_t buf_mutex;
AudioDeviceID device_id;
int frame_size_setting;
uint32_t buffer_count;
UInt32 device_frame_size;
AudioDeviceID outputDeviceID;
int frameSizeSetting;
uint32_t bufferCount;
UInt32 audioDevicePropertyBufferFrameSize;
AudioDeviceIOProcID ioprocid;
bool enabled;
} CoreaudioVoiceOut;
} coreaudioVoiceOut;
static const AudioObjectPropertyAddress voice_out_addr = {
static const AudioObjectPropertyAddress voice_addr = {
kAudioHardwarePropertyDefaultOutputDevice,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMain
};
static OSStatus coreaudio_get_voice_out(AudioDeviceID *id)
static OSStatus coreaudio_get_voice(AudioDeviceID *id)
{
UInt32 size = sizeof(*id);
return AudioObjectGetPropertyData(kAudioObjectSystemObject,
&voice_out_addr,
&voice_addr,
0,
NULL,
&size,
id);
}
static OSStatus coreaudio_get_out_framesizerange(AudioDeviceID id,
AudioValueRange *framerange)
static OSStatus coreaudio_get_framesizerange(AudioDeviceID id,
AudioValueRange *framerange)
{
UInt32 size = sizeof(*framerange);
AudioObjectPropertyAddress addr = {
@@ -87,7 +80,7 @@ static OSStatus coreaudio_get_out_framesizerange(AudioDeviceID id,
framerange);
}
static OSStatus coreaudio_get_out_framesize(AudioDeviceID id, UInt32 *framesize)
static OSStatus coreaudio_get_framesize(AudioDeviceID id, UInt32 *framesize)
{
UInt32 size = sizeof(*framesize);
AudioObjectPropertyAddress addr = {
@@ -104,7 +97,7 @@ static OSStatus coreaudio_get_out_framesize(AudioDeviceID id, UInt32 *framesize)
framesize);
}
static OSStatus coreaudio_set_out_framesize(AudioDeviceID id, UInt32 *framesize)
static OSStatus coreaudio_set_framesize(AudioDeviceID id, UInt32 *framesize)
{
UInt32 size = sizeof(*framesize);
AudioObjectPropertyAddress addr = {
@@ -121,8 +114,8 @@ static OSStatus coreaudio_set_out_framesize(AudioDeviceID id, UInt32 *framesize)
framesize);
}
static OSStatus coreaudio_set_out_streamformat(AudioDeviceID id,
AudioStreamBasicDescription *d)
static OSStatus coreaudio_set_streamformat(AudioDeviceID id,
AudioStreamBasicDescription *d)
{
UInt32 size = sizeof(*d);
AudioObjectPropertyAddress addr = {
@@ -139,7 +132,7 @@ static OSStatus coreaudio_set_out_streamformat(AudioDeviceID id,
d);
}
static OSStatus coreaudio_get_out_isrunning(AudioDeviceID id, UInt32 *result)
static OSStatus coreaudio_get_isrunning(AudioDeviceID id, UInt32 *result)
{
UInt32 size = sizeof(*result);
AudioObjectPropertyAddress addr = {
@@ -156,7 +149,7 @@ static OSStatus coreaudio_get_out_isrunning(AudioDeviceID id, UInt32 *result)
result);
}
static void coreaudio_logstatus(OSStatus status)
static void coreaudio_logstatus (OSStatus status)
{
const char *str = "BUG";
@@ -206,85 +199,89 @@ static void coreaudio_logstatus(OSStatus status)
break;
default:
error_printf(" Reason: status code %" PRId32, (int32_t)status);
AUD_log (AUDIO_CAP, "Reason: status code %" PRId32 "\n", (int32_t)status);
return;
}
error_printf(" Reason: %s", str);
AUD_log (AUDIO_CAP, "Reason: %s\n", str);
}
static void G_GNUC_PRINTF(2, 3) coreaudio_logerr(OSStatus status,
const char *fmt, ...)
static void G_GNUC_PRINTF (2, 3) coreaudio_logerr (
OSStatus status,
const char *fmt,
...
)
{
va_list ap;
error_printf("coreaudio: ");
va_start(ap, fmt);
error_vprintf(fmt, ap);
va_end(ap);
coreaudio_logstatus(status);
error_printf("\n");
va_start (ap, fmt);
AUD_log (AUDIO_CAP, fmt, ap);
va_end (ap);
coreaudio_logstatus (status);
}
static void G_GNUC_PRINTF(3, 4) coreaudio_logerr2(OSStatus status,
const char *typ,
const char *fmt, ...)
static void G_GNUC_PRINTF (3, 4) coreaudio_logerr2 (
OSStatus status,
const char *typ,
const char *fmt,
...
)
{
va_list ap;
error_printf("coreaudio: Could not initialize %s: ", typ);
va_start(ap, fmt);
error_vprintf(fmt, ap);
va_end(ap);
coreaudio_logstatus(status);
error_printf("\n");
AUD_log (AUDIO_CAP, "Could not initialize %s\n", typ);
va_start (ap, fmt);
AUD_vlog (AUDIO_CAP, fmt, ap);
va_end (ap);
coreaudio_logstatus (status);
}
#define coreaudio_playback_logerr(status, ...) \
coreaudio_logerr2(status, "playback", __VA_ARGS__)
static int coreaudio_voice_out_buf_lock(CoreaudioVoiceOut *core,
const char *fn_name)
static int coreaudio_buf_lock (coreaudioVoiceOut *core, const char *fn_name)
{
int err;
err = pthread_mutex_lock(&core->buf_mutex);
err = pthread_mutex_lock (&core->buf_mutex);
if (err) {
error_report("coreaudio: Could not lock voice for %s: %s",
fn_name, strerror(err));
dolog ("Could not lock voice for %s\nReason: %s\n",
fn_name, strerror (err));
return -1;
}
return 0;
}
static int coreaudio_voice_out_buf_unlock(CoreaudioVoiceOut *core,
const char *fn_name)
static int coreaudio_buf_unlock (coreaudioVoiceOut *core, const char *fn_name)
{
int err;
err = pthread_mutex_unlock(&core->buf_mutex);
err = pthread_mutex_unlock (&core->buf_mutex);
if (err) {
error_report("coreaudio: Could not unlock voice for %s: %s",
fn_name, strerror(err));
dolog ("Could not unlock voice for %s\nReason: %s\n",
fn_name, strerror (err));
return -1;
}
return 0;
}
#define COREAUDIO_WRAPPER_FUNC(name, ret_type, args_decl, args) \
static ret_type glue(coreaudio_, name)args_decl \
{ \
CoreaudioVoiceOut *core = (CoreaudioVoiceOut *)hw; \
ret_type ret; \
\
if (coreaudio_voice_out_buf_lock(core, "coreaudio_" #name)) { \
return 0; \
} \
\
ret = glue(audio_generic_, name)args; \
\
coreaudio_voice_out_buf_unlock(core, "coreaudio_" #name); \
return ret; \
#define COREAUDIO_WRAPPER_FUNC(name, ret_type, args_decl, args) \
static ret_type glue(coreaudio_, name)args_decl \
{ \
coreaudioVoiceOut *core = (coreaudioVoiceOut *) hw; \
ret_type ret; \
\
if (coreaudio_buf_lock(core, "coreaudio_" #name)) { \
return 0; \
} \
\
ret = glue(audio_generic_, name)args; \
\
coreaudio_buf_unlock(core, "coreaudio_" #name); \
return ret; \
}
COREAUDIO_WRAPPER_FUNC(buffer_get_free, size_t, (HWVoiceOut *hw), (hw))
COREAUDIO_WRAPPER_FUNC(get_buffer_out, void *, (HWVoiceOut *hw, size_t *size),
@@ -300,7 +297,7 @@ COREAUDIO_WRAPPER_FUNC(write, size_t, (HWVoiceOut *hw, void *buf, size_t size),
* callback to feed audiooutput buffer. called without BQL.
* allowed to lock "buf_mutex", but disallowed to have any other locks.
*/
static OSStatus out_device_ioproc(
static OSStatus audioDeviceIOProc(
AudioDeviceID inDevice,
const AudioTimeStamp *inNow,
const AudioBufferList *inInputData,
@@ -309,33 +306,33 @@ static OSStatus out_device_ioproc(
const AudioTimeStamp *inOutputTime,
void *hwptr)
{
UInt32 frame_size, pending_frames;
UInt32 frameCount, pending_frames;
void *out = outOutputData->mBuffers[0].mData;
HWVoiceOut *hw = hwptr;
CoreaudioVoiceOut *core = hwptr;
coreaudioVoiceOut *core = (coreaudioVoiceOut *) hwptr;
size_t len;
if (coreaudio_voice_out_buf_lock(core, "out_device_ioproc")) {
if (coreaudio_buf_lock (core, "audioDeviceIOProc")) {
inInputTime = 0;
return 0;
}
if (inDevice != core->device_id) {
coreaudio_voice_out_buf_unlock(core, "out_device_ioproc(old device)");
if (inDevice != core->outputDeviceID) {
coreaudio_buf_unlock (core, "audioDeviceIOProc(old device)");
return 0;
}
frame_size = core->device_frame_size;
frameCount = core->audioDevicePropertyBufferFrameSize;
pending_frames = hw->pending_emul / hw->info.bytes_per_frame;
/* if there are not enough samples, set signal and return */
if (pending_frames < frame_size) {
if (pending_frames < frameCount) {
inInputTime = 0;
coreaudio_voice_out_buf_unlock(core, "out_device_ioproc(empty)");
coreaudio_buf_unlock (core, "audioDeviceIOProc(empty)");
return 0;
}
len = frame_size * hw->info.bytes_per_frame;
len = frameCount * hw->info.bytes_per_frame;
while (len) {
size_t write_len, start;
@@ -351,20 +348,17 @@ static OSStatus out_device_ioproc(
out += write_len;
}
coreaudio_voice_out_buf_unlock(core, "out_device_ioproc");
coreaudio_buf_unlock (core, "audioDeviceIOProc");
return 0;
}
static OSStatus init_out_device(CoreaudioVoiceOut *core)
static OSStatus init_out_device(coreaudioVoiceOut *core)
{
AudioDeviceID device_id;
AudioDeviceIOProcID ioprocid;
AudioValueRange value_range;
OSStatus status;
UInt32 device_frame_size;
AudioValueRange frameRange;
AudioStreamBasicDescription stream_basic_description = {
.mBitsPerChannel = audio_format_bits(core->hw.info.af),
AudioStreamBasicDescription streamBasicDescription = {
.mBitsPerChannel = core->hw.info.bits,
.mBytesPerFrame = core->hw.info.bytes_per_frame,
.mBytesPerPacket = core->hw.info.bytes_per_frame,
.mChannelsPerFrame = core->hw.info.nchannels,
@@ -374,74 +368,76 @@ static OSStatus init_out_device(CoreaudioVoiceOut *core)
.mSampleRate = core->hw.info.freq
};
status = coreaudio_get_voice_out(&device_id);
status = coreaudio_get_voice(&core->outputDeviceID);
if (status != kAudioHardwareNoError) {
coreaudio_playback_logerr(status,
"Could not get default output device");
coreaudio_playback_logerr (status,
"Could not get default output Device\n");
return status;
}
if (device_id == kAudioDeviceUnknown) {
error_report("coreaudio: Could not initialize playback: "
"Unknown audio device");
if (core->outputDeviceID == kAudioDeviceUnknown) {
dolog ("Could not initialize playback - Unknown Audiodevice\n");
return status;
}
/* get minimum and maximum buffer frame sizes */
status = coreaudio_get_out_framesizerange(device_id, &value_range);
status = coreaudio_get_framesizerange(core->outputDeviceID,
&frameRange);
if (status == kAudioHardwareBadObjectError) {
return 0;
}
if (status != kAudioHardwareNoError) {
coreaudio_playback_logerr(status,
"Could not get device buffer frame range");
coreaudio_playback_logerr (status,
"Could not get device buffer frame range\n");
return status;
}
if (value_range.mMinimum > core->frame_size_setting) {
device_frame_size = value_range.mMinimum;
warn_report("coreaudio: Upsizing buffer frames to %f",
value_range.mMinimum);
} else if (value_range.mMaximum < core->frame_size_setting) {
device_frame_size = value_range.mMaximum;
warn_report("coreaudio: Downsizing buffer frames to %f",
value_range.mMaximum);
if (frameRange.mMinimum > core->frameSizeSetting) {
core->audioDevicePropertyBufferFrameSize = (UInt32) frameRange.mMinimum;
dolog ("warning: Upsizing Buffer Frames to %f\n", frameRange.mMinimum);
} else if (frameRange.mMaximum < core->frameSizeSetting) {
core->audioDevicePropertyBufferFrameSize = (UInt32) frameRange.mMaximum;
dolog ("warning: Downsizing Buffer Frames to %f\n", frameRange.mMaximum);
} else {
device_frame_size = core->frame_size_setting;
core->audioDevicePropertyBufferFrameSize = core->frameSizeSetting;
}
/* set Buffer Frame Size */
status = coreaudio_set_out_framesize(device_id, &device_frame_size);
status = coreaudio_set_framesize(core->outputDeviceID,
&core->audioDevicePropertyBufferFrameSize);
if (status == kAudioHardwareBadObjectError) {
return 0;
}
if (status != kAudioHardwareNoError) {
coreaudio_playback_logerr(status,
"Could not set device buffer frame size %" PRIu32,
(uint32_t)device_frame_size);
coreaudio_playback_logerr (status,
"Could not set device buffer frame size %" PRIu32 "\n",
(uint32_t)core->audioDevicePropertyBufferFrameSize);
return status;
}
/* get Buffer Frame Size */
status = coreaudio_get_out_framesize(device_id, &device_frame_size);
status = coreaudio_get_framesize(core->outputDeviceID,
&core->audioDevicePropertyBufferFrameSize);
if (status == kAudioHardwareBadObjectError) {
return 0;
}
if (status != kAudioHardwareNoError) {
coreaudio_playback_logerr(status,
"Could not get device buffer frame size");
coreaudio_playback_logerr (status,
"Could not get device buffer frame size\n");
return status;
}
core->hw.samples = core->bufferCount * core->audioDevicePropertyBufferFrameSize;
/* set Samplerate */
status = coreaudio_set_out_streamformat(device_id,
&stream_basic_description);
status = coreaudio_set_streamformat(core->outputDeviceID,
&streamBasicDescription);
if (status == kAudioHardwareBadObjectError) {
return 0;
}
if (status != kAudioHardwareNoError) {
coreaudio_playback_logerr(status,
"Could not set samplerate %lf",
stream_basic_description.mSampleRate);
coreaudio_playback_logerr (status,
"Could not set samplerate %lf\n",
streamBasicDescription.mSampleRate);
core->outputDeviceID = kAudioDeviceUnknown;
return status;
}
@@ -455,68 +451,63 @@ static OSStatus init_out_device(CoreaudioVoiceOut *core)
* Therefore, the specified callback must be designed to avoid a deadlock
* with the callers of AudioObjectGetPropertyData.
*/
ioprocid = NULL;
status = AudioDeviceCreateIOProcID(device_id,
out_device_ioproc,
core->ioprocid = NULL;
status = AudioDeviceCreateIOProcID(core->outputDeviceID,
audioDeviceIOProc,
&core->hw,
&ioprocid);
&core->ioprocid);
if (status == kAudioHardwareBadDeviceError) {
return 0;
}
if (status != kAudioHardwareNoError || ioprocid == NULL) {
coreaudio_playback_logerr(status, "Could not set IOProc");
if (status != kAudioHardwareNoError || core->ioprocid == NULL) {
coreaudio_playback_logerr (status, "Could not set IOProc\n");
core->outputDeviceID = kAudioDeviceUnknown;
return status;
}
core->device_id = device_id;
core->device_frame_size = device_frame_size;
core->hw.samples = core->buffer_count * core->device_frame_size;
audio_generic_initialize_buffer_out(&core->hw);
core->ioprocid = ioprocid;
return 0;
}
static void fini_out_device(CoreaudioVoiceOut *core)
static void fini_out_device(coreaudioVoiceOut *core)
{
OSStatus status;
UInt32 isrunning;
/* stop playback */
status = coreaudio_get_out_isrunning(core->device_id, &isrunning);
status = coreaudio_get_isrunning(core->outputDeviceID, &isrunning);
if (status != kAudioHardwareBadObjectError) {
if (status != kAudioHardwareNoError) {
coreaudio_logerr(status,
"Could not determine whether device is playing");
"Could not determine whether Device is playing\n");
}
if (isrunning) {
status = AudioDeviceStop(core->device_id, core->ioprocid);
status = AudioDeviceStop(core->outputDeviceID, core->ioprocid);
if (status != kAudioHardwareBadDeviceError && status != kAudioHardwareNoError) {
coreaudio_logerr(status, "Could not stop playback");
coreaudio_logerr(status, "Could not stop playback\n");
}
}
}
/* remove callback */
status = AudioDeviceDestroyIOProcID(core->device_id,
status = AudioDeviceDestroyIOProcID(core->outputDeviceID,
core->ioprocid);
if (status != kAudioHardwareBadDeviceError && status != kAudioHardwareNoError) {
coreaudio_logerr(status, "Could not remove IOProc");
coreaudio_logerr(status, "Could not remove IOProc\n");
}
core->device_id = kAudioDeviceUnknown;
core->outputDeviceID = kAudioDeviceUnknown;
}
static void update_out_device_playback_state(CoreaudioVoiceOut *core)
static void update_device_playback_state(coreaudioVoiceOut *core)
{
OSStatus status;
UInt32 isrunning;
status = coreaudio_get_out_isrunning(core->device_id, &isrunning);
status = coreaudio_get_isrunning(core->outputDeviceID, &isrunning);
if (status != kAudioHardwareNoError) {
if (status != kAudioHardwareBadObjectError) {
coreaudio_logerr(status,
"Could not determine whether device is playing");
"Could not determine whether Device is playing\n");
}
return;
@@ -525,92 +516,90 @@ static void update_out_device_playback_state(CoreaudioVoiceOut *core)
if (core->enabled) {
/* start playback */
if (!isrunning) {
status = AudioDeviceStart(core->device_id, core->ioprocid);
status = AudioDeviceStart(core->outputDeviceID, core->ioprocid);
if (status != kAudioHardwareBadDeviceError && status != kAudioHardwareNoError) {
coreaudio_logerr(status, "Could not resume playback");
coreaudio_logerr (status, "Could not resume playback\n");
}
}
} else {
/* stop playback */
if (isrunning) {
status = AudioDeviceStop(core->device_id,
status = AudioDeviceStop(core->outputDeviceID,
core->ioprocid);
if (status != kAudioHardwareBadDeviceError && status != kAudioHardwareNoError) {
coreaudio_logerr(status, "Could not pause playback");
coreaudio_logerr(status, "Could not pause playback\n");
}
}
}
}
/* called without BQL. */
static OSStatus handle_voice_out_change(
static OSStatus handle_voice_change(
AudioObjectID in_object_id,
UInt32 in_number_addresses,
const AudioObjectPropertyAddress *in_addresses,
void *in_client_data)
{
CoreaudioVoiceOut *core = in_client_data;
coreaudioVoiceOut *core = in_client_data;
bql_lock();
if (core->device_id) {
if (core->outputDeviceID) {
fini_out_device(core);
}
init_out_device(core);
if (core->device_id) {
update_out_device_playback_state(core);
if (!init_out_device(core)) {
update_device_playback_state(core);
}
bql_unlock();
return 0;
}
static int coreaudio_init_out(HWVoiceOut *hw, struct audsettings *as)
static int coreaudio_init_out(HWVoiceOut *hw, struct audsettings *as,
void *drv_opaque)
{
OSStatus status;
CoreaudioVoiceOut *core = (CoreaudioVoiceOut *)hw;
coreaudioVoiceOut *core = (coreaudioVoiceOut *) hw;
int err;
Audiodev *dev = hw->s->dev;
Audiodev *dev = drv_opaque;
AudiodevCoreaudioPerDirectionOptions *cpdo = dev->u.coreaudio.out;
struct audsettings obt_as;
/* create mutex */
err = pthread_mutex_init(&core->buf_mutex, NULL);
if (err) {
error_report("coreaudio: Could not create mutex: %s", strerror(err));
dolog("Could not create mutex\nReason: %s\n", strerror (err));
return -1;
}
obt_as = *as;
as = &obt_as;
as->fmt = AUDIO_FORMAT_F32;
audio_pcm_init_info(&hw->info, as);
audio_pcm_init_info (&hw->info, as);
core->frame_size_setting = audio_buffer_frames(
core->frameSizeSetting = audio_buffer_frames(
qapi_AudiodevCoreaudioPerDirectionOptions_base(cpdo), as, 11610);
core->buffer_count = cpdo->has_buffer_count ? cpdo->buffer_count : 4;
core->bufferCount = cpdo->has_buffer_count ? cpdo->buffer_count : 4;
status = AudioObjectAddPropertyListener(kAudioObjectSystemObject,
&voice_out_addr,
handle_voice_out_change,
&voice_addr, handle_voice_change,
core);
if (status != kAudioHardwareNoError) {
coreaudio_playback_logerr(status,
"Could not listen to voice property change");
coreaudio_playback_logerr (status,
"Could not listen to voice property change\n");
return -1;
}
if (init_out_device(core)) {
status = AudioObjectRemovePropertyListener(kAudioObjectSystemObject,
&voice_out_addr,
handle_voice_out_change,
&voice_addr,
handle_voice_change,
core);
if (status != kAudioHardwareNoError) {
coreaudio_playback_logerr(status,
"Could not remove voice property change listener");
"Could not remove voice property change listener\n");
}
return -1;
@@ -623,14 +612,14 @@ static void coreaudio_fini_out (HWVoiceOut *hw)
{
OSStatus status;
int err;
CoreaudioVoiceOut *core = (CoreaudioVoiceOut *)hw;
coreaudioVoiceOut *core = (coreaudioVoiceOut *) hw;
status = AudioObjectRemovePropertyListener(kAudioObjectSystemObject,
&voice_out_addr,
handle_voice_out_change,
&voice_addr,
handle_voice_change,
core);
if (status != kAudioHardwareNoError) {
coreaudio_logerr(status, "Could not remove voice property change listener");
coreaudio_logerr(status, "Could not remove voice property change listener\n");
}
fini_out_device(core);
@@ -638,48 +627,54 @@ static void coreaudio_fini_out (HWVoiceOut *hw)
/* destroy mutex */
err = pthread_mutex_destroy(&core->buf_mutex);
if (err) {
error_report("coreaudio: Could not destroy mutex: %s", strerror(err));
dolog("Could not destroy mutex\nReason: %s\n", strerror (err));
}
}
static void coreaudio_enable_out(HWVoiceOut *hw, bool enable)
{
CoreaudioVoiceOut *core = (CoreaudioVoiceOut *)hw;
coreaudioVoiceOut *core = (coreaudioVoiceOut *) hw;
core->enabled = enable;
update_out_device_playback_state(core);
update_device_playback_state(core);
}
static void audio_coreaudio_class_init(ObjectClass *klass, const void *data)
static void *coreaudio_audio_init(Audiodev *dev, Error **errp)
{
AudioMixengBackendClass *k = AUDIO_MIXENG_BACKEND_CLASS(klass);
k->max_voices_out = 1;
k->max_voices_in = 0;
k->voice_size_out = sizeof(CoreaudioVoiceOut);
k->voice_size_in = 0;
k->init_out = coreaudio_init_out;
k->fini_out = coreaudio_fini_out;
/* wrapper for audio_generic_write */
k->write = coreaudio_write;
/* wrapper for audio_generic_buffer_get_free */
k->buffer_get_free = coreaudio_buffer_get_free;
/* wrapper for audio_generic_get_buffer_out */
k->get_buffer_out = coreaudio_get_buffer_out;
/* wrapper for audio_generic_put_buffer_out */
k->put_buffer_out = coreaudio_put_buffer_out;
k->enable_out = coreaudio_enable_out;
return dev;
}
static const TypeInfo audio_types[] = {
{
.name = TYPE_AUDIO_COREAUDIO,
.parent = TYPE_AUDIO_MIXENG_BACKEND,
.instance_size = sizeof(AudioCoreaudio),
.class_init = audio_coreaudio_class_init,
},
static void coreaudio_audio_fini (void *opaque)
{
}
static struct audio_pcm_ops coreaudio_pcm_ops = {
.init_out = coreaudio_init_out,
.fini_out = coreaudio_fini_out,
/* wrapper for audio_generic_write */
.write = coreaudio_write,
/* wrapper for audio_generic_buffer_get_free */
.buffer_get_free = coreaudio_buffer_get_free,
/* wrapper for audio_generic_get_buffer_out */
.get_buffer_out = coreaudio_get_buffer_out,
/* wrapper for audio_generic_put_buffer_out */
.put_buffer_out = coreaudio_put_buffer_out,
.enable_out = coreaudio_enable_out
};
DEFINE_TYPES(audio_types)
module_obj(TYPE_AUDIO_COREAUDIO);
static struct audio_driver coreaudio_audio_driver = {
.name = "coreaudio",
.init = coreaudio_audio_init,
.fini = coreaudio_audio_fini,
.pcm_ops = &coreaudio_pcm_ops,
.max_voices_out = 1,
.max_voices_in = 0,
.voice_size_out = sizeof (coreaudioVoiceOut),
.voice_size_in = 0
};
static void register_audio_coreaudio(void)
{
audio_driver_register(&coreaudio_audio_driver);
}
type_init(register_audio_coreaudio);
+73 -95
View File
@@ -26,16 +26,15 @@
#include "qemu/error-report.h"
#include "qemu/module.h"
#include "qemu/dbus.h"
#include "qom/object.h"
#ifdef G_OS_UNIX
#include <gio/gunixfdlist.h>
#endif
#include "ui/dbus.h"
#include "ui/dbus-display.h"
#include "ui/dbus-display1.h"
#define AUDIO_CAP "dbus"
#include "qemu/audio.h"
#include "audio_int.h"
#include "trace.h"
@@ -44,22 +43,15 @@
#define DBUS_DEFAULT_AUDIO_NSAMPLES 480
#define TYPE_AUDIO_DBUS "audio-dbus"
OBJECT_DECLARE_SIMPLE_TYPE(AudioDbus, AUDIO_DBUS)
static AudioBackendClass *audio_dbus_parent_class;
struct AudioDbus {
AudioMixengBackend parent_obj;
typedef struct DBusAudio {
Audiodev *dev;
GDBusObjectManagerServer *server;
bool p2p;
GDBusObjectSkeleton *audio;
QemuDBusDisplay1Audio *iface;
GHashTable *out_listeners;
GHashTable *in_listeners;
};
} DBusAudio;
typedef struct DBusVoiceOut {
HWVoiceOut hw;
@@ -102,7 +94,7 @@ static void *dbus_get_buffer_out(HWVoiceOut *hw, size_t *size)
static size_t dbus_put_buffer_out(HWVoiceOut *hw, void *buf, size_t size)
{
AudioDbus *da = AUDIO_DBUS(hw->s);
DBusAudio *da = (DBusAudio *)hw->s->drv_opaque;
DBusVoiceOut *vo = container_of(hw, DBusVoiceOut, hw);
GHashTableIter iter;
QemuDBusDisplay1AudioOutListener *listener = NULL;
@@ -147,9 +139,9 @@ dbus_init_out_listener(QemuDBusDisplay1AudioOutListener *listener,
qemu_dbus_display1_audio_out_listener_call_init(
listener,
(uintptr_t)hw,
audio_format_bits(hw->info.af),
audio_format_is_signed(hw->info.af),
audio_format_is_float(hw->info.af),
hw->info.bits,
hw->info.is_signed,
hw->info.is_float,
hw->info.freq,
hw->info.nchannels,
hw->info.bytes_per_frame,
@@ -159,9 +151,9 @@ dbus_init_out_listener(QemuDBusDisplay1AudioOutListener *listener,
}
static guint
dbus_audio_get_nsamples(AudioDbus *da)
dbus_audio_get_nsamples(DBusAudio *da)
{
AudiodevDBusOptions *opts = &AUDIO_MIXENG_BACKEND(da)->dev->u.dbus;
AudiodevDBusOptions *opts = &da->dev->u.dbus;
if (opts->has_nsamples && opts->nsamples) {
return opts->nsamples;
@@ -171,9 +163,9 @@ dbus_audio_get_nsamples(AudioDbus *da)
}
static int
dbus_init_out(HWVoiceOut *hw, struct audsettings *as)
dbus_init_out(HWVoiceOut *hw, struct audsettings *as, void *drv_opaque)
{
AudioDbus *da = AUDIO_DBUS(hw->s);
DBusAudio *da = (DBusAudio *)hw->s->drv_opaque;
DBusVoiceOut *vo = container_of(hw, DBusVoiceOut, hw);
GHashTableIter iter;
QemuDBusDisplay1AudioOutListener *listener = NULL;
@@ -192,7 +184,7 @@ dbus_init_out(HWVoiceOut *hw, struct audsettings *as)
static void
dbus_fini_out(HWVoiceOut *hw)
{
AudioDbus *da = AUDIO_DBUS(hw->s);
DBusAudio *da = (DBusAudio *)hw->s->drv_opaque;
DBusVoiceOut *vo = container_of(hw, DBusVoiceOut, hw);
GHashTableIter iter;
QemuDBusDisplay1AudioOutListener *listener = NULL;
@@ -211,7 +203,7 @@ dbus_fini_out(HWVoiceOut *hw)
static void
dbus_enable_out(HWVoiceOut *hw, bool enable)
{
AudioDbus *da = AUDIO_DBUS(hw->s);
DBusAudio *da = (DBusAudio *)hw->s->drv_opaque;
DBusVoiceOut *vo = container_of(hw, DBusVoiceOut, hw);
GHashTableIter iter;
QemuDBusDisplay1AudioOutListener *listener = NULL;
@@ -253,7 +245,7 @@ dbus_volume_out_listener(HWVoiceOut *hw,
static void
dbus_volume_out(HWVoiceOut *hw, Volume *vol)
{
AudioDbus *da = AUDIO_DBUS(hw->s);
DBusAudio *da = (DBusAudio *)hw->s->drv_opaque;
DBusVoiceOut *vo = container_of(hw, DBusVoiceOut, hw);
GHashTableIter iter;
QemuDBusDisplay1AudioOutListener *listener = NULL;
@@ -273,9 +265,9 @@ dbus_init_in_listener(QemuDBusDisplay1AudioInListener *listener, HWVoiceIn *hw)
qemu_dbus_display1_audio_in_listener_call_init(
listener,
(uintptr_t)hw,
audio_format_bits(hw->info.af),
audio_format_is_signed(hw->info.af),
audio_format_is_float(hw->info.af),
hw->info.bits,
hw->info.is_signed,
hw->info.is_float,
hw->info.freq,
hw->info.nchannels,
hw->info.bytes_per_frame,
@@ -285,9 +277,9 @@ dbus_init_in_listener(QemuDBusDisplay1AudioInListener *listener, HWVoiceIn *hw)
}
static int
dbus_init_in(HWVoiceIn *hw, struct audsettings *as)
dbus_init_in(HWVoiceIn *hw, struct audsettings *as, void *drv_opaque)
{
AudioDbus *da = AUDIO_DBUS(hw->s);
DBusAudio *da = (DBusAudio *)hw->s->drv_opaque;
DBusVoiceIn *vo = container_of(hw, DBusVoiceIn, hw);
GHashTableIter iter;
QemuDBusDisplay1AudioInListener *listener = NULL;
@@ -306,7 +298,7 @@ dbus_init_in(HWVoiceIn *hw, struct audsettings *as)
static void
dbus_fini_in(HWVoiceIn *hw)
{
AudioDbus *da = AUDIO_DBUS(hw->s);
DBusAudio *da = (DBusAudio *)hw->s->drv_opaque;
GHashTableIter iter;
QemuDBusDisplay1AudioInListener *listener = NULL;
@@ -343,7 +335,7 @@ dbus_volume_in_listener(HWVoiceIn *hw,
static void
dbus_volume_in(HWVoiceIn *hw, Volume *vol)
{
AudioDbus *da = AUDIO_DBUS(hw->s);
DBusAudio *da = (DBusAudio *)hw->s->drv_opaque;
DBusVoiceIn *vo = container_of(hw, DBusVoiceIn, hw);
GHashTableIter iter;
QemuDBusDisplay1AudioInListener *listener = NULL;
@@ -360,7 +352,7 @@ dbus_volume_in(HWVoiceIn *hw, Volume *vol)
static size_t
dbus_read(HWVoiceIn *hw, void *buf, size_t size)
{
AudioDbus *da = AUDIO_DBUS(hw->s);
DBusAudio *da = (DBusAudio *)hw->s->drv_opaque;
/* DBusVoiceIn *vo = container_of(hw, DBusVoiceIn, hw); */
GHashTableIter iter;
QemuDBusDisplay1AudioInListener *listener = NULL;
@@ -395,7 +387,7 @@ dbus_read(HWVoiceIn *hw, void *buf, size_t size)
static void
dbus_enable_in(HWVoiceIn *hw, bool enable)
{
AudioDbus *da = AUDIO_DBUS(hw->s);
DBusAudio *da = (DBusAudio *)hw->s->drv_opaque;
DBusVoiceIn *vo = container_of(hw, DBusVoiceIn, hw);
GHashTableIter iter;
QemuDBusDisplay1AudioInListener *listener = NULL;
@@ -413,31 +405,23 @@ dbus_enable_in(HWVoiceIn *hw, bool enable)
}
}
static bool
audio_dbus_realize(AudioBackend *abe, Audiodev *dev, Error **errp)
static void *
dbus_audio_init(Audiodev *dev, Error **errp)
{
AudioDbus *da = AUDIO_DBUS(abe);
if (!qemu_using_dbus_display(errp)) {
qapi_free_Audiodev(dev);
return false;
}
if (!audio_dbus_parent_class->realize(abe, dev, errp)) {
return false;
}
DBusAudio *da = g_new0(DBusAudio, 1);
da->dev = dev;
da->out_listeners = g_hash_table_new_full(g_str_hash, g_str_equal,
g_free, g_object_unref);
g_free, g_object_unref);
da->in_listeners = g_hash_table_new_full(g_str_hash, g_str_equal,
g_free, g_object_unref);
return true;
g_free, g_object_unref);
return da;
}
static void
audio_dbus_finalize(Object *obj)
dbus_audio_fini(void *opaque)
{
AudioDbus *da = AUDIO_DBUS(obj);
DBusAudio *da = opaque;
if (da->server) {
g_dbus_object_manager_server_unexport(da->server,
@@ -448,13 +432,14 @@ audio_dbus_finalize(Object *obj)
g_clear_pointer(&da->in_listeners, g_hash_table_unref);
g_clear_pointer(&da->out_listeners, g_hash_table_unref);
g_clear_object(&da->server);
g_free(da);
}
static void
listener_out_vanished_cb(GDBusConnection *connection,
gboolean remote_peer_vanished,
GError *error,
AudioDbus *da)
DBusAudio *da)
{
char *name = g_object_get_data(G_OBJECT(connection), "name");
@@ -465,7 +450,7 @@ static void
listener_in_vanished_cb(GDBusConnection *connection,
gboolean remote_peer_vanished,
GError *error,
AudioDbus *da)
DBusAudio *da)
{
char *name = g_object_get_data(G_OBJECT(connection), "name");
@@ -473,7 +458,7 @@ listener_in_vanished_cb(GDBusConnection *connection,
}
static gboolean
dbus_audio_register_listener(AudioMixengBackend *s,
dbus_audio_register_listener(AudioBackend *s,
GDBusMethodInvocation *invocation,
#ifdef G_OS_UNIX
GUnixFDList *fd_list,
@@ -481,7 +466,7 @@ dbus_audio_register_listener(AudioMixengBackend *s,
GVariant *arg_listener,
bool out)
{
AudioDbus *da = AUDIO_DBUS(s);
DBusAudio *da = s->drv_opaque;
const char *sender =
da->p2p ? "p2p" : g_dbus_method_invocation_get_sender(invocation);
g_autoptr(GDBusConnection) listener_conn = NULL;
@@ -630,7 +615,7 @@ dbus_audio_register_listener(AudioMixengBackend *s,
}
static gboolean
dbus_audio_register_out_listener(AudioMixengBackend *s,
dbus_audio_register_out_listener(AudioBackend *s,
GDBusMethodInvocation *invocation,
#ifdef G_OS_UNIX
GUnixFDList *fd_list,
@@ -646,7 +631,7 @@ dbus_audio_register_out_listener(AudioMixengBackend *s,
}
static gboolean
dbus_audio_register_in_listener(AudioMixengBackend *s,
dbus_audio_register_in_listener(AudioBackend *s,
GDBusMethodInvocation *invocation,
#ifdef G_OS_UNIX
GUnixFDList *fd_list,
@@ -666,8 +651,9 @@ dbus_audio_set_server(AudioBackend *s,
bool p2p,
Error **errp)
{
AudioDbus *da = AUDIO_DBUS(s);
DBusAudio *da = s->drv_opaque;
g_assert(da);
g_assert(!da->server);
da->server = g_object_ref(server);
@@ -690,47 +676,39 @@ dbus_audio_set_server(AudioBackend *s,
return true;
}
static void audio_dbus_class_init(ObjectClass *klass, const void *data)
{
AudioBackendClass *b = AUDIO_BACKEND_CLASS(klass);
AudioMixengBackendClass *k = AUDIO_MIXENG_BACKEND_CLASS(klass);
static struct audio_pcm_ops dbus_pcm_ops = {
.init_out = dbus_init_out,
.fini_out = dbus_fini_out,
.write = audio_generic_write,
.get_buffer_out = dbus_get_buffer_out,
.put_buffer_out = dbus_put_buffer_out,
.enable_out = dbus_enable_out,
.volume_out = dbus_volume_out,
audio_dbus_parent_class = AUDIO_BACKEND_CLASS(object_class_get_parent(klass));
b->realize = audio_dbus_realize;
b->set_dbus_server = dbus_audio_set_server;
k->max_voices_out = INT_MAX;
k->max_voices_in = INT_MAX;
k->voice_size_out = sizeof(DBusVoiceOut);
k->voice_size_in = sizeof(DBusVoiceIn);
k->init_out = dbus_init_out;
k->fini_out = dbus_fini_out;
k->write = audio_generic_write;
k->get_buffer_out = dbus_get_buffer_out;
k->put_buffer_out = dbus_put_buffer_out;
k->enable_out = dbus_enable_out;
k->volume_out = dbus_volume_out;
k->init_in = dbus_init_in;
k->fini_in = dbus_fini_in;
k->read = dbus_read;
k->run_buffer_in = audio_generic_run_buffer_in;
k->enable_in = dbus_enable_in;
k->volume_in = dbus_volume_in;
}
static const TypeInfo audio_types[] = {
{
.name = TYPE_AUDIO_DBUS,
.parent = TYPE_AUDIO_MIXENG_BACKEND,
.instance_size = sizeof(AudioDbus),
.instance_finalize = audio_dbus_finalize,
.class_init = audio_dbus_class_init,
},
.init_in = dbus_init_in,
.fini_in = dbus_fini_in,
.read = dbus_read,
.run_buffer_in = audio_generic_run_buffer_in,
.enable_in = dbus_enable_in,
.volume_in = dbus_volume_in,
};
DEFINE_TYPES(audio_types)
static struct audio_driver dbus_audio_driver = {
.name = "dbus",
.init = dbus_audio_init,
.fini = dbus_audio_fini,
.set_dbus_server = dbus_audio_set_server,
.pcm_ops = &dbus_pcm_ops,
.max_voices_out = INT_MAX,
.max_voices_in = INT_MAX,
.voice_size_out = sizeof(DBusVoiceOut),
.voice_size_in = sizeof(DBusVoiceIn)
};
static void register_audio_dbus(void)
{
audio_driver_register(&dbus_audio_driver);
}
type_init(register_audio_dbus);
module_dep("ui-dbus")
module_obj(TYPE_AUDIO_DBUS)
+48 -41
View File
@@ -53,9 +53,9 @@ static int glue (dsound_unlock_, TYPE) (
{
HRESULT hr;
hr = glue(IFACE, _Unlock)(buf, p1, blen1, p2, blen2);
if (FAILED(hr)) {
dsound_logerr(hr, "Could not unlock " NAME);
hr = glue (IFACE, _Unlock) (buf, p1, blen1, p2, blen2);
if (FAILED (hr)) {
dsound_logerr (hr, "Could not unlock " NAME "\n");
return -1;
}
@@ -72,7 +72,7 @@ static int glue (dsound_lock_, TYPE) (
DWORD *blen1p,
DWORD *blen2p,
int entire,
AudioDsound *s
dsound *s
)
{
HRESULT hr;
@@ -85,35 +85,35 @@ static int glue (dsound_lock_, TYPE) (
#endif
hr = glue(IFACE, _Lock)(buf, pos, len, p1p, blen1p, p2p, blen2p, flag);
if (FAILED(hr)) {
if (FAILED (hr)) {
#ifndef DSBTYPE_IN
if (hr == DSERR_BUFFERLOST) {
if (glue(dsound_restore_, TYPE)(buf, s)) {
dsound_logerr(hr, "Could not lock " NAME);
if (glue (dsound_restore_, TYPE) (buf, s)) {
dsound_logerr (hr, "Could not lock " NAME "\n");
}
goto fail;
}
#endif
dsound_logerr(hr, "Could not lock " NAME);
dsound_logerr (hr, "Could not lock " NAME "\n");
goto fail;
}
if ((p1p && *p1p && (*blen1p % info->bytes_per_frame)) ||
(p2p && *p2p && (*blen2p % info->bytes_per_frame))) {
error_report("dsound: returned misaligned buffer %ld %ld",
*blen1p, *blen2p);
dolog("DirectSound returned misaligned buffer %ld %ld\n",
*blen1p, *blen2p);
glue(dsound_unlock_, TYPE)(buf, *p1p, p2p ? *p2p : NULL, *blen1p,
blen2p ? *blen2p : 0);
goto fail;
}
if (p1p && !*p1p && *blen1p) {
warn_report("dsound: !p1 && blen1=%ld", *blen1p);
dolog("warning: !p1 && blen1=%ld\n", *blen1p);
*blen1p = 0;
}
if (p2p && !*p2p && *blen2p) {
warn_report("dsound: !p2 && blen2=%ld", *blen2p);
dolog("warning: !p2 && blen2=%ld\n", *blen2p);
*blen2p = 0;
}
@@ -143,28 +143,30 @@ static void dsound_fini_out (HWVoiceOut *hw)
#endif
if (ds->FIELD) {
hr = glue(IFACE, _Stop)(ds->FIELD);
if (FAILED(hr)) {
dsound_logerr(hr, "Could not stop " NAME);
hr = glue (IFACE, _Stop) (ds->FIELD);
if (FAILED (hr)) {
dsound_logerr (hr, "Could not stop " NAME "\n");
}
hr = glue(IFACE, _Release)(ds->FIELD);
if (FAILED(hr)) {
dsound_logerr(hr, "Could not release " NAME);
hr = glue (IFACE, _Release) (ds->FIELD);
if (FAILED (hr)) {
dsound_logerr (hr, "Could not release " NAME "\n");
}
ds->FIELD = NULL;
}
}
#ifdef DSBTYPE_IN
static int dsound_init_in(HWVoiceIn *hw, struct audsettings *as)
static int dsound_init_in(HWVoiceIn *hw, struct audsettings *as,
void *drv_opaque)
#else
static int dsound_init_out(HWVoiceOut *hw, struct audsettings *as)
static int dsound_init_out(HWVoiceOut *hw, struct audsettings *as,
void *drv_opaque)
#endif
{
int err;
HRESULT hr;
AudioDsound *s = AUDIO_DSOUND(hw->s);
dsound *s = drv_opaque;
WAVEFORMATEX wfx;
struct audsettings obt_as;
#ifdef DSBTYPE_IN
@@ -172,18 +174,17 @@ static int dsound_init_out(HWVoiceOut *hw, struct audsettings *as)
DSoundVoiceIn *ds = (DSoundVoiceIn *) hw;
DSCBUFFERDESC bd;
DSCBCAPS bc;
AudiodevPerDirectionOptions *pdo = hw->s->dev->u.dsound.in;
AudiodevPerDirectionOptions *pdo = s->dev->u.dsound.in;
#else
const char *typ = "DAC";
DSoundVoiceOut *ds = (DSoundVoiceOut *) hw;
DSBUFFERDESC bd;
DSBCAPS bc;
AudiodevPerDirectionOptions *pdo = hw->s->dev->u.dsound.out;
AudiodevPerDirectionOptions *pdo = s->dev->u.dsound.out;
#endif
if (!s->FIELD2) {
error_report("dsound: Attempt to initialize voice without "
NAME2 " object");
dolog ("Attempt to initialize voice without " NAME2 " object\n");
return -1;
}
@@ -213,28 +214,28 @@ static int dsound_init_out(HWVoiceOut *hw, struct audsettings *as)
);
#endif
if (FAILED(hr)) {
dsound_logerr2(hr, typ, "Could not create " NAME);
if (FAILED (hr)) {
dsound_logerr2 (hr, typ, "Could not create " NAME "\n");
return -1;
}
hr = glue(IFACE, _GetFormat)(ds->FIELD, &wfx, sizeof(wfx), NULL);
if (FAILED(hr)) {
dsound_logerr2(hr, typ, "Could not get " NAME " format");
hr = glue (IFACE, _GetFormat) (ds->FIELD, &wfx, sizeof (wfx), NULL);
if (FAILED (hr)) {
dsound_logerr2 (hr, typ, "Could not get " NAME " format\n");
goto fail0;
}
trace_dsound_wave_format(
wfx.wFormatTag, wfx.nChannels,
wfx.nSamplesPerSec, wfx.nAvgBytesPerSec,
wfx.nBlockAlign, wfx.wBitsPerSample, wfx.cbSize);
#ifdef DEBUG_DSOUND
dolog (NAME "\n");
print_wave_format (&wfx);
#endif
memset (&bc, 0, sizeof (bc));
bc.dwSize = sizeof (bc);
hr = glue(IFACE, _GetCaps)(ds->FIELD, &bc);
if (FAILED(hr)) {
dsound_logerr2(hr, typ, "Could not get " NAME " caps");
hr = glue (IFACE, _GetCaps) (ds->FIELD, &bc);
if (FAILED (hr)) {
dsound_logerr2 (hr, typ, "Could not get " NAME " format\n");
goto fail0;
}
@@ -244,17 +245,23 @@ static int dsound_init_out(HWVoiceOut *hw, struct audsettings *as)
}
ds->first_time = true;
obt_as.big_endian = false;
obt_as.endianness = 0;
audio_pcm_init_info (&hw->info, &obt_as);
if (bc.dwBufferBytes % hw->info.bytes_per_frame) {
warn_report("dsound: GetCaps returned misaligned buffer size %ld, "
"alignment %d", bc.dwBufferBytes, hw->info.bytes_per_frame);
dolog (
"GetCaps returned misaligned buffer size %ld, alignment %d\n",
bc.dwBufferBytes, hw->info.bytes_per_frame
);
}
hw->size_emul = bc.dwBufferBytes;
hw->samples = bc.dwBufferBytes / hw->info.bytes_per_frame;
ds->s = s;
trace_dsound_buffer_bytes(bc.dwBufferBytes, bd.dwBufferBytes);
#ifdef DEBUG_DSOUND
dolog ("caps %ld, desc %ld\n",
bc.dwBufferBytes, bd.dwBufferBytes);
#endif
return 0;
fail0:
+141 -124
View File
@@ -28,43 +28,40 @@
#include "qemu/osdep.h"
#include "qemu/audio.h"
#include "qemu/error-report.h"
#define AUDIO_CAP "dsound"
#include "audio_int.h"
#include "qemu/module.h"
#include "qapi/error.h"
#include "qom/object.h"
#include <windows.h>
#include <mmsystem.h>
#include <objbase.h>
#include <dsound.h>
#include "trace.h"
#include "audio_win_int.h"
#define TYPE_AUDIO_DSOUND "audio-dsound"
OBJECT_DECLARE_SIMPLE_TYPE(AudioDsound, AUDIO_DSOUND)
static AudioBackendClass *audio_dsound_parent_class;
struct AudioDsound {
AudioMixengBackend parent_obj;
/* #define DEBUG_DSOUND */
typedef struct {
LPDIRECTSOUND dsound;
LPDIRECTSOUNDCAPTURE dsound_capture;
struct audsettings settings;
};
Audiodev *dev;
} dsound;
typedef struct {
HWVoiceOut hw;
LPDIRECTSOUNDBUFFER dsound_buffer;
bool first_time;
dsound *s;
} DSoundVoiceOut;
typedef struct {
HWVoiceIn hw;
LPDIRECTSOUNDCAPTUREBUFFER dsound_capture_buffer;
bool first_time;
dsound *s;
} DSoundVoiceIn;
static const char *dserror(HRESULT hr)
@@ -211,46 +208,65 @@ static void dsound_log_hresult(HRESULT hr)
const char *str = dserror(hr);
if (str) {
error_printf(" Reason: %s", str);
AUD_log (AUDIO_CAP, "Reason: %s\n", str);
} else {
error_printf(" Reason: Unknown (HRESULT: 0x%lx)", hr);
AUD_log (AUDIO_CAP, "Reason: Unknown (HRESULT: 0x%lx)\n", hr);
}
}
static void G_GNUC_PRINTF(2, 3) dsound_logerr(HRESULT hr, const char *fmt, ...)
static void G_GNUC_PRINTF (2, 3) dsound_logerr (
HRESULT hr,
const char *fmt,
...
)
{
va_list ap;
error_printf("dsound: ");
va_start(ap, fmt);
error_vprintf(fmt, ap);
va_end(ap);
dsound_log_hresult(hr);
error_printf("\n");
va_start (ap, fmt);
AUD_vlog (AUDIO_CAP, fmt, ap);
va_end (ap);
dsound_log_hresult (hr);
}
static void G_GNUC_PRINTF(3, 4) dsound_logerr2(HRESULT hr, const char *typ,
const char *fmt, ...)
static void G_GNUC_PRINTF (3, 4) dsound_logerr2 (
HRESULT hr,
const char *typ,
const char *fmt,
...
)
{
va_list ap;
error_printf("dsound: Could not initialize %s: ", typ);
va_start(ap, fmt);
error_vprintf(fmt, ap);
va_end(ap);
dsound_log_hresult(hr);
error_printf("\n");
AUD_log (AUDIO_CAP, "Could not initialize %s\n", typ);
va_start (ap, fmt);
AUD_vlog (AUDIO_CAP, fmt, ap);
va_end (ap);
dsound_log_hresult (hr);
}
#ifdef DEBUG_DSOUND
static void print_wave_format (WAVEFORMATEX *wfx)
{
dolog ("tag = %d\n", wfx->wFormatTag);
dolog ("nChannels = %d\n", wfx->nChannels);
dolog ("nSamplesPerSec = %ld\n", wfx->nSamplesPerSec);
dolog ("nAvgBytesPerSec = %ld\n", wfx->nAvgBytesPerSec);
dolog ("nBlockAlign = %d\n", wfx->nBlockAlign);
dolog ("wBitsPerSample = %d\n", wfx->wBitsPerSample);
dolog ("cbSize = %d\n", wfx->cbSize);
}
#endif
static int dsound_restore_out (LPDIRECTSOUNDBUFFER dsb, AudioDsound *s)
static int dsound_restore_out (LPDIRECTSOUNDBUFFER dsb, dsound *s)
{
HRESULT hr;
hr = IDirectSoundBuffer_Restore (dsb);
if (hr != DS_OK) {
dsound_logerr(hr, "Could not restore playback buffer");
dsound_logerr (hr, "Could not restore playback buffer\n");
return -1;
}
return 0;
@@ -262,13 +278,13 @@ static int dsound_restore_out (LPDIRECTSOUNDBUFFER dsb, AudioDsound *s)
#undef DSBTYPE_IN
static int dsound_get_status_out (LPDIRECTSOUNDBUFFER dsb, DWORD *statusp,
AudioDsound *s)
dsound *s)
{
HRESULT hr;
hr = IDirectSoundBuffer_GetStatus (dsb, statusp);
if (FAILED (hr)) {
dsound_logerr(hr, "Could not get playback buffer status");
dsound_logerr (hr, "Could not get playback buffer status\n");
return -1;
}
@@ -287,7 +303,7 @@ static int dsound_get_status_in (LPDIRECTSOUNDCAPTUREBUFFER dscb,
hr = IDirectSoundCaptureBuffer_GetStatus (dscb, statusp);
if (FAILED (hr)) {
dsound_logerr(hr, "Could not get capture buffer status");
dsound_logerr (hr, "Could not get capture buffer status\n");
return -1;
}
@@ -295,7 +311,7 @@ static int dsound_get_status_in (LPDIRECTSOUNDCAPTUREBUFFER dscb,
}
static void dsound_clear_sample (HWVoiceOut *hw, LPDIRECTSOUNDBUFFER dsb,
AudioDsound *s)
dsound *s)
{
int err;
LPVOID p1, p2;
@@ -318,7 +334,11 @@ static void dsound_clear_sample (HWVoiceOut *hw, LPDIRECTSOUNDBUFFER dsb,
len1 = blen1 / hw->info.bytes_per_frame;
len2 = blen2 / hw->info.bytes_per_frame;
trace_dsound_clear_sample(p1, blen1, len1, p2, blen2, len2);
#ifdef DEBUG_DSOUND
dolog ("clear %p,%ld,%ld %p,%ld,%ld\n",
p1, blen1, len1,
p2, blen2, len2);
#endif
if (p1 && len1) {
audio_pcm_info_clear_buf (&hw->info, p1, len1);
@@ -335,45 +355,45 @@ static void dsound_enable_out(HWVoiceOut *hw, bool enable)
{
HRESULT hr;
DWORD status;
AudioDsound *s = AUDIO_DSOUND(hw->s);
DSoundVoiceOut *ds = (DSoundVoiceOut *) hw;
LPDIRECTSOUNDBUFFER dsb = ds->dsound_buffer;
dsound *s = ds->s;
if (!dsb) {
error_report("dsound: Attempt to control voice without a buffer");
dolog ("Attempt to control voice without a buffer\n");
return;
}
if (enable) {
if (dsound_get_status_out(dsb, &status, s)) {
if (dsound_get_status_out (dsb, &status, s)) {
return;
}
if (status & DSBSTATUS_PLAYING) {
warn_report("dsound: Voice is already playing");
dolog ("warning: Voice is already playing\n");
return;
}
dsound_clear_sample(hw, dsb, s);
dsound_clear_sample (hw, dsb, s);
hr = IDirectSoundBuffer_Play(dsb, 0, 0, DSBPLAY_LOOPING);
if (FAILED(hr)) {
dsound_logerr(hr, "Could not start playing buffer");
hr = IDirectSoundBuffer_Play (dsb, 0, 0, DSBPLAY_LOOPING);
if (FAILED (hr)) {
dsound_logerr (hr, "Could not start playing buffer\n");
return;
}
} else {
if (dsound_get_status_out(dsb, &status, s)) {
if (dsound_get_status_out (dsb, &status, s)) {
return;
}
if (status & DSBSTATUS_PLAYING) {
hr = IDirectSoundBuffer_Stop(dsb);
if (FAILED(hr)) {
dsound_logerr(hr, "Could not stop playing buffer");
hr = IDirectSoundBuffer_Stop (dsb);
if (FAILED (hr)) {
dsound_logerr (hr, "Could not stop playing buffer\n");
return;
}
} else {
warn_report("dsound: Voice is not playing");
dolog ("warning: Voice is not playing\n");
}
}
}
@@ -388,7 +408,7 @@ static size_t dsound_buffer_get_free(HWVoiceOut *hw)
hr = IDirectSoundBuffer_GetCurrentPosition(
dsb, &ppos, ds->first_time ? &wpos : NULL);
if (FAILED(hr)) {
dsound_logerr(hr, "Could not get playback buffer position");
dsound_logerr(hr, "Could not get playback buffer position\n");
return 0;
}
@@ -413,9 +433,9 @@ static void *dsound_get_buffer_out(HWVoiceOut *hw, size_t *size)
assert(req_size > 0);
err = dsound_lock_out(dsb, &hw->info, hw->pos_emul, req_size, &ret, NULL,
&act_size, NULL, false, AUDIO_DSOUND(hw->s));
&act_size, NULL, false, ds->s);
if (err) {
error_report("dsound: Failed to lock buffer");
dolog("Failed to lock buffer\n");
*size = 0;
return NULL;
}
@@ -431,7 +451,7 @@ static size_t dsound_put_buffer_out(HWVoiceOut *hw, void *buf, size_t len)
int err = dsound_unlock_out(dsb, buf, NULL, len, 0);
if (err) {
error_report("dsound: Failed to unlock buffer");
dolog("Failed to unlock buffer!!\n");
return 0;
}
hw->pos_emul = (hw->pos_emul + len) % hw->size_emul;
@@ -447,40 +467,40 @@ static void dsound_enable_in(HWVoiceIn *hw, bool enable)
LPDIRECTSOUNDCAPTUREBUFFER dscb = ds->dsound_capture_buffer;
if (!dscb) {
error_report("dsound: Attempt to control capture voice without a buffer");
dolog ("Attempt to control capture voice without a buffer\n");
return;
}
if (enable) {
if (dsound_get_status_in(dscb, &status)) {
if (dsound_get_status_in (dscb, &status)) {
return;
}
if (status & DSCBSTATUS_CAPTURING) {
warn_report("dsound: Voice is already capturing");
dolog ("warning: Voice is already capturing\n");
return;
}
/* clear ?? */
hr = IDirectSoundCaptureBuffer_Start(dscb, DSCBSTART_LOOPING);
if (FAILED(hr)) {
dsound_logerr(hr, "Could not start capturing");
hr = IDirectSoundCaptureBuffer_Start (dscb, DSCBSTART_LOOPING);
if (FAILED (hr)) {
dsound_logerr (hr, "Could not start capturing\n");
return;
}
} else {
if (dsound_get_status_in(dscb, &status)) {
if (dsound_get_status_in (dscb, &status)) {
return;
}
if (status & DSCBSTATUS_CAPTURING) {
hr = IDirectSoundCaptureBuffer_Stop(dscb);
if (FAILED(hr)) {
dsound_logerr(hr, "Could not stop capturing");
hr = IDirectSoundCaptureBuffer_Stop (dscb);
if (FAILED (hr)) {
dsound_logerr (hr, "Could not stop capturing\n");
return;
}
} else {
warn_report("dsound: Voice is not capturing");
dolog ("warning: Voice is not capturing\n");
}
}
}
@@ -497,7 +517,7 @@ static void *dsound_get_buffer_in(HWVoiceIn *hw, size_t *size)
hr = IDirectSoundCaptureBuffer_GetCurrentPosition(dscb, NULL, &rpos);
if (FAILED(hr)) {
dsound_logerr(hr, "Could not get capture buffer position");
dsound_logerr(hr, "Could not get capture buffer position\n");
*size = 0;
return NULL;
}
@@ -516,9 +536,9 @@ static void *dsound_get_buffer_in(HWVoiceIn *hw, size_t *size)
}
err = dsound_lock_in(dscb, &hw->info, hw->pos_emul, req_size, &ret, NULL,
&act_size, NULL, false, AUDIO_DSOUND(hw->s));
&act_size, NULL, false, ds->s);
if (err) {
error_report("dsound: Failed to lock buffer");
dolog("Failed to lock buffer\n");
*size = 0;
return NULL;
}
@@ -534,51 +554,50 @@ static void dsound_put_buffer_in(HWVoiceIn *hw, void *buf, size_t len)
int err = dsound_unlock_in(dscb, buf, NULL, len, 0);
if (err) {
error_report("dsound: Failed to unlock buffer");
dolog("Failed to unlock buffer!!\n");
return;
}
hw->pos_emul = (hw->pos_emul + len) % hw->size_emul;
}
static void audio_dsound_finalize(Object *obj)
static void dsound_audio_fini (void *opaque)
{
AudioDsound *s = AUDIO_DSOUND(obj);
HRESULT hr;
dsound *s = opaque;
if (!s->dsound) {
g_free(s);
return;
}
hr = IDirectSound_Release (s->dsound);
if (FAILED (hr)) {
dsound_logerr(hr, "Could not release DirectSound");
dsound_logerr (hr, "Could not release DirectSound\n");
}
s->dsound = NULL;
if (!s->dsound_capture) {
g_free(s);
return;
}
hr = IDirectSoundCapture_Release (s->dsound_capture);
if (FAILED (hr)) {
dsound_logerr(hr, "Could not release DirectSoundCapture");
dsound_logerr (hr, "Could not release DirectSoundCapture\n");
}
s->dsound_capture = NULL;
g_free(s);
}
static bool
audio_dsound_realize(AudioBackend *abe, Audiodev *dev, Error **errp)
static void *dsound_audio_init(Audiodev *dev, Error **errp)
{
AudioDsound *s = AUDIO_DSOUND(abe);
HRESULT hr;
dsound *s = g_new0(dsound, 1);
AudiodevDsoundOptions *dso;
assert(dev->driver == AUDIODEV_DRIVER_DSOUND);
if (!audio_dsound_parent_class->realize(abe, dev, errp)) {
return false;
}
s->dev = dev;
dso = &dev->u.dsound;
if (!dso->has_latency) {
@@ -589,7 +608,8 @@ audio_dsound_realize(AudioBackend *abe, Audiodev *dev, Error **errp)
hr = CoInitialize (NULL);
if (FAILED (hr)) {
dserror_set(errp, hr, "Could not initialize COM");
return false;
dsound_audio_fini(s);
return NULL;
}
hr = CoCreateInstance (
@@ -601,13 +621,15 @@ audio_dsound_realize(AudioBackend *abe, Audiodev *dev, Error **errp)
);
if (FAILED (hr)) {
dserror_set(errp, hr, "Could not create DirectSound instance");
return false;
dsound_audio_fini(s);
return NULL;
}
hr = IDirectSound_Initialize (s->dsound, NULL);
if (FAILED (hr)) {
dserror_set(errp, hr, "Could not initialize DirectSound");
return false;
dsound_audio_fini(s);
return NULL;
}
hr = CoCreateInstance (
@@ -619,13 +641,15 @@ audio_dsound_realize(AudioBackend *abe, Audiodev *dev, Error **errp)
);
if (FAILED (hr)) {
dserror_set(errp, hr, "Could not create DirectSoundCapture instance");
return false;
dsound_audio_fini(s);
return NULL;
}
hr = IDirectSoundCapture_Initialize (s->dsound_capture, NULL);
if (FAILED(hr)) {
dserror_set(errp, hr, "Could not initialize DirectSoundCapture");
return false;
dsound_audio_fini(s);
return NULL;
}
hr = IDirectSound_SetCooperativeLevel (
@@ -635,50 +659,43 @@ audio_dsound_realize(AudioBackend *abe, Audiodev *dev, Error **errp)
);
if (FAILED(hr)) {
dserror_set(errp, hr, "Could not set cooperative level");
return false;
dsound_audio_fini(s);
return NULL;
}
return true;
return s;
}
static void audio_dsound_class_init(ObjectClass *klass, const void *data)
{
AudioBackendClass *b = AUDIO_BACKEND_CLASS(klass);
AudioMixengBackendClass *k = AUDIO_MIXENG_BACKEND_CLASS(klass);
static struct audio_pcm_ops dsound_pcm_ops = {
.init_out = dsound_init_out,
.fini_out = dsound_fini_out,
.write = audio_generic_write,
.buffer_get_free = dsound_buffer_get_free,
.get_buffer_out = dsound_get_buffer_out,
.put_buffer_out = dsound_put_buffer_out,
.enable_out = dsound_enable_out,
audio_dsound_parent_class = AUDIO_BACKEND_CLASS(object_class_get_parent(klass));
b->realize = audio_dsound_realize;
k->max_voices_out = INT_MAX;
k->max_voices_in = 1;
k->voice_size_out = sizeof(DSoundVoiceOut);
k->voice_size_in = sizeof(DSoundVoiceIn);
k->init_out = dsound_init_out;
k->fini_out = dsound_fini_out;
k->write = audio_generic_write;
k->buffer_get_free = dsound_buffer_get_free;
k->get_buffer_out = dsound_get_buffer_out;
k->put_buffer_out = dsound_put_buffer_out;
k->enable_out = dsound_enable_out;
k->init_in = dsound_init_in;
k->fini_in = dsound_fini_in;
k->read = audio_generic_read;
k->get_buffer_in = dsound_get_buffer_in;
k->put_buffer_in = dsound_put_buffer_in;
k->enable_in = dsound_enable_in;
}
static const TypeInfo audio_types[] = {
{
.name = TYPE_AUDIO_DSOUND,
.parent = TYPE_AUDIO_MIXENG_BACKEND,
.instance_size = sizeof(AudioDsound),
.class_init = audio_dsound_class_init,
.instance_finalize = audio_dsound_finalize,
},
.init_in = dsound_init_in,
.fini_in = dsound_fini_in,
.read = audio_generic_read,
.get_buffer_in = dsound_get_buffer_in,
.put_buffer_in = dsound_put_buffer_in,
.enable_in = dsound_enable_in,
};
DEFINE_TYPES(audio_types)
module_obj(TYPE_AUDIO_DSOUND);
static struct audio_driver dsound_audio_driver = {
.name = "dsound",
.init = dsound_audio_init,
.fini = dsound_audio_fini,
.pcm_ops = &dsound_pcm_ops,
.max_voices_out = INT_MAX,
.max_voices_in = 1,
.voice_size_out = sizeof (DSoundVoiceOut),
.voice_size_in = sizeof (DSoundVoiceIn)
};
static void register_audio_dsound(void)
{
audio_driver_register(&dsound_audio_driver);
}
type_init(register_audio_dsound);
+69 -88
View File
@@ -26,23 +26,14 @@
#include "qemu/module.h"
#include "qemu/atomic.h"
#include "qemu/main-loop.h"
#include "qemu/error-report.h"
#include "qemu/audio.h"
#include "qom/object.h"
#define AUDIO_CAP "jack"
#include "audio_int.h"
#include "trace.h"
#include <jack/jack.h>
#include <jack/thread.h>
#define TYPE_AUDIO_JACK "audio-jack"
OBJECT_DECLARE_SIMPLE_TYPE(AudioJack, AUDIO_JACK)
struct AudioJack {
AudioMixengBackend parent_obj;
};
struct QJack;
typedef enum QJackState {
@@ -343,7 +334,7 @@ static void qjack_client_recover(QJackClient *c)
/* if enabled then attempt to recover */
if (c->enabled) {
trace_jack_client_recover();
dolog("attempting to reconnect to server\n");
qjack_client_init(c);
}
}
@@ -399,10 +390,10 @@ static void qjack_client_connect_ports(QJackClient *c)
}
if (c->out) {
trace_jack_connect(p, ports[i]);
dolog("connect %s -> %s\n", p, ports[i]);
jack_connect(c->client, p, ports[i]);
} else {
trace_jack_connect(ports[i], p);
dolog("connect %s -> %s\n", ports[i], p);
jack_connect(c->client, ports[i], p);
}
}
@@ -441,9 +432,9 @@ static int qjack_client_init(QJackClient *c)
c->opt->server_name);
if (c->client == NULL) {
error_report("jack: jack_client_open failed: status = 0x%2.0x", status);
dolog("jack_client_open failed: status = 0x%2.0x\n", status);
if (status & JackServerFailed) {
error_report("jack: unable to connect to JACK server");
dolog("unable to connect to JACK server\n");
}
return -1;
}
@@ -451,11 +442,12 @@ static int qjack_client_init(QJackClient *c)
c->freq = jack_get_sample_rate(c->client);
if (status & JackServerStarted) {
trace_jack_server_started();
dolog("JACK server started\n");
}
if (status & JackNameNotUnique) {
trace_jack_unique_name(jack_get_client_name(c->client));
dolog("JACK unique name assigned %s\n",
jack_get_client_name(c->client));
}
/* Allocate working buffer for process callback */
@@ -505,10 +497,11 @@ static int qjack_client_init(QJackClient *c)
return 0;
}
static int qjack_init_out(HWVoiceOut *hw, struct audsettings *as)
static int qjack_init_out(HWVoiceOut *hw, struct audsettings *as,
void *drv_opaque)
{
QJackOut *jo = (QJackOut *)hw;
Audiodev *dev = hw->s->dev;
Audiodev *dev = (Audiodev *)drv_opaque;
jo->c.out = true;
jo->c.enabled = false;
@@ -531,19 +524,21 @@ static int qjack_init_out(HWVoiceOut *hw, struct audsettings *as)
.freq = jo->c.freq,
.nchannels = jo->c.nchannels,
.fmt = AUDIO_FORMAT_F32,
.big_endian = false
.endianness = 0
};
audio_pcm_init_info(&hw->info, &os);
trace_jack_out_init(jo->c.freq, jo->c.buffersize);
dolog("JACK output configured for %dHz (%d samples)\n",
jo->c.freq, jo->c.buffersize);
return 0;
}
static int qjack_init_in(HWVoiceIn *hw, struct audsettings *as)
static int qjack_init_in(HWVoiceIn *hw, struct audsettings *as,
void *drv_opaque)
{
QJackIn *ji = (QJackIn *)hw;
Audiodev *dev = hw->s->dev;
Audiodev *dev = (Audiodev *)drv_opaque;
ji->c.out = false;
ji->c.enabled = false;
@@ -566,11 +561,12 @@ static int qjack_init_in(HWVoiceIn *hw, struct audsettings *as)
.freq = ji->c.freq,
.nchannels = ji->c.nchannels,
.fmt = AUDIO_FORMAT_F32,
.big_endian = false
.endianness = 0
};
audio_pcm_init_info(&hw->info, &is);
trace_jack_in_init(ji->c.freq, ji->c.buffersize);
dolog("JACK input configured for %dHz (%d samples)\n",
ji->c.freq, ji->c.buffersize);
return 0;
}
@@ -633,91 +629,76 @@ static void qjack_enable_in(HWVoiceIn *hw, bool enable)
ji->c.enabled = enable;
}
#if !defined(WIN32)
struct QJackThreadData {
void *(*function)(void *);
void *arg;
};
static void *qjack_thread_trampoline(void *targ)
{
struct QJackThreadData *data = targ;
void *(*function)(void *) = data->function;
void *arg = data->arg;
g_free(data);
qemu_thread_set_name("jack-client");
return function(arg);
}
#if !defined(WIN32) && defined(CONFIG_PTHREAD_SETNAME_NP_W_TID)
static int qjack_thread_creator(jack_native_thread_t *thread,
const pthread_attr_t *attr, void *(*function)(void *), void *arg)
{
struct QJackThreadData *data = g_new0(struct QJackThreadData, 1);
data->function = function;
data->arg = arg;
int ret = pthread_create(thread, attr, qjack_thread_trampoline, data);
int ret = pthread_create(thread, attr, function, arg);
if (ret != 0) {
g_free(data);
return ret;
}
/* set the name of the thread */
pthread_setname_np(*thread, "jack-client");
return ret;
}
#endif
static void *qjack_init(Audiodev *dev, Error **errp)
{
assert(dev->driver == AUDIODEV_DRIVER_JACK);
return dev;
}
static void qjack_fini(void *opaque)
{
}
static struct audio_pcm_ops jack_pcm_ops = {
.init_out = qjack_init_out,
.fini_out = qjack_fini_out,
.write = qjack_write,
.buffer_get_free = audio_generic_buffer_get_free,
.run_buffer_out = audio_generic_run_buffer_out,
.enable_out = qjack_enable_out,
.init_in = qjack_init_in,
.fini_in = qjack_fini_in,
.read = qjack_read,
.run_buffer_in = audio_generic_run_buffer_in,
.enable_in = qjack_enable_in
};
static struct audio_driver jack_driver = {
.name = "jack",
.init = qjack_init,
.fini = qjack_fini,
.pcm_ops = &jack_pcm_ops,
.max_voices_out = INT_MAX,
.max_voices_in = INT_MAX,
.voice_size_out = sizeof(QJackOut),
.voice_size_in = sizeof(QJackIn)
};
static void qjack_error(const char *msg)
{
error_report("jack: %s", msg);
dolog("E: %s\n", msg);
}
static void qjack_info(const char *msg)
{
trace_jack_info(msg);
dolog("I: %s\n", msg);
}
static void audio_jack_class_init(ObjectClass *klass, const void *data)
{
AudioMixengBackendClass *k = AUDIO_MIXENG_BACKEND_CLASS(klass);
k->max_voices_out = INT_MAX;
k->max_voices_in = INT_MAX;
k->voice_size_out = sizeof(QJackOut);
k->voice_size_in = sizeof(QJackIn);
k->init_out = qjack_init_out;
k->fini_out = qjack_fini_out;
k->write = qjack_write;
k->buffer_get_free = audio_generic_buffer_get_free;
k->run_buffer_out = audio_generic_run_buffer_out;
k->enable_out = qjack_enable_out;
k->init_in = qjack_init_in;
k->fini_in = qjack_fini_in;
k->read = qjack_read;
k->run_buffer_in = audio_generic_run_buffer_in;
k->enable_in = qjack_enable_in;
}
static const TypeInfo audio_types[] = {
{
.name = TYPE_AUDIO_JACK,
.parent = TYPE_AUDIO_MIXENG_BACKEND,
.instance_size = sizeof(AudioJack),
.class_init = audio_jack_class_init,
},
};
static void __attribute__((__constructor__)) audio_jack_init(void)
static void register_audio_jack(void)
{
qemu_mutex_init(&qjack_shutdown_lock);
#if !defined(WIN32)
audio_driver_register(&jack_driver);
#if !defined(WIN32) && defined(CONFIG_PTHREAD_SETNAME_NP_W_TID)
jack_set_thread_creator(qjack_thread_creator);
#endif
jack_set_error_function(qjack_error);
jack_set_info_function(qjack_info);
}
DEFINE_TYPES(audio_types)
module_obj(TYPE_AUDIO_JACK);
type_init(register_audio_jack);
+5 -7
View File
@@ -1,8 +1,5 @@
audio_ss = ss.source_set()
audio_ss.add(files(
system_ss.add(files(
'audio.c',
'audio-be.c',
'audio-mixeng-be.c',
'mixeng.c',
'noaudio.c',
'wavaudio.c',
@@ -11,11 +8,12 @@ audio_ss.add(files(
# deprecated since v10.2, to be removed
system_ss.add(files('audio-hmp-cmds.c', 'wavcapture.c'))
system_ss.add(when: coreaudio, if_true: files('coreaudio.m'))
system_ss.add(when: dsound, if_true: files('dsoundaudio.c', 'audio_win_int.c'))
audio_modules = {}
foreach m : [
['alsa', alsa, files('alsaaudio.c')],
['coreaudio', coreaudio, files('coreaudio.m')],
['dsound', dsound, files('dsoundaudio.c', 'audio_win_int.c')],
['oss', oss, files('ossaudio.c')],
['pa', pulse, files('paaudio.c')],
['sdl', sdl, files('sdlaudio.c')],
@@ -34,7 +32,7 @@ endforeach
if dbus_display
module_ss = ss.source_set()
module_ss.add(when: [gio, pixman],
if_true: [dbus_display1_h, files('dbusaudio.c')])
if_true: [dbus_display1, files('dbusaudio.c')])
audio_modules += {'dbus': module_ss}
endif
+1
View File
@@ -26,6 +26,7 @@
#include "qemu/bswap.h"
#include "qemu/audio.h"
#define AUDIO_CAP "mixeng"
#include "audio_int.h"
#ifdef FLOAT_MIXENG
#include "qemu/error-report.h"
+39 -39
View File
@@ -25,17 +25,10 @@
#include "qemu/osdep.h"
#include "qemu/module.h"
#include "qemu/audio.h"
#include "qom/object.h"
#define AUDIO_CAP "noaudio"
#include "audio_int.h"
#define TYPE_AUDIO_NONE "audio-none"
OBJECT_DECLARE_SIMPLE_TYPE(AudioNone, AUDIO_NONE)
struct AudioNone {
AudioMixengBackend parent_obj;
};
typedef struct NoVoiceOut {
HWVoiceOut hw;
RateCtl rate;
@@ -52,7 +45,7 @@ static size_t no_write(HWVoiceOut *hw, void *buf, size_t len)
return audio_rate_get_bytes(&no->rate, &hw->info, len);
}
static int no_init_out(HWVoiceOut *hw, struct audsettings *as)
static int no_init_out(HWVoiceOut *hw, struct audsettings *as, void *drv_opaque)
{
NoVoiceOut *no = (NoVoiceOut *) hw;
@@ -76,7 +69,7 @@ static void no_enable_out(HWVoiceOut *hw, bool enable)
}
}
static int no_init_in(HWVoiceIn *hw, struct audsettings *as)
static int no_init_in(HWVoiceIn *hw, struct audsettings *as, void *drv_opaque)
{
NoVoiceIn *no = (NoVoiceIn *) hw;
@@ -109,37 +102,44 @@ static void no_enable_in(HWVoiceIn *hw, bool enable)
}
}
static void audio_none_class_init(ObjectClass *klass, const void *data)
static void *no_audio_init(Audiodev *dev, Error **errp)
{
AudioMixengBackendClass *k = AUDIO_MIXENG_BACKEND_CLASS(klass);
k->max_voices_out = INT_MAX;
k->max_voices_in = INT_MAX;
k->voice_size_out = sizeof(NoVoiceOut);
k->voice_size_in = sizeof(NoVoiceIn);
k->init_out = no_init_out;
k->fini_out = no_fini_out;
k->write = no_write;
k->buffer_get_free = audio_generic_buffer_get_free;
k->run_buffer_out = audio_generic_run_buffer_out;
k->enable_out = no_enable_out;
k->init_in = no_init_in;
k->fini_in = no_fini_in;
k->read = no_read;
k->run_buffer_in = audio_generic_run_buffer_in;
k->enable_in = no_enable_in;
return &no_audio_init;
}
static const TypeInfo audio_types[] = {
{
.name = TYPE_AUDIO_NONE,
.parent = TYPE_AUDIO_MIXENG_BACKEND,
.instance_size = sizeof(AudioNone),
.class_init = audio_none_class_init,
},
static void no_audio_fini (void *opaque)
{
(void) opaque;
}
static struct audio_pcm_ops no_pcm_ops = {
.init_out = no_init_out,
.fini_out = no_fini_out,
.write = no_write,
.buffer_get_free = audio_generic_buffer_get_free,
.run_buffer_out = audio_generic_run_buffer_out,
.enable_out = no_enable_out,
.init_in = no_init_in,
.fini_in = no_fini_in,
.read = no_read,
.run_buffer_in = audio_generic_run_buffer_in,
.enable_in = no_enable_in
};
DEFINE_TYPES(audio_types)
module_obj(TYPE_AUDIO_NONE);
static struct audio_driver no_audio_driver = {
.name = "none",
.init = no_audio_init,
.fini = no_audio_fini,
.pcm_ops = &no_pcm_ops,
.max_voices_out = INT_MAX,
.max_voices_in = INT_MAX,
.voice_size_out = sizeof (NoVoiceOut),
.voice_size_in = sizeof (NoVoiceIn)
};
static void register_audio_none(void)
{
audio_driver_register(&no_audio_driver);
}
type_init(register_audio_none);
+153 -147
View File
@@ -23,7 +23,6 @@
*/
#include "qemu/osdep.h"
#include "qapi-types-audio.h"
#include <sys/ioctl.h>
#include <sys/soundcard.h>
#include "qemu/main-loop.h"
@@ -31,20 +30,10 @@
#include "qemu/host-utils.h"
#include "qapi/error.h"
#include "qemu/audio.h"
#include "qemu/error-report.h"
#include "qom/object.h"
#include "audio_int.h"
#include "trace.h"
#define TYPE_AUDIO_OSS "audio-oss"
OBJECT_DECLARE_SIMPLE_TYPE(AudioOss, AUDIO_OSS)
static AudioBackendClass *audio_oss_parent_class;
struct AudioOss {
AudioMixengBackend parent_obj;
};
#define AUDIO_CAP "oss"
#include "audio_int.h"
#if defined OSS_GETVERSION && defined SNDCTL_DSP_POLICY
#define USE_DSP_POLICY
@@ -75,53 +64,56 @@ struct oss_params {
int fragsize;
};
static void G_GNUC_PRINTF(2, 3) oss_logerr(int err, const char *fmt, ...)
static void G_GNUC_PRINTF (2, 3) oss_logerr (int err, const char *fmt, ...)
{
va_list ap;
error_printf("oss: ");
va_start(ap, fmt);
error_vprintf(fmt, ap);
va_end(ap);
va_start (ap, fmt);
AUD_vlog (AUDIO_CAP, fmt, ap);
va_end (ap);
error_printf(" Reason: %s\n", strerror(err));
AUD_log (AUDIO_CAP, "Reason: %s\n", strerror (err));
}
static void G_GNUC_PRINTF(3, 4) oss_logerr2(int err, const char *typ,
const char *fmt, ...)
static void G_GNUC_PRINTF (3, 4) oss_logerr2 (
int err,
const char *typ,
const char *fmt,
...
)
{
va_list ap;
error_printf("oss: Could not initialize %s: ", typ);
AUD_log (AUDIO_CAP, "Could not initialize %s\n", typ);
va_start(ap, fmt);
error_vprintf(fmt, ap);
va_end(ap);
va_start (ap, fmt);
AUD_vlog (AUDIO_CAP, fmt, ap);
va_end (ap);
error_printf(" Reason: %s\n", strerror(err));
AUD_log (AUDIO_CAP, "Reason: %s\n", strerror (err));
}
static void oss_anal_close(int *fdp)
static void oss_anal_close (int *fdp)
{
int err;
qemu_set_fd_handler(*fdp, NULL, NULL, NULL);
err = close(*fdp);
qemu_set_fd_handler (*fdp, NULL, NULL, NULL);
err = close (*fdp);
if (err) {
oss_logerr(errno, "Failed to close file(fd=%d)", *fdp);
oss_logerr (errno, "Failed to close file(fd=%d)\n", *fdp);
}
*fdp = -1;
}
static void oss_helper_poll_out (void *opaque)
{
AudioMixengBackend *s = opaque;
AudioBackend *s = opaque;
audio_run(s, "oss_poll_out");
}
static void oss_helper_poll_in (void *opaque)
{
AudioMixengBackend *s = opaque;
AudioBackend *s = opaque;
audio_run(s, "oss_poll_in");
}
@@ -155,52 +147,69 @@ static int aud_to_ossfmt(AudioFormat fmt, bool big_endian)
return big_endian ? AFMT_U16_BE : AFMT_U16_LE;
default:
error_report("oss: Internal logic error: Bad audio format %d", fmt);
dolog ("Internal logic error: Bad audio format %d\n", fmt);
#ifdef DEBUG_AUDIO
abort ();
#endif
return AFMT_U8;
}
}
static int oss_to_audfmt (int ossfmt, AudioFormat *fmt, bool *big_endian)
static int oss_to_audfmt (int ossfmt, AudioFormat *fmt, int *endianness)
{
switch (ossfmt) {
case AFMT_S8:
*big_endian = false;
*endianness = 0;
*fmt = AUDIO_FORMAT_S8;
break;
case AFMT_U8:
*big_endian = false;
*endianness = 0;
*fmt = AUDIO_FORMAT_U8;
break;
case AFMT_S16_LE:
*big_endian = false;
*endianness = 0;
*fmt = AUDIO_FORMAT_S16;
break;
case AFMT_U16_LE:
*big_endian = false;
*endianness = 0;
*fmt = AUDIO_FORMAT_U16;
break;
case AFMT_S16_BE:
*big_endian = true;
*endianness = 1;
*fmt = AUDIO_FORMAT_S16;
break;
case AFMT_U16_BE:
*big_endian = true;
*endianness = 1;
*fmt = AUDIO_FORMAT_U16;
break;
default:
error_report("oss: Unrecognized audio format %d", ossfmt);
dolog ("Unrecognized audio format %d\n", ossfmt);
return -1;
}
return 0;
}
#if defined DEBUG_MISMATCHES || defined DEBUG
static void oss_dump_info (struct oss_params *req, struct oss_params *obt)
{
dolog ("parameter | requested value | obtained value\n");
dolog ("format | %10d | %10d\n", req->fmt, obt->fmt);
dolog ("channels | %10d | %10d\n",
req->nchannels, obt->nchannels);
dolog ("frequency | %10d | %10d\n", req->freq, obt->freq);
dolog ("nfrags | %10d | %10d\n", req->nfrags, obt->nfrags);
dolog ("fragsize | %10d | %10d\n",
req->fragsize, obt->fragsize);
}
#endif
#ifdef USE_DSP_POLICY
static int oss_get_version (int fd, int *version, const char *typ)
{
@@ -219,7 +228,7 @@ static int oss_get_version (int fd, int *version, const char *typ)
return 0;
}
#endif
oss_logerr2(errno, typ, "Failed to get OSS version");
oss_logerr2 (errno, typ, "Failed to get OSS version\n");
return -1;
}
return 0;
@@ -248,7 +257,7 @@ static int oss_open(int in, struct oss_params *req, audsettings *as,
fd = open (dspname, oflags | O_NONBLOCK);
if (-1 == fd) {
oss_logerr2(errno, typ, "Failed to open '%s'", dspname);
oss_logerr2 (errno, typ, "Failed to open `%s'\n", dspname);
return -1;
}
@@ -260,23 +269,23 @@ static int oss_open(int in, struct oss_params *req, audsettings *as,
qapi_AudiodevOssPerDirectionOptions_base(opdo), as, 23220);
if (ioctl (fd, SNDCTL_DSP_SAMPLESIZE, &fmt)) {
oss_logerr2(errno, typ, "Failed to set sample size %d", req->fmt);
oss_logerr2 (errno, typ, "Failed to set sample size %d\n", req->fmt);
goto err;
}
if (ioctl (fd, SNDCTL_DSP_CHANNELS, &nchannels)) {
oss_logerr2(errno, typ, "Failed to set number of channels %d",
req->nchannels);
oss_logerr2 (errno, typ, "Failed to set number of channels %d\n",
req->nchannels);
goto err;
}
if (ioctl (fd, SNDCTL_DSP_SPEED, &freq)) {
oss_logerr2(errno, typ, "Failed to set frequency %d", req->freq);
oss_logerr2 (errno, typ, "Failed to set frequency %d\n", req->freq);
goto err;
}
if (ioctl (fd, SNDCTL_DSP_NONBLOCK, NULL)) {
oss_logerr2(errno, typ, "Failed to set non-blocking mode");
oss_logerr2 (errno, typ, "Failed to set non-blocking mode\n");
goto err;
}
@@ -290,9 +299,9 @@ static int oss_open(int in, struct oss_params *req, audsettings *as,
if (version >= 0x040000) {
int policy2 = policy;
if (ioctl(fd, SNDCTL_DSP_POLICY, &policy2)) {
oss_logerr2(errno, typ,
"Failed to set timing policy to %d",
policy);
oss_logerr2 (errno, typ,
"Failed to set timing policy to %d\n",
policy);
goto err;
}
setfragment = 0;
@@ -304,20 +313,20 @@ static int oss_open(int in, struct oss_params *req, audsettings *as,
if (setfragment) {
int mmmmssss = (req->nfrags << 16) | ctz32 (req->fragsize);
if (ioctl (fd, SNDCTL_DSP_SETFRAGMENT, &mmmmssss)) {
oss_logerr2(errno, typ, "Failed to set buffer length (%d, %d)",
req->nfrags, req->fragsize);
oss_logerr2 (errno, typ, "Failed to set buffer length (%d, %d)\n",
req->nfrags, req->fragsize);
goto err;
}
}
if (ioctl (fd, in ? SNDCTL_DSP_GETISPACE : SNDCTL_DSP_GETOSPACE, &abinfo)) {
oss_logerr2(errno, typ, "Failed to get buffer length");
oss_logerr2 (errno, typ, "Failed to get buffer length\n");
goto err;
}
if (!abinfo.fragstotal || !abinfo.fragsize) {
error_report("oss: Returned bogus buffer information(%d, %d) for %s",
abinfo.fragstotal, abinfo.fragsize, typ);
AUD_log (AUDIO_CAP, "Returned bogus buffer information(%d, %d) for %s\n",
abinfo.fragstotal, abinfo.fragsize, typ);
goto err;
}
@@ -328,13 +337,20 @@ static int oss_open(int in, struct oss_params *req, audsettings *as,
obt->fragsize = abinfo.fragsize;
*pfd = fd;
trace_oss_out_params(
req->fmt, obt->fmt,
req->nchannels, obt->nchannels,
req->freq, obt->freq,
req->nfrags, obt->nfrags,
req->fragsize, obt->fragsize);
#ifdef DEBUG_MISMATCHES
if ((req->fmt != obt->fmt) ||
(req->nchannels != obt->nchannels) ||
(req->freq != obt->freq) ||
(req->fragsize != obt->fragsize) ||
(req->nfrags != obt->nfrags)) {
dolog ("Audio parameters mismatch\n");
oss_dump_info (req, obt);
}
#endif
#ifdef DEBUG
oss_dump_info (req, obt);
#endif
return 0;
err:
@@ -350,7 +366,7 @@ static size_t oss_get_available_bytes(OSSVoiceOut *oss)
err = ioctl(oss->fd, SNDCTL_DSP_GETOPTR, &cntinfo);
if (err < 0) {
oss_logerr(errno, "SNDCTL_DSP_GETOPTR failed");
oss_logerr(errno, "SNDCTL_DSP_GETOPTR failed\n");
return 0;
}
@@ -431,7 +447,8 @@ static size_t oss_write(HWVoiceOut *hw, void *buf, size_t len)
bytes_written = write(oss->fd, pcm, len);
if (bytes_written < 0) {
if (errno != EAGAIN) {
oss_logerr(errno, "failed to write %zu bytes", len);
oss_logerr(errno, "failed to write %zu bytes\n",
len);
}
return pos;
}
@@ -445,37 +462,38 @@ static size_t oss_write(HWVoiceOut *hw, void *buf, size_t len)
return pos;
}
static void oss_fini_out(HWVoiceOut *hw)
static void oss_fini_out (HWVoiceOut *hw)
{
int err;
OSSVoiceOut *oss = (OSSVoiceOut *)hw;
OSSVoiceOut *oss = (OSSVoiceOut *) hw;
trace_oss_fini_out();
oss_anal_close(&oss->fd);
ldebug ("oss_fini\n");
oss_anal_close (&oss->fd);
if (oss->mmapped && hw->buf_emul) {
err = munmap(hw->buf_emul, hw->size_emul);
if (err) {
oss_logerr(errno, "Failed to unmap buffer %p, size %zu",
oss_logerr(errno, "Failed to unmap buffer %p, size %zu\n",
hw->buf_emul, hw->size_emul);
}
hw->buf_emul = NULL;
}
}
static int oss_init_out(HWVoiceOut *hw, struct audsettings *as)
static int oss_init_out(HWVoiceOut *hw, struct audsettings *as,
void *drv_opaque)
{
OSSVoiceOut *oss = (OSSVoiceOut *) hw;
struct oss_params req, obt;
int err;
int fd;
struct audsettings obt_as;
Audiodev *dev = hw->s->dev;
Audiodev *dev = drv_opaque;
AudiodevOssOptions *oopts = &dev->u.oss;
oss->fd = -1;
req.fmt = aud_to_ossfmt (as->fmt, as->big_endian);
req.fmt = aud_to_ossfmt (as->fmt, as->endianness);
req.freq = as->freq;
req.nchannels = as->nchannels;
@@ -483,7 +501,7 @@ static int oss_init_out(HWVoiceOut *hw, struct audsettings *as)
return -1;
}
err = oss_to_audfmt(obt.fmt, &obt_as.fmt, &obt_as.big_endian);
err = oss_to_audfmt(obt.fmt, &obt_as.fmt, &obt_as.endianness);
if (err) {
oss_anal_close (&fd);
return -1;
@@ -497,8 +515,8 @@ static int oss_init_out(HWVoiceOut *hw, struct audsettings *as)
oss->fragsize = obt.fragsize;
if (obt.nfrags * obt.fragsize % hw->info.bytes_per_frame) {
warn_report("oss: Misaligned DAC buffer, size %d, alignment %d",
obt.nfrags * obt.fragsize, hw->info.bytes_per_frame);
dolog ("warning: Misaligned DAC buffer, size %d, alignment %d\n",
obt.nfrags * obt.fragsize, hw->info.bytes_per_frame);
}
hw->samples = (obt.nfrags * obt.fragsize) / hw->info.bytes_per_frame;
@@ -515,16 +533,20 @@ static int oss_init_out(HWVoiceOut *hw, struct audsettings *as)
0
);
if (hw->buf_emul == MAP_FAILED) {
oss_logerr(errno, "Failed to map %zu bytes of DAC", hw->size_emul);
oss_logerr(errno, "Failed to map %zu bytes of DAC\n",
hw->size_emul);
hw->buf_emul = NULL;
} else {
int trig = 0;
if (ioctl (fd, SNDCTL_DSP_SETTRIGGER, &trig) < 0) {
oss_logerr(errno, "SNDCTL_DSP_SETTRIGGER 0 failed");
oss_logerr (errno, "SNDCTL_DSP_SETTRIGGER 0 failed\n");
} else {
trig = PCM_ENABLE_OUTPUT;
if (ioctl(fd, SNDCTL_DSP_SETTRIGGER, &trig) < 0) {
oss_logerr(errno, "SNDCTL_DSP_SETTRIGGER PCM_ENABLE_OUTPUT failed");
if (ioctl (fd, SNDCTL_DSP_SETTRIGGER, &trig) < 0) {
oss_logerr (
errno,
"SNDCTL_DSP_SETTRIGGER PCM_ENABLE_OUTPUT failed\n"
);
} else {
oss->mmapped = 1;
}
@@ -533,7 +555,7 @@ static int oss_init_out(HWVoiceOut *hw, struct audsettings *as)
if (!oss->mmapped) {
err = munmap(hw->buf_emul, hw->size_emul);
if (err) {
oss_logerr(errno, "Failed to unmap buffer %p size %zu",
oss_logerr(errno, "Failed to unmap buffer %p size %zu\n",
hw->buf_emul, hw->size_emul);
}
hw->buf_emul = NULL;
@@ -549,14 +571,13 @@ static int oss_init_out(HWVoiceOut *hw, struct audsettings *as)
static void oss_enable_out(HWVoiceOut *hw, bool enable)
{
int trig;
OSSVoiceOut *oss = (OSSVoiceOut *)hw;
OSSVoiceOut *oss = (OSSVoiceOut *) hw;
AudiodevOssPerDirectionOptions *opdo = oss->dev->u.oss.out;
trace_oss_enable_out(enable);
if (enable) {
hw->poll_mode = opdo->try_poll;
ldebug("enabling voice\n");
if (hw->poll_mode) {
oss_poll_out(hw);
}
@@ -569,12 +590,12 @@ static void oss_enable_out(HWVoiceOut *hw, bool enable)
trig = PCM_ENABLE_OUTPUT;
if (ioctl(oss->fd, SNDCTL_DSP_SETTRIGGER, &trig) < 0) {
oss_logerr(errno,
"SNDCTL_DSP_SETTRIGGER PCM_ENABLE_OUTPUT failed");
"SNDCTL_DSP_SETTRIGGER PCM_ENABLE_OUTPUT failed\n");
return;
}
} else {
if (hw->poll_mode) {
qemu_set_fd_handler(oss->fd, NULL, NULL, NULL);
qemu_set_fd_handler (oss->fd, NULL, NULL, NULL);
hw->poll_mode = 0;
}
@@ -582,33 +603,34 @@ static void oss_enable_out(HWVoiceOut *hw, bool enable)
return;
}
ldebug ("disabling voice\n");
trig = 0;
if (ioctl(oss->fd, SNDCTL_DSP_SETTRIGGER, &trig) < 0) {
oss_logerr(errno, "SNDCTL_DSP_SETTRIGGER 0 failed");
if (ioctl (oss->fd, SNDCTL_DSP_SETTRIGGER, &trig) < 0) {
oss_logerr (errno, "SNDCTL_DSP_SETTRIGGER 0 failed\n");
return;
}
}
}
static int oss_init_in(HWVoiceIn *hw, struct audsettings *as)
static int oss_init_in(HWVoiceIn *hw, struct audsettings *as, void *drv_opaque)
{
OSSVoiceIn *oss = (OSSVoiceIn *) hw;
struct oss_params req, obt;
int err;
int fd;
struct audsettings obt_as;
Audiodev *dev = hw->s->dev;
Audiodev *dev = drv_opaque;
oss->fd = -1;
req.fmt = aud_to_ossfmt (as->fmt, as->big_endian);
req.fmt = aud_to_ossfmt (as->fmt, as->endianness);
req.freq = as->freq;
req.nchannels = as->nchannels;
if (oss_open(1, &req, as, &obt, &fd, dev)) {
return -1;
}
err = oss_to_audfmt(obt.fmt, &obt_as.fmt, &obt_as.big_endian);
err = oss_to_audfmt(obt.fmt, &obt_as.fmt, &obt_as.endianness);
if (err) {
oss_anal_close (&fd);
return -1;
@@ -621,16 +643,9 @@ static int oss_init_in(HWVoiceIn *hw, struct audsettings *as)
oss->nfrags = obt.nfrags;
oss->fragsize = obt.fragsize;
trace_oss_in_params(
req.fmt, obt.fmt,
req.nchannels, obt.nchannels,
req.freq, obt.freq,
req.nfrags, obt.nfrags,
req.fragsize, obt.fragsize);
if (obt.nfrags * obt.fragsize % hw->info.bytes_per_frame) {
warn_report("oss: Misaligned ADC buffer, size %d, alignment %d",
obt.nfrags * obt.fragsize, hw->info.bytes_per_frame);
dolog ("warning: Misaligned ADC buffer, size %d, alignment %d\n",
obt.nfrags * obt.fragsize, hw->info.bytes_per_frame);
}
hw->samples = (obt.nfrags * obt.fragsize) / hw->info.bytes_per_frame;
@@ -664,7 +679,7 @@ static size_t oss_read(HWVoiceIn *hw, void *buf, size_t len)
case EAGAIN:
break;
default:
oss_logerr(errno, "Failed to read %zu bytes of audio (to %p)",
oss_logerr(errno, "Failed to read %zu bytes of audio (to %p)\n",
len, dst);
break;
}
@@ -680,11 +695,9 @@ static size_t oss_read(HWVoiceIn *hw, void *buf, size_t len)
static void oss_enable_in(HWVoiceIn *hw, bool enable)
{
OSSVoiceIn *oss = (OSSVoiceIn *)hw;
OSSVoiceIn *oss = (OSSVoiceIn *) hw;
AudiodevOssPerDirectionOptions *opdo = oss->dev->u.oss.out;
trace_oss_enable_in(enable);
if (enable) {
hw->poll_mode = opdo->try_poll;
@@ -707,8 +720,7 @@ static void oss_init_per_direction(AudiodevOssPerDirectionOptions *opdo)
}
}
static bool
audio_oss_realize(AudioBackend *abe, Audiodev *dev, Error **errp)
static void *oss_audio_init(Audiodev *dev, Error **errp)
{
AudiodevOssOptions *oopts;
assert(dev->driver == AUDIODEV_DRIVER_OSS);
@@ -719,55 +731,49 @@ audio_oss_realize(AudioBackend *abe, Audiodev *dev, Error **errp)
if (access(oopts->in->dev ?: "/dev/dsp", R_OK | W_OK) < 0) {
error_setg_errno(errp, errno, "%s not accessible", oopts->in->dev ?: "/dev/dsp");
qapi_free_Audiodev(dev);
return false;
return NULL;
}
if (access(oopts->out->dev ?: "/dev/dsp", R_OK | W_OK) < 0) {
error_setg_errno(errp, errno, "%s not accessible", oopts->out->dev ?: "/dev/dsp");
qapi_free_Audiodev(dev);
return false;
return NULL;
}
return audio_oss_parent_class->realize(abe, dev, errp);
return dev;
}
static void audio_oss_class_init(ObjectClass *klass, const void *data)
static void oss_audio_fini (void *opaque)
{
AudioBackendClass *b = AUDIO_BACKEND_CLASS(klass);
AudioMixengBackendClass *k = AUDIO_MIXENG_BACKEND_CLASS(klass);
audio_oss_parent_class = AUDIO_BACKEND_CLASS(object_class_get_parent(klass));
b->realize = audio_oss_realize;
k->max_voices_out = INT_MAX;
k->max_voices_in = INT_MAX;
k->voice_size_out = sizeof(OSSVoiceOut);
k->voice_size_in = sizeof(OSSVoiceIn);
k->init_out = oss_init_out;
k->fini_out = oss_fini_out;
k->write = oss_write;
k->buffer_get_free = oss_buffer_get_free;
k->run_buffer_out = oss_run_buffer_out;
k->get_buffer_out = oss_get_buffer_out;
k->put_buffer_out = oss_put_buffer_out;
k->enable_out = oss_enable_out;
k->init_in = oss_init_in;
k->fini_in = oss_fini_in;
k->read = oss_read;
k->run_buffer_in = audio_generic_run_buffer_in;
k->enable_in = oss_enable_in;
}
static const TypeInfo audio_types[] = {
{
.name = TYPE_AUDIO_OSS,
.parent = TYPE_AUDIO_MIXENG_BACKEND,
.instance_size = sizeof(AudioOss),
.class_init = audio_oss_class_init,
},
static struct audio_pcm_ops oss_pcm_ops = {
.init_out = oss_init_out,
.fini_out = oss_fini_out,
.write = oss_write,
.buffer_get_free = oss_buffer_get_free,
.run_buffer_out = oss_run_buffer_out,
.get_buffer_out = oss_get_buffer_out,
.put_buffer_out = oss_put_buffer_out,
.enable_out = oss_enable_out,
.init_in = oss_init_in,
.fini_in = oss_fini_in,
.read = oss_read,
.run_buffer_in = audio_generic_run_buffer_in,
.enable_in = oss_enable_in
};
DEFINE_TYPES(audio_types)
module_obj(TYPE_AUDIO_OSS);
static struct audio_driver oss_audio_driver = {
.name = "oss",
.init = oss_audio_init,
.fini = oss_audio_fini,
.pcm_ops = &oss_pcm_ops,
.max_voices_out = INT_MAX,
.max_voices_in = INT_MAX,
.voice_size_out = sizeof (OSSVoiceOut),
.voice_size_in = sizeof (OSSVoiceIn)
};
static void register_audio_oss(void)
{
audio_driver_register(&oss_audio_driver);
}
type_init(register_audio_oss);
+148 -141
View File
@@ -3,18 +3,12 @@
#include "qemu/osdep.h"
#include "qemu/module.h"
#include "qemu/audio.h"
#include "qemu/error-report.h"
#include "qapi/error.h"
#include "qom/object.h"
#include "audio_int.h"
#include <pulse/pulseaudio.h>
#define TYPE_AUDIO_PA "audio-pa"
OBJECT_DECLARE_SIMPLE_TYPE(AudioPa, AUDIO_PA)
static AudioBackendClass *audio_pa_parent_class;
#define AUDIO_CAP "pulseaudio"
#include "audio_int.h"
typedef struct PAConnection {
char *server;
@@ -25,19 +19,18 @@ typedef struct PAConnection {
pa_context *context;
} PAConnection;
struct AudioPa {
AudioMixengBackend parent_obj;
PAConnection *conn;
};
static QTAILQ_HEAD(PAConnectionHead, PAConnection) pa_conns =
QTAILQ_HEAD_INITIALIZER(pa_conns);
typedef struct {
Audiodev *dev;
PAConnection *conn;
} paaudio;
typedef struct {
HWVoiceOut hw;
pa_stream *stream;
AudioPa *g;
paaudio *g;
} PAVoiceOut;
typedef struct {
@@ -45,23 +38,42 @@ typedef struct {
pa_stream *stream;
const void *read_data;
size_t read_length;
AudioPa *g;
paaudio *g;
} PAVoiceIn;
static void qpa_conn_fini(PAConnection *c);
static void G_GNUC_PRINTF(2, 3) qpa_logerr(int err, const char *fmt, ...)
static void G_GNUC_PRINTF (2, 3) qpa_logerr (int err, const char *fmt, ...)
{
va_list ap;
error_printf("pulseaudio: ");
va_start(ap, fmt);
error_vprintf(fmt, ap);
va_end(ap);
va_start (ap, fmt);
AUD_vlog (AUDIO_CAP, fmt, ap);
va_end (ap);
error_printf(" Reason: %s\n", pa_strerror(err));
AUD_log (AUDIO_CAP, "Reason: %s\n", pa_strerror (err));
}
#ifndef PA_CONTEXT_IS_GOOD
static inline int PA_CONTEXT_IS_GOOD(pa_context_state_t x)
{
return
x == PA_CONTEXT_CONNECTING ||
x == PA_CONTEXT_AUTHORIZING ||
x == PA_CONTEXT_SETTING_NAME ||
x == PA_CONTEXT_READY;
}
#endif
#ifndef PA_STREAM_IS_GOOD
static inline int PA_STREAM_IS_GOOD(pa_stream_state_t x)
{
return
x == PA_STREAM_CREATING ||
x == PA_STREAM_READY;
}
#endif
#define CHECK_SUCCESS_GOTO(c, expression, label, msg) \
do { \
if (!(expression)) { \
@@ -93,12 +105,12 @@ static void *qpa_get_buffer_in(HWVoiceIn *hw, size_t *size)
pa_threaded_mainloop_lock(c->mainloop);
CHECK_DEAD_GOTO(c, p->stream, unlock_and_fail,
"pa_threaded_mainloop_lock failed");
"pa_threaded_mainloop_lock failed\n");
if (!p->read_length) {
r = pa_stream_peek(p->stream, &p->read_data, &p->read_length);
CHECK_SUCCESS_GOTO(c, r == 0, unlock_and_fail,
"pa_stream_peek failed");
"pa_stream_peek failed\n");
}
*size = MIN(p->read_length, *size);
@@ -121,7 +133,7 @@ static void qpa_put_buffer_in(HWVoiceIn *hw, void *buf, size_t size)
pa_threaded_mainloop_lock(c->mainloop);
CHECK_DEAD_GOTO(c, p->stream, unlock,
"pa_threaded_mainloop_lock failed");
"pa_threaded_mainloop_lock failed\n");
assert(buf == p->read_data && size <= p->read_length);
@@ -130,7 +142,7 @@ static void qpa_put_buffer_in(HWVoiceIn *hw, void *buf, size_t size)
if (size && !p->read_length) {
r = pa_stream_drop(p->stream);
CHECK_SUCCESS_GOTO(c, r == 0, unlock, "pa_stream_drop failed");
CHECK_SUCCESS_GOTO(c, r == 0, unlock, "pa_stream_drop failed\n");
}
unlock:
@@ -146,7 +158,7 @@ static size_t qpa_read(HWVoiceIn *hw, void *data, size_t length)
pa_threaded_mainloop_lock(c->mainloop);
CHECK_DEAD_GOTO(c, p->stream, unlock_and_fail,
"pa_threaded_mainloop_lock failed");
"pa_threaded_mainloop_lock failed\n");
if (pa_stream_get_state(p->stream) != PA_STREAM_READY) {
/* wait for stream to become ready */
goto unlock;
@@ -159,7 +171,7 @@ static size_t qpa_read(HWVoiceIn *hw, void *data, size_t length)
if (!p->read_length) {
r = pa_stream_peek(p->stream, &p->read_data, &p->read_length);
CHECK_SUCCESS_GOTO(c, r == 0, unlock_and_fail,
"pa_stream_peek failed");
"pa_stream_peek failed\n");
if (!p->read_length) {
/* buffer is empty */
break;
@@ -176,7 +188,7 @@ static size_t qpa_read(HWVoiceIn *hw, void *data, size_t length)
if (!p->read_length) {
r = pa_stream_drop(p->stream);
CHECK_SUCCESS_GOTO(c, r == 0, unlock_and_fail,
"pa_stream_drop failed");
"pa_stream_drop failed\n");
}
}
@@ -198,7 +210,7 @@ static size_t qpa_buffer_get_free(HWVoiceOut *hw)
pa_threaded_mainloop_lock(c->mainloop);
CHECK_DEAD_GOTO(c, p->stream, unlock_and_fail,
"pa_threaded_mainloop_lock failed");
"pa_threaded_mainloop_lock failed\n");
if (pa_stream_get_state(p->stream) != PA_STREAM_READY) {
/* wait for stream to become ready */
l = 0;
@@ -207,7 +219,7 @@ static size_t qpa_buffer_get_free(HWVoiceOut *hw)
l = pa_stream_writable_size(p->stream);
CHECK_SUCCESS_GOTO(c, l != (size_t) -1, unlock_and_fail,
"pa_stream_writable_size failed");
"pa_stream_writable_size failed\n");
unlock:
pa_threaded_mainloop_unlock(c->mainloop);
@@ -228,12 +240,12 @@ static void *qpa_get_buffer_out(HWVoiceOut *hw, size_t *size)
pa_threaded_mainloop_lock(c->mainloop);
CHECK_DEAD_GOTO(c, p->stream, unlock_and_fail,
"pa_threaded_mainloop_lock failed");
"pa_threaded_mainloop_lock failed\n");
*size = -1;
r = pa_stream_begin_write(p->stream, &ret, size);
CHECK_SUCCESS_GOTO(c, r >= 0, unlock_and_fail,
"pa_stream_begin_write failed");
"pa_stream_begin_write failed\n");
pa_threaded_mainloop_unlock(c->mainloop);
return ret;
@@ -253,10 +265,10 @@ static size_t qpa_put_buffer_out(HWVoiceOut *hw, void *data, size_t length)
pa_threaded_mainloop_lock(c->mainloop);
CHECK_DEAD_GOTO(c, p->stream, unlock_and_fail,
"pa_threaded_mainloop_lock failed");
"pa_threaded_mainloop_lock failed\n");
r = pa_stream_write(p->stream, data, length, NULL, 0LL, PA_SEEK_RELATIVE);
CHECK_SUCCESS_GOTO(c, r >= 0, unlock_and_fail, "pa_stream_write failed");
CHECK_SUCCESS_GOTO(c, r >= 0, unlock_and_fail, "pa_stream_write failed\n");
pa_threaded_mainloop_unlock(c->mainloop);
return length;
@@ -276,7 +288,7 @@ static size_t qpa_write(HWVoiceOut *hw, void *data, size_t length)
pa_threaded_mainloop_lock(c->mainloop);
CHECK_DEAD_GOTO(c, p->stream, unlock_and_fail,
"pa_threaded_mainloop_lock failed");
"pa_threaded_mainloop_lock failed\n");
if (pa_stream_get_state(p->stream) != PA_STREAM_READY) {
/* wait for stream to become ready */
l = 0;
@@ -286,14 +298,14 @@ static size_t qpa_write(HWVoiceOut *hw, void *data, size_t length)
l = pa_stream_writable_size(p->stream);
CHECK_SUCCESS_GOTO(c, l != (size_t) -1, unlock_and_fail,
"pa_stream_writable_size failed");
"pa_stream_writable_size failed\n");
if (l > length) {
l = length;
}
r = pa_stream_write(p->stream, data, l, NULL, 0LL, PA_SEEK_RELATIVE);
CHECK_SUCCESS_GOTO(c, r >= 0, unlock_and_fail, "pa_stream_write failed");
CHECK_SUCCESS_GOTO(c, r >= 0, unlock_and_fail, "pa_stream_write failed\n");
unlock:
pa_threaded_mainloop_unlock(c->mainloop);
@@ -325,43 +337,43 @@ static pa_sample_format_t audfmt_to_pa(AudioFormat afmt, bool big_endian)
format = big_endian ? PA_SAMPLE_FLOAT32BE : PA_SAMPLE_FLOAT32LE;
break;
default:
error_report("pulseaudio: Internal logic error: Bad audio format %d", afmt);
dolog ("Internal logic error: Bad audio format %d\n", afmt);
format = PA_SAMPLE_U8;
break;
}
return format;
}
static AudioFormat pa_to_audfmt (pa_sample_format_t fmt, bool *big_endian)
static AudioFormat pa_to_audfmt (pa_sample_format_t fmt, int *endianness)
{
switch (fmt) {
case PA_SAMPLE_U8:
return AUDIO_FORMAT_U8;
case PA_SAMPLE_S16BE:
*big_endian = true;
*endianness = 1;
return AUDIO_FORMAT_S16;
case PA_SAMPLE_S16LE:
*big_endian = false;
*endianness = 0;
return AUDIO_FORMAT_S16;
case PA_SAMPLE_S32BE:
*big_endian = true;
*endianness = 1;
return AUDIO_FORMAT_S32;
case PA_SAMPLE_S32LE:
*big_endian = false;
*endianness = 0;
return AUDIO_FORMAT_S32;
case PA_SAMPLE_FLOAT32BE:
*big_endian = true;
*endianness = 1;
return AUDIO_FORMAT_F32;
case PA_SAMPLE_FLOAT32LE:
*big_endian = false;
*endianness = 0;
return AUDIO_FORMAT_F32;
default:
error_report("pulseaudio: Internal logic error: Bad pa_sample_format %d", fmt);
dolog ("Internal logic error: Bad pa_sample_format %d\n", fmt);
return AUDIO_FORMAT_U8;
}
}
static void context_state_cb(pa_context *c, void *userdata)
static void context_state_cb (pa_context *c, void *userdata)
{
PAConnection *conn = userdata;
@@ -453,7 +465,7 @@ static pa_stream *qpa_simple_new (
break;
default:
error_report("pulseaudio: unsupported channel count %d", ss->channels);
dolog("Internal error: unsupported channel count %d\n", ss->channels);
goto fail;
}
@@ -497,35 +509,34 @@ fail:
return NULL;
}
static int qpa_init_out(HWVoiceOut *hw, struct audsettings *as)
static int qpa_init_out(HWVoiceOut *hw, struct audsettings *as,
void *drv_opaque)
{
AudioMixengBackend *amb = hw->s;
AudioPa *apa = AUDIO_PA(amb);
int error;
pa_sample_spec ss;
pa_buffer_attr ba;
struct audsettings obt_as = *as;
PAVoiceOut *pa = (PAVoiceOut *) hw;
AudiodevPaOptions *popts = &amb->dev->u.pa;
paaudio *g = pa->g = drv_opaque;
AudiodevPaOptions *popts = &g->dev->u.pa;
AudiodevPaPerDirectionOptions *ppdo = popts->out;
PAConnection *c = apa->conn;
PAConnection *c = g->conn;
pa->g = apa;
ss.format = audfmt_to_pa (as->fmt, as->big_endian);
ss.format = audfmt_to_pa (as->fmt, as->endianness);
ss.channels = as->nchannels;
ss.rate = as->freq;
ba.tlength = pa_usec_to_bytes(ppdo->latency, &ss);
ba.minreq = pa_usec_to_bytes(MIN(ppdo->latency >> 2,
(amb->dev->timer_period >> 2) * 3), &ss);
(g->dev->timer_period >> 2) * 3), &ss);
ba.maxlength = -1;
ba.prebuf = -1;
obt_as.fmt = pa_to_audfmt (ss.format, &obt_as.big_endian);
obt_as.fmt = pa_to_audfmt (ss.format, &obt_as.endianness);
pa->stream = qpa_simple_new (
c,
ppdo->stream_name ?: amb->dev->id,
ppdo->stream_name ?: g->dev->id,
PA_STREAM_PLAYBACK,
ppdo->name,
&ss,
@@ -533,7 +544,7 @@ static int qpa_init_out(HWVoiceOut *hw, struct audsettings *as)
&error
);
if (!pa->stream) {
qpa_logerr(error, "pa_simple_new for playback failed");
qpa_logerr (error, "pa_simple_new for playback failed\n");
goto fail1;
}
@@ -548,35 +559,33 @@ static int qpa_init_out(HWVoiceOut *hw, struct audsettings *as)
return -1;
}
static int qpa_init_in(HWVoiceIn *hw, struct audsettings *as)
static int qpa_init_in(HWVoiceIn *hw, struct audsettings *as, void *drv_opaque)
{
AudioMixengBackend *amb = hw->s;
AudioPa *apa = AUDIO_PA(amb);
int error;
pa_sample_spec ss;
pa_buffer_attr ba;
struct audsettings obt_as = *as;
PAVoiceIn *pa = (PAVoiceIn *) hw;
AudiodevPaOptions *popts = &amb->dev->u.pa;
paaudio *g = pa->g = drv_opaque;
AudiodevPaOptions *popts = &g->dev->u.pa;
AudiodevPaPerDirectionOptions *ppdo = popts->in;
PAConnection *c = apa->conn;
PAConnection *c = g->conn;
pa->g = apa;
ss.format = audfmt_to_pa (as->fmt, as->big_endian);
ss.format = audfmt_to_pa (as->fmt, as->endianness);
ss.channels = as->nchannels;
ss.rate = as->freq;
ba.fragsize = pa_usec_to_bytes((amb->dev->timer_period >> 1) * 3, &ss);
ba.fragsize = pa_usec_to_bytes((g->dev->timer_period >> 1) * 3, &ss);
ba.maxlength = pa_usec_to_bytes(
MAX(ppdo->latency, amb->dev->timer_period * 3), &ss);
MAX(ppdo->latency, g->dev->timer_period * 3), &ss);
ba.minreq = -1;
ba.prebuf = -1;
obt_as.fmt = pa_to_audfmt (ss.format, &obt_as.big_endian);
obt_as.fmt = pa_to_audfmt (ss.format, &obt_as.endianness);
pa->stream = qpa_simple_new (
c,
ppdo->stream_name ?: amb->dev->id,
ppdo->stream_name ?: g->dev->id,
PA_STREAM_RECORD,
ppdo->name,
&ss,
@@ -584,7 +593,7 @@ static int qpa_init_in(HWVoiceIn *hw, struct audsettings *as)
&error
);
if (!pa->stream) {
qpa_logerr(error, "pa_simple_new for capture failed");
qpa_logerr (error, "pa_simple_new for capture failed\n");
goto fail1;
}
@@ -613,7 +622,7 @@ static void qpa_simple_disconnect(PAConnection *c, pa_stream *stream)
err = pa_stream_disconnect(stream);
if (err != 0) {
error_report("pulseaudio: Failed to disconnect! err=%d", err);
dolog("Failed to disconnect! err=%d\n", err);
}
pa_stream_unref(stream);
}
@@ -644,7 +653,7 @@ static void qpa_fini_in (HWVoiceIn *hw)
int r = pa_stream_drop(pa->stream);
if (r) {
qpa_logerr(pa_context_errno(c->context),
"pa_stream_drop failed");
"pa_stream_drop failed\n");
}
pa->read_length = 0;
}
@@ -662,7 +671,9 @@ static void qpa_volume_out(HWVoiceOut *hw, Volume *vol)
PAConnection *c = pa->g->conn;
int i;
pa_cvolume_init(&v);
#ifdef PA_CHECK_VERSION /* macro is present in 0.9.16+ */
pa_cvolume_init (&v); /* function is present in 0.9.13+ */
#endif
v.channels = vol->channels;
for (i = 0; i < vol->channels; ++i) {
@@ -676,7 +687,7 @@ static void qpa_volume_out(HWVoiceOut *hw, Volume *vol)
&v, NULL, NULL);
if (!op) {
qpa_logerr(pa_context_errno(c->context),
"set_sink_input_volume() failed");
"set_sink_input_volume() failed\n");
} else {
pa_operation_unref(op);
}
@@ -686,7 +697,7 @@ static void qpa_volume_out(HWVoiceOut *hw, Volume *vol)
vol->mute, NULL, NULL);
if (!op) {
qpa_logerr(pa_context_errno(c->context),
"set_sink_input_mute() failed");
"set_sink_input_mute() failed\n");
} else {
pa_operation_unref(op);
}
@@ -702,7 +713,9 @@ static void qpa_volume_in(HWVoiceIn *hw, Volume *vol)
PAConnection *c = pa->g->conn;
int i;
pa_cvolume_init(&v);
#ifdef PA_CHECK_VERSION
pa_cvolume_init (&v);
#endif
v.channels = vol->channels;
for (i = 0; i < vol->channels; ++i) {
@@ -716,7 +729,7 @@ static void qpa_volume_in(HWVoiceIn *hw, Volume *vol)
&v, NULL, NULL);
if (!op) {
qpa_logerr(pa_context_errno(c->context),
"set_source_output_volume() failed");
"set_source_output_volume() failed\n");
} else {
pa_operation_unref(op);
}
@@ -726,7 +739,7 @@ static void qpa_volume_in(HWVoiceIn *hw, Volume *vol)
vol->mute, NULL, NULL);
if (!op) {
qpa_logerr(pa_context_errno(c->context),
"set_source_output_mute() failed");
"set_source_output_mute() failed\n");
} else {
pa_operation_unref(op);
}
@@ -764,7 +777,7 @@ static void *qpa_conn_init(const char *server)
if (pa_context_connect(c->context, server, 0, NULL) < 0) {
qpa_logerr(pa_context_errno(c->context),
"pa_context_connect() failed");
"pa_context_connect() failed\n");
goto fail;
}
@@ -785,7 +798,7 @@ static void *qpa_conn_init(const char *server)
if (!PA_CONTEXT_IS_GOOD(state)) {
qpa_logerr(pa_context_errno(c->context),
"Wrong context state");
"Wrong context state\n");
goto unlock_and_fail;
}
@@ -799,24 +812,20 @@ static void *qpa_conn_init(const char *server)
unlock_and_fail:
pa_threaded_mainloop_unlock(c->mainloop);
fail:
AUD_log (AUDIO_CAP, "Failed to initialize PA context");
qpa_conn_fini(c);
return NULL;
}
static bool
audio_pa_realize(AudioBackend *abe, Audiodev *dev, Error **errp)
static void *qpa_audio_init(Audiodev *dev, Error **errp)
{
AudioPa *apa = AUDIO_PA(abe);
paaudio *g;
AudiodevPaOptions *popts = &dev->u.pa;
const char *server;
PAConnection *c;
assert(dev->driver == AUDIODEV_DRIVER_PA);
if (!audio_pa_parent_class->realize(abe, dev, errp)) {
return false;
}
if (!popts->server) {
char pidfile[64];
char *runtime;
@@ -825,38 +834,42 @@ audio_pa_realize(AudioBackend *abe, Audiodev *dev, Error **errp)
runtime = getenv("XDG_RUNTIME_DIR");
if (!runtime) {
error_setg(errp, "XDG_RUNTIME_DIR not set");
return false;
return NULL;
}
snprintf(pidfile, sizeof(pidfile), "%s/pulse/pid", runtime);
if (stat(pidfile, &st) != 0) {
error_setg_errno(errp, errno, "could not stat pidfile %s", pidfile);
return false;
return NULL;
}
}
qpa_validate_per_direction_opts(dev, popts->in);
qpa_validate_per_direction_opts(dev, popts->out);
g = g_new0(paaudio, 1);
server = popts->server;
g->dev = dev;
QTAILQ_FOREACH(c, &pa_conns, list) {
if (server == NULL || c->server == NULL ?
server == c->server :
strcmp(server, c->server) == 0) {
apa->conn = c;
g->conn = c;
break;
}
}
if (!apa->conn) {
apa->conn = qpa_conn_init(server);
if (!g->conn) {
g->conn = qpa_conn_init(server);
}
if (!apa->conn) {
if (!g->conn) {
g_free(g);
error_setg(errp, "could not connect to PulseAudio server");
return false;
return NULL;
}
++apa->conn->refcount;
return true;
++g->conn->refcount;
return g;
}
static void qpa_conn_fini(PAConnection *c)
@@ -878,54 +891,48 @@ static void qpa_conn_fini(PAConnection *c)
g_free(c);
}
static void audio_pa_finalize(Object *obj)
static void qpa_audio_fini (void *opaque)
{
AudioPa *apa = AUDIO_PA(obj);
PAConnection *c = apa->conn;
paaudio *g = opaque;
PAConnection *c = g->conn;
if (c && --c->refcount == 0) {
if (--c->refcount == 0) {
qpa_conn_fini(c);
}
g_free(g);
}
static void audio_pa_class_init(ObjectClass *klass, const void *data)
{
AudioBackendClass *b = AUDIO_BACKEND_CLASS(klass);
AudioMixengBackendClass *k = AUDIO_MIXENG_BACKEND_CLASS(klass);
static struct audio_pcm_ops qpa_pcm_ops = {
.init_out = qpa_init_out,
.fini_out = qpa_fini_out,
.write = qpa_write,
.buffer_get_free = qpa_buffer_get_free,
.get_buffer_out = qpa_get_buffer_out,
.put_buffer_out = qpa_put_buffer_out,
.volume_out = qpa_volume_out,
audio_pa_parent_class = AUDIO_BACKEND_CLASS(object_class_get_parent(klass));
b->realize = audio_pa_realize;
k->max_voices_out = INT_MAX;
k->max_voices_in = INT_MAX;
k->voice_size_out = sizeof(PAVoiceOut);
k->voice_size_in = sizeof(PAVoiceIn);
k->init_out = qpa_init_out;
k->fini_out = qpa_fini_out;
k->write = qpa_write;
k->buffer_get_free = qpa_buffer_get_free;
k->get_buffer_out = qpa_get_buffer_out;
k->put_buffer_out = qpa_put_buffer_out;
k->volume_out = qpa_volume_out;
k->init_in = qpa_init_in;
k->fini_in = qpa_fini_in;
k->read = qpa_read;
k->get_buffer_in = qpa_get_buffer_in;
k->put_buffer_in = qpa_put_buffer_in;
k->volume_in = qpa_volume_in;
}
static const TypeInfo audio_types[] = {
{
.name = TYPE_AUDIO_PA,
.parent = TYPE_AUDIO_MIXENG_BACKEND,
.instance_size = sizeof(AudioPa),
.class_init = audio_pa_class_init,
.instance_finalize = audio_pa_finalize,
},
.init_in = qpa_init_in,
.fini_in = qpa_fini_in,
.read = qpa_read,
.get_buffer_in = qpa_get_buffer_in,
.put_buffer_in = qpa_put_buffer_in,
.volume_in = qpa_volume_in
};
DEFINE_TYPES(audio_types)
module_obj(TYPE_AUDIO_PA);
static struct audio_driver pa_audio_driver = {
.name = "pa",
.init = qpa_audio_init,
.fini = qpa_audio_fini,
.pcm_ops = &qpa_pcm_ops,
.max_voices_out = INT_MAX,
.max_voices_in = INT_MAX,
.voice_size_out = sizeof (PAVoiceOut),
.voice_size_in = sizeof (PAVoiceIn),
};
static void register_audio_pa(void)
{
audio_driver_register(&pa_audio_driver);
}
type_init(register_audio_pa);
+106 -114
View File
@@ -13,43 +13,37 @@
#include "qemu/audio.h"
#include "qemu/error-report.h"
#include "qapi/error.h"
#include "qom/object.h"
#include <spa/param/audio/format-utils.h>
#include <spa/utils/ringbuffer.h>
#include <spa/utils/result.h>
#include <spa/param/props.h>
#include <pipewire/pipewire.h>
#include "audio_int.h"
#include "trace.h"
#define AUDIO_CAP "pipewire"
#define RINGBUFFER_SIZE (1u << 22)
#define RINGBUFFER_MASK (RINGBUFFER_SIZE - 1)
#define TYPE_AUDIO_PW "audio-pipewire"
OBJECT_DECLARE_SIMPLE_TYPE(AudioPw, AUDIO_PW)
static AudioBackendClass *audio_pw_parent_class;
struct AudioPw {
AudioMixengBackend parent_obj;
struct pw_thread_loop *thread_loop;
struct pw_context *context;
struct pw_core *core;
struct spa_hook core_listener;
int last_seq, pending_seq, error;
};
#include "audio_int.h"
typedef struct pwvolume {
uint32_t channels;
float values[SPA_AUDIO_MAX_CHANNELS];
} pwvolume;
typedef struct pwaudio {
Audiodev *dev;
struct pw_thread_loop *thread_loop;
struct pw_context *context;
struct pw_core *core;
struct spa_hook core_listener;
int last_seq, pending_seq, error;
} pwaudio;
typedef struct PWVoice {
pwaudio *g;
struct pw_stream *stream;
struct spa_hook stream_listener;
struct spa_audio_info_raw info;
@@ -225,9 +219,9 @@ static const struct pw_stream_events playback_stream_events = {
static size_t
qpw_read(HWVoiceIn *hw, void *data, size_t len)
{
AudioPw *c = AUDIO_PW(hw->s);
PWVoiceIn *pw = (PWVoiceIn *) hw;
PWVoice *v = &pw->v;
pwaudio *c = v->g;
const char *error = NULL;
size_t l;
int32_t avail;
@@ -262,9 +256,9 @@ done_unlock:
static size_t qpw_buffer_get_free(HWVoiceOut *hw)
{
AudioPw *c = AUDIO_PW(hw->s);
PWVoiceOut *pw = (PWVoiceOut *)hw;
PWVoice *v = &pw->v;
pwaudio *c = v->g;
const char *error = NULL;
int32_t filled, avail;
uint32_t index;
@@ -287,9 +281,9 @@ done_unlock:
static size_t
qpw_write(HWVoiceOut *hw, void *data, size_t len)
{
AudioPw *c = AUDIO_PW(hw->s);
PWVoiceOut *pw = (PWVoiceOut *) hw;
PWVoice *v = &pw->v;
pwaudio *c = v->g;
const char *error = NULL;
int32_t filled, avail;
uint32_t index;
@@ -357,7 +351,7 @@ audfmt_to_pw(AudioFormat fmt, bool big_endian)
format = big_endian ? SPA_AUDIO_FORMAT_F32_BE : SPA_AUDIO_FORMAT_F32_LE;
break;
default:
error_report("pipewire: internal logic error: bad audio format %d", fmt);
dolog("Internal logic error: Bad audio format %d\n", fmt);
format = SPA_AUDIO_FORMAT_U8;
break;
}
@@ -365,7 +359,7 @@ audfmt_to_pw(AudioFormat fmt, bool big_endian)
}
static AudioFormat
pw_to_audfmt(enum spa_audio_format fmt, bool *big_endian,
pw_to_audfmt(enum spa_audio_format fmt, int *endianness,
uint32_t *sample_size)
{
switch (fmt) {
@@ -377,53 +371,53 @@ pw_to_audfmt(enum spa_audio_format fmt, bool *big_endian,
return AUDIO_FORMAT_U8;
case SPA_AUDIO_FORMAT_S16_BE:
*sample_size = 2;
*big_endian = true;
*endianness = 1;
return AUDIO_FORMAT_S16;
case SPA_AUDIO_FORMAT_S16_LE:
*sample_size = 2;
*big_endian = false;
*endianness = 0;
return AUDIO_FORMAT_S16;
case SPA_AUDIO_FORMAT_U16_BE:
*sample_size = 2;
*big_endian = true;
*endianness = 1;
return AUDIO_FORMAT_U16;
case SPA_AUDIO_FORMAT_U16_LE:
*sample_size = 2;
*big_endian = false;
*endianness = 0;
return AUDIO_FORMAT_U16;
case SPA_AUDIO_FORMAT_S32_BE:
*sample_size = 4;
*big_endian = true;
*endianness = 1;
return AUDIO_FORMAT_S32;
case SPA_AUDIO_FORMAT_S32_LE:
*sample_size = 4;
*big_endian = false;
*endianness = 0;
return AUDIO_FORMAT_S32;
case SPA_AUDIO_FORMAT_U32_BE:
*sample_size = 4;
*big_endian = true;
*endianness = 1;
return AUDIO_FORMAT_U32;
case SPA_AUDIO_FORMAT_U32_LE:
*sample_size = 4;
*big_endian = false;
*endianness = 0;
return AUDIO_FORMAT_U32;
case SPA_AUDIO_FORMAT_F32_BE:
*sample_size = 4;
*big_endian = true;
*endianness = 1;
return AUDIO_FORMAT_F32;
case SPA_AUDIO_FORMAT_F32_LE:
*sample_size = 4;
*big_endian = false;
*endianness = 0;
return AUDIO_FORMAT_F32;
default:
*sample_size = 1;
error_report("pipewire: internal logic error: bad spa_audio_format %d", fmt);
dolog("Internal logic error: Bad spa_audio_format %d\n", fmt);
return AUDIO_FORMAT_U8;
}
}
static int
qpw_stream_new(AudioPw *c, PWVoice *v, const char *stream_name,
qpw_stream_new(pwaudio *c, PWVoice *v, const char *stream_name,
const char *name, enum spa_direction dir)
{
int res;
@@ -441,8 +435,8 @@ qpw_stream_new(AudioPw *c, PWVoice *v, const char *stream_name,
}
/* 75% of the timer period for faster updates */
buf_samples = (uint64_t)AUDIO_MIXENG_BACKEND(c)->dev->timer_period
* v->info.rate * 3 / 4 / 1000000;
buf_samples = (uint64_t)v->g->dev->timer_period * v->info.rate
* 3 / 4 / 1000000;
pw_properties_setf(props, PW_KEY_NODE_LATENCY, "%" PRIu64 "/%u",
buf_samples, v->info.rate);
@@ -517,37 +511,37 @@ qpw_set_position(uint32_t channels, uint32_t position[SPA_AUDIO_MAX_CHANNELS])
position[0] = SPA_AUDIO_CHANNEL_MONO;
break;
default:
error_report("pipewire: unsupported channel count %d", channels);
dolog("Internal error: unsupported channel count %d\n", channels);
}
}
static int
qpw_init_out(HWVoiceOut *hw, struct audsettings *as)
qpw_init_out(HWVoiceOut *hw, struct audsettings *as, void *drv_opaque)
{
AudioPw *c = AUDIO_PW(hw->s);
PWVoiceOut *pw = (PWVoiceOut *) hw;
PWVoice *v = &pw->v;
struct audsettings obt_as = *as;
AudiodevPipewireOptions *popts = &AUDIO_MIXENG_BACKEND(c)->dev->u.pipewire;
pwaudio *c = v->g = drv_opaque;
AudiodevPipewireOptions *popts = &c->dev->u.pipewire;
AudiodevPipewirePerDirectionOptions *ppdo = popts->out;
int r;
pw_thread_loop_lock(c->thread_loop);
v->info.format = audfmt_to_pw(as->fmt, as->big_endian);
v->info.format = audfmt_to_pw(as->fmt, as->endianness);
v->info.channels = as->nchannels;
qpw_set_position(as->nchannels, v->info.position);
v->info.rate = as->freq;
obt_as.fmt =
pw_to_audfmt(v->info.format, &obt_as.big_endian, &v->frame_size);
pw_to_audfmt(v->info.format, &obt_as.endianness, &v->frame_size);
v->frame_size *= as->nchannels;
v->req = (uint64_t)AUDIO_MIXENG_BACKEND(c)->dev->timer_period * v->info.rate
v->req = (uint64_t)c->dev->timer_period * v->info.rate
* 1 / 2 / 1000000 * v->frame_size;
/* call the function that creates a new stream for playback */
r = qpw_stream_new(c, v, ppdo->stream_name ?: AUDIO_MIXENG_BACKEND(c)->dev->id,
r = qpw_stream_new(c, v, ppdo->stream_name ? : c->dev->id,
ppdo->name, SPA_DIRECTION_OUTPUT);
if (r < 0) {
pw_thread_loop_unlock(c->thread_loop);
@@ -569,29 +563,29 @@ qpw_init_out(HWVoiceOut *hw, struct audsettings *as)
}
static int
qpw_init_in(HWVoiceIn *hw, struct audsettings *as)
qpw_init_in(HWVoiceIn *hw, struct audsettings *as, void *drv_opaque)
{
AudioPw *c = AUDIO_PW(hw->s);
PWVoiceIn *pw = (PWVoiceIn *) hw;
PWVoice *v = &pw->v;
struct audsettings obt_as = *as;
AudiodevPipewireOptions *popts = &AUDIO_MIXENG_BACKEND(c)->dev->u.pipewire;
pwaudio *c = v->g = drv_opaque;
AudiodevPipewireOptions *popts = &c->dev->u.pipewire;
AudiodevPipewirePerDirectionOptions *ppdo = popts->in;
int r;
pw_thread_loop_lock(c->thread_loop);
v->info.format = audfmt_to_pw(as->fmt, as->big_endian);
v->info.format = audfmt_to_pw(as->fmt, as->endianness);
v->info.channels = as->nchannels;
qpw_set_position(as->nchannels, v->info.position);
v->info.rate = as->freq;
obt_as.fmt =
pw_to_audfmt(v->info.format, &obt_as.big_endian, &v->frame_size);
pw_to_audfmt(v->info.format, &obt_as.endianness, &v->frame_size);
v->frame_size *= as->nchannels;
/* call the function that creates a new stream for recording */
r = qpw_stream_new(c, v, ppdo->stream_name ? : AUDIO_MIXENG_BACKEND(c)->dev->id,
r = qpw_stream_new(c, v, ppdo->stream_name ? : c->dev->id,
ppdo->name, SPA_DIRECTION_INPUT);
if (r < 0) {
pw_thread_loop_unlock(c->thread_loop);
@@ -610,8 +604,10 @@ qpw_init_in(HWVoiceIn *hw, struct audsettings *as)
}
static void
qpw_voice_fini(AudioPw *c, PWVoice *v)
qpw_voice_fini(PWVoice *v)
{
pwaudio *c = v->g;
if (!v->stream) {
return;
}
@@ -624,18 +620,19 @@ qpw_voice_fini(AudioPw *c, PWVoice *v)
static void
qpw_fini_out(HWVoiceOut *hw)
{
qpw_voice_fini(AUDIO_PW(hw->s), &PW_VOICE_OUT(hw)->v);
qpw_voice_fini(&PW_VOICE_OUT(hw)->v);
}
static void
qpw_fini_in(HWVoiceIn *hw)
{
qpw_voice_fini(AUDIO_PW(hw->s), &PW_VOICE_IN(hw)->v);
qpw_voice_fini(&PW_VOICE_IN(hw)->v);
}
static void
qpw_voice_set_enabled(AudioPw *c, PWVoice *v, bool enable)
qpw_voice_set_enabled(PWVoice *v, bool enable)
{
pwaudio *c = v->g;
pw_thread_loop_lock(c->thread_loop);
pw_stream_set_active(v->stream, enable);
pw_thread_loop_unlock(c->thread_loop);
@@ -644,18 +641,19 @@ qpw_voice_set_enabled(AudioPw *c, PWVoice *v, bool enable)
static void
qpw_enable_out(HWVoiceOut *hw, bool enable)
{
qpw_voice_set_enabled(AUDIO_PW(hw->s), &PW_VOICE_OUT(hw)->v, enable);
qpw_voice_set_enabled(&PW_VOICE_OUT(hw)->v, enable);
}
static void
qpw_enable_in(HWVoiceIn *hw, bool enable)
{
qpw_voice_set_enabled(AUDIO_PW(hw->s), &PW_VOICE_IN(hw)->v, enable);
qpw_voice_set_enabled(&PW_VOICE_IN(hw)->v, enable);
}
static void
qpw_voice_set_volume(AudioPw *c, PWVoice *v, Volume *vol)
qpw_voice_set_volume(PWVoice *v, Volume *vol)
{
pwaudio *c = v->g;
int i, ret;
pw_thread_loop_lock(c->thread_loop);
@@ -678,16 +676,16 @@ qpw_voice_set_volume(AudioPw *c, PWVoice *v, Volume *vol)
static void
qpw_volume_out(HWVoiceOut *hw, Volume *vol)
{
qpw_voice_set_volume(AUDIO_PW(hw->s), &PW_VOICE_OUT(hw)->v, vol);
qpw_voice_set_volume(&PW_VOICE_OUT(hw)->v, vol);
}
static void
qpw_volume_in(HWVoiceIn *hw, Volume *vol)
{
qpw_voice_set_volume(AUDIO_PW(hw->s), &PW_VOICE_IN(hw)->v, vol);
qpw_voice_set_volume(&PW_VOICE_IN(hw)->v, vol);
}
static int wait_resync(AudioPw *pw)
static int wait_resync(pwaudio *pw)
{
int res;
pw->pending_seq = pw_core_sync(pw->core, PW_ID_CORE, pw->pending_seq);
@@ -710,7 +708,7 @@ static int wait_resync(AudioPw *pw)
static void
on_core_error(void *data, uint32_t id, int seq, int res, const char *message)
{
AudioPw *pw = data;
pwaudio *pw = data;
error_report("error id:%u seq:%d res:%d (%s): %s",
id, seq, res, spa_strerror(res), message);
@@ -722,7 +720,7 @@ on_core_error(void *data, uint32_t id, int seq, int res, const char *message)
static void
on_core_done(void *data, uint32_t id, int seq)
{
AudioPw *pw = data;
pwaudio *pw = data;
assert(id == PW_ID_CORE);
pw->last_seq = seq;
if (pw->pending_seq == seq) {
@@ -737,20 +735,17 @@ static const struct pw_core_events core_events = {
.error = on_core_error,
};
static bool
audio_pw_realize(AudioBackend *abe, Audiodev *dev, Error **errp)
static void *
qpw_audio_init(Audiodev *dev, Error **errp)
{
AudioPw *pw = AUDIO_PW(abe);
g_autofree pwaudio *pw = g_new0(pwaudio, 1);
assert(dev->driver == AUDIODEV_DRIVER_PIPEWIRE);
trace_pw_audio_init();
if (!audio_pw_parent_class->realize(abe, dev, errp)) {
return false;
}
pw_init(NULL, NULL);
pw->dev = dev;
pw->thread_loop = pw_thread_loop_new("PipeWire thread loop", NULL);
if (pw->thread_loop == NULL) {
error_setg_errno(errp, errno, "Could not create PipeWire loop");
@@ -789,7 +784,8 @@ audio_pw_realize(AudioBackend *abe, Audiodev *dev, Error **errp)
}
pw_thread_loop_unlock(pw->thread_loop);
return true;
return g_steal_pointer(&pw);
fail:
if (pw->thread_loop) {
@@ -797,13 +793,13 @@ fail:
}
g_clear_pointer(&pw->context, pw_context_destroy);
g_clear_pointer(&pw->thread_loop, pw_thread_loop_destroy);
return false;
return NULL;
}
static void
audio_pw_finalize(Object *obj)
qpw_audio_fini(void *opaque)
{
AudioPw *pw = AUDIO_PW(obj);
pwaudio *pw = opaque;
if (pw->thread_loop) {
pw_thread_loop_stop(pw->thread_loop);
@@ -818,47 +814,43 @@ audio_pw_finalize(Object *obj)
if (pw->context) {
pw_context_destroy(pw->context);
}
g_clear_pointer(&pw->thread_loop, pw_thread_loop_destroy);
pw_thread_loop_destroy(pw->thread_loop);
g_free(pw);
}
static void audio_pw_class_init(ObjectClass *klass, const void *data)
{
AudioBackendClass *b = AUDIO_BACKEND_CLASS(klass);
AudioMixengBackendClass *k = AUDIO_MIXENG_BACKEND_CLASS(klass);
static struct audio_pcm_ops qpw_pcm_ops = {
.init_out = qpw_init_out,
.fini_out = qpw_fini_out,
.write = qpw_write,
.buffer_get_free = qpw_buffer_get_free,
.run_buffer_out = audio_generic_run_buffer_out,
.enable_out = qpw_enable_out,
.volume_out = qpw_volume_out,
.volume_in = qpw_volume_in,
audio_pw_parent_class = AUDIO_BACKEND_CLASS(object_class_get_parent(klass));
b->realize = audio_pw_realize;
k->max_voices_out = INT_MAX;
k->max_voices_in = INT_MAX;
k->voice_size_out = sizeof(PWVoiceOut);
k->voice_size_in = sizeof(PWVoiceIn);
k->init_out = qpw_init_out;
k->fini_out = qpw_fini_out;
k->write = qpw_write;
k->buffer_get_free = qpw_buffer_get_free;
k->run_buffer_out = audio_generic_run_buffer_out;
k->enable_out = qpw_enable_out;
k->volume_out = qpw_volume_out;
k->init_in = qpw_init_in;
k->fini_in = qpw_fini_in;
k->read = qpw_read;
k->run_buffer_in = audio_generic_run_buffer_in;
k->enable_in = qpw_enable_in;
k->volume_in = qpw_volume_in;
}
static const TypeInfo audio_types[] = {
{
.name = TYPE_AUDIO_PW,
.parent = TYPE_AUDIO_MIXENG_BACKEND,
.instance_size = sizeof(AudioPw),
.class_init = audio_pw_class_init,
.instance_finalize = audio_pw_finalize,
},
.init_in = qpw_init_in,
.fini_in = qpw_fini_in,
.read = qpw_read,
.run_buffer_in = audio_generic_run_buffer_in,
.enable_in = qpw_enable_in
};
DEFINE_TYPES(audio_types)
module_obj(TYPE_AUDIO_PW);
static struct audio_driver pw_audio_driver = {
.name = "pipewire",
.init = qpw_audio_init,
.fini = qpw_audio_fini,
.pcm_ops = &qpw_pcm_ops,
.max_voices_out = INT_MAX,
.max_voices_in = INT_MAX,
.voice_size_out = sizeof(PWVoiceOut),
.voice_size_in = sizeof(PWVoiceIn),
};
static void
register_audio_pw(void)
{
audio_driver_register(&pw_audio_driver);
}
type_init(register_audio_pw);
+88 -90
View File
@@ -26,10 +26,8 @@
#include <SDL.h>
#include <SDL_thread.h>
#include "qemu/module.h"
#include "qemu/error-report.h"
#include "qapi/error.h"
#include "qemu/audio.h"
#include "qom/object.h"
#ifndef _WIN32
#ifdef __sun__
@@ -39,18 +37,9 @@
#endif
#endif
#define AUDIO_CAP "sdl"
#include "audio_int.h"
#define TYPE_AUDIO_SDL "audio-sdl"
OBJECT_DECLARE_SIMPLE_TYPE(AudioSdl, AUDIO_SDL)
static AudioBackendClass *audio_sdl_parent_class;
struct AudioSdl {
AudioMixengBackend parent_obj;
};
typedef struct SDLVoiceOut {
HWVoiceOut hw;
int exit;
@@ -67,6 +56,17 @@ typedef struct SDLVoiceIn {
SDL_AudioDeviceID devid;
} SDLVoiceIn;
static void G_GNUC_PRINTF (1, 2) sdl_logerr (const char *fmt, ...)
{
va_list ap;
va_start (ap, fmt);
AUD_vlog (AUDIO_CAP, fmt, ap);
va_end (ap);
AUD_log (AUDIO_CAP, "Reason: %s\n", SDL_GetError ());
}
static int aud_to_sdlfmt (AudioFormat fmt)
{
switch (fmt) {
@@ -91,66 +91,69 @@ static int aud_to_sdlfmt (AudioFormat fmt)
return AUDIO_F32LSB;
default:
error_report("sdl: internal logic error: bad audio format %d", fmt);
dolog ("Internal logic error: Bad audio format %d\n", fmt);
#ifdef DEBUG_AUDIO
abort ();
#endif
return AUDIO_U8;
}
}
static int sdl_to_audfmt(int sdlfmt, AudioFormat *fmt, bool *big_endian)
static int sdl_to_audfmt(int sdlfmt, AudioFormat *fmt, int *endianness)
{
switch (sdlfmt) {
case AUDIO_S8:
*big_endian = false;
*endianness = 0;
*fmt = AUDIO_FORMAT_S8;
break;
case AUDIO_U8:
*big_endian = false;
*endianness = 0;
*fmt = AUDIO_FORMAT_U8;
break;
case AUDIO_S16LSB:
*big_endian = false;
*endianness = 0;
*fmt = AUDIO_FORMAT_S16;
break;
case AUDIO_U16LSB:
*big_endian = false;
*endianness = 0;
*fmt = AUDIO_FORMAT_U16;
break;
case AUDIO_S16MSB:
*big_endian = true;
*endianness = 1;
*fmt = AUDIO_FORMAT_S16;
break;
case AUDIO_U16MSB:
*big_endian = true;
*endianness = 1;
*fmt = AUDIO_FORMAT_U16;
break;
case AUDIO_S32LSB:
*big_endian = false;
*endianness = 0;
*fmt = AUDIO_FORMAT_S32;
break;
case AUDIO_S32MSB:
*big_endian = true;
*endianness = 1;
*fmt = AUDIO_FORMAT_S32;
break;
case AUDIO_F32LSB:
*big_endian = false;
*endianness = 0;
*fmt = AUDIO_FORMAT_F32;
break;
case AUDIO_F32MSB:
*big_endian = true;
*endianness = 1;
*fmt = AUDIO_FORMAT_F32;
break;
default:
error_report("sdl: unrecognized audio format %d", sdlfmt);
dolog ("Unrecognized SDL audio format %d\n", sdlfmt);
return -1;
}
@@ -168,27 +171,27 @@ static SDL_AudioDeviceID sdl_open(SDL_AudioSpec *req, SDL_AudioSpec *obt,
/* Make sure potential threads created by SDL don't hog signals. */
err = sigfillset (&new);
if (err) {
error_report("sdl: sigfillset failed: %s", strerror (errno));
dolog ("sdl_open: sigfillset failed: %s\n", strerror (errno));
return 0;
}
err = pthread_sigmask (SIG_BLOCK, &new, &old);
if (err) {
error_report("sdl: pthread_sigmask failed: %s", strerror (err));
dolog ("sdl_open: pthread_sigmask failed: %s\n", strerror (err));
return 0;
}
#endif
devid = SDL_OpenAudioDevice(NULL, rec, req, obt, 0);
if (!devid) {
error_report("SDL_OpenAudioDevice for %s failed: %s",
rec ? "recording" : "playback", SDL_GetError());
sdl_logerr("SDL_OpenAudioDevice for %s failed\n",
rec ? "recording" : "playback");
}
#ifndef _WIN32
err = pthread_sigmask (SIG_SETMASK, &old, NULL);
if (err) {
error_report("sdl: pthread_sigmask (restore) failed: %s",
strerror (errno));
dolog ("sdl_open: pthread_sigmask (restore) failed: %s\n",
strerror (errno));
/* We have failed to restore original signal mask, all bets are off,
so exit the process */
exit (EXIT_FAILURE);
@@ -219,6 +222,8 @@ static void sdl_callback_out(void *opaque, Uint8 *buf, int len)
if (!sdl->exit) {
/* dolog("callback_out: len=%d avail=%zu\n", len, hw->pending_emul); */
while (hw->pending_emul && len) {
size_t write_len, start;
@@ -267,6 +272,8 @@ static void sdl_callback_in(void *opaque, Uint8 *buf, int len)
return;
}
/* dolog("callback_in: len=%d pending=%zu\n", len, hw->pending_emul); */
while (hw->pending_emul < hw->size_emul && len) {
size_t read_len = MIN(len, MIN(hw->size_emul - hw->pos_emul,
hw->size_emul - hw->pending_emul));
@@ -326,12 +333,13 @@ static void sdl_fini_out(HWVoiceOut *hw)
sdl_close_out(sdl);
}
static int sdl_init_out(HWVoiceOut *hw, struct audsettings *as)
static int sdl_init_out(HWVoiceOut *hw, struct audsettings *as,
void *drv_opaque)
{
SDLVoiceOut *sdl = (SDLVoiceOut *)hw;
SDL_AudioSpec req, obt;
int err;
Audiodev *dev = hw->s->dev;
Audiodev *dev = drv_opaque;
AudiodevSdlPerDirectionOptions *spdo = dev->u.sdl.out;
struct audsettings obt_as;
@@ -350,7 +358,7 @@ static int sdl_init_out(HWVoiceOut *hw, struct audsettings *as)
return -1;
}
err = sdl_to_audfmt(obt.format, &obt_as.fmt, &obt_as.big_endian);
err = sdl_to_audfmt(obt.format, &obt_as.fmt, &obt_as.endianness);
if (err) {
sdl_close_out(sdl);
return -1;
@@ -382,12 +390,12 @@ static void sdl_fini_in(HWVoiceIn *hw)
sdl_close_in(sdl);
}
static int sdl_init_in(HWVoiceIn *hw, audsettings *as)
static int sdl_init_in(HWVoiceIn *hw, audsettings *as, void *drv_opaque)
{
SDLVoiceIn *sdl = (SDLVoiceIn *)hw;
SDL_AudioSpec req, obt;
int err;
Audiodev *dev = hw->s->dev;
Audiodev *dev = drv_opaque;
AudiodevSdlPerDirectionOptions *spdo = dev->u.sdl.in;
struct audsettings obt_as;
@@ -406,7 +414,7 @@ static int sdl_init_in(HWVoiceIn *hw, audsettings *as)
return -1;
}
err = sdl_to_audfmt(obt.format, &obt_as.fmt, &obt_as.big_endian);
err = sdl_to_audfmt(obt.format, &obt_as.fmt, &obt_as.endianness);
if (err) {
sdl_close_in(sdl);
return -1;
@@ -434,67 +442,57 @@ static void sdl_enable_in(HWVoiceIn *hw, bool enable)
SDL_PauseAudioDevice(sdl->devid, !enable);
}
static bool audio_sdl_realize(AudioBackend *abe, Audiodev *dev, Error **errp)
static void *sdl_audio_init(Audiodev *dev, Error **errp)
{
if (SDL_InitSubSystem(SDL_INIT_AUDIO)) {
if (SDL_InitSubSystem (SDL_INIT_AUDIO)) {
error_setg(errp, "SDL failed to initialize audio subsystem");
qapi_free_Audiodev(dev);
return false;
return NULL;
}
return audio_sdl_parent_class->realize(abe, dev, errp);
return dev;
}
static void audio_sdl_finalize(Object *obj)
static void sdl_audio_fini (void *opaque)
{
SDL_QuitSubSystem(SDL_INIT_AUDIO);
SDL_QuitSubSystem (SDL_INIT_AUDIO);
}
static void audio_sdl_class_init(ObjectClass *klass, const void *data)
{
AudioBackendClass *b = AUDIO_BACKEND_CLASS(klass);
AudioMixengBackendClass *k = AUDIO_MIXENG_BACKEND_CLASS(klass);
audio_sdl_parent_class = AUDIO_BACKEND_CLASS(object_class_get_parent(klass));
b->realize = audio_sdl_realize;
k->max_voices_out = INT_MAX;
k->max_voices_in = INT_MAX;
k->voice_size_out = sizeof(SDLVoiceOut);
k->voice_size_in = sizeof(SDLVoiceIn);
k->init_out = sdl_init_out;
k->fini_out = sdl_fini_out;
/* wrapper for audio_generic_write */
k->write = sdl_write;
/* wrapper for audio_generic_buffer_get_free */
k->buffer_get_free = sdl_buffer_get_free;
/* wrapper for audio_generic_get_buffer_out */
k->get_buffer_out = sdl_get_buffer_out;
/* wrapper for audio_generic_put_buffer_out */
k->put_buffer_out = sdl_put_buffer_out;
k->enable_out = sdl_enable_out;
k->init_in = sdl_init_in;
k->fini_in = sdl_fini_in;
/* wrapper for audio_generic_read */
k->read = sdl_read;
/* wrapper for audio_generic_get_buffer_in */
k->get_buffer_in = sdl_get_buffer_in;
/* wrapper for audio_generic_put_buffer_in */
k->put_buffer_in = sdl_put_buffer_in;
k->enable_in = sdl_enable_in;
}
static const TypeInfo audio_types[] = {
{
.name = TYPE_AUDIO_SDL,
.parent = TYPE_AUDIO_MIXENG_BACKEND,
.instance_size = sizeof(AudioSdl),
.class_init = audio_sdl_class_init,
.instance_finalize = audio_sdl_finalize,
},
static struct audio_pcm_ops sdl_pcm_ops = {
.init_out = sdl_init_out,
.fini_out = sdl_fini_out,
/* wrapper for audio_generic_write */
.write = sdl_write,
/* wrapper for audio_generic_buffer_get_free */
.buffer_get_free = sdl_buffer_get_free,
/* wrapper for audio_generic_get_buffer_out */
.get_buffer_out = sdl_get_buffer_out,
/* wrapper for audio_generic_put_buffer_out */
.put_buffer_out = sdl_put_buffer_out,
.enable_out = sdl_enable_out,
.init_in = sdl_init_in,
.fini_in = sdl_fini_in,
/* wrapper for audio_generic_read */
.read = sdl_read,
/* wrapper for audio_generic_get_buffer_in */
.get_buffer_in = sdl_get_buffer_in,
/* wrapper for audio_generic_put_buffer_in */
.put_buffer_in = sdl_put_buffer_in,
.enable_in = sdl_enable_in,
};
DEFINE_TYPES(audio_types)
module_obj(TYPE_AUDIO_SDL);
static struct audio_driver sdl_audio_driver = {
.name = "sdl",
.init = sdl_audio_init,
.fini = sdl_audio_fini,
.pcm_ops = &sdl_pcm_ops,
.max_voices_out = INT_MAX,
.max_voices_in = INT_MAX,
.voice_size_out = sizeof(SDLVoiceOut),
.voice_size_in = sizeof(SDLVoiceIn),
};
static void register_audio_sdl(void)
{
audio_driver_register(&sdl_audio_driver);
}
type_init(register_audio_sdl);
+53 -55
View File
@@ -18,20 +18,11 @@
#include <poll.h>
#include <sndio.h>
#include "qemu/main-loop.h"
#include "qemu/error-report.h"
#include "qemu/audio.h"
#include "qom/object.h"
#include "audio_int.h"
#include "trace.h"
#define TYPE_AUDIO_SNDIO "audio-sndio"
OBJECT_DECLARE_SIMPLE_TYPE(AudioSndio, AUDIO_SNDIO)
struct AudioSndio {
AudioMixengBackend parent_obj;
};
#define AUDIO_CAP "sndio"
#include "audio_int.h"
/* default latency in microseconds if no option is set */
#define SNDIO_LATENCY_US 50000
@@ -348,7 +339,7 @@ static int sndio_init(SndioVoice *self,
/* open the device in non-blocking mode */
self->hdl = sio_open(dev_name, mode, 1);
if (self->hdl == NULL) {
error_report("sndio: failed to open device");
dolog("failed to open device\n");
return -1;
}
@@ -382,12 +373,12 @@ static int sndio_init(SndioVoice *self,
req.sig = 0;
break;
default:
error_report("sndio: unknown audio sample format");
dolog("unknown audio sample format\n");
return -1;
}
if (req.bits > 8) {
req.le = !as->big_endian;
req.le = as->endianness ? 0 : 1;
}
req.rate = as->freq;
@@ -401,12 +392,12 @@ static int sndio_init(SndioVoice *self,
req.appbufsz = req.rate * latency / 1000000;
if (!sio_setpar(self->hdl, &req)) {
error_report("sndio: failed to set audio params");
dolog("failed set audio params\n");
goto fail;
}
if (!sio_getpar(self->hdl, &self->par)) {
error_report("sndio: failed to get audio params");
dolog("failed get audio params\n");
goto fail;
}
@@ -419,7 +410,7 @@ static int sndio_init(SndioVoice *self,
if (self->par.bits != req.bits || self->par.bps != req.bits / 8 ||
self->par.sig != req.sig || (req.bits > 8 && self->par.le != req.le) ||
self->par.rate != as->freq || nch != as->nchannels) {
error_report("sndio: unsupported audio params");
dolog("unsupported audio params\n");
goto fail;
}
@@ -431,7 +422,7 @@ static int sndio_init(SndioVoice *self,
self->buf = g_malloc(self->buf_size);
if (self->buf == NULL) {
error_report("sndio: failed to allocate audio buffer");
dolog("failed to allocate audio buffer\n");
goto fail;
}
@@ -439,13 +430,13 @@ static int sndio_init(SndioVoice *self,
self->pfds = g_malloc_n(nfds, sizeof(struct pollfd));
if (self->pfds == NULL) {
error_report("sndio: failed to allocate pollfd structures");
dolog("failed to allocate pollfd structures\n");
goto fail;
}
self->pindexes = g_malloc_n(nfds, sizeof(struct pollindex));
if (self->pindexes == NULL) {
error_report("sndio: failed to allocate pollindex structures");
dolog("failed to allocate pollindex structures\n");
goto fail;
}
@@ -487,11 +478,11 @@ static void sndio_enable_in(HWVoiceIn *hw, bool enable)
sndio_enable(self, enable);
}
static int sndio_init_out(HWVoiceOut *hw, struct audsettings *as)
static int sndio_init_out(HWVoiceOut *hw, struct audsettings *as, void *opaque)
{
SndioVoice *self = (SndioVoice *) hw;
if (sndio_init(self, as, SIO_PLAY, hw->s->dev) == -1) {
if (sndio_init(self, as, SIO_PLAY, opaque) == -1) {
return -1;
}
@@ -500,11 +491,11 @@ static int sndio_init_out(HWVoiceOut *hw, struct audsettings *as)
return 0;
}
static int sndio_init_in(HWVoiceIn *hw, struct audsettings *as)
static int sndio_init_in(HWVoiceIn *hw, struct audsettings *as, void *opaque)
{
SndioVoice *self = (SndioVoice *) hw;
if (sndio_init(self, as, SIO_REC, hw->s->dev) == -1) {
if (sndio_init(self, as, SIO_REC, opaque) == -1) {
return -1;
}
@@ -527,39 +518,46 @@ static void sndio_fini_in(HWVoiceIn *hw)
sndio_fini(self);
}
static void audio_sndio_class_init(ObjectClass *klass, const void *data)
static void *sndio_audio_init(Audiodev *dev, Error **errp)
{
AudioMixengBackendClass *k = AUDIO_MIXENG_BACKEND_CLASS(klass);
k->max_voices_out = INT_MAX;
k->max_voices_in = INT_MAX;
k->voice_size_out = sizeof(SndioVoice);
k->voice_size_in = sizeof(SndioVoice);
k->init_out = sndio_init_out;
k->fini_out = sndio_fini_out;
k->write = audio_generic_write;
k->buffer_get_free = sndio_buffer_get_free;
k->get_buffer_out = sndio_get_buffer_out;
k->put_buffer_out = sndio_put_buffer_out;
k->enable_out = sndio_enable_out;
k->init_in = sndio_init_in;
k->fini_in = sndio_fini_in;
k->read = audio_generic_read;
k->get_buffer_in = sndio_get_buffer_in;
k->put_buffer_in = sndio_put_buffer_in;
k->enable_in = sndio_enable_in;
assert(dev->driver == AUDIODEV_DRIVER_SNDIO);
return dev;
}
static const TypeInfo audio_types[] = {
{
.name = TYPE_AUDIO_SNDIO,
.parent = TYPE_AUDIO_MIXENG_BACKEND,
.instance_size = sizeof(AudioSndio),
.class_init = audio_sndio_class_init,
},
static void sndio_audio_fini(void *opaque)
{
}
static struct audio_pcm_ops sndio_pcm_ops = {
.init_out = sndio_init_out,
.fini_out = sndio_fini_out,
.enable_out = sndio_enable_out,
.write = audio_generic_write,
.buffer_get_free = sndio_buffer_get_free,
.get_buffer_out = sndio_get_buffer_out,
.put_buffer_out = sndio_put_buffer_out,
.init_in = sndio_init_in,
.fini_in = sndio_fini_in,
.read = audio_generic_read,
.enable_in = sndio_enable_in,
.get_buffer_in = sndio_get_buffer_in,
.put_buffer_in = sndio_put_buffer_in,
};
DEFINE_TYPES(audio_types)
module_obj(TYPE_AUDIO_SNDIO);
static struct audio_driver sndio_audio_driver = {
.name = "sndio",
.init = sndio_audio_init,
.fini = sndio_audio_fini,
.pcm_ops = &sndio_pcm_ops,
.max_voices_out = INT_MAX,
.max_voices_in = INT_MAX,
.voice_size_out = sizeof(SndioVoice),
.voice_size_in = sizeof(SndioVoice)
};
static void register_audio_sndio(void)
{
audio_driver_register(&sndio_audio_driver);
}
type_init(register_audio_sndio);
+82 -63
View File
@@ -24,33 +24,22 @@
#include "qemu/timer.h"
#include "qapi/error.h"
#include "ui/qemu-spice.h"
#include "qom/object.h"
#define AUDIO_CAP "spice"
#include "qemu/audio.h"
#include "audio_int.h"
#define TYPE_AUDIO_SPICE "audio-spice"
OBJECT_DECLARE_SIMPLE_TYPE(AudioSpice, AUDIO_SPICE)
static AudioBackendClass *audio_spice_parent_class;
struct AudioSpice {
AudioMixengBackend parent_obj;
};
static bool spice_audio_realize(AudioBackend *abe, Audiodev *dev, Error **errp)
{
if (!using_spice) {
error_setg(errp, "Cannot use spice audio without -spice");
qapi_free_Audiodev(dev);
return false;
}
return audio_spice_parent_class->realize(abe, dev, errp);
}
#if SPICE_INTERFACE_PLAYBACK_MAJOR > 1 || SPICE_INTERFACE_PLAYBACK_MINOR >= 3
#define LINE_OUT_SAMPLES (480 * 4)
#else
#define LINE_OUT_SAMPLES (256 * 4)
#endif
#if SPICE_INTERFACE_RECORD_MAJOR > 2 || SPICE_INTERFACE_RECORD_MINOR >= 3
#define LINE_IN_SAMPLES (480 * 4)
#else
#define LINE_IN_SAMPLES (256 * 4)
#endif
typedef struct SpiceVoiceOut {
HWVoiceOut hw;
@@ -83,17 +72,37 @@ static const SpiceRecordInterface record_sif = {
.base.minor_version = SPICE_INTERFACE_RECORD_MINOR,
};
static void *spice_audio_init(Audiodev *dev, Error **errp)
{
if (!using_spice) {
error_setg(errp, "Cannot use spice audio without -spice");
return NULL;
}
return &spice_audio_init;
}
static void spice_audio_fini (void *opaque)
{
/* nothing */
}
/* playback */
static int line_out_init(HWVoiceOut *hw, struct audsettings *as)
static int line_out_init(HWVoiceOut *hw, struct audsettings *as,
void *drv_opaque)
{
SpiceVoiceOut *out = container_of (hw, SpiceVoiceOut, hw);
struct audsettings settings;
#if SPICE_INTERFACE_PLAYBACK_MAJOR > 1 || SPICE_INTERFACE_PLAYBACK_MINOR >= 3
settings.freq = spice_server_get_best_playback_rate(NULL);
#else
settings.freq = SPICE_INTERFACE_PLAYBACK_FREQ;
#endif
settings.nchannels = SPICE_INTERFACE_PLAYBACK_CHAN;
settings.fmt = AUDIO_FORMAT_S16;
settings.big_endian = HOST_BIG_ENDIAN;
settings.endianness = HOST_BIG_ENDIAN;
audio_pcm_init_info (&hw->info, &settings);
hw->samples = LINE_OUT_SAMPLES;
@@ -101,7 +110,9 @@ static int line_out_init(HWVoiceOut *hw, struct audsettings *as)
out->sin.base.sif = &playback_sif.base;
qemu_spice.add_interface(&out->sin.base);
#if SPICE_INTERFACE_PLAYBACK_MAJOR > 1 || SPICE_INTERFACE_PLAYBACK_MINOR >= 3
spice_server_set_playback_rate(&out->sin, settings.freq);
#endif
return 0;
}
@@ -179,6 +190,7 @@ static void line_out_enable(HWVoiceOut *hw, bool enable)
}
}
#if ((SPICE_INTERFACE_PLAYBACK_MAJOR >= 1) && (SPICE_INTERFACE_PLAYBACK_MINOR >= 2))
static void line_out_volume(HWVoiceOut *hw, Volume *vol)
{
SpiceVoiceOut *out = container_of(hw, SpiceVoiceOut, hw);
@@ -190,18 +202,23 @@ static void line_out_volume(HWVoiceOut *hw, Volume *vol)
spice_server_playback_set_volume(&out->sin, 2, svol);
spice_server_playback_set_mute(&out->sin, vol->mute);
}
#endif
/* record */
static int line_in_init(HWVoiceIn *hw, struct audsettings *as)
static int line_in_init(HWVoiceIn *hw, struct audsettings *as, void *drv_opaque)
{
SpiceVoiceIn *in = container_of (hw, SpiceVoiceIn, hw);
struct audsettings settings;
#if SPICE_INTERFACE_RECORD_MAJOR > 2 || SPICE_INTERFACE_RECORD_MINOR >= 3
settings.freq = spice_server_get_best_record_rate(NULL);
#else
settings.freq = SPICE_INTERFACE_RECORD_FREQ;
#endif
settings.nchannels = SPICE_INTERFACE_RECORD_CHAN;
settings.fmt = AUDIO_FORMAT_S16;
settings.big_endian = HOST_BIG_ENDIAN;
settings.endianness = HOST_BIG_ENDIAN;
audio_pcm_init_info (&hw->info, &settings);
hw->samples = LINE_IN_SAMPLES;
@@ -209,7 +226,9 @@ static int line_in_init(HWVoiceIn *hw, struct audsettings *as)
in->sin.base.sif = &record_sif.base;
qemu_spice.add_interface(&in->sin.base);
#if SPICE_INTERFACE_RECORD_MAJOR > 2 || SPICE_INTERFACE_RECORD_MINOR >= 3
spice_server_set_record_rate(&in->sin, settings.freq);
#endif
return 0;
}
@@ -258,6 +277,7 @@ static void line_in_enable(HWVoiceIn *hw, bool enable)
}
}
#if ((SPICE_INTERFACE_RECORD_MAJOR >= 2) && (SPICE_INTERFACE_RECORD_MINOR >= 2))
static void line_in_volume(HWVoiceIn *hw, Volume *vol)
{
SpiceVoiceIn *in = container_of(hw, SpiceVoiceIn, hw);
@@ -269,47 +289,46 @@ static void line_in_volume(HWVoiceIn *hw, Volume *vol)
spice_server_record_set_volume(&in->sin, 2, svol);
spice_server_record_set_mute(&in->sin, vol->mute);
}
#endif
static void audio_spice_class_init(ObjectClass *klass, const void *data)
{
AudioBackendClass *b = AUDIO_BACKEND_CLASS(klass);
AudioMixengBackendClass *k = AUDIO_MIXENG_BACKEND_CLASS(klass);
static struct audio_pcm_ops audio_callbacks = {
.init_out = line_out_init,
.fini_out = line_out_fini,
.write = audio_generic_write,
.buffer_get_free = line_out_get_free,
.get_buffer_out = line_out_get_buffer,
.put_buffer_out = line_out_put_buffer,
.enable_out = line_out_enable,
#if (SPICE_INTERFACE_PLAYBACK_MAJOR >= 1) && \
(SPICE_INTERFACE_PLAYBACK_MINOR >= 2)
.volume_out = line_out_volume,
#endif
audio_spice_parent_class = AUDIO_BACKEND_CLASS(object_class_get_parent(klass));
b->realize = spice_audio_realize;
k->max_voices_out = 1;
k->max_voices_in = 1;
k->voice_size_out = sizeof(SpiceVoiceOut);
k->voice_size_in = sizeof(SpiceVoiceIn);
k->init_out = line_out_init;
k->fini_out = line_out_fini;
k->write = audio_generic_write;
k->buffer_get_free = line_out_get_free;
k->get_buffer_out = line_out_get_buffer;
k->put_buffer_out = line_out_put_buffer;
k->enable_out = line_out_enable;
k->volume_out = line_out_volume;
k->init_in = line_in_init;
k->fini_in = line_in_fini;
k->read = line_in_read;
k->run_buffer_in = audio_generic_run_buffer_in;
k->enable_in = line_in_enable;
k->volume_in = line_in_volume;
}
static const TypeInfo audio_types[] = {
{
.name = TYPE_AUDIO_SPICE,
.parent = TYPE_AUDIO_MIXENG_BACKEND,
.instance_size = sizeof(AudioSpice),
.class_init = audio_spice_class_init,
},
.init_in = line_in_init,
.fini_in = line_in_fini,
.read = line_in_read,
.run_buffer_in = audio_generic_run_buffer_in,
.enable_in = line_in_enable,
#if ((SPICE_INTERFACE_RECORD_MAJOR >= 2) && (SPICE_INTERFACE_RECORD_MINOR >= 2))
.volume_in = line_in_volume,
#endif
};
DEFINE_TYPES(audio_types)
module_obj(TYPE_AUDIO_SPICE);
static struct audio_driver spice_audio_driver = {
.name = "spice",
.init = spice_audio_init,
.fini = spice_audio_fini,
.pcm_ops = &audio_callbacks,
.max_voices_out = 1,
.max_voices_in = 1,
.voice_size_out = sizeof (SpiceVoiceOut),
.voice_size_in = sizeof (SpiceVoiceIn),
};
static void register_audio_spice(void)
{
audio_driver_register(&spice_audio_driver);
}
type_init(register_audio_spice);
module_dep("ui-spice-core");
-46
View File
@@ -9,39 +9,15 @@ alsa_read_zero(long len) "Failed to read %ld frames (read zero)"
alsa_xrun_out(void) "Recovering from playback xrun"
alsa_xrun_in(void) "Recovering from capture xrun"
alsa_resume_out(void) "Resuming suspended output stream"
alsa_info_params(int req_fmt, int obt_fmt, int req_channels, int obt_channels, int req_freq, int obt_freq) "format %d->%d, channels %d->%d, frequency %d->%d"
alsa_info_samples(int buffer_length, int period_length, long samples) "requested: buffer len %d, period len %d; obtained: %ld samples"
alsa_fini_out(void) ""
alsa_enable_out(bool enable) "enable=%d"
alsa_enable_in(bool enable) "enable=%d"
# ossaudio.c
oss_version(int version) "OSS version = 0x%x"
oss_out_params(int req_fmt, int obt_fmt, int req_channels, int obt_channels, int req_freq, int obt_freq, int req_nfrags, int obt_nfrags, int req_fragsize, int obt_fragsize) "fmt=%d->%d, channels %d->%d, freq=%d->%d, nfrags=%d->%d, fragsize=%d->%d"
oss_in_params(int req_fmt, int obt_fmt, int req_channels, int obt_channels, int req_freq, int obt_freq, int req_nfrags, int obt_nfrags, int req_fragsize, int obt_fragsize) "fmt=%d->%d, channels %d->%d, freq=%d->%d, nfrags=%d->%d, fragsize=%d->%d"
oss_fini_out(void) ""
oss_enable_out(bool enable) "enable=%d"
oss_enable_in(bool enable) "enable=%d"
# dbusaudio.c
dbus_audio_register(const char *s, const char *dir) "sender = %s, dir = %s"
dbus_audio_put_buffer_out(size_t pos, size_t size) "buf_pos = %zu, buf_size = %zu"
dbus_audio_read(size_t len) "len = %zu"
# dsoundaudio.c
dsound_clear_sample(void *p1, uint32_t blen1, uint32_t len1, void *p2, uint32_t blen2, uint32_t len2) "p1=%p, blen1=%u, len1=%u, p2=%p, blen2=%u, len2=%u"
dsound_wave_format(uint16_t wFormatTag, uint16_t nChannels, uint32_t nSamplesPerSec, uint32_t nAvgBytesPerSec, uint16_t nBlockAlign, uint16_t wBitsPerSample, uint16_t cbSize) "wFormatTag=%u, nChannels=%u, nSamplesPerSec=%u, nAvgBytesPerSec=%u, nBlockAlign=%u, wBitsPerSample=%u, cbSize=%u"
dsound_buffer_bytes(uint32_t caps_bytes, uint32_t desc_bytes) "caps_bytes=%u, desc_bytes=%u"
# jackaudio.c
jack_client_recover(void) "attempting to reconnect to server"
jack_connect(const char *src, const char *dst) "connect %s -> %s"
jack_server_started(void) "server started"
jack_unique_name(const char *name) "unique name assigned %s"
jack_out_init(uint32_t freq, int buffersize) "output configured for %uHz (%d samples)"
jack_in_init(uint32_t freq, int buffersize) "input configured for %uHz (%d samples)"
jack_info(const char *msg) "%s"
# pwaudio.c
pw_state_changed(int nodeid, const char *s) "node id: %d stream state: %s"
pw_read(int32_t avail, uint32_t index, size_t len) "avail=%d index=%u len=%zu"
@@ -50,29 +26,7 @@ pw_vol(const char *ret) "set volume: %s"
pw_period(uint64_t quantum, uint32_t rate) "period =%" PRIu64 "/%u"
pw_audio_init(void) "Initialize PipeWire context"
# audio-be.c
audio_be_set_active_in(void *sw, bool on) "sw=%p, on=%d"
audio_be_set_active_out(void *sw, bool on) "sw=%p, on=%d"
# audio.c
audio_timer_start(int interval) "interval %d ms"
audio_timer_stop(void) ""
audio_timer_delayed(int interval) "interval %d ms"
audio_notify_capture(int cmd) "notification %d sent"
audio_capture_attach(const char *name, bool active) "capture %s active=%d"
# audio-mixeng-be.c
audio_get_avail(const char *name, size_t live, uint32_t frontend_frames) "%s: get_avail live %zu frontend frames %u"
audio_run_poll(const char *msg, int64_t elapsed_us) "Elapsed since last %s: %" PRId64 " us"
audio_capture_free_sw(const char *name) "freeing %s"
audio_out_full(const char *name, size_t live) "%s is full %zu"
audio_sw_write(const char *name, size_t size, size_t written, size_t total_mixed) "%s: write size %zu written %zu total mixed %zu"
audio_get_free(const char *name, size_t live, size_t dead, uint32_t frontend_frames) "%s: get_free live %zu dead %zu frontend frames %u"
audio_out_disable(void) "Disabling voice"
audio_out_played(size_t played) "played=%zu"
audio_rate_reset(int64_t frames) "Resetting rate control (%" PRId64 " frames)"
# audio_template.h
audio_open_out(const char *name, int freq, int nchannels, int fmt) "open %s, freq %d, nchannels %d, fmt %d"
audio_open_in(const char *name, int freq, int nchannels, int fmt) "open %s, freq %d, nchannels %d, fmt %d"
audio_voice_pair(const char *type, const char *name, const char *hw_fmt, int hw_freq, int hw_nchannels, const char *sw_fmt, int sw_freq, int sw_nchannels) "%s: name=%s hw=%s/%d/%d sw=%s/%d/%d"
+54 -47
View File
@@ -24,19 +24,11 @@
#include "qemu/osdep.h"
#include "qemu/module.h"
#include "qemu/error-report.h"
#include "qemu/audio.h"
#include "qom/object.h"
#define AUDIO_CAP "wav"
#include "audio_int.h"
#define TYPE_AUDIO_WAV "audio-wav"
OBJECT_DECLARE_SIMPLE_TYPE(AudioWav, AUDIO_WAV)
struct AudioWav {
AudioMixengBackend parent_obj;
};
typedef struct WAVVoiceOut {
HWVoiceOut hw;
FILE *f;
@@ -51,8 +43,8 @@ static size_t wav_write_out(HWVoiceOut *hw, void *buf, size_t len)
assert(bytes % hw->info.bytes_per_frame == 0);
if (bytes && fwrite(buf, bytes, 1, wav->f) != 1) {
error_report("wav: fwrite of %" PRId64 " bytes failed: %s",
bytes, strerror(errno));
dolog("wav_write_out: fwrite of %" PRId64 " bytes failed\nReason: %s\n",
bytes, strerror(errno));
}
wav->total_samples += bytes / hw->info.bytes_per_frame;
@@ -69,7 +61,8 @@ static void le_store (uint8_t *buf, uint32_t val, int len)
}
}
static int wav_init_out(HWVoiceOut *hw, struct audsettings *as)
static int wav_init_out(HWVoiceOut *hw, struct audsettings *as,
void *drv_opaque)
{
WAVVoiceOut *wav = (WAVVoiceOut *) hw;
int bits16 = 0, stereo = 0;
@@ -79,7 +72,7 @@ static int wav_init_out(HWVoiceOut *hw, struct audsettings *as)
0x02, 0x00, 0x44, 0xac, 0x00, 0x00, 0x10, 0xb1, 0x02, 0x00, 0x04,
0x00, 0x10, 0x00, 0x64, 0x61, 0x74, 0x61, 0x00, 0x00, 0x00, 0x00
};
Audiodev *dev = hw->s->dev;
Audiodev *dev = drv_opaque;
AudiodevWavOptions *wopts = &dev->u.wav;
struct audsettings wav_as = audiodev_to_audsettings(dev->u.wav.out);
const char *wav_path = wopts->path ?: "qemu.wav";
@@ -98,11 +91,11 @@ static int wav_init_out(HWVoiceOut *hw, struct audsettings *as)
case AUDIO_FORMAT_S32:
case AUDIO_FORMAT_U32:
error_report("wav: WAVE files cannot handle 32-bit formats");
dolog ("WAVE files can not handle 32bit formats\n");
return -1;
case AUDIO_FORMAT_F32:
error_report("wav: WAVE files cannot handle float formats");
dolog("WAVE files can not handle float formats\n");
return -1;
default:
@@ -111,7 +104,7 @@ static int wav_init_out(HWVoiceOut *hw, struct audsettings *as)
hdr[34] = bits16 ? 0x10 : 0x08;
wav_as.big_endian = false;
wav_as.endianness = 0;
audio_pcm_init_info (&hw->info, &wav_as);
hw->samples = 1024;
@@ -122,13 +115,14 @@ static int wav_init_out(HWVoiceOut *hw, struct audsettings *as)
wav->f = fopen(wav_path, "wb");
if (!wav->f) {
error_report("wav: failed to open wave file '%s': %s",
wav_path, strerror(errno));
dolog ("Failed to open wave file `%s'\nReason: %s\n",
wav_path, strerror(errno));
return -1;
}
if (fwrite (hdr, sizeof (hdr), 1, wav->f) != 1) {
error_report("wav: failed to write header: %s", strerror(errno));
dolog ("wav_init_out: failed to write header\nReason: %s\n",
strerror(errno));
return -1;
}
@@ -152,25 +146,30 @@ static void wav_fini_out (HWVoiceOut *hw)
le_store (dlen, datalen, 4);
if (fseek (wav->f, 4, SEEK_SET)) {
error_report("wav: fseek to rlen failed: %s", strerror(errno));
dolog ("wav_fini_out: fseek to rlen failed\nReason: %s\n",
strerror(errno));
goto doclose;
}
if (fwrite (rlen, 4, 1, wav->f) != 1) {
error_report("wav: failed to write rlen: %s", strerror(errno));
dolog ("wav_fini_out: failed to write rlen\nReason: %s\n",
strerror (errno));
goto doclose;
}
if (fseek (wav->f, 32, SEEK_CUR)) {
error_report("wav: fseek to dlen failed: %s", strerror(errno));
dolog ("wav_fini_out: fseek to dlen failed\nReason: %s\n",
strerror (errno));
goto doclose;
}
if (fwrite (dlen, 4, 1, wav->f) != 1) {
error_report("wav: failed to write dlen: %s", strerror(errno));
dolog ("wav_fini_out: failed to write dlen\nReaons: %s\n",
strerror (errno));
goto doclose;
}
doclose:
if (fclose (wav->f)) {
error_report("wav: fclose failed: %s", strerror(errno));
dolog ("wav_fini_out: fclose %p failed\nReason: %s\n",
wav->f, strerror (errno));
}
wav->f = NULL;
}
@@ -184,31 +183,39 @@ static void wav_enable_out(HWVoiceOut *hw, bool enable)
}
}
static void audio_wav_class_init(ObjectClass *klass, const void *data)
static void *wav_audio_init(Audiodev *dev, Error **errp)
{
AudioMixengBackendClass *k = AUDIO_MIXENG_BACKEND_CLASS(klass);
k->max_voices_out = 1;
k->max_voices_in = 0;
k->voice_size_out = sizeof(WAVVoiceOut);
k->voice_size_in = 0;
k->init_out = wav_init_out;
k->fini_out = wav_fini_out;
k->write = wav_write_out;
k->buffer_get_free = audio_generic_buffer_get_free;
k->run_buffer_out = audio_generic_run_buffer_out;
k->enable_out = wav_enable_out;
assert(dev->driver == AUDIODEV_DRIVER_WAV);
return dev;
}
static const TypeInfo audio_types[] = {
{
.name = TYPE_AUDIO_WAV,
.parent = TYPE_AUDIO_MIXENG_BACKEND,
.instance_size = sizeof(AudioWav),
.class_init = audio_wav_class_init,
}
static void wav_audio_fini (void *opaque)
{
ldebug ("wav_fini");
}
static struct audio_pcm_ops wav_pcm_ops = {
.init_out = wav_init_out,
.fini_out = wav_fini_out,
.write = wav_write_out,
.buffer_get_free = audio_generic_buffer_get_free,
.run_buffer_out = audio_generic_run_buffer_out,
.enable_out = wav_enable_out,
};
DEFINE_TYPES(audio_types)
module_obj(TYPE_AUDIO_WAV);
static struct audio_driver wav_audio_driver = {
.name = "wav",
.init = wav_audio_init,
.fini = wav_audio_fini,
.pcm_ops = &wav_pcm_ops,
.max_voices_out = 1,
.max_voices_in = 0,
.voice_size_out = sizeof (WAVVoiceOut),
.voice_size_in = 0
};
static void register_audio_wav(void)
{
audio_driver_register(&wav_audio_driver);
}
type_init(register_audio_wav);
+3 -6
View File
@@ -1,5 +1,4 @@
#include "qemu/osdep.h"
#include "qemu/audio.h"
#include "qemu/qemu-print.h"
#include "qemu/error-report.h"
#include "audio_int.h"
@@ -11,7 +10,6 @@ typedef struct {
int freq;
int bits;
int nchannels;
AudioBackend *audio_be;
CaptureVoiceOut *cap;
} WAVState;
@@ -86,7 +84,7 @@ static void wav_capture_destroy (void *opaque)
{
WAVState *wav = opaque;
audio_be_del_capture(wav->audio_be, wav->cap, wav);
AUD_del_capture (wav->cap, wav);
g_free (wav);
}
@@ -137,7 +135,7 @@ int wav_start_capture(AudioBackend *state, CaptureState *s, const char *path,
as.freq = freq;
as.nchannels = 1 << stereo;
as.fmt = bits16 ? AUDIO_FORMAT_S16 : AUDIO_FORMAT_U8;
as.big_endian = false;
as.endianness = 0;
ops.notify = wav_notify;
ops.capture = wav_capture;
@@ -161,7 +159,6 @@ int wav_start_capture(AudioBackend *state, CaptureState *s, const char *path,
return -1;
}
wav->audio_be = state;
wav->path = g_strdup (path);
wav->bits = bits;
wav->nchannels = nchannels;
@@ -172,7 +169,7 @@ int wav_start_capture(AudioBackend *state, CaptureState *s, const char *path,
goto error_free;
}
cap = audio_be_add_capture(wav->audio_be, &as, &ops, wav);
cap = AUD_add_capture(state, &as, &ops, wav);
if (!cap) {
error_report("Failed to add audio capture");
goto error_free;
+1 -1
View File
@@ -218,7 +218,7 @@ static void cryptodev_lkcf_init(CryptoDevBackend *backend, Error **errp)
}
lkcf->eventfd = eventfd(0, 0);
if (lkcf->eventfd < 0) {
error_setg_errno(errp, errno, "Failed to create eventfd");
error_setg(errp, "Failed to create eventfd: %d", errno);
return;
}
+2 -3
View File
@@ -12,8 +12,7 @@
#include "qemu/osdep.h"
#include "system/hostmem.h"
#include "system/ramblock.h"
#include "hw/core/boards.h"
#include "hw/boards.h"
#include "qapi/error.h"
#include "qapi/qapi-builtin-visit.h"
#include "qapi/visitor.h"
@@ -22,7 +21,7 @@
#include "qemu/mmap-alloc.h"
#include "qemu/madvise.h"
#include "qemu/cutils.h"
#include "hw/core/qdev.h"
#include "hw/qdev-core.h"
#ifdef CONFIG_NUMA
#include <numaif.h>
+2 -62
View File
@@ -11,15 +11,9 @@
#include "qemu/osdep.h"
#include "system/igvm.h"
#include "system/igvm-cfg.h"
#include "system/igvm-internal.h"
#include "system/reset.h"
#include "system/igvm.h"
#include "qom/object_interfaces.h"
#include "hw/core/qdev.h"
#include "hw/core/boards.h"
#include "trace.h"
static char *get_igvm(Object *obj, Error **errp)
{
@@ -34,78 +28,24 @@ static void set_igvm(Object *obj, const char *value, Error **errp)
igvm->filename = g_strdup(value);
}
static ResettableState *igvm_reset_state(Object *obj)
{
IgvmCfg *igvm = IGVM_CFG(obj);
return &igvm->reset_state;
}
static void igvm_reset_enter(Object *obj, ResetType type)
{
trace_igvm_reset_enter(type);
}
static void igvm_reset_hold(Object *obj, ResetType type)
{
MachineState *ms = MACHINE(qdev_get_machine());
IgvmCfg *igvm = IGVM_CFG(obj);
trace_igvm_reset_hold(type);
qigvm_process_file(igvm, ms, false, &error_fatal);
}
static void igvm_reset_exit(Object *obj, ResetType type)
{
trace_igvm_reset_exit(type);
}
static void igvm_complete(UserCreatable *uc, Error **errp)
{
IgvmCfg *igvm = IGVM_CFG(uc);
igvm->file = qigvm_file_init(igvm->filename, errp);
}
OBJECT_DEFINE_TYPE_WITH_INTERFACES(IgvmCfg, igvm_cfg, IGVM_CFG, OBJECT,
{ TYPE_USER_CREATABLE },
{ TYPE_RESETTABLE_INTERFACE },
{ NULL })
{ TYPE_USER_CREATABLE }, { NULL })
static void igvm_cfg_class_init(ObjectClass *oc, const void *data)
{
IgvmCfgClass *igvmc = IGVM_CFG_CLASS(oc);
ResettableClass *rc = RESETTABLE_CLASS(oc);
UserCreatableClass *uc = USER_CREATABLE_CLASS(oc);
object_class_property_add_str(oc, "file", get_igvm, set_igvm);
object_class_property_set_description(oc, "file",
"Set the IGVM filename to use");
igvmc->process = qigvm_process_file;
rc->get_state = igvm_reset_state;
rc->phases.enter = igvm_reset_enter;
rc->phases.hold = igvm_reset_hold;
rc->phases.exit = igvm_reset_exit;
uc->complete = igvm_complete;
}
static void igvm_cfg_init(Object *obj)
{
IgvmCfg *igvm = IGVM_CFG(obj);
igvm->file = -1;
qemu_register_resettable(obj);
}
static void igvm_cfg_finalize(Object *obj)
{
IgvmCfg *igvm = IGVM_CFG(obj);
qemu_unregister_resettable(obj);
if (igvm->file >= 0) {
igvm_free(igvm->file);
}
}
+148 -161
View File
@@ -12,20 +12,21 @@
#include "qemu/osdep.h"
#include "qapi/error.h"
#include "qemu/error-report.h"
#include "qemu/target-info-qapi.h"
#include "system/igvm.h"
#include "system/igvm-cfg.h"
#include "system/igvm-internal.h"
#include "system/memory.h"
#include "system/address-spaces.h"
#include "hw/core/cpu.h"
#include "trace.h"
#include <igvm/igvm.h>
#include <igvm/igvm_defs.h>
typedef struct QIgvmParameterData {
QTAILQ_ENTRY(QIgvmParameterData) next;
uint8_t *data;
uint32_t size;
uint32_t index;
} QIgvmParameterData;
/*
* Some directives are specific to particular confidential computing platforms.
@@ -61,19 +62,36 @@ struct QEMU_PACKED sev_id_authentication {
#define IGVM_SEV_ID_BLOCK_VERSION 1
QIgvmParameterData*
qigvm_find_param_entry(QIgvm *igvm, uint32_t parameter_area_index)
{
QIgvmParameterData *param_entry;
QTAILQ_FOREACH(param_entry, &igvm->parameter_data, next)
{
if (param_entry->index == parameter_area_index) {
return param_entry;
}
}
warn_report("IGVM: No parameter area for index %u", parameter_area_index);
return NULL;
}
/*
* QIgvm contains the information required during processing
* of a single IGVM file.
*/
typedef struct QIgvm {
IgvmHandle file;
ConfidentialGuestSupport *cgs;
ConfidentialGuestSupportClass *cgsc;
uint32_t compatibility_mask;
unsigned current_header_index;
QTAILQ_HEAD(, QIgvmParameterData) parameter_data;
IgvmPlatformType platform_type;
/*
* SEV-SNP platforms can contain an ID block and authentication
* that should be verified by the guest.
*/
struct sev_id_block *id_block;
struct sev_id_authentication *id_auth;
/* Define the guest policy for SEV guests */
uint64_t sev_policy;
/* These variables keep track of contiguous page regions */
IGVM_VHS_PAGE_DATA region_prev_page_data;
uint64_t region_start;
unsigned region_start_index;
unsigned region_last_index;
unsigned region_page_count;
} QIgvm;
static int qigvm_directive_page_data(QIgvm *ctx, const uint8_t *header_data,
Error **errp);
@@ -128,8 +146,6 @@ static struct QIGVMHandler handlers[] = {
qigvm_directive_snp_id_block },
{ IGVM_VHT_GUEST_POLICY, IGVM_HEADER_SECTION_INITIALIZATION,
qigvm_initialization_guest_policy },
{ IGVM_VHT_MADT, IGVM_HEADER_SECTION_DIRECTIVE,
qigvm_directive_madt },
};
static int qigvm_handler(QIgvm *ctx, uint32_t type, Error **errp)
@@ -152,17 +168,9 @@ static int qigvm_handler(QIgvm *ctx, uint32_t type, Error **errp)
(int)header_handle);
return -1;
}
header_data = igvm_get_buffer(ctx->file, header_handle);
if (header_data != NULL) {
header_data += sizeof(IGVM_VHS_VARIABLE_HEADER);
result = handlers[handler].handler(ctx, header_data, errp);
} else {
error_setg(errp,
"IGVM: No buffer for handle %d: "
"(type 0x%X)",
header_handle, type);
result = -1;
}
header_data = igvm_get_buffer(ctx->file, header_handle) +
sizeof(IGVM_VHS_VARIABLE_HEADER);
result = handlers[handler].handler(ctx, header_data, errp);
igvm_free_buffer(ctx->file, header_handle);
return result;
}
@@ -187,7 +195,7 @@ static void *qigvm_prepare_memory(QIgvm *ctx, uint64_t addr, uint64_t size,
error_setg(
errp,
"Processing of IGVM file failed: Could not prepare memory "
"at address 0x%" PRIx64 " due to existing non-RAM region",
"at address 0x%lX due to existing non-RAM region",
addr);
return NULL;
}
@@ -198,7 +206,7 @@ static void *qigvm_prepare_memory(QIgvm *ctx, uint64_t addr, uint64_t size,
error_setg(
errp,
"Processing of IGVM file failed: Could not prepare memory "
"at address 0x%" PRIx64 ": region size exceeded",
"at address 0x%lX: region size exceeded",
addr);
return NULL;
}
@@ -212,17 +220,14 @@ static void *qigvm_prepare_memory(QIgvm *ctx, uint64_t addr, uint64_t size,
g_autofree char *region_name =
g_strdup_printf("igvm.%X", region_identifier);
igvm_pages = g_new0(MemoryRegion, 1);
if (ctx->machine_state->cgs &&
ctx->machine_state->cgs->require_guest_memfd) {
if (ctx->cgs && ctx->cgs->require_guest_memfd) {
if (!memory_region_init_ram_guest_memfd(igvm_pages, NULL,
region_name, size, errp)) {
g_free(igvm_pages);
return NULL;
}
} else {
if (!memory_region_init_ram(igvm_pages, NULL, region_name, size,
errp)) {
g_free(igvm_pages);
return NULL;
}
}
@@ -326,11 +331,6 @@ static int qigvm_process_mem_region(QIgvm *ctx, unsigned start_index,
return -1;
}
data = igvm_get_buffer(ctx->file, data_handle);
if (data == NULL) {
error_setg(errp, "IGVM: No buffer for handle %d", data_handle);
igvm_free_buffer(ctx->file, data_handle);
return -1;
}
memcpy(&region[page_index * page_size], data, data_size);
igvm_free_buffer(ctx->file, data_handle);
}
@@ -340,7 +340,7 @@ static int qigvm_process_mem_region(QIgvm *ctx, unsigned start_index,
* If a confidential guest support object is provided then use it to set the
* guest state.
*/
if (ctx->machine_state->cgs) {
if (ctx->cgs) {
cgs_page_type =
qigvm_type_to_cgs_type(page_type, flags->unmeasured, zero);
if (cgs_page_type < 0) {
@@ -441,13 +441,8 @@ static int qigvm_directive_vp_context(QIgvm *ctx, const uint8_t *header_data,
}
data = (uint8_t *)igvm_get_buffer(ctx->file, data_handle);
if (data == NULL) {
error_setg(errp, "IGVM: No buffer for handle %d", data_handle);
result = -1;
goto exit;
}
if (ctx->machine_state->cgs) {
if (ctx->cgs) {
result = ctx->cgsc->set_guest_state(
vp_context->gpa, data, igvm_get_buffer_size(ctx->file, data_handle),
CGS_PAGE_TYPE_VMSA, vp_context->vp_index, errp);
@@ -461,7 +456,6 @@ static int qigvm_directive_vp_context(QIgvm *ctx, const uint8_t *header_data,
result = -1;
}
exit:
igvm_free_buffer(ctx->file, data_handle);
if (result < 0) {
return result;
@@ -500,31 +494,31 @@ static int qigvm_directive_parameter_insert(QIgvm *ctx,
return 0;
}
param_entry = qigvm_find_param_entry(ctx, param->parameter_area_index);
if (param_entry == NULL) {
return 0;
}
QTAILQ_FOREACH(param_entry, &ctx->parameter_data, next)
{
if (param_entry->index == param->parameter_area_index) {
region = qigvm_prepare_memory(ctx, param->gpa, param_entry->size,
ctx->current_header_index, errp);
if (!region) {
return -1;
}
memcpy(region, param_entry->data, param_entry->size);
g_free(param_entry->data);
param_entry->data = NULL;
region = qigvm_prepare_memory(ctx, param->gpa, param_entry->size,
ctx->current_header_index, errp);
if (!region) {
return -1;
}
memcpy(region, param_entry->data, param_entry->size);
g_free(param_entry->data);
param_entry->data = NULL;
/*
* If a confidential guest support object is provided then use it to
* set the guest state.
*/
if (ctx->machine_state->cgs) {
result = ctx->cgsc->set_guest_state(param->gpa, region,
param_entry->size,
CGS_PAGE_TYPE_UNMEASURED, 0,
errp);
if (result < 0) {
return -1;
/*
* If a confidential guest support object is provided then use it to
* set the guest state.
*/
if (ctx->cgs) {
result = ctx->cgsc->set_guest_state(param->gpa, region,
param_entry->size,
CGS_PAGE_TYPE_UNMEASURED, 0,
errp);
if (result < 0) {
return -1;
}
}
}
}
return 0;
@@ -559,7 +553,7 @@ static int qigvm_directive_memory_map(QIgvm *ctx, const uint8_t *header_data,
ConfidentialGuestMemoryMapEntry cgmm_entry;
int retval = 0;
if (ctx->machine_state->cgs && ctx->cgsc->get_mem_map_entry) {
if (ctx->cgs && ctx->cgsc->get_mem_map_entry) {
get_mem_map_entry = ctx->cgsc->get_mem_map_entry;
} else if (target_arch() == SYS_EMU_TARGET_X86_64) {
@@ -573,54 +567,58 @@ static int qigvm_directive_memory_map(QIgvm *ctx, const uint8_t *header_data,
}
/* Find the parameter area that should hold the memory map */
param_entry = qigvm_find_param_entry(ctx, param->parameter_area_index);
if (param_entry == NULL) {
return 0;
}
QTAILQ_FOREACH(param_entry, &ctx->parameter_data, next)
{
if (param_entry->index == param->parameter_area_index) {
max_entry_count =
param_entry->size / sizeof(IGVM_VHS_MEMORY_MAP_ENTRY);
mm_entry = (IGVM_VHS_MEMORY_MAP_ENTRY *)param_entry->data;
max_entry_count = param_entry->size / sizeof(IGVM_VHS_MEMORY_MAP_ENTRY);
mm_entry = (IGVM_VHS_MEMORY_MAP_ENTRY *)param_entry->data;
retval = get_mem_map_entry(entry, &cgmm_entry, errp);
while (retval == 0) {
if (entry >= max_entry_count) {
error_setg(
errp,
"IGVM: guest memory map size exceeds parameter area defined in IGVM file");
return -1;
}
mm_entry[entry].starting_gpa_page_number = cgmm_entry.gpa >> 12;
mm_entry[entry].number_of_pages = cgmm_entry.size >> 12;
retval = get_mem_map_entry(entry, &cgmm_entry, errp);
while (retval == 0) {
if (entry >= max_entry_count) {
error_setg(
errp,
"IGVM: guest memory map size exceeds parameter area defined "
"in IGVM file");
return -1;
}
mm_entry[entry].starting_gpa_page_number = cgmm_entry.gpa >> 12;
mm_entry[entry].number_of_pages = cgmm_entry.size >> 12;
switch (cgmm_entry.type) {
case CGS_MEM_RAM:
mm_entry[entry].entry_type =
IGVM_MEMORY_MAP_ENTRY_TYPE_MEMORY;
break;
case CGS_MEM_RESERVED:
mm_entry[entry].entry_type =
IGVM_MEMORY_MAP_ENTRY_TYPE_PLATFORM_RESERVED;
break;
case CGS_MEM_ACPI:
mm_entry[entry].entry_type =
IGVM_MEMORY_MAP_ENTRY_TYPE_PLATFORM_RESERVED;
break;
case CGS_MEM_NVS:
mm_entry[entry].entry_type =
IGVM_MEMORY_MAP_ENTRY_TYPE_PERSISTENT;
break;
case CGS_MEM_UNUSABLE:
mm_entry[entry].entry_type =
IGVM_MEMORY_MAP_ENTRY_TYPE_PLATFORM_RESERVED;
break;
}
retval = get_mem_map_entry(++entry, &cgmm_entry, errp);
}
if (retval < 0) {
return retval;
}
/* The entries need to be sorted */
qsort(mm_entry, entry, sizeof(IGVM_VHS_MEMORY_MAP_ENTRY),
qigvm_cmp_mm_entry);
switch (cgmm_entry.type) {
case CGS_MEM_RAM:
mm_entry[entry].entry_type = IGVM_MEMORY_MAP_ENTRY_TYPE_MEMORY;
break;
case CGS_MEM_RESERVED:
mm_entry[entry].entry_type =
IGVM_MEMORY_MAP_ENTRY_TYPE_PLATFORM_RESERVED;
break;
case CGS_MEM_ACPI:
mm_entry[entry].entry_type =
IGVM_MEMORY_MAP_ENTRY_TYPE_PLATFORM_RESERVED;
break;
case CGS_MEM_NVS:
mm_entry[entry].entry_type = IGVM_MEMORY_MAP_ENTRY_TYPE_PERSISTENT;
break;
case CGS_MEM_UNUSABLE:
mm_entry[entry].entry_type =
IGVM_MEMORY_MAP_ENTRY_TYPE_PLATFORM_RESERVED;
break;
}
retval = get_mem_map_entry(++entry, &cgmm_entry, errp);
}
if (retval < 0) {
return retval;
}
/* The entries need to be sorted */
qsort(mm_entry, entry, sizeof(IGVM_VHS_MEMORY_MAP_ENTRY),
qigvm_cmp_mm_entry);
return 0;
}
@@ -632,18 +630,18 @@ static int qigvm_directive_vp_count(QIgvm *ctx, const uint8_t *header_data,
uint32_t *vp_count;
CPUState *cpu;
param_entry = qigvm_find_param_entry(ctx, param->parameter_area_index);
if (param_entry == NULL) {
return 0;
}
vp_count = (uint32_t *)(param_entry->data + param->byte_offset);
*vp_count = 0;
CPU_FOREACH(cpu)
QTAILQ_FOREACH(param_entry, &ctx->parameter_data, next)
{
(*vp_count)++;
if (param_entry->index == param->parameter_area_index) {
vp_count = (uint32_t *)(param_entry->data + param->byte_offset);
*vp_count = 0;
CPU_FOREACH(cpu)
{
(*vp_count)++;
}
break;
}
}
return 0;
}
@@ -655,15 +653,15 @@ static int qigvm_directive_environment_info(QIgvm *ctx,
QIgvmParameterData *param_entry;
IgvmEnvironmentInfo *environmental_state;
param_entry = qigvm_find_param_entry(ctx, param->parameter_area_index);
if (param_entry == NULL) {
return 0;
QTAILQ_FOREACH(param_entry, &ctx->parameter_data, next)
{
if (param_entry->index == param->parameter_area_index) {
environmental_state =
(IgvmEnvironmentInfo *)(param_entry->data + param->byte_offset);
environmental_state->memory_is_shared = 1;
break;
}
}
environmental_state =
(IgvmEnvironmentInfo *)(param_entry->data + param->byte_offset);
environmental_state->memory_is_shared = 1;
return 0;
}
@@ -685,7 +683,7 @@ static int qigvm_directive_required_memory(QIgvm *ctx,
if (!region) {
return -1;
}
if (ctx->machine_state->cgs) {
if (ctx->cgs) {
result =
ctx->cgsc->set_guest_state(mem->gpa, region, mem->number_of_bytes,
CGS_PAGE_TYPE_REQUIRED_MEMORY, 0, errp);
@@ -799,24 +797,18 @@ static int qigvm_supported_platform_compat_mask(QIgvm *ctx, Error **errp)
}
platform =
(IGVM_VHS_SUPPORTED_PLATFORM *)(igvm_get_buffer(ctx->file,
header_handle));
if (platform == NULL) {
error_setg(errp, "IGVM: No buffer for handle %d", header_handle);
igvm_free_buffer(ctx->file, header_handle);
return -1;
}
platform = (IGVM_VHS_SUPPORTED_PLATFORM *)((void *)platform
+ sizeof(IGVM_VHS_VARIABLE_HEADER));
header_handle) +
sizeof(
IGVM_VHS_VARIABLE_HEADER));
if ((platform->platform_type == IGVM_PLATFORM_TYPE_SEV_ES) &&
ctx->machine_state->cgs) {
ctx->cgs) {
if (ctx->cgsc->check_support(
CGS_PLATFORM_SEV_ES, platform->platform_version,
platform->highest_vtl, platform->shared_gpa_boundary)) {
compatibility_mask_sev_es = platform->compatibility_mask;
}
} else if ((platform->platform_type == IGVM_PLATFORM_TYPE_SEV) &&
ctx->machine_state->cgs) {
ctx->cgs) {
if (ctx->cgsc->check_support(
CGS_PLATFORM_SEV, platform->platform_version,
platform->highest_vtl, platform->shared_gpa_boundary)) {
@@ -824,7 +816,7 @@ static int qigvm_supported_platform_compat_mask(QIgvm *ctx, Error **errp)
}
} else if ((platform->platform_type ==
IGVM_PLATFORM_TYPE_SEV_SNP) &&
ctx->machine_state->cgs) {
ctx->cgs) {
if (ctx->cgsc->check_support(
CGS_PLATFORM_SEV_SNP, platform->platform_version,
platform->highest_vtl, platform->shared_gpa_boundary)) {
@@ -875,7 +867,7 @@ static int qigvm_handle_policy(QIgvm *ctx, Error **errp)
return 0;
}
IgvmHandle qigvm_file_init(char *filename, Error **errp)
static IgvmHandle qigvm_file_init(char *filename, Error **errp)
{
IgvmHandle igvm;
g_autofree uint8_t *buf = NULL;
@@ -892,12 +884,10 @@ IgvmHandle qigvm_file_init(char *filename, Error **errp)
error_setg(errp, "Unable to parse IGVM file %s: %d", filename, igvm);
return -1;
}
trace_igvm_file_loaded(filename, igvm);
return igvm;
}
int qigvm_process_file(IgvmCfg *cfg, MachineState *machine_state,
int qigvm_process_file(IgvmCfg *cfg, ConfidentialGuestSupport *cgs,
bool onlyVpContext, Error **errp)
{
int32_t header_count;
@@ -906,23 +896,18 @@ int qigvm_process_file(IgvmCfg *cfg, MachineState *machine_state,
QIgvm ctx;
memset(&ctx, 0, sizeof(ctx));
if (cfg->file < 0) {
error_setg(errp, "No IGVM file loaded.");
ctx.file = qigvm_file_init(cfg->filename, errp);
if (ctx.file < 0) {
return -1;
}
ctx.file = cfg->file;
trace_igvm_process_file(cfg->file, onlyVpContext);
ctx.machine_state = machine_state;
/*
* The ConfidentialGuestSupport object is optional and allows a confidential
* guest platform to perform extra processing, such as page measurement, on
* IGVM directives.
*/
ctx.cgsc = machine_state->cgs ?
CONFIDENTIAL_GUEST_SUPPORT_GET_CLASS(machine_state->cgs) :
NULL;
ctx.cgs = cgs;
ctx.cgsc = cgs ? CONFIDENTIAL_GUEST_SUPPORT_GET_CLASS(cgs) : NULL;
/*
* Check that the IGVM file provides configuration for the current
@@ -1005,5 +990,7 @@ cleanup_parameters:
g_free(ctx.id_auth);
cleanup:
igvm_free(ctx.file);
return retval;
}
+3 -112
View File
@@ -82,9 +82,6 @@ static void iommufd_backend_complete(UserCreatable *uc, Error **errp)
} else {
cpr_save_fd(name, 0, be->fd);
}
} else if (!g_file_test("/dev/iommu", G_FILE_TEST_EXISTS)) {
error_setg(errp, "/dev/iommu does not exist"
" (is your kernel config missing CONFIG_IOMMUFD?)");
}
}
@@ -364,7 +361,7 @@ bool iommufd_backend_get_dirty_bitmap(IOMMUFDBackend *be,
uint32_t hwpt_id,
uint64_t iova, ram_addr_t size,
uint64_t page_size, uint64_t *data,
uint64_t flags, Error **errp)
Error **errp)
{
int ret;
struct iommu_hwpt_get_dirty_bitmap get_dirty_bitmap = {
@@ -374,12 +371,11 @@ bool iommufd_backend_get_dirty_bitmap(IOMMUFDBackend *be,
.length = size,
.page_size = page_size,
.data = (uintptr_t)data,
.flags = flags,
};
ret = ioctl(be->fd, IOMMU_HWPT_GET_DIRTY_BITMAP, &get_dirty_bitmap);
trace_iommufd_backend_get_dirty_bitmap(be->fd, hwpt_id, iova, size,
flags, page_size, ret ? errno : 0);
page_size, ret ? errno : 0);
if (ret) {
error_setg_errno(errp, errno,
"IOMMU_HWPT_GET_DIRTY_BITMAP (iova: 0x%"HWADDR_PRIx
@@ -392,8 +388,7 @@ bool iommufd_backend_get_dirty_bitmap(IOMMUFDBackend *be,
bool iommufd_backend_get_device_info(IOMMUFDBackend *be, uint32_t devid,
uint32_t *type, void *data, uint32_t len,
uint64_t *caps, uint8_t *max_pasid_log2,
Error **errp)
uint64_t *caps, Error **errp)
{
struct iommu_hw_info info = {
.size = sizeof(info),
@@ -412,9 +407,6 @@ bool iommufd_backend_get_device_info(IOMMUFDBackend *be, uint32_t devid,
g_assert(caps);
*caps = info.out_capabilities;
if (max_pasid_log2) {
*max_pasid_log2 = info.out_max_pasid_log2;
}
return true;
}
@@ -454,90 +446,6 @@ bool iommufd_backend_invalidate_cache(IOMMUFDBackend *be, uint32_t id,
return !ret;
}
bool iommufd_backend_alloc_viommu(IOMMUFDBackend *be, uint32_t dev_id,
uint32_t viommu_type, uint32_t hwpt_id,
uint32_t *out_viommu_id, Error **errp)
{
int ret;
struct iommu_viommu_alloc alloc_viommu = {
.size = sizeof(alloc_viommu),
.type = viommu_type,
.dev_id = dev_id,
.hwpt_id = hwpt_id,
};
ret = ioctl(be->fd, IOMMU_VIOMMU_ALLOC, &alloc_viommu);
trace_iommufd_backend_alloc_viommu(be->fd, dev_id, viommu_type, hwpt_id,
alloc_viommu.out_viommu_id, ret);
if (ret) {
error_setg_errno(errp, errno, "IOMMU_VIOMMU_ALLOC failed");
return false;
}
g_assert(out_viommu_id);
*out_viommu_id = alloc_viommu.out_viommu_id;
return true;
}
bool iommufd_backend_alloc_vdev(IOMMUFDBackend *be, uint32_t dev_id,
uint32_t viommu_id, uint64_t virt_id,
uint32_t *out_vdev_id, Error **errp)
{
int ret;
struct iommu_vdevice_alloc alloc_vdev = {
.size = sizeof(alloc_vdev),
.viommu_id = viommu_id,
.dev_id = dev_id,
.virt_id = virt_id,
};
ret = ioctl(be->fd, IOMMU_VDEVICE_ALLOC, &alloc_vdev);
trace_iommufd_backend_alloc_vdev(be->fd, dev_id, viommu_id, virt_id,
alloc_vdev.out_vdevice_id, ret);
if (ret) {
error_setg_errno(errp, errno, "IOMMU_VDEVICE_ALLOC failed");
return false;
}
g_assert(out_vdev_id);
*out_vdev_id = alloc_vdev.out_vdevice_id;
return true;
}
bool iommufd_backend_alloc_veventq(IOMMUFDBackend *be, uint32_t viommu_id,
uint32_t type, uint32_t depth,
uint32_t *out_veventq_id,
uint32_t *out_veventq_fd, Error **errp)
{
int ret;
struct iommu_veventq_alloc alloc_veventq = {
.size = sizeof(alloc_veventq),
.flags = 0,
.type = type,
.veventq_depth = depth,
.viommu_id = viommu_id,
};
ret = ioctl(be->fd, IOMMU_VEVENTQ_ALLOC, &alloc_veventq);
trace_iommufd_viommu_alloc_eventq(be->fd, viommu_id, type,
alloc_veventq.out_veventq_id,
alloc_veventq.out_veventq_fd, ret);
if (ret) {
error_setg_errno(errp, errno, "IOMMU_VEVENTQ_ALLOC failed");
return false;
}
g_assert(out_veventq_id);
g_assert(out_veventq_fd);
*out_veventq_id = alloc_veventq.out_veventq_id;
*out_veventq_fd = alloc_veventq.out_veventq_fd;
return true;
}
bool host_iommu_device_iommufd_attach_hwpt(HostIOMMUDeviceIOMMUFD *idev,
uint32_t hwpt_id, Error **errp)
{
@@ -573,28 +481,11 @@ static int hiod_iommufd_get_cap(HostIOMMUDevice *hiod, int cap, Error **errp)
}
}
static bool hiod_iommufd_get_pasid_info(HostIOMMUDevice *hiod,
PasidInfo *pasid_info)
{
HostIOMMUDeviceCaps *caps = &hiod->caps;
if (!caps->max_pasid_log2) {
return false;
}
g_assert(pasid_info);
pasid_info->exec_perm = (caps->hw_caps & IOMMU_HW_CAP_PCI_PASID_EXEC);
pasid_info->priv_mod = (caps->hw_caps & IOMMU_HW_CAP_PCI_PASID_PRIV);
pasid_info->max_pasid_log2 = caps->max_pasid_log2;
return true;
}
static void hiod_iommufd_class_init(ObjectClass *oc, const void *data)
{
HostIOMMUDeviceClass *hioc = HOST_IOMMU_DEVICE_CLASS(oc);
hioc->get_cap = hiod_iommufd_get_cap;
hioc->get_pasid_info = hiod_iommufd_get_pasid_info;
};
static const TypeInfo types[] = {
+4 -4
View File
@@ -13,8 +13,8 @@
#include "qemu/osdep.h"
#include "system/spdm-socket.h"
#include "qapi/error.h"
#include "hw/core/qdev-properties.h"
#include "hw/core/qdev-properties-system.h"
#include "hw/qdev-properties.h"
#include "hw/qdev-properties-system.h"
#include "hw/core/qdev-prop-internal.h"
static bool read_bytes(const int socket, uint8_t *buffer,
@@ -167,7 +167,7 @@ int spdm_socket_connect(uint16_t port, Error **errp)
client_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (client_socket < 0) {
error_setg_errno(errp, errno, "cannot create socket");
error_setg(errp, "cannot create socket: %s", strerror(errno));
return -1;
}
@@ -179,7 +179,7 @@ int spdm_socket_connect(uint16_t port, Error **errp)
if (connect(client_socket, (struct sockaddr *)&server_addr,
sizeof(server_addr)) < 0) {
error_setg_errno(errp, errno, "cannot connect");
error_setg(errp, "cannot connect: %s", strerror(errno));
close(client_socket);
return -1;
}
+38 -24
View File
@@ -225,7 +225,8 @@ static int tpm_emulator_set_locality(TPMEmulator *tpm_emu, uint8_t locty_number,
if (tpm_emulator_ctrlcmd(tpm_emu, CMD_SET_LOCALITY, &loc,
sizeof(loc), sizeof(loc.u.resp.tpm_result),
sizeof(loc)) < 0) {
error_setg(errp, "tpm-emulator: could not set locality");
error_setg(errp, "tpm-emulator: could not set locality : %s",
strerror(errno));
return -1;
}
@@ -263,7 +264,7 @@ static int tpm_emulator_probe_caps(TPMEmulator *tpm_emu)
if (tpm_emulator_ctrlcmd(tpm_emu, CMD_GET_CAPABILITY, &cap_n, 0,
sizeof(cap_n.u.resp.tpm_result),
sizeof(cap_n)) < 0) {
error_report("tpm-emulator: probing failed");
error_report("tpm-emulator: probing failed : %s", strerror(errno));
return -1;
}
@@ -314,7 +315,8 @@ static int tpm_emulator_stop_tpm(TPMBackend *tb, Error **errp)
if (tpm_emulator_ctrlcmd(tpm_emu, CMD_STOP, &res, 0,
sizeof(ptm_res), sizeof(res)) < 0) {
error_setg(errp, "tpm-emulator: Could not stop TPM");
error_setg(errp, "tpm-emulator: Could not stop TPM: %s",
strerror(errno));
return -1;
}
@@ -342,7 +344,8 @@ static int tpm_emulator_lock_storage(TPMEmulator *tpm_emu)
if (tpm_emulator_ctrlcmd(tpm_emu, CMD_LOCK_STORAGE, &pls, sizeof(pls.u.req),
sizeof(pls.u.resp.tpm_result),
sizeof(pls.u.resp)) < 0) {
error_report("tpm-emulator: Could not lock storage within 3 seconds");
error_report("tpm-emulator: Could not lock storage within 3 seconds: "
"%s", strerror(errno));
return -1;
}
@@ -374,7 +377,8 @@ static int tpm_emulator_set_buffer_size(TPMBackend *tb,
if (tpm_emulator_ctrlcmd(tpm_emu, CMD_SET_BUFFERSIZE, &psbs,
sizeof(psbs.u.req), sizeof(psbs.u.resp.tpm_result),
sizeof(psbs.u.resp)) < 0) {
error_setg(errp, "tpm-emulator: Could not set buffer size");
error_setg(errp, "tpm-emulator: Could not set buffer size: %s",
strerror(errno));
return -1;
}
@@ -422,7 +426,8 @@ static int tpm_emulator_startup_tpm_resume(TPMBackend *tb, size_t buffersize,
if (tpm_emulator_ctrlcmd(tpm_emu, CMD_INIT, &init, sizeof(init),
sizeof(init.u.resp.tpm_result),
sizeof(init)) < 0) {
error_setg(errp, "tpm-emulator: could not send INIT");
error_setg(errp, "tpm-emulator: could not send INIT: %s",
strerror(errno));
goto err_exit;
}
@@ -477,7 +482,8 @@ static bool tpm_emulator_get_tpm_established_flag(TPMBackend *tb)
if (tpm_emulator_ctrlcmd(tpm_emu, CMD_GET_TPMESTABLISHED, &est, 0,
sizeof(est) /* always returns resp.bit */,
sizeof(est)) < 0) {
error_report("tpm-emulator: Could not get the TPM established flag");
error_report("tpm-emulator: Could not get the TPM established flag: %s",
strerror(errno));
return false;
}
trace_tpm_emulator_get_tpm_established_flag(est.u.resp.bit);
@@ -505,7 +511,8 @@ static int tpm_emulator_reset_tpm_established_flag(TPMBackend *tb,
&reset_est, sizeof(reset_est),
sizeof(reset_est.u.resp.tpm_result),
sizeof(reset_est)) < 0) {
error_report("tpm-emulator: Could not reset the establishment bit");
error_report("tpm-emulator: Could not reset the establishment bit: %s",
strerror(errno));
return -1;
}
@@ -535,7 +542,8 @@ static void tpm_emulator_cancel_cmd(TPMBackend *tb)
/* FIXME: make the function non-blocking, or it may block a VCPU */
if (tpm_emulator_ctrlcmd(tpm_emu, CMD_CANCEL_TPM_CMD, &res, 0,
sizeof(ptm_res), sizeof(res)) < 0) {
error_report("tpm-emulator: Could not cancel command");
error_report("tpm-emulator: Could not cancel command: %s",
strerror(errno));
} else if (res != 0) {
error_report("tpm-emulator: Failed to cancel TPM: 0x%x",
be32_to_cpu(res));
@@ -552,10 +560,8 @@ static TPMVersion tpm_emulator_get_tpm_version(TPMBackend *tb)
static size_t tpm_emulator_get_buffer_size(TPMBackend *tb)
{
size_t actual_size;
Error *local_err = NULL;
if (tpm_emulator_set_buffer_size(tb, 0, &actual_size, &local_err) < 0) {
error_report_err(local_err);
if (tpm_emulator_set_buffer_size(tb, 0, &actual_size, NULL) < 0) {
return 4096;
}
@@ -596,7 +602,8 @@ static int tpm_emulator_prepare_data_fd(TPMEmulator *tpm_emu)
if (tpm_emulator_ctrlcmd(tpm_emu, CMD_SET_DATAFD, &res, 0,
sizeof(ptm_res), sizeof(res)) < 0 || res != 0) {
error_report("tpm-emulator: Failed to send CMD_SET_DATAFD");
error_report("tpm-emulator: Failed to send CMD_SET_DATAFD: %s",
strerror(errno));
goto err_exit;
}
@@ -653,8 +660,8 @@ static int tpm_emulator_handle_device_opts(TPMEmulator *tpm_emu, QemuOpts *opts)
*/
if (tpm_util_test_tpmdev(QIO_CHANNEL_SOCKET(tpm_emu->data_ioc)->fd,
&tpm_emu->tpm_version)) {
error_report("'%s' is not emulating TPM device.",
tpm_emu->options->chardev);
error_report("'%s' is not emulating TPM device. Error: %s",
tpm_emu->options->chardev, strerror(errno));
goto err;
}
@@ -744,7 +751,8 @@ static int tpm_emulator_get_state_blob(TPMEmulator *tpm_emu,
/* always returns up to resp.data */
offsetof(ptm_getstate, u.resp.data),
offsetof(ptm_getstate, u.resp.data)) < 0) {
error_report("tpm-emulator: could not get state blob type %d", type);
error_report("tpm-emulator: could not get state blob type %d : %s",
type, strerror(errno));
return -1;
}
@@ -846,8 +854,9 @@ static int tpm_emulator_set_state_blob(TPMEmulator *tpm_emu,
/* write the header only */
if (tpm_emulator_ctrlcmd(tpm_emu, CMD_SET_STATEBLOB, &pss,
offsetof(ptm_setstate, u.req.data), 0, 0) < 0) {
error_setg(errp, "tpm-emulator: could not set state blob type %d",
type);
error_setg_errno(errp, errno,
"tpm-emulator: could not set state blob type %d",
type);
return -1;
}
@@ -885,8 +894,10 @@ static int tpm_emulator_set_state_blob(TPMEmulator *tpm_emu,
/*
* Set all the TPM state blobs.
*
* Returns a negative errno code in case of error.
*/
static bool tpm_emulator_set_state_blobs(TPMBackend *tb, Error **errp)
static int tpm_emulator_set_state_blobs(TPMBackend *tb, Error **errp)
{
TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
TPMBlobBuffers *state_blobs = &tpm_emu->state_blobs;
@@ -895,7 +906,7 @@ static bool tpm_emulator_set_state_blobs(TPMBackend *tb, Error **errp)
if (tpm_emulator_stop_tpm(tb, errp) < 0) {
trace_tpm_emulator_set_state_blobs_error("Could not stop TPM");
return false;
return -EIO;
}
if (tpm_emulator_set_state_blob(tpm_emu, PTM_BLOB_TYPE_PERMANENT,
@@ -907,12 +918,12 @@ static bool tpm_emulator_set_state_blobs(TPMBackend *tb, Error **errp)
tpm_emulator_set_state_blob(tpm_emu, PTM_BLOB_TYPE_SAVESTATE,
&state_blobs->savestate,
state_blobs->savestate_flags, errp) < 0) {
return false;
return -EIO;
}
trace_tpm_emulator_set_state_blobs_done();
return true;
return 0;
}
static int tpm_emulator_pre_save(void *opaque)
@@ -955,8 +966,10 @@ static void tpm_emulator_vm_state_change(void *opaque, bool running,
static bool tpm_emulator_post_load(void *opaque, int version_id, Error **errp)
{
TPMBackend *tb = opaque;
int ret;
if (!tpm_emulator_set_state_blobs(tb, errp)) {
ret = tpm_emulator_set_state_blobs(tb, errp);
if (ret < 0) {
return false;
}
@@ -1025,7 +1038,8 @@ static void tpm_emulator_shutdown(TPMEmulator *tpm_emu)
if (tpm_emulator_ctrlcmd(tpm_emu, CMD_SHUTDOWN, &res, 0,
sizeof(ptm_res), sizeof(res)) < 0) {
error_report("tpm-emulator: Could not cleanly shutdown the TPM");
error_report("tpm-emulator: Could not cleanly shutdown the TPM: %s",
strerror(errno));
} else if (res != 0) {
error_report("tpm-emulator: TPM result for shutdown: 0x%x %s",
be32_to_cpu(res), tpm_emulator_strerror(be32_to_cpu(res)));
+1 -2
View File
@@ -26,7 +26,7 @@
#include "qapi/visitor.h"
#include "tpm_int.h"
#include "system/memory.h"
#include "hw/core/qdev-properties.h"
#include "hw/qdev-properties.h"
#include "system/tpm_backend.h"
#include "system/tpm_util.h"
#include "trace.h"
@@ -72,7 +72,6 @@ static void release_tpm(Object *obj, const char *name, void *opaque)
if (*be) {
tpm_backend_reset(*be);
*be = NULL;
}
}
+1 -11
View File
@@ -19,15 +19,5 @@ iommufd_backend_alloc_ioas(int iommufd, uint32_t ioas) " iommufd=%d ioas=%d"
iommufd_backend_alloc_hwpt(int iommufd, uint32_t dev_id, uint32_t pt_id, uint32_t flags, uint32_t hwpt_type, uint32_t len, uint64_t data_ptr, uint32_t out_hwpt_id, int ret) " iommufd=%d dev_id=%u pt_id=%u flags=0x%x hwpt_type=%u len=%u data_ptr=0x%"PRIx64" out_hwpt=%u (%d)"
iommufd_backend_free_id(int iommufd, uint32_t id, int ret) " iommufd=%d id=%d (%d)"
iommufd_backend_set_dirty(int iommufd, uint32_t hwpt_id, bool start, int ret) " iommufd=%d hwpt=%u enable=%d (%d)"
iommufd_backend_get_dirty_bitmap(int iommufd, uint32_t hwpt_id, uint64_t iova, uint64_t size, uint64_t flags, uint64_t page_size, int ret) " iommufd=%d hwpt=%u iova=0x%"PRIx64" size=0x%"PRIx64" flags=0x%"PRIx64" page_size=0x%"PRIx64" (%d)"
iommufd_backend_get_dirty_bitmap(int iommufd, uint32_t hwpt_id, uint64_t iova, uint64_t size, uint64_t page_size, int ret) " iommufd=%d hwpt=%u iova=0x%"PRIx64" size=0x%"PRIx64" page_size=0x%"PRIx64" (%d)"
iommufd_backend_invalidate_cache(int iommufd, uint32_t id, uint32_t data_type, uint32_t entry_len, uint32_t entry_num, uint32_t done_num, uint64_t data_ptr, int ret) " iommufd=%d id=%u data_type=%u entry_len=%u entry_num=%u done_num=%u data_ptr=0x%"PRIx64" (%d)"
iommufd_backend_alloc_viommu(int iommufd, uint32_t dev_id, uint32_t type, uint32_t hwpt_id, uint32_t viommu_id, int ret) " iommufd=%d type=%u dev_id=%u hwpt_id=%u viommu_id=%u (%d)"
iommufd_backend_alloc_vdev(int iommufd, uint32_t dev_id, uint32_t viommu_id, uint64_t virt_id, uint32_t vdev_id, int ret) " iommufd=%d dev_id=%u viommu_id=%u virt_id=0x%"PRIx64" vdev_id=%u (%d)"
iommufd_viommu_alloc_eventq(int iommufd, uint32_t viommu_id, uint32_t type, uint32_t veventq_id, uint32_t veventq_fd, int ret) " iommufd=%d viommu_id=%u type=%u veventq_id=%u veventq_fd=%u (%d)"
# igvm-cfg.c
igvm_reset_enter(int type) "type=%u"
igvm_reset_hold(int type) "type=%u"
igvm_reset_exit(int type) "type=%u"
igvm_file_loaded(const char *fn, int32_t handle) "fn=%s, handle=0x%x"
igvm_process_file(int32_t handle, bool context_only) "handle=0x%x context-only=%d"
+3 -3
View File
@@ -8477,7 +8477,7 @@ static bool bdrv_bsc_range_overlaps_locked(BlockDriverState *bs,
}
/**
* See block_int-io.h for this function's documentation.
* See block_int.h for this function's documentation.
*/
bool bdrv_bsc_is_data(BlockDriverState *bs, int64_t offset, int64_t *pnum)
{
@@ -8487,7 +8487,7 @@ bool bdrv_bsc_is_data(BlockDriverState *bs, int64_t offset, int64_t *pnum)
}
/**
* See block_int-io.h for this function's documentation.
* See block_int.h for this function's documentation.
*/
void bdrv_bsc_invalidate_range(BlockDriverState *bs,
int64_t offset, int64_t bytes)
@@ -8501,7 +8501,7 @@ void bdrv_bsc_invalidate_range(BlockDriverState *bs,
}
/**
* See block_int-io.h for this function's documentation.
* See block_int.h for this function's documentation.
*/
void bdrv_bsc_fill(BlockDriverState *bs, int64_t offset, int64_t bytes)
{
+1 -9
View File
@@ -73,6 +73,7 @@ bool block_acct_setup(BlockAcctStats *stats, enum OnOffAuto account_invalid,
}
block_acct_add_interval(stats, stats_intervals[i]);
}
g_free(stats_intervals);
}
return true;
}
@@ -185,15 +186,6 @@ int block_latency_histogram_set(BlockAcctStats *stats, enum BlockAcctType type,
prev = entry->value;
}
/*
* block_latency_histogram_account() assumes that it can always access
* hist->boundaries[0], so require at least one boundary. A histogram with
* a single bin is useless anyway.
*/
if (new_nbins <= 1) {
return -EINVAL;
}
hist->nbins = new_nbins;
g_free(hist->boundaries);
hist->boundaries = g_new(uint64_t, hist->nbins - 1);
+1 -1
View File
@@ -23,7 +23,7 @@
*/
#include "qemu/osdep.h"
#include "qemu/aio.h"
#include "block/aio.h"
#include "block/aio_task.h"
struct AioTaskPool {
+2 -15
View File
@@ -95,7 +95,6 @@ typedef struct BlkdebugRule {
int immediately;
int once;
int64_t offset;
int64_t delay_ns;
} inject;
struct {
int new_state;
@@ -145,10 +144,6 @@ static QemuOptsList inject_error_opts = {
.name = "immediately",
.type = QEMU_OPT_BOOL,
},
{
.name = "delay-ns",
.type = QEMU_OPT_NUMBER,
},
{ /* end of list */ }
},
};
@@ -221,8 +216,6 @@ 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;
@@ -295,7 +288,7 @@ static int read_config(BDRVBlkdebugState *s, const char *filename,
if (filename) {
f = fopen(filename, "r");
if (f == NULL) {
error_setg_file_open(errp, errno, filename);
error_setg_errno(errp, errno, "Could not read blkdebug config file");
return -errno;
}
@@ -601,7 +594,6 @@ 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) {
@@ -616,14 +608,13 @@ static int coroutine_fn rule_check(BlockDriverState *bs, uint64_t offset,
}
}
if (!rule) {
if (!rule || !rule->options.inject.error) {
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);
@@ -631,10 +622,6 @@ 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();
+1 -1
View File
@@ -12,7 +12,7 @@
#include <blkio.h>
#include "block/block_int.h"
#include "system/memory.h"
#include "system/ramblock.h"
#include "exec/cpu-common.h" /* for qemu_ram_get_fd() */
#include "qemu/defer-call.h"
#include "qapi/error.h"
#include "qemu/error-report.h"
-1
View File
@@ -16,7 +16,6 @@
#include "block/block_int.h"
#include "qobject/qdict.h"
#include "qobject/qstring.h"
#include "qemu/bswap.h"
#include "qemu/cutils.h"
#include "qemu/module.h"
#include "qemu/option.h"
Loaded 100 of 3747 files, more files were not shown because too many files have changed in this diff. Show more