Author SHA1 Message Date
Nwflower 21bda5437d ci: reduce upstream sync to daily and remove upstream QEMU lockdown workflow 2026-12-05 00:29:10 -07:00
YXC0915 a7a727a739 build: Update maintenance branch references [ci skip]
Keep automation and documentation aligned with the renamed branch.
The source pins and build steps stay the same.
2026-12-02 19:27:52 +08:00
Xiaochi You 0b057da401 🆕 Automate merging upstream updates into the maintenance branch 2026-12-01 23:47:03 +08:00
136 changed files with 2377 additions and 11421 deletions

No files matched your search

-30
View File
@@ -1,30 +0,0 @@
# Configuration for Repo Lockdown - https://github.com/dessant/repo-lockdown
name: 'Repo Lockdown'
on:
pull_request_target:
types: opened
permissions:
pull-requests: write
jobs:
action:
runs-on: ubuntu-latest
steps:
- uses: dessant/repo-lockdown@v2
with:
pr-comment: |
Thank you for your interest in the QEMU project.
This repository is a read-only mirror of the project's repostories hosted
on https://gitlab.com/qemu-project/qemu.git.
The project does not process merge requests filed on GitHub.
QEMU welcomes contributions of code (either fixing bugs or adding new
functionality). However, we get a lot of patches, and so we have some
guidelines about contributing on the project website:
https://www.qemu.org/contribute/
lock-pr: true
close-pr: true
+91
View File
@@ -0,0 +1,91 @@
name: Merge upstream updates
on:
schedule:
- cron: '11 2 * * *'
workflow_dispatch:
permissions:
contents: write
concurrency:
group: merge-upstream-intel-vm-suspend
cancel-in-progress: false
jobs:
sync:
if: github.repository == 'reims-go/qemu-reims-vgpu'
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Merge upstream into the maintenance branch
shell: bash
env:
GH_TOKEN: ${{ github.token }}
TARGET_BRANCH: intel-vm-suspend
UPSTREAM_REPO: steelbrain/qemu-reims-vgpu
UPSTREAM_BRANCH: steelbrain/reims-vgpu-rebase-2
GIT_AUTHOR_NAME: YXC0915
GIT_AUTHOR_EMAIL: 62410385+yxc0915@users.noreply.github.com
GIT_COMMITTER_NAME: 'github-actions[bot]'
GIT_COMMITTER_EMAIL: '41898282+github-actions[bot]@users.noreply.github.com'
GIT_TERMINAL_PROMPT: '0'
run: |
set -euo pipefail
summary() {
printf '%s\n' "$1" | tee -a "$GITHUB_STEP_SUMMARY"
}
# Check ancestry on GitHub first so routine polls do not fetch QEMU history.
target_ref=${TARGET_BRANCH//\//%2F}
upstream_ref=${UPSTREAM_BRANCH//\//%2F}
status=$(gh api "repos/$GITHUB_REPOSITORY/compare/$target_ref...${UPSTREAM_REPO%%/*}:$upstream_ref?per_page=1" --jq .status)
case "$status" in
identical|behind)
summary "$TARGET_BRANCH already contains $UPSTREAM_REPO:$UPSTREAM_BRANCH."
exit 0
;;
ahead|diverged) ;;
*)
echo "::error::Unexpected upstream comparison status: $status"
exit 1
;;
esac
git init --bare --quiet "$RUNNER_TEMP/upstream-sync.git"
cd "$RUNNER_TEMP/upstream-sync.git"
git remote add origin "https://github.com/$GITHUB_REPOSITORY.git"
git remote add upstream "https://github.com/$UPSTREAM_REPO.git"
git fetch --no-tags --refmap= origin "refs/heads/$TARGET_BRANCH:refs/remotes/origin/target"
git fetch --no-tags --refmap= upstream "refs/heads/$UPSTREAM_BRANCH:refs/remotes/upstream/source"
target=$(git rev-parse refs/remotes/origin/target)
source=$(git rev-parse refs/remotes/upstream/source)
# Recheck ancestry using the exact commits that were fetched.
if git merge-base --is-ancestor "$source" "$target"; then
summary "$TARGET_BRANCH already contains upstream commit $source."
exit 0
fi
if git merge-base --is-ancestor "$target" "$source"; then
merged=$source
elif tree=$(git merge-tree --write-tree "$target" "$source"); then
merged=$(git commit-tree "$tree" -p "$target" -p "$source" \
-m "Merge $UPSTREAM_REPO:$UPSTREAM_BRANCH into $TARGET_BRANCH")
else
result=$?
printf '%s\n' "$tree" | sed 's/^/ /'
if [[ "$result" != 1 ]]; then
exit "$result"
fi
echo "::warning::Upstream merge has conflicts. The maintenance branch was not updated."
summary "Skipped merging $source into $TARGET_BRANCH at $target because of merge conflicts. See the job log."
exit 0
fi
# A normal push rejects a competing branch update and leaves its work intact.
auth=$(printf 'x-access-token:%s' "$GH_TOKEN" | base64 -w0)
echo "::add-mask::$auth"
git -c "http.https://github.com/.extraheader=AUTHORIZATION: basic $auth" \
push origin "$merged:refs/heads/$TARGET_BRANCH"
summary "Merged upstream commit $source into $TARGET_BRANCH at $merged."
+1 -1
View File
@@ -62,5 +62,5 @@ config HV_BALLOON_POSSIBLE
config HAVE_RUST
bool
config REIMS_GRAPHICS
config MAC_PVG
bool
+5 -1
View File
@@ -3044,6 +3044,11 @@ F: hw/display/edid*
F: include/hw/display/edid.h
F: qemu-edid.c
macOS PV Graphics (apple-gfx)
M: Phil Dennis-Jordan <phil@philjordan.eu>
S: Maintained
F: hw/display/apple-gfx*
PIIX4 South Bridge (i82371AB)
M: Hervé Poussineau <hpoussin@reactos.org>
M: Philippe Mathieu-Daudé <philmd@oss.qualcomm.com>
@@ -3213,7 +3218,6 @@ M: Phil Dennis-Jordan <phil@philjordan.eu>
S: Maintained
F: hw/vmapple/*
F: include/hw/vmapple/*
F: hw/usb/dev-vmapple-tablet.c
F: docs/system/arm/vmapple.rst
Nitro Enclaves (native)
-12
View File
@@ -59,7 +59,6 @@
#include "system/hvf.h"
#include "system/hvf_int.h"
#include <mach/mach_time.h>
#include <pthread/qos.h>
HVFState *hvf_state;
@@ -159,17 +158,6 @@ static void *hvf_cpu_thread_fn(void *arg)
assert(hvf_enabled());
/*
* The vCPU runs the guest at the user-initiated QoS, above the default
* QoS a build or any other CPU-bound process on the host runs at, and
* below the host's own user-interactive work. At the default QoS a vCPU
* running the guest's work is one CPU-bound thread among the build's,
* and loses its share to them: an arm64 macOS guest's timers then fire
* up to 1.9 s late and its display falls to 22 frames a second beside 64
* spinning processes on an M3 Max's 16 cores.
*/
pthread_set_qos_class_self_np(QOS_CLASS_USER_INITIATED, 0);
rcu_register_thread();
bql_lock();
-37
View File
@@ -1972,43 +1972,6 @@ static void kvm_region_commit(MemoryListener *listener)
kvm_slots_unlock();
}
bool kvm_unmap_before_del(uint64_t gpa, uint64_t size)
{
KVMState *s = kvm_state;
KVMMemoryListener *kml;
KVMSlot *mem;
bool done = false;
int i, err;
if (!s || size > kvm_max_slot_size) {
return false;
}
kvm_slots_lock();
for (i = 0; i < s->nr_as; i++) {
kml = s->as[i].ml;
mem = kml ? kvm_lookup_matching_slot(kml, gpa, size) : NULL;
/* A dirty log, which the removal syncs first, stays the removal's. */
if (!mem || (mem->flags & KVM_MEM_LOG_DIRTY_PAGES) ||
mem->guest_memfd >= 0) {
continue;
}
g_free(mem->dirty_bmap);
mem->dirty_bmap = NULL;
mem->memory_size = 0;
mem->flags = 0;
err = kvm_set_user_memory_region(kml, mem, false);
if (err) {
fprintf(stderr, "%s: error unregistering slot: %s\n",
__func__, strerror(-err));
abort();
}
kml->nr_slots_used--;
done = true;
}
kvm_slots_unlock();
return done;
}
static void kvm_log_sync(MemoryListener *listener,
MemoryRegionSection *section)
{
-5
View File
@@ -139,11 +139,6 @@ bool kvm_hwpoisoned_mem(void)
return false;
}
bool kvm_unmap_before_del(uint64_t gpa, uint64_t size)
{
return false;
}
int kvm_create_guest_memfd(uint64_t size, uint64_t flags, Error **errp)
{
error_setg(errp, "KVM is not enabled");
-29
View File
@@ -11,32 +11,3 @@
bool whpx_allowed;
bool whpx_irqchip_in_kernel;
bool whpx_send_msi_direct(uint64_t address, uint32_t data)
{
return false;
}
bool whpx_map_ahead(void *host, uint64_t gpa, uint64_t size)
{
return false;
}
void whpx_unmap_ahead(uint64_t gpa, uint64_t size, void *host)
{
}
bool whpx_unmap_before_del(uint64_t gpa, uint64_t size)
{
return false;
}
bool whpx_can_populate(void)
{
return false;
}
int whpx_populate(uint64_t gpa, uint64_t size)
{
return -ENOTSUP;
}
+2 -216
View File
@@ -17,8 +17,6 @@
#include "system/cpus.h"
#include "system/runstate.h"
#include "qemu/main-loop.h"
#include "qemu/queue.h"
#include "qemu/thread.h"
#include "hw/core/boards.h"
#include "hw/intc/ioapic.h"
#include "qemu/error-report.h"
@@ -50,14 +48,8 @@ struct WHPDispatch whp_dispatch;
void whpx_flush_cpu_state(CPUState *cpu)
{
if (cpu->vcpu_dirty) {
WHPXStateLevel level = (cpu->accel && cpu->accel->loadvm_pending)
? WHPX_LEVEL_FULL_STATE
: WHPX_LEVEL_RUNTIME_STATE;
whpx_set_registers(cpu, level);
whpx_set_registers(cpu, WHPX_LEVEL_RUNTIME_STATE);
cpu->vcpu_dirty = false;
if (cpu->accel) {
cpu->accel->loadvm_pending = false;
}
}
}
@@ -213,19 +205,6 @@ static void do_whpx_cpu_synchronize_pre_loadvm(CPUState *cpu,
run_on_cpu_data arg)
{
cpu->vcpu_dirty = true;
if (cpu->accel) {
cpu->accel->loadvm_pending = true;
}
}
static void do_whpx_cpu_synchronize_post_loadvm(CPUState *cpu,
run_on_cpu_data arg)
{
if (cpu->accel && cpu->accel->loadvm_pending) {
whpx_set_registers(cpu, WHPX_LEVEL_FULL_STATE);
cpu->vcpu_dirty = false;
cpu->accel->loadvm_pending = false;
}
}
/*
@@ -256,36 +235,7 @@ void whpx_cpu_synchronize_pre_loadvm(CPUState *cpu)
static void whpx_pre_resume_vm(AccelState *as, bool step_pending)
{
CPUState *cpu;
bool any_loadvm = false;
whpx_global.step_pending = step_pending;
CPU_FOREACH(cpu) {
if (cpu->accel && cpu->accel->loadvm_pending) {
any_loadvm = true;
break;
}
}
if (any_loadvm) {
uint64_t max_tsc = 0;
CPU_FOREACH(cpu) {
uint64_t t = cpu_env(cpu)->tsc;
if (t > max_tsc) {
max_tsc = t;
}
}
if (whp_dispatch.WHvSuspendPartitionTime) {
whp_dispatch.WHvSuspendPartitionTime(whpx_global.partition);
}
CPU_FOREACH(cpu) {
if (cpu->accel && cpu->accel->loadvm_pending) {
cpu_env(cpu)->tsc = max_tsc;
run_on_cpu(cpu, do_whpx_cpu_synchronize_post_loadvm,
RUN_ON_CPU_NULL);
}
}
}
}
/*
@@ -336,161 +286,6 @@ void whpx_vcpu_kick(CPUState *cpu)
* Memory support.
*/
/*
* The ranges a device mapped ahead of their RAM region's add
* (whpx_map_ahead), each until the listener meets its add; and those it
* unmapped ahead of their RAM region's removal (whpx_unmap_before_del), each
* until the listener meets the removal.
*/
typedef struct WhpxMappedAhead {
uint64_t gpa;
uint64_t size;
void *host;
QSLIST_ENTRY(WhpxMappedAhead) next;
} WhpxMappedAhead;
static QSLIST_HEAD(, WhpxMappedAhead) whpx_mapped_ahead =
QSLIST_HEAD_INITIALIZER(whpx_mapped_ahead);
static QSLIST_HEAD(, WhpxMappedAhead) whpx_unmapped_ahead =
QSLIST_HEAD_INITIALIZER(whpx_unmapped_ahead);
static QemuMutex whpx_mapped_ahead_lock;
static void __attribute__((__constructor__)) whpx_mapped_ahead_init(void)
{
qemu_mutex_init(&whpx_mapped_ahead_lock);
}
/*
* Takes the entry a device mapped ahead for exactly @gpa, @size and @host, if
* any: true where the listener's map of that section is already done.
*/
static bool whpx_take_mapped_ahead(uint64_t gpa, uint64_t size, void *host)
{
WhpxMappedAhead *m;
bool found = false;
qemu_mutex_lock(&whpx_mapped_ahead_lock);
QSLIST_FOREACH(m, &whpx_mapped_ahead, next) {
if (m->gpa == gpa && m->size == size && m->host == host) {
QSLIST_REMOVE(&whpx_mapped_ahead, m, WhpxMappedAhead, next);
g_free(m);
found = true;
break;
}
}
qemu_mutex_unlock(&whpx_mapped_ahead_lock);
return found;
}
bool whpx_map_ahead(void *host, uint64_t gpa, uint64_t size)
{
struct whpx_state *whpx = &whpx_global;
WhpxMappedAhead *m;
HRESULT hr;
hr = whp_dispatch.WHvMapGpaRange(whpx->partition, host, gpa, size,
WHvMapGpaRangeFlagRead |
WHvMapGpaRangeFlagWrite |
WHvMapGpaRangeFlagExecute);
if (FAILED(hr)) {
return false;
}
m = g_new0(WhpxMappedAhead, 1);
m->gpa = gpa;
m->size = size;
m->host = host;
qemu_mutex_lock(&whpx_mapped_ahead_lock);
QSLIST_INSERT_HEAD(&whpx_mapped_ahead, m, next);
qemu_mutex_unlock(&whpx_mapped_ahead_lock);
return true;
}
void whpx_unmap_ahead(uint64_t gpa, uint64_t size, void *host)
{
struct whpx_state *whpx = &whpx_global;
if (whpx_take_mapped_ahead(gpa, size, host)) {
whp_dispatch.WHvUnmapGpaRange(whpx->partition, gpa, size);
}
}
/*
* Takes the entry a device unmapped ahead for exactly @gpa and @size, if any:
* true where the listener's unmap of that section is already done.
*/
static bool whpx_take_unmapped_ahead(uint64_t gpa, uint64_t size)
{
WhpxMappedAhead *m;
bool found = false;
qemu_mutex_lock(&whpx_mapped_ahead_lock);
QSLIST_FOREACH(m, &whpx_unmapped_ahead, next) {
if (m->gpa == gpa && m->size == size) {
QSLIST_REMOVE(&whpx_unmapped_ahead, m, WhpxMappedAhead, next);
g_free(m);
found = true;
break;
}
}
qemu_mutex_unlock(&whpx_mapped_ahead_lock);
return found;
}
bool whpx_unmap_before_del(uint64_t gpa, uint64_t size)
{
struct whpx_state *whpx = &whpx_global;
WhpxMappedAhead *m, *a;
HRESULT hr;
m = g_new0(WhpxMappedAhead, 1);
m->gpa = gpa;
m->size = size;
qemu_mutex_lock(&whpx_mapped_ahead_lock);
QSLIST_FOREACH(a, &whpx_mapped_ahead, next) {
if (a->gpa == gpa) {
/* Its add is still to come: the listener unmaps it as usual. */
qemu_mutex_unlock(&whpx_mapped_ahead_lock);
g_free(m);
return false;
}
}
/* Recorded first: a removal the listener meets meanwhile unmaps nothing. */
QSLIST_INSERT_HEAD(&whpx_unmapped_ahead, m, next);
qemu_mutex_unlock(&whpx_mapped_ahead_lock);
hr = whp_dispatch.WHvUnmapGpaRange(whpx->partition, gpa, size);
if (FAILED(hr)) {
whpx_take_unmapped_ahead(gpa, size);
return false;
}
return true;
}
bool whpx_can_populate(void)
{
return whp_dispatch.WHvAdviseGpaRange != NULL;
}
int whpx_populate(uint64_t gpa, uint64_t size)
{
struct whpx_state *whpx = &whpx_global;
WHV_MEMORY_RANGE_ENTRY range = {
.GuestAddress = gpa,
.SizeInBytes = size,
};
WHV_ADVISE_GPA_RANGE_POPULATE populate = {
.AccessType = WHvMemoryAccessWrite,
};
HRESULT hr;
if (!whp_dispatch.WHvAdviseGpaRange) {
return -ENOTSUP;
}
hr = whp_dispatch.WHvAdviseGpaRange(whpx->partition, &range, 1,
WHvAdviseGpaRangeCodePopulate,
&populate, sizeof(populate));
return FAILED(hr) ? -EIO : 0;
}
static void whpx_set_phys_mem(MemoryRegionSection *section, bool add)
{
struct whpx_state *whpx = &whpx_global;
@@ -518,10 +313,6 @@ static void whpx_set_phys_mem(MemoryRegionSection *section, bool add)
}
if (!add) {
/* A device unmapped it ahead, outside the BQL: the unmap is done. */
if (whpx_take_unmapped_ahead(gva, size)) {
return;
}
hr = whp_dispatch.WHvUnmapGpaRange(whpx->partition,
gva, size);
if (FAILED(hr)) {
@@ -535,11 +326,6 @@ static void whpx_set_phys_mem(MemoryRegionSection *section, bool add)
| (writable ? WHvMapGpaRangeFlagWrite : 0);
mem = memory_region_get_ram_ptr(area) + section->offset_within_region;
/* A device mapped it ahead, outside the BQL: the map is done. */
if (writable && whpx_take_mapped_ahead(gva, size, mem)) {
return;
}
hr = whp_dispatch.WHvMapGpaRange(whpx->partition,
mem, gva, size, flags);
if (FAILED(hr)) {
@@ -573,7 +359,7 @@ static void whpx_log_sync(MemoryListener *listener,
{
MemoryRegion *mr = section->mr;
if (!memory_region_is_ram(mr) || !runstate_is_running()) {
if (!memory_region_is_ram(mr)) {
return;
}
-9
View File
@@ -145,15 +145,6 @@ void audio_be_set_active_out(AudioBackend *be, SWVoiceOut *sw, bool on)
return klass->set_active_out(be, sw, on);
}
void audio_be_kick(AudioBackend *be)
{
AudioBackendClass *klass = AUDIO_BACKEND_GET_CLASS(be);
if (klass->kick) {
klass->kick(be);
}
}
void audio_be_set_active_in(AudioBackend *be, SWVoiceIn *sw, bool on)
{
AudioBackendClass *klass = AUDIO_BACKEND_GET_CLASS(be);
-7
View File
@@ -1426,12 +1426,6 @@ static void audio_mixeng_backend_set_volume_out(AudioBackend *be, SWVoiceOut *sw
static void audio_mixeng_backend_set_volume_in(AudioBackend *be, SWVoiceIn *sw,
Volume *vol);
/* What the timer runs, between its runs: its period stays as it was. */
static void audio_mixeng_backend_kick(AudioBackend *be)
{
audio_run(AUDIO_MIXENG_BACKEND(be), "kick");
}
static void audio_mixeng_backend_class_init(ObjectClass *klass, const void *data)
{
AudioBackendClass *be = AUDIO_BACKEND_CLASS(klass);
@@ -1453,7 +1447,6 @@ static void audio_mixeng_backend_class_init(ObjectClass *klass, const void *data
be->get_buffer_size_out = audio_mixeng_backend_get_buffer_size_out;
be->add_capture = audio_mixeng_backend_add_capture;
be->del_capture = audio_mixeng_backend_del_capture;
be->kick = audio_mixeng_backend_kick;
}
static void audio_mixeng_backend_init(Object *obj)
-66
View File
@@ -1,66 +0,0 @@
/*
* QEMU DirectSound audio driver: its playback buffer's arithmetic
*
* Moved out of dsoundaudio.c, which builds only on Windows, unchanged, so
* that tests/unit/test-dsound-ring.c holds it on any host.
*
* SPDX-License-Identifier: MIT
*/
#ifndef AUDIO_DSOUND_RING_H
#define AUDIO_DSOUND_RING_H
#include "qemu/host-utils.h"
/*
* The reserve past the write cursor. An x86-64 macOS guest posts its periods
* on a 41.67 ms grid, their arrivals spread over 43 to 53 ms about their pace,
* and DirectSound's cursors move in 10 ms steps: 60 ms covers both, where the
* voice is written as each period comes.
*/
#define DSOUND_RESERVE_US 60000
/*
* The reserve in bytes of a voice of @freq frames a second and @bpf bytes a
* frame in a buffer of @size_emul bytes, where the write cursor leads the
* play cursor by @lead bytes: whole frames, as far as the play cursor at most.
*/
static inline size_t dsound_reserve(int freq, size_t bpf, size_t size_emul,
size_t lead)
{
size_t reserve = (size_t)muldiv64(freq, DSOUND_RESERVE_US,
1000000) * bpf;
return MIN(reserve, size_emul - lead) / bpf * bpf;
}
/* The play cursor @ppos at its frame's start. */
static inline size_t dsound_play_frame(size_t ppos, size_t bpf)
{
return ppos / bpf * bpf;
}
/* The first frame's start at or past the write cursor @wpos, in the buffer. */
static inline size_t dsound_write_frame(size_t wpos, size_t bpf,
size_t size_emul)
{
return (wpos + bpf - 1) / bpf * bpf % size_emul;
}
/*
* The bytes from the play cursor to the write position once the play cursor
* has moved @played bytes, @since_ns after its last read, of @filled before:
* none where it passed them all, or where most of a turn of the buffer
* (@buffer_ns) went by since, short of a stall of the main loop.
*/
static inline size_t dsound_filled_after(size_t filled, size_t played,
int64_t since_ns, int64_t buffer_ns)
{
if (played >= filled ||
since_ns >= buffer_ns / 4 * 3) {
return 0;
}
return filled - played;
}
#endif
-12
View File
@@ -195,15 +195,7 @@ static int dsound_init_out(HWVoiceOut *hw, struct audsettings *as)
memset (&bd, 0, sizeof (bd));
bd.dwSize = sizeof (bd);
bd.lpwfxFormat = &wfx;
#ifdef DSBTYPE_IN
bd.dwBufferBytes = audio_buffer_bytes(pdo, as, 92880);
#else
/*
* Twice the 92880 us of a capture buffer: room past the write cursor
* for dsound_place_out's reserve and the guest's periods beyond it.
*/
bd.dwBufferBytes = audio_buffer_bytes(pdo, as, 185760);
#endif
#ifdef DSBTYPE_IN
hr = IDirectSoundCapture_CreateCaptureBuffer (
s->dsound_capture,
@@ -261,10 +253,6 @@ static int dsound_init_out(HWVoiceOut *hw, struct audsettings *as)
}
hw->size_emul = bc.dwBufferBytes;
hw->samples = bc.dwBufferBytes / hw->info.bytes_per_frame;
#ifndef DSBTYPE_IN
ds->buffer_ns = muldiv64(hw->samples, NANOSECONDS_PER_SECOND,
hw->info.freq);
#endif
trace_dsound_buffer_bytes(bc.dwBufferBytes, bd.dwBufferBytes);
return 0;
+13 -132
View File
@@ -29,9 +29,7 @@
#include "qemu/osdep.h"
#include "qemu/audio.h"
#include "qemu/error-report.h"
#include "qemu/timer.h"
#include "audio_int.h"
#include "dsound-ring.h"
#include "qemu/module.h"
#include "qapi/error.h"
#include "qom/object.h"
@@ -57,33 +55,10 @@ struct AudioDsound {
struct audsettings settings;
};
/*
* A playback voice writes only past DirectSound's write cursor: the bytes
* between its play and write cursors DirectSound has mixed already, so what is
* written there is not heard, and the buffer's audio from one turn earlier
* plays in its place. The write position (hw.pos_emul) is placed
* DSOUND_RESERVE_US past the write cursor, with silence before it, when the
* voice starts, and again when the audio written runs out before the write
* cursor: a guest that hands its audio over in periods, their arrivals spread
* over some 50 ms about their pace, is played from that reserve without a
* gap, where its frontend has the voice written as each period comes
* (virtio-snd does). The reserve is latency. What the play cursor has passed
* becomes silence, so a gap plays silence.
*/
typedef struct {
HWVoiceOut hw;
LPDIRECTSOUNDBUFFER dsound_buffer;
bool first_time;
/* The bytes from the play cursor, at play_pos, to the write position. */
size_t filled;
DWORD play_pos;
/* When play_pos was read, and the buffer's length, in nanoseconds. */
int64_t play_ns;
int64_t buffer_ns;
/* Whether audio was written since the write position was placed. */
bool primed;
/* The times the audio written ran out before the write cursor. */
uint32_t gaps;
} DSoundVoiceOut;
typedef struct {
@@ -380,8 +355,6 @@ static void dsound_enable_out(HWVoiceOut *hw, bool enable)
}
dsound_clear_sample(hw, dsb, s);
/* The next read of the cursors places the write position. */
ds->first_time = true;
hr = IDirectSoundBuffer_Play(dsb, 0, 0, DSBPLAY_LOOPING);
if (FAILED(hr)) {
@@ -405,101 +378,26 @@ static void dsound_enable_out(HWVoiceOut *hw, bool enable)
}
}
/* Fill @len bytes of the buffer from @pos with silence. */
static void dsound_clear_out(HWVoiceOut *hw, DWORD pos, size_t len)
{
DSoundVoiceOut *ds = (DSoundVoiceOut *)hw;
size_t bpf = hw->info.bytes_per_frame;
LPVOID p1, p2;
DWORD blen1, blen2;
if (!len ||
dsound_lock_out(ds->dsound_buffer, &hw->info, pos, len, &p1, &p2,
&blen1, &blen2, 0, AUDIO_DSOUND(hw->s))) {
return;
}
if (p1 && blen1) {
audio_pcm_info_clear_buf(&hw->info, p1, blen1 / bpf);
}
if (p2 && blen2) {
audio_pcm_info_clear_buf(&hw->info, p2, blen2 / bpf);
}
dsound_unlock_out(ds->dsound_buffer, p1, p2, blen1, blen2);
}
/*
* Place the write position DSOUND_RESERVE_US past the write cursor @wpos, with
* silence from the write cursor to it. Where the buffer is too short for that,
* the write position goes as far as the play cursor.
*/
static void dsound_place_out(HWVoiceOut *hw, DWORD ppos, DWORD wpos)
{
DSoundVoiceOut *ds = (DSoundVoiceOut *)hw;
size_t bpf = hw->info.bytes_per_frame;
size_t lead = audio_ring_dist(wpos, ppos, hw->size_emul);
size_t reserve = dsound_reserve(hw->info.freq, bpf, hw->size_emul, lead);
if (ds->primed) {
ds->gaps++;
}
trace_dsound_place_out(hw, ppos, wpos, ds->filled, reserve, ds->primed,
ds->gaps);
dsound_clear_out(hw, wpos, reserve);
hw->pos_emul = (wpos + reserve) % hw->size_emul;
ds->filled = lead + reserve;
ds->primed = false;
}
static size_t dsound_buffer_get_free(HWVoiceOut *hw)
{
DSoundVoiceOut *ds = (DSoundVoiceOut *) hw;
LPDIRECTSOUNDBUFFER dsb = ds->dsound_buffer;
size_t bpf = hw->info.bytes_per_frame;
int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
size_t played;
HRESULT hr;
DWORD ppos, wpos;
hr = IDirectSoundBuffer_GetCurrentPosition(dsb, &ppos, &wpos);
hr = IDirectSoundBuffer_GetCurrentPosition(
dsb, &ppos, ds->first_time ? &wpos : NULL);
if (FAILED(hr)) {
dsound_logerr(hr, "Could not get playback buffer position");
return 0;
}
/* Whole frames: the play cursor's frame, and the first past the write's. */
ppos = dsound_play_frame(ppos, bpf);
wpos = dsound_write_frame(wpos, bpf, hw->size_emul);
/*
* The play cursor's advance since the last read, which reads it more
* often than once a turn of the buffer, short of a stall of the main
* loop: after one of most of a turn, the audio written counts as played.
* What it played becomes silence, which a gap then plays rather than the
* audio of a turn earlier.
*/
played = audio_ring_dist(ppos, ds->play_pos, hw->size_emul);
if (ds->first_time) {
hw->pos_emul = wpos;
ds->first_time = false;
ds->primed = false;
} else {
dsound_clear_out(hw, ds->play_pos, played);
ds->filled = dsound_filled_after(ds->filled, played,
now - ds->play_ns, ds->buffer_ns);
}
ds->play_pos = ppos;
ds->play_ns = now;
/*
* Until audio comes, the write position keeps its place past the write
* cursor; once the audio written runs out before the write cursor, it
* takes it again, a gap of silence.
*/
if (!ds->primed ||
ds->filled < audio_ring_dist(wpos, ppos, hw->size_emul)) {
dsound_place_out(hw, ppos, wpos);
}
trace_dsound_buffer_get_free(hw, ppos, wpos, ds->filled);
return hw->size_emul - ds->filled;
return audio_ring_dist(ppos, hw->pos_emul, hw->size_emul);
}
static void *dsound_get_buffer_out(HWVoiceOut *hw, size_t *size)
@@ -511,13 +409,8 @@ static void *dsound_get_buffer_out(HWVoiceOut *hw, size_t *size)
int err;
void *ret;
/* Never over audio not yet played. */
req_size = MIN(*size, hw->size_emul - hw->pos_emul);
req_size = MIN(req_size, hw->size_emul - ds->filled);
if (!req_size) {
*size = 0;
return NULL;
}
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));
@@ -542,10 +435,6 @@ static size_t dsound_put_buffer_out(HWVoiceOut *hw, void *buf, size_t len)
return 0;
}
hw->pos_emul = (hw->pos_emul + len) % hw->size_emul;
ds->filled += len;
if (len) {
ds->primed = true;
}
return len;
}
@@ -721,11 +610,6 @@ audio_dsound_realize(AudioBackend *abe, Audiodev *dev, Error **errp)
return false;
}
/*
* Capture is optional: a host with no recording device (no microphone)
* still plays sound. Without the capture object, an input voice fails to
* initialize (dsound_init_in).
*/
hr = CoCreateInstance (
&CLSID_DirectSoundCapture,
NULL,
@@ -734,17 +618,14 @@ audio_dsound_realize(AudioBackend *abe, Audiodev *dev, Error **errp)
(void **) &s->dsound_capture
);
if (FAILED (hr)) {
dsound_logerr(hr, "Could not create DirectSoundCapture instance, "
"no recording");
s->dsound_capture = NULL;
} else {
hr = IDirectSoundCapture_Initialize (s->dsound_capture, NULL);
if (FAILED(hr)) {
dsound_logerr(hr, "Could not initialize DirectSoundCapture, "
"no recording");
IDirectSoundCapture_Release (s->dsound_capture);
s->dsound_capture = NULL;
}
dserror_set(errp, hr, "Could not create DirectSoundCapture instance");
return false;
}
hr = IDirectSoundCapture_Initialize (s->dsound_capture, NULL);
if (FAILED(hr)) {
dserror_set(errp, hr, "Could not initialize DirectSoundCapture");
return false;
}
hr = IDirectSound_SetCooperativeLevel (
+80 -164
View File
@@ -40,22 +40,12 @@ typedef struct {
AudioPa *g;
} PAVoiceOut;
/*
* A capture voice has a record stream only while the voice is enabled, so
* the host's sound server lists a recording client only while the guest
* captures. What the stream opens with, and the guest's last volume for
* it, are kept with the voice.
*/
typedef struct {
HWVoiceIn hw;
pa_stream *stream;
const void *read_data;
size_t read_length;
AudioPa *g;
pa_sample_spec ss;
pa_buffer_attr ba;
bool has_volume;
Volume volume;
} PAVoiceIn;
static void qpa_conn_fini(PAConnection *c);
@@ -102,15 +92,8 @@ static void *qpa_get_buffer_in(HWVoiceIn *hw, size_t *size)
pa_threaded_mainloop_lock(c->mainloop);
if (!p->stream) {
goto unlock_empty;
}
CHECK_DEAD_GOTO(c, p->stream, unlock_and_fail,
"pa_threaded_mainloop_lock failed");
if (pa_stream_get_state(p->stream) != PA_STREAM_READY) {
/* wait for stream to become ready */
goto unlock_empty;
}
if (!p->read_length) {
r = pa_stream_peek(p->stream, &p->read_data, &p->read_length);
@@ -124,7 +107,6 @@ static void *qpa_get_buffer_in(HWVoiceIn *hw, size_t *size)
return (void *) p->read_data;
unlock_and_fail:
unlock_empty:
pa_threaded_mainloop_unlock(c->mainloop);
*size = 0;
return NULL;
@@ -138,9 +120,6 @@ static void qpa_put_buffer_in(HWVoiceIn *hw, void *buf, size_t size)
pa_threaded_mainloop_lock(c->mainloop);
if (!p->stream) {
goto unlock;
}
CHECK_DEAD_GOTO(c, p->stream, unlock,
"pa_threaded_mainloop_lock failed");
@@ -166,9 +145,6 @@ static size_t qpa_read(HWVoiceIn *hw, void *data, size_t length)
pa_threaded_mainloop_lock(c->mainloop);
if (!p->stream) {
goto unlock;
}
CHECK_DEAD_GOTO(c, p->stream, unlock_and_fail,
"pa_threaded_mainloop_lock failed");
if (pa_stream_get_state(p->stream) != PA_STREAM_READY) {
@@ -422,54 +398,6 @@ static void stream_state_cb (pa_stream *s, void * userdata)
}
}
/* The channel map of a stream of CHANNELS, false where none is known */
static bool qpa_channel_map_init(pa_channel_map *map, int channels)
{
pa_channel_map_init(map);
map->channels = channels;
/*
* TODO: This currently expects the only frontend supporting more than 2
* channels is the usb-audio. We will need some means to set channel
* order when a new frontend gains multi-channel support.
*/
switch (channels) {
case 1:
map->map[0] = PA_CHANNEL_POSITION_MONO;
break;
case 2:
map->map[0] = PA_CHANNEL_POSITION_LEFT;
map->map[1] = PA_CHANNEL_POSITION_RIGHT;
break;
case 6:
map->map[0] = PA_CHANNEL_POSITION_FRONT_LEFT;
map->map[1] = PA_CHANNEL_POSITION_FRONT_RIGHT;
map->map[2] = PA_CHANNEL_POSITION_CENTER;
map->map[3] = PA_CHANNEL_POSITION_LFE;
map->map[4] = PA_CHANNEL_POSITION_REAR_LEFT;
map->map[5] = PA_CHANNEL_POSITION_REAR_RIGHT;
break;
case 8:
map->map[0] = PA_CHANNEL_POSITION_FRONT_LEFT;
map->map[1] = PA_CHANNEL_POSITION_FRONT_RIGHT;
map->map[2] = PA_CHANNEL_POSITION_CENTER;
map->map[3] = PA_CHANNEL_POSITION_LFE;
map->map[4] = PA_CHANNEL_POSITION_REAR_LEFT;
map->map[5] = PA_CHANNEL_POSITION_REAR_RIGHT;
map->map[6] = PA_CHANNEL_POSITION_SIDE_LEFT;
map->map[7] = PA_CHANNEL_POSITION_SIDE_RIGHT;
break;
default:
error_report("pulseaudio: unsupported channel count %d", channels);
return false;
}
return true;
}
static pa_stream *qpa_simple_new (
PAConnection *c,
const char *name,
@@ -477,8 +405,6 @@ static pa_stream *qpa_simple_new (
const char *dev,
const pa_sample_spec *ss,
const pa_buffer_attr *attr,
pa_stream_notify_cb_t state_cb,
void *state_userdata,
int *rerror)
{
int r;
@@ -488,7 +414,46 @@ static pa_stream *qpa_simple_new (
pa_threaded_mainloop_lock(c->mainloop);
if (!qpa_channel_map_init(&map, ss->channels)) {
pa_channel_map_init(&map);
map.channels = ss->channels;
/*
* TODO: This currently expects the only frontend supporting more than 2
* channels is the usb-audio. We will need some means to set channel
* order when a new frontend gains multi-channel support.
*/
switch (ss->channels) {
case 1:
map.map[0] = PA_CHANNEL_POSITION_MONO;
break;
case 2:
map.map[0] = PA_CHANNEL_POSITION_LEFT;
map.map[1] = PA_CHANNEL_POSITION_RIGHT;
break;
case 6:
map.map[0] = PA_CHANNEL_POSITION_FRONT_LEFT;
map.map[1] = PA_CHANNEL_POSITION_FRONT_RIGHT;
map.map[2] = PA_CHANNEL_POSITION_CENTER;
map.map[3] = PA_CHANNEL_POSITION_LFE;
map.map[4] = PA_CHANNEL_POSITION_REAR_LEFT;
map.map[5] = PA_CHANNEL_POSITION_REAR_RIGHT;
break;
case 8:
map.map[0] = PA_CHANNEL_POSITION_FRONT_LEFT;
map.map[1] = PA_CHANNEL_POSITION_FRONT_RIGHT;
map.map[2] = PA_CHANNEL_POSITION_CENTER;
map.map[3] = PA_CHANNEL_POSITION_LFE;
map.map[4] = PA_CHANNEL_POSITION_REAR_LEFT;
map.map[5] = PA_CHANNEL_POSITION_REAR_RIGHT;
map.map[6] = PA_CHANNEL_POSITION_SIDE_LEFT;
map.map[7] = PA_CHANNEL_POSITION_SIDE_RIGHT;
break;
default:
error_report("pulseaudio: unsupported channel count %d", ss->channels);
goto fail;
}
@@ -497,7 +462,7 @@ static pa_stream *qpa_simple_new (
goto fail;
}
pa_stream_set_state_callback(stream, state_cb, state_userdata);
pa_stream_set_state_callback(stream, stream_state_cb, c);
flags = PA_STREAM_EARLY_REQUESTS;
@@ -565,8 +530,6 @@ static int qpa_init_out(HWVoiceOut *hw, struct audsettings *as)
ppdo->name,
&ss,
&ba, /* buffering attributes */
stream_state_cb,
c,
&error
);
if (!pa->stream) {
@@ -589,37 +552,51 @@ static int qpa_init_in(HWVoiceIn *hw, struct audsettings *as)
{
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;
AudiodevPaPerDirectionOptions *ppdo = popts->in;
pa_channel_map map;
PAConnection *c = apa->conn;
pa->g = apa;
pa->ss.format = audfmt_to_pa (as->fmt, as->big_endian);
pa->ss.channels = as->nchannels;
pa->ss.rate = as->freq;
ss.format = audfmt_to_pa (as->fmt, as->big_endian);
ss.channels = as->nchannels;
ss.rate = as->freq;
pa->ba.fragsize = pa_usec_to_bytes((amb->dev->timer_period >> 1) * 3,
&pa->ss);
pa->ba.maxlength = pa_usec_to_bytes(
MAX(ppdo->latency, amb->dev->timer_period * 3), &pa->ss);
pa->ba.minreq = -1;
pa->ba.prebuf = -1;
ba.fragsize = pa_usec_to_bytes((amb->dev->timer_period >> 1) * 3, &ss);
ba.maxlength = pa_usec_to_bytes(
MAX(ppdo->latency, amb->dev->timer_period * 3), &ss);
ba.minreq = -1;
ba.prebuf = -1;
/* What the record stream would refuse, refused before it is opened */
if (!qpa_channel_map_init(&map, pa->ss.channels)) {
return -1;
obt_as.fmt = pa_to_audfmt (ss.format, &obt_as.big_endian);
pa->stream = qpa_simple_new (
c,
ppdo->stream_name ?: amb->dev->id,
PA_STREAM_RECORD,
ppdo->name,
&ss,
&ba, /* buffering attributes */
&error
);
if (!pa->stream) {
qpa_logerr(error, "pa_simple_new for capture failed");
goto fail1;
}
obt_as.fmt = pa_to_audfmt (pa->ss.format, &obt_as.big_endian);
audio_pcm_init_info (&hw->info, &obt_as);
/* hw->samples counts in frames */
hw->samples = audio_buffer_frames(
qapi_AudiodevPaPerDirectionOptions_base(ppdo), &obt_as, 46440);
return 0;
fail1:
return -1;
}
static void qpa_simple_disconnect(PAConnection *c, pa_stream *stream)
@@ -655,8 +632,10 @@ static void qpa_fini_out (HWVoiceOut *hw)
}
}
static void qpa_close_in(PAVoiceIn *pa)
static void qpa_fini_in (HWVoiceIn *hw)
{
PAVoiceIn *pa = (PAVoiceIn *) hw;
if (pa->stream) {
PAConnection *c = pa->g->conn;
@@ -675,11 +654,6 @@ static void qpa_close_in(PAVoiceIn *pa)
}
}
static void qpa_fini_in (HWVoiceIn *hw)
{
qpa_close_in((PAVoiceIn *) hw);
}
static void qpa_volume_out(HWVoiceOut *hw, Volume *vol)
{
PAVoiceOut *pa = (PAVoiceOut *) hw;
@@ -720,12 +694,12 @@ static void qpa_volume_out(HWVoiceOut *hw, Volume *vol)
pa_threaded_mainloop_unlock(c->mainloop);
}
/* Give a record stream the guest's volume, with the mainloop locked */
static void qpa_set_source_output_volume(PAConnection *c, pa_stream *stream,
Volume *vol)
static void qpa_volume_in(HWVoiceIn *hw, Volume *vol)
{
PAVoiceIn *pa = (PAVoiceIn *) hw;
pa_operation *op;
pa_cvolume v;
PAConnection *c = pa->g->conn;
int i;
pa_cvolume_init(&v);
@@ -735,8 +709,10 @@ static void qpa_set_source_output_volume(PAConnection *c, pa_stream *stream,
v.values[i] = ((PA_VOLUME_NORM - PA_VOLUME_MUTED) * vol->vol[i]) / 255;
}
pa_threaded_mainloop_lock(c->mainloop);
op = pa_context_set_source_output_volume(c->context,
pa_stream_get_index(stream),
pa_stream_get_index(pa->stream),
&v, NULL, NULL);
if (!op) {
qpa_logerr(pa_context_errno(c->context),
@@ -746,7 +722,7 @@ static void qpa_set_source_output_volume(PAConnection *c, pa_stream *stream,
}
op = pa_context_set_source_output_mute(c->context,
pa_stream_get_index(stream),
pa_stream_get_index(pa->stream),
vol->mute, NULL, NULL);
if (!op) {
qpa_logerr(pa_context_errno(c->context),
@@ -754,69 +730,10 @@ static void qpa_set_source_output_volume(PAConnection *c, pa_stream *stream,
} else {
pa_operation_unref(op);
}
}
static void qpa_volume_in(HWVoiceIn *hw, Volume *vol)
{
PAVoiceIn *pa = (PAVoiceIn *) hw;
PAConnection *c = pa->g->conn;
pa_threaded_mainloop_lock(c->mainloop);
pa->volume = *vol;
pa->has_volume = true;
if (pa->stream && pa_stream_get_state(pa->stream) == PA_STREAM_READY) {
qpa_set_source_output_volume(c, pa->stream, vol);
}
pa_threaded_mainloop_unlock(c->mainloop);
}
/* A record stream takes the guest's last volume as it becomes ready */
static void record_state_cb(pa_stream *s, void *userdata)
{
PAVoiceIn *pa = userdata;
if (pa_stream_get_state(s) == PA_STREAM_READY && pa->has_volume) {
qpa_set_source_output_volume(pa->g->conn, s, &pa->volume);
}
stream_state_cb(s, pa->g->conn);
}
/*
* The record stream opens as the guest's capture starts, and closes as it
* stops.
*/
static void qpa_enable_in(HWVoiceIn *hw, bool enable)
{
PAVoiceIn *pa = (PAVoiceIn *) hw;
AudioMixengBackend *amb = hw->s;
AudiodevPaPerDirectionOptions *ppdo = amb->dev->u.pa.in;
int error;
if (!enable) {
qpa_close_in(pa);
return;
}
if (pa->stream) {
return;
}
pa->stream = qpa_simple_new (
pa->g->conn,
ppdo->stream_name ?: amb->dev->id,
PA_STREAM_RECORD,
ppdo->name,
&pa->ss,
&pa->ba, /* buffering attributes */
record_state_cb,
pa,
&error
);
if (!pa->stream) {
qpa_logerr(error, "pa_simple_new for capture failed");
}
}
static void qpa_validate_per_direction_opts(Audiodev *dev,
AudiodevPaPerDirectionOptions *pdo)
{
@@ -999,7 +916,6 @@ static void audio_pa_class_init(ObjectClass *klass, const void *data)
k->read = qpa_read;
k->get_buffer_in = qpa_get_buffer_in;
k->put_buffer_in = qpa_put_buffer_in;
k->enable_in = qpa_enable_in;
k->volume_in = qpa_volume_in;
}
+6 -76
View File
@@ -60,18 +60,6 @@ typedef struct PWVoice {
pwvolume volume;
bool muted;
/*
* The capture overruns: the cycles that found the ring full, and the
* bytes they dropped. Written on PipeWire's data thread, read once the
* stream is gone.
*/
uint64_t overruns, overrun_bytes;
/*
* The bytes qpw_read skipped in a full ring to read its newest audio.
* Written by the reader, read once the stream is gone.
*/
uint64_t skipped_bytes;
} PWVoice;
typedef struct PWVoiceOut {
@@ -196,25 +184,12 @@ capture_on_process(void *data)
error_report("%p: underrun write:%u filled:%d", p, index, filled);
pw_stream_queue_buffer(v->stream, b);
return;
} else if ((uint32_t) filled + n_bytes > RINGBUFFER_SIZE) {
/*
* Nothing has read the ring for as long as it holds: the guest's
* input stream runs, and the guest takes none of it. The source runs
* on, a cycle each quantum (every 5.3 ms at 256 frames of 48 kHz),
* each finding the ring full: what does not fit is dropped, said at
* the first such cycle and counted, and the count is said as the
* stream closes.
*/
uint32_t room = RINGBUFFER_SIZE - (uint32_t)filled;
if (v->overruns++ == 0) {
warn_report("pipewire: capture stream %s: its %u-byte buffer is "
"full of audio nothing has read: captured audio is "
"dropped while it stays full, and counted",
pw_stream_get_name(v->stream), RINGBUFFER_SIZE);
} else {
if ((uint32_t) filled + n_bytes > RINGBUFFER_SIZE) {
error_report("%p: overrun write:%u filled:%d + size:%u > max:%u",
p, index, filled, n_bytes, RINGBUFFER_SIZE);
n_bytes = RINGBUFFER_SIZE - (uint32_t)filled;
}
v->overrun_bytes += n_bytes - room;
n_bytes = room;
}
spa_ringbuffer_write_data(&v->ring,
v->buffer, RINGBUFFER_SIZE,
@@ -277,22 +252,6 @@ qpw_read(HWVoiceIn *hw, void *data, size_t len)
goto done_unlock;
}
if ((uint32_t)avail >= RINGBUFFER_SIZE && (size_t)avail > len) {
/*
* A full ring holds its oldest audio: capture_on_process drops what
* does not fit. Read from its start, it would give the reader as
* much stale audio as it holds (about 24 s of 16-bit stereo at
* 44.1 kHz), and that delay for the rest of the stream. Skip to the
* newest len bytes, in whole frames, and count what is skipped. A
* reader that keeps up never finds the ring full.
*/
uint32_t skip = ((uint32_t)avail - len) / v->frame_size * v->frame_size;
index += skip;
avail -= skip;
v->skipped_bytes += skip;
}
if ((size_t)avail < len) {
len = avail;
}
@@ -671,26 +630,13 @@ qpw_init_in(HWVoiceIn *hw, struct audsettings *as)
static void
qpw_voice_fini(AudioPw *c, PWVoice *v)
{
g_autofree char *name = NULL;
if (!v->stream) {
return;
}
pw_thread_loop_lock(c->thread_loop);
name = g_strdup(pw_stream_get_name(v->stream));
pw_stream_destroy(v->stream);
v->stream = NULL;
pw_thread_loop_unlock(c->thread_loop);
if (v->overruns) {
info_report("pipewire: capture stream %s: %" PRIu64 " bytes of "
"captured audio dropped in %" PRIu64 " cycles that found "
"its buffer full", name, v->overrun_bytes, v->overruns);
}
if (v->skipped_bytes) {
info_report("pipewire: capture stream %s: %" PRIu64 " bytes of its "
"oldest audio skipped to read the newest", name,
v->skipped_bytes);
}
}
static void
@@ -722,23 +668,7 @@ qpw_enable_out(HWVoiceOut *hw, bool enable)
static void
qpw_enable_in(HWVoiceIn *hw, bool enable)
{
AudioPw *c = AUDIO_PW(hw->s);
PWVoice *v = &PW_VOICE_IN(hw)->v;
if (enable) {
uint32_t index;
/*
* What the stream captured before it stopped is stale: a capture
* that starts again gives the reader what the source captures from
* then on, as ALSA's snd_pcm_drop and snd_pcm_start do for alsa.
*/
pw_thread_loop_lock(c->thread_loop);
spa_ringbuffer_get_write_index(&v->ring, &index);
spa_ringbuffer_read_update(&v->ring, index);
pw_thread_loop_unlock(c->thread_loop);
}
qpw_voice_set_enabled(c, v, enable);
qpw_voice_set_enabled(AUDIO_PW(hw->s), &PW_VOICE_IN(hw)->v, enable);
}
static void
-2
View File
@@ -32,8 +32,6 @@ dbus_audio_read(size_t len) "len = %zu"
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"
dsound_buffer_get_free(void *voice, uint32_t play, uint32_t write, uint32_t filled) "voice=%p, play=%u, write=%u, filled=%u"
dsound_place_out(void *voice, uint32_t play, uint32_t write, uint32_t filled, uint32_t reserve, bool gap, uint32_t gaps) "voice=%p, play=%u, write=%u, filled=%u, reserve=%u, gap=%d, gaps=%u"
# jackaudio.c
jack_client_recover(void) "attempting to reconnect to server"
-55
View File
@@ -24,8 +24,6 @@
#include "qemu/mmap-alloc.h"
#include "qemu/madvise.h"
#include "qemu/cutils.h"
#include "qemu/error-report.h"
#include "qemu/units.h"
#include "hw/core/qdev.h"
#ifdef CONFIG_NUMA
@@ -334,58 +332,6 @@ size_t host_memory_backend_pagesize(HostMemoryBackend *memdev)
return pagesize;
}
/*
* Put a shared file's preallocated RAM, a memfd's shmem among it, on
* transparent huge pages, 2 MiB at a time, on Linux. At a fault the kernel
* backs shmem with a huge page only where
* /sys/kernel/mm/transparent_hugepage/shmem_enabled lets it (advise with
* QEMU_MADV_HUGEPAGE, always, within_size) and a free 2 MiB page is found;
* at never, most distributions' default, the guest runs on 4 KiB pages
* alone. MADV_COLLAPSE (Linux 6.1) copies a 2 MiB range onto one huge page
* at any shmem_enabled but deny, and leaves a range already on one as it is.
* It runs before any device is realized, so before a device pins guest
* pages, which would keep them where they are. A range it cannot collapse
* stays on its pages; one line says how much is on huge pages, and the first
* failure. An async prealloc (prealloc-context) has not run yet here: none.
*/
static void host_memory_backend_collapse(HostMemoryBackend *backend,
void *ptr, uint64_t sz,
size_t pagesize, bool async)
{
#if defined(CONFIG_LINUX) && (defined(__x86_64__) || defined(__aarch64__))
#ifndef MADV_COLLAPSE
#define MADV_COLLAPSE 25
#endif
const uintptr_t huge = 2 * MiB;
uintptr_t start = QEMU_ALIGN_UP((uintptr_t)ptr, huge);
uintptr_t end = QEMU_ALIGN_DOWN((uintptr_t)ptr + sz, huge);
g_autofree char *name = NULL;
uint64_t done = 0;
int64_t t0;
int err = 0;
/* A 2 MiB page is a huge page only over 4 KiB base pages. */
if (!backend->prealloc || !backend->share ||
(async && backend->prealloc_context) ||
memory_region_get_fd(&backend->mr) < 0 || pagesize != 4 * KiB) {
return;
}
t0 = g_get_monotonic_time();
for (uintptr_t addr = start; addr < end; addr += huge) {
if (madvise((void *)addr, huge, MADV_COLLAPSE) == 0) {
done += huge;
} else if (!err) {
err = errno;
}
}
name = host_memory_backend_get_name(backend);
info_report("memory backend '%s': %" PRIu64 " of %" PRIu64 " bytes on "
"huge pages after MADV_COLLAPSE, in %" PRId64 " ms%s%s",
name, done, sz, (g_get_monotonic_time() - t0) / 1000,
err ? "; first failure: " : "", err ? strerror(err) : "");
#endif
}
static void
host_memory_backend_memory_complete(UserCreatable *uc, Error **errp)
{
@@ -486,7 +432,6 @@ host_memory_backend_memory_complete(UserCreatable *uc, Error **errp)
async, errp)) {
return;
}
host_memory_backend_collapse(backend, ptr, sz, pagesize, async);
}
static bool
+166 -374
View File
@@ -25,8 +25,6 @@
#include "qemu/osdep.h"
#include "qapi/error.h"
#include "qemu/cutils.h"
#include "qemu/host-utils.h"
#include "qemu/memalign.h"
#include "block/block-io.h"
#include "block/block_int.h"
#include "qemu/module.h"
@@ -45,11 +43,12 @@
#define FTYPE_HARDDISK 2
typedef struct RawWin32AIOData {
BlockDriverState *bs;
HANDLE hfile;
QEMUIOVector *qiov;
void *bounce_buf;
struct iovec *aio_iov;
int aio_niov;
size_t aio_nbytes;
int64_t aio_offset;
off64_t aio_offset;
int aio_type;
} RawWin32AIOData;
@@ -58,117 +57,85 @@ typedef struct BDRVRawState {
int type;
char drive_path[16]; /* format: "d:\" */
QEMUWin32AIOState *aio;
bool needs_alignment;
uint32_t probed_req_align;
uint32_t probed_mem_align;
} BDRVRawState;
typedef struct BDRVRawReopenState {
HANDLE hfile;
bool needs_alignment;
uint32_t probed_req_align;
uint32_t probed_mem_align;
} BDRVRawReopenState;
static int win32_error_to_errno(DWORD err)
/*
* Read/writes the data to/from a given linear buffer.
*
* Returns the number of bytes handles or -errno in case of an error. Short
* reads are only returned if the end of the file is reached.
*/
static size_t handle_aiocb_rw(RawWin32AIOData *aiocb)
{
switch (err) {
case ERROR_DISK_FULL:
case ERROR_HANDLE_DISK_FULL:
return -ENOSPC;
case ERROR_ACCESS_DENIED:
return -EACCES;
case ERROR_INVALID_PARAMETER:
return -EINVAL;
case ERROR_OPERATION_ABORTED:
return -ECANCELED;
case ERROR_NOT_ENOUGH_MEMORY:
case ERROR_OUTOFMEMORY:
return -ENOMEM;
default:
return -EIO;
}
}
size_t offset = 0;
int i;
static int handle_aiocb_rw(RawWin32AIOData *aiocb, size_t *transferred)
{
QEMUIOVector *qiov = aiocb->qiov;
struct iovec bounce_iov = {
.iov_base = aiocb->bounce_buf,
.iov_len = aiocb->aio_nbytes,
};
const struct iovec *iov = aiocb->bounce_buf ? &bounce_iov : qiov->iov;
int niov = aiocb->bounce_buf ? 1 : qiov->niov;
bool is_read = (aiocb->aio_type & QEMU_AIO_TYPE_MASK) == QEMU_AIO_READ;
for (i = 0; i < aiocb->aio_niov; i++) {
OVERLAPPED ov;
DWORD ret, ret_count, len;
*transferred = 0;
for (int i = 0; i < niov; i++) {
uint64_t offset = aiocb->aio_offset + *transferred;
OVERLAPPED ov = {
.Offset = (DWORD)offset,
.OffsetHigh = (DWORD)(offset >> 32),
};
DWORD len = (DWORD)iov[i].iov_len;
DWORD count;
BOOL ok;
if (len == 0) {
continue;
}
if (is_read) {
ok = ReadFile(aiocb->hfile, iov[i].iov_base, len, &count, &ov);
memset(&ov, 0, sizeof(ov));
ov.Offset = (aiocb->aio_offset + offset);
ov.OffsetHigh = (aiocb->aio_offset + offset) >> 32;
len = aiocb->aio_iov[i].iov_len;
if (aiocb->aio_type & QEMU_AIO_WRITE) {
ret = WriteFile(aiocb->hfile, aiocb->aio_iov[i].iov_base,
len, &ret_count, &ov);
} else {
ok = WriteFile(aiocb->hfile, iov[i].iov_base, len, &count, &ov);
ret = ReadFile(aiocb->hfile, aiocb->aio_iov[i].iov_base,
len, &ret_count, &ov);
}
if (!ok) {
DWORD err = GetLastError();
if (is_read && err == ERROR_HANDLE_EOF) {
return 0;
}
return win32_error_to_errno(err);
if (!ret) {
ret_count = 0;
}
if (count > len) {
return -EIO;
}
*transferred += count;
if (count < len) {
if (ret_count != len) {
offset += ret_count;
break;
}
offset += len;
}
return 0;
return offset;
}
static int aio_worker(void *arg)
{
RawWin32AIOData *aiocb = arg;
int ret = 0;
ssize_t ret = 0;
size_t count;
QEMUIOVector *qiov = aiocb->qiov;
switch (aiocb->aio_type & QEMU_AIO_TYPE_MASK) {
case QEMU_AIO_READ:
ret = handle_aiocb_rw(aiocb, &count);
if (ret < 0) {
break;
}
if (aiocb->bounce_buf && count) {
iov_from_buf(qiov->iov, qiov->niov, 0, aiocb->bounce_buf, count);
}
count = handle_aiocb_rw(aiocb);
if (count < aiocb->aio_nbytes) {
qemu_iovec_memset(qiov, count, 0, aiocb->aio_nbytes - count);
/* A short read means that we have reached EOF. Pad the buffer
* with zeros for bytes after EOF. */
iov_memset(aiocb->aio_iov, aiocb->aio_niov, count,
0, aiocb->aio_nbytes - count);
count = aiocb->aio_nbytes;
}
if (count == aiocb->aio_nbytes) {
ret = 0;
} else {
ret = -EINVAL;
}
break;
case QEMU_AIO_WRITE:
ret = handle_aiocb_rw(aiocb, &count);
if (ret == 0 && count < aiocb->aio_nbytes) {
ret = -EIO;
count = handle_aiocb_rw(aiocb);
if (count == aiocb->aio_nbytes) {
ret = 0;
} else {
ret = -EINVAL;
}
break;
case QEMU_AIO_FLUSH:
if (!FlushFileBuffers(aiocb->hfile)) {
ret = win32_error_to_errno(GetLastError());
return -EIO;
}
break;
default:
@@ -177,47 +144,30 @@ static int aio_worker(void *arg)
break;
}
g_free(aiocb);
return ret;
}
static int coroutine_fn paio_co_submit(BlockDriverState *bs, HANDLE hfile,
int64_t offset, QEMUIOVector *qiov, int64_t bytes, int type)
static BlockAIOCB *paio_submit(BlockDriverState *bs, HANDLE hfile,
int64_t offset, QEMUIOVector *qiov, int count,
BlockCompletionFunc *cb, void *opaque, int type)
{
RawWin32AIOData acb = {
.hfile = hfile,
.aio_type = type,
.aio_offset = offset,
.qiov = qiov,
};
int ret;
RawWin32AIOData *acb = g_new(RawWin32AIOData, 1);
if (bytes < 0 || bytes > BDRV_REQUEST_MAX_BYTES ||
(qiov && qiov->size != (uint64_t)bytes)) {
return -EINVAL;
}
acb.aio_nbytes = bytes;
if (bytes && (bs->open_flags & BDRV_O_NOCACHE)) {
if (!QEMU_IS_ALIGNED(offset, bs->bl.request_alignment) ||
!QEMU_IS_ALIGNED(bytes, bs->bl.request_alignment)) {
return -EINVAL;
}
if (qiov->niov > 1 ||
!QEMU_PTR_IS_ALIGNED(qiov->iov[0].iov_base,
bdrv_min_mem_align(bs))) {
acb.bounce_buf = qemu_try_blockalign(bs, bytes);
if (!acb.bounce_buf) {
return -ENOMEM;
}
if (type & QEMU_AIO_WRITE) {
iov_to_buf(qiov->iov, qiov->niov, 0, acb.bounce_buf, bytes);
}
}
}
acb->bs = bs;
acb->hfile = hfile;
acb->aio_type = type;
trace_file_paio_submit(&acb, NULL, offset, (int)acb.aio_nbytes, type);
ret = thread_pool_submit_co(aio_worker, &acb);
qemu_vfree(acb.bounce_buf);
return ret;
if (qiov) {
acb->aio_iov = qiov->iov;
acb->aio_niov = qiov->niov;
assert(qiov->size == count);
}
acb->aio_nbytes = count;
acb->aio_offset = offset;
trace_file_paio_submit(acb, opaque, offset, count, type);
return thread_pool_submit_aio(aio_worker, acb, cb, opaque);
}
static int set_sparse(int fd)
@@ -246,184 +196,37 @@ static void raw_attach_aio_context(BlockDriverState *bs,
}
}
typedef struct RawIoStatusBlock {
union {
LONG Status;
PVOID Pointer;
};
ULONG_PTR Information;
} RawIoStatusBlock;
typedef struct RawFileFsSizeInfo {
LARGE_INTEGER TotalAllocationUnits;
LARGE_INTEGER AvailableAllocationUnits;
ULONG SectorsPerAllocationUnit;
ULONG BytesPerSector;
} RawFileFsSizeInfo;
typedef LONG (NTAPI * nt_query_volume_info_file_t)(HANDLE, RawIoStatusBlock *,
PVOID, ULONG, ULONG);
static bool raw_query_fs_sector_size(HANDLE hfile, uint32_t *logical)
{
enum { RAW_FILE_FS_SIZE_INFORMATION = 3 };
HMODULE ntdll = GetModuleHandleA("ntdll.dll");
nt_query_volume_info_file_t query_vol;
RawIoStatusBlock iosb = { 0 };
RawFileFsSizeInfo info = { 0 };
LONG status;
if (!ntdll) {
return false;
}
query_vol = (nt_query_volume_info_file_t)
GetProcAddress(ntdll, "NtQueryVolumeInformationFile");
if (!query_vol) {
return false;
}
/* Called before hfile is attached to an IOCP. */
status = query_vol(hfile, &iosb, &info, sizeof(info),
RAW_FILE_FS_SIZE_INFORMATION);
if (status == (LONG)STATUS_PENDING) {
if (WaitForSingleObject(hfile, INFINITE) != WAIT_OBJECT_0) {
return false;
}
status = iosb.Status;
}
if (status < 0 || iosb.Information < sizeof(info)) {
return false;
}
*logical = info.BytesPerSector;
return true;
}
static int raw_probe_volume_alignment(HANDLE hfile, const char *filename,
uint32_t *logical, uint32_t *physical,
Error **errp)
{
DWORD path_size = GetFinalPathNameByHandleW(hfile, NULL, 0,
VOLUME_NAME_GUID);
if (path_size > 0) {
g_autofree wchar_t *path = g_new(wchar_t, path_size);
DWORD length = GetFinalPathNameByHandleW(hfile, path, path_size,
VOLUME_NAME_GUID);
wchar_t *slash = (length > 4 && length < path_size)
? wcschr(path + 4, L'\\') : NULL;
if (slash) {
HANDLE volume_handle;
*slash = L'\0';
volume_handle = CreateFileW(path, 0,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, 0, NULL);
if (volume_handle != INVALID_HANDLE_VALUE) {
STORAGE_PROPERTY_QUERY query = {
.PropertyId = StorageAccessAlignmentProperty,
.QueryType = PropertyStandardQuery,
};
STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR info;
DWORD returned;
BOOL ok = DeviceIoControl(volume_handle,
IOCTL_STORAGE_QUERY_PROPERTY,
&query, sizeof(query),
&info, sizeof(info),
&returned, NULL);
CloseHandle(volume_handle);
if (ok && returned >= sizeof(info) &&
info.Size >= sizeof(info) &&
info.BytesPerLogicalSector >= BDRV_SECTOR_SIZE &&
info.BytesPerLogicalSector <= BDRV_MAX_ALIGNMENT &&
is_power_of_2(info.BytesPerLogicalSector)) {
*logical = info.BytesPerLogicalSector;
*physical = info.BytesPerPhysicalSector;
return 0;
}
}
}
}
if (raw_query_fs_sector_size(hfile, logical)) {
*physical = 0;
return 0;
}
error_setg(errp, "Could not query sector size for '%s'", filename);
return -EINVAL;
}
static int raw_probe_direct_alignment(HANDLE hfile, const char *drive_path,
uint32_t *req_align, uint32_t *mem_align,
Error **errp)
{
FILE_STORAGE_INFO fsi;
FILE_ALIGNMENT_INFO fai;
uint32_t logical, physical;
uint64_t file_align = 0;
bool have_storage_info;
have_storage_info = GetFileInformationByHandleEx(hfile, FileStorageInfo,
&fsi, sizeof(fsi));
if (have_storage_info) {
logical = fsi.LogicalBytesPerSector;
physical = 0;
if (is_power_of_2(fsi.PhysicalBytesPerSectorForAtomicity) &&
fsi.PhysicalBytesPerSectorForAtomicity <= BDRV_MAX_ALIGNMENT) {
physical = fsi.PhysicalBytesPerSectorForAtomicity;
}
} else {
int ret = raw_probe_volume_alignment(hfile, drive_path, &logical,
&physical, errp);
if (ret < 0) {
return ret;
}
if (!is_power_of_2(physical) || physical > BDRV_MAX_ALIGNMENT) {
physical = 0;
}
}
if (GetFileInformationByHandleEx(hfile, FileAlignmentInfo,
&fai, sizeof(fai))) {
file_align = (uint64_t)fai.AlignmentRequirement + 1;
if (!is_power_of_2(file_align) || file_align > BDRV_MAX_ALIGNMENT) {
error_setg(errp, "Unsupported buffer alignment for '%s'",
drive_path);
return -EINVAL;
}
}
if (logical < BDRV_SECTOR_SIZE || logical > BDRV_MAX_ALIGNMENT ||
!is_power_of_2(logical)) {
error_setg(errp, "Unsupported logical sector size %" PRIu32
" for '%s'", logical, drive_path);
return -EINVAL;
}
if (!have_storage_info && !physical) {
if (!file_align) {
error_setg(errp, "Could not determine direct I/O buffer alignment "
"for '%s'", drive_path);
return -EINVAL;
}
physical = qemu_real_host_page_size();
}
*req_align = logical;
*mem_align = MAX(logical, MAX(physical, (uint32_t)file_align));
return 0;
}
static void raw_probe_alignment(BlockDriverState *bs, Error **errp)
{
BDRVRawState *s = bs->opaque;
DWORD sectorsPerCluster, freeClusters, totalClusters, count;
DISK_GEOMETRY_EX dg;
BOOL status;
bs->bl.request_alignment = s->needs_alignment ? s->probed_req_align : 1;
if (s->needs_alignment) {
bs->bl.min_mem_alignment = s->probed_mem_align;
bs->bl.opt_mem_alignment = MAX(s->probed_mem_align,
qemu_real_host_page_size());
if (s->type == FTYPE_CD) {
bs->bl.request_alignment = 2048;
return;
}
if (s->type == FTYPE_HARDDISK) {
status = DeviceIoControl(s->hfile, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX,
NULL, 0, &dg, sizeof(dg), &count, NULL);
if (status != 0) {
bs->bl.request_alignment = dg.Geometry.BytesPerSector;
return;
}
/* try GetDiskFreeSpace too */
}
if (s->drive_path[0]) {
GetDiskFreeSpace(s->drive_path, &sectorsPerCluster,
&dg.Geometry.BytesPerSector,
&freeClusters, &totalClusters);
bs->bl.request_alignment = dg.Geometry.BytesPerSector;
return;
}
/* XXX Does Windows support AIO on less than 512-byte alignment? */
bs->bl.request_alignment = 512;
}
static void raw_parse_flags(int flags, bool use_aio, int *access_flags,
@@ -548,6 +351,17 @@ static int raw_open(BlockDriverState *bs, QDict *options, int flags,
raw_parse_flags(flags, use_aio, &access_flags, &overlapped);
if (filename[0] && filename[1] == ':') {
snprintf(s->drive_path, sizeof(s->drive_path), "%c:\\", filename[0]);
} else if (filename[0] == '\\' && filename[1] == '\\') {
s->drive_path[0] = 0;
} else {
/* Relative path. */
char buf[MAX_PATH];
GetCurrentDirectory(MAX_PATH, buf);
snprintf(s->drive_path, sizeof(s->drive_path), "%c:\\", buf[0]);
}
s->hfile = CreateFile(filename, access_flags,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
OPEN_EXISTING, overlapped, NULL);
@@ -563,30 +377,21 @@ static int raw_open(BlockDriverState *bs, QDict *options, int flags,
goto fail;
}
s->needs_alignment = flags & BDRV_O_NOCACHE;
if (s->needs_alignment) {
ret = raw_probe_direct_alignment(s->hfile, filename,
&s->probed_req_align,
&s->probed_mem_align, errp);
if (ret < 0) {
goto fail_handle;
}
}
if (use_aio) {
s->aio = win32_aio_init();
if (s->aio == NULL) {
DWORD err = GetLastError();
error_setg_win32(errp, err, "Could not initialize AIO");
ret = win32_error_to_errno(err);
goto fail_handle;
CloseHandle(s->hfile);
error_setg(errp, "Could not initialize AIO");
ret = -EINVAL;
goto fail;
}
ret = win32_aio_attach(s->aio, s->hfile);
if (ret < 0) {
error_setg_win32(errp, GetLastError(), "Could not enable AIO");
goto fail_handle;
win32_aio_cleanup(s->aio);
CloseHandle(s->hfile);
error_setg_errno(errp, -ret, "Could not enable AIO");
goto fail;
}
win32_aio_attach_aio_context(s->aio, bdrv_get_aio_context(bs));
@@ -595,54 +400,47 @@ static int raw_open(BlockDriverState *bs, QDict *options, int flags,
/* When extending regular files, we get zeros from the OS */
bs->supported_truncate_flags = BDRV_REQ_ZERO_WRITE;
qemu_opts_del(opts);
return 0;
fail_handle:
CloseHandle(s->hfile);
s->hfile = INVALID_HANDLE_VALUE;
if (s->aio) {
win32_aio_cleanup(s->aio);
s->aio = NULL;
}
ret = 0;
fail:
qemu_opts_del(opts);
return ret;
}
static int coroutine_fn raw_co_preadv(BlockDriverState *bs,
int64_t offset, int64_t bytes,
QEMUIOVector *qiov,
BdrvRequestFlags flags)
static BlockAIOCB *raw_aio_preadv(BlockDriverState *bs,
int64_t offset, int64_t bytes,
QEMUIOVector *qiov, BdrvRequestFlags flags,
BlockCompletionFunc *cb, void *opaque)
{
BDRVRawState *s = bs->opaque;
if (s->aio) {
return win32_aio_co_submit(bs, s->aio, s->hfile, offset, bytes, qiov,
QEMU_AIO_READ);
return win32_aio_submit(bs, s->aio, s->hfile, offset, bytes, qiov,
cb, opaque, QEMU_AIO_READ);
} else {
return paio_submit(bs, s->hfile, offset, qiov, bytes,
cb, opaque, QEMU_AIO_READ);
}
return paio_co_submit(bs, s->hfile, offset, qiov, bytes, QEMU_AIO_READ);
}
static int coroutine_fn raw_co_pwritev(BlockDriverState *bs,
int64_t offset, int64_t bytes,
QEMUIOVector *qiov,
BdrvRequestFlags flags)
static BlockAIOCB *raw_aio_pwritev(BlockDriverState *bs,
int64_t offset, int64_t bytes,
QEMUIOVector *qiov, BdrvRequestFlags flags,
BlockCompletionFunc *cb, void *opaque)
{
BDRVRawState *s = bs->opaque;
if (s->aio) {
return win32_aio_co_submit(bs, s->aio, s->hfile, offset, bytes, qiov,
QEMU_AIO_WRITE);
return win32_aio_submit(bs, s->aio, s->hfile, offset, bytes, qiov,
cb, opaque, QEMU_AIO_WRITE);
} else {
return paio_submit(bs, s->hfile, offset, qiov, bytes,
cb, opaque, QEMU_AIO_WRITE);
}
return paio_co_submit(bs, s->hfile, offset, qiov, bytes, QEMU_AIO_WRITE);
}
static int coroutine_fn raw_co_flush_to_disk(BlockDriverState *bs)
static BlockAIOCB *raw_aio_flush(BlockDriverState *bs,
BlockCompletionFunc *cb, void *opaque)
{
BDRVRawState *s = bs->opaque;
return paio_co_submit(bs, s->hfile, 0, NULL, 0, QEMU_AIO_FLUSH);
return paio_submit(bs, s->hfile, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
}
static void raw_close(BlockDriverState *bs)
@@ -651,12 +449,11 @@ static void raw_close(BlockDriverState *bs)
if (s->aio) {
win32_aio_detach_aio_context(s->aio, bdrv_get_aio_context(bs));
}
CloseHandle(s->hfile);
if (s->aio) {
win32_aio_cleanup(s->aio);
s->aio = NULL;
}
CloseHandle(s->hfile);
if (bs->open_flags & BDRV_O_TEMPORARY) {
unlink(bs->filename);
}
@@ -667,7 +464,8 @@ static int coroutine_fn raw_co_truncate(BlockDriverState *bs, int64_t offset,
BdrvRequestFlags flags, Error **errp)
{
BDRVRawState *s = bs->opaque;
FILE_END_OF_FILE_INFO info = { .EndOfFile.QuadPart = offset };
LONG low, high;
DWORD dwPtrLow;
if (prealloc != PREALLOC_MODE_OFF) {
error_setg(errp, "Unsupported preallocation mode '%s'",
@@ -675,12 +473,21 @@ static int coroutine_fn raw_co_truncate(BlockDriverState *bs, int64_t offset,
return -ENOTSUP;
}
if (!SetFileInformationByHandle(s->hfile, FileEndOfFileInfo,
&info, sizeof(info))) {
DWORD err = GetLastError();
low = offset;
high = offset >> 32;
error_setg_win32(errp, err, "Could not set end of file");
return win32_error_to_errno(err);
/*
* An error has occurred if the return value is INVALID_SET_FILE_POINTER
* and GetLastError doesn't return NO_ERROR.
*/
dwPtrLow = SetFilePointer(s->hfile, low, &high, FILE_BEGIN);
if (dwPtrLow == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) {
error_setg_win32(errp, GetLastError(), "SetFilePointer error");
return -EIO;
}
if (SetEndOfFile(s->hfile) == 0) {
error_setg_win32(errp, GetLastError(), "SetEndOfFile error");
return -EIO;
}
return 0;
}
@@ -804,7 +611,7 @@ static int raw_reopen_prepare(BDRVReopenState *state,
BDRVRawReopenState *rs;
int access_flags;
DWORD overlapped;
int ret;
int ret = 0;
if (s->type != FTYPE_FILE) {
error_setg(errp, "Can only reopen files");
@@ -838,21 +645,12 @@ static int raw_reopen_prepare(BDRVReopenState *state,
goto fail;
}
rs->needs_alignment = state->flags & BDRV_O_NOCACHE;
if (rs->needs_alignment) {
ret = raw_probe_direct_alignment(rs->hfile, state->bs->filename,
&rs->probed_req_align,
&rs->probed_mem_align, errp);
if (ret < 0) {
goto fail_handle;
}
}
if (s->aio) {
ret = win32_aio_attach(s->aio, rs->hfile);
if (ret < 0) {
error_setg_win32(errp, GetLastError(), "Could not enable AIO");
goto fail_handle;
error_setg_errno(errp, -ret, "Could not enable AIO");
CloseHandle(rs->hfile);
goto fail;
}
}
@@ -860,8 +658,6 @@ static int raw_reopen_prepare(BDRVReopenState *state,
return 0;
fail_handle:
CloseHandle(rs->hfile);
fail:
g_free(rs);
state->opaque = NULL;
@@ -878,9 +674,6 @@ static void raw_reopen_commit(BDRVReopenState *state)
CloseHandle(s->hfile);
s->hfile = rs->hfile;
s->needs_alignment = rs->needs_alignment;
s->probed_req_align = rs->probed_req_align;
s->probed_mem_align = rs->probed_mem_align;
g_free(rs);
state->opaque = NULL;
@@ -894,7 +687,9 @@ static void raw_reopen_abort(BDRVReopenState *state)
return;
}
CloseHandle(rs->hfile);
if (rs->hfile != INVALID_HANDLE_VALUE) {
CloseHandle(rs->hfile);
}
g_free(rs);
state->opaque = NULL;
@@ -929,12 +724,9 @@ BlockDriver bdrv_file = {
.bdrv_reopen_commit = raw_reopen_commit,
.bdrv_reopen_abort = raw_reopen_abort,
.bdrv_co_preadv = raw_co_preadv,
.bdrv_co_pwritev = raw_co_pwritev,
.bdrv_co_flush_to_disk = raw_co_flush_to_disk,
.bdrv_detach_aio_context = raw_detach_aio_context,
.bdrv_attach_aio_context = raw_attach_aio_context,
.bdrv_aio_preadv = raw_aio_preadv,
.bdrv_aio_pwritev = raw_aio_pwritev,
.bdrv_aio_flush = raw_aio_flush,
.bdrv_co_truncate = raw_co_truncate,
.bdrv_co_getlength = raw_co_getlength,
@@ -1100,9 +892,9 @@ static BlockDriver bdrv_host_device = {
.bdrv_close = raw_close,
.bdrv_refresh_limits = hdev_refresh_limits,
.bdrv_co_preadv = raw_co_preadv,
.bdrv_co_pwritev = raw_co_pwritev,
.bdrv_co_flush_to_disk = raw_co_flush_to_disk,
.bdrv_aio_preadv = raw_aio_preadv,
.bdrv_aio_pwritev = raw_aio_pwritev,
.bdrv_aio_flush = raw_aio_flush,
.bdrv_detach_aio_context = raw_detach_aio_context,
.bdrv_attach_aio_context = raw_attach_aio_context,
+138 -243
View File
@@ -23,319 +23,214 @@
*/
#include "qemu/osdep.h"
#include "qemu/timer.h"
#include "block/block-io.h"
#include "block/block_int.h"
#include "qemu/aio.h"
#include "block/raw-aio.h"
#include "qemu/error-report.h"
#include "qemu/aiocb.h"
#include "qemu/event_notifier.h"
#include "qemu/iov.h"
#include "qemu/lockable.h"
#include "qemu/memalign.h"
#include "qemu/thread.h"
#include "qemu/units.h"
#include <windows.h>
#include <winioctl.h>
enum {
WIN32_AIO_KEY_IO = 1,
WIN32_AIO_KEY_STOP,
};
#define WIN32_AIO_BOUNCE_MAX_CACHED 16
static const struct {
size_t size;
unsigned int capacity;
} bounce_buckets[] = {
{ 64 * KiB, WIN32_AIO_BOUNCE_MAX_CACHED },
{ 256 * KiB, 8 },
{ MiB, 8 },
};
typedef struct Win32AioBounceBucket {
void *buffers[WIN32_AIO_BOUNCE_MAX_CACHED];
unsigned int count;
} Win32AioBounceBucket;
#define FTYPE_FILE 0
#define FTYPE_CD 1
#define FTYPE_HARDDISK 2
struct QEMUWin32AIOState {
HANDLE hIOCP;
QemuThread waiter_thread;
EventNotifier e;
int count;
AioContext *aio_ctx;
bool skip_iocp_on_success;
QemuMutex pool_lock;
size_t pool_align;
Win32AioBounceBucket pool[ARRAY_SIZE(bounce_buckets)];
};
typedef struct Win32AioCoReq {
OVERLAPPED ov;
Coroutine *co;
typedef struct QEMUWin32AIOCB {
BlockAIOCB common;
struct QEMUWin32AIOState *ctx;
AioContext *req_ctx;
DWORD win32_err;
DWORD transferred;
} Win32AioCoReq;
static int win32_error_to_errno(DWORD err)
{
switch (err) {
case ERROR_DISK_FULL:
case ERROR_HANDLE_DISK_FULL:
return -ENOSPC;
case ERROR_ACCESS_DENIED:
return -EACCES;
case ERROR_INVALID_PARAMETER:
return -EINVAL;
case ERROR_OPERATION_ABORTED:
return -ECANCELED;
case ERROR_NOT_ENOUGH_MEMORY:
case ERROR_OUTOFMEMORY:
return -ENOMEM;
default:
return -EIO;
}
}
static void *win32_aio_bounce_alloc(QEMUWin32AIOState *aio,
BlockDriverState *bs, size_t bytes,
int *bucket_out)
{
int bucket = 0;
int nbytes;
OVERLAPPED ov;
QEMUIOVector *qiov;
void *buf;
bool is_read;
bool is_linear;
int ret;
} QEMUWin32AIOCB;
while (bucket < ARRAY_SIZE(bounce_buckets) &&
bytes > bounce_buckets[bucket].size) {
bucket++;
}
if (bucket == ARRAY_SIZE(bounce_buckets) ||
bdrv_min_mem_align(bs) > aio->pool_align) {
*bucket_out = -1;
return qemu_try_blockalign(bs, bytes);
}
static void win32_aio_completion_cb_bh(void *opaque)
{
QEMUWin32AIOCB *waiocb = opaque;
WITH_QEMU_LOCK_GUARD(&aio->pool_lock) {
Win32AioBounceBucket *pool = &aio->pool[bucket];
if (pool->count) {
*bucket_out = bucket;
return pool->buffers[--pool->count];
}
}
buf = qemu_try_memalign(aio->pool_align, bounce_buckets[bucket].size);
if (buf) {
*bucket_out = bucket;
}
return buf;
waiocb->common.cb(waiocb->common.opaque, waiocb->ret);
aio_context_unref(waiocb->req_ctx);
qemu_aio_unref(waiocb);
}
static void win32_aio_bounce_free(QEMUWin32AIOState *aio, void *buf, int bucket)
/*
* Completes an AIO request (calls the callback and frees the ACB).
*/
static void win32_aio_process_completion(QEMUWin32AIOState *s,
QEMUWin32AIOCB *waiocb, DWORD count)
{
if (!buf) {
return;
}
if (bucket >= 0) {
Win32AioBounceBucket *pool = &aio->pool[bucket];
QEMU_LOCK_GUARD(&aio->pool_lock);
s->count--;
if (pool->count < bounce_buckets[bucket].capacity) {
pool->buffers[pool->count++] = buf;
return;
}
}
qemu_vfree(buf);
}
static void *win32_aio_waiter(void *opaque)
{
QEMUWin32AIOState *s = opaque;
for (;;) {
DWORD count = 0;
ULONG_PTR key;
OVERLAPPED *ov;
Win32AioCoReq *req;
AioContext *ctx;
Coroutine *co;
BOOL ok = GetQueuedCompletionStatus(s->hIOCP, &count, &key, &ov,
INFINITE);
DWORD err = ok ? ERROR_SUCCESS : GetLastError();
if (!ov) {
if (!ok) {
error_report("GetQueuedCompletionStatus failed: %lu", err);
abort();
if (waiocb->ov.Internal != 0) {
waiocb->ret = -EIO;
} else {
waiocb->ret = 0;
if (count < waiocb->nbytes) {
/* Short reads mean EOF, pad with zeros. */
if (waiocb->is_read) {
qemu_iovec_memset(waiocb->qiov, count, 0,
waiocb->qiov->size - count);
} else {
waiocb->ret = -EINVAL;
}
assert(key == WIN32_AIO_KEY_STOP);
break;
}
}
if (!waiocb->is_linear) {
if (waiocb->ret == 0 && waiocb->is_read) {
QEMUIOVector *qiov = waiocb->qiov;
iov_from_buf(qiov->iov, qiov->niov, 0, waiocb->buf, qiov->size);
}
qemu_vfree(waiocb->buf);
}
assert(key == WIN32_AIO_KEY_IO);
req = container_of(ov, Win32AioCoReq, ov);
ctx = req->req_ctx;
co = req->co;
req->win32_err = err;
req->transferred = err == ERROR_HANDLE_EOF ? 0 : count;
aio_co_schedule(ctx, co);
if (waiocb->req_ctx == s->aio_ctx) {
win32_aio_completion_cb_bh(waiocb);
} else {
aio_bh_schedule_oneshot(waiocb->req_ctx, win32_aio_completion_cb_bh,
waiocb);
}
return NULL;
}
int coroutine_fn win32_aio_co_submit(BlockDriverState *bs,
QEMUWin32AIOState *aio, HANDLE hfile,
uint64_t offset, uint64_t bytes, QEMUIOVector *qiov, int type)
static void win32_aio_completion_cb(EventNotifier *e)
{
Win32AioCoReq req;
void *bounce_buf = NULL;
int bucket = -1;
void *buf;
BOOL ok;
DWORD sync_transferred = 0;
DWORD transferred;
DWORD win32_err;
int ret = 0;
bool direct = bs->open_flags & BDRV_O_NOCACHE;
bool is_read = (type & QEMU_AIO_TYPE_MASK) == QEMU_AIO_READ;
QEMUWin32AIOState *s = container_of(e, QEMUWin32AIOState, e);
DWORD count;
ULONG_PTR key;
OVERLAPPED *ov;
assert(aio->aio_ctx);
if (bytes != qiov->size || bytes > BDRV_REQUEST_MAX_BYTES ||
bytes > UINT32_MAX) {
return -EINVAL;
}
if (bytes == 0) {
return 0;
}
if (direct && (!QEMU_IS_ALIGNED(offset, bs->bl.request_alignment) ||
!QEMU_IS_ALIGNED(bytes, bs->bl.request_alignment))) {
return -EINVAL;
}
event_notifier_test_and_clear(&s->e);
while (GetQueuedCompletionStatus(s->hIOCP, &count, &key, &ov, 0)) {
QEMUWin32AIOCB *waiocb = container_of(ov, QEMUWin32AIOCB, ov);
if (qiov->niov > 1 ||
(direct && !QEMU_PTR_IS_ALIGNED(qiov->iov[0].iov_base,
bdrv_min_mem_align(bs)))) {
bounce_buf = win32_aio_bounce_alloc(aio, bs, bytes, &bucket);
if (!bounce_buf) {
return -ENOMEM;
win32_aio_process_completion(s, waiocb, count);
}
}
static const AIOCBInfo win32_aiocb_info = {
.aiocb_size = sizeof(QEMUWin32AIOCB),
};
BlockAIOCB *win32_aio_submit(BlockDriverState *bs,
QEMUWin32AIOState *aio, HANDLE hfile,
uint64_t offset, uint64_t bytes, QEMUIOVector *qiov,
BlockCompletionFunc *cb, void *opaque, int type)
{
struct QEMUWin32AIOCB *waiocb;
DWORD rc;
waiocb = qemu_aio_get(&win32_aiocb_info, bs, cb, opaque);
waiocb->req_ctx = qemu_get_current_aio_context();
waiocb->nbytes = bytes;
waiocb->qiov = qiov;
waiocb->is_read = (type == QEMU_AIO_READ);
aio_context_ref(waiocb->req_ctx);
if (qiov->niov > 1) {
waiocb->buf = qemu_try_blockalign(bs, qiov->size);
if (waiocb->buf == NULL) {
goto out;
}
if (!is_read) {
iov_to_buf(qiov->iov, qiov->niov, 0, bounce_buf, bytes);
if (type & QEMU_AIO_WRITE) {
iov_to_buf(qiov->iov, qiov->niov, 0, waiocb->buf, qiov->size);
}
}
buf = bounce_buf ? bounce_buf : qiov->iov[0].iov_base;
/* The waiter can queue the coroutine before the system call returns. */
req = (Win32AioCoReq) {
.ov = {
.Offset = (DWORD)offset,
.OffsetHigh = (DWORD)(offset >> 32),
.hEvent = NULL,
},
.co = qemu_coroutine_self(),
.req_ctx = qemu_get_current_aio_context(),
};
if (is_read) {
ok = ReadFile(hfile, buf, (DWORD)bytes,
aio->skip_iocp_on_success ? &sync_transferred : NULL,
&req.ov);
waiocb->is_linear = false;
} else {
ok = WriteFile(hfile, buf, (DWORD)bytes,
aio->skip_iocp_on_success ? &sync_transferred : NULL,
&req.ov);
waiocb->buf = qiov->iov[0].iov_base;
waiocb->is_linear = true;
}
win32_err = ok ? ERROR_SUCCESS : GetLastError();
if (win32_err == ERROR_IO_PENDING || (ok && !aio->skip_iocp_on_success)) {
qemu_coroutine_yield();
win32_err = req.win32_err;
transferred = req.transferred;
memset(&waiocb->ov, 0, sizeof(waiocb->ov));
waiocb->ov.Offset = (DWORD)offset;
waiocb->ov.OffsetHigh = (DWORD)(offset >> 32);
waiocb->ov.hEvent = event_notifier_get_handle(&aio->e);
aio->count++;
if (type & QEMU_AIO_READ) {
rc = ReadFile(hfile, waiocb->buf, waiocb->nbytes, NULL, &waiocb->ov);
} else {
transferred = ok ? sync_transferred : 0;
rc = WriteFile(hfile, waiocb->buf, waiocb->nbytes, NULL, &waiocb->ov);
}
if (win32_err != ERROR_SUCCESS &&
!(is_read && win32_err == ERROR_HANDLE_EOF)) {
ret = win32_error_to_errno(win32_err);
} else if (transferred > bytes || (!is_read && transferred < bytes)) {
ret = -EIO;
} else if (is_read) {
if (bounce_buf && transferred) {
iov_from_buf(qiov->iov, qiov->niov, 0, bounce_buf, transferred);
}
if (transferred < bytes) {
qemu_iovec_memset(qiov, transferred, 0, bytes - transferred);
}
if(rc == 0 && GetLastError() != ERROR_IO_PENDING) {
goto out_dec_count;
}
return &waiocb->common;
win32_aio_bounce_free(aio, bounce_buf, bucket);
return ret;
out_dec_count:
aio->count--;
out:
qemu_aio_unref(waiocb);
return NULL;
}
int win32_aio_attach(QEMUWin32AIOState *aio, HANDLE hfile)
{
UCHAR modes = FILE_SKIP_COMPLETION_PORT_ON_SUCCESS |
FILE_SKIP_SET_EVENT_ON_HANDLE;
if (!CreateIoCompletionPort(hfile, aio->hIOCP, WIN32_AIO_KEY_IO, 0)) {
return win32_error_to_errno(GetLastError());
}
if (!aio->aio_ctx) {
aio->skip_iocp_on_success =
SetFileCompletionNotificationModes(hfile, modes) != 0;
} else if (aio->skip_iocp_on_success) {
if (!SetFileCompletionNotificationModes(hfile, modes)) {
return win32_error_to_errno(GetLastError());
}
if (CreateIoCompletionPort(hfile, aio->hIOCP, (ULONG_PTR) 0, 0) == NULL) {
return -EINVAL;
} else {
SetFileCompletionNotificationModes(hfile,
FILE_SKIP_SET_EVENT_ON_HANDLE);
return 0;
}
return 0;
}
void win32_aio_detach_aio_context(QEMUWin32AIOState *aio,
AioContext *old_context)
{
assert(aio->aio_ctx == old_context);
/* Block layer drain has waited for all requests to finish. */
if (!PostQueuedCompletionStatus(aio->hIOCP, 0, WIN32_AIO_KEY_STOP, NULL)) {
error_report("PostQueuedCompletionStatus failed: %lu", GetLastError());
abort();
}
qemu_thread_join(&aio->waiter_thread);
aio_set_event_notifier(old_context, &aio->e, NULL, NULL, NULL);
aio->aio_ctx = NULL;
}
void win32_aio_attach_aio_context(QEMUWin32AIOState *aio,
AioContext *new_context)
{
assert(!aio->aio_ctx);
aio->aio_ctx = new_context;
qemu_thread_create(&aio->waiter_thread, "win32-aio", win32_aio_waiter, aio,
QEMU_THREAD_JOINABLE);
aio_set_event_notifier(new_context, &aio->e, win32_aio_completion_cb,
NULL, NULL);
}
QEMUWin32AIOState *win32_aio_init(void)
{
HANDLE port = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);
QEMUWin32AIOState *s;
if (!port) {
return NULL;
s = g_malloc0(sizeof(*s));
if (event_notifier_init(&s->e, false) < 0) {
goto out_free_state;
}
s = g_new0(QEMUWin32AIOState, 1);
s->hIOCP = port;
qemu_mutex_init(&s->pool_lock);
s->pool_align = qemu_real_host_page_size();
s->hIOCP = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);
if (s->hIOCP == NULL) {
goto out_close_efd;
}
return s;
out_close_efd:
event_notifier_cleanup(&s->e);
out_free_state:
g_free(s);
return NULL;
}
void win32_aio_cleanup(QEMUWin32AIOState *aio)
{
assert(!aio->aio_ctx);
for (int i = 0; i < ARRAY_SIZE(aio->pool); i++) {
Win32AioBounceBucket *pool = &aio->pool[i];
for (unsigned int j = 0; j < pool->count; j++) {
qemu_vfree(pool->buffers[j]);
}
}
qemu_mutex_destroy(&aio->pool_lock);
CloseHandle(aio->hIOCP);
event_notifier_cleanup(&aio->e);
g_free(aio);
}
-5
View File
@@ -66,11 +66,6 @@ static void term_exit(void)
}
}
void qemu_chr_stdio_term_exit(void)
{
term_exit();
}
static void stdio_chr_set_echo(Chardev *chr, bool echo)
{
struct termios tty;
+1 -4
View File
@@ -9,7 +9,4 @@ include ../arm-softmmu/default.mak
# CONFIG_XLNX_VERSAL=n
# CONFIG_SBSA_REF=n
# CONFIG_NPCM8XX=n
# Selected by default when TCG or HVF is enabled; uncomment it to keep it
# out of the build.
# CONFIG_VMAPPLE=n
CONFIG_VMAPPLE=n
+10 -132
View File
@@ -12,17 +12,12 @@ Prerequisites
To run the vmapple machine model, you need to
* Run on Apple Silicon, on macOS 12.0 or above, for HVF; or on any host
under TCG (see `Under TCG`_)
* Have an already installed copy of a Virtualization.Framework macOS 12 or
later virtual machine. I will assume that you installed it using the
* Run on Apple Silicon
* Run on macOS 12.0 or above
* Have an already installed copy of a Virtualization.Framework macOS 12 virtual
machine. Note that newer versions than 12.x are currently NOT supported on
the guest side. I will assume that you installed it using the
`macosvm <https://github.com/s-u/macosvm>`__ CLI.
* Have a firmware for the machine, such as Ambrosia.
Virtualization.framework's own, AVPBooter, does not boot on it (see
`Guest firmware`_).
* Build QEMU with a crypto library (gnutls, nettle or libgcrypt), whose AES
ciphers the machine's AES engine runs on. Without one, the engine fails to
realize and QEMU exits at start.
First, we need to extract the UUID from the virtual machine that you installed. You can do this
by running the shell script in contrib/vmapple/uuid.sh on the macosvm.json file.
@@ -42,15 +37,15 @@ Now we also need to trim the aux partition. It contains metadata that we can jus
How to run
----------
Then, we can launch QEMU with the firmware and the readily installed target disk images. I
recommend to port forward the VM's ssh and vnc ports to the host to get better interactive access
into the target system:
Then, we can launch QEMU with the Virtualization.Framework pre-boot environment and the readily
installed target disk images. I recommend to port forward the VM's ssh and vnc ports to the host
to get better interactive access into the target system:
.. code-block:: bash
:caption: Example execution command line
$ UUID="$(contrib/vmapple/uuid.sh 'macosvm.json')"
$ FIRMWARE="ambrosia.bin"
$ AVPBOOTER="/System/Library/Frameworks/Virtualization.framework/Resources/AVPBooter.vmapple2.bin"
$ AUX="aux.img.trimmed"
$ DISK="disk.img"
$ qemu-system-aarch64 \
@@ -58,7 +53,7 @@ into the target system:
-m 4G \
-accel hvf \
-M vmapple,uuid="$UUID" \
-bios "$FIRMWARE" \
-bios "$AVPBOOTER" \
-drive file="$AUX",if=pflash,format=raw \
-drive file="$DISK",if=pflash,format=raw \
-drive file="$AUX",if=none,id=aux,format=raw \
@@ -68,120 +63,3 @@ into the target system:
-netdev user,id=net0,ipv6=off,hostfwd=tcp::2222-:22,hostfwd=tcp::5901-:5900 \
-device virtio-net-pci,netdev=net0
The machine offers virtio-net devices without a control queue: macOS's
driver can miss the completion of its first control command, and its
interface then never comes up. Without the queue the device stays
promiscuous and passes the guest every frame its backend delivers.
Under TCG
---------
The machine also runs under TCG, on any host, with ``-accel tcg`` in place of
``-accel hvf``. Its CPU type defaults to ``max`` under both; under HVF,
``max`` is the host's CPU. Under TCG, the machine's generic timer counts at
24 MHz, the timebase frequency macOS's device tree gives every CPU, and the
frequency of Apple silicon's system counter, which HVF passes through. The
``max`` CPU has no SME by default under TCG: macOS 14 sizes each thread's
SME state from the longest streaming vector, and with TCG's 2048-bit
vectors it panics as it starts. ``-cpu max,sme=on`` turns SME back on.
The pointer authentication calls of `Guest firmware`_ reach QEMU under TCG,
whose PSCI code answers each of them as not supported, as
Hypervisor.framework does, so a guest needs the same firmware under both.
As it starts, macOS's platform driver asks Virtualization.framework's machine
for a configuration register by writing the physical address of a request to
0x004ffff8. The machine leaves the request unanswered, as HVF leaves an
access to an address with no device, and the driver goes on without the
register; ``-d unimp`` logs the write. Under TCG any other access to an
address with no device is an external abort, which the kernel does not
survive. So the firmware's device tree must not list a device that the
machine lacks and macOS probes, such as Virtualization.framework's CTRR
device at 0x30260000.
Guest firmware
--------------
The machine's RAM starts at 4 GiB, and below it the PCIe MMIO window runs
from 0x50000000 up to RAM. macOS places every PCI BAR below 4 GiB, aligned
to its size, so a device with a 1 GiB BAR needs a free, 1 GiB-aligned
gigabyte there. Virtualization.framework's machine has its RAM at
0x70000000, and its firmware, AVPBooter, keeps its stack there, so AVPBooter
does not boot on this machine. A firmware for it gives macOS this layout in
the device tree; Ambrosia is one.
Under HVF the machine asks for 40 bits of guest physical address, or for the
most the host gives where that is fewer, where HVF's default is 36 bits:
macOS's kernel maps physical addresses of up to 40 bits. HVF gives the guest
that size as its ``ID_AA64MMFR0_EL1.PARange``. RAM must end within it.
The machine places nothing past RAM. From the end of RAM, rounded up to
1 GiB, to the end of the guest's physical addresses, in whole GiB, is room
that a device may map memory into once the guest runs; the read-only machine
properties ``x-pool-room-base`` and ``x-pool-room-size`` give it, and
``reims-graphics-pci`` puts its Shared pool there. Under KVM and TCG its end
is the CPU's ``PARange``, at most 40 bits.
The firmware also makes one change that macOS needs on this machine before
it enters the kernel. The machine makes no change to the guest itself.
A vmapple guest kernel asks the hypervisor to manage its pointer
authentication keys through paravirtualized hypercalls: ``hvc #0`` with
SMCCC function IDs 0xC1000000 to 0xC10000FF. Hypervisor.framework answers
these calls itself, without an exit to QEMU, and for a VM created through
its public API it answers each of them as not supported. The macOS 12 and
13 kernels carry on with the keys the firmware set up, which all processes
then share. From macOS 14 on, the kernel checks the result of every one of
these calls and loops forever when one fails, with ``hvc #0; cbnz x0, .``.
Hypervisor.framework implements the calls only for VMs created with a
private ISA setting, which needs an entitlement that only Apple-signed
binaries can hold. QEMU does not use it. So the firmware replaces each of
those loops with a ``nop``.
Clock
-----
Beside its PL031 at 0x20050000, the machine has Virtualization.framework's
second clock at 0x30240000, which macOS's device tree lists as ``avp-rtc``.
macOS keeps the offset from it to calendar time in NVRAM, on the aux drive,
and its timed daemon reads that offset to tell whether the clock was reset.
macOS's PL031 driver keeps no offset: with the PL031 alone, timed takes the
clock for reset on every boot, and sets it back to the last write to the
guest's disk until it reaches a time server. Both clocks count QEMU's RTC
clock from the Unix epoch, so ``-rtc base=`` and ``-rtc clock=`` apply to
both. The firmware's device tree gives the guest one of the two. macOS 14
and later drive ``avp-rtc``; the device trees of earlier releases list only
the PL031.
Display
-------
The machine gives the guest no display. Virtualization.framework's
paravirtualized display, which macOS drives with a driver of its own, is not
in this tree. A guest has a display only from a PCI display device given with
``-device`` that the guest has a driver for. Without one, reach the guest
through the serial console, or through ``ssh`` on host port 2222, which the
example forwards to the guest's port 22.
Input
-----
The machine gives the guest a USB keyboard and a USB pointing device,
``usb-vmapple-tablet`` unless the machine's ``tablet`` property names another
USB device: ``-M vmapple,tablet=usb-tablet`` gives it QEMU's usual USB
tablet instead.
``usb-vmapple-tablet`` is the pointing device Virtualization.framework gives
its macOS guests: an absolute pointer with three buttons, a wheel and a
horizontal wheel, whose reports also carry smooth scrolling, that is, the
distance scrolled with the phases of the gesture it belongs to and of the
momentum scrolling after it. macOS drives it with a driver of its own
(AppleVirtualPlatformHIDEventDriver in macOS 13.6), and scrolls as it does
with a trackpad: smooth scroll events, such as a window's under ``-display
none`` or the ``scroll`` events of ``input-send-event``, scroll the guest
point by point, both ways, with the momentum the host gave the gesture. A
wheel's notch scrolls a fixed 20 pixels there. Other guests see a HID mouse
with an absolute pointer and two wheels.
With ``usb-tablet``, macOS scrolls by whole wheel notches, which it
accelerates, vertically only.
-10
View File
@@ -393,16 +393,6 @@ usb device at hand, so it's a trial-and-error game. If the default
doesn't work, try another option and see whenever the situation
improves.
QEMU also resets the device itself when it lets go of it: when the
``usb-host`` device is removed or its host device closed, when QEMU
exits, and when opening the device fails. ``reset-on-close=false``
leaves it unreset: QEMU releases its interfaces and gives them back to
the host's drivers in the configuration the guest left. An Apple iOS
device switched to another USB mode by a macOS guest needs this: the
reset leaves it in a state from which the next guest's mode switch makes
it leave the bus until it is plugged in again, while unreset it stays in
the mode the guest set, which the next guest finds and keeps.
record usb transfers
^^^^^^^^^^^^^^^^^^^^
+1 -3
View File
@@ -22,9 +22,7 @@ Device properties
The Virtio sound device can be configured with the following properties:
* ``jacks`` number of physical jacks (Unimplemented).
* ``streams`` number of PCM streams: the playback streams first, then the capture streams.
* ``input-streams`` how many of the streams capture; by default the second half of them (none of
one stream, one of two). ``streams=1,input-streams=1`` makes a capture-only device.
* ``streams`` number of PCM streams. At the moment, no stream configuration is supported: the first one will always be a playback stream, an optional second will always be a capture stream. Adding more will cycle stream directions from playback to capture.
* ``chmaps`` number of channel maps (Unimplemented).
All streams are stereo and have the default channel positions ``Front left, right``.
-4
View File
@@ -61,7 +61,3 @@ virtio_snd_handle_event(void) "event queue callback called"
virtio_snd_pcm_stream_flush(uint32_t stream) "flushing stream %"PRIu32
virtio_snd_handle_tx_xfer(void) "tx queue callback called"
virtio_snd_handle_rx_xfer(void) "rx queue callback called"
virtio_snd_pcm_params(uint32_t stream, uint32_t buffer_bytes, uint32_t period_bytes, uint8_t channels, uint8_t format, uint8_t rate) "stream %"PRIu32": buffer_bytes=%"PRIu32" period_bytes=%"PRIu32" channels=%u format=%u rate=%u"
virtio_snd_pcm_queued(uint32_t stream, size_t size, size_t pending) "stream %"PRIu32": I/O message of %zu bytes queued, %zu pending"
virtio_snd_pcm_completed(uint32_t stream, size_t size, uint32_t latency, size_t pending) "stream %"PRIu32": I/O message completed with %zu bytes, latency_bytes=%"PRIu32", %zu pending"
virtio_snd_pcm_state(uint32_t stream, const char *command, size_t pending) "stream %"PRIu32": %s with %zu I/O messages pending"
-26
View File
@@ -12,7 +12,6 @@
#include "qom/object.h"
#include "qapi/error.h"
#include "hw/audio/model.h"
#include "hw/pci/pci.h"
#include "hw/virtio/virtio-pci.h"
#include "hw/audio/virtio-snd.h"
@@ -26,15 +25,12 @@ struct VirtIOSoundPCI {
VirtIOPCIProxy parent_obj;
VirtIOSound vdev;
bool ascending_capabilities;
};
static const Property virtio_snd_pci_properties[] = {
DEFINE_PROP_BIT("ioeventfd", VirtIOPCIProxy, flags,
VIRTIO_PCI_FLAG_USE_IOEVENTFD_BIT, true),
DEFINE_PROP_UINT32("vectors", VirtIOPCIProxy, nvectors, 2),
DEFINE_PROP_BOOL("x-ascending-capabilities", VirtIOSoundPCI,
ascending_capabilities, false),
};
static void virtio_snd_pci_realize(VirtIOPCIProxy *vpci_dev, Error **errp)
@@ -44,28 +40,6 @@ static void virtio_snd_pci_realize(VirtIOPCIProxy *vpci_dev, Error **errp)
virtio_pci_force_virtio_1(vpci_dev);
qdev_realize(vdev, BUS(&vpci_dev->bus), errp);
if (dev->ascending_capabilities && qdev_is_realized(vdev)) {
uint8_t *config = vpci_dev->pci_dev.config;
bool capabilities[PCI_CONFIG_SPACE_SIZE] = { false };
unsigned offset, previous = PCI_CAPABILITY_LIST;
/* macOS 27's virtio PCI transport revisits PCI_CFG and NOTIFY
* forever on a descending list, as virtio-net-pci's does. Keep
* capability contents and offsets; only reorder the links. */
for (offset = config[PCI_CAPABILITY_LIST]; offset;
offset = config[offset + PCI_CAP_LIST_NEXT]) {
capabilities[offset] = true;
}
for (offset = PCI_CONFIG_HEADER_SIZE; offset < PCI_CONFIG_SPACE_SIZE;
offset++) {
if (capabilities[offset]) {
config[previous] = offset;
previous = offset + PCI_CAP_LIST_NEXT;
}
}
config[previous] = 0;
}
}
static void virtio_snd_pci_class_init(ObjectClass *klass, const void *data)
+10 -94
View File
@@ -31,8 +31,6 @@
#define VIRTIO_SOUND_STREAM_DEFAULT 2
#define VIRTIO_SOUND_CHMAP_DEFAULT 0
#define VIRTIO_SOUND_HDA_FN_NID 0
/* input-streams unset: the second half of the streams take input. */
#define VIRTIO_SOUND_INPUT_STREAMS_HALF UINT32_MAX
typedef enum virtio_snd_pcm_state {
VIRTIO_SND_PCM_STATE_UNINIT = 0,
@@ -74,13 +72,6 @@ static void virtio_snd_process_cmdq(VirtIOSound *s);
static void virtio_snd_pcm_flush(VirtIOSoundPCMStream *stream);
static void virtio_snd_pcm_close(VirtIOSoundPCMStream *stream);
static void virtio_snd_pcm_in_cb(void *data, int available);
static size_t virtio_snd_pcm_get_io_msgs_count(VirtIOSoundPCMStream *stream);
/* The stream's id: its index in the device's array of streams. */
static uint32_t virtio_snd_pcm_stream_id(VirtIOSoundPCMStream *stream)
{
return stream - stream->s->streams;
}
static uint32_t supported_formats = BIT(VIRTIO_SND_PCM_FMT_S8)
| BIT(VIRTIO_SND_PCM_FMT_U8)
@@ -153,8 +144,6 @@ static const Property virtio_snd_properties[] = {
VIRTIO_SOUND_STREAM_DEFAULT),
DEFINE_PROP_UINT32("chmaps", VirtIOSound, snd_conf.chmaps,
VIRTIO_SOUND_CHMAP_DEFAULT),
DEFINE_PROP_UINT32("input-streams", VirtIOSound, input_streams,
VIRTIO_SOUND_INPUT_STREAMS_HALF),
};
static void
@@ -411,9 +400,6 @@ uint32_t virtio_snd_set_pcm_params(VirtIOSound *s,
st_params->channels = params->channels;
st_params->format = params->format;
st_params->rate = params->rate;
trace_virtio_snd_pcm_params(stream_id, st_params->buffer_bytes,
st_params->period_bytes, st_params->channels,
st_params->format, st_params->rate);
if (virtio_snd_pcm_state_prepared(stream->state)) {
/* implicit VIRTIO_SND_R_PCM_RELEASE */
@@ -534,6 +520,7 @@ static void virtio_snd_get_qemu_audsettings(audsettings *as,
static void virtio_snd_pcm_open(VirtIOSoundPCMStream *stream)
{
virtio_snd_get_qemu_audsettings(&stream->as, &stream->params);
stream->info.channels_max = stream->as.nchannels;
if (stream->info.direction == VIRTIO_SND_D_OUTPUT) {
stream->voice.out = audio_be_open_out(stream->s->audio_be,
@@ -694,8 +681,6 @@ static uint32_t virtio_snd_pcm_start_stop(VirtIOSound *s,
return cpu_to_le32(VIRTIO_SND_S_BAD_MSG);
}
trace_virtio_snd_pcm_state(stream_id, start ? "start" : "stop",
virtio_snd_pcm_get_io_msgs_count(stream));
if (start) {
switch (stream->state) {
case VIRTIO_SND_PCM_STATE_PREPARED:
@@ -725,14 +710,7 @@ static uint32_t virtio_snd_pcm_start_stop(VirtIOSound *s,
stream->state = VIRTIO_SND_PCM_STATE_STOPPED;
}
/*
* A started input stream captures only while the driver has buffers
* posted for it: virtio_snd_handle_rx_xfer starts its voice, and
* virtio_snd_pcm_in_cb stops it.
*/
virtio_snd_pcm_set_active(stream, start &&
(stream->info.direction == VIRTIO_SND_D_OUTPUT ||
!QSIMPLEQ_EMPTY(&stream->queue)));
virtio_snd_pcm_set_active(stream, start);
return cpu_to_le32(VIRTIO_SND_S_OK);
}
@@ -812,10 +790,6 @@ static void virtio_snd_handle_pcm_release(VirtIOSound *s,
stream_id = le32_to_cpu(stream_id);
trace_virtio_snd_handle_pcm_release(stream_id);
stream = virtio_snd_pcm_get_stream(s, stream_id);
if (stream) {
trace_virtio_snd_pcm_state(stream_id, "release",
virtio_snd_pcm_get_io_msgs_count(stream));
}
if (stream == NULL) {
error_report("%s already released stream %"PRIu32,
VIRTIO_DEVICE(s)->name, stream_id);
@@ -1054,7 +1028,6 @@ static void virtio_snd_handle_tx_xfer(VirtIODevice *vdev, VirtQueue *vq)
* return them after the for loop.
*/
bool must_empty_invalid_queue = false;
bool queued = false;
if (!virtio_queue_ready(vq)) {
return;
@@ -1107,9 +1080,6 @@ static void virtio_snd_handle_tx_xfer(VirtIODevice *vdev, VirtQueue *vq)
stream->latency_bytes += size;
QSIMPLEQ_INSERT_TAIL(&stream->queue, buffer, entry);
trace_virtio_snd_pcm_queued(stream_id, size,
virtio_snd_pcm_get_io_msgs_count(stream));
queued = true;
continue;
tx_err:
@@ -1123,15 +1093,6 @@ tx_err:
if (must_empty_invalid_queue) {
empty_invalid_queue(vdev, vq);
}
/*
* The guest's new audio goes to the host's device now, not at the audio
* timer's next run: a guest that hands its audio over in periods is then
* played that much sooner, and the backend's reserve need not cover the
* timer's step and lateness.
*/
if (queued) {
audio_be_kick(vsnd->audio_be);
}
}
/*
@@ -1201,11 +1162,6 @@ static void virtio_snd_handle_rx_xfer(VirtIODevice *vdev, VirtQueue *vq)
buffer->size = 0;
buffer->offset = 0;
QSIMPLEQ_INSERT_TAIL(&stream->queue, buffer, entry);
trace_virtio_snd_pcm_queued(stream_id, size,
virtio_snd_pcm_get_io_msgs_count(stream));
if (stream->state == VIRTIO_SND_PCM_STATE_STARTED) {
virtio_snd_pcm_set_active(stream, true);
}
continue;
@@ -1271,16 +1227,6 @@ static void virtio_snd_realize(DeviceState *dev, Error **errp)
return;
}
if (vsnd->input_streams == VIRTIO_SOUND_INPUT_STREAMS_HALF) {
vsnd->input_streams = vsnd->snd_conf.streams / 2;
}
if (vsnd->input_streams > vsnd->snd_conf.streams) {
error_setg(errp,
"Invalid number of input streams: %"PRIu32" of %"PRIu32,
vsnd->input_streams, vsnd->snd_conf.streams);
return;
}
if (vsnd->snd_conf.chmaps > VIRTIO_SND_CHMAP_MAX_SIZE) {
error_setg(errp,
"Invalid number of channel maps: %"PRIu32,
@@ -1308,7 +1254,7 @@ static void virtio_snd_realize(DeviceState *dev, Error **errp)
stream->info.formats = supported_formats;
stream->info.rates = supported_rates;
stream->info.direction =
i < vsnd->snd_conf.streams - vsnd->input_streams
i < vsnd->snd_conf.streams / 2 + (vsnd->snd_conf.streams & 1)
? VIRTIO_SND_D_OUTPUT : VIRTIO_SND_D_INPUT;
stream->info.channels_min = 1;
stream->info.channels_max = 2;
@@ -1357,9 +1303,6 @@ static inline void return_tx_buffer(VirtIOSoundPCMStream *stream,
buffer,
VirtIOSoundPCMBuffer,
entry);
trace_virtio_snd_pcm_completed(virtio_snd_pcm_stream_id(stream),
buffer->offset, stream->latency_bytes,
virtio_snd_pcm_get_io_msgs_count(stream));
virtio_snd_pcm_buffer_free(buffer);
}
@@ -1423,23 +1366,15 @@ static void virtio_snd_pcm_out_cb(void *data, int available)
}
/*
* Complete an input stream's I/O message: the frames recorded into it, from
* the start of its buffer, then the status part, which follows the buffer
* (5.14.6.8) wherever the frames end, as a buffer completes partly filled
* at the stream's end. The used length is the status' size plus that of the
* frames recorded.
* Flush all buffer data from this input stream's queue into the driver's
* virtual queue.
*
* @stream: VirtIOSoundPCMStream *stream
* @buffer: the I/O message's buffer
*/
static inline void return_rx_buffer(VirtIOSoundPCMStream *stream,
VirtIOSoundPCMBuffer *buffer)
{
virtio_snd_pcm_status resp = { 0 };
/* virtio_snd_handle_rx_xfer took no message shorter than the status. */
size_t status_offset = iov_size(buffer->elem->in_sg, buffer->elem->in_num)
- sizeof(virtio_snd_pcm_status);
resp.status = cpu_to_le32(VIRTIO_SND_S_OK);
resp.latency_bytes = 0;
/* Copy data -if any- to guest */
@@ -1450,7 +1385,7 @@ static inline void return_rx_buffer(VirtIOSoundPCMStream *stream,
buffer->size);
iov_from_buf(buffer->elem->in_sg,
buffer->elem->in_num,
status_offset,
buffer->size,
&resp,
sizeof(virtio_snd_pcm_status));
virtqueue_push(buffer->vq,
@@ -1463,9 +1398,6 @@ static inline void return_rx_buffer(VirtIOSoundPCMStream *stream,
buffer,
VirtIOSoundPCMBuffer,
entry);
trace_virtio_snd_pcm_completed(virtio_snd_pcm_stream_id(stream),
buffer->size, 0,
virtio_snd_pcm_get_io_msgs_count(stream));
virtio_snd_pcm_buffer_free(buffer);
}
@@ -1482,18 +1414,6 @@ static void virtio_snd_pcm_in_cb(void *data, int available)
VirtIOSoundPCMBuffer *buffer;
size_t size, max_size, to_read;
if (QSIMPLEQ_EMPTY(&stream->queue)) {
/*
* Audio came, and the driver has no buffer posted to take it: stop
* the voice until it posts one (virtio_snd_handle_rx_xfer). A driver
* that keeps its input stream started and posts no buffers for it
* (macOS's AppleVirtIOSound starts its input with each output) then
* runs no capture on the host.
*/
virtio_snd_pcm_set_active(stream, false);
return;
}
while (!QSIMPLEQ_EMPTY(&stream->queue)) {
buffer = QSIMPLEQ_FIRST(&stream->queue);
if (!virtio_queue_ready(buffer->vq)) {
@@ -1512,18 +1432,14 @@ static void virtio_snd_pcm_in_cb(void *data, int available)
}
max_size -= sizeof(virtio_snd_pcm_status);
/*
* A message completes once its buffer is full, whatever its size
* against period_bytes: the device MUST NOT complete it before, but
* at the stream's end (5.14.6.8, Input Stream), where a flush and a
* stopped stream complete it as it is.
*/
for (;;) {
if (buffer->size >= max_size) {
return_rx_buffer(stream, buffer);
break;
}
to_read = MIN(max_size - buffer->size, available);
to_read = stream->params.period_bytes - buffer->size;
to_read = MIN(to_read, available);
to_read = MIN(to_read, max_size - buffer->size);
size = audio_be_read(stream->s->audio_be,
stream->voice.in,
buffer->data + buffer->size,
@@ -1534,7 +1450,7 @@ static void virtio_snd_pcm_in_cb(void *data, int available)
}
buffer->size += size;
available -= size;
if (buffer->size >= max_size) {
if (buffer->size >= stream->params.period_bytes) {
return_rx_buffer(stream, buffer);
break;
}
-6
View File
@@ -708,12 +708,6 @@ static void pl011_reset(DeviceState *dev)
s->logged_disabled_uart = false;
pl011_reset_rx_fifo(s);
pl011_reset_tx_fifo(s);
/*
* Lower the interrupt lines the cleared state no longer raises: a line
* keeps its level across a reset otherwise, and an in-kernel GIC (HVF's,
* KVM's) raises its interrupt again once the GIC is reset.
*/
pl011_update(s);
}
static void pl011_class_init(ObjectClass *oc, const void *data)
+6 -2
View File
@@ -150,7 +150,11 @@ config XLNX_DISPLAYPORT
config DM163
bool
config REIMS_GRAPHICS_PCI
config MAC_PVG_MMIO
bool
depends on REIMS_GRAPHICS && PCI && MSI_NONBROKEN
depends on MAC_PVG && AARCH64
config MAC_PVG_PCI
bool
depends on MAC_PVG && PCI
default y if PCI_DEVICES
+285
View File
@@ -0,0 +1,285 @@
/*
* QEMU Apple ParavirtualizedGraphics.framework device, MMIO (arm64) variant
*
* Copyright © 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: GPL-2.0-or-later
*
* ParavirtualizedGraphics.framework is a set of libraries that macOS provides
* which implements 3d graphics passthrough to the host as well as a
* proprietary guest communication channel to drive it. This device model
* implements support to drive that library from within QEMU as an MMIO-based
* system device for macOS on arm64 VMs.
*/
#include "qemu/osdep.h"
#include "qemu/log.h"
#include "qemu/aio-wait.h"
#include "hw/core/sysbus.h"
#include "hw/core/irq.h"
#include "apple-gfx.h"
#include "trace.h"
#import <ParavirtualizedGraphics/ParavirtualizedGraphics.h>
OBJECT_DECLARE_SIMPLE_TYPE(AppleGFXMMIOState, APPLE_GFX_MMIO)
/*
* ParavirtualizedGraphics.Framework only ships header files for the PCI
* variant which does not include IOSFC descriptors and host devices. We add
* their definitions here so that we can also work with the ARM version.
*/
typedef bool(^IOSFCRaiseInterrupt)(uint32_t vector);
typedef bool(^IOSFCUnmapMemory)(void *, void *, void *, void *, void *, void *);
typedef bool(^IOSFCMapMemory)(uint64_t phys, uint64_t len, bool ro, void **va,
void *, void *);
@interface PGDeviceDescriptor (IOSurfaceMapper)
@property (readwrite, nonatomic) bool usingIOSurfaceMapper;
@end
@interface PGIOSurfaceHostDeviceDescriptor : NSObject
-(PGIOSurfaceHostDeviceDescriptor *)init;
@property (readwrite, nonatomic, copy, nullable) IOSFCMapMemory mapMemory;
@property (readwrite, nonatomic, copy, nullable) IOSFCUnmapMemory unmapMemory;
@property (readwrite, nonatomic, copy, nullable) IOSFCRaiseInterrupt raiseInterrupt;
@end
@interface PGIOSurfaceHostDevice : NSObject
-(instancetype)initWithDescriptor:(PGIOSurfaceHostDeviceDescriptor *)desc;
-(uint32_t)mmioReadAtOffset:(size_t)offset;
-(void)mmioWriteAtOffset:(size_t)offset value:(uint32_t)value;
@end
struct AppleGFXMapSurfaceMemoryJob;
struct AppleGFXMMIOState {
SysBusDevice parent_obj;
AppleGFXState common;
qemu_irq irq_gfx;
qemu_irq irq_iosfc;
MemoryRegion iomem_iosfc;
PGIOSurfaceHostDevice *pgiosfc;
};
typedef struct AppleGFXMMIOJob {
AppleGFXMMIOState *state;
uint64_t offset;
uint64_t value;
bool completed;
} AppleGFXMMIOJob;
static void iosfc_do_read(void *opaque)
{
AppleGFXMMIOJob *job = opaque;
job->value = [job->state->pgiosfc mmioReadAtOffset:job->offset];
qatomic_set(&job->completed, true);
aio_wait_kick();
}
static uint64_t iosfc_read(void *opaque, hwaddr offset, unsigned size)
{
AppleGFXMMIOJob job = {
.state = opaque,
.offset = offset,
.completed = false,
};
dispatch_queue_t queue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async_f(queue, &job, iosfc_do_read);
AIO_WAIT_WHILE(NULL, !qatomic_read(&job.completed));
trace_apple_gfx_mmio_iosfc_read(offset, job.value);
return job.value;
}
static void iosfc_do_write(void *opaque)
{
AppleGFXMMIOJob *job = opaque;
[job->state->pgiosfc mmioWriteAtOffset:job->offset value:job->value];
qatomic_set(&job->completed, true);
aio_wait_kick();
}
static void iosfc_write(void *opaque, hwaddr offset, uint64_t val,
unsigned size)
{
AppleGFXMMIOJob job = {
.state = opaque,
.offset = offset,
.value = val,
.completed = false,
};
dispatch_queue_t queue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async_f(queue, &job, iosfc_do_write);
AIO_WAIT_WHILE(NULL, !qatomic_read(&job.completed));
trace_apple_gfx_mmio_iosfc_write(offset, val);
}
static const MemoryRegionOps apple_iosfc_ops = {
.read = iosfc_read,
.write = iosfc_write,
.endianness = DEVICE_LITTLE_ENDIAN,
.valid = {
.min_access_size = 4,
.max_access_size = 8,
},
.impl = {
.min_access_size = 4,
.max_access_size = 8,
},
};
static void raise_irq_bh(void *opaque)
{
qemu_irq *irq = opaque;
qemu_irq_pulse(*irq);
}
static void *apple_gfx_mmio_map_surface_memory(uint64_t guest_physical_address,
uint64_t length, bool read_only)
{
void *mem;
MemoryRegion *region = NULL;
RCU_READ_LOCK_GUARD();
mem = apple_gfx_host_ptr_for_gpa_range(guest_physical_address,
length, read_only, &region);
if (mem) {
memory_region_ref(region);
}
return mem;
}
static bool apple_gfx_mmio_unmap_surface_memory(void *ptr)
{
MemoryRegion *region;
ram_addr_t offset = 0;
RCU_READ_LOCK_GUARD();
region = memory_region_from_host(ptr, &offset);
if (!region) {
qemu_log_mask(LOG_GUEST_ERROR,
"%s: memory at %p to be unmapped not found.\n",
__func__, ptr);
return false;
}
trace_apple_gfx_iosfc_unmap_memory_region(ptr, region);
memory_region_unref(region);
return true;
}
static PGIOSurfaceHostDevice *apple_gfx_prepare_iosurface_host_device(
AppleGFXMMIOState *s)
{
PGIOSurfaceHostDeviceDescriptor *iosfc_desc =
[PGIOSurfaceHostDeviceDescriptor new];
PGIOSurfaceHostDevice *iosfc_host_dev;
iosfc_desc.mapMemory =
^bool(uint64_t phys, uint64_t len, bool ro, void **va, void *e, void *f) {
*va = apple_gfx_mmio_map_surface_memory(phys, len, ro);
trace_apple_gfx_iosfc_map_memory(phys, len, ro, va, e, f, *va);
return *va != NULL;
};
iosfc_desc.unmapMemory =
^bool(void *va, void *b, void *c, void *d, void *e, void *f) {
return apple_gfx_mmio_unmap_surface_memory(va);
};
iosfc_desc.raiseInterrupt = ^bool(uint32_t vector) {
trace_apple_gfx_iosfc_raise_irq(vector);
aio_bh_schedule_oneshot(qemu_get_aio_context(),
raise_irq_bh, &s->irq_iosfc);
return true;
};
iosfc_host_dev =
[[PGIOSurfaceHostDevice alloc] initWithDescriptor:iosfc_desc];
[iosfc_desc release];
return iosfc_host_dev;
}
static void apple_gfx_mmio_realize(DeviceState *dev, Error **errp)
{
@autoreleasepool {
AppleGFXMMIOState *s = APPLE_GFX_MMIO(dev);
PGDeviceDescriptor *desc = [PGDeviceDescriptor new];
desc.raiseInterrupt = ^(uint32_t vector) {
trace_apple_gfx_raise_irq(vector);
aio_bh_schedule_oneshot(qemu_get_aio_context(),
raise_irq_bh, &s->irq_gfx);
};
desc.usingIOSurfaceMapper = true;
s->pgiosfc = apple_gfx_prepare_iosurface_host_device(s);
if (!apple_gfx_common_realize(&s->common, dev, desc, errp)) {
[s->pgiosfc release];
s->pgiosfc = nil;
}
[desc release];
desc = nil;
}
}
static void apple_gfx_mmio_init(Object *obj)
{
AppleGFXMMIOState *s = APPLE_GFX_MMIO(obj);
apple_gfx_common_init(obj, &s->common, TYPE_APPLE_GFX_MMIO);
sysbus_init_mmio(SYS_BUS_DEVICE(s), &s->common.iomem_gfx);
memory_region_init_io(&s->iomem_iosfc, obj, &apple_iosfc_ops, s,
TYPE_APPLE_GFX_MMIO, 0x10000);
sysbus_init_mmio(SYS_BUS_DEVICE(s), &s->iomem_iosfc);
sysbus_init_irq(SYS_BUS_DEVICE(s), &s->irq_gfx);
sysbus_init_irq(SYS_BUS_DEVICE(s), &s->irq_iosfc);
}
static void apple_gfx_mmio_reset(Object *obj, ResetType type)
{
AppleGFXMMIOState *s = APPLE_GFX_MMIO(obj);
[s->common.pgdev reset];
}
static const Property apple_gfx_mmio_properties[] = {
DEFINE_PROP_ARRAY("display-modes", AppleGFXMMIOState,
common.num_display_modes, common.display_modes,
qdev_prop_apple_gfx_display_mode, AppleGFXDisplayMode),
};
static void apple_gfx_mmio_class_init(ObjectClass *klass, const void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
ResettableClass *rc = RESETTABLE_CLASS(klass);
rc->phases.hold = apple_gfx_mmio_reset;
dc->hotpluggable = false;
dc->realize = apple_gfx_mmio_realize;
device_class_set_props(dc, apple_gfx_mmio_properties);
}
static const TypeInfo apple_gfx_mmio_types[] = {
{
.name = TYPE_APPLE_GFX_MMIO,
.parent = TYPE_SYS_BUS_DEVICE,
.instance_size = sizeof(AppleGFXMMIOState),
.class_init = apple_gfx_mmio_class_init,
.instance_init = apple_gfx_mmio_init,
}
};
DEFINE_TYPES(apple_gfx_mmio_types)
+157
View File
@@ -0,0 +1,157 @@
/*
* QEMU Apple ParavirtualizedGraphics.framework device, PCI variant
*
* Copyright © 2023-2024 Phil Dennis-Jordan
*
* SPDX-License-Identifier: GPL-2.0-or-later
*
* ParavirtualizedGraphics.framework is a set of libraries that macOS provides
* which implements 3d graphics passthrough to the host as well as a
* proprietary guest communication channel to drive it. This device model
* implements support to drive that library from within QEMU as a PCI device
* aimed primarily at x86-64 macOS VMs.
*/
#include "qemu/osdep.h"
#include "hw/pci/pci_device.h"
#include "hw/pci/msi.h"
#include "apple-gfx.h"
#include "trace.h"
#import <ParavirtualizedGraphics/ParavirtualizedGraphics.h>
OBJECT_DECLARE_SIMPLE_TYPE(AppleGFXPCIState, APPLE_GFX_PCI)
struct AppleGFXPCIState {
PCIDevice parent_obj;
AppleGFXState common;
};
static const char *apple_gfx_pci_option_rom_path = NULL;
static void apple_gfx_init_option_rom_path(void)
{
NSURL *option_rom_url = PGCopyOptionROMURL();
const char *option_rom_path = option_rom_url.fileSystemRepresentation;
apple_gfx_pci_option_rom_path = g_strdup(option_rom_path);
[option_rom_url release];
}
static void apple_gfx_pci_init(Object *obj)
{
AppleGFXPCIState *s = APPLE_GFX_PCI(obj);
if (!apple_gfx_pci_option_rom_path) {
/*
* The following is done on device not class init to avoid running
* ObjC code before fork() in -daemonize mode.
*/
PCIDeviceClass *pci = PCI_DEVICE_CLASS(object_get_class(obj));
apple_gfx_init_option_rom_path();
pci->romfile = apple_gfx_pci_option_rom_path;
}
apple_gfx_common_init(obj, &s->common, TYPE_APPLE_GFX_PCI);
}
typedef struct AppleGFXPCIInterruptJob {
PCIDevice *device;
uint32_t vector;
} AppleGFXPCIInterruptJob;
static void apple_gfx_pci_raise_interrupt(void *opaque)
{
AppleGFXPCIInterruptJob *job = opaque;
if (msi_enabled(job->device)) {
msi_notify(job->device, job->vector);
}
g_free(job);
}
static void apple_gfx_pci_interrupt(PCIDevice *dev, uint32_t vector)
{
AppleGFXPCIInterruptJob *job;
trace_apple_gfx_raise_irq(vector);
job = g_malloc0(sizeof(*job));
job->device = dev;
job->vector = vector;
aio_bh_schedule_oneshot(qemu_get_aio_context(),
apple_gfx_pci_raise_interrupt, job);
}
static void apple_gfx_pci_realize(PCIDevice *dev, Error **errp)
{
AppleGFXPCIState *s = APPLE_GFX_PCI(dev);
int ret;
pci_register_bar(dev, PG_PCI_BAR_MMIO,
PCI_BASE_ADDRESS_SPACE_MEMORY, &s->common.iomem_gfx);
ret = msi_init(dev, 0x0 /* config offset; 0 = find space */,
PG_PCI_MAX_MSI_VECTORS, true /* msi64bit */,
false /* msi_per_vector_mask */, errp);
if (ret != 0) {
return;
}
@autoreleasepool {
PGDeviceDescriptor *desc = [PGDeviceDescriptor new];
desc.raiseInterrupt = ^(uint32_t vector) {
apple_gfx_pci_interrupt(dev, vector);
};
apple_gfx_common_realize(&s->common, DEVICE(dev), desc, errp);
[desc release];
desc = nil;
}
}
static void apple_gfx_pci_reset(Object *obj, ResetType type)
{
AppleGFXPCIState *s = APPLE_GFX_PCI(obj);
[s->common.pgdev reset];
}
static const Property apple_gfx_pci_properties[] = {
DEFINE_PROP_ARRAY("display-modes", AppleGFXPCIState,
common.num_display_modes, common.display_modes,
qdev_prop_apple_gfx_display_mode, AppleGFXDisplayMode),
};
static void apple_gfx_pci_class_init(ObjectClass *klass, const void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
PCIDeviceClass *pci = PCI_DEVICE_CLASS(klass);
ResettableClass *rc = RESETTABLE_CLASS(klass);
rc->phases.hold = apple_gfx_pci_reset;
dc->desc = "macOS Paravirtualized Graphics PCI Display Controller";
dc->hotpluggable = false;
set_bit(DEVICE_CATEGORY_DISPLAY, dc->categories);
pci->vendor_id = PG_PCI_VENDOR_ID;
pci->device_id = PG_PCI_DEVICE_ID;
pci->class_id = PCI_CLASS_DISPLAY_OTHER;
pci->realize = apple_gfx_pci_realize;
device_class_set_props(dc, apple_gfx_pci_properties);
}
static const TypeInfo apple_gfx_pci_types[] = {
{
.name = TYPE_APPLE_GFX_PCI,
.parent = TYPE_PCI_DEVICE,
.instance_size = sizeof(AppleGFXPCIState),
.class_init = apple_gfx_pci_class_init,
.instance_init = apple_gfx_pci_init,
.interfaces = (const InterfaceInfo[]) {
{ INTERFACE_PCIE_DEVICE },
{ },
},
}
};
DEFINE_TYPES(apple_gfx_pci_types)
+74
View File
@@ -0,0 +1,74 @@
/*
* Data structures and functions shared between variants of the macOS
* ParavirtualizedGraphics.framework based apple-gfx display adapter.
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef QEMU_APPLE_GFX_H
#define QEMU_APPLE_GFX_H
#include "qemu/queue.h"
#include "system/memory.h"
#include "hw/core/qdev-properties.h"
#include "ui/surface.h"
#define TYPE_APPLE_GFX_MMIO "apple-gfx-mmio"
#define TYPE_APPLE_GFX_PCI "apple-gfx-pci"
@class PGDeviceDescriptor;
@protocol PGDevice;
@protocol PGDisplay;
@protocol MTLDevice;
@protocol MTLTexture;
@protocol MTLCommandQueue;
typedef QTAILQ_HEAD(, PGTask_s) PGTaskList;
typedef struct AppleGFXDisplayMode {
uint16_t width_px;
uint16_t height_px;
uint16_t refresh_rate_hz;
} AppleGFXDisplayMode;
typedef struct AppleGFXState {
/* Initialised on init/realize() */
MemoryRegion iomem_gfx;
id<PGDevice> pgdev;
id<PGDisplay> pgdisp;
QemuConsole *con;
id<MTLDevice> mtl;
id<MTLCommandQueue> mtl_queue;
AppleGFXDisplayMode *display_modes;
uint32_t num_display_modes;
/* List `tasks` is protected by task_mutex */
QemuMutex task_mutex;
PGTaskList tasks;
/* Mutable state (BQL protected) */
QEMUCursor *cursor;
DisplaySurface *surface;
id<MTLTexture> texture;
int8_t pending_frames; /* # guest frames in the rendering pipeline */
bool gfx_update_requested; /* QEMU display system wants a new frame */
bool new_frame_ready; /* Guest has rendered a frame, ready to be used */
bool using_managed_texture_storage;
uint32_t rendering_frame_width;
uint32_t rendering_frame_height;
/* Mutable state (atomic) */
bool cursor_show;
} AppleGFXState;
void apple_gfx_common_init(Object *obj, AppleGFXState *s, const char* obj_name);
bool apple_gfx_common_realize(AppleGFXState *s, DeviceState *dev,
PGDeviceDescriptor *desc, Error **errp);
void *apple_gfx_host_ptr_for_gpa_range(uint64_t guest_physical,
uint64_t length, bool read_only,
MemoryRegion **mapping_in_region);
extern const PropertyInfo qdev_prop_apple_gfx_display_mode;
#endif
+882
View File
@@ -0,0 +1,882 @@
/*
* QEMU Apple ParavirtualizedGraphics.framework device
*
* Copyright © 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: GPL-2.0-or-later
*
* ParavirtualizedGraphics.framework is a set of libraries that macOS provides
* which implements 3d graphics passthrough to the host as well as a
* proprietary guest communication channel to drive it. This device model
* implements support to drive that library from within QEMU.
*/
#include "qemu/osdep.h"
#include "qemu/lockable.h"
#include "qemu/cutils.h"
#include "qemu/log.h"
#include "qapi/qapi-builtin-type-infos.h"
#include "qapi/visitor.h"
#include "qapi/error.h"
#include "qemu/aio-wait.h"
#include "system/address-spaces.h"
#include "system/dma.h"
#include "migration/blocker.h"
#include "ui/console.h"
#include "apple-gfx.h"
#include "trace.h"
#include <mach/mach.h>
#include <mach/mach_vm.h>
#include <dispatch/dispatch.h>
#import <ParavirtualizedGraphics/ParavirtualizedGraphics.h>
static const AppleGFXDisplayMode apple_gfx_default_modes[] = {
{ 1920, 1080, 60 },
{ 1440, 1080, 60 },
{ 1280, 1024, 60 },
};
static Error *apple_gfx_mig_blocker;
static uint32_t next_pgdisplay_serial_num = 1;
static dispatch_queue_t get_background_queue(void)
{
return dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
}
/* ------ PGTask and task operations: new/destroy/map/unmap ------ */
/*
* This implements the type declared in <ParavirtualizedGraphics/PGDevice.h>
* which is opaque from the framework's point of view. It is used in callbacks
* in the form of its typedef PGTask_t, which also already exists in the
* framework headers.
*
* A "task" in PVG terminology represents a host-virtual contiguous address
* range which is reserved in a large chunk on task creation. The mapMemory
* callback then requests ranges of guest system memory (identified by their
* GPA) to be mapped into subranges of this reserved address space.
* This type of operation isn't well-supported by QEMU's memory subsystem,
* but it is fortunately trivial to achieve with Darwin's mach_vm_remap() call,
* which allows us to refer to the same backing memory via multiple virtual
* address ranges. The Mach VM APIs are therefore used throughout for managing
* task memory.
*/
struct PGTask_s {
QTAILQ_ENTRY(PGTask_s) node;
AppleGFXState *s;
mach_vm_address_t address;
uint64_t len;
/*
* All unique MemoryRegions for which a mapping has been created in this
* task, and on which we have thus called memory_region_ref(). There are
* usually very few regions of system RAM in total, so we expect this array
* to be very short. Therefore, no need for sorting or fancy search
* algorithms, linear search will do.
* Protected by AppleGFXState's task_mutex.
*/
GPtrArray *mapped_regions;
};
static PGTask_t *apple_gfx_new_task(AppleGFXState *s, uint64_t len)
{
mach_vm_address_t task_mem;
PGTask_t *task;
kern_return_t r;
r = mach_vm_allocate(mach_task_self(), &task_mem, len, VM_FLAGS_ANYWHERE);
if (r != KERN_SUCCESS) {
return NULL;
}
task = g_new0(PGTask_t, 1);
task->s = s;
task->address = task_mem;
task->len = len;
task->mapped_regions = g_ptr_array_sized_new(2 /* Usually enough */);
QEMU_LOCK_GUARD(&s->task_mutex);
QTAILQ_INSERT_TAIL(&s->tasks, task, node);
return task;
}
static void apple_gfx_destroy_task(AppleGFXState *s, PGTask_t *task)
{
GPtrArray *regions = task->mapped_regions;
MemoryRegion *region;
size_t i;
for (i = 0; i < regions->len; ++i) {
region = g_ptr_array_index(regions, i);
memory_region_unref(region);
}
g_ptr_array_unref(regions);
mach_vm_deallocate(mach_task_self(), task->address, task->len);
QEMU_LOCK_GUARD(&s->task_mutex);
QTAILQ_REMOVE(&s->tasks, task, node);
g_free(task);
}
void *apple_gfx_host_ptr_for_gpa_range(uint64_t guest_physical,
uint64_t length, bool read_only,
MemoryRegion **mapping_in_region)
{
MemoryRegion *ram_region;
char *host_ptr;
hwaddr ram_region_offset = 0;
hwaddr ram_region_length = length;
ram_region = address_space_translate(&address_space_memory,
guest_physical,
&ram_region_offset,
&ram_region_length, !read_only,
MEMTXATTRS_UNSPECIFIED);
if (!ram_region || ram_region_length < length ||
!memory_access_is_direct(ram_region, !read_only,
MEMTXATTRS_UNSPECIFIED)) {
return NULL;
}
host_ptr = memory_region_get_ram_ptr(ram_region);
if (!host_ptr) {
return NULL;
}
host_ptr += ram_region_offset;
*mapping_in_region = ram_region;
return host_ptr;
}
static bool apple_gfx_task_map_memory(AppleGFXState *s, PGTask_t *task,
uint64_t virtual_offset,
PGPhysicalMemoryRange_t *ranges,
uint32_t range_count, bool read_only)
{
kern_return_t r;
void *source_ptr;
mach_vm_address_t target;
vm_prot_t cur_protection, max_protection;
bool success = true;
MemoryRegion *region;
RCU_READ_LOCK_GUARD();
QEMU_LOCK_GUARD(&s->task_mutex);
trace_apple_gfx_map_memory(task, range_count, virtual_offset, read_only);
for (int i = 0; i < range_count; i++) {
PGPhysicalMemoryRange_t *range = &ranges[i];
target = task->address + virtual_offset;
virtual_offset += range->physicalLength;
trace_apple_gfx_map_memory_range(i, range->physicalAddress,
range->physicalLength);
region = NULL;
source_ptr = apple_gfx_host_ptr_for_gpa_range(range->physicalAddress,
range->physicalLength,
read_only, &region);
if (!source_ptr) {
success = false;
continue;
}
if (!g_ptr_array_find(task->mapped_regions, region, NULL)) {
g_ptr_array_add(task->mapped_regions, region);
memory_region_ref(region);
}
cur_protection = 0;
max_protection = 0;
/* Map guest RAM at range->physicalAddress into PG task memory range */
r = mach_vm_remap(mach_task_self(),
&target, range->physicalLength, vm_page_size - 1,
VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE,
mach_task_self(), (mach_vm_address_t)source_ptr,
false /* shared mapping, no copy */,
&cur_protection, &max_protection,
VM_INHERIT_COPY);
trace_apple_gfx_remap(r, source_ptr, target);
g_assert(r == KERN_SUCCESS);
}
return success;
}
static void apple_gfx_task_unmap_memory(AppleGFXState *s, PGTask_t *task,
uint64_t virtual_offset, uint64_t length)
{
kern_return_t r;
mach_vm_address_t range_address;
trace_apple_gfx_unmap_memory(task, virtual_offset, length);
/*
* Replace task memory range with fresh 0 pages, undoing the mapping
* from guest RAM.
*/
range_address = task->address + virtual_offset;
r = mach_vm_allocate(mach_task_self(), &range_address, length,
VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE);
g_assert(r == KERN_SUCCESS);
}
/* ------ Rendering and frame management ------ */
static void apple_gfx_render_frame_completed_bh(void *opaque);
static void apple_gfx_render_new_frame(AppleGFXState *s)
{
bool managed_texture = s->using_managed_texture_storage;
uint32_t width = surface_width(s->surface);
uint32_t height = surface_height(s->surface);
MTLRegion region = MTLRegionMake2D(0, 0, width, height);
id<MTLCommandBuffer> command_buffer = [s->mtl_queue commandBuffer];
id<MTLTexture> texture = s->texture;
assert(bql_locked());
[texture retain];
[command_buffer retain];
s->rendering_frame_width = width;
s->rendering_frame_height = height;
dispatch_async(get_background_queue(), ^{
/*
* This is not safe to call from the BQL/BH due to PVG-internal locks
* causing deadlocks.
*/
bool r = [s->pgdisp encodeCurrentFrameToCommandBuffer:command_buffer
texture:texture
region:region];
if (!r) {
[texture release];
[command_buffer release];
qemu_log_mask(LOG_GUEST_ERROR,
"%s: encodeCurrentFrameToCommandBuffer:texture:region: "
"failed\n", __func__);
bql_lock();
--s->pending_frames;
if (s->pending_frames > 0) {
apple_gfx_render_new_frame(s);
}
bql_unlock();
return;
}
if (managed_texture) {
/* "Managed" textures exist in both VRAM and RAM and must be synced. */
id<MTLBlitCommandEncoder> blit = [command_buffer blitCommandEncoder];
[blit synchronizeResource:texture];
[blit endEncoding];
}
[texture release];
[command_buffer addCompletedHandler:
^(id<MTLCommandBuffer> cb)
{
aio_bh_schedule_oneshot(qemu_get_aio_context(),
apple_gfx_render_frame_completed_bh, s);
}];
[command_buffer commit];
[command_buffer release];
});
}
static void copy_mtl_texture_to_surface_mem(id<MTLTexture> texture, void *vram)
{
/*
* TODO: Skip this entirely on a pure Metal or headless/guest-only
* rendering path, else use a blit command encoder? Needs careful
* (double?) buffering design.
*/
size_t width = texture.width, height = texture.height;
MTLRegion region = MTLRegionMake2D(0, 0, width, height);
[texture getBytes:vram
bytesPerRow:(width * 4)
bytesPerImage:(width * height * 4)
fromRegion:region
mipmapLevel:0
slice:0];
}
static void apple_gfx_render_frame_completed_bh(void *opaque)
{
AppleGFXState *s = opaque;
@autoreleasepool {
--s->pending_frames;
assert(s->pending_frames >= 0);
/* Only update display if mode hasn't changed since we started rendering. */
if (s->rendering_frame_width == surface_width(s->surface) &&
s->rendering_frame_height == surface_height(s->surface)) {
copy_mtl_texture_to_surface_mem(s->texture, surface_data(s->surface));
if (s->gfx_update_requested) {
s->gfx_update_requested = false;
qemu_console_update_full(s->con);
qemu_console_hw_update_done(s->con);
s->new_frame_ready = false;
} else {
s->new_frame_ready = true;
}
}
if (s->pending_frames > 0) {
apple_gfx_render_new_frame(s);
}
}
}
static bool apple_gfx_fb_update_display(void *opaque)
{
AppleGFXState *s = opaque;
bool done = true;
assert(bql_locked());
if (s->new_frame_ready) {
qemu_console_update_full(s->con);
s->new_frame_ready = false;
} else if (s->pending_frames > 0) {
s->gfx_update_requested = true;
done = false;
}
return done;
}
static const GraphicHwOps apple_gfx_fb_ops = {
.gfx_update = apple_gfx_fb_update_display,
};
/* ------ Mouse cursor and display mode setting ------ */
static void set_mode(AppleGFXState *s, uint32_t width, uint32_t height)
{
MTLTextureDescriptor *textureDescriptor;
if (s->surface &&
width == surface_width(s->surface) &&
height == surface_height(s->surface)) {
return;
}
[s->texture release];
s->surface = qemu_create_displaysurface(width, height);
@autoreleasepool {
textureDescriptor =
[MTLTextureDescriptor
texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
width:width
height:height
mipmapped:NO];
textureDescriptor.usage = s->pgdisp.minimumTextureUsage;
s->texture = [s->mtl newTextureWithDescriptor:textureDescriptor];
s->using_managed_texture_storage =
(s->texture.storageMode == MTLStorageModeManaged);
}
qemu_console_set_surface(s->con, s->surface);
}
static void update_cursor(AppleGFXState *s)
{
assert(bql_locked());
qemu_console_set_mouse(s->con, s->pgdisp.cursorPosition.x,
s->pgdisp.cursorPosition.y, qatomic_read(&s->cursor_show));
}
static void update_cursor_bh(void *opaque)
{
AppleGFXState *s = opaque;
update_cursor(s);
}
typedef struct AppleGFXSetCursorGlyphJob {
AppleGFXState *s;
NSBitmapImageRep *glyph;
PGDisplayCoord_t hotspot;
} AppleGFXSetCursorGlyphJob;
static void set_cursor_glyph(void *opaque)
{
AppleGFXSetCursorGlyphJob *job = opaque;
AppleGFXState *s = job->s;
NSBitmapImageRep *glyph = job->glyph;
uint32_t bpp = glyph.bitsPerPixel;
size_t width = glyph.pixelsWide;
size_t height = glyph.pixelsHigh;
size_t padding_bytes_per_row = glyph.bytesPerRow - width * 4;
const uint8_t* px_data = glyph.bitmapData;
trace_apple_gfx_cursor_set(bpp, width, height);
if (s->cursor) {
cursor_unref(s->cursor);
s->cursor = NULL;
}
if (bpp == 32) { /* Shouldn't be anything else, but just to be safe... */
s->cursor = cursor_alloc(width, height);
s->cursor->hot_x = job->hotspot.x;
s->cursor->hot_y = job->hotspot.y;
uint32_t *dest_px = s->cursor->data;
for (size_t y = 0; y < height; ++y) {
for (size_t x = 0; x < width; ++x) {
/*
* NSBitmapImageRep's red & blue channels are swapped
* compared to QEMUCursor's.
*/
*dest_px =
(px_data[0] << 16u) |
(px_data[1] << 8u) |
(px_data[2] << 0u) |
(px_data[3] << 24u);
++dest_px;
px_data += 4;
}
px_data += padding_bytes_per_row;
}
qemu_console_set_cursor(s->con, s->cursor);
update_cursor(s);
}
[glyph release];
g_free(job);
}
/* ------ DMA (device reading system memory) ------ */
typedef struct AppleGFXReadMemoryJob {
QemuEvent event;
hwaddr physical_address;
uint64_t length;
void *dst;
bool success;
} AppleGFXReadMemoryJob;
static void apple_gfx_do_read_memory(void *opaque)
{
AppleGFXReadMemoryJob *job = opaque;
MemTxResult r;
r = dma_memory_read(&address_space_memory, job->physical_address,
job->dst, job->length, MEMTXATTRS_UNSPECIFIED);
job->success = (r == MEMTX_OK);
qemu_event_set(&job->event);
}
static bool apple_gfx_read_memory(AppleGFXState *s, hwaddr physical_address,
uint64_t length, void *dst)
{
AppleGFXReadMemoryJob job = {
.physical_address = physical_address, .length = length, .dst = dst
};
trace_apple_gfx_read_memory(physical_address, length, dst);
/* Performing DMA requires BQL, so do it in a BH. */
qemu_event_init(&job.event, 0);
aio_bh_schedule_oneshot(qemu_get_aio_context(),
apple_gfx_do_read_memory, &job);
qemu_event_wait(&job.event);
qemu_event_destroy(&job.event);
return job.success;
}
/* ------ Memory-mapped device I/O operations ------ */
typedef struct AppleGFXIOJob {
AppleGFXState *state;
uint64_t offset;
uint64_t value;
bool completed;
} AppleGFXIOJob;
static void apple_gfx_do_read(void *opaque)
{
AppleGFXIOJob *job = opaque;
job->value = [job->state->pgdev mmioReadAtOffset:job->offset];
qatomic_set(&job->completed, true);
aio_wait_kick();
}
static uint64_t apple_gfx_read(void *opaque, hwaddr offset, unsigned size)
{
AppleGFXIOJob job = {
.state = opaque,
.offset = offset,
.completed = false,
};
dispatch_queue_t queue = get_background_queue();
dispatch_async_f(queue, &job, apple_gfx_do_read);
AIO_WAIT_WHILE(NULL, !qatomic_read(&job.completed));
trace_apple_gfx_read(offset, job.value);
return job.value;
}
static void apple_gfx_do_write(void *opaque)
{
AppleGFXIOJob *job = opaque;
[job->state->pgdev mmioWriteAtOffset:job->offset value:job->value];
qatomic_set(&job->completed, true);
aio_wait_kick();
}
static void apple_gfx_write(void *opaque, hwaddr offset, uint64_t val,
unsigned size)
{
/*
* The methods mmioReadAtOffset: and especially mmioWriteAtOffset: can
* trigger synchronous operations on other dispatch queues, which in turn
* may call back out on one or more of the callback blocks. For this reason,
* and as we are holding the BQL, we invoke the I/O methods on a pool
* thread and handle AIO tasks while we wait. Any work in the callbacks
* requiring the BQL will in turn schedule BHs which this thread will
* process while waiting.
*/
AppleGFXIOJob job = {
.state = opaque,
.offset = offset,
.value = val,
.completed = false,
};
dispatch_queue_t queue = get_background_queue();
dispatch_async_f(queue, &job, apple_gfx_do_write);
AIO_WAIT_WHILE(NULL, !qatomic_read(&job.completed));
trace_apple_gfx_write(offset, val);
}
static const MemoryRegionOps apple_gfx_ops = {
.read = apple_gfx_read,
.write = apple_gfx_write,
.endianness = DEVICE_LITTLE_ENDIAN,
.valid = {
.min_access_size = 4,
.max_access_size = 8,
},
.impl = {
.min_access_size = 4,
.max_access_size = 4,
},
};
static size_t apple_gfx_get_default_mmio_range_size(void)
{
size_t mmio_range_size;
@autoreleasepool {
PGDeviceDescriptor *desc = [PGDeviceDescriptor new];
mmio_range_size = desc.mmioLength;
[desc release];
}
return mmio_range_size;
}
/* ------ Initialisation and startup ------ */
void apple_gfx_common_init(Object *obj, AppleGFXState *s, const char* obj_name)
{
size_t mmio_range_size = apple_gfx_get_default_mmio_range_size();
trace_apple_gfx_common_init(obj_name, mmio_range_size);
memory_region_init_io(&s->iomem_gfx, obj, &apple_gfx_ops, s, obj_name,
mmio_range_size);
/* TODO: PVG framework supports serialising device state: integrate it! */
}
static void apple_gfx_register_task_mapping_handlers(AppleGFXState *s,
PGDeviceDescriptor *desc)
{
desc.createTask = ^(uint64_t vmSize, void * _Nullable * _Nonnull baseAddress) {
PGTask_t *task = apple_gfx_new_task(s, vmSize);
*baseAddress = (void *)task->address;
trace_apple_gfx_create_task(vmSize, *baseAddress);
return task;
};
desc.destroyTask = ^(PGTask_t * _Nonnull task) {
trace_apple_gfx_destroy_task(task, task->mapped_regions->len);
apple_gfx_destroy_task(s, task);
};
desc.mapMemory = ^bool(PGTask_t * _Nonnull task, uint32_t range_count,
uint64_t virtual_offset, bool read_only,
PGPhysicalMemoryRange_t * _Nonnull ranges) {
return apple_gfx_task_map_memory(s, task, virtual_offset,
ranges, range_count, read_only);
};
desc.unmapMemory = ^bool(PGTask_t * _Nonnull task, uint64_t virtual_offset,
uint64_t length) {
apple_gfx_task_unmap_memory(s, task, virtual_offset, length);
return true;
};
desc.readMemory = ^bool(uint64_t physical_address, uint64_t length,
void * _Nonnull dst) {
return apple_gfx_read_memory(s, physical_address, length, dst);
};
}
static void new_frame_handler_bh(void *opaque)
{
AppleGFXState *s = opaque;
/* Drop frames if guest gets too far ahead. */
if (s->pending_frames >= 2) {
return;
}
++s->pending_frames;
if (s->pending_frames > 1) {
return;
}
@autoreleasepool {
apple_gfx_render_new_frame(s);
}
}
static PGDisplayDescriptor *apple_gfx_prepare_display_descriptor(AppleGFXState *s)
{
PGDisplayDescriptor *disp_desc = [PGDisplayDescriptor new];
disp_desc.name = @"QEMU display";
disp_desc.sizeInMillimeters = NSMakeSize(400., 300.); /* A 20" display */
disp_desc.queue = dispatch_get_main_queue();
disp_desc.newFrameEventHandler = ^(void) {
trace_apple_gfx_new_frame();
aio_bh_schedule_oneshot(qemu_get_aio_context(), new_frame_handler_bh, s);
};
disp_desc.modeChangeHandler = ^(PGDisplayCoord_t sizeInPixels,
OSType pixelFormat) {
trace_apple_gfx_mode_change(sizeInPixels.x, sizeInPixels.y);
BQL_LOCK_GUARD();
set_mode(s, sizeInPixels.x, sizeInPixels.y);
};
disp_desc.cursorGlyphHandler = ^(NSBitmapImageRep *glyph,
PGDisplayCoord_t hotspot) {
AppleGFXSetCursorGlyphJob *job = g_malloc0(sizeof(*job));
job->s = s;
job->glyph = glyph;
job->hotspot = hotspot;
[glyph retain];
aio_bh_schedule_oneshot(qemu_get_aio_context(),
set_cursor_glyph, job);
};
disp_desc.cursorShowHandler = ^(BOOL show) {
trace_apple_gfx_cursor_show(show);
qatomic_set(&s->cursor_show, show);
aio_bh_schedule_oneshot(qemu_get_aio_context(),
update_cursor_bh, s);
};
disp_desc.cursorMoveHandler = ^(void) {
trace_apple_gfx_cursor_move();
aio_bh_schedule_oneshot(qemu_get_aio_context(),
update_cursor_bh, s);
};
return disp_desc;
}
static NSArray<PGDisplayMode *> *apple_gfx_create_display_mode_array(
const AppleGFXDisplayMode display_modes[], uint32_t display_mode_count)
{
PGDisplayMode *mode_obj;
NSMutableArray<PGDisplayMode *> *mode_array =
[[NSMutableArray alloc] initWithCapacity:display_mode_count];
for (unsigned i = 0; i < display_mode_count; i++) {
const AppleGFXDisplayMode *mode = &display_modes[i];
trace_apple_gfx_display_mode(i, mode->width_px, mode->height_px);
PGDisplayCoord_t mode_size = { mode->width_px, mode->height_px };
mode_obj =
[[PGDisplayMode alloc] initWithSizeInPixels:mode_size
refreshRateInHz:mode->refresh_rate_hz];
[mode_array addObject:mode_obj];
[mode_obj release];
}
return mode_array;
}
static id<MTLDevice> copy_suitable_metal_device(void)
{
id<MTLDevice> dev = nil;
NSArray<id<MTLDevice>> *devs = MTLCopyAllDevices();
/* Prefer a unified memory GPU. Failing that, pick a non-removable GPU. */
for (size_t i = 0; i < devs.count; ++i) {
if (devs[i].hasUnifiedMemory) {
dev = devs[i];
break;
}
if (!devs[i].removable) {
dev = devs[i];
}
}
if (dev != nil) {
[dev retain];
} else {
dev = MTLCreateSystemDefaultDevice();
}
[devs release];
return dev;
}
bool apple_gfx_common_realize(AppleGFXState *s, DeviceState *dev,
PGDeviceDescriptor *desc, Error **errp)
{
PGDisplayDescriptor *disp_desc;
const AppleGFXDisplayMode *display_modes = apple_gfx_default_modes;
uint32_t num_display_modes = ARRAY_SIZE(apple_gfx_default_modes);
NSArray<PGDisplayMode *> *mode_array;
if (apple_gfx_mig_blocker == NULL) {
error_setg(&apple_gfx_mig_blocker,
"Migration state blocked by apple-gfx display device");
if (migrate_add_blocker(&apple_gfx_mig_blocker, errp) < 0) {
return false;
}
}
qemu_mutex_init(&s->task_mutex);
QTAILQ_INIT(&s->tasks);
s->mtl = copy_suitable_metal_device();
s->mtl_queue = [s->mtl newCommandQueue];
desc.device = s->mtl;
apple_gfx_register_task_mapping_handlers(s, desc);
s->cursor_show = true;
s->pgdev = PGNewDeviceWithDescriptor(desc);
disp_desc = apple_gfx_prepare_display_descriptor(s);
/*
* Although the framework does, this integration currently does not support
* multiple virtual displays connected to a single PV graphics device.
* It is however possible to create
* more than one instance of the device, each with one display. The macOS
* guest will ignore these displays if they share the same serial number,
* so ensure each instance gets a unique one.
*/
s->pgdisp = [s->pgdev newDisplayWithDescriptor:disp_desc
port:0
serialNum:next_pgdisplay_serial_num++];
[disp_desc release];
if (s->display_modes != NULL && s->num_display_modes > 0) {
trace_apple_gfx_common_realize_modes_property(s->num_display_modes);
display_modes = s->display_modes;
num_display_modes = s->num_display_modes;
}
s->pgdisp.modeList = mode_array =
apple_gfx_create_display_mode_array(display_modes, num_display_modes);
[mode_array release];
s->con = qemu_graphic_console_create(dev, 0, &apple_gfx_fb_ops, s);
return true;
}
/* ------ Display mode list device property ------ */
static void apple_gfx_get_display_mode(Object *obj, Visitor *v,
const char *name, void *opaque,
Error **errp)
{
Property *prop = opaque;
AppleGFXDisplayMode *mode = object_field_prop_ptr(obj, prop);
/* 3 uint16s (max 5 digits) + 2 separator characters + nul. */
char buffer[5 * 3 + 2 + 1];
char *pos = buffer;
int rc = snprintf(buffer, sizeof(buffer),
"%"PRIu16"x%"PRIu16"@%"PRIu16,
mode->width_px, mode->height_px,
mode->refresh_rate_hz);
assert(rc < sizeof(buffer));
visit_type_str(v, name, &pos, errp);
}
static void apple_gfx_set_display_mode(Object *obj, Visitor *v,
const char *name, void *opaque,
Error **errp)
{
Property *prop = opaque;
AppleGFXDisplayMode *mode = object_field_prop_ptr(obj, prop);
const char *endptr;
g_autofree char *str = NULL;
int ret;
int val;
if (!visit_type_str(v, name, &str, errp)) {
return;
}
endptr = str;
ret = qemu_strtoi(endptr, &endptr, 10, &val);
if (ret || val > UINT16_MAX || val <= 0) {
error_setg(errp, "width in '%s' must be a decimal integer number"
" of pixels in the range 1..65535", name);
return;
}
mode->width_px = val;
if (*endptr != 'x') {
goto separator_error;
}
ret = qemu_strtoi(endptr + 1, &endptr, 10, &val);
if (ret || val > UINT16_MAX || val <= 0) {
error_setg(errp, "height in '%s' must be a decimal integer number"
" of pixels in the range 1..65535", name);
return;
}
mode->height_px = val;
if (*endptr != '@') {
goto separator_error;
}
ret = qemu_strtoi(endptr + 1, &endptr, 10, &val);
if (ret || val > UINT16_MAX || val <= 0) {
error_setg(errp, "refresh rate in '%s'"
" must be a positive decimal integer (Hertz)", name);
return;
}
mode->refresh_rate_hz = val;
return;
separator_error:
error_setg(errp,
"Each display mode takes the format '<width>x<height>@<rate>'");
}
const PropertyInfo qdev_prop_apple_gfx_display_mode = {
.type = "display_mode",
.qapi_type = &str_type_info,
.description =
"Display mode in pixels and Hertz, as <width>x<height>@<refresh-rate> "
"Example: 3840x2160@60",
.get = apple_gfx_get_display_mode,
.set = apple_gfx_set_display_mode,
};
+2 -14
View File
@@ -65,20 +65,8 @@ system_ss.add(when: 'CONFIG_ARTIST', if_true: files('artist.c'))
system_ss.add(when: 'CONFIG_ATI_VGA', if_true: [files('ati.c', 'ati_2d.c', 'ati_dbg.c'), pixman])
# The reims-graphics device's transport; reims-vgpu's graphics device is its
# host side.
reims_graphics_ss = ss.source_set()
reims_graphics_ss.add(files('reims-graphics-pci.c',
'reims-graphics-pci-prefault.c'))
# Its calls into KVM. system_ss builds the device once for every target, and a
# target without KVM links no KVM function, so those targets take the stub.
if host_os == 'linux'
reims_graphics_ss.add(when: 'CONFIG_KVM',
if_true: files('reims-graphics-pci-kvm.c'),
if_false: files('reims-graphics-pci-kvm-stub.c'))
endif
system_ss.add_all(when: [reims_vgpu, 'CONFIG_REIMS_GRAPHICS_PCI'],
if_true: reims_graphics_ss)
system_ss.add(when: [pvg, 'CONFIG_MAC_PVG_PCI'], if_true: [files('apple-gfx.m', 'apple-gfx-pci.m')])
system_ss.add(when: [pvg, 'CONFIG_MAC_PVG_MMIO'], if_true: [files('apple-gfx.m', 'apple-gfx-mmio.m')])
if config_all_devices.has_key('CONFIG_VIRTIO_GPU')
virtio_gpu_ss = ss.source_set()
-18
View File
@@ -1,18 +0,0 @@
/*
* QEMU reims-graphics device: its calls into KVM, for the targets without KVM
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "qemu/osdep.h"
#include "reims-graphics-pci-kvm.h"
bool reims_graphics_kvm_disable_slot_zap_all(void)
{
return true;
}
const ReimsGraphicsPrefaultOps *reims_graphics_kvm_prefault_ops(void)
{
return NULL;
}
-317
View File
@@ -1,317 +0,0 @@
/*
* QEMU reims-graphics device: its calls into KVM, for the targets with KVM
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "qemu/osdep.h"
#include <sys/ioctl.h>
#include "qapi/error.h"
#include "qemu/error-report.h"
#include "qemu/main-loop.h"
#include "qemu/notify.h"
#include "hw/core/boards.h"
#include "hw/core/cpu.h"
#include "system/kvm.h"
#include <linux/kvm.h>
#include "reims-graphics-pci-kvm.h"
#include "reims-graphics-pci-prefault.h"
#include "trace.h"
bool reims_graphics_kvm_disable_slot_zap_all(void)
{
#ifdef KVM_X86_QUIRK_SLOT_ZAP_ALL
struct kvm_enable_cap cap = {
.cap = KVM_CAP_DISABLE_QUIRKS2,
.args = { KVM_X86_QUIRK_SLOT_ZAP_ALL },
};
if (!kvm_enabled() ||
!(kvm_check_extension(kvm_state, KVM_CAP_DISABLE_QUIRKS2) &
KVM_X86_QUIRK_SLOT_ZAP_ALL)) {
return true;
}
return kvm_vm_ioctl(kvm_state, KVM_ENABLE_CAP, &cap) >= 0;
#else
return true;
#endif
}
#if defined(__x86_64__) && defined(KVM_PRE_FAULT_MEMORY)
/*
* The pool's populate on KVM: KVM_PRE_FAULT_MEMORY, a vCPU ioctl, on a vCPU
* of the populate thread's own, the helper. The guest's vCPUs are never
* used for it: each call holds its vCPU's mutex, which a guest vCPU's
* KVM_RUN holds while the guest runs.
*
* The helper is made by the populate thread (KVM_CREATE_VCPU), which issues
* every call on it, and never runs: no KVM_RUN, no state put but its CPUID,
* its TSC frequency and its TSC (below). KVM fills the VM's shared TDP
* tables, whose root a vCPU picks by its role: CPUID's MAXPHYADDR (on a
* host with 5-level paging), SMM and guest mode, and the memory type of a
* mapping takes no vCPU state (arch/x86/kvm/mmu/mmu.c:5963-6010,
* arch/x86/kvm/vmx/vmx.c:7791-7805 in Linux 7.3.3). Given vCPU 0's CPUID,
* outside SMM and guest mode, the helper fills the tables the guest's vCPUs
* use.
*
* Its id is one past every APIC id the guest has or can be given
* (MachineClass::possible_cpu_arch_ids), so no message the guest sends to
* the CPUs it is told of names it, and its APIC stays software-disabled
* with its LVTs masked, so a fixed, lowest-priority or logical message
* never takes it. KVM_CAP_MAX_VCPU_ID is one higher for it
* (target/i386/kvm/kvm.c, kvm_set_max_apic_id). Ids past 254 make none:
* AVIC without x2AVIC inhibits itself for the whole VM at such an id.
*/
#define REIMS_GRAPHICS_KVM_HELPER_MAX_ID 254
#define REIMS_GRAPHICS_KVM_CPUID_MAX 4096
#define REIMS_GRAPHICS_KVM_MSR_IA32_TSC 0x10
/*
* The time a call runs before the thread is signalled, which ends it with
* its progress (-EINTR where it made none). A call retries a page with no
* reload of its vCPU's MMU for as long as the VM's TDP root is obsolete,
* until a signal (arch/x86/kvm/mmu/mmu.c:5063-5072, 4817-4843 in Linux
* 7.3.3), holding KVM's SRCU, which every slot change then waits for under
* the BQL. Roots go obsolete at a slot's delete where KVM zaps every slot
* (KVM_X86_QUIRK_SLOT_ZAP_ALL on, KVM's default, which the device turns off
* where KVM has it; mmu.c:7629-7650), at an MMIO generation wrap after many
* slot changes (mmu.c:7653-7678), or when nx_huge_pages is switched
* (mmu.c:7755-7766). The next call frees the obsolete root
* (arch/x86/kvm/mmu.h:195-198). A slice takes 0.3-0.6 ms.
*/
#define REIMS_GRAPHICS_KVM_CALL_LIMIT_NS (20 * 1000 * 1000)
#ifndef sigev_notify_thread_id
#define sigev_notify_thread_id _sigev_un._tid
#endif
static struct {
unsigned long id; /* the helper's vCPU id */
struct kvm_cpuid2 *cpuid; /* vCPU 0's, for the helper */
int tsc_khz; /* vCPU 0's, or <= 0 where KVM did not say */
int fd; /* the helper's vCPU fd, -1 until made */
pthread_t thread; /* the populate thread */
timer_t timer; /* the populate thread's call limit */
Notifier tsc_put;
} reims_graphics_kvm_helper = { .fd = -1 };
/*
* Writes the helper's TSC as the host, to 0, which KVM always takes as
* synchronizing: the helper joins the TSC generation the VM's vCPUs are
* in, with no change to theirs (arch/x86/kvm/msrs.c:1630-1632,
* arch/x86/kvm/x86.c:1314-1319, 1351-1361), and a write to a helper
* already in it changes nothing (x86.c:1287-1288).
*/
static int reims_graphics_kvm_helper_tsc_zero(int fd)
{
struct {
struct kvm_msrs info;
struct kvm_msr_entry entries[1];
} msrs = {
.info.nmsrs = 1,
.entries[0].index = REIMS_GRAPHICS_KVM_MSR_IA32_TSC,
};
return ioctl(fd, KVM_SET_MSRS, &msrs) == 1 ? 0 : -errno;
}
/*
* After each put of a guest vCPU's TSC at a reset (a guest reboot writes
* TSC 1 on each vCPU, target/i386/cpu.c:9486-9496) or of its full state: on
* that vCPU's thread. KVM's master clock needs every vCPU, the helper
* included, in one TSC generation (x86.c:1088-1101); the first vCPU's
* write starts a new one, which the others join, and a helper nobody
* wrote would be left out, so the master clock would go off for the guest's
* kvmclock until the next reset (x86.c:1587-1594). The helper joins after
* each put, so it is in the generation the last put leaves.
*/
static void reims_graphics_kvm_tsc_put(Notifier *n, void *data)
{
CPUState *cpu = data;
int fd = qatomic_read(&reims_graphics_kvm_helper.fd);
int ret;
if (fd < 0) {
return;
}
ret = reims_graphics_kvm_helper_tsc_zero(fd);
trace_reims_graphics_prefault_tsc_rejoin(cpu->cpu_index, ret);
if (ret < 0) {
warn_report_once("reims-graphics-pci: the pre-fault helper's TSC "
"write failed (%s): KVM's master clock may stay "
"off", strerror(-ret));
}
}
/* On the populate thread: makes the helper and the call limit's timer. */
static bool reims_graphics_kvm_prefault_start(Error **errp)
{
struct sigevent sev = {
.sigev_notify = SIGEV_THREAD_ID,
.sigev_signo = SIG_IPI,
};
sigset_t set;
int fd, khz, ret;
/*
* The timer and a pause's kick signal this thread with SIG_IPI, whose
* handler (kvm_ipi_signal, accel/kvm/kvm-all.c) does nothing on a
* thread that is no vCPU's; the signal only ends the call in flight
* (virt/kvm/kvm_main.c:4411-4415, arch/x86/kvm/mmu/mmu.c:5063-5065).
*/
sigemptyset(&set);
sigaddset(&set, SIG_IPI);
pthread_sigmask(SIG_UNBLOCK, &set, NULL);
reims_graphics_kvm_helper.thread = pthread_self();
sev.sigev_notify_thread_id = qemu_get_thread_id();
if (timer_create(CLOCK_MONOTONIC, &sev,
&reims_graphics_kvm_helper.timer) < 0) {
error_setg_errno(errp, errno, "reims-graphics-pci: no pre-fault of "
"the pool: timer_create");
return false;
}
fd = kvm_vm_ioctl(kvm_state, KVM_CREATE_VCPU,
(void *)reims_graphics_kvm_helper.id);
if (fd < 0) {
error_setg_errno(errp, -fd, "reims-graphics-pci: no pre-fault of the "
"pool: KVM_CREATE_VCPU %lu",
reims_graphics_kvm_helper.id);
return false;
}
/*
* The helper's TSC frequency is the guest's vCPUs', as KVM's TSC
* generations match only at one frequency; then it joins theirs, and
* from here on rejoins it after each of their puts, whatever comes
* of the rest: the helper is in the VM for good.
*/
khz = reims_graphics_kvm_helper.tsc_khz;
if (khz > 0 && ioctl(fd, KVM_GET_TSC_KHZ) != khz &&
ioctl(fd, KVM_SET_TSC_KHZ, khz) < 0) {
error_setg_errno(errp, errno, "reims-graphics-pci: no pre-fault of "
"the pool: KVM_SET_TSC_KHZ %d on its vCPU", khz);
return false;
}
ret = reims_graphics_kvm_helper_tsc_zero(fd);
if (ret < 0) {
error_setg_errno(errp, -ret, "reims-graphics-pci: no pre-fault of "
"the pool: the TSC write on its vCPU");
return false;
}
qatomic_set(&reims_graphics_kvm_helper.fd, fd);
if (ioctl(fd, KVM_SET_CPUID2, reims_graphics_kvm_helper.cpuid) < 0) {
error_setg_errno(errp, errno, "reims-graphics-pci: no pre-fault of "
"the pool: KVM_SET_CPUID2 on its vCPU");
return false;
}
trace_reims_graphics_prefault_helper(reims_graphics_kvm_helper.id,
reims_graphics_kvm_helper.cpuid->nent,
khz);
return true;
}
static int64_t reims_graphics_kvm_prefault_populate(hwaddr gpa, uint64_t size,
bool *cut)
{
struct kvm_pre_fault_memory range = { .gpa = gpa, .size = size };
struct itimerspec limit = {
.it_value.tv_nsec = REIMS_GRAPHICS_KVM_CALL_LIMIT_NS,
};
struct itimerspec off = { 0 }, left;
int ret, err;
timer_settime(reims_graphics_kvm_helper.timer, 0, &limit, NULL);
ret = ioctl(reims_graphics_kvm_helper.fd, KVM_PRE_FAULT_MEMORY, &range);
err = errno;
timer_settime(reims_graphics_kvm_helper.timer, 0, &off, &left);
/* A one-shot timer with nothing left ran out: it signalled. */
*cut = left.it_value.tv_sec == 0 && left.it_value.tv_nsec == 0;
if (ret == 0) {
/* Progress: KVM gives the range left back. */
return range.size < size ? size - range.size : -EIO;
}
return -err;
}
static void reims_graphics_kvm_prefault_kick(void)
{
pthread_kill(reims_graphics_kvm_helper.thread, SIG_IPI);
}
static const ReimsGraphicsPrefaultOps reims_graphics_kvm_prefault = {
.start = reims_graphics_kvm_prefault_start,
.populate = reims_graphics_kvm_prefault_populate,
.kick = reims_graphics_kvm_prefault_kick,
};
/* vCPU 0's CPUID, as KVM holds it: NULL where it did not answer. */
static struct kvm_cpuid2 *reims_graphics_kvm_cpuid(CPUState *cpu)
{
struct kvm_cpuid2 *cpuid;
unsigned nent;
for (nent = 128; nent <= REIMS_GRAPHICS_KVM_CPUID_MAX; nent *= 2) {
cpuid = g_malloc0(sizeof(*cpuid) +
nent * sizeof(struct kvm_cpuid_entry2));
cpuid->nent = nent;
if (ioctl(cpu->kvm_fd, KVM_GET_CPUID2, cpuid) == 0) {
return cpuid;
}
g_free(cpuid);
if (errno != E2BIG) {
break;
}
}
return NULL;
}
const ReimsGraphicsPrefaultOps *reims_graphics_kvm_prefault_ops(void)
{
MachineState *ms = MACHINE(qdev_get_machine());
MachineClass *mc = MACHINE_GET_CLASS(ms);
const CPUArchIdList *ids;
CPUState *cpu = first_cpu;
unsigned long id = 0;
int i;
if (!kvm_enabled() || !kvm_pre_fault_memory_supported) {
return NULL;
}
if (!mc->possible_cpu_arch_ids || !cpu || cpu->kvm_fd < 0) {
warn_report("reims-graphics-pci: no pre-fault of the pool: the "
"machine names no vCPUs");
return NULL;
}
ids = mc->possible_cpu_arch_ids(ms);
for (i = 0; i < ids->len; i++) {
id = MAX(id, ids->cpus[i].arch_id + 1);
}
if (id > REIMS_GRAPHICS_KVM_HELPER_MAX_ID) {
warn_report("reims-graphics-pci: no pre-fault of the pool: its "
"vCPU's id would be %lu, past %d", id,
REIMS_GRAPHICS_KVM_HELPER_MAX_ID);
return NULL;
}
reims_graphics_kvm_helper.id = id;
reims_graphics_kvm_helper.cpuid = reims_graphics_kvm_cpuid(cpu);
if (!reims_graphics_kvm_helper.cpuid) {
warn_report("reims-graphics-pci: no pre-fault of the pool: "
"KVM_GET_CPUID2 on vCPU 0: %s", strerror(errno));
return NULL;
}
reims_graphics_kvm_helper.tsc_khz = ioctl(cpu->kvm_fd, KVM_GET_TSC_KHZ);
reims_graphics_kvm_helper.tsc_put.notify = reims_graphics_kvm_tsc_put;
kvm_tsc_put_add_notifier(&reims_graphics_kvm_helper.tsc_put);
return &reims_graphics_kvm_prefault;
}
#else
const ReimsGraphicsPrefaultOps *reims_graphics_kvm_prefault_ops(void)
{
return NULL;
}
#endif
-32
View File
@@ -1,32 +0,0 @@
/*
* QEMU reims-graphics device: its calls into KVM
*
* SPDX-License-Identifier: GPL-2.0-or-later
*
* reims-graphics-pci.c is built once for every target (system_ss), and a
* target without KVM links neither kvm_check_extension nor kvm_vm_ioctl. The
* device's calls into KVM are therefore in reims-graphics-pci-kvm.c, which
* only the targets with KVM link; the others link
* reims-graphics-pci-kvm-stub.c (hw/display/meson.build). Linux hosts alone
* build either.
*/
#ifndef HW_DISPLAY_REIMS_GRAPHICS_PCI_KVM_H
#define HW_DISPLAY_REIMS_GRAPHICS_PCI_KVM_H
#include "reims-graphics-pci-prefault.h"
/*
* Turns KVM's KVM_X86_QUIRK_SLOT_ZAP_ALL off for the VM, where KVM runs it
* and has the quirk. False only where KVM refused to turn it off.
*/
bool reims_graphics_kvm_disable_slot_zap_all(void);
/*
* The pool's populate on KVM (reims-graphics-pci-prefault.h), under the
* BQL at realize, once the VM's vCPUs are made: NULL where KVM has no
* KVM_CAP_PRE_FAULT_MEMORY or the host is not x86-64.
*/
const ReimsGraphicsPrefaultOps *reims_graphics_kvm_prefault_ops(void);
#endif
-356
View File
@@ -1,356 +0,0 @@
/*
* QEMU reims-graphics device: the pool's pre-fault
*
* SPDX-License-Identifier: GPL-2.0-or-later
*
* reims-graphics-pci-prefault.h says what it does. One thread a VM, for
* every device of the VM's: the populate's calls run on the thread, and
* the queue, under its lock, holds the pieces not yet started, sorted by
* address.
*/
#include "qemu/osdep.h"
#include "qapi/error.h"
#include "qemu/error-report.h"
#include "qemu/lockable.h"
#include "qemu/thread.h"
#include "qemu/timer.h"
#include "system/kvm.h"
#include "system/whpx.h"
#include "reims-graphics-pci-prefault.h"
#ifdef CONFIG_LINUX
#include "reims-graphics-pci-kvm.h"
#endif
#include "trace.h"
/* Calls in a row cut with nothing done, after which a piece is let go. */
#define REIMS_GRAPHICS_PREFAULT_CUTS 3
typedef struct ReimsGraphicsPrefaultRange {
hwaddr gpa;
uint64_t size;
int64_t queued; /* get_clock() at the add */
} ReimsGraphicsPrefaultRange;
struct ReimsGraphicsPrefault {
const ReimsGraphicsPrefaultOps *ops;
QemuThread thread;
QemuSemaphore started;
bool ok; /* the start's answer, once started is posted */
QemuMutex lock;
QemuCond cond;
GArray *queue; /* lock: ReimsGraphicsPrefaultRange, sorted by gpa */
bool busy; /* lock: a piece is in flight, */
hwaddr cur_gpa; /* lock: at cur_gpa, */
uint64_t cur_size; /* lock: of cur_size bytes, */
bool cur_stopped; /* lock: and its removal stopped it */
unsigned paused; /* lock: the pauses on, which no call starts under */
bool in_call; /* lock: the thread is in a call, */
bool kicked; /* lock: which a pause has signalled */
QemuCond idle; /* broadcast when a call a pause waits for ends */
/* lock: the totals */
uint64_t regions, bytes, slices, cuts, kicks, errors, stopped, dropped;
int64_t cpu_ns;
};
static bool reims_graphics_prefault_overlap(hwaddr a, uint64_t a_size,
hwaddr b, uint64_t b_size)
{
return a < b + b_size && b < a + a_size;
}
/* The calling thread's CPU time, in ns: 0 where the host does not say. */
static int64_t reims_graphics_prefault_cpu_ns(void)
{
#ifdef CLOCK_THREAD_CPUTIME_ID
struct timespec ts;
if (clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts) == 0) {
return ts.tv_sec * NANOSECONDS_PER_SECOND + ts.tv_nsec;
}
#endif
return 0;
}
/*
* Populates @r, lowest address first, a slice a call, until it is done, its
* removal stops it, or a call fails: a failed call leaves the rest of the
* piece to the guest's first touch, as without the populate.
*/
static void reims_graphics_prefault_region(ReimsGraphicsPrefault *pf,
const ReimsGraphicsPrefaultRange *r)
{
hwaddr gpa = r->gpa, end = r->gpa + r->size, next;
int64_t t0 = get_clock(), c0 = reims_graphics_prefault_cpu_ns();
int64_t s0, slice_ns, slice_max = 0, wall, cpu;
unsigned slices = 0, cuts = 0, kicks = 0, cut_run = 0;
int64_t done;
bool cut, kicked, stopped = false;
int err = 0;
while (gpa < end) {
WITH_QEMU_LOCK_GUARD(&pf->lock) {
while (pf->paused) {
qemu_cond_wait(&pf->cond, &pf->lock);
}
stopped = pf->cur_stopped;
pf->in_call = !stopped;
pf->kicked = false;
}
if (stopped) {
break;
}
next = MIN(end, QEMU_ALIGN_DOWN(gpa, REIMS_GRAPHICS_PREFAULT_SLICE) +
REIMS_GRAPHICS_PREFAULT_SLICE);
cut = false;
s0 = get_clock();
done = pf->ops->populate(gpa, next - gpa, &cut);
slice_ns = get_clock() - s0;
WITH_QEMU_LOCK_GUARD(&pf->lock) {
pf->in_call = false;
kicked = pf->kicked;
if (pf->paused) {
qemu_cond_broadcast(&pf->idle);
}
}
slice_max = MAX(slice_max, slice_ns);
slices++;
cuts += cut;
kicks += kicked;
if (done > 0) {
gpa += done;
cut_run = 0;
} else if (done == -EINTR && kicked) {
/* A pause ended it with nothing done: it starts afresh after. */
} else if (done == -EINTR &&
++cut_run < REIMS_GRAPHICS_PREFAULT_CUTS) {
/* Cut with nothing done: the next call starts afresh. */
} else {
err = -done;
break;
}
}
wall = get_clock() - t0;
cpu = reims_graphics_prefault_cpu_ns() - c0;
trace_reims_graphics_prefault_region(r->gpa, r->size, gpa - r->gpa,
slices, cuts, kicks, err, stopped);
trace_reims_graphics_prefault_region_time(r->gpa, t0 - r->queued, wall,
cpu, slice_max);
WITH_QEMU_LOCK_GUARD(&pf->lock) {
pf->regions++;
pf->bytes += gpa - r->gpa;
pf->slices += slices;
pf->cuts += cuts;
pf->kicks += kicks;
pf->errors += err != 0;
pf->stopped += stopped;
pf->cpu_ns += cpu;
}
}
/*
* The populate on WHPX: one partition call a slice, which needs no vCPU.
* Measured 11-18 on the Windows mini (UHD 630, Windows 10.0.26300), with
* a 64 MiB map and unmap of another range looped beside a 548 MiB populate:
* the populate in one call took 54 ms and the map beside it waited 55 ms
* (p50), where in 2 MiB slices it took 218 ms and a map waited 1.25 / 1.64
* / 3.94 ms (p50 / p90 / max), against 1.60 / 1.76 / 2.25 ms with no
* populate.
*/
static bool reims_graphics_whpx_prefault_start(Error **errp)
{
if (!whpx_can_populate()) {
error_setg(errp, "reims-graphics-pci: no pre-fault of the pool: "
"the hypervisor has no WHvAdviseGpaRange");
return false;
}
return true;
}
static int64_t reims_graphics_whpx_prefault_populate(hwaddr gpa,
uint64_t size, bool *cut)
{
int ret = whpx_populate(gpa, size);
return ret < 0 ? ret : size;
}
static const ReimsGraphicsPrefaultOps reims_graphics_whpx_prefault = {
.start = reims_graphics_whpx_prefault_start,
.populate = reims_graphics_whpx_prefault_populate,
};
static void *reims_graphics_prefault_thread(void *opaque)
{
ReimsGraphicsPrefault *pf = opaque;
ReimsGraphicsPrefaultRange r;
Error *err = NULL;
pf->ok = pf->ops->start(&err);
if (!pf->ok) {
warn_report_err(err);
}
qemu_sem_post(&pf->started);
if (!pf->ok) {
return NULL;
}
for (;;) {
WITH_QEMU_LOCK_GUARD(&pf->lock) {
while (pf->queue->len == 0) {
qemu_cond_wait(&pf->cond, &pf->lock);
}
r = g_array_index(pf->queue, ReimsGraphicsPrefaultRange, 0);
g_array_remove_index(pf->queue, 0);
pf->busy = true;
pf->cur_gpa = r.gpa;
pf->cur_size = r.size;
pf->cur_stopped = false;
}
reims_graphics_prefault_region(pf, &r);
WITH_QEMU_LOCK_GUARD(&pf->lock) {
pf->busy = false;
}
}
return NULL;
}
ReimsGraphicsPrefault *reims_graphics_prefault_get(void)
{
static ReimsGraphicsPrefault *made;
static bool tried;
const ReimsGraphicsPrefaultOps *ops = NULL;
ReimsGraphicsPrefault *pf;
if (tried) {
return made;
}
tried = true;
#ifdef CONFIG_LINUX
if (kvm_enabled()) {
ops = reims_graphics_kvm_prefault_ops();
}
#endif
if (whpx_enabled()) {
ops = &reims_graphics_whpx_prefault;
}
if (!ops) {
return NULL;
}
pf = g_new0(ReimsGraphicsPrefault, 1);
pf->ops = ops;
qemu_sem_init(&pf->started, 0);
qemu_mutex_init(&pf->lock);
qemu_cond_init(&pf->cond);
qemu_cond_init(&pf->idle);
pf->queue = g_array_new(false, false, sizeof(ReimsGraphicsPrefaultRange));
/* It lives to the process's exit, waiting for pieces. */
qemu_thread_create(&pf->thread, "rgfx-prefault",
reims_graphics_prefault_thread, pf,
QEMU_THREAD_DETACHED);
qemu_sem_wait(&pf->started);
if (!pf->ok) {
g_array_free(pf->queue, true);
qemu_cond_destroy(&pf->idle);
qemu_cond_destroy(&pf->cond);
qemu_mutex_destroy(&pf->lock);
qemu_sem_destroy(&pf->started);
g_free(pf);
return NULL;
}
made = pf;
return made;
}
void reims_graphics_prefault_add(ReimsGraphicsPrefault *pf, hwaddr gpa,
uint64_t size)
{
ReimsGraphicsPrefaultRange r = {
.gpa = gpa, .size = size, .queued = get_clock(),
};
guint i;
WITH_QEMU_LOCK_GUARD(&pf->lock) {
for (i = 0; i < pf->queue->len; i++) {
if (g_array_index(pf->queue, ReimsGraphicsPrefaultRange,
i).gpa > gpa) {
break;
}
}
g_array_insert_val(pf->queue, i, r);
qemu_cond_broadcast(&pf->cond);
}
}
void reims_graphics_prefault_stop(ReimsGraphicsPrefault *pf, hwaddr gpa,
uint64_t size)
{
ReimsGraphicsPrefaultRange *r;
guint i = 0;
WITH_QEMU_LOCK_GUARD(&pf->lock) {
while (i < pf->queue->len) {
r = &g_array_index(pf->queue, ReimsGraphicsPrefaultRange, i);
if (reims_graphics_prefault_overlap(r->gpa, r->size, gpa, size)) {
trace_reims_graphics_prefault_dropped(r->gpa, r->size);
pf->dropped++;
g_array_remove_index(pf->queue, i);
} else {
i++;
}
}
if (pf->busy &&
reims_graphics_prefault_overlap(pf->cur_gpa, pf->cur_size,
gpa, size)) {
pf->cur_stopped = true;
}
}
}
void reims_graphics_prefault_pause(ReimsGraphicsPrefault *pf)
{
int64_t t0 = get_clock();
unsigned kicks = 0;
bool in_call;
if (!pf->ops->kick) {
return;
}
WITH_QEMU_LOCK_GUARD(&pf->lock) {
pf->paused++;
in_call = pf->in_call;
while (pf->in_call) {
/*
* A signal that lands before the call is in the kernel ends
* nothing: each millisecond the call goes on, it is sent again.
*/
pf->kicked = true;
pf->ops->kick();
kicks++;
qemu_cond_timedwait(&pf->idle, &pf->lock, 1);
}
}
trace_reims_graphics_prefault_pause(in_call, kicks, get_clock() - t0);
}
void reims_graphics_prefault_resume(ReimsGraphicsPrefault *pf)
{
if (!pf->ops->kick) {
return;
}
WITH_QEMU_LOCK_GUARD(&pf->lock) {
assert(pf->paused > 0);
if (--pf->paused == 0) {
qemu_cond_broadcast(&pf->cond);
}
}
}
void reims_graphics_prefault_report(ReimsGraphicsPrefault *pf)
{
WITH_QEMU_LOCK_GUARD(&pf->lock) {
trace_reims_graphics_prefault_totals(pf->regions, pf->bytes,
pf->slices, pf->cuts, pf->kicks,
pf->errors, pf->stopped,
pf->dropped, pf->cpu_ns);
}
}
-95
View File
@@ -1,95 +0,0 @@
/*
* QEMU reims-graphics device: the pool's pre-fault
*
* SPDX-License-Identifier: GPL-2.0-or-later
*
* A pool piece's first touch by the guest takes one second-level fault a
* 4 KiB page: 140,289 of them for a 548 MiB piece, about 180-260 ms on KVM
* and 1.3 s on WHPX. Once the piece is in the guest and its add answered,
* one thread of the VM's fills the second-level tables for it ahead of the
* guest's touch, so the guest's first touch takes no fault: the populate.
* The answer never waits for it.
*
* The thread takes the pieces lowest address first, each in 2 MiB slices,
* one call a slice, and stops a piece between slices at its removal. Each
* call holds what a slot change waits for (KVM's SRCU, WHPX's partition
* map), so a slice bounds that wait. The accelerator's part, the call, is a
* ReimsGraphicsPrefaultOps: KVM's KVM_PRE_FAULT_MEMORY on a vCPU of the
* thread's own that never runs (reims-graphics-pci-kvm.c), or WHPX's
* WHvAdviseGpaRange populate (whpx_populate).
*
* On KVM a pool piece's add changes a slot under the BQL, and its removal
* deletes its slot on the library's thread first (kvm_unmap_before_del),
* neither of which must wait for a call: each pauses the populate first,
* which signals the call in flight to end it at once, and resumes it once
* its slot change is done. On WHPX the device maps and unmaps its pieces
* outside the BQL (whpx_map_ahead, whpx_unmap_before_del), and a map or
* unmap under the BQL waits for at most the slice in flight: the populate
* takes no pause there.
*/
#ifndef HW_DISPLAY_REIMS_GRAPHICS_PCI_PREFAULT_H
#define HW_DISPLAY_REIMS_GRAPHICS_PCI_PREFAULT_H
#include "exec/hwaddr.h"
#include "qemu/units.h"
/* The most a call populates: what a slot change waits for, at most. */
#define REIMS_GRAPHICS_PREFAULT_SLICE (2 * MiB)
typedef struct ReimsGraphicsPrefaultOps {
/*
* On the populate thread, once, before any call: false, with @errp
* set, where it cannot populate.
*/
bool (*start)(Error **errp);
/*
* On the populate thread: populates [@gpa, @gpa + @size), at most one
* slice. The bytes done from @gpa (> 0), or a negative errno where
* none were. *@cut is set where the call ran into its time limit.
*/
int64_t (*populate)(hwaddr gpa, uint64_t size, bool *cut);
/*
* Any thread: signals the populate thread, so that the call it is in
* ends with what it has done (-EINTR where it did nothing). NULL where
* a slot change under the BQL waits for at most the slice in flight: a
* pause and its resume then do nothing.
*/
void (*kick)(void);
} ReimsGraphicsPrefaultOps;
typedef struct ReimsGraphicsPrefault ReimsGraphicsPrefault;
/*
* The VM's populate thread, under the BQL: made at the first call, which
* waits for its start. NULL where the accelerator has no populate or its
* start failed (a warning says why).
*/
ReimsGraphicsPrefault *reims_graphics_prefault_get(void);
/*
* Queues [@gpa, @gpa + @size) for the populate, once the guest's address
* space has it and its add was answered. Any thread.
*/
void reims_graphics_prefault_add(ReimsGraphicsPrefault *pf, hwaddr gpa,
uint64_t size);
/*
* Drops what is queued of [@gpa, @gpa + @size), and stops the piece in
* flight there before its next slice. Any thread; it waits for no call.
*/
void reims_graphics_prefault_stop(ReimsGraphicsPrefault *pf, hwaddr gpa,
uint64_t size);
/*
* Any thread, before a slot change: no call starts until the matching
* resume, and the call in flight is ended; returns once none is. Pauses
* nest.
*/
void reims_graphics_prefault_pause(ReimsGraphicsPrefault *pf);
void reims_graphics_prefault_resume(ReimsGraphicsPrefault *pf);
/* Traces the thread's totals so far. */
void reims_graphics_prefault_report(ReimsGraphicsPrefault *pf);
#endif
File diff suppressed because it is too large. Load diff
+28 -15
View File
@@ -198,19 +198,32 @@ dm163_leds(int led, uint32_t value) "led %d: 0x%x"
dm163_channels(int channel, uint8_t value) "channel %d: 0x%x"
dm163_refresh_rate(uint32_t rr) "refresh rate %d"
# reims-graphics-pci.c
reims_graphics_pool_reserved(uint64_t gpa, uint64_t size, uint64_t end) "the pool's range at 0x%"PRIx64", 0x%"PRIx64" bytes, reserved to 0x%"PRIx64
reims_graphics_pool_add(uint64_t gpa, uint64_t size, bool ahead, int64_t ask_ns, int64_t map_ahead_ns, unsigned run, int64_t held_ns) "piece at 0x%"PRIx64", 0x%"PRIx64" bytes, mapped ahead %d: %"PRId64" ns from the ask, map ahead %"PRId64" ns, BQL part of its run of %u %"PRId64" ns"
reims_graphics_pool_remove(uint64_t gpa, uint64_t size, bool ahead, int64_t unmap_ahead_ns, unsigned run, int64_t held_ns) "piece at 0x%"PRIx64", 0x%"PRIx64" bytes taken out, unmapped ahead %d: unmap ahead %"PRId64" ns, BQL part of its run of %u %"PRId64" ns"
reims_graphics_pool_removed(uint64_t gpa) "piece at 0x%"PRIx64" ended"
reims_graphics_quiesce(const char *where, bool may_exit, int64_t ns) "at the %s: answered %d in %"PRId64" ns"
reims_graphics_end(const char *where, int status) "at the %s: ends with _exit(%d)"
# apple-gfx.m
apple_gfx_read(uint64_t offset, uint64_t res) "offset=0x%"PRIx64" res=0x%"PRIx64
apple_gfx_write(uint64_t offset, uint64_t val) "offset=0x%"PRIx64" val=0x%"PRIx64
apple_gfx_create_task(uint32_t vm_size, void *va) "vm_size=0x%x base_addr=%p"
apple_gfx_destroy_task(void *task, unsigned int num_mapped_regions) "task=%p, task->mapped_regions->len=%u"
apple_gfx_map_memory(void *task, uint32_t range_count, uint64_t virtual_offset, uint32_t read_only) "task=%p range_count=0x%x virtual_offset=0x%"PRIx64" read_only=%d"
apple_gfx_map_memory_range(uint32_t i, uint64_t phys_addr, uint64_t phys_len) "[%d] phys_addr=0x%"PRIx64" phys_len=0x%"PRIx64
apple_gfx_remap(uint64_t retval, void *source_ptr, uint64_t target) "retval=%"PRId64" source=%p target=0x%"PRIx64
apple_gfx_unmap_memory(void *task, uint64_t virtual_offset, uint64_t length) "task=%p virtual_offset=0x%"PRIx64" length=0x%"PRIx64
apple_gfx_read_memory(uint64_t phys_address, uint64_t length, void *dst) "phys_addr=0x%"PRIx64" length=0x%"PRIx64" dest=%p"
apple_gfx_raise_irq(uint32_t vector) "vector=0x%x"
apple_gfx_new_frame(void) ""
apple_gfx_mode_change(uint64_t x, uint64_t y) "x=%"PRId64" y=%"PRId64
apple_gfx_cursor_set(uint32_t bpp, uint64_t width, uint64_t height) "bpp=%d width=%"PRId64" height=0x%"PRId64
apple_gfx_cursor_show(uint32_t show) "show=%d"
apple_gfx_cursor_move(void) ""
apple_gfx_common_init(const char *device_name, size_t mmio_size) "device: %s; MMIO size: %zu bytes"
apple_gfx_common_realize_modes_property(uint32_t num_modes) "using %u modes supplied by 'display-modes' device property"
apple_gfx_display_mode(uint32_t mode_idx, uint16_t width_px, uint16_t height_px) "mode %2"PRIu32": %4"PRIu16"x%4"PRIu16
# apple-gfx-mmio.m
apple_gfx_mmio_iosfc_read(uint64_t offset, uint64_t res) "offset=0x%"PRIx64" res=0x%"PRIx64
apple_gfx_mmio_iosfc_write(uint64_t offset, uint64_t val) "offset=0x%"PRIx64" val=0x%"PRIx64
apple_gfx_iosfc_map_memory(uint64_t phys, uint64_t len, uint32_t ro, void *va, void *e, void *f, void* va_result) "phys=0x%"PRIx64" len=0x%"PRIx64" ro=%d va=%p e=%p f=%p -> *va=%p"
apple_gfx_iosfc_map_memory_new_region(size_t i, void *region, uint64_t start, uint64_t end) "index=%zu, region=%p, 0x%"PRIx64"-0x%"PRIx64
apple_gfx_iosfc_unmap_memory(void *a, void *b, void *c, void *d, void *e, void *f) "a=%p b=%p c=%p d=%p e=%p f=%p"
apple_gfx_iosfc_unmap_memory_region(void* mem, void *region) "unmapping @ %p from memory region %p"
apple_gfx_iosfc_raise_irq(uint32_t vector) "vector=0x%x"
# reims-graphics-pci-prefault.c, reims-graphics-pci-kvm.c
reims_graphics_prefault_helper(unsigned long id, unsigned cpuid_entries, int tsc_khz) "the populate's vCPU %lu made, with vCPU 0's %u CPUID entries and TSC kHz %d"
reims_graphics_prefault_tsc_rejoin(int cpu_index, int ret) "after vCPU %d's TSC put, the populate's vCPU's TSC write answered %d"
reims_graphics_prefault_region(uint64_t gpa, uint64_t size, uint64_t done, unsigned slices, unsigned cuts, unsigned kicks, int err, bool stopped) "piece at 0x%"PRIx64", 0x%"PRIx64" bytes: 0x%"PRIx64" populated in %u slices, %u cut by the timer, %u by a pause; errno %d, stopped %d"
reims_graphics_prefault_region_time(uint64_t gpa, int64_t queued_ns, int64_t wall_ns, int64_t cpu_ns, int64_t slice_max_ns) "piece at 0x%"PRIx64": queued %"PRId64" ns, wall %"PRId64" ns, thread CPU %"PRId64" ns, longest slice %"PRId64" ns"
reims_graphics_prefault_dropped(uint64_t gpa, uint64_t size) "piece at 0x%"PRIx64", 0x%"PRIx64" bytes, removed before its populate started"
reims_graphics_prefault_pause(bool in_call, unsigned kicks, int64_t wait_ns) "paused for a slot change: in a call %d, %u signals, %"PRId64" ns"
reims_graphics_prefault_totals(uint64_t regions, uint64_t bytes, uint64_t slices, uint64_t cuts, uint64_t kicks, uint64_t errors, uint64_t stopped, uint64_t dropped, int64_t cpu_ns) "%"PRIu64" pieces, 0x%"PRIx64" bytes populated in %"PRIu64" slices, %"PRIu64" cut by the timer, %"PRIu64" by a pause; %"PRIu64" ended by an error, %"PRIu64" stopped, %"PRIu64" dropped; thread CPU %"PRId64" ns"
-6
View File
@@ -499,12 +499,6 @@ static void pl061_hold_reset(Object *obj, ResetType type)
qemu_set_irq(s->out[i], level);
}
s->old_out_data = pullups;
/*
* Lower the interrupt line, as the enter phase cleared what raises it:
* a line keeps its level across a reset otherwise, and an in-kernel GIC
* (HVF's, KVM's) raises its interrupt again once the GIC is reset.
*/
qemu_set_irq(s->irq, (s->istate & s->im) != 0);
}
static void pl061_set_irq(void * opaque, int irq, int level)
-5
View File
@@ -57,7 +57,6 @@ struct ARMGICv2mState {
uint32_t base_spi;
uint32_t num_spi;
uint32_t macos_compat;
};
static void gicv2m_set_irq(void *opaque, int irq)
@@ -82,9 +81,6 @@ static uint64_t gicv2m_read(void *opaque, hwaddr offset,
case V2M_MSI_TYPER:
val = (s->base_spi + 32) << 16;
val |= s->num_spi;
if (s->macos_compat) {
val |= BIT(31);
}
return val;
case V2M_MSI_IIDR:
/* We don't have any valid implementor so we leave that field as zero
@@ -177,7 +173,6 @@ static void gicv2m_init(Object *obj)
static const Property gicv2m_properties[] = {
DEFINE_PROP_UINT32("base-spi", ARMGICv2mState, base_spi, 0),
DEFINE_PROP_UINT32("num-spi", ARMGICv2mState, num_spi, 64),
DEFINE_PROP_UINT32("macos-compat", ARMGICv2mState, macos_compat, 0),
};
static void gicv2m_class_init(ObjectClass *klass, const void *data)
+3 -21
View File
@@ -90,13 +90,8 @@ static void hvf_dist_get_priority(GICv3State *s,
uint64_t reg;
uint32_t *field;
int irq;
field = (uint32_t *)(bmp);
/*
* The loop starts at the first SPI: skip the internal IRQs' fields in
* bmp and their registers, as for_each_dist_irq_reg() does.
*/
field = (uint32_t *)(bmp + GIC_INTERNAL);
offset += (GIC_INTERNAL * 8) / 8;
for_each_dist_irq_reg(irq, s->num_irq, 8) {
hv_gic_get_distributor_reg(offset, &reg);
*field = reg;
@@ -111,10 +106,8 @@ static void hvf_dist_put_priority(GICv3State *s,
{
uint32_t reg, *field;
int irq;
field = (uint32_t *)(bmp);
/* As in hvf_dist_get_priority(): the loop starts at the first SPI. */
field = (uint32_t *)(bmp + GIC_INTERNAL);
offset += (GIC_INTERNAL * 8) / 8;
for_each_dist_irq_reg(irq, s->num_irq, 8) {
reg = *field;
hv_gic_set_distributor_reg(offset, reg);
@@ -130,8 +123,6 @@ static void hvf_dist_get_edge_trigger(GICv3State *s,
uint64_t reg;
int irq;
/* The loop starts at the first SPI: skip the internal IRQs' registers. */
offset += (GIC_INTERNAL * 2) / 8;
for_each_dist_irq_reg(irq, s->num_irq, 2) {
hv_gic_get_distributor_reg(offset, &reg);
reg = half_unshuffle32(reg >> 1);
@@ -150,8 +141,6 @@ static void hvf_dist_put_edge_trigger(GICv3State *s,
uint32_t reg;
int irq;
/* The loop starts at the first SPI: skip the internal IRQs' registers. */
offset += (GIC_INTERNAL * 2) / 8;
for_each_dist_irq_reg(irq, s->num_irq, 2) {
reg = *gic_bmp_ptr32(bmp, irq);
if (irq % 32 != 0) {
@@ -172,8 +161,6 @@ static void hvf_dist_getbmp(GICv3State *s, hv_gic_distributor_reg_t offset,
uint64_t reg;
int irq;
/* The loop starts at the first SPI: skip the internal IRQs' register. */
offset += (GIC_INTERNAL * 1) / 8;
for_each_dist_irq_reg(irq, s->num_irq, 1) {
hv_gic_get_distributor_reg(offset, &reg);
*gic_bmp_ptr32(bmp, irq) = reg;
@@ -187,11 +174,6 @@ static void hvf_dist_putbmp(GICv3State *s, hv_gic_distributor_reg_t offset,
uint32_t reg;
int irq;
/* The loop starts at the first SPI: skip the internal IRQs' register. */
offset += (GIC_INTERNAL * 1) / 8;
if (clroffset != 0) {
clroffset += (GIC_INTERNAL * 1) / 8;
}
for_each_dist_irq_reg(irq, s->num_irq, 1) {
/*
* If this bitmap is a set/clear register pair, first write to the
@@ -199,7 +181,7 @@ static void hvf_dist_putbmp(GICv3State *s, hv_gic_distributor_reg_t offset,
* the 1 bits.
*/
if (clroffset != 0) {
reg = ~0;
reg = 0;
hv_gic_set_distributor_reg(clroffset, reg);
clroffset += 4;
}
+1 -53
View File
@@ -37,7 +37,6 @@
#include "qemu/error-report.h"
#include "qemu/module.h"
#include "qemu/timer.h"
#include "migration/vmstate.h"
#include "qom/object.h"
#include "hw/acpi/acpi_aml_interface.h"
@@ -109,7 +108,7 @@ struct AppleSMCState {
uint8_t status;
uint8_t status_1e;
uint8_t last_ret;
uint8_t key[4];
char key[4];
uint8_t read_pos;
uint8_t data_len;
uint8_t data_pos;
@@ -127,7 +126,6 @@ static void applesmc_io_cmd_write(void *opaque, hwaddr addr, uint64_t val,
smc_debug("CMD received: 0x%02x\n", (uint8_t)val);
switch (val) {
case APPLESMC_READ_CMD:
case APPLESMC_GET_KEY_BY_INDEX_CMD:
/* did last command run through OK? */
if (status == APPLESMC_ST_CMD_DONE || status == APPLESMC_ST_NEW_CMD) {
s->cmd = val;
@@ -164,7 +162,6 @@ static void applesmc_io_data_write(void *opaque, hwaddr addr, uint64_t val,
{
AppleSMCState *s = opaque;
const struct AppleSMCData *d;
uint32_t index;
smc_debug("DATA received: 0x%02x\n", (uint8_t)val);
switch (s->cmd) {
@@ -192,34 +189,6 @@ static void applesmc_io_data_write(void *opaque, hwaddr addr, uint64_t val,
}
s->read_pos++;
break;
case APPLESMC_GET_KEY_BY_INDEX_CMD:
/* a big-endian index of 4 bytes, with no length byte after it */
if ((s->status & 0x0f) == APPLESMC_ST_CMD_DONE || s->read_pos == 4) {
break;
}
s->key[s->read_pos++] = val;
s->status = APPLESMC_ST_ACK;
if (s->read_pos < 4) {
break;
}
/* the keys in the list's order but OSK0 and OSK1, found by name only */
index = ldl_be_p(s->key);
QLIST_FOREACH(d, &s->data_def, node) {
if (memcmp(d->key, "OSK", 3) && index-- == 0) {
break;
}
}
if (d != NULL) {
memcpy(s->data, d->key, 4);
s->data_len = 4;
s->data_pos = 0;
s->status = APPLESMC_ST_ACK | APPLESMC_ST_DATA_READY;
s->status_1e = APPLESMC_ST_CMD_DONE;
} else {
s->status = APPLESMC_ST_CMD_DONE;
s->status_1e = APPLESMC_ST_1E_BAD_INDEX;
}
break;
default:
s->status = APPLESMC_ST_CMD_DONE;
s->status_1e = APPLESMC_ST_1E_STILL_BAD_CMD;
@@ -239,7 +208,6 @@ static uint64_t applesmc_io_data_read(void *opaque, hwaddr addr, unsigned size)
switch (s->cmd) {
case APPLESMC_READ_CMD:
case APPLESMC_GET_KEY_BY_INDEX_CMD:
if (!(s->status & APPLESMC_ST_DATA_READY)) {
break;
}
@@ -362,7 +330,6 @@ static void applesmc_isa_realize(DeviceState *dev, Error **errp)
}
QLIST_INIT(&s->data_def);
/* each goes at the head: GET_KEY_BY_INDEX lists MSSD, MSSP, NATJ, REV */
applesmc_add_key(s, "REV ", 6, "\x01\x13\x0f\x00\x00\x03");
applesmc_add_key(s, "OSK0", 32, s->osk);
applesmc_add_key(s, "OSK1", 32, s->osk + 32);
@@ -408,30 +375,11 @@ static void build_applesmc_aml(AcpiDevAmlIf *adev, Aml *scope)
aml_append(scope, dev);
}
static const VMStateDescription vmstate_applesmc = {
.name = "applesmc",
.version_id = 1,
.minimum_version_id = 1,
.fields = (const VMStateField[]) {
VMSTATE_UINT8(cmd, AppleSMCState),
VMSTATE_UINT8(status, AppleSMCState),
VMSTATE_UINT8(status_1e, AppleSMCState),
VMSTATE_UINT8(last_ret, AppleSMCState),
VMSTATE_UINT8_ARRAY(key, AppleSMCState, 4),
VMSTATE_UINT8(read_pos, AppleSMCState),
VMSTATE_UINT8(data_len, AppleSMCState),
VMSTATE_UINT8(data_pos, AppleSMCState),
VMSTATE_UINT8_ARRAY(data, AppleSMCState, 255),
VMSTATE_END_OF_LIST()
}
};
static void qdev_applesmc_class_init(ObjectClass *klass, const void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
AcpiDevAmlIfClass *adevc = ACPI_DEV_AML_IF_CLASS(klass);
dc->vmsd = &vmstate_applesmc;
dc->realize = applesmc_isa_realize;
dc->unrealize = applesmc_unrealize;
device_class_set_legacy_reset(dc, qdev_applesmc_isa_reset);
+3 -22
View File
@@ -109,10 +109,7 @@ static struct {
static struct {
const char *loc_pfx, *bank, *manufacturer, *serial, *asset, *part;
uint16_t speed;
uint8_t memory_type;
} type17 = {
.memory_type = 0x07, /* RAM */
};
} type17;
static QEnumLookup type41_kind_lookup = {
.array = (const char *const[]) {
@@ -472,10 +469,6 @@ static const QemuOptDesc qemu_smbios_type17_opts[] = {
.name = "speed",
.type = QEMU_OPT_NUMBER,
.help = "maximum capable speed",
},{
.name = "memory_type",
.type = QEMU_OPT_NUMBER,
.help = "memory type (7, RAM, by default; 26 is DDR4)",
},
{ /* end of list */ }
};
@@ -904,7 +897,7 @@ static void smbios_build_type_17_table(unsigned instance, uint64_t size)
snprintf(loc_str, sizeof(loc_str), "%s %d", type17.loc_pfx, instance);
SMBIOS_TABLE_SET_STR(17, device_locator_str, loc_str);
SMBIOS_TABLE_SET_STR(17, bank_locator_str, type17.bank);
t->memory_type = type17.memory_type;
t->memory_type = 0x07; /* RAM */
t->type_detail = cpu_to_le16(0x02); /* Other */
t->speed = cpu_to_le16(type17.speed);
SMBIOS_TABLE_SET_STR(17, manufacturer_str, type17.manufacturer);
@@ -1540,9 +1533,7 @@ void smbios_entry_add(QemuOpts *opts, Error **errp)
return;
}
return;
case 17: {
uint64_t memory_type;
case 17:
if (!qemu_opts_validate(opts, qemu_smbios_type17_opts, errp)) {
return;
}
@@ -1553,17 +1544,7 @@ void smbios_entry_add(QemuOpts *opts, Error **errp)
save_opt(&type17.asset, opts, "asset");
save_opt(&type17.part, opts, "part");
type17.speed = qemu_opt_get_number(opts, "speed", 0);
memory_type = qemu_opt_get_number(opts, "memory_type",
0x07 /* RAM */);
if (memory_type == 0 || memory_type > UINT8_MAX) {
error_setg(errp, "SMBIOS memory type %" PRIu64
" is out of range (1 to %d)", memory_type,
UINT8_MAX);
return;
}
type17.memory_type = memory_type;
return;
}
case 41: {
struct type41_instance *t41_i;
Error *local_err = NULL;
-5
View File
@@ -72,11 +72,6 @@ config USB_TABLET_WACOM
default y
depends on USB
config USB_TABLET_VMAPPLE
bool
default y
depends on USB
config USB_STORAGE_CORE
bool
depends on USB
-875
View File
@@ -1,875 +0,0 @@
/*
* USB tablet of Virtualization.framework's macOS guests
*
* The USB pointing device Virtualization.framework gives a macOS guest: an
* absolute pointer whose reports also carry smooth scrolling, that is, the
* scroll distance in pixels with the phases of the gesture it belongs to
* and of the momentum scrolling after it. macOS binds its own driver,
* AppleVirtualPlatformHIDEventDriver, to the device's vendor and product
* IDs, and scrolls as it does with a trackpad. Other guests see a HID
* mouse with an absolute pointer, a wheel and a horizontal wheel.
*
* Report 1, in the input direction:
* byte 0 buttons 1 to 3
* bytes 1-4 X and Y, 0 to 0x7fff
* bytes 5-6 wheel notches, above 0 up
* bytes 7-8 horizontal wheel notches (AC Pan), above 0 right
* bytes 9-12 vertical scroll in 1/65536 line, above 0 up
* bytes 13-16 horizontal scroll in 1/65536 line, above 0 left
* bytes 17-18 phases: bits 1:0 momentum (none, began, changed, ended),
* bits 4:2 gesture (none, may begin, began, changed, ended,
* cancelled)
* Feature report 2 is the wheels' resolution multiplier: set, the wheels
* count 1/120 notch. Feature report 3 bit 0 turns on the smooth scrolling
* fields; this device fills them in either way.
*
* macOS takes a report as a scroll when one of its scroll fields is new: a
* relative field that is not 0 or was not 0 in the report before, phases
* that differ from the report before, or any field of the first report it
* reads. It then ignores the report's pointer and buttons, and it moves the
* pointer or presses a button only for a field that differs from the report
* before. So a report of nothing goes first after a reset, scroll reports
* repeat the pointer and buttons of the report before them, and a report
* that returns the scroll fields to 0 comes between a scroll report and a
* pointer report.
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "qemu/osdep.h"
#include "qapi/error.h"
#include "ui/console.h"
#include "ui/input.h"
#include "hw/usb/usb.h"
#include "hw/usb/hid.h"
#include "hw/core/qdev-properties.h"
#include "migration/vmstate.h"
#include "qemu/bswap.h"
#include "qemu/module.h"
#include "desc.h"
#include "trace.h"
#include "qom/object.h"
#define VMAPPLE_TABLET_QUEUE_LENGTH 16
/* macOS scrolls 10 pixels a line of the smooth scrolling fields. */
#define VMAPPLE_TABLET_LINE_PIXELS 10
/*
* The pixels a wheel notch stands for: what a notch of a wheel scrolls, and
* the smooth scrolling that makes a notch in the wheel fields. macOS does
* not accelerate this device's scrolling; a notch of usb-tablet's wheel
* scrolls from 5 to 40 pixels there, by how fast the wheel turns.
*/
#define VMAPPLE_TABLET_NOTCH_PIXELS 20
/* Wheel units a notch makes when the resolution multiplier is set */
#define VMAPPLE_TABLET_MULTIPLIED_NOTCH 120
enum {
VMAPPLE_TABLET_REPORT_INPUT = 1,
VMAPPLE_TABLET_REPORT_MULTIPLIER = 2,
VMAPPLE_TABLET_REPORT_SMOOTH = 3,
};
#define VMAPPLE_TABLET_REPORT_SIZE 20
typedef struct VMAppleTabletReport {
uint8_t buttons;
uint16_t x;
uint16_t y;
int16_t wheel;
int16_t pan;
int32_t scroll_y;
int32_t scroll_x;
uint16_t phases;
} VMAppleTabletReport;
struct USBVMAppleTabletState {
USBDevice dev;
USBEndpoint *intr;
QemuInputHandlerState *hs;
bool input_active;
char *display;
uint32_t head;
/* Input since the last synchronization */
uint8_t buttons;
uint16_t x;
uint16_t y;
bool pointer_changed;
int32_t notches_y;
int32_t notches_x;
int64_t scroll_y;
int64_t scroll_x;
uint16_t phases;
bool scrolled;
/*
* Smooth scrolling not yet a whole wheel unit, in 1/256 pixel times the
* units a notch makes
*/
int32_t notch_rest_y;
int32_t notch_rest_x;
VMAppleTabletReport queue[VMAPPLE_TABLET_QUEUE_LENGTH];
uint32_t queue_head;
uint32_t queue_count;
/* The last report queued, which the guest reads last */
VMAppleTabletReport last;
/* Reports were dropped, the queue being full; see vmapple_tablet_push() */
bool overflow;
/* The phases of the last scroll report dropped that had some */
uint16_t owed_phases;
uint8_t idle;
uint8_t multiplier;
uint8_t smooth;
};
#define TYPE_USB_VMAPPLE_TABLET "usb-vmapple-tablet"
OBJECT_DECLARE_SIMPLE_TYPE(USBVMAppleTabletState, USB_VMAPPLE_TABLET)
enum {
STR_MANUFACTURER = 1,
STR_PRODUCT,
STR_SERIALNUMBER,
STR_CONFIG,
};
static const USBDescStrings desc_strings = {
[STR_MANUFACTURER] = "QEMU",
[STR_PRODUCT] = "QEMU vmapple USB Tablet",
[STR_SERIALNUMBER] = "1",
[STR_CONFIG] = "HID Tablet",
};
/* The descriptor Virtualization.framework's device has. */
static const uint8_t vmapple_tablet_report_descriptor[] = {
0x05, 0x01, /* Usage Page (Generic Desktop) */
0x09, 0x02, /* Usage (Mouse) */
0xa1, 0x01, /* Collection (Application) */
0x85, 0x01, /* Report ID (1) */
0x09, 0x01, /* Usage (Pointer) */
0xa1, 0x00, /* Collection (Physical) */
0x05, 0x09, /* Usage Page (Button) */
0x19, 0x01, /* Usage Minimum (1) */
0x29, 0x03, /* Usage Maximum (3) */
0x15, 0x00, /* Logical Minimum (0) */
0x25, 0x01, /* Logical Maximum (1) */
0x95, 0x03, /* Report Count (3) */
0x75, 0x01, /* Report Size (1) */
0x81, 0x02, /* Input (Data, Variable, Absolute) */
0x95, 0x01, /* Report Count (1) */
0x75, 0x05, /* Report Size (5) */
0x81, 0x01, /* Input (Constant) */
0x05, 0x01, /* Usage Page (Generic Desktop) */
0x09, 0x30, /* Usage (X) */
0x09, 0x31, /* Usage (Y) */
0x15, 0x00, /* Logical Minimum (0) */
0x26, 0xff, 0x7f, /* Logical Maximum (0x7fff) */
0x75, 0x10, /* Report Size (16) */
0x95, 0x02, /* Report Count (2) */
0x81, 0x02, /* Input (Data, Variable, Absolute) */
0xa1, 0x02, /* Collection (Logical) */
0x85, 0x02, /* Report ID (2) */
0x09, 0x48, /* Usage (Resolution Multiplier) */
0x95, 0x01, /* Report Count (1) */
0x75, 0x08, /* Report Size (8) */
0x15, 0x00, /* Logical Minimum (0) */
0x25, 0x01, /* Logical Maximum (1) */
0x35, 0x01, /* Physical Minimum (1) */
0x45, 0x78, /* Physical Maximum (120) */
0xb1, 0x02, /* Feature (Data, Variable, Absolute) */
0x85, 0x01, /* Report ID (1) */
0x09, 0x38, /* Usage (Wheel) */
0x35, 0x00, /* Physical Minimum (0) */
0x45, 0x00, /* Physical Maximum (0) */
0x16, 0x01, 0x80, /* Logical Minimum (-0x7fff) */
0x26, 0xff, 0x7f, /* Logical Maximum (0x7fff) */
0x75, 0x10, /* Report Size (16) */
0x95, 0x01, /* Report Count (1) */
0x81, 0x06, /* Input (Data, Variable, Relative) */
0x05, 0x0c, /* Usage Page (Consumer) */
0x0a, 0x38, 0x02, /* Usage (AC Pan) */
0x81, 0x06, /* Input (Data, Variable, Relative) */
0x06, 0x61, 0xff, /* Usage Page (0xff61, vendor-defined) */
0x09, 0x02, /* Usage (2): vertical scroll */
0x09, 0x01, /* Usage (1): horizontal scroll */
0x75, 0x20, /* Report Size (32) */
0x95, 0x02, /* Report Count (2) */
0x81, 0x06, /* Input (Data, Variable, Relative) */
0x09, 0x03, /* Usage (3): phases */
0x75, 0x10, /* Report Size (16) */
0x95, 0x01, /* Report Count (1) */
0x81, 0x02, /* Input (Data, Variable, Absolute) */
0x85, 0x03, /* Report ID (3) */
0x09, 0x04, /* Usage (4): smooth scrolling on */
0x95, 0x01, /* Report Count (1) */
0x75, 0x01, /* Report Size (1) */
0xb1, 0x02, /* Feature (Data, Variable, Absolute) */
0x95, 0x01, /* Report Count (1) */
0x75, 0x07, /* Report Size (7) */
0xb1, 0x01, /* Feature (Constant) */
0xc0, /* End Collection */
0xc0, /* End Collection */
0xc0, /* End Collection */
};
static const uint8_t desc_hid_vmapple_tablet[] = {
0x09, /* u8 bLength */
USB_DT_HID, /* u8 bDescriptorType */
0x11, 0x01, /* u16 HID_class */
0x00, /* u8 country_code */
0x01, /* u8 num_descriptors */
USB_DT_REPORT, /* u8 type: Report */
sizeof(vmapple_tablet_report_descriptor), 0, /* u16 len */
};
static const USBDescIface desc_iface_vmapple_tablet_full = {
.bInterfaceNumber = 0,
.bNumEndpoints = 1,
.bInterfaceClass = USB_CLASS_HID,
.ndesc = 1,
.descs = (USBDescOther[]) {
{ .data = desc_hid_vmapple_tablet },
},
.eps = (USBDescEndpoint[]) {
{
.bEndpointAddress = USB_DIR_IN | 0x01,
.bmAttributes = USB_ENDPOINT_XFER_INT,
.wMaxPacketSize = VMAPPLE_TABLET_REPORT_SIZE,
.bInterval = 1, /* 1 ms */
},
},
};
static const USBDescIface desc_iface_vmapple_tablet = {
.bInterfaceNumber = 0,
.bNumEndpoints = 1,
.bInterfaceClass = USB_CLASS_HID,
.ndesc = 1,
.descs = (USBDescOther[]) {
{ .data = desc_hid_vmapple_tablet },
},
.eps = (USBDescEndpoint[]) {
{
.bEndpointAddress = USB_DIR_IN | 0x01,
.bmAttributes = USB_ENDPOINT_XFER_INT,
.wMaxPacketSize = VMAPPLE_TABLET_REPORT_SIZE,
.bInterval = 4, /* 2 ^ (4 - 1) * 125 usecs = 1 ms */
},
},
};
static const USBDescDevice desc_device_vmapple_tablet_full = {
.bcdUSB = 0x0110,
.bMaxPacketSize0 = 8,
.bNumConfigurations = 1,
.confs = (USBDescConfig[]) {
{
.bNumInterfaces = 1,
.bConfigurationValue = 1,
.iConfiguration = STR_CONFIG,
.bmAttributes = USB_CFG_ATT_ONE,
.bMaxPower = 50,
.nif = 1,
.ifs = &desc_iface_vmapple_tablet_full,
},
},
};
static const USBDescDevice desc_device_vmapple_tablet = {
.bcdUSB = 0x0200,
.bMaxPacketSize0 = 64,
.bNumConfigurations = 1,
.confs = (USBDescConfig[]) {
{
.bNumInterfaces = 1,
.bConfigurationValue = 1,
.iConfiguration = STR_CONFIG,
.bmAttributes = USB_CFG_ATT_ONE,
.bMaxPower = 50,
.nif = 1,
.ifs = &desc_iface_vmapple_tablet,
},
},
};
static const USBDesc desc_vmapple_tablet = {
.id = {
/* The IDs macOS binds AppleVirtualPlatformHIDEventDriver to */
.idVendor = 0x05ac,
.idProduct = 0x8106,
.bcdDevice = 0,
.iManufacturer = STR_MANUFACTURER,
.iProduct = STR_PRODUCT,
.iSerialNumber = STR_SERIALNUMBER,
},
.full = &desc_device_vmapple_tablet_full,
.high = &desc_device_vmapple_tablet,
.str = desc_strings,
};
static bool vmapple_tablet_report_scrolls(const VMAppleTabletReport *r)
{
return r->wheel || r->pan || r->scroll_y || r->scroll_x || r->phases;
}
static void vmapple_tablet_enqueue(USBVMAppleTabletState *s,
const VMAppleTabletReport *r)
{
assert(s->queue_count < VMAPPLE_TABLET_QUEUE_LENGTH);
s->queue[(s->queue_head + s->queue_count++) %
VMAPPLE_TABLET_QUEUE_LENGTH] = *r;
s->last = *r;
}
/*
* Queue @r, after a report that returns the scroll fields to 0 if needed.
*
* A full queue drops @r, and every report after it until the guest has read
* the queue empty, which then gets what the guest missed, from
* vmapple_tablet_resync(). Merging @r into the last report queued instead
* would lose it where the two differ in kind: macOS ignores the pointer and
* buttons of a scroll report, and then sees no change in a pointer report
* that repeats them, so a button released while the queue is full would
* stay held.
*/
static void vmapple_tablet_push(USBVMAppleTabletState *s,
const VMAppleTabletReport *r)
{
bool settle = vmapple_tablet_report_scrolls(&s->last) &&
!vmapple_tablet_report_scrolls(r);
trace_usb_vmapple_tablet_report(r->buttons, r->x, r->y, r->wheel, r->pan,
r->scroll_y, r->scroll_x, r->phases);
if (s->overflow ||
s->queue_count + settle >= VMAPPLE_TABLET_QUEUE_LENGTH) {
trace_usb_vmapple_tablet_queue_full();
s->overflow = true;
if (r->phases) {
s->owed_phases = r->phases;
}
return;
}
if (settle) {
VMAppleTabletReport zero = {
.buttons = s->last.buttons,
.x = s->last.x,
.y = s->last.y,
};
vmapple_tablet_enqueue(s, &zero);
}
vmapple_tablet_enqueue(s, r);
}
/*
* Once the guest has read the queue empty after reports were dropped: the
* phases of the last scrolling dropped, so that a gesture the guest missed
* the end of ends, and the pointer and buttons as they are.
*/
static void vmapple_tablet_resync(USBVMAppleTabletState *s)
{
VMAppleTabletReport scroll = {
.buttons = s->last.buttons,
.x = s->last.x,
.y = s->last.y,
.phases = s->owed_phases,
};
VMAppleTabletReport pointer = {
.buttons = s->buttons,
.x = s->x,
.y = s->y,
};
s->overflow = false;
s->owed_phases = 0;
if (scroll.phases) {
vmapple_tablet_push(s, &scroll);
}
vmapple_tablet_push(s, &pointer);
}
static uint16_t vmapple_tablet_phases(InputScrollPhase phase,
InputScrollMomentum momentum)
{
static const uint8_t gesture[INPUT_SCROLL_PHASE__MAX] = {
[INPUT_SCROLL_PHASE_NONE] = 0,
[INPUT_SCROLL_PHASE_MAY_BEGIN] = 1,
[INPUT_SCROLL_PHASE_BEGAN] = 2,
[INPUT_SCROLL_PHASE_CHANGED] = 3,
[INPUT_SCROLL_PHASE_ENDED] = 4,
[INPUT_SCROLL_PHASE_CANCELLED] = 5,
};
static const uint8_t momentum_phase[INPUT_SCROLL_MOMENTUM__MAX] = {
[INPUT_SCROLL_MOMENTUM_NONE] = 0,
[INPUT_SCROLL_MOMENTUM_BEGAN] = 1,
[INPUT_SCROLL_MOMENTUM_CHANGED] = 2,
[INPUT_SCROLL_MOMENTUM_ENDED] = 3,
};
return gesture[phase] << 2 | momentum_phase[momentum];
}
static int64_t vmapple_tablet_notch_units(USBVMAppleTabletState *s)
{
return s->multiplier ? VMAPPLE_TABLET_MULTIPLIED_NOTCH : 1;
}
/*
* @distance in 1/256 pixel as whole wheel units, keeping the rest in @rest,
* which counts afresh when the direction turns.
*/
static int64_t vmapple_tablet_wheel(USBVMAppleTabletState *s, int32_t *rest,
int64_t distance)
{
const int64_t notch = VMAPPLE_TABLET_NOTCH_PIXELS * 256;
int64_t sum = distance * vmapple_tablet_notch_units(s);
int64_t units;
if (!sum) {
return 0;
}
if ((int64_t)*rest * sum > 0) {
sum += *rest;
}
units = sum / notch;
*rest = sum - units * notch;
return units;
}
/* @distance in 1/256 pixel in 1/65536 line */
static int32_t vmapple_tablet_lines(int64_t distance)
{
int64_t lines = distance * 256 / VMAPPLE_TABLET_LINE_PIXELS;
return MIN(MAX(lines, INT32_MIN), INT32_MAX);
}
/*
* @distance plus @value, in 1/256 pixel, held to 32 bits: input-send-event
* takes any 64-bit value, which the sums after this would overflow.
*/
static int64_t vmapple_tablet_add(int64_t distance, int64_t value)
{
value = MIN(MAX(value, INT32_MIN), INT32_MAX);
return MIN(MAX(distance + value, INT32_MIN), INT32_MAX);
}
static void vmapple_tablet_input_event(DeviceState *dev, QemuConsole *src,
QemuInputEvent *evt)
{
static const uint8_t bmap[INPUT_BUTTON__MAX] = {
[INPUT_BUTTON_LEFT] = 0x01,
[INPUT_BUTTON_RIGHT] = 0x02,
[INPUT_BUTTON_MIDDLE] = 0x04,
};
USBVMAppleTabletState *s = USB_VMAPPLE_TABLET(dev);
switch (evt->type) {
case INPUT_EVENT_KIND_BTN:
switch (evt->btn.button) {
case INPUT_BUTTON_WHEEL_UP:
s->notches_y += evt->btn.down;
break;
case INPUT_BUTTON_WHEEL_DOWN:
s->notches_y -= evt->btn.down;
break;
case INPUT_BUTTON_WHEEL_LEFT:
s->notches_x += evt->btn.down;
break;
case INPUT_BUTTON_WHEEL_RIGHT:
s->notches_x -= evt->btn.down;
break;
default:
if (evt->btn.down) {
s->buttons |= bmap[evt->btn.button];
} else {
s->buttons &= ~bmap[evt->btn.button];
}
s->pointer_changed = true;
break;
}
break;
case INPUT_EVENT_KIND_ABS:
if (evt->abs.axis == INPUT_AXIS_X) {
s->x = evt->abs.value;
} else if (evt->abs.axis == INPUT_AXIS_Y) {
s->y = evt->abs.value;
}
s->pointer_changed = true;
break;
case INPUT_EVENT_KIND_SCROLL:
if (evt->scroll.axis == INPUT_AXIS_X) {
s->scroll_x = vmapple_tablet_add(s->scroll_x, evt->scroll.value);
} else if (evt->scroll.axis == INPUT_AXIS_Y) {
s->scroll_y = vmapple_tablet_add(s->scroll_y, evt->scroll.value);
}
s->phases = vmapple_tablet_phases(evt->scroll.phase,
evt->scroll.momentum);
s->scrolled = true;
break;
default:
break;
}
}
static void vmapple_tablet_input_sync(DeviceState *dev)
{
USBVMAppleTabletState *s = USB_VMAPPLE_TABLET(dev);
bool pushed = false;
/* The pointer first, so that the scrolling is where the pointer went. */
if (s->pointer_changed) {
VMAppleTabletReport r = {
.buttons = s->buttons,
.x = s->x,
.y = s->y,
};
vmapple_tablet_push(s, &r);
pushed = true;
}
if (s->scrolled || s->notches_y || s->notches_x) {
const int64_t notch = VMAPPLE_TABLET_NOTCH_PIXELS * 256;
int64_t units = vmapple_tablet_notch_units(s);
int64_t wheel = s->notches_y * units +
vmapple_tablet_wheel(s, &s->notch_rest_y, s->scroll_y);
int64_t left = s->notches_x * units +
vmapple_tablet_wheel(s, &s->notch_rest_x, s->scroll_x);
VMAppleTabletReport r = {
.buttons = s->last.buttons,
.x = s->last.x,
.y = s->last.y,
.wheel = MIN(MAX(wheel, -INT16_MAX), INT16_MAX),
/* AC Pan counts to the right, as HID has it */
.pan = MIN(MAX(-left, -INT16_MAX), INT16_MAX),
.scroll_y = vmapple_tablet_lines(s->scroll_y +
s->notches_y * notch),
.scroll_x = vmapple_tablet_lines(s->scroll_x +
s->notches_x * notch),
.phases = s->scrolled ? s->phases : 0,
};
vmapple_tablet_push(s, &r);
pushed = true;
}
s->pointer_changed = false;
s->notches_y = 0;
s->notches_x = 0;
s->scroll_y = 0;
s->scroll_x = 0;
s->scrolled = false;
if (pushed) {
usb_wakeup(s->intr, 0);
}
}
static const QemuInputHandler vmapple_tablet_handler = {
.name = "QEMU vmapple USB Tablet",
.mask = INPUT_EVENT_MASK_BTN | INPUT_EVENT_MASK_ABS |
INPUT_EVENT_MASK_SCROLL,
.event = vmapple_tablet_input_event,
.sync = vmapple_tablet_input_sync,
};
static int vmapple_tablet_write_report(const VMAppleTabletReport *r,
uint8_t *buf, int len)
{
uint8_t report[VMAPPLE_TABLET_REPORT_SIZE];
report[0] = VMAPPLE_TABLET_REPORT_INPUT;
report[1] = r->buttons;
stw_le_p(&report[2], r->x);
stw_le_p(&report[4], r->y);
stw_le_p(&report[6], r->wheel);
stw_le_p(&report[8], r->pan);
stl_le_p(&report[10], r->scroll_y);
stl_le_p(&report[14], r->scroll_x);
stw_le_p(&report[18], r->phases);
len = MIN(len, sizeof(report));
memcpy(buf, report, len);
return len;
}
static void usb_vmapple_tablet_handle_reset(USBDevice *dev)
{
USBVMAppleTabletState *s = USB_VMAPPLE_TABLET(dev);
const VMAppleTabletReport nothing = { 0 };
s->buttons = 0;
s->pointer_changed = false;
s->notches_y = 0;
s->notches_x = 0;
s->scroll_y = 0;
s->scroll_x = 0;
s->phases = 0;
s->scrolled = false;
s->notch_rest_y = 0;
s->notch_rest_x = 0;
s->queue_head = 0;
s->queue_count = 0;
s->overflow = false;
s->owed_phases = 0;
/* The first report the guest reads, which it takes as a scroll */
vmapple_tablet_enqueue(s, &nothing);
s->idle = 0;
s->multiplier = 0;
s->smooth = 0;
}
static void usb_vmapple_tablet_handle_control(USBDevice *dev, USBPacket *p,
int request, int value,
int index, int length,
uint8_t *data)
{
USBVMAppleTabletState *s = USB_VMAPPLE_TABLET(dev);
uint8_t type = value >> 8;
uint8_t id = value & 0xff;
int ret;
ret = usb_desc_handle_control(dev, p, request, value, index, length, data);
if (ret >= 0) {
return;
}
switch (request) {
case InterfaceRequest | USB_REQ_GET_DESCRIPTOR:
if (type != USB_DT_REPORT) {
goto fail;
}
length = MIN(length, sizeof(vmapple_tablet_report_descriptor));
memcpy(data, vmapple_tablet_report_descriptor, length);
p->actual_length = length;
break;
case HID_GET_REPORT:
if (type == 1 && id == VMAPPLE_TABLET_REPORT_INPUT) {
VMAppleTabletReport r = {
.buttons = s->buttons,
.x = s->x,
.y = s->y,
};
p->actual_length = vmapple_tablet_write_report(&r, data, length);
} else if (type == 3 && id == VMAPPLE_TABLET_REPORT_MULTIPLIER &&
length >= 2) {
data[0] = id;
data[1] = s->multiplier;
p->actual_length = 2;
} else if (type == 3 && id == VMAPPLE_TABLET_REPORT_SMOOTH &&
length >= 2) {
data[0] = id;
data[1] = s->smooth;
p->actual_length = 2;
} else {
goto fail;
}
trace_usb_vmapple_tablet_get_report(type, id);
break;
case HID_SET_REPORT:
if (type != 3 || length < 2 || data[0] != id) {
goto fail;
}
if (id == VMAPPLE_TABLET_REPORT_MULTIPLIER) {
s->multiplier = data[1] & 1;
s->notch_rest_y = 0;
s->notch_rest_x = 0;
} else if (id == VMAPPLE_TABLET_REPORT_SMOOTH) {
s->smooth = data[1] & 1;
} else {
goto fail;
}
trace_usb_vmapple_tablet_set_report(id, data[1]);
break;
case HID_GET_IDLE:
data[0] = s->idle;
p->actual_length = 1;
break;
case HID_SET_IDLE:
s->idle = value >> 8;
break;
default:
fail:
p->status = USB_RET_STALL;
break;
}
}
static void usb_vmapple_tablet_handle_data(USBDevice *dev, USBPacket *p)
{
USBVMAppleTabletState *s = USB_VMAPPLE_TABLET(dev);
uint8_t buf[VMAPPLE_TABLET_REPORT_SIZE];
int len;
if (p->pid != USB_TOKEN_IN || p->ep->nr != 1) {
p->status = USB_RET_STALL;
return;
}
/* As usb-tablet does: take the input once the guest reads the device. */
if (!s->input_active) {
qemu_input_handler_activate(s->hs);
s->input_active = true;
}
if (!s->queue_count && s->overflow) {
vmapple_tablet_resync(s);
}
if (!s->queue_count) {
p->status = USB_RET_NAK;
return;
}
len = vmapple_tablet_write_report(&s->queue[s->queue_head], buf,
p->iov.size);
s->queue_head = (s->queue_head + 1) % VMAPPLE_TABLET_QUEUE_LENGTH;
s->queue_count--;
usb_packet_copy(p, buf, len);
}
static void usb_vmapple_tablet_unrealize(USBDevice *dev)
{
USBVMAppleTabletState *s = USB_VMAPPLE_TABLET(dev);
qemu_input_handler_unregister(s->hs);
}
static void usb_vmapple_tablet_realize(USBDevice *dev, Error **errp)
{
ERRP_GUARD();
USBVMAppleTabletState *s = USB_VMAPPLE_TABLET(dev);
dev->usb_desc = &desc_vmapple_tablet;
usb_desc_create_serial(dev);
usb_desc_init(dev);
s->intr = usb_ep_get(dev, USB_TOKEN_IN, 1);
s->hs = qemu_input_handler_register(DEVICE(dev), &vmapple_tablet_handler);
if (s->display) {
qemu_input_handler_bind(s->hs, s->display, s->head, errp);
if (*errp) {
/* A device that fails to realize is freed, not unrealized. */
g_clear_pointer(&s->hs, qemu_input_handler_unregister);
}
}
}
static const VMStateDescription vmstate_vmapple_tablet_report = {
.name = "usb-vmapple-tablet/report",
.version_id = 1,
.minimum_version_id = 1,
.fields = (const VMStateField[]) {
VMSTATE_UINT8(buttons, VMAppleTabletReport),
VMSTATE_UINT16(x, VMAppleTabletReport),
VMSTATE_UINT16(y, VMAppleTabletReport),
VMSTATE_INT16(wheel, VMAppleTabletReport),
VMSTATE_INT16(pan, VMAppleTabletReport),
VMSTATE_INT32(scroll_y, VMAppleTabletReport),
VMSTATE_INT32(scroll_x, VMAppleTabletReport),
VMSTATE_UINT16(phases, VMAppleTabletReport),
VMSTATE_END_OF_LIST()
}
};
static int usb_vmapple_tablet_post_load(void *opaque, int version_id)
{
USBVMAppleTabletState *s = opaque;
if (s->queue_head >= VMAPPLE_TABLET_QUEUE_LENGTH ||
s->queue_count > VMAPPLE_TABLET_QUEUE_LENGTH) {
return -EINVAL;
}
return 0;
}
static bool usb_vmapple_tablet_overflow_needed(void *opaque)
{
USBVMAppleTabletState *s = opaque;
return s->overflow;
}
static const VMStateDescription vmstate_usb_vmapple_tablet_overflow = {
.name = "usb-vmapple-tablet/overflow",
.version_id = 1,
.minimum_version_id = 1,
.needed = usb_vmapple_tablet_overflow_needed,
.fields = (const VMStateField[]) {
VMSTATE_BOOL(overflow, USBVMAppleTabletState),
VMSTATE_UINT16(owed_phases, USBVMAppleTabletState),
VMSTATE_END_OF_LIST()
}
};
static const VMStateDescription vmstate_usb_vmapple_tablet = {
.name = "usb-vmapple-tablet",
.version_id = 1,
.minimum_version_id = 1,
.post_load = usb_vmapple_tablet_post_load,
.fields = (const VMStateField[]) {
VMSTATE_USB_DEVICE(dev, USBVMAppleTabletState),
VMSTATE_UINT8(buttons, USBVMAppleTabletState),
VMSTATE_UINT16(x, USBVMAppleTabletState),
VMSTATE_UINT16(y, USBVMAppleTabletState),
VMSTATE_INT32(notch_rest_y, USBVMAppleTabletState),
VMSTATE_INT32(notch_rest_x, USBVMAppleTabletState),
VMSTATE_STRUCT_ARRAY(queue, USBVMAppleTabletState,
VMAPPLE_TABLET_QUEUE_LENGTH, 1,
vmstate_vmapple_tablet_report,
VMAppleTabletReport),
VMSTATE_UINT32(queue_head, USBVMAppleTabletState),
VMSTATE_UINT32(queue_count, USBVMAppleTabletState),
VMSTATE_STRUCT(last, USBVMAppleTabletState, 1,
vmstate_vmapple_tablet_report, VMAppleTabletReport),
VMSTATE_UINT8(idle, USBVMAppleTabletState),
VMSTATE_UINT8(multiplier, USBVMAppleTabletState),
VMSTATE_UINT8(smooth, USBVMAppleTabletState),
VMSTATE_END_OF_LIST()
},
.subsections = (const VMStateDescription * const []) {
&vmstate_usb_vmapple_tablet_overflow,
NULL
}
};
static const Property usb_vmapple_tablet_properties[] = {
DEFINE_PROP_STRING("display", USBVMAppleTabletState, display),
DEFINE_PROP_UINT32("head", USBVMAppleTabletState, head, 0),
};
static void usb_vmapple_tablet_class_init(ObjectClass *klass,
const void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
uc->product_desc = "QEMU vmapple USB Tablet";
uc->realize = usb_vmapple_tablet_realize;
uc->unrealize = usb_vmapple_tablet_unrealize;
uc->handle_reset = usb_vmapple_tablet_handle_reset;
uc->handle_control = usb_vmapple_tablet_handle_control;
uc->handle_data = usb_vmapple_tablet_handle_data;
uc->handle_attach = usb_desc_attach;
dc->desc = "USB tablet of Virtualization.framework's macOS guests";
dc->vmsd = &vmstate_usb_vmapple_tablet;
device_class_set_props(dc, usb_vmapple_tablet_properties);
set_bit(DEVICE_CATEGORY_INPUT, dc->categories);
}
static const TypeInfo usb_vmapple_tablet_info = {
.name = TYPE_USB_VMAPPLE_TABLET,
.parent = TYPE_USB_DEVICE,
.instance_size = sizeof(USBVMAppleTabletState),
.class_init = usb_vmapple_tablet_class_init,
};
static void usb_vmapple_tablet_register_types(void)
{
type_register_static(&usb_vmapple_tablet_info);
}
type_init(usb_vmapple_tablet_register_types)
-27
View File
@@ -28,7 +28,6 @@
#include "migration/vmstate.h"
#include "hw/pci/msi.h"
#include "hw/pci/msix.h"
#include "hw/pci/pcie.h"
#include "hcd-xhci-pci.h"
#include "trace.h"
#include "qapi/error.h"
@@ -121,29 +120,6 @@ static int xhci_pci_vmstate_post_load(void *opaque, int version_id)
return 0;
}
/*
* An xHC with LTC set supports its interconnect's LTR mechanism (xHCI 4.13.1):
* on PCI Express, LTR in Device Capabilities 2, its enable in Device Control 2
* and the LTR Extended Capability with its two maximum latencies.
*/
#define XHCI_PCI_LTR_OFFSET 0x100
static void xhci_pci_ltr_init(PCIDevice *dev)
{
uint16_t exp_cap = dev->exp.exp_cap;
pci_long_test_and_set_mask(dev->config + exp_cap + PCI_EXP_DEVCAP2,
PCI_EXP_DEVCAP2_LTR);
pci_word_test_and_set_mask(dev->wmask + exp_cap + PCI_EXP_DEVCTL2,
PCI_EXP_DEVCTL2_LTR_EN);
pcie_add_capability(dev, PCI_EXT_CAP_ID_LTR, 1, XHCI_PCI_LTR_OFFSET,
PCI_EXT_CAP_LTR_SIZEOF);
pci_set_word(dev->wmask + XHCI_PCI_LTR_OFFSET + PCI_LTR_MAX_SNOOP_LAT,
PCI_LTR_VALUE_MASK | PCI_LTR_SCALE_MASK);
pci_set_word(dev->wmask + XHCI_PCI_LTR_OFFSET + PCI_LTR_MAX_NOSNOOP_LAT,
PCI_LTR_VALUE_MASK | PCI_LTR_SCALE_MASK);
}
static void usb_xhci_pci_realize(struct PCIDevice *dev, Error **errp)
{
int ret;
@@ -161,8 +137,6 @@ static void usb_xhci_pci_realize(struct PCIDevice *dev, Error **errp)
if (s->conditional_intr_mapping) {
s->xhci.intr_mapping_supported = xhci_pci_intr_mapping_conditional;
}
/* PCI Express has an LTR mechanism, so the xHC supports LTM (4.13.1) */
s->xhci.ltm = pci_bus_is_express(pci_get_bus(dev));
if (!qdev_realize(DEVICE(&s->xhci), NULL, errp)) {
return;
}
@@ -196,7 +170,6 @@ static void usb_xhci_pci_realize(struct PCIDevice *dev, Error **errp)
if (pci_bus_is_express(pci_get_bus(dev))) {
ret = pcie_endpoint_cap_init(dev, 0xa0);
assert(ret > 0);
xhci_pci_ltr_init(dev);
}
if (s->msix != ON_OFF_AUTO_OFF) {
+54 -313
View File
@@ -115,8 +115,6 @@
#define PORTSC_DR (1<<30)
#define PORTSC_WPR (1<<31)
#define HCCP1_LTC (1<<6)
#define CRCR_RCS (1<<0)
#define CRCR_CS (1<<1)
#define CRCR_CA (1<<2)
@@ -293,8 +291,6 @@ struct XHCIEPContext {
unsigned int interval;
int64_t mfindex_last;
QEMUTimer *kick_timer;
/* a Ring Underrun or Overrun event reports this empty ring already */
bool iso_empty_reported;
};
typedef struct XHCIEvRingSeg {
@@ -305,8 +301,7 @@ typedef struct XHCIEvRingSeg {
} XHCIEvRingSeg;
static void xhci_kick_ep(XHCIState *xhci, unsigned int slotid,
unsigned int epid, unsigned int streamid,
bool doorbell);
unsigned int epid, unsigned int streamid);
static void xhci_kick_epctx(XHCIEPContext *epctx, unsigned int streamid);
static TRBCCode xhci_disable_ep(XHCIState *xhci, unsigned int slotid,
unsigned int epid);
@@ -600,45 +595,18 @@ static void xhci_intr_update(XHCIState *xhci, int v)
}
}
/* IMODI and IMODC count in 250 ns steps */
#define IMOD_TICK_NS 250
static uint32_t xhci_imodc(XHCIInterrupter *intr)
{
int64_t left;
if (!timer_pending(intr->imod_timer)) {
return 0;
}
left = timer_expire_time_ns(intr->imod_timer) -
qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
return left <= 0 ? 0 : MIN(DIV_ROUND_UP(left, IMOD_TICK_NS), 0xffff);
}
/*
* Assert interrupter v's interrupt when a non-blocking event awaits (IPE),
* the moderation counter is at 0 and the event handler is not busy (4.17.2):
* set IP and EHB, signal the interrupt, and load IMODC with IMODI.
*/
static void xhci_intr_raise(XHCIState *xhci, int v)
{
XHCIInterrupter *intr = &xhci->intr[v];
uint32_t imodi = intr->imod & 0xffff;
bool pending = (xhci->intr[v].erdp_low & ERDP_EHB);
if (!intr->ipe || (intr->erdp_low & ERDP_EHB) ||
timer_pending(intr->imod_timer)) {
xhci->intr[v].erdp_low |= ERDP_EHB;
xhci->intr[v].iman |= IMAN_IP;
xhci->usbsts |= USBSTS_EINT;
if (pending) {
return;
}
intr->erdp_low |= ERDP_EHB;
intr->iman |= IMAN_IP;
xhci->usbsts |= USBSTS_EINT;
if (imodi) {
timer_mod(intr->imod_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
(int64_t)imodi * IMOD_TICK_NS);
}
if (!(intr->iman & IMAN_IE)) {
if (!(xhci->intr[v].iman & IMAN_IE)) {
return;
}
@@ -647,24 +615,11 @@ static void xhci_intr_raise(XHCIState *xhci, int v)
}
if (xhci->intr_raise) {
if (xhci->intr_raise(xhci, v, true)) {
intr->iman &= ~IMAN_IP;
xhci->intr[v].iman &= ~IMAN_IP;
}
}
}
/* IMODC reached 0 */
static void xhci_imod_timer(void *opaque)
{
XHCIInterrupter *intr = opaque;
XHCIState *xhci = intr->xhci;
MemReentrancyGuard *guard = &xhci->parent.mem_reentrancy_guard;
assert(!guard->engaged_in_io);
guard->engaged_in_io = true;
xhci_intr_raise(xhci, intr - xhci->intr);
guard->engaged_in_io = false;
}
static inline int xhci_running(XHCIState *xhci)
{
return !(xhci->usbsts & USBSTS_HCH);
@@ -705,13 +660,7 @@ static void xhci_write_event(XHCIState *xhci, XHCIEvent *event, int v)
}
}
/*
* Post an event on interrupter v's ring. A Transfer Event of a TRB with Block
* Event Interrupt set (4.17.5) is written without asserting the interrupt
* (block_irq): the interrupter's next interrupt brings the guest to it.
*/
static void xhci_event_blockable(XHCIState *xhci, XHCIEvent *event, int v,
bool block_irq)
static void xhci_event(XHCIState *xhci, XHCIEvent *event, int v)
{
XHCIInterrupter *intr;
dma_addr_t erdp;
@@ -749,20 +698,11 @@ static void xhci_event_blockable(XHCIState *xhci, XHCIEvent *event, int v,
DPRINTF("xhci: ER %d full, drop event\n", v);
} else {
xhci_write_event(xhci, event, v);
if (block_irq) {
return;
}
}
intr->ipe = true;
xhci_intr_raise(xhci, v);
}
static void xhci_event(XHCIState *xhci, XHCIEvent *event, int v)
{
xhci_event_blockable(xhci, event, v, false);
}
static void xhci_ring_init(XHCIState *xhci, XHCIRing *ring,
dma_addr_t base)
{
@@ -920,7 +860,6 @@ static void xhci_er_reset(XHCIState *xhci, int v)
intr->er_ep_idx = 0;
intr->er_pcs = 1;
intr->ipe = false;
DPRINTF("xhci: event ring[%d]:" DMA_ADDR_FMT " [%d]\n",
v, intr->er_start, intr->er_size);
@@ -1173,11 +1112,6 @@ static void xhci_ep_kick_timer(void *opaque)
XHCIEPContext *epctx = opaque;
MemReentrancyGuard *guard = &epctx->xhci->parent.mem_reentrancy_guard;
/* a timer armed before a Stop Endpoint restarts nothing (4.6.9) */
if (epctx->state != EP_RUNNING) {
return;
}
assert(!guard->engaged_in_io);
guard->engaged_in_io = true;
@@ -1224,7 +1158,6 @@ static void xhci_init_epctx(XHCIEPContext *epctx,
}
epctx->interval = 1u << MIN((ctx[0] >> 16) & 0xffu, 18u);
epctx->iso_empty_reported = false;
}
static TRBCCode xhci_enable_ep(XHCIState *xhci, unsigned int slotid,
@@ -1537,7 +1470,6 @@ static TRBCCode xhci_set_ep_dequeue(XHCIState *xhci, unsigned int slotid,
xhci_ring_init(xhci, &epctx->ring, dequeue & ~0xF);
epctx->ring.ccs = dequeue & 1;
}
epctx->iso_empty_reported = false;
xhci_set_ep_state(xhci, epctx, sctx, EP_STOPPED);
@@ -1594,34 +1526,12 @@ err:
return -1;
}
/*
* Post the Transfer Events of a transfer's TDs (xHCI 4.10.1.1). Without a
* Short Packet, each TRB with IOC posts Success. A Short Packet ends the
* data of its TD on the TRB it meets: that TRB posts Short Packet with its
* residue if it has ISP or IOC, and that event is the TD Completion Event.
* The xHC then advances to the end of the TD, and each later Transfer TRB
* with IOC posts Short Packet too, with the TD Completion Event's residue
* (4.10.1.1.2): a TD of TRBs with ISP whose last TRB has IOC posts two
* events, and software does not take the TD as complete before the one
* that points at its last TRB. An Event Data TRB after the Short Packet is
* parsed only if no event completed the TD yet, and then only the first
* (PAE is 0, 4.10.1.1.1). An error posts one event, at the first TRB with
* IOC or the TRB where the data transferred ran out, and ends the report.
*/
static void xhci_xfer_report(XHCITransfer *xfer)
{
uint32_t edtla = 0;
unsigned int left;
/*
* The current TD's Short Packet: shortpkt once the TD met it,
* short_reported once the TRB it met it on posted its event, with that
* event's residue in short_length, and ed_parsed once an Event Data TRB
* after it was parsed.
*/
bool shortpkt = false;
bool short_reported = false;
uint32_t short_length = 0;
bool ed_parsed = false;
bool reported = 0;
bool shortpkt = 0;
XHCIEvent event = {ER_TRANSFER, CC_SUCCESS};
XHCIState *xhci = xfer->epctx->xhci;
int i;
@@ -1631,8 +1541,6 @@ static void xhci_xfer_report(XHCITransfer *xfer)
for (i = 0; i < xfer->trb_count; i++) {
XHCITRB *trb = &xfer->trbs[i];
unsigned int chunk = 0;
bool short_trb = false;
bool post;
switch (TRB_TYPE(*trb)) {
case TR_SETUP:
@@ -1647,56 +1555,32 @@ static void xhci_xfer_report(XHCITransfer *xfer)
chunk = trb->status & 0x1ffff;
if (chunk > left) {
chunk = left;
if (xfer->status == CC_SUCCESS && !shortpkt) {
shortpkt = true;
short_trb = true;
if (xfer->status == CC_SUCCESS) {
shortpkt = 1;
}
}
left -= chunk;
edtla += chunk;
break;
case TR_STATUS:
/* the Status Stage is a TD of its own */
shortpkt = false;
short_reported = false;
ed_parsed = false;
reported = 0;
shortpkt = 0;
break;
}
event.slotid = xfer->epctx->slotid;
event.epid = xfer->epctx->epid;
event.length = (trb->status & 0x1ffff) - chunk;
event.flags = 0;
event.ptr = trb->addr;
if (xfer->status != CC_SUCCESS) {
post = (trb->control & TRB_TR_IOC) || left == 0;
event.ccode = xfer->status;
} else if (TRB_TYPE(*trb) == TR_EVDATA && shortpkt) {
post = false;
if (!short_reported && !ed_parsed) {
ed_parsed = true;
post = trb->control & TRB_TR_IOC;
if (!reported && ((trb->control & TRB_TR_IOC) ||
(shortpkt && (trb->control & TRB_TR_ISP)) ||
(xfer->status != CC_SUCCESS && left == 0))) {
event.slotid = xfer->epctx->slotid;
event.epid = xfer->epctx->epid;
event.length = (trb->status & 0x1ffff) - chunk;
event.flags = 0;
event.ptr = trb->addr;
if (xfer->status == CC_SUCCESS) {
event.ccode = shortpkt ? CC_SHORT_PACKET : CC_SUCCESS;
} else {
event.ccode = xfer->status;
}
event.ccode = CC_SHORT_PACKET;
} else if (short_trb) {
post = trb->control & (TRB_TR_IOC | TRB_TR_ISP);
event.ccode = CC_SHORT_PACKET;
if (post) {
short_reported = true;
short_length = event.length;
}
} else if (shortpkt) {
post = trb->control & TRB_TR_IOC;
event.ccode = CC_SHORT_PACKET;
if (short_reported) {
event.length = short_length;
}
} else {
post = trb->control & TRB_TR_IOC;
event.ccode = CC_SUCCESS;
}
if (post) {
if (TRB_TYPE(*trb) == TR_EVDATA) {
event.ptr = trb->parameter;
event.flags |= TRB_EV_ED;
@@ -1704,28 +1588,20 @@ static void xhci_xfer_report(XHCITransfer *xfer)
DPRINTF("xhci_xfer_data: EDTLA=%d\n", event.length);
edtla = 0;
}
/*
* Normal, Isoch and Event Data TRBs have BEI; it blocks the
* interrupt of a completion, not of an error.
*/
xhci_event_blockable(xhci, &event, TRB_INTR(*trb),
(TRB_TYPE(*trb) == TR_NORMAL ||
TRB_TYPE(*trb) == TR_ISOCH ||
TRB_TYPE(*trb) == TR_EVDATA) &&
(trb->control & TRB_TR_BEI) &&
(event.ccode == CC_SUCCESS ||
event.ccode == CC_SHORT_PACKET));
xhci_event(xhci, &event, TRB_INTR(*trb));
reported = 1;
if (xfer->status != CC_SUCCESS) {
return;
}
}
/* a TRB without Chain, and a Setup Stage TRB, end their TD */
if (TRB_TYPE(*trb) == TR_SETUP || !(trb->control & TRB_TR_CH)) {
shortpkt = false;
short_reported = false;
ed_parsed = false;
switch (TRB_TYPE(*trb)) {
case TR_SETUP:
reported = 0;
shortpkt = 0;
break;
}
}
}
@@ -1916,22 +1792,11 @@ static void xhci_calc_iso_kick(XHCIState *xhci, XHCITransfer *xfer,
xfer->mfindex_kick = asap;
}
} else {
/*
* Frame ID holds the frame's low 11 bits, a window of 2048 frames.
* A TD is scheduled at most 895 ms ahead (4.11.2.5), so a frame in
* the half of the window behind the current frame is late and runs
* now, and one in the half ahead is waited for. A late TD used to
* be scheduled 2048 frames ahead once it was more than 32 frames
* late, or 1 frame late just after the window wrapped.
*/
xfer->mfindex_kick = ((xfer->trbs[0].control >> TRB_TR_FRAMEID_SHIFT)
& TRB_TR_FRAMEID_MASK) << 3;
xfer->mfindex_kick |= mfindex & ~0x3fff;
if (xfer->mfindex_kick + 0x2000 <= mfindex) {
if (xfer->mfindex_kick + 0x100 < mfindex) {
xfer->mfindex_kick += 0x4000;
} else if (xfer->mfindex_kick >= mfindex + 0x2000 &&
xfer->mfindex_kick >= 0x4000) {
xfer->mfindex_kick -= 0x4000;
}
}
}
@@ -2011,8 +1876,7 @@ static int xhci_fire_transfer(XHCIState *xhci, XHCITransfer *xfer, XHCIEPContext
}
static void xhci_kick_ep(XHCIState *xhci, unsigned int slotid,
unsigned int epid, unsigned int streamid,
bool doorbell)
unsigned int epid, unsigned int streamid)
{
XHCIEPContext *epctx;
@@ -2030,15 +1894,6 @@ static void xhci_kick_ep(XHCIState *xhci, unsigned int slotid,
return;
}
/*
* 4.6.9: only a doorbell moves a stopped endpoint back to running. A
* device that has data for an endpoint the guest stopped leaves it
* stopped: the guest reads the endpoint context after Stop Endpoint
* completes and expects it stopped until it rings the doorbell.
*/
if (!doorbell && epctx->state != EP_RUNNING) {
return;
}
if (epctx->kick_active) {
return;
}
@@ -2133,14 +1988,8 @@ static void xhci_kick_epctx(XHCIEPContext *epctx, unsigned int streamid)
while (1) {
length = xhci_ring_chain_length(xhci, ring);
if (length <= 0) {
/*
* 4.10.3.1: an isochronous ring found empty is reported once,
* when it runs out of TDs, and not again until TDs were queued
* and ran out. A doorbell rung on a ring already reported empty
* reports nothing: the guest may ring it in answer to the event.
*/
if ((epctx->type == ET_ISO_OUT || epctx->type == ET_ISO_IN) &&
!epctx->iso_empty_reported) {
if (epctx->type == ET_ISO_OUT || epctx->type == ET_ISO_IN) {
/* 4.10.3.1 */
XHCIEvent ev = { ER_TRANSFER };
ev.ccode = epctx->type == ET_ISO_IN ?
CC_RING_OVERRUN : CC_RING_UNDERRUN;
@@ -2148,7 +1997,6 @@ static void xhci_kick_epctx(XHCIEPContext *epctx, unsigned int streamid)
ev.epid = epctx->epid;
ev.ptr = epctx->ring.dequeue;
xhci_event(xhci, &ev, xhci->slots[epctx->slotid-1].intr);
epctx->iso_empty_reported = true;
}
break;
}
@@ -2156,7 +2004,6 @@ static void xhci_kick_epctx(XHCIEPContext *epctx, unsigned int streamid)
if (xfer == NULL) {
break;
}
epctx->iso_empty_reported = false;
for (i = 0; i < length; i++) {
TRBType type;
@@ -2569,16 +2416,10 @@ static TRBCCode xhci_reset_slot(XHCIState *xhci, unsigned int slotid)
return CC_SUCCESS;
}
/*
* The slot a command names, or 0 where it names none that is enabled. Its
* completion holds the command's Slot ID either way (6.4.2.2, and 4.6.4 to
* 4.6.10 set it before checking the slot).
*/
static unsigned int xhci_get_slot(XHCIState *xhci, XHCIEvent *event, XHCITRB *trb)
{
unsigned int slotid;
slotid = (trb->control >> TRB_CR_SLOTID_SHIFT) & TRB_CR_SLOTID_MASK;
event->slotid = slotid;
if (slotid < 1 || slotid > xhci->numslots) {
DPRINTF("xhci: bad slot id %d\n", slotid);
event->ccode = CC_TRB_ERROR;
@@ -2656,8 +2497,9 @@ static void xhci_process_commands(XHCIState *xhci)
{
XHCITRB trb;
TRBType type;
XHCIEvent event = {ER_COMMAND_COMPLETE, CC_SUCCESS};
dma_addr_t addr;
unsigned int i, slotid, count = 0;
unsigned int i, slotid = 0, count = 0;
DPRINTF("xhci_process_commands()\n");
if (!xhci_running(xhci)) {
@@ -2668,17 +2510,7 @@ static void xhci_process_commands(XHCIState *xhci)
xhci->crcr_low |= CRCR_CRR;
while ((type = xhci_ring_fetch(xhci, &xhci->cmd_ring, &trb, &addr))) {
/*
* Each command completes with a Command Completion Event of its own
* (6.4.2.2): nothing of the previous command's carries over. Its Slot
* ID is the slot the command names, the slot an Enable Slot enabled,
* and 0 for No Op, Set LTV, Get Port Bandwidth, Force Event, a
* command the xHC does not support and an Enable Slot that finds no
* free slot.
*/
XHCIEvent event = { .type = ER_COMMAND_COMPLETE, .ccode = CC_SUCCESS,
.ptr = addr };
event.ptr = addr;
switch (type) {
case CR_ENABLE_SLOT:
for (i = 0; i < xhci->numslots; i++) {
@@ -2692,7 +2524,6 @@ static void xhci_process_commands(XHCIState *xhci)
} else {
slotid = i+1;
event.ccode = xhci_enable_slot(xhci, slotid);
event.slotid = slotid;
}
break;
case CR_DISABLE_SLOT:
@@ -2754,20 +2585,6 @@ static void xhci_process_commands(XHCIState *xhci)
event.ccode = xhci_reset_slot(xhci, slotid);
}
break;
case CR_SET_LATENCY_TOLERANCE:
/*
* 4.6.14: an xHC with LTC set records the host's Best Effort
* Latency Tolerance; one without it refuses the command. No LTR
* message carries it on: nothing in QEMU receives one.
*/
if (xhci->ltm) {
xhci->belt = (trb.control >> 16) & 0xfff;
trace_usb_xhci_set_ltv(xhci->belt);
event.ccode = CC_SUCCESS;
} else {
event.ccode = CC_TRB_ERROR;
}
break;
case CR_GET_PORT_BANDWIDTH:
event.ccode = xhci_get_port_bandwidth(xhci, trb.parameter);
break;
@@ -2789,7 +2606,7 @@ static void xhci_process_commands(XHCIState *xhci)
uint32_t val = xhci_nec_challenge(chi, clo);
event.length = val & 0xFFFF;
event.epid = val >> 16;
event.slotid = val >> 24;
slotid = val >> 24;
event.type = 48; /* NEC reply */
} else {
event.ccode = CC_TRB_ERROR;
@@ -2800,6 +2617,7 @@ static void xhci_process_commands(XHCIState *xhci)
event.ccode = CC_TRB_ERROR;
break;
}
event.slotid = slotid;
xhci_event(xhci, &event, 0);
if (count++ > COMMAND_LIMIT) {
@@ -2916,7 +2734,6 @@ static void xhci_reset(DeviceState *dev)
xhci->dcbaap_low = 0;
xhci->dcbaap_high = 0;
xhci->config = 0;
xhci->belt = 0;
for (i = 0; i < xhci->numslots; i++) {
xhci_disable_slot(xhci, i+1);
@@ -2928,9 +2745,7 @@ static void xhci_reset(DeviceState *dev)
for (i = 0; i < xhci->numintrs; i++) {
xhci->intr[i].iman = 0;
xhci->intr[i].imod = 4000; /* IMODI's default, 1 ms (5.5.2.2) */
xhci->intr[i].ipe = false;
timer_del(xhci->intr[i].imod_timer);
xhci->intr[i].imod = 0;
xhci->intr[i].erstsz = 0;
xhci->intr[i].erstba_low = 0;
xhci->intr[i].erstba_high = 0;
@@ -2972,9 +2787,6 @@ static uint64_t xhci_cap_read(void *ptr, hwaddr reg, unsigned size)
} else {
ret = 0x00080001 | (xhci->max_pstreams_mask << 12);
}
if (xhci->ltm) {
ret |= HCCP1_LTC;
}
break;
case 0x14: /* DBOFF */
ret = OFF_DOORBELL;
@@ -2982,9 +2794,6 @@ static uint64_t xhci_cap_read(void *ptr, hwaddr reg, unsigned size)
case 0x18: /* RTSOFF */
ret = OFF_RUNTIME;
break;
case 0x1c: /* HCCPARAMS2 from xHCI 1.1 on, reserved before */
ret = 0; /* none of its capabilities */
break;
/* extended capabilities */
case 0x20: /* Supported Protocol:00 */
@@ -3269,7 +3078,7 @@ static uint64_t xhci_runtime_read(void *ptr, hwaddr reg,
ret = intr->iman;
break;
case 0x04: /* IMOD */
ret = (xhci_imodc(intr) << 16) | intr->imod;
ret = intr->imod;
break;
case 0x08: /* ERSTSZ */
ret = intr->erstsz;
@@ -3325,16 +3134,8 @@ static void xhci_runtime_write(void *ptr, hwaddr reg,
intr->iman |= val & IMAN_IE;
xhci_intr_update(xhci, v);
break;
case 0x04: /* IMOD: IMODI, and IMODC, which software may set */
intr->imod = val & 0xffff;
trace_usb_xhci_imod(v, intr->imod, val >> 16);
if (val >> 16) {
timer_mod(intr->imod_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
(int64_t)(val >> 16) * IMOD_TICK_NS);
} else {
timer_del(intr->imod_timer);
xhci_intr_raise(xhci, v);
}
case 0x04: /* IMOD */
intr->imod = val;
break;
case 0x08: /* ERSTSZ */
intr->erstsz = val & 0xffff;
@@ -3356,19 +3157,15 @@ static void xhci_runtime_write(void *ptr, hwaddr reg,
intr->erdp_low &= ~ERDP_EHB;
}
intr->erdp_low = (val & ~ERDP_EHB) | (intr->erdp_low & ERDP_EHB);
{
if (val & ERDP_EHB) {
dma_addr_t erdp = xhci_addr64(intr->erdp_low, intr->erdp_high);
unsigned int dp_idx = (erdp - intr->er_start) / TRB_SIZE;
/* the ring is empty: no event awaits (4.17.5) */
if (erdp >= intr->er_start &&
erdp < (intr->er_start + TRB_SIZE * intr->er_size) &&
dp_idx == intr->er_ep_idx) {
intr->ipe = false;
dp_idx != intr->er_ep_idx) {
xhci_intr_raise(xhci, v);
}
}
if (val & ERDP_EHB) {
xhci_intr_raise(xhci, v);
}
break;
case 0x1c: /* ERDP high */
intr->erdp_high = val;
@@ -3417,7 +3214,7 @@ static void xhci_doorbell_write(void *ptr, hwaddr reg,
DPRINTF("xhci: bad doorbell %d write: 0x%x\n",
(int)reg, (uint32_t)val);
} else {
xhci_kick_ep(xhci, reg, epid, streamid, true);
xhci_kick_ep(xhci, reg, epid, streamid);
}
}
}
@@ -3598,7 +3395,7 @@ static void xhci_wakeup_endpoint(USBBus *bus, USBEndpoint *ep,
return;
}
prev_engaged = xhci_engage_reentrancy_guard(xhci);
xhci_kick_ep(xhci, slotid, xhci_find_epid(ep), stream, false);
xhci_kick_ep(xhci, slotid, xhci_find_epid(ep), stream);
xhci_restore_reentrancy_guard(xhci, prev_engaged);
}
@@ -3623,8 +3420,6 @@ static void usb_xhci_init(XHCIState *xhci)
xhci->numports = xhci->numports_2 + xhci->numports_3;
usb_bus_new(&xhci->bus, sizeof(xhci->bus), &xhci_bus_ops, xhci->hostOpaque);
/* a NAKed isochronous TD waits in epctx->retry for its endpoint's wakeup */
xhci->bus.iso_nak_retry = true;
for (i = 0; i < usbports; i++) {
speedmask = 0;
@@ -3683,12 +3478,6 @@ static void usb_xhci_realize(DeviceState *dev, Error **errp)
usb_xhci_init(xhci);
xhci->mfwrap_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, xhci_mfwrap_timer, xhci);
for (i = 0; i < xhci->numintrs; i++) {
xhci->intr[i].xhci = xhci;
xhci->intr[i].imod_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL,
xhci_imod_timer,
&xhci->intr[i]);
}
memory_region_init(&xhci->mem, OBJECT(dev), "xhci", XHCI_LEN_REGS);
memory_region_init_io(&xhci->mem_cap, OBJECT(dev), &xhci_cap_ops, xhci,
@@ -3730,9 +3519,6 @@ static void usb_xhci_unrealize(DeviceState *dev)
timer_free(xhci->mfwrap_timer);
xhci->mfwrap_timer = NULL;
}
for (i = 0; i < xhci->numintrs; i++) {
g_clear_pointer(&xhci->intr[i].imod_timer, timer_free);
}
memory_region_del_subregion(&xhci->mem, &xhci->mem_cap);
memory_region_del_subregion(&xhci->mem, &xhci->mem_oper);
@@ -3844,32 +3630,9 @@ static bool xhci_er_full(void *opaque, int version_id)
return false;
}
static bool xhci_intr_moderation_needed(void *opaque)
{
XHCIInterrupter *intr = opaque;
return intr->ipe || timer_pending(intr->imod_timer);
}
static const VMStateDescription vmstate_xhci_intr_moderation = {
.name = "xhci-intr/moderation",
.version_id = 1,
.minimum_version_id = 1,
.needed = xhci_intr_moderation_needed,
.fields = (const VMStateField[]) {
VMSTATE_BOOL(ipe, XHCIInterrupter),
VMSTATE_TIMER_PTR(imod_timer, XHCIInterrupter),
VMSTATE_END_OF_LIST()
}
};
static const VMStateDescription vmstate_xhci_intr = {
.name = "xhci-intr",
.version_id = 1,
.subsections = (const VMStateDescription * const []) {
&vmstate_xhci_intr_moderation,
NULL
},
.fields = (const VMStateField[]) {
/* registers */
VMSTATE_UINT32(iman, XHCIInterrupter),
@@ -3899,32 +3662,10 @@ static const VMStateDescription vmstate_xhci_intr = {
}
};
static bool xhci_belt_needed(void *opaque)
{
XHCIState *xhci = opaque;
return xhci->belt != 0;
}
static const VMStateDescription vmstate_xhci_belt = {
.name = "xhci-core/belt",
.version_id = 1,
.minimum_version_id = 1,
.needed = xhci_belt_needed,
.fields = (const VMStateField[]) {
VMSTATE_UINT16(belt, XHCIState),
VMSTATE_END_OF_LIST()
}
};
const VMStateDescription vmstate_xhci = {
.name = "xhci-core",
.version_id = 1,
.post_load = usb_xhci_post_load,
.subsections = (const VMStateDescription * const []) {
&vmstate_xhci_belt,
NULL
},
.fields = (const VMStateField[]) {
VMSTATE_STRUCT_VARRAY_UINT32(ports, XHCIState, numports, 1,
vmstate_xhci_port, XHCIPort),
+1 -15
View File
@@ -150,9 +150,8 @@ typedef struct XHCIEvent {
} XHCIEvent;
typedef struct XHCIInterrupter {
XHCIState *xhci;
uint32_t iman;
uint32_t imod; /* IMODI; IMODC counts down while imod_timer is pending */
uint32_t imod;
uint32_t erstsz;
uint32_t erstba_low;
uint32_t erstba_high;
@@ -161,11 +160,6 @@ typedef struct XHCIInterrupter {
bool msix_used, er_pcs;
/* Interrupt Pending Enable (4.17.5): a non-blocking event awaits */
bool ipe;
/* expires when IMODC reaches 0 (4.17.2) */
QEMUTimer *imod_timer;
dma_addr_t er_start;
uint32_t er_size;
unsigned int er_ep_idx;
@@ -205,11 +199,6 @@ typedef struct XHCIState {
*/
bool (*intr_mapping_supported)(XHCIState *s);
DeviceState *hostOpaque;
/*
* Latency Tolerance Messaging Capability (LTC, 4.13.1), set where the
* host interconnect has an LTR mechanism (PCI Express)
*/
bool ltm;
/* Operational Registers */
uint32_t usbcmd;
@@ -233,9 +222,6 @@ typedef struct XHCIState {
XHCIRing cmd_ring;
/* the BELT of the last Set LTV Command, 0 while none set one */
uint16_t belt;
bool nec_quirks;
} XHCIState;
+31 -433
View File
@@ -52,8 +52,6 @@
#include "qemu/error-report.h"
#include "qemu/main-loop.h"
#include "qemu/module.h"
#include "qemu/thread.h"
#include "block/thread-pool.h"
#include "system/runstate.h"
#include "system/system.h"
#include "trace.h"
@@ -69,8 +67,6 @@ OBJECT_DECLARE_SIMPLE_TYPE(USBHostDevice, USB_HOST_DEVICE)
typedef struct USBHostRequest USBHostRequest;
typedef struct USBHostIsoXfer USBHostIsoXfer;
typedef struct USBHostIsoRing USBHostIsoRing;
typedef struct USBHostSetIntf USBHostSetIntf;
typedef struct USBHostDeferred USBHostDeferred;
typedef struct libusb_config_descriptor libusb_config_descriptor;
G_DEFINE_AUTOPTR_CLEANUP_FUNC(libusb_config_descriptor,
@@ -101,7 +97,6 @@ struct USBHostDevice {
uint32_t loglevel;
bool allow_one_guest_reset;
bool allow_all_guest_resets;
bool reset_on_close;
bool suppress_remote_wake;
/* state */
@@ -121,9 +116,6 @@ struct USBHostDevice {
bool claimed;
} ifs[USB_MAX_INTERFACES];
/* bInterval of each endpoint of the current settings, [in][number] */
uint8_t ep_interval[2][USB_MAX_ENDPOINTS + 1];
/* callbacks & friends */
QEMUBH *bh_nodev;
QEMUBH *bh_postld;
@@ -133,15 +125,6 @@ struct USBHostDevice {
/* request queues */
QTAILQ_HEAD(, USBHostRequest) requests;
QTAILQ_HEAD(, USBHostIsoRing) isorings;
/* the SET_INTERFACE request a worker thread carries out, if any */
USBHostSetIntf *setintf;
/*
* Set from the start of that request until the submits and cancels that
* waited for it have been made, in their order, from deferred.
*/
bool deferring;
QSIMPLEQ_HEAD(, USBHostDeferred) deferred;
};
struct USBHostRequest {
@@ -156,38 +139,6 @@ struct USBHostRequest {
QTAILQ_ENTRY(USBHostRequest) next;
};
/*
* libusb_set_interface_alt_setting() is synchronous: the kernel holds the
* device while it kills the interface's transfers, sends SET_INTERFACE and
* reconfigures the host controller's endpoints. A worker thread makes the call,
* so QEMU's main loop and vCPUs keep running; the guest's control transfer
* completes when the call returns.
*
* Linux's usbfs takes the same lock of the device for each of its ioctls,
* so the main loop makes none on the device until the call returns: it
* handles no libusb events, where libusb reaps the completed URBs of every
* device it has any for (usb_host_events_pause), and the device's submits and
* cancels wait in its deferred queue (usb_host_submit, usb_host_cancel),
* which runs in order as the call returns.
*/
struct USBHostSetIntf {
USBHostDevice *host;
USBPacket *p; /* NULL once the guest canceled it */
libusb_device_handle *dh;
int iface;
int alt;
int rc;
bool finished;
QemuEvent done; /* the worker's call returned */
};
/* A submit, or a cancel, of a transfer that waits for a SET_INTERFACE call */
struct USBHostDeferred {
struct libusb_transfer *xfer;
bool cancel;
QSIMPLEQ_ENTRY(USBHostDeferred) next;
};
struct USBHostIsoXfer {
USBHostIsoRing *ring;
struct libusb_transfer *xfer;
@@ -199,12 +150,6 @@ struct USBHostIsoXfer {
struct USBHostIsoRing {
USBHostDevice *host;
USBEndpoint *ep;
unsigned int nr_xfers;
/* IN: transfers completed before the stream gave the guest data */
unsigned int nr_primed;
bool primed;
/* OUT: a packet waits for a transfer to complete and free its buffer */
bool out_waiting;
QTAILQ_HEAD(, USBHostIsoXfer) unused;
QTAILQ_HEAD(, USBHostIsoXfer) inflight;
QTAILQ_HEAD(, USBHostIsoXfer) copy;
@@ -219,7 +164,6 @@ static void usb_host_release_interfaces(USBHostDevice *s);
static void usb_host_nodev(USBHostDevice *s);
static void usb_host_detach_kernel(USBHostDevice *s);
static void usb_host_attach_kernel(USBHostDevice *s);
static void usb_host_set_interface_wait(USBHostDevice *s);
/* ------------------------------------------------------------------------ */
@@ -295,13 +239,6 @@ static const char *err_names[] = {
static libusb_context *ctx;
static uint32_t loglevel;
/*
* The SET_INTERFACE calls in flight. While there is one, the main loop
* handles no libusb events: the other devices' completions wait for the
* call, as the whole main loop did while it made the call itself.
*/
static unsigned int events_paused;
#ifndef CONFIG_WIN32
static void usb_host_handle_fd(void *opaque)
@@ -312,9 +249,6 @@ static void usb_host_handle_fd(void *opaque)
static void usb_host_add_fd(int fd, short events, void *user_data)
{
if (events_paused) {
return; /* usb_host_events_resume adds it */
}
qemu_set_fd_handler(fd,
(events & POLLIN) ? usb_host_handle_fd : NULL,
(events & POLLOUT) ? usb_host_handle_fd : NULL,
@@ -326,22 +260,6 @@ static void usb_host_del_fd(int fd, void *user_data)
qemu_set_fd_handler(fd, NULL, NULL, NULL);
}
/* Take libusb's fds out of the main loop, or put them back */
static void usb_host_watch_fds(bool watch)
{
const struct libusb_pollfd **poll = libusb_get_pollfds(ctx);
int i;
for (i = 0; poll && poll[i] != NULL; i++) {
if (watch) {
usb_host_add_fd(poll[i]->fd, poll[i]->events, ctx);
} else {
usb_host_del_fd(poll[i]->fd, ctx);
}
}
free(poll);
}
#else
static QEMUTimer *poll_timer;
@@ -361,33 +279,12 @@ static void usb_host_timer(void *opaque)
{
struct timeval tv = { 0, 0 };
if (!events_paused) {
libusb_handle_events_timeout(ctx, &tv);
}
libusb_handle_events_timeout(ctx, &tv);
usb_host_timer_kick();
}
#endif /* !CONFIG_WIN32 */
static void usb_host_events_pause(void)
{
if (events_paused++ == 0) {
#ifndef CONFIG_WIN32
usb_host_watch_fds(false);
#endif
}
}
static void usb_host_events_resume(void)
{
assert(events_paused > 0);
if (--events_paused == 0) {
#ifndef CONFIG_WIN32
usb_host_watch_fds(true);
#endif
}
}
static int usb_host_init(void)
{
#ifndef CONFIG_WIN32
@@ -465,126 +362,6 @@ static void usb_host_libusb_error(const char *func, int rc)
/* ------------------------------------------------------------------------ */
static void usb_host_defer(USBHostDevice *s, struct libusb_transfer *xfer,
bool cancel)
{
USBHostDeferred *d = g_new0(USBHostDeferred, 1);
d->xfer = xfer;
d->cancel = cancel;
QSIMPLEQ_INSERT_TAIL(&s->deferred, d, next);
}
/* Drop what waits in the deferred queue for a transfer that is done */
static void usb_host_undefer(USBHostDevice *s, struct libusb_transfer *xfer)
{
USBHostDeferred *d, *dn;
QSIMPLEQ_FOREACH_SAFE(d, &s->deferred, next, dn) {
if (d->xfer == xfer) {
QSIMPLEQ_REMOVE(&s->deferred, d, USBHostDeferred, next);
g_free(d);
}
}
}
/*
* Complete a transfer that never reached the kernel through its callback, as
* libusb completes one: with status, and nothing transferred.
*/
static void usb_host_xfer_unsent(struct libusb_transfer *xfer,
enum libusb_transfer_status status)
{
int i;
xfer->status = status;
xfer->actual_length = 0;
for (i = 0; i < xfer->num_iso_packets; i++) {
xfer->iso_packet_desc[i].status = status;
xfer->iso_packet_desc[i].actual_length = 0;
}
xfer->callback(xfer);
}
/* libusb_submit_transfer, or its place in the deferred queue */
static int usb_host_submit(USBHostDevice *s, struct libusb_transfer *xfer)
{
if (s->deferring) {
usb_host_defer(s, xfer, false);
return 0;
}
return libusb_submit_transfer(xfer);
}
/*
* libusb_cancel_transfer, or its place in the deferred queue. A transfer
* whose submit still waits there never reaches the kernel: it leaves the
* queue and completes as canceled.
*/
static void usb_host_cancel(USBHostDevice *s, struct libusb_transfer *xfer)
{
USBHostDeferred *d;
if (!s->deferring) {
libusb_cancel_transfer(xfer);
return;
}
QSIMPLEQ_FOREACH(d, &s->deferred, next) {
if (d->xfer == xfer && !d->cancel) {
QSIMPLEQ_REMOVE(&s->deferred, d, USBHostDeferred, next);
g_free(d);
usb_host_xfer_unsent(xfer, LIBUSB_TRANSFER_CANCELLED);
return;
}
}
usb_host_defer(s, xfer, true);
}
/*
* Make the submits and cancels that waited for a SET_INTERFACE call, in their
* order, with whatever a completion here queues behind them. libusb's events
* stay paused meanwhile, so no transfer completes, and none is freed, under a
* cancel that waits. A submit that fails completes its transfer with the
* error, as one that failed in the kernel would, and a cancel of it that
* waits is dropped. A SET_INTERFACE started meanwhile (the guest canceled
* this one) keeps what is left for its own call.
*/
static void usb_host_run_deferred(USBHostDevice *s)
{
USBHostDeferred *d;
struct libusb_transfer *xfer;
bool cancel;
int rc;
while (!s->setintf && (d = QSIMPLEQ_FIRST(&s->deferred)) != NULL) {
QSIMPLEQ_REMOVE_HEAD(&s->deferred, next);
xfer = d->xfer;
cancel = d->cancel;
g_free(d);
if (cancel) {
libusb_cancel_transfer(xfer);
continue;
}
rc = libusb_submit_transfer(xfer);
if (rc == 0) {
continue;
}
usb_host_libusb_error("libusb_submit_transfer [deferred]", rc);
usb_host_undefer(s, xfer);
usb_host_xfer_unsent(xfer, rc == LIBUSB_ERROR_NO_DEVICE ?
LIBUSB_TRANSFER_NO_DEVICE :
LIBUSB_TRANSFER_ERROR);
if (rc == LIBUSB_ERROR_NO_DEVICE) {
usb_host_nodev(s);
}
}
if (!s->setintf) {
s->deferring = false;
}
}
/* ------------------------------------------------------------------------ */
static bool usb_host_use_combining(USBEndpoint *ep)
{
int type;
@@ -630,11 +407,6 @@ static void usb_host_req_free(USBHostRequest *r)
request_count--;
#endif
QTAILQ_REMOVE(&r->host->requests, r, next);
/*
* A cancel can wait for a transfer that completed: one that libusb had
* reaped in the same pass as a SET_INTERFACE request started.
*/
usb_host_undefer(r->host, r->xfer);
libusb_free_transfer(r->xfer);
g_free(r->buffer);
g_free(r);
@@ -747,7 +519,7 @@ static void usb_host_req_abort(USBHostRequest *r)
}
r->p = NULL;
usb_host_cancel(s, r->xfer);
libusb_cancel_transfer(r->xfer);
}
}
@@ -772,58 +544,28 @@ usb_host_req_complete_iso(struct libusb_transfer *transfer)
}
if (xfer->ring->ep->pid == USB_TOKEN_IN) {
QTAILQ_INSERT_TAIL(&xfer->ring->copy, xfer, next);
if (!xfer->ring->primed) {
xfer->ring->nr_primed++;
}
usb_wakeup(xfer->ring->ep, 0);
} else {
QTAILQ_INSERT_TAIL(&xfer->ring->unused, xfer, next);
if (xfer->ring->out_waiting) {
xfer->ring->out_waiting = false;
usb_wakeup(xfer->ring->ep, 0);
}
}
}
/*
* Packets in each transfer of an endpoint's ring: one millisecond of the
* bus, at most isobsize. A high or super speed endpoint is serviced every
* 2^(bInterval-1) microframes, eight to a millisecond, and a full speed one
* every 2^(bInterval-1) frames, one to a millisecond; an endpoint serviced
* less often than every millisecond gets one packet a transfer.
*/
static unsigned int usb_host_iso_xfer_packets(USBHostDevice *s,
USBEndpoint *ep)
{
USBDevice *udev = USB_DEVICE(s);
unsigned int interval, packets = 1;
if (udev->speed >= USB_SPEED_HIGH) {
interval = s->ep_interval[ep->pid == USB_TOKEN_IN][ep->nr];
interval = MIN(MAX(interval, 1), 4);
packets = 8 >> (interval - 1);
}
return MAX(MIN(packets, s->iso_urb_frames), 1);
}
static USBHostIsoRing *usb_host_iso_alloc(USBHostDevice *s, USBEndpoint *ep)
{
USBHostIsoRing *ring = g_new0(USBHostIsoRing, 1);
USBHostIsoXfer *xfer;
unsigned int packets = usb_host_iso_xfer_packets(s, ep);
unsigned int i;
/* FIXME: check interval (for now assume one xfer per frame) */
int packets = s->iso_urb_frames;
int i;
ring->host = s;
ring->ep = ep;
/* the ring holds isobufs * isobsize packets in all */
ring->nr_xfers = MAX(DIV_ROUND_UP(s->iso_urb_count * s->iso_urb_frames,
packets), 1);
QTAILQ_INIT(&ring->unused);
QTAILQ_INIT(&ring->inflight);
QTAILQ_INIT(&ring->copy);
QTAILQ_INSERT_TAIL(&s->isorings, ring, next);
for (i = 0; i < ring->nr_xfers; i++) {
for (i = 0; i < s->iso_urb_count; i++) {
xfer = g_new0(USBHostIsoXfer, 1);
xfer->ring = ring;
xfer->xfer = libusb_alloc_transfer(packets);
@@ -939,7 +681,6 @@ static void usb_host_iso_data_in(USBHostDevice *s, USBPacket *p)
USBHostIsoRing *ring;
USBHostIsoXfer *xfer;
bool disconnect = false;
bool hold = false;
int rc;
ring = usb_host_iso_find(s, p->ep);
@@ -947,29 +688,8 @@ static void usb_host_iso_data_in(USBHostDevice *s, USBPacket *p)
ring = usb_host_iso_alloc(s, p->ep);
}
/*
* A device sends a packet at each of its endpoint's service intervals
* from the first, but the host's transfers bring them only as each
* completes. Until two have, a controller that retries a NAKed packet
* holds the guest's first packet, and the stream starts a transfer of
* data ahead of the guest; other controllers get empty packets.
*/
if (!ring->primed) {
ring->primed = ring->nr_primed >= MIN(2, ring->nr_xfers) ||
!usb_bus_from_device(USB_DEVICE(s))->iso_nak_retry;
hold = !ring->primed;
}
/* copy data to guest */
xfer = hold ? NULL : QTAILQ_FIRST(&ring->copy);
if (xfer == NULL && usb_bus_from_device(USB_DEVICE(s))->iso_nak_retry) {
/*
* The guest has caught up with the device: QEMU ran its packets
* late, or ran them before handling transfers that had completed
* meanwhile. The device's packet is on its way; wait for it.
*/
hold = true;
}
xfer = QTAILQ_FIRST(&ring->copy);
if (xfer != NULL) {
if (usb_host_iso_data_copy(xfer, p)) {
QTAILQ_REMOVE(&ring->copy, xfer, next);
@@ -981,7 +701,7 @@ static void usb_host_iso_data_in(USBHostDevice *s, USBPacket *p)
while ((xfer = QTAILQ_FIRST(&ring->unused)) != NULL) {
QTAILQ_REMOVE(&ring->unused, xfer, next);
usb_host_iso_reset_xfer(xfer);
rc = usb_host_submit(s, xfer->xfer);
rc = libusb_submit_transfer(xfer->xfer);
if (rc != 0) {
usb_host_libusb_error("libusb_submit_transfer [iso]", rc);
QTAILQ_INSERT_TAIL(&ring->unused, xfer, next);
@@ -996,11 +716,6 @@ static void usb_host_iso_data_in(USBHostDevice *s, USBPacket *p)
QTAILQ_INSERT_TAIL(&ring->inflight, xfer, next);
}
if (hold && !QTAILQ_EMPTY(&ring->inflight)) {
/* usb_host_req_complete_iso wakes the endpoint */
p->status = USB_RET_NAK;
}
if (disconnect) {
usb_host_nodev(s);
}
@@ -1028,17 +743,6 @@ static void usb_host_iso_data_out(USBHostDevice *s, USBPacket *p)
xfer = QTAILQ_FIRST(&ring->unused);
if (xfer == NULL) {
trace_usb_host_iso_out_of_bufs(s->bus_num, s->addr, p->ep->nr);
/*
* Every buffer is on its way to the device. A controller that
* retries a NAKed packet holds this one until a transfer
* completes and wakes the endpoint; other controllers complete
* it with nothing sent.
*/
if (usb_bus_from_device(USB_DEVICE(s))->iso_nak_retry &&
!QTAILQ_EMPTY(&ring->inflight)) {
ring->out_waiting = true;
p->status = USB_RET_NAK;
}
return;
}
QTAILQ_REMOVE(&ring->unused, xfer, next);
@@ -1050,7 +754,7 @@ static void usb_host_iso_data_out(USBHostDevice *s, USBPacket *p)
if (QTAILQ_EMPTY(&ring->inflight)) {
/* wait until half of our buffers are filled
before kicking the iso out stream */
if (filled * 2 < ring->nr_xfers) {
if (filled*2 < s->iso_urb_count) {
return;
}
}
@@ -1059,7 +763,7 @@ static void usb_host_iso_data_out(USBHostDevice *s, USBPacket *p)
while ((xfer = QTAILQ_FIRST(&ring->copy)) != NULL &&
xfer->copy_complete) {
QTAILQ_REMOVE(&ring->copy, xfer, next);
rc = usb_host_submit(s, xfer->xfer);
rc = libusb_submit_transfer(xfer->xfer);
if (rc != 0) {
usb_host_libusb_error("libusb_submit_transfer [iso]", rc);
QTAILQ_INSERT_TAIL(&ring->unused, xfer, next);
@@ -1235,7 +939,6 @@ static void usb_host_ep_update(USBHostDevice *s)
usb_ep_set_max_packet_size(udev, pid, ep,
endp->wMaxPacketSize);
usb_ep_set_type(udev, pid, ep, type);
s->ep_interval[pid == USB_TOKEN_IN][ep] = endp->bInterval;
usb_ep_set_ifnum(udev, pid, ep, intf->bInterfaceNumber);
usb_ep_set_halted(udev, pid, ep, 0);
#ifdef HAVE_STREAMS
@@ -1366,9 +1069,7 @@ fail:
trace_usb_host_open_failure(bus_num, addr);
if (s->dh != NULL) {
usb_host_release_interfaces(s);
if (s->reset_on_close) {
libusb_reset_device(s->dh);
}
libusb_reset_device(s->dh);
usb_host_attach_kernel(s);
libusb_close(s->dh);
s->dh = NULL;
@@ -1379,7 +1080,6 @@ fail:
static void usb_host_abort_xfers(USBHostDevice *s)
{
USBHostDevice *other;
USBHostRequest *r, *rtmp;
int limit = 100;
@@ -1387,16 +1087,6 @@ static void usb_host_abort_xfers(USBHostDevice *s)
usb_host_req_abort(r);
}
if (QTAILQ_FIRST(&s->requests) != NULL) {
/*
* libusb reaps every device's completed URBs below: no other
* device's SET_INTERFACE call may still run, or anything wait for it.
*/
QTAILQ_FOREACH(other, &hostdevs, next) {
usb_host_set_interface_wait(other);
}
}
while (QTAILQ_FIRST(&s->requests) != NULL) {
struct timeval tv;
memset(&tv, 0, sizeof(tv));
@@ -1428,7 +1118,6 @@ static int usb_host_close(USBHostDevice *s)
trace_usb_host_close(s->bus_num, s->addr);
usb_host_set_interface_wait(s);
usb_host_abort_xfers(s);
usb_host_iso_free_all(s);
@@ -1437,9 +1126,7 @@ static int usb_host_close(USBHostDevice *s)
}
usb_host_release_interfaces(s);
if (s->reset_on_close) {
libusb_reset_device(s->dh);
}
libusb_reset_device(s->dh);
usb_host_attach_kernel(s);
libusb_close(s->dh);
s->dh = NULL;
@@ -1474,12 +1161,9 @@ static void usb_host_exit_notifier(struct Notifier *n, void *data)
USBHostDevice *s = container_of(n, USBHostDevice, exit);
if (s->dh) {
usb_host_set_interface_wait(s);
usb_host_abort_xfers(s);
usb_host_release_interfaces(s);
if (s->reset_on_close) {
libusb_reset_device(s->dh);
}
libusb_reset_device(s->dh);
usb_host_attach_kernel(s);
libusb_close(s->dh);
}
@@ -1531,7 +1215,6 @@ static void usb_host_realize(USBDevice *udev, Error **errp)
udev->auto_attach = 0;
QTAILQ_INIT(&s->requests);
QTAILQ_INIT(&s->isorings);
QSIMPLEQ_INIT(&s->deferred);
s->hostfd = -1;
#if LIBUSB_API_VERSION >= 0x01000107 && !defined(CONFIG_WIN32)
@@ -1621,15 +1304,10 @@ static void usb_host_cancel_packet(USBDevice *udev, USBPacket *p)
trace_usb_host_req_canceled(s->bus_num, s->addr, p);
if (s->setintf && s->setintf->p == p) {
s->setintf->p = NULL; /* the call still runs, and its result applies */
return;
}
r = usb_host_req_find(s, p);
if (r && r->p) {
r->p = NULL; /* mark as dead */
usb_host_cancel(s, r->xfer);
libusb_cancel_transfer(r->xfer);
}
}
@@ -1771,79 +1449,11 @@ static void usb_host_set_config(USBHostDevice *s, int config, USBPacket *p)
usb_host_ep_update(s);
}
static int usb_host_set_interface_worker(void *opaque)
{
USBHostSetIntf *job = opaque;
job->rc = libusb_set_interface_alt_setting(job->dh, job->iface, job->alt);
qemu_event_set(&job->done);
return 0;
}
/* Apply what the worker's call did, and complete the guest's request */
static void usb_host_set_interface_finish(USBHostSetIntf *job)
{
USBHostDevice *s = job->host;
USBDevice *udev = USB_DEVICE(s);
USBPacket *p = job->p;
assert(s->setintf == job && !job->finished);
s->setintf = NULL;
job->finished = true;
trace_usb_host_set_interface_done(s->bus_num, s->addr, job->iface,
job->alt, job->rc);
if (job->rc == 0) {
udev->altsetting[job->iface] = job->alt;
usb_host_ep_update(s);
} else {
usb_host_libusb_error("libusb_set_interface_alt_setting", job->rc);
}
/* what waited for the call, then libusb's events, whatever rc is */
usb_host_run_deferred(s);
usb_host_events_resume();
if (p) {
p->status = job->rc == 0 ? USB_RET_SUCCESS : USB_RET_STALL;
trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
usb_generic_async_ctrl_complete(udev, p);
}
if (job->rc == LIBUSB_ERROR_NO_DEVICE) {
usb_host_nodev(s);
}
}
static void usb_host_set_interface_complete(void *opaque, int ret)
{
USBHostSetIntf *job = opaque;
if (!job->finished) {
usb_host_set_interface_finish(job);
}
qemu_event_destroy(&job->done);
g_free(job);
}
/*
* Wait for the SET_INTERFACE request in flight, if any, and apply it, and make
* the submits and cancels that waited for it, before anything else changes
* the device's state or closes its handle.
*/
static void usb_host_set_interface_wait(USBHostDevice *s)
{
USBHostSetIntf *job = s->setintf;
if (job) {
qemu_event_wait(&job->done);
usb_host_set_interface_finish(job);
} else if (s->deferring) {
usb_host_run_deferred(s); /* from a completion that run made */
}
}
static void usb_host_set_interface(USBHostDevice *s, int iface, int alt,
USBPacket *p)
{
USBHostSetIntf *job;
USBDevice *udev = USB_DEVICE(s);
int rc;
trace_usb_host_set_interface(s->bus_num, s->addr, iface, alt);
@@ -1851,23 +1461,21 @@ static void usb_host_set_interface(USBHostDevice *s, int iface, int alt,
if (iface >= USB_MAX_INTERFACES) {
p->status = USB_RET_STALL;
trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
return;
}
job = g_new0(USBHostSetIntf, 1);
job->host = s;
job->p = p;
job->dh = s->dh;
job->iface = iface;
job->alt = alt;
qemu_event_init(&job->done, false);
s->setintf = job;
s->deferring = true;
usb_host_events_pause();
thread_pool_submit_aio(usb_host_set_interface_worker, job,
usb_host_set_interface_complete, job);
p->status = USB_RET_ASYNC;
rc = libusb_set_interface_alt_setting(s->dh, iface, alt);
if (rc != 0) {
usb_host_libusb_error("libusb_set_interface_alt_setting", rc);
p->status = USB_RET_STALL;
if (rc == LIBUSB_ERROR_NO_DEVICE) {
usb_host_nodev(s);
}
return;
}
udev->altsetting[iface] = alt;
usb_host_ep_update(s);
}
static void usb_host_handle_control(USBDevice *udev, USBPacket *p,
@@ -1886,12 +1494,6 @@ static void usb_host_handle_control(USBDevice *udev, USBPacket *p,
return;
}
/*
* Control requests reach the device in the guest's order. One waits here
* only when the guest canceled a SET_INTERFACE that still runs.
*/
usb_host_set_interface_wait(s);
switch (request) {
case DeviceOutRequest | USB_REQ_SET_ADDRESS:
usb_host_set_address(s, value);
@@ -1905,6 +1507,7 @@ static void usb_host_handle_control(USBDevice *udev, USBPacket *p,
case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
usb_host_set_interface(s, index, value, p);
trace_usb_host_req_emulated(s->bus_num, s->addr, p, p->status);
return;
case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:
@@ -1936,7 +1539,7 @@ static void usb_host_handle_control(USBDevice *udev, USBPacket *p,
libusb_fill_control_transfer(r->xfer, s->dh, r->buffer,
usb_host_req_complete_ctrl, r,
CONTROL_TIMEOUT);
rc = usb_host_submit(s, r->xfer);
rc = libusb_submit_transfer(r->xfer);
if (rc != 0) {
/*
* Free the request to avoid a dangling r->p pointer.
@@ -2037,7 +1640,7 @@ static void usb_host_handle_data(USBDevice *udev, USBPacket *p)
return;
}
rc = usb_host_submit(s, r->xfer);
rc = libusb_submit_transfer(r->xfer);
if (rc != 0) {
/*
* Free the request to avoid a dangling r->p pointer.
@@ -2079,7 +1682,6 @@ static void usb_host_handle_reset(USBDevice *udev)
trace_usb_host_reset(s->bus_num, s->addr);
usb_host_set_interface_wait(s);
rc = libusb_reset_device(s->dh);
if (rc != 0) {
usb_host_nodev(s);
@@ -2094,7 +1696,6 @@ static int usb_host_alloc_streams(USBDevice *udev, USBEndpoint **eps,
unsigned char endpoints[30];
int i, rc;
usb_host_set_interface_wait(s);
for (i = 0; i < nr_eps; i++) {
endpoints[i] = eps[i]->nr;
if (eps[i]->pid == USB_TOKEN_IN) {
@@ -2124,7 +1725,6 @@ static void usb_host_free_streams(USBDevice *udev, USBEndpoint **eps,
unsigned char endpoints[30];
int i;
usb_host_set_interface_wait(s);
for (i = 0; i < nr_eps; i++) {
endpoints[i] = eps[i]->nr;
if (eps[i]->pid == USB_TOKEN_IN) {
@@ -2205,8 +1805,6 @@ static const Property usb_host_dev_properties[] = {
allow_one_guest_reset, true),
DEFINE_PROP_BOOL("guest-resets-all", USBHostDevice,
allow_all_guest_resets, false),
DEFINE_PROP_BOOL("reset-on-close", USBHostDevice,
reset_on_close, true),
DEFINE_PROP_UINT32("loglevel", USBHostDevice, loglevel,
LIBUSB_LOG_LEVEL_WARNING),
DEFINE_PROP_BIT("pipeline", USBHostDevice, options,
-1
View File
@@ -38,7 +38,6 @@ system_ss.add(when: 'CONFIG_XLNX_USB_SUBSYS', if_true: files('xlnx-usb-subsystem
system_ss.add(when: 'CONFIG_USB_HUB', if_true: files('dev-hub.c'))
system_ss.add(when: 'CONFIG_USB_HID', if_true: files('dev-hid.c'))
system_ss.add(when: 'CONFIG_USB_TABLET_WACOM', if_true: files('dev-wacom.c'))
system_ss.add(when: 'CONFIG_USB_TABLET_VMAPPLE', if_true: files('dev-vmapple-tablet.c'))
system_ss.add(when: 'CONFIG_USB_STORAGE_CORE', if_true: files('dev-storage.c'))
system_ss.add(when: 'CONFIG_USB_STORAGE_BOT', if_true: files('dev-storage-bot.c'))
system_ss.add(when: 'CONFIG_USB_STORAGE_CLASSIC', if_true: files('dev-storage-classic.c'))
-9
View File
@@ -162,8 +162,6 @@ usb_xhci_doorbell_read(uint32_t off, uint32_t val) "off 0x%04x, ret 0x%08x"
usb_xhci_oper_write(uint32_t off, uint32_t val) "off 0x%04x, val 0x%08x"
usb_xhci_port_write(uint32_t port, uint32_t off, uint32_t val) "port %d, off 0x%04x, val 0x%08x"
usb_xhci_runtime_write(uint32_t off, uint32_t val) "off 0x%04x, val 0x%08x"
usb_xhci_imod(int v, uint32_t imodi, uint32_t imodc) "intr %d, imodi %u, imodc %u"
usb_xhci_set_ltv(uint32_t belt) "belt 0x%03x"
usb_xhci_doorbell_write(uint32_t off, uint32_t val) "off 0x%04x, val 0x%08x"
usb_xhci_irq_intx(uint32_t level) "level %d"
usb_xhci_irq_msi(uint32_t nr) "nr %d"
@@ -334,7 +332,6 @@ usb_host_detach_kernel(int bus, int addr, int interface) "dev %d:%d, if %d"
usb_host_set_address(int bus, int addr, int config) "dev %d:%d, address %d"
usb_host_set_config(int bus, int addr, int config) "dev %d:%d, config %d"
usb_host_set_interface(int bus, int addr, int interface, int alt) "dev %d:%d, interface %d, alt %d"
usb_host_set_interface_done(int bus, int addr, int interface, int alt, int rc) "dev %d:%d, interface %d, alt %d, rc %d"
usb_host_claim_interface(int bus, int addr, int config, int interface) "dev %d:%d, config %d, if %d"
usb_host_release_interface(int bus, int addr, int interface) "dev %d:%d, if %d"
usb_host_req_control(int bus, int addr, void *p, int req, int value, int index) "dev %d:%d, packet %p, req 0x%x, value %d, index %d"
@@ -398,9 +395,3 @@ aspeed_udc_handle_data(int ep_nr, const char *dir, uint32_t iov, int ep_idx) "ep
aspeed_udc_ep_data_in(unsigned ep, uint32_t rptr, uint32_t wptr, uint32_t iov) "ep %u, rptr %u, wptr %u, iov %u"
aspeed_udc_ep_data_out(unsigned ep, uint32_t wptr, uint32_t avail, uint32_t iov) "ep %u, wptr %u, avail %u, iov %u"
aspeed_udc_ep_ack(unsigned ep) "ep %u"
# dev-vmapple-tablet.c
usb_vmapple_tablet_report(uint8_t buttons, uint16_t x, uint16_t y, int16_t wheel, int16_t pan, int32_t scroll_y, int32_t scroll_x, uint16_t phases) "buttons 0x%x x %u y %u wheel %d pan %d scroll y %d x %d phases 0x%x"
usb_vmapple_tablet_queue_full(void) "queue full"
usb_vmapple_tablet_get_report(uint8_t type, uint8_t id) "type %u id %u"
usb_vmapple_tablet_set_report(uint8_t id, uint8_t value) "feature %u value %u"
-25
View File
@@ -36,12 +36,9 @@ DECLARE_INSTANCE_CHECKER(VirtIONetPCI, VIRTIO_NET_PCI,
struct VirtIONetPCI {
VirtIOPCIProxy parent_obj;
VirtIONet vdev;
bool ascending_capabilities;
};
static const Property virtio_net_properties[] = {
DEFINE_PROP_BOOL("x-ascending-capabilities", VirtIONetPCI,
ascending_capabilities, false),
DEFINE_PROP_BIT("ioeventfd", VirtIOPCIProxy, flags,
VIRTIO_PCI_FLAG_USE_IOEVENTFD_BIT, true),
DEFINE_PROP_UINT32("vectors", VirtIOPCIProxy, nvectors,
@@ -64,28 +61,6 @@ static void virtio_net_pci_realize(VirtIOPCIProxy *vpci_dev, Error **errp)
virtio_net_set_netclient_name(&dev->vdev, qdev->id,
object_get_typename(OBJECT(qdev)));
qdev_realize(vdev, BUS(&vpci_dev->bus), errp);
if (dev->ascending_capabilities && qdev_is_realized(vdev)) {
uint8_t *config = vpci_dev->pci_dev.config;
bool capabilities[PCI_CONFIG_SPACE_SIZE] = { false };
unsigned offset, previous = PCI_CAPABILITY_LIST;
/* Local Golden Gate workaround: its cached and fallback capability
* lookups revisit PCI_CFG and NOTIFY forever on descending lists.
* Keep capability contents and offsets; only reorder the links. */
for (offset = config[PCI_CAPABILITY_LIST]; offset;
offset = config[offset + PCI_CAP_LIST_NEXT]) {
capabilities[offset] = true;
}
for (offset = PCI_CONFIG_HEADER_SIZE; offset < PCI_CONFIG_SPACE_SIZE;
offset++) {
if (capabilities[offset]) {
config[previous] = offset;
previous = offset + PCI_CAP_LIST_NEXT;
}
}
config[previous] = 0;
}
}
static void virtio_net_pci_class_init(ObjectClass *klass, const void *data)
+4 -8
View File
@@ -9,17 +9,14 @@ config VMAPPLE_BDIF
config VMAPPLE_CFG
bool
config VMAPPLE_RTC
bool
config VMAPPLE_VIRTIO_BLK
bool
config VMAPPLE
bool
depends on AARCH64
depends on TCG || HVF
default y
depends on ARM
depends on HVF
default y if ARM
imply PCI_DEVICES
select ARM_GICV3
select PLATFORM_BUS
@@ -29,9 +26,8 @@ config VMAPPLE
select PL031 # RTC
select PL061 # GPIO
select PVPANIC_MMIO
select UNIMP
select VMAPPLE_AES
select VMAPPLE_BDIF
select VMAPPLE_CFG
select VMAPPLE_RTC
select MAC_PVG_MMIO
select VMAPPLE_VIRTIO_BLK
+1 -56
View File
@@ -18,7 +18,6 @@
#include "hw/core/sysbus.h"
#include "hw/vmapple/vmapple.h"
#include "migration/vmstate.h"
#include "qapi/error.h"
#include "qemu/cutils.h"
#include "qemu/log.h"
#include "qemu/module.h"
@@ -254,7 +253,7 @@ static bool cmd_iv(AESState *s)
static void dump_data(const char *desc, const void *p, size_t len)
{
#define MAX_LEN 0x1000
static const size_t MAX_LEN = 0x1000;
char hex[MAX_LEN * 2 + 1] = "";
if (len > MAX_LEN) {
@@ -263,7 +262,6 @@ static void dump_data(const char *desc, const void *p, size_t len)
qemu_hexdump_to_buffer(hex, sizeof(hex), p, len);
trace_aes_dump_data(desc, hex);
#undef MAX_LEN
}
static bool cmd_data(AESState *s)
@@ -537,16 +535,6 @@ static const MemoryRegionOps aes2_ops = {
},
};
/*
* A guest reboot resets the engine as it was at power-on, with its FIFO,
* keys, IVs and mode, and lowers its interrupt. A guest that panics in the
* middle of a command leaves words of it in the FIFO: kept, they become the
* head of the next boot's first command, which the engine then fails as
* invalid (REG_IRQ_STATUS_INVALID_CMD), and macOS panics on that
* ("AES Error: IntStatus 0x4"). The interrupt line keeps its level across
* a reset unless the device lowers it, and an in-kernel GIC (HVF's, KVM's)
* then raises the line's interrupt in the next boot.
*/
static void aes_reset(Object *obj, ResetType type)
{
AESState *s = APPLE_AES(obj);
@@ -556,14 +544,6 @@ static void aes_reset(Object *obj, ResetType type)
s->irq_status = 0;
s->irq_enable = 0;
s->watermark = 0;
s->flag_info = 0;
memset(s->fifo, 0, sizeof(s->fifo));
s->fifo_idx = 0;
memset(s->key, 0, sizeof(s->key));
memset(s->iv, 0, sizeof(s->iv));
s->is_encrypt = false;
s->block_mode = QCRYPTO_CIPHER_MODE_ECB;
aes_update_irq(s);
}
static void aes_init(Object *obj)
@@ -578,45 +558,10 @@ static void aes_init(Object *obj)
s->as = &address_space_memory;
}
/*
* The guest's DATA commands run on QEMU's ciphers. A build that found no
* crypto library (gnutls, nettle or libgcrypt) has none: each DATA command
* then fails, stays at the head of the FIFO, and the guest waits for it
* forever. A macOS guest sends one as it mounts its root volume, so refuse
* to start rather than hang there.
*/
static void aes_realize(DeviceState *dev, Error **errp)
{
static const QCryptoCipherAlgo algs[] = {
QCRYPTO_CIPHER_ALGO_AES_128,
QCRYPTO_CIPHER_ALGO_AES_192,
QCRYPTO_CIPHER_ALGO_AES_256,
};
static const QCryptoCipherMode modes[] = {
QCRYPTO_CIPHER_MODE_ECB,
QCRYPTO_CIPHER_MODE_CBC,
};
for (size_t a = 0; a < ARRAY_SIZE(algs); a++) {
for (size_t m = 0; m < ARRAY_SIZE(modes); m++) {
if (!qcrypto_cipher_supports(algs[a], modes[m])) {
error_setg(errp, "%s needs %s in %s mode, which this QEMU "
"lacks: build it with a crypto library (gnutls, "
"nettle or libgcrypt)", TYPE_APPLE_AES,
QCryptoCipherAlgo_str(algs[a]),
QCryptoCipherMode_str(modes[m]));
return;
}
}
}
}
static void aes_class_init(ObjectClass *klass, const void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
ResettableClass *rc = RESETTABLE_CLASS(klass);
dc->realize = aes_realize;
rc->phases.hold = aes_reset;
}
+7 -7
View File
@@ -46,13 +46,13 @@ typedef struct VMAppleCfg {
uint8_t pad4[2];
uint8_t reserved[0xa0]; /* 0x060 */
uint32_t cpu_ids[0x80]; /* 0x100 */
uint8_t scratch[0x200]; /* 0x300 */
char serial[32]; /* 0x500 */
char unk8[32]; /* 0x520 */
char model[32]; /* 0x540 */
uint8_t unk9[32]; /* 0x560 */
uint32_t unk10; /* 0x580 */
char soc_name[32]; /* 0x584 */
uint8_t scratch[0x200]; /* 0x180 */
char serial[32]; /* 0x380 */
char unk8[32]; /* 0x3a0 */
char model[32]; /* 0x3c0 */
uint8_t unk9[32]; /* 0x3e0 */
uint32_t unk10; /* 0x400 */
char soc_name[32]; /* 0x404 */
} VMAppleCfg;
struct VMAppleCfgState {
-1
View File
@@ -3,6 +3,5 @@
system_ss.add(when: 'CONFIG_VMAPPLE_AES', if_true: files('aes.c'))
system_ss.add(when: 'CONFIG_VMAPPLE_BDIF', if_true: files('bdif.c'))
system_ss.add(when: 'CONFIG_VMAPPLE_CFG', if_true: files('cfg.c'))
system_ss.add(when: 'CONFIG_VMAPPLE_RTC', if_true: files('rtc.c'))
system_ss.add(when: 'CONFIG_VMAPPLE_VIRTIO_BLK', if_true: files('virtio-blk.c'))
specific_ss.add(when: 'CONFIG_VMAPPLE', if_true: files('vmapple.c'))
-196
View File
@@ -1,196 +0,0 @@
/*
* VMApple RTC
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
/*
* Beside its PL031, Virtualization.framework's machine has a clock that the
* guest's device tree lists as avp-rtc ("avp,rtc"), and that macOS drives
* with its AppleVirtualPlatformRTC driver. The driver reads the device's
* counter of microseconds and keeps the offset from it to calendar time in
* NVRAM, as com.apple.System.rtc-offset, which it sets whenever the guest
* sets its clock. It gives that offset to userspace as
* kern.monotoniclock_offset_usecs, from which timed tells whether the clock
* was reset. macOS's PL031 driver has no offset, so on the PL031 alone timed
* takes the clock for reset on every boot, and sets it back to the last
* write to the guest's filesystem.
*
* The counter counts microseconds of QEMU's rtc clock from the Unix epoch,
* as the PL031 counts seconds, so -rtc base= and clock= apply to both. The
* driver uses 64-bit accesses; the registers are:
*
* 0x00 COUNTER read only, the counter
* 0x18 CTRL bit 0 enables the clock; reads back what was written
* 0x20 INT_EN interrupt enables; reads back what was written
* 0x30 INT_STAT pending interrupts; always 0
* 0x38 INT_CLR write ones to clear pending interrupts
* 0x40 ID reads 0xf001
*
* The driver passes interrupts 1 and 2 on to its user clients. Nothing here
* raises them, so the device has no interrupt line. iBoot keeps avp-rtc in
* the device tree and drops pl031-rtc when ID reads 0xf001, and the reverse
* otherwise.
*/
#include "qemu/osdep.h"
#include "trace.h"
#include "hw/core/sysbus.h"
#include "hw/vmapple/vmapple.h"
#include "qemu/bitops.h"
#include "qemu/cutils.h"
#include "qemu/log.h"
#include "qemu/module.h"
#include "qemu/timer.h"
#include "system/rtc.h"
#include "system/system.h"
OBJECT_DECLARE_SIMPLE_TYPE(VMAppleRTCState, VMAPPLE_RTC)
#define VMAPPLE_RTC_SIZE 0x1000
#define REG_COUNTER 0x00
#define REG_CTRL 0x18
#define REG_INT_EN 0x20
#define REG_INT_STAT 0x30
#define REG_INT_CLR 0x38
#define REG_ID 0x40
#define VMAPPLE_RTC_ID 0xf001
struct VMAppleRTCState {
SysBusDevice parent_obj;
MemoryRegion iomem;
/* Seconds from the rtc clock to the guest's time, as the PL031 keeps */
int64_t tick_offset;
uint64_t ctrl;
uint64_t int_en;
};
static uint64_t vmapple_rtc_usecs(VMAppleRTCState *s)
{
int64_t now = qemu_clock_get_ns(rtc_clock);
return (s->tick_offset * NANOSECONDS_PER_SECOND + now) / SCALE_US;
}
static uint64_t vmapple_rtc_reg(VMAppleRTCState *s, hwaddr reg)
{
switch (reg) {
case REG_COUNTER:
return vmapple_rtc_usecs(s);
case REG_CTRL:
return s->ctrl;
case REG_INT_EN:
return s->int_en;
case REG_INT_STAT:
case REG_INT_CLR:
return 0;
case REG_ID:
return VMAPPLE_RTC_ID;
default:
qemu_log_mask(LOG_UNIMP, "%s: unknown register 0x%" HWADDR_PRIx "\n",
__func__, reg);
return 0;
}
}
static uint64_t vmapple_rtc_read(void *opaque, hwaddr offset, unsigned size)
{
VMAppleRTCState *s = opaque;
unsigned shift = (offset & 7) * BITS_PER_BYTE;
uint64_t val;
val = extract64(vmapple_rtc_reg(s, offset & ~7ULL), shift,
size * BITS_PER_BYTE);
trace_vmapple_rtc_read(offset, size, val);
return val;
}
static void vmapple_rtc_write(void *opaque, hwaddr offset, uint64_t val,
unsigned size)
{
VMAppleRTCState *s = opaque;
unsigned shift = (offset & 7) * BITS_PER_BYTE;
unsigned len = size * BITS_PER_BYTE;
trace_vmapple_rtc_write(offset, size, val);
switch (offset & ~7ULL) {
case REG_CTRL:
s->ctrl = deposit64(s->ctrl, shift, len, val);
break;
case REG_INT_EN:
s->int_en = deposit64(s->int_en, shift, len, val);
break;
case REG_INT_CLR:
/* No interrupt is ever pending. */
break;
default:
qemu_log_mask(LOG_GUEST_ERROR,
"%s: write to read-only or unknown register 0x%"
HWADDR_PRIx "\n", __func__, offset);
break;
}
}
static const MemoryRegionOps vmapple_rtc_ops = {
.read = vmapple_rtc_read,
.write = vmapple_rtc_write,
.endianness = DEVICE_LITTLE_ENDIAN,
.valid = {
.min_access_size = 4,
.max_access_size = 8,
},
/* Whole, so that the counter's halves come from one reading. */
.impl = {
.min_access_size = 4,
.max_access_size = 8,
},
};
static void vmapple_rtc_reset(Object *obj, ResetType type)
{
VMAppleRTCState *s = VMAPPLE_RTC(obj);
s->ctrl = 0;
s->int_en = 0;
}
static void vmapple_rtc_init(Object *obj)
{
VMAppleRTCState *s = VMAPPLE_RTC(obj);
struct tm tm;
memory_region_init_io(&s->iomem, obj, &vmapple_rtc_ops, s, "vmapple-rtc",
VMAPPLE_RTC_SIZE);
sysbus_init_mmio(SYS_BUS_DEVICE(obj), &s->iomem);
qemu_get_timedate(&tm, 0);
s->tick_offset = mktimegm(&tm) -
qemu_clock_get_ns(rtc_clock) / NANOSECONDS_PER_SECOND;
}
static void vmapple_rtc_class_init(ObjectClass *klass, const void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
ResettableClass *rc = RESETTABLE_CLASS(klass);
dc->desc = "VMApple RTC";
rc->phases.hold = vmapple_rtc_reset;
}
static const TypeInfo vmapple_rtc_info = {
.name = TYPE_VMAPPLE_RTC,
.parent = TYPE_SYS_BUS_DEVICE,
.instance_size = sizeof(VMAppleRTCState),
.instance_init = vmapple_rtc_init,
.class_init = vmapple_rtc_class_init,
};
static void vmapple_rtc_register_types(void)
{
type_register_static(&vmapple_rtc_info);
}
type_init(vmapple_rtc_register_types)
-4
View File
@@ -19,7 +19,3 @@ aes_dump_data(const char *desc, const char *hex) "%s%s"
bdif_read(uint64_t offset, uint32_t size, uint64_t value) "offset=0x%"PRIx64" size=0x%x value=0x%"PRIx64
bdif_write(uint64_t offset, uint32_t size, uint64_t value) "offset=0x%"PRIx64" size=0x%x value=0x%"PRIx64
bdif_vblk_read(const char *dev, uint64_t addr, uint64_t offset, uint32_t len, int r) "dev=%s addr=0x%"PRIx64" off=0x%"PRIx64" size=0x%x r=%d"
# rtc.c
vmapple_rtc_read(uint64_t offset, uint32_t size, uint64_t value) "offset=0x%"PRIx64" size=0x%x value=0x%"PRIx64
vmapple_rtc_write(uint64_t offset, uint32_t size, uint64_t value) "offset=0x%"PRIx64" size=0x%x value=0x%"PRIx64
-39
View File
@@ -16,7 +16,6 @@
*/
#include "qemu/osdep.h"
#include "hw/pci/pci.h"
#include "hw/vmapple/vmapple.h"
#include "hw/virtio/virtio-blk.h"
#include "hw/virtio/virtio-pci.h"
@@ -45,8 +44,6 @@ typedef struct VMAppleVirtIOBlk {
OBJECT_DECLARE_SIMPLE_TYPE(VMAppleVirtIOBlkPCI, VMAPPLE_VIRTIO_BLK_PCI)
#define VIRTIO_BLK_T_APPLE_BARRIER 0x10000
#define VMAPPLE_PCI_VNDR_SIZE 14
#define VMAPPLE_PCI_VNDR_DISABLE_ENCRYPTION 1
static bool vmapple_virtio_blk_handle_unknown_request(VirtIOBlockReq *req,
MultiReqBuffer *mrb,
@@ -128,10 +125,6 @@ static void vmapple_virtio_blk_pci_realize(VirtIOPCIProxy *vpci_dev, Error **err
VMAppleVirtIOBlkPCI *dev = VMAPPLE_VIRTIO_BLK_PCI(vpci_dev);
DeviceState *vdev = DEVICE(&dev->vdev);
VirtIOBlkConf *conf = &dev->vdev.parent_obj.conf;
int offset;
uint8_t capabilities[PCI_CONFIG_SPACE_SIZE] = { 0 };
uint8_t *config = vpci_dev->pci_dev.config;
int previous = PCI_CAPABILITY_LIST;
if (dev->variant == VM_APPLE_VIRTIO_BLK_VARIANT_UNSPECIFIED) {
error_setg(errp, "vmapple virtio block device variant unspecified");
@@ -169,38 +162,6 @@ static void vmapple_virtio_blk_pci_realize(VirtIOPCIProxy *vpci_dev, Error **err
pci_config_set_vendor_id(vpci_dev->pci_dev.config, PCI_VENDOR_ID_APPLE);
pci_config_set_device_id(vpci_dev->pci_dev.config,
PCI_DEVICE_ID_APPLE_VIRTIO_BLK);
pci_set_word(vpci_dev->pci_dev.config + PCI_SUBSYSTEM_ID, 0x1100);
/* A non-FileVault Golden Gate root disk requires Apple's vendor
* capability to advertise that transport encryption is disabled. */
offset = pci_add_capability(&vpci_dev->pci_dev, PCI_CAP_ID_VNDR, 0,
VMAPPLE_PCI_VNDR_SIZE, errp);
if (offset < 0) {
return;
}
pci_set_byte(vpci_dev->pci_dev.config + offset + 2,
VMAPPLE_PCI_VNDR_SIZE);
pci_set_byte(vpci_dev->pci_dev.config + offset + 3, 9);
pci_set_word(vpci_dev->pci_dev.config + offset + 4, PCI_VENDOR_ID_APPLE);
pci_set_byte(vpci_dev->pci_dev.config + offset + 6,
VMAPPLE_PCI_VNDR_DISABLE_ENCRYPTION);
/* Golden Gate's cached capability lookup and its fallback disagree on
* descending lists: the storage probe alternates between the final
* vendor capability and VIRTIO_PCI_CAP_PCI_CFG forever. Keep the same
* capabilities and offsets, but enumerate them in address order. */
for (offset = config[PCI_CAPABILITY_LIST]; offset;
offset = config[offset + PCI_CAP_LIST_NEXT]) {
capabilities[offset] = 1;
}
for (offset = PCI_CONFIG_HEADER_SIZE; offset < PCI_CONFIG_SPACE_SIZE;
offset++) {
if (capabilities[offset]) {
config[previous] = offset;
previous = offset + PCI_CAP_LIST_NEXT;
}
}
config[previous] = 0;
}
static void vmapple_virtio_blk_pci_class_init(ObjectClass *klass,
+27 -281
View File
@@ -36,10 +36,8 @@
#include "hw/intc/arm_gic.h"
#include "hw/intc/arm_gicv3_common.h"
#include "hw/misc/pvpanic.h"
#include "hw/misc/unimp.h"
#include "hw/pci-host/gpex.h"
#include "hw/usb/hcd-xhci-pci.h"
#include "hw/virtio/virtio-net.h"
#include "hw/virtio/virtio-pci.h"
#include "hw/vmapple/vmapple.h"
#include "net/net.h"
@@ -49,15 +47,11 @@
#include "qobject/qlist.h"
#include "standard-headers/linux/input.h"
#include "system/hvf.h"
#include "system/kvm.h"
#include "system/reset.h"
#include "system/runstate.h"
#include "system/system.h"
#include "system/tcg.h"
#include "target/arm/gtimer.h"
#include "target/arm/cpu.h"
#include "target/arm/internals.h"
#include "target/arm/kvm_arm.h"
struct VMAppleMachineState {
MachineState parent;
@@ -74,10 +68,6 @@ struct VMAppleMachineState {
MemoryRegion fw_mr;
MemoryRegion ecam_alias;
uint64_t uuid;
char *tablet;
/* The room past RAM (vmapple_pool_room) */
uint64_t pool_room_base;
uint64_t pool_room_size;
};
#define TYPE_VMAPPLE_MACHINE MACHINE_TYPE_NAME("vmapple")
@@ -86,17 +76,12 @@ OBJECT_DECLARE_SIMPLE_TYPE(VMAppleMachineState, VMAPPLE_MACHINE)
/* Number of external interrupt lines to configure the GIC with */
#define NUM_IRQS 256
/* The most guest physical address bits the machine asks of HVF */
#define VMAPPLE_PHYS_BITS 40
enum {
VMAPPLE_FIRMWARE,
VMAPPLE_CONFIG,
VMAPPLE_DMA_CONFIG,
VMAPPLE_MEM,
VMAPPLE_GIC_DIST,
VMAPPLE_GIC_REDIST,
VMAPPLE_GICV2M,
VMAPPLE_UART,
VMAPPLE_RTC,
VMAPPLE_PCIE,
@@ -104,48 +89,45 @@ enum {
VMAPPLE_PCIE_ECAM,
VMAPPLE_GPIO,
VMAPPLE_PVPANIC,
VMAPPLE_APV_GFX,
VMAPPLE_APV_IOSFC,
VMAPPLE_AES_1,
VMAPPLE_AES_2,
VMAPPLE_BDOOR,
VMAPPLE_AVP_RTC,
VMAPPLE_MEMMAP_LAST,
};
static const MemMapEntry memmap[] = {
[VMAPPLE_FIRMWARE] = { 0x00100000, 0x00100000 },
[VMAPPLE_CONFIG] = { 0x00400000, 0x00010000 },
[VMAPPLE_DMA_CONFIG] = { 0x004ffff8, 0x00000008 },
[VMAPPLE_GIC_DIST] = { 0x10000000, 0x00010000 },
[VMAPPLE_GIC_REDIST] = { 0x10010000, 0x00400000 },
[VMAPPLE_GICV2M] = { 0x1FFF0000, 0x00010000 },
[VMAPPLE_UART] = { 0x20010000, 0x00010000 },
[VMAPPLE_RTC] = { 0x20050000, 0x00001000 },
[VMAPPLE_GPIO] = { 0x20060000, 0x00001000 },
[VMAPPLE_PVPANIC] = { 0x20070000, 0x00000002 },
[VMAPPLE_BDOOR] = { 0x30000000, 0x00200000 },
[VMAPPLE_APV_GFX] = { 0x30200000, 0x00010000 },
[VMAPPLE_APV_IOSFC] = { 0x30210000, 0x00010000 },
[VMAPPLE_AES_1] = { 0x30220000, 0x00004000 },
[VMAPPLE_AES_2] = { 0x30230000, 0x00004000 },
[VMAPPLE_AVP_RTC] = { 0x30240000, 0x00001000 },
[VMAPPLE_PCIE_ECAM] = { 0x40000000, 0x10000000 },
/*
* macOS places every BAR below 4 GiB, aligned to its size, so the
* window runs up to 4 GiB and RAM starts there.
*/
[VMAPPLE_PCIE_MMIO] = { 0x50000000, 0xb0000000 },
[VMAPPLE_PCIE_MMIO] = { 0x50000000, 0x1fff0000 },
/* Actual RAM size depends on configuration */
[VMAPPLE_MEM] = { 0x100000000ULL, GiB},
[VMAPPLE_MEM] = { 0x70000000ULL, GiB},
};
static const int irqmap[] = {
[VMAPPLE_UART] = 1,
[VMAPPLE_RTC] = 2,
[VMAPPLE_GPIO] = 0x5,
[VMAPPLE_APV_IOSFC] = 0x10,
[VMAPPLE_APV_GFX] = 0x11,
[VMAPPLE_AES_1] = 0x12,
[VMAPPLE_PCIE] = 0x20,
[VMAPPLE_GICV2M] = 0x80
};
#define GPEX_NUM_IRQS 16
@@ -183,21 +165,6 @@ static void create_bdif(VMAppleMachineState *vms, MemoryRegion *mem)
sysbus_realize_and_unref(bdif_sb, &error_fatal);
}
/*
* macOS's platform driver reads a register of its configuration by writing
* the physical address of a request to 0x004ffff8, an address its code holds
* rather than one the device tree gives. Virtualization.framework's machine
* answers the request. This machine leaves it unanswered, as an address with
* no device is under HVF, and the driver goes on without the register; under
* TCG the write would be an external abort.
*/
static void create_dma_config(VMAppleMachineState *vms)
{
create_unimplemented_device("vmapple.dma-config",
vms->memmap[VMAPPLE_DMA_CONFIG].base,
vms->memmap[VMAPPLE_DMA_CONFIG].size);
}
static void create_pvpanic(VMAppleMachineState *vms, MemoryRegion *mem)
{
SysBusDevice *pvpanic;
@@ -236,6 +203,20 @@ static bool create_cfg(VMAppleMachineState *vms, MemoryRegion *mem,
return true;
}
static void create_gfx(VMAppleMachineState *vms, MemoryRegion *mem)
{
int irq_gfx = vms->irqmap[VMAPPLE_APV_GFX];
int irq_iosfc = vms->irqmap[VMAPPLE_APV_IOSFC];
SysBusDevice *gfx;
gfx = SYS_BUS_DEVICE(qdev_new("apple-gfx-mmio"));
sysbus_mmio_map(gfx, 0, vms->memmap[VMAPPLE_APV_GFX].base);
sysbus_mmio_map(gfx, 1, vms->memmap[VMAPPLE_APV_IOSFC].base);
sysbus_connect_irq(gfx, 0, qdev_get_gpio_in(vms->gic, irq_gfx));
sysbus_connect_irq(gfx, 1, qdev_get_gpio_in(vms->gic, irq_iosfc));
sysbus_realize_and_unref(gfx, &error_fatal);
}
static void create_aes(VMAppleMachineState *vms, MemoryRegion *mem)
{
int irq = vms->irqmap[VMAPPLE_AES_1];
@@ -304,27 +285,6 @@ static void create_gic(VMAppleMachineState *vms, MemoryRegion *mem)
}
}
#define NUM_GICV2M_SPIS 128
static void create_gicv2m(VMAppleMachineState *vms)
{
int i;
int irq = vms->irqmap[VMAPPLE_GICV2M];
DeviceState *dev;
dev = qdev_new("arm-gicv2m");
qdev_prop_set_uint32(dev, "base-spi", irq);
qdev_prop_set_uint32(dev, "num-spi", NUM_GICV2M_SPIS);
qdev_prop_set_uint32(dev, "macos-compat", 1);
sysbus_realize_and_unref(SYS_BUS_DEVICE(dev), &error_fatal);
sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, vms->memmap[VMAPPLE_GICV2M].base);
for (i = 0; i < NUM_GICV2M_SPIS; i++) {
sysbus_connect_irq(SYS_BUS_DEVICE(dev), i,
qdev_get_gpio_in(vms->gic, irq + i));
}
}
static void create_uart(const VMAppleMachineState *vms, int uart,
MemoryRegion *mem, Chardev *chr)
{
@@ -346,13 +306,6 @@ static void create_rtc(const VMAppleMachineState *vms)
int irq = vms->irqmap[VMAPPLE_RTC];
sysbus_create_simple("pl031", base, qdev_get_gpio_in(vms->gic, irq));
/*
* macOS keeps its clock's offset to calendar time only with the second
* clock, avp-rtc in its device tree, so the guest needs it to keep time
* from one boot to the next.
*/
sysbus_create_simple(TYPE_VMAPPLE_RTC, vms->memmap[VMAPPLE_AVP_RTC].base,
NULL);
}
static DeviceState *gpio_key_dev;
@@ -443,8 +396,8 @@ static void create_pcie(VMAppleMachineState *vms)
&vms->ecam_alias);
/*
* Map the MMIO window from [0x50000000-0xffffffff] in PCI space into
* system address space at [0x50000000-0xffffffff].
* Map the MMIO window from [0x50000000-0x7fff0000] in PCI space into
* system address space at [0x50000000-0x7fff0000].
*/
mmio_alias = g_new0(MemoryRegion, 1);
mmio_reg = sysbus_mmio_get_region(SYS_BUS_DEVICE(dev), 1);
@@ -473,9 +426,7 @@ static void create_pcie(VMAppleMachineState *vms)
usb_bus = USB_BUS(object_resolve_type_unambiguous(TYPE_USB_BUS,
&error_fatal));
usb_create_simple(usb_bus, "usb-kbd");
/* The user names the tablet, which may not realize on its own. */
usb_realize_and_unref(USB_DEVICE(qdev_new(vms->tablet)), usb_bus,
&error_fatal);
usb_create_simple(usb_bus, "usb-tablet");
}
}
@@ -487,32 +438,6 @@ static void vmapple_reset(void *opaque)
cpu_set_pc(first_cpu, base);
}
/*
* The room past RAM that a device may map memory into once the guest runs,
* reims-graphics-pci's Shared pool: from the end of RAM, rounded up to 1 GiB,
* to the end of the guest's physical addresses, in whole GiB. The machine
* places nothing past RAM, and the firmware tells macOS of RAM alone. The
* bits are the CPU's PARange, at most VMAPPLE_PHYS_BITS, which macOS's
* kernel maps; under HVF that is the VM's IPA size
* (vmapple_get_physical_address_range), and under KVM it is at most the
* VM's, KVM's maximum (the machine asks KVM for no other size).
*/
static void vmapple_pool_room(VMAppleMachineState *vms, MachineState *machine)
{
hwaddr base = ROUND_UP(vms->memmap[VMAPPLE_MEM].base + machine->ram_size,
GiB);
unsigned int bits = MIN(VMAPPLE_PHYS_BITS, arm_pamax(ARM_CPU(first_cpu)));
uint64_t end;
bool fixed_ipa;
if (kvm_enabled()) {
bits = MIN(bits, kvm_arm_get_max_vm_ipa_size(machine, &fixed_ipa));
}
end = 1ULL << bits;
vms->pool_room_base = base;
vms->pool_room_size = end > base ? QEMU_ALIGN_DOWN(end - base, GiB) : 0;
}
static void mach_vmapple_init(MachineState *machine)
{
VMAppleMachineState *vms = VMAPPLE_MACHINE(machine);
@@ -528,27 +453,6 @@ static void mach_vmapple_init(MachineState *machine)
possible_cpus = mc->possible_cpu_arch_ids(machine);
assert(possible_cpus->len == max_cpus);
/*
* Under KVM, PSCI is the host kernel's, and the CPUs it powers on start
* on the pointer authentication keys KVM resets them to, not the boot
* CPU's, so cpu-on-copies-pauth-keys (below) would never apply. Have
* KVM pass CPU_ON to QEMU, which starts CPUs with it.
*/
if (kvm_enabled() && smp_cpus > 1) {
kvm_arm_forward_psci_cpu_on(&error_fatal);
}
/*
* macOS's pointer authentication calls, SMCCC 0xC1000000 to 0xC10000FF
* (see cpu-on-copies-pauth-keys below): HVF and TCG answer them
* NOT_SUPPORTED in x0 and change no other register, and macOS takes
* x1 to x3 of some of them as they are. KVM's answer zeroes x1 to x3,
* so answer them in QEMU as the others do.
*/
if (kvm_enabled()) {
kvm_arm_forward_smccc_range(0xc1000000, 0x100, &error_fatal);
}
for (n = 0; n < possible_cpus->len; n++) {
Object *cpu;
CPUState *cs;
@@ -576,44 +480,6 @@ static void mach_vmapple_init(MachineState *machine)
object_property_set_int(cpu, "psci-conduit", QEMU_PSCI_CONDUIT_HVC,
&error_fatal);
/*
* Under KVM: vmapple does not initialize KVM's PMU, and KVM will
* not run a vCPU that has one uninitialized; and macOS's ApplePSCI
* accepts PSCI 1.1, which HVF reports, but not the 1.3 that
* current kernels give by default.
*/
if (kvm_enabled()) {
if (object_property_find(cpu, "pmu")) {
object_property_set_bool(cpu, "pmu", false, &error_fatal);
}
object_property_set_str(cpu, "kvm-psci-version", "1.1",
&error_fatal);
}
/*
* macOS's device tree gives every CPU a 24 MHz timebase, the
* frequency of Apple silicon's system counter, which HVF passes
* through to the guest. Run TCG's counter at that frequency too.
*/
if (tcg_enabled()) {
object_property_set_uint(cpu, "cntfrq", 24 * 1000 * 1000,
&error_fatal);
}
/*
* macOS asks the hypervisor to program its pointer authentication
* keys, through the paravirtualized calls SMCCC 0xC1000000 to
* 0xC1000006. Hypervisor.framework answers them itself, without an
* exit to QEMU, and under TCG QEMU's PSCI code answers them; both
* answer that they are not supported, and program no key: the
* guest runs on the keys each CPU holds. The boot firmware sets
* them on the boot CPU only, so start each CPU the guest powers on
* with the keys of the CPU that powers it on, and all CPUs share
* them.
*/
object_property_set_bool(cpu, "cpu-on-copies-pauth-keys", true,
&error_fatal);
/* Secondary CPUs start in PSCI powered-down state */
if (n > 0) {
object_property_set_bool(cpu, "start-powered-off", true,
@@ -627,13 +493,12 @@ static void mach_vmapple_init(MachineState *machine)
memory_region_add_subregion(sysmem, vms->memmap[VMAPPLE_MEM].base,
machine->ram);
vmapple_pool_room(vms, machine);
create_gic(vms, sysmem);
create_gicv2m(vms);
create_bdif(vms, sysmem);
create_pvpanic(vms, sysmem);
create_aes(vms, sysmem);
create_gfx(vms, sysmem);
create_uart(vms, VMAPPLE_UART, sysmem, serial_hd(0));
create_rtc(vms);
create_pcie(vms);
@@ -642,7 +507,6 @@ static void mach_vmapple_init(MachineState *machine)
vmapple_firmware_init(vms, sysmem);
create_cfg(vms, sysmem, &error_fatal);
create_dma_config(vms);
/* connect powerdown request */
vms->powerdown_notifier.notify = vmapple_powerdown_req;
@@ -697,39 +561,6 @@ static const CPUArchIdList *vmapple_possible_cpu_arch_ids(MachineState *ms)
return ms->possible_cpus;
}
/*
* The guest's physical address bits under HVF: VMAPPLE_PHYS_BITS, or the
* most the hypervisor gives where that is fewer. HVF's default is 36 bits,
* 64 GiB, which RAM from 4 GiB fills quickly; macOS's kernel maps physical
* addresses of up to 40 bits (its TCR_EL1.IPS), so the guest reaches all of
* a 40-bit space. HVF gives the guest the size chosen as its
* ID_AA64MMFR0_EL1.PARange. Fails, as virt's does, where RAM ends past the
* bits the hypervisor gives.
*/
static int vmapple_get_physical_address_range(MachineState *ms,
int default_ipa_size,
int max_ipa_size)
{
hwaddr ram_end = memmap[VMAPPLE_MEM].base + ms->ram_size;
int bits = MIN(VMAPPLE_PHYS_BITS, max_ipa_size);
if (ram_end > 1ULL << bits) {
error_report("vmapple: RAM ending at 0x%" HWADDR_PRIx " needs more "
"than the %d bits of guest physical address the "
"hypervisor gives", ram_end, bits);
return -1;
}
return bits;
}
static bool vmapple_get_vgic_bases(const MachineState *ms,
uint64_t *dist_base, uint64_t *redist_base)
{
*dist_base = memmap[VMAPPLE_GIC_DIST].base;
*redist_base = memmap[VMAPPLE_GIC_REDIST].base;
return true;
}
static GlobalProperty vmapple_compat_defaults[] = {
{ TYPE_VIRTIO_PCI, "disable-legacy", "on" },
/*
@@ -738,59 +569,8 @@ static GlobalProperty vmapple_compat_defaults[] = {
* mapping in the XHCI controller works around the problem.
*/
{ TYPE_XHCI_PCI, "conditional-intr-mapping", "on" },
/*
* macOS 27's virtio PCI transport never starts a device whose
* capabilities are linked from high offsets to low.
*/
{ "virtio-net-pci-base", "x-ascending-capabilities", "on" },
{ "virtio-sound-pci", "x-ascending-capabilities", "on" },
/*
* macOS's virtio-net driver can miss the completion of its first control
* command, which QEMU gives before the driver waits for it, and the
* interface then never comes up. Offer no control queue, nor the
* features that need one. The device stays promiscuous, as it resets,
* and passes the guest every frame its backend delivers.
*/
{ TYPE_VIRTIO_NET, "ctrl_vq", "off" },
{ TYPE_VIRTIO_NET, "ctrl_rx", "off" },
{ TYPE_VIRTIO_NET, "ctrl_rx_extra", "off" },
{ TYPE_VIRTIO_NET, "ctrl_vlan", "off" },
{ TYPE_VIRTIO_NET, "ctrl_mac_addr", "off" },
{ TYPE_VIRTIO_NET, "ctrl_guest_offloads", "off" },
{ TYPE_VIRTIO_NET, "guest_announce", "off" },
/*
* Under TCG, the max CPU offers SME with streaming vectors of up to 2048
* bits. macOS 14 sizes a zone for each thread's SME state from the
* longest, and panics as it starts because that zone's element is too
* large. Offer no SME, as an M1 to M3 under HVF gives none. Under HVF
* the CPU gets its "sme" property only as its vCPU starts, after this
* default would apply, so the default is optional and HVF's CPU keeps
* what the host gives.
*/
{ ARM_CPU_TYPE_NAME("max"), "sme", "off", .optional = true },
};
static char *vmapple_get_tablet(Object *obj, Error **errp)
{
VMAppleMachineState *vms = VMAPPLE_MACHINE(obj);
return g_strdup(vms->tablet);
}
static void vmapple_set_tablet(Object *obj, const char *value, Error **errp)
{
VMAppleMachineState *vms = VMAPPLE_MACHINE(obj);
ObjectClass *oc = object_class_by_name(value);
if (!oc || object_class_is_abstract(oc) ||
!object_class_dynamic_cast(oc, TYPE_USB_DEVICE)) {
error_setg(errp, "tablet: '%s' is not a USB device", value);
return;
}
g_free(vms->tablet);
vms->tablet = g_strdup(value);
}
static void vmapple_machine_class_init(ObjectClass *oc, const void *data)
{
MachineClass *mc = MACHINE_CLASS(oc);
@@ -803,24 +583,13 @@ static void vmapple_machine_class_init(ObjectClass *oc, const void *data)
mc->minimum_page_bits = 12;
mc->possible_cpu_arch_ids = vmapple_possible_cpu_arch_ids;
mc->cpu_index_to_instance_props = vmapple_cpu_index_to_props;
/* Under HVF, max is the host CPU. */
mc->default_cpu_type = ARM_CPU_TYPE_NAME("max");
mc->default_cpu_type = ARM_CPU_TYPE_NAME("host");
mc->get_default_cpu_node_id = vmapple_get_default_cpu_node_id;
mc->get_vgic_bases = vmapple_get_vgic_bases;
mc->get_physical_address_range = vmapple_get_physical_address_range;
mc->default_ram_id = "mach-vmapple.ram";
mc->desc = "Apple aarch64 Virtual Machine";
compat_props_add(mc->compat_props, vmapple_compat_defaults,
G_N_ELEMENTS(vmapple_compat_defaults));
object_class_property_add_str(oc, "tablet", vmapple_get_tablet,
vmapple_set_tablet);
object_class_property_set_description(oc, "tablet",
"The USB pointing device: "
"usb-vmapple-tablet (default), "
"or another USB device such as "
"usb-tablet");
}
static void vmapple_instance_init(Object *obj)
@@ -828,32 +597,10 @@ static void vmapple_instance_init(Object *obj)
VMAppleMachineState *vms = VMAPPLE_MACHINE(obj);
vms->irqmap = irqmap;
/*
* macOS drives Virtualization.framework's USB tablet with its own
* driver, which takes smooth scrolling.
*/
vms->tablet = g_strdup("usb-vmapple-tablet");
object_property_add_uint64_ptr(obj, "uuid", &vms->uuid,
OBJ_PROP_FLAG_READWRITE);
object_property_set_description(obj, "uuid", "Machine UUID (SDOM)");
object_property_add_uint64_ptr(obj, "x-pool-room-base",
&vms->pool_room_base, OBJ_PROP_FLAG_READ);
object_property_set_description(obj, "x-pool-room-base",
"Where the room past RAM for a device's "
"pool starts (read-only)");
object_property_add_uint64_ptr(obj, "x-pool-room-size",
&vms->pool_room_size, OBJ_PROP_FLAG_READ);
object_property_set_description(obj, "x-pool-room-size",
"The size of the room past RAM for a "
"device's pool, 0 for none (read-only)");
}
static void vmapple_instance_finalize(Object *obj)
{
VMAppleMachineState *vms = VMAPPLE_MACHINE(obj);
g_free(vms->tablet);
}
static const TypeInfo vmapple_machine_info = {
@@ -862,7 +609,6 @@ static const TypeInfo vmapple_machine_info = {
.instance_size = sizeof(VMAppleMachineState),
.class_init = vmapple_machine_class_init,
.instance_init = vmapple_instance_init,
.instance_finalize = vmapple_instance_finalize,
};
static void machvmapple_machine_init(void)
+3 -2
View File
@@ -92,9 +92,10 @@ typedef struct QEMUWin32AIOState QEMUWin32AIOState;
QEMUWin32AIOState *win32_aio_init(void);
void win32_aio_cleanup(QEMUWin32AIOState *aio);
int win32_aio_attach(QEMUWin32AIOState *aio, HANDLE hfile);
int coroutine_fn win32_aio_co_submit(BlockDriverState *bs,
BlockAIOCB *win32_aio_submit(BlockDriverState *bs,
QEMUWin32AIOState *aio, HANDLE hfile,
uint64_t offset, uint64_t bytes, QEMUIOVector *qiov, int type);
uint64_t offset, uint64_t bytes, QEMUIOVector *qiov,
BlockCompletionFunc *cb, void *opaque, int type);
void win32_aio_detach_aio_context(QEMUWin32AIOState *aio,
AioContext *old_context);
void win32_aio_attach_aio_context(QEMUWin32AIOState *aio,
-11
View File
@@ -158,17 +158,6 @@ void qemu_chr_change(QemuOpts *opts, Error **errp);
*/
void qemu_chr_cleanup(void);
#ifndef _WIN32
/**
* qemu_chr_stdio_term_exit:
*
* Restores the terminal a stdio chardev took, as its atexit handler does:
* for a process that then ends with _exit, which runs no atexit handler.
* Nothing where no stdio chardev took it.
*/
void qemu_chr_stdio_term_exit(void);
#endif
/**
* qemu_chr_new_noreplay:
* @label: the name of the backend
-5
View File
@@ -200,11 +200,6 @@ struct VirtIOSound {
AudioBackend *audio_be;
VMChangeStateEntry *vmstate;
virtio_snd_config snd_conf;
/*
* How many of the streams take input: the last ones. The others,
* first, give output.
*/
uint32_t input_streams;
QTAILQ_HEAD(, virtio_snd_ctrl_command) cmdq;
/*
* Convenience queue to keep track of invalid tx/rx queue messages inside
-8
View File
@@ -281,14 +281,6 @@ struct MachineClass {
int (*get_physical_address_range)(MachineState *machine,
int default_ipa_size, int max_ipa_size);
bool (*get_kernel_irqchip_default) (const MachineState *machine);
/*
* Guest physical addresses of the GICv3 distributor and (first)
* redistributor region, for accelerators (HVF) that must place an
* in-kernel vGIC before any vCPU exists. Returns false when the
* board has no GICv3.
*/
bool (*get_vgic_bases) (const MachineState *machine,
uint64_t *dist_base, uint64_t *redist_base);
BlockInterfaceType block_default_type;
int units_per_default_bus;
-6
View File
@@ -481,12 +481,6 @@ OBJECT_DECLARE_SIMPLE_TYPE(USBBus, USB_BUS)
struct USBBus {
BusState qbus;
USBBusOps *ops;
/*
* The controller holds an isochronous packet its device answers with
* USB_RET_NAK and retries it when the device wakes its endpoint, where
* other controllers complete the packet empty or with an error.
*/
bool iso_nak_retry;
int busnr;
int nfree;
int nused;
-2
View File
@@ -18,8 +18,6 @@
#define TYPE_VMAPPLE_CFG "vmapple-cfg"
#define TYPE_VMAPPLE_RTC "vmapple-rtc"
#define TYPE_VMAPPLE_VIRTIO_BLK_PCI "vmapple-virtio-blk-pci"
#endif /* HW_VMAPPLE_VMAPPLE_H */
-9
View File
@@ -44,9 +44,6 @@ OBJECT_DECLARE_SIMPLE_TYPE(QIOChannelFile, QIO_CHANNEL_FILE)
struct QIOChannelFile {
QIOChannel parent;
int fd;
#ifdef WIN32
bool direct_io;
#endif
};
@@ -114,10 +111,4 @@ qio_channel_file_new_path(const char *path,
mode_t mode,
Error **errp);
QIOChannelFile *
qio_channel_file_new_path_direct(const char *path,
int flags,
mode_t mode,
Error **errp);
#endif /* QIO_CHANNEL_FILE_H */
+17 -17
View File
@@ -146,12 +146,12 @@ struct QIOChannelClass {
ssize_t (*io_pwritev)(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
int64_t offset,
off_t offset,
Error **errp);
ssize_t (*io_preadv)(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
int64_t offset,
off_t offset,
Error **errp);
int (*io_shutdown)(QIOChannel *ioc,
QIOChannelShutdown how,
@@ -160,8 +160,8 @@ struct QIOChannelClass {
bool enabled);
void (*io_set_delay)(QIOChannel *ioc,
bool enabled);
int64_t (*io_seek)(QIOChannel *ioc,
int64_t offset,
off_t (*io_seek)(QIOChannel *ioc,
off_t offset,
int whence,
Error **errp);
void (*io_set_aio_fd_handler)(QIOChannel *ioc,
@@ -579,7 +579,7 @@ int qio_channel_close(QIOChannel *ioc,
*
*/
ssize_t qio_channel_pwritev(QIOChannel *ioc, const struct iovec *iov,
size_t niov, int64_t offset, Error **errp);
size_t niov, off_t offset, Error **errp);
/**
* qio_channel_pwrite
@@ -595,7 +595,7 @@ ssize_t qio_channel_pwritev(QIOChannel *ioc, const struct iovec *iov,
*
*/
ssize_t qio_channel_pwrite(QIOChannel *ioc, void *buf, size_t buflen,
int64_t offset, Error **errp);
off_t offset, Error **errp);
/**
* qio_channel_pwritev_all:
@@ -614,7 +614,7 @@ ssize_t qio_channel_pwrite(QIOChannel *ioc, void *buf, size_t buflen,
int coroutine_mixed_fn qio_channel_pwritev_all(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
int64_t offset,
off_t offset,
Error **errp);
/**
@@ -635,7 +635,7 @@ int coroutine_mixed_fn qio_channel_pwritev_all(QIOChannel *ioc,
int coroutine_mixed_fn qio_channel_pwrite_all(QIOChannel *ioc,
const void *buf,
size_t buflen,
int64_t offset,
off_t offset,
Error **errp);
/**
@@ -656,7 +656,7 @@ int coroutine_mixed_fn qio_channel_pwrite_all(QIOChannel *ioc,
*
*/
ssize_t qio_channel_preadv(QIOChannel *ioc, const struct iovec *iov,
size_t niov, int64_t offset, Error **errp);
size_t niov, off_t offset, Error **errp);
/**
* qio_channel_pread
@@ -672,7 +672,7 @@ ssize_t qio_channel_preadv(QIOChannel *ioc, const struct iovec *iov,
*
*/
ssize_t qio_channel_pread(QIOChannel *ioc, void *buf, size_t buflen,
int64_t offset, Error **errp);
off_t offset, Error **errp);
/**
* qio_channel_preadv_all_eof:
@@ -695,7 +695,7 @@ ssize_t qio_channel_pread(QIOChannel *ioc, void *buf, size_t buflen,
int coroutine_mixed_fn qio_channel_preadv_all_eof(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
int64_t offset,
off_t offset,
Error **errp);
/**
@@ -717,7 +717,7 @@ int coroutine_mixed_fn qio_channel_preadv_all_eof(QIOChannel *ioc,
int coroutine_mixed_fn qio_channel_preadv_all(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
int64_t offset,
off_t offset,
Error **errp);
/**
@@ -741,7 +741,7 @@ int coroutine_mixed_fn qio_channel_preadv_all(QIOChannel *ioc,
int coroutine_mixed_fn qio_channel_pread_all_eof(QIOChannel *ioc,
void *buf,
size_t buflen,
int64_t offset,
off_t offset,
Error **errp);
/**
@@ -763,7 +763,7 @@ int coroutine_mixed_fn qio_channel_pread_all_eof(QIOChannel *ioc,
int coroutine_mixed_fn qio_channel_pread_all(QIOChannel *ioc,
void *buf,
size_t buflen,
int64_t offset,
off_t offset,
Error **errp);
/**
@@ -861,10 +861,10 @@ void qio_channel_set_cork(QIOChannel *ioc,
* Not all implementations will support this facility,
* so may report an error.
*
* Returns: the new position on success, (int64_t)-1 on failure
* Returns: the new position on success, (off_t)-1 on failure
*/
int64_t qio_channel_io_seek(QIOChannel *ioc,
int64_t offset,
off_t qio_channel_io_seek(QIOChannel *ioc,
off_t offset,
int whence,
Error **errp);
-8
View File
@@ -100,8 +100,6 @@ typedef struct AudioBackendClass {
const struct audio_capture_ops *ops,
void *cb_opaque);
void (*del_capture)(AudioBackend *be, CaptureVoiceOut *cap, void *cb_opaque);
/* Optional: run the voices now, as the backend's own period does. */
void (*kick)(AudioBackend *be);
#ifdef CONFIG_GIO
bool (*set_dbus_server)(AudioBackend *be,
@@ -127,12 +125,6 @@ void audio_be_close_out(AudioBackend *be, SWVoiceOut *sw);
size_t audio_be_write(AudioBackend *be, SWVoiceOut *sw, void *pcm_buf, size_t size);
int audio_be_get_buffer_size_out(AudioBackend *be, SWVoiceOut *sw);
void audio_be_set_active_out(AudioBackend *be, SWVoiceOut *sw, bool on);
/*
* Run the backend's voices now, as its own period does: a frontend calls it
* when it has new audio, which is then written without waiting for the
* period.
*/
void audio_be_kick(AudioBackend *be);
bool audio_be_is_active_out(AudioBackend *be, SWVoiceOut *sw);
-12
View File
@@ -174,18 +174,6 @@ int qemu_strtosz_metric(const char *nptr, const char **end, uint64_t *result);
char *size_to_str(uint64_t val);
/**
* qemu_linux_release_meets_floor:
* @release: a Linux kernel release, as uname(2) gives it ("7.3.3-1-cachyos")
*
* Returns: whether @release's leading "MAJOR.MINOR" is 7.2 or later, the
* oldest Linux the reims-graphics device runs on; false where @release does
* not start with two numbers and a dot between them. Before 7.2 a udmabuf
* over large pages is malformed, and an AMD GPU's import of it is bound to
* the wrong pages (reims-vgpu issue 185).
*/
bool qemu_linux_release_meets_floor(const char *release);
/**
* freq_to_str:
* @freq_hz: frequency to stringify
-22
View File
@@ -220,28 +220,6 @@ void kvm_irqchip_add_change_notifier(Notifier *n);
void kvm_irqchip_remove_change_notifier(Notifier *n);
void kvm_irqchip_change_notify(void);
/*
* x86 targets only: @n runs on a vCPU's thread, with its CPUState as the
* data, each time kvm_arch_put_registers has put the vCPU's TSC, at a
* reset or a full put.
*/
void kvm_tsc_put_add_notifier(Notifier *n);
/*
* Deletes the KVM slots of exactly [@gpa, @gpa + @size), in each address
* space that holds one, on any thread, without the BQL, ahead of the removal
* of the RAM region that made them: the listener's removal of that section
* then finds no slot and deletes nothing, so the delete, which zaps what of
* the slot is mapped (measured on a 256 MiB slot: 3-8 ms fully mapped,
* against about 1 ms for the whole removal of an untouched one), is not
* spent under the BQL. Until the removal a guest access there exits, and
* QEMU carries it out on the region's memory. False, with nothing deleted,
* where no address space holds such a slot (the region's add is still to
* come, or was never made); a slot with a dirty log or guest_memfd is left
* to the removal.
*/
bool kvm_unmap_before_del(uint64_t gpa, uint64_t size);
#ifdef COMPILING_PER_TARGET
#include "cpu.h"
-2
View File
@@ -270,8 +270,6 @@ win32_close_exception_handler(struct _EXCEPTION_RECORD*, void*,
struct _CONTEXT*, void*);
void *qemu_win32_map_alloc(size_t size, HANDLE *h, Error **errp);
void *qemu_win32_ram_alloc(size_t size, uint64_t *align, HANDLE *h,
Error **errp);
void qemu_win32_map_free(void *ptr, HANDLE h, Error **errp);
#ifdef __cplusplus
+1 -12
View File
@@ -40,14 +40,6 @@ struct RAMBlock {
Error *cpr_blocker;
int fd;
uint64_t fd_offset;
#ifdef _WIN32
/*
* Shared RAM's section (RAM_SHARED): @host is a view of the whole
* section, which the paging file backs, so another mapping of it shares
* the block's pages. NULL for RAM that is not such a view.
*/
HANDLE section;
#endif
/*
* When RAM_GUEST_MEMFD_PRIVATE flag is set, this ramblock can have
* private pages backed by guest_memfd_private specified, while shared
@@ -68,7 +60,7 @@ struct RAMBlock {
* offset in the file pages belonging to this ramblock are saved,
* used only during migration to a file.
*/
int64_t bitmap_offset;
off_t bitmap_offset;
uint64_t pages_offset;
/* Bitmap of already received pages. Only used on destination side. */
@@ -190,9 +182,6 @@ void qemu_ram_set_migratable(RAMBlock *rb);
void qemu_ram_unset_migratable(RAMBlock *rb);
bool qemu_ram_is_named_file(const RAMBlock *rb);
int qemu_ram_get_fd(const RAMBlock *rb);
#ifdef _WIN32
HANDLE qemu_ram_get_section(const RAMBlock *rb);
#endif
size_t qemu_ram_pagesize(const RAMBlock *block);
size_t qemu_ram_pagesize_largest(void);
-15
View File
@@ -19,21 +19,6 @@ const char *qemu_get_vm_name(void);
void qemu_add_exit_notifier(Notifier *notify);
void qemu_remove_exit_notifier(Notifier *notify);
/*
* Cleanup notifiers run at the end of qemu_cleanup(), with the BQL held and
* the exit status (an int *) as their data: before exit() itself, so before
* every atexit handler. Exit notifiers run from an atexit handler registered
* at QEMU's start, so after every handler registered later, a driver's among
* them.
*/
void qemu_add_cleanup_notifier(Notifier *notify);
/*
* Runs the exit notifiers now, with the BQL held: what exit() runs of them,
* for a process that then ends with _exit, which runs no atexit handler.
*/
void qemu_run_exit_notifiers(void);
void qemu_add_machine_init_done_notifier(Notifier *notify);
void qemu_remove_machine_init_done_notifier(Notifier *notify);
-1
View File
@@ -9,7 +9,6 @@ struct AccelCPUState {
bool ready_for_pic_interrupt;
uint64_t tpr;
bool interruption_pending;
bool loadvm_pending;
/* Must be the last field as it may have a tail */
WHV_RUN_VP_EXIT_CONTEXT exit_ctx;
};
-12
View File
@@ -51,13 +51,6 @@ struct whpx_state {
bool ignore_unknown_msr;
bool intercept_msr_gp;
/* intercept-msr-gp was given on or off, not left to the host's vendor */
bool intercept_msr_gp_given;
/*
* Hyper-V refuses the TSC deadline timer's register, so the guest is
* offered no TSC deadline timer (whpx_tsc_deadline_refused)
*/
bool tsc_deadline_refused;
};
extern struct whpx_state whpx_global;
@@ -126,11 +119,6 @@ void whpx_apic_get(APICCommonState *s);
(WHV_PARTITION_HANDLE Partition, UINT32 VpIndex, \
WHV_VIRTUAL_PROCESSOR_STATE_TYPE StateType, PVOID Buffer, \
UINT32 BufferSizeInBytes)) \
X(HRESULT, WHvAdviseGpaRange, \
(WHV_PARTITION_HANDLE Partition, \
const WHV_MEMORY_RANGE_ENTRY *GpaRanges, UINT32 GpaRangesCount, \
WHV_ADVISE_GPA_RANGE_CODE Advice, const VOID *AdviceBuffer, \
UINT32 AdviceBufferSizeInBytes)) \
LIST_WINHVPLATFORM_FUNCTIONS_SUPPLEMENTAL_ARCH(X)
#define WHP_DEFINE_TYPE(return_type, function_name, signature) \
-45
View File
@@ -28,51 +28,6 @@ extern bool whpx_allowed;
extern bool whpx_irqchip_in_kernel;
#define whpx_enabled() (whpx_allowed)
#define whpx_irqchip_in_kernel() (whpx_irqchip_in_kernel)
/*
* Delivers the MSI of @address and @data as its write to the APIC's MSI
* region does, on any thread, with the BQL held or not. False, with nothing
* delivered, where the platform's APIC is not the hypervisor's
* (whpx_irqchip_in_kernel()), the vector is 0, or the hypervisor refused the
* request: the caller then sends it the usual way (msix_notify), which says
* why it is lost.
*/
bool whpx_send_msi_direct(uint64_t address, uint32_t data);
/*
* Maps @size bytes of host memory at @host into the guest at @gpa, read,
* write and execute, on any thread, without the BQL, ahead of the add of the
* RAM region that holds exactly that memory there: the listener's add of that
* section then maps nothing, so the hypervisor's map, which takes about 26 ms
* a GiB, is not spent under the BQL. The range must hold nothing in the
* guest's address space until that add. False, with nothing mapped, where the
* hypervisor refused it; the add then maps it as usual.
*/
bool whpx_map_ahead(void *host, uint64_t gpa, uint64_t size);
/*
* Undoes a whpx_map_ahead of exactly @gpa, @size and @host whose region was
* never added; nothing where the add took it.
*/
void whpx_unmap_ahead(uint64_t gpa, uint64_t size, void *host);
/*
* Unmaps the @size bytes at @gpa of a RAM region the device is about to take
* out of the guest's address space, on any thread, without the BQL: the
* listener's removal of exactly that section then unmaps nothing, so the
* hypervisor's unmap, which takes about 45 ms a GiB, is not spent under the
* BQL. Until the removal a guest access there exits, and QEMU carries it out
* on the region's memory. False, with nothing unmapped, where the region's add
* mapped ahead is still to come or the hypervisor refused; the removal then
* unmaps it as usual.
*/
bool whpx_unmap_before_del(uint64_t gpa, uint64_t size);
/* Whether the hypervisor has whpx_populate's call (WHvAdviseGpaRange). */
bool whpx_can_populate(void);
/*
* Fills the hypervisor's second-level tables for the @size bytes at @gpa,
* mapped in the guest, ahead of the guest's first touch, for reads and
* writes (WHvAdviseGpaRange's WHvAdviseGpaRangeCodePopulate), on any thread,
* without the BQL. The partition's maps and unmaps wait for the call. 0, or
* -EIO where the hypervisor refused, -ENOTSUP where it has no such call.
*/
int whpx_populate(uint64_t gpa, uint64_t size);
#else /* !CONFIG_WHPX_IS_POSSIBLE */
#define whpx_enabled() 0
#define whpx_irqchip_in_kernel() (0)
-6
View File
@@ -9,7 +9,6 @@
#define INPUT_EVENT_MASK_REL (1<<INPUT_EVENT_KIND_REL)
#define INPUT_EVENT_MASK_ABS (1<<INPUT_EVENT_KIND_ABS)
#define INPUT_EVENT_MASK_MTT (1<<INPUT_EVENT_KIND_MTT)
#define INPUT_EVENT_MASK_SCROLL (1 << INPUT_EVENT_KIND_SCROLL)
#define INPUT_EVENT_ABS_MIN 0x0000
#define INPUT_EVENT_ABS_MAX 0x7FFF
@@ -32,7 +31,6 @@ typedef struct QemuInputEvent {
InputMoveEvent rel;
InputMoveEvent abs;
InputMultiTouchEvent mtt;
InputScrollEvent scroll;
};
} QemuInputEvent;
@@ -76,7 +74,6 @@ void qemu_input_update_buttons(QemuConsole *src, uint32_t *button_map,
uint32_t button_old, uint32_t button_new);
bool qemu_input_is_absolute(const QemuConsole *con);
bool qemu_input_scrolls_smoothly(const QemuConsole *con);
int qemu_input_scale_axis(int value,
int min_in, int max_in,
int min_out, int max_out);
@@ -88,9 +85,6 @@ void qemu_input_queue_mtt(QemuConsole *src, InputMultiTouchType type, int slot,
void qemu_input_queue_mtt_abs(QemuConsole *src, InputAxis axis, int value,
int min_in, int max_in,
int slot, int tracking_id);
void qemu_input_queue_scroll(QemuConsole *src, InputAxis axis, int value,
InputScrollPhase phase,
InputScrollMomentum momentum);
/* Touch devices */
typedef struct touch_slot {
+2 -2
View File
@@ -124,8 +124,8 @@ static int qio_channel_buffer_set_blocking(QIOChannel *ioc G_GNUC_UNUSED,
}
static int64_t qio_channel_buffer_seek(QIOChannel *ioc,
int64_t offset,
static off_t qio_channel_buffer_seek(QIOChannel *ioc,
off_t offset,
int whence,
Error **errp)
{
+10 -233
View File
@@ -27,9 +27,6 @@
#include "qemu/module.h"
#include "qemu/sockets.h"
#include "trace.h"
#ifdef WIN32
#include <winioctl.h>
#endif
QIOChannelFile *
qio_channel_file_new_fd(int fd)
@@ -45,7 +42,7 @@ qio_channel_file_new_fd(int fd)
ioc->fd = fd;
if (lseek(fd, 0, SEEK_CUR) != (int64_t)-1) {
if (lseek(fd, 0, SEEK_CUR) != (off_t)-1) {
qio_channel_set_feature(QIO_CHANNEL(ioc), QIO_CHANNEL_FEATURE_SEEKABLE);
}
@@ -77,9 +74,6 @@ qio_channel_file_new_path(const char *path,
ioc = QIO_CHANNEL_FILE(object_new(TYPE_QIO_CHANNEL_FILE));
#ifdef O_BINARY
flags |= O_BINARY;
#endif
if (flags & O_CREAT) {
ioc->fd = qemu_create(path, flags & ~O_CREAT, mode, errp);
} else {
@@ -90,93 +84,15 @@ qio_channel_file_new_path(const char *path,
return NULL;
}
if (lseek(ioc->fd, 0, SEEK_CUR) != (int64_t)-1) {
if (lseek(ioc->fd, 0, SEEK_CUR) != (off_t)-1) {
qio_channel_set_feature(QIO_CHANNEL(ioc), QIO_CHANNEL_FEATURE_SEEKABLE);
}
#ifdef WIN32
if (flags & O_CREAT) {
HANDLE h = (HANDLE)_get_osfhandle(ioc->fd);
if (h != INVALID_HANDLE_VALUE && GetFileType(h) == FILE_TYPE_DISK) {
DWORD br = 0;
DeviceIoControl(h, FSCTL_SET_SPARSE, NULL, 0, NULL, 0, &br, NULL);
}
}
#endif
trace_qio_channel_file_new_path(ioc, path, flags, mode, ioc->fd);
return ioc;
}
QIOChannelFile *
qio_channel_file_new_path_direct(const char *path,
int flags,
mode_t mode,
Error **errp)
{
#ifdef O_DIRECT
return qio_channel_file_new_path(path, flags | O_DIRECT, mode, errp);
#elif defined(WIN32)
QIOChannelFile *ioc;
g_autofree gunichar2 *wpath = NULL;
DWORD access = 0;
DWORD disp = (flags & O_CREAT) ? OPEN_ALWAYS : OPEN_EXISTING;
DWORD share = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
int accmode = flags & O_ACCMODE;
int crt_flags = _O_BINARY;
HANDLE h;
int fd;
if (accmode == O_RDONLY) {
access = GENERIC_READ;
crt_flags |= _O_RDONLY;
} else if (accmode == O_WRONLY) {
access = GENERIC_WRITE;
} else {
access = GENERIC_READ | GENERIC_WRITE;
}
wpath = g_utf8_to_utf16(path, -1, NULL, NULL, NULL);
if (!wpath) {
error_setg(errp, "Invalid UTF-8 path for direct I/O: %s", path);
return NULL;
}
h = CreateFileW((LPCWSTR)wpath, access, share, NULL, disp,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_NO_BUFFERING, NULL);
if (h == INVALID_HANDLE_VALUE) {
error_setg_win32(errp, GetLastError(),
"Unable to open '%s' with direct I/O", path);
return NULL;
}
if ((flags & O_CREAT) && GetFileType(h) == FILE_TYPE_DISK) {
DWORD br = 0;
DeviceIoControl(h, FSCTL_SET_SPARSE, NULL, 0, NULL, 0, &br, NULL);
}
fd = _open_osfhandle((intptr_t)h, crt_flags);
if (fd < 0) {
CloseHandle(h);
error_setg_errno(errp, errno,
"Unable to wrap direct I/O handle for '%s'", path);
return NULL;
}
ioc = QIO_CHANNEL_FILE(object_new(TYPE_QIO_CHANNEL_FILE));
ioc->fd = fd;
ioc->direct_io = true;
if (lseek(ioc->fd, 0, SEEK_CUR) != (int64_t)-1) {
qio_channel_set_feature(QIO_CHANNEL(ioc), QIO_CHANNEL_FEATURE_SEEKABLE);
}
trace_qio_channel_file_new_path(ioc, path, flags, mode, ioc->fd);
return ioc;
#else
error_setg(errp, "Direct I/O is not supported on this platform");
return NULL;
#endif
}
static void qio_channel_file_init(Object *obj)
{
@@ -254,7 +170,7 @@ static ssize_t qio_channel_file_writev(QIOChannel *ioc,
static ssize_t qio_channel_file_preadv(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
int64_t offset,
off_t offset,
Error **errp)
{
QIOChannelFile *fioc = QIO_CHANNEL_FILE(ioc);
@@ -280,7 +196,7 @@ static ssize_t qio_channel_file_preadv(QIOChannel *ioc,
static ssize_t qio_channel_file_pwritev(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
int64_t offset,
off_t offset,
Error **errp)
{
QIOChannelFile *fioc = QIO_CHANNEL_FILE(ioc);
@@ -300,137 +216,6 @@ static ssize_t qio_channel_file_pwritev(QIOChannel *ioc,
}
return ret;
}
#elif defined(WIN32)
static ssize_t qio_channel_file_prw_win32(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
int64_t offset,
bool is_write,
Error **errp)
{
static const size_t max_chunk = 16U * 1024U * 1024U;
QIOChannelFile *fioc = QIO_CHANNEL_FILE(ioc);
HANDLE h = (HANDLE)_get_osfhandle(fioc->fd);
LARGE_INTEGER zero = { .QuadPart = 0 };
LARGE_INTEGER saved = { .QuadPart = 0 };
bool have_saved = false;
uint64_t cur;
ssize_t total = 0;
ssize_t ret = -1;
size_t i = 0;
if (offset < 0) {
error_setg_errno(errp, EINVAL, "Invalid negative offset for %s",
is_write ? "pwritev" : "preadv");
return -1;
}
if (h == INVALID_HANDLE_VALUE) {
error_setg_errno(errp, EBADF, "Invalid file handle for %s",
is_write ? "pwritev" : "preadv");
return -1;
}
cur = (uint64_t)offset;
have_saved = SetFilePointerEx(h, zero, &saved, FILE_CURRENT);
while (i < niov) {
uint8_t *base = (uint8_t *)iov[i].iov_base;
size_t run = iov[i].iov_len;
size_t j = i + 1;
while (j < niov && (uint8_t *)iov[j].iov_base == base + run &&
run < max_chunk && iov[j].iov_len <= max_chunk - run) {
run += iov[j].iov_len;
j++;
}
if (run == 0) {
i = j;
continue;
}
size_t done = 0;
while (done < run) {
DWORD chunk = (DWORD)MIN(run - done, max_chunk);
DWORD xfer = 0;
OVERLAPPED ov;
BOOL ok;
memset(&ov, 0, sizeof(ov));
ov.Offset = (DWORD)(cur & 0xFFFFFFFFULL);
ov.OffsetHigh = (DWORD)(cur >> 32);
if (is_write) {
ok = WriteFile(h, base + done, chunk, &xfer, &ov);
} else {
ok = ReadFile(h, base + done, chunk, &xfer, &ov);
}
if (!ok) {
DWORD err = GetLastError();
const char *msg = is_write ? "Unable to pwritev to file"
: "Unable to preadv from file";
if (!is_write && err == ERROR_HANDLE_EOF) {
ret = total;
goto out;
}
/*
* A volume can accept the handle and reject an unbuffered
* write. Keep this distinct from disk or media failures
* so the caller can retry with buffering.
*/
if (is_write && fioc->direct_io &&
(err == ERROR_INVALID_PARAMETER ||
err == ERROR_INVALID_FUNCTION ||
err == ERROR_NOT_SUPPORTED)) {
msg = "Unable to pwritev to file with direct I/O";
}
error_setg_win32(errp, err, "%s", msg);
goto out;
}
if (xfer == 0) {
if (!is_write || total > 0) {
ret = total;
goto out;
}
error_setg_errno(errp, EIO, "pwritev made no progress");
goto out;
}
done += xfer;
cur += xfer;
total += xfer;
if (is_write && xfer < chunk) {
/* Preserve short-write semantics for caller retry/error handling. */
ret = total;
goto out;
}
}
i = j;
}
ret = total;
out:
if (have_saved) {
SetFilePointerEx(h, saved, NULL, FILE_BEGIN);
}
return ret;
}
static ssize_t qio_channel_file_preadv(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
int64_t offset,
Error **errp)
{
return qio_channel_file_prw_win32(ioc, iov, niov, offset, false, errp);
}
static ssize_t qio_channel_file_pwritev(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
int64_t offset,
Error **errp)
{
return qio_channel_file_prw_win32(ioc, iov, niov, offset, true, errp);
}
#endif /* CONFIG_PREADV */
static int qio_channel_file_set_blocking(QIOChannel *ioc,
@@ -438,11 +223,7 @@ static int qio_channel_file_set_blocking(QIOChannel *ioc,
Error **errp)
{
#ifdef WIN32
QIOChannelFile *fioc = QIO_CHANNEL_FILE(ioc);
if (enabled ||
GetFileType((HANDLE)_get_osfhandle(fioc->fd)) == FILE_TYPE_DISK) {
return 0;
}
/* not implemented */
error_setg_errno(errp, errno, "Failed to set FD nonblocking");
return -1;
#else
@@ -456,20 +237,16 @@ static int qio_channel_file_set_blocking(QIOChannel *ioc,
}
static int64_t qio_channel_file_seek(QIOChannel *ioc,
int64_t offset,
static off_t qio_channel_file_seek(QIOChannel *ioc,
off_t offset,
int whence,
Error **errp)
{
QIOChannelFile *fioc = QIO_CHANNEL_FILE(ioc);
int64_t ret;
off_t ret;
#ifdef WIN32
ret = (int64_t)_lseeki64(fioc->fd, (int64_t)offset, whence);
#else
ret = lseek(fioc->fd, offset, whence);
#endif
if (ret == (int64_t)-1) {
if (ret == (off_t)-1) {
error_setg_errno(errp, errno,
"Unable to seek to offset %lld whence %d in file",
(long long int)offset, whence);
@@ -537,7 +314,7 @@ static void qio_channel_file_class_init(ObjectClass *klass,
ioc_klass->io_writev = qio_channel_file_writev;
ioc_klass->io_readv = qio_channel_file_readv;
ioc_klass->io_set_blocking = qio_channel_file_set_blocking;
#if defined(CONFIG_PREADV) || defined(WIN32)
#ifdef CONFIG_PREADV
ioc_klass->io_pwritev = qio_channel_file_pwritev;
ioc_klass->io_preadv = qio_channel_file_preadv;
#endif
+2 -2
View File
@@ -105,9 +105,9 @@ qio_channel_null_set_blocking(QIOChannel *ioc G_GNUC_UNUSED,
}
static int64_t
static off_t
qio_channel_null_seek(QIOChannel *ioc G_GNUC_UNUSED,
int64_t offset G_GNUC_UNUSED,
off_t offset G_GNUC_UNUSED,
int whence G_GNUC_UNUSED,
Error **errp G_GNUC_UNUSED)
{
+12 -12
View File
@@ -450,7 +450,7 @@ GSource *qio_channel_add_watch_source(QIOChannel *ioc,
ssize_t qio_channel_pwritev(QIOChannel *ioc, const struct iovec *iov,
size_t niov, int64_t offset, Error **errp)
size_t niov, off_t offset, Error **errp)
{
QIOChannelClass *klass = QIO_CHANNEL_GET_CLASS(ioc);
@@ -468,7 +468,7 @@ ssize_t qio_channel_pwritev(QIOChannel *ioc, const struct iovec *iov,
}
ssize_t qio_channel_pwrite(QIOChannel *ioc, void *buf, size_t buflen,
int64_t offset, Error **errp)
off_t offset, Error **errp)
{
struct iovec iov = {
.iov_base = buf,
@@ -481,7 +481,7 @@ ssize_t qio_channel_pwrite(QIOChannel *ioc, void *buf, size_t buflen,
int coroutine_mixed_fn qio_channel_pwritev_all(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
int64_t offset,
off_t offset,
Error **errp)
{
int ret = -1;
@@ -519,7 +519,7 @@ int coroutine_mixed_fn qio_channel_pwritev_all(QIOChannel *ioc,
int coroutine_mixed_fn qio_channel_pwrite_all(QIOChannel *ioc,
const void *buf,
size_t buflen,
int64_t offset,
off_t offset,
Error **errp)
{
struct iovec iov = { .iov_base = (char *)buf, .iov_len = buflen };
@@ -527,7 +527,7 @@ int coroutine_mixed_fn qio_channel_pwrite_all(QIOChannel *ioc,
}
ssize_t qio_channel_preadv(QIOChannel *ioc, const struct iovec *iov,
size_t niov, int64_t offset, Error **errp)
size_t niov, off_t offset, Error **errp)
{
QIOChannelClass *klass = QIO_CHANNEL_GET_CLASS(ioc);
@@ -545,7 +545,7 @@ ssize_t qio_channel_preadv(QIOChannel *ioc, const struct iovec *iov,
}
ssize_t qio_channel_pread(QIOChannel *ioc, void *buf, size_t buflen,
int64_t offset, Error **errp)
off_t offset, Error **errp)
{
struct iovec iov = {
.iov_base = buf,
@@ -558,7 +558,7 @@ ssize_t qio_channel_pread(QIOChannel *ioc, void *buf, size_t buflen,
int coroutine_mixed_fn qio_channel_preadv_all_eof(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
int64_t offset,
off_t offset,
Error **errp)
{
int ret = -1;
@@ -609,7 +609,7 @@ int coroutine_mixed_fn qio_channel_preadv_all_eof(QIOChannel *ioc,
int coroutine_mixed_fn qio_channel_preadv_all(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
int64_t offset,
off_t offset,
Error **errp)
{
int ret = qio_channel_preadv_all_eof(ioc, iov, niov, offset, errp);
@@ -629,7 +629,7 @@ int coroutine_mixed_fn qio_channel_preadv_all(QIOChannel *ioc,
int coroutine_mixed_fn qio_channel_pread_all_eof(QIOChannel *ioc,
void *buf,
size_t buflen,
int64_t offset,
off_t offset,
Error **errp)
{
struct iovec iov = { .iov_base = buf, .iov_len = buflen };
@@ -639,7 +639,7 @@ int coroutine_mixed_fn qio_channel_pread_all_eof(QIOChannel *ioc,
int coroutine_mixed_fn qio_channel_pread_all(QIOChannel *ioc,
void *buf,
size_t buflen,
int64_t offset,
off_t offset,
Error **errp)
{
struct iovec iov = { .iov_base = buf, .iov_len = buflen };
@@ -696,8 +696,8 @@ int qio_channel_get_peerpid(QIOChannel *ioc,
return 0;
}
int64_t qio_channel_io_seek(QIOChannel *ioc,
int64_t offset,
off_t qio_channel_io_seek(QIOChannel *ioc,
off_t offset,
int whence,
Error **errp)
{
+9 -18
View File
@@ -838,7 +838,7 @@ socket = []
version_res = []
coref = []
iokit = []
reims_vgpu = not_found
pvg = not_found
emulator_link_args = []
midl = not_found
widl = not_found
@@ -864,6 +864,8 @@ elif host_os == 'darwin'
coref = dependency('appleframeworks', modules: 'CoreFoundation')
iokit = dependency('appleframeworks', modules: 'IOKit', required: false)
host_dsosuf = '.dylib'
pvg = dependency('appleframeworks', modules: ['ParavirtualizedGraphics', 'Metal'],
required: get_option('pvg'))
elif host_os == 'sunos'
socket = [cc.find_library('socket'),
cc.find_library('nsl'),
@@ -879,16 +881,6 @@ elif host_os == 'openbsd'
endif
endif
# reims-graphics-pci drives reims-vgpu's C API (reims_vgpu.h), a library
# found through pkg-config: reims-vgpu.pc, which reims-vgpu's `cargo xtask
# dist` writes into its target/dist/lib/pkgconfig. It is linked statically,
# so the binary records no path to it. The library runs on macOS, on Linux
# and on Windows.
if host_os in ['darwin', 'linux', 'windows']
reims_vgpu = dependency('reims-vgpu', method: 'pkg-config', static: true,
required: get_option('reims_vgpu'))
endif
###############################################
# Host-specific configuration of accelerators #
###############################################
@@ -3425,11 +3417,10 @@ foreach target : target_dirs
target_kconfig += 'CONFIG_' + config_target['TARGET_ARCH'].to_upper() + '=y'
target_kconfig += 'CONFIG_TARGET_BIG_ENDIAN=' + config_target['TARGET_BIG_ENDIAN']
# The reims-graphics device's region is plain host memory the guest maps,
# whatever its architecture or accelerator, so every target may have it:
# x86-64 guests under TCG on a Mac among them.
if reims_vgpu.found()
target_kconfig += 'CONFIG_REIMS_GRAPHICS=y'
# PVG is not cross-architecture. Use accelerator_targets as a proxy to
# figure out which target can support PVG on this host
if pvg.found() and target in accelerator_targets.get('CONFIG_HVF', [])
target_kconfig += 'CONFIG_MAC_PVG=y'
endif
config_input = meson.get_external_property(target, 'default')
@@ -5085,8 +5076,8 @@ summary_info += {'libdw': libdw}
if host_os == 'freebsd'
summary_info += {'libinotify-kqueue': inotify}
endif
if host_os in ['darwin', 'linux']
summary_info += {'reims-vgpu support': reims_vgpu}
if host_os == 'darwin'
summary_info += {'ParavirtualizedGraphics support': pvg}
endif
summary_info += {'valgrind': valgrind}
summary(summary_info, bool_yn: true, section: 'Dependencies')
+2 -2
View File
@@ -208,10 +208,10 @@ option('lzfse', type : 'feature', value : 'auto',
description: 'lzfse support for DMG images')
option('lzo', type : 'feature', value : 'auto',
description: 'lzo compression support')
option('pvg', type: 'feature', value: 'auto',
description: 'macOS paravirtualized graphics support')
option('rbd', type : 'feature', value : 'auto',
description: 'Ceph block device driver')
option('reims_vgpu', type : 'feature', value : 'auto',
description: 'reims-vgpu graphics device (reims-graphics-pci)')
option('opengl', type : 'feature', value : 'auto',
description: 'OpenGL support')
option('rdma', type : 'feature', value : 'auto',
+5 -5
View File
@@ -101,7 +101,7 @@ static ssize_t
qio_channel_block_preadv(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
int64_t offset,
off_t offset,
Error **errp)
{
QIOChannelBlock *bioc = QIO_CHANNEL_BLOCK(ioc);
@@ -122,7 +122,7 @@ static ssize_t
qio_channel_block_pwritev(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
int64_t offset,
off_t offset,
Error **errp)
{
QIOChannelBlock *bioc = QIO_CHANNEL_BLOCK(ioc);
@@ -152,9 +152,9 @@ qio_channel_block_set_blocking(QIOChannel *ioc,
}
static int64_t
static off_t
qio_channel_block_seek(QIOChannel *ioc,
int64_t offset,
off_t offset,
int whence,
Error **errp)
{
@@ -169,7 +169,7 @@ qio_channel_block_seek(QIOChannel *ioc,
break;
case SEEK_END:
error_setg(errp, "Size of VMstate region is unknown");
return (int64_t)-1;
return (off_t)-1;
default:
g_assert_not_reached();
}
+1 -1
View File
@@ -39,7 +39,7 @@ OBJECT_DECLARE_SIMPLE_TYPE(QIOChannelBlock, QIO_CHANNEL_BLOCK)
struct QIOChannelBlock {
QIOChannel parent;
BlockDriverState *bs;
int64_t offset;
off_t offset;
};
+21 -107
View File
@@ -16,7 +16,6 @@
#include "io/channel-file.h"
#include "io/channel-socket.h"
#include "io/channel-util.h"
#include "multifd.h"
#include "options.h"
#include "trace.h"
@@ -51,17 +50,14 @@ void file_cleanup_outgoing_migration(void)
outgoing_args.fname = NULL;
}
static QIOChannelFile *file_open_channel(const char *path, int flags,
bool direct_io, Error **errp)
static void file_enable_direct_io(int *flags)
{
if (direct_io) {
/*
* Enable direct I/O for the secondary channels. These are used
* for sending/receiving ram pages and I/O is aligned to page size.
*/
return qio_channel_file_new_path_direct(path, flags, 0, errp);
}
return qio_channel_file_new_path(path, flags, 0, errp);
#ifdef O_DIRECT
*flags |= O_DIRECT;
#else
/* it should have been rejected when setting the parameter */
g_assert_not_reached();
#endif
}
bool file_send_channel_create(gpointer opaque, Error **errp)
@@ -70,7 +66,16 @@ bool file_send_channel_create(gpointer opaque, Error **errp)
int flags = O_WRONLY;
bool ret = true;
ioc = file_open_channel(outgoing_args.fname, flags, migrate_direct_io(), errp);
if (migrate_direct_io()) {
/*
* Enable O_DIRECT for the secondary channels. These are used
* for sending ram pages and writes should be guaranteed to be
* aligned to at least page size.
*/
file_enable_direct_io(&flags);
}
ioc = qio_channel_file_new_path(outgoing_args.fname, flags, 0, errp);
if (!ioc) {
ret = false;
goto out;
@@ -103,11 +108,7 @@ QIOChannel *file_connect_outgoing(MigrationState *s,
goto out;
}
#ifdef WIN32
if (_chsize_s(fioc->fd, (int64_t)offset) != 0) {
#else
if (ftruncate(fioc->fd, offset)) {
#endif
error_setg_errno(errp, errno,
"failed to truncate migration file to offset %" PRIx64,
offset);
@@ -144,18 +145,18 @@ static void file_create_incoming_channels(QIOChannel *ioc, char *filename,
g_autofree QIOChannel **iocs = NULL;
int flags = O_RDONLY;
bool direct_io = false;
if (migrate_multifd()) {
channels += migrate_multifd_channels();
direct_io = migrate_direct_io();
if (migrate_direct_io()) {
file_enable_direct_io(&flags);
}
}
iocs = g_new0(QIOChannel *, channels);
iocs[0] = ioc;
for (i = 1; i < channels; i++) {
QIOChannelFile *fioc = file_open_channel(filename, flags, direct_io, errp);
QIOChannelFile *fioc = qio_channel_file_new_path(filename, flags, 0, errp);
if (!fioc) {
while (i) {
@@ -198,84 +199,6 @@ void file_connect_incoming(FileMigrationArgs *file_args, Error **errp)
file_create_incoming_channels(QIO_CHANNEL(fioc), filename, errp);
}
#ifdef WIN32
/*
* NTFS sparse files allocate in 64 KiB compression units. Coalescing a
* contiguous multifd packet's non-zero pages into one 64 KiB-aligned write
* within the packet's exclusive [pkt_min, pkt_max) span eliminates tiny
* unaligned sparse writes without overlapping any other multifd thread or
* changing the mapped-ram file format or file_bmap.
*/
static int file_write_ramblock_win32_coalesced(QIOChannel *ioc,
int niov,
MultiFDPages_t *pages,
Error **errp)
{
RAMBlock *block = pages->block;
size_t page_size = multifd_ram_page_size();
uint32_t total = pages->num;
uint32_t norm_n = (uint32_t)niov;
ram_addr_t pkt_min, pkt_max, norm_min, norm_max;
if (niov <= 0 || total == 0 || norm_n != pages->normal_num ||
norm_n > total || page_size == 0 || block->used_length < page_size) {
return 1;
}
/* Verify strict ascending order within normal and zero partitions. */
for (uint32_t k = 1; k < norm_n; k++) {
if (pages->offset[k] <= pages->offset[k - 1]) {
return 1;
}
}
for (uint32_t k = norm_n + 1; k < total; k++) {
if (pages->offset[k] <= pages->offset[k - 1]) {
return 1;
}
}
if (pages->offset[norm_n - 1] > block->used_length - page_size) {
return 1;
}
norm_min = pages->offset[0];
norm_max = pages->offset[norm_n - 1] + page_size;
pkt_min = norm_min;
pkt_max = norm_max;
if (norm_n < total) {
if (pages->offset[total - 1] > block->used_length - page_size) {
return 1;
}
if (pages->offset[norm_n] < pkt_min) {
pkt_min = pages->offset[norm_n];
}
if (pages->offset[total - 1] + page_size > pkt_max) {
pkt_max = pages->offset[total - 1] + page_size;
}
}
if ((pkt_max - pkt_min) != (ram_addr_t)total * page_size) {
return 1;
}
const ram_addr_t unit = 64 * 1024;
ram_addr_t start = QEMU_ALIGN_DOWN(norm_min, unit);
ram_addr_t end = QEMU_ALIGN_UP(norm_max, unit);
if (start < pkt_min) {
start = pkt_min;
}
if (end > pkt_max) {
end = pkt_max;
}
struct iovec single = {
.iov_base = block->host + start,
.iov_len = end - start,
};
return qio_channel_pwritev_all(ioc, &single, 1,
block->pages_offset + start, errp);
}
#endif
int file_write_ramblock_iov(QIOChannel *ioc, const struct iovec *iov,
int niov, MultiFDPages_t *pages, Error **errp)
{
@@ -285,15 +208,6 @@ int file_write_ramblock_iov(QIOChannel *ioc, const struct iovec *iov,
size_t len;
RAMBlock *block = pages->block;
#ifdef WIN32
if (niov > 0) {
int cret = file_write_ramblock_win32_coalesced(ioc, niov, pages, errp);
if (cret <= 0) {
return cret;
}
}
#endif
slice_idx = 0;
slice_num = 1;
-29
View File
@@ -63,7 +63,6 @@
#include "system/dirtylimit.h"
#include "qemu/sockets.h"
#include "system/kvm.h"
#include "system/whpx.h"
#include "math.h"
#define NOTIFIER_ELEM_INIT(array, elem) \
@@ -2175,34 +2174,6 @@ void qmp_migrate(const char *uri, bool has_channels,
return;
}
if (whpx_enabled()) {
if (has_resume && resume) {
error_setg(errp, "WHPX: migration resume is not supported");
return;
}
if (migrate_mode() != MIG_MODE_NORMAL) {
error_setg(errp, "WHPX: only normal migration mode is supported");
return;
}
if (runstate_is_running()) {
error_setg(errp,
"WHPX: live migration is not supported while the VM is running; stop the VM first");
return;
}
if (main_ch->addr->transport != MIGRATION_ADDRESS_TYPE_FILE) {
error_setg(errp,
"WHPX: only stopped-VM file suspend (file: URI) is supported");
return;
}
if (migrate_postcopy() || migrate_background_snapshot() ||
migrate_colo() || migrate_dirty_bitmaps() ||
migrate_return_path()) {
error_setg(errp,
"WHPX: unsupported migration capability for stopped-VM file suspend");
return;
}
}
if (!migrate_prepare(s, has_resume && resume, errp)) {
/* Error detected, put into errp */
return;
+30 -26
View File
@@ -24,12 +24,24 @@ static bool multifd_zero_page_enabled(void)
return migrate_zero_page_detection() == ZERO_PAGE_DETECTION_MULTIFD;
}
static void swap_page_offset(ram_addr_t *pages_offset, int a, int b)
{
ram_addr_t temp;
if (a == b) {
return;
}
temp = pages_offset[a];
pages_offset[a] = pages_offset[b];
pages_offset[b] = temp;
}
/**
* multifd_send_zero_page_detect: Perform zero page detection on all pages.
*
* Partitions normal pages before zero pages in p->pages->offset while
* preserving ascending offset order so mapped-ram file writes coalesce cleanly,
* and updates p->pages->normal_num.
* Sorts normal pages before zero pages in p->pages->offset and updates
* p->pages->normal_num.
*
* @param p A pointer to the send params.
*/
@@ -37,40 +49,32 @@ void multifd_send_zero_page_detect(MultiFDSendParams *p)
{
MultiFDPages_t *pages = &p->data->u.ram;
RAMBlock *rb = pages->block;
size_t page_size = multifd_ram_page_size();
uint32_t normal_num = 0;
uint32_t zero_num = 0;
ram_addr_t stack_zero[128];
g_autofree ram_addr_t *heap_zero = NULL;
ram_addr_t *zero_offsets = stack_zero;
int i = 0;
int j = pages->num - 1;
if (!multifd_zero_page_enabled()) {
pages->normal_num = pages->num;
goto out;
}
if (pages->num > ARRAY_SIZE(stack_zero)) {
heap_zero = g_new(ram_addr_t, pages->num);
zero_offsets = heap_zero;
}
for (uint32_t i = 0; i < pages->num; i++) {
/*
* Sort the page offset array by moving all normal pages to
* the left and all zero pages to the right of the array.
*/
while (i <= j) {
uint64_t offset = pages->offset[i];
if (!buffer_is_zero(rb->host + offset, page_size)) {
pages->offset[normal_num++] = offset;
} else {
zero_offsets[zero_num++] = offset;
ram_release_page(rb->idstr, offset);
if (!buffer_is_zero(rb->host + offset, multifd_ram_page_size())) {
i++;
continue;
}
swap_page_offset(pages->offset, i, j);
ram_release_page(rb->idstr, offset);
j--;
}
if (zero_num > 0) {
memcpy(&pages->offset[normal_num], zero_offsets,
zero_num * sizeof(ram_addr_t));
}
pages->normal_num = normal_num;
pages->normal_num = i;
out:
qatomic_add(&mig_stats.normal_pages, pages->normal_num);
+1 -1
View File
@@ -133,7 +133,7 @@ struct MultiFDRecvData {
void *opaque;
size_t size;
/* for preadv */
int64_t file_offset;
off_t file_offset;
};
typedef struct {
+8 -8
View File
@@ -532,7 +532,7 @@ void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, size_t size)
}
void qemu_put_buffer_at(QEMUFile *f, const uint8_t *buf, size_t buflen,
int64_t pos)
off_t pos)
{
Error *err = NULL;
@@ -550,7 +550,7 @@ void qemu_put_buffer_at(QEMUFile *f, const uint8_t *buf, size_t buflen,
}
size_t qemu_get_buffer_at(QEMUFile *f, uint8_t *buf, size_t buflen, int64_t pos,
size_t qemu_get_buffer_at(QEMUFile *f, uint8_t *buf, size_t buflen, off_t pos,
Error **errp)
{
if (f->last_error) {
@@ -566,10 +566,10 @@ size_t qemu_get_buffer_at(QEMUFile *f, uint8_t *buf, size_t buflen, int64_t pos,
return buflen;
}
void qemu_set_offset(QEMUFile *f, int64_t off, int whence)
void qemu_set_offset(QEMUFile *f, off_t off, int whence)
{
Error *err = NULL;
int64_t ret;
off_t ret;
if (qemu_file_is_writable(f)) {
qemu_fflush(f);
@@ -580,20 +580,20 @@ void qemu_set_offset(QEMUFile *f, int64_t off, int whence)
}
ret = qio_channel_io_seek(f->ioc, off, whence, &err);
if (ret == (int64_t)-1) {
if (ret == (off_t)-1) {
qemu_file_set_error_obj(f, -EIO, err);
}
}
int64_t qemu_get_offset(QEMUFile *f)
off_t qemu_get_offset(QEMUFile *f)
{
Error *err = NULL;
int64_t ret;
off_t ret;
qemu_fflush(f);
ret = qio_channel_io_seek(f->ioc, 0, SEEK_CUR, &err);
if (ret == (int64_t)-1) {
if (ret == (off_t)-1) {
qemu_file_set_error_obj(f, -EIO, err);
}
return ret;
+4 -4
View File
@@ -72,11 +72,11 @@ QEMUFile *qemu_file_get_return_path(QEMUFile *f);
int qemu_fflush(QEMUFile *f);
bool qemu_file_set_blocking(QEMUFile *f, bool block, Error **errp);
int qemu_file_get_to_fd(QEMUFile *f, int fd, size_t size);
void qemu_set_offset(QEMUFile *f, int64_t off, int whence);
int64_t qemu_get_offset(QEMUFile *f);
void qemu_set_offset(QEMUFile *f, off_t off, int whence);
off_t qemu_get_offset(QEMUFile *f);
void qemu_put_buffer_at(QEMUFile *f, const uint8_t *buf, size_t buflen,
int64_t pos);
size_t qemu_get_buffer_at(QEMUFile *f, uint8_t *buf, size_t buflen, int64_t pos,
off_t pos);
size_t qemu_get_buffer_at(QEMUFile *f, uint8_t *buf, size_t buflen, off_t pos,
Error **errp);
QIOChannel *qemu_file_get_ioc(QEMUFile *file);
+5 -5
View File
@@ -1010,7 +1010,7 @@ static uint64_t physical_memory_sync_dirty_bitmap(RAMBlock *rb,
unsigned long *dest = rb->bmap;
/* start address and length is aligned at the start of a word? */
if ((((ram_addr_t)word * BITS_PER_LONG) << TARGET_PAGE_BITS) ==
if (((word * BITS_PER_LONG) << TARGET_PAGE_BITS) ==
(start + rb->offset) &&
!(length & ((BITS_PER_LONG << TARGET_PAGE_BITS) - 1))) {
int k;
@@ -4137,8 +4137,8 @@ static bool handle_zero_mapped_ram(RAMBlock *block, unsigned long from_bit_idx,
return true;
}
size = (size_t)TARGET_PAGE_SIZE * (to_bit_idx - from_bit_idx);
offset = ((ram_addr_t)from_bit_idx) << TARGET_PAGE_BITS;
size = TARGET_PAGE_SIZE * (to_bit_idx - from_bit_idx);
offset = from_bit_idx << TARGET_PAGE_BITS;
host = host_from_ram_block_offset(block, offset);
if (!host) {
error_setg(errp, "zero page outside of ramblock %s range",
@@ -4172,8 +4172,8 @@ static bool read_ramblock_mapped_ram(QEMUFile *f, RAMBlock *block,
/* Non-zero pages */
clear_bit_idx = find_next_zero_bit(bitmap, num_pages, set_bit_idx + 1);
unread = (size_t)TARGET_PAGE_SIZE * (clear_bit_idx - set_bit_idx);
offset = ((ram_addr_t)set_bit_idx) << TARGET_PAGE_BITS;
unread = TARGET_PAGE_SIZE * (clear_bit_idx - set_bit_idx);
offset = set_bit_idx << TARGET_PAGE_BITS;
while (unread > 0) {
host = host_from_ram_block_offset(block, offset);
-7
View File
@@ -64,7 +64,6 @@
#include "system/runstate.h"
#include "system/system.h"
#include "system/xen.h"
#include "system/whpx.h"
#include "migration/colo.h"
#include "qemu/bitmap.h"
#include "net/announce.h"
@@ -3318,12 +3317,6 @@ bool save_snapshot(const char *name, bool overwrite, const char *vmstate,
return false;
}
if (whpx_enabled()) {
error_setg(errp,
"WHPX: internal VM snapshots are not supported; use stopped-VM file migration");
return false;
}
if (!replay_can_snapshot()) {
error_setg(errp, "Record/replay does not allow making snapshot "
"right now. Try once more later.");
+2 -92
View File
@@ -1120,73 +1120,6 @@
'axis' : 'InputAxis',
'value' : 'int' } }
##
# @InputScrollPhase:
#
# Phase of a scroll gesture, such as two fingers moving on a touchpad.
#
# @none: The scroll is not part of a gesture.
#
# @may-begin: Fingers rest on the device, and a gesture may begin.
#
# @began: A gesture began.
#
# @changed: A gesture moved.
#
# @ended: A gesture ended.
#
# @cancelled: A gesture was cancelled.
#
# Since: 11.2
##
{ 'enum' : 'InputScrollPhase',
'data' : [ 'none', 'may-begin', 'began', 'changed', 'ended',
'cancelled' ] }
##
# @InputScrollMomentum:
#
# Phase of the momentum scrolling that follows a scroll gesture, which
# the source of the events computes.
#
# @none: The scroll is not momentum scrolling.
#
# @began: Momentum scrolling began.
#
# @changed: Momentum scrolling continued.
#
# @ended: Momentum scrolling ended.
#
# Since: 11.2
##
{ 'enum' : 'InputScrollMomentum',
'data' : [ 'none', 'began', 'changed', 'ended' ] }
##
# @InputScrollEvent:
#
# Smooth scroll input event: a distance to scroll rather than wheel
# notches, with the phases of the gesture it belongs to. The events
# up to the next synchronization make one report, and carry the same
# @phase and @momentum.
#
# @axis: Which axis is referenced by @value.
#
# @value: Distance in 1/256 pixel. Positive values scroll up (y) or
# left (x), as @wheel-up and @wheel-left of @InputButton do.
#
# @phase: Phase of the gesture.
#
# @momentum: Phase of the momentum scrolling.
#
# Since: 11.2
##
{ 'struct' : 'InputScrollEvent',
'data' : { 'axis' : 'InputAxis',
'value' : 'int',
'phase' : 'InputScrollPhase',
'momentum' : 'InputScrollMomentum' } }
##
# @InputEventKind:
#
@@ -1200,12 +1133,10 @@
#
# @mtt: a multi-touch input event
#
# @scroll: a smooth scroll input event (since 11.2)
#
# Since: 2.0
##
{ 'enum': 'InputEventKind',
'data': [ 'key', 'btn', 'rel', 'abs', 'mtt', 'scroll' ] }
'data': [ 'key', 'btn', 'rel', 'abs', 'mtt' ] }
##
# @InputKeyEventWrapper:
@@ -1247,16 +1178,6 @@
{ 'struct': 'InputMultiTouchEventWrapper',
'data': { 'data': 'InputMultiTouchEvent' } }
##
# @InputScrollEventWrapper:
#
# @data: Smooth scroll input event
#
# Since: 11.2
##
{ 'struct': 'InputScrollEventWrapper',
'data': { 'data': 'InputScrollEvent' } }
##
# @InputEvent:
# Input event union.
@@ -1272,8 +1193,7 @@
'btn' : 'InputBtnEventWrapper',
'rel' : 'InputMoveEventWrapper',
'abs' : 'InputMoveEventWrapper',
'mtt' : 'InputMultiTouchEventWrapper',
'scroll' : 'InputScrollEventWrapper' } }
'mtt' : 'InputMultiTouchEventWrapper' } }
##
# @input-send-event:
@@ -1340,16 +1260,6 @@
# { "type": "abs", "data" : { "axis": "x", "value" : 20000 } },
# { "type": "abs", "data" : { "axis": "y", "value" : 400 } } ] } }
# <- { "return": {} }
#
# .. qmp-example::
# :title: Begin a scroll gesture, moving 10 pixels up
#
# -> { "execute": "input-send-event" ,
# "arguments": { "events": [
# { "type": "scroll", "data" : { "axis": "y",
# "value" : 2560, "phase": "began",
# "momentum": "none" } } ] } }
# <- { "return": {} }
##
{ 'command': 'input-send-event',
'data': { '*device': 'str',
+3 -4
View File
@@ -2876,7 +2876,7 @@ DEF("smbios", HAS_ARG, QEMU_OPTION_smbios,
"-smbios type=11[,value=str][,path=filename]\n"
" specify SMBIOS type 11 fields\n"
"-smbios type=17[,loc_pfx=str][,bank=str][,manufacturer=str][,serial=str]\n"
" [,asset=str][,part=str][,speed=%d][,memory_type=%d]\n"
" [,asset=str][,part=str][,speed=%d]\n"
" specify SMBIOS type 17 fields\n"
"-smbios type=41[,designation=str][,kind=str][,instance=%d][,pcidev=str]\n"
" specify SMBIOS type 41 fields\n",
@@ -2942,9 +2942,8 @@ SRST
String 3: myapp:some extra data
``-smbios type=17[,loc_pfx=str][,bank=str][,manufacturer=str][,serial=str][,asset=str][,part=str][,speed=%d][,memory_type=%d]``
Specify SMBIOS type 17 fields. ``memory_type`` is the Memory Type
field's value, 1 to 255 (7, RAM, by default; 26 is DDR4).
``-smbios type=17[,loc_pfx=str][,bank=str][,manufacturer=str][,serial=str][,asset=str][,part=str][,speed=%d]``
Specify SMBIOS type 17 fields
``-smbios type=41[,designation=str][,kind=str][,instance=%d][,pcidev=str]``
Specify SMBIOS type 41 fields
Loaded 100 of 136 files, more files were not shown because too many files have changed in this diff. Show more