VirtualBox

source: vbox/trunk/src/VBox/VMM/VMMR3/NEMR3Native-win-armv8.cpp@ 105702

Last change on this file since 105702 was 104672, checked in by vboxsync, 7 months ago

VMM/NEM: Pretty much work in progress Hyper-V on win.arm64 experiment, bugref:10392

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 124.4 KB
Line 
1/* $Id: NEMR3Native-win-armv8.cpp 104672 2024-05-16 10:50:35Z vboxsync $ */
2/** @file
3 * NEM - Native execution manager, native ring-3 Windows backend.
4 *
5 * Log group 2: Exit logging.
6 * Log group 3: Log context on exit.
7 * Log group 5: Ring-3 memory management
8 * Log group 6: Ring-0 memory management
9 * Log group 12: API intercepts.
10 */
11
12/*
13 * Copyright (C) 2018-2023 Oracle and/or its affiliates.
14 *
15 * This file is part of VirtualBox base platform packages, as
16 * available from https://www.virtualbox.org.
17 *
18 * This program is free software; you can redistribute it and/or
19 * modify it under the terms of the GNU General Public License
20 * as published by the Free Software Foundation, in version 3 of the
21 * License.
22 *
23 * This program is distributed in the hope that it will be useful, but
24 * WITHOUT ANY WARRANTY; without even the implied warranty of
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
26 * General Public License for more details.
27 *
28 * You should have received a copy of the GNU General Public License
29 * along with this program; if not, see <https://www.gnu.org/licenses>.
30 *
31 * SPDX-License-Identifier: GPL-3.0-only
32 */
33
34
35/*********************************************************************************************************************************
36* Header Files *
37*********************************************************************************************************************************/
38#define LOG_GROUP LOG_GROUP_NEM
39#define VMCPU_INCL_CPUM_GST_CTX
40#include <iprt/nt/nt-and-windows.h>
41#include <iprt/nt/hyperv.h>
42#include <WinHvPlatform.h>
43
44#ifndef _WIN32_WINNT_WIN10
45# error "Missing _WIN32_WINNT_WIN10"
46#endif
47#ifndef _WIN32_WINNT_WIN10_RS1 /* Missing define, causing trouble for us. */
48# define _WIN32_WINNT_WIN10_RS1 (_WIN32_WINNT_WIN10 + 1)
49#endif
50#include <sysinfoapi.h>
51#include <debugapi.h>
52#include <errhandlingapi.h>
53#include <fileapi.h>
54#include <winerror.h> /* no api header for this. */
55
56#include <VBox/vmm/nem.h>
57#include <VBox/vmm/iem.h>
58#include <VBox/vmm/em.h>
59#include <VBox/vmm/apic.h>
60#include <VBox/vmm/pdm.h>
61#include <VBox/vmm/dbgftrace.h>
62#include "NEMInternal.h"
63#include <VBox/vmm/vmcc.h>
64
65#include <iprt/ldr.h>
66#include <iprt/path.h>
67#include <iprt/string.h>
68#include <iprt/system.h>
69#include <iprt/utf16.h>
70
71#ifndef NTDDI_WIN10_VB /* Present in W10 2004 SDK, quite possibly earlier. */
72HRESULT WINAPI WHvQueryGpaRangeDirtyBitmap(WHV_PARTITION_HANDLE, WHV_GUEST_PHYSICAL_ADDRESS, UINT64, UINT64 *, UINT32);
73# define WHvMapGpaRangeFlagTrackDirtyPages ((WHV_MAP_GPA_RANGE_FLAGS)0x00000008)
74#endif
75
76
77/*********************************************************************************************************************************
78* Defined Constants And Macros *
79*********************************************************************************************************************************/
80
81
82/*********************************************************************************************************************************
83* Global Variables *
84*********************************************************************************************************************************/
85/** @name APIs imported from WinHvPlatform.dll
86 * @{ */
87static decltype(WHvGetCapability) * g_pfnWHvGetCapability;
88static decltype(WHvCreatePartition) * g_pfnWHvCreatePartition;
89static decltype(WHvSetupPartition) * g_pfnWHvSetupPartition;
90static decltype(WHvDeletePartition) * g_pfnWHvDeletePartition;
91static decltype(WHvGetPartitionProperty) * g_pfnWHvGetPartitionProperty;
92static decltype(WHvSetPartitionProperty) * g_pfnWHvSetPartitionProperty;
93static decltype(WHvMapGpaRange) * g_pfnWHvMapGpaRange;
94static decltype(WHvUnmapGpaRange) * g_pfnWHvUnmapGpaRange;
95static decltype(WHvTranslateGva) * g_pfnWHvTranslateGva;
96static decltype(WHvQueryGpaRangeDirtyBitmap) * g_pfnWHvQueryGpaRangeDirtyBitmap;
97static decltype(WHvCreateVirtualProcessor) * g_pfnWHvCreateVirtualProcessor;
98static decltype(WHvDeleteVirtualProcessor) * g_pfnWHvDeleteVirtualProcessor;
99static decltype(WHvRunVirtualProcessor) * g_pfnWHvRunVirtualProcessor;
100static decltype(WHvCancelRunVirtualProcessor) * g_pfnWHvCancelRunVirtualProcessor;
101static decltype(WHvGetVirtualProcessorRegisters) * g_pfnWHvGetVirtualProcessorRegisters;
102static decltype(WHvSetVirtualProcessorRegisters) * g_pfnWHvSetVirtualProcessorRegisters;
103/** @} */
104
105/** The Windows build number. */
106static uint32_t g_uBuildNo = 17134;
107
108
109
110/**
111 * Import instructions.
112 */
113static const struct
114{
115 uint8_t idxDll; /**< 0 for WinHvPlatform.dll, 1 for vid.dll. */
116 bool fOptional; /**< Set if import is optional. */
117 PFNRT *ppfn; /**< The function pointer variable. */
118 const char *pszName; /**< The function name. */
119} g_aImports[] =
120{
121#define NEM_WIN_IMPORT(a_idxDll, a_fOptional, a_Name) { (a_idxDll), (a_fOptional), (PFNRT *)&RT_CONCAT(g_pfn,a_Name), #a_Name }
122 NEM_WIN_IMPORT(0, false, WHvGetCapability),
123 NEM_WIN_IMPORT(0, false, WHvCreatePartition),
124 NEM_WIN_IMPORT(0, false, WHvSetupPartition),
125 NEM_WIN_IMPORT(0, false, WHvDeletePartition),
126 NEM_WIN_IMPORT(0, false, WHvGetPartitionProperty),
127 NEM_WIN_IMPORT(0, false, WHvSetPartitionProperty),
128 NEM_WIN_IMPORT(0, false, WHvMapGpaRange),
129 NEM_WIN_IMPORT(0, false, WHvUnmapGpaRange),
130 NEM_WIN_IMPORT(0, false, WHvTranslateGva),
131 NEM_WIN_IMPORT(0, true, WHvQueryGpaRangeDirtyBitmap),
132 NEM_WIN_IMPORT(0, false, WHvCreateVirtualProcessor),
133 NEM_WIN_IMPORT(0, false, WHvDeleteVirtualProcessor),
134 NEM_WIN_IMPORT(0, false, WHvRunVirtualProcessor),
135 NEM_WIN_IMPORT(0, false, WHvCancelRunVirtualProcessor),
136 NEM_WIN_IMPORT(0, false, WHvGetVirtualProcessorRegisters),
137 NEM_WIN_IMPORT(0, false, WHvSetVirtualProcessorRegisters),
138#undef NEM_WIN_IMPORT
139};
140
141
142/*
143 * Let the preprocessor alias the APIs to import variables for better autocompletion.
144 */
145#ifndef IN_SLICKEDIT
146# define WHvGetCapability g_pfnWHvGetCapability
147# define WHvCreatePartition g_pfnWHvCreatePartition
148# define WHvSetupPartition g_pfnWHvSetupPartition
149# define WHvDeletePartition g_pfnWHvDeletePartition
150# define WHvGetPartitionProperty g_pfnWHvGetPartitionProperty
151# define WHvSetPartitionProperty g_pfnWHvSetPartitionProperty
152# define WHvMapGpaRange g_pfnWHvMapGpaRange
153# define WHvUnmapGpaRange g_pfnWHvUnmapGpaRange
154# define WHvTranslateGva g_pfnWHvTranslateGva
155# define WHvQueryGpaRangeDirtyBitmap g_pfnWHvQueryGpaRangeDirtyBitmap
156# define WHvCreateVirtualProcessor g_pfnWHvCreateVirtualProcessor
157# define WHvDeleteVirtualProcessor g_pfnWHvDeleteVirtualProcessor
158# define WHvRunVirtualProcessor g_pfnWHvRunVirtualProcessor
159# define WHvGetRunExitContextSize g_pfnWHvGetRunExitContextSize
160# define WHvCancelRunVirtualProcessor g_pfnWHvCancelRunVirtualProcessor
161# define WHvGetVirtualProcessorRegisters g_pfnWHvGetVirtualProcessorRegisters
162# define WHvSetVirtualProcessorRegisters g_pfnWHvSetVirtualProcessorRegisters
163
164# define VidMessageSlotHandleAndGetNext g_pfnVidMessageSlotHandleAndGetNext
165# define VidStartVirtualProcessor g_pfnVidStartVirtualProcessor
166# define VidStopVirtualProcessor g_pfnVidStopVirtualProcessor
167
168#endif
169
170/** WHV_MEMORY_ACCESS_TYPE names */
171static const char * const g_apszWHvMemAccesstypes[4] = { "read", "write", "exec", "!undefined!" };
172/** NEM_WIN_PAGE_STATE_XXX names. */
173NEM_TMPL_STATIC const char * const g_apszPageStates[4] = { "not-set", "unmapped", "readable", "writable" };
174/** HV_INTERCEPT_ACCESS_TYPE names. */
175static const char * const g_apszHvInterceptAccessTypes[4] = { "read", "write", "exec", "!undefined!" };
176
177
178/*********************************************************************************************************************************
179* Internal Functions *
180*********************************************************************************************************************************/
181DECLINLINE(int) nemR3NativeGCPhys2R3PtrReadOnly(PVM pVM, RTGCPHYS GCPhys, const void **ppv);
182DECLINLINE(int) nemR3NativeGCPhys2R3PtrWriteable(PVM pVM, RTGCPHYS GCPhys, void **ppv);
183
184NEM_TMPL_STATIC int nemHCNativeSetPhysPage(PVMCC pVM, PVMCPUCC pVCpu, RTGCPHYS GCPhysSrc, RTGCPHYS GCPhysDst,
185 uint32_t fPageProt, uint8_t *pu2State, bool fBackingChanged);
186
187/**
188 * Worker for nemR3NativeInit that probes and load the native API.
189 *
190 * @returns VBox status code.
191 * @param fForced Whether the HMForced flag is set and we should
192 * fail if we cannot initialize.
193 * @param pErrInfo Where to always return error info.
194 */
195static int nemR3WinInitProbeAndLoad(bool fForced, PRTERRINFO pErrInfo)
196{
197 /*
198 * Check that the DLL files we need are present, but without loading them.
199 * We'd like to avoid loading them unnecessarily.
200 */
201 WCHAR wszPath[MAX_PATH + 64];
202 UINT cwcPath = GetSystemDirectoryW(wszPath, MAX_PATH);
203 if (cwcPath >= MAX_PATH || cwcPath < 2)
204 return RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED, "GetSystemDirectoryW failed (%#x / %u)", cwcPath, GetLastError());
205
206 if (wszPath[cwcPath - 1] != '\\' || wszPath[cwcPath - 1] != '/')
207 wszPath[cwcPath++] = '\\';
208 RTUtf16CopyAscii(&wszPath[cwcPath], RT_ELEMENTS(wszPath) - cwcPath, "WinHvPlatform.dll");
209 if (GetFileAttributesW(wszPath) == INVALID_FILE_ATTRIBUTES)
210 return RTErrInfoSetF(pErrInfo, VERR_NEM_NOT_AVAILABLE, "The native API dll was not found (%ls)", wszPath);
211
212 /*
213 * Check that we're in a VM and that the hypervisor identifies itself as Hyper-V.
214 */
215 /** @todo */
216
217 /** @todo would be great if we could recognize a root partition from the
218 * CPUID info, but I currently don't dare do that. */
219
220 /*
221 * Now try load the DLLs and resolve the APIs.
222 */
223 static const char * const s_apszDllNames[1] = { "WinHvPlatform.dll" };
224 RTLDRMOD ahMods[1] = { NIL_RTLDRMOD };
225 int rc = VINF_SUCCESS;
226 for (unsigned i = 0; i < RT_ELEMENTS(s_apszDllNames); i++)
227 {
228 int rc2 = RTLdrLoadSystem(s_apszDllNames[i], true /*fNoUnload*/, &ahMods[i]);
229 if (RT_FAILURE(rc2))
230 {
231 if (!RTErrInfoIsSet(pErrInfo))
232 RTErrInfoSetF(pErrInfo, rc2, "Failed to load API DLL: %s: %Rrc", s_apszDllNames[i], rc2);
233 else
234 RTErrInfoAddF(pErrInfo, rc2, "; %s: %Rrc", s_apszDllNames[i], rc2);
235 ahMods[i] = NIL_RTLDRMOD;
236 rc = VERR_NEM_INIT_FAILED;
237 }
238 }
239 if (RT_SUCCESS(rc))
240 {
241 for (unsigned i = 0; i < RT_ELEMENTS(g_aImports); i++)
242 {
243 int rc2 = RTLdrGetSymbol(ahMods[g_aImports[i].idxDll], g_aImports[i].pszName, (void **)g_aImports[i].ppfn);
244 if (RT_SUCCESS(rc2))
245 {
246 if (g_aImports[i].fOptional)
247 LogRel(("NEM: info: Found optional import %s!%s.\n",
248 s_apszDllNames[g_aImports[i].idxDll], g_aImports[i].pszName));
249 }
250 else
251 {
252 *g_aImports[i].ppfn = NULL;
253
254 LogRel(("NEM: %s: Failed to import %s!%s: %Rrc",
255 g_aImports[i].fOptional ? "info" : fForced ? "fatal" : "error",
256 s_apszDllNames[g_aImports[i].idxDll], g_aImports[i].pszName, rc2));
257 if (!g_aImports[i].fOptional)
258 {
259 if (RTErrInfoIsSet(pErrInfo))
260 RTErrInfoAddF(pErrInfo, rc2, ", %s!%s",
261 s_apszDllNames[g_aImports[i].idxDll], g_aImports[i].pszName);
262 else
263 rc = RTErrInfoSetF(pErrInfo, rc2, "Failed to import: %s!%s",
264 s_apszDllNames[g_aImports[i].idxDll], g_aImports[i].pszName);
265 Assert(RT_FAILURE(rc));
266 }
267 }
268 }
269 if (RT_SUCCESS(rc))
270 {
271 Assert(!RTErrInfoIsSet(pErrInfo));
272 }
273 }
274
275 for (unsigned i = 0; i < RT_ELEMENTS(ahMods); i++)
276 RTLdrClose(ahMods[i]);
277 return rc;
278}
279
280
281/**
282 * Wrapper for different WHvGetCapability signatures.
283 */
284DECLINLINE(HRESULT) WHvGetCapabilityWrapper(WHV_CAPABILITY_CODE enmCap, WHV_CAPABILITY *pOutput, uint32_t cbOutput)
285{
286 return g_pfnWHvGetCapability(enmCap, pOutput, cbOutput, NULL);
287}
288
289
290/**
291 * Worker for nemR3NativeInit that gets the hypervisor capabilities.
292 *
293 * @returns VBox status code.
294 * @param pVM The cross context VM structure.
295 * @param pErrInfo Where to always return error info.
296 */
297static int nemR3WinInitCheckCapabilities(PVM pVM, PRTERRINFO pErrInfo)
298{
299#define NEM_LOG_REL_CAP_EX(a_szField, a_szFmt, a_Value) LogRel(("NEM: %-38s= " a_szFmt "\n", a_szField, a_Value))
300#define NEM_LOG_REL_CAP_SUB_EX(a_szField, a_szFmt, a_Value) LogRel(("NEM: %36s: " a_szFmt "\n", a_szField, a_Value))
301#define NEM_LOG_REL_CAP_SUB(a_szField, a_Value) NEM_LOG_REL_CAP_SUB_EX(a_szField, "%d", a_Value)
302
303 /*
304 * Is the hypervisor present with the desired capability?
305 *
306 * In build 17083 this translates into:
307 * - CPUID[0x00000001].HVP is set
308 * - CPUID[0x40000000] == "Microsoft Hv"
309 * - CPUID[0x40000001].eax == "Hv#1"
310 * - CPUID[0x40000003].ebx[12] is set.
311 * - VidGetExoPartitionProperty(INVALID_HANDLE_VALUE, 0x60000, &Ignored) returns
312 * a non-zero value.
313 */
314 /**
315 * @todo Someone at Microsoft please explain weird API design:
316 * 1. Pointless CapabilityCode duplication int the output;
317 * 2. No output size.
318 */
319 WHV_CAPABILITY Caps;
320 RT_ZERO(Caps);
321 SetLastError(0);
322 HRESULT hrc = WHvGetCapabilityWrapper(WHvCapabilityCodeHypervisorPresent, &Caps, sizeof(Caps));
323 DWORD rcWin = GetLastError();
324 if (FAILED(hrc))
325 return RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED,
326 "WHvGetCapability/WHvCapabilityCodeHypervisorPresent failed: %Rhrc (Last=%#x/%u)",
327 hrc, RTNtLastStatusValue(), RTNtLastErrorValue());
328 if (!Caps.HypervisorPresent)
329 {
330 if (!RTPathExists(RTPATH_NT_PASSTHRU_PREFIX "Device\\VidExo"))
331 return RTErrInfoSetF(pErrInfo, VERR_NEM_NOT_AVAILABLE,
332 "WHvCapabilityCodeHypervisorPresent is FALSE! Make sure you have enabled the 'Windows Hypervisor Platform' feature.");
333 return RTErrInfoSetF(pErrInfo, VERR_NEM_NOT_AVAILABLE, "WHvCapabilityCodeHypervisorPresent is FALSE! (%u)", rcWin);
334 }
335 LogRel(("NEM: WHvCapabilityCodeHypervisorPresent is TRUE, so this might work...\n"));
336
337
338 /*
339 * Check what extended VM exits are supported.
340 */
341 RT_ZERO(Caps);
342 hrc = WHvGetCapabilityWrapper(WHvCapabilityCodeExtendedVmExits, &Caps, sizeof(Caps));
343 if (FAILED(hrc))
344 return RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED,
345 "WHvGetCapability/WHvCapabilityCodeExtendedVmExits failed: %Rhrc (Last=%#x/%u)",
346 hrc, RTNtLastStatusValue(), RTNtLastErrorValue());
347 NEM_LOG_REL_CAP_EX("WHvCapabilityCodeExtendedVmExits", "%'#018RX64", Caps.ExtendedVmExits.AsUINT64);
348 pVM->nem.s.fHypercallExit = RT_BOOL(Caps.ExtendedVmExits.HypercallExit);
349 pVM->nem.s.fGpaAccessFaultExit = RT_BOOL(Caps.ExtendedVmExits.GpaAccessFaultExit);
350 NEM_LOG_REL_CAP_SUB("fHypercallExit", pVM->nem.s.fHypercallExit);
351 NEM_LOG_REL_CAP_SUB("fGpaAccessFaultExit", pVM->nem.s.fGpaAccessFaultExit);
352 if (Caps.ExtendedVmExits.AsUINT64 & ~(uint64_t)7)
353 LogRel(("NEM: Warning! Unknown VM exit definitions: %#RX64\n", Caps.ExtendedVmExits.AsUINT64));
354 /** @todo RECHECK: WHV_EXTENDED_VM_EXITS typedef. */
355
356 /*
357 * Check features in case they end up defining any.
358 */
359 RT_ZERO(Caps);
360 hrc = WHvGetCapabilityWrapper(WHvCapabilityCodeFeatures, &Caps, sizeof(Caps));
361 if (FAILED(hrc))
362 return RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED,
363 "WHvGetCapability/WHvCapabilityCodeFeatures failed: %Rhrc (Last=%#x/%u)",
364 hrc, RTNtLastStatusValue(), RTNtLastErrorValue());
365 if (Caps.Features.AsUINT64 & ~(uint64_t)0)
366 LogRel(("NEM: Warning! Unknown feature definitions: %#RX64\n", Caps.Features.AsUINT64));
367 /** @todo RECHECK: WHV_CAPABILITY_FEATURES typedef. */
368
369 /*
370 * Check that the CPU vendor is supported.
371 */
372 RT_ZERO(Caps);
373 hrc = WHvGetCapabilityWrapper(WHvCapabilityCodeProcessorVendor, &Caps, sizeof(Caps));
374 if (FAILED(hrc))
375 return RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED,
376 "WHvGetCapability/WHvCapabilityCodeProcessorVendor failed: %Rhrc (Last=%#x/%u)",
377 hrc, RTNtLastStatusValue(), RTNtLastErrorValue());
378 switch (Caps.ProcessorVendor)
379 {
380 /** @todo RECHECK: WHV_PROCESSOR_VENDOR typedef. */
381 case WHvProcessorVendorArm:
382 NEM_LOG_REL_CAP_EX("WHvCapabilityCodeProcessorVendor", "%d - ARM", Caps.ProcessorVendor);
383 pVM->nem.s.enmCpuVendor = CPUMCPUVENDOR_UNKNOWN;
384 break;
385 default:
386 NEM_LOG_REL_CAP_EX("WHvCapabilityCodeProcessorVendor", "%d", Caps.ProcessorVendor);
387 return RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED, "Unknown processor vendor: %d", Caps.ProcessorVendor);
388 }
389
390 /*
391 * CPU features, guessing these are virtual CPU features?
392 */
393 RT_ZERO(Caps);
394 hrc = WHvGetCapabilityWrapper(WHvCapabilityCodeProcessorFeatures, &Caps, sizeof(Caps));
395 if (FAILED(hrc))
396 return RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED,
397 "WHvGetCapability/WHvCapabilityCodeProcessorFeatures failed: %Rhrc (Last=%#x/%u)",
398 hrc, RTNtLastStatusValue(), RTNtLastErrorValue());
399 NEM_LOG_REL_CAP_EX("WHvCapabilityCodeProcessorFeatures", "%'#018RX64", Caps.ProcessorFeatures.AsUINT64);
400#define NEM_LOG_REL_CPU_FEATURE(a_Field) NEM_LOG_REL_CAP_SUB(#a_Field, Caps.ProcessorFeatures.a_Field)
401 NEM_LOG_REL_CPU_FEATURE(Asid16);
402 NEM_LOG_REL_CPU_FEATURE(TGran16);
403 NEM_LOG_REL_CPU_FEATURE(TGran64);
404 NEM_LOG_REL_CPU_FEATURE(Haf);
405 NEM_LOG_REL_CPU_FEATURE(Hdbs);
406 NEM_LOG_REL_CPU_FEATURE(Pan);
407 NEM_LOG_REL_CPU_FEATURE(AtS1E1);
408 NEM_LOG_REL_CPU_FEATURE(Uao);
409 NEM_LOG_REL_CPU_FEATURE(El0Aarch32);
410 NEM_LOG_REL_CPU_FEATURE(Fp);
411 NEM_LOG_REL_CPU_FEATURE(FpHp);
412 NEM_LOG_REL_CPU_FEATURE(AdvSimd);
413 NEM_LOG_REL_CPU_FEATURE(AdvSimdHp);
414 NEM_LOG_REL_CPU_FEATURE(GicV3V4);
415 NEM_LOG_REL_CPU_FEATURE(GicV41);
416 NEM_LOG_REL_CPU_FEATURE(Ras);
417 NEM_LOG_REL_CPU_FEATURE(PmuV3);
418 NEM_LOG_REL_CPU_FEATURE(PmuV3ArmV81);
419 NEM_LOG_REL_CPU_FEATURE(PmuV3ArmV84);
420 NEM_LOG_REL_CPU_FEATURE(PmuV3ArmV85);
421 NEM_LOG_REL_CPU_FEATURE(Aes);
422 NEM_LOG_REL_CPU_FEATURE(PolyMul);
423 NEM_LOG_REL_CPU_FEATURE(Sha1);
424 NEM_LOG_REL_CPU_FEATURE(Sha256);
425 NEM_LOG_REL_CPU_FEATURE(Sha512);
426 NEM_LOG_REL_CPU_FEATURE(Crc32);
427 NEM_LOG_REL_CPU_FEATURE(Atomic);
428 NEM_LOG_REL_CPU_FEATURE(Rdm);
429 NEM_LOG_REL_CPU_FEATURE(Sha3);
430 NEM_LOG_REL_CPU_FEATURE(Sm3);
431 NEM_LOG_REL_CPU_FEATURE(Sm4);
432 NEM_LOG_REL_CPU_FEATURE(Dp);
433 NEM_LOG_REL_CPU_FEATURE(Fhm);
434 NEM_LOG_REL_CPU_FEATURE(DcCvap);
435 NEM_LOG_REL_CPU_FEATURE(DcCvadp);
436 NEM_LOG_REL_CPU_FEATURE(ApaBase);
437 NEM_LOG_REL_CPU_FEATURE(ApaEp);
438 NEM_LOG_REL_CPU_FEATURE(ApaEp2);
439 NEM_LOG_REL_CPU_FEATURE(ApaEp2Fp);
440 NEM_LOG_REL_CPU_FEATURE(ApaEp2Fpc);
441 NEM_LOG_REL_CPU_FEATURE(Jscvt);
442 NEM_LOG_REL_CPU_FEATURE(Fcma);
443 NEM_LOG_REL_CPU_FEATURE(RcpcV83);
444 NEM_LOG_REL_CPU_FEATURE(RcpcV84);
445 NEM_LOG_REL_CPU_FEATURE(Gpa);
446 NEM_LOG_REL_CPU_FEATURE(L1ipPipt);
447 NEM_LOG_REL_CPU_FEATURE(DzPermitted);
448
449#undef NEM_LOG_REL_CPU_FEATURE
450 if (Caps.ProcessorFeatures.AsUINT64 & (~(RT_BIT_64(47) - 1)))
451 LogRel(("NEM: Warning! Unknown CPU features: %#RX64\n", Caps.ProcessorFeatures.AsUINT64));
452 pVM->nem.s.uCpuFeatures.u64 = Caps.ProcessorFeatures.AsUINT64;
453 /** @todo RECHECK: WHV_PROCESSOR_FEATURES typedef. */
454
455 /*
456 * The cache line flush size.
457 */
458 RT_ZERO(Caps);
459 hrc = WHvGetCapabilityWrapper(WHvCapabilityCodeProcessorClFlushSize, &Caps, sizeof(Caps));
460 if (FAILED(hrc))
461 return RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED,
462 "WHvGetCapability/WHvCapabilityCodeProcessorClFlushSize failed: %Rhrc (Last=%#x/%u)",
463 hrc, RTNtLastStatusValue(), RTNtLastErrorValue());
464 NEM_LOG_REL_CAP_EX("WHvCapabilityCodeProcessorClFlushSize", "2^%u", Caps.ProcessorClFlushSize);
465 if (Caps.ProcessorClFlushSize < 8 && Caps.ProcessorClFlushSize > 9)
466 return RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED, "Unsupported cache line flush size: %u", Caps.ProcessorClFlushSize);
467 pVM->nem.s.cCacheLineFlushShift = Caps.ProcessorClFlushSize;
468
469 RT_ZERO(Caps);
470 hrc = WHvGetCapabilityWrapper(WHvCapabilityCodePhysicalAddressWidth, &Caps, sizeof(Caps));
471 if (FAILED(hrc))
472 return RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED,
473 "WHvGetCapability/WHvCapabilityCodePhysicalAddressWidth failed: %Rhrc (Last=%#x/%u)",
474 hrc, RTNtLastStatusValue(), RTNtLastErrorValue());
475 NEM_LOG_REL_CAP_EX("WHvCapabilityCodePhysicalAddressWidth", "2^%u", Caps.PhysicalAddressWidth);
476 if (Caps.PhysicalAddressWidth < 32 && Caps.PhysicalAddressWidth > 52)
477 return RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED, "Unsupported physical address width: %u", Caps.ProcessorClFlushSize);
478 pVM->nem.s.cPhysicalAddressWidth = Caps.PhysicalAddressWidth;
479
480
481 /*
482 * See if they've added more properties that we're not aware of.
483 */
484 /** @todo RECHECK: WHV_CAPABILITY_CODE typedef. */
485 if (!IsDebuggerPresent()) /* Too noisy when in debugger, so skip. */
486 {
487 static const struct
488 {
489 uint32_t iMin, iMax; } s_aUnknowns[] =
490 {
491 { 0x0004, 0x000f },
492 { 0x1003, 0x100f },
493 { 0x2000, 0x200f },
494 { 0x3000, 0x300f },
495 { 0x4000, 0x400f },
496 };
497 for (uint32_t j = 0; j < RT_ELEMENTS(s_aUnknowns); j++)
498 for (uint32_t i = s_aUnknowns[j].iMin; i <= s_aUnknowns[j].iMax; i++)
499 {
500 RT_ZERO(Caps);
501 hrc = WHvGetCapabilityWrapper((WHV_CAPABILITY_CODE)i, &Caps, sizeof(Caps));
502 if (SUCCEEDED(hrc))
503 LogRel(("NEM: Warning! Unknown capability %#x returning: %.*Rhxs\n", i, sizeof(Caps), &Caps));
504 }
505 }
506
507 /*
508 * For proper operation, we require CPUID exits.
509 */
510 /** @todo Any? */
511
512#undef NEM_LOG_REL_CAP_EX
513#undef NEM_LOG_REL_CAP_SUB_EX
514#undef NEM_LOG_REL_CAP_SUB
515 return VINF_SUCCESS;
516}
517
518
519/**
520 * Creates and sets up a Hyper-V (exo) partition.
521 *
522 * @returns VBox status code.
523 * @param pVM The cross context VM structure.
524 * @param pErrInfo Where to always return error info.
525 */
526static int nemR3WinInitCreatePartition(PVM pVM, PRTERRINFO pErrInfo)
527{
528 AssertReturn(!pVM->nem.s.hPartition, RTErrInfoSet(pErrInfo, VERR_WRONG_ORDER, "Wrong initalization order"));
529 AssertReturn(!pVM->nem.s.hPartitionDevice, RTErrInfoSet(pErrInfo, VERR_WRONG_ORDER, "Wrong initalization order"));
530
531 /*
532 * Create the partition.
533 */
534 WHV_PARTITION_HANDLE hPartition;
535 HRESULT hrc = WHvCreatePartition(&hPartition);
536 if (FAILED(hrc))
537 return RTErrInfoSetF(pErrInfo, VERR_NEM_VM_CREATE_FAILED, "WHvCreatePartition failed with %Rhrc (Last=%#x/%u)",
538 hrc, RTNtLastStatusValue(), RTNtLastErrorValue());
539
540 int rc;
541
542 /*
543 * Set partition properties, most importantly the CPU count.
544 */
545 /**
546 * @todo Someone at Microsoft please explain another weird API:
547 * - Why this API doesn't take the WHV_PARTITION_PROPERTY_CODE value as an
548 * argument rather than as part of the struct. That is so weird if you've
549 * used any other NT or windows API, including WHvGetCapability().
550 * - Why use PVOID when WHV_PARTITION_PROPERTY is what's expected. We
551 * technically only need 9 bytes for setting/getting
552 * WHVPartitionPropertyCodeProcessorClFlushSize, but the API insists on 16. */
553 WHV_PARTITION_PROPERTY Property;
554 RT_ZERO(Property);
555 Property.ProcessorCount = pVM->cCpus;
556 hrc = WHvSetPartitionProperty(hPartition, WHvPartitionPropertyCodeProcessorCount, &Property, sizeof(Property));
557 if (SUCCEEDED(hrc))
558 {
559 RT_ZERO(Property);
560 Property.ExtendedVmExits.HypercallExit = pVM->nem.s.fHypercallExit;
561 hrc = WHvSetPartitionProperty(hPartition, WHvPartitionPropertyCodeExtendedVmExits, &Property, sizeof(Property));
562 if (SUCCEEDED(hrc))
563 {
564 /*
565 * We'll continue setup in nemR3NativeInitAfterCPUM.
566 */
567 pVM->nem.s.fCreatedEmts = false;
568 pVM->nem.s.hPartition = hPartition;
569 LogRel(("NEM: Created partition %p.\n", hPartition));
570 return VINF_SUCCESS;
571 }
572
573 rc = RTErrInfoSetF(pErrInfo, VERR_NEM_VM_CREATE_FAILED,
574 "Failed setting WHvPartitionPropertyCodeExtendedVmExits to %'#RX64: %Rhrc",
575 Property.ExtendedVmExits.AsUINT64, hrc);
576 }
577 else
578 rc = RTErrInfoSetF(pErrInfo, VERR_NEM_VM_CREATE_FAILED,
579 "Failed setting WHvPartitionPropertyCodeProcessorCount to %u: %Rhrc (Last=%#x/%u)",
580 pVM->cCpus, hrc, RTNtLastStatusValue(), RTNtLastErrorValue());
581 WHvDeletePartition(hPartition);
582
583 Assert(!pVM->nem.s.hPartitionDevice);
584 Assert(!pVM->nem.s.hPartition);
585 return rc;
586}
587
588
589static int nemR3NativeInitSetupVm(PVM pVM)
590{
591 WHV_PARTITION_HANDLE hPartition = pVM->nem.s.hPartition;
592 AssertReturn(hPartition != NULL, VERR_WRONG_ORDER);
593 AssertReturn(!pVM->nem.s.hPartitionDevice, VERR_WRONG_ORDER);
594 AssertReturn(!pVM->nem.s.fCreatedEmts, VERR_WRONG_ORDER);
595
596 /*
597 * Continue setting up the partition now that we've got most of the CPUID feature stuff.
598 */
599 WHV_PARTITION_PROPERTY Property;
600 HRESULT hrc;
601
602#if 0
603 /* Not sure if we really need to set the vendor.
604 Update: Apparently we don't. WHvPartitionPropertyCodeProcessorVendor was removed in 17110. */
605 RT_ZERO(Property);
606 Property.ProcessorVendor = pVM->nem.s.enmCpuVendor == CPUMCPUVENDOR_AMD ? WHvProcessorVendorAmd
607 : WHvProcessorVendorIntel;
608 hrc = WHvSetPartitionProperty(hPartition, WHvPartitionPropertyCodeProcessorVendor, &Property, sizeof(Property));
609 if (FAILED(hrc))
610 return VMSetError(pVM, VERR_NEM_VM_CREATE_FAILED, RT_SRC_POS,
611 "Failed to set WHvPartitionPropertyCodeProcessorVendor to %u: %Rhrc (Last=%#x/%u)",
612 Property.ProcessorVendor, hrc, RTNtLastStatusValue(), RTNtLastErrorValue());
613#endif
614
615 /* Not sure if we really need to set the cache line flush size. */
616 RT_ZERO(Property);
617 Property.ProcessorClFlushSize = pVM->nem.s.cCacheLineFlushShift;
618 hrc = WHvSetPartitionProperty(hPartition, WHvPartitionPropertyCodeProcessorClFlushSize, &Property, sizeof(Property));
619 if (FAILED(hrc))
620 return VMSetError(pVM, VERR_NEM_VM_CREATE_FAILED, RT_SRC_POS,
621 "Failed to set WHvPartitionPropertyCodeProcessorClFlushSize to %u: %Rhrc (Last=%#x/%u)",
622 pVM->nem.s.cCacheLineFlushShift, hrc, RTNtLastStatusValue(), RTNtLastErrorValue());
623
624 /*
625 * Sync CPU features with CPUM.
626 */
627 /** @todo sync CPU features with CPUM. */
628
629 /* Set the partition property. */
630 RT_ZERO(Property);
631 Property.ProcessorFeatures.AsUINT64 = pVM->nem.s.uCpuFeatures.u64;
632 hrc = WHvSetPartitionProperty(hPartition, WHvPartitionPropertyCodeProcessorFeatures, &Property, sizeof(Property));
633 if (FAILED(hrc))
634 return VMSetError(pVM, VERR_NEM_VM_CREATE_FAILED, RT_SRC_POS,
635 "Failed to set WHvPartitionPropertyCodeProcessorFeatures to %'#RX64: %Rhrc (Last=%#x/%u)",
636 pVM->nem.s.uCpuFeatures.u64, hrc, RTNtLastStatusValue(), RTNtLastErrorValue());
637
638 /*
639 * Set up the partition.
640 *
641 * Seems like this is where the partition is actually instantiated and we get
642 * a handle to it.
643 */
644 hrc = WHvSetupPartition(hPartition);
645 if (FAILED(hrc))
646 return VMSetError(pVM, VERR_NEM_VM_CREATE_FAILED, RT_SRC_POS,
647 "Call to WHvSetupPartition failed: %Rhrc (Last=%#x/%u)",
648 hrc, RTNtLastStatusValue(), RTNtLastErrorValue());
649
650 /*
651 * Setup the EMTs.
652 */
653 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
654 {
655 hrc = WHvCreateVirtualProcessor(hPartition, idCpu, 0 /*fFlags*/);
656 if (FAILED(hrc))
657 {
658 NTSTATUS const rcNtLast = RTNtLastStatusValue();
659 DWORD const dwErrLast = RTNtLastErrorValue();
660 while (idCpu-- > 0)
661 {
662 HRESULT hrc2 = WHvDeleteVirtualProcessor(hPartition, idCpu);
663 AssertLogRelMsg(SUCCEEDED(hrc2), ("WHvDeleteVirtualProcessor(%p, %u) -> %Rhrc (Last=%#x/%u)\n",
664 hPartition, idCpu, hrc2, RTNtLastStatusValue(),
665 RTNtLastErrorValue()));
666 }
667 return VMSetError(pVM, VERR_NEM_VM_CREATE_FAILED, RT_SRC_POS,
668 "Call to WHvCreateVirtualProcessor failed: %Rhrc (Last=%#x/%u)", hrc, rcNtLast, dwErrLast);
669 }
670
671 if (idCpu == 0)
672 {
673 /* Need to query the ID registers and populate CPUM. */
674 CPUMIDREGS IdRegs; RT_ZERO(IdRegs);
675
676#if 1
677 WHV_REGISTER_NAME aenmNames[12];
678 WHV_REGISTER_VALUE aValues[12];
679 RT_ZERO(aValues);
680
681 aenmNames[0] = WHvArm64RegisterIdAa64Dfr0El1;
682 aenmNames[1] = WHvArm64RegisterIdAa64Dfr1El1;
683 aenmNames[2] = WHvArm64RegisterIdAa64Isar0El1;
684 aenmNames[3] = WHvArm64RegisterIdAa64Isar1El1;
685 aenmNames[4] = WHvArm64RegisterIdAa64Isar2El1;
686 aenmNames[5] = WHvArm64RegisterIdAa64Mmfr0El1;
687 aenmNames[6] = WHvArm64RegisterIdAa64Mmfr1El1;
688 aenmNames[7] = WHvArm64RegisterIdAa64Mmfr2El1;
689 aenmNames[8] = WHvArm64RegisterIdAa64Pfr0El1;
690 aenmNames[9] = WHvArm64RegisterIdAa64Pfr1El1;
691 aenmNames[10] = WHvArm64RegisterCtrEl0;
692 aenmNames[11] = WHvArm64RegisterDczidEl0;
693
694 hrc = WHvGetVirtualProcessorRegisters(hPartition, WHV_ANY_VP /*idCpu*/, aenmNames, RT_ELEMENTS(aenmNames), aValues);
695 AssertLogRelMsgReturn(SUCCEEDED(hrc),
696 ("WHvGetVirtualProcessorRegisters(%p, %u,,%u,) -> %Rhrc (Last=%#x/%u)\n",
697 hPartition, WHV_ANY_VP, RT_ELEMENTS(aenmNames), hrc, RTNtLastStatusValue(), RTNtLastErrorValue())
698 , VERR_NEM_GET_REGISTERS_FAILED);
699
700 IdRegs.u64RegIdAa64Pfr0El1 = aValues[8].Reg64;
701 IdRegs.u64RegIdAa64Pfr1El1 = aValues[9].Reg64;
702 IdRegs.u64RegIdAa64Dfr0El1 = aValues[0].Reg64;
703 IdRegs.u64RegIdAa64Dfr1El1 = aValues[1].Reg64;
704 IdRegs.u64RegIdAa64Isar0El1 = aValues[2].Reg64;
705 IdRegs.u64RegIdAa64Isar1El1 = aValues[3].Reg64;
706 IdRegs.u64RegIdAa64Isar2El1 = aValues[4].Reg64;
707 IdRegs.u64RegIdAa64Mmfr0El1 = aValues[5].Reg64;
708 IdRegs.u64RegIdAa64Mmfr1El1 = aValues[6].Reg64;
709 IdRegs.u64RegIdAa64Mmfr2El1 = aValues[7].Reg64;
710 IdRegs.u64RegCtrEl0 = aValues[10].Reg64;
711 IdRegs.u64RegDczidEl0 = aValues[11].Reg64;
712#else
713 switch (pVM->nem.s.cPhysicalAddressWidth)
714 {
715 case 32: IdRegs.u64RegIdAa64Mmfr0El1 = RT_BF_SET(IdRegs.u64RegIdAa64Mmfr0El1, ARMV8_ID_AA64MMFR0_EL1_PARANGE, ARMV8_ID_AA64MMFR0_EL1_PARANGE_32BITS); break;
716 case 36: IdRegs.u64RegIdAa64Mmfr0El1 = RT_BF_SET(IdRegs.u64RegIdAa64Mmfr0El1, ARMV8_ID_AA64MMFR0_EL1_PARANGE, ARMV8_ID_AA64MMFR0_EL1_PARANGE_36BITS); break;
717 case 40: IdRegs.u64RegIdAa64Mmfr0El1 = RT_BF_SET(IdRegs.u64RegIdAa64Mmfr0El1, ARMV8_ID_AA64MMFR0_EL1_PARANGE, ARMV8_ID_AA64MMFR0_EL1_PARANGE_40BITS); break;
718 case 42: IdRegs.u64RegIdAa64Mmfr0El1 = RT_BF_SET(IdRegs.u64RegIdAa64Mmfr0El1, ARMV8_ID_AA64MMFR0_EL1_PARANGE, ARMV8_ID_AA64MMFR0_EL1_PARANGE_42BITS); break;
719 case 44: IdRegs.u64RegIdAa64Mmfr0El1 = RT_BF_SET(IdRegs.u64RegIdAa64Mmfr0El1, ARMV8_ID_AA64MMFR0_EL1_PARANGE, ARMV8_ID_AA64MMFR0_EL1_PARANGE_44BITS); break;
720 case 48: IdRegs.u64RegIdAa64Mmfr0El1 = RT_BF_SET(IdRegs.u64RegIdAa64Mmfr0El1, ARMV8_ID_AA64MMFR0_EL1_PARANGE, ARMV8_ID_AA64MMFR0_EL1_PARANGE_48BITS); break;
721 case 52: IdRegs.u64RegIdAa64Mmfr0El1 = RT_BF_SET(IdRegs.u64RegIdAa64Mmfr0El1, ARMV8_ID_AA64MMFR0_EL1_PARANGE, ARMV8_ID_AA64MMFR0_EL1_PARANGE_52BITS); break;
722 default: AssertReleaseFailed(); break;
723 }
724#endif
725
726 int rc = CPUMR3PopulateFeaturesByIdRegisters(pVM, &IdRegs);
727 if (RT_FAILURE(rc))
728 return rc;
729 }
730 }
731 pVM->nem.s.fCreatedEmts = true;
732
733 LogRel(("NEM: Successfully set up partition\n"));
734 return VINF_SUCCESS;
735}
736
737
738/**
739 * Try initialize the native API.
740 *
741 * This may only do part of the job, more can be done in
742 * nemR3NativeInitAfterCPUM() and nemR3NativeInitCompleted().
743 *
744 * @returns VBox status code.
745 * @param pVM The cross context VM structure.
746 * @param fFallback Whether we're in fallback mode or use-NEM mode. In
747 * the latter we'll fail if we cannot initialize.
748 * @param fForced Whether the HMForced flag is set and we should
749 * fail if we cannot initialize.
750 */
751int nemR3NativeInit(PVM pVM, bool fFallback, bool fForced)
752{
753 g_uBuildNo = RTSystemGetNtBuildNo();
754
755 /*
756 * Error state.
757 * The error message will be non-empty on failure and 'rc' will be set too.
758 */
759 RTERRINFOSTATIC ErrInfo;
760 PRTERRINFO pErrInfo = RTErrInfoInitStatic(&ErrInfo);
761 int rc = nemR3WinInitProbeAndLoad(fForced, pErrInfo);
762 if (RT_SUCCESS(rc))
763 {
764 /*
765 * Check the capabilties of the hypervisor, starting with whether it's present.
766 */
767 rc = nemR3WinInitCheckCapabilities(pVM, pErrInfo);
768 if (RT_SUCCESS(rc))
769 {
770 /*
771 * Create and initialize a partition.
772 */
773 rc = nemR3WinInitCreatePartition(pVM, pErrInfo);
774 if (RT_SUCCESS(rc))
775 {
776 rc = nemR3NativeInitSetupVm(pVM);
777 if (RT_SUCCESS(rc))
778 {
779 /*
780 * Set ourselves as the execution engine and make config adjustments.
781 */
782 VM_SET_MAIN_EXECUTION_ENGINE(pVM, VM_EXEC_ENGINE_NATIVE_API);
783 Log(("NEM: Marked active!\n"));
784 PGMR3EnableNemMode(pVM);
785
786 /*
787 * Register release statistics
788 */
789 STAMR3Register(pVM, (void *)&pVM->nem.s.cMappedPages, STAMTYPE_U32, STAMVISIBILITY_ALWAYS,
790 "/NEM/PagesCurrentlyMapped", STAMUNIT_PAGES, "Number guest pages currently mapped by the VM");
791 STAMR3Register(pVM, (void *)&pVM->nem.s.StatMapPage, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS,
792 "/NEM/PagesMapCalls", STAMUNIT_PAGES, "Calls to WHvMapGpaRange/HvCallMapGpaPages");
793 STAMR3Register(pVM, (void *)&pVM->nem.s.StatMapPageFailed, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS,
794 "/NEM/PagesMapFails", STAMUNIT_PAGES, "Calls to WHvMapGpaRange/HvCallMapGpaPages that failed");
795 STAMR3Register(pVM, (void *)&pVM->nem.s.StatUnmapPage, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS,
796 "/NEM/PagesUnmapCalls", STAMUNIT_PAGES, "Calls to WHvUnmapGpaRange/HvCallUnmapGpaPages");
797 STAMR3Register(pVM, (void *)&pVM->nem.s.StatUnmapPageFailed, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS,
798 "/NEM/PagesUnmapFails", STAMUNIT_PAGES, "Calls to WHvUnmapGpaRange/HvCallUnmapGpaPages that failed");
799 STAMR3Register(pVM, &pVM->nem.s.StatProfMapGpaRange, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS,
800 "/NEM/PagesMapGpaRange", STAMUNIT_TICKS_PER_CALL, "Profiling calls to WHvMapGpaRange for bigger stuff");
801 STAMR3Register(pVM, &pVM->nem.s.StatProfUnmapGpaRange, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS,
802 "/NEM/PagesUnmapGpaRange", STAMUNIT_TICKS_PER_CALL, "Profiling calls to WHvUnmapGpaRange for bigger stuff");
803 STAMR3Register(pVM, &pVM->nem.s.StatProfMapGpaRangePage, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS,
804 "/NEM/PagesMapGpaRangePage", STAMUNIT_TICKS_PER_CALL, "Profiling calls to WHvMapGpaRange for single pages");
805 STAMR3Register(pVM, &pVM->nem.s.StatProfUnmapGpaRangePage, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS,
806 "/NEM/PagesUnmapGpaRangePage", STAMUNIT_TICKS_PER_CALL, "Profiling calls to WHvUnmapGpaRange for single pages");
807
808 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
809 {
810 PNEMCPU pNemCpu = &pVM->apCpusR3[idCpu]->nem.s;
811 STAMR3RegisterF(pVM, &pNemCpu->StatExitPortIo, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of port I/O exits", "/NEM/CPU%u/ExitPortIo", idCpu);
812 STAMR3RegisterF(pVM, &pNemCpu->StatExitMemUnmapped, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of unmapped memory exits", "/NEM/CPU%u/ExitMemUnmapped", idCpu);
813 STAMR3RegisterF(pVM, &pNemCpu->StatExitMemIntercept, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of intercepted memory exits", "/NEM/CPU%u/ExitMemIntercept", idCpu);
814 STAMR3RegisterF(pVM, &pNemCpu->StatExitHalt, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of HLT exits", "/NEM/CPU%u/ExitHalt", idCpu);
815 STAMR3RegisterF(pVM, &pNemCpu->StatExitInterruptWindow, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of interrupt window exits", "/NEM/CPU%u/ExitInterruptWindow", idCpu);
816 STAMR3RegisterF(pVM, &pNemCpu->StatExitCpuId, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of CPUID exits", "/NEM/CPU%u/ExitCpuId", idCpu);
817 STAMR3RegisterF(pVM, &pNemCpu->StatExitMsr, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of MSR access exits", "/NEM/CPU%u/ExitMsr", idCpu);
818 STAMR3RegisterF(pVM, &pNemCpu->StatExitException, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of exception exits", "/NEM/CPU%u/ExitException", idCpu);
819 STAMR3RegisterF(pVM, &pNemCpu->StatExitExceptionBp, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of #BP exits", "/NEM/CPU%u/ExitExceptionBp", idCpu);
820 STAMR3RegisterF(pVM, &pNemCpu->StatExitExceptionDb, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of #DB exits", "/NEM/CPU%u/ExitExceptionDb", idCpu);
821 STAMR3RegisterF(pVM, &pNemCpu->StatExitExceptionGp, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of #GP exits", "/NEM/CPU%u/ExitExceptionGp", idCpu);
822 STAMR3RegisterF(pVM, &pNemCpu->StatExitExceptionGpMesa, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of #GP exits from mesa driver", "/NEM/CPU%u/ExitExceptionGpMesa", idCpu);
823 STAMR3RegisterF(pVM, &pNemCpu->StatExitExceptionUd, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of #UD exits", "/NEM/CPU%u/ExitExceptionUd", idCpu);
824 STAMR3RegisterF(pVM, &pNemCpu->StatExitExceptionUdHandled, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of handled #UD exits", "/NEM/CPU%u/ExitExceptionUdHandled", idCpu);
825 STAMR3RegisterF(pVM, &pNemCpu->StatExitUnrecoverable, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of unrecoverable exits", "/NEM/CPU%u/ExitUnrecoverable", idCpu);
826 STAMR3RegisterF(pVM, &pNemCpu->StatGetMsgTimeout, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of get message timeouts/alerts", "/NEM/CPU%u/GetMsgTimeout", idCpu);
827 STAMR3RegisterF(pVM, &pNemCpu->StatStopCpuSuccess, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of successful CPU stops", "/NEM/CPU%u/StopCpuSuccess", idCpu);
828 STAMR3RegisterF(pVM, &pNemCpu->StatStopCpuPending, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of pending CPU stops", "/NEM/CPU%u/StopCpuPending", idCpu);
829 STAMR3RegisterF(pVM, &pNemCpu->StatStopCpuPendingAlerts,STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of pending CPU stop alerts", "/NEM/CPU%u/StopCpuPendingAlerts", idCpu);
830 STAMR3RegisterF(pVM, &pNemCpu->StatStopCpuPendingOdd, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of odd pending CPU stops (see code)", "/NEM/CPU%u/StopCpuPendingOdd", idCpu);
831 STAMR3RegisterF(pVM, &pNemCpu->StatCancelChangedState, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of cancel changed state", "/NEM/CPU%u/CancelChangedState", idCpu);
832 STAMR3RegisterF(pVM, &pNemCpu->StatCancelAlertedThread, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of cancel alerted EMT", "/NEM/CPU%u/CancelAlertedEMT", idCpu);
833 STAMR3RegisterF(pVM, &pNemCpu->StatBreakOnFFPre, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of pre execution FF breaks", "/NEM/CPU%u/BreakOnFFPre", idCpu);
834 STAMR3RegisterF(pVM, &pNemCpu->StatBreakOnFFPost, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of post execution FF breaks", "/NEM/CPU%u/BreakOnFFPost", idCpu);
835 STAMR3RegisterF(pVM, &pNemCpu->StatBreakOnCancel, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of cancel execution breaks", "/NEM/CPU%u/BreakOnCancel", idCpu);
836 STAMR3RegisterF(pVM, &pNemCpu->StatBreakOnStatus, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of status code breaks", "/NEM/CPU%u/BreakOnStatus", idCpu);
837 STAMR3RegisterF(pVM, &pNemCpu->StatImportOnDemand, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of on-demand state imports", "/NEM/CPU%u/ImportOnDemand", idCpu);
838 STAMR3RegisterF(pVM, &pNemCpu->StatImportOnReturn, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of state imports on loop return", "/NEM/CPU%u/ImportOnReturn", idCpu);
839 STAMR3RegisterF(pVM, &pNemCpu->StatImportOnReturnSkipped, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of skipped state imports on loop return", "/NEM/CPU%u/ImportOnReturnSkipped", idCpu);
840 STAMR3RegisterF(pVM, &pNemCpu->StatQueryCpuTick, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of TSC queries", "/NEM/CPU%u/QueryCpuTick", idCpu);
841 }
842
843 if (!SUPR3IsDriverless())
844 {
845 PUVM pUVM = pVM->pUVM;
846 STAMR3RegisterRefresh(pUVM, &pVM->nem.s.R0Stats.cPagesAvailable, STAMTYPE_U64, STAMVISIBILITY_ALWAYS,
847 STAMUNIT_PAGES, STAM_REFRESH_GRP_NEM, "Free pages available to the hypervisor",
848 "/NEM/R0Stats/cPagesAvailable");
849 STAMR3RegisterRefresh(pUVM, &pVM->nem.s.R0Stats.cPagesInUse, STAMTYPE_U64, STAMVISIBILITY_ALWAYS,
850 STAMUNIT_PAGES, STAM_REFRESH_GRP_NEM, "Pages in use by hypervisor",
851 "/NEM/R0Stats/cPagesInUse");
852 }
853 }
854
855 }
856
857 }
858 }
859
860 /*
861 * We only fail if in forced mode, otherwise just log the complaint and return.
862 */
863 Assert(pVM->bMainExecutionEngine == VM_EXEC_ENGINE_NATIVE_API || RTErrInfoIsSet(pErrInfo));
864 if ( (fForced || !fFallback)
865 && pVM->bMainExecutionEngine != VM_EXEC_ENGINE_NATIVE_API)
866 return VMSetError(pVM, RT_SUCCESS_NP(rc) ? VERR_NEM_NOT_AVAILABLE : rc, RT_SRC_POS, "%s", pErrInfo->pszMsg);
867
868 if (RTErrInfoIsSet(pErrInfo))
869 LogRel(("NEM: Not available: %s\n", pErrInfo->pszMsg));
870 return VINF_SUCCESS;
871}
872
873
874/**
875 * This is called after CPUMR3Init is done.
876 *
877 * @returns VBox status code.
878 * @param pVM The VM handle..
879 */
880int nemR3NativeInitAfterCPUM(PVM pVM)
881{
882 /*
883 * Validate sanity.
884 */
885 AssertReturn(pVM->bMainExecutionEngine == VM_EXEC_ENGINE_NATIVE_API, VERR_WRONG_ORDER);
886
887 /** @todo */
888
889 /*
890 * Any hyper-v statistics we can get at now? HvCallMapStatsPage isn't accessible any more.
891 */
892 /** @todo stats */
893
894 /*
895 * Adjust features.
896 *
897 * Note! We've already disabled X2APIC and MONITOR/MWAIT via CFGM during
898 * the first init call.
899 */
900
901 return VINF_SUCCESS;
902}
903
904
905int nemR3NativeInitCompleted(PVM pVM, VMINITCOMPLETED enmWhat)
906{
907 //BOOL fRet = SetThreadPriority(GetCurrentThread(), 0);
908 //AssertLogRel(fRet);
909
910 NOREF(pVM); NOREF(enmWhat);
911 return VINF_SUCCESS;
912}
913
914
915int nemR3NativeTerm(PVM pVM)
916{
917 /*
918 * Delete the partition.
919 */
920 WHV_PARTITION_HANDLE hPartition = pVM->nem.s.hPartition;
921 pVM->nem.s.hPartition = NULL;
922 pVM->nem.s.hPartitionDevice = NULL;
923 if (hPartition != NULL)
924 {
925 VMCPUID idCpu = pVM->nem.s.fCreatedEmts ? pVM->cCpus : 0;
926 LogRel(("NEM: Destroying partition %p with its %u VCpus...\n", hPartition, idCpu));
927 while (idCpu-- > 0)
928 {
929 HRESULT hrc = WHvDeleteVirtualProcessor(hPartition, idCpu);
930 AssertLogRelMsg(SUCCEEDED(hrc), ("WHvDeleteVirtualProcessor(%p, %u) -> %Rhrc (Last=%#x/%u)\n",
931 hPartition, idCpu, hrc, RTNtLastStatusValue(),
932 RTNtLastErrorValue()));
933 }
934 WHvDeletePartition(hPartition);
935 }
936 pVM->nem.s.fCreatedEmts = false;
937 return VINF_SUCCESS;
938}
939
940
941/**
942 * VM reset notification.
943 *
944 * @param pVM The cross context VM structure.
945 */
946void nemR3NativeReset(PVM pVM)
947{
948 RT_NOREF(pVM);
949}
950
951
952/**
953 * Reset CPU due to INIT IPI or hot (un)plugging.
954 *
955 * @param pVCpu The cross context virtual CPU structure of the CPU being
956 * reset.
957 * @param fInitIpi Whether this is the INIT IPI or hot (un)plugging case.
958 */
959void nemR3NativeResetCpu(PVMCPU pVCpu, bool fInitIpi)
960{
961 RT_NOREF(pVCpu, fInitIpi);
962}
963
964
965NEM_TMPL_STATIC int nemHCWinCopyStateToHyperV(PVMCC pVM, PVMCPUCC pVCpu)
966{
967 WHV_REGISTER_NAME aenmNames[128];
968 WHV_REGISTER_VALUE aValues[128];
969
970 uint64_t const fWhat = ~pVCpu->cpum.GstCtx.fExtrn & CPUMCTX_EXTRN_ALL;
971 if (!fWhat)
972 return VINF_SUCCESS;
973 uintptr_t iReg = 0;
974
975#define ADD_REG64(a_enmName, a_uValue) do { \
976 aenmNames[iReg] = (a_enmName); \
977 aValues[iReg].Reg128.High64 = 0; \
978 aValues[iReg].Reg64 = (a_uValue).x; \
979 iReg++; \
980 } while (0)
981#define ADD_REG64_RAW(a_enmName, a_uValue) do { \
982 aenmNames[iReg] = (a_enmName); \
983 aValues[iReg].Reg128.High64 = 0; \
984 aValues[iReg].Reg64 = (a_uValue); \
985 iReg++; \
986 } while (0)
987#define ADD_REG128(a_enmName, a_uValue) do { \
988 aenmNames[iReg] = (a_enmName); \
989 aValues[iReg].Reg128.Low64 = (a_uValue).au64[0]; \
990 aValues[iReg].Reg128.High64 = (a_uValue).au64[1]; \
991 iReg++; \
992 } while (0)
993
994 /* GPRs */
995 if (fWhat & CPUMCTX_EXTRN_GPRS_MASK)
996 {
997 if (fWhat & CPUMCTX_EXTRN_X0)
998 ADD_REG64(WHvArm64RegisterX0, pVCpu->cpum.GstCtx.aGRegs[0]);
999 if (fWhat & CPUMCTX_EXTRN_X1)
1000 ADD_REG64(WHvArm64RegisterX1, pVCpu->cpum.GstCtx.aGRegs[1]);
1001 if (fWhat & CPUMCTX_EXTRN_X2)
1002 ADD_REG64(WHvArm64RegisterX2, pVCpu->cpum.GstCtx.aGRegs[2]);
1003 if (fWhat & CPUMCTX_EXTRN_X3)
1004 ADD_REG64(WHvArm64RegisterX3, pVCpu->cpum.GstCtx.aGRegs[3]);
1005 if (fWhat & CPUMCTX_EXTRN_X4_X28)
1006 {
1007 ADD_REG64(WHvArm64RegisterX4, pVCpu->cpum.GstCtx.aGRegs[4]);
1008 ADD_REG64(WHvArm64RegisterX5, pVCpu->cpum.GstCtx.aGRegs[5]);
1009 ADD_REG64(WHvArm64RegisterX6, pVCpu->cpum.GstCtx.aGRegs[6]);
1010 ADD_REG64(WHvArm64RegisterX7, pVCpu->cpum.GstCtx.aGRegs[7]);
1011 ADD_REG64(WHvArm64RegisterX8, pVCpu->cpum.GstCtx.aGRegs[8]);
1012 ADD_REG64(WHvArm64RegisterX9, pVCpu->cpum.GstCtx.aGRegs[9]);
1013 ADD_REG64(WHvArm64RegisterX10, pVCpu->cpum.GstCtx.aGRegs[10]);
1014 ADD_REG64(WHvArm64RegisterX11, pVCpu->cpum.GstCtx.aGRegs[11]);
1015 ADD_REG64(WHvArm64RegisterX12, pVCpu->cpum.GstCtx.aGRegs[12]);
1016 ADD_REG64(WHvArm64RegisterX13, pVCpu->cpum.GstCtx.aGRegs[13]);
1017 ADD_REG64(WHvArm64RegisterX14, pVCpu->cpum.GstCtx.aGRegs[14]);
1018 ADD_REG64(WHvArm64RegisterX15, pVCpu->cpum.GstCtx.aGRegs[15]);
1019 ADD_REG64(WHvArm64RegisterX16, pVCpu->cpum.GstCtx.aGRegs[16]);
1020 ADD_REG64(WHvArm64RegisterX17, pVCpu->cpum.GstCtx.aGRegs[17]);
1021 ADD_REG64(WHvArm64RegisterX18, pVCpu->cpum.GstCtx.aGRegs[18]);
1022 ADD_REG64(WHvArm64RegisterX19, pVCpu->cpum.GstCtx.aGRegs[19]);
1023 ADD_REG64(WHvArm64RegisterX20, pVCpu->cpum.GstCtx.aGRegs[20]);
1024 ADD_REG64(WHvArm64RegisterX21, pVCpu->cpum.GstCtx.aGRegs[21]);
1025 ADD_REG64(WHvArm64RegisterX22, pVCpu->cpum.GstCtx.aGRegs[22]);
1026 ADD_REG64(WHvArm64RegisterX23, pVCpu->cpum.GstCtx.aGRegs[23]);
1027 ADD_REG64(WHvArm64RegisterX24, pVCpu->cpum.GstCtx.aGRegs[24]);
1028 ADD_REG64(WHvArm64RegisterX25, pVCpu->cpum.GstCtx.aGRegs[25]);
1029 ADD_REG64(WHvArm64RegisterX26, pVCpu->cpum.GstCtx.aGRegs[26]);
1030 ADD_REG64(WHvArm64RegisterX27, pVCpu->cpum.GstCtx.aGRegs[27]);
1031 ADD_REG64(WHvArm64RegisterX28, pVCpu->cpum.GstCtx.aGRegs[28]);
1032 }
1033 if (fWhat & CPUMCTX_EXTRN_LR)
1034 ADD_REG64(WHvArm64RegisterLr, pVCpu->cpum.GstCtx.aGRegs[30]);
1035 if (fWhat & CPUMCTX_EXTRN_FP)
1036 ADD_REG64(WHvArm64RegisterFp, pVCpu->cpum.GstCtx.aGRegs[29]);
1037 }
1038
1039 /* RIP & Flags */
1040 if (fWhat & CPUMCTX_EXTRN_PC)
1041 ADD_REG64_RAW(WHvArm64RegisterPc, pVCpu->cpum.GstCtx.Pc.u64);
1042 if (fWhat & CPUMCTX_EXTRN_PSTATE)
1043 ADD_REG64_RAW(WHvArm64RegisterPstate, pVCpu->cpum.GstCtx.fPState);
1044
1045 /* Vector state. */
1046 if (fWhat & CPUMCTX_EXTRN_V0_V31)
1047 {
1048 ADD_REG128(WHvArm64RegisterQ0, pVCpu->cpum.GstCtx.aVRegs[0]);
1049 ADD_REG128(WHvArm64RegisterQ1, pVCpu->cpum.GstCtx.aVRegs[1]);
1050 ADD_REG128(WHvArm64RegisterQ2, pVCpu->cpum.GstCtx.aVRegs[2]);
1051 ADD_REG128(WHvArm64RegisterQ3, pVCpu->cpum.GstCtx.aVRegs[3]);
1052 ADD_REG128(WHvArm64RegisterQ4, pVCpu->cpum.GstCtx.aVRegs[4]);
1053 ADD_REG128(WHvArm64RegisterQ5, pVCpu->cpum.GstCtx.aVRegs[5]);
1054 ADD_REG128(WHvArm64RegisterQ6, pVCpu->cpum.GstCtx.aVRegs[6]);
1055 ADD_REG128(WHvArm64RegisterQ7, pVCpu->cpum.GstCtx.aVRegs[7]);
1056 ADD_REG128(WHvArm64RegisterQ8, pVCpu->cpum.GstCtx.aVRegs[8]);
1057 ADD_REG128(WHvArm64RegisterQ9, pVCpu->cpum.GstCtx.aVRegs[9]);
1058 ADD_REG128(WHvArm64RegisterQ10, pVCpu->cpum.GstCtx.aVRegs[10]);
1059 ADD_REG128(WHvArm64RegisterQ11, pVCpu->cpum.GstCtx.aVRegs[11]);
1060 ADD_REG128(WHvArm64RegisterQ12, pVCpu->cpum.GstCtx.aVRegs[12]);
1061 ADD_REG128(WHvArm64RegisterQ13, pVCpu->cpum.GstCtx.aVRegs[13]);
1062 ADD_REG128(WHvArm64RegisterQ14, pVCpu->cpum.GstCtx.aVRegs[14]);
1063 ADD_REG128(WHvArm64RegisterQ15, pVCpu->cpum.GstCtx.aVRegs[15]);
1064 ADD_REG128(WHvArm64RegisterQ16, pVCpu->cpum.GstCtx.aVRegs[16]);
1065 ADD_REG128(WHvArm64RegisterQ17, pVCpu->cpum.GstCtx.aVRegs[17]);
1066 ADD_REG128(WHvArm64RegisterQ18, pVCpu->cpum.GstCtx.aVRegs[18]);
1067 ADD_REG128(WHvArm64RegisterQ19, pVCpu->cpum.GstCtx.aVRegs[19]);
1068 ADD_REG128(WHvArm64RegisterQ20, pVCpu->cpum.GstCtx.aVRegs[20]);
1069 ADD_REG128(WHvArm64RegisterQ21, pVCpu->cpum.GstCtx.aVRegs[21]);
1070 ADD_REG128(WHvArm64RegisterQ22, pVCpu->cpum.GstCtx.aVRegs[22]);
1071 ADD_REG128(WHvArm64RegisterQ23, pVCpu->cpum.GstCtx.aVRegs[23]);
1072 ADD_REG128(WHvArm64RegisterQ24, pVCpu->cpum.GstCtx.aVRegs[24]);
1073 ADD_REG128(WHvArm64RegisterQ25, pVCpu->cpum.GstCtx.aVRegs[25]);
1074 ADD_REG128(WHvArm64RegisterQ26, pVCpu->cpum.GstCtx.aVRegs[26]);
1075 ADD_REG128(WHvArm64RegisterQ27, pVCpu->cpum.GstCtx.aVRegs[27]);
1076 ADD_REG128(WHvArm64RegisterQ28, pVCpu->cpum.GstCtx.aVRegs[28]);
1077 ADD_REG128(WHvArm64RegisterQ29, pVCpu->cpum.GstCtx.aVRegs[29]);
1078 ADD_REG128(WHvArm64RegisterQ30, pVCpu->cpum.GstCtx.aVRegs[30]);
1079 ADD_REG128(WHvArm64RegisterQ31, pVCpu->cpum.GstCtx.aVRegs[31]);
1080 }
1081
1082#undef ADD_REG64
1083#undef ADD_REG64_RAW
1084#undef ADD_REG128
1085
1086 /*
1087 * Set the registers.
1088 */
1089 Assert(iReg < RT_ELEMENTS(aValues));
1090 Assert(iReg < RT_ELEMENTS(aenmNames));
1091 HRESULT hrc = WHvSetVirtualProcessorRegisters(pVM->nem.s.hPartition, pVCpu->idCpu, aenmNames, iReg, aValues);
1092 if (SUCCEEDED(hrc))
1093 {
1094 pVCpu->cpum.GstCtx.fExtrn |= CPUMCTX_EXTRN_ALL | CPUMCTX_EXTRN_KEEPER_NEM;
1095 return VINF_SUCCESS;
1096 }
1097 AssertLogRelMsgFailed(("WHvSetVirtualProcessorRegisters(%p, %u,,%u,) -> %Rhrc (Last=%#x/%u)\n",
1098 pVM->nem.s.hPartition, pVCpu->idCpu, iReg,
1099 hrc, RTNtLastStatusValue(), RTNtLastErrorValue()));
1100 return VERR_INTERNAL_ERROR;
1101}
1102
1103
1104NEM_TMPL_STATIC int nemHCWinCopyStateFromHyperV(PVMCC pVM, PVMCPUCC pVCpu, uint64_t fWhat)
1105{
1106 WHV_REGISTER_NAME aenmNames[128];
1107
1108 fWhat &= pVCpu->cpum.GstCtx.fExtrn;
1109 if (!fWhat)
1110 return VINF_SUCCESS;
1111
1112 uintptr_t iReg = 0;
1113
1114 /* GPRs */
1115 if (fWhat & CPUMCTX_EXTRN_GPRS_MASK)
1116 {
1117 if (fWhat & CPUMCTX_EXTRN_X0)
1118 aenmNames[iReg++] = WHvArm64RegisterX0;
1119 if (fWhat & CPUMCTX_EXTRN_X1)
1120 aenmNames[iReg++] = WHvArm64RegisterX1;
1121 if (fWhat & CPUMCTX_EXTRN_X2)
1122 aenmNames[iReg++] = WHvArm64RegisterX2;
1123 if (fWhat & CPUMCTX_EXTRN_X3)
1124 aenmNames[iReg++] = WHvArm64RegisterX3;
1125 if (fWhat & CPUMCTX_EXTRN_X4_X28)
1126 {
1127 aenmNames[iReg++] = WHvArm64RegisterX4;
1128 aenmNames[iReg++] = WHvArm64RegisterX5;
1129 aenmNames[iReg++] = WHvArm64RegisterX6;
1130 aenmNames[iReg++] = WHvArm64RegisterX7;
1131 aenmNames[iReg++] = WHvArm64RegisterX8;
1132 aenmNames[iReg++] = WHvArm64RegisterX9;
1133 aenmNames[iReg++] = WHvArm64RegisterX10;
1134 aenmNames[iReg++] = WHvArm64RegisterX11;
1135 aenmNames[iReg++] = WHvArm64RegisterX12;
1136 aenmNames[iReg++] = WHvArm64RegisterX13;
1137 aenmNames[iReg++] = WHvArm64RegisterX14;
1138 aenmNames[iReg++] = WHvArm64RegisterX15;
1139 aenmNames[iReg++] = WHvArm64RegisterX16;
1140 aenmNames[iReg++] = WHvArm64RegisterX17;
1141 aenmNames[iReg++] = WHvArm64RegisterX18;
1142 aenmNames[iReg++] = WHvArm64RegisterX19;
1143 aenmNames[iReg++] = WHvArm64RegisterX20;
1144 aenmNames[iReg++] = WHvArm64RegisterX21;
1145 aenmNames[iReg++] = WHvArm64RegisterX22;
1146 aenmNames[iReg++] = WHvArm64RegisterX23;
1147 aenmNames[iReg++] = WHvArm64RegisterX24;
1148 aenmNames[iReg++] = WHvArm64RegisterX25;
1149 aenmNames[iReg++] = WHvArm64RegisterX26;
1150 aenmNames[iReg++] = WHvArm64RegisterX27;
1151 aenmNames[iReg++] = WHvArm64RegisterX28;
1152 }
1153 if (fWhat & CPUMCTX_EXTRN_LR)
1154 aenmNames[iReg++] = WHvArm64RegisterLr;
1155 if (fWhat & CPUMCTX_EXTRN_FP)
1156 aenmNames[iReg++] = WHvArm64RegisterFp;
1157 }
1158
1159 /* PC & Flags */
1160 if (fWhat & CPUMCTX_EXTRN_PC)
1161 aenmNames[iReg++] = WHvArm64RegisterPc;
1162 if (fWhat & CPUMCTX_EXTRN_PSTATE)
1163 aenmNames[iReg++] = WHvArm64RegisterPstate;
1164 if (fWhat & CPUMCTX_EXTRN_SPSR)
1165 aenmNames[iReg++] = WHvArm64RegisterSpsrEl1;
1166 if (fWhat & CPUMCTX_EXTRN_ELR)
1167 aenmNames[iReg++] = WHvArm64RegisterElrEl1;
1168 if (fWhat & CPUMCTX_EXTRN_SP)
1169 {
1170 aenmNames[iReg++] = WHvArm64RegisterSpEl0;
1171 aenmNames[iReg++] = WHvArm64RegisterSpEl1;
1172 }
1173 if (fWhat & CPUMCTX_EXTRN_SCTLR_TCR_TTBR)
1174 {
1175 aenmNames[iReg++] = WHvArm64RegisterSctlrEl1;
1176 aenmNames[iReg++] = WHvArm64RegisterTcrEl1;
1177 aenmNames[iReg++] = WHvArm64RegisterTtbr0El1;
1178 aenmNames[iReg++] = WHvArm64RegisterTtbr1El1;
1179 }
1180
1181 /* Vector state. */
1182 if (fWhat & CPUMCTX_EXTRN_V0_V31)
1183 {
1184 aenmNames[iReg++] = WHvArm64RegisterQ0;
1185 aenmNames[iReg++] = WHvArm64RegisterQ1;
1186 aenmNames[iReg++] = WHvArm64RegisterQ2;
1187 aenmNames[iReg++] = WHvArm64RegisterQ3;
1188 aenmNames[iReg++] = WHvArm64RegisterQ4;
1189 aenmNames[iReg++] = WHvArm64RegisterQ5;
1190 aenmNames[iReg++] = WHvArm64RegisterQ6;
1191 aenmNames[iReg++] = WHvArm64RegisterQ7;
1192 aenmNames[iReg++] = WHvArm64RegisterQ8;
1193 aenmNames[iReg++] = WHvArm64RegisterQ9;
1194 aenmNames[iReg++] = WHvArm64RegisterQ10;
1195 aenmNames[iReg++] = WHvArm64RegisterQ11;
1196 aenmNames[iReg++] = WHvArm64RegisterQ12;
1197 aenmNames[iReg++] = WHvArm64RegisterQ13;
1198 aenmNames[iReg++] = WHvArm64RegisterQ14;
1199 aenmNames[iReg++] = WHvArm64RegisterQ15;
1200
1201 aenmNames[iReg++] = WHvArm64RegisterQ16;
1202 aenmNames[iReg++] = WHvArm64RegisterQ17;
1203 aenmNames[iReg++] = WHvArm64RegisterQ18;
1204 aenmNames[iReg++] = WHvArm64RegisterQ19;
1205 aenmNames[iReg++] = WHvArm64RegisterQ20;
1206 aenmNames[iReg++] = WHvArm64RegisterQ21;
1207 aenmNames[iReg++] = WHvArm64RegisterQ22;
1208 aenmNames[iReg++] = WHvArm64RegisterQ23;
1209 aenmNames[iReg++] = WHvArm64RegisterQ24;
1210 aenmNames[iReg++] = WHvArm64RegisterQ25;
1211 aenmNames[iReg++] = WHvArm64RegisterQ26;
1212 aenmNames[iReg++] = WHvArm64RegisterQ27;
1213 aenmNames[iReg++] = WHvArm64RegisterQ28;
1214 aenmNames[iReg++] = WHvArm64RegisterQ29;
1215 aenmNames[iReg++] = WHvArm64RegisterQ30;
1216 aenmNames[iReg++] = WHvArm64RegisterQ31;
1217 }
1218 if (fWhat & CPUMCTX_EXTRN_FPCR)
1219 aenmNames[iReg++] = WHvArm64RegisterFpcr;
1220 if (fWhat & CPUMCTX_EXTRN_FPSR)
1221 aenmNames[iReg++] = WHvArm64RegisterFpsr;
1222
1223 /* System registers. */
1224 if (fWhat & CPUMCTX_EXTRN_SYSREG_MISC)
1225 {
1226 aenmNames[iReg++] = WHvArm64RegisterVbarEl1;
1227 aenmNames[iReg++] = WHvArm64RegisterEsrEl1;
1228 aenmNames[iReg++] = WHvArm64RegisterFarEl1;
1229 /** @todo */
1230 }
1231
1232#if 0
1233 if (fWhat & CPUMCTX_EXTRN_SYSREG_DEBUG)
1234 {
1235 aenmNames[iReg++] = WHvArm64RegisterDbgbcr0El1;
1236 /** @todo */
1237 }
1238#endif
1239
1240 if (fWhat & CPUMCTX_EXTRN_SYSREG_PAUTH_KEYS)
1241 {
1242 aenmNames[iReg++] = WHvArm64RegisterApdAKeyHiEl1;
1243 /** @todo */
1244 }
1245
1246 size_t const cRegs = iReg;
1247 Assert(cRegs < RT_ELEMENTS(aenmNames));
1248
1249 /*
1250 * Get the registers.
1251 */
1252 WHV_REGISTER_VALUE aValues[128];
1253 RT_ZERO(aValues);
1254 Assert(RT_ELEMENTS(aValues) >= cRegs);
1255 Assert(RT_ELEMENTS(aenmNames) >= cRegs);
1256 HRESULT hrc = WHvGetVirtualProcessorRegisters(pVM->nem.s.hPartition, pVCpu->idCpu, aenmNames, (uint32_t)cRegs, aValues);
1257 AssertLogRelMsgReturn(SUCCEEDED(hrc),
1258 ("WHvGetVirtualProcessorRegisters(%p, %u,,%u,) -> %Rhrc (Last=%#x/%u)\n",
1259 pVM->nem.s.hPartition, pVCpu->idCpu, cRegs, hrc, RTNtLastStatusValue(), RTNtLastErrorValue())
1260 , VERR_NEM_GET_REGISTERS_FAILED);
1261
1262 iReg = 0;
1263#define GET_REG64(a_DstVar, a_enmName) do { \
1264 Assert(aenmNames[iReg] == (a_enmName)); \
1265 (a_DstVar).x = aValues[iReg].Reg64; \
1266 iReg++; \
1267 } while (0)
1268#define GET_REG64_RAW(a_DstVar, a_enmName) do { \
1269 Assert(aenmNames[iReg] == (a_enmName)); \
1270 (a_DstVar) = aValues[iReg].Reg64; \
1271 iReg++; \
1272 } while (0)
1273#define GET_SYSREG64(a_DstVar, a_enmName) do { \
1274 Assert(aenmNames[iReg] == (a_enmName)); \
1275 (a_DstVar).u64 = aValues[iReg].Reg64; \
1276 iReg++; \
1277 } while (0)
1278#define GET_REG128(a_DstVar, a_enmName) do { \
1279 Assert(aenmNames[iReg] == a_enmName); \
1280 (a_DstVar).au64[0] = aValues[iReg].Reg128.Low64; \
1281 (a_DstVar).au64[1] = aValues[iReg].Reg128.High64; \
1282 iReg++; \
1283 } while (0)
1284
1285 /* GPRs */
1286 if (fWhat & CPUMCTX_EXTRN_GPRS_MASK)
1287 {
1288 if (fWhat & CPUMCTX_EXTRN_X0)
1289 GET_REG64(pVCpu->cpum.GstCtx.aGRegs[0], WHvArm64RegisterX0);
1290 if (fWhat & CPUMCTX_EXTRN_X1)
1291 GET_REG64(pVCpu->cpum.GstCtx.aGRegs[1], WHvArm64RegisterX1);
1292 if (fWhat & CPUMCTX_EXTRN_X2)
1293 GET_REG64(pVCpu->cpum.GstCtx.aGRegs[2], WHvArm64RegisterX2);
1294 if (fWhat & CPUMCTX_EXTRN_X3)
1295 GET_REG64(pVCpu->cpum.GstCtx.aGRegs[3], WHvArm64RegisterX3);
1296 if (fWhat & CPUMCTX_EXTRN_X4_X28)
1297 {
1298 GET_REG64(pVCpu->cpum.GstCtx.aGRegs[4], WHvArm64RegisterX4);
1299 GET_REG64(pVCpu->cpum.GstCtx.aGRegs[5], WHvArm64RegisterX5);
1300 GET_REG64(pVCpu->cpum.GstCtx.aGRegs[6], WHvArm64RegisterX6);
1301 GET_REG64(pVCpu->cpum.GstCtx.aGRegs[7], WHvArm64RegisterX7);
1302 GET_REG64(pVCpu->cpum.GstCtx.aGRegs[8], WHvArm64RegisterX8);
1303 GET_REG64(pVCpu->cpum.GstCtx.aGRegs[9], WHvArm64RegisterX9);
1304 GET_REG64(pVCpu->cpum.GstCtx.aGRegs[10], WHvArm64RegisterX10);
1305 GET_REG64(pVCpu->cpum.GstCtx.aGRegs[11], WHvArm64RegisterX11);
1306 GET_REG64(pVCpu->cpum.GstCtx.aGRegs[12], WHvArm64RegisterX12);
1307 GET_REG64(pVCpu->cpum.GstCtx.aGRegs[13], WHvArm64RegisterX13);
1308 GET_REG64(pVCpu->cpum.GstCtx.aGRegs[14], WHvArm64RegisterX14);
1309 GET_REG64(pVCpu->cpum.GstCtx.aGRegs[15], WHvArm64RegisterX15);
1310 GET_REG64(pVCpu->cpum.GstCtx.aGRegs[16], WHvArm64RegisterX16);
1311 GET_REG64(pVCpu->cpum.GstCtx.aGRegs[17], WHvArm64RegisterX17);
1312 GET_REG64(pVCpu->cpum.GstCtx.aGRegs[18], WHvArm64RegisterX18);
1313 GET_REG64(pVCpu->cpum.GstCtx.aGRegs[19], WHvArm64RegisterX19);
1314 GET_REG64(pVCpu->cpum.GstCtx.aGRegs[20], WHvArm64RegisterX20);
1315 GET_REG64(pVCpu->cpum.GstCtx.aGRegs[21], WHvArm64RegisterX21);
1316 GET_REG64(pVCpu->cpum.GstCtx.aGRegs[22], WHvArm64RegisterX22);
1317 GET_REG64(pVCpu->cpum.GstCtx.aGRegs[23], WHvArm64RegisterX23);
1318 GET_REG64(pVCpu->cpum.GstCtx.aGRegs[24], WHvArm64RegisterX24);
1319 GET_REG64(pVCpu->cpum.GstCtx.aGRegs[25], WHvArm64RegisterX25);
1320 GET_REG64(pVCpu->cpum.GstCtx.aGRegs[26], WHvArm64RegisterX26);
1321 GET_REG64(pVCpu->cpum.GstCtx.aGRegs[27], WHvArm64RegisterX27);
1322 GET_REG64(pVCpu->cpum.GstCtx.aGRegs[28], WHvArm64RegisterX28);
1323 }
1324 if (fWhat & CPUMCTX_EXTRN_LR)
1325 GET_REG64(pVCpu->cpum.GstCtx.aGRegs[30], WHvArm64RegisterLr);
1326 if (fWhat & CPUMCTX_EXTRN_FP)
1327 GET_REG64(pVCpu->cpum.GstCtx.aGRegs[29], WHvArm64RegisterFp);
1328 }
1329
1330 /* RIP & Flags */
1331 if (fWhat & CPUMCTX_EXTRN_PC)
1332 GET_REG64_RAW(pVCpu->cpum.GstCtx.Pc.u64, WHvArm64RegisterPc);
1333 if (fWhat & CPUMCTX_EXTRN_PSTATE)
1334 GET_REG64_RAW(pVCpu->cpum.GstCtx.fPState, WHvArm64RegisterPstate);
1335 if (fWhat & CPUMCTX_EXTRN_SPSR)
1336 GET_SYSREG64(pVCpu->cpum.GstCtx.Spsr, WHvArm64RegisterSpsrEl1);
1337 if (fWhat & CPUMCTX_EXTRN_ELR)
1338 GET_SYSREG64(pVCpu->cpum.GstCtx.Elr, WHvArm64RegisterElrEl1);
1339 if (fWhat & CPUMCTX_EXTRN_SP)
1340 {
1341 GET_SYSREG64(pVCpu->cpum.GstCtx.aSpReg[0], WHvArm64RegisterSpEl0);
1342 GET_SYSREG64(pVCpu->cpum.GstCtx.aSpReg[1], WHvArm64RegisterSpEl1);
1343 }
1344 if (fWhat & CPUMCTX_EXTRN_SCTLR_TCR_TTBR)
1345 {
1346 GET_SYSREG64(pVCpu->cpum.GstCtx.Sctlr, WHvArm64RegisterSctlrEl1);
1347 GET_SYSREG64(pVCpu->cpum.GstCtx.Tcr, WHvArm64RegisterTcrEl1);
1348 GET_SYSREG64(pVCpu->cpum.GstCtx.Ttbr0, WHvArm64RegisterTtbr0El1);
1349 GET_SYSREG64(pVCpu->cpum.GstCtx.Ttbr1, WHvArm64RegisterTtbr1El1);
1350 }
1351
1352 /* Vector state. */
1353 if (fWhat & CPUMCTX_EXTRN_V0_V31)
1354 {
1355 GET_REG128(pVCpu->cpum.GstCtx.aVRegs[0], WHvArm64RegisterQ0);
1356 GET_REG128(pVCpu->cpum.GstCtx.aVRegs[1], WHvArm64RegisterQ1);
1357 GET_REG128(pVCpu->cpum.GstCtx.aVRegs[2], WHvArm64RegisterQ2);
1358 GET_REG128(pVCpu->cpum.GstCtx.aVRegs[3], WHvArm64RegisterQ3);
1359 GET_REG128(pVCpu->cpum.GstCtx.aVRegs[4], WHvArm64RegisterQ4);
1360 GET_REG128(pVCpu->cpum.GstCtx.aVRegs[5], WHvArm64RegisterQ5);
1361 GET_REG128(pVCpu->cpum.GstCtx.aVRegs[6], WHvArm64RegisterQ6);
1362 GET_REG128(pVCpu->cpum.GstCtx.aVRegs[7], WHvArm64RegisterQ7);
1363 GET_REG128(pVCpu->cpum.GstCtx.aVRegs[8], WHvArm64RegisterQ8);
1364 GET_REG128(pVCpu->cpum.GstCtx.aVRegs[9], WHvArm64RegisterQ9);
1365 GET_REG128(pVCpu->cpum.GstCtx.aVRegs[10], WHvArm64RegisterQ10);
1366 GET_REG128(pVCpu->cpum.GstCtx.aVRegs[11], WHvArm64RegisterQ11);
1367 GET_REG128(pVCpu->cpum.GstCtx.aVRegs[12], WHvArm64RegisterQ12);
1368 GET_REG128(pVCpu->cpum.GstCtx.aVRegs[13], WHvArm64RegisterQ13);
1369 GET_REG128(pVCpu->cpum.GstCtx.aVRegs[14], WHvArm64RegisterQ14);
1370 GET_REG128(pVCpu->cpum.GstCtx.aVRegs[15], WHvArm64RegisterQ15);
1371
1372 GET_REG128(pVCpu->cpum.GstCtx.aVRegs[16], WHvArm64RegisterQ16);
1373 GET_REG128(pVCpu->cpum.GstCtx.aVRegs[17], WHvArm64RegisterQ17);
1374 GET_REG128(pVCpu->cpum.GstCtx.aVRegs[18], WHvArm64RegisterQ18);
1375 GET_REG128(pVCpu->cpum.GstCtx.aVRegs[19], WHvArm64RegisterQ19);
1376 GET_REG128(pVCpu->cpum.GstCtx.aVRegs[20], WHvArm64RegisterQ20);
1377 GET_REG128(pVCpu->cpum.GstCtx.aVRegs[21], WHvArm64RegisterQ21);
1378 GET_REG128(pVCpu->cpum.GstCtx.aVRegs[22], WHvArm64RegisterQ22);
1379 GET_REG128(pVCpu->cpum.GstCtx.aVRegs[23], WHvArm64RegisterQ23);
1380 GET_REG128(pVCpu->cpum.GstCtx.aVRegs[24], WHvArm64RegisterQ24);
1381 GET_REG128(pVCpu->cpum.GstCtx.aVRegs[25], WHvArm64RegisterQ25);
1382 GET_REG128(pVCpu->cpum.GstCtx.aVRegs[26], WHvArm64RegisterQ26);
1383 GET_REG128(pVCpu->cpum.GstCtx.aVRegs[27], WHvArm64RegisterQ27);
1384 GET_REG128(pVCpu->cpum.GstCtx.aVRegs[28], WHvArm64RegisterQ28);
1385 GET_REG128(pVCpu->cpum.GstCtx.aVRegs[29], WHvArm64RegisterQ29);
1386 GET_REG128(pVCpu->cpum.GstCtx.aVRegs[30], WHvArm64RegisterQ30);
1387 GET_REG128(pVCpu->cpum.GstCtx.aVRegs[31], WHvArm64RegisterQ31);
1388 }
1389 if (fWhat & CPUMCTX_EXTRN_FPCR)
1390 GET_REG64_RAW(pVCpu->cpum.GstCtx.fpcr, WHvArm64RegisterFpcr);
1391 if (fWhat & CPUMCTX_EXTRN_FPSR)
1392 GET_REG64_RAW(pVCpu->cpum.GstCtx.fpsr, WHvArm64RegisterFpsr);
1393
1394 /* System registers. */
1395 if (fWhat & CPUMCTX_EXTRN_SYSREG_MISC)
1396 {
1397 GET_SYSREG64(pVCpu->cpum.GstCtx.VBar, WHvArm64RegisterVbarEl1);
1398 GET_SYSREG64(pVCpu->cpum.GstCtx.Esr, WHvArm64RegisterEsrEl1);
1399 GET_SYSREG64(pVCpu->cpum.GstCtx.Far, WHvArm64RegisterFarEl1);
1400 /** @todo */
1401 }
1402
1403#if 0
1404 if (fWhat & CPUMCTX_EXTRN_SYSREG_DEBUG)
1405 {
1406 GET_SYSREG64(pVCpu->cpum.GstCtx.aBp[0].Ctrl, WHvArm64RegisterDbgbcr0El1);
1407 /** @todo */
1408 }
1409#endif
1410
1411 if (fWhat & CPUMCTX_EXTRN_SYSREG_PAUTH_KEYS)
1412 {
1413 GET_SYSREG64(pVCpu->cpum.GstCtx.Apda.High, WHvArm64RegisterApdAKeyHiEl1);
1414 /** @todo */
1415 }
1416
1417 /* Almost done, just update extrn flags. */
1418 pVCpu->cpum.GstCtx.fExtrn &= ~fWhat;
1419 if (!(pVCpu->cpum.GstCtx.fExtrn & CPUMCTX_EXTRN_ALL))
1420 pVCpu->cpum.GstCtx.fExtrn = 0;
1421
1422 return VINF_SUCCESS;
1423}
1424
1425
1426/**
1427 * Interface for importing state on demand (used by IEM).
1428 *
1429 * @returns VBox status code.
1430 * @param pVCpu The cross context CPU structure.
1431 * @param fWhat What to import, CPUMCTX_EXTRN_XXX.
1432 */
1433VMM_INT_DECL(int) NEMImportStateOnDemand(PVMCPUCC pVCpu, uint64_t fWhat)
1434{
1435 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatImportOnDemand);
1436 return nemHCWinCopyStateFromHyperV(pVCpu->pVMR3, pVCpu, fWhat);
1437}
1438
1439
1440/**
1441 * Query the CPU tick counter and optionally the TSC_AUX MSR value.
1442 *
1443 * @returns VBox status code.
1444 * @param pVCpu The cross context CPU structure.
1445 * @param pcTicks Where to return the CPU tick count.
1446 * @param puAux Where to return the TSC_AUX register value.
1447 */
1448VMM_INT_DECL(int) NEMHCQueryCpuTick(PVMCPUCC pVCpu, uint64_t *pcTicks, uint32_t *puAux)
1449{
1450 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatQueryCpuTick);
1451
1452 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
1453 VMCPU_ASSERT_EMT_RETURN(pVCpu, VERR_VM_THREAD_NOT_EMT);
1454 AssertReturn(VM_IS_NEM_ENABLED(pVM), VERR_NEM_IPE_9);
1455
1456#if 0 /** @todo */
1457 /* Call the offical API. */
1458 WHV_REGISTER_NAME aenmNames[2] = { WHvX64RegisterTsc, WHvX64RegisterTscAux };
1459 WHV_REGISTER_VALUE aValues[2] = { { {0, 0} }, { {0, 0} } };
1460 Assert(RT_ELEMENTS(aenmNames) == RT_ELEMENTS(aValues));
1461 HRESULT hrc = WHvGetVirtualProcessorRegisters(pVM->nem.s.hPartition, pVCpu->idCpu, aenmNames, 2, aValues);
1462 AssertLogRelMsgReturn(SUCCEEDED(hrc),
1463 ("WHvGetVirtualProcessorRegisters(%p, %u,{tsc,tsc_aux},2,) -> %Rhrc (Last=%#x/%u)\n",
1464 pVM->nem.s.hPartition, pVCpu->idCpu, hrc, RTNtLastStatusValue(), RTNtLastErrorValue())
1465 , VERR_NEM_GET_REGISTERS_FAILED);
1466 *pcTicks = aValues[0].Reg64;
1467 if (puAux)
1468 *puAux = pVCpu->cpum.GstCtx.fExtrn & CPUMCTX_EXTRN_TSC_AUX ? aValues[1].Reg64 : CPUMGetGuestTscAux(pVCpu);
1469#endif
1470 return VINF_SUCCESS;
1471}
1472
1473
1474/**
1475 * Resumes CPU clock (TSC) on all virtual CPUs.
1476 *
1477 * This is called by TM when the VM is started, restored, resumed or similar.
1478 *
1479 * @returns VBox status code.
1480 * @param pVM The cross context VM structure.
1481 * @param pVCpu The cross context CPU structure of the calling EMT.
1482 * @param uPausedTscValue The TSC value at the time of pausing.
1483 */
1484VMM_INT_DECL(int) NEMHCResumeCpuTickOnAll(PVMCC pVM, PVMCPUCC pVCpu, uint64_t uPausedTscValue)
1485{
1486 VMCPU_ASSERT_EMT_RETURN(pVCpu, VERR_VM_THREAD_NOT_EMT);
1487 AssertReturn(VM_IS_NEM_ENABLED(pVM), VERR_NEM_IPE_9);
1488
1489 /*
1490 * Call the offical API to do the job.
1491 */
1492 if (pVM->cCpus > 1)
1493 RTThreadYield(); /* Try decrease the chance that we get rescheduled in the middle. */
1494
1495#if 0 /** @todo */
1496 /* Start with the first CPU. */
1497 WHV_REGISTER_NAME enmName = WHvX64RegisterTsc;
1498 WHV_REGISTER_VALUE Value = { {0, 0} };
1499 Value.Reg64 = uPausedTscValue;
1500 uint64_t const uFirstTsc = ASMReadTSC();
1501 HRESULT hrc = WHvSetVirtualProcessorRegisters(pVM->nem.s.hPartition, 0 /*iCpu*/, &enmName, 1, &Value);
1502 AssertLogRelMsgReturn(SUCCEEDED(hrc),
1503 ("WHvSetVirtualProcessorRegisters(%p, 0,{tsc},2,%#RX64) -> %Rhrc (Last=%#x/%u)\n",
1504 pVM->nem.s.hPartition, uPausedTscValue, hrc, RTNtLastStatusValue(), RTNtLastErrorValue())
1505 , VERR_NEM_SET_TSC);
1506
1507 /* Do the other CPUs, adjusting for elapsed TSC and keeping finger crossed
1508 that we don't introduce too much drift here. */
1509 for (VMCPUID iCpu = 1; iCpu < pVM->cCpus; iCpu++)
1510 {
1511 Assert(enmName == WHvX64RegisterTsc);
1512 const uint64_t offDelta = (ASMReadTSC() - uFirstTsc);
1513 Value.Reg64 = uPausedTscValue + offDelta;
1514 hrc = WHvSetVirtualProcessorRegisters(pVM->nem.s.hPartition, iCpu, &enmName, 1, &Value);
1515 AssertLogRelMsgReturn(SUCCEEDED(hrc),
1516 ("WHvSetVirtualProcessorRegisters(%p, 0,{tsc},2,%#RX64 + %#RX64) -> %Rhrc (Last=%#x/%u)\n",
1517 pVM->nem.s.hPartition, iCpu, uPausedTscValue, offDelta, hrc, RTNtLastStatusValue(), RTNtLastErrorValue())
1518 , VERR_NEM_SET_TSC);
1519 }
1520#endif
1521
1522 return VINF_SUCCESS;
1523}
1524
1525
1526#ifdef LOG_ENABLED
1527/**
1528 * Logs the current CPU state.
1529 */
1530static void nemR3WinLogState(PVMCC pVM, PVMCPUCC pVCpu)
1531{
1532 if (LogIs3Enabled())
1533 {
1534 char szRegs[4096];
1535 DBGFR3RegPrintf(pVM->pUVM, pVCpu->idCpu, &szRegs[0], sizeof(szRegs),
1536 "x0=%016VR{x0} x1=%016VR{x1} x2=%016VR{x2} x3=%016VR{x3}\n"
1537 "x4=%016VR{x4} x5=%016VR{x5} x6=%016VR{x6} x7=%016VR{x7}\n"
1538 "x8=%016VR{x8} x9=%016VR{x9} x10=%016VR{x10} x11=%016VR{x11}\n"
1539 "x12=%016VR{x12} x13=%016VR{x13} x14=%016VR{x14} x15=%016VR{x15}\n"
1540 "x16=%016VR{x16} x17=%016VR{x17} x18=%016VR{x18} x19=%016VR{x19}\n"
1541 "x20=%016VR{x20} x21=%016VR{x21} x22=%016VR{x22} x23=%016VR{x23}\n"
1542 "x24=%016VR{x24} x25=%016VR{x25} x26=%016VR{x26} x27=%016VR{x27}\n"
1543 "x28=%016VR{x28} x29=%016VR{x29} x30=%016VR{x30}\n"
1544 "pc=%016VR{pc} pstate=%016VR{pstate}\n"
1545 "sp_el0=%016VR{sp_el0} sp_el1=%016VR{sp_el1} elr_el1=%016VR{elr_el1}\n"
1546 "sctlr_el1=%016VR{sctlr_el1} tcr_el1=%016VR{tcr_el1}\n"
1547 "ttbr0_el1=%016VR{ttbr0_el1} ttbr1_el1=%016VR{ttbr1_el1}\n"
1548 "vbar_el1=%016VR{vbar_el1}\n"
1549 );
1550 char szInstr[256]; RT_ZERO(szInstr);
1551#if 0
1552 DBGFR3DisasInstrEx(pVM->pUVM, pVCpu->idCpu, 0, 0,
1553 DBGF_DISAS_FLAGS_CURRENT_GUEST | DBGF_DISAS_FLAGS_DEFAULT_MODE,
1554 szInstr, sizeof(szInstr), NULL);
1555#endif
1556 Log3(("%s%s\n", szRegs, szInstr));
1557 }
1558}
1559#endif /* LOG_ENABLED */
1560
1561
1562/**
1563 * Copies register state from the (common) exit context.
1564 *
1565 * ASSUMES no state copied yet.
1566 *
1567 * @param pVCpu The cross context per CPU structure.
1568 * @param pMsgHdr The common message header.
1569 */
1570DECLINLINE(void) nemR3WinCopyStateFromArmHeader(PVMCPUCC pVCpu, WHV_INTERCEPT_MESSAGE_HEADER const *pMsgHdr)
1571{
1572 Assert( (pVCpu->cpum.GstCtx.fExtrn & (CPUMCTX_EXTRN_PC | CPUMCTX_EXTRN_PSTATE))
1573 == (CPUMCTX_EXTRN_PC | CPUMCTX_EXTRN_PSTATE));
1574
1575 pVCpu->cpum.GstCtx.Pc.u64 = pMsgHdr->Pc;
1576 pVCpu->cpum.GstCtx.fPState = pMsgHdr->Cpsr;
1577
1578 pVCpu->cpum.GstCtx.fExtrn &= ~(CPUMCTX_EXTRN_PC | CPUMCTX_EXTRN_PSTATE);
1579}
1580
1581
1582/**
1583 * State to pass between nemHCWinHandleMemoryAccess / nemR3WinWHvHandleMemoryAccess
1584 * and nemHCWinHandleMemoryAccessPageCheckerCallback.
1585 */
1586typedef struct NEMHCWINHMACPCCSTATE
1587{
1588 /** Input: Write access. */
1589 bool fWriteAccess;
1590 /** Output: Set if we did something. */
1591 bool fDidSomething;
1592 /** Output: Set it we should resume. */
1593 bool fCanResume;
1594} NEMHCWINHMACPCCSTATE;
1595
1596/**
1597 * @callback_method_impl{FNPGMPHYSNEMCHECKPAGE,
1598 * Worker for nemR3WinHandleMemoryAccess; pvUser points to a
1599 * NEMHCWINHMACPCCSTATE structure. }
1600 */
1601NEM_TMPL_STATIC DECLCALLBACK(int)
1602nemHCWinHandleMemoryAccessPageCheckerCallback(PVMCC pVM, PVMCPUCC pVCpu, RTGCPHYS GCPhys, PPGMPHYSNEMPAGEINFO pInfo, void *pvUser)
1603{
1604 NEMHCWINHMACPCCSTATE *pState = (NEMHCWINHMACPCCSTATE *)pvUser;
1605 pState->fDidSomething = false;
1606 pState->fCanResume = false;
1607
1608 /* If A20 is disabled, we may need to make another query on the masked
1609 page to get the correct protection information. */
1610 uint8_t u2State = pInfo->u2NemState;
1611 RTGCPHYS GCPhysSrc = GCPhys;
1612
1613 /*
1614 * Consolidate current page state with actual page protection and access type.
1615 * We don't really consider downgrades here, as they shouldn't happen.
1616 */
1617 int rc;
1618 switch (u2State)
1619 {
1620 case NEM_WIN_PAGE_STATE_UNMAPPED:
1621 case NEM_WIN_PAGE_STATE_NOT_SET:
1622 if (pInfo->fNemProt == NEM_PAGE_PROT_NONE)
1623 {
1624 Log4(("nemHCWinHandleMemoryAccessPageCheckerCallback: %RGp - #1\n", GCPhys));
1625 return VINF_SUCCESS;
1626 }
1627
1628 /* Don't bother remapping it if it's a write request to a non-writable page. */
1629 if ( pState->fWriteAccess
1630 && !(pInfo->fNemProt & NEM_PAGE_PROT_WRITE))
1631 {
1632 Log4(("nemHCWinHandleMemoryAccessPageCheckerCallback: %RGp - #1w\n", GCPhys));
1633 return VINF_SUCCESS;
1634 }
1635
1636 /* Map the page. */
1637 rc = nemHCNativeSetPhysPage(pVM,
1638 pVCpu,
1639 GCPhysSrc & ~(RTGCPHYS)X86_PAGE_OFFSET_MASK,
1640 GCPhys & ~(RTGCPHYS)X86_PAGE_OFFSET_MASK,
1641 pInfo->fNemProt,
1642 &u2State,
1643 true /*fBackingState*/);
1644 pInfo->u2NemState = u2State;
1645 Log4(("nemHCWinHandleMemoryAccessPageCheckerCallback: %RGp - synced => %s + %Rrc\n",
1646 GCPhys, g_apszPageStates[u2State], rc));
1647 pState->fDidSomething = true;
1648 pState->fCanResume = true;
1649 return rc;
1650
1651 case NEM_WIN_PAGE_STATE_READABLE:
1652 if ( !(pInfo->fNemProt & NEM_PAGE_PROT_WRITE)
1653 && (pInfo->fNemProt & (NEM_PAGE_PROT_READ | NEM_PAGE_PROT_EXECUTE)))
1654 {
1655 Log4(("nemHCWinHandleMemoryAccessPageCheckerCallback: %RGp - #2\n", GCPhys));
1656 return VINF_SUCCESS;
1657 }
1658
1659 break;
1660
1661 case NEM_WIN_PAGE_STATE_WRITABLE:
1662 if (pInfo->fNemProt & NEM_PAGE_PROT_WRITE)
1663 {
1664 if (pInfo->u2OldNemState == NEM_WIN_PAGE_STATE_WRITABLE)
1665 Log4(("nemHCWinHandleMemoryAccessPageCheckerCallback: %RGp - #3a\n", GCPhys));
1666 else
1667 {
1668 pState->fCanResume = true;
1669 Log4(("nemHCWinHandleMemoryAccessPageCheckerCallback: %RGp - #3b (%s -> %s)\n",
1670 GCPhys, g_apszPageStates[pInfo->u2OldNemState], g_apszPageStates[u2State]));
1671 }
1672 return VINF_SUCCESS;
1673 }
1674 break;
1675
1676 default:
1677 AssertLogRelMsgFailedReturn(("u2State=%#x\n", u2State), VERR_NEM_IPE_4);
1678 }
1679
1680 /*
1681 * Unmap and restart the instruction.
1682 * If this fails, which it does every so often, just unmap everything for now.
1683 */
1684 /** @todo figure out whether we mess up the state or if it's WHv. */
1685 STAM_REL_PROFILE_START(&pVM->nem.s.StatProfUnmapGpaRangePage, a);
1686 HRESULT hrc = WHvUnmapGpaRange(pVM->nem.s.hPartition, GCPhys, X86_PAGE_SIZE);
1687 STAM_REL_PROFILE_STOP(&pVM->nem.s.StatProfUnmapGpaRangePage, a);
1688 if (SUCCEEDED(hrc))
1689 {
1690 pState->fDidSomething = true;
1691 pState->fCanResume = true;
1692 pInfo->u2NemState = NEM_WIN_PAGE_STATE_UNMAPPED;
1693 STAM_REL_COUNTER_INC(&pVM->nem.s.StatUnmapPage);
1694 uint32_t cMappedPages = ASMAtomicDecU32(&pVM->nem.s.cMappedPages); NOREF(cMappedPages);
1695 Log5(("NEM GPA unmapped/exit: %RGp (was %s, cMappedPages=%u)\n", GCPhys, g_apszPageStates[u2State], cMappedPages));
1696 return VINF_SUCCESS;
1697 }
1698 STAM_REL_COUNTER_INC(&pVM->nem.s.StatUnmapPageFailed);
1699 LogRel(("nemHCWinHandleMemoryAccessPageCheckerCallback/unmap: GCPhysDst=%RGp %s hrc=%Rhrc (%#x)\n",
1700 GCPhys, g_apszPageStates[u2State], hrc, hrc));
1701 return VERR_NEM_UNMAP_PAGES_FAILED;
1702}
1703
1704
1705/**
1706 * Returns the byte size from the given access SAS value.
1707 *
1708 * @returns Number of bytes to transfer.
1709 * @param uSas The SAS value to convert.
1710 */
1711DECLINLINE(size_t) nemR3WinGetByteCountFromSas(uint8_t uSas)
1712{
1713 switch (uSas)
1714 {
1715 case ARMV8_EC_ISS_DATA_ABRT_SAS_BYTE: return sizeof(uint8_t);
1716 case ARMV8_EC_ISS_DATA_ABRT_SAS_HALFWORD: return sizeof(uint16_t);
1717 case ARMV8_EC_ISS_DATA_ABRT_SAS_WORD: return sizeof(uint32_t);
1718 case ARMV8_EC_ISS_DATA_ABRT_SAS_DWORD: return sizeof(uint64_t);
1719 default:
1720 AssertReleaseFailed();
1721 }
1722
1723 return 0;
1724}
1725
1726
1727/**
1728 * Sets the given general purpose register to the given value.
1729 *
1730 * @param pVCpu The cross context virtual CPU structure of the
1731 * calling EMT.
1732 * @param uReg The register index.
1733 * @param f64BitReg Flag whether to operate on a 64-bit or 32-bit register.
1734 * @param fSignExtend Flag whether to sign extend the value.
1735 * @param u64Val The value.
1736 */
1737DECLINLINE(void) nemR3WinSetGReg(PVMCPU pVCpu, uint8_t uReg, bool f64BitReg, bool fSignExtend, uint64_t u64Val)
1738{
1739 AssertReturnVoid(uReg < 31);
1740
1741 if (f64BitReg)
1742 pVCpu->cpum.GstCtx.aGRegs[uReg].x = fSignExtend ? (int64_t)u64Val : u64Val;
1743 else
1744 pVCpu->cpum.GstCtx.aGRegs[uReg].w = fSignExtend ? (int32_t)u64Val : u64Val; /** @todo Does this clear the upper half on real hardware? */
1745
1746 /* Mark the register as not extern anymore. */
1747 switch (uReg)
1748 {
1749 case 0:
1750 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_X0;
1751 break;
1752 case 1:
1753 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_X1;
1754 break;
1755 case 2:
1756 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_X2;
1757 break;
1758 case 3:
1759 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_X3;
1760 break;
1761 default:
1762 AssertRelease(!(pVCpu->cpum.GstCtx.fExtrn & CPUMCTX_EXTRN_X4_X28));
1763 /** @todo We need to import all missing registers in order to clear this flag (or just set it in HV from here). */
1764 }
1765}
1766
1767
1768/**
1769 * Gets the given general purpose register and returns the value.
1770 *
1771 * @returns Value from the given register.
1772 * @param pVCpu The cross context virtual CPU structure of the
1773 * calling EMT.
1774 * @param uReg The register index.
1775 */
1776DECLINLINE(uint64_t) nemR3WinGetGReg(PVMCPU pVCpu, uint8_t uReg)
1777{
1778 AssertReturn(uReg <= ARMV8_AARCH64_REG_ZR, 0);
1779
1780 if (uReg == ARMV8_AARCH64_REG_ZR)
1781 return 0;
1782
1783 /** @todo Import the register if extern. */
1784 AssertRelease(!(pVCpu->cpum.GstCtx.fExtrn & CPUMCTX_EXTRN_GPRS_MASK));
1785
1786 return pVCpu->cpum.GstCtx.aGRegs[uReg].x;
1787}
1788
1789
1790/**
1791 * Deals with memory access exits (WHvRunVpExitReasonMemoryAccess).
1792 *
1793 * @returns Strict VBox status code.
1794 * @param pVM The cross context VM structure.
1795 * @param pVCpu The cross context per CPU structure.
1796 * @param pExit The VM exit information to handle.
1797 * @sa nemHCWinHandleMessageMemory
1798 */
1799NEM_TMPL_STATIC VBOXSTRICTRC
1800nemR3WinHandleExitMemory(PVMCC pVM, PVMCPUCC pVCpu, WHV_RUN_VP_EXIT_CONTEXT const *pExit)
1801{
1802 uint64_t const uHostTsc = ASMReadTSC();
1803 Assert(pExit->MemoryAccess.Header.InterceptAccessType != 3);
1804
1805 /*
1806 * Ask PGM for information about the given GCPhys. We need to check if we're
1807 * out of sync first.
1808 */
1809 WHV_INTERCEPT_MESSAGE_HEADER const *pHdr = &pExit->MemoryAccess.Header;
1810 NEMHCWINHMACPCCSTATE State = { pExit->MemoryAccess.Header.InterceptAccessType == WHvMemoryAccessWrite, false, false };
1811 PGMPHYSNEMPAGEINFO Info;
1812 int rc = PGMPhysNemPageInfoChecker(pVM, pVCpu, pExit->MemoryAccess.Gpa, State.fWriteAccess, &Info,
1813 nemHCWinHandleMemoryAccessPageCheckerCallback, &State);
1814 if (RT_SUCCESS(rc))
1815 {
1816 if (Info.fNemProt & ( pExit->MemoryAccess.Header.InterceptAccessType == WHvMemoryAccessWrite
1817 ? NEM_PAGE_PROT_WRITE : NEM_PAGE_PROT_READ))
1818 {
1819 if (State.fCanResume)
1820 {
1821 Log4(("MemExit/%u: %08RX64: %RGp (=>%RHp) %s fProt=%u%s%s%s; restarting (%s)\n",
1822 pVCpu->idCpu, pHdr->Pc,
1823 pExit->MemoryAccess.Gpa, Info.HCPhys, g_apszPageStates[Info.u2NemState], Info.fNemProt,
1824 Info.fHasHandlers ? " handlers" : "", Info.fZeroPage ? " zero-pg" : "",
1825 State.fDidSomething ? "" : " no-change", g_apszHvInterceptAccessTypes[pExit->MemoryAccess.Header.InterceptAccessType]));
1826 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_MEMORY_ACCESS),
1827 pHdr->Pc, uHostTsc);
1828 return VINF_SUCCESS;
1829 }
1830 }
1831 Log4(("MemExit/%u: %08RX64: %RGp (=>%RHp) %s fProt=%u%s%s%s; emulating (%s)\n",
1832 pVCpu->idCpu, pHdr->Pc,
1833 pExit->MemoryAccess.Gpa, Info.HCPhys, g_apszPageStates[Info.u2NemState], Info.fNemProt,
1834 Info.fHasHandlers ? " handlers" : "", Info.fZeroPage ? " zero-pg" : "",
1835 State.fDidSomething ? "" : " no-change", g_apszHvInterceptAccessTypes[pExit->MemoryAccess.Header.InterceptAccessType]));
1836 }
1837 else
1838 Log4(("MemExit/%u: %08RX64: %RGp rc=%Rrc%s; emulating (%s)\n",
1839 pVCpu->idCpu, pHdr->Pc,
1840 pExit->MemoryAccess.Gpa, rc, State.fDidSomething ? " modified-backing" : "",
1841 g_apszHvInterceptAccessTypes[pExit->MemoryAccess.Header.InterceptAccessType]));
1842
1843 /*
1844 * Emulate the memory access, either access handler or special memory.
1845 */
1846 PCEMEXITREC pExitRec = EMHistoryAddExit(pVCpu,
1847 pExit->MemoryAccess.Header.InterceptAccessType == WHvMemoryAccessWrite
1848 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_MMIO_WRITE)
1849 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_MMIO_READ),
1850 pHdr->Pc, uHostTsc);
1851 //nemR3WinCopyStateFromArmHeader(pVCpu, &pExit->MemoryAccess.Header);
1852 rc = nemHCWinCopyStateFromHyperV(pVM, pVCpu, IEM_CPUMCTX_EXTRN_MUST_MASK);
1853 AssertRCReturn(rc, rc);
1854
1855 uint8_t const cbInstr = pExit->MemoryAccess.InstructionByteCount;
1856 RTGCPTR const GCPtrVa = pExit->MemoryAccess.Gva;
1857 RTGCPHYS const GCPhys = pExit->MemoryAccess.Gpa;
1858 uint64_t const uIss = pExit->MemoryAccess.Syndrome;
1859 bool fIsv = RT_BOOL(uIss & ARMV8_EC_ISS_DATA_ABRT_ISV);
1860 bool fL2Fault = RT_BOOL(uIss & ARMV8_EC_ISS_DATA_ABRT_S1PTW);
1861 bool fWrite = RT_BOOL(uIss & ARMV8_EC_ISS_DATA_ABRT_WNR);
1862 bool f64BitReg = RT_BOOL(uIss & ARMV8_EC_ISS_DATA_ABRT_SF);
1863 bool fSignExtend = RT_BOOL(uIss & ARMV8_EC_ISS_DATA_ABRT_SSE);
1864 uint8_t uReg = ARMV8_EC_ISS_DATA_ABRT_SRT_GET(uIss);
1865 uint8_t uAcc = ARMV8_EC_ISS_DATA_ABRT_SAS_GET(uIss);
1866 size_t cbAcc = nemR3WinGetByteCountFromSas(uAcc);
1867 LogFlowFunc(("fIsv=%RTbool fL2Fault=%RTbool fWrite=%RTbool f64BitReg=%RTbool fSignExtend=%RTbool uReg=%u uAcc=%u GCPtrDataAbrt=%RGv GCPhys=%RGp cbInstr=%u\n",
1868 fIsv, fL2Fault, fWrite, f64BitReg, fSignExtend, uReg, uAcc, GCPtrVa, GCPhys, cbInstr));
1869
1870 RT_NOREF(fL2Fault);
1871
1872 AssertReturn(fIsv, VERR_NOT_SUPPORTED); /** @todo Implement using IEM when this should occur. */
1873
1874 EMHistoryAddExit(pVCpu,
1875 fWrite
1876 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_MMIO_WRITE)
1877 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_MMIO_READ),
1878 pVCpu->cpum.GstCtx.Pc.u64, ASMReadTSC());
1879
1880 VBOXSTRICTRC rcStrict = VINF_SUCCESS;
1881 uint64_t u64Val = 0;
1882 if (fWrite)
1883 {
1884 u64Val = nemR3WinGetGReg(pVCpu, uReg);
1885 rcStrict = PGMPhysWrite(pVM, GCPhys, &u64Val, cbAcc, PGMACCESSORIGIN_HM);
1886 Log4(("MmioExit/%u: %08RX64: WRITE %RGp LB %u, %.*Rhxs -> rcStrict=%Rrc\n",
1887 pVCpu->idCpu, pVCpu->cpum.GstCtx.Pc.u64, GCPhys, cbAcc, cbAcc,
1888 &u64Val, VBOXSTRICTRC_VAL(rcStrict) ));
1889 }
1890 else
1891 {
1892 rcStrict = PGMPhysRead(pVM, GCPhys, &u64Val, cbAcc, PGMACCESSORIGIN_HM);
1893 Log4(("MmioExit/%u: %08RX64: READ %RGp LB %u -> %.*Rhxs rcStrict=%Rrc\n",
1894 pVCpu->idCpu, pVCpu->cpum.GstCtx.Pc.u64, GCPhys, cbAcc, cbAcc,
1895 &u64Val, VBOXSTRICTRC_VAL(rcStrict) ));
1896 if (rcStrict == VINF_SUCCESS)
1897 nemR3WinSetGReg(pVCpu, uReg, f64BitReg, fSignExtend, u64Val);
1898 }
1899
1900 if (rcStrict == VINF_SUCCESS)
1901 pVCpu->cpum.GstCtx.Pc.u64 += sizeof(uint32_t); /** @todo Why is InstructionByteCount always 0? */
1902
1903 return rcStrict;
1904}
1905
1906
1907/**
1908 * Deals with MSR access exits (WHvRunVpExitReasonUnrecoverableException).
1909 *
1910 * @returns Strict VBox status code.
1911 * @param pVM The cross context VM structure.
1912 * @param pVCpu The cross context per CPU structure.
1913 * @param pExit The VM exit information to handle.
1914 * @sa nemHCWinHandleMessageUnrecoverableException
1915 */
1916NEM_TMPL_STATIC VBOXSTRICTRC nemR3WinHandleExitUnrecoverableException(PVMCC pVM, PVMCPUCC pVCpu, WHV_RUN_VP_EXIT_CONTEXT const *pExit)
1917{
1918#if 0
1919 /*
1920 * Just copy the state we've got and handle it in the loop for now.
1921 */
1922 nemR3WinCopyStateFromX64Header(pVCpu, &pExit->VpContext);
1923 Log(("TripleExit/%u: %04x:%08RX64/%s: RFL=%#RX64 -> VINF_EM_TRIPLE_FAULT\n", pVCpu->idCpu, pExit->VpContext.Cs.Selector,
1924 pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext), pExit->VpContext.Rflags));
1925 RT_NOREF_PV(pVM);
1926 return VINF_EM_TRIPLE_FAULT;
1927#else
1928 /*
1929 * Let IEM decide whether this is really it.
1930 */
1931 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_UNRECOVERABLE_EXCEPTION),
1932 pExit->UnrecoverableException.Header.Pc, ASMReadTSC());
1933 nemR3WinCopyStateFromArmHeader(pVCpu, &pExit->UnrecoverableException.Header);
1934 AssertReleaseFailed();
1935 RT_NOREF_PV(pVM);
1936 return VINF_SUCCESS;
1937#endif
1938}
1939
1940
1941/**
1942 * Handles VM exits.
1943 *
1944 * @returns Strict VBox status code.
1945 * @param pVM The cross context VM structure.
1946 * @param pVCpu The cross context per CPU structure.
1947 * @param pExit The VM exit information to handle.
1948 * @sa nemHCWinHandleMessage
1949 */
1950NEM_TMPL_STATIC VBOXSTRICTRC nemR3WinHandleExit(PVMCC pVM, PVMCPUCC pVCpu, WHV_RUN_VP_EXIT_CONTEXT const *pExit)
1951{
1952 int rc = nemHCWinCopyStateFromHyperV(pVM, pVCpu, CPUMCTX_EXTRN_ALL);
1953 AssertRCReturn(rc, rc);
1954
1955#ifdef LOG_ENABLED
1956 if (LogIs3Enabled())
1957 nemR3WinLogState(pVM, pVCpu);
1958#endif
1959
1960 switch (pExit->ExitReason)
1961 {
1962 case WHvRunVpExitReasonUnmappedGpa:
1963 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitMemUnmapped);
1964 return nemR3WinHandleExitMemory(pVM, pVCpu, pExit);
1965
1966 case WHvRunVpExitReasonCanceled:
1967 Log4(("CanceledExit/%u\n", pVCpu->idCpu));
1968 return VINF_SUCCESS;
1969
1970 case WHvRunVpExitReasonUnrecoverableException:
1971 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitUnrecoverable);
1972 return nemR3WinHandleExitUnrecoverableException(pVM, pVCpu, pExit);
1973
1974 case WHvRunVpExitReasonUnsupportedFeature:
1975 case WHvRunVpExitReasonInvalidVpRegisterValue:
1976 LogRel(("Unimplemented exit:\n%.*Rhxd\n", (int)sizeof(*pExit), pExit));
1977 AssertLogRelMsgFailedReturn(("Unexpected exit on CPU #%u: %#x\n%.32Rhxd\n",
1978 pVCpu->idCpu, pExit->ExitReason, pExit), VERR_NEM_IPE_3);
1979
1980 /* Undesired exits: */
1981 case WHvRunVpExitReasonNone:
1982 default:
1983 LogRel(("Unknown exit:\n%.*Rhxd\n", (int)sizeof(*pExit), pExit));
1984 AssertLogRelMsgFailedReturn(("Unknown exit on CPU #%u: %#x!\n", pVCpu->idCpu, pExit->ExitReason), VERR_NEM_IPE_3);
1985 }
1986}
1987
1988
1989VBOXSTRICTRC nemR3NativeRunGC(PVM pVM, PVMCPU pVCpu)
1990{
1991 LogFlow(("NEM/%u: %08RX64 pstate=%#08RX64 <=\n", pVCpu->idCpu, pVCpu->cpum.GstCtx.Pc, pVCpu->cpum.GstCtx.fPState));
1992#ifdef LOG_ENABLED
1993 if (LogIs3Enabled())
1994 nemR3WinLogState(pVM, pVCpu);
1995#endif
1996
1997 if (RT_UNLIKELY(!pVCpu->nem.s.fIdRegsSynced))
1998 {
1999 /*
2000 * Sync the guest ID registers which are per VM once (they are readonly and stay constant during VM lifetime).
2001 * Need to do it here and not during the init because loading a saved state might change the ID registers from what
2002 * done in the call to CPUMR3PopulateFeaturesByIdRegisters().
2003 */
2004 PCCPUMIDREGS pIdRegsGst = NULL;
2005 int rc = CPUMR3QueryGuestIdRegs(pVM, &pIdRegsGst);
2006 AssertRCReturn(rc, rc);
2007
2008 WHV_REGISTER_NAME aenmNames[12];
2009 WHV_REGISTER_VALUE aValues[12];
2010
2011 uint32_t iReg = 0;
2012#define ADD_REG64(a_enmName, a_uValue) do { \
2013 aenmNames[iReg] = (a_enmName); \
2014 aValues[iReg].Reg128.High64 = 0; \
2015 aValues[iReg].Reg64 = (a_uValue); \
2016 iReg++; \
2017 } while (0)
2018
2019
2020 ADD_REG64(WHvArm64RegisterIdAa64Mmfr0El1, pIdRegsGst->u64RegIdAa64Mmfr0El1);
2021#undef ADD_REG64
2022
2023 //HRESULT hrc = WHvSetVirtualProcessorRegisters(pVM->nem.s.hPartition, pVCpu->idCpu, aenmNames, iReg, aValues);
2024 //AssertReturn(SUCCEEDED(hrc), VERR_NEM_IPE_9);
2025
2026 pVCpu->nem.s.fIdRegsSynced = true;
2027 }
2028
2029 /*
2030 * Try switch to NEM runloop state.
2031 */
2032 if (VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC_NEM, VMCPUSTATE_STARTED))
2033 { /* likely */ }
2034 else
2035 {
2036 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC_NEM, VMCPUSTATE_STARTED_EXEC_NEM_CANCELED);
2037 LogFlow(("NEM/%u: returning immediately because canceled\n", pVCpu->idCpu));
2038 return VINF_SUCCESS;
2039 }
2040
2041 /*
2042 * The run loop.
2043 *
2044 * Current approach to state updating to use the sledgehammer and sync
2045 * everything every time. This will be optimized later.
2046 */
2047 const bool fSingleStepping = DBGFIsStepping(pVCpu);
2048// const uint32_t fCheckVmFFs = !fSingleStepping ? VM_FF_HP_R0_PRE_HM_MASK
2049// : VM_FF_HP_R0_PRE_HM_STEP_MASK;
2050// const uint32_t fCheckCpuFFs = !fSingleStepping ? VMCPU_FF_HP_R0_PRE_HM_MASK : VMCPU_FF_HP_R0_PRE_HM_STEP_MASK;
2051 VBOXSTRICTRC rcStrict = VINF_SUCCESS;
2052 for (unsigned iLoop = 0;; iLoop++)
2053 {
2054 /*
2055 * Pending interrupts or such? Need to check and deal with this prior
2056 * to the state syncing.
2057 */
2058#if 0
2059 if (VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_INTERRUPT_FIQ | VMCPU_FF_UPDATE_IRQ))
2060 {
2061 /* Try inject interrupt. */
2062 rcStrict = nemHCWinHandleInterruptFF(pVM, pVCpu, &pVCpu->nem.s.fDesiredInterruptWindows);
2063 if (rcStrict == VINF_SUCCESS)
2064 { /* likely */ }
2065 else
2066 {
2067 LogFlow(("NEM/%u: breaking: nemHCWinHandleInterruptFF -> %Rrc\n", pVCpu->idCpu, VBOXSTRICTRC_VAL(rcStrict) ));
2068 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatBreakOnStatus);
2069 break;
2070 }
2071 }
2072#endif
2073
2074 /* Ensure that Hyper-V has the whole state. */
2075 int rc2 = nemHCWinCopyStateToHyperV(pVM, pVCpu);
2076 AssertRCReturn(rc2, rc2);
2077
2078 /*
2079 * Poll timers and run for a bit.
2080 *
2081 * With the VID approach (ring-0 or ring-3) we can specify a timeout here,
2082 * so we take the time of the next timer event and uses that as a deadline.
2083 * The rounding heuristics are "tuned" so that rhel5 (1K timer) will boot fine.
2084 */
2085 /** @todo See if we cannot optimize this TMTimerPollGIP by only redoing
2086 * the whole polling job when timers have changed... */
2087 uint64_t offDeltaIgnored;
2088 uint64_t const nsNextTimerEvt = TMTimerPollGIP(pVM, pVCpu, &offDeltaIgnored); NOREF(nsNextTimerEvt);
2089 if ( !VM_FF_IS_ANY_SET(pVM, VM_FF_EMT_RENDEZVOUS | VM_FF_TM_VIRTUAL_SYNC)
2090 && !VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
2091 {
2092 if (VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC_NEM_WAIT, VMCPUSTATE_STARTED_EXEC_NEM))
2093 {
2094#if 0 //def LOG_ENABLED
2095 if (LogIsFlowEnabled())
2096 {
2097 static const WHV_REGISTER_NAME s_aNames[6] = { WHvX64RegisterCs, WHvX64RegisterRip, WHvX64RegisterRflags,
2098 WHvX64RegisterSs, WHvX64RegisterRsp, WHvX64RegisterCr0 };
2099 WHV_REGISTER_VALUE aRegs[RT_ELEMENTS(s_aNames)] = { {{0, 0} } };
2100 WHvGetVirtualProcessorRegisters(pVM->nem.s.hPartition, pVCpu->idCpu, s_aNames, RT_ELEMENTS(s_aNames), aRegs);
2101 LogFlow(("NEM/%u: Entry @ %04x:%08RX64 IF=%d EFL=%#RX64 SS:RSP=%04x:%08RX64 cr0=%RX64\n",
2102 pVCpu->idCpu, aRegs[0].Segment.Selector, aRegs[1].Reg64, RT_BOOL(aRegs[2].Reg64 & X86_EFL_IF),
2103 aRegs[2].Reg64, aRegs[3].Segment.Selector, aRegs[4].Reg64, aRegs[5].Reg64));
2104 }
2105#endif
2106 WHV_RUN_VP_EXIT_CONTEXT ExitReason = {0};
2107 TMNotifyStartOfExecution(pVM, pVCpu);
2108
2109 HRESULT hrc = WHvRunVirtualProcessor(pVM->nem.s.hPartition, pVCpu->idCpu, &ExitReason, sizeof(ExitReason));
2110
2111 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC_NEM, VMCPUSTATE_STARTED_EXEC_NEM_WAIT);
2112 TMNotifyEndOfExecution(pVM, pVCpu, ASMReadTSC());
2113#ifdef LOG_ENABLED
2114 LogFlow(("NEM/%u: Exit @ @todo Reason=%#x\n", pVCpu->idCpu, ExitReason.ExitReason));
2115#endif
2116 if (SUCCEEDED(hrc))
2117 {
2118 /*
2119 * Deal with the message.
2120 */
2121 rcStrict = nemR3WinHandleExit(pVM, pVCpu, &ExitReason);
2122 if (rcStrict == VINF_SUCCESS)
2123 { /* hopefully likely */ }
2124 else
2125 {
2126 LogFlow(("NEM/%u: breaking: nemHCWinHandleMessage -> %Rrc\n", pVCpu->idCpu, VBOXSTRICTRC_VAL(rcStrict) ));
2127 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatBreakOnStatus);
2128 break;
2129 }
2130 }
2131 else
2132 AssertLogRelMsgFailedReturn(("WHvRunVirtualProcessor failed for CPU #%u: %#x (%u)\n",
2133 pVCpu->idCpu, hrc, GetLastError()),
2134 VERR_NEM_IPE_0);
2135
2136 /*
2137 * If no relevant FFs are pending, loop.
2138 */
2139 if ( !VM_FF_IS_ANY_SET( pVM, !fSingleStepping ? VM_FF_HP_R0_PRE_HM_MASK : VM_FF_HP_R0_PRE_HM_STEP_MASK)
2140 && !VMCPU_FF_IS_ANY_SET(pVCpu, !fSingleStepping ? VMCPU_FF_HP_R0_PRE_HM_MASK : VMCPU_FF_HP_R0_PRE_HM_STEP_MASK) )
2141 continue;
2142
2143 /** @todo Try handle pending flags, not just return to EM loops. Take care
2144 * not to set important RCs here unless we've handled a message. */
2145 LogFlow(("NEM/%u: breaking: pending FF (%#x / %#RX64)\n",
2146 pVCpu->idCpu, pVM->fGlobalForcedActions, (uint64_t)pVCpu->fLocalForcedActions));
2147 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatBreakOnFFPost);
2148 }
2149 else
2150 {
2151 LogFlow(("NEM/%u: breaking: canceled %d (pre exec)\n", pVCpu->idCpu, VMCPU_GET_STATE(pVCpu) ));
2152 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatBreakOnCancel);
2153 }
2154 }
2155 else
2156 {
2157 LogFlow(("NEM/%u: breaking: pending FF (pre exec)\n", pVCpu->idCpu));
2158 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatBreakOnFFPre);
2159 }
2160 break;
2161 } /* the run loop */
2162
2163
2164 /*
2165 * If the CPU is running, make sure to stop it before we try sync back the
2166 * state and return to EM. We don't sync back the whole state if we can help it.
2167 */
2168 if (!VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED, VMCPUSTATE_STARTED_EXEC_NEM))
2169 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED, VMCPUSTATE_STARTED_EXEC_NEM_CANCELED);
2170
2171 if (pVCpu->cpum.GstCtx.fExtrn & CPUMCTX_EXTRN_ALL)
2172 {
2173 /* Try anticipate what we might need. */
2174 uint64_t fImport = IEM_CPUMCTX_EXTRN_MUST_MASK;
2175 if ( (rcStrict >= VINF_EM_FIRST && rcStrict <= VINF_EM_LAST)
2176 || RT_FAILURE(rcStrict))
2177 fImport = CPUMCTX_EXTRN_ALL;
2178 else if (VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_INTERRUPT_IRQ | VMCPU_FF_INTERRUPT_FIQ))
2179 fImport |= IEM_CPUMCTX_EXTRN_XCPT_MASK;
2180
2181 if (pVCpu->cpum.GstCtx.fExtrn & fImport)
2182 {
2183 int rc2 = nemHCWinCopyStateFromHyperV(pVM, pVCpu, fImport);
2184 if (RT_SUCCESS(rc2))
2185 pVCpu->cpum.GstCtx.fExtrn &= ~fImport;
2186 else if (RT_SUCCESS(rcStrict))
2187 rcStrict = rc2;
2188 if (!(pVCpu->cpum.GstCtx.fExtrn & CPUMCTX_EXTRN_ALL))
2189 pVCpu->cpum.GstCtx.fExtrn = 0;
2190 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatImportOnReturn);
2191 }
2192 else
2193 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatImportOnReturnSkipped);
2194 }
2195 else
2196 {
2197 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatImportOnReturnSkipped);
2198 pVCpu->cpum.GstCtx.fExtrn = 0;
2199 }
2200
2201#if 0
2202 LogFlow(("NEM/%u: %04x:%08RX64 efl=%#08RX64 => %Rrc\n", pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel,
2203 pVCpu->cpum.GstCtx.rip, pVCpu->cpum.GstCtx.rflags.u, VBOXSTRICTRC_VAL(rcStrict) ));
2204#endif
2205 return rcStrict;
2206}
2207
2208
2209VMMR3_INT_DECL(bool) NEMR3CanExecuteGuest(PVM pVM, PVMCPU pVCpu)
2210{
2211 Assert(VM_IS_NEM_ENABLED(pVM));
2212 RT_NOREF(pVM, pVCpu);
2213 return true;
2214}
2215
2216
2217bool nemR3NativeSetSingleInstruction(PVM pVM, PVMCPU pVCpu, bool fEnable)
2218{
2219 NOREF(pVM); NOREF(pVCpu); NOREF(fEnable);
2220 return false;
2221}
2222
2223
2224void nemR3NativeNotifyFF(PVM pVM, PVMCPU pVCpu, uint32_t fFlags)
2225{
2226 Log8(("nemR3NativeNotifyFF: canceling %u\n", pVCpu->idCpu));
2227 HRESULT hrc = WHvCancelRunVirtualProcessor(pVM->nem.s.hPartition, pVCpu->idCpu, 0);
2228 AssertMsg(SUCCEEDED(hrc), ("WHvCancelRunVirtualProcessor -> hrc=%Rhrc\n", hrc));
2229 RT_NOREF_PV(hrc);
2230 RT_NOREF_PV(fFlags);
2231}
2232
2233
2234DECLHIDDEN(bool) nemR3NativeNotifyDebugEventChanged(PVM pVM, bool fUseDebugLoop)
2235{
2236 RT_NOREF(pVM, fUseDebugLoop);
2237 return false;
2238}
2239
2240
2241DECLHIDDEN(bool) nemR3NativeNotifyDebugEventChangedPerCpu(PVM pVM, PVMCPU pVCpu, bool fUseDebugLoop)
2242{
2243 RT_NOREF(pVM, pVCpu, fUseDebugLoop);
2244 return false;
2245}
2246
2247
2248DECLINLINE(int) nemR3NativeGCPhys2R3PtrReadOnly(PVM pVM, RTGCPHYS GCPhys, const void **ppv)
2249{
2250 PGMPAGEMAPLOCK Lock;
2251 int rc = PGMPhysGCPhys2CCPtrReadOnly(pVM, GCPhys, ppv, &Lock);
2252 if (RT_SUCCESS(rc))
2253 PGMPhysReleasePageMappingLock(pVM, &Lock);
2254 return rc;
2255}
2256
2257
2258DECLINLINE(int) nemR3NativeGCPhys2R3PtrWriteable(PVM pVM, RTGCPHYS GCPhys, void **ppv)
2259{
2260 PGMPAGEMAPLOCK Lock;
2261 int rc = PGMPhysGCPhys2CCPtr(pVM, GCPhys, ppv, &Lock);
2262 if (RT_SUCCESS(rc))
2263 PGMPhysReleasePageMappingLock(pVM, &Lock);
2264 return rc;
2265}
2266
2267
2268VMMR3_INT_DECL(int) NEMR3NotifyPhysRamRegister(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, void *pvR3,
2269 uint8_t *pu2State, uint32_t *puNemRange)
2270{
2271 Log5(("NEMR3NotifyPhysRamRegister: %RGp LB %RGp, pvR3=%p pu2State=%p (%d) puNemRange=%p (%d)\n",
2272 GCPhys, cb, pvR3, pu2State, pu2State, puNemRange, *puNemRange));
2273
2274 *pu2State = UINT8_MAX;
2275 RT_NOREF(puNemRange);
2276
2277 if (pvR3)
2278 {
2279 STAM_REL_PROFILE_START(&pVM->nem.s.StatProfMapGpaRange, a);
2280 HRESULT hrc = WHvMapGpaRange(pVM->nem.s.hPartition, pvR3, GCPhys, cb,
2281 WHvMapGpaRangeFlagRead | WHvMapGpaRangeFlagWrite | WHvMapGpaRangeFlagExecute);
2282 STAM_REL_PROFILE_STOP(&pVM->nem.s.StatProfMapGpaRange, a);
2283 if (SUCCEEDED(hrc))
2284 *pu2State = NEM_WIN_PAGE_STATE_WRITABLE;
2285 else
2286 {
2287 LogRel(("NEMR3NotifyPhysRamRegister: GCPhys=%RGp LB %RGp pvR3=%p hrc=%Rhrc (%#x) Last=%#x/%u\n",
2288 GCPhys, cb, pvR3, hrc, hrc, RTNtLastStatusValue(), RTNtLastErrorValue()));
2289 STAM_REL_COUNTER_INC(&pVM->nem.s.StatMapPageFailed);
2290 return VERR_NEM_MAP_PAGES_FAILED;
2291 }
2292 }
2293 return VINF_SUCCESS;
2294}
2295
2296
2297VMMR3_INT_DECL(bool) NEMR3IsMmio2DirtyPageTrackingSupported(PVM pVM)
2298{
2299 RT_NOREF(pVM);
2300 return g_pfnWHvQueryGpaRangeDirtyBitmap != NULL;
2301}
2302
2303
2304VMMR3_INT_DECL(int) NEMR3NotifyPhysMmioExMapEarly(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, uint32_t fFlags,
2305 void *pvRam, void *pvMmio2, uint8_t *pu2State, uint32_t *puNemRange)
2306{
2307 Log5(("NEMR3NotifyPhysMmioExMapEarly: %RGp LB %RGp fFlags=%#x pvRam=%p pvMmio2=%p pu2State=%p (%d) puNemRange=%p (%#x)\n",
2308 GCPhys, cb, fFlags, pvRam, pvMmio2, pu2State, *pu2State, puNemRange, puNemRange ? *puNemRange : UINT32_MAX));
2309 RT_NOREF(puNemRange);
2310
2311 /*
2312 * Unmap the RAM we're replacing.
2313 */
2314 if (fFlags & NEM_NOTIFY_PHYS_MMIO_EX_F_REPLACE)
2315 {
2316 STAM_REL_PROFILE_START(&pVM->nem.s.StatProfUnmapGpaRange, a);
2317 HRESULT hrc = WHvUnmapGpaRange(pVM->nem.s.hPartition, GCPhys, cb);
2318 STAM_REL_PROFILE_STOP(&pVM->nem.s.StatProfUnmapGpaRange, a);
2319 if (SUCCEEDED(hrc))
2320 { /* likely */ }
2321 else if (pvMmio2)
2322 LogRel(("NEMR3NotifyPhysMmioExMapEarly: GCPhys=%RGp LB %RGp fFlags=%#x: Unmap -> hrc=%Rhrc (%#x) Last=%#x/%u (ignored)\n",
2323 GCPhys, cb, fFlags, hrc, hrc, RTNtLastStatusValue(), RTNtLastErrorValue()));
2324 else
2325 {
2326 LogRel(("NEMR3NotifyPhysMmioExMapEarly: GCPhys=%RGp LB %RGp fFlags=%#x: Unmap -> hrc=%Rhrc (%#x) Last=%#x/%u\n",
2327 GCPhys, cb, fFlags, hrc, hrc, RTNtLastStatusValue(), RTNtLastErrorValue()));
2328 STAM_REL_COUNTER_INC(&pVM->nem.s.StatUnmapPageFailed);
2329 return VERR_NEM_UNMAP_PAGES_FAILED;
2330 }
2331 }
2332
2333 /*
2334 * Map MMIO2 if any.
2335 */
2336 if (pvMmio2)
2337 {
2338 Assert(fFlags & NEM_NOTIFY_PHYS_MMIO_EX_F_MMIO2);
2339 WHV_MAP_GPA_RANGE_FLAGS fWHvFlags = WHvMapGpaRangeFlagRead | WHvMapGpaRangeFlagWrite | WHvMapGpaRangeFlagExecute;
2340 if ((fFlags & NEM_NOTIFY_PHYS_MMIO_EX_F_TRACK_DIRTY_PAGES) && g_pfnWHvQueryGpaRangeDirtyBitmap)
2341 fWHvFlags |= WHvMapGpaRangeFlagTrackDirtyPages;
2342 STAM_REL_PROFILE_START(&pVM->nem.s.StatProfMapGpaRange, a);
2343 HRESULT hrc = WHvMapGpaRange(pVM->nem.s.hPartition, pvMmio2, GCPhys, cb, fWHvFlags);
2344 STAM_REL_PROFILE_STOP(&pVM->nem.s.StatProfMapGpaRange, a);
2345 if (SUCCEEDED(hrc))
2346 *pu2State = NEM_WIN_PAGE_STATE_WRITABLE;
2347 else
2348 {
2349 LogRel(("NEMR3NotifyPhysMmioExMapEarly: GCPhys=%RGp LB %RGp fFlags=%#x pvMmio2=%p fWHvFlags=%#x: Map -> hrc=%Rhrc (%#x) Last=%#x/%u\n",
2350 GCPhys, cb, fFlags, pvMmio2, fWHvFlags, hrc, hrc, RTNtLastStatusValue(), RTNtLastErrorValue()));
2351 STAM_REL_COUNTER_INC(&pVM->nem.s.StatMapPageFailed);
2352 return VERR_NEM_MAP_PAGES_FAILED;
2353 }
2354 }
2355 else
2356 {
2357 Assert(!(fFlags & NEM_NOTIFY_PHYS_MMIO_EX_F_MMIO2));
2358 *pu2State = NEM_WIN_PAGE_STATE_UNMAPPED;
2359 }
2360 RT_NOREF(pvRam);
2361 return VINF_SUCCESS;
2362}
2363
2364
2365VMMR3_INT_DECL(int) NEMR3NotifyPhysMmioExMapLate(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, uint32_t fFlags,
2366 void *pvRam, void *pvMmio2, uint32_t *puNemRange)
2367{
2368 RT_NOREF(pVM, GCPhys, cb, fFlags, pvRam, pvMmio2, puNemRange);
2369 return VINF_SUCCESS;
2370}
2371
2372
2373VMMR3_INT_DECL(int) NEMR3NotifyPhysMmioExUnmap(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, uint32_t fFlags, void *pvRam,
2374 void *pvMmio2, uint8_t *pu2State, uint32_t *puNemRange)
2375{
2376 int rc = VINF_SUCCESS;
2377 Log5(("NEMR3NotifyPhysMmioExUnmap: %RGp LB %RGp fFlags=%#x pvRam=%p pvMmio2=%p pu2State=%p uNemRange=%#x (%#x)\n",
2378 GCPhys, cb, fFlags, pvRam, pvMmio2, pu2State, puNemRange, *puNemRange));
2379
2380 /*
2381 * Unmap the MMIO2 pages.
2382 */
2383 /** @todo If we implement aliasing (MMIO2 page aliased into MMIO range),
2384 * we may have more stuff to unmap even in case of pure MMIO... */
2385 if (fFlags & NEM_NOTIFY_PHYS_MMIO_EX_F_MMIO2)
2386 {
2387 STAM_REL_PROFILE_START(&pVM->nem.s.StatProfUnmapGpaRange, a);
2388 HRESULT hrc = WHvUnmapGpaRange(pVM->nem.s.hPartition, GCPhys, cb);
2389 STAM_REL_PROFILE_STOP(&pVM->nem.s.StatProfUnmapGpaRange, a);
2390 if (FAILED(hrc))
2391 {
2392 LogRel2(("NEMR3NotifyPhysMmioExUnmap: GCPhys=%RGp LB %RGp fFlags=%#x: Unmap -> hrc=%Rhrc (%#x) Last=%#x/%u (ignored)\n",
2393 GCPhys, cb, fFlags, hrc, hrc, RTNtLastStatusValue(), RTNtLastErrorValue()));
2394 rc = VERR_NEM_UNMAP_PAGES_FAILED;
2395 STAM_REL_COUNTER_INC(&pVM->nem.s.StatUnmapPageFailed);
2396 }
2397 }
2398
2399 /*
2400 * Restore the RAM we replaced.
2401 */
2402 if (fFlags & NEM_NOTIFY_PHYS_MMIO_EX_F_REPLACE)
2403 {
2404 AssertPtr(pvRam);
2405 STAM_REL_PROFILE_START(&pVM->nem.s.StatProfMapGpaRange, a);
2406 HRESULT hrc = WHvMapGpaRange(pVM->nem.s.hPartition, pvRam, GCPhys, cb,
2407 WHvMapGpaRangeFlagRead | WHvMapGpaRangeFlagWrite | WHvMapGpaRangeFlagExecute);
2408 STAM_REL_PROFILE_STOP(&pVM->nem.s.StatProfMapGpaRange, a);
2409 if (SUCCEEDED(hrc))
2410 { /* likely */ }
2411 else
2412 {
2413 LogRel(("NEMR3NotifyPhysMmioExUnmap: GCPhys=%RGp LB %RGp pvMmio2=%p hrc=%Rhrc (%#x) Last=%#x/%u\n",
2414 GCPhys, cb, pvMmio2, hrc, hrc, RTNtLastStatusValue(), RTNtLastErrorValue()));
2415 rc = VERR_NEM_MAP_PAGES_FAILED;
2416 STAM_REL_COUNTER_INC(&pVM->nem.s.StatMapPageFailed);
2417 }
2418 if (pu2State)
2419 *pu2State = NEM_WIN_PAGE_STATE_WRITABLE;
2420 }
2421 /* Mark the pages as unmapped if relevant. */
2422 else if (pu2State)
2423 *pu2State = NEM_WIN_PAGE_STATE_UNMAPPED;
2424
2425 RT_NOREF(pvMmio2, puNemRange);
2426 return rc;
2427}
2428
2429
2430VMMR3_INT_DECL(int) NEMR3PhysMmio2QueryAndResetDirtyBitmap(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, uint32_t uNemRange,
2431 void *pvBitmap, size_t cbBitmap)
2432{
2433 Assert(VM_IS_NEM_ENABLED(pVM));
2434 AssertReturn(g_pfnWHvQueryGpaRangeDirtyBitmap, VERR_INTERNAL_ERROR_2);
2435 Assert(cbBitmap == (uint32_t)cbBitmap);
2436 RT_NOREF(uNemRange);
2437
2438 /* This is being profiled by PGM, see /PGM/Mmio2QueryAndResetDirtyBitmap. */
2439 HRESULT hrc = WHvQueryGpaRangeDirtyBitmap(pVM->nem.s.hPartition, GCPhys, cb, (UINT64 *)pvBitmap, (uint32_t)cbBitmap);
2440 if (SUCCEEDED(hrc))
2441 return VINF_SUCCESS;
2442
2443 AssertLogRelMsgFailed(("GCPhys=%RGp LB %RGp pvBitmap=%p LB %#zx hrc=%Rhrc (%#x) Last=%#x/%u\n",
2444 GCPhys, cb, pvBitmap, cbBitmap, hrc, hrc, RTNtLastStatusValue(), RTNtLastErrorValue()));
2445 return VERR_NEM_QUERY_DIRTY_BITMAP_FAILED;
2446}
2447
2448
2449VMMR3_INT_DECL(int) NEMR3NotifyPhysRomRegisterEarly(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, void *pvPages, uint32_t fFlags,
2450 uint8_t *pu2State, uint32_t *puNemRange)
2451{
2452 Log5(("nemR3NativeNotifyPhysRomRegisterEarly: %RGp LB %RGp pvPages=%p fFlags=%#x\n", GCPhys, cb, pvPages, fFlags));
2453 *pu2State = UINT8_MAX;
2454 *puNemRange = 0;
2455
2456#if 0 /* Let's not do this after all. We'll protection change notifications for each page and if not we'll map them lazily. */
2457 RTGCPHYS const cPages = cb >> X86_PAGE_SHIFT;
2458 for (RTGCPHYS iPage = 0; iPage < cPages; iPage++, GCPhys += X86_PAGE_SIZE)
2459 {
2460 const void *pvPage;
2461 int rc = nemR3NativeGCPhys2R3PtrReadOnly(pVM, GCPhys, &pvPage);
2462 if (RT_SUCCESS(rc))
2463 {
2464 HRESULT hrc = WHvMapGpaRange(pVM->nem.s.hPartition, (void *)pvPage, GCPhys, X86_PAGE_SIZE,
2465 WHvMapGpaRangeFlagRead | WHvMapGpaRangeFlagExecute);
2466 if (SUCCEEDED(hrc))
2467 { /* likely */ }
2468 else
2469 {
2470 LogRel(("nemR3NativeNotifyPhysRomRegisterEarly: GCPhys=%RGp hrc=%Rhrc (%#x) Last=%#x/%u\n",
2471 GCPhys, hrc, hrc, RTNtLastStatusValue(), RTNtLastErrorValue()));
2472 return VERR_NEM_INIT_FAILED;
2473 }
2474 }
2475 else
2476 {
2477 LogRel(("nemR3NativeNotifyPhysRomRegisterEarly: GCPhys=%RGp rc=%Rrc\n", GCPhys, rc));
2478 return rc;
2479 }
2480 }
2481 RT_NOREF_PV(fFlags);
2482#else
2483 RT_NOREF(pVM, GCPhys, cb, pvPages, fFlags);
2484#endif
2485 return VINF_SUCCESS;
2486}
2487
2488
2489VMMR3_INT_DECL(int) NEMR3NotifyPhysRomRegisterLate(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, void *pvPages,
2490 uint32_t fFlags, uint8_t *pu2State, uint32_t *puNemRange)
2491{
2492 Log5(("nemR3NativeNotifyPhysRomRegisterLate: %RGp LB %RGp pvPages=%p fFlags=%#x pu2State=%p (%d) puNemRange=%p (%#x)\n",
2493 GCPhys, cb, pvPages, fFlags, pu2State, *pu2State, puNemRange, *puNemRange));
2494 *pu2State = UINT8_MAX;
2495
2496 /*
2497 * (Re-)map readonly.
2498 */
2499 AssertPtrReturn(pvPages, VERR_INVALID_POINTER);
2500 STAM_REL_PROFILE_START(&pVM->nem.s.StatProfMapGpaRange, a);
2501 HRESULT hrc = WHvMapGpaRange(pVM->nem.s.hPartition, pvPages, GCPhys, cb, WHvMapGpaRangeFlagRead | WHvMapGpaRangeFlagExecute);
2502 STAM_REL_PROFILE_STOP(&pVM->nem.s.StatProfMapGpaRange, a);
2503 if (SUCCEEDED(hrc))
2504 *pu2State = NEM_WIN_PAGE_STATE_READABLE;
2505 else
2506 {
2507 LogRel(("nemR3NativeNotifyPhysRomRegisterEarly: GCPhys=%RGp LB %RGp pvPages=%p fFlags=%#x hrc=%Rhrc (%#x) Last=%#x/%u\n",
2508 GCPhys, cb, pvPages, fFlags, hrc, hrc, RTNtLastStatusValue(), RTNtLastErrorValue()));
2509 STAM_REL_COUNTER_INC(&pVM->nem.s.StatMapPageFailed);
2510 return VERR_NEM_MAP_PAGES_FAILED;
2511 }
2512 RT_NOREF(fFlags, puNemRange);
2513 return VINF_SUCCESS;
2514}
2515
2516VMMR3_INT_DECL(void) NEMR3NotifySetA20(PVMCPU pVCpu, bool fEnabled)
2517{
2518 Log(("nemR3NativeNotifySetA20: fEnabled=%RTbool\n", fEnabled));
2519 Assert(VM_IS_NEM_ENABLED(pVCpu->CTX_SUFF(pVM)));
2520 RT_NOREF(pVCpu, fEnabled);
2521}
2522
2523
2524void nemHCNativeNotifyHandlerPhysicalRegister(PVMCC pVM, PGMPHYSHANDLERKIND enmKind, RTGCPHYS GCPhys, RTGCPHYS cb)
2525{
2526 Log5(("nemHCNativeNotifyHandlerPhysicalRegister: %RGp LB %RGp enmKind=%d\n", GCPhys, cb, enmKind));
2527 NOREF(pVM); NOREF(enmKind); NOREF(GCPhys); NOREF(cb);
2528}
2529
2530
2531VMM_INT_DECL(void) NEMHCNotifyHandlerPhysicalDeregister(PVMCC pVM, PGMPHYSHANDLERKIND enmKind, RTGCPHYS GCPhys, RTGCPHYS cb,
2532 RTR3PTR pvMemR3, uint8_t *pu2State)
2533{
2534 Log5(("NEMHCNotifyHandlerPhysicalDeregister: %RGp LB %RGp enmKind=%d pvMemR3=%p pu2State=%p (%d)\n",
2535 GCPhys, cb, enmKind, pvMemR3, pu2State, *pu2State));
2536
2537 *pu2State = UINT8_MAX;
2538 if (pvMemR3)
2539 {
2540 STAM_REL_PROFILE_START(&pVM->nem.s.StatProfMapGpaRange, a);
2541 HRESULT hrc = WHvMapGpaRange(pVM->nem.s.hPartition, pvMemR3, GCPhys, cb,
2542 WHvMapGpaRangeFlagRead | WHvMapGpaRangeFlagExecute | WHvMapGpaRangeFlagWrite);
2543 STAM_REL_PROFILE_STOP(&pVM->nem.s.StatProfMapGpaRange, a);
2544 if (SUCCEEDED(hrc))
2545 *pu2State = NEM_WIN_PAGE_STATE_WRITABLE;
2546 else
2547 AssertLogRelMsgFailed(("NEMHCNotifyHandlerPhysicalDeregister: WHvMapGpaRange(,%p,%RGp,%RGp,) -> %Rhrc\n",
2548 pvMemR3, GCPhys, cb, hrc));
2549 }
2550 RT_NOREF(enmKind);
2551}
2552
2553
2554void nemHCNativeNotifyHandlerPhysicalModify(PVMCC pVM, PGMPHYSHANDLERKIND enmKind, RTGCPHYS GCPhysOld,
2555 RTGCPHYS GCPhysNew, RTGCPHYS cb, bool fRestoreAsRAM)
2556{
2557 Log5(("nemHCNativeNotifyHandlerPhysicalModify: %RGp LB %RGp -> %RGp enmKind=%d fRestoreAsRAM=%d\n",
2558 GCPhysOld, cb, GCPhysNew, enmKind, fRestoreAsRAM));
2559 NOREF(pVM); NOREF(enmKind); NOREF(GCPhysOld); NOREF(GCPhysNew); NOREF(cb); NOREF(fRestoreAsRAM);
2560}
2561
2562
2563/**
2564 * Worker that maps pages into Hyper-V.
2565 *
2566 * This is used by the PGM physical page notifications as well as the memory
2567 * access VMEXIT handlers.
2568 *
2569 * @returns VBox status code.
2570 * @param pVM The cross context VM structure.
2571 * @param pVCpu The cross context virtual CPU structure of the
2572 * calling EMT.
2573 * @param GCPhysSrc The source page address.
2574 * @param GCPhysDst The hyper-V destination page. This may differ from
2575 * GCPhysSrc when A20 is disabled.
2576 * @param fPageProt NEM_PAGE_PROT_XXX.
2577 * @param pu2State Our page state (input/output).
2578 * @param fBackingChanged Set if the page backing is being changed.
2579 * @thread EMT(pVCpu)
2580 */
2581NEM_TMPL_STATIC int nemHCNativeSetPhysPage(PVMCC pVM, PVMCPUCC pVCpu, RTGCPHYS GCPhysSrc, RTGCPHYS GCPhysDst,
2582 uint32_t fPageProt, uint8_t *pu2State, bool fBackingChanged)
2583{
2584 /*
2585 * Looks like we need to unmap a page before we can change the backing
2586 * or even modify the protection. This is going to be *REALLY* efficient.
2587 * PGM lends us two bits to keep track of the state here.
2588 */
2589 RT_NOREF(pVCpu);
2590 uint8_t const u2OldState = *pu2State;
2591 uint8_t const u2NewState = fPageProt & NEM_PAGE_PROT_WRITE ? NEM_WIN_PAGE_STATE_WRITABLE
2592 : fPageProt & NEM_PAGE_PROT_READ ? NEM_WIN_PAGE_STATE_READABLE : NEM_WIN_PAGE_STATE_UNMAPPED;
2593 if ( fBackingChanged
2594 || u2NewState != u2OldState)
2595 {
2596 if (u2OldState > NEM_WIN_PAGE_STATE_UNMAPPED)
2597 {
2598 STAM_REL_PROFILE_START(&pVM->nem.s.StatProfUnmapGpaRangePage, a);
2599 HRESULT hrc = WHvUnmapGpaRange(pVM->nem.s.hPartition, GCPhysDst, X86_PAGE_SIZE);
2600 STAM_REL_PROFILE_STOP(&pVM->nem.s.StatProfUnmapGpaRangePage, a);
2601 if (SUCCEEDED(hrc))
2602 {
2603 *pu2State = NEM_WIN_PAGE_STATE_UNMAPPED;
2604 STAM_REL_COUNTER_INC(&pVM->nem.s.StatUnmapPage);
2605 uint32_t cMappedPages = ASMAtomicDecU32(&pVM->nem.s.cMappedPages); NOREF(cMappedPages);
2606 if (u2NewState == NEM_WIN_PAGE_STATE_UNMAPPED)
2607 {
2608 Log5(("NEM GPA unmapped/set: %RGp (was %s, cMappedPages=%u)\n",
2609 GCPhysDst, g_apszPageStates[u2OldState], cMappedPages));
2610 return VINF_SUCCESS;
2611 }
2612 }
2613 else
2614 {
2615 STAM_REL_COUNTER_INC(&pVM->nem.s.StatUnmapPageFailed);
2616 LogRel(("nemHCNativeSetPhysPage/unmap: GCPhysDst=%RGp hrc=%Rhrc (%#x) Last=%#x/%u\n",
2617 GCPhysDst, hrc, hrc, RTNtLastStatusValue(), RTNtLastErrorValue()));
2618 return VERR_NEM_INIT_FAILED;
2619 }
2620 }
2621 }
2622
2623 /*
2624 * Writeable mapping?
2625 */
2626 if (fPageProt & NEM_PAGE_PROT_WRITE)
2627 {
2628 void *pvPage;
2629 int rc = nemR3NativeGCPhys2R3PtrWriteable(pVM, GCPhysSrc, &pvPage);
2630 if (RT_SUCCESS(rc))
2631 {
2632 HRESULT hrc = WHvMapGpaRange(pVM->nem.s.hPartition, pvPage, GCPhysDst, X86_PAGE_SIZE,
2633 WHvMapGpaRangeFlagRead | WHvMapGpaRangeFlagExecute | WHvMapGpaRangeFlagWrite);
2634 if (SUCCEEDED(hrc))
2635 {
2636 *pu2State = NEM_WIN_PAGE_STATE_WRITABLE;
2637 STAM_REL_COUNTER_INC(&pVM->nem.s.StatMapPage);
2638 uint32_t cMappedPages = ASMAtomicIncU32(&pVM->nem.s.cMappedPages); NOREF(cMappedPages);
2639 Log5(("NEM GPA mapped/set: %RGp %s (was %s, cMappedPages=%u)\n",
2640 GCPhysDst, g_apszPageStates[u2NewState], g_apszPageStates[u2OldState], cMappedPages));
2641 return VINF_SUCCESS;
2642 }
2643 STAM_REL_COUNTER_INC(&pVM->nem.s.StatMapPageFailed);
2644 LogRel(("nemHCNativeSetPhysPage/writable: GCPhysDst=%RGp hrc=%Rhrc (%#x) Last=%#x/%u\n",
2645 GCPhysDst, hrc, hrc, RTNtLastStatusValue(), RTNtLastErrorValue()));
2646 return VERR_NEM_INIT_FAILED;
2647 }
2648 LogRel(("nemHCNativeSetPhysPage/writable: GCPhysSrc=%RGp rc=%Rrc\n", GCPhysSrc, rc));
2649 return rc;
2650 }
2651
2652 if (fPageProt & NEM_PAGE_PROT_READ)
2653 {
2654 const void *pvPage;
2655 int rc = nemR3NativeGCPhys2R3PtrReadOnly(pVM, GCPhysSrc, &pvPage);
2656 if (RT_SUCCESS(rc))
2657 {
2658 STAM_REL_PROFILE_START(&pVM->nem.s.StatProfMapGpaRangePage, a);
2659 HRESULT hrc = WHvMapGpaRange(pVM->nem.s.hPartition, (void *)pvPage, GCPhysDst, X86_PAGE_SIZE,
2660 WHvMapGpaRangeFlagRead | WHvMapGpaRangeFlagExecute);
2661 STAM_REL_PROFILE_STOP(&pVM->nem.s.StatProfMapGpaRangePage, a);
2662 if (SUCCEEDED(hrc))
2663 {
2664 *pu2State = NEM_WIN_PAGE_STATE_READABLE;
2665 STAM_REL_COUNTER_INC(&pVM->nem.s.StatMapPage);
2666 uint32_t cMappedPages = ASMAtomicIncU32(&pVM->nem.s.cMappedPages); NOREF(cMappedPages);
2667 Log5(("NEM GPA mapped/set: %RGp %s (was %s, cMappedPages=%u)\n",
2668 GCPhysDst, g_apszPageStates[u2NewState], g_apszPageStates[u2OldState], cMappedPages));
2669 return VINF_SUCCESS;
2670 }
2671 STAM_REL_COUNTER_INC(&pVM->nem.s.StatMapPageFailed);
2672 LogRel(("nemHCNativeSetPhysPage/readonly: GCPhysDst=%RGp hrc=%Rhrc (%#x) Last=%#x/%u\n",
2673 GCPhysDst, hrc, hrc, RTNtLastStatusValue(), RTNtLastErrorValue()));
2674 return VERR_NEM_INIT_FAILED;
2675 }
2676 LogRel(("nemHCNativeSetPhysPage/readonly: GCPhysSrc=%RGp rc=%Rrc\n", GCPhysSrc, rc));
2677 return rc;
2678 }
2679
2680 /* We already unmapped it above. */
2681 *pu2State = NEM_WIN_PAGE_STATE_UNMAPPED;
2682 return VINF_SUCCESS;
2683}
2684
2685
2686NEM_TMPL_STATIC int nemHCJustUnmapPageFromHyperV(PVMCC pVM, RTGCPHYS GCPhysDst, uint8_t *pu2State)
2687{
2688 if (*pu2State <= NEM_WIN_PAGE_STATE_UNMAPPED)
2689 {
2690 Log5(("nemHCJustUnmapPageFromHyperV: %RGp == unmapped\n", GCPhysDst));
2691 *pu2State = NEM_WIN_PAGE_STATE_UNMAPPED;
2692 return VINF_SUCCESS;
2693 }
2694
2695 STAM_REL_PROFILE_START(&pVM->nem.s.StatProfUnmapGpaRangePage, a);
2696 HRESULT hrc = WHvUnmapGpaRange(pVM->nem.s.hPartition, GCPhysDst & ~(RTGCPHYS)X86_PAGE_OFFSET_MASK, X86_PAGE_SIZE);
2697 STAM_REL_PROFILE_STOP(&pVM->nem.s.StatProfUnmapGpaRangePage, a);
2698 if (SUCCEEDED(hrc))
2699 {
2700 STAM_REL_COUNTER_INC(&pVM->nem.s.StatUnmapPage);
2701 uint32_t cMappedPages = ASMAtomicDecU32(&pVM->nem.s.cMappedPages); NOREF(cMappedPages);
2702 *pu2State = NEM_WIN_PAGE_STATE_UNMAPPED;
2703 Log5(("nemHCJustUnmapPageFromHyperV: %RGp => unmapped (total %u)\n", GCPhysDst, cMappedPages));
2704 return VINF_SUCCESS;
2705 }
2706 STAM_REL_COUNTER_INC(&pVM->nem.s.StatUnmapPageFailed);
2707 LogRel(("nemHCJustUnmapPageFromHyperV(%RGp): failed! hrc=%Rhrc (%#x) Last=%#x/%u\n",
2708 GCPhysDst, hrc, hrc, RTNtLastStatusValue(), RTNtLastErrorValue()));
2709 return VERR_NEM_IPE_6;
2710}
2711
2712
2713int nemHCNativeNotifyPhysPageAllocated(PVMCC pVM, RTGCPHYS GCPhys, RTHCPHYS HCPhys, uint32_t fPageProt,
2714 PGMPAGETYPE enmType, uint8_t *pu2State)
2715{
2716 Log5(("nemHCNativeNotifyPhysPageAllocated: %RGp HCPhys=%RHp fPageProt=%#x enmType=%d *pu2State=%d\n",
2717 GCPhys, HCPhys, fPageProt, enmType, *pu2State));
2718 RT_NOREF_PV(HCPhys); RT_NOREF_PV(enmType);
2719
2720 int rc;
2721 RT_NOREF_PV(fPageProt);
2722 rc = nemHCJustUnmapPageFromHyperV(pVM, GCPhys, pu2State);
2723 return rc;
2724}
2725
2726
2727VMM_INT_DECL(void) NEMHCNotifyPhysPageProtChanged(PVMCC pVM, RTGCPHYS GCPhys, RTHCPHYS HCPhys, RTR3PTR pvR3, uint32_t fPageProt,
2728 PGMPAGETYPE enmType, uint8_t *pu2State)
2729{
2730 Log5(("NEMHCNotifyPhysPageProtChanged: %RGp HCPhys=%RHp fPageProt=%#x enmType=%d *pu2State=%d\n",
2731 GCPhys, HCPhys, fPageProt, enmType, *pu2State));
2732 Assert(VM_IS_NEM_ENABLED(pVM));
2733 RT_NOREF(HCPhys, enmType, pvR3);
2734
2735 RT_NOREF_PV(fPageProt);
2736 nemHCJustUnmapPageFromHyperV(pVM, GCPhys, pu2State);
2737}
2738
2739
2740VMM_INT_DECL(void) NEMHCNotifyPhysPageChanged(PVMCC pVM, RTGCPHYS GCPhys, RTHCPHYS HCPhysPrev, RTHCPHYS HCPhysNew,
2741 RTR3PTR pvNewR3, uint32_t fPageProt, PGMPAGETYPE enmType, uint8_t *pu2State)
2742{
2743 Log5(("nemHCNativeNotifyPhysPageChanged: %RGp HCPhys=%RHp->%RHp pvNewR3=%p fPageProt=%#x enmType=%d *pu2State=%d\n",
2744 GCPhys, HCPhysPrev, HCPhysNew, pvNewR3, fPageProt, enmType, *pu2State));
2745 Assert(VM_IS_NEM_ENABLED(pVM));
2746 RT_NOREF(HCPhysPrev, HCPhysNew, pvNewR3, enmType);
2747
2748 RT_NOREF_PV(fPageProt);
2749 nemHCJustUnmapPageFromHyperV(pVM, GCPhys, pu2State);
2750}
2751
2752
2753/**
2754 * Returns features supported by the NEM backend.
2755 *
2756 * @returns Flags of features supported by the native NEM backend.
2757 * @param pVM The cross context VM structure.
2758 */
2759VMM_INT_DECL(uint32_t) NEMHCGetFeatures(PVMCC pVM)
2760{
2761 RT_NOREF(pVM);
2762 /** @todo Is NEM_FEAT_F_FULL_GST_EXEC always true? */
2763 return NEM_FEAT_F_NESTED_PAGING | NEM_FEAT_F_FULL_GST_EXEC;
2764}
2765
2766
2767/** @page pg_nem_win_aarmv8 NEM/win - Native Execution Manager, Windows.
2768 *
2769 * Open questions:
2770 * - Why can't one read and write WHvArm64RegisterId*
2771 * - WHvArm64RegisterDbgbcr0El1 is not readable?
2772 * - Getting notified about system register reads/writes (GIC)?
2773 * - InstructionByteCount and InstructionBytes for unmapped GPA exit are zero...
2774 * - Handling of (vTimer) interrupts, how is WHvRequestInterrupt() supposed to be used?
2775 */
2776
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