VirtualBox

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

Last change on this file since 106666 was 106592, checked in by vboxsync, 3 months ago

VMM/NEM-win/arm: Unused parmaeters & variable warnings (left pragma messages as reminders about incomplete code). jiraref:VBP-1171

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