VirtualBox

source: vbox/trunk/src/VBox/VMM/VMMR3/NEMR3Native-darwin.cpp@ 92556

Last change on this file since 92556 was 92541, checked in by vboxsync, 3 years ago

VMM: Nested VMX: bugref:10092 Allow forcing mapping/unmapping of CR3 even when the paging mode deosn't actually change. This is required for VMX/SVM guest transitions.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 129.0 KB
Line 
1/* $Id: NEMR3Native-darwin.cpp 92541 2021-11-22 06:35:38Z vboxsync $ */
2/** @file
3 * NEM - Native execution manager, native ring-3 macOS backend using Hypervisor.framework.
4 *
5 * Log group 2: Exit logging.
6 * Log group 3: Log context on exit.
7 * Log group 5: Ring-3 memory management
8 */
9
10/*
11 * Copyright (C) 2020 Oracle Corporation
12 *
13 * This file is part of VirtualBox Open Source Edition (OSE), as
14 * available from http://www.virtualbox.org. This file is free software;
15 * you can redistribute it and/or modify it under the terms of the GNU
16 * General Public License (GPL) as published by the Free Software
17 * Foundation, in version 2 as it comes in the "COPYING" file of the
18 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
19 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
20 */
21
22
23/*********************************************************************************************************************************
24* Header Files *
25*********************************************************************************************************************************/
26#define LOG_GROUP LOG_GROUP_NEM
27#define VMCPU_INCL_CPUM_GST_CTX
28#include <VBox/vmm/nem.h>
29#include <VBox/vmm/iem.h>
30#include <VBox/vmm/em.h>
31#include <VBox/vmm/apic.h>
32#include <VBox/vmm/pdm.h>
33#include <VBox/vmm/hm.h>
34#include <VBox/vmm/hm_vmx.h>
35#include <VBox/vmm/dbgftrace.h>
36#include "VMXInternal.h"
37#include "NEMInternal.h"
38#include <VBox/vmm/vmcc.h>
39#include "dtrace/VBoxVMM.h"
40
41#include <iprt/asm.h>
42#include <iprt/ldr.h>
43#include <iprt/mem.h>
44#include <iprt/path.h>
45#include <iprt/string.h>
46#include <iprt/system.h>
47#include <iprt/utf16.h>
48
49
50/*********************************************************************************************************************************
51* Defined Constants And Macros *
52*********************************************************************************************************************************/
53/* No nested hwvirt (for now). */
54#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
55# undef VBOX_WITH_NESTED_HWVIRT_VMX
56#endif
57
58
59/** @name HV return codes.
60 * @{ */
61/** Operation was successful. */
62#define HV_SUCCESS 0
63/** An error occurred during operation. */
64#define HV_ERROR 0xfae94001
65/** The operation could not be completed right now, try again. */
66#define HV_BUSY 0xfae94002
67/** One of the parameters passed wis invalid. */
68#define HV_BAD_ARGUMENT 0xfae94003
69/** Not enough resources left to fulfill the operation. */
70#define HV_NO_RESOURCES 0xfae94005
71/** The device could not be found. */
72#define HV_NO_DEVICE 0xfae94006
73/** The operation is not supportd on this platform with this configuration. */
74#define HV_UNSUPPORTED 0xfae94007
75/** @} */
76
77
78/** @name HV memory protection flags.
79 * @{ */
80/** Memory is readable. */
81#define HV_MEMORY_READ RT_BIT_64(0)
82/** Memory is writeable. */
83#define HV_MEMORY_WRITE RT_BIT_64(1)
84/** Memory is executable. */
85#define HV_MEMORY_EXEC RT_BIT_64(2)
86/** @} */
87
88
89/** @name HV shadow VMCS protection flags.
90 * @{ */
91/** Shadow VMCS field is not accessible. */
92#define HV_SHADOW_VMCS_NONE 0
93/** Shadow VMCS fild is readable. */
94#define HV_SHADOW_VMCS_READ RT_BIT_64(0)
95/** Shadow VMCS field is writeable. */
96#define HV_SHADOW_VMCS_WRITE RT_BIT_64(1)
97/** @} */
98
99
100/** Default VM creation flags. */
101#define HV_VM_DEFAULT 0
102/** Default guest address space creation flags. */
103#define HV_VM_SPACE_DEFAULT 0
104/** Default vCPU creation flags. */
105#define HV_VCPU_DEFAULT 0
106
107#define HV_DEADLINE_FOREVER UINT64_MAX
108
109
110/*********************************************************************************************************************************
111* Structures and Typedefs *
112*********************************************************************************************************************************/
113
114/** HV return code type. */
115typedef uint32_t hv_return_t;
116/** HV capability bitmask. */
117typedef uint64_t hv_capability_t;
118/** Option bitmask type when creating a VM. */
119typedef uint64_t hv_vm_options_t;
120/** Option bitmask when creating a vCPU. */
121typedef uint64_t hv_vcpu_options_t;
122/** HV memory protection flags type. */
123typedef uint64_t hv_memory_flags_t;
124/** Shadow VMCS protection flags. */
125typedef uint64_t hv_shadow_flags_t;
126/** Guest physical address type. */
127typedef uint64_t hv_gpaddr_t;
128
129
130/**
131 * VMX Capability enumeration.
132 */
133typedef enum
134{
135 HV_VMX_CAP_PINBASED = 0,
136 HV_VMX_CAP_PROCBASED,
137 HV_VMX_CAP_PROCBASED2,
138 HV_VMX_CAP_ENTRY,
139 HV_VMX_CAP_EXIT,
140 HV_VMX_CAP_BASIC, /* Since 11.0 */
141 HV_VMX_CAP_TRUE_PINBASED, /* Since 11.0 */
142 HV_VMX_CAP_TRUE_PROCBASED, /* Since 11.0 */
143 HV_VMX_CAP_TRUE_ENTRY, /* Since 11.0 */
144 HV_VMX_CAP_TRUE_EXIT, /* Since 11.0 */
145 HV_VMX_CAP_MISC, /* Since 11.0 */
146 HV_VMX_CAP_CR0_FIXED0, /* Since 11.0 */
147 HV_VMX_CAP_CR0_FIXED1, /* Since 11.0 */
148 HV_VMX_CAP_CR4_FIXED0, /* Since 11.0 */
149 HV_VMX_CAP_CR4_FIXED1, /* Since 11.0 */
150 HV_VMX_CAP_VMCS_ENUM, /* Since 11.0 */
151 HV_VMX_CAP_EPT_VPID_CAP, /* Since 11.0 */
152 HV_VMX_CAP_PREEMPTION_TIMER = 32
153} hv_vmx_capability_t;
154
155
156/**
157 * HV x86 register enumeration.
158 */
159typedef enum
160{
161 HV_X86_RIP = 0,
162 HV_X86_RFLAGS,
163 HV_X86_RAX,
164 HV_X86_RCX,
165 HV_X86_RDX,
166 HV_X86_RBX,
167 HV_X86_RSI,
168 HV_X86_RDI,
169 HV_X86_RSP,
170 HV_X86_RBP,
171 HV_X86_R8,
172 HV_X86_R9,
173 HV_X86_R10,
174 HV_X86_R11,
175 HV_X86_R12,
176 HV_X86_R13,
177 HV_X86_R14,
178 HV_X86_R15,
179 HV_X86_CS,
180 HV_X86_SS,
181 HV_X86_DS,
182 HV_X86_ES,
183 HV_X86_FS,
184 HV_X86_GS,
185 HV_X86_IDT_BASE,
186 HV_X86_IDT_LIMIT,
187 HV_X86_GDT_BASE,
188 HV_X86_GDT_LIMIT,
189 HV_X86_LDTR,
190 HV_X86_LDT_BASE,
191 HV_X86_LDT_LIMIT,
192 HV_X86_LDT_AR,
193 HV_X86_TR,
194 HV_X86_TSS_BASE,
195 HV_X86_TSS_LIMIT,
196 HV_X86_TSS_AR,
197 HV_X86_CR0,
198 HV_X86_CR1,
199 HV_X86_CR2,
200 HV_X86_CR3,
201 HV_X86_CR4,
202 HV_X86_DR0,
203 HV_X86_DR1,
204 HV_X86_DR2,
205 HV_X86_DR3,
206 HV_X86_DR4,
207 HV_X86_DR5,
208 HV_X86_DR6,
209 HV_X86_DR7,
210 HV_X86_TPR,
211 HV_X86_XCR0,
212 HV_X86_REGISTERS_MAX
213} hv_x86_reg_t;
214
215
216typedef hv_return_t FN_HV_CAPABILITY(hv_capability_t capability, uint64_t *valu);
217typedef hv_return_t FN_HV_VM_CREATE(hv_vm_options_t flags);
218typedef hv_return_t FN_HV_VM_DESTROY(void);
219typedef hv_return_t FN_HV_VM_SPACE_CREATE(hv_vm_space_t *asid);
220typedef hv_return_t FN_HV_VM_SPACE_DESTROY(hv_vm_space_t asid);
221typedef hv_return_t FN_HV_VM_MAP(const void *uva, hv_gpaddr_t gpa, size_t size, hv_memory_flags_t flags);
222typedef hv_return_t FN_HV_VM_UNMAP(hv_gpaddr_t gpa, size_t size);
223typedef hv_return_t FN_HV_VM_PROTECT(hv_gpaddr_t gpa, size_t size, hv_memory_flags_t flags);
224typedef hv_return_t FN_HV_VM_MAP_SPACE(hv_vm_space_t asid, const void *uva, hv_gpaddr_t gpa, size_t size, hv_memory_flags_t flags);
225typedef hv_return_t FN_HV_VM_UNMAP_SPACE(hv_vm_space_t asid, hv_gpaddr_t gpa, size_t size);
226typedef hv_return_t FN_HV_VM_PROTECT_SPACE(hv_vm_space_t asid, hv_gpaddr_t gpa, size_t size, hv_memory_flags_t flags);
227typedef hv_return_t FN_HV_VM_SYNC_TSC(uint64_t tsc);
228
229typedef hv_return_t FN_HV_VCPU_CREATE(hv_vcpuid_t *vcpu, hv_vcpu_options_t flags);
230typedef hv_return_t FN_HV_VCPU_DESTROY(hv_vcpuid_t vcpu);
231typedef hv_return_t FN_HV_VCPU_SET_SPACE(hv_vcpuid_t vcpu, hv_vm_space_t asid);
232typedef hv_return_t FN_HV_VCPU_READ_REGISTER(hv_vcpuid_t vcpu, hv_x86_reg_t reg, uint64_t *value);
233typedef hv_return_t FN_HV_VCPU_WRITE_REGISTER(hv_vcpuid_t vcpu, hv_x86_reg_t reg, uint64_t value);
234typedef hv_return_t FN_HV_VCPU_READ_FPSTATE(hv_vcpuid_t vcpu, void *buffer, size_t size);
235typedef hv_return_t FN_HV_VCPU_WRITE_FPSTATE(hv_vcpuid_t vcpu, const void *buffer, size_t size);
236typedef hv_return_t FN_HV_VCPU_ENABLE_NATIVE_MSR(hv_vcpuid_t vcpu, uint32_t msr, bool enable);
237typedef hv_return_t FN_HV_VCPU_READ_MSR(hv_vcpuid_t vcpu, uint32_t msr, uint64_t *value);
238typedef hv_return_t FN_HV_VCPU_WRITE_MSR(hv_vcpuid_t vcpu, uint32_t msr, uint64_t value);
239typedef hv_return_t FN_HV_VCPU_FLUSH(hv_vcpuid_t vcpu);
240typedef hv_return_t FN_HV_VCPU_INVALIDATE_TLB(hv_vcpuid_t vcpu);
241typedef hv_return_t FN_HV_VCPU_RUN(hv_vcpuid_t vcpu);
242typedef hv_return_t FN_HV_VCPU_RUN_UNTIL(hv_vcpuid_t vcpu, uint64_t deadline);
243typedef hv_return_t FN_HV_VCPU_INTERRUPT(hv_vcpuid_t *vcpus, unsigned int vcpu_count);
244typedef hv_return_t FN_HV_VCPU_GET_EXEC_TIME(hv_vcpuid_t *vcpus, uint64_t *time);
245
246typedef hv_return_t FN_HV_VMX_VCPU_READ_VMCS(hv_vcpuid_t vcpu, uint32_t field, uint64_t *value);
247typedef hv_return_t FN_HV_VMX_VCPU_WRITE_VMCS(hv_vcpuid_t vcpu, uint32_t field, uint64_t value);
248
249typedef hv_return_t FN_HV_VMX_VCPU_READ_SHADOW_VMCS(hv_vcpuid_t vcpu, uint32_t field, uint64_t *value);
250typedef hv_return_t FN_HV_VMX_VCPU_WRITE_SHADOW_VMCS(hv_vcpuid_t vcpu, uint32_t field, uint64_t value);
251typedef hv_return_t FN_HV_VMX_VCPU_SET_SHADOW_ACCESS(hv_vcpuid_t vcpu, uint32_t field, hv_shadow_flags_t flags);
252
253typedef hv_return_t FN_HV_VMX_READ_CAPABILITY(hv_vmx_capability_t field, uint64_t *value);
254typedef hv_return_t FN_HV_VMX_VCPU_SET_APIC_ADDRESS(hv_vcpuid_t vcpu, hv_gpaddr_t gpa);
255
256
257/*********************************************************************************************************************************
258* Global Variables *
259*********************************************************************************************************************************/
260/** NEM_DARWIN_PAGE_STATE_XXX names. */
261NEM_TMPL_STATIC const char * const g_apszPageStates[4] = { "not-set", "unmapped", "readable", "writable" };
262/** MSRs. */
263static SUPHWVIRTMSRS g_HmMsrs;
264/** VMX: Set if swapping EFER is supported. */
265static bool g_fHmVmxSupportsVmcsEfer = false;
266/** @name APIs imported from Hypervisor.framework.
267 * @{ */
268static FN_HV_CAPABILITY *g_pfnHvCapability = NULL; /* Since 10.15 */
269static FN_HV_VM_CREATE *g_pfnHvVmCreate = NULL; /* Since 10.10 */
270static FN_HV_VM_DESTROY *g_pfnHvVmDestroy = NULL; /* Since 10.10 */
271static FN_HV_VM_SPACE_CREATE *g_pfnHvVmSpaceCreate = NULL; /* Since 10.15 */
272static FN_HV_VM_SPACE_DESTROY *g_pfnHvVmSpaceDestroy = NULL; /* Since 10.15 */
273static FN_HV_VM_MAP *g_pfnHvVmMap = NULL; /* Since 10.10 */
274static FN_HV_VM_UNMAP *g_pfnHvVmUnmap = NULL; /* Since 10.10 */
275static FN_HV_VM_PROTECT *g_pfnHvVmProtect = NULL; /* Since 10.10 */
276static FN_HV_VM_MAP_SPACE *g_pfnHvVmMapSpace = NULL; /* Since 10.15 */
277static FN_HV_VM_UNMAP_SPACE *g_pfnHvVmUnmapSpace = NULL; /* Since 10.15 */
278static FN_HV_VM_PROTECT_SPACE *g_pfnHvVmProtectSpace = NULL; /* Since 10.15 */
279static FN_HV_VM_SYNC_TSC *g_pfnHvVmSyncTsc = NULL; /* Since 10.10 */
280
281static FN_HV_VCPU_CREATE *g_pfnHvVCpuCreate = NULL; /* Since 10.10 */
282static FN_HV_VCPU_DESTROY *g_pfnHvVCpuDestroy = NULL; /* Since 10.10 */
283static FN_HV_VCPU_SET_SPACE *g_pfnHvVCpuSetSpace = NULL; /* Since 10.15 */
284static FN_HV_VCPU_READ_REGISTER *g_pfnHvVCpuReadRegister = NULL; /* Since 10.10 */
285static FN_HV_VCPU_WRITE_REGISTER *g_pfnHvVCpuWriteRegister = NULL; /* Since 10.10 */
286static FN_HV_VCPU_READ_FPSTATE *g_pfnHvVCpuReadFpState = NULL; /* Since 10.10 */
287static FN_HV_VCPU_WRITE_FPSTATE *g_pfnHvVCpuWriteFpState = NULL; /* Since 10.10 */
288static FN_HV_VCPU_ENABLE_NATIVE_MSR *g_pfnHvVCpuEnableNativeMsr = NULL; /* Since 10.10 */
289static FN_HV_VCPU_READ_MSR *g_pfnHvVCpuReadMsr = NULL; /* Since 10.10 */
290static FN_HV_VCPU_WRITE_MSR *g_pfnHvVCpuWriteMsr = NULL; /* Since 10.10 */
291static FN_HV_VCPU_FLUSH *g_pfnHvVCpuFlush = NULL; /* Since 10.10 */
292static FN_HV_VCPU_INVALIDATE_TLB *g_pfnHvVCpuInvalidateTlb = NULL; /* Since 10.10 */
293static FN_HV_VCPU_RUN *g_pfnHvVCpuRun = NULL; /* Since 10.10 */
294static FN_HV_VCPU_RUN_UNTIL *g_pfnHvVCpuRunUntil = NULL; /* Since 10.15 */
295static FN_HV_VCPU_INTERRUPT *g_pfnHvVCpuInterrupt = NULL; /* Since 10.10 */
296static FN_HV_VCPU_GET_EXEC_TIME *g_pfnHvVCpuGetExecTime = NULL; /* Since 10.10 */
297
298static FN_HV_VMX_READ_CAPABILITY *g_pfnHvVmxReadCapability = NULL; /* Since 10.10 */
299static FN_HV_VMX_VCPU_READ_VMCS *g_pfnHvVmxVCpuReadVmcs = NULL; /* Since 10.10 */
300static FN_HV_VMX_VCPU_WRITE_VMCS *g_pfnHvVmxVCpuWriteVmcs = NULL; /* Since 10.10 */
301static FN_HV_VMX_VCPU_READ_SHADOW_VMCS *g_pfnHvVmxVCpuReadShadowVmcs = NULL; /* Since 10.15 */
302static FN_HV_VMX_VCPU_WRITE_SHADOW_VMCS *g_pfnHvVmxVCpuWriteShadowVmcs = NULL; /* Since 10.15 */
303static FN_HV_VMX_VCPU_SET_SHADOW_ACCESS *g_pfnHvVmxVCpuSetShadowAccess = NULL; /* Since 10.15 */
304static FN_HV_VMX_VCPU_SET_APIC_ADDRESS *g_pfnHvVmxVCpuSetApicAddress = NULL; /* Since 10.10 */
305/** @} */
306
307
308/**
309 * Import instructions.
310 */
311static const struct
312{
313 bool fOptional; /**< Set if import is optional. */
314 void **ppfn; /**< The function pointer variable. */
315 const char *pszName; /**< The function name. */
316} g_aImports[] =
317{
318#define NEM_DARWIN_IMPORT(a_fOptional, a_Pfn, a_Name) { (a_fOptional), (void **)&(a_Pfn), #a_Name }
319 NEM_DARWIN_IMPORT(true, g_pfnHvCapability, hv_capability),
320 NEM_DARWIN_IMPORT(false, g_pfnHvVmCreate, hv_vm_create),
321 NEM_DARWIN_IMPORT(false, g_pfnHvVmDestroy, hv_vm_destroy),
322 NEM_DARWIN_IMPORT(true, g_pfnHvVmSpaceCreate, hv_vm_space_create),
323 NEM_DARWIN_IMPORT(true, g_pfnHvVmSpaceDestroy, hv_vm_space_destroy),
324 NEM_DARWIN_IMPORT(false, g_pfnHvVmMap, hv_vm_map),
325 NEM_DARWIN_IMPORT(false, g_pfnHvVmUnmap, hv_vm_unmap),
326 NEM_DARWIN_IMPORT(false, g_pfnHvVmProtect, hv_vm_protect),
327 NEM_DARWIN_IMPORT(true, g_pfnHvVmMapSpace, hv_vm_map_space),
328 NEM_DARWIN_IMPORT(true, g_pfnHvVmUnmapSpace, hv_vm_unmap_space),
329 NEM_DARWIN_IMPORT(true, g_pfnHvVmProtectSpace, hv_vm_protect_space),
330 NEM_DARWIN_IMPORT(false, g_pfnHvVmSyncTsc, hv_vm_sync_tsc),
331
332 NEM_DARWIN_IMPORT(false, g_pfnHvVCpuCreate, hv_vcpu_create),
333 NEM_DARWIN_IMPORT(false, g_pfnHvVCpuDestroy, hv_vcpu_destroy),
334 NEM_DARWIN_IMPORT(true, g_pfnHvVCpuSetSpace, hv_vcpu_set_space),
335 NEM_DARWIN_IMPORT(false, g_pfnHvVCpuReadRegister, hv_vcpu_read_register),
336 NEM_DARWIN_IMPORT(false, g_pfnHvVCpuWriteRegister, hv_vcpu_write_register),
337 NEM_DARWIN_IMPORT(false, g_pfnHvVCpuReadFpState, hv_vcpu_read_fpstate),
338 NEM_DARWIN_IMPORT(false, g_pfnHvVCpuWriteFpState, hv_vcpu_write_fpstate),
339 NEM_DARWIN_IMPORT(false, g_pfnHvVCpuEnableNativeMsr, hv_vcpu_enable_native_msr),
340 NEM_DARWIN_IMPORT(false, g_pfnHvVCpuReadMsr, hv_vcpu_read_msr),
341 NEM_DARWIN_IMPORT(false, g_pfnHvVCpuWriteMsr, hv_vcpu_write_msr),
342 NEM_DARWIN_IMPORT(false, g_pfnHvVCpuFlush, hv_vcpu_flush),
343 NEM_DARWIN_IMPORT(false, g_pfnHvVCpuInvalidateTlb, hv_vcpu_invalidate_tlb),
344 NEM_DARWIN_IMPORT(false, g_pfnHvVCpuRun, hv_vcpu_run),
345 NEM_DARWIN_IMPORT(true, g_pfnHvVCpuRunUntil, hv_vcpu_run_until),
346 NEM_DARWIN_IMPORT(false, g_pfnHvVCpuInterrupt, hv_vcpu_interrupt),
347 NEM_DARWIN_IMPORT(true, g_pfnHvVCpuGetExecTime, hv_vcpu_get_exec_time),
348 NEM_DARWIN_IMPORT(false, g_pfnHvVmxReadCapability, hv_vmx_read_capability),
349 NEM_DARWIN_IMPORT(false, g_pfnHvVmxVCpuReadVmcs, hv_vmx_vcpu_read_vmcs),
350 NEM_DARWIN_IMPORT(false, g_pfnHvVmxVCpuWriteVmcs, hv_vmx_vcpu_write_vmcs),
351 NEM_DARWIN_IMPORT(true, g_pfnHvVmxVCpuReadShadowVmcs, hv_vmx_vcpu_read_shadow_vmcs),
352 NEM_DARWIN_IMPORT(true, g_pfnHvVmxVCpuWriteShadowVmcs, hv_vmx_vcpu_write_shadow_vmcs),
353 NEM_DARWIN_IMPORT(true, g_pfnHvVmxVCpuSetShadowAccess, hv_vmx_vcpu_set_shadow_access),
354 NEM_DARWIN_IMPORT(false, g_pfnHvVmxVCpuSetApicAddress, hv_vmx_vcpu_set_apic_address),
355#undef NEM_DARWIN_IMPORT
356};
357
358
359/*
360 * Let the preprocessor alias the APIs to import variables for better autocompletion.
361 */
362#ifndef IN_SLICKEDIT
363# define hv_capability g_pfnHvCapability
364# define hv_vm_create g_pfnHvVmCreate
365# define hv_vm_destroy g_pfnHvVmDestroy
366# define hv_vm_space_create g_pfnHvVmSpaceCreate
367# define hv_vm_space_destroy g_pfnHvVmSpaceDestroy
368# define hv_vm_map g_pfnHvVmMap
369# define hv_vm_unmap g_pfnHvVmUnmap
370# define hv_vm_protect g_pfnHvVmProtect
371# define hv_vm_map_space g_pfnHvVmMapSpace
372# define hv_vm_unmap_space g_pfnHvVmUnmapSpace
373# define hv_vm_protect_space g_pfnHvVmProtectSpace
374# define hv_vm_sync_tsc g_pfnHvVmSyncTsc
375
376# define hv_vcpu_create g_pfnHvVCpuCreate
377# define hv_vcpu_destroy g_pfnHvVCpuDestroy
378# define hv_vcpu_set_space g_pfnHvVCpuSetSpace
379# define hv_vcpu_read_register g_pfnHvVCpuReadRegister
380# define hv_vcpu_write_register g_pfnHvVCpuWriteRegister
381# define hv_vcpu_read_fpstate g_pfnHvVCpuReadFpState
382# define hv_vcpu_write_fpstate g_pfnHvVCpuWriteFpState
383# define hv_vcpu_enable_native_msr g_pfnHvVCpuEnableNativeMsr
384# define hv_vcpu_read_msr g_pfnHvVCpuReadMsr
385# define hv_vcpu_write_msr g_pfnHvVCpuWriteMsr
386# define hv_vcpu_flush g_pfnHvVCpuFlush
387# define hv_vcpu_invalidate_tlb g_pfnHvVCpuInvalidateTlb
388# define hv_vcpu_run g_pfnHvVCpuRun
389# define hv_vcpu_run_until g_pfnHvVCpuRunUntil
390# define hv_vcpu_interrupt g_pfnHvVCpuInterrupt
391# define hv_vcpu_get_exec_time g_pfnHvVCpuGetExecTime
392
393# define hv_vmx_read_capability g_pfnHvVmxReadCapability
394# define hv_vmx_vcpu_read_vmcs g_pfnHvVmxVCpuReadVmcs
395# define hv_vmx_vcpu_write_vmcs g_pfnHvVmxVCpuWriteVmcs
396# define hv_vmx_vcpu_read_shadow_vmcs g_pfnHvVmxVCpuReadShadowVmcs
397# define hv_vmx_vcpu_write_shadow_vmcs g_pfnHvVmxVCpuWriteShadowVmcs
398# define hv_vmx_vcpu_set_shadow_access g_pfnHvVmxVCpuSetShadowAccess
399# define hv_vmx_vcpu_set_apic_address g_pfnHvVmxVCpuSetApicAddress
400#endif
401
402
403/*********************************************************************************************************************************
404* Internal Functions *
405*********************************************************************************************************************************/
406
407/**
408 * Converts a HV return code to a VBox status code.
409 *
410 * @returns VBox status code.
411 * @param hrc The HV return code to convert.
412 */
413DECLINLINE(int) nemR3DarwinHvSts2Rc(hv_return_t hrc)
414{
415 if (hrc == HV_SUCCESS)
416 return VINF_SUCCESS;
417
418 switch (hrc)
419 {
420 case HV_ERROR: return VERR_INVALID_STATE;
421 case HV_BUSY: return VERR_RESOURCE_BUSY;
422 case HV_BAD_ARGUMENT: return VERR_INVALID_PARAMETER;
423 case HV_NO_RESOURCES: return VERR_OUT_OF_RESOURCES;
424 case HV_NO_DEVICE: return VERR_NOT_FOUND;
425 case HV_UNSUPPORTED: return VERR_NOT_SUPPORTED;
426 }
427
428 return VERR_IPE_UNEXPECTED_STATUS;
429}
430
431
432/**
433 * Unmaps the given guest physical address range (page aligned).
434 *
435 * @returns VBox status code.
436 * @param pVM The cross context VM structure.
437 * @param GCPhys The guest physical address to start unmapping at.
438 * @param cb The size of the range to unmap in bytes.
439 */
440DECLINLINE(int) nemR3DarwinUnmap(PVM pVM, RTGCPHYS GCPhys, size_t cb)
441{
442 LogFlowFunc(("Unmapping %RGp LB %zu\n", GCPhys, cb));
443 hv_return_t hrc;
444 if (pVM->nem.s.fCreatedAsid)
445 hrc = hv_vm_unmap_space(pVM->nem.s.uVmAsid, GCPhys, cb);
446 else
447 hrc = hv_vm_unmap(GCPhys, cb);
448 return nemR3DarwinHvSts2Rc(hrc);
449}
450
451
452/**
453 * Maps a given guest physical address range backed by the given memory with the given
454 * protection flags.
455 *
456 * @returns VBox status code.
457 * @param pVM The cross context VM structure.
458 * @param GCPhys The guest physical address to start mapping.
459 * @param pvRam The R3 pointer of the memory to back the range with.
460 * @param cb The size of the range, page aligned.
461 * @param fPageProt The page protection flags to use for this range, combination of NEM_PAGE_PROT_XXX
462 */
463DECLINLINE(int) nemR3DarwinMap(PVM pVM, RTGCPHYS GCPhys, void *pvRam, size_t cb, uint32_t fPageProt)
464{
465 LogFlowFunc(("Mapping %RGp LB %zu fProt=%#x\n", GCPhys, cb, fPageProt));
466
467 hv_memory_flags_t fHvMemProt = 0;
468 if (fPageProt & NEM_PAGE_PROT_READ)
469 fHvMemProt |= HV_MEMORY_READ;
470 if (fPageProt & NEM_PAGE_PROT_WRITE)
471 fHvMemProt |= HV_MEMORY_WRITE;
472 if (fPageProt & NEM_PAGE_PROT_EXECUTE)
473 fHvMemProt |= HV_MEMORY_EXEC;
474
475 hv_return_t hrc;
476 if (pVM->nem.s.fCreatedAsid)
477 hrc = hv_vm_map_space(pVM->nem.s.uVmAsid, pvRam, GCPhys, cb, fHvMemProt);
478 else
479 hrc = hv_vm_map(pvRam, GCPhys, cb, fHvMemProt);
480 return nemR3DarwinHvSts2Rc(hrc);
481}
482
483
484#if 0 /* unused */
485DECLINLINE(int) nemR3DarwinProtectPage(PVM pVM, RTGCPHYS GCPhys, size_t cb, uint32_t fPageProt)
486{
487 hv_memory_flags_t fHvMemProt = 0;
488 if (fPageProt & NEM_PAGE_PROT_READ)
489 fHvMemProt |= HV_MEMORY_READ;
490 if (fPageProt & NEM_PAGE_PROT_WRITE)
491 fHvMemProt |= HV_MEMORY_WRITE;
492 if (fPageProt & NEM_PAGE_PROT_EXECUTE)
493 fHvMemProt |= HV_MEMORY_EXEC;
494
495 if (pVM->nem.s.fCreatedAsid)
496 hrc = hv_vm_protect_space(pVM->nem.s.uVmAsid, GCPhys, cb, fHvMemProt);
497 else
498 hrc = hv_vm_protect(GCPhys, cb, fHvMemProt);
499
500 return nemR3DarwinHvSts2Rc(hrc);
501}
502#endif
503
504
505DECLINLINE(int) nemR3NativeGCPhys2R3PtrReadOnly(PVM pVM, RTGCPHYS GCPhys, const void **ppv)
506{
507 PGMPAGEMAPLOCK Lock;
508 int rc = PGMPhysGCPhys2CCPtrReadOnly(pVM, GCPhys, ppv, &Lock);
509 if (RT_SUCCESS(rc))
510 PGMPhysReleasePageMappingLock(pVM, &Lock);
511 return rc;
512}
513
514
515DECLINLINE(int) nemR3NativeGCPhys2R3PtrWriteable(PVM pVM, RTGCPHYS GCPhys, void **ppv)
516{
517 PGMPAGEMAPLOCK Lock;
518 int rc = PGMPhysGCPhys2CCPtr(pVM, GCPhys, ppv, &Lock);
519 if (RT_SUCCESS(rc))
520 PGMPhysReleasePageMappingLock(pVM, &Lock);
521 return rc;
522}
523
524
525/**
526 * Worker that maps pages into Hyper-V.
527 *
528 * This is used by the PGM physical page notifications as well as the memory
529 * access VMEXIT handlers.
530 *
531 * @returns VBox status code.
532 * @param pVM The cross context VM structure.
533 * @param pVCpu The cross context virtual CPU structure of the
534 * calling EMT.
535 * @param GCPhysSrc The source page address.
536 * @param GCPhysDst The hyper-V destination page. This may differ from
537 * GCPhysSrc when A20 is disabled.
538 * @param fPageProt NEM_PAGE_PROT_XXX.
539 * @param pu2State Our page state (input/output).
540 * @param fBackingChanged Set if the page backing is being changed.
541 * @thread EMT(pVCpu)
542 */
543NEM_TMPL_STATIC int nemHCNativeSetPhysPage(PVMCC pVM, PVMCPUCC pVCpu, RTGCPHYS GCPhysSrc, RTGCPHYS GCPhysDst,
544 uint32_t fPageProt, uint8_t *pu2State, bool fBackingChanged)
545{
546 /*
547 * Looks like we need to unmap a page before we can change the backing
548 * or even modify the protection. This is going to be *REALLY* efficient.
549 * PGM lends us two bits to keep track of the state here.
550 */
551 RT_NOREF(pVCpu);
552 uint8_t const u2OldState = *pu2State;
553 uint8_t const u2NewState = fPageProt & NEM_PAGE_PROT_WRITE ? NEM_DARWIN_PAGE_STATE_WRITABLE
554 : fPageProt & NEM_PAGE_PROT_READ ? NEM_DARWIN_PAGE_STATE_READABLE : NEM_DARWIN_PAGE_STATE_UNMAPPED;
555 if ( fBackingChanged
556 || u2NewState != u2OldState)
557 {
558 if (u2OldState > NEM_DARWIN_PAGE_STATE_UNMAPPED)
559 {
560 int rc = nemR3DarwinUnmap(pVM, GCPhysDst, X86_PAGE_SIZE);
561 if (RT_SUCCESS(rc))
562 {
563 *pu2State = NEM_DARWIN_PAGE_STATE_UNMAPPED;
564 STAM_REL_COUNTER_INC(&pVM->nem.s.StatUnmapPage);
565 if (u2NewState == NEM_DARWIN_PAGE_STATE_UNMAPPED)
566 {
567 Log5(("NEM GPA unmapped/set: %RGp (was %s)\n", GCPhysDst, g_apszPageStates[u2OldState]));
568 return VINF_SUCCESS;
569 }
570 }
571 else
572 {
573 STAM_REL_COUNTER_INC(&pVM->nem.s.StatUnmapPageFailed);
574 LogRel(("nemHCNativeSetPhysPage/unmap: GCPhysDst=%RGp rc=%Rrc\n", GCPhysDst, rc));
575 return VERR_NEM_INIT_FAILED;
576 }
577 }
578 }
579
580 /*
581 * Writeable mapping?
582 */
583 if (fPageProt & NEM_PAGE_PROT_WRITE)
584 {
585 void *pvPage;
586 int rc = nemR3NativeGCPhys2R3PtrWriteable(pVM, GCPhysSrc, &pvPage);
587 if (RT_SUCCESS(rc))
588 {
589 rc = nemR3DarwinMap(pVM, GCPhysDst, pvPage, X86_PAGE_SIZE, NEM_PAGE_PROT_READ | NEM_PAGE_PROT_WRITE | NEM_PAGE_PROT_EXECUTE);
590 if (RT_SUCCESS(rc))
591 {
592 *pu2State = NEM_DARWIN_PAGE_STATE_WRITABLE;
593 STAM_REL_COUNTER_INC(&pVM->nem.s.StatMapPage);
594 Log5(("NEM GPA mapped/set: %RGp %s (was %s)\n", GCPhysDst, g_apszPageStates[u2NewState], g_apszPageStates[u2OldState]));
595 return VINF_SUCCESS;
596 }
597 STAM_REL_COUNTER_INC(&pVM->nem.s.StatMapPageFailed);
598 LogRel(("nemHCNativeSetPhysPage/writable: GCPhysDst=%RGp rc=%Rrc\n", GCPhysDst));
599 return VERR_NEM_INIT_FAILED;
600 }
601 LogRel(("nemHCNativeSetPhysPage/writable: GCPhysSrc=%RGp rc=%Rrc\n", GCPhysSrc, rc));
602 return rc;
603 }
604
605 if (fPageProt & NEM_PAGE_PROT_READ)
606 {
607 const void *pvPage;
608 int rc = nemR3NativeGCPhys2R3PtrReadOnly(pVM, GCPhysSrc, &pvPage);
609 if (RT_SUCCESS(rc))
610 {
611 rc = nemR3DarwinMap(pVM, GCPhysDst, (void *)pvPage, X86_PAGE_SIZE, NEM_PAGE_PROT_READ | NEM_PAGE_PROT_EXECUTE);
612 if (RT_SUCCESS(rc))
613 {
614 *pu2State = NEM_DARWIN_PAGE_STATE_READABLE;
615 STAM_REL_COUNTER_INC(&pVM->nem.s.StatMapPage);
616 Log5(("NEM GPA mapped/set: %RGp %s (was %s)\n", GCPhysDst, g_apszPageStates[u2NewState], g_apszPageStates[u2OldState]));
617 return VINF_SUCCESS;
618 }
619 STAM_REL_COUNTER_INC(&pVM->nem.s.StatMapPageFailed);
620 LogRel(("nemHCNativeSetPhysPage/readonly: GCPhysDst=%RGp rc=%Rrc\n", GCPhysDst, rc));
621 return VERR_NEM_INIT_FAILED;
622 }
623 LogRel(("nemHCNativeSetPhysPage/readonly: GCPhysSrc=%RGp rc=%Rrc\n", GCPhysSrc, rc));
624 return rc;
625 }
626
627 /* We already unmapped it above. */
628 *pu2State = NEM_DARWIN_PAGE_STATE_UNMAPPED;
629 return VINF_SUCCESS;
630}
631
632
633#ifdef LOG_ENABLED
634/**
635 * Logs the current CPU state.
636 */
637static void nemR3DarwinLogState(PVMCC pVM, PVMCPUCC pVCpu)
638{
639 if (LogIs3Enabled())
640 {
641#if 0
642 char szRegs[4096];
643 DBGFR3RegPrintf(pVM->pUVM, pVCpu->idCpu, &szRegs[0], sizeof(szRegs),
644 "rax=%016VR{rax} rbx=%016VR{rbx} rcx=%016VR{rcx} rdx=%016VR{rdx}\n"
645 "rsi=%016VR{rsi} rdi=%016VR{rdi} r8 =%016VR{r8} r9 =%016VR{r9}\n"
646 "r10=%016VR{r10} r11=%016VR{r11} r12=%016VR{r12} r13=%016VR{r13}\n"
647 "r14=%016VR{r14} r15=%016VR{r15} %VRF{rflags}\n"
648 "rip=%016VR{rip} rsp=%016VR{rsp} rbp=%016VR{rbp}\n"
649 "cs={%04VR{cs} base=%016VR{cs_base} limit=%08VR{cs_lim} flags=%04VR{cs_attr}} cr0=%016VR{cr0}\n"
650 "ds={%04VR{ds} base=%016VR{ds_base} limit=%08VR{ds_lim} flags=%04VR{ds_attr}} cr2=%016VR{cr2}\n"
651 "es={%04VR{es} base=%016VR{es_base} limit=%08VR{es_lim} flags=%04VR{es_attr}} cr3=%016VR{cr3}\n"
652 "fs={%04VR{fs} base=%016VR{fs_base} limit=%08VR{fs_lim} flags=%04VR{fs_attr}} cr4=%016VR{cr4}\n"
653 "gs={%04VR{gs} base=%016VR{gs_base} limit=%08VR{gs_lim} flags=%04VR{gs_attr}} cr8=%016VR{cr8}\n"
654 "ss={%04VR{ss} base=%016VR{ss_base} limit=%08VR{ss_lim} flags=%04VR{ss_attr}}\n"
655 "dr0=%016VR{dr0} dr1=%016VR{dr1} dr2=%016VR{dr2} dr3=%016VR{dr3}\n"
656 "dr6=%016VR{dr6} dr7=%016VR{dr7}\n"
657 "gdtr=%016VR{gdtr_base}:%04VR{gdtr_lim} idtr=%016VR{idtr_base}:%04VR{idtr_lim} rflags=%08VR{rflags}\n"
658 "ldtr={%04VR{ldtr} base=%016VR{ldtr_base} limit=%08VR{ldtr_lim} flags=%08VR{ldtr_attr}}\n"
659 "tr ={%04VR{tr} base=%016VR{tr_base} limit=%08VR{tr_lim} flags=%08VR{tr_attr}}\n"
660 " sysenter={cs=%04VR{sysenter_cs} eip=%08VR{sysenter_eip} esp=%08VR{sysenter_esp}}\n"
661 " efer=%016VR{efer}\n"
662 " pat=%016VR{pat}\n"
663 " sf_mask=%016VR{sf_mask}\n"
664 "krnl_gs_base=%016VR{krnl_gs_base}\n"
665 " lstar=%016VR{lstar}\n"
666 " star=%016VR{star} cstar=%016VR{cstar}\n"
667 "fcw=%04VR{fcw} fsw=%04VR{fsw} ftw=%04VR{ftw} mxcsr=%04VR{mxcsr} mxcsr_mask=%04VR{mxcsr_mask}\n"
668 );
669
670 char szInstr[256];
671 DBGFR3DisasInstrEx(pVM->pUVM, pVCpu->idCpu, 0, 0,
672 DBGF_DISAS_FLAGS_CURRENT_GUEST | DBGF_DISAS_FLAGS_DEFAULT_MODE,
673 szInstr, sizeof(szInstr), NULL);
674 Log3(("%s%s\n", szRegs, szInstr));
675#else
676 RT_NOREF(pVM, pVCpu);
677#endif
678 }
679}
680#endif /* LOG_ENABLED */
681
682
683DECLINLINE(int) nemR3DarwinReadVmcs16(PVMCPUCC pVCpu, uint32_t uFieldEnc, uint16_t *pData)
684{
685 uint64_t u64Data;
686 hv_return_t hrc = hv_vmx_vcpu_read_vmcs(pVCpu->nem.s.hVCpuId, uFieldEnc, &u64Data);
687 if (RT_LIKELY(hrc == HV_SUCCESS))
688 {
689 *pData = (uint16_t)u64Data;
690 return VINF_SUCCESS;
691 }
692
693 return nemR3DarwinHvSts2Rc(hrc);
694}
695
696
697DECLINLINE(int) nemR3DarwinReadVmcs32(PVMCPUCC pVCpu, uint32_t uFieldEnc, uint32_t *pData)
698{
699 uint64_t u64Data;
700 hv_return_t hrc = hv_vmx_vcpu_read_vmcs(pVCpu->nem.s.hVCpuId, uFieldEnc, &u64Data);
701 if (RT_LIKELY(hrc == HV_SUCCESS))
702 {
703 *pData = (uint32_t)u64Data;
704 return VINF_SUCCESS;
705 }
706
707 return nemR3DarwinHvSts2Rc(hrc);
708}
709
710
711DECLINLINE(int) nemR3DarwinReadVmcs64(PVMCPUCC pVCpu, uint32_t uFieldEnc, uint64_t *pData)
712{
713 hv_return_t hrc = hv_vmx_vcpu_read_vmcs(pVCpu->nem.s.hVCpuId, uFieldEnc, pData);
714 if (RT_LIKELY(hrc == HV_SUCCESS))
715 return VINF_SUCCESS;
716
717 return nemR3DarwinHvSts2Rc(hrc);
718}
719
720
721DECLINLINE(int) nemR3DarwinWriteVmcs16(PVMCPUCC pVCpu, uint32_t uFieldEnc, uint16_t u16Val)
722{
723 hv_return_t hrc = hv_vmx_vcpu_write_vmcs(pVCpu->nem.s.hVCpuId, uFieldEnc, u16Val);
724 if (RT_LIKELY(hrc == HV_SUCCESS))
725 return VINF_SUCCESS;
726
727 return nemR3DarwinHvSts2Rc(hrc);
728}
729
730
731DECLINLINE(int) nemR3DarwinWriteVmcs32(PVMCPUCC pVCpu, uint32_t uFieldEnc, uint32_t u32Val)
732{
733 hv_return_t hrc = hv_vmx_vcpu_write_vmcs(pVCpu->nem.s.hVCpuId, uFieldEnc, u32Val);
734 if (RT_LIKELY(hrc == HV_SUCCESS))
735 return VINF_SUCCESS;
736
737 return nemR3DarwinHvSts2Rc(hrc);
738}
739
740
741DECLINLINE(int) nemR3DarwinWriteVmcs64(PVMCPUCC pVCpu, uint32_t uFieldEnc, uint64_t u64Val)
742{
743 hv_return_t hrc = hv_vmx_vcpu_write_vmcs(pVCpu->nem.s.hVCpuId, uFieldEnc, u64Val);
744 if (RT_LIKELY(hrc == HV_SUCCESS))
745 return VINF_SUCCESS;
746
747 return nemR3DarwinHvSts2Rc(hrc);
748}
749
750DECLINLINE(int) nemR3DarwinMsrRead(PVMCPUCC pVCpu, uint32_t idMsr, uint64_t *pu64Val)
751{
752 hv_return_t hrc = hv_vcpu_read_msr(pVCpu->nem.s.hVCpuId, idMsr, pu64Val);
753 if (RT_LIKELY(hrc == HV_SUCCESS))
754 return VINF_SUCCESS;
755
756 return nemR3DarwinHvSts2Rc(hrc);
757}
758
759#if 0 /*unused*/
760DECLINLINE(int) nemR3DarwinMsrWrite(PVMCPUCC pVCpu, uint32_t idMsr, uint64_t u64Val)
761{
762 hv_return_t hrc = hv_vcpu_write_msr(pVCpu->nem.s.hVCpuId, idMsr, u64Val);
763 if (RT_LIKELY(hrc == HV_SUCCESS))
764 return VINF_SUCCESS;
765
766 return nemR3DarwinHvSts2Rc(hrc);
767}
768#endif
769
770static int nemR3DarwinCopyStateFromHv(PVMCC pVM, PVMCPUCC pVCpu, uint64_t fWhat)
771{
772#define READ_GREG(a_GReg, a_Value) \
773 do \
774 { \
775 hrc = hv_vcpu_read_register(pVCpu->nem.s.hVCpuId, (a_GReg), &(a_Value)); \
776 if (RT_LIKELY(hrc == HV_SUCCESS)) \
777 { /* likely */ } \
778 else \
779 return VERR_INTERNAL_ERROR; \
780 } while(0)
781#define READ_VMCS_FIELD(a_Field, a_Value) \
782 do \
783 { \
784 hrc = hv_vmx_vcpu_read_vmcs(pVCpu->nem.s.hVCpuId, (a_Field), &(a_Value)); \
785 if (RT_LIKELY(hrc == HV_SUCCESS)) \
786 { /* likely */ } \
787 else \
788 return VERR_INTERNAL_ERROR; \
789 } while(0)
790#define READ_VMCS16_FIELD(a_Field, a_Value) \
791 do \
792 { \
793 uint64_t u64Data; \
794 hrc = hv_vmx_vcpu_read_vmcs(pVCpu->nem.s.hVCpuId, (a_Field), &u64Data); \
795 if (RT_LIKELY(hrc == HV_SUCCESS)) \
796 { (a_Value) = (uint16_t)u64Data; } \
797 else \
798 return VERR_INTERNAL_ERROR; \
799 } while(0)
800#define READ_VMCS32_FIELD(a_Field, a_Value) \
801 do \
802 { \
803 uint64_t u64Data; \
804 hrc = hv_vmx_vcpu_read_vmcs(pVCpu->nem.s.hVCpuId, (a_Field), &u64Data); \
805 if (RT_LIKELY(hrc == HV_SUCCESS)) \
806 { (a_Value) = (uint32_t)u64Data; } \
807 else \
808 return VERR_INTERNAL_ERROR; \
809 } while(0)
810#define READ_MSR(a_Msr, a_Value) \
811 do \
812 { \
813 hrc = hv_vcpu_read_msr(pVCpu->nem.s.hVCpuId, (a_Msr), &(a_Value)); \
814 if (RT_LIKELY(hrc == HV_SUCCESS)) \
815 { /* likely */ } \
816 else \
817 AssertFailedReturn(VERR_INTERNAL_ERROR); \
818 } while(0)
819
820 STAM_PROFILE_ADV_START(&pVCpu->nem.s.StatProfGstStateImport, x);
821
822 RT_NOREF(pVM);
823 fWhat &= pVCpu->cpum.GstCtx.fExtrn;
824
825 /* GPRs */
826 hv_return_t hrc;
827 if (fWhat & CPUMCTX_EXTRN_GPRS_MASK)
828 {
829 if (fWhat & CPUMCTX_EXTRN_RAX)
830 READ_GREG(HV_X86_RAX, pVCpu->cpum.GstCtx.rax);
831 if (fWhat & CPUMCTX_EXTRN_RCX)
832 READ_GREG(HV_X86_RCX, pVCpu->cpum.GstCtx.rcx);
833 if (fWhat & CPUMCTX_EXTRN_RDX)
834 READ_GREG(HV_X86_RDX, pVCpu->cpum.GstCtx.rdx);
835 if (fWhat & CPUMCTX_EXTRN_RBX)
836 READ_GREG(HV_X86_RBX, pVCpu->cpum.GstCtx.rbx);
837 if (fWhat & CPUMCTX_EXTRN_RSP)
838 READ_GREG(HV_X86_RSP, pVCpu->cpum.GstCtx.rsp);
839 if (fWhat & CPUMCTX_EXTRN_RBP)
840 READ_GREG(HV_X86_RBP, pVCpu->cpum.GstCtx.rbp);
841 if (fWhat & CPUMCTX_EXTRN_RSI)
842 READ_GREG(HV_X86_RSI, pVCpu->cpum.GstCtx.rsi);
843 if (fWhat & CPUMCTX_EXTRN_RDI)
844 READ_GREG(HV_X86_RDI, pVCpu->cpum.GstCtx.rdi);
845 if (fWhat & CPUMCTX_EXTRN_R8_R15)
846 {
847 READ_GREG(HV_X86_R8, pVCpu->cpum.GstCtx.r8);
848 READ_GREG(HV_X86_R9, pVCpu->cpum.GstCtx.r9);
849 READ_GREG(HV_X86_R10, pVCpu->cpum.GstCtx.r10);
850 READ_GREG(HV_X86_R11, pVCpu->cpum.GstCtx.r11);
851 READ_GREG(HV_X86_R12, pVCpu->cpum.GstCtx.r12);
852 READ_GREG(HV_X86_R13, pVCpu->cpum.GstCtx.r13);
853 READ_GREG(HV_X86_R14, pVCpu->cpum.GstCtx.r14);
854 READ_GREG(HV_X86_R15, pVCpu->cpum.GstCtx.r15);
855 }
856 }
857
858 /* RIP & Flags */
859 if (fWhat & CPUMCTX_EXTRN_RIP)
860 READ_GREG(HV_X86_RIP, pVCpu->cpum.GstCtx.rip);
861 if (fWhat & CPUMCTX_EXTRN_RFLAGS)
862 READ_GREG(HV_X86_RFLAGS, pVCpu->cpum.GstCtx.rflags.u);
863
864 /* Segments */
865#define READ_SEG(a_SReg, a_enmName) \
866 do { \
867 READ_VMCS16_FIELD(VMX_VMCS16_GUEST_ ## a_enmName ## _SEL, (a_SReg).Sel); \
868 READ_VMCS32_FIELD(VMX_VMCS32_GUEST_ ## a_enmName ## _LIMIT, (a_SReg).u32Limit); \
869 READ_VMCS32_FIELD(VMX_VMCS32_GUEST_ ## a_enmName ## _ACCESS_RIGHTS, (a_SReg).Attr.u); \
870 READ_VMCS_FIELD(VMX_VMCS_GUEST_ ## a_enmName ## _BASE, (a_SReg).u64Base); \
871 (a_SReg).ValidSel = (a_SReg).Sel; \
872 } while (0)
873 if (fWhat & CPUMCTX_EXTRN_SREG_MASK)
874 {
875 if (fWhat & CPUMCTX_EXTRN_ES)
876 READ_SEG(pVCpu->cpum.GstCtx.es, ES);
877 if (fWhat & CPUMCTX_EXTRN_CS)
878 READ_SEG(pVCpu->cpum.GstCtx.cs, CS);
879 if (fWhat & CPUMCTX_EXTRN_SS)
880 READ_SEG(pVCpu->cpum.GstCtx.ss, SS);
881 if (fWhat & CPUMCTX_EXTRN_DS)
882 READ_SEG(pVCpu->cpum.GstCtx.ds, DS);
883 if (fWhat & CPUMCTX_EXTRN_FS)
884 READ_SEG(pVCpu->cpum.GstCtx.fs, FS);
885 if (fWhat & CPUMCTX_EXTRN_GS)
886 READ_SEG(pVCpu->cpum.GstCtx.gs, GS);
887 }
888
889 /* Descriptor tables and the task segment. */
890 if (fWhat & CPUMCTX_EXTRN_TABLE_MASK)
891 {
892 if (fWhat & CPUMCTX_EXTRN_LDTR)
893 READ_SEG(pVCpu->cpum.GstCtx.ldtr, LDTR);
894
895 if (fWhat & CPUMCTX_EXTRN_TR)
896 {
897 /* AMD-V likes loading TR with in AVAIL state, whereas intel insists on BUSY. So,
898 avoid to trigger sanity assertions around the code, always fix this. */
899 READ_SEG(pVCpu->cpum.GstCtx.tr, TR);
900 switch (pVCpu->cpum.GstCtx.tr.Attr.n.u4Type)
901 {
902 case X86_SEL_TYPE_SYS_386_TSS_BUSY:
903 case X86_SEL_TYPE_SYS_286_TSS_BUSY:
904 break;
905 case X86_SEL_TYPE_SYS_386_TSS_AVAIL:
906 pVCpu->cpum.GstCtx.tr.Attr.n.u4Type = X86_SEL_TYPE_SYS_386_TSS_BUSY;
907 break;
908 case X86_SEL_TYPE_SYS_286_TSS_AVAIL:
909 pVCpu->cpum.GstCtx.tr.Attr.n.u4Type = X86_SEL_TYPE_SYS_286_TSS_BUSY;
910 break;
911 }
912 }
913 if (fWhat & CPUMCTX_EXTRN_IDTR)
914 {
915 READ_VMCS32_FIELD(VMX_VMCS32_GUEST_IDTR_LIMIT, pVCpu->cpum.GstCtx.idtr.cbIdt);
916 READ_VMCS_FIELD(VMX_VMCS_GUEST_IDTR_BASE, pVCpu->cpum.GstCtx.idtr.pIdt);
917 }
918 if (fWhat & CPUMCTX_EXTRN_GDTR)
919 {
920 READ_VMCS32_FIELD(VMX_VMCS32_GUEST_GDTR_LIMIT, pVCpu->cpum.GstCtx.gdtr.cbGdt);
921 READ_VMCS_FIELD(VMX_VMCS_GUEST_GDTR_BASE, pVCpu->cpum.GstCtx.gdtr.pGdt);
922 }
923 }
924
925 /* Control registers. */
926 bool fMaybeChangedMode = false;
927 bool fUpdateCr3 = false;
928 if (fWhat & CPUMCTX_EXTRN_CR_MASK)
929 {
930 uint64_t u64CrTmp = 0;
931
932 if (fWhat & CPUMCTX_EXTRN_CR0)
933 {
934 READ_GREG(HV_X86_CR0, u64CrTmp);
935 if (pVCpu->cpum.GstCtx.cr0 != u64CrTmp)
936 {
937 CPUMSetGuestCR0(pVCpu, u64CrTmp);
938 fMaybeChangedMode = true;
939 }
940 }
941 if (fWhat & CPUMCTX_EXTRN_CR2)
942 READ_GREG(HV_X86_CR2, pVCpu->cpum.GstCtx.cr2);
943 if (fWhat & CPUMCTX_EXTRN_CR3)
944 {
945 READ_GREG(HV_X86_CR3, u64CrTmp);
946 if (pVCpu->cpum.GstCtx.cr3 != u64CrTmp)
947 {
948 CPUMSetGuestCR3(pVCpu, u64CrTmp);
949 fUpdateCr3 = true;
950 }
951 }
952 if (fWhat & CPUMCTX_EXTRN_CR4)
953 {
954 READ_GREG(HV_X86_CR4, u64CrTmp);
955 u64CrTmp &= ~VMX_V_CR4_FIXED0;
956
957 if (pVCpu->cpum.GstCtx.cr4 != u64CrTmp)
958 {
959 CPUMSetGuestCR4(pVCpu, u64CrTmp);
960 fMaybeChangedMode = true;
961 }
962 }
963 }
964
965#if 0 /* Always done. */
966 if (fWhat & CPUMCTX_EXTRN_APIC_TPR)
967 {
968 uint64_t u64Cr8 = 0;
969
970 READ_GREG(HV_X86_TPR, u64Cr8);
971 APICSetTpr(pVCpu, u64Cr8 << 4);
972 }
973#endif
974
975 if (fWhat & CPUMCTX_EXTRN_XCRx)
976 READ_GREG(HV_X86_XCR0, pVCpu->cpum.GstCtx.aXcr[0]);
977
978 /* Debug registers. */
979 if (fWhat & CPUMCTX_EXTRN_DR7)
980 {
981 uint64_t u64Dr7;
982 READ_GREG(HV_X86_DR7, u64Dr7);
983 if (pVCpu->cpum.GstCtx.dr[7] != u64Dr7)
984 CPUMSetGuestDR7(pVCpu, u64Dr7);
985 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_DR7; /* Hack alert! Avoids asserting when processing CPUMCTX_EXTRN_DR0_DR3. */
986 }
987 if (fWhat & CPUMCTX_EXTRN_DR0_DR3)
988 {
989 uint64_t u64DrTmp;
990
991 READ_GREG(HV_X86_DR0, u64DrTmp);
992 if (pVCpu->cpum.GstCtx.dr[0] != u64DrTmp)
993 CPUMSetGuestDR0(pVCpu, u64DrTmp);
994 READ_GREG(HV_X86_DR1, u64DrTmp);
995 if (pVCpu->cpum.GstCtx.dr[1] != u64DrTmp)
996 CPUMSetGuestDR1(pVCpu, u64DrTmp);
997 READ_GREG(HV_X86_DR2, u64DrTmp);
998 if (pVCpu->cpum.GstCtx.dr[2] != u64DrTmp)
999 CPUMSetGuestDR2(pVCpu, u64DrTmp);
1000 READ_GREG(HV_X86_DR3, u64DrTmp);
1001 if (pVCpu->cpum.GstCtx.dr[3] != u64DrTmp)
1002 CPUMSetGuestDR3(pVCpu, u64DrTmp);
1003 }
1004 if (fWhat & CPUMCTX_EXTRN_DR6)
1005 {
1006 uint64_t u64Dr6;
1007 READ_GREG(HV_X86_DR6, u64Dr6);
1008 if (pVCpu->cpum.GstCtx.dr[6] != u64Dr6)
1009 CPUMSetGuestDR6(pVCpu, u64Dr6);
1010 }
1011
1012 if (fWhat & (CPUMCTX_EXTRN_X87 | CPUMCTX_EXTRN_SSE_AVX))
1013 {
1014 hrc = hv_vcpu_read_fpstate(pVCpu->nem.s.hVCpuId, &pVCpu->cpum.GstCtx.XState, sizeof(pVCpu->cpum.GstCtx.XState));
1015 if (hrc == HV_SUCCESS)
1016 { /* likely */ }
1017 else
1018 {
1019 STAM_PROFILE_ADV_STOP(&pVCpu->nem.s.StatProfGstStateImport, x);
1020 return nemR3DarwinHvSts2Rc(hrc);
1021 }
1022 }
1023
1024 /* MSRs */
1025 if (fWhat & CPUMCTX_EXTRN_EFER)
1026 {
1027 uint64_t u64Efer;
1028
1029 READ_VMCS_FIELD(VMX_VMCS64_GUEST_EFER_FULL, u64Efer);
1030 if (u64Efer != pVCpu->cpum.GstCtx.msrEFER)
1031 {
1032 Log7(("NEM/%u: MSR EFER changed %RX64 -> %RX64\n", pVCpu->idCpu, pVCpu->cpum.GstCtx.msrEFER, u64Efer));
1033 if ((u64Efer ^ pVCpu->cpum.GstCtx.msrEFER) & MSR_K6_EFER_NXE)
1034 PGMNotifyNxeChanged(pVCpu, RT_BOOL(u64Efer & MSR_K6_EFER_NXE));
1035 pVCpu->cpum.GstCtx.msrEFER = u64Efer;
1036 fMaybeChangedMode = true;
1037 }
1038 }
1039
1040 if (fWhat & CPUMCTX_EXTRN_KERNEL_GS_BASE)
1041 READ_MSR(MSR_K8_KERNEL_GS_BASE, pVCpu->cpum.GstCtx.msrKERNELGSBASE);
1042 if (fWhat & CPUMCTX_EXTRN_SYSENTER_MSRS)
1043 {
1044 uint64_t u64Tmp;
1045 READ_MSR(MSR_IA32_SYSENTER_EIP, u64Tmp);
1046 pVCpu->cpum.GstCtx.SysEnter.eip = u64Tmp;
1047 READ_MSR(MSR_IA32_SYSENTER_ESP, u64Tmp);
1048 pVCpu->cpum.GstCtx.SysEnter.esp = u64Tmp;
1049 READ_MSR(MSR_IA32_SYSENTER_CS, u64Tmp);
1050 pVCpu->cpum.GstCtx.SysEnter.cs = u64Tmp;
1051 }
1052 if (fWhat & CPUMCTX_EXTRN_SYSCALL_MSRS)
1053 {
1054 READ_MSR(MSR_K6_STAR, pVCpu->cpum.GstCtx.msrSTAR);
1055 READ_MSR(MSR_K8_LSTAR, pVCpu->cpum.GstCtx.msrLSTAR);
1056 READ_MSR(MSR_K8_CSTAR, pVCpu->cpum.GstCtx.msrCSTAR);
1057 READ_MSR(MSR_K8_SF_MASK, pVCpu->cpum.GstCtx.msrSFMASK);
1058 }
1059#if 0
1060 if (fWhat & CPUMCTX_EXTRN_OTHER_MSRS)
1061 {
1062 Assert(aenmNames[iReg] == WHvX64RegisterApicBase);
1063 const uint64_t uOldBase = APICGetBaseMsrNoCheck(pVCpu);
1064 if (aValues[iReg].Reg64 != uOldBase)
1065 {
1066 Log7(("NEM/%u: MSR APICBase changed %RX64 -> %RX64 (%RX64)\n",
1067 pVCpu->idCpu, uOldBase, aValues[iReg].Reg64, aValues[iReg].Reg64 ^ uOldBase));
1068 int rc2 = APICSetBaseMsr(pVCpu, aValues[iReg].Reg64);
1069 AssertLogRelMsg(rc2 == VINF_SUCCESS, ("%Rrc %RX64\n", rc2, aValues[iReg].Reg64));
1070 }
1071 iReg++;
1072
1073 GET_REG64_LOG7(pVCpu->cpum.GstCtx.msrPAT, WHvX64RegisterPat, "MSR PAT");
1074#if 0 /*def LOG_ENABLED*/ /** @todo something's wrong with HvX64RegisterMtrrCap? (AMD) */
1075 GET_REG64_LOG7(pVCpu->cpum.GstCtx.msrPAT, WHvX64RegisterMsrMtrrCap);
1076#endif
1077 PCPUMCTXMSRS pCtxMsrs = CPUMQueryGuestCtxMsrsPtr(pVCpu);
1078 GET_REG64_LOG7(pCtxMsrs->msr.MtrrDefType, WHvX64RegisterMsrMtrrDefType, "MSR MTRR_DEF_TYPE");
1079 GET_REG64_LOG7(pCtxMsrs->msr.MtrrFix64K_00000, WHvX64RegisterMsrMtrrFix64k00000, "MSR MTRR_FIX_64K_00000");
1080 GET_REG64_LOG7(pCtxMsrs->msr.MtrrFix16K_80000, WHvX64RegisterMsrMtrrFix16k80000, "MSR MTRR_FIX_16K_80000");
1081 GET_REG64_LOG7(pCtxMsrs->msr.MtrrFix16K_A0000, WHvX64RegisterMsrMtrrFix16kA0000, "MSR MTRR_FIX_16K_A0000");
1082 GET_REG64_LOG7(pCtxMsrs->msr.MtrrFix4K_C0000, WHvX64RegisterMsrMtrrFix4kC0000, "MSR MTRR_FIX_4K_C0000");
1083 GET_REG64_LOG7(pCtxMsrs->msr.MtrrFix4K_C8000, WHvX64RegisterMsrMtrrFix4kC8000, "MSR MTRR_FIX_4K_C8000");
1084 GET_REG64_LOG7(pCtxMsrs->msr.MtrrFix4K_D0000, WHvX64RegisterMsrMtrrFix4kD0000, "MSR MTRR_FIX_4K_D0000");
1085 GET_REG64_LOG7(pCtxMsrs->msr.MtrrFix4K_D8000, WHvX64RegisterMsrMtrrFix4kD8000, "MSR MTRR_FIX_4K_D8000");
1086 GET_REG64_LOG7(pCtxMsrs->msr.MtrrFix4K_E0000, WHvX64RegisterMsrMtrrFix4kE0000, "MSR MTRR_FIX_4K_E0000");
1087 GET_REG64_LOG7(pCtxMsrs->msr.MtrrFix4K_E8000, WHvX64RegisterMsrMtrrFix4kE8000, "MSR MTRR_FIX_4K_E8000");
1088 GET_REG64_LOG7(pCtxMsrs->msr.MtrrFix4K_F0000, WHvX64RegisterMsrMtrrFix4kF0000, "MSR MTRR_FIX_4K_F0000");
1089 GET_REG64_LOG7(pCtxMsrs->msr.MtrrFix4K_F8000, WHvX64RegisterMsrMtrrFix4kF8000, "MSR MTRR_FIX_4K_F8000");
1090 GET_REG64_LOG7(pCtxMsrs->msr.TscAux, WHvX64RegisterTscAux, "MSR TSC_AUX");
1091 /** @todo look for HvX64RegisterIa32MiscEnable and HvX64RegisterIa32FeatureControl? */
1092 }
1093#endif
1094
1095 /* Almost done, just update extrn flags and maybe change PGM mode. */
1096 pVCpu->cpum.GstCtx.fExtrn &= ~fWhat;
1097 if (!(pVCpu->cpum.GstCtx.fExtrn & CPUMCTX_EXTRN_ALL))
1098 pVCpu->cpum.GstCtx.fExtrn = 0;
1099
1100#ifdef LOG_ENABLED
1101 nemR3DarwinLogState(pVM, pVCpu);
1102#endif
1103
1104 /* Typical. */
1105 if (!fMaybeChangedMode && !fUpdateCr3)
1106 {
1107 STAM_PROFILE_ADV_STOP(&pVCpu->nem.s.StatProfGstStateImport, x);
1108 return VINF_SUCCESS;
1109 }
1110
1111 /*
1112 * Slow.
1113 */
1114 if (fMaybeChangedMode)
1115 {
1116 int rc = PGMChangeMode(pVCpu, pVCpu->cpum.GstCtx.cr0, pVCpu->cpum.GstCtx.cr4, pVCpu->cpum.GstCtx.msrEFER,
1117 false /* fForce */);
1118 AssertMsgReturn(rc == VINF_SUCCESS, ("rc=%Rrc\n", rc), RT_FAILURE_NP(rc) ? rc : VERR_NEM_IPE_1);
1119 }
1120
1121 if (fUpdateCr3)
1122 {
1123 int rc = PGMUpdateCR3(pVCpu, pVCpu->cpum.GstCtx.cr3, false /*fPdpesMapped*/);
1124 if (rc == VINF_SUCCESS)
1125 { /* likely */ }
1126 else
1127 AssertMsgFailedReturn(("rc=%Rrc\n", rc), RT_FAILURE_NP(rc) ? rc : VERR_NEM_IPE_2);
1128 }
1129
1130 STAM_PROFILE_ADV_STOP(&pVCpu->nem.s.StatProfGstStateImport, x);
1131
1132 return VINF_SUCCESS;
1133#undef READ_GREG
1134#undef READ_VMCS_FIELD
1135#undef READ_VMCS32_FIELD
1136#undef READ_SEG
1137#undef READ_MSR
1138}
1139
1140
1141/**
1142 * State to pass between nemHCWinHandleMemoryAccess / nemR3WinWHvHandleMemoryAccess
1143 * and nemHCWinHandleMemoryAccessPageCheckerCallback.
1144 */
1145typedef struct NEMHCDARWINHMACPCCSTATE
1146{
1147 /** Input: Write access. */
1148 bool fWriteAccess;
1149 /** Output: Set if we did something. */
1150 bool fDidSomething;
1151 /** Output: Set it we should resume. */
1152 bool fCanResume;
1153} NEMHCDARWINHMACPCCSTATE;
1154
1155/**
1156 * @callback_method_impl{FNPGMPHYSNEMCHECKPAGE,
1157 * Worker for nemR3WinHandleMemoryAccess; pvUser points to a
1158 * NEMHCDARWINHMACPCCSTATE structure. }
1159 */
1160static DECLCALLBACK(int)
1161nemR3DarwinHandleMemoryAccessPageCheckerCallback(PVMCC pVM, PVMCPUCC pVCpu, RTGCPHYS GCPhys, PPGMPHYSNEMPAGEINFO pInfo, void *pvUser)
1162{
1163 NEMHCDARWINHMACPCCSTATE *pState = (NEMHCDARWINHMACPCCSTATE *)pvUser;
1164 pState->fDidSomething = false;
1165 pState->fCanResume = false;
1166
1167 uint8_t u2State = pInfo->u2NemState;
1168
1169 /*
1170 * Consolidate current page state with actual page protection and access type.
1171 * We don't really consider downgrades here, as they shouldn't happen.
1172 */
1173 int rc;
1174 switch (u2State)
1175 {
1176 case NEM_DARWIN_PAGE_STATE_UNMAPPED:
1177 case NEM_DARWIN_PAGE_STATE_NOT_SET:
1178 if (pInfo->fNemProt == NEM_PAGE_PROT_NONE)
1179 {
1180 Log4(("nemR3DarwinHandleMemoryAccessPageCheckerCallback: %RGp - #1\n", GCPhys));
1181 return VINF_SUCCESS;
1182 }
1183
1184 /* Don't bother remapping it if it's a write request to a non-writable page. */
1185 if ( pState->fWriteAccess
1186 && !(pInfo->fNemProt & NEM_PAGE_PROT_WRITE))
1187 {
1188 Log4(("nemR3DarwinHandleMemoryAccessPageCheckerCallback: %RGp - #1w\n", GCPhys));
1189 return VINF_SUCCESS;
1190 }
1191
1192 /* Map the page. */
1193 rc = nemHCNativeSetPhysPage(pVM,
1194 pVCpu,
1195 GCPhys & ~(RTGCPHYS)X86_PAGE_OFFSET_MASK,
1196 GCPhys & ~(RTGCPHYS)X86_PAGE_OFFSET_MASK,
1197 pInfo->fNemProt,
1198 &u2State,
1199 true /*fBackingState*/);
1200 pInfo->u2NemState = u2State;
1201 Log4(("nemR3DarwinHandleMemoryAccessPageCheckerCallback: %RGp - synced => %s + %Rrc\n",
1202 GCPhys, g_apszPageStates[u2State], rc));
1203 pState->fDidSomething = true;
1204 pState->fCanResume = true;
1205 return rc;
1206
1207 case NEM_DARWIN_PAGE_STATE_READABLE:
1208 if ( !(pInfo->fNemProt & NEM_PAGE_PROT_WRITE)
1209 && (pInfo->fNemProt & (NEM_PAGE_PROT_READ | NEM_PAGE_PROT_EXECUTE)))
1210 {
1211 pState->fCanResume = true;
1212 Log4(("nemR3DarwinHandleMemoryAccessPageCheckerCallback: %RGp - #2\n", GCPhys));
1213 return VINF_SUCCESS;
1214 }
1215 break;
1216
1217 case NEM_DARWIN_PAGE_STATE_WRITABLE:
1218 if (pInfo->fNemProt & NEM_PAGE_PROT_WRITE)
1219 {
1220 /* We get spurious EPT exit violations when everything is fine (#3a case) but can resume without issues here... */
1221 pState->fCanResume = true;
1222 if (pInfo->u2OldNemState == NEM_DARWIN_PAGE_STATE_WRITABLE)
1223 Log4(("nemR3DarwinHandleMemoryAccessPageCheckerCallback: %RGp - #3a\n", GCPhys));
1224 else
1225 Log4(("nemR3DarwinHandleMemoryAccessPageCheckerCallback: %RGp - #3b (%s -> %s)\n",
1226 GCPhys, g_apszPageStates[pInfo->u2OldNemState], g_apszPageStates[u2State]));
1227 return VINF_SUCCESS;
1228 }
1229
1230 break;
1231
1232 default:
1233 AssertLogRelMsgFailedReturn(("u2State=%#x\n", u2State), VERR_NEM_IPE_4);
1234 }
1235
1236 /*
1237 * Unmap and restart the instruction.
1238 * If this fails, which it does every so often, just unmap everything for now.
1239 */
1240 rc = nemR3DarwinUnmap(pVM, GCPhys, X86_PAGE_SIZE);
1241 if (RT_SUCCESS(rc))
1242 {
1243 pState->fDidSomething = true;
1244 pState->fCanResume = true;
1245 pInfo->u2NemState = NEM_DARWIN_PAGE_STATE_UNMAPPED;
1246 STAM_REL_COUNTER_INC(&pVM->nem.s.StatUnmapPage);
1247 Log5(("NEM GPA unmapped/exit: %RGp (was %s)\n", GCPhys, g_apszPageStates[u2State]));
1248 return VINF_SUCCESS;
1249 }
1250 STAM_REL_COUNTER_INC(&pVM->nem.s.StatUnmapPageFailed);
1251 LogRel(("nemR3DarwinHandleMemoryAccessPageCheckerCallback/unmap: GCPhysDst=%RGp %s rc=%Rrc\n",
1252 GCPhys, g_apszPageStates[u2State], rc));
1253 return VERR_NEM_UNMAP_PAGES_FAILED;
1254}
1255
1256
1257DECL_FORCE_INLINE(bool) vmxHCShouldSwapEferMsr(PCVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient)
1258{
1259 RT_NOREF(pVCpu, pVmxTransient);
1260 return true;
1261}
1262
1263
1264DECL_FORCE_INLINE(bool) nemR3DarwinIsUnrestrictedGuest(PCVMCC pVM)
1265{
1266 RT_NOREF(pVM);
1267 return true;
1268}
1269
1270
1271DECL_FORCE_INLINE(bool) nemR3DarwinIsNestedPaging(PCVMCC pVM)
1272{
1273 RT_NOREF(pVM);
1274 return true;
1275}
1276
1277
1278DECL_FORCE_INLINE(bool) nemR3DarwinIsPreemptTimerUsed(PCVMCC pVM)
1279{
1280 RT_NOREF(pVM);
1281 return false;
1282}
1283
1284
1285#if 0 /* unused */
1286DECL_FORCE_INLINE(bool) nemR3DarwinIsVmxLbr(PCVMCC pVM)
1287{
1288 RT_NOREF(pVM);
1289 return false;
1290}
1291#endif
1292
1293
1294/*
1295 * Instantiate the code we share with ring-0.
1296 */
1297#define IN_NEM_DARWIN
1298//#define HMVMX_ALWAYS_TRAP_ALL_XCPTS
1299//#define HMVMX_ALWAYS_SYNC_FULL_GUEST_STATE
1300#define VCPU_2_VMXSTATE(a_pVCpu) (a_pVCpu)->nem.s
1301#define VCPU_2_VMXSTATS(a_pVCpu) (*(a_pVCpu)->nem.s.pVmxStats)
1302
1303#define VM_IS_VMX_UNRESTRICTED_GUEST(a_pVM) nemR3DarwinIsUnrestrictedGuest((a_pVM))
1304#define VM_IS_VMX_NESTED_PAGING(a_pVM) nemR3DarwinIsNestedPaging((a_pVM))
1305#define VM_IS_VMX_PREEMPT_TIMER_USED(a_pVM) nemR3DarwinIsPreemptTimerUsed((a_pVM))
1306#define VM_IS_VMX_LBR(a_pVM) nemR3DarwinIsVmxLbr((a_pVM))
1307
1308#define VMX_VMCS_WRITE_16(a_pVCpu, a_FieldEnc, a_Val) nemR3DarwinWriteVmcs16((a_pVCpu), (a_FieldEnc), (a_Val))
1309#define VMX_VMCS_WRITE_32(a_pVCpu, a_FieldEnc, a_Val) nemR3DarwinWriteVmcs32((a_pVCpu), (a_FieldEnc), (a_Val))
1310#define VMX_VMCS_WRITE_64(a_pVCpu, a_FieldEnc, a_Val) nemR3DarwinWriteVmcs64((a_pVCpu), (a_FieldEnc), (a_Val))
1311#define VMX_VMCS_WRITE_NW(a_pVCpu, a_FieldEnc, a_Val) nemR3DarwinWriteVmcs64((a_pVCpu), (a_FieldEnc), (a_Val))
1312
1313#define VMX_VMCS_READ_16(a_pVCpu, a_FieldEnc, a_pVal) nemR3DarwinReadVmcs16((a_pVCpu), (a_FieldEnc), (a_pVal))
1314#define VMX_VMCS_READ_32(a_pVCpu, a_FieldEnc, a_pVal) nemR3DarwinReadVmcs32((a_pVCpu), (a_FieldEnc), (a_pVal))
1315#define VMX_VMCS_READ_64(a_pVCpu, a_FieldEnc, a_pVal) nemR3DarwinReadVmcs64((a_pVCpu), (a_FieldEnc), (a_pVal))
1316#define VMX_VMCS_READ_NW(a_pVCpu, a_FieldEnc, a_pVal) nemR3DarwinReadVmcs64((a_pVCpu), (a_FieldEnc), (a_pVal))
1317
1318#include "../VMMAll/VMXAllTemplate.cpp.h"
1319
1320#undef VMX_VMCS_WRITE_16
1321#undef VMX_VMCS_WRITE_32
1322#undef VMX_VMCS_WRITE_64
1323#undef VMX_VMCS_WRITE_NW
1324
1325#undef VMX_VMCS_READ_16
1326#undef VMX_VMCS_READ_32
1327#undef VMX_VMCS_READ_64
1328#undef VMX_VMCS_READ_NW
1329
1330#undef VM_IS_VMX_PREEMPT_TIMER_USED
1331#undef VM_IS_VMX_NESTED_PAGING
1332#undef VM_IS_VMX_UNRESTRICTED_GUEST
1333#undef VCPU_2_VMXSTATS
1334#undef VCPU_2_VMXSTATE
1335
1336
1337/**
1338 * Exports the guest GP registers to HV for execution.
1339 *
1340 * @returns VBox status code.
1341 * @param pVCpu The cross context virtual CPU structure of the
1342 * calling EMT.
1343 */
1344static int nemR3DarwinExportGuestGprs(PVMCPUCC pVCpu)
1345{
1346#define WRITE_GREG(a_GReg, a_Value) \
1347 do \
1348 { \
1349 hv_return_t hrc = hv_vcpu_write_register(pVCpu->nem.s.hVCpuId, (a_GReg), (a_Value)); \
1350 if (RT_LIKELY(hrc == HV_SUCCESS)) \
1351 { /* likely */ } \
1352 else \
1353 return VERR_INTERNAL_ERROR; \
1354 } while(0)
1355
1356 uint64_t fCtxChanged = ASMAtomicUoReadU64(&pVCpu->nem.s.fCtxChanged);
1357 if (fCtxChanged & HM_CHANGED_GUEST_GPRS_MASK)
1358 {
1359 if (fCtxChanged & HM_CHANGED_GUEST_RAX)
1360 WRITE_GREG(HV_X86_RAX, pVCpu->cpum.GstCtx.rax);
1361 if (fCtxChanged & HM_CHANGED_GUEST_RCX)
1362 WRITE_GREG(HV_X86_RCX, pVCpu->cpum.GstCtx.rcx);
1363 if (fCtxChanged & HM_CHANGED_GUEST_RDX)
1364 WRITE_GREG(HV_X86_RDX, pVCpu->cpum.GstCtx.rdx);
1365 if (fCtxChanged & HM_CHANGED_GUEST_RBX)
1366 WRITE_GREG(HV_X86_RBX, pVCpu->cpum.GstCtx.rbx);
1367 if (fCtxChanged & HM_CHANGED_GUEST_RSP)
1368 WRITE_GREG(HV_X86_RSP, pVCpu->cpum.GstCtx.rsp);
1369 if (fCtxChanged & HM_CHANGED_GUEST_RBP)
1370 WRITE_GREG(HV_X86_RBP, pVCpu->cpum.GstCtx.rbp);
1371 if (fCtxChanged & HM_CHANGED_GUEST_RSI)
1372 WRITE_GREG(HV_X86_RSI, pVCpu->cpum.GstCtx.rsi);
1373 if (fCtxChanged & HM_CHANGED_GUEST_RDI)
1374 WRITE_GREG(HV_X86_RDI, pVCpu->cpum.GstCtx.rdi);
1375 if (fCtxChanged & HM_CHANGED_GUEST_R8_R15)
1376 {
1377 WRITE_GREG(HV_X86_R8, pVCpu->cpum.GstCtx.r8);
1378 WRITE_GREG(HV_X86_R9, pVCpu->cpum.GstCtx.r9);
1379 WRITE_GREG(HV_X86_R10, pVCpu->cpum.GstCtx.r10);
1380 WRITE_GREG(HV_X86_R11, pVCpu->cpum.GstCtx.r11);
1381 WRITE_GREG(HV_X86_R12, pVCpu->cpum.GstCtx.r12);
1382 WRITE_GREG(HV_X86_R13, pVCpu->cpum.GstCtx.r13);
1383 WRITE_GREG(HV_X86_R14, pVCpu->cpum.GstCtx.r14);
1384 WRITE_GREG(HV_X86_R15, pVCpu->cpum.GstCtx.r15);
1385 }
1386
1387 ASMAtomicUoAndU64(&pVCpu->nem.s.fCtxChanged, ~HM_CHANGED_GUEST_GPRS_MASK);
1388 }
1389
1390 if (fCtxChanged & HM_CHANGED_GUEST_CR2)
1391 {
1392 WRITE_GREG(HV_X86_CR2, pVCpu->cpum.GstCtx.cr2);
1393 ASMAtomicUoAndU64(&pVCpu->nem.s.fCtxChanged, ~HM_CHANGED_GUEST_CR2);
1394 }
1395
1396 return VINF_SUCCESS;
1397#undef WRITE_GREG
1398}
1399
1400
1401/**
1402 * Converts the given CPUM externalized bitmask to the appropriate HM changed bitmask.
1403 *
1404 * @returns Bitmask of HM changed flags.
1405 * @param fCpumExtrn The CPUM extern bitmask.
1406 */
1407static uint64_t nemR3DarwinCpumExtrnToHmChanged(uint64_t fCpumExtrn)
1408{
1409 uint64_t fHmChanged = 0;
1410
1411 /* Invert to gt a mask of things which are kept in CPUM. */
1412 uint64_t fCpumIntern = ~fCpumExtrn;
1413
1414 if (fCpumIntern & CPUMCTX_EXTRN_GPRS_MASK)
1415 {
1416 if (fCpumIntern & CPUMCTX_EXTRN_RAX)
1417 fHmChanged |= HM_CHANGED_GUEST_RAX;
1418 if (fCpumIntern & CPUMCTX_EXTRN_RCX)
1419 fHmChanged |= HM_CHANGED_GUEST_RCX;
1420 if (fCpumIntern & CPUMCTX_EXTRN_RDX)
1421 fHmChanged |= HM_CHANGED_GUEST_RDX;
1422 if (fCpumIntern & CPUMCTX_EXTRN_RBX)
1423 fHmChanged |= HM_CHANGED_GUEST_RBX;
1424 if (fCpumIntern & CPUMCTX_EXTRN_RSP)
1425 fHmChanged |= HM_CHANGED_GUEST_RSP;
1426 if (fCpumIntern & CPUMCTX_EXTRN_RBP)
1427 fHmChanged |= HM_CHANGED_GUEST_RBP;
1428 if (fCpumIntern & CPUMCTX_EXTRN_RSI)
1429 fHmChanged |= HM_CHANGED_GUEST_RSI;
1430 if (fCpumIntern & CPUMCTX_EXTRN_RDI)
1431 fHmChanged |= HM_CHANGED_GUEST_RDI;
1432 if (fCpumIntern & CPUMCTX_EXTRN_R8_R15)
1433 fHmChanged |= HM_CHANGED_GUEST_R8_R15;
1434 }
1435
1436 /* RIP & Flags */
1437 if (fCpumIntern & CPUMCTX_EXTRN_RIP)
1438 fHmChanged |= HM_CHANGED_GUEST_RIP;
1439 if (fCpumIntern & CPUMCTX_EXTRN_RFLAGS)
1440 fHmChanged |= HM_CHANGED_GUEST_RFLAGS;
1441
1442 /* Segments */
1443 if (fCpumIntern & CPUMCTX_EXTRN_SREG_MASK)
1444 {
1445 if (fCpumIntern & CPUMCTX_EXTRN_ES)
1446 fHmChanged |= HM_CHANGED_GUEST_ES;
1447 if (fCpumIntern & CPUMCTX_EXTRN_CS)
1448 fHmChanged |= HM_CHANGED_GUEST_CS;
1449 if (fCpumIntern & CPUMCTX_EXTRN_SS)
1450 fHmChanged |= HM_CHANGED_GUEST_SS;
1451 if (fCpumIntern & CPUMCTX_EXTRN_DS)
1452 fHmChanged |= HM_CHANGED_GUEST_DS;
1453 if (fCpumIntern & CPUMCTX_EXTRN_FS)
1454 fHmChanged |= HM_CHANGED_GUEST_FS;
1455 if (fCpumIntern & CPUMCTX_EXTRN_GS)
1456 fHmChanged |= HM_CHANGED_GUEST_GS;
1457 }
1458
1459 /* Descriptor tables & task segment. */
1460 if (fCpumIntern & CPUMCTX_EXTRN_TABLE_MASK)
1461 {
1462 if (fCpumIntern & CPUMCTX_EXTRN_LDTR)
1463 fHmChanged |= HM_CHANGED_GUEST_LDTR;
1464 if (fCpumIntern & CPUMCTX_EXTRN_TR)
1465 fHmChanged |= HM_CHANGED_GUEST_TR;
1466 if (fCpumIntern & CPUMCTX_EXTRN_IDTR)
1467 fHmChanged |= HM_CHANGED_GUEST_IDTR;
1468 if (fCpumIntern & CPUMCTX_EXTRN_GDTR)
1469 fHmChanged |= HM_CHANGED_GUEST_GDTR;
1470 }
1471
1472 /* Control registers. */
1473 if (fCpumIntern & CPUMCTX_EXTRN_CR_MASK)
1474 {
1475 if (fCpumIntern & CPUMCTX_EXTRN_CR0)
1476 fHmChanged |= HM_CHANGED_GUEST_CR0;
1477 if (fCpumIntern & CPUMCTX_EXTRN_CR2)
1478 fHmChanged |= HM_CHANGED_GUEST_CR2;
1479 if (fCpumIntern & CPUMCTX_EXTRN_CR3)
1480 fHmChanged |= HM_CHANGED_GUEST_CR3;
1481 if (fCpumIntern & CPUMCTX_EXTRN_CR4)
1482 fHmChanged |= HM_CHANGED_GUEST_CR4;
1483 }
1484 if (fCpumIntern & CPUMCTX_EXTRN_APIC_TPR)
1485 fHmChanged |= HM_CHANGED_GUEST_APIC_TPR;
1486
1487 /* Debug registers. */
1488 if (fCpumIntern & CPUMCTX_EXTRN_DR0_DR3)
1489 fHmChanged |= HM_CHANGED_GUEST_DR0_DR3;
1490 if (fCpumIntern & CPUMCTX_EXTRN_DR6)
1491 fHmChanged |= HM_CHANGED_GUEST_DR6;
1492 if (fCpumIntern & CPUMCTX_EXTRN_DR7)
1493 fHmChanged |= HM_CHANGED_GUEST_DR7;
1494
1495 /* Floating point state. */
1496 if (fCpumIntern & CPUMCTX_EXTRN_X87)
1497 fHmChanged |= HM_CHANGED_GUEST_X87;
1498 if (fCpumIntern & CPUMCTX_EXTRN_SSE_AVX)
1499 fHmChanged |= HM_CHANGED_GUEST_SSE_AVX;
1500 if (fCpumIntern & CPUMCTX_EXTRN_OTHER_XSAVE)
1501 fHmChanged |= HM_CHANGED_GUEST_OTHER_XSAVE;
1502 if (fCpumIntern & CPUMCTX_EXTRN_XCRx)
1503 fHmChanged |= HM_CHANGED_GUEST_XCRx;
1504
1505 /* MSRs */
1506 if (fCpumIntern & CPUMCTX_EXTRN_EFER)
1507 fHmChanged |= HM_CHANGED_GUEST_EFER_MSR;
1508 if (fCpumIntern & CPUMCTX_EXTRN_KERNEL_GS_BASE)
1509 fHmChanged |= HM_CHANGED_GUEST_KERNEL_GS_BASE;
1510 if (fCpumIntern & CPUMCTX_EXTRN_SYSENTER_MSRS)
1511 fHmChanged |= HM_CHANGED_GUEST_SYSENTER_MSR_MASK;
1512 if (fCpumIntern & CPUMCTX_EXTRN_SYSCALL_MSRS)
1513 fHmChanged |= HM_CHANGED_GUEST_SYSCALL_MSRS;
1514 if (fCpumIntern & CPUMCTX_EXTRN_TSC_AUX)
1515 fHmChanged |= HM_CHANGED_GUEST_TSC_AUX;
1516 if (fCpumIntern & CPUMCTX_EXTRN_OTHER_MSRS)
1517 fHmChanged |= HM_CHANGED_GUEST_OTHER_MSRS;
1518
1519 return fHmChanged;
1520}
1521
1522
1523/**
1524 * Exports the guest state to HV for execution.
1525 *
1526 * @returns VBox status code.
1527 * @param pVM The cross context VM structure.
1528 * @param pVCpu The cross context virtual CPU structure of the
1529 * calling EMT.
1530 * @param pVmxTransient The transient VMX structure.
1531 */
1532static int nemR3DarwinExportGuestState(PVMCC pVM, PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
1533{
1534#define WRITE_GREG(a_GReg, a_Value) \
1535 do \
1536 { \
1537 hv_return_t hrc = hv_vcpu_write_register(pVCpu->nem.s.hVCpuId, (a_GReg), (a_Value)); \
1538 if (RT_LIKELY(hrc == HV_SUCCESS)) \
1539 { /* likely */ } \
1540 else \
1541 return VERR_INTERNAL_ERROR; \
1542 } while(0)
1543#define WRITE_VMCS_FIELD(a_Field, a_Value) \
1544 do \
1545 { \
1546 hv_return_t hrc = hv_vmx_vcpu_write_vmcs(pVCpu->nem.s.hVCpuId, (a_Field), (a_Value)); \
1547 if (RT_LIKELY(hrc == HV_SUCCESS)) \
1548 { /* likely */ } \
1549 else \
1550 return VERR_INTERNAL_ERROR; \
1551 } while(0)
1552#define WRITE_MSR(a_Msr, a_Value) \
1553 do \
1554 { \
1555 hv_return_t hrc = hv_vcpu_write_msr(pVCpu->nem.s.hVCpuId, (a_Msr), (a_Value)); \
1556 if (RT_LIKELY(hrc == HV_SUCCESS)) \
1557 { /* likely */ } \
1558 else \
1559 AssertFailedReturn(VERR_INTERNAL_ERROR); \
1560 } while(0)
1561
1562 RT_NOREF(pVM);
1563
1564#ifdef LOG_ENABLED
1565 nemR3DarwinLogState(pVM, pVCpu);
1566#endif
1567
1568 STAM_PROFILE_ADV_START(&pVCpu->nem.s.StatProfGstStateExport, x);
1569
1570 uint64_t const fWhat = ~pVCpu->cpum.GstCtx.fExtrn & CPUMCTX_EXTRN_ALL;
1571 if (!fWhat)
1572 return VINF_SUCCESS;
1573
1574 pVCpu->nem.s.fCtxChanged |= nemR3DarwinCpumExtrnToHmChanged(pVCpu->cpum.GstCtx.fExtrn);
1575
1576 int rc = vmxHCExportGuestEntryExitCtls(pVCpu, pVmxTransient);
1577 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
1578
1579 rc = nemR3DarwinExportGuestGprs(pVCpu);
1580 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
1581
1582 rc = vmxHCExportGuestCR0(pVCpu, pVmxTransient);
1583 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
1584
1585 VBOXSTRICTRC rcStrict = vmxHCExportGuestCR3AndCR4(pVCpu, pVmxTransient);
1586 if (rcStrict == VINF_SUCCESS)
1587 { /* likely */ }
1588 else
1589 {
1590 Assert(rcStrict == VINF_EM_RESCHEDULE_REM || RT_FAILURE_NP(rcStrict));
1591 return VBOXSTRICTRC_VAL(rcStrict);
1592 }
1593
1594 vmxHCExportGuestXcptIntercepts(pVCpu, pVmxTransient);
1595 vmxHCExportGuestRip(pVCpu);
1596 //vmxHCExportGuestRsp(pVCpu);
1597 vmxHCExportGuestRflags(pVCpu, pVmxTransient);
1598
1599 rc = vmxHCExportGuestSegRegsXdtr(pVCpu, pVmxTransient);
1600 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
1601
1602 if (fWhat & CPUMCTX_EXTRN_XCRx)
1603 {
1604 WRITE_GREG(HV_X86_XCR0, pVCpu->cpum.GstCtx.aXcr[0]);
1605 ASMAtomicUoAndU64(&pVCpu->nem.s.fCtxChanged, ~HM_CHANGED_GUEST_XCRx);
1606 }
1607
1608 if (fWhat & CPUMCTX_EXTRN_APIC_TPR)
1609 {
1610 Assert(pVCpu->nem.s.fCtxChanged & HM_CHANGED_GUEST_APIC_TPR);
1611 vmxHCExportGuestApicTpr(pVCpu, pVmxTransient);
1612
1613 rc = APICGetTpr(pVCpu, &pVmxTransient->u8GuestTpr, NULL /*pfPending*/, NULL /*pu8PendingIntr*/);
1614 AssertRC(rc);
1615
1616 WRITE_GREG(HV_X86_TPR, pVmxTransient->u8GuestTpr);
1617 ASMAtomicUoAndU64(&pVCpu->nem.s.fCtxChanged, ~HM_CHANGED_GUEST_APIC_TPR);
1618 }
1619
1620 /* Debug registers. */
1621 if (fWhat & CPUMCTX_EXTRN_DR0_DR3)
1622 {
1623 WRITE_GREG(HV_X86_DR0, pVCpu->cpum.GstCtx.dr[0]); // CPUMGetHyperDR0(pVCpu));
1624 WRITE_GREG(HV_X86_DR1, pVCpu->cpum.GstCtx.dr[1]); // CPUMGetHyperDR1(pVCpu));
1625 WRITE_GREG(HV_X86_DR2, pVCpu->cpum.GstCtx.dr[2]); // CPUMGetHyperDR2(pVCpu));
1626 WRITE_GREG(HV_X86_DR3, pVCpu->cpum.GstCtx.dr[3]); // CPUMGetHyperDR3(pVCpu));
1627 ASMAtomicUoAndU64(&pVCpu->nem.s.fCtxChanged, ~HM_CHANGED_GUEST_DR0_DR3);
1628 }
1629 if (fWhat & CPUMCTX_EXTRN_DR6)
1630 {
1631 WRITE_GREG(HV_X86_DR6, pVCpu->cpum.GstCtx.dr[6]); // CPUMGetHyperDR6(pVCpu));
1632 ASMAtomicUoAndU64(&pVCpu->nem.s.fCtxChanged, ~HM_CHANGED_GUEST_DR6);
1633 }
1634 if (fWhat & CPUMCTX_EXTRN_DR7)
1635 {
1636 WRITE_GREG(HV_X86_DR7, pVCpu->cpum.GstCtx.dr[7]); // CPUMGetHyperDR7(pVCpu));
1637 ASMAtomicUoAndU64(&pVCpu->nem.s.fCtxChanged, ~HM_CHANGED_GUEST_DR7);
1638 }
1639
1640 if (fWhat & (CPUMCTX_EXTRN_X87 | CPUMCTX_EXTRN_SSE_AVX | CPUMCTX_EXTRN_OTHER_XSAVE))
1641 {
1642 hv_return_t hrc = hv_vcpu_write_fpstate(pVCpu->nem.s.hVCpuId, &pVCpu->cpum.GstCtx.XState, sizeof(pVCpu->cpum.GstCtx.XState));
1643 if (hrc == HV_SUCCESS)
1644 { /* likely */ }
1645 else
1646 return nemR3DarwinHvSts2Rc(hrc);
1647
1648 ASMAtomicUoAndU64(&pVCpu->nem.s.fCtxChanged, ~(HM_CHANGED_GUEST_X87 | HM_CHANGED_GUEST_SSE_AVX | CPUMCTX_EXTRN_OTHER_XSAVE));
1649 }
1650
1651 /* MSRs */
1652 if (fWhat & CPUMCTX_EXTRN_EFER)
1653 {
1654 WRITE_VMCS_FIELD(VMX_VMCS64_GUEST_EFER_FULL, pVCpu->cpum.GstCtx.msrEFER);
1655 ASMAtomicUoAndU64(&pVCpu->nem.s.fCtxChanged, ~HM_CHANGED_GUEST_EFER_MSR);
1656 }
1657 if (fWhat & CPUMCTX_EXTRN_KERNEL_GS_BASE)
1658 {
1659 WRITE_MSR(MSR_K8_KERNEL_GS_BASE, pVCpu->cpum.GstCtx.msrKERNELGSBASE);
1660 ASMAtomicUoAndU64(&pVCpu->nem.s.fCtxChanged, ~HM_CHANGED_GUEST_KERNEL_GS_BASE);
1661 }
1662 if (fWhat & CPUMCTX_EXTRN_SYSENTER_MSRS)
1663 {
1664 WRITE_MSR(MSR_IA32_SYSENTER_CS, pVCpu->cpum.GstCtx.SysEnter.cs);
1665 WRITE_MSR(MSR_IA32_SYSENTER_EIP, pVCpu->cpum.GstCtx.SysEnter.eip);
1666 WRITE_MSR(MSR_IA32_SYSENTER_ESP, pVCpu->cpum.GstCtx.SysEnter.esp);
1667 ASMAtomicUoAndU64(&pVCpu->nem.s.fCtxChanged, ~HM_CHANGED_GUEST_SYSENTER_MSR_MASK);
1668 }
1669 if (fWhat & CPUMCTX_EXTRN_SYSCALL_MSRS)
1670 {
1671 WRITE_MSR(MSR_K6_STAR, pVCpu->cpum.GstCtx.msrSTAR);
1672 WRITE_MSR(MSR_K8_LSTAR, pVCpu->cpum.GstCtx.msrLSTAR);
1673 WRITE_MSR(MSR_K8_CSTAR, pVCpu->cpum.GstCtx.msrCSTAR);
1674 WRITE_MSR(MSR_K8_SF_MASK, pVCpu->cpum.GstCtx.msrSFMASK);
1675 ASMAtomicUoAndU64(&pVCpu->nem.s.fCtxChanged, ~HM_CHANGED_GUEST_SYSCALL_MSRS);
1676 }
1677 if (fWhat & CPUMCTX_EXTRN_OTHER_MSRS)
1678 {
1679#if 0
1680 hv_return_t hrc = hv_vmx_vcpu_set_apic_address(pVCpu->nem.s.hVCpuId, APICGetBaseMsrNoCheck(pVCpu) & PAGE_BASE_GC_MASK);
1681 if (RT_UNLIKELY(hrc != HV_SUCCESS))
1682 return nemR3DarwinHvSts2Rc(hrc);
1683#endif
1684
1685 ASMAtomicUoAndU64(&pVCpu->nem.s.fCtxChanged, ~HM_CHANGED_GUEST_OTHER_MSRS);
1686
1687#if 0
1688 ADD_REG64(WHvX64RegisterPat, pVCpu->cpum.GstCtx.msrPAT);
1689#if 0 /** @todo check if WHvX64RegisterMsrMtrrCap works here... */
1690 ADD_REG64(WHvX64RegisterMsrMtrrCap, CPUMGetGuestIa32MtrrCap(pVCpu));
1691#endif
1692 PCPUMCTXMSRS pCtxMsrs = CPUMQueryGuestCtxMsrsPtr(pVCpu);
1693 ADD_REG64(WHvX64RegisterMsrMtrrDefType, pCtxMsrs->msr.MtrrDefType);
1694 ADD_REG64(WHvX64RegisterMsrMtrrFix64k00000, pCtxMsrs->msr.MtrrFix64K_00000);
1695 ADD_REG64(WHvX64RegisterMsrMtrrFix16k80000, pCtxMsrs->msr.MtrrFix16K_80000);
1696 ADD_REG64(WHvX64RegisterMsrMtrrFix16kA0000, pCtxMsrs->msr.MtrrFix16K_A0000);
1697 ADD_REG64(WHvX64RegisterMsrMtrrFix4kC0000, pCtxMsrs->msr.MtrrFix4K_C0000);
1698 ADD_REG64(WHvX64RegisterMsrMtrrFix4kC8000, pCtxMsrs->msr.MtrrFix4K_C8000);
1699 ADD_REG64(WHvX64RegisterMsrMtrrFix4kD0000, pCtxMsrs->msr.MtrrFix4K_D0000);
1700 ADD_REG64(WHvX64RegisterMsrMtrrFix4kD8000, pCtxMsrs->msr.MtrrFix4K_D8000);
1701 ADD_REG64(WHvX64RegisterMsrMtrrFix4kE0000, pCtxMsrs->msr.MtrrFix4K_E0000);
1702 ADD_REG64(WHvX64RegisterMsrMtrrFix4kE8000, pCtxMsrs->msr.MtrrFix4K_E8000);
1703 ADD_REG64(WHvX64RegisterMsrMtrrFix4kF0000, pCtxMsrs->msr.MtrrFix4K_F0000);
1704 ADD_REG64(WHvX64RegisterMsrMtrrFix4kF8000, pCtxMsrs->msr.MtrrFix4K_F8000);
1705 ADD_REG64(WHvX64RegisterTscAux, pCtxMsrs->msr.TscAux);
1706#if 0 /** @todo these registers aren't available? Might explain something.. .*/
1707 const CPUMCPUVENDOR enmCpuVendor = CPUMGetHostCpuVendor(pVM);
1708 if (enmCpuVendor != CPUMCPUVENDOR_AMD)
1709 {
1710 ADD_REG64(HvX64RegisterIa32MiscEnable, pCtxMsrs->msr.MiscEnable);
1711 ADD_REG64(HvX64RegisterIa32FeatureControl, CPUMGetGuestIa32FeatureControl(pVCpu));
1712 }
1713#endif
1714#endif
1715 }
1716
1717 WRITE_VMCS_FIELD(VMX_VMCS64_GUEST_DEBUGCTL_FULL, 0 /*MSR_IA32_DEBUGCTL_LBR*/);
1718
1719 hv_vcpu_invalidate_tlb(pVCpu->nem.s.hVCpuId);
1720 hv_vcpu_flush(pVCpu->nem.s.hVCpuId);
1721
1722 pVCpu->cpum.GstCtx.fExtrn |= CPUMCTX_EXTRN_ALL | CPUMCTX_EXTRN_KEEPER_NEM;
1723
1724 /* Clear any bits that may be set but exported unconditionally or unused/reserved bits. */
1725 ASMAtomicUoAndU64(&pVCpu->nem.s.fCtxChanged, ~(
1726 HM_CHANGED_GUEST_TSC_AUX
1727 | HM_CHANGED_GUEST_HWVIRT
1728 | HM_CHANGED_VMX_GUEST_AUTO_MSRS
1729 | HM_CHANGED_VMX_GUEST_LAZY_MSRS
1730 | (HM_CHANGED_KEEPER_STATE_MASK & ~HM_CHANGED_VMX_MASK)));
1731
1732 STAM_PROFILE_ADV_STOP(&pVCpu->nem.s.StatProfGstStateExport, x);
1733 return VINF_SUCCESS;
1734#undef WRITE_GREG
1735#undef WRITE_VMCS_FIELD
1736}
1737
1738
1739/**
1740 * Handles an exit from hv_vcpu_run().
1741 *
1742 * @returns VBox strict status code.
1743 * @param pVM The cross context VM structure.
1744 * @param pVCpu The cross context virtual CPU structure of the
1745 * calling EMT.
1746 * @param pVmxTransient The transient VMX structure.
1747 */
1748static VBOXSTRICTRC nemR3DarwinHandleExit(PVM pVM, PVMCPU pVCpu, PVMXTRANSIENT pVmxTransient)
1749{
1750 uint32_t uExitReason;
1751 int rc = nemR3DarwinReadVmcs32(pVCpu, VMX_VMCS32_RO_EXIT_REASON, &uExitReason);
1752 AssertRC(rc);
1753 pVmxTransient->fVmcsFieldsRead = 0;
1754 pVmxTransient->fIsNestedGuest = false;
1755 pVmxTransient->uExitReason = VMX_EXIT_REASON_BASIC(uExitReason);
1756 pVmxTransient->fVMEntryFailed = VMX_EXIT_REASON_HAS_ENTRY_FAILED(uExitReason);
1757
1758 if (RT_UNLIKELY(pVmxTransient->fVMEntryFailed))
1759 AssertLogRelMsgFailedReturn(("Running guest failed for CPU #%u: %#x %u\n",
1760 pVCpu->idCpu, pVmxTransient->uExitReason, vmxHCCheckGuestState(pVCpu, &pVCpu->nem.s.VmcsInfo)),
1761 VERR_NEM_IPE_0);
1762
1763 /** @todo Only copy the state on demand (the R0 VT-x code saves some stuff unconditionally and the VMX template assumes that
1764 * when handling exits). */
1765 rc = nemR3DarwinCopyStateFromHv(pVM, pVCpu, CPUMCTX_EXTRN_ALL);
1766 AssertRCReturn(rc, rc);
1767
1768 STAM_COUNTER_INC(&pVCpu->nem.s.pVmxStats->aStatExitReason[pVmxTransient->uExitReason & MASK_EXITREASON_STAT]);
1769 STAM_REL_COUNTER_INC(&pVCpu->nem.s.pVmxStats->StatExitAll);
1770
1771#ifndef HMVMX_USE_FUNCTION_TABLE
1772 return vmxHCHandleExit(pVCpu, pVmxTransient);
1773#else
1774 return g_aVMExitHandlers[pVmxTransient->uExitReason].pfn(pVCpu, pVmxTransient);
1775#endif
1776}
1777
1778
1779/**
1780 * Worker for nemR3NativeInit that loads the Hypervisor.framework shared library.
1781 *
1782 * @returns VBox status code.
1783 * @param fForced Whether the HMForced flag is set and we should
1784 * fail if we cannot initialize.
1785 * @param pErrInfo Where to always return error info.
1786 */
1787static int nemR3DarwinLoadHv(bool fForced, PRTERRINFO pErrInfo)
1788{
1789 RTLDRMOD hMod = NIL_RTLDRMOD;
1790 static const char *s_pszHvPath = "/System/Library/Frameworks/Hypervisor.framework/Hypervisor";
1791
1792 int rc = RTLdrLoadEx(s_pszHvPath, &hMod, RTLDRLOAD_FLAGS_NO_UNLOAD | RTLDRLOAD_FLAGS_NO_SUFFIX, pErrInfo);
1793 if (RT_SUCCESS(rc))
1794 {
1795 for (unsigned i = 0; i < RT_ELEMENTS(g_aImports); i++)
1796 {
1797 int rc2 = RTLdrGetSymbol(hMod, g_aImports[i].pszName, (void **)g_aImports[i].ppfn);
1798 if (RT_SUCCESS(rc2))
1799 {
1800 if (g_aImports[i].fOptional)
1801 LogRel(("NEM: info: Found optional import Hypervisor!%s.\n",
1802 g_aImports[i].pszName));
1803 }
1804 else
1805 {
1806 *g_aImports[i].ppfn = NULL;
1807
1808 LogRel(("NEM: %s: Failed to import Hypervisor!%s: %Rrc\n",
1809 g_aImports[i].fOptional ? "info" : fForced ? "fatal" : "error",
1810 g_aImports[i].pszName, rc2));
1811 if (!g_aImports[i].fOptional)
1812 {
1813 if (RTErrInfoIsSet(pErrInfo))
1814 RTErrInfoAddF(pErrInfo, rc2, ", Hypervisor!%s", g_aImports[i].pszName);
1815 else
1816 rc = RTErrInfoSetF(pErrInfo, rc2, "Failed to import: Hypervisor!%s", g_aImports[i].pszName);
1817 Assert(RT_FAILURE(rc));
1818 }
1819 }
1820 }
1821 if (RT_SUCCESS(rc))
1822 {
1823 Assert(!RTErrInfoIsSet(pErrInfo));
1824 }
1825
1826 RTLdrClose(hMod);
1827 }
1828 else
1829 {
1830 RTErrInfoAddF(pErrInfo, rc, "Failed to load Hypervisor.framwork: %s: %Rrc", s_pszHvPath, rc);
1831 rc = VERR_NEM_INIT_FAILED;
1832 }
1833
1834 return rc;
1835}
1836
1837
1838/**
1839 * Read and initialize the global capabilities supported by this CPU.
1840 *
1841 * @returns VBox status code.
1842 */
1843static int nemR3DarwinCapsInit(void)
1844{
1845 RT_ZERO(g_HmMsrs);
1846
1847 hv_return_t hrc = hv_vmx_read_capability(HV_VMX_CAP_PINBASED, &g_HmMsrs.u.vmx.PinCtls.u);
1848 if (hrc == HV_SUCCESS)
1849 hrc = hv_vmx_read_capability(HV_VMX_CAP_PROCBASED, &g_HmMsrs.u.vmx.ProcCtls.u);
1850 if (hrc == HV_SUCCESS)
1851 hrc = hv_vmx_read_capability(HV_VMX_CAP_ENTRY, &g_HmMsrs.u.vmx.EntryCtls.u);
1852 if (hrc == HV_SUCCESS)
1853 hrc = hv_vmx_read_capability(HV_VMX_CAP_EXIT, &g_HmMsrs.u.vmx.ExitCtls.u);
1854 if (hrc == HV_SUCCESS)
1855 {
1856 hrc = hv_vmx_read_capability(HV_VMX_CAP_BASIC, &g_HmMsrs.u.vmx.u64Basic);
1857 if (hrc == HV_SUCCESS)
1858 {
1859 if (hrc == HV_SUCCESS)
1860 hrc = hv_vmx_read_capability(HV_VMX_CAP_MISC, &g_HmMsrs.u.vmx.u64Misc);
1861 if (hrc == HV_SUCCESS)
1862 hrc = hv_vmx_read_capability(HV_VMX_CAP_CR0_FIXED0, &g_HmMsrs.u.vmx.u64Cr0Fixed0);
1863 if (hrc == HV_SUCCESS)
1864 hrc = hv_vmx_read_capability(HV_VMX_CAP_CR0_FIXED1, &g_HmMsrs.u.vmx.u64Cr0Fixed1);
1865 if (hrc == HV_SUCCESS)
1866 hrc = hv_vmx_read_capability(HV_VMX_CAP_CR4_FIXED0, &g_HmMsrs.u.vmx.u64Cr4Fixed0);
1867 if (hrc == HV_SUCCESS)
1868 hrc = hv_vmx_read_capability(HV_VMX_CAP_CR4_FIXED1, &g_HmMsrs.u.vmx.u64Cr4Fixed1);
1869 if (hrc == HV_SUCCESS)
1870 hrc = hv_vmx_read_capability(HV_VMX_CAP_VMCS_ENUM, &g_HmMsrs.u.vmx.u64VmcsEnum);
1871 if ( hrc == HV_SUCCESS
1872 && RT_BF_GET(g_HmMsrs.u.vmx.u64Basic, VMX_BF_BASIC_TRUE_CTLS))
1873 {
1874 hrc = hv_vmx_read_capability(HV_VMX_CAP_TRUE_PINBASED, &g_HmMsrs.u.vmx.TruePinCtls.u);
1875 if (hrc == HV_SUCCESS)
1876 hrc = hv_vmx_read_capability(HV_VMX_CAP_TRUE_PROCBASED, &g_HmMsrs.u.vmx.TrueProcCtls.u);
1877 if (hrc == HV_SUCCESS)
1878 hrc = hv_vmx_read_capability(HV_VMX_CAP_TRUE_ENTRY, &g_HmMsrs.u.vmx.TrueEntryCtls.u);
1879 if (hrc == HV_SUCCESS)
1880 hrc = hv_vmx_read_capability(HV_VMX_CAP_TRUE_EXIT, &g_HmMsrs.u.vmx.TrueExitCtls.u);
1881 }
1882 }
1883 else
1884 {
1885 /* Likely running on anything < 11.0 (BigSur) so provide some sensible defaults. */
1886 g_HmMsrs.u.vmx.u64Cr0Fixed0 = 0x80000021;
1887 g_HmMsrs.u.vmx.u64Cr0Fixed1 = 0xffffffff;
1888 g_HmMsrs.u.vmx.u64Cr4Fixed0 = 0x2000;
1889 g_HmMsrs.u.vmx.u64Cr4Fixed1 = 0x1767ff;
1890 hrc = HV_SUCCESS;
1891 }
1892 }
1893
1894 if ( hrc == HV_SUCCESS
1895 && g_HmMsrs.u.vmx.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_SECONDARY_CTLS)
1896 {
1897 hrc = hv_vmx_read_capability(HV_VMX_CAP_PROCBASED2, &g_HmMsrs.u.vmx.ProcCtls2.u);
1898
1899 if ( hrc == HV_SUCCESS
1900 && g_HmMsrs.u.vmx.ProcCtls2.n.allowed1 & (VMX_PROC_CTLS2_EPT | VMX_PROC_CTLS2_VPID))
1901 {
1902 hrc = hv_vmx_read_capability(HV_VMX_CAP_EPT_VPID_CAP, &g_HmMsrs.u.vmx.u64EptVpidCaps);
1903 if (hrc != HV_SUCCESS)
1904 hrc = HV_SUCCESS; /* Probably just outdated OS. */
1905 }
1906
1907 g_HmMsrs.u.vmx.u64VmFunc = 0; /* No way to read that on macOS. */
1908 }
1909
1910 if (hrc == HV_SUCCESS)
1911 {
1912 /*
1913 * Check for EFER swapping support.
1914 */
1915 g_fHmVmxSupportsVmcsEfer = true; //(g_HmMsrs.u.vmx.EntryCtls.n.allowed1 & VMX_ENTRY_CTLS_LOAD_EFER_MSR)
1916 //&& (g_HmMsrs.u.vmx.ExitCtls.n.allowed1 & VMX_EXIT_CTLS_LOAD_EFER_MSR)
1917 //&& (g_HmMsrs.u.vmx.ExitCtls.n.allowed1 & VMX_EXIT_CTLS_SAVE_EFER_MSR);
1918 }
1919
1920 return nemR3DarwinHvSts2Rc(hrc);
1921}
1922
1923
1924/**
1925 * Sets up pin-based VM-execution controls in the VMCS.
1926 *
1927 * @returns VBox status code.
1928 * @param pVCpu The cross context virtual CPU structure.
1929 * @param pVmcsInfo The VMCS info. object.
1930 */
1931static int nemR3DarwinVmxSetupVmcsPinCtls(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
1932{
1933 //PVMCC pVM = pVCpu->CTX_SUFF(pVM);
1934 uint32_t fVal = g_HmMsrs.u.vmx.PinCtls.n.allowed0; /* Bits set here must always be set. */
1935 uint32_t const fZap = g_HmMsrs.u.vmx.PinCtls.n.allowed1; /* Bits cleared here must always be cleared. */
1936
1937 if (g_HmMsrs.u.vmx.PinCtls.n.allowed1 & VMX_PIN_CTLS_VIRT_NMI)
1938 fVal |= VMX_PIN_CTLS_VIRT_NMI; /* Use virtual NMIs and virtual-NMI blocking features. */
1939
1940#if 0 /** @todo Use preemption timer */
1941 /* Enable the VMX-preemption timer. */
1942 if (pVM->hmr0.s.vmx.fUsePreemptTimer)
1943 {
1944 Assert(g_HmMsrs.u.vmx.PinCtls.n.allowed1 & VMX_PIN_CTLS_PREEMPT_TIMER);
1945 fVal |= VMX_PIN_CTLS_PREEMPT_TIMER;
1946 }
1947
1948 /* Enable posted-interrupt processing. */
1949 if (pVM->hm.s.fPostedIntrs)
1950 {
1951 Assert(g_HmMsrs.u.vmx.PinCtls.n.allowed1 & VMX_PIN_CTLS_POSTED_INT);
1952 Assert(g_HmMsrs.u.vmx.ExitCtls.n.allowed1 & VMX_EXIT_CTLS_ACK_EXT_INT);
1953 fVal |= VMX_PIN_CTLS_POSTED_INT;
1954 }
1955#endif
1956
1957 if ((fVal & fZap) != fVal)
1958 {
1959 LogRelFunc(("Invalid pin-based VM-execution controls combo! Cpu=%#RX32 fVal=%#RX32 fZap=%#RX32\n",
1960 g_HmMsrs.u.vmx.PinCtls.n.allowed0, fVal, fZap));
1961 pVCpu->nem.s.u32HMError = VMX_UFC_CTRL_PIN_EXEC;
1962 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
1963 }
1964
1965 /* Commit it to the VMCS and update our cache. */
1966 int rc = nemR3DarwinWriteVmcs32(pVCpu, VMX_VMCS32_CTRL_PIN_EXEC, fVal);
1967 AssertRC(rc);
1968 pVmcsInfo->u32PinCtls = fVal;
1969
1970 return VINF_SUCCESS;
1971}
1972
1973
1974/**
1975 * Sets up secondary processor-based VM-execution controls in the VMCS.
1976 *
1977 * @returns VBox status code.
1978 * @param pVCpu The cross context virtual CPU structure.
1979 * @param pVmcsInfo The VMCS info. object.
1980 */
1981static int nemR3DarwinVmxSetupVmcsProcCtls2(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
1982{
1983 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
1984 uint32_t fVal = g_HmMsrs.u.vmx.ProcCtls2.n.allowed0; /* Bits set here must be set in the VMCS. */
1985 uint32_t const fZap = g_HmMsrs.u.vmx.ProcCtls2.n.allowed1; /* Bits cleared here must be cleared in the VMCS. */
1986
1987 /* WBINVD causes a VM-exit. */
1988 if (g_HmMsrs.u.vmx.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_WBINVD_EXIT)
1989 fVal |= VMX_PROC_CTLS2_WBINVD_EXIT;
1990
1991 /* Enable the INVPCID instruction if we expose it to the guest and is supported
1992 by the hardware. Without this, guest executing INVPCID would cause a #UD. */
1993 if ( pVM->cpum.ro.GuestFeatures.fInvpcid
1994 && (g_HmMsrs.u.vmx.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_INVPCID))
1995 fVal |= VMX_PROC_CTLS2_INVPCID;
1996
1997#if 0 /** @todo */
1998 /* Enable VPID. */
1999 if (pVM->hmr0.s.vmx.fVpid)
2000 fVal |= VMX_PROC_CTLS2_VPID;
2001
2002 if (pVM->hm.s.fVirtApicRegs)
2003 {
2004 /* Enable APIC-register virtualization. */
2005 Assert(g_HmMsrs.u.vmx.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_APIC_REG_VIRT);
2006 fVal |= VMX_PROC_CTLS2_APIC_REG_VIRT;
2007
2008 /* Enable virtual-interrupt delivery. */
2009 Assert(g_HmMsrs.u.vmx.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_VIRT_INTR_DELIVERY);
2010 fVal |= VMX_PROC_CTLS2_VIRT_INTR_DELIVERY;
2011 }
2012
2013 /* Virtualize-APIC accesses if supported by the CPU. The virtual-APIC page is
2014 where the TPR shadow resides. */
2015 /** @todo VIRT_X2APIC support, it's mutually exclusive with this. So must be
2016 * done dynamically. */
2017 if (g_HmMsrs.u.vmx.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_VIRT_APIC_ACCESS)
2018 {
2019 fVal |= VMX_PROC_CTLS2_VIRT_APIC_ACCESS;
2020 hmR0VmxSetupVmcsApicAccessAddr(pVCpu);
2021 }
2022#endif
2023
2024 /* Enable the RDTSCP instruction if we expose it to the guest and is supported
2025 by the hardware. Without this, guest executing RDTSCP would cause a #UD. */
2026 if ( pVM->cpum.ro.GuestFeatures.fRdTscP
2027 && (g_HmMsrs.u.vmx.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_RDTSCP))
2028 fVal |= VMX_PROC_CTLS2_RDTSCP;
2029
2030#if 0
2031 /* Enable Pause-Loop exiting. */
2032 if ( (g_HmMsrs.u.vmx.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_PAUSE_LOOP_EXIT)
2033 && pVM->hm.s.vmx.cPleGapTicks
2034 && pVM->hm.s.vmx.cPleWindowTicks)
2035 {
2036 fVal |= VMX_PROC_CTLS2_PAUSE_LOOP_EXIT;
2037
2038 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PLE_GAP, pVM->hm.s.vmx.cPleGapTicks); AssertRC(rc);
2039 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PLE_WINDOW, pVM->hm.s.vmx.cPleWindowTicks); AssertRC(rc);
2040 }
2041#endif
2042
2043 if ((fVal & fZap) != fVal)
2044 {
2045 LogRelFunc(("Invalid secondary processor-based VM-execution controls combo! cpu=%#RX32 fVal=%#RX32 fZap=%#RX32\n",
2046 g_HmMsrs.u.vmx.ProcCtls2.n.allowed0, fVal, fZap));
2047 pVCpu->nem.s.u32HMError = VMX_UFC_CTRL_PROC_EXEC2;
2048 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
2049 }
2050
2051 /* Commit it to the VMCS and update our cache. */
2052 int rc = nemR3DarwinWriteVmcs32(pVCpu, VMX_VMCS32_CTRL_PROC_EXEC2, fVal);
2053 AssertRC(rc);
2054 pVmcsInfo->u32ProcCtls2 = fVal;
2055
2056 return VINF_SUCCESS;
2057}
2058
2059
2060/**
2061 * Enables native access for the given MSR.
2062 *
2063 * @returns VBox status code.
2064 * @param pVCpu The cross context virtual CPU structure.
2065 * @param idMsr The MSR to enable native access for.
2066 */
2067static int nemR3DarwinMsrSetNative(PVMCPUCC pVCpu, uint32_t idMsr)
2068{
2069 hv_return_t hrc = hv_vcpu_enable_native_msr(pVCpu->nem.s.hVCpuId, idMsr, true /*enable*/);
2070 if (hrc == HV_SUCCESS)
2071 return VINF_SUCCESS;
2072
2073 return nemR3DarwinHvSts2Rc(hrc);
2074}
2075
2076
2077/**
2078 * Sets up the MSR permissions which don't change through the lifetime of the VM.
2079 *
2080 * @returns VBox status code.
2081 * @param pVCpu The cross context virtual CPU structure.
2082 * @param pVmcsInfo The VMCS info. object.
2083 */
2084static int nemR3DarwinSetupVmcsMsrPermissions(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
2085{
2086 RT_NOREF(pVmcsInfo);
2087
2088 /*
2089 * The guest can access the following MSRs (read, write) without causing
2090 * VM-exits; they are loaded/stored automatically using fields in the VMCS.
2091 */
2092 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
2093 int rc;
2094 rc = nemR3DarwinMsrSetNative(pVCpu, MSR_IA32_SYSENTER_CS); AssertRCReturn(rc, rc);
2095 rc = nemR3DarwinMsrSetNative(pVCpu, MSR_IA32_SYSENTER_ESP); AssertRCReturn(rc, rc);
2096 rc = nemR3DarwinMsrSetNative(pVCpu, MSR_IA32_SYSENTER_EIP); AssertRCReturn(rc, rc);
2097 rc = nemR3DarwinMsrSetNative(pVCpu, MSR_K8_GS_BASE); AssertRCReturn(rc, rc);
2098 rc = nemR3DarwinMsrSetNative(pVCpu, MSR_K8_FS_BASE); AssertRCReturn(rc, rc);
2099
2100 /*
2101 * The IA32_PRED_CMD and IA32_FLUSH_CMD MSRs are write-only and has no state
2102 * associated with then. We never need to intercept access (writes need to be
2103 * executed without causing a VM-exit, reads will #GP fault anyway).
2104 *
2105 * The IA32_SPEC_CTRL MSR is read/write and has state. We allow the guest to
2106 * read/write them. We swap the guest/host MSR value using the
2107 * auto-load/store MSR area.
2108 */
2109 if (pVM->cpum.ro.GuestFeatures.fIbpb)
2110 {
2111 rc = nemR3DarwinMsrSetNative(pVCpu, MSR_IA32_PRED_CMD);
2112 AssertRCReturn(rc, rc);
2113 }
2114#if 0 /* Doesn't work. */
2115 if (pVM->cpum.ro.GuestFeatures.fFlushCmd)
2116 {
2117 rc = nemR3DarwinMsrSetNative(pVCpu, MSR_IA32_FLUSH_CMD);
2118 AssertRCReturn(rc, rc);
2119 }
2120#endif
2121 if (pVM->cpum.ro.GuestFeatures.fIbrs)
2122 {
2123 rc = nemR3DarwinMsrSetNative(pVCpu, MSR_IA32_SPEC_CTRL);
2124 AssertRCReturn(rc, rc);
2125 }
2126
2127 /*
2128 * Allow full read/write access for the following MSRs (mandatory for VT-x)
2129 * required for 64-bit guests.
2130 */
2131 rc = nemR3DarwinMsrSetNative(pVCpu, MSR_K8_LSTAR); AssertRCReturn(rc, rc);
2132 rc = nemR3DarwinMsrSetNative(pVCpu, MSR_K6_STAR); AssertRCReturn(rc, rc);
2133 rc = nemR3DarwinMsrSetNative(pVCpu, MSR_K8_SF_MASK); AssertRCReturn(rc, rc);
2134 rc = nemR3DarwinMsrSetNative(pVCpu, MSR_K8_KERNEL_GS_BASE); AssertRCReturn(rc, rc);
2135
2136 /* Required for enabling the RDTSCP instruction. */
2137 rc = nemR3DarwinMsrSetNative(pVCpu, MSR_K8_TSC_AUX); AssertRCReturn(rc, rc);
2138
2139 return VINF_SUCCESS;
2140}
2141
2142
2143/**
2144 * Sets up processor-based VM-execution controls in the VMCS.
2145 *
2146 * @returns VBox status code.
2147 * @param pVCpu The cross context virtual CPU structure.
2148 * @param pVmcsInfo The VMCS info. object.
2149 */
2150static int nemR3DarwinVmxSetupVmcsProcCtls(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
2151{
2152 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
2153 uint32_t fVal = g_HmMsrs.u.vmx.ProcCtls.n.allowed0; /* Bits set here must be set in the VMCS. */
2154 uint32_t const fZap = g_HmMsrs.u.vmx.ProcCtls.n.allowed1; /* Bits cleared here must be cleared in the VMCS. */
2155
2156 fVal |= VMX_PROC_CTLS_HLT_EXIT /* HLT causes a VM-exit. */
2157// | VMX_PROC_CTLS_USE_TSC_OFFSETTING /* Use TSC-offsetting. */
2158 | VMX_PROC_CTLS_MOV_DR_EXIT /* MOV DRx causes a VM-exit. */
2159 | VMX_PROC_CTLS_UNCOND_IO_EXIT /* All IO instructions cause a VM-exit. */
2160 | VMX_PROC_CTLS_RDPMC_EXIT /* RDPMC causes a VM-exit. */
2161 | VMX_PROC_CTLS_MONITOR_EXIT /* MONITOR causes a VM-exit. */
2162 | VMX_PROC_CTLS_MWAIT_EXIT; /* MWAIT causes a VM-exit. */
2163
2164 /* We toggle VMX_PROC_CTLS_MOV_DR_EXIT later, check if it's not -always- needed to be set or clear. */
2165 if ( !(g_HmMsrs.u.vmx.ProcCtls.n.allowed1 & VMX_PROC_CTLS_MOV_DR_EXIT)
2166 || (g_HmMsrs.u.vmx.ProcCtls.n.allowed0 & VMX_PROC_CTLS_MOV_DR_EXIT))
2167 {
2168 pVCpu->nem.s.u32HMError = VMX_UFC_CTRL_PROC_MOV_DRX_EXIT;
2169 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
2170 }
2171
2172 /* Use the secondary processor-based VM-execution controls if supported by the CPU. */
2173 if (g_HmMsrs.u.vmx.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_SECONDARY_CTLS)
2174 fVal |= VMX_PROC_CTLS_USE_SECONDARY_CTLS;
2175
2176 if ((fVal & fZap) != fVal)
2177 {
2178 LogRelFunc(("Invalid processor-based VM-execution controls combo! cpu=%#RX32 fVal=%#RX32 fZap=%#RX32\n",
2179 g_HmMsrs.u.vmx.ProcCtls.n.allowed0, fVal, fZap));
2180 pVCpu->nem.s.u32HMError = VMX_UFC_CTRL_PROC_EXEC;
2181 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
2182 }
2183
2184 /* Commit it to the VMCS and update our cache. */
2185 int rc = nemR3DarwinWriteVmcs32(pVCpu, VMX_VMCS32_CTRL_PROC_EXEC, fVal);
2186 AssertRC(rc);
2187 pVmcsInfo->u32ProcCtls = fVal;
2188
2189 /* Set up MSR permissions that don't change through the lifetime of the VM. */
2190 rc = nemR3DarwinSetupVmcsMsrPermissions(pVCpu, pVmcsInfo);
2191 AssertRCReturn(rc, rc);
2192
2193 /*
2194 * Set up secondary processor-based VM-execution controls
2195 * (we assume the CPU to always support it as we rely on unrestricted guest execution support).
2196 */
2197 Assert(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_SECONDARY_CTLS);
2198 return nemR3DarwinVmxSetupVmcsProcCtls2(pVCpu, pVmcsInfo);
2199}
2200
2201
2202/**
2203 * Sets up miscellaneous (everything other than Pin, Processor and secondary
2204 * Processor-based VM-execution) control fields in the VMCS.
2205 *
2206 * @returns VBox status code.
2207 * @param pVCpu The cross context virtual CPU structure.
2208 * @param pVmcsInfo The VMCS info. object.
2209 */
2210static int nemR3DarwinVmxSetupVmcsMiscCtls(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
2211{
2212 int rc = VINF_SUCCESS;
2213 //rc = hmR0VmxSetupVmcsAutoLoadStoreMsrAddrs(pVmcsInfo); TODO
2214 if (RT_SUCCESS(rc))
2215 {
2216 uint64_t const u64Cr0Mask = vmxHCGetFixedCr0Mask(pVCpu);
2217 uint64_t const u64Cr4Mask = vmxHCGetFixedCr4Mask(pVCpu);
2218
2219 rc = nemR3DarwinWriteVmcs64(pVCpu, VMX_VMCS_CTRL_CR0_MASK, u64Cr0Mask); AssertRC(rc);
2220 rc = nemR3DarwinWriteVmcs64(pVCpu, VMX_VMCS_CTRL_CR4_MASK, u64Cr4Mask); AssertRC(rc);
2221
2222 pVmcsInfo->u64Cr0Mask = u64Cr0Mask;
2223 pVmcsInfo->u64Cr4Mask = u64Cr4Mask;
2224
2225#if 0 /** @todo */
2226 if (pVCpu->CTX_SUFF(pVM)->hmr0.s.vmx.fLbr)
2227 {
2228 rc = VMXWriteVmcsNw(VMX_VMCS64_GUEST_DEBUGCTL_FULL, MSR_IA32_DEBUGCTL_LBR);
2229 AssertRC(rc);
2230 }
2231#endif
2232 return VINF_SUCCESS;
2233 }
2234 else
2235 LogRelFunc(("Failed to initialize VMCS auto-load/store MSR addresses. rc=%Rrc\n", rc));
2236 return rc;
2237}
2238
2239
2240/**
2241 * Sets up the initial exception bitmap in the VMCS based on static conditions.
2242 *
2243 * We shall setup those exception intercepts that don't change during the
2244 * lifetime of the VM here. The rest are done dynamically while loading the
2245 * guest state.
2246 *
2247 * @param pVCpu The cross context virtual CPU structure.
2248 * @param pVmcsInfo The VMCS info. object.
2249 */
2250static void nemR3DarwinVmxSetupVmcsXcptBitmap(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
2251{
2252 /*
2253 * The following exceptions are always intercepted:
2254 *
2255 * #AC - To prevent the guest from hanging the CPU and for dealing with
2256 * split-lock detecting host configs.
2257 * #DB - To maintain the DR6 state even when intercepting DRx reads/writes and
2258 * recursive #DBs can cause a CPU hang.
2259 */
2260 uint32_t const uXcptBitmap = RT_BIT(X86_XCPT_AC)
2261 | RT_BIT(X86_XCPT_DB);
2262
2263 /* Commit it to the VMCS. */
2264 int rc = nemR3DarwinWriteVmcs32(pVCpu, VMX_VMCS32_CTRL_EXCEPTION_BITMAP, uXcptBitmap);
2265 AssertRC(rc);
2266
2267 /* Update our cache of the exception bitmap. */
2268 pVmcsInfo->u32XcptBitmap = uXcptBitmap;
2269}
2270
2271
2272/**
2273 * Initialize the VMCS information field for the given vCPU.
2274 *
2275 * @returns VBox status code.
2276 * @param pVCpu The cross context virtual CPU structure of the
2277 * calling EMT.
2278 */
2279static int nemR3DarwinInitVmcs(PVMCPU pVCpu)
2280{
2281 int rc = nemR3DarwinVmxSetupVmcsPinCtls(pVCpu, &pVCpu->nem.s.VmcsInfo);
2282 if (RT_SUCCESS(rc))
2283 {
2284 rc = nemR3DarwinVmxSetupVmcsProcCtls(pVCpu, &pVCpu->nem.s.VmcsInfo);
2285 if (RT_SUCCESS(rc))
2286 {
2287 rc = nemR3DarwinVmxSetupVmcsMiscCtls(pVCpu, &pVCpu->nem.s.VmcsInfo);
2288 if (RT_SUCCESS(rc))
2289 {
2290 rc = nemR3DarwinReadVmcs32(pVCpu, VMX_VMCS32_CTRL_ENTRY, &pVCpu->nem.s.VmcsInfo.u32EntryCtls);
2291 if (RT_SUCCESS(rc))
2292 {
2293 rc = nemR3DarwinReadVmcs32(pVCpu, VMX_VMCS32_CTRL_EXIT, &pVCpu->nem.s.VmcsInfo.u32ExitCtls);
2294 if (RT_SUCCESS(rc))
2295 {
2296 nemR3DarwinVmxSetupVmcsXcptBitmap(pVCpu, &pVCpu->nem.s.VmcsInfo);
2297 return VINF_SUCCESS;
2298 }
2299 else
2300 LogRelFunc(("Failed to read the exit controls. rc=%Rrc\n", rc));
2301 }
2302 else
2303 LogRelFunc(("Failed to read the entry controls. rc=%Rrc\n", rc));
2304 }
2305 else
2306 LogRelFunc(("Failed to setup miscellaneous controls. rc=%Rrc\n", rc));
2307 }
2308 else
2309 LogRelFunc(("Failed to setup processor-based VM-execution controls. rc=%Rrc\n", rc));
2310 }
2311 else
2312 LogRelFunc(("Failed to setup pin-based controls. rc=%Rrc\n", rc));
2313
2314 return rc;
2315}
2316
2317
2318/**
2319 * Registers statistics for the given vCPU.
2320 *
2321 * @returns VBox status code.
2322 * @param pVM The cross context VM structure.
2323 * @param idCpu The CPU ID.
2324 * @param pNemCpu The NEM CPU structure.
2325 */
2326static int nemR3DarwinStatisticsRegister(PVM pVM, VMCPUID idCpu, PNEMCPU pNemCpu)
2327{
2328#define NEM_REG_STAT(a_pVar, a_enmType, s_enmVisibility, a_enmUnit, a_szNmFmt, a_szDesc) do { \
2329 int rc = STAMR3RegisterF(pVM, a_pVar, a_enmType, s_enmVisibility, a_enmUnit, a_szDesc, a_szNmFmt, idCpu); \
2330 AssertRC(rc); \
2331 } while (0)
2332#define NEM_REG_PROFILE(a_pVar, a_szNmFmt, a_szDesc) \
2333 NEM_REG_STAT(a_pVar, STAMTYPE_PROFILE, STAMVISIBILITY_USED, STAMUNIT_TICKS_PER_CALL, a_szNmFmt, a_szDesc)
2334#define NEM_REG_COUNTER(a, b, desc) NEM_REG_STAT(a, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, b, desc)
2335
2336 NEM_REG_COUNTER(&pNemCpu->pVmxStats->StatExitCR0Read, "/NEM/CPU%u/Exit/Instr/CR-Read/CR0", "CR0 read.");
2337 NEM_REG_COUNTER(&pNemCpu->pVmxStats->StatExitCR2Read, "/NEM/CPU%u/Exit/Instr/CR-Read/CR2", "CR2 read.");
2338 NEM_REG_COUNTER(&pNemCpu->pVmxStats->StatExitCR3Read, "/NEM/CPU%u/Exit/Instr/CR-Read/CR3", "CR3 read.");
2339 NEM_REG_COUNTER(&pNemCpu->pVmxStats->StatExitCR4Read, "/NEM/CPU%u/Exit/Instr/CR-Read/CR4", "CR4 read.");
2340 NEM_REG_COUNTER(&pNemCpu->pVmxStats->StatExitCR8Read, "/NEM/CPU%u/Exit/Instr/CR-Read/CR8", "CR8 read.");
2341 NEM_REG_COUNTER(&pNemCpu->pVmxStats->StatExitCR0Write, "/NEM/CPU%u/Exit/Instr/CR-Write/CR0", "CR0 write.");
2342 NEM_REG_COUNTER(&pNemCpu->pVmxStats->StatExitCR2Write, "/NEM/CPU%u/Exit/Instr/CR-Write/CR2", "CR2 write.");
2343 NEM_REG_COUNTER(&pNemCpu->pVmxStats->StatExitCR3Write, "/NEM/CPU%u/Exit/Instr/CR-Write/CR3", "CR3 write.");
2344 NEM_REG_COUNTER(&pNemCpu->pVmxStats->StatExitCR4Write, "/NEM/CPU%u/Exit/Instr/CR-Write/CR4", "CR4 write.");
2345 NEM_REG_COUNTER(&pNemCpu->pVmxStats->StatExitCR8Write, "/NEM/CPU%u/Exit/Instr/CR-Write/CR8", "CR8 write.");
2346
2347 NEM_REG_COUNTER(&pNemCpu->pVmxStats->StatExitAll, "/NEM/CPU%u/Exit/All", "Total exits (including nested-guest exits).");
2348
2349#ifdef VBOX_WITH_STATISTICS
2350 NEM_REG_PROFILE(&pNemCpu->StatProfGstStateImport, "/NEM/CPU%u/ImportGuestState", "Profiling of importing guest state from hardware after VM-exit.");
2351 NEM_REG_PROFILE(&pNemCpu->StatProfGstStateExport, "/NEM/CPU%u/ExportGuestState", "Profiling of exporting guest state from hardware after VM-exit.");
2352
2353 for (int j = 0; j < MAX_EXITREASON_STAT; j++)
2354 {
2355 const char *pszExitName = HMGetVmxExitName(j);
2356 if (pszExitName)
2357 {
2358 int rc = STAMR3RegisterF(pVM, &pNemCpu->pVmxStats->aStatExitReason[j], STAMTYPE_COUNTER, STAMVISIBILITY_USED,
2359 STAMUNIT_OCCURENCES, pszExitName, "/NEM/CPU%u/Exit/Reason/%02x", idCpu, j);
2360 AssertRCReturn(rc, rc);
2361 }
2362 }
2363#endif
2364
2365 return VINF_SUCCESS;
2366
2367#undef NEM_REG_COUNTER
2368#undef NEM_REG_PROFILE
2369#undef NEM_REG_STAT
2370}
2371
2372
2373/**
2374 * Try initialize the native API.
2375 *
2376 * This may only do part of the job, more can be done in
2377 * nemR3NativeInitAfterCPUM() and nemR3NativeInitCompleted().
2378 *
2379 * @returns VBox status code.
2380 * @param pVM The cross context VM structure.
2381 * @param fFallback Whether we're in fallback mode or use-NEM mode. In
2382 * the latter we'll fail if we cannot initialize.
2383 * @param fForced Whether the HMForced flag is set and we should
2384 * fail if we cannot initialize.
2385 */
2386int nemR3NativeInit(PVM pVM, bool fFallback, bool fForced)
2387{
2388 AssertReturn(!pVM->nem.s.fCreatedVm, VERR_WRONG_ORDER);
2389
2390 /*
2391 * Some state init.
2392 */
2393
2394 /*
2395 * Error state.
2396 * The error message will be non-empty on failure and 'rc' will be set too.
2397 */
2398 RTERRINFOSTATIC ErrInfo;
2399 PRTERRINFO pErrInfo = RTErrInfoInitStatic(&ErrInfo);
2400 int rc = nemR3DarwinLoadHv(fForced, pErrInfo);
2401 if (RT_SUCCESS(rc))
2402 {
2403 hv_return_t hrc = hv_vm_create(HV_VM_DEFAULT);
2404 if (hrc == HV_SUCCESS)
2405 {
2406 if (hv_vm_space_create)
2407 {
2408 hrc = hv_vm_space_create(&pVM->nem.s.uVmAsid);
2409 if (hrc == HV_SUCCESS)
2410 {
2411 LogRel(("NEM: Successfully created ASID: %u\n", pVM->nem.s.uVmAsid));
2412 pVM->nem.s.fCreatedAsid = true;
2413 }
2414 else
2415 LogRel(("NEM: Failed to create ASID for VM (hrc=%#x), continuing...\n", pVM->nem.s.uVmAsid));
2416 }
2417 pVM->nem.s.fCreatedVm = true;
2418
2419 /* Register release statistics */
2420 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
2421 {
2422 PNEMCPU pNemCpu = &pVM->apCpusR3[idCpu]->nem.s;
2423 PVMXSTATISTICS pVmxStats = (PVMXSTATISTICS)RTMemAllocZ(sizeof(*pVmxStats));
2424 if (RT_LIKELY(pVmxStats))
2425 {
2426 pNemCpu->pVmxStats = pVmxStats;
2427 rc = nemR3DarwinStatisticsRegister(pVM, idCpu, pNemCpu);
2428 AssertRC(rc);
2429 }
2430 else
2431 {
2432 rc = VERR_NO_MEMORY;
2433 break;
2434 }
2435 }
2436
2437 if (RT_SUCCESS(rc))
2438 {
2439 VM_SET_MAIN_EXECUTION_ENGINE(pVM, VM_EXEC_ENGINE_NATIVE_API);
2440 Log(("NEM: Marked active!\n"));
2441 PGMR3EnableNemMode(pVM);
2442 }
2443 }
2444 else
2445 rc = RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED,
2446 "hv_vm_create() failed: %#x", hrc);
2447 }
2448
2449 /*
2450 * We only fail if in forced mode, otherwise just log the complaint and return.
2451 */
2452 Assert(pVM->bMainExecutionEngine == VM_EXEC_ENGINE_NATIVE_API || RTErrInfoIsSet(pErrInfo));
2453 if ( (fForced || !fFallback)
2454 && pVM->bMainExecutionEngine != VM_EXEC_ENGINE_NATIVE_API)
2455 return VMSetError(pVM, RT_SUCCESS_NP(rc) ? VERR_NEM_NOT_AVAILABLE : rc, RT_SRC_POS, "%s", pErrInfo->pszMsg);
2456
2457 if (RTErrInfoIsSet(pErrInfo))
2458 LogRel(("NEM: Not available: %s\n", pErrInfo->pszMsg));
2459 return VINF_SUCCESS;
2460}
2461
2462
2463/**
2464 * Worker to create the vCPU handle on the EMT running it later on (as required by HV).
2465 *
2466 * @returns VBox status code
2467 * @param pVM The VM handle.
2468 * @param pVCpu The vCPU handle.
2469 * @param idCpu ID of the CPU to create.
2470 */
2471static DECLCALLBACK(int) nemR3DarwinNativeInitVCpuOnEmt(PVM pVM, PVMCPU pVCpu, VMCPUID idCpu)
2472{
2473 hv_return_t hrc = hv_vcpu_create(&pVCpu->nem.s.hVCpuId, HV_VCPU_DEFAULT);
2474 if (hrc != HV_SUCCESS)
2475 return VMSetError(pVM, VERR_NEM_VM_CREATE_FAILED, RT_SRC_POS,
2476 "Call to hv_vcpu_create failed on vCPU %u: %#x (%Rrc)", idCpu, hrc, nemR3DarwinHvSts2Rc(hrc));
2477
2478 if (idCpu == 0)
2479 {
2480 /* First call initializs the MSR structure holding the capabilities of the host CPU. */
2481 int rc = nemR3DarwinCapsInit();
2482 AssertRCReturn(rc, rc);
2483 }
2484
2485 int rc = nemR3DarwinInitVmcs(pVCpu);
2486 AssertRCReturn(rc, rc);
2487
2488 if (pVM->nem.s.fCreatedAsid)
2489 {
2490 hrc = hv_vcpu_set_space(pVCpu->nem.s.hVCpuId, pVM->nem.s.uVmAsid);
2491 AssertReturn(hrc == HV_SUCCESS, VERR_NEM_VM_CREATE_FAILED);
2492 }
2493
2494 ASMAtomicUoOrU64(&pVCpu->nem.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
2495
2496 return VINF_SUCCESS;
2497}
2498
2499
2500/**
2501 * Worker to destroy the vCPU handle on the EMT running it later on (as required by HV).
2502 *
2503 * @returns VBox status code
2504 * @param pVCpu The vCPU handle.
2505 */
2506static DECLCALLBACK(int) nemR3DarwinNativeTermVCpuOnEmt(PVMCPU pVCpu)
2507{
2508 hv_return_t hrc = hv_vcpu_set_space(pVCpu->nem.s.hVCpuId, 0 /*asid*/);
2509 Assert(hrc == HV_SUCCESS);
2510
2511 hrc = hv_vcpu_destroy(pVCpu->nem.s.hVCpuId);
2512 Assert(hrc == HV_SUCCESS); RT_NOREF(hrc);
2513 return VINF_SUCCESS;
2514}
2515
2516
2517/**
2518 * Worker to setup the TPR shadowing feature if available on the CPU and the VM has an APIC enabled.
2519 *
2520 * @returns VBox status code
2521 * @param pVM The VM handle.
2522 * @param pVCpu The vCPU handle.
2523 * @param idCpu ID of the CPU to create.
2524 */
2525static DECLCALLBACK(int) nemR3DarwinNativeInitTprShadowing(PVM pVM, PVMCPU pVCpu, VMCPUID idCpu)
2526{
2527 PVMXVMCSINFO pVmcsInfo = &pVCpu->nem.s.VmcsInfo;
2528 uint32_t fVal = pVmcsInfo->u32ProcCtls;
2529
2530 /* Use TPR shadowing if supported by the CPU. */
2531 if ( PDMHasApic(pVM)
2532 && (g_HmMsrs.u.vmx.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_TPR_SHADOW))
2533 {
2534 fVal |= VMX_PROC_CTLS_USE_TPR_SHADOW; /* CR8 reads from the Virtual-APIC page. */
2535 /* CR8 writes cause a VM-exit based on TPR threshold. */
2536 Assert(!(fVal & VMX_PROC_CTLS_CR8_STORE_EXIT));
2537 Assert(!(fVal & VMX_PROC_CTLS_CR8_LOAD_EXIT));
2538 }
2539 else
2540 {
2541 fVal |= VMX_PROC_CTLS_CR8_STORE_EXIT /* CR8 reads cause a VM-exit. */
2542 | VMX_PROC_CTLS_CR8_LOAD_EXIT; /* CR8 writes cause a VM-exit. */
2543 }
2544
2545 /* Commit it to the VMCS and update our cache. */
2546 int rc = nemR3DarwinWriteVmcs32(pVCpu, VMX_VMCS32_CTRL_PROC_EXEC, fVal);
2547 AssertRC(rc);
2548 pVmcsInfo->u32ProcCtls = fVal;
2549
2550 return VINF_SUCCESS;
2551}
2552
2553
2554/**
2555 * This is called after CPUMR3Init is done.
2556 *
2557 * @returns VBox status code.
2558 * @param pVM The VM handle..
2559 */
2560int nemR3NativeInitAfterCPUM(PVM pVM)
2561{
2562 /*
2563 * Validate sanity.
2564 */
2565 AssertReturn(!pVM->nem.s.fCreatedEmts, VERR_WRONG_ORDER);
2566 AssertReturn(pVM->bMainExecutionEngine == VM_EXEC_ENGINE_NATIVE_API, VERR_WRONG_ORDER);
2567
2568 /*
2569 * Setup the EMTs.
2570 */
2571 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
2572 {
2573 PVMCPU pVCpu = pVM->apCpusR3[idCpu];
2574
2575 int rc = VMR3ReqCallWait(pVM, idCpu, (PFNRT)nemR3DarwinNativeInitVCpuOnEmt, 3, pVM, pVCpu, idCpu);
2576 if (RT_FAILURE(rc))
2577 {
2578 /* Rollback. */
2579 while (idCpu--)
2580 VMR3ReqCallWait(pVM, idCpu, (PFNRT)nemR3DarwinNativeTermVCpuOnEmt, 1, pVCpu);
2581
2582 return VMSetError(pVM, VERR_NEM_VM_CREATE_FAILED, RT_SRC_POS, "Call to hv_vcpu_create failed: %Rrc", rc);
2583 }
2584 }
2585
2586 pVM->nem.s.fCreatedEmts = true;
2587 return VINF_SUCCESS;
2588}
2589
2590
2591int nemR3NativeInitCompleted(PVM pVM, VMINITCOMPLETED enmWhat)
2592{
2593 if (enmWhat == VMINITCOMPLETED_RING3)
2594 {
2595 /* Now that PDM is initialized the APIC state is known in order to enable the TPR shadowing feature on all EMTs. */
2596 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
2597 {
2598 PVMCPU pVCpu = pVM->apCpusR3[idCpu];
2599
2600 int rc = VMR3ReqCallWait(pVM, idCpu, (PFNRT)nemR3DarwinNativeInitTprShadowing, 3, pVM, pVCpu, idCpu);
2601 if (RT_FAILURE(rc))
2602 return VMSetError(pVM, VERR_NEM_VM_CREATE_FAILED, RT_SRC_POS, "Call to hv_vcpu_create failed: %Rrc", rc);
2603 }
2604 }
2605 return VINF_SUCCESS;
2606}
2607
2608
2609int nemR3NativeTerm(PVM pVM)
2610{
2611 /*
2612 * Delete the VM.
2613 */
2614
2615 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu--)
2616 {
2617 PVMCPU pVCpu = pVM->apCpusR3[idCpu];
2618
2619 /*
2620 * Need to do this or hv_vm_space_destroy() fails later on (on 10.15 at least). Could've been documented in
2621 * API reference so I wouldn't have to decompile the kext to find this out but we are talking
2622 * about Apple here unfortunately, API documentation is not their strong suit...
2623 * Would have been of course even better to just automatically drop the address space reference when the vCPU
2624 * gets destroyed.
2625 */
2626 hv_return_t hrc = hv_vcpu_set_space(pVCpu->nem.s.hVCpuId, 0 /*asid*/);
2627 Assert(hrc == HV_SUCCESS);
2628
2629 /*
2630 * Apple's documentation states that the vCPU should be destroyed
2631 * on the thread running the vCPU but as all the other EMTs are gone
2632 * at this point, destroying the VM would hang.
2633 *
2634 * We seem to be at luck here though as destroying apparently works
2635 * from EMT(0) as well.
2636 */
2637 hrc = hv_vcpu_destroy(pVCpu->nem.s.hVCpuId);
2638 Assert(hrc == HV_SUCCESS); RT_NOREF(hrc);
2639
2640 if (pVCpu->nem.s.pVmxStats)
2641 {
2642 RTMemFree(pVCpu->nem.s.pVmxStats);
2643 pVCpu->nem.s.pVmxStats = NULL;
2644 }
2645 }
2646
2647 pVM->nem.s.fCreatedEmts = false;
2648
2649 if (pVM->nem.s.fCreatedAsid)
2650 {
2651 hv_return_t hrc = hv_vm_space_destroy(pVM->nem.s.uVmAsid);
2652 Assert(hrc == HV_SUCCESS); RT_NOREF(hrc);
2653 pVM->nem.s.fCreatedAsid = false;
2654 }
2655
2656 if (pVM->nem.s.fCreatedVm)
2657 {
2658 hv_return_t hrc = hv_vm_destroy();
2659 if (hrc != HV_SUCCESS)
2660 LogRel(("NEM: hv_vm_destroy() failed with %#x\n", hrc));
2661
2662 pVM->nem.s.fCreatedVm = false;
2663 }
2664 return VINF_SUCCESS;
2665}
2666
2667
2668/**
2669 * VM reset notification.
2670 *
2671 * @param pVM The cross context VM structure.
2672 */
2673void nemR3NativeReset(PVM pVM)
2674{
2675 RT_NOREF(pVM);
2676}
2677
2678
2679/**
2680 * Reset CPU due to INIT IPI or hot (un)plugging.
2681 *
2682 * @param pVCpu The cross context virtual CPU structure of the CPU being
2683 * reset.
2684 * @param fInitIpi Whether this is the INIT IPI or hot (un)plugging case.
2685 */
2686void nemR3NativeResetCpu(PVMCPU pVCpu, bool fInitIpi)
2687{
2688 RT_NOREF(fInitIpi);
2689 ASMAtomicUoOrU64(&pVCpu->nem.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
2690}
2691
2692
2693VBOXSTRICTRC nemR3NativeRunGC(PVM pVM, PVMCPU pVCpu)
2694{
2695 LogFlow(("NEM/%u: %04x:%08RX64 efl=%#08RX64 <=\n", pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, pVCpu->cpum.GstCtx.rflags));
2696#ifdef LOG_ENABLED
2697 if (LogIs3Enabled())
2698 nemR3DarwinLogState(pVM, pVCpu);
2699#endif
2700
2701 /*
2702 * Try switch to NEM runloop state.
2703 */
2704 if (VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC_NEM, VMCPUSTATE_STARTED))
2705 { /* likely */ }
2706 else
2707 {
2708 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC_NEM, VMCPUSTATE_STARTED_EXEC_NEM_CANCELED);
2709 LogFlow(("NEM/%u: returning immediately because canceled\n", pVCpu->idCpu));
2710 return VINF_SUCCESS;
2711 }
2712
2713 /*
2714 * The run loop.
2715 *
2716 * Current approach to state updating to use the sledgehammer and sync
2717 * everything every time. This will be optimized later.
2718 */
2719
2720 VMXTRANSIENT VmxTransient;
2721 RT_ZERO(VmxTransient);
2722 VmxTransient.pVmcsInfo = &pVCpu->nem.s.VmcsInfo;
2723
2724 const bool fSingleStepping = DBGFIsStepping(pVCpu);
2725 VBOXSTRICTRC rcStrict = VINF_SUCCESS;
2726 for (unsigned iLoop = 0;; iLoop++)
2727 {
2728 /*
2729 * Check and process force flag actions, some of which might require us to go back to ring-3.
2730 */
2731 rcStrict = vmxHCCheckForceFlags(pVCpu, false /*fIsNestedGuest*/, fSingleStepping);
2732 if (rcStrict == VINF_SUCCESS)
2733 { /*likely */ }
2734 else
2735 break;
2736
2737 /*
2738 * Evaluate events to be injected into the guest.
2739 *
2740 * Events in TRPM can be injected without inspecting the guest state.
2741 * If any new events (interrupts/NMI) are pending currently, we try to set up the
2742 * guest to cause a VM-exit the next time they are ready to receive the event.
2743 */
2744 if (TRPMHasTrap(pVCpu))
2745 vmxHCTrpmTrapToPendingEvent(pVCpu);
2746
2747 uint32_t fIntrState;
2748 rcStrict = vmxHCEvaluatePendingEvent(pVCpu, &pVCpu->nem.s.VmcsInfo, false /*fIsNestedGuest*/, &fIntrState);
2749
2750 /*
2751 * Event injection may take locks (currently the PGM lock for real-on-v86 case) and thus
2752 * needs to be done with longjmps or interrupts + preemption enabled. Event injection might
2753 * also result in triple-faulting the VM.
2754 *
2755 * With nested-guests, the above does not apply since unrestricted guest execution is a
2756 * requirement. Regardless, we do this here to avoid duplicating code elsewhere.
2757 */
2758 rcStrict = vmxHCInjectPendingEvent(pVCpu, &pVCpu->nem.s.VmcsInfo, false /*fIsNestedGuest*/, fIntrState, fSingleStepping);
2759 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
2760 { /* likely */ }
2761 else
2762 {
2763 AssertMsg(rcStrict == VINF_EM_RESET || (rcStrict == VINF_EM_DBG_STEPPED && fSingleStepping),
2764 ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
2765 break;
2766 }
2767
2768 int rc = nemR3DarwinExportGuestState(pVM, pVCpu, &VmxTransient);
2769 AssertRCReturn(rc, rc);
2770
2771 /*
2772 * Poll timers and run for a bit.
2773 */
2774 /** @todo See if we cannot optimize this TMTimerPollGIP by only redoing
2775 * the whole polling job when timers have changed... */
2776 uint64_t offDeltaIgnored;
2777 uint64_t const nsNextTimerEvt = TMTimerPollGIP(pVM, pVCpu, &offDeltaIgnored); NOREF(nsNextTimerEvt);
2778 if ( !VM_FF_IS_ANY_SET(pVM, VM_FF_EMT_RENDEZVOUS | VM_FF_TM_VIRTUAL_SYNC)
2779 && !VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
2780 {
2781 LogFlowFunc(("Running vCPU\n"));
2782 pVCpu->nem.s.Event.fPending = false;
2783
2784 TMNotifyStartOfExecution(pVM, pVCpu);
2785
2786 Assert(!pVCpu->nem.s.fCtxChanged);
2787 hv_return_t hrc;
2788 if (hv_vcpu_run_until)
2789 hrc = hv_vcpu_run_until(pVCpu->nem.s.hVCpuId, HV_DEADLINE_FOREVER);
2790 else
2791 hrc = hv_vcpu_run(pVCpu->nem.s.hVCpuId);
2792
2793 TMNotifyEndOfExecution(pVM, pVCpu, ASMReadTSC());
2794
2795 /*
2796 * Sync the TPR shadow with our APIC state.
2797 */
2798 if ( !VmxTransient.fIsNestedGuest
2799 && (pVCpu->nem.s.VmcsInfo.u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW))
2800 {
2801 uint64_t u64Tpr;
2802 hrc = hv_vcpu_read_register(pVCpu->nem.s.hVCpuId, HV_X86_TPR, &u64Tpr);
2803 Assert(hrc == HV_SUCCESS);
2804
2805 if (VmxTransient.u8GuestTpr != (uint8_t)u64Tpr)
2806 {
2807 rc = APICSetTpr(pVCpu, (uint8_t)u64Tpr);
2808 AssertRC(rc);
2809 ASMAtomicUoOrU64(&pVCpu->nem.s.fCtxChanged, HM_CHANGED_GUEST_APIC_TPR);
2810 }
2811 }
2812
2813 if (hrc == HV_SUCCESS)
2814 {
2815 /*
2816 * Deal with the message.
2817 */
2818 rcStrict = nemR3DarwinHandleExit(pVM, pVCpu, &VmxTransient);
2819 if (rcStrict == VINF_SUCCESS)
2820 { /* hopefully likely */ }
2821 else
2822 {
2823 LogFlow(("NEM/%u: breaking: nemR3DarwinHandleExit -> %Rrc\n", pVCpu->idCpu, VBOXSTRICTRC_VAL(rcStrict) ));
2824 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatBreakOnStatus);
2825 break;
2826 }
2827 //Assert(!pVCpu->cpum.GstCtx.fExtrn);
2828 }
2829 else
2830 {
2831 AssertLogRelMsgFailedReturn(("hv_vcpu_run()) failed for CPU #%u: %#x %u\n",
2832 pVCpu->idCpu, hrc, vmxHCCheckGuestState(pVCpu, &pVCpu->nem.s.VmcsInfo)),
2833 VERR_NEM_IPE_0);
2834 }
2835
2836 /*
2837 * If no relevant FFs are pending, loop.
2838 */
2839 if ( !VM_FF_IS_ANY_SET( pVM, !fSingleStepping ? VM_FF_HP_R0_PRE_HM_MASK : VM_FF_HP_R0_PRE_HM_STEP_MASK)
2840 && !VMCPU_FF_IS_ANY_SET(pVCpu, !fSingleStepping ? VMCPU_FF_HP_R0_PRE_HM_MASK : VMCPU_FF_HP_R0_PRE_HM_STEP_MASK) )
2841 continue;
2842
2843 /** @todo Try handle pending flags, not just return to EM loops. Take care
2844 * not to set important RCs here unless we've handled a message. */
2845 LogFlow(("NEM/%u: breaking: pending FF (%#x / %#RX64)\n",
2846 pVCpu->idCpu, pVM->fGlobalForcedActions, (uint64_t)pVCpu->fLocalForcedActions));
2847 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatBreakOnFFPost);
2848 }
2849 else
2850 {
2851 LogFlow(("NEM/%u: breaking: pending FF (pre exec)\n", pVCpu->idCpu));
2852 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatBreakOnFFPre);
2853 }
2854 break;
2855 } /* the run loop */
2856
2857
2858 /*
2859 * Convert any pending HM events back to TRPM due to premature exits.
2860 *
2861 * This is because execution may continue from IEM and we would need to inject
2862 * the event from there (hence place it back in TRPM).
2863 */
2864 if (pVCpu->nem.s.Event.fPending)
2865 {
2866 vmxHCPendingEventToTrpmTrap(pVCpu);
2867 Assert(!pVCpu->nem.s.Event.fPending);
2868
2869 /* Clear the events from the VMCS. */
2870 int rc = nemR3DarwinWriteVmcs32(pVCpu, VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, 0); AssertRC(rc);
2871 rc = nemR3DarwinWriteVmcs32(pVCpu, VMX_VMCS_GUEST_PENDING_DEBUG_XCPTS, 0); AssertRC(rc);
2872 }
2873
2874
2875 if (!VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED, VMCPUSTATE_STARTED_EXEC_NEM))
2876 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED, VMCPUSTATE_STARTED_EXEC_NEM_CANCELED);
2877
2878 if (pVCpu->cpum.GstCtx.fExtrn & (CPUMCTX_EXTRN_ALL))
2879 {
2880 /* Try anticipate what we might need. */
2881 uint64_t fImport = IEM_CPUMCTX_EXTRN_MUST_MASK;
2882 if ( (rcStrict >= VINF_EM_FIRST && rcStrict <= VINF_EM_LAST)
2883 || RT_FAILURE(rcStrict))
2884 fImport = CPUMCTX_EXTRN_ALL;
2885 else if (VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_INTERRUPT_PIC | VMCPU_FF_INTERRUPT_APIC
2886 | VMCPU_FF_INTERRUPT_NMI | VMCPU_FF_INTERRUPT_SMI))
2887 fImport |= IEM_CPUMCTX_EXTRN_XCPT_MASK;
2888
2889 if (pVCpu->cpum.GstCtx.fExtrn & fImport)
2890 {
2891 /* Only import what is external currently. */
2892 int rc2 = nemR3DarwinCopyStateFromHv(pVM, pVCpu, fImport);
2893 if (RT_SUCCESS(rc2))
2894 pVCpu->cpum.GstCtx.fExtrn &= ~fImport;
2895 else if (RT_SUCCESS(rcStrict))
2896 rcStrict = rc2;
2897 if (!(pVCpu->cpum.GstCtx.fExtrn & CPUMCTX_EXTRN_ALL))
2898 {
2899 pVCpu->cpum.GstCtx.fExtrn = 0;
2900 ASMAtomicUoOrU64(&pVCpu->nem.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
2901 }
2902 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatImportOnReturn);
2903 }
2904 else
2905 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatImportOnReturnSkipped);
2906 }
2907 else
2908 {
2909 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatImportOnReturnSkipped);
2910 pVCpu->cpum.GstCtx.fExtrn = 0;
2911 ASMAtomicUoOrU64(&pVCpu->nem.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
2912 }
2913
2914 LogFlow(("NEM/%u: %04x:%08RX64 efl=%#08RX64 => %Rrc\n",
2915 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, pVCpu->cpum.GstCtx.rflags, VBOXSTRICTRC_VAL(rcStrict) ));
2916 return rcStrict;
2917}
2918
2919
2920VMMR3_INT_DECL(bool) NEMR3CanExecuteGuest(PVM pVM, PVMCPU pVCpu)
2921{
2922 NOREF(pVM);
2923 return PGMPhysIsA20Enabled(pVCpu);
2924}
2925
2926
2927bool nemR3NativeSetSingleInstruction(PVM pVM, PVMCPU pVCpu, bool fEnable)
2928{
2929 NOREF(pVM); NOREF(pVCpu); NOREF(fEnable);
2930 return false;
2931}
2932
2933
2934/**
2935 * Forced flag notification call from VMEmt.h.
2936 *
2937 * This is only called when pVCpu is in the VMCPUSTATE_STARTED_EXEC_NEM state.
2938 *
2939 * @param pVM The cross context VM structure.
2940 * @param pVCpu The cross context virtual CPU structure of the CPU
2941 * to be notified.
2942 * @param fFlags Notification flags, VMNOTIFYFF_FLAGS_XXX.
2943 */
2944void nemR3NativeNotifyFF(PVM pVM, PVMCPU pVCpu, uint32_t fFlags)
2945{
2946 LogFlowFunc(("pVM=%p pVCpu=%p fFlags=%#x\n", pVM, pVCpu, fFlags));
2947
2948 RT_NOREF(pVM, fFlags);
2949
2950 hv_return_t hrc = hv_vcpu_interrupt(&pVCpu->nem.s.hVCpuId, 1);
2951 if (hrc != HV_SUCCESS)
2952 LogRel(("NEM: hv_vcpu_interrupt(%u, 1) failed with %#x\n", pVCpu->nem.s.hVCpuId, hrc));
2953}
2954
2955
2956VMMR3_INT_DECL(int) NEMR3NotifyPhysRamRegister(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, void *pvR3,
2957 uint8_t *pu2State, uint32_t *puNemRange)
2958{
2959 RT_NOREF(pVM, puNemRange);
2960
2961 Log5(("NEMR3NotifyPhysRamRegister: %RGp LB %RGp, pvR3=%p\n", GCPhys, cb, pvR3));
2962#if defined(VBOX_WITH_PGM_NEM_MODE)
2963 if (pvR3)
2964 {
2965 int rc = nemR3DarwinMap(pVM, GCPhys, pvR3, cb, NEM_PAGE_PROT_READ | NEM_PAGE_PROT_WRITE | NEM_PAGE_PROT_EXECUTE);
2966 if (RT_SUCCESS(rc))
2967 *pu2State = NEM_DARWIN_PAGE_STATE_WRITABLE;
2968 else
2969 {
2970 LogRel(("NEMR3NotifyPhysRamRegister: GCPhys=%RGp LB %RGp pvR3=%p rc=%Rrc\n", GCPhys, cb, pvR3, rc));
2971 return VERR_NEM_MAP_PAGES_FAILED;
2972 }
2973 }
2974 return VINF_SUCCESS;
2975#else
2976 RT_NOREF(pVM, GCPhys, cb, pvR3);
2977 return VERR_NEM_MAP_PAGES_FAILED;
2978#endif
2979}
2980
2981
2982VMMR3_INT_DECL(bool) NEMR3IsMmio2DirtyPageTrackingSupported(PVM pVM)
2983{
2984 RT_NOREF(pVM);
2985 return false;
2986}
2987
2988
2989VMMR3_INT_DECL(int) NEMR3NotifyPhysMmioExMapEarly(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, uint32_t fFlags,
2990 void *pvRam, void *pvMmio2, uint8_t *pu2State, uint32_t *puNemRange)
2991{
2992 RT_NOREF(pVM, puNemRange, pvRam, fFlags);
2993
2994 Log5(("NEMR3NotifyPhysMmioExMapEarly: %RGp LB %RGp fFlags=%#x pvRam=%p pvMmio2=%p pu2State=%p (%d)\n",
2995 GCPhys, cb, fFlags, pvRam, pvMmio2, pu2State, *pu2State));
2996
2997#if defined(VBOX_WITH_PGM_NEM_MODE)
2998 /*
2999 * Unmap the RAM we're replacing.
3000 */
3001 if (fFlags & NEM_NOTIFY_PHYS_MMIO_EX_F_REPLACE)
3002 {
3003 int rc = nemR3DarwinUnmap(pVM, GCPhys, cb);
3004 if (RT_SUCCESS(rc))
3005 { /* likely */ }
3006 else if (pvMmio2)
3007 LogRel(("NEMR3NotifyPhysMmioExMapEarly: GCPhys=%RGp LB %RGp fFlags=%#x: Unmap -> rc=%Rc(ignored)\n",
3008 GCPhys, cb, fFlags, rc));
3009 else
3010 {
3011 LogRel(("NEMR3NotifyPhysMmioExMapEarly: GCPhys=%RGp LB %RGp fFlags=%#x: Unmap -> rc=%Rrc\n",
3012 GCPhys, cb, fFlags, rc));
3013 return VERR_NEM_UNMAP_PAGES_FAILED;
3014 }
3015 }
3016
3017 /*
3018 * Map MMIO2 if any.
3019 */
3020 if (pvMmio2)
3021 {
3022 Assert(fFlags & NEM_NOTIFY_PHYS_MMIO_EX_F_MMIO2);
3023 int rc = nemR3DarwinMap(pVM, GCPhys, pvMmio2, cb, NEM_PAGE_PROT_READ | NEM_PAGE_PROT_WRITE | NEM_PAGE_PROT_EXECUTE);
3024 if (RT_SUCCESS(rc))
3025 *pu2State = NEM_DARWIN_PAGE_STATE_WRITABLE;
3026 else
3027 {
3028 LogRel(("NEMR3NotifyPhysMmioExMapEarly: GCPhys=%RGp LB %RGp fFlags=%#x pvMmio2=%p: Map -> rc=%Rrc\n",
3029 GCPhys, cb, fFlags, pvMmio2, rc));
3030 return VERR_NEM_MAP_PAGES_FAILED;
3031 }
3032 }
3033 else
3034 {
3035 Assert(!(fFlags & NEM_NOTIFY_PHYS_MMIO_EX_F_MMIO2));
3036 *pu2State = NEM_DARWIN_PAGE_STATE_UNMAPPED;
3037 }
3038
3039#else
3040 RT_NOREF(pVM, GCPhys, cb, pvRam, pvMmio2);
3041 *pu2State = (fFlags & NEM_NOTIFY_PHYS_MMIO_EX_F_REPLACE) ? UINT8_MAX : NEM_DARWIN_PAGE_STATE_UNMAPPED;
3042#endif
3043 return VINF_SUCCESS;
3044}
3045
3046
3047VMMR3_INT_DECL(int) NEMR3NotifyPhysMmioExMapLate(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, uint32_t fFlags,
3048 void *pvRam, void *pvMmio2, uint32_t *puNemRange)
3049{
3050 RT_NOREF(pVM, GCPhys, cb, fFlags, pvRam, pvMmio2, puNemRange);
3051 return VINF_SUCCESS;
3052}
3053
3054
3055VMMR3_INT_DECL(int) NEMR3NotifyPhysMmioExUnmap(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, uint32_t fFlags, void *pvRam,
3056 void *pvMmio2, uint8_t *pu2State, uint32_t *puNemRange)
3057{
3058 RT_NOREF(pVM, puNemRange);
3059
3060 Log5(("NEMR3NotifyPhysMmioExUnmap: %RGp LB %RGp fFlags=%#x pvRam=%p pvMmio2=%p pu2State=%p uNemRange=%#x (%#x)\n",
3061 GCPhys, cb, fFlags, pvRam, pvMmio2, pu2State, puNemRange, *puNemRange));
3062
3063 int rc = VINF_SUCCESS;
3064#if defined(VBOX_WITH_PGM_NEM_MODE)
3065 /*
3066 * Unmap the MMIO2 pages.
3067 */
3068 /** @todo If we implement aliasing (MMIO2 page aliased into MMIO range),
3069 * we may have more stuff to unmap even in case of pure MMIO... */
3070 if (fFlags & NEM_NOTIFY_PHYS_MMIO_EX_F_MMIO2)
3071 {
3072 rc = nemR3DarwinUnmap(pVM, GCPhys, cb);
3073 if (RT_FAILURE(rc))
3074 {
3075 LogRel2(("NEMR3NotifyPhysMmioExUnmap: GCPhys=%RGp LB %RGp fFlags=%#x: Unmap -> rc=%Rrc\n",
3076 GCPhys, cb, fFlags, rc));
3077 rc = VERR_NEM_UNMAP_PAGES_FAILED;
3078 }
3079 }
3080
3081 /*
3082 * Restore the RAM we replaced.
3083 */
3084 if (fFlags & NEM_NOTIFY_PHYS_MMIO_EX_F_REPLACE)
3085 {
3086 AssertPtr(pvRam);
3087 rc = nemR3DarwinMap(pVM, GCPhys, pvRam, cb, NEM_PAGE_PROT_READ | NEM_PAGE_PROT_WRITE | NEM_PAGE_PROT_EXECUTE);
3088 if (RT_SUCCESS(rc))
3089 { /* likely */ }
3090 else
3091 {
3092 LogRel(("NEMR3NotifyPhysMmioExUnmap: GCPhys=%RGp LB %RGp pvMmio2=%p rc=%Rrc\n", GCPhys, cb, pvMmio2, rc));
3093 rc = VERR_NEM_MAP_PAGES_FAILED;
3094 }
3095 if (pu2State)
3096 *pu2State = NEM_DARWIN_PAGE_STATE_WRITABLE;
3097 }
3098 /* Mark the pages as unmapped if relevant. */
3099 else if (pu2State)
3100 *pu2State = NEM_DARWIN_PAGE_STATE_UNMAPPED;
3101
3102 RT_NOREF(pvMmio2);
3103#else
3104 RT_NOREF(pVM, GCPhys, cb, fFlags, pvRam, pvMmio2, pu2State);
3105 if (pu2State)
3106 *pu2State = UINT8_MAX;
3107 rc = VERR_NEM_UNMAP_PAGES_FAILED;
3108#endif
3109 return rc;
3110}
3111
3112
3113VMMR3_INT_DECL(int) NEMR3PhysMmio2QueryAndResetDirtyBitmap(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, uint32_t uNemRange,
3114 void *pvBitmap, size_t cbBitmap)
3115{
3116 RT_NOREF(pVM, GCPhys, cb, uNemRange, pvBitmap, cbBitmap);
3117 AssertFailed();
3118 return VERR_NOT_IMPLEMENTED;
3119}
3120
3121
3122VMMR3_INT_DECL(int) NEMR3NotifyPhysRomRegisterEarly(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, void *pvPages, uint32_t fFlags,
3123 uint8_t *pu2State, uint32_t *puNemRange)
3124{
3125 RT_NOREF(pVM, GCPhys, cb, pvPages, fFlags, puNemRange);
3126
3127 Log5(("nemR3NativeNotifyPhysRomRegisterEarly: %RGp LB %RGp pvPages=%p fFlags=%#x\n", GCPhys, cb, pvPages, fFlags));
3128 *pu2State = UINT8_MAX;
3129 *puNemRange = 0;
3130 return VINF_SUCCESS;
3131}
3132
3133
3134VMMR3_INT_DECL(int) NEMR3NotifyPhysRomRegisterLate(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, void *pvPages,
3135 uint32_t fFlags, uint8_t *pu2State, uint32_t *puNemRange)
3136{
3137 Log5(("nemR3NativeNotifyPhysRomRegisterLate: %RGp LB %RGp pvPages=%p fFlags=%#x pu2State=%p (%d) puNemRange=%p (%#x)\n",
3138 GCPhys, cb, pvPages, fFlags, pu2State, *pu2State, puNemRange, *puNemRange));
3139 *pu2State = UINT8_MAX;
3140
3141#if defined(VBOX_WITH_PGM_NEM_MODE)
3142 /*
3143 * (Re-)map readonly.
3144 */
3145 AssertPtrReturn(pvPages, VERR_INVALID_POINTER);
3146 int rc = nemR3DarwinMap(pVM, GCPhys, pvPages, cb, NEM_PAGE_PROT_READ | NEM_PAGE_PROT_EXECUTE);
3147 if (RT_SUCCESS(rc))
3148 *pu2State = NEM_DARWIN_PAGE_STATE_READABLE;
3149 else
3150 {
3151 LogRel(("nemR3NativeNotifyPhysRomRegisterLate: GCPhys=%RGp LB %RGp pvPages=%p fFlags=%#x rc=%Rrc\n",
3152 GCPhys, cb, pvPages, fFlags, rc));
3153 return VERR_NEM_MAP_PAGES_FAILED;
3154 }
3155 RT_NOREF(pVM, fFlags, puNemRange);
3156 return VINF_SUCCESS;
3157#else
3158 RT_NOREF(pVM, GCPhys, cb, pvPages, fFlags, puNemRange);
3159 return VERR_NEM_MAP_PAGES_FAILED;
3160#endif
3161}
3162
3163
3164VMM_INT_DECL(void) NEMHCNotifyHandlerPhysicalDeregister(PVMCC pVM, PGMPHYSHANDLERKIND enmKind, RTGCPHYS GCPhys, RTGCPHYS cb,
3165 RTR3PTR pvMemR3, uint8_t *pu2State)
3166{
3167 RT_NOREF(pVM);
3168
3169 Log5(("NEMHCNotifyHandlerPhysicalDeregister: %RGp LB %RGp enmKind=%d pvMemR3=%p pu2State=%p (%d)\n",
3170 GCPhys, cb, enmKind, pvMemR3, pu2State, *pu2State));
3171
3172 *pu2State = UINT8_MAX;
3173#if defined(VBOX_WITH_PGM_NEM_MODE)
3174 if (pvMemR3)
3175 {
3176 int rc = nemR3DarwinMap(pVM, GCPhys, pvMemR3, cb, NEM_PAGE_PROT_READ | NEM_PAGE_PROT_WRITE | NEM_PAGE_PROT_EXECUTE);
3177 if (RT_SUCCESS(rc))
3178 *pu2State = NEM_DARWIN_PAGE_STATE_WRITABLE;
3179 else
3180 AssertLogRelMsgFailed(("NEMHCNotifyHandlerPhysicalDeregister: nemR3DarwinMap(,%p,%RGp,%RGp,) -> %Rrc\n",
3181 pvMemR3, GCPhys, cb, rc));
3182 }
3183 RT_NOREF(enmKind);
3184#else
3185 RT_NOREF(pVM, enmKind, GCPhys, cb, pvMemR3);
3186 AssertFailed();
3187#endif
3188}
3189
3190
3191static int nemHCJustUnmapPage(PVMCC pVM, RTGCPHYS GCPhysDst, uint8_t *pu2State)
3192{
3193 if (*pu2State <= NEM_DARWIN_PAGE_STATE_UNMAPPED)
3194 {
3195 Log5(("nemHCJustUnmapPage: %RGp == unmapped\n", GCPhysDst));
3196 *pu2State = NEM_DARWIN_PAGE_STATE_UNMAPPED;
3197 return VINF_SUCCESS;
3198 }
3199
3200 int rc = nemR3DarwinUnmap(pVM, GCPhysDst & ~(RTGCPHYS)X86_PAGE_OFFSET_MASK, X86_PAGE_SIZE);
3201 if (RT_SUCCESS(rc))
3202 {
3203 STAM_REL_COUNTER_INC(&pVM->nem.s.StatUnmapPage);
3204 *pu2State = NEM_DARWIN_PAGE_STATE_UNMAPPED;
3205 Log5(("nemHCJustUnmapPage: %RGp => unmapped\n", GCPhysDst));
3206 return VINF_SUCCESS;
3207 }
3208 STAM_REL_COUNTER_INC(&pVM->nem.s.StatUnmapPageFailed);
3209 LogRel(("nemHCJustUnmapPage(%RGp): failed! rc=%Rrc\n",
3210 GCPhysDst, rc));
3211 return VERR_NEM_IPE_6;
3212}
3213
3214
3215/**
3216 * Called when the A20 state changes.
3217 *
3218 * @param pVCpu The CPU the A20 state changed on.
3219 * @param fEnabled Whether it was enabled (true) or disabled.
3220 */
3221VMMR3_INT_DECL(void) NEMR3NotifySetA20(PVMCPU pVCpu, bool fEnabled)
3222{
3223 Log(("NEMR3NotifySetA20: fEnabled=%RTbool\n", fEnabled));
3224 RT_NOREF(pVCpu, fEnabled);
3225}
3226
3227
3228void nemHCNativeNotifyHandlerPhysicalRegister(PVMCC pVM, PGMPHYSHANDLERKIND enmKind, RTGCPHYS GCPhys, RTGCPHYS cb)
3229{
3230 Log5(("nemHCNativeNotifyHandlerPhysicalRegister: %RGp LB %RGp enmKind=%d\n", GCPhys, cb, enmKind));
3231 NOREF(pVM); NOREF(enmKind); NOREF(GCPhys); NOREF(cb);
3232}
3233
3234
3235void nemHCNativeNotifyHandlerPhysicalModify(PVMCC pVM, PGMPHYSHANDLERKIND enmKind, RTGCPHYS GCPhysOld,
3236 RTGCPHYS GCPhysNew, RTGCPHYS cb, bool fRestoreAsRAM)
3237{
3238 Log5(("nemHCNativeNotifyHandlerPhysicalModify: %RGp LB %RGp -> %RGp enmKind=%d fRestoreAsRAM=%d\n",
3239 GCPhysOld, cb, GCPhysNew, enmKind, fRestoreAsRAM));
3240 NOREF(pVM); NOREF(enmKind); NOREF(GCPhysOld); NOREF(GCPhysNew); NOREF(cb); NOREF(fRestoreAsRAM);
3241}
3242
3243
3244int nemHCNativeNotifyPhysPageAllocated(PVMCC pVM, RTGCPHYS GCPhys, RTHCPHYS HCPhys, uint32_t fPageProt,
3245 PGMPAGETYPE enmType, uint8_t *pu2State)
3246{
3247 Log5(("nemHCNativeNotifyPhysPageAllocated: %RGp HCPhys=%RHp fPageProt=%#x enmType=%d *pu2State=%d\n",
3248 GCPhys, HCPhys, fPageProt, enmType, *pu2State));
3249 RT_NOREF(HCPhys, fPageProt, enmType);
3250
3251 return nemHCJustUnmapPage(pVM, GCPhys, pu2State);
3252}
3253
3254
3255VMM_INT_DECL(void) NEMHCNotifyPhysPageProtChanged(PVMCC pVM, RTGCPHYS GCPhys, RTHCPHYS HCPhys, RTR3PTR pvR3, uint32_t fPageProt,
3256 PGMPAGETYPE enmType, uint8_t *pu2State)
3257{
3258 Log5(("NEMHCNotifyPhysPageProtChanged: %RGp HCPhys=%RHp fPageProt=%#x enmType=%d *pu2State=%d\n",
3259 GCPhys, HCPhys, fPageProt, enmType, *pu2State));
3260 RT_NOREF(HCPhys, pvR3, fPageProt, enmType)
3261
3262 nemHCJustUnmapPage(pVM, GCPhys, pu2State);
3263}
3264
3265
3266VMM_INT_DECL(void) NEMHCNotifyPhysPageChanged(PVMCC pVM, RTGCPHYS GCPhys, RTHCPHYS HCPhysPrev, RTHCPHYS HCPhysNew,
3267 RTR3PTR pvNewR3, uint32_t fPageProt, PGMPAGETYPE enmType, uint8_t *pu2State)
3268{
3269 Log5(("NEMHCNotifyPhysPageChanged: %RGp HCPhys=%RHp->%RHp fPageProt=%#x enmType=%d *pu2State=%d\n",
3270 GCPhys, HCPhysPrev, HCPhysNew, fPageProt, enmType, *pu2State));
3271 RT_NOREF(HCPhysPrev, HCPhysNew, pvNewR3, fPageProt, enmType);
3272
3273 nemHCJustUnmapPage(pVM, GCPhys, pu2State);
3274}
3275
3276
3277/**
3278 * Interface for importing state on demand (used by IEM).
3279 *
3280 * @returns VBox status code.
3281 * @param pVCpu The cross context CPU structure.
3282 * @param fWhat What to import, CPUMCTX_EXTRN_XXX.
3283 */
3284VMM_INT_DECL(int) NEMImportStateOnDemand(PVMCPUCC pVCpu, uint64_t fWhat)
3285{
3286 LogFlowFunc(("pVCpu=%p fWhat=%RX64\n", pVCpu, fWhat));
3287 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatImportOnDemand);
3288
3289 return nemR3DarwinCopyStateFromHv(pVCpu->pVMR3, pVCpu, fWhat);
3290}
3291
3292
3293/**
3294 * Query the CPU tick counter and optionally the TSC_AUX MSR value.
3295 *
3296 * @returns VBox status code.
3297 * @param pVCpu The cross context CPU structure.
3298 * @param pcTicks Where to return the CPU tick count.
3299 * @param puAux Where to return the TSC_AUX register value.
3300 */
3301VMM_INT_DECL(int) NEMHCQueryCpuTick(PVMCPUCC pVCpu, uint64_t *pcTicks, uint32_t *puAux)
3302{
3303 LogFlowFunc(("pVCpu=%p pcTicks=%RX64 puAux=%RX32\n", pVCpu, pcTicks, puAux));
3304 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatQueryCpuTick);
3305
3306 int rc = nemR3DarwinMsrRead(pVCpu, MSR_IA32_TSC, pcTicks);
3307 if ( RT_SUCCESS(rc)
3308 && puAux)
3309 {
3310 if (pVCpu->cpum.GstCtx.fExtrn & CPUMCTX_EXTRN_TSC_AUX)
3311 {
3312 /** @todo Why the heck is puAux a uint32_t?. */
3313 uint64_t u64Aux;
3314 rc = nemR3DarwinMsrRead(pVCpu, MSR_K8_TSC_AUX, &u64Aux);
3315 if (RT_SUCCESS(rc))
3316 *puAux = (uint32_t)u64Aux;
3317 }
3318 else
3319 *puAux = CPUMGetGuestTscAux(pVCpu);
3320 }
3321
3322 return rc;
3323}
3324
3325
3326/**
3327 * Resumes CPU clock (TSC) on all virtual CPUs.
3328 *
3329 * This is called by TM when the VM is started, restored, resumed or similar.
3330 *
3331 * @returns VBox status code.
3332 * @param pVM The cross context VM structure.
3333 * @param pVCpu The cross context CPU structure of the calling EMT.
3334 * @param uPausedTscValue The TSC value at the time of pausing.
3335 */
3336VMM_INT_DECL(int) NEMHCResumeCpuTickOnAll(PVMCC pVM, PVMCPUCC pVCpu, uint64_t uPausedTscValue)
3337{
3338 LogFlowFunc(("pVM=%p pVCpu=%p uPausedTscValue=%RX64\n", pVCpu, uPausedTscValue));
3339 VMCPU_ASSERT_EMT_RETURN(pVCpu, VERR_VM_THREAD_NOT_EMT);
3340 AssertReturn(VM_IS_NEM_ENABLED(pVM), VERR_NEM_IPE_9);
3341
3342 hv_return_t hrc = hv_vm_sync_tsc(uPausedTscValue);
3343 if (RT_LIKELY(hrc == HV_SUCCESS))
3344 {
3345 ASMAtomicUoAndU64(&pVCpu->nem.s.fCtxChanged, ~HM_CHANGED_GUEST_TSC_AUX);
3346 return VINF_SUCCESS;
3347 }
3348
3349 return nemR3DarwinHvSts2Rc(hrc);
3350}
3351
3352
3353/**
3354 * Returns features supported by the NEM backend.
3355 *
3356 * @returns Flags of features supported by the native NEM backend.
3357 * @param pVM The cross context VM structure.
3358 */
3359VMM_INT_DECL(uint32_t) NEMHCGetFeatures(PVMCC pVM)
3360{
3361 RT_NOREF(pVM);
3362 /*
3363 * Apple's Hypervisor.framework is not supported if the CPU doesn't support nested paging
3364 * and unrestricted guest execution support so we can safely return these flags here always.
3365 */
3366 return NEM_FEAT_F_NESTED_PAGING | NEM_FEAT_F_FULL_GST_EXEC | NEM_FEAT_F_XSAVE_XRSTOR;
3367}
3368
3369
3370/** @page pg_nem_darwin NEM/darwin - Native Execution Manager, macOS.
3371 *
3372 * @todo Add notes as the implementation progresses...
3373 */
3374
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette