Implementing a MSHV (Microsoft Hypervisor) accelerator
v4 cover Implementing a MSHV (Microsoft Hypervisor) accelerator
Hello all,
This is the fourth revision of a patch set implementing an accelerator for the MSHV kernel driver, exposing HyperV to Linux "Dom0" hosts in various scenarios. Thanks for the feedback to the previous revision, I tried to incorporate those. The changes in the currenct patchset beyond the suggested fixes are mostly related to the replacement of retired ioctl calls that will not part of the upstreamed MSHV kernel driver.
Best regards,
magnus
Changelog:
v3 => v4
- Addressed code review comments
- Extended mention of MSHV accelerator in documentation
- Reworked the QMP query-mshv command to work like other accelerator's implementations (availability of the accelerator, instead of issueing stat() on /dev/mshv)
- Added a HMP info mshv command
- Replaced ioctls MSHV_GET_VP_REGISTERS, MSHV_SET_VP_REGISTERS, and MSHV_TRANSLATE_GVA with calls to MSHV_ROOT_HVCALL
- Allocate static pages in cpu->accel for the HVCALL input/output params (to avoid allocations in the MMIO exit path)
v2 => v3
- Addressed code review comments (style)
- Reserve GSI 01-23 for IO-APIC pins (this resolved a problem in which MSI routes would be overwritten with interrupts from legacy devices, breaking irqfd notification for virtio-blk queues)
- Guard memory slot table with mutex and RCU mechanism (multiple threads might access the memory slot table, and in the event of an UNMAPPED_GPA exit we need to query the table for an unmapped region covering that GPA)
- Include memory slot manager in MshvState
- Produce mshv.h kernel header with ./scripts/update-linux-headers.sh from linux 6.16 (not all UAPI definitions are defined in the upstream kernel, hence we ship hw/hyper/hvgdk*.h and hw/hyperv/hvhdk*.h headers)
- Added a QMP command query-mshv (a requirement for integration into higher-level tooling)
- Removed handling of HALT vm exit, since this is not a supported HV message any more.
- Added 2 maintainers from Microsoft for the respective file hierarchy
- Added mshv as accelerator option in the documentation
RFC (v1) => v2
- Addressed code review comments (style, consilidation).
- Rewrote the logic that handles overlap-in-userspace mappings to use a static list of slots, inspired by the HVF accelerator code.
- Fixed a bug that wrote corrupt payload in a MSHV_SET_MSI_ROUTING call, preventing vhost=on to work on tap network devices.
- Removed an erronous truncation of guest addresses to 32bit when registering ioeventfd's using MSHV_IOEVENTFD. This resulted in shadowing of low memory when ioevents were registered with addresses beyond the 4gb barrier and thus unexpected "unmapped gpa" vm exits in lower mem regions (impacting io performance).
- Fixed problem in which the MSI routing table was committed for KVM KVM instead of MSHV in virtio-pci bus initialization.
- Added handler for HLT vm exits.
- The above fixes removed a few limitation present in the previous revision:
- Guest with machine type "pc" are booting (testing is still mostly performed with q35)
- Tap network devices can be used with vhost=on option.
- Seabios can be used with >2.75G memory and multiple virtio-pci devices
- I/O performance improvement as extranous MMIO vm exits are avoided by registering ioevents with a correct address.
Notes:
- A discrete kernel ioctl "set_immediate_exit" (to avoid a race condition when handling terminiation signals like ctrl-a x) has been tested and proven to mitigate the problem. Since other consumers of /dev/mshv have simular requirements as QEMU, we opted to iterate a bit more on the respective kernel interface.
Magnus Kulke (26):
accel: Add Meson and config support for MSHV accelerator target/i386/emulate: Allow instruction decoding from stream target/i386/mshv: Add x86 decoder/emu implementation hw/intc: Generalize APIC helper names from kvm_* to accel_* include/hw/hyperv: Add MSHV ABI header definitions linux-headers/linux: Add mshv.h headers accel/mshv: Add accelerator skeleton
accel/mshv: Register memory region listeners accel/mshv: Initialize VM partition
accel/mshv: Add vCPU creation and execution loop accel/mshv: Add vCPU signal handling target/i386/mshv: Add CPU create and remove logic target/i386/mshv: Implement mshv_store_regs() target/i386/mshv: Implement mshv_get_standard_regs() target/i386/mshv: Implement mshv_get_special_regs() target/i386/mshv: Implement mshv_arch_put_registers() target/i386/mshv: Set local interrupt controller state target/i386/mshv: Register CPUID entries with MSHV target/i386/mshv: Register MSRs with MSHV target/i386/mshv: Integrate x86 instruction decoder/emulator target/i386/mshv: Write MSRs to the hypervisor target/i386/mshv: Implement mshv_vcpu_run() accel/mshv: Handle overlapping mem mappings target/i386/mshv: Use preallocated page for hvcall
docs: Add mshv to documentation
MAINTAINERS: Add maintainers for mshv accelerator
Praveen K Paladugu (1):
qapi/accel: Allow to query mshv capabilities
MAINTAINERS | 15 + accel/Kconfig | 3 + accel/accel-irq.c | 106 ++ accel/meson.build | 3 +- accel/mshv/irq.c | 397 +++++++ accel/mshv/mem.c | 562 ++++++++++ accel/mshv/meson.build | 9 + accel/mshv/mshv-all.c | 728 ++++++++++++ accel/mshv/msr.c | 374 +++++++ accel/mshv/trace-events | 33 + accel/mshv/trace.h | 14 + docs/about/build-platforms.rst | 2 +- docs/devel/codebase.rst | 2 +- docs/glossary.rst | 6 +- docs/system/introduction.rst | 3 + hmp-commands-info.hx | 13 + hw/core/machine-hmp-cmds.c | 15 + hw/core/machine-qmp-cmds.c | 14 + hw/intc/apic.c | 8 + hw/intc/ioapic.c | 20 +- hw/virtio/virtio-pci.c | 21 +- include/hw/hyperv/hvgdk.h | 20 + include/hw/hyperv/hvgdk_mini.h | 817 ++++++++++++++ include/hw/hyperv/hvhdk.h | 249 +++++ include/hw/hyperv/hvhdk_mini.h | 102 ++ include/monitor/hmp.h | 1 + include/system/accel-irq.h | 37 + include/system/hw_accel.h | 1 + include/system/mshv.h | 196 ++++ linux-headers/linux/mshv.h | 291 +++++ meson.build | 11 + meson_options.txt | 2 + qapi/accelerator.json | 29 + qemu-options.hx | 16 +- scripts/meson-buildoptions.sh | 3 + scripts/update-linux-headers.sh | 2 +- target/i386/cpu.h | 4 +- target/i386/emulate/meson.build | 7 +- target/i386/emulate/x86_decode.c | 27 +- target/i386/emulate/x86_decode.h | 9 + target/i386/emulate/x86_emu.c | 3 +- target/i386/emulate/x86_emu.h | 2 + target/i386/meson.build | 2 + target/i386/mshv/meson.build | 8 + target/i386/mshv/mshv-cpu.c | 1764 ++++++++++++++++++++++++++++++ target/i386/mshv/x86.c | 297 +++++ 46 files changed, 6208 insertions(+), 40 deletions(-) create mode 100644 accel/accel-irq.c create mode 100644 accel/mshv/irq.c create mode 100644 accel/mshv/mem.c create mode 100644 accel/mshv/meson.build create mode 100644 accel/mshv/mshv-all.c create mode 100644 accel/mshv/msr.c create mode 100644 accel/mshv/trace-events create mode 100644 accel/mshv/trace.h create mode 100644 include/hw/hyperv/hvgdk.h create mode 100644 include/hw/hyperv/hvgdk_mini.h create mode 100644 include/hw/hyperv/hvhdk.h create mode 100644 include/hw/hyperv/hvhdk_mini.h create mode 100644 include/system/accel-irq.h create mode 100644 include/system/mshv.h create mode 100644 linux-headers/linux/mshv.h create mode 100644 target/i386/mshv/meson.build create mode 100644 target/i386/mshv/mshv-cpu.c create mode 100644 target/i386/mshv/x86.c
Signature · 1 line
2.34.1
PATCH v4 1/27 accel: Add Meson and config support for MSHV accelerator
Introduce a Meson feature option and default-config entry to allow building QEMU with MSHV (Microsoft Hypervisor) acceleration support.
This is the first step toward implementing an MSHV backend in QEMU.
--- accel/Kconfig | 3 +++ meson.build | 10 ++++++++++ meson_options.txt | 2 ++ scripts/meson-buildoptions.sh | 3 +++ 4 files changed, 18 insertions(+)
accel/Kconfig +3 -0
@@ -13,6 +13,9 @@ config TCG config KVM bool +config MSHV + bool + config XEN bool select FSDEV_9P if VIRTFS
meson.build +10 -0
@@ -334,6 +334,7 @@ elif cpu == 'x86_64' 'CONFIG_HVF': ['x86_64-softmmu'], 'CONFIG_NVMM': ['i386-softmmu', 'x86_64-softmmu'], 'CONFIG_WHPX': ['i386-softmmu', 'x86_64-softmmu'], + 'CONFIG_MSHV': ['x86_64-softmmu'], } endif
@@ -880,6 +881,14 @@ accelerators = [] if get_option('kvm').allowed() and host_os == 'linux' accelerators += 'CONFIG_KVM' endif + +if get_option('mshv').allowed() and host_os == 'linux' + if get_option('mshv').enabled() and host_machine.cpu() != 'x86_64' + error('mshv accelerator requires x64_64 host') + endif + accelerators += 'CONFIG_MSHV' +endif + if get_option('whpx').allowed() and host_os == 'windows' if get_option('whpx').enabled() and host_machine.cpu() != 'x86_64' error('WHPX requires 64-bit host')
@@ -4821,6 +4830,7 @@ if have_system summary_info += {'HVF support': config_all_accel.has_key('CONFIG_HVF')} summary_info += {'WHPX support': config_all_accel.has_key('CONFIG_WHPX')} summary_info += {'NVMM support': config_all_accel.has_key('CONFIG_NVMM')} + summary_info += {'MSHV support': config_all_accel.has_key('CONFIG_MSHV')} summary_info += {'Xen support': xen.found()} if xen.found() summary_info += {'xen ctrl version': xen.version()}
meson_options.txt +2 -0
@@ -71,6 +71,8 @@ option('malloc', type : 'combo', choices : ['system', 'tcmalloc', 'jemalloc'], option('kvm', type: 'feature', value: 'auto', description: 'KVM acceleration support') +option('mshv', type: 'feature', value: 'auto', + description: 'MSHV acceleration support') option('whpx', type: 'feature', value: 'auto', description: 'WHPX acceleration support') option('hvf', type: 'feature', value: 'auto',
scripts/meson-buildoptions.sh +3 -0
@@ -154,6 +154,7 @@ meson_options_help() { printf "%s\n" ' membarrier membarrier system call (for Linux 4.14+ or Windows' printf "%s\n" ' modules modules support (non Windows)' printf "%s\n" ' mpath Multipath persistent reservation passthrough' + printf "%s\n" ' mshv MSHV acceleration support' printf "%s\n" ' multiprocess Out of process device emulation support' printf "%s\n" ' netmap netmap network backend support' printf "%s\n" ' nettle nettle cryptography support'
@@ -408,6 +409,8 @@ _meson_option_parse() { --disable-modules) printf "%s" -Dmodules=disabled ;; --enable-mpath) printf "%s" -Dmpath=enabled ;; --disable-mpath) printf "%s" -Dmpath=disabled ;; + --enable-mshv) printf "%s" -Dmshv=enabled ;; + --disable-mshv) printf "%s" -Dmshv=disabled ;; --enable-multiprocess) printf "%s" -Dmultiprocess=enabled ;; --disable-multiprocess) printf "%s" -Dmultiprocess=disabled ;; --enable-netmap) printf "%s" -Dnetmap=enabled ;;
Signature · 1 line
2.34.1
Re: [PATCH v4 01/27] accel: Add Meson and config support for MSHV accelerator
Quoted 5 lines · Magnus Kulke
Introduce a Meson feature option and default-config entry to allow building QEMU with MSHV (Microsoft Hypervisor) acceleration support.
This is the first step toward implementing an MSHV backend in QEMU.
Quoted 7 lines
Signed-off-by Magnus Kulke <[email protected]>--- accel/Kconfig | 3 +++ meson.build | 10 ++++++++++ meson_options.txt | 2 ++ scripts/meson-buildoptions.sh | 3 +++ 4 files changed, 18 insertions(+)
With regards,
Daniel
Signature · 3 lines
|: https://berrange.com -o- https://www.flickr.com/photos/dberrange :| |: https://libvirt.org -o- https://fstop138.berrange.com :| |: https://entangle-photo.org -o- https://www.instagram.com/dberrange :|
Re: [PATCH v4 01/27] accel: Add Meson and config support for MSHV accelerator
In reply to Magnus KulkeQuoted 18 lines · Magnus Kulke
Introduce a Meson feature option and default-config entry to allow building QEMU with MSHV (Microsoft Hypervisor) acceleration support.
This is the first step toward implementing an MSHV backend in QEMU.
Signed-off-by Magnus Kulke <[email protected]>--- accel/Kconfig | 3 +++ meson.build | 10 ++++++++++ meson_options.txt | 2 ++ scripts/meson-buildoptions.sh | 3 +++ 4 files changed, 18 insertions(+)meson.build +0
-0
meson.build accelerators = [] · line 887
Quoted 5 lines
meson.build +3
-0+if get_option('mshv').allowed() and host_os == 'linux' + if get_option('mshv').enabled() and host_machine.cpu() != 'x86_64' + error('mshv accelerator requires x64_64 host')
Either:
error('MSHV accelerator requires x86_64 host')
Or simply:
error('MSHV accelerator requires 64-bit host')
Quoted 3 lines
meson.build +3
-0+ endif + accelerators += 'CONFIG_MSHV' +endif
PATCH v4 2/27 target/i386/emulate: Allow instruction decoding from stream
In reply to Magnus KulkeIntroduce a new helper function to decode x86 instructions from a raw instruction byte stream. MSHV delivers an instruction stream in a buffer of the vm_exit message. It can be used to speed up MMIO emulation, since instructions do not have to be fetched and translated.
Added "fetch_instruction()" op to x86_emul_ops() to improve traceability.
--- target/i386/emulate/x86_decode.c | 27 +++++++++++++++++++++++---- target/i386/emulate/x86_decode.h | 9 +++++++++ target/i386/emulate/x86_emu.c | 3 ++- target/i386/emulate/x86_emu.h | 2 ++ 4 files changed, 36 insertions(+), 5 deletions(-)
target/i386/emulate/x86_decode.c +23 -4
@@ -71,10 +71,16 @@ static inline uint64_t decode_bytes(CPUX86State *env, struct x86_decode *decode,VM_PANIC_EX ("%s invalid size %d\n" , __func__, size);break ; } -target_ulong va =linear_rip (env_cpu (env), env->eip) + decode->len; - emul_ops->read_mem (env_cpu (env), &val, va, size); + +/* copy the bytes from the instruction stream, if available */ +if (decode->stream && decode->len + size <= decode->stream->len) { +memcpy (&val, decode->stream->bytes + decode->len, size); + }else { +target_ulong va =linear_rip (env_cpu (env), env->eip) + decode->len; + emul_ops->fetch_instruction (env_cpu (env), &val, va, size); + } decode->len += size; - +return val; }
@@ -2076,9 +2082,10 @@ static void decode_opcodes(CPUX86State *env, struct x86_decode *decode) } } -uint32_t decode_instruction (CPUX86State *env,struct x86_decode *decode) +static uint32_t decode_opcode (CPUX86State *env,struct x86_decode *decode) {memset (decode,0 ,sizeof (*decode)); +decode_prefix (env, decode);set_addressing_size (env, decode);set_operand_size (env, decode);
@@ -2088,6 +2095,18 @@ uint32_t decode_instruction(CPUX86State *env, struct x86_decode *decode)return decode->len; } +uint32_t decode_instruction (CPUX86State *env,struct x86_decode *decode) +{ +return decode_opcode (env, decode); +} + +uint32_t decode_instruction_stream (CPUX86State *env,struct x86_decode *decode, +struct x86_insn_stream *stream) +{ + decode->stream = stream; +return decode_opcode (env, decode); +} +void init_decoder (void ) {int i;
target/i386/emulate/x86_decode.h +9 -0
@@ -272,6 +272,11 @@ typedef struct x86_decode_op { }; } x86_decode_op; +typedef struct x86_insn_stream { +const uint8_t *bytes; +size_t len; +}x86_insn_stream ; + typedef struct x86_decode { int len; uint8_t opcode[4];
@@ -298,11 +303,15 @@ typedef struct x86_decode {struct x86_modrm modrm;struct x86_decode_op op[4 ];bool is_fpu; + +x86_insn_stream *stream; } x86_decode;uint64_t sign (uint64_t val,int size);uint32_t decode_instruction (CPUX86State *env,struct x86_decode *decode); +uint32_t decode_instruction_stream (CPUX86State *env,struct x86_decode *decode, +struct x86_insn_stream *stream);void *get_reg_ref (CPUX86State *env,int reg,int rex_present,int is_extended,int size);
target/i386/emulate/x86_emu.c +2 -1
@@ -1246,7 +1246,8 @@ static void init_cmd_handler(void)bool exec_instruction (CPUX86State *env,struct x86_decode *ins) {if (!_cmd_handler[ins->cmd].handler) { -printf ("Unimplemented handler (" TARGET_FMT_lx") for %d (%x %x) \n" , env->eip, +printf ("Unimplemented handler (" TARGET_FMT_lx") for %d (%x %x)\n" , + env->eip, ins->cmd, ins->opcode[0 ], ins->opcode_len >1 ? ins->opcode[1 ] :0 ); env->eip += ins->len;
target/i386/emulate/x86_emu.h +2 -0
@@ -24,6 +24,8 @@#include "cpu.h" struct x86_emul_ops { +void (*fetch_instruction)(CPUState *cpu,void *data,target_ulong addr, +int bytes);void (*read_mem)(CPUState *cpu,void *data,target_ulong addr,int bytes);void (*write_mem)(CPUState *cpu,void *data,target_ulong addr,int bytes); void (*read_segment_descriptor)(CPUState *cpu, struct x86_segment_descriptor *desc,
Signature · 1 line
2.34.1
PATCH v4 3/27 target/i386/mshv: Add x86 decoder/emu implementation
In reply to Magnus KulkeThe MSHV accelerator requires a x86 decoder/emulator in userland to emulate MMIO instructions. This change contains the implementations for the generalized i386 instruction decoder/emulator.
--- include/system/mshv.h | 25 +++ target/i386/cpu.h | 2 +- target/i386/emulate/meson.build | 7 +- target/i386/meson.build | 2 + target/i386/mshv/meson.build | 7 + target/i386/mshv/x86.c | 297 ++++++++++++++++++++++++++++++++ 6 files changed, 337 insertions(+), 3 deletions(-) create mode 100644 include/system/mshv.h create mode 100644 target/i386/mshv/meson.build create mode 100644 target/i386/mshv/x86.c
include/system/mshv.h new file +25 -0
@@ -0,0 +1,25 @@ +/* +* QEMU MSHV support +* +* Copyright Microsoft, Corp. 2025 +* +* Authors: Ziqiao Zhou <[email protected]> +* Magnus Kulke <[email protected]> +* Jinank Jain <[email protected]> +* +* SPDX-License-Identifier: GPL-2.0-or-later +* +*/ + +#ifndef QEMU_MSHV_INT_H +#define QEMU_MSHV_INT_H + +#ifdef COMPILING_PER_TARGET +#ifdef CONFIG_MSHV +#define CONFIG_MSHV_IS_POSSIBLE +#endif +#else +#define CONFIG_MSHV_IS_POSSIBLE +#endif + +#endif
target/i386/cpu.h +1 -1
@@ -2126,7 +2126,7 @@ typedef struct CPUArchState {QEMUTimer *xen_periodic_timer;QemuMutex xen_timers_lock;#endif -#if defined(CONFIG_HVF ) +#if defined(CONFIG_HVF ) || defined(CONFIG_MSHV )void *emu_mmio_buf;#endif
target/i386/emulate/meson.build +5 -2
@@ -1,5 +1,8 @@ -i386_system_ss.add(when: [hvf, 'CONFIG_HVF'], if_true: files( +emulator_files = files( 'x86_decode.c', 'x86_emu.c', 'x86_flags.c', -)) +) + +i386_system_ss.add(when: [hvf, 'CONFIG_HVF'], if_true: emulator_files) +i386_system_ss.add(when: 'CONFIG_MSHV', if_true: emulator_files)
target/i386/meson.build +2 -0
@@ -13,6 +13,7 @@ i386_ss.add(when: 'CONFIG_KVM', if_true: files('host-cpu.c')) i386_ss.add(when: 'CONFIG_HVF', if_true: files('host-cpu.c')) i386_ss.add(when: 'CONFIG_WHPX', if_true: files('host-cpu.c')) i386_ss.add(when: 'CONFIG_NVMM', if_true: files('host-cpu.c')) +i386_ss.add(when: 'CONFIG_MSHV', if_true: files('host-cpu.c')) i386_system_ss = ss.source_set() i386_system_ss.add(files(
@@ -34,6 +35,7 @@ subdir('nvmm') subdir('hvf') subdir('tcg') subdir('emulate') +subdir('mshv') target_arch += {'i386': i386_ss} target_system_arch += {'i386': i386_system_ss}
target/i386/mshv/meson.build new file +7 -0
@@ -0,0 +1,7 @@ +i386_mshv_ss = ss.source_set() + +i386_mshv_ss.add(files( + 'x86.c', +)) + +i386_system_ss.add_all(when: 'CONFIG_MSHV', if_true: i386_mshv_ss)
target/i386/mshv/x86.c new file +297 -0
297 lines not on this page · raw message
Signature · 1 line
2.34.1
Re: [PATCH v4 03/27] target/i386/mshv: Add x86 decoder/emu implementation
Quoted 5 lines · * Magnus Kulke ([email protected]) wrote:
The MSHV accelerator requires a x86 decoder/emulator in userland to emulate MMIO instructions. This change contains the implementations for the generalized i386 instruction decoder/emulator.
Signed-off-by Magnus Kulke <[email protected]>
Hi Magnus,
Just some things I noticed.
Quoted 12 lines
--- include/system/mshv.h | 25 +++ target/i386/cpu.h | 2 +- target/i386/emulate/meson.build | 7 +- target/i386/meson.build | 2 + target/i386/mshv/meson.build | 7 + target/i386/mshv/x86.c | 297 ++++++++++++++++++++++++++++++++ 6 files changed, 337 insertions(+), 3 deletions(-) create mode 100644 include/system/mshv.h create mode 100644 target/i386/mshv/meson.build create mode 100644 target/i386/mshv/x86.c
<snip>
Quoted 25 lines
target/i386/mshv/x86.c new file +19
-0@@ -0,0 +1,297 @@ +/* +* QEMU MSHV support +* +* Copyright Microsoft, Corp. 2025 +* +* Authors: Magnus Kulke <[email protected]> +* +* SPDX-License-Identifier: GPL-2.0-or-later +*/ + +#include "qemu/osdep.h" + +#include "cpu.h" +#include "emulate/x86_decode.h" +#include "emulate/x86_emu.h" +#include "qemu/typedefs.h" +#include "qemu/error-report.h" +#include "system/mshv.h" +
target/i386/mshv/x86.c line 29
Quoted 10 lines
target/i386/mshv/x86.c new file +10
-0+/* RW or Exec segment */ +static const uint8_t RWRX_SEGMENT_TYPE =0x2 ; +static const uint8_t CODE_SEGMENT_TYPE =0x8 ; +static const uint8_t EXPAND_DOWN_SEGMENT_TYPE =0x4 ; + +typedef enum CpuMode { +REAL_MODE , +PROTECTED_MODE , +LONG_MODE , +}CpuMode ;
These consts and enum look like things that should be in some shared x86 thing; in fact there are some existing routines that partially map to some of this.
For example 'x86_is_real' is declared in target/i386/emulate/x86.h and defined in target/i386/hvf/x86.c (hmm that's a bit weird). So it's probably best to check if what you want already exists, move it into target/i386 somewhere I guess, and everyone shares it.
(Don't worry, I'm not suggesting you fix all the zillions of places that open code this type of stuff, but once it's in somewhere shared that can happen).
Quoted 8 lines
target/i386/mshv/x86.c new file +8
-0+static CpuMode cpu_mode (CPUState *cpu) +{ +enum CpuMode m =REAL_MODE ; + +if (x86_is_protected (cpu)) { + m =PROTECTED_MODE ; + +if (x86_is_long_mode (cpu)) {
target/i386/mshv/x86.c line 48
Quoted 10 lines
target/i386/mshv/x86.c new file +10
-0+ m =LONG_MODE ; + } + } + +return m; +} + +static bool segment_type_ro (const SegmentCache *seg) +{ +uint32_t type_ = (seg->flags >>DESC_TYPE_SHIFT ) &15 ;
A variable ending in '_' is a bit odd for qemu.
Dave
Quoted 252 lines
target/i386/mshv/x86.c new file +249
-0+return (type_ & (~RWRX_SEGMENT_TYPE )) ==0 ; +} + +static bool segment_type_code (const SegmentCache *seg) +{ +uint32_t type_ = (seg->flags >>DESC_TYPE_SHIFT ) &15 ; +return (type_ &CODE_SEGMENT_TYPE ) !=0 ; +} + +static bool segment_expands_down (const SegmentCache *seg) +{ +uint32_t type_ = (seg->flags >>DESC_TYPE_SHIFT ) &15 ; + +if (segment_type_code (seg)) { +return false; + } + +return (type_ &EXPAND_DOWN_SEGMENT_TYPE ) !=0 ; +} + +static uint32_t segment_limit (const SegmentCache *seg) +{ +uint32_t limit = seg->limit; +uint32_t granularity = (seg->flags &DESC_G_MASK ) !=0 ; + +if (granularity !=0 ) { + limit = (limit <<12 ) |0xFFF ; + } + +return limit; +} + +static uint8_t segment_db (const SegmentCache *seg) +{ +return (seg->flags >>DESC_B_SHIFT ) &1 ; +} + +static uint32_t segment_max_limit (const SegmentCache *seg) +{ +if (segment_db (seg) !=0 ) { +return 0xFFFFFFFF ; + } +return 0xFFFF ; +} + +static int linearize (CPUState *cpu, +target_ulong logical_addr,target_ulong *linear_addr, +X86Seg seg_idx) +{ +enum CpuMode mode; +X86CPU *x86_cpu =X86_CPU (cpu); +CPUX86State *env = &x86_cpu->env; +SegmentCache *seg = &env->segs[seg_idx]; +target_ulong base = seg->base; +target_ulong logical_addr_32b; +uint32_t limit; +/* TODO: the emulator will not pass us "write" indicator yet */ +bool write = false; + + mode =cpu_mode (cpu); + +switch (mode) { +case LONG_MODE : +if (__builtin_add_overflow (logical_addr, base, linear_addr)) { +error_report ("Address overflow" ); +return -1 ; + } +break ; +case PROTECTED_MODE : +case REAL_MODE : +if (segment_type_ro (seg) && write) { +error_report ("Cannot write to read-only segment" ); +return -1 ; + } + + logical_addr_32b = logical_addr &0xFFFFFFFF ; + limit =segment_limit (seg); + +if (segment_expands_down (seg)) { +if (logical_addr_32b >= limit) { +error_report ("Address exceeds limit (expands down)" ); +return -1 ; + } + + limit =segment_max_limit (seg); + } + +if (logical_addr_32b > limit) { +error_report ("Address exceeds limit %u" , limit); +return -1 ; + } + *linear_addr = logical_addr_32b + base; +break ; +default : +error_report ("Unknown cpu mode: %d" , mode); +return -1 ; + } + +return 0 ; +} + +bool x86_read_segment_descriptor (CPUState *cpu, +struct x86_segment_descriptor *desc, +x86_segment_selector sel) +{ +target_ulong base; +uint32_t limit; +X86CPU *x86_cpu =X86_CPU (cpu); +CPUX86State *env = &x86_cpu->env; +target_ulong gva; + +memset (desc,0 ,sizeof (*desc)); + +/* valid gdt descriptors start from index 1 */ +if (!sel.index &&GDT_SEL == sel.ti) { +return false; + } + +if (GDT_SEL == sel.ti) { + base = env->gdt.base; + limit = env->gdt.limit; + }else { + base = env->ldt.base; + limit = env->ldt.limit; + } + +if (sel.index *8 >= limit) { +return false; + } + + gva = base + sel.index *8 ; + emul_ops->read_mem (cpu, desc, gva,sizeof (*desc)); + +return true; +} + +bool x86_read_call_gate (CPUState *cpu,struct x86_call_gate *idt_desc, +int gate) +{ +target_ulong base; +uint32_t limit; +X86CPU *x86_cpu =X86_CPU (cpu); +CPUX86State *env = &x86_cpu->env; +target_ulong gva; + + base = env->idt.base; + limit = env->idt.limit; + +memset (idt_desc,0 ,sizeof (*idt_desc)); +if (gate *8 >= limit) { +perror ("call gate exceeds idt limit" ); +return false; + } + + gva = base + gate *8 ; + emul_ops->read_mem (cpu, idt_desc, gva,sizeof (*idt_desc)); + +return true; +} + +bool x86_is_protected (CPUState *cpu) +{ +X86CPU *x86_cpu =X86_CPU (cpu); +CPUX86State *env = &x86_cpu->env; +uint64_t cr0 = env->cr[0 ]; + +return cr0 &CR0_PE_MASK ; +} + +bool x86_is_real (CPUState *cpu) +{ +return !x86_is_protected (cpu); +} + +bool x86_is_v8086 (CPUState *cpu) +{ +X86CPU *x86_cpu =X86_CPU (cpu); +CPUX86State *env = &x86_cpu->env; +return x86_is_protected (cpu) && (env->eflags &VM_MASK ); +} + +bool x86_is_long_mode (CPUState *cpu) +{ +X86CPU *x86_cpu =X86_CPU (cpu); +CPUX86State *env = &x86_cpu->env; +uint64_t efer = env->efer; +uint64_t lme_lma = (MSR_EFER_LME |MSR_EFER_LMA ); + +return ((efer & lme_lma) == lme_lma); +} + +bool x86_is_long64_mode (CPUState *cpu) +{ +error_report ("unimplemented: is_long64_mode()" ); +abort (); +} + +bool x86_is_paging_mode (CPUState *cpu) +{ +X86CPU *x86_cpu =X86_CPU (cpu); +CPUX86State *env = &x86_cpu->env; +uint64_t cr0 = env->cr[0 ]; + +return cr0 &CR0_PG_MASK ; +} + +bool x86_is_pae_enabled (CPUState *cpu) +{ +X86CPU *x86_cpu =X86_CPU (cpu); +CPUX86State *env = &x86_cpu->env; +uint64_t cr4 = env->cr[4 ]; + +return cr4 &CR4_PAE_MASK ; +} + +target_ulong linear_addr (CPUState *cpu,target_ulong addr,X86Seg seg) +{ +int ret; +target_ulong linear_addr; + + ret =linearize (cpu, addr, &linear_addr, seg); +if (ret <0 ) { +error_report ("failed to linearize address" ); +abort (); + } + +return linear_addr; +} + +target_ulong linear_addr_size (CPUState *cpu,target_ulong addr,int size, +X86Seg seg) +{ +switch (size) { +case 2 : + addr = (uint16_t )addr; +break ; +case 4 : + addr = (uint32_t )addr; +break ; +default : +break ; + } +return linear_addr (cpu, addr, seg); +} + +target_ulong linear_rip (CPUState *cpu,target_ulong rip) +{ +return linear_addr (cpu, rip,R_CS ); +}Signature · 1 line
2.34.1
Signature · 4 lines
-----Open up your eyes, open up your mind, open up your code ------- / Dr. David Alan Gilbert | Running GNU/Linux | Happy \ \ dave @ treblig.org | | In Hex / \ _________________________|_____ http://www.treblig.org |_______/
Re: [PATCH v4 03/27] target/i386/mshv: Add x86 decoder/emu implementation
Quoted 8 lines · Dr. David Alan Gilbert
For example '
x86_is_real' is declared intarget/i386/emulate/x86.hand defined intarget/i386/hvf/x86.c(hmm that's a bit weird). So it's probably best to check if what you want already exists, move it into target/i386 somewhere I guess, and everyone shares it.
Currently there isn’t a backend-agnostic interface for this. It was part of the import of HVF support to qemu from downstream.
Notably means that the emulate infrastructure isn’t usable by multiple backends in the same build. It might be possible to get away without that however as HVF is macOS specific, MSHV is Linux-specific and WHPX (which is currently using winhvemulator instead of this) is Windows-specific...
Re: [CRM114spam]: Re: [PATCH v4 03/27] target/i386/mshv: Add x86 decoder/emu implementation
Quoted 11 lines · * Mohamed Mediouni ([email protected]) wrote:
Quoted 8 lines · Dr. David Alan Gilbert
For example '
x86_is_real' is declared intarget/i386/emulate/x86.hand defined intarget/i386/hvf/x86.c(hmm that's a bit weird). So it's probably best to check if what you want already exists, move it into target/i386 somewhere I guess, and everyone shares it.Currently there isn’t a backend-agnostic interface for this. It was part of the import of HVF support to qemu from downstream.
Hmm.
Quoted 4 lines
Notably means that the emulate infrastructure isn’t usable by multiple backends in the same build. It might be possible to get away without that however as HVF is macOS specific, MSHV is Linux-specific and WHPX (which is currently using winhvemulator instead of this) is Windows-specific...
It does scare me a bit having 2 different functions with the same name like that; but hmm OK...
But - x86_is_real() is identical in these cases - the x86_is_protected() is the implementation dependent bit.
The only bit that seems different is the reading of the register, eg. CR0, so there could be a:
x86_read_CR0(CPUState *cpu)
and the x86_is_real and x86_is_paging_mode all be shared (as inline's ???).
But this does all get messy - I mean, even if MSHV is Linux specific, and HVF is macos specific; it's a shame that the logic behind x86_is_* is open coded in all of tcg, kvm and copied twice in hvf and mshv.
(I don't understand the structure as to why some stuff needs backend specific reads and some are in env).
Dave
Quoted 1 line
Signature · 4 lines
-----Open up your eyes, open up your mind, open up your code ------- / Dr. David Alan Gilbert | Running GNU/Linux | Happy \ \ dave @ treblig.org | | In Hex / \ _________________________|_____ http://www.treblig.org |_______/
Re: [CRM114spam]: Re: [PATCH v4 03/27] target/i386/mshv: Add x86 decoder/emu implementation
Quoted 31 lines · Dr. David Alan Gilbert
Quoted 11 lines · * Mohamed Mediouni ([email protected]) wrote:
Quoted 8 lines · Dr. David Alan Gilbert
For example '
x86_is_real' is declared intarget/i386/emulate/x86.hand defined intarget/i386/hvf/x86.c(hmm that's a bit weird). So it's probably best to check if what you want already exists, move it into target/i386 somewhere I guess, and everyone shares it.Currently there isn’t a backend-agnostic interface for this. It was part of the import of HVF support to qemu from downstream.
Hmm.
Quoted 4 lines
Notably means that the emulate infrastructure isn’t usable by multiple backends in the same build. It might be possible to get away without that however as HVF is macOS specific, MSHV is Linux-specific and WHPX (which is currently using winhvemulator instead of this) is Windows-specific...
It does scare me a bit having 2 different functions with the same name like that; but hmm OK...
But -
x86_is_real()is identical in these cases - thex86_is_protected()is the implementation dependent bit.
The only bit that seems different is the reading of the register, eg. CR0, so there could be a:x86_read_CR0(CPUState *cpu)and the
x86_is_realandx86_is_paging_modeall be shared (as inline's ???).
Quoted 8 lines
But this does all get messy - I mean, even if MSHV is Linux specific, and HVF is macos specific; it's a shame that the logic behind x86_is_* is open coded in all of tcg, kvm and copied twice in hvf and mshv.
(I don't understand the structure as to why some stuff needs backend specific reads and some are in env).
Dave
Hey Dave,
in preperation for the MSHV patches Wei Liu did rework the HVF x86 emulator code and abstracted it into target/i386/emulate, so we could use prior art as much as possible. Since HVF had to perform similar userland decoding/emulation of instruction on MMIO exits that was a good fit. However, the requirements are not exactly the same.
Thus, in the current approach there is some duplication, like x86_is_real() (which is sort of trivial and arguably could indeed be inlined), but e.g. x86_is_paging_mode() would have different implementations per accelerator target.
best,
magnus
Re: [CRM114spam]: Re: [PATCH v4 03/27] target/i386/mshv: Add x86 decoder/emu implementation
In reply to Dr. David Alan GilbertQuoted 2 lines · Dr. David Alan Gilbert
(I don't understand the structure as to why some stuff needs backend specific reads and some are in env).
Ah, that's because HVF is working on a slightly different level of abstraction I suppose: the HVF impl will read/write values to VMCS via VMREAD/VMWRITE, which would be Intel VMX specific.
Re: [PATCH v4 03/27] target/i386/mshv: Add x86 decoder/emu implementation
In reply to Magnus KulkeQuoted 24 lines · Magnus Kulke
The MSHV accelerator requires a x86 decoder/emulator in userland to emulate MMIO instructions. This change contains the implementations for the generalized i386 instruction decoder/emulator.
Signed-off-by Magnus Kulke <[email protected]>--- include/system/mshv.h | 25 +++ target/i386/cpu.h | 2 +- target/i386/emulate/meson.build | 7 +- target/i386/meson.build | 2 + target/i386/mshv/meson.build | 7 + target/i386/mshv/x86.c | 297 ++++++++++++++++++++++++++++++++ 6 files changed, 337 insertions(+), 3 deletions(-) create mode 100644 include/system/mshv.h create mode 100644 target/i386/mshv/meson.build create mode 100644 target/i386/mshv/x86.ctarget/i386/mshv/meson.build new file +0
-0
target/i386/mshv/meson.build line 7
Quoted 7 lines
target/i386/mshv/meson.build new file +7
-0@@ -0,0 +1,7 @@ +i386_mshv_ss = ss.source_set() + +i386_mshv_ss.add(files( + 'x86.c', +)) + +i386_system_ss.add_all(when: 'CONFIG_MSHV', if_true: i386_mshv_ss)
FYI, we expect the SPDX-License-Identifier to be present on all new files[1] added to git, even if they're relatively simple in some cases like this meson.build.
If you run the series though checkpatch.pl it should tell you which files you've missed.
With regards,
Daniel
[1] exception for non-plain text files, or if there's some reason it would cause problems.
Signature · 3 lines
|: https://berrange.com -o- https://www.flickr.com/photos/dberrange :| |: https://libvirt.org -o- https://fstop138.berrange.com :| |: https://entangle-photo.org -o- https://www.instagram.com/dberrange :|
Re: [PATCH v4 03/27] target/i386/mshv: Add x86 decoder/emu implementation
Quoted 37 lines · Daniel P. Berrangé
Quoted 24 lines · Magnus Kulke
The MSHV accelerator requires a x86 decoder/emulator in userland to emulate MMIO instructions. This change contains the implementations for the generalized i386 instruction decoder/emulator.
Signed-off-by Magnus Kulke <[email protected]>--- include/system/mshv.h | 25 +++ target/i386/cpu.h | 2 +- target/i386/emulate/meson.build | 7 +- target/i386/meson.build | 2 + target/i386/mshv/meson.build | 7 + target/i386/mshv/x86.c | 297 ++++++++++++++++++++++++++++++++ 6 files changed, 337 insertions(+), 3 deletions(-)create mode 100644
include/system/mshv.h
create mode 100644 target/i386/mshv/meson.build
create mode 100644target/i386/mshv/x86.ctarget/i386/mshv/meson.build new file +0
-0target/i386/mshv/meson.build line 7
Quoted 7 lines
target/i386/mshv/meson.build new file +7
-0@@ -0,0 +1,7 @@ +i386_mshv_ss = ss.source_set() + +i386_mshv_ss.add(files( + 'x86.c', +)) + +i386_system_ss.add_all(when: 'CONFIG_MSHV', if_true: i386_mshv_ss)FYI, we expect the SPDX-License-Identifier to be present on all new files[1] added to git, even if they're relatively simple in some cases like this meson.build.
Quoted 2 lines
If you run the series though checkpatch.pl it should tell you which files you've missed.
I'll handle this when applying.
Paolo
PATCH v4 4/27 hw/intc: Generalize APIC helper names from kvm_* to accel_*
In reply to Magnus KulkeRename APIC helper functions to use an accel_* prefix instead of kvm_* to support use by accelerators other than KVM. This is a preparatory step for integrating MSHV support with common APIC logic.
--- accel/accel-irq.c | 106 +++++++++++++++++++++++++++++++++++++ accel/meson.build | 2 +- hw/intc/ioapic.c | 20 ++++--- hw/virtio/virtio-pci.c | 21 ++++---- include/system/accel-irq.h | 37 +++++++++++++ include/system/mshv.h | 21 ++++++++ 6 files changed, 189 insertions(+), 18 deletions(-) create mode 100644 accel/accel-irq.c create mode 100644 include/system/accel-irq.h
accel/accel-irq.c new file +106 -0
@@ -0,0 +1,106 @@ +/* +* Accelerated irqchip abstraction +* +* Copyright Microsoft, Corp. 2025 +* +* Authors: Ziqiao Zhou <[email protected]> +* Magnus Kulke <[email protected]> +* +* SPDX-License-Identifier: GPL-2.0-or-later +*/ + +#include "qemu/osdep.h" +#include "hw/pci/msi.h" + +#include "system/kvm.h" +#include "system/mshv.h" +#include "system/accel-irq.h" + +int accel_irqchip_add_msi_route (KVMRouteChange *c,int vector,PCIDevice *dev) +{ +#ifdef CONFIG_MSHV_IS_POSSIBLE +if (mshv_msi_via_irqfd_enabled ()) { +return mshv_irqchip_add_msi_route (vector, dev); + } +#endif +if (kvm_enabled ()) { +return kvm_irqchip_add_msi_route (c, vector, dev); + } +return -ENOSYS ; +} + +int accel_irqchip_update_msi_route (int vector,MSIMessage msg,PCIDevice *dev) +{ +#ifdef CONFIG_MSHV_IS_POSSIBLE +if (mshv_msi_via_irqfd_enabled ()) { +return mshv_irqchip_update_msi_route (vector, msg, dev); + } +#endif +if (kvm_enabled ()) { +return kvm_irqchip_update_msi_route (kvm_state, vector, msg, dev); + } +return -ENOSYS ; +} + +void accel_irqchip_commit_route_changes (KVMRouteChange *c) +{ +#ifdef CONFIG_MSHV_IS_POSSIBLE +if (mshv_msi_via_irqfd_enabled ()) { +mshv_irqchip_commit_routes (); + } +#endif +if (kvm_enabled ()) { +kvm_irqchip_commit_route_changes (c); + } +} + +void accel_irqchip_commit_routes (void ) +{ +#ifdef CONFIG_MSHV_IS_POSSIBLE +if (mshv_msi_via_irqfd_enabled ()) { +mshv_irqchip_commit_routes (); + } +#endif +if (kvm_enabled ()) { +kvm_irqchip_commit_routes (kvm_state); + } +} + +void accel_irqchip_release_virq (int virq) +{ +#ifdef CONFIG_MSHV_IS_POSSIBLE +if (mshv_msi_via_irqfd_enabled ()) { +mshv_irqchip_release_virq (virq); + } +#endif +if (kvm_enabled ()) { +kvm_irqchip_release_virq (kvm_state, virq); + } +} + +int accel_irqchip_add_irqfd_notifier_gsi (EventNotifier *n,EventNotifier *rn, +int virq) +{ +#ifdef CONFIG_MSHV_IS_POSSIBLE +if (mshv_msi_via_irqfd_enabled ()) { +return mshv_irqchip_add_irqfd_notifier_gsi (n, rn, virq); + } +#endif +if (kvm_enabled ()) { +return kvm_irqchip_add_irqfd_notifier_gsi (kvm_state, n, rn, virq); + } +return -ENOSYS ; +} + +int accel_irqchip_remove_irqfd_notifier_gsi (EventNotifier *n,int virq) +{ +#ifdef CONFIG_MSHV_IS_POSSIBLE +if (mshv_msi_via_irqfd_enabled ()) { +return mshv_irqchip_remove_irqfd_notifier_gsi (n, virq); + } +#endif +if (kvm_enabled ()) { +return kvm_irqchip_remove_irqfd_notifier_gsi (kvm_state, n, virq); + } +return -ENOSYS ; +}
accel/meson.build +1 -1
@@ -1,6 +1,6 @@ common_ss.add(files('accel-common.c')) specific_ss.add(files('accel-target.c')) -system_ss.add(files('accel-system.c', 'accel-blocker.c', 'accel-qmp.c')) +system_ss.add(files('accel-system.c', 'accel-blocker.c', 'accel-qmp.c', 'accel-irq.c')) user_ss.add(files('accel-user.c')) subdir('tcg')
hw/intc/ioapic.c +13 -7
@@ -30,12 +30,18 @@#include "hw/intc/ioapic_internal.h" #include "hw/pci/msi.h" #include "hw/qdev-properties.h" +#include "system/accel-irq.h" #include "system/kvm.h" #include "system/system.h" #include "hw/i386/apic-msidef.h" #include "hw/i386/x86-iommu.h" #include "trace.h" + +#if defined(CONFIG_KVM ) || defined(CONFIG_MSHV ) +#define ACCEL_GSI_IRQFD_POSSIBLE +#endif +#define APIC_DELIVERY_MODE_SHIFT 8#define APIC_POLARITY_SHIFT 14#define APIC_TRIG_MODE_SHIFT 15
@@ -191,10 +197,10 @@ static void ioapic_set_irq(void *opaque, int vector, int level)static void ioapic_update_kvm_routes (IOAPICCommonState *s) { -#ifdef CONFIG_KVM +#ifdef ACCEL_GSI_IRQFD_POSSIBLE int i; -if (kvm_irqchip_is_split ()) { +if (accel_irqchip_is_split ()) {for (i =0 ; i <IOAPIC_NUM_PINS ; i++) {MSIMessage msg;struct ioapic_entry_info info;
@@ -202,15 +208,15 @@ static void ioapic_update_kvm_routes(IOAPICCommonState *s)if (!info.masked) { msg.address = info.addr; msg.data = info.data; -kvm_irqchip_update_msi_route (kvm_state, i, msg,NULL ); +accel_irqchip_update_msi_route (i, msg,NULL ); } } -kvm_irqchip_commit_routes (kvm_state); +accel_irqchip_commit_routes (); }#endif } -#ifdef CONFIG_KVM +#ifdef ACCEL_KERNEL_GSI_IRQFD_POSSIBLE static void ioapic_iec_notifier (void *private,bool global,uint32_t index,uint32_t mask) {
@@ -428,11 +434,11 @@ static const MemoryRegionOps ioapic_io_ops = {static void ioapic_machine_done_notify (Notifier *notifier,void *data) { -#ifdef CONFIG_KVM +#ifdef ACCEL_KERNEL_GSI_IRQFD_POSSIBLE IOAPICCommonState *s =container_of (notifier, IOAPICCommonState, machine_done); -if (kvm_irqchip_is_split ()) { +if (accel_irqchip_is_split ()) {X86IOMMUState *iommu =x86_iommu_get_default ();if (iommu) {/* Register this IOAPIC with IOMMU IEC notifier, so that
hw/virtio/virtio-pci.c +11 -10
@@ -34,6 +34,7 @@#include "hw/pci/msi.h" #include "hw/pci/msix.h" #include "hw/loader.h" +#include "system/accel-irq.h" #include "system/kvm.h" #include "hw/virtio/virtio-pci.h" #include "qemu/range.h"
@@ -825,11 +826,11 @@ static int kvm_virtio_pci_vq_vector_use(VirtIOPCIProxy *proxy,if (irqfd->users ==0 ) {KVMRouteChange c =kvm_irqchip_begin_route_changes (kvm_state); - ret =kvm_irqchip_add_msi_route (&c, vector, &proxy->pci_dev); + ret =accel_irqchip_add_msi_route (&c, vector, &proxy->pci_dev);if (ret <0 ) {return ret; } -kvm_irqchip_commit_route_changes (&c); +accel_irqchip_commit_route_changes (&c); irqfd->virq = ret; } irqfd->users++;
@@ -841,7 +842,7 @@ static void kvm_virtio_pci_vq_vector_release(VirtIOPCIProxy *proxy, {VirtIOIRQFD *irqfd = &proxy->vector_irqfd[vector];if (--irqfd->users ==0 ) { -kvm_irqchip_release_virq (kvm_state, irqfd->virq); +accel_irqchip_release_virq (irqfd->virq); } }
@@ -850,7 +851,7 @@ static int kvm_virtio_pci_irqfd_use(VirtIOPCIProxy *proxy, unsigned int vector) {VirtIOIRQFD *irqfd = &proxy->vector_irqfd[vector]; -return kvm_irqchip_add_irqfd_notifier_gsi (kvm_state, n,NULL , irqfd->virq); +return accel_irqchip_add_irqfd_notifier_gsi (n,NULL , irqfd->virq); } static void kvm_virtio_pci_irqfd_release(VirtIOPCIProxy *proxy,
@@ -860,7 +861,7 @@ static void kvm_virtio_pci_irqfd_release(VirtIOPCIProxy *proxy,VirtIOIRQFD *irqfd = &proxy->vector_irqfd[vector];int ret; - ret =kvm_irqchip_remove_irqfd_notifier_gsi (kvm_state, n, irqfd->virq); + ret =accel_irqchip_remove_irqfd_notifier_gsi (n, irqfd->virq);assert (ret ==0 ); } static int virtio_pci_get_notifier(VirtIOPCIProxy *proxy, int queue_no,
@@ -995,12 +996,12 @@ static int virtio_pci_one_vector_unmask(VirtIOPCIProxy *proxy,if (proxy->vector_irqfd) { irqfd = &proxy->vector_irqfd[vector];if (irqfd->msg.data != msg.data || irqfd->msg.address != msg.address) { - ret =kvm_irqchip_update_msi_route (kvm_state, irqfd->virq, msg, - &proxy->pci_dev); + ret =accel_irqchip_update_msi_route (irqfd->virq, msg, + &proxy->pci_dev);if (ret <0 ) {return ret; } -kvm_irqchip_commit_routes (kvm_state); +accel_irqchip_commit_routes (); } }
@@ -1229,7 +1230,7 @@ static int virtio_pci_set_guest_notifiers(DeviceState *d, int nvqs, bool assign)VirtioDeviceClass *k =VIRTIO_DEVICE_GET_CLASS (vdev);int r, n;bool with_irqfd =msix_enabled (&proxy->pci_dev) && -kvm_msi_via_irqfd_enabled (); +accel_msi_via_irqfd_enabled () ; nvqs =MIN (nvqs,VIRTIO_QUEUE_MAX );
@@ -1433,7 +1434,7 @@ static void virtio_pci_set_vector(VirtIODevice *vdev, uint16_t new_vector) {bool kvm_irqfd = (vdev->status &VIRTIO_CONFIG_S_DRIVER_OK ) && -msix_enabled (&proxy->pci_dev) &&kvm_msi_via_irqfd_enabled (); +msix_enabled (&proxy->pci_dev) &&accel_msi_via_irqfd_enabled ();if (new_vector == old_vector) {return ;
include/system/accel-irq.h new file +37 -0
@@ -0,0 +1,37 @@ +/* +* Accelerated irqchip abstraction +* +* Copyright Microsoft, Corp. 2025 +* +* Authors: Ziqiao Zhou <[email protected]> +* Magnus Kulke <[email protected]> +* +* SPDX-License-Identifier: GPL-2.0-or-later +*/ + +#ifndef SYSTEM_ACCEL_IRQ_H +#define SYSTEM_ACCEL_IRQ_H +#include "hw/pci/msi.h" +#include "qemu/osdep.h" +#include "system/kvm.h" +#include "system/mshv.h" + +static inline bool accel_msi_via_irqfd_enabled (void ) +{ +return mshv_msi_via_irqfd_enabled () ||kvm_msi_via_irqfd_enabled (); +} + +static inline bool accel_irqchip_is_split (void ) +{ +return mshv_msi_via_irqfd_enabled () ||kvm_irqchip_is_split (); +} + +int accel_irqchip_add_msi_route (KVMRouteChange *c,int vector,PCIDevice *dev); +int accel_irqchip_update_msi_route (int vector,MSIMessage msg,PCIDevice *dev); +void accel_irqchip_commit_route_changes (KVMRouteChange *c); +void accel_irqchip_commit_routes (void ); +void accel_irqchip_release_virq (int virq); +int accel_irqchip_add_irqfd_notifier_gsi (EventNotifier *n,EventNotifier *rn, +int virq); +int accel_irqchip_remove_irqfd_notifier_gsi (EventNotifier *n,int virq); +#endif
include/system/mshv.h +21 -0
@@ -22,4 +22,25 @@#define CONFIG_MSHV_IS_POSSIBLE #endif +#ifdef CONFIG_MSHV_IS_POSSIBLE +extern bool mshv_allowed; +#define mshv_enabled () (mshv_allowed) +#else /* CONFIG_MSHV_IS_POSSIBLE */ +#define mshv_enabled () false +#endif +#ifdef MSHV_USE_KERNEL_GSI_IRQFD +#define mshv_msi_via_irqfd_enabled () mshv_enabled() +#else +#define mshv_msi_via_irqfd_enabled () false +#endif + +/* interrupt */ +int mshv_irqchip_add_msi_route (int vector,PCIDevice *dev); +int mshv_irqchip_update_msi_route (int virq,MSIMessage msg,PCIDevice *dev); +void mshv_irqchip_commit_routes (void ); +void mshv_irqchip_release_virq (int virq); +int mshv_irqchip_add_irqfd_notifier_gsi (const EventNotifier *n, +const EventNotifier *rn,int virq); +int mshv_irqchip_remove_irqfd_notifier_gsi (const EventNotifier *n,int virq); +#endif
Signature · 1 line
2.34.1
Re: [PATCH v4 04/27] hw/intc: Generalize APIC helper names from kvm_* to accel_*
Quoted 344 lines · Magnus Kulke
Rename APIC helper functions to use an accel_* prefix instead of kvm_* to support use by accelerators other than KVM. This is a preparatory step for integrating MSHV support with common APIC logic.
Signed-off-by Magnus Kulke <[email protected]>--- accel/accel-irq.c | 106 +++++++++++++++++++++++++++++++++++++ accel/meson.build | 2 +- hw/intc/ioapic.c | 20 ++++--- hw/virtio/virtio-pci.c | 21 ++++---- include/system/accel-irq.h | 37 +++++++++++++ include/system/mshv.h | 21 ++++++++ 6 files changed, 189 insertions(+), 18 deletions(-)create mode 100644
accel/accel-irq.c
create mode 100644include/system/accel-irq.haccel/accel-irq.c new file +106
-0@@ -0,0 +1,106 @@ +/* +* Accelerated irqchip abstraction +* +* Copyright Microsoft, Corp. 2025 +* +* Authors: Ziqiao Zhou <[email protected]> +* Magnus Kulke <[email protected]> +* +* SPDX-License-Identifier: GPL-2.0-or-later +*/ + +#include "qemu/osdep.h" +#include "hw/pci/msi.h" + +#include "system/kvm.h" +#include "system/mshv.h" +#include "system/accel-irq.h" + +int accel_irqchip_add_msi_route (KVMRouteChange *c,int vector,PCIDevice *dev) +{ +#ifdef CONFIG_MSHV_IS_POSSIBLE +if (mshv_msi_via_irqfd_enabled ()) { +return mshv_irqchip_add_msi_route (vector, dev); + } +#endif +if (kvm_enabled ()) { +return kvm_irqchip_add_msi_route (c, vector, dev); + } +return -ENOSYS ; +} + +int accel_irqchip_update_msi_route (int vector,MSIMessage msg,PCIDevice *dev) +{ +#ifdef CONFIG_MSHV_IS_POSSIBLE +if (mshv_msi_via_irqfd_enabled ()) { +return mshv_irqchip_update_msi_route (vector, msg, dev); + } +#endif +if (kvm_enabled ()) { +return kvm_irqchip_update_msi_route (kvm_state, vector, msg, dev); + } +return -ENOSYS ; +} + +void accel_irqchip_commit_route_changes (KVMRouteChange *c) +{ +#ifdef CONFIG_MSHV_IS_POSSIBLE +if (mshv_msi_via_irqfd_enabled ()) { +mshv_irqchip_commit_routes (); + } +#endif +if (kvm_enabled ()) { +kvm_irqchip_commit_route_changes (c); + } +} + +void accel_irqchip_commit_routes (void ) +{ +#ifdef CONFIG_MSHV_IS_POSSIBLE +if (mshv_msi_via_irqfd_enabled ()) { +mshv_irqchip_commit_routes (); + } +#endif +if (kvm_enabled ()) { +kvm_irqchip_commit_routes (kvm_state); + } +} + +void accel_irqchip_release_virq (int virq) +{ +#ifdef CONFIG_MSHV_IS_POSSIBLE +if (mshv_msi_via_irqfd_enabled ()) { +mshv_irqchip_release_virq (virq); + } +#endif +if (kvm_enabled ()) { +kvm_irqchip_release_virq (kvm_state, virq); + } +} + +int accel_irqchip_add_irqfd_notifier_gsi (EventNotifier *n,EventNotifier *rn, +int virq) +{ +#ifdef CONFIG_MSHV_IS_POSSIBLE +if (mshv_msi_via_irqfd_enabled ()) { +return mshv_irqchip_add_irqfd_notifier_gsi (n, rn, virq); + } +#endif +if (kvm_enabled ()) { +return kvm_irqchip_add_irqfd_notifier_gsi (kvm_state, n, rn, virq); + } +return -ENOSYS ; +} + +int accel_irqchip_remove_irqfd_notifier_gsi (EventNotifier *n,int virq) +{ +#ifdef CONFIG_MSHV_IS_POSSIBLE +if (mshv_msi_via_irqfd_enabled ()) { +return mshv_irqchip_remove_irqfd_notifier_gsi (n, virq); + } +#endif +if (kvm_enabled ()) { +return kvm_irqchip_remove_irqfd_notifier_gsi (kvm_state, n, virq); + } +return -ENOSYS ; +}accel/meson.build +1
-1@@ -1,6 +1,6 @@ common_ss.add(files('accel-common.c')) specific_ss.add(files('accel-target.c')) -system_ss.add(files('accel-system.c', 'accel-blocker.c', 'accel-qmp.c')) +system_ss.add(files('accel-system.c', 'accel-blocker.c', 'accel-qmp.c', 'accel-irq.c')) user_ss.add(files('accel-user.c')) subdir('tcg')hw/intc/ioapic.c +13
-7@@ -30,12 +30,18 @@#include "hw/intc/ioapic_internal.h" #include "hw/pci/msi.h" #include "hw/qdev-properties.h" +#include "system/accel-irq.h" #include "system/kvm.h" #include "system/system.h" #include "hw/i386/apic-msidef.h" #include "hw/i386/x86-iommu.h" #include "trace.h" + +#if defined(CONFIG_KVM ) || defined(CONFIG_MSHV ) +#define ACCEL_GSI_IRQFD_POSSIBLE +#endif +#define APIC_DELIVERY_MODE_SHIFT 8#define APIC_POLARITY_SHIFT 14#define APIC_TRIG_MODE_SHIFT 15@@ -191,10 +197,10 @@ static void ioapic_set_irq(void *opaque, int vector, int level)static void ioapic_update_kvm_routes (IOAPICCommonState *s) { -#ifdef CONFIG_KVM +#ifdef ACCEL_GSI_IRQFD_POSSIBLE int i; -if (kvm_irqchip_is_split ()) { +if (accel_irqchip_is_split ()) {for (i =0 ; i <IOAPIC_NUM_PINS ; i++) {MSIMessage msg;struct ioapic_entry_info info;@@ -202,15 +208,15 @@ static void ioapic_update_kvm_routes(IOAPICCommonState *s)if (!info.masked) { msg.address = info.addr; msg.data = info.data; -kvm_irqchip_update_msi_route (kvm_state, i, msg,NULL ); +accel_irqchip_update_msi_route (i, msg,NULL ); } } -kvm_irqchip_commit_routes (kvm_state); +accel_irqchip_commit_routes (); }#endif } -#ifdef CONFIG_KVM +#ifdef ACCEL_KERNEL_GSI_IRQFD_POSSIBLE static void ioapic_iec_notifier (void *private,bool global,uint32_t index,uint32_t mask) {@@ -428,11 +434,11 @@ static const MemoryRegionOps ioapic_io_ops = {static void ioapic_machine_done_notify (Notifier *notifier,void *data) { -#ifdef CONFIG_KVM +#ifdef ACCEL_KERNEL_GSI_IRQFD_POSSIBLE IOAPICCommonState *s =container_of (notifier, IOAPICCommonState, machine_done); -if (kvm_irqchip_is_split ()) { +if (accel_irqchip_is_split ()) {X86IOMMUState *iommu =x86_iommu_get_default ();if (iommu) {/* Register this IOAPIC with IOMMU IEC notifier, so that hw/virtio/virtio-pci.c +11
-10@@ -34,6 +34,7 @@#include "hw/pci/msi.h" #include "hw/pci/msix.h" #include "hw/loader.h" +#include "system/accel-irq.h" #include "system/kvm.h" #include "hw/virtio/virtio-pci.h" #include "qemu/range.h" @@ -825,11 +826,11 @@ static int kvm_virtio_pci_vq_vector_use(VirtIOPCIProxy *proxy,if (irqfd->users ==0 ) {KVMRouteChange c =kvm_irqchip_begin_route_changes (kvm_state); - ret =kvm_irqchip_add_msi_route (&c, vector, &proxy->pci_dev); + ret =accel_irqchip_add_msi_route (&c, vector, &proxy->pci_dev);if (ret <0 ) {return ret; } -kvm_irqchip_commit_route_changes (&c); +accel_irqchip_commit_route_changes (&c); irqfd->virq = ret; } irqfd->users++;@@ -841,7 +842,7 @@ static void kvm_virtio_pci_vq_vector_release(VirtIOPCIProxy *proxy, {VirtIOIRQFD *irqfd = &proxy->vector_irqfd[vector];if (--irqfd->users ==0 ) { -kvm_irqchip_release_virq (kvm_state, irqfd->virq); +accel_irqchip_release_virq (irqfd->virq); } }@@ -850,7 +851,7 @@ static int kvm_virtio_pci_irqfd_use(VirtIOPCIProxy *proxy, unsigned int vector) {VirtIOIRQFD *irqfd = &proxy->vector_irqfd[vector]; -return kvm_irqchip_add_irqfd_notifier_gsi (kvm_state, n,NULL , irqfd->virq); +return accel_irqchip_add_irqfd_notifier_gsi (n,NULL , irqfd->virq); } static void kvm_virtio_pci_irqfd_release(VirtIOPCIProxy *proxy,@@ -860,7 +861,7 @@ static void kvm_virtio_pci_irqfd_release(VirtIOPCIProxy *proxy,VirtIOIRQFD *irqfd = &proxy->vector_irqfd[vector];int ret; - ret =kvm_irqchip_remove_irqfd_notifier_gsi (kvm_state, n, irqfd->virq); + ret =accel_irqchip_remove_irqfd_notifier_gsi (n, irqfd->virq);assert (ret ==0 ); } static int virtio_pci_get_notifier(VirtIOPCIProxy *proxy, int queue_no,@@ -995,12 +996,12 @@ static int virtio_pci_one_vector_unmask(VirtIOPCIProxy *proxy,if (proxy->vector_irqfd) { irqfd = &proxy->vector_irqfd[vector];if (irqfd->msg.data != msg.data || irqfd->msg.address != msg.address) { - ret =kvm_irqchip_update_msi_route (kvm_state, irqfd->virq, msg, - &proxy->pci_dev); + ret =accel_irqchip_update_msi_route (irqfd->virq, msg, + &proxy->pci_dev);if (ret <0 ) {return ret; } -kvm_irqchip_commit_routes (kvm_state); +accel_irqchip_commit_routes (); } }@@ -1229,7 +1230,7 @@ static int virtio_pci_set_guest_notifiers(DeviceState *d, int nvqs, bool assign)VirtioDeviceClass *k =VIRTIO_DEVICE_GET_CLASS (vdev);int r, n;bool with_irqfd =msix_enabled (&proxy->pci_dev) && -kvm_msi_via_irqfd_enabled (); +accel_msi_via_irqfd_enabled () ; nvqs =MIN (nvqs,VIRTIO_QUEUE_MAX );@@ -1433,7 +1434,7 @@ static void virtio_pci_set_vector(VirtIODevice *vdev, uint16_t new_vector) {bool kvm_irqfd = (vdev->status &VIRTIO_CONFIG_S_DRIVER_OK ) && -msix_enabled (&proxy->pci_dev) &&kvm_msi_via_irqfd_enabled (); +msix_enabled (&proxy->pci_dev) &&accel_msi_via_irqfd_enabled ();if (new_vector == old_vector) {return ;include/system/accel-irq.h new file +37
-0@@ -0,0 +1,37 @@ +/* +* Accelerated irqchip abstraction +* +* Copyright Microsoft, Corp. 2025 +* +* Authors: Ziqiao Zhou <[email protected]> +* Magnus Kulke <[email protected]> +* +* SPDX-License-Identifier: GPL-2.0-or-later +*/ + +#ifndef SYSTEM_ACCEL_IRQ_H +#define SYSTEM_ACCEL_IRQ_H +#include "hw/pci/msi.h" +#include "qemu/osdep.h" +#include "system/kvm.h" +#include "system/mshv.h" + +static inline bool accel_msi_via_irqfd_enabled (void ) +{ +return mshv_msi_via_irqfd_enabled () ||kvm_msi_via_irqfd_enabled (); +} + +static inline bool accel_irqchip_is_split (void ) +{ +return mshv_msi_via_irqfd_enabled () ||kvm_irqchip_is_split (); +} + +int accel_irqchip_add_msi_route (KVMRouteChange *c,int vector,PCIDevice *dev); +int accel_irqchip_update_msi_route (int vector,MSIMessage msg,PCIDevice *dev); +void accel_irqchip_commit_route_changes (KVMRouteChange *c); +void accel_irqchip_commit_routes (void ); +void accel_irqchip_release_virq (int virq); +int accel_irqchip_add_irqfd_notifier_gsi (EventNotifier *n,EventNotifier *rn, +int virq); +int accel_irqchip_remove_irqfd_notifier_gsi (EventNotifier *n,int virq); +#endif include/system/mshv.h +0
-0
include/system/mshv.h line 31
Quoted 10 lines
include/system/mshv.h +7
-0@@ -22,4 +22,25 @@#define CONFIG_MSHV_IS_POSSIBLE #endif +#ifdef CONFIG_MSHV_IS_POSSIBLE +extern bool mshv_allowed; +#define mshv_enabled () (mshv_allowed) +#else /* CONFIG_MSHV_IS_POSSIBLE */ +#define mshv_enabled () false +#endif +#ifdef MSHV_USE_KERNEL_GSI_IRQFD
Stupid question, who defines MSHV_USE_KERNEL_GSI_IRQFD? In QEMU generally we prefer to probe capabilities at run-time, so that you can build with version A of the headers and run on version B.
If there's no interesting setup where MSHV_USE_KERNEL_GSI_IRQFD is not defined, it would of course be nice to assume that it's enabled.
Paolo
Quoted 15 lines
include/system/mshv.h +14
-0+#define mshv_msi_via_irqfd_enabled () mshv_enabled() +#else +#define mshv_msi_via_irqfd_enabled () false +#endif + +/* interrupt */ +int mshv_irqchip_add_msi_route (int vector,PCIDevice *dev); +int mshv_irqchip_update_msi_route (int virq,MSIMessage msg,PCIDevice *dev); +void mshv_irqchip_commit_routes (void ); +void mshv_irqchip_release_virq (int virq); +int mshv_irqchip_add_irqfd_notifier_gsi (const EventNotifier *n, +const EventNotifier *rn,int virq); +int mshv_irqchip_remove_irqfd_notifier_gsi (const EventNotifier *n,int virq); +#endif
PATCH v4 5/27 include/hw/hyperv: Add MSHV ABI header definitions
In reply to Magnus KulkeIntroduce headers for the Microsoft Hypervisor (MSHV) userspace ABI, including IOCTLs and structures used to interface with the hypervisor.
These definitions are based on the upstream Linux MSHV interface and will be used by the MSHV accelerator backend in later patches.
--- include/hw/hyperv/hvgdk.h | 20 + include/hw/hyperv/hvgdk_mini.h | 817 ++++++++++++++++++++++++++++++++ include/hw/hyperv/hvhdk.h | 249 ++++++++++ include/hw/hyperv/hvhdk_mini.h | 102 ++++ scripts/update-linux-headers.sh | 2 +- 5 files changed, 1189 insertions(+), 1 deletion(-) create mode 100644 include/hw/hyperv/hvgdk.h create mode 100644 include/hw/hyperv/hvgdk_mini.h create mode 100644 include/hw/hyperv/hvhdk.h create mode 100644 include/hw/hyperv/hvhdk_mini.h
include/hw/hyperv/hvgdk.h new file +20 -0
@@ -0,0 +1,20 @@ +/* +* Type definitions for the mshv guest interface. +* +* Copyright Microsoft, Corp. 2025 +* +* SPDX-License-Identifier: GPL-2.0-or-later +*/ + +#ifndef HW_HYPERV_HVGDK_H +#define HW_HYPERV_HVGDK_H + +#define HVGDK_H_VERSION (25125) + +enum hv_unimplemented_msr_action { +HV_UNIMPLEMENTED_MSR_ACTION_FAULT =0 , +HV_UNIMPLEMENTED_MSR_ACTION_IGNORE_WRITE_READ_ZERO =1 , +HV_UNIMPLEMENTED_MSR_ACTION_COUNT =2 , +}; + +#endif /* HW_HYPERV_HVGDK_H */
include/hw/hyperv/hvgdk_mini.h new file +817 -0
817 lines not on this page · raw message
include/hw/hyperv/hvhdk.h new file +249 -0
249 lines not on this page · raw message
include/hw/hyperv/hvhdk_mini.h new file +102 -0
102 lines not on this page · raw message
scripts/update-linux-headers.sh +1 -1
@@ -195,7 +195,7 @@ rm -rf "$output/linux-headers/linux" mkdir -p "$output/linux-headers/linux" for header in const.h stddef.h kvm.h vfio.h vfio_ccw.h vfio_zdev.h vhost.h \ psci.h psp-sev.h userfaultfd.h memfd.h mman.h nvme_ioctl.h \ - vduse.h iommufd.h bits.h; do + vduse.h iommufd.h bits.h mshv.h; do cp "$hdrdir/include/linux/$header" "$output/linux-headers/linux" done
Signature · 1 line
2.34.1
PATCH v4 6/27 linux-headers/linux: Add mshv.h headers
In reply to Magnus KulkeThis file has been added to the tree by running update-linux-header.sh on linux v6.16.
--- linux-headers/linux/mshv.h | 291 +++++++++++++++++++++++++++++++++++++ 1 file changed, 291 insertions(+) create mode 100644 linux-headers/linux/mshv.h
linux-headers/linux/mshv.h new file +291 -0
@@ -0,0 +1,291 @@ +/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ +/* +* Userspace interfaces for /dev/mshv* devices and derived fds +* +* This file is divided into sections containing data structures and IOCTLs for +* a particular set of related devices or derived file descriptors. +* +* The IOCTL definitions are at the end of each section. They are grouped by +* device/fd, so that new IOCTLs can easily be added with a monotonically +* increasing number. +*/ +#ifndef _LINUX_MSHV_H +#define _LINUX_MSHV_H + +#include <linux/types.h> + +#define MSHV_IOCTL 0xB8 + +/* +******************************************* +* Entry point to main VMM APIs: /dev/mshv * +******************************************* +*/ + +enum { +MSHV_PT_BIT_LAPIC , +MSHV_PT_BIT_X2APIC , +MSHV_PT_BIT_GPA_SUPER_PAGES , +MSHV_PT_BIT_COUNT , +}; + +#define MSHV_PT_FLAGS_MASK ((1 << MSHV_PT_BIT_COUNT) - 1) + +enum { +MSHV_PT_ISOLATION_NONE , +MSHV_PT_ISOLATION_COUNT , +}; + +/** +* struct mshv_create_partition - arguments for MSHV_CREATE_PARTITION +* @pt_flags: Bitmask of 1 << MSHV_PT_BIT_* +* @pt_isolation: MSHV_PT_ISOLATION_* +* +* Returns a file descriptor to act as a handle to a guest partition. +* At this point the partition is not yet initialized in the hypervisor. +* Some operations must be done with the partition in this state, e.g. setting +* so-called "early" partition properties. The partition can then be +* initialized with MSHV_INITIALIZE_PARTITION. +*/ +struct mshv_create_partition { +__u64 pt_flags; +__u64 pt_isolation; +}; + +/* /dev/mshv */ +#define MSHV_CREATE_PARTITION _IOW(MSHV_IOCTL, 0x00, struct mshv_create_partition) + +/* +************************ +* Child partition APIs * +************************ +*/ + +struct mshv_create_vp { +__u32 vp_index; +}; + +enum { +MSHV_SET_MEM_BIT_WRITABLE , +MSHV_SET_MEM_BIT_EXECUTABLE , +MSHV_SET_MEM_BIT_UNMAP , +MSHV_SET_MEM_BIT_COUNT +}; + +#define MSHV_SET_MEM_FLAGS_MASK ((1 << MSHV_SET_MEM_BIT_COUNT) - 1) + +/* The hypervisor's "native" page size */ +#define MSHV_HV_PAGE_SIZE 0x1000 + +/** +* struct mshv_user_mem_region - arguments for MSHV_SET_GUEST_MEMORY +* @size: Size of the memory region (bytes). Must be aligned to +* MSHV_HV_PAGE_SIZE +* @guest_pfn: Base guest page number to map +* @userspace_addr: Base address of userspace memory. Must be aligned to +* MSHV_HV_PAGE_SIZE +* @flags: Bitmask of 1 << MSHV_SET_MEM_BIT_*. If (1 << MSHV_SET_MEM_BIT_UNMAP) +* is set, ignore other bits. +* @rsvd: MBZ +* +* Map or unmap a region of userspace memory to Guest Physical Addresses (GPA). +* Mappings can't overlap in GPA space or userspace. +* To unmap, these fields must match an existing mapping. +*/ +struct mshv_user_mem_region { +__u64 size; +__u64 guest_pfn; +__u64 userspace_addr; +__u8 flags; +__u8 rsvd[7 ]; +}; + +enum { +MSHV_IRQFD_BIT_DEASSIGN , +MSHV_IRQFD_BIT_RESAMPLE , +MSHV_IRQFD_BIT_COUNT , +}; + +#define MSHV_IRQFD_FLAGS_MASK ((1 << MSHV_IRQFD_BIT_COUNT) - 1) + +struct mshv_user_irqfd { +__s32 fd; +__s32 resamplefd; +__u32 gsi; +__u32 flags; +}; + +enum { +MSHV_IOEVENTFD_BIT_DATAMATCH , +MSHV_IOEVENTFD_BIT_PIO , +MSHV_IOEVENTFD_BIT_DEASSIGN , +MSHV_IOEVENTFD_BIT_COUNT , +}; + +#define MSHV_IOEVENTFD_FLAGS_MASK ((1 << MSHV_IOEVENTFD_BIT_COUNT) - 1) + +struct mshv_user_ioeventfd { +__u64 datamatch; +__u64 addr;/* legal pio/mmio address */ +__u32 len;/* 1, 2, 4, or 8 bytes */ +__s32 fd; +__u32 flags; +__u8 rsvd[4 ]; +}; + +struct mshv_user_irq_entry { +__u32 gsi; +__u32 address_lo; +__u32 address_hi; +__u32 data; +}; + +struct mshv_user_irq_table { +__u32 nr; +__u32 rsvd;/* MBZ */ +struct mshv_user_irq_entry entries[]; +}; + +enum { +MSHV_GPAP_ACCESS_TYPE_ACCESSED , +MSHV_GPAP_ACCESS_TYPE_DIRTY , +MSHV_GPAP_ACCESS_TYPE_COUNT /* Count of enum members */ +}; + +enum { +MSHV_GPAP_ACCESS_OP_NOOP , +MSHV_GPAP_ACCESS_OP_CLEAR , +MSHV_GPAP_ACCESS_OP_SET , +MSHV_GPAP_ACCESS_OP_COUNT /* Count of enum members */ +}; + +/** +* struct mshv_gpap_access_bitmap - arguments for MSHV_GET_GPAP_ACCESS_BITMAP +* @access_type: MSHV_GPAP_ACCESS_TYPE_* - The type of access to record in the +* bitmap +* @access_op: MSHV_GPAP_ACCESS_OP_* - Allows an optional clear or set of all +* the access states in the range, after retrieving the current +* states. +* @rsvd: MBZ +* @page_count: Number of pages +* @gpap_base: Base gpa page number +* @bitmap_ptr: Output buffer for bitmap, at least (page_count + 7) / 8 bytes +* +* Retrieve a bitmap of either ACCESSED or DIRTY bits for a given range of guest +* memory, and optionally clear or set the bits. +*/ +struct mshv_gpap_access_bitmap { +__u8 access_type; +__u8 access_op; +__u8 rsvd[6 ]; +__u64 page_count; +__u64 gpap_base; +__u64 bitmap_ptr; +}; + +/** +* struct mshv_root_hvcall - arguments for MSHV_ROOT_HVCALL +* @code: Hypercall code (HVCALL_*) +* @reps: in: Rep count ('repcount') +* out: Reps completed ('repcomp'). MBZ unless rep hvcall +* @in_sz: Size of input incl rep data. <= MSHV_HV_PAGE_SIZE +* @out_sz: Size of output buffer. <= MSHV_HV_PAGE_SIZE. MBZ if out_ptr is 0 +* @status: in: MBZ +* out: HV_STATUS_* from hypercall +* @rsvd: MBZ +* @in_ptr: Input data buffer (struct hv_input_*). If used with partition or +* vp fd, partition id field is populated by kernel. +* @out_ptr: Output data buffer (optional) +*/ +struct mshv_root_hvcall { +__u16 code; +__u16 reps; +__u16 in_sz; +__u16 out_sz; +__u16 status; +__u8 rsvd[6 ]; +__u64 in_ptr; +__u64 out_ptr; +}; + +/* Partition fds created with MSHV_CREATE_PARTITION */ +#define MSHV_INITIALIZE_PARTITION _IO(MSHV_IOCTL, 0x00) +#define MSHV_CREATE_VP _IOW(MSHV_IOCTL, 0x01, struct mshv_create_vp) +#define MSHV_SET_GUEST_MEMORY _IOW(MSHV_IOCTL, 0x02, struct mshv_user_mem_region) +#define MSHV_IRQFD _IOW(MSHV_IOCTL, 0x03, struct mshv_user_irqfd) +#define MSHV_IOEVENTFD _IOW(MSHV_IOCTL, 0x04, struct mshv_user_ioeventfd) +#define MSHV_SET_MSI_ROUTING _IOW(MSHV_IOCTL, 0x05, struct mshv_user_irq_table) +#define MSHV_GET_GPAP_ACCESS_BITMAP _IOWR(MSHV_IOCTL, 0x06, struct mshv_gpap_access_bitmap) +/* Generic hypercall */ +#define MSHV_ROOT_HVCALL _IOWR(MSHV_IOCTL, 0x07, struct mshv_root_hvcall) + +/* +******************************** +* VP APIs for child partitions * +******************************** +*/ + +#define MSHV_RUN_VP_BUF_SZ 256 + +/* +* VP state pages may be mapped to userspace via mmap(). +* To specify which state page, use MSHV_VP_MMAP_OFFSET_ values multiplied by +* the system page size. +* e.g. +* long page_size = sysconf(_SC_PAGE_SIZE); +* void *reg_page = mmap(NULL, MSHV_HV_PAGE_SIZE, PROT_READ|PROT_WRITE, +* MAP_SHARED, vp_fd, +* MSHV_VP_MMAP_OFFSET_REGISTERS * page_size); +*/ +enum { +MSHV_VP_MMAP_OFFSET_REGISTERS , +MSHV_VP_MMAP_OFFSET_INTERCEPT_MESSAGE , +MSHV_VP_MMAP_OFFSET_GHCB , +MSHV_VP_MMAP_OFFSET_COUNT +}; + +/** +* struct mshv_run_vp - argument for MSHV_RUN_VP +* @msg_buf: On success, the intercept message is copied here. It can be +* interpreted using the relevant hypervisor definitions. +*/ +struct mshv_run_vp { +__u8 msg_buf[MSHV_RUN_VP_BUF_SZ ]; +}; + +enum { +MSHV_VP_STATE_LAPIC ,/* Local interrupt controller state (either arch) */ +MSHV_VP_STATE_XSAVE ,/* XSAVE data in compacted form (x86_64) */ +MSHV_VP_STATE_SIMP , +MSHV_VP_STATE_SIEFP , +MSHV_VP_STATE_SYNTHETIC_TIMERS , +MSHV_VP_STATE_COUNT , +}; + +/** +* struct mshv_get_set_vp_state - arguments for MSHV_[GET,SET]_VP_STATE +* @type: MSHV_VP_STATE_* +* @rsvd: MBZ +* @buf_sz: in: 4k page-aligned size of buffer +* out: Actual size of data (on EINVAL, check this to see if buffer +* was too small) +* @buf_ptr: 4k page-aligned data buffer +*/ +struct mshv_get_set_vp_state { +__u8 type; +__u8 rsvd[3 ]; +__u32 buf_sz; +__u64 buf_ptr; +}; + +/* VP fds created with MSHV_CREATE_VP */ +#define MSHV_RUN_VP _IOR(MSHV_IOCTL, 0x00, struct mshv_run_vp) +#define MSHV_GET_VP_STATE _IOWR(MSHV_IOCTL, 0x01, struct mshv_get_set_vp_state) +#define MSHV_SET_VP_STATE _IOWR(MSHV_IOCTL, 0x02, struct mshv_get_set_vp_state) +/* +* Generic hypercall +* Defined above in partition IOCTLs, avoid redefining it here +* #define MSHV_ROOT_HVCALL _IOWR(MSHV_IOCTL, 0x07, struct mshv_root_hvcall) +*/ + +#endif
Signature · 1 line
2.34.1
Re: [PATCH v4 06/27] linux-headers/linux: Add mshv.h headers
Quoted 8 lines · Magnus Kulke
This file has been added to the tree by running
update-linux-header.shon linux v6.16.Signed-off-by Magnus Kulke <[email protected]>--- linux-headers/linux/mshv.h | 291 +++++++++++++++++++++++++++++++++++++ 1 file changed, 291 insertions(+) create mode 100644 linux-headers/linux/mshv.h
With regards,
Daniel
Signature · 3 lines
|: https://berrange.com -o- https://www.flickr.com/photos/dberrange :| |: https://libvirt.org -o- https://fstop138.berrange.com :| |: https://entangle-photo.org -o- https://www.instagram.com/dberrange :|
PATCH v4 7/27 accel/mshv: Add accelerator skeleton
In reply to Magnus KulkeIntroduce the initial scaffold for the MSHV (Microsoft Hypervisor) accelerator backend. This includes the basic directory structure and stub implementations needed to integrate with QEMU's accelerator framework.
--- accel/meson.build | 1 + accel/mshv/meson.build | 6 ++ accel/mshv/mshv-all.c | 143 +++++++++++++++++++++++++++++++++++++++++ include/system/mshv.h | 35 ++++++++++ 4 files changed, 185 insertions(+) create mode 100644 accel/mshv/meson.build create mode 100644 accel/mshv/mshv-all.c
accel/meson.build +1 -0
@@ -10,6 +10,7 @@ if have_system subdir('kvm') subdir('xen') subdir('stubs') + subdir('mshv') endif # qtest
accel/mshv/meson.build new file +6 -0
@@ -0,0 +1,6 @@ +mshv_ss = ss.source_set() +mshv_ss.add(if_true: files( + 'mshv-all.c' +)) + +specific_ss.add_all(when: 'CONFIG_MSHV', if_true: mshv_ss)
accel/mshv/mshv-all.c new file +143 -0
143 lines not on this page · raw message
include/system/mshv.h +35 -0
@@ -14,6 +14,15 @@#ifndef QEMU_MSHV_INT_H #define QEMU_MSHV_INT_H +#include "qemu/osdep.h" +#include "qemu/accel.h" +#include "hw/hyperv/hyperv-proto.h" +#include "linux/mshv.h" +#include "hw/hyperv/hvhdk.h" +#include "qapi/qapi-types-common.h" +#include "system/memory.h" +#include "accel/accel-ops.h" +#ifdef COMPILING_PER_TARGET #ifdef CONFIG_MSHV #define CONFIG_MSHV_IS_POSSIBLE
@@ -25,6 +34,32 @@#ifdef CONFIG_MSHV_IS_POSSIBLE extern bool mshv_allowed;#define mshv_enabled () (mshv_allowed) + +typedef struct MshvMemoryListener { +MemoryListener listener; +int as_id; +}MshvMemoryListener ; + +typedef struct MshvAddressSpace { +MshvMemoryListener *ml; +AddressSpace *as; +}MshvAddressSpace ; + +typedef struct MshvState { +AccelState parent_obj; +int vm; +MshvMemoryListener memory_listener; +/* number of listeners */ +int nr_as; +MshvAddressSpace *as; +}MshvState ; +extern MshvState *mshv_state; + +struct AccelCPUState { +int cpufd; +bool dirty; +}; +#else /* CONFIG_MSHV_IS_POSSIBLE */ #define mshv_enabled () false#endif
Signature · 1 line
2.34.1
PATCH v4 8/27 accel/mshv: Register memory region listeners
In reply to Magnus KulkeAdd memory listener hooks for the MSHV accelerator to track guest memory regions. This enables the backend to respond to region additions, removals and will be used to manage guest memory mappings inside the hypervisor.
Actually registering physical memory in the hypervisor is still stubbed out.
--- accel/mshv/mem.c | 24 +++++++++++++++ accel/mshv/meson.build | 1 + accel/mshv/mshv-all.c | 67 ++++++++++++++++++++++++++++++++++++++++-- include/system/mshv.h | 4 +++ 4 files changed, 94 insertions(+), 2 deletions(-) create mode 100644 accel/mshv/mem.c
accel/mshv/mem.c new file +24 -0
@@ -0,0 +1,24 @@ +/* +* QEMU MSHV support +* +* Copyright Microsoft, Corp. 2025 +* +* Authors: +* Magnus Kulke <[email protected]> +* +* SPDX-License-Identifier: GPL-2.0-or-later +* +*/ + +#include "qemu/osdep.h" +#include "qemu/error-report.h" +#include "system/address-spaces.h" +#include "system/mshv.h" + +void mshv_set_phys_mem (MshvMemoryListener *mml,MemoryRegionSection *section, +bool add) +{ +error_report ("unimplemented" ); +abort (); +} +
accel/mshv/meson.build +1 -0
@@ -1,5 +1,6 @@ mshv_ss = ss.source_set() mshv_ss.add(if_true: files( + 'mem.c', 'mshv-all.c' ))
accel/mshv/mshv-all.c +65 -2
75 lines not on this page · raw message
include/system/mshv.h +4 -0
@@ -69,6 +69,10 @@ struct AccelCPUState {#define mshv_msi_via_irqfd_enabled () false#endif +/* memory */ +void mshv_set_phys_mem (MshvMemoryListener *mml,MemoryRegionSection *section, +bool add); +/* interrupt */ int mshv_irqchip_add_msi_route (int vector,PCIDevice *dev);int mshv_irqchip_update_msi_route (int virq,MSIMessage msg,PCIDevice *dev);
Signature · 1 line
2.34.1
PATCH v4 9/27 accel/mshv: Initialize VM partition
In reply to Magnus KulkeCreate the MSHV virtual machine by opening a partition and issuing the necessary ioctl to initialize it. This sets up the basic VM structure and initial configuration used by MSHV to manage guest state.
--- accel/mshv/irq.c | 397 +++++++++++++++++++++++++++++++++++ accel/mshv/mem.c | 129 +++++++++++- accel/mshv/meson.build | 1 + accel/mshv/mshv-all.c | 326 ++++++++++++++++++++++++++++ accel/mshv/trace-events | 26 +++ accel/mshv/trace.h | 14 ++ hw/intc/apic.c | 8 + include/system/mshv.h | 38 +++- meson.build | 1 + target/i386/mshv/meson.build | 1 + target/i386/mshv/mshv-cpu.c | 71 +++++++ 11 files changed, 1005 insertions(+), 7 deletions(-) create mode 100644 accel/mshv/irq.c create mode 100644 accel/mshv/trace-events create mode 100644 accel/mshv/trace.h create mode 100644 target/i386/mshv/mshv-cpu.c
accel/mshv/irq.c new file +397 -0
@@ -0,0 +1,397 @@ +/* +* QEMU MSHV support +* +* Copyright Microsoft, Corp. 2025 +* +* Authors: Ziqiao Zhou <[email protected]> +* Magnus Kulke <[email protected]> +* Stanislav Kinsburskii <[email protected]> +* +* SPDX-License-Identifier: GPL-2.0-or-later +*/ + +#include "linux/mshv.h" +#include "qemu/osdep.h" +#include "qemu/error-report.h" +#include "hw/hyperv/hvhdk_mini.h" +#include "hw/hyperv/hvgdk_mini.h" +#include "hw/intc/ioapic.h" +#include "hw/pci/msi.h" +#include "system/mshv.h" +#include "trace.h" +#include <stdint.h> +#include <sys/ioctl.h> + +#define MSHV_IRQFD_RESAMPLE_FLAG (1 << MSHV_IRQFD_BIT_RESAMPLE) +#define MSHV_IRQFD_BIT_DEASSIGN_FLAG (1 << MSHV_IRQFD_BIT_DEASSIGN) + +static MshvMsiControl *msi_control; +static QemuMutex msi_control_mutex; + +void mshv_init_msicontrol (void ) +{ +qemu_mutex_init (&msi_control_mutex); + msi_control =g_new0 (MshvMsiControl,1 ); + msi_control->gsi_routes =g_hash_table_new (g_direct_hash, g_direct_equal); + msi_control->updated = false; +} + +static int set_msi_routing (uint32_t gsi,uint64_t addr,uint32_t data) +{ +struct mshv_user_irq_entry *entry; +uint32_t high_addr = addr >>32 ; +uint32_t low_addr = addr &0xFFFFFFFF ; +GHashTable *gsi_routes; + +trace_mshv_set_msi_routing (gsi, addr, data); + +if (gsi >=MSHV_MAX_MSI_ROUTES ) { +error_report ("gsi >= MSHV_MAX_MSI_ROUTES" ); +return -1 ; + } + +assert (msi_control); + + WITH_QEMU_LOCK_GUARD(&msi_control_mutex) { + gsi_routes = msi_control->gsi_routes; + entry =g_hash_table_lookup (gsi_routes,GINT_TO_POINTER (gsi)); + +if (entry + && entry->address_hi == high_addr + && entry->address_lo == low_addr + && entry->data == data) + { +/* nothing to update */ +return 0 ; + } + +/* free old entry */ +g_free (entry); + +/* create new entry */ + entry = g_new0(struct mshv_user_irq_entry, 1); + entry->gsi = gsi; + entry->address_hi = high_addr; + entry->address_lo = low_addr; + entry->data = data; + +g_hash_table_insert (gsi_routes,GINT_TO_POINTER (gsi), entry); + msi_control->updated = true; + } + +return 0 ; +} + +static int add_msi_routing (uint64_t addr,uint32_t data) +{ +struct mshv_user_irq_entry *route_entry; +uint32_t high_addr = addr >>32 ; +uint32_t low_addr = addr &0xFFFFFFFF ; +int gsi; +GHashTable *gsi_routes; + +trace_mshv_add_msi_routing (addr, data); + +assert (msi_control); + + WITH_QEMU_LOCK_GUARD(&msi_control_mutex) { +/* find an empty slot */ + gsi =0 ; + gsi_routes = msi_control->gsi_routes; +while (gsi <MSHV_MAX_MSI_ROUTES ) { + route_entry =g_hash_table_lookup (gsi_routes,GINT_TO_POINTER (gsi)); +if (!route_entry) { +break ; + } + gsi++; + } +if (gsi >=MSHV_MAX_MSI_ROUTES ) { +error_report ("No empty gsi slot available" ); +return -1 ; + } + +/* create new entry */ + route_entry = g_new0(struct mshv_user_irq_entry, 1); + route_entry->gsi = gsi; + route_entry->address_hi = high_addr; + route_entry->address_lo = low_addr; + route_entry->data = data; + +g_hash_table_insert (gsi_routes,GINT_TO_POINTER (gsi), route_entry); + msi_control->updated = true; + } + +return gsi; +} + +static int commit_msi_routing_table (int vm_fd) +{ +guint len; +int i, ret; +size_t table_size; +struct mshv_user_irq_table *table; +GHashTableIter iter; +gpointer key, value; + +assert (msi_control); + + WITH_QEMU_LOCK_GUARD(&msi_control_mutex) { +if (!msi_control->updated) { +/* nothing to update */ +return 0 ; + } + +/* Calculate the size of the table */ + len =g_hash_table_size (msi_control->gsi_routes); + table_size =sizeof (struct mshv_user_irq_table ) + + len *sizeof (struct mshv_user_irq_entry ); + table =g_malloc0 (table_size); + +g_hash_table_iter_init (&iter, msi_control->gsi_routes); + i =0 ; +while (g_hash_table_iter_next (&iter, &key, &value)) { +struct mshv_user_irq_entry *entry = value; + table->entries[i] = *entry; + i++; + } + table->nr = i; + +trace_mshv_commit_msi_routing_table (vm_fd, len); + + ret =ioctl (vm_fd,MSHV_SET_MSI_ROUTING , table); +g_free (table); +if (ret <0 ) { +error_report ("Failed to commit msi routing table" ); +return -1 ; + } + msi_control->updated = false; + } +return 0 ; +} + +static int remove_msi_routing (uint32_t gsi) +{ +struct mshv_user_irq_entry *route_entry; +GHashTable *gsi_routes; + +trace_mshv_remove_msi_routing (gsi); + +if (gsi >=MSHV_MAX_MSI_ROUTES ) { +error_report ("Invalid GSI: %u" , gsi); +return -1 ; + } + +assert (msi_control); + + WITH_QEMU_LOCK_GUARD(&msi_control_mutex) { + gsi_routes = msi_control->gsi_routes; + route_entry =g_hash_table_lookup (gsi_routes,GINT_TO_POINTER (gsi)); +if (route_entry) { +g_hash_table_remove (gsi_routes,GINT_TO_POINTER (gsi)); +g_free (route_entry); + msi_control->updated = true; + } + } + +return 0 ; +} + +/* Pass an eventfd which is to be used for injecting interrupts from userland */ +static int irqfd (int vm_fd,int fd,int resample_fd,uint32_t gsi, +uint32_t flags) +{ +int ret; +struct mshv_user_irqfd arg = { + .fd = fd, + .resamplefd = resample_fd, + .gsi = gsi, + .flags = flags, + }; + + ret =ioctl (vm_fd,MSHV_IRQFD , &arg); +if (ret <0 ) { +error_report ("Failed to set irqfd: gsi=%u, fd=%d" , gsi, fd); +return -1 ; + } +return ret; +} + +static int register_irqfd (int vm_fd,int event_fd,uint32_t gsi) +{ +int ret; + +trace_mshv_register_irqfd (vm_fd, event_fd, gsi); + + ret =irqfd (vm_fd, event_fd,0 , gsi,0 ); +if (ret <0 ) { +error_report ("Failed to register irqfd: gsi=%u" , gsi); +return -1 ; + } +return 0 ; +} + +static int register_irqfd_with_resample (int vm_fd,int event_fd, +int resample_fd,uint32_t gsi) +{ +int ret; +uint32_t flags =MSHV_IRQFD_RESAMPLE_FLAG ; + + ret =irqfd (vm_fd, event_fd, resample_fd, gsi, flags); +if (ret <0 ) { +error_report ("Failed to register irqfd with resample: gsi=%u" , gsi); +return -errno; + } +return 0 ; +} + +static int unregister_irqfd (int vm_fd,int event_fd,uint32_t gsi) +{ +int ret; +uint32_t flags =MSHV_IRQFD_BIT_DEASSIGN_FLAG ; + + ret =irqfd (vm_fd, event_fd,0 , gsi, flags); +if (ret <0 ) { +error_report ("Failed to unregister irqfd: gsi=%u" , gsi); +return -errno; + } +return 0 ; +} + +static int irqchip_update_irqfd_notifier_gsi (const EventNotifier *event, +const EventNotifier *resample, +int virq,bool add) +{ +int fd =event_notifier_get_fd (event); +int rfd = resample ?event_notifier_get_fd (resample) :-1 ; +int vm_fd = mshv_state->vm; + +trace_mshv_irqchip_update_irqfd_notifier_gsi (fd, rfd, virq, add); + +if (!add) { +return unregister_irqfd (vm_fd, fd, virq); + } + +if (rfd >0 ) { +return register_irqfd_with_resample (vm_fd, fd, rfd, virq); + } + +return register_irqfd (vm_fd, fd, virq); +} + + +int mshv_irqchip_add_msi_route (int vector,PCIDevice *dev) +{ +MSIMessage msg = {0 ,0 }; +int virq =0 ; + +if (pci_available && dev) { + msg =pci_get_msi_message (dev, vector); + virq =add_msi_routing (msg.address,le32_to_cpu (msg.data)); + } + +return virq; +} + +void mshv_irqchip_release_virq (int virq) +{ +remove_msi_routing (virq); +} + +int mshv_irqchip_update_msi_route (int virq,MSIMessage msg,PCIDevice *dev) +{ +int ret; + + ret =set_msi_routing (virq, msg.address,le32_to_cpu (msg.data)); +if (ret <0 ) { +error_report ("Failed to set msi routing" ); +return -1 ; + } + +return 0 ; +} + +int mshv_request_interrupt (int vm_fd,uint32_t interrupt_type,uint32_t vector, +uint32_t vp_index,bool logical_dest_mode, +bool level_triggered) +{ +int ret; + +if (vector ==0 ) { +warn_report ("Ignoring request for interrupt vector 0" ); +return 0 ; + } + +union hv_interrupt_control control = { + .interrupt_type = interrupt_type, + .level_triggered = level_triggered, + .logical_dest_mode = logical_dest_mode, + .rsvd =0 , + }; + +struct hv_input_assert_virtual_interrupt arg = {0 }; + arg.control = control; + arg.dest_addr = (uint64_t )vp_index; + arg.vector = vector; + +struct mshv_root_hvcall args = {0 }; + args.code =HVCALL_ASSERT_VIRTUAL_INTERRUPT ; + args.in_sz =sizeof (arg); + args.in_ptr = (uint64_t )&arg; + + ret =mshv_hvcall (vm_fd, &args); +if (ret <0 ) { +error_report ("Failed to request interrupt" ); +return -errno; + } +return 0 ; +} + +void mshv_irqchip_commit_routes (void ) +{ +int ret; +int vm_fd = mshv_state->vm; + + ret =commit_msi_routing_table (vm_fd); +if (ret <0 ) { +error_report ("Failed to commit msi routing table" ); +abort (); + } +} + +int mshv_irqchip_add_irqfd_notifier_gsi (const EventNotifier *event, +const EventNotifier *resample, +int virq) +{ +return irqchip_update_irqfd_notifier_gsi (event, resample, virq, true); +} + +int mshv_irqchip_remove_irqfd_notifier_gsi (const EventNotifier *event, +int virq) +{ +return irqchip_update_irqfd_notifier_gsi (event,NULL , virq, false); +} + +int mshv_reserve_ioapic_msi_routes (int vm_fd) +{ +int ret, gsi; + +/* +* Reserve GSI 0-23 for IOAPIC pins, to avoid conflicts of legacy +* peripherals with MSI-X devices +*/ +for (gsi =0 ; gsi <IOAPIC_NUM_PINS ; gsi++) { + ret =add_msi_routing (0 ,0 ); +if (ret <0 ) { +error_report ("Failed to reserve GSI %d" , gsi); +return -1 ; + } + } + + ret =commit_msi_routing_table (vm_fd); +if (ret <0 ) { +error_report ("Failed to commit reserved IOAPIC MSI routes" ); +return -1 ; + } + +return 0 ; +}
accel/mshv/mem.c +126 -3
139 lines not on this page · raw message
accel/mshv/meson.build +1 -0
@@ -1,5 +1,6 @@ mshv_ss = ss.source_set() mshv_ss.add(if_true: files( + 'irq.c', 'mem.c', 'mshv-all.c' ))
accel/mshv/mshv-all.c +326 -0
370 lines not on this page · raw message
accel/mshv/trace-events new file +26 -0
@@ -0,0 +1,26 @@ +# Authors: Ziqiao Zhou <[email protected]> +# Magnus Kulke <[email protected]> +# +# SPDX-License-Identifier: GPL-2.0-or-later + +mshv_set_memory(bool add, uint64_t gpa, uint64_t size, uint64_t user_addr, bool readonly, int ret) "add=%d gpa=0x%lx size=0x%lx user=0x%lx readonly=%d result=%d" +mshv_mem_ioeventfd_add(uint64_t addr, uint32_t size, uint32_t data) "addr=0x%lx size=%d data=0x%x" +mshv_mem_ioeventfd_del(uint64_t addr, uint32_t size, uint32_t data) "addr=0x%lx size=%d data=0x%x" + +mshv_hvcall_args(const char* hvcall, uint16_t code, uint16_t in_sz) "built args for '%s' code: %d in_sz: %d" + +mshv_handle_interrupt(uint32_t cpu, int mask) "cpu_index=%d mask=0x%x" +mshv_set_msi_routing(uint32_t gsi, uint64_t addr, uint32_t data) "gsi=%d addr=0x%lx data=0x%x" +mshv_remove_msi_routing(uint32_t gsi) "gsi=%d" +mshv_add_msi_routing(uint64_t addr, uint32_t data) "addr=0x%lx data=0x%x" +mshv_commit_msi_routing_table(int vm_fd, int len) "vm_fd=%d table_size=%d" +mshv_register_irqfd(int vm_fd, int event_fd, uint32_t gsi) "vm_fd=%d event_fd=%d gsi=%d" +mshv_irqchip_update_irqfd_notifier_gsi(int event_fd, int resample_fd, int virq, bool add) "event_fd=%d resample_fd=%d virq=%d add=%d" + +mshv_insn_fetch(uint64_t addr, size_t size) "gpa=0x%lx size=%lu" +mshv_mem_write(uint64_t addr, size_t size) "\tgpa=0x%lx size=%lu" +mshv_mem_read(uint64_t addr, size_t size) "\tgpa=0x%lx size=%lu" +mshv_map_memory(uint64_t userspace_addr, uint64_t gpa, uint64_t size) "\tu_a=0x%lx gpa=0x%010lx size=0x%08lx" +mshv_unmap_memory(uint64_t userspace_addr, uint64_t gpa, uint64_t size) "\tu_a=0x%lx gpa=0x%010lx size=0x%08lx" +mshv_set_phys_mem(bool add, const char *name, uint64_t gpa) "\tadd=%d name=%s gpa=0x%010lx" +mshv_handle_mmio(uint64_t gva, uint64_t gpa, uint64_t size, uint8_t access_type) "\tgva=0x%lx gpa=0x%010lx size=0x%lx access_type=%d"
accel/mshv/trace.h new file +14 -0
@@ -0,0 +1,14 @@ +/* +* QEMU MSHV support +* +* Copyright Microsoft, Corp. 2025 +* +* Authors: +* Ziqiao Zhou <[email protected]> +* Magnus Kulke <[email protected]> +* +* SPDX-License-Identifier: GPL-2.0-or-later +* +*/ + +#include "trace/trace-accel_mshv.h"
hw/intc/apic.c +8 -0
@@ -27,6 +27,7 @@#include "hw/pci/msi.h" #include "qemu/host-utils.h" #include "system/kvm.h" +#include "system/mshv.h" #include "trace.h" #include "hw/i386/apic-msidef.h" #include "qapi/error.h"
@@ -932,6 +933,13 @@ static void apic_send_msi(MSIMessage *msi)uint8_t trigger_mode = (data >>MSI_DATA_TRIGGER_SHIFT ) &0x1 ;uint8_t delivery = (data >>MSI_DATA_DELIVERY_MODE_SHIFT ) &0x7 ;/* XXX: Ignore redirection hint. */ +#ifdef CONFIG_MSHV +if (mshv_enabled ()) { +mshv_request_interrupt (mshv_state->vm, delivery, vector, dest, + dest_mode, trigger_mode); +return ; + } +#endif apic_deliver_irq (dest, dest_mode, delivery, vector, trigger_mode); }
include/system/mshv.h +34 -4
@@ -31,6 +31,12 @@#define CONFIG_MSHV_IS_POSSIBLE #endif +typedef struct hyperv_message hv_message ; + +#define MSHV_MAX_MSI_ROUTES 4096 + +#define MSHV_PAGE_SHIFT 12 +#ifdef CONFIG_MSHV_IS_POSSIBLE extern bool mshv_allowed;#define mshv_enabled () (mshv_allowed)
@@ -52,6 +58,7 @@ typedef struct MshvState {/* number of listeners */ int nr_as;MshvAddressSpace *as; +int fd; } MshvState;extern MshvState *mshv_state;
@@ -60,20 +67,42 @@ struct AccelCPUState {bool dirty; }; +typedef struct MshvMsiControl { +bool updated; +GHashTable *gsi_routes; +}MshvMsiControl ; +#else /* CONFIG_MSHV_IS_POSSIBLE */ #define mshv_enabled () false#endif -#ifdef MSHV_USE_KERNEL_GSI_IRQFD #define mshv_msi_via_irqfd_enabled () mshv_enabled() -#else -#define mshv_msi_via_irqfd_enabled () false -#endif + +/* cpu */ +void mshv_arch_amend_proc_features ( +union hv_partition_synthetic_processor_features *features); +int mshv_arch_post_init_vm (int vm_fd); + +int mshv_hvcall (int fd,const struct mshv_root_hvcall *args);/* memory */ +typedef struct MshvMemoryRegion { +uint64_t guest_phys_addr; +uint64_t memory_size; +uint64_t userspace_addr; +bool readonly; +}MshvMemoryRegion ; + +int mshv_add_mem (int vm_fd,const MshvMemoryRegion *mr); +int mshv_remove_mem (int vm_fd,const MshvMemoryRegion *mr);void mshv_set_phys_mem (MshvMemoryListener *mml,MemoryRegionSection *section,bool add);/* interrupt */ +void mshv_init_msicontrol (void ); +int mshv_request_interrupt (int vm_fd,uint32_t interrupt_type,uint32_t vector, +uint32_t vp_index,bool logical_destination_mode, +bool level_triggered); +int mshv_irqchip_add_msi_route (int vector,PCIDevice *dev);int mshv_irqchip_update_msi_route (int virq,MSIMessage msg,PCIDevice *dev);void mshv_irqchip_commit_routes (void );
@@ -81,5 +110,6 @@ void mshv_irqchip_release_virq(int virq);int mshv_irqchip_add_irqfd_notifier_gsi (const EventNotifier *n,const EventNotifier *rn,int virq);int mshv_irqchip_remove_irqfd_notifier_gsi (const EventNotifier *n,int virq); +int mshv_reserve_ioapic_msi_routes (int vm_fd);#endif
meson.build +1 -0
@@ -3659,6 +3659,7 @@ if have_system trace_events_subdirs += [ 'accel/hvf', 'accel/kvm', + 'accel/mshv', 'audio', 'backends', 'backends/tpm',
target/i386/mshv/meson.build +1 -0
@@ -1,6 +1,7 @@ i386_mshv_ss = ss.source_set() i386_mshv_ss.add(files( + 'mshv-cpu.c', 'x86.c', ))
target/i386/mshv/mshv-cpu.c new file +71 -0
71 lines not on this page · raw message
Signature · 1 line
2.34.1
Re: [PATCH v4 09/27] accel/mshv: Initialize VM partition
include/system/mshv.h struct AccelCPUState { · line 70
Quoted 5 lines · Magnus Kulke
include/system/mshv.h +0
-4-#ifdef MSHV_USE_KERNEL_GSI_IRQFD #define mshv_msi_via_irqfd_enabled () mshv_enabled() -#else -#define mshv_msi_via_irqfd_enabled () false -#endif
Ah, nevermind, here's the answer. :)
Paolo
PATCH v4 10/27 accel/mshv: Add vCPU creation and execution loop
In reply to Magnus KulkeCreate MSHV vCPUs using MSHV_CREATE_VP and initialize their state. Register the MSHV CPU execution loop loop with the QEMU accelerator framework to enable guest code execution.
The target/i386 functionality is still mostly stubbed out and will be populated in a later commit in this series.
--- accel/mshv/mshv-all.c | 188 +++++++++++++++++++++++++++++++++--- accel/mshv/trace-events | 2 + include/system/mshv.h | 17 ++++ target/i386/mshv/mshv-cpu.c | 64 ++++++++++++ 4 files changed, 259 insertions(+), 12 deletions(-)
accel/mshv/mshv-all.c +176 -12
@@ -392,6 +392,24 @@ int mshv_hvcall(int fd, const struct mshv_root_hvcall *args)return ret; } +static int mshv_init_vcpu (CPUState *cpu) +{ +int vm_fd = mshv_state->vm; +uint8_t vp_index = cpu->cpu_index; +int ret; + +mshv_arch_init_vcpu (cpu); + cpu->accel =g_new0 (AccelCPUState,1 ); + + ret =mshv_create_vcpu (vm_fd, vp_index, &cpu->accel->cpufd); +if (ret <0 ) { +return -1 ; + } + + cpu->accel->dirty = true; + +return 0 ; +}static int mshv_init (AccelState *as,MachineState *ms) {
@@ -414,6 +432,8 @@ static int mshv_init(AccelState *as, MachineState *ms)return -1 ; } +mshv_init_mmio_emu (); +mshv_init_msicontrol (); ret =create_vm (mshv_fd, &vm_fd);
@@ -443,40 +463,184 @@ static int mshv_init(AccelState *as, MachineState *ms)return 0 ; } +static int mshv_destroy_vcpu (CPUState *cpu) +{ +int cpu_fd =mshv_vcpufd (cpu); +int vm_fd = mshv_state->vm; + +mshv_remove_vcpu (vm_fd, cpu_fd); +mshv_vcpufd (cpu) =0 ; + +mshv_arch_destroy_vcpu (cpu); +g_free (cpu->accel); +g_clear_pointer (&cpu->accel, g_free); +return 0 ; +} + +static int mshv_cpu_exec (CPUState *cpu) +{ +hv_message mshv_msg; +enum MshvVmExit exit_reason; +int ret =0 ; + +bql_unlock (); +cpu_exec_start (cpu); + +do { +if (cpu->accel->dirty) { + ret =mshv_arch_put_registers (cpu); +if (ret) { +error_report ("Failed to put registers after init: %s" , +strerror (-ret)); + ret =-1 ; +break ; + } + cpu->accel->dirty = false; + } + + ret =mshv_run_vcpu (mshv_state->vm, cpu, &mshv_msg, &exit_reason); +if (ret <0 ) { +error_report ("Failed to run on vcpu %d" , cpu->cpu_index); +abort (); + } + +switch (exit_reason) { +case MshvVmExitIgnore: +break ; +default : + ret =EXCP_INTERRUPT ; +break ; + } + }while (ret ==0 ); + +cpu_exec_end (cpu); +bql_lock (); + +if (ret <0 ) { +cpu_dump_state (cpu, stderr,CPU_DUMP_CODE ); +vm_stop (RUN_STATE_INTERNAL_ERROR ); + } + +qatomic_set (&cpu->exit_request,0 ); +return ret; +} + +static void *mshv_vcpu_thread (void *arg) +{ +CPUState *cpu = arg; +int ret; + +rcu_register_thread (); + +bql_lock (); +qemu_thread_get_self (cpu->thread); + cpu->thread_id =qemu_get_thread_id (); + current_cpu = cpu; + ret =mshv_init_vcpu (cpu); +if (ret <0 ) { +error_report ("Failed to init vcpu %d" , cpu->cpu_index); + goto cleanup; + } + +/* signal CPU creation */ +cpu_thread_signal_created (cpu); +qemu_guest_random_seed_thread_part2 (cpu->random_seed); + +do { +if (cpu_can_run (cpu)) { +mshv_cpu_exec (cpu); + } +qemu_wait_io_event (cpu); + }while (!cpu->unplug ||cpu_can_run (cpu)); + +mshv_destroy_vcpu (cpu); +cleanup: +cpu_thread_signal_destroyed (cpu); +bql_unlock (); +rcu_unregister_thread (); +return NULL ; +} +static void mshv_start_vcpu_thread (CPUState *cpu) { -error_report ("unimplemented" ); -abort (); +char thread_name[VCPU_THREAD_NAME_SIZE ]; + + cpu->thread =g_malloc0 (sizeof (QemuThread)); + cpu->halt_cond =g_malloc0 (sizeof (QemuCond)); + +qemu_cond_init (cpu->halt_cond); + +trace_mshv_start_vcpu_thread (thread_name, cpu->cpu_index); +qemu_thread_create (cpu->thread, thread_name, mshv_vcpu_thread, cpu, +QEMU_THREAD_JOINABLE ); +} + +static void do_mshv_cpu_synchronize_post_init (CPUState *cpu, +run_on_cpu_data arg) +{ +int ret =mshv_arch_put_registers (cpu); +if (ret <0 ) { +error_report ("Failed to put registers after init: %s" ,strerror (-ret)); +abort (); + } + + cpu->accel->dirty = false; }static void mshv_cpu_synchronize_post_init (CPUState *cpu) { -error_report ("unimplemented" ); -abort (); +run_on_cpu (cpu, do_mshv_cpu_synchronize_post_init,RUN_ON_CPU_NULL ); }static void mshv_cpu_synchronize_post_reset (CPUState *cpu) { -error_report ("unimplemented" ); -abort (); +int ret =mshv_arch_put_registers (cpu); +if (ret) { +error_report ("Failed to put registers after reset: %s" , +strerror (-ret)); +cpu_dump_state (cpu, stderr,CPU_DUMP_CODE ); +vm_stop (RUN_STATE_INTERNAL_ERROR ); + } + cpu->accel->dirty = false; +} + +static void do_mshv_cpu_synchronize_pre_loadvm (CPUState *cpu, +run_on_cpu_data arg) +{ + cpu->accel->dirty = true; }static void mshv_cpu_synchronize_pre_loadvm (CPUState *cpu) { -error_report ("unimplemented" ); -abort (); +run_on_cpu (cpu, do_mshv_cpu_synchronize_pre_loadvm,RUN_ON_CPU_NULL ); +} + +static void do_mshv_cpu_synchronize (CPUState *cpu,run_on_cpu_data arg) +{ +if (!cpu->accel->dirty) { +int ret =mshv_load_regs (cpu); +if (ret <0 ) { +error_report ("Failed to load registers for vcpu %d" , + cpu->cpu_index); + +cpu_dump_state (cpu, stderr,CPU_DUMP_CODE ); +vm_stop (RUN_STATE_INTERNAL_ERROR ); + } + + cpu->accel->dirty = true; + } }static void mshv_cpu_synchronize (CPUState *cpu) { -error_report ("unimplemented" ); -abort (); +if (!cpu->accel->dirty) { +run_on_cpu (cpu, do_mshv_cpu_synchronize,RUN_ON_CPU_NULL ); + } }static bool mshv_cpus_are_resettable (void ) { -error_report ("unimplemented" ); -abort (); +return false; }static void mshv_accel_class_init (ObjectClass *oc,const void *data)
accel/mshv/trace-events +2 -0
@@ -3,6 +3,8 @@ # # SPDX-License-Identifier: GPL-2.0-or-later +mshv_start_vcpu_thread(const char* thread, uint32_t cpu) "thread=%s cpu_index=%d" + mshv_set_memory(bool add, uint64_t gpa, uint64_t size, uint64_t user_addr, bool readonly, int ret) "add=%d gpa=0x%lx size=0x%lx user=0x%lx readonly=%d result=%d" mshv_mem_ioeventfd_add(uint64_t addr, uint32_t size, uint32_t data) "addr=0x%lx size=%d data=0x%x" mshv_mem_ioeventfd_del(uint64_t addr, uint32_t size, uint32_t data) "addr=0x%lx size=%d data=0x%x"
include/system/mshv.h +17 -0
@@ -72,12 +72,29 @@ typedef struct MshvMsiControl {GHashTable *gsi_routes; } MshvMsiControl; +#define mshv_vcpufd (cpu) (cpu->accel->cpufd) +#else /* CONFIG_MSHV_IS_POSSIBLE */ #define mshv_enabled () false#endif #define mshv_msi_via_irqfd_enabled () mshv_enabled()/* cpu */ +typedef enum MshvVmExit { + MshvVmExitIgnore =0 , + MshvVmExitShutdown =1 , + MshvVmExitSpecial =2 , +}MshvVmExit ; + +void mshv_init_mmio_emu (void ); +int mshv_create_vcpu (int vm_fd,uint8_t vp_index,int *cpu_fd); +void mshv_remove_vcpu (int vm_fd,int cpu_fd); +int mshv_run_vcpu (int vm_fd,CPUState *cpu,hv_message *msg,MshvVmExit *exit); +int mshv_load_regs (CPUState *cpu); +int mshv_store_regs (CPUState *cpu); +int mshv_arch_put_registers (const CPUState *cpu); +void mshv_arch_init_vcpu (CPUState *cpu); +void mshv_arch_destroy_vcpu (CPUState *cpu);void mshv_arch_amend_proc_features (union hv_partition_synthetic_processor_features *features);int mshv_arch_post_init_vm (int vm_fd);
target/i386/mshv/mshv-cpu.c +64 -0
79 lines not on this page · raw message
Signature · 1 line
2.34.1
Re: [PATCH v4 10/27] accel/mshv: Add vCPU creation and execution loop
Quoted 58 lines · Magnus Kulke
Create MSHV vCPUs using
MSHV_CREATE_VPand initialize their state. Register the MSHV CPU execution loop loop with the QEMU accelerator framework to enable guest code execution.The target/i386 functionality is still mostly stubbed out and will be populated in a later commit in this series.
Signed-off-by Magnus Kulke <[email protected]>--- accel/mshv/mshv-all.c | 188 +++++++++++++++++++++++++++++++++--- accel/mshv/trace-events | 2 + include/system/mshv.h | 17 ++++ target/i386/mshv/mshv-cpu.c | 64 ++++++++++++ 4 files changed, 259 insertions(+), 12 deletions(-)accel/mshv/mshv-all.c +21
-0@@ -392,6 +392,24 @@ int mshv_hvcall(int fd, const struct mshv_root_hvcall *args)return ret; } +static int mshv_init_vcpu (CPUState *cpu) +{ +int vm_fd = mshv_state->vm; +uint8_t vp_index = cpu->cpu_index; +int ret; + +mshv_arch_init_vcpu (cpu); + cpu->accel =g_new0 (AccelCPUState,1 ); + + ret =mshv_create_vcpu (vm_fd, vp_index, &cpu->accel->cpufd); +if (ret <0 ) { +return -1 ; + } + + cpu->accel->dirty = true; + +return 0 ; +}static int mshv_init (AccelState *as,MachineState *ms) {@@ -414,6 +432,8 @@ static int mshv_init(AccelState *as, MachineState *ms)return -1 ; } +mshv_init_mmio_emu (); +mshv_init_msicontrol (); ret =create_vm (mshv_fd, &vm_fd);@@ -443,40 +463,184 @@ static int mshv_init(AccelState *as, MachineState *ms)return 0 ; } +static int mshv_destroy_vcpu (CPUState *cpu)
accel/mshv/mshv-all.c static int mshv_init(AccelState *as, MachineState *ms) · line 476
Quoted 10 lines
accel/mshv/mshv-all.c +10
-0+{ +int cpu_fd =mshv_vcpufd (cpu); +int vm_fd = mshv_state->vm; + +mshv_remove_vcpu (vm_fd, cpu_fd); +mshv_vcpufd (cpu) =0 ; + +mshv_arch_destroy_vcpu (cpu); +g_free (cpu->accel); +g_clear_pointer (&cpu->accel, g_free);
This is a double-free.
g_clear_pointer(&cpu->accel, g_free);
is equivalent to
g_free(cpu->accel) cpu->accel = NULL;
So you don't need the earlier 'g_free(cpu->accel)' call
accel/mshv/mshv-all.c static int mshv_init(AccelState *as, MachineState *ms) · line 483
Quoted 7 lines
accel/mshv/mshv-all.c +7
-0+void mshv_arch_destroy_vcpu (CPUState *cpu) +{ +X86CPU *x86_cpu =X86_CPU (cpu); +CPUX86State *env = &x86_cpu->env; + +g_free (env->emu_mmio_buf); + env->emu_mmio_buf =NULL ;
These two lines could be replaced with
g_clear_pointer(&env->emu_mmio_buf, g_free);
With regards,
Daniel
Signature · 3 lines
|: https://berrange.com -o- https://www.flickr.com/photos/dberrange :| |: https://libvirt.org -o- https://fstop138.berrange.com :| |: https://entangle-photo.org -o- https://www.instagram.com/dberrange :|
PATCH v4 11/27 accel/mshv: Add vCPU signal handling
In reply to Magnus KulkeImplement signal handling for MSHV vCPUs to support asynchronous interrupts from the main thread.
--- accel/mshv/mshv-all.c | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+)
accel/mshv/mshv-all.c +30 -0
@@ -525,6 +525,35 @@ static int mshv_cpu_exec(CPUState *cpu)return ret; } +/* +* The signal handler is triggered when QEMU's main thread receives a SIG_IPI +* (SIGUSR1). This signal causes the current CPU thread to be kicked, forcing a +* VM exit on the CPU. The VM exit generates an exit reason that breaks the loop +* (see mshv_cpu_exec). If the exit is due to a Ctrl+A+x command, the system +* will shut down. For other cases, the system will continue running. +*/ +static void sa_ipi_handler (int sig) +{ +/* TODO: call IOCTL to set_immediate_exit, once implemented. */ + +qemu_cpu_kick_self (); +} + +static void init_signal (CPUState *cpu) +{ +/* init cpu signals */ +struct sigaction sigact; +sigset_t set; + +memset (&sigact,0 ,sizeof (sigact)); + sigact.sa_handler = sa_ipi_handler; +sigaction (SIG_IPI , &sigact,NULL ); + +pthread_sigmask (SIG_BLOCK ,NULL , &set); +sigdelset (&set,SIG_IPI ); +pthread_sigmask (SIG_SETMASK , &set,NULL ); +} +static void *mshv_vcpu_thread (void *arg) {CPUState *cpu = arg;
@@ -541,6 +570,7 @@ static void *mshv_vcpu_thread(void *arg)error_report ("Failed to init vcpu %d" , cpu->cpu_index); goto cleanup; } +init_signal (cpu);/* signal CPU creation */ cpu_thread_signal_created (cpu);
Signature · 1 line
2.34.1
PATCH v4 12/27 target/i386/mshv: Add CPU create and remove logic
In reply to Magnus KulkeImplement MSHV-specific hooks for vCPU creation and teardown in the i386 target.
--- target/i386/mshv/mshv-cpu.c | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-)
target/i386/mshv/mshv-cpu.c +17 -6
@@ -29,6 +29,8 @@#include "trace-accel_mshv.h" #include "trace.h" +#include <sys/ioctl.h> +int mshv_store_regs (CPUState *cpu) {error_report ("unimplemented" );
@@ -61,20 +63,29 @@ int mshv_run_vcpu(int vm_fd, CPUState *cpu, hv_message *msg, MshvVmExit *exit)void mshv_remove_vcpu (int vm_fd,int cpu_fd) { -error_report ("unimplemented" ); -abort (); +close (cpu_fd); } +int mshv_create_vcpu (int vm_fd,uint8_t vp_index,int *cpu_fd) { -error_report ("unimplemented" ); -abort (); +int ret; +struct mshv_create_vp vp_arg = { + .vp_index = vp_index, + }; + ret =ioctl (vm_fd,MSHV_CREATE_VP , &vp_arg); +if (ret <0 ) { +error_report ("failed to create mshv vcpu: %s" ,strerror (errno)); +return -1 ; + } + + *cpu_fd = ret; + +return 0 ; }void mshv_init_mmio_emu (void ) { -error_report ("unimplemented" ); -abort (); }void mshv_arch_init_vcpu (CPUState *cpu)
Signature · 1 line
2.34.1
PATCH v4 13/27 target/i386/mshv: Implement mshv_store_regs()
In reply to Magnus KulkeAdd support for writing general-purpose registers to MSHV vCPUs during initialization or migration using the MSHV register interface. A generic set_register call is introduced to abstract the HV call over the various register types.
--- include/system/mshv.h | 3 + target/i386/mshv/mshv-cpu.c | 116 +++++++++++++++++++++++++++++++++++- 2 files changed, 117 insertions(+), 2 deletions(-)
include/system/mshv.h +3 -0
@@ -19,6 +19,7 @@#include "hw/hyperv/hyperv-proto.h" #include "linux/mshv.h" #include "hw/hyperv/hvhdk.h" +#include "hw/hyperv/hvgdk_mini.h" #include "qapi/qapi-types-common.h" #include "system/memory.h" #include "accel/accel-ops.h"
@@ -92,6 +93,8 @@ void mshv_remove_vcpu(int vm_fd, int cpu_fd);int mshv_run_vcpu (int vm_fd,CPUState *cpu,hv_message *msg,MshvVmExit *exit);int mshv_load_regs (CPUState *cpu);int mshv_store_regs (CPUState *cpu); +int mshv_set_generic_regs (const CPUState *cpu,const hv_register_assoc *assocs, +size_t n_regs);int mshv_arch_put_registers (const CPUState *cpu);void mshv_arch_init_vcpu (CPUState *cpu);void mshv_arch_destroy_vcpu (CPUState *cpu);
target/i386/mshv/mshv-cpu.c +114 -2
126 lines not on this page · raw message
Signature · 1 line
2.34.1
PATCH v4 14/27 target/i386/mshv: Implement mshv_get_standard_regs()
In reply to Magnus KulkeFetch standard register state from MSHV vCPUs to support debugging, migration, and other introspection features in QEMU.
Fetch standard register state from a MHSV vCPU's. A generic get_regs() function and a mapper to map the different register representations are introduced.
--- include/system/mshv.h | 1 + target/i386/mshv/mshv-cpu.c | 116 +++++++++++++++++++++++++++++++++++- 2 files changed, 115 insertions(+), 2 deletions(-)
include/system/mshv.h +1 -0
@@ -90,6 +90,7 @@ typedef enum MshvVmExit {void mshv_init_mmio_emu (void );int mshv_create_vcpu (int vm_fd,uint8_t vp_index,int *cpu_fd);void mshv_remove_vcpu (int vm_fd,int cpu_fd); +int mshv_get_standard_regs (CPUState *cpu);int mshv_run_vcpu (int vm_fd,CPUState *cpu,hv_message *msg,MshvVmExit *exit);int mshv_load_regs (CPUState *cpu);int mshv_store_regs (CPUState *cpu);
target/i386/mshv/mshv-cpu.c +114 -2
131 lines not on this page · raw message
Signature · 1 line
2.34.1
PATCH v4 15/27 target/i386/mshv: Implement mshv_get_special_regs()
In reply to Magnus KulkeRetrieve special registers (e.g. segment, control, and descriptor table registers) from MSHV vCPUs.
Various helper functions to map register state representations between Qemu and MSHV are introduced.
--- include/system/mshv.h | 1 + target/i386/mshv/mshv-cpu.c | 104 ++++++++++++++++++++++++++++++++++++ 2 files changed, 105 insertions(+)
include/system/mshv.h +1 -0
@@ -91,6 +91,7 @@ void mshv_init_mmio_emu(void);int mshv_create_vcpu (int vm_fd,uint8_t vp_index,int *cpu_fd);void mshv_remove_vcpu (int vm_fd,int cpu_fd);int mshv_get_standard_regs (CPUState *cpu); +int mshv_get_special_regs (CPUState *cpu);int mshv_run_vcpu (int vm_fd,CPUState *cpu,hv_message *msg,MshvVmExit *exit);int mshv_load_regs (CPUState *cpu);int mshv_store_regs (CPUState *cpu);
target/i386/mshv/mshv-cpu.c +104 -0
122 lines not on this page · raw message
Signature · 1 line
2.34.1
PATCH v4 16/27 target/i386/mshv: Implement mshv_arch_put_registers()
In reply to Magnus KulkeWrite CPU register state to MSHV vCPUs. Various mapping functions to prepare the payload for the HV call have been implemented.
--- include/system/mshv.h | 15 +++ target/i386/mshv/mshv-cpu.c | 237 ++++++++++++++++++++++++++++++++++++ 2 files changed, 252 insertions(+)
include/system/mshv.h +15 -0
@@ -81,6 +81,20 @@ typedef struct MshvMsiControl {#define mshv_msi_via_irqfd_enabled () mshv_enabled()/* cpu */ +typedef struct MshvFPU { +uint8_t fpr[8 ][16 ]; +uint16_t fcw; +uint16_t fsw; +uint8_t ftwx; +uint8_t pad1; +uint16_t last_opcode; +uint64_t last_ip; +uint64_t last_dp; +uint8_t xmm[16 ][16 ]; +uint32_t mxcsr; +uint32_t pad2; +}MshvFPU ; + typedef enum MshvVmExit { MshvVmExitIgnore = 0, MshvVmExitShutdown = 1,
@@ -90,6 +104,7 @@ typedef enum MshvVmExit {void mshv_init_mmio_emu (void );int mshv_create_vcpu (int vm_fd,uint8_t vp_index,int *cpu_fd);void mshv_remove_vcpu (int vm_fd,int cpu_fd); +int mshv_configure_vcpu (const CPUState *cpu,const MshvFPU *fpu,uint64_t xcr0);int mshv_get_standard_regs (CPUState *cpu);int mshv_get_special_regs (CPUState *cpu);int mshv_run_vcpu (int vm_fd,CPUState *cpu,hv_message *msg,MshvVmExit *exit);
target/i386/mshv/mshv-cpu.c +237 -0
251 lines not on this page · raw message
Signature · 1 line
2.34.1
PATCH v4 17/27 target/i386/mshv: Set local interrupt controller state
In reply to Magnus KulkeTo set the local interrupt controller state, perform hv calls retrieving partition state from the hypervisor.
--- target/i386/mshv/mshv-cpu.c | 117 ++++++++++++++++++++++++++++++++++++ 1 file changed, 117 insertions(+)
target/i386/mshv/mshv-cpu.c +117 -0
@@ -12,6 +12,7 @@#include "qemu/osdep.h" #include "qemu/error-report.h" +#include "qemu/memalign.h" #include "qemu/typedefs.h" #include "system/mshv.h"
@@ -20,6 +21,7 @@#include "hw/hyperv/hvgdk.h" #include "hw/hyperv/hvgdk_mini.h" #include "hw/hyperv/hvhdk_mini.h" +#include "hw/i386/apic_internal.h" #include "cpu.h" #include "emulate/x86_decode.h"
@@ -561,6 +563,114 @@ static int set_cpu_state(const CPUState *cpu, const MshvFPU *fpu_regs,return 0 ; } +static int get_vp_state (int cpu_fd,struct mshv_get_set_vp_state *state) +{ +int ret; + + ret =ioctl (cpu_fd,MSHV_GET_VP_STATE , state); +if (ret <0 ) { +error_report ("failed to get partition state: %s" ,strerror (errno)); +return -1 ; + } + +return 0 ; +} + +static int get_lapic (int cpu_fd, +struct hv_local_interrupt_controller_state *state) +{ +int ret; +size_t size =4096 ; +/* buffer aligned to 4k, as *state requires that */ +void *buffer =qemu_memalign (size, size); +struct mshv_get_set_vp_state mshv_state = {0 }; + + mshv_state.buf_ptr = (uint64_t ) buffer; + mshv_state.buf_sz = size; + mshv_state.type =MSHV_VP_STATE_LAPIC ; + + ret =get_vp_state (cpu_fd, &mshv_state); +if (ret ==0 ) { +memcpy (state, buffer,sizeof (*state)); + } +qemu_vfree (buffer); +if (ret <0 ) { +error_report ("failed to get lapic" ); +return -1 ; + } + +return 0 ; +} + +static uint32_t set_apic_delivery_mode (uint32_t reg,uint32_t mode) +{ +return ((reg) & ~0x700 ) | ((mode) <<8 ); +} + +static int set_vp_state (int cpu_fd,const struct mshv_get_set_vp_state *state) +{ +int ret; + + ret =ioctl (cpu_fd,MSHV_SET_VP_STATE , state); +if (ret <0 ) { +error_report ("failed to set partition state: %s" ,strerror (errno)); +return -1 ; + } + +return 0 ; +} + +static int set_lapic (int cpu_fd, +const struct hv_local_interrupt_controller_state *state) +{ +int ret; +size_t size =4096 ; +/* buffer aligned to 4k, as *state requires that */ +void *buffer =qemu_memalign (size, size); +struct mshv_get_set_vp_state mshv_state = {0 }; + +if (!state) { +error_report ("lapic state is NULL" ); +return -1 ; + } +memcpy (buffer, state,sizeof (*state)); + + mshv_state.buf_ptr = (uint64_t ) buffer; + mshv_state.buf_sz = size; + mshv_state.type =MSHV_VP_STATE_LAPIC ; + + ret =set_vp_state (cpu_fd, &mshv_state); +qemu_vfree (buffer); +if (ret <0 ) { +error_report ("failed to set lapic: %s" ,strerror (errno)); +return -1 ; + } + +return 0 ; +} + +static int set_lint (int cpu_fd) +{ +int ret; +uint32_t *lvt_lint0, *lvt_lint1; + +struct hv_local_interrupt_controller_state lapic_state = {0 }; + ret =get_lapic (cpu_fd, &lapic_state); +if (ret <0 ) { +return ret; + } + + lvt_lint0 = &lapic_state.apic_lvt_lint0; + *lvt_lint0 =set_apic_delivery_mode (*lvt_lint0,APIC_DM_EXTINT ); + + lvt_lint1 = &lapic_state.apic_lvt_lint1; + *lvt_lint1 =set_apic_delivery_mode (*lvt_lint1,APIC_DM_NMI ); + +/* TODO: should we skip setting lapic if the values are the same? */ + +return set_lapic (cpu_fd, &lapic_state); +} +/* * TODO: populate topology info: *
@@ -572,6 +682,7 @@ int mshv_configure_vcpu(const CPUState *cpu, const struct MshvFPU *fpu, uint64_t xcr0) {int ret; +int cpu_fd =mshv_vcpufd (cpu); ret =set_cpu_state (cpu, fpu, xcr0);if (ret <0 ) {
@@ -579,6 +690,12 @@ int mshv_configure_vcpu(const CPUState *cpu, const struct MshvFPU *fpu,return -1 ; } + ret =set_lint (cpu_fd); +if (ret <0 ) { +error_report ("failed to set lpic int" ); +return -1 ; + } +return 0 ; }
Signature · 1 line
2.34.1
PATCH v4 18/27 target/i386/mshv: Register CPUID entries with MSHV
In reply to Magnus KulkeConvert the guest CPU's CPUID model into MSHV's format and register it with the hypervisor. This ensures that the guest observes the correct CPU feature set during CPUID instructions.
--- target/i386/mshv/mshv-cpu.c | 206 ++++++++++++++++++++++++++++++++++++ 1 file changed, 206 insertions(+)
target/i386/mshv/mshv-cpu.c +206 -0
@@ -402,6 +402,206 @@ int mshv_load_regs(CPUState *cpu)return 0 ; } +static void add_cpuid_entry (GList *cpuid_entries, +uint32_t function,uint32_t index, +uint32_t eax,uint32_t ebx, +uint32_t ecx,uint32_t edx) +{ +struct hv_cpuid_entry *entry; + + entry =g_malloc0 (sizeof (struct hv_cpuid_entry )); + entry->function = function; + entry->index = index; + entry->eax = eax; + entry->ebx = ebx; + entry->ecx = ecx; + entry->edx = edx; + + cpuid_entries =g_list_append (cpuid_entries, entry); +} + +static void collect_cpuid_entries (const CPUState *cpu,GList *cpuid_entries) +{ +X86CPU *x86_cpu =X86_CPU (cpu); +CPUX86State *env = &x86_cpu->env; +uint32_t eax, ebx, ecx, edx; +uint32_t leaf, subleaf; +size_t max_leaf =0x1F ; +size_t max_subleaf =0x20 ; + +uint32_t leaves_with_subleaves[] = {0x4 ,0x7 ,0xD ,0xF ,0x10 }; +int n_subleaf_leaves =ARRAY_SIZE (leaves_with_subleaves); + +/* Regular leaves without subleaves */ +for (leaf =0 ; leaf <= max_leaf; leaf++) { +bool has_subleaves = false; +for (int i =0 ; i < n_subleaf_leaves; i++) { +if (leaf == leaves_with_subleaves[i]) { + has_subleaves = true; +break ; + } + } + +if (!has_subleaves) { +cpu_x86_cpuid (env, leaf,0 , &eax, &ebx, &ecx, &edx); +if (eax ==0 && ebx ==0 && ecx ==0 && edx ==0 ) { +/* all zeroes indicates no more leaves */ +continue ; + } + +add_cpuid_entry (cpuid_entries, leaf,0 , eax, ebx, ecx, edx); +continue ; + } + + subleaf =0 ; +while (subleaf < max_subleaf) { +cpu_x86_cpuid (env, leaf, subleaf, &eax, &ebx, &ecx, &edx); + +if (eax ==0 && ebx ==0 && ecx ==0 && edx ==0 ) { +/* all zeroes indicates no more leaves */ +break ; + } +add_cpuid_entry (cpuid_entries, leaf,0 , eax, ebx, ecx, edx); + subleaf++; + } + } +} + +static int register_intercept_result_cpuid_entry (const CPUState *cpu, +uint8_t subleaf_specific, +uint8_t always_override, +struct hv_cpuid_entry *entry) +{ +int ret; +int vp_index = cpu->cpu_index; +int cpu_fd =mshv_vcpufd (cpu); + +struct hv_register_x64_cpuid_result_parameters cpuid_params = { + .input.eax = entry->function, + .input.ecx = entry->index, + .input.subleaf_specific = subleaf_specific, + .input.always_override = always_override, + .input.padding =0 , +/* +* With regard to masks - these are to specify bits to be overwritten +* The current CpuidEntry structure wouldn't allow to carry the masks +* in addition to the actual register values. For this reason, the +* masks are set to the exact values of the corresponding register bits +* to be registered for an overwrite. To view resulting values the +* hypervisor would return, HvCallGetVpCpuidValues hypercall can be +* used. +*/ + .result.eax = entry->eax, + .result.eax_mask = entry->eax, + .result.ebx = entry->ebx, + .result.ebx_mask = entry->ebx, + .result.ecx = entry->ecx, + .result.ecx_mask = entry->ecx, + .result.edx = entry->edx, + .result.edx_mask = entry->edx, + }; +union hv_register_intercept_result_parameters parameters = { + .cpuid = cpuid_params, + }; + +hv_input_register_intercept_result in = {0 }; + in.vp_index = vp_index; + in.intercept_type =HV_INTERCEPT_TYPE_X64_CPUID ; + in.parameters = parameters; + +struct mshv_root_hvcall args = {0 }; + args.code =HVCALL_REGISTER_INTERCEPT_RESULT ; + args.in_sz =sizeof (in); + args.in_ptr = (uint64_t )∈ + + ret =mshv_hvcall (cpu_fd, &args); +if (ret <0 ) { +error_report ("failed to register intercept result for cpuid" ); +return -1 ; + } + +return 0 ; +} + +static int register_intercept_result_cpuid (const CPUState *cpu, +struct hv_cpuid *cpuid) +{ +int ret =0 , entry_ret; +struct hv_cpuid_entry *entry; +uint8_t subleaf_specific, always_override; + +for (size_t i =0 ; i < cpuid->nent; i++) { + entry = &cpuid->entries[i]; + +/* set defaults */ + subleaf_specific =0 ; + always_override =1 ; + +/* Intel */ +/* 0xb - Extended Topology Enumeration Leaf */ +/* 0x1f - V2 Extended Topology Enumeration Leaf */ +/* AMD */ +/* 0x8000_001e - Processor Topology Information */ +/* 0x8000_0026 - Extended CPU Topology */ +if (entry->function ==0xb + || entry->function ==0x1f + || entry->function ==0x8000001e + || entry->function ==0x80000026 ) { + subleaf_specific =1 ; + always_override =1 ; + }else if (entry->function ==0x00000001 + || entry->function ==0x80000000 + || entry->function ==0x80000001 + || entry->function ==0x80000008 ) { + subleaf_specific =0 ; + always_override =1 ; + } + + entry_ret =register_intercept_result_cpuid_entry (cpu, subleaf_specific, + always_override, + entry); +if ((entry_ret <0 ) && (ret ==0 )) { + ret = entry_ret; + } + } + +return ret; +} + +static int set_cpuid2 (const CPUState *cpu) +{ +int ret; +size_t n_entries, cpuid_size; +struct hv_cpuid *cpuid; +struct hv_cpuid_entry *entry; +GList *entries =NULL ; + +collect_cpuid_entries (cpu, entries); + n_entries =g_list_length (entries); + + cpuid_size =sizeof (struct hv_cpuid ) + + n_entries *sizeof (struct hv_cpuid_entry ); + + cpuid =g_malloc0 (cpuid_size); + cpuid->nent = n_entries; + cpuid->padding =0 ; + +for (size_t i =0 ; i < n_entries; i++) { + entry =g_list_nth_data (entries, i); + cpuid->entries[i] = *entry; +g_free (entry); + } +g_list_free (entries); + + ret =register_intercept_result_cpuid (cpu, cpuid); +g_free (cpuid); +if (ret <0 ) { +return ret; + } + +return 0 ; +} +static inline void populate_hv_segment_reg (SegmentCache *seg,hv_x64_segment_register *hv_reg) {
@@ -684,6 +884,12 @@ int mshv_configure_vcpu(const CPUState *cpu, const struct MshvFPU *fpu,int ret;int cpu_fd =mshv_vcpufd (cpu); + ret =set_cpuid2 (cpu); +if (ret <0 ) { +error_report ("failed to set cpuid" ); +return -1 ; + } + ret =set_cpu_state (cpu, fpu, xcr0);if (ret <0 ) {error_report ("failed to set cpu state" );
Signature · 1 line
2.34.1
PATCH v4 19/27 target/i386/mshv: Register MSRs with MSHV
In reply to Magnus KulkeBuild and register the guest vCPU's model-specific registers using the MSHV interface.
--- accel/mshv/meson.build | 1 + accel/mshv/msr.c | 374 ++++++++++++++++++++++++++++++++++++ include/system/mshv.h | 17 ++ target/i386/cpu.h | 2 + target/i386/mshv/mshv-cpu.c | 33 ++++ 5 files changed, 427 insertions(+) create mode 100644 accel/mshv/msr.c
accel/mshv/meson.build +1 -0
@@ -2,6 +2,7 @@ mshv_ss = ss.source_set() mshv_ss.add(if_true: files( 'irq.c', 'mem.c', + 'msr.c', 'mshv-all.c' ))
accel/mshv/msr.c new file +374 -0
374 lines not on this page · raw message
include/system/mshv.h +17 -0
@@ -38,6 +38,8 @@ typedef struct hyperv_message hv_message;#define MSHV_PAGE_SHIFT 12 +#define MSHV_MSR_ENTRIES_COUNT 64 +#ifdef CONFIG_MSHV_IS_POSSIBLE extern bool mshv_allowed;#define mshv_enabled () (mshv_allowed)
@@ -121,6 +123,21 @@ int mshv_arch_post_init_vm(int vm_fd);int mshv_hvcall (int fd,const struct mshv_root_hvcall *args); +/* msr */ +typedef struct MshvMsrEntry { +uint32_t index; +uint32_t reserved; +uint64_t data; +}MshvMsrEntry ; + +typedef struct MshvMsrEntries { +MshvMsrEntry entries[MSHV_MSR_ENTRIES_COUNT ]; +uint32_t nmsrs; +}MshvMsrEntries ; + +int mshv_configure_msr (const CPUState *cpu,const MshvMsrEntry *msrs, +size_t n_msrs); +/* memory */ typedef struct MshvMemoryRegion { uint64_t guest_phys_addr;
target/i386/cpu.h +2 -0
@@ -435,9 +435,11 @@ typedef enum X86Seg {#define MSR_SMI_COUNT 0x34#define MSR_CORE_THREAD_COUNT 0x35#define MSR_MTRRcap 0xfe +#define MSR_MTRR_MEM_TYPE_WB 0x06#define MSR_MTRRcap_VCNT 8#define MSR_MTRRcap_FIXRANGE_SUPPORT (1 << 8)#define MSR_MTRRcap_WC_SUPPORTED (1 << 10) +#define MSR_MTRR_ENABLE (1 << 11)#define MSR_IA32_SYSENTER_CS 0x174#define MSR_IA32_SYSENTER_ESP 0x175
target/i386/mshv/mshv-cpu.c +33 -0
@@ -871,6 +871,33 @@ static int set_lint(int cpu_fd)return set_lapic (cpu_fd, &lapic_state); } +static int setup_msrs (const CPUState *cpu) +{ +int ret; +uint64_t default_type =MSR_MTRR_ENABLE |MSR_MTRR_MEM_TYPE_WB ; + +/* boot msr entries */ +MshvMsrEntry msrs[9 ] = { + { .index =IA32_MSR_SYSENTER_CS , .data =0x0 , }, + { .index =IA32_MSR_SYSENTER_ESP , .data =0x0 , }, + { .index =IA32_MSR_SYSENTER_EIP , .data =0x0 , }, + { .index =IA32_MSR_STAR , .data =0x0 , }, + { .index =IA32_MSR_CSTAR , .data =0x0 , }, + { .index =IA32_MSR_LSTAR , .data =0x0 , }, + { .index =IA32_MSR_KERNEL_GS_BASE , .data =0x0 , }, + { .index =IA32_MSR_SFMASK , .data =0x0 , }, + { .index =IA32_MSR_MTRR_DEF_TYPE , .data = default_type, }, + }; + + ret =mshv_configure_msr (cpu, msrs,9 ); +if (ret <0 ) { +error_report ("failed to setup msrs" ); +return -1 ; + } + +return 0 ; +} +/* * TODO: populate topology info: *
@@ -890,6 +917,12 @@ int mshv_configure_vcpu(const CPUState *cpu, const struct MshvFPU *fpu,return -1 ; } + ret =setup_msrs (cpu); +if (ret <0 ) { +error_report ("failed to setup msrs" ); +return -1 ; + } + ret =set_cpu_state (cpu, fpu, xcr0);if (ret <0 ) {error_report ("failed to set cpu state" );
Signature · 1 line
2.34.1
PATCH v4 20/27 target/i386/mshv: Integrate x86 instruction decoder/emulator
In reply to Magnus KulkeConnect the x86 instruction decoder and emulator to the MSHV backend to handle intercepted instructions. This enables software emulation of MMIO operations in MSHV guests. MSHV has a translate_gva hypercall that is used to accessing the physical guest memory.
A guest might read from unmapped memory regions (e.g. OVMF will probe 0xfed40000 for a vTPM). In those cases 0xFF bytes is returned instead of aborting the execution.
--- accel/mshv/mem.c | 65 +++++++++++++++++ include/system/mshv.h | 4 ++ target/i386/mshv/mshv-cpu.c | 135 ++++++++++++++++++++++++++++++++++++ 3 files changed, 204 insertions(+)
accel/mshv/mem.c +65 -0
@@ -58,6 +58,71 @@ static int map_or_unmap(int vm_fd, const MshvMemoryRegion *mr, bool map)return set_guest_memory (vm_fd, ®ion); } +static int handle_unmapped_mmio_region_read (uint64_t gpa,uint64_t size, +uint8_t *data) +{ +warn_report ("read from unmapped mmio region gpa=0x%lx size=%lu" , gpa, size); + +if (size ==0 || size >8 ) { +error_report ("invalid size %lu for reading from unmapped mmio region" , + size); +return -1 ; + } + +memset (data,0xFF , size); + +return 0 ; +} + +int mshv_guest_mem_read (uint64_t gpa,uint8_t *data,uintptr_t size, +bool is_secure_mode,bool instruction_fetch) +{ +int ret; +MemTxAttrs memattr = { .secure = is_secure_mode }; + +if (instruction_fetch) { +trace_mshv_insn_fetch (gpa, size); + }else { +trace_mshv_mem_read (gpa, size); + } + + ret =address_space_rw (&address_space_memory, gpa, memattr, (void *)data, + size, false); +if (ret ==MEMTX_OK ) { +return 0 ; + } + +if (ret ==MEMTX_DECODE_ERROR ) { +return handle_unmapped_mmio_region_read (gpa, size, data); + } + +error_report ("failed to read guest memory at 0x%lx" , gpa); +return -1 ; +} + +int mshv_guest_mem_write (uint64_t gpa,const uint8_t *data,uintptr_t size, +bool is_secure_mode) +{ +int ret; +MemTxAttrs memattr = { .secure = is_secure_mode }; + +trace_mshv_mem_write (gpa, size); + ret =address_space_rw (&address_space_memory, gpa, memattr, (void *)data, + size, true); +if (ret ==MEMTX_OK ) { +return 0 ; + } + +if (ret ==MEMTX_DECODE_ERROR ) { +warn_report ("write to unmapped mmio region gpa=0x%lx size=%lu" , gpa, + size); +return 0 ; + } + +error_report ("Failed to write guest memory" ); +return -1 ; +} +static int set_memory (const MshvMemoryRegion *mshv_mr,bool add) {int ret =0 ;
include/system/mshv.h +4 -0
@@ -148,6 +148,10 @@ typedef struct MshvMemoryRegion {int mshv_add_mem (int vm_fd,const MshvMemoryRegion *mr);int mshv_remove_mem (int vm_fd,const MshvMemoryRegion *mr); +int mshv_guest_mem_read (uint64_t gpa,uint8_t *data,uintptr_t size, +bool is_secure_mode,bool instruction_fetch); +int mshv_guest_mem_write (uint64_t gpa,const uint8_t *data,uintptr_t size, +bool is_secure_mode);void mshv_set_phys_mem (MshvMemoryListener *mml,MemoryRegionSection *section,bool add);
target/i386/mshv/mshv-cpu.c +135 -0
149 lines not on this page · raw message
Signature · 1 line
2.34.1
PATCH v4 21/27 target/i386/mshv: Write MSRs to the hypervisor
In reply to Magnus KulkePush current model-specific register (MSR) values to MSHV's vCPUs as part of setting state to the hypervisor.
--- target/i386/mshv/mshv-cpu.c | 68 +++++++++++++++++++++++++++++++++++-- 1 file changed, 66 insertions(+), 2 deletions(-)
target/i386/mshv/mshv-cpu.c +66 -2
@@ -997,6 +997,65 @@ static int put_regs(const CPUState *cpu)return 0 ; } +struct MsrPair { +uint32_t index; +uint64_t value; +}; + +static int put_msrs (const CPUState *cpu) +{ +int ret =0 ; +X86CPU *x86cpu =X86_CPU (cpu); +CPUX86State *env = &x86cpu->env; +MshvMsrEntries *msrs =g_malloc0 (sizeof (MshvMsrEntries)); + +struct MsrPair pairs[] = { + {MSR_IA32_SYSENTER_CS , env->sysenter_cs }, + {MSR_IA32_SYSENTER_ESP , env->sysenter_esp }, + {MSR_IA32_SYSENTER_EIP , env->sysenter_eip }, + {MSR_EFER , env->efer }, + {MSR_PAT , env->pat }, + {MSR_STAR , env->star }, + {MSR_CSTAR , env->cstar }, + {MSR_LSTAR , env->lstar }, + {MSR_KERNELGSBASE , env->kernelgsbase }, + {MSR_FMASK , env->fmask }, + { MSR_MTRRdefType, env->mtrr_deftype }, + {MSR_VM_HSAVE_PA , env->vm_hsave }, + {MSR_SMI_COUNT , env->msr_smi_count }, + {MSR_IA32_PKRS , env->pkrs }, + {MSR_IA32_BNDCFGS , env->msr_bndcfgs }, + {MSR_IA32_XSS , env->xss }, + {MSR_IA32_UMWAIT_CONTROL , env->umwait }, + {MSR_IA32_TSX_CTRL , env->tsx_ctrl }, + {MSR_AMD64_TSC_RATIO , env->amd_tsc_scale_msr }, + {MSR_TSC_AUX , env->tsc_aux }, + {MSR_TSC_ADJUST , env->tsc_adjust }, + {MSR_IA32_SMBASE , env->smbase }, + {MSR_IA32_SPEC_CTRL , env->spec_ctrl }, + {MSR_VIRT_SSBD , env->virt_ssbd }, + }; + +if (ARRAY_SIZE (pairs) >MSHV_MSR_ENTRIES_COUNT ) { +error_report ("MSR entries exceed maximum size" ); +g_free (msrs); +return -1 ; + } + +for (size_t i =0 ; i <ARRAY_SIZE (pairs); i++) { +MshvMsrEntry *entry = &msrs->entries[i]; + entry->index = pairs[i].index; + entry->reserved =0 ; + entry->data = pairs[i].value; + msrs->nmsrs++; + } + + ret =mshv_configure_msr (cpu, &msrs->entries[0 ], msrs->nmsrs); +g_free (msrs); +return ret; +} + +int mshv_arch_put_registers (const CPUState *cpu) {int ret;
@@ -1007,8 +1066,13 @@ int mshv_arch_put_registers(const CPUState *cpu)return -1 ; } -error_report ("unimplemented" ); -abort (); + ret =put_msrs (cpu); +if (ret <0 ) { +error_report ("Failed to put msrs" ); +return -1 ; + } + +return 0 ; } void mshv_arch_amend_proc_features(
Signature · 1 line
2.34.1
PATCH v4 22/27 target/i386/mshv: Implement mshv_vcpu_run()
In reply to Magnus KulkeAdd the main vCPU execution loop for MSHV using the MSHV_RUN_VP ioctl.
The execution loop handles guest entry and VM exits. There are handlers for memory r/w, PIO and MMIO to which the exit events are dispatched.
In case of MMIO the i386 instruction decoder/emulator is invoked to perform the operation in user space.
--- target/i386/mshv/mshv-cpu.c | 444 +++++++++++++++++++++++++++++++++++- 1 file changed, 442 insertions(+), 2 deletions(-)
target/i386/mshv/mshv-cpu.c +442 -2
@@ -1081,10 +1081,450 @@ void mshv_arch_amend_proc_features( features->access_guest_idle_reg =1 ; } +static int set_memory_info (const struct hyperv_message *msg, +struct hv_x64_memory_intercept_message *info) +{ +if (msg->header.message_type !=HVMSG_GPA_INTERCEPT + && msg->header.message_type !=HVMSG_UNMAPPED_GPA + && msg->header.message_type !=HVMSG_UNACCEPTED_GPA ) { +error_report ("invalid message type" ); +return -1 ; + } +memcpy (info, msg->payload,sizeof (*info)); + +return 0 ; +} + +static int emulate_instruction (CPUState *cpu, +const uint8_t *insn_bytes,size_t insn_len, +uint64_t gva,uint64_t gpa) +{ +X86CPU *x86_cpu =X86_CPU (cpu); +CPUX86State *env = &x86_cpu->env; +struct x86_decode decode = {0 }; +int ret; +x86_insn_stream stream = { .bytes = insn_bytes, .len = insn_len }; + + ret =mshv_load_regs (cpu); +if (ret <0 ) { +error_report ("failed to load registers" ); +return -1 ; + } + +decode_instruction_stream (env, &decode, &stream); +exec_instruction (env, &decode); + + ret =mshv_store_regs (cpu); +if (ret <0 ) { +error_report ("failed to store registers" ); +return -1 ; + } + +return 0 ; +} + +static int handle_mmio (CPUState *cpu,const struct hyperv_message *msg, +MshvVmExit *exit_reason) +{ +struct hv_x64_memory_intercept_message info = {0 }; +size_t insn_len; +uint8_t access_type; +uint8_t *instruction_bytes; +int ret; + + ret =set_memory_info (msg, &info); +if (ret <0 ) { +error_report ("failed to convert message to memory info" ); +return -1 ; + } + insn_len = info.instruction_byte_count; + access_type = info.header.intercept_access_type; + +if (access_type ==HV_X64_INTERCEPT_ACCESS_TYPE_EXECUTE ) { +error_report ("invalid intercept access type: execute" ); +return -1 ; + } + +if (insn_len >16 ) { +error_report ("invalid mmio instruction length: %zu" , insn_len); +return -1 ; + } + +trace_mshv_handle_mmio (info.guest_virtual_address, + info.guest_physical_address, + info.instruction_byte_count, access_type); + + instruction_bytes = info.instruction_bytes; + + ret =emulate_instruction (cpu, instruction_bytes, insn_len, + info.guest_virtual_address, + info.guest_physical_address); +if (ret <0 ) { +error_report ("failed to emulate mmio" ); +return -1 ; + } + + *exit_reason = MshvVmExitIgnore; + +return 0 ; +} + +static int set_ioport_info (const struct hyperv_message *msg, +hv_x64_io_port_intercept_message *info) +{ +if (msg->header.message_type !=HVMSG_X64_IO_PORT_INTERCEPT ) { +error_report ("Invalid message type" ); +return -1 ; + } +memcpy (info, msg->payload,sizeof (*info)); + +return 0 ; +} + +static int set_x64_registers (const CPUState *cpu,const uint32_t *names, +const uint64_t *values) +{ + +hv_register_assoc assocs[2 ]; +int ret; + +for (size_t i =0 ; i <ARRAY_SIZE (assocs); i++) { + assocs[i].name = names[i]; + assocs[i].value.reg64 = values[i]; + } + + ret =mshv_set_generic_regs (cpu, assocs,ARRAY_SIZE (assocs)); +if (ret <0 ) { +error_report ("failed to set x64 registers" ); +return -1 ; + } + +return 0 ; +} + +static inline MemTxAttrs get_mem_attrs (bool is_secure_mode) +{ +MemTxAttrs memattr = {0 }; + memattr.secure = is_secure_mode; +return memattr; +} + +static void pio_read (uint64_t port,uint8_t *data,uintptr_t size, +bool is_secure_mode) +{ +int ret =0 ; +MemTxAttrs memattr =get_mem_attrs (is_secure_mode); + ret =address_space_rw (&address_space_io, port, memattr, (void *)data, size, + false); +if (ret !=MEMTX_OK ) { +error_report ("Failed to read from port %lx: %d" , port, ret); +abort (); + } +} + +static int pio_write (uint64_t port,const uint8_t *data,uintptr_t size, +bool is_secure_mode) +{ +int ret =0 ; +MemTxAttrs memattr =get_mem_attrs (is_secure_mode); + ret =address_space_rw (&address_space_io, port, memattr, (void *)data, size, + true); +return ret; +} + +static int handle_pio_non_str (const CPUState *cpu, +hv_x64_io_port_intercept_message *info) +{ +size_t len = info->access_info.access_size; +uint8_t access_type = info->header.intercept_access_type; +int ret; +uint32_t val, eax; +const uint32_t eax_mask =0xffffffffu >> (32 - len *8 ); +size_t insn_len; +uint64_t rip, rax; +uint32_t reg_names[2 ]; +uint64_t reg_values[2 ]; +uint16_t port = info->port_number; + +if (access_type ==HV_X64_INTERCEPT_ACCESS_TYPE_WRITE ) { +union { +uint32_t u32; +uint8_t bytes[4 ]; + } conv; + +/* convert the first 4 bytes of rax to bytes */ + conv.u32 = (uint32_t )info->rax; +/* secure mode is set to false */ + ret =pio_write (port, conv.bytes, len, false); +if (ret <0 ) { +error_report ("Failed to write to io port" ); +return -1 ; + } + }else { +uint8_t data[4 ] = {0 }; +/* secure mode is set to false */ +pio_read (info->port_number, data, len, false); + +/* Preserve high bits in EAX, but clear out high bits in RAX */ + val = *(uint32_t *)data; + eax = (((uint32_t )info->rax) & ~eax_mask) | (val & eax_mask); + info->rax = (uint64_t )eax; + } + + insn_len = info->header.instruction_length; + +/* Advance RIP and update RAX */ + rip = info->header.rip + insn_len; + rax = info->rax; + + reg_names[0 ] =HV_X64_REGISTER_RIP ; + reg_values[0 ] = rip; + reg_names[1 ] =HV_X64_REGISTER_RAX ; + reg_values[1 ] = rax; + + ret =set_x64_registers (cpu, reg_names, reg_values); +if (ret <0 ) { +error_report ("Failed to set x64 registers" ); +return -1 ; + } + + cpu->accel->dirty = false; + +return 0 ; +} + +static int fetch_guest_state (CPUState *cpu) +{ +int ret; + + ret =mshv_get_standard_regs (cpu); +if (ret <0 ) { +error_report ("Failed to get standard registers" ); +return -1 ; + } + + ret =mshv_get_special_regs (cpu); +if (ret <0 ) { +error_report ("Failed to get special registers" ); +return -1 ; + } + +return 0 ; +} + +static int read_memory (const CPUState *cpu,uint64_t initial_gva, +uint64_t initial_gpa,uint64_t gva,uint8_t *data, +size_t len) +{ +int ret; +uint64_t gpa, flags; + +if (gva == initial_gva) { + gpa = initial_gpa; + }else { + flags =HV_TRANSLATE_GVA_VALIDATE_READ ; + ret =translate_gva (cpu, gva, &gpa, flags); +if (ret <0 ) { +return -1 ; + } + + ret =mshv_guest_mem_read (gpa, data, len, false, false); +if (ret <0 ) { +error_report ("failed to read guest mem" ); +return -1 ; + } + } + +return 0 ; +} + +static int write_memory (const CPUState *cpu,uint64_t initial_gva, +uint64_t initial_gpa,uint64_t gva,const uint8_t *data, +size_t len) +{ +int ret; +uint64_t gpa, flags; + +if (gva == initial_gva) { + gpa = initial_gpa; + }else { + flags =HV_TRANSLATE_GVA_VALIDATE_WRITE ; + ret =translate_gva (cpu, gva, &gpa, flags); +if (ret <0 ) { +error_report ("failed to translate gva to gpa" ); +return -1 ; + } + } + ret =mshv_guest_mem_write (gpa, data, len, false); +if (ret !=MEMTX_OK ) { +error_report ("failed to write to mmio" ); +return -1 ; + } + +return 0 ; +} + +static int handle_pio_str_write (CPUState *cpu, +hv_x64_io_port_intercept_message *info, +size_t repeat,uint16_t port, +bool direction_flag) +{ +int ret; +uint64_t src; +uint8_t data[4 ] = {0 }; +size_t len = info->access_info.access_size; + + src =linear_addr (cpu, info->rsi,R_DS ); + +for (size_t i =0 ; i < repeat; i++) { + ret =read_memory (cpu,0 ,0 , src, data, len); +if (ret <0 ) { +error_report ("Failed to read memory" ); +return -1 ; + } + ret =pio_write (port, data, len, false); +if (ret <0 ) { +error_report ("Failed to write to io port" ); +return -1 ; + } + src += direction_flag ? -len : len; + info->rsi += direction_flag ? -len : len; + } + +return 0 ; +} + +static int handle_pio_str_read (CPUState *cpu, +hv_x64_io_port_intercept_message *info, +size_t repeat,uint16_t port, +bool direction_flag) +{ +int ret; +uint64_t dst; +size_t len = info->access_info.access_size; +uint8_t data[4 ] = {0 }; + + dst =linear_addr (cpu, info->rdi,R_ES ); + +for (size_t i =0 ; i < repeat; i++) { +pio_read (port, data, len, false); + + ret =write_memory (cpu,0 ,0 , dst, data, len); +if (ret <0 ) { +error_report ("Failed to write memory" ); +return -1 ; + } + dst += direction_flag ? -len : len; + info->rdi += direction_flag ? -len : len; + } + +return 0 ; +} + +static int handle_pio_str (CPUState *cpu,hv_x64_io_port_intercept_message *info) +{ +uint8_t access_type = info->header.intercept_access_type; +uint16_t port = info->port_number; +bool repop = info->access_info.rep_prefix ==1 ; +size_t repeat = repop ? info->rcx :1 ; +size_t insn_len = info->header.instruction_length; +bool direction_flag; +uint32_t reg_names[3 ]; +uint64_t reg_values[3 ]; +int ret; +X86CPU *x86_cpu =X86_CPU (cpu); +CPUX86State *env = &x86_cpu->env; + + ret =fetch_guest_state (cpu); +if (ret <0 ) { +error_report ("Failed to fetch guest state" ); +return -1 ; + } + + direction_flag = (env->eflags &DESC_E_MASK ) !=0 ; + +if (access_type ==HV_X64_INTERCEPT_ACCESS_TYPE_WRITE ) { + ret =handle_pio_str_write (cpu, info, repeat, port, direction_flag); +if (ret <0 ) { +error_report ("Failed to handle pio str write" ); +return -1 ; + } + reg_names[0 ] =HV_X64_REGISTER_RSI ; + reg_values[0 ] = info->rsi; + }else { + ret =handle_pio_str_read (cpu, info, repeat, port, direction_flag); + reg_names[0 ] =HV_X64_REGISTER_RDI ; + reg_values[0 ] = info->rdi; + } + + reg_names[1 ] =HV_X64_REGISTER_RIP ; + reg_values[1 ] = info->header.rip + insn_len; + reg_names[2 ] =HV_X64_REGISTER_RAX ; + reg_values[2 ] = info->rax; + + ret =set_x64_registers (cpu, reg_names, reg_values); +if (ret <0 ) { +error_report ("Failed to set x64 registers" ); +return -1 ; + } + + cpu->accel->dirty = false; + +return 0 ; +} + +static int handle_pio (CPUState *cpu,const struct hyperv_message *msg) +{ +struct hv_x64_io_port_intercept_message info = {0 }; +int ret; + + ret =set_ioport_info (msg, &info); +if (ret <0 ) { +error_report ("Failed to convert message to ioport info" ); +return -1 ; + } + +if (info.access_info.string_op) { +return handle_pio_str (cpu, &info); + } + +return handle_pio_non_str (cpu, &info); +} +int mshv_run_vcpu (int vm_fd,CPUState *cpu,hv_message *msg,MshvVmExit *exit) { -error_report ("unimplemented" ); -abort (); +int ret; +enum MshvVmExit exit_reason; +int cpu_fd =mshv_vcpufd (cpu); + + ret =ioctl (cpu_fd,MSHV_RUN_VP , msg); +if (ret <0 ) { +return MshvVmExitShutdown; + } + +switch (msg->header.message_type) { +case HVMSG_UNRECOVERABLE_EXCEPTION : +return MshvVmExitShutdown; +case HVMSG_UNMAPPED_GPA : +case HVMSG_GPA_INTERCEPT : + ret =handle_mmio (cpu, msg, &exit_reason); +if (ret <0 ) { +error_report ("failed to handle mmio" ); +return -1 ; + } +return exit_reason; +case HVMSG_X64_IO_PORT_INTERCEPT : + ret =handle_pio (cpu, msg); +if (ret <0 ) { +return MshvVmExitSpecial; + } +return MshvVmExitIgnore; +default : +break ; + } + + *exit = MshvVmExitIgnore; +return 0 ; }void mshv_remove_vcpu (int vm_fd,int cpu_fd)
Signature · 1 line
2.34.1
PATCH v4 23/27 accel/mshv: Handle overlapping mem mappings
In reply to Magnus KulkeQEMU maps certain regions into the guest multiple times, as seen in the trace below. Currently the MSHV kernel driver will reject those mappings. To workaround this, a record is kept (a static global list of "slots", inspired by what the HVF accelerator has implemented). An overlapping region is not registered at the hypervisor, and marked as mapped=false. If there is an UNMAPPED_GPA exit, we can look for a slot that is unmapped and would cover the GPA. In this case we map out the conflicting slot and map in the requested region.
mshv_set_phys_mem add=1 name=pc.biosmshv_map_memory => u_a=7ffff4e00000 gpa=00fffc0000 size=00040000
mshv_set_phys_mem add=1 name=ioapic mshv_set_phys_mem add=1 name=hpet mshv_set_phys_mem add=0 name=pc.ram mshv_unmap_memory u_a=7fff67e00000 gpa=0000000000 size=80000000 mshv_set_phys_mem add=1 name=pc.ram mshv_map_memory u_a=7fff67e00000 gpa=0000000000 size=000c0000 mshv_set_phys_mem add=1 name=pc.rom mshv_map_memory u_a=7ffff4c00000 gpa=00000c0000 size=00020000 mshv_set_phys_mem add=1 name=pc.bios
mshv_remap_attempt => u_a=7ffff4e20000 gpa=00000e0000 size=00020000
The mapping table is guarded by a mutex for concurrent modification and RCU mechanisms for concurrent reads. Writes occur rarely, but we'll have to verify whether an unmapped region exist for each UNMAPPED_GPA exit, which happens frequently.
--- accel/mshv/mem.c | 406 +++++++++++++++++++++++++++++++++--- accel/mshv/mshv-all.c | 2 + accel/mshv/trace-events | 5 + include/system/mshv.h | 24 ++- target/i386/mshv/mshv-cpu.c | 43 ++++ 5 files changed, 448 insertions(+), 32 deletions(-)
accel/mshv/mem.c +378 -28
@@ -11,7 +11,9 @@*/ #include "qemu/osdep.h" +#include "qemu/lockable.h" #include "qemu/error-report.h" +#include "qemu/rcu.h" #include "linux/mshv.h" #include "system/address-spaces.h" #include "system/mshv.h"
@@ -19,6 +21,137 @@#include <sys/ioctl.h> #include "trace.h" +typedef struct SlotsRCUReclaim { +struct rcu_head rcu; +GList *old_head; +MshvMemorySlot *removed_slot; +}SlotsRCUReclaim ; + +static void rcu_reclaim_slotlist (struct rcu_head *rcu) +{ +SlotsRCUReclaim *r =container_of (rcu, SlotsRCUReclaim, rcu); +g_list_free (r->old_head); +g_free (r->removed_slot); +g_free (r); +} + +static void publish_slots (GList *new_head,GList *old_head, +MshvMemorySlot *removed_slot) +{ +MshvMemorySlotManager *manager = &mshv_state->msm; + +assert (manager); +qatomic_store_release (&manager->slots, new_head); + +SlotsRCUReclaim *r =g_new (SlotsRCUReclaim,1 ); + r->old_head = old_head; + r->removed_slot = removed_slot; + +call_rcu1 (&r->rcu, rcu_reclaim_slotlist); +} + +/* Needs to be called with mshv_state->msm.mutex held */ +static int remove_slot (MshvMemorySlot *slot) +{ +GList *old_head, *new_head; +MshvMemorySlotManager *manager = &mshv_state->msm; + +assert (manager); + old_head =qatomic_load_acquire (&manager->slots); + +if (!g_list_find (old_head, slot)) { +error_report ("slot requested for removal not found" ); +return -1 ; + } + + new_head =g_list_copy (old_head); + new_head =g_list_remove (new_head, slot); + manager->n_slots--; + +publish_slots (new_head, old_head, slot); + +return 0 ; +} + +/* Needs to be called with mshv_state->msm.mutex held */ +static MshvMemorySlot *append_slot (uint64_t gpa,uint64_t userspace_addr, +uint64_t size,bool readonly) +{ +GList *old_head, *new_head; +MshvMemorySlot *slot; +MshvMemorySlotManager *manager = &mshv_state->msm; + +assert (manager); + + old_head =qatomic_load_acquire (&manager->slots); + +if (manager->n_slots >=MSHV_MAX_MEM_SLOTS ) { +error_report ("no free memory slots available" ); +return NULL ; + } + + slot =g_new0 (MshvMemorySlot,1 ); + slot->guest_phys_addr = gpa; + slot->userspace_addr = userspace_addr; + slot->memory_size = size; + slot->readonly = readonly; + + new_head =g_list_copy (old_head); + new_head =g_list_append (new_head, slot); + manager->n_slots++; + +publish_slots (new_head, old_head,NULL ); + +return slot; +} + +static int slot_overlaps (const MshvMemorySlot *slot1, +const MshvMemorySlot *slot2) +{ +uint64_t start_1 = slot1->userspace_addr, + start_2 = slot2->userspace_addr; +size_t len_1 = slot1->memory_size, + len_2 = slot2->memory_size; + +if (slot1 == slot2) { +return -1 ; + } + +return ranges_overlap (start_1, len_1, start_2, len_2) ?0 :-1 ; +} + +static bool is_mapped (MshvMemorySlot *slot) +{ +/* Subsequent reads of mapped field see a fully-initialized slot */ +return qatomic_load_acquire (&slot->mapped); +} + +/* +* Find slot that is: +* - overlapping in userspace +* - currently mapped in the guest +* +* Needs to be called with mshv_state->msm.mutex or RCU read lock held. +*/ +static MshvMemorySlot *find_overlap_mem_slot (GList *head,MshvMemorySlot *slot) +{ +GList *found; +MshvMemorySlot *overlap_slot; + + found =g_list_find_custom (head, slot, (GCompareFunc ) slot_overlaps); + +if (!found) { +return NULL ; + } + + overlap_slot = found->data; +if (!overlap_slot || !is_mapped (overlap_slot)) { +return NULL ; + } + +return overlap_slot; +} +static int set_guest_memory (int vm_fd,const struct mshv_user_mem_region *region) {
@@ -26,38 +159,169 @@ static int set_guest_memory(int vm_fd, ret =ioctl (vm_fd,MSHV_SET_GUEST_MEMORY , region);if (ret <0 ) { -error_report ("failed to set guest memory" ); -return -errno; +error_report ("failed to set guest memory: %s" ,strerror (errno)); +return -1 ; }return 0 ; } -static int map_or_unmap (int vm_fd,const MshvMemoryRegion *mr,bool map) +static int map_or_unmap (int vm_fd,const MshvMemorySlot *slot,bool map) {struct mshv_user_mem_region region = {0 }; - region.guest_pfn = mr->guest_phys_addr >>MSHV_PAGE_SHIFT ; - region.size = mr->memory_size; - region.userspace_addr = mr->userspace_addr; + region.guest_pfn = slot->guest_phys_addr >>MSHV_PAGE_SHIFT ; + region.size = slot->memory_size; + region.userspace_addr = slot->userspace_addr;if (!map) { region.flags |= (1 <<MSHV_SET_MEM_BIT_UNMAP ); -trace_mshv_unmap_memory (mr->userspace_addr, mr->guest_phys_addr, - mr->memory_size); +trace_mshv_unmap_memory (slot->userspace_addr, slot->guest_phys_addr, + slot->memory_size);return set_guest_memory (vm_fd, ®ion); } region.flags =BIT (MSHV_SET_MEM_BIT_EXECUTABLE ); -if (!mr->readonly) { +if (!slot->readonly) { region.flags |=BIT (MSHV_SET_MEM_BIT_WRITABLE ); } -trace_mshv_map_memory (mr->userspace_addr, mr->guest_phys_addr, - mr->memory_size); +trace_mshv_map_memory (slot->userspace_addr, slot->guest_phys_addr, + slot->memory_size);return set_guest_memory (vm_fd, ®ion); } +static int slot_matches_region (const MshvMemorySlot *slot1, +const MshvMemorySlot *slot2) +{ +return (slot1->guest_phys_addr == slot2->guest_phys_addr && + slot1->userspace_addr == slot2->userspace_addr && + slot1->memory_size == slot2->memory_size) ?0 :-1 ; +} + +/* Needs to be called with mshv_state->msm.mutex held */ +static MshvMemorySlot *find_mem_slot_by_region (uint64_t gpa,uint64_t size, +uint64_t userspace_addr) +{ +MshvMemorySlot ref_slot = { + .guest_phys_addr = gpa, + .userspace_addr = userspace_addr, + .memory_size = size, + }; +GList *found; +MshvMemorySlotManager *manager = &mshv_state->msm; + +assert (manager); + found =g_list_find_custom (manager->slots, &ref_slot, + (GCompareFunc ) slot_matches_region); + +return found ? found->data :NULL ; +} + +static int slot_covers_gpa (const MshvMemorySlot *slot,uint64_t *gpa_p) +{ +uint64_t gpa_offset, gpa = *gpa_p; + + gpa_offset = gpa - slot->guest_phys_addr; +return (slot->guest_phys_addr <= gpa && gpa_offset < slot->memory_size) + ?0 :-1 ; +} + +/* Needs to be called with mshv_state->msm.mutex or RCU read lock held */ +static MshvMemorySlot *find_mem_slot_by_gpa (GList *head,uint64_t gpa) +{ +GList *found; +MshvMemorySlot *slot; + +trace_mshv_find_slot_by_gpa (gpa); + + found =g_list_find_custom (head, &gpa, (GCompareFunc ) slot_covers_gpa); +if (found) { + slot = found->data; +trace_mshv_found_slot (slot->userspace_addr, slot->guest_phys_addr, + slot->memory_size); +return slot; + } + +return NULL ; +} + +/* Needs to be called with mshv_state->msm.mutex held */ +static void set_mapped (MshvMemorySlot *slot,bool mapped) +{ +/* prior writes to mapped field becomes visible before readers see slot */ +qatomic_store_release (&slot->mapped, mapped); +} + +MshvRemapResult mshv_remap_overlap_region (int vm_fd,uint64_t gpa) +{ +MshvMemorySlot *gpa_slot, *overlap_slot; +GList *head; +int ret; +MshvMemorySlotManager *manager = &mshv_state->msm; + +/* fast path, called often by unmapped_gpa vm exit */ + WITH_RCU_READ_LOCK_GUARD() { +assert (manager); + head =qatomic_load_acquire (&manager->slots); +/* return early if no slot is found */ + gpa_slot =find_mem_slot_by_gpa (head, gpa); +if (gpa_slot ==NULL ) { +return MshvRemapNoMapping; + } + +/* return early if no overlapping slot is found */ + overlap_slot =find_overlap_mem_slot (head, gpa_slot); +if (overlap_slot ==NULL ) { +return MshvRemapNoOverlap; + } + } + +/* +* We'll modify the mapping list, so we need to upgrade to mutex and +* recheck. +*/ +assert (manager); +QEMU_LOCK_GUARD (&manager->mutex); + +/* return early if no slot is found */ + gpa_slot =find_mem_slot_by_gpa (manager->slots, gpa); +if (gpa_slot ==NULL ) { +return MshvRemapNoMapping; + } + +/* return early if no overlapping slot is found */ + overlap_slot =find_overlap_mem_slot (manager->slots, gpa_slot); +if (overlap_slot ==NULL ) { +return MshvRemapNoOverlap; + } + +/* unmap overlapping slot */ + ret =map_or_unmap (vm_fd, overlap_slot, false); +if (ret <0 ) { +error_report ("failed to unmap overlap region" ); +abort (); + } +set_mapped (overlap_slot, false); +warn_report ("mapped out userspace_addr=0x%016lx gpa=0x%010lx size=0x%lx" , + overlap_slot->userspace_addr, + overlap_slot->guest_phys_addr, + overlap_slot->memory_size); + +/* map region for gpa */ + ret =map_or_unmap (vm_fd, gpa_slot, true); +if (ret <0 ) { +error_report ("failed to map new region" ); +abort (); + } +set_mapped (gpa_slot, true); +warn_report ("mapped in userspace_addr=0x%016lx gpa=0x%010lx size=0x%lx" , + gpa_slot->userspace_addr, gpa_slot->guest_phys_addr, + gpa_slot->memory_size); + +return MshvRemapOk; +} +static int handle_unmapped_mmio_region_read (uint64_t gpa,uint64_t size,uint8_t *data) {
@@ -123,20 +387,97 @@ int mshv_guest_mem_write(uint64_t gpa, const uint8_t *data, uintptr_t size,return -1 ; } -static int set_memory (const MshvMemoryRegion *mshv_mr,bool add) +static int tracked_unmap (int vm_fd,uint64_t gpa,uint64_t size, +uint64_t userspace_addr) { -int ret =0 ; +int ret; +MshvMemorySlot *slot; +MshvMemorySlotManager *manager = &mshv_state->msm; + +assert (manager); + +QEMU_LOCK_GUARD (&manager->mutex); + + slot =find_mem_slot_by_region (gpa, size, userspace_addr); +if (!slot) { +trace_mshv_skip_unset_mem (userspace_addr, gpa, size); +/* no work to do */ +return 0 ; + } + +if (!is_mapped (slot)) { +/* remove slot, no need to unmap */ +return remove_slot (slot); + } -if (!mshv_mr) { -error_report ("Invalid mshv_mr" ); + ret =map_or_unmap (vm_fd, slot, false); +if (ret <0 ) { +error_report ("failed to unmap memory region" ); +return ret; + } +return remove_slot (slot); +} + +static int tracked_map (int vm_fd,uint64_t gpa,uint64_t size,bool readonly, +uint64_t userspace_addr) +{ +MshvMemorySlot *slot, *overlap_slot; +int ret; +MshvMemorySlotManager *manager = &mshv_state->msm; + +assert (manager); + +QEMU_LOCK_GUARD (&manager->mutex); + + slot =find_mem_slot_by_region (gpa, size, userspace_addr); +if (slot) { +error_report ("memory region already mapped at gpa=0x%lx, " +"userspace_addr=0x%lx, size=0x%lx" , + slot->guest_phys_addr, slot->userspace_addr, + slot->memory_size);return -1 ; } -trace_mshv_set_memory (add, mshv_mr->guest_phys_addr, - mshv_mr->memory_size, - mshv_mr->userspace_addr, mshv_mr->readonly, - ret); -return map_or_unmap (mshv_state->vm, mshv_mr, add); + slot =append_slot (gpa, userspace_addr, size, readonly); + + overlap_slot =find_overlap_mem_slot (manager->slots, slot); +if (overlap_slot) { +trace_mshv_remap_attempt (slot->userspace_addr, + slot->guest_phys_addr, + slot->memory_size); +warn_report ("attempt to map region [0x%lx-0x%lx], while " +"[0x%lx-0x%lx] is already mapped in the guest" , + userspace_addr, userspace_addr + size -1 , + overlap_slot->userspace_addr, + overlap_slot->userspace_addr + + overlap_slot->memory_size -1 ); + +/* do not register mem slot in hv, but record for later swap-in */ +set_mapped (slot, false); + +return 0 ; + } + + ret =map_or_unmap (vm_fd, slot, true); +if (ret <0 ) { +error_report ("failed to map memory region" ); +return -1 ; + } +set_mapped (slot, true); + +return 0 ; +} + +static int set_memory (uint64_t gpa,uint64_t size,bool readonly, +uint64_t userspace_addr,bool add) +{ +int vm_fd = mshv_state->vm; + +if (add) { +return tracked_map (vm_fd, gpa, size, readonly, userspace_addr); + } + +return tracked_unmap (vm_fd, gpa, size, userspace_addr); }/*
@@ -172,7 +513,9 @@ void mshv_set_phys_mem(MshvMemoryListener *mml, MemoryRegionSection *section,bool writable = !area->readonly && !area->rom_device;hwaddr start_addr, mr_offset, size;void *ram; -MshvMemoryRegion mshv_mr = {0 }; + + size =align_section (section, &start_addr); +trace_mshv_set_phys_mem (add, section->mr->name, start_addr); size =align_section (section, &start_addr);trace_mshv_set_phys_mem (add, section->mr->name, start_addr);
@@ -199,14 +542,21 @@ void mshv_set_phys_mem(MshvMemoryListener *mml, MemoryRegionSection *section, ram =memory_region_get_ram_ptr (area) + mr_offset; - mshv_mr.guest_phys_addr = start_addr; - mshv_mr.memory_size = size; - mshv_mr.readonly = !writable; - mshv_mr.userspace_addr = (uint64_t )ram; - - ret =set_memory (&mshv_mr, add); + ret =set_memory (start_addr, size, !writable, (uint64_t )ram, add);if (ret <0 ) { -error_report ("Failed to set memory region" ); +error_report ("failed to set memory region" );abort (); } } + +void mshv_init_memory_slot_manager (MshvState *mshv_state) +{ +MshvMemorySlotManager *manager; + +assert (mshv_state); + manager = &mshv_state->msm; + + manager->n_slots =0 ; + manager->slots =NULL ; +qemu_mutex_init (&manager->mutex); +}
accel/mshv/mshv-all.c +2 -0
@@ -436,6 +436,8 @@ static int mshv_init(AccelState *as, MachineState *ms)mshv_init_msicontrol (); +mshv_init_memory_slot_manager (s); + ret =create_vm (mshv_fd, &vm_fd);if (ret <0 ) {close (mshv_fd);
accel/mshv/trace-events +5 -0
@@ -26,3 +26,8 @@ mshv_map_memory(uint64_t userspace_addr, uint64_t gpa, uint64_t size) "\tu_a=0x% mshv_unmap_memory(uint64_t userspace_addr, uint64_t gpa, uint64_t size) "\tu_a=0x%lx gpa=0x%010lx size=0x%08lx" mshv_set_phys_mem(bool add, const char *name, uint64_t gpa) "\tadd=%d name=%s gpa=0x%010lx" mshv_handle_mmio(uint64_t gva, uint64_t gpa, uint64_t size, uint8_t access_type) "\tgva=0x%lx gpa=0x%010lx size=0x%lx access_type=%d" + +mshv_found_slot(uint64_t userspace_addr, uint64_t gpa, uint64_t size) "\tu_a=0x%lx gpa=0x%010lx size=0x%08lx" +mshv_skip_unset_mem(uint64_t userspace_addr, uint64_t gpa, uint64_t size) "\tu_a=0x%lx gpa=0x%010lx size=0x%08lx" +mshv_remap_attempt(uint64_t userspace_addr, uint64_t gpa, uint64_t size) "\tu_a=0x%lx gpa=0x%010lx size=0x%08lx" +mshv_find_slot_by_gpa(uint64_t gpa) "\tgpa=0x%010lx"
include/system/mshv.h +20 -4
@@ -40,6 +40,8 @@ typedef struct hyperv_message hv_message;#define MSHV_MSR_ENTRIES_COUNT 64 +#define MSHV_MAX_MEM_SLOTS 32 +#ifdef CONFIG_MSHV_IS_POSSIBLE extern bool mshv_allowed;#define mshv_enabled () (mshv_allowed)
@@ -54,6 +56,12 @@ typedef struct MshvAddressSpace {AddressSpace *as; } MshvAddressSpace; +typedef struct MshvMemorySlotManager { +size_t n_slots; +GList *slots; +QemuMutex mutex; +}MshvMemorySlotManager ; + typedef struct MshvState { AccelState parent_obj; int vm;
@@ -62,6 +70,7 @@ typedef struct MshvState {int nr_as;MshvAddressSpace *as;int fd; +MshvMemorySlotManager msm; } MshvState;extern MshvState *mshv_state;
@@ -103,6 +112,12 @@ typedef enum MshvVmExit { MshvVmExitSpecial =2 , } MshvVmExit; +typedef enum MshvRemapResult { + MshvRemapOk =0 , + MshvRemapNoMapping =1 , + MshvRemapNoOverlap =2 , +}MshvRemapResult ; +void mshv_init_mmio_emu (void );int mshv_create_vcpu (int vm_fd,uint8_t vp_index,int *cpu_fd);void mshv_remove_vcpu (int vm_fd,int cpu_fd);
@@ -139,21 +154,22 @@ int mshv_configure_msr(const CPUState *cpu, const MshvMsrEntry *msrs, size_t n_msrs);/* memory */ -typedef struct MshvMemoryRegion { +typedef struct MshvMemorySlot {uint64_t guest_phys_addr;uint64_t memory_size;uint64_t userspace_addr;bool readonly; -}MshvMemoryRegion ; +bool mapped; +}MshvMemorySlot ; -int mshv_add_mem (int vm_fd,const MshvMemoryRegion *mr); -int mshv_remove_mem (int vm_fd,const MshvMemoryRegion *mr); +MshvRemapResult mshv_remap_overlap_region (int vm_fd,uint64_t gpa);int mshv_guest_mem_read (uint64_t gpa,uint8_t *data,uintptr_t size,bool is_secure_mode,bool instruction_fetch);int mshv_guest_mem_write (uint64_t gpa,const uint8_t *data,uintptr_t size,bool is_secure_mode);void mshv_set_phys_mem (MshvMemoryListener *mml,MemoryRegionSection *section,bool add); +void mshv_init_memory_slot_manager (MshvState *mshv_state);/* interrupt */ void mshv_init_msicontrol (void );
target/i386/mshv/mshv-cpu.c +43 -0
55 lines not on this page · raw message
Signature · 1 line
2.34.1
PATCH v4 24/27 qapi/accel: Allow to query mshv capabilities
In reply to Magnus KulkeFrom: Praveen K Paladugu <[email protected]>
Allow to query mshv capabilities via query-mshv QMP and info mshv HMP commands.
--- hmp-commands-info.hx | 13 +++++++++++++ hw/core/machine-hmp-cmds.c | 15 +++++++++++++++ hw/core/machine-qmp-cmds.c | 14 ++++++++++++++ include/monitor/hmp.h | 1 + include/system/hw_accel.h | 1 + qapi/accelerator.json | 29 +++++++++++++++++++++++++++++ 6 files changed, 73 insertions(+)
hmp-commands-info.hx +13 -0
@@ -307,6 +307,19 @@ SRST Show KVM information. ERST + { + .name = "mshv", + .args_type = "", + .params = "", + .help = "show MSHV information", + .cmd = hmp_info_mshv, + }, + +SRST + ``info mshv`` + Show MSHV information. +ERST + { .name = "numa", .args_type = "",
hw/core/machine-hmp-cmds.c +15 -0
@@ -163,6 +163,21 @@ void hmp_info_kvm(Monitor *mon, const QDict *qdict)qapi_free_KvmInfo (info); } +void hmp_info_mshv (Monitor *mon,const QDict *qdict) +{ +MshvInfo *info; + + info =qmp_query_mshv (NULL ); +monitor_printf (mon,"mshv support: " ); +if (info->present) { +monitor_printf (mon,"%s\n" , info->enabled ?"enabled" :"disabled" ); + }else { +monitor_printf (mon,"not compiled\n" ); + } + +qapi_free_MshvInfo (info); +} +void hmp_info_uuid (Monitor *mon,const QDict *qdict) {UuidInfo *info;
hw/core/machine-qmp-cmds.c +14 -0
@@ -28,6 +28,20 @@#include "system/runstate.h" #include "system/system.h" #include "hw/s390x/storage-keys.h" +#include <sys/stat.h> + +/* +* QMP query for MSHV +*/ +MshvInfo *qmp_query_mshv (Error **errp) +{ +MshvInfo *info =g_malloc0 (sizeof (*info)); + + info->enabled =mshv_enabled (); + info->present =accel_find ("mshv" ); + +return info; +}/* * fast means: we NEVER interrupt vCPU threads to retrieve
include/monitor/hmp.h +1 -0
@@ -24,6 +24,7 @@ strList *hmp_split_at_comma(const char *str);void hmp_info_name (Monitor *mon,const QDict *qdict);void hmp_info_version (Monitor *mon,const QDict *qdict);void hmp_info_kvm (Monitor *mon,const QDict *qdict); +void hmp_info_mshv (Monitor *mon,const QDict *qdict);void hmp_info_status (Monitor *mon,const QDict *qdict);void hmp_info_uuid (Monitor *mon,const QDict *qdict);void hmp_info_chardev (Monitor *mon,const QDict *qdict);
include/system/hw_accel.h +1 -0
@@ -14,6 +14,7 @@#include "hw/core/cpu.h" #include "system/kvm.h" #include "system/hvf.h" +#include "system/mshv.h" #include "system/whpx.h" #include "system/nvmm.h"
qapi/accelerator.json +29 -0
@@ -54,3 +54,32 @@ { 'command': 'x-accel-stats', 'returns': 'HumanReadableText', 'features': [ 'unstable' ] } + +## +# @MshvInfo: +# +# Information about support for MSHV acceleration +# +# @enabled: true if MSHV acceleration is active +# +# @present: true if MSHV acceleration is built into this executable +# +# Since: 10.0.92 +## +{ 'struct': 'MshvInfo', 'data': {'enabled': 'bool', 'present': 'bool'} } + +## +# @query-mshv: +# +# Return information about MSHV acceleration +# +# Returns: @MshvInfo +# +# Since: 10.0.92 +# +# .. qmp-example:: +# +# -> { "execute": "query-mshv" } +# <- { "return": { "enabled": true, "present": true } } +## +{ 'command': 'query-mshv', 'returns': 'MshvInfo' }
Signature · 1 line
2.34.1
Re: [PATCH v4 24/27] qapi/accel: Allow to query mshv capabilities
Quoted 51 lines · * Magnus Kulke ([email protected]) wrote:
From: Praveen K Paladugu <[email protected]>
Allow to query mshv capabilities via query-mshv QMP and info mshv HMP commands.
Signed-off-by Magnus Kulke <[email protected]>--- hmp-commands-info.hx | 13 +++++++++++++ hw/core/machine-hmp-cmds.c | 15 +++++++++++++++ hw/core/machine-qmp-cmds.c | 14 ++++++++++++++ include/monitor/hmp.h | 1 + include/system/hw_accel.h | 1 + qapi/accelerator.json | 29 +++++++++++++++++++++++++++++ 6 files changed, 73 insertions(+)hmp-commands-info.hx +13
-0@@ -307,6 +307,19 @@ SRST Show KVM information. ERST + { + .name = "mshv", + .args_type = "", + .params = "", + .help = "show MSHV information", + .cmd = hmp_info_mshv, + }, + +SRST + ``info mshv`` + Show MSHV information. +ERST + { .name = "numa", .args_type = "",hw/core/machine-hmp-cmds.c +5
-0@@ -163,6 +163,21 @@ void hmp_info_kvm(Monitor *mon, const QDict *qdict)qapi_free_KvmInfo (info); } +void hmp_info_mshv (Monitor *mon,const QDict *qdict) +{ +MshvInfo *info; + + info =qmp_query_mshv (NULL );
hw/core/machine-hmp-cmds.c void hmp_info_kvm(Monitor *mon, const QDict *qdict) · line 180
Quoted 10 lines
hw/core/machine-hmp-cmds.c +10
-0+monitor_printf (mon,"mshv support: " ); +if (info->present) { +monitor_printf (mon,"%s\n" , info->enabled ?"enabled" :"disabled" ); + }else { +monitor_printf (mon,"not compiled\n" ); + } + +qapi_free_MshvInfo (info); +} +
Looks the same as info kvm, so just for HMP
Quoted 92 lines
hw/core/machine-hmp-cmds.c +0
-0void hmp_info_uuid (Monitor *mon,const QDict *qdict) {UuidInfo *info;hw/core/machine-qmp-cmds.c +14
-0@@ -28,6 +28,20 @@#include "system/runstate.h" #include "system/system.h" #include "hw/s390x/storage-keys.h" +#include <sys/stat.h> + +/* +* QMP query for MSHV +*/ +MshvInfo *qmp_query_mshv (Error **errp) +{ +MshvInfo *info =g_malloc0 (sizeof (*info)); + + info->enabled =mshv_enabled (); + info->present =accel_find ("mshv" ); + +return info; +}/* * fast means: we NEVER interrupt vCPU threads to retrieve include/monitor/hmp.h +1
-0@@ -24,6 +24,7 @@ strList *hmp_split_at_comma(const char *str);void hmp_info_name (Monitor *mon,const QDict *qdict);void hmp_info_version (Monitor *mon,const QDict *qdict);void hmp_info_kvm (Monitor *mon,const QDict *qdict); +void hmp_info_mshv (Monitor *mon,const QDict *qdict);void hmp_info_status (Monitor *mon,const QDict *qdict);void hmp_info_uuid (Monitor *mon,const QDict *qdict);void hmp_info_chardev (Monitor *mon,const QDict *qdict);include/system/hw_accel.h +1
-0@@ -14,6 +14,7 @@#include "hw/core/cpu.h" #include "system/kvm.h" #include "system/hvf.h" +#include "system/mshv.h" #include "system/whpx.h" #include "system/nvmm.h" qapi/accelerator.json +29
-0@@ -54,3 +54,32 @@ { 'command': 'x-accel-stats', 'returns': 'HumanReadableText', 'features': [ 'unstable' ] } + +## +# @MshvInfo: +# +# Information about support for MSHV acceleration +# +# @enabled: true if MSHV acceleration is active +# +# @present: true if MSHV acceleration is built into this executable +# +# Since: 10.0.92 +## +{ 'struct': 'MshvInfo', 'data': {'enabled': 'bool', 'present': 'bool'} } + +## +# @query-mshv: +# +# Return information about MSHV acceleration +# +# Returns: @MshvInfo +# +# Since: 10.0.92 +# +# .. qmp-example:: +# +# -> { "execute": "query-mshv" } +# <- { "return": { "enabled": true, "present": true } } +## +{ 'command': 'query-mshv', 'returns': 'MshvInfo' }Signature · 1 line
2.34.1
Signature · 4 lines
-----Open up your eyes, open up your mind, open up your code ------- / Dr. David Alan Gilbert | Running GNU/Linux | Happy \ \ dave @ treblig.org | | In Hex / \ _________________________|_____ http://www.treblig.org |_______/
Re: [PATCH v4 24/27] qapi/accel: Allow to query mshv capabilities
In reply to Magnus KulkeQuoted 23 lines · Magnus Kulke
From: Praveen K Paladugu <[email protected]>
Allow to query mshv capabilities via query-mshv QMP and info mshv HMP commands.
Signed-off-by Magnus Kulke <[email protected]>--- hmp-commands-info.hx | 13 +++++++++++++ hw/core/machine-hmp-cmds.c | 15 +++++++++++++++ hw/core/machine-qmp-cmds.c | 14 ++++++++++++++ include/monitor/hmp.h | 1 + include/system/hw_accel.h | 1 + qapi/accelerator.json | 29 +++++++++++++++++++++++++++++ 6 files changed, 73 insertions(+)qapi/accelerator.json +1
-0@@ -54,3 +54,32 @@ { 'command': 'x-accel-stats', 'returns': 'HumanReadableText', 'features': [ 'unstable' ] } +
qapi/accelerator.json line 67
Quoted 10 lines
qapi/accelerator.json +10
-0+## +# @MshvInfo: +# +# Information about support for MSHV acceleration +# +# @enabled: true if MSHV acceleration is active +# +# @present: true if MSHV acceleration is built into this executable +# +# Since: 10.0.92
FYI, any time the last "miro" component is 50, it indicates a development stream, and 90 onwards indicates a release candidate.
QAPI schema 'Since" tags shouldn't ever used those numbers, instead when proposing patches, use the forthcoming GA release version which will be a .0 in the micro component.
QEMU does three releases a year, and bumps the major version component at the start of each year, and minor component for each release. The micro component is always 0 for the first release, and then stable branches bump micro.
We've just had 10.1.0, so the next release will be 10.2.0 and then after that next year we'll be going to 11.0.0,
IOW for your patches, this should now be using 10.2.0 as that's the next release available for merging
Quoted 21 lines
qapi/accelerator.json +18
-0+## +{ 'struct': 'MshvInfo', 'data': {'enabled': 'bool', 'present': 'bool'} } + +## +# @query-mshv: +# +# Return information about MSHV acceleration +# +# Returns: @MshvInfo +# +# Since: 10.0.92 +# +# .. qmp-example:: +# +# -> { "execute": "query-mshv" } +# <- { "return": { "enabled": true, "present": true } } +## +{ 'command': 'query-mshv', 'returns': 'MshvInfo' }Signature · 1 line
2.34.1
With regards,
Daniel
Signature · 3 lines
|: https://berrange.com -o- https://www.flickr.com/photos/dberrange :| |: https://libvirt.org -o- https://fstop138.berrange.com :| |: https://entangle-photo.org -o- https://www.instagram.com/dberrange :|
Re: [PATCH v4 24/27] qapi/accel: Allow to query mshv capabilities
In reply to Magnus KulkeQuoted 20 lines · Magnus Kulke
From: Praveen K Paladugu <[email protected]>
Allow to query mshv capabilities via query-mshv QMP and info mshv HMP commands.
Signed-off-by Magnus Kulke <[email protected]>--- hmp-commands-info.hx | 13 +++++++++++++ hw/core/machine-hmp-cmds.c | 15 +++++++++++++++ hw/core/machine-qmp-cmds.c | 14 ++++++++++++++ include/monitor/hmp.h | 1 + include/system/hw_accel.h | 1 + qapi/accelerator.json | 29 +++++++++++++++++++++++++++++ 6 files changed, 73 insertions(+)hw/core/machine-qmp-cmds.c +0
-0
hw/core/machine-qmp-cmds.c line 31
Quoted 4 lines
hw/core/machine-qmp-cmds.c +1
-0@@ -28,6 +28,20 @@#include "system/runstate.h" #include "system/system.h" #include "hw/s390x/storage-keys.h" +#include <sys/stat.h>
I think this is left over from a previous version of the patch that directly called stat() on the device node, and can be removed.
Quoted 6 lines
hw/core/machine-qmp-cmds.c +6
-0+ +/* +* QMP query for MSHV +*/ +MshvInfo *qmp_query_mshv (Error **errp) +{
hw/core/machine-qmp-cmds.c line 47
Quoted 10 lines
hw/core/machine-qmp-cmds.c +7
-0+MshvInfo *info =g_malloc0 (sizeof (*info)); + + info->enabled =mshv_enabled (); + info->present =accel_find ("mshv" ); + +return info; +}/* * fast means: we NEVER interrupt vCPU threads to retrieve
With regards,
Daniel
Signature · 3 lines
|: https://berrange.com -o- https://www.flickr.com/photos/dberrange :| |: https://libvirt.org -o- https://fstop138.berrange.com :| |: https://entangle-photo.org -o- https://www.instagram.com/dberrange :|
Re: [PATCH v4 24/27] qapi/accel: Allow to query mshv capabilities
In reply to Magnus KulkeQuoted 25 lines · Magnus Kulke
From: Praveen K Paladugu <[email protected]>
Allow to query mshv capabilities via query-mshv QMP and info mshv HMP commands.
Signed-off-by Magnus Kulke <[email protected]>--- hmp-commands-info.hx | 13 +++++++++++++ hw/core/machine-hmp-cmds.c | 15 +++++++++++++++ hw/core/machine-qmp-cmds.c | 14 ++++++++++++++ include/monitor/hmp.h | 1 + include/system/hw_accel.h | 1 + qapi/accelerator.json | 29 +++++++++++++++++++++++++++++ 6 files changed, 73 insertions(+)hmp-commands-info.hx +3
-0@@ -307,6 +307,19 @@ SRST Show KVM information. ERST + { + .name = "mshv", + .args_type = "",
hmp-commands-info.hx SRST · line 322
Quoted 10 lines
hmp-commands-info.hx +10
-0+ .params = "", + .help = "show MSHV information", + .cmd = hmp_info_mshv, + }, + +SRST + ``info mshv`` + Show MSHV information. +ERST +
Mirrors the entry for "kvm".
Quoted 16 lines
hmp-commands-info.hx +0
-0{ .name = "numa", .args_type = "",hw/core/machine-hmp-cmds.c +5
-0@@ -163,6 +163,21 @@ void hmp_info_kvm(Monitor *mon, const QDict *qdict)qapi_free_KvmInfo (info); } +void hmp_info_mshv (Monitor *mon,const QDict *qdict) +{ +MshvInfo *info; + + info =qmp_query_mshv (NULL );
hw/core/machine-hmp-cmds.c void hmp_info_kvm(Monitor *mon, const QDict *qdict) · line 180
Quoted 10 lines
hw/core/machine-hmp-cmds.c +10
-0+monitor_printf (mon,"mshv support: " ); +if (info->present) { +monitor_printf (mon,"%s\n" , info->enabled ?"enabled" :"disabled" ); + }else { +monitor_printf (mon,"not compiled\n" ); + } + +qapi_free_MshvInfo (info); +} +
Mirrors hmp_info_kvm().
Quoted 15 lines
hw/core/machine-hmp-cmds.c +0
-0void hmp_info_uuid (Monitor *mon,const QDict *qdict) {UuidInfo *info;hw/core/machine-qmp-cmds.c +4
-0@@ -28,6 +28,20 @@#include "system/runstate.h" #include "system/system.h" #include "hw/s390x/storage-keys.h" +#include <sys/stat.h> + +/* +* QMP query for MSHV
hw/core/machine-qmp-cmds.c line 44
Quoted 10 lines
hw/core/machine-qmp-cmds.c +10
-0+*/ +MshvInfo *qmp_query_mshv (Error **errp) +{ +MshvInfo *info =g_malloc0 (sizeof (*info)); + + info->enabled =mshv_enabled (); + info->present =accel_find ("mshv" ); + +return info; +}
Mirrors qmp_query_kvm().
Note that accel_find() works for any accelerator. It returns the AccelClass. As far as I can tell, AccelClass member @allowed points to the variable _enabled() returns. So, this function could be made generic. More on that below.
Quoted 20 lines
hw/core/machine-qmp-cmds.c +0
-0/* * fast means: we NEVER interrupt vCPU threads to retrieve include/monitor/hmp.h +1
-0@@ -24,6 +24,7 @@ strList *hmp_split_at_comma(const char *str);void hmp_info_name (Monitor *mon,const QDict *qdict);void hmp_info_version (Monitor *mon,const QDict *qdict);void hmp_info_kvm (Monitor *mon,const QDict *qdict); +void hmp_info_mshv (Monitor *mon,const QDict *qdict);void hmp_info_status (Monitor *mon,const QDict *qdict);void hmp_info_uuid (Monitor *mon,const QDict *qdict);void hmp_info_chardev (Monitor *mon,const QDict *qdict);include/system/hw_accel.h +0
-0
include/system/hw_accel.h line 17
Quoted 4 lines
include/system/hw_accel.h +1
-0@@ -14,6 +14,7 @@#include "hw/core/cpu.h" #include "system/kvm.h" #include "system/hvf.h" +#include "system/mshv.h"
Why?
Quoted 30 lines
include/system/hw_accel.h +0
-0#include "system/whpx.h" #include "system/nvmm.h" qapi/accelerator.json +19
-0@@ -54,3 +54,32 @@ { 'command': 'x-accel-stats', 'returns': 'HumanReadableText', 'features': [ 'unstable' ] } + +## +# @MshvInfo: +# +# Information about support for MSHV acceleration +# +# @enabled: true if MSHV acceleration is active +# +# @present: true if MSHV acceleration is built into this executable +# +# Since: 10.0.92 +## +{ 'struct': 'MshvInfo', 'data': {'enabled': 'bool', 'present': 'bool'} } + +## +# @query-mshv: +# +# Return information about MSHV acceleration +#
qapi/accelerator.json line 85
Quoted 10 lines
qapi/accelerator.json +10
-0+# Returns: @MshvInfo +# +# Since: 10.0.92 +# +# .. qmp-example:: +# +# -> { "execute": "query-mshv" } +# <- { "return": { "enabled": true, "present": true } } +## +{ 'command': 'query-mshv', 'returns': 'MshvInfo' }
Mirrors query-kvm. Okay apart from the Since: issues Daniel pointed out.
Should we have a generic query-accelerator instead of one query-FOO for every accelerator FOO?
Re: [PATCH v4 24/27] qapi/accel: Allow to query mshv capabilities
Quoted 4 lines · Markus Armbruster
Quoted 1 line
+{ 'command': 'query-mshv', 'returns': 'MshvInfo' }
Mirrors query-kvm. Okay apart from the Since: issues Daniel pointed out.
Which I swore I had fixed, but didn't.
Quoted 2 lines
Should we have a generic query-accelerator instead of one query-FOO for every accelerator FOO?
If we want it, it should be query-accelerators with return value {"enabled": "Accelerator", "present": ["Accelerator"]}.
The patch is already merged, but it is pretty self-contained so I have no objection to reverting just this one.
Paolo
A message that is not in the archive (sent off-list or not yet received): [email protected]
Re: [PATCH v4 24/27] qapi/accel: Allow to query mshv capabilities
Quoted 18 lines · Wei Liu
Quoted 8 lines · Paolo Bonzini
Quoted 4 lines · Markus Armbruster
Quoted 1 line
+{ 'command': 'query-mshv', 'returns': 'MshvInfo' }
Mirrors query-kvm. Okay apart from the Since: issues Daniel pointed out.
Which I swore I had fixed, but didn't.
Quoted 8 lines
Quoted 2 lines
Should we have a generic query-accelerator instead of one query-FOO for every accelerator FOO?
If we want it, it should be query-accelerators with return value {"enabled":
"Accelerator", "present": ["Accelerator"]}.The patch is already merged, but it is pretty self-contained so I have no objection to reverting just this one.
Quoted 6 lines
Using a generic query-accelerator API should be fine.
As I understand it, We need this to query MSHV support in libvirt, so we need to get this correct before the libvirt patches are merged.
Just let us know how to proceed.
On the libvirt side, we're happy to deal with either query-mshv/kvm/etc or a generator query-accelerator.
With regards,
Daniel
Signature · 3 lines
|: https://berrange.com -o- https://www.flickr.com/photos/dberrange :| |: https://libvirt.org -o- https://fstop138.berrange.com :| |: https://entangle-photo.org -o- https://www.instagram.com/dberrange :|
PATCH v4 25/27 target/i386/mshv: Use preallocated page for hvcall
In reply to Magnus KulkeThere are hvcalls that are invoked during MMIO exits, the payload is of dynamic size. To avoid heap allocations we can use preallocated pages as in/out buffer for those calls. A page is reserved per vCPU and used for set/get register hv calls.
--- accel/mshv/mshv-all.c | 2 +- include/system/mshv.h | 7 +++++++ target/i386/mshv/mshv-cpu.c | 39 +++++++++++++++++++++++++------------ 3 files changed, 35 insertions(+), 13 deletions(-)
accel/mshv/mshv-all.c +1 -1
@@ -398,8 +398,8 @@ static int mshv_init_vcpu(CPUState *cpu)uint8_t vp_index = cpu->cpu_index;int ret; -mshv_arch_init_vcpu (cpu); cpu->accel =g_new0 (AccelCPUState,1 ); +mshv_arch_init_vcpu (cpu); ret =mshv_create_vcpu (vm_fd, vp_index, &cpu->accel->cpufd);if (ret <0 ) {
include/system/mshv.h +7 -0
@@ -74,9 +74,16 @@ typedef struct MshvState { } MshvState;extern MshvState *mshv_state; +typedef struct MshvHvCallArgs { +void *base; +void *input_page; +void *output_page; +}MshvHvCallArgs ; +struct AccelCPUState {int cpufd;bool dirty; +MshvHvCallArgs hvcall_args; }; typedef struct MshvMsiControl {
target/i386/mshv/mshv-cpu.c +27 -12
@@ -33,6 +33,11 @@#include <sys/ioctl.h> +#define MAX_SIZE (a, b) ((a) > (b) ? (a) : (b)) +#define MAX_REGISTER_COUNT (MAX_SIZE(ARRAY_SIZE(STANDARD_REGISTER_NAMES), \ + MAX_SIZE(ARRAY_SIZE(SPECIAL_REGISTER_NAMES), \ + ARRAY_SIZE(FPU_REGISTER_NAMES)))) +static enum hv_register_name STANDARD_REGISTER_NAMES [18 ] = {HV_X64_REGISTER_RAX ,HV_X64_REGISTER_RBX ,
@@ -150,7 +155,7 @@ int mshv_set_generic_regs(const CPUState *cpu, const hv_register_assoc *assocs,int cpu_fd =mshv_vcpufd (cpu);int vp_index = cpu->cpu_index;size_t in_sz, assocs_sz; -hv_input_set_vp_registers *in; +hv_input_set_vp_registers *in = cpu->accel->hvcall_args.input_page;struct mshv_root_hvcall args = {0 };int ret;
@@ -159,7 +164,7 @@ int mshv_set_generic_regs(const CPUState *cpu, const hv_register_assoc *assocs, in_sz =sizeof (hv_input_set_vp_registers) + assocs_sz;/* fill the input struct */ - in =g_malloc0 (in_sz); +memset (in,0 ,sizeof (hv_input_set_vp_registers)); in->vp_index = vp_index;memcpy (in->elements, assocs, assocs_sz);
@@ -171,7 +176,6 @@ int mshv_set_generic_regs(const CPUState *cpu, const hv_register_assoc *assocs,/* perform the call */ ret =mshv_hvcall (cpu_fd, &args); -g_free (in);if (ret <0 ) {error_report ("Failed to set registers" );return -1 ;
@@ -192,8 +196,8 @@ static int get_generic_regs(CPUState *cpu, hv_register_assoc *assocs, {int cpu_fd =mshv_vcpufd (cpu);int vp_index = cpu->cpu_index; -hv_input_get_vp_registers *in; -hv_register_value *values; +hv_input_get_vp_registers *in = cpu->accel->hvcall_args.input_page; +hv_register_value *values = cpu->accel->hvcall_args.output_page;size_t in_sz, names_sz, values_sz;int i, ret;struct mshv_root_hvcall args = {0 };
@@ -203,15 +207,14 @@ static int get_generic_regs(CPUState *cpu, hv_register_assoc *assocs, in_sz =sizeof (hv_input_get_vp_registers) + names_sz;/* fill the input struct */ - in =g_malloc0 (in_sz); +memset (in,0 ,sizeof (hv_input_get_vp_registers)); in->vp_index = vp_index;for (i =0 ; i < n_regs; i++) { in->names[i] = assocs[i].name; } -/* allocate value output buffer */ +/* determine size of value output buffer */ values_sz = n_regs *sizeof (union hv_register_value ); - values =g_malloc0 (values_sz);/* create the hvcall envelope */ args.code =HVCALL_GET_VP_REGISTERS ;
@@ -223,16 +226,13 @@ static int get_generic_regs(CPUState *cpu, hv_register_assoc *assocs,/* perform the call */ ret =mshv_hvcall (cpu_fd, &args); -g_free (in);if (ret <0 ) { -g_free (values);error_report ("Failed to retrieve registers" );return -1 ; }/* assert we got all registers */ if (args.reps != n_regs) { -g_free (values);error_report ("Failed to retrieve registers: expected %zu elements" ", got %u" , n_regs, args.reps);return -1 ;
@@ -242,7 +242,6 @@ static int get_generic_regs(CPUState *cpu, hv_register_assoc *assocs,for (i =0 ; i < n_regs; i++) { assocs[i].value = values[i]; } -g_free (values);return 0 ; }
@@ -1695,6 +1694,19 @@ void mshv_arch_init_vcpu(CPUState *cpu) {X86CPU *x86_cpu =X86_CPU (cpu);CPUX86State *env = &x86_cpu->env; +AccelCPUState *state = cpu->accel; +size_t page =HV_HYP_PAGE_SIZE ; +void *mem =qemu_memalign (page,2 * page); + +/* sanity check, to make sure we don't overflow the page */ +QEMU_BUILD_BUG_ON ((MAX_REGISTER_COUNT + *sizeof (hv_register_assoc) + +sizeof (hv_input_get_vp_registers) + >HV_HYP_PAGE_SIZE )); + + state->hvcall_args.base = mem; + state->hvcall_args.input_page = mem; + state->hvcall_args.output_page = (uint8_t *)mem + page; env->emu_mmio_buf =g_new (char,4096 ); }
@@ -1703,7 +1715,10 @@ void mshv_arch_destroy_vcpu(CPUState *cpu) {X86CPU *x86_cpu =X86_CPU (cpu);CPUX86State *env = &x86_cpu->env; +AccelCPUState *state = cpu->accel; +g_free (state->hvcall_args.base); + state->hvcall_args = (MshvHvCallArgs ){0 };g_free (env->emu_mmio_buf); env->emu_mmio_buf =NULL ; }
Signature · 1 line
2.34.1
Re: [PATCH v4 25/27] target/i386/mshv: Use preallocated page for hvcall
Quoted 17 lines · Magnus Kulke
There are hvcalls that are invoked during MMIO exits, the payload is of dynamic size. To avoid heap allocations we can use preallocated pages as in/out buffer for those calls. A page is reserved per vCPU and used for set/get register hv calls.
Signed-off-by Magnus Kulke <[email protected]>--- accel/mshv/mshv-all.c | 2 +- include/system/mshv.h | 7 +++++++ target/i386/mshv/mshv-cpu.c | 39 +++++++++++++++++++++++++------------ 3 files changed, 35 insertions(+), 13 deletions(-)accel/mshv/mshv-all.c +0
-0
accel/mshv/mshv-all.c static int mshv_init_vcpu(CPUState *cpu) · line 402
Quoted 6 lines
accel/mshv/mshv-all.c +1
-1@@ -398,8 +398,8 @@ static int mshv_init_vcpu(CPUState *cpu)uint8_t vp_index = cpu->cpu_index;int ret; -mshv_arch_init_vcpu (cpu); cpu->accel =g_new0 (AccelCPUState,1 ); +mshv_arch_init_vcpu (cpu);
This change can either be dropped, or squashed into the earlier patch in this series that introduced this method.
target/i386/mshv/mshv-cpu.c line 36
Quoted 13 lines
accel/mshv/mshv-all.c +0
-0ret =mshv_create_vcpu (vm_fd, vp_index, &cpu->accel->cpufd);if (ret <0 ) {target/i386/mshv/mshv-cpu.c +1
-0@@ -33,6 +33,11 @@#include <sys/ioctl.h> +#define MAX_SIZE (a, b) ((a) > (b) ? (a) : (b))
Isn't this the same as the existing 'MAX(a, b)' macro in osdep.h ?
target/i386/mshv/mshv-cpu.c line 40
Quoted 4 lines
target/i386/mshv/mshv-cpu.c +4
-0+#define MAX_REGISTER_COUNT (MAX_SIZE(ARRAY_SIZE(STANDARD_REGISTER_NAMES), \ + MAX_SIZE(ARRAY_SIZE(SPECIAL_REGISTER_NAMES), \ + ARRAY_SIZE(FPU_REGISTER_NAMES)))) +
With regards,
Daniel
Signature · 3 lines
|: https://berrange.com -o- https://www.flickr.com/photos/dberrange :| |: https://libvirt.org -o- https://fstop138.berrange.com :| |: https://entangle-photo.org -o- https://www.instagram.com/dberrange :|
Re: [PATCH v4 25/27] target/i386/mshv: Use preallocated page for hvcall
Quoted 8 lines · Daniel P. Berrangé
accel/mshv/mshv-all.c static int mshv_init_vcpu(CPUState *cpu) · line 402
Quoted 3 lines · Magnus Kulke
accel/mshv/mshv-all.c +1
-1-mshv_arch_init_vcpu (cpu); cpu->accel =g_new0 (AccelCPUState,1 ); +mshv_arch_init_vcpu (cpu);This change can either be dropped, or squashed into the earlier patch in this series that introduced this method.
right, this makes sense.
Quoted 4 lines
Quoted 1 line
+#define
MAX_SIZE(a, b)((a) > (b) ? (a) : (b))Isn't this the same as the existing '
MAX(a, b)' macro inosdep.h?
not quite, I don't think MAX can be used in a static assertion, but there's a MAX_CONST sibling that we can use.
Re: [PATCH v4 25/27] target/i386/mshv: Use preallocated page for hvcall
Quoted 12 lines · Magnus Kulke
Quoted 8 lines · Daniel P. Berrangé
accel/mshv/mshv-all.c static int mshv_init_vcpu(CPUState *cpu) · line 402
Quoted 3 lines · Magnus Kulke
accel/mshv/mshv-all.c +1
-1-mshv_arch_init_vcpu (cpu); cpu->accel =g_new0 (AccelCPUState,1 ); +mshv_arch_init_vcpu (cpu);This change can either be dropped, or squashed into the earlier patch in this series that introduced this method.
right, this makes sense.
Quoted 7 lines
Quoted 4 lines
Quoted 1 line
+#define
MAX_SIZE(a, b)((a) > (b) ? (a) : (b))Isn't this the same as the existing '
MAX(a, b)' macro inosdep.h?not quite, I don't think MAX can be used in a static assertion, but there's a
MAX_CONSTsibling that we can use.
Ah yes, that sounds good.
With regards,
Daniel
Signature · 3 lines
|: https://berrange.com -o- https://www.flickr.com/photos/dberrange :| |: https://libvirt.org -o- https://fstop138.berrange.com :| |: https://entangle-photo.org -o- https://www.instagram.com/dberrange :|
PATCH v4 26/27 docs: Add mshv to documentation
In reply to Magnus KulkeAdded mshv to the list of accelerators in doc text.
--- docs/about/build-platforms.rst | 2 +- docs/devel/codebase.rst | 2 +- docs/glossary.rst | 6 +++--- docs/system/introduction.rst | 3 +++ qemu-options.hx | 16 ++++++++-------- 5 files changed, 16 insertions(+), 13 deletions(-)
docs/about/build-platforms.rst +1 -1
@@ -55,7 +55,7 @@ Those hosts are officially supported, with various accelerators: * - SPARC - tcg * - x86 - - hvf (64 bit only), kvm, nvmm, tcg, whpx (64 bit only), xen + - hvf (64 bit only), mshv (64 bit only), kvm, nvmm, tcg, whpx (64 bit only), xen Other host architectures are not supported. It is possible to build QEMU system emulation on an unsupported host architecture using the configure
docs/devel/codebase.rst +1 -1
@@ -48,7 +48,7 @@ yet, so sometimes the source code is all you have. * `accel <https://gitlab.com/qemu-project/qemu/-/tree/master/accel>`_: Infrastructure and architecture agnostic code related to the various `accelerators <Accelerators>` supported by QEMU - (TCG, KVM, hvf, whpx, xen, nvmm). + (TCG, KVM, hvf, whpx, xen, nvmm, mshv). Contains interfaces for operations that will be implemented per `target <https://gitlab.com/qemu-project/qemu/-/tree/master/target>`_. * `audio <https://gitlab.com/qemu-project/qemu/-/tree/master/audio>`_:
docs/glossary.rst +3 -3
@@ -12,7 +12,7 @@ Accelerator A specific API used to accelerate execution of guest instructions. It can be hardware-based, through a virtualization API provided by the host OS (kvm, hvf, -whpx, ...), or software-based (tcg). See this description of `supported +whpx, mshv, ...), or software-based (tcg). See this description of `supported accelerators<Accelerators>`. Board
@@ -102,8 +102,8 @@ hypervisors. In the context of QEMU, an hypervisor is an API, provided by the Host OS, allowing to execute virtual machines. Linux implementation is KVM (and supports -Xen as well). For MacOS, it's HVF. Windows defines WHPX. And NetBSD provides -NVMM. +Xen and MSHV as well). For MacOS, it's HVF. Windows defines WHPX. And NetBSD +provides NVMM. .. _machine:
docs/system/introduction.rst +3 -0
@@ -23,6 +23,9 @@ Tiny Code Generator (TCG) capable of emulating many CPUs. * - Xen - Linux (as dom0) - Arm, x86 + * - MSHV + - Linux (as dom0) + - x86 * - Hypervisor Framework (hvf) - MacOS - x86 (64 bit only), Arm (64 bit only)
qemu-options.hx +8 -8
@@ -28,7 +28,7 @@ DEF("machine", HAS_ARG, QEMU_OPTION_machine, \ "-machine [type=]name[,prop[=value][,...]]\n" " selects emulated machine ('-machine help' for list)\n" " property accel=accel1[:accel2[:...]] selects accelerator\n" - " supported accelerators are kvm, xen, hvf, nvmm, whpx or tcg (default: tcg)\n" + " supported accelerators are kvm, xen, hvf, nvmm, whpx, mshv or tcg (default: tcg)\n" " vmport=on|off|auto controls emulation of vmport (default: auto)\n" " dump-guest-core=on|off include guest memory in a core dump (default=on)\n" " mem-merge=on|off controls memory merge support (default: on)\n"
@@ -66,10 +66,10 @@ SRST ``accel=accels1[:accels2[:...]]`` This is used to enable an accelerator. Depending on the target - architecture, kvm, xen, hvf, nvmm, whpx or tcg can be available. - By default, tcg is used. If there is more than one accelerator - specified, the next one is used if the previous one fails to - initialize. + architecture, kvm, xen, hvf, nvmm, whpx, mshv or tcg can be + available. By default, tcg is used. If there is more than one + accelerator specified, the next one is used if the previous one + fails to initialize. ``vmport=on|off|auto`` Enables emulation of VMWare IO port, for vmmouse etc. auto says
@@ -226,7 +226,7 @@ ERST DEF("accel", HAS_ARG, QEMU_OPTION_accel, "-accel [accel=]accelerator[,prop[=value][,...]]\n" - " select accelerator (kvm, xen, hvf, nvmm, whpx or tcg; use 'help' for a list)\n" + " select accelerator (kvm, xen, hvf, nvmm, whpx, mshv or tcg; use 'help' for a list)\n" " igd-passthru=on|off (enable Xen integrated Intel graphics passthrough, default=off)\n" " kernel-irqchip=on|off|split controls accelerated irqchip support (default=on)\n" " kvm-shadow-mem=size of KVM shadow MMU in bytes\n"
@@ -241,8 +241,8 @@ DEF("accel", HAS_ARG, QEMU_OPTION_accel, SRST ``-accel name[,prop=value[,...]]`` This is used to enable an accelerator. Depending on the target - architecture, kvm, xen, hvf, nvmm, whpx or tcg can be available. By - default, tcg is used. If there is more than one accelerator + architecture, kvm, xen, hvf, nvmm, whpx, mshv or tcg can be available. + By default, tcg is used. If there is more than one accelerator specified, the next one is used if the previous one fails to initialize.
Signature · 1 line
2.34.1
Re: [PATCH v4 26/27] docs: Add mshv to documentation
Quoted 43 lines · Magnus Kulke
Added mshv to the list of accelerators in doc text.
Signed-off-by Magnus Kulke <[email protected]>--- docs/about/build-platforms.rst | 2 +- docs/devel/codebase.rst | 2 +- docs/glossary.rst | 6 +++--- docs/system/introduction.rst | 3 +++ qemu-options.hx | 16 ++++++++-------- 5 files changed, 16 insertions(+), 13 deletions(-)docs/about/build-platforms.rst +1
-1@@ -55,7 +55,7 @@ Those hosts are officially supported, with various accelerators: * - SPARC - tcg * - x86 - - hvf (64 bit only), kvm, nvmm, tcg, whpx (64 bit only), xen + - hvf (64 bit only), mshv (64 bit only), kvm, nvmm, tcg, whpx (64 bit only), xen Other host architectures are not supported. It is possible to build QEMU system emulation on an unsupported host architecture using the configuredocs/devel/codebase.rst +1
-1@@ -48,7 +48,7 @@ yet, so sometimes the source code is all you have. * `accel <https://gitlab.com/qemu-project/qemu/-/tree/master/accel>`_: Infrastructure and architecture agnostic code related to the various `accelerators <Accelerators>` supported by QEMU - (TCG, KVM, hvf, whpx, xen, nvmm). + (TCG, KVM, hvf, whpx, xen, nvmm, mshv). Contains interfaces for operations that will be implemented per `target <https://gitlab.com/qemu-project/qemu/-/tree/master/target>`_. * `audio <https://gitlab.com/qemu-project/qemu/-/tree/master/audio>`_:docs/glossary.rst +0
-0
docs/glossary.rst hypervisors. · line 106
Quoted 7 lines
docs/glossary.rst +2
-2@@ -102,8 +102,8 @@ hypervisors. In the context of QEMU, an hypervisor is an API, provided by the Host OS, allowing to execute virtual machines. Linux implementation is KVM (and supports -Xen as well). For MacOS, it's HVF. Windows defines WHPX. And NetBSD provides -NVMM. +Xen and MSHV as well). For MacOS, it's HVF. Windows defines WHPX. And NetBSD +provides NVMM.
This is a bit of a bike-shed colouring comment, but how about saying
"Linux provides a choice of KVM, Xen or MSHV; MacOS provides HVF;
Windows provides WPHX; NetBSD provides NVMM."
With regards,
Daniel
Signature · 3 lines
|: https://berrange.com -o- https://www.flickr.com/photos/dberrange :| |: https://libvirt.org -o- https://fstop138.berrange.com :| |: https://entangle-photo.org -o- https://www.instagram.com/dberrange :|
PATCH v4 27/27 MAINTAINERS: Add maintainers for mshv accelerator
In reply to Magnus KulkeAdding Magnus Kulke and Wei Liu to the maintainers file for the respective folders/files.
--- MAINTAINERS | 15 +++++++++++++++ 1 file changed, 15 insertions(+)
MAINTAINERS +15 -0
@@ -551,6 +551,21 @@ F: target/i386/whpx/ F: accel/stubs/whpx-stub.c F: include/system/whpx.h +MSHV +M: Magnus Kulke <[email protected]> +R: Wei Liu <[email protected]> +S: Supported +F: accel/mshv/ +F: include/system/mshv.h +F: include/hw/hyperv/hvgdk*.h +F: include/hw/hyperv/hvhdk*.h + +MSHV CPUs +M: Magnus Kulke <[email protected]> +R: Wei Liu <[email protected]> +S: Supported +F: target/i386/mshv/ + X86 Instruction Emulator M: Cameron Esfahani <[email protected]> M: Roman Bolshakov <[email protected]>
Signature · 1 line
2.34.1
Re: [PATCH v4 27/27] MAINTAINERS: Add maintainers for mshv accelerator
Quoted 20 lines · Magnus Kulke
Adding Magnus Kulke and Wei Liu to the maintainers file for the respective folders/files.
Signed-off-by Magnus Kulke <[email protected]>--- MAINTAINERS | 15 +++++++++++++++ 1 file changed, 15 insertions(+)MAINTAINERS +4
-0@@ -551,6 +551,21 @@ F: target/i386/whpx/ F: accel/stubs/whpx-stub.c F: include/system/whpx.h +MSHV +M: Magnus Kulke <[email protected]> +R: Wei Liu <[email protected]> +S: Supported
MAINTAINERS F: target/i386/whpx/ · line 567
Quoted 10 lines
MAINTAINERS +10
-0+F: accel/mshv/ +F: include/system/mshv.h +F: include/hw/hyperv/hvgdk*.h +F: include/hw/hyperv/hvhdk*.h + +MSHV CPUs +M: Magnus Kulke <[email protected]> +R: Wei Liu <[email protected]> +S: Supported +F: target/i386/mshv/
Do you need separate groupings ? If the maintainers are the same in both cases, and changes are liable to span both accel/mshv and target/i386/mshv dir, then perhaps 'target/i386/mshv/' is fine being listed under the 'MSHV' group ?
Either way though
With regards,
Daniel
Signature · 3 lines
|: https://berrange.com -o- https://www.flickr.com/photos/dberrange :| |: https://libvirt.org -o- https://fstop138.berrange.com :| |: https://entangle-photo.org -o- https://www.instagram.com/dberrange :|
Re: [PATCH v4 27/27] MAINTAINERS: Add maintainers for mshv accelerator
Quoted 4 lines · Daniel P. Berrangé
Do you need separate groupings ? If the maintainers are the same in both cases, and changes are liable to span both accel/mshv and target/i386/mshv dir, then perhaps 'target/i386/mshv/' is fine being listed under the 'MSHV' group ?
that's true. however, there is work ongoing to add MSHV support to other targets, so eventually it wouldn't be the same maintainers for both.
Re: [PATCH v4 27/27] MAINTAINERS: Add maintainers for mshv accelerator
Quoted 9 lines · Magnus Kulke
Quoted 4 lines · Daniel P. Berrangé
Do you need separate groupings ? If the maintainers are the same in both cases, and changes are liable to span both accel/mshv and target/i386/mshv dir, then perhaps 'target/i386/mshv/' is fine being listed under the 'MSHV' group ?
that's true. however, there is work ongoing to add MSHV support to other targets, so eventually it wouldn't be the same maintainers for both.
Ok, that's sounds fine then.
With regards,
Daniel
Signature · 3 lines
|: https://berrange.com -o- https://www.flickr.com/photos/dberrange :| |: https://libvirt.org -o- https://fstop138.berrange.com :| |: https://entangle-photo.org -o- https://www.instagram.com/dberrange :|
Quoted 8 lines · Magnus Kulke
Hello all,
This is the fourth revision of a patch set implementing an accelerator for the MSHV kernel driver, exposing HyperV to Linux "Dom0" hosts in various scenarios. Thanks for the feedback to the previous revision, I tried to incorporate those. The changes in the currenct patchset beyond the suggested fixes are mostly related to the replacement of retired ioctl calls that will not part of the upstreamed MSHV kernel driver.
Externally we follow Microsoft's convention of calling Linux the "root partition" in this setup. "Dom0" is an internal term. We drew parallels to Xen at the beginning of the project.
Quoted 28 lines
Magnus Kulke (26):
accel: Add Meson and config support for MSHV accelerator target/i386/emulate: Allow instruction decoding from stream target/i386/mshv: Add x86 decoder/emu implementation hw/intc: Generalize APIC helper names from kvm_* to accel_*include/hw/hyperv: Add MSHV ABI header definitions linux-headers/linux: Addmshv.hheaders accel/mshv: Add accelerator skeleton
accel/mshv: Register memory region listeners accel/mshv: Initialize VM partition
accel/mshv: Add vCPU creation and execution loop accel/mshv: Add vCPU signal handling target/i386/mshv: Add CPU create and remove logic target/i386/mshv: Implementmshv_store_regs()target/i386/mshv: Implementmshv_get_standard_regs()target/i386/mshv: Implementmshv_get_special_regs()target/i386/mshv: Implementmshv_arch_put_registers()target/i386/mshv: Set local interrupt controller state target/i386/mshv: Register CPUID entries with MSHV target/i386/mshv: Register MSRs with MSHV target/i386/mshv: Integrate x86 instruction decoder/emulator target/i386/mshv: Write MSRs to the hypervisor target/i386/mshv: Implementmshv_vcpu_run()accel/mshv: Handle overlapping mem mappings target/i386/mshv: Use preallocated page for hvcall
docs: Add mshv to documentation
MAINTAINERS: Add maintainers for mshv accelerator
Quoted 3 lines
Praveen K Paladugu (1):
qapi/accel: Allow to query mshv capabilities
I've gone through this patch series and it generally looks good to me.
It would be great if we can merge this soon so we can do more testing and implement other missing features.
Wei
Hi Magnus,
Quoted 13 lines · Magnus Kulke
Hello all,
This is the fourth revision of a patch set implementing an accelerator for the MSHV kernel driver, exposing HyperV to Linux "Dom0" hosts in various scenarios. Thanks for the feedback to the previous revision, I tried to incorporate those. The changes in the currenct patchset beyond the suggested fixes are mostly related to the replacement of retired ioctl calls that will not part of the upstreamed MSHV kernel driver.
Magnus Kulke (26):
accel: Add Meson and config support for MSHV accelerator
Quoted 7 lines
accel/mshv: Add accelerator skeleton accel/mshv: Register memory region listeners accel/mshv: Initialize VM partition accel/mshv: Add vCPU creation and execution loop accel/mshv: Add vCPU signal handling
accel/mshv: Handle overlapping mem mappings
Due to my generic work on accelerators, I'll have to refactor these patches. Obviously I don't want to break your implementation! Can you add some (functional?) tests? Ideally we should be running tests on our CI to ensure code doesn't bitrot.
Regards,
Phil.
Quoted 23 lines · Philippe Mathieu-Daudé
Hi Magnus,
Quoted 13 lines · Magnus Kulke
Hello all,
This is the fourth revision of a patch set implementing an accelerator for the MSHV kernel driver, exposing HyperV to Linux "Dom0" hosts in various scenarios. Thanks for the feedback to the previous revision, I tried to incorporate those. The changes in the currenct patchset beyond the suggested fixes are mostly related to the replacement of retired ioctl calls that will not part of the upstreamed MSHV kernel driver.
Magnus Kulke (26):
accel: Add Meson and config support for MSHV acceleratorQuoted 6 lines
accel/mshv: Add accelerator skeleton accel/mshv: Register memory region listeners accel/mshv: Initialize VM partition accel/mshv: Add vCPU creation and execution loop accel/mshv: Add vCPU signal handling accel/mshv: Handle overlapping mem mappings
Quoted 4 lines
Due to my generic work on accelerators, I'll have to refactor these patches. Obviously I don't want to break your implementation! Can you add some (functional?) tests? Ideally we should be running tests on our CI to ensure code doesn't bitrot.
NB our CI systems don't have HyperV available, so it is unrealistic for us to test it in our CI upstream.
With regards,
Daniel
Signature · 3 lines
|: https://berrange.com -o- https://www.flickr.com/photos/dberrange :| |: https://libvirt.org -o- https://fstop138.berrange.com :| |: https://entangle-photo.org -o- https://www.instagram.com/dberrange :|
Quoted 24 lines · Daniel P. Berrangé
Quoted 23 lines · Philippe Mathieu-Daudé
Hi Magnus,
Quoted 19 lines · Magnus Kulke
Hello all,
This is the fourth revision of a patch set implementing an accelerator for the MSHV kernel driver, exposing HyperV to Linux "Dom0" hosts in various scenarios. Thanks for the feedback to the previous revision, I tried to incorporate those. The changes in the currenct patchset beyond the suggested fixes are mostly related to the replacement of retired ioctl calls that will not part of the upstreamed MSHV kernel driver.
Magnus Kulke (26):
accel: Add Meson and config support for MSHV acceleratoraccel/mshv: Add accelerator skeleton accel/mshv: Register memory region listeners accel/mshv: Initialize VM partition accel/mshv: Add vCPU creation and execution loop accel/mshv: Add vCPU signal handling accel/mshv: Handle overlapping mem mappings
Quoted 7 lines
Quoted 4 lines
Due to my generic work on accelerators, I'll have to refactor these patches. Obviously I don't want to break your implementation! Can you add some (functional?) tests? Ideally we should be running tests on our CI to ensure code doesn't bitrot.
NB our CI systems don't have HyperV available, so it is unrealistic for us to test it in our CI upstream.
OK. Hopefully meson will autodetect it on x86_64 Linux hosts so at least we'll compile & link.
That said, IIUC our Xen-only job should now use --disable-mshv:
.gitlab-ci.d/crossbuilds.yml:181:cross-amd64-xen-only:
.gitlab-ci.d/crossbuilds.yml-182- extends: .cross_accel_build_job .gitlab-ci.d/crossbuilds.yml-183- needs:
.gitlab-ci.d/crossbuilds.yml-184- - job: amd64-debian-cross-container
.gitlab-ci.d/crossbuilds.yml-185- variables:
.gitlab-ci.d/crossbuilds.yml-186- IMAGE: debian-amd64-cross .gitlab-ci.d/crossbuilds.yml-187- ACCEL: xen .gitlab-ci.d/crossbuilds.yml-188- EXTRA_CONFIGURE_OPTS: --disable-tcg --disable-kvm
.gitlab-ci.d/crossbuilds.yml-189-
Tests are optionally run on CI, having a test we can run locally is still valuable.
Quoted 8 lines · Philippe Mathieu-Daudé
Due to my generic work on accelerators, I'll have to refactor these patches. Obviously I don't want to break your implementation! Can you add some (functional?) tests? Ideally we should be running tests on our CI to ensure code doesn't bitrot.
Regards,
Phil.
Hey Phil,
yes, that's a good point. I assume for functional tests we will face the challenge those will require external infra, because eventually there needs to be a HyperV Hypervisor running somewhere.
Is there any precedent/prior art in QEMU (e.g. for HVF or WHPX) that we could follow?
FWIW, in smoke tests for the patch series I've been using a nested HyperV hypervisor that is shipped as dll and made available as UEFI protocol to the MSHV driver (I _think_ that is how it works, I'm a bit out of my depth here since I don't know how those things are glued together in detail).
For reference: https://github.com/mkulke/qemu/actions/runs/18187719634
There will be other virt topologies supported by the MSHV driver and the nested option is not upstreamed to mainline yet. However, from QEMU's perspective those topologies do not matter, they share the same ABI of the kernel driver.
So we could do something similar, provide/maintain a VM on Azure with a similar nested HyperV hypervisor configuration that we can used for testing. Would this make sense?
Best,
magnus
Quoted 12 lines · Magnus Kulke
Quoted 7 lines · Philippe Mathieu-Daudé
Due to my generic work on accelerators, I'll have to refactor these patches. Obviously I don't want to break your implementation! Can you add some (functional?) tests? Ideally we should be running tests on our CI to ensure code doesn't bitrot.
Regards,
Quoted 7 lines
Quoted 1 line
Phil.
Hey Phil,
yes, that's a good point. I assume for functional tests we will face the challenge those will require external infra, because eventually there needs to be a HyperV Hypervisor running somewhere.
Worth noting that x86_64 MSHV on Linux is available to the public as part of Azure Linux, and runs inside of a Qemu VM just fine. (with the catch that MBEC isn’t currently emulated by KVM)
Perhaps having an Azure Linux instance in CI could be the right thing to do?
Thank you,
Quoted 24 lines
Is there any precedent/prior art in QEMU (e.g. for HVF or WHPX) that we could follow?
FWIW, in smoke tests for the patch series I've been using a nested HyperV hypervisor that is shipped as dll and made available as UEFI protocol to the MSHV driver (I _think_ that is how it works, I'm a bit out of my depth here since I don't know how those things are glued together in detail).
For reference: https://github.com/mkulke/qemu/actions/runs/18187719634
There will be other virt topologies supported by the MSHV driver and the nested option is not upstreamed to mainline yet. However, from QEMU's perspective those topologies do not matter, they share the same ABI of the kernel driver.
So we could do something similar, provide/maintain a VM on Azure with a similar nested HyperV hypervisor configuration that we can used for testing. Would this make sense?
Best,
magnus
Quoted 5 lines · Mohamed Mediouni
Worth noting that
x86_64MSHV on Linux is available to the public as part of Azure Linux, and runs inside of a Qemu VM just fine. (with the catch that MBEC isn’t currently emulated by KVM)Perhaps having an Azure Linux instance in CI could be the right thing to do?
Yes, that's right, MSHV is shipped as part of Azure Linux images, albeit the mshv kernel driver in the AL kernel tree has more features that are being upstreamed to mainline incrementally over time.
If I understand correctly, your suggestion is to run HyperV as a nested hypervisor inside a QEMU VM (with KVM accel) on the CI machine that runs on on baremetal/L0? (mshv-on-kvm)
We haven't tested this scenario yet, AFAIK the images that ship the HyperV bits are meant to run as part of proprietary Azure products, so the CI setup wouldn't really be representative of a real-world user workloads.
We'll investigate if this is a feasible option, but I suspect that it'll be more straight forward to provide CI runners as L1 compute on Azure cloud (or run tests downstream somewhere if this is not trivial to integrate).
best,
magnus
Quoted 7 lines · Magnus Kulke
If I understand correctly, your suggestion is to run HyperV as a nested hypervisor inside a QEMU VM (with KVM accel) on the CI machine that runs on on baremetal/L0? (mshv-on-kvm)
Yes. I’ve been playing around with that configuration using cloud-hypervisor on an AMD Zen 4 host and it works fine.
Thanks,