VirtualBox

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

最後變更 在這個檔案從80191是 80191,由 vboxsync 提交於 6 年 前

VMM/r3: Refactored VMCPU enumeration in preparation that aCpus will be replaced with a pointer array. Removed two raw-mode offset members from the CPUM and CPUMCPU sub-structures. bugref:9217 bugref:9517

  • 屬性 svn:eol-style 設為 native
  • 屬性 svn:keywords 設為 Author Date Id Revision
檔案大小: 135.8 KB
 
1/* $Id: NEMR3Native-win.cpp 80191 2019-08-08 00:36:57Z 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-2019 Oracle Corporation
14 *
15 * This file is part of VirtualBox Open Source Edition (OSE), as
16 * available from http://www.alldomusa.eu.org. This file is free software;
17 * you can redistribute it and/or modify it under the terms of the GNU
18 * General Public License (GPL) as published by the Free Software
19 * Foundation, in version 2 as it comes in the "COPYING" file of the
20 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
21 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
22 */
23
24
25/*********************************************************************************************************************************
26* Header Files *
27*********************************************************************************************************************************/
28#define VBOX_BUGREF_9217_PART_I
29#define LOG_GROUP LOG_GROUP_NEM
30#define VMCPU_INCL_CPUM_GST_CTX
31#include <iprt/nt/nt-and-windows.h>
32#include <iprt/nt/hyperv.h>
33#include <iprt/nt/vid.h>
34#include <WinHvPlatform.h>
35
36#ifndef _WIN32_WINNT_WIN10
37# error "Missing _WIN32_WINNT_WIN10"
38#endif
39#ifndef _WIN32_WINNT_WIN10_RS1 /* Missing define, causing trouble for us. */
40# define _WIN32_WINNT_WIN10_RS1 (_WIN32_WINNT_WIN10 + 1)
41#endif
42#include <sysinfoapi.h>
43#include <debugapi.h>
44#include <errhandlingapi.h>
45#include <fileapi.h>
46#include <winerror.h> /* no api header for this. */
47
48#include <VBox/vmm/nem.h>
49#include <VBox/vmm/iem.h>
50#include <VBox/vmm/em.h>
51#include <VBox/vmm/apic.h>
52#include <VBox/vmm/pdm.h>
53#include <VBox/vmm/dbgftrace.h>
54#include "NEMInternal.h"
55#include <VBox/vmm/vm.h>
56
57#include <iprt/ldr.h>
58#include <iprt/path.h>
59#include <iprt/string.h>
60#include <iprt/system.h>
61#include <iprt/utf16.h>
62
63
64/*********************************************************************************************************************************
65* Defined Constants And Macros *
66*********************************************************************************************************************************/
67#ifdef LOG_ENABLED
68# define NEM_WIN_INTERCEPT_NT_IO_CTLS
69#endif
70
71/** VID I/O control detection: Fake partition handle input. */
72#define NEM_WIN_IOCTL_DETECTOR_FAKE_HANDLE ((HANDLE)(uintptr_t)38479125)
73/** VID I/O control detection: Fake partition ID return. */
74#define NEM_WIN_IOCTL_DETECTOR_FAKE_PARTITION_ID UINT64_C(0xfa1e000042424242)
75/** VID I/O control detection: Fake CPU index input. */
76#define NEM_WIN_IOCTL_DETECTOR_FAKE_VP_INDEX UINT32_C(42)
77/** VID I/O control detection: Fake timeout input. */
78#define NEM_WIN_IOCTL_DETECTOR_FAKE_TIMEOUT UINT32_C(0x00080286)
79
80
81/*********************************************************************************************************************************
82* Global Variables *
83*********************************************************************************************************************************/
84/** @name APIs imported from WinHvPlatform.dll
85 * @{ */
86static decltype(WHvGetCapability) * g_pfnWHvGetCapability;
87static decltype(WHvCreatePartition) * g_pfnWHvCreatePartition;
88static decltype(WHvSetupPartition) * g_pfnWHvSetupPartition;
89static decltype(WHvDeletePartition) * g_pfnWHvDeletePartition;
90static decltype(WHvGetPartitionProperty) * g_pfnWHvGetPartitionProperty;
91static decltype(WHvSetPartitionProperty) * g_pfnWHvSetPartitionProperty;
92static decltype(WHvMapGpaRange) * g_pfnWHvMapGpaRange;
93static decltype(WHvUnmapGpaRange) * g_pfnWHvUnmapGpaRange;
94static decltype(WHvTranslateGva) * g_pfnWHvTranslateGva;
95#ifndef NEM_WIN_USE_OUR_OWN_RUN_API
96static decltype(WHvCreateVirtualProcessor) * g_pfnWHvCreateVirtualProcessor;
97static decltype(WHvDeleteVirtualProcessor) * g_pfnWHvDeleteVirtualProcessor;
98static decltype(WHvRunVirtualProcessor) * g_pfnWHvRunVirtualProcessor;
99static decltype(WHvCancelRunVirtualProcessor) * g_pfnWHvCancelRunVirtualProcessor;
100static decltype(WHvGetVirtualProcessorRegisters) * g_pfnWHvGetVirtualProcessorRegisters;
101static decltype(WHvSetVirtualProcessorRegisters) * g_pfnWHvSetVirtualProcessorRegisters;
102#endif
103/** @} */
104
105/** @name APIs imported from Vid.dll
106 * @{ */
107static decltype(VidGetHvPartitionId) *g_pfnVidGetHvPartitionId;
108static decltype(VidStartVirtualProcessor) *g_pfnVidStartVirtualProcessor;
109static decltype(VidStopVirtualProcessor) *g_pfnVidStopVirtualProcessor;
110static decltype(VidMessageSlotMap) *g_pfnVidMessageSlotMap;
111static decltype(VidMessageSlotHandleAndGetNext) *g_pfnVidMessageSlotHandleAndGetNext;
112#ifdef LOG_ENABLED
113static decltype(VidGetVirtualProcessorState) *g_pfnVidGetVirtualProcessorState;
114static decltype(VidSetVirtualProcessorState) *g_pfnVidSetVirtualProcessorState;
115static decltype(VidGetVirtualProcessorRunningStatus) *g_pfnVidGetVirtualProcessorRunningStatus;
116#endif
117/** @} */
118
119/** The Windows build number. */
120static uint32_t g_uBuildNo = 17134;
121
122
123
124/**
125 * Import instructions.
126 */
127static const struct
128{
129 uint8_t idxDll; /**< 0 for WinHvPlatform.dll, 1 for vid.dll. */
130 bool fOptional; /**< Set if import is optional. */
131 PFNRT *ppfn; /**< The function pointer variable. */
132 const char *pszName; /**< The function name. */
133} g_aImports[] =
134{
135#define NEM_WIN_IMPORT(a_idxDll, a_fOptional, a_Name) { (a_idxDll), (a_fOptional), (PFNRT *)&RT_CONCAT(g_pfn,a_Name), #a_Name }
136 NEM_WIN_IMPORT(0, false, WHvGetCapability),
137 NEM_WIN_IMPORT(0, false, WHvCreatePartition),
138 NEM_WIN_IMPORT(0, false, WHvSetupPartition),
139 NEM_WIN_IMPORT(0, false, WHvDeletePartition),
140 NEM_WIN_IMPORT(0, false, WHvGetPartitionProperty),
141 NEM_WIN_IMPORT(0, false, WHvSetPartitionProperty),
142 NEM_WIN_IMPORT(0, false, WHvMapGpaRange),
143 NEM_WIN_IMPORT(0, false, WHvUnmapGpaRange),
144 NEM_WIN_IMPORT(0, false, WHvTranslateGva),
145#ifndef NEM_WIN_USE_OUR_OWN_RUN_API
146 NEM_WIN_IMPORT(0, false, WHvCreateVirtualProcessor),
147 NEM_WIN_IMPORT(0, false, WHvDeleteVirtualProcessor),
148 NEM_WIN_IMPORT(0, false, WHvRunVirtualProcessor),
149 NEM_WIN_IMPORT(0, false, WHvCancelRunVirtualProcessor),
150 NEM_WIN_IMPORT(0, false, WHvGetVirtualProcessorRegisters),
151 NEM_WIN_IMPORT(0, false, WHvSetVirtualProcessorRegisters),
152#endif
153 NEM_WIN_IMPORT(1, false, VidGetHvPartitionId),
154 NEM_WIN_IMPORT(1, false, VidMessageSlotMap),
155 NEM_WIN_IMPORT(1, false, VidMessageSlotHandleAndGetNext),
156 NEM_WIN_IMPORT(1, false, VidStartVirtualProcessor),
157 NEM_WIN_IMPORT(1, false, VidStopVirtualProcessor),
158#ifdef LOG_ENABLED
159 NEM_WIN_IMPORT(1, false, VidGetVirtualProcessorState),
160 NEM_WIN_IMPORT(1, false, VidSetVirtualProcessorState),
161 NEM_WIN_IMPORT(1, false, VidGetVirtualProcessorRunningStatus),
162#endif
163#undef NEM_WIN_IMPORT
164};
165
166
167/** The real NtDeviceIoControlFile API in NTDLL. */
168static decltype(NtDeviceIoControlFile) *g_pfnNtDeviceIoControlFile;
169/** Pointer to the NtDeviceIoControlFile import table entry. */
170static decltype(NtDeviceIoControlFile) **g_ppfnVidNtDeviceIoControlFile;
171/** Info about the VidGetHvPartitionId I/O control interface. */
172static NEMWINIOCTL g_IoCtlGetHvPartitionId;
173/** Info about the VidStartVirtualProcessor I/O control interface. */
174static NEMWINIOCTL g_IoCtlStartVirtualProcessor;
175/** Info about the VidStopVirtualProcessor I/O control interface. */
176static NEMWINIOCTL g_IoCtlStopVirtualProcessor;
177/** Info about the VidMessageSlotHandleAndGetNext I/O control interface. */
178static NEMWINIOCTL g_IoCtlMessageSlotHandleAndGetNext;
179#ifdef LOG_ENABLED
180/** Info about the VidMessageSlotMap I/O control interface - for logging. */
181static NEMWINIOCTL g_IoCtlMessageSlotMap;
182/* Info about the VidGetVirtualProcessorState I/O control interface - for logging. */
183static NEMWINIOCTL g_IoCtlGetVirtualProcessorState;
184/* Info about the VidSetVirtualProcessorState I/O control interface - for logging. */
185static NEMWINIOCTL g_IoCtlSetVirtualProcessorState;
186/** Pointer to what nemR3WinIoctlDetector_ForLogging should fill in. */
187static NEMWINIOCTL *g_pIoCtlDetectForLogging;
188#endif
189
190#ifdef NEM_WIN_INTERCEPT_NT_IO_CTLS
191/** Mapping slot for CPU #0.
192 * @{ */
193static VID_MESSAGE_MAPPING_HEADER *g_pMsgSlotMapping = NULL;
194static const HV_MESSAGE_HEADER *g_pHvMsgHdr;
195static const HV_X64_INTERCEPT_MESSAGE_HEADER *g_pX64MsgHdr;
196/** @} */
197#endif
198
199
200/*
201 * Let the preprocessor alias the APIs to import variables for better autocompletion.
202 */
203#ifndef IN_SLICKEDIT
204# define WHvGetCapability g_pfnWHvGetCapability
205# define WHvCreatePartition g_pfnWHvCreatePartition
206# define WHvSetupPartition g_pfnWHvSetupPartition
207# define WHvDeletePartition g_pfnWHvDeletePartition
208# define WHvGetPartitionProperty g_pfnWHvGetPartitionProperty
209# define WHvSetPartitionProperty g_pfnWHvSetPartitionProperty
210# define WHvMapGpaRange g_pfnWHvMapGpaRange
211# define WHvUnmapGpaRange g_pfnWHvUnmapGpaRange
212# define WHvTranslateGva g_pfnWHvTranslateGva
213# define WHvCreateVirtualProcessor g_pfnWHvCreateVirtualProcessor
214# define WHvDeleteVirtualProcessor g_pfnWHvDeleteVirtualProcessor
215# define WHvRunVirtualProcessor g_pfnWHvRunVirtualProcessor
216# define WHvGetRunExitContextSize g_pfnWHvGetRunExitContextSize
217# define WHvCancelRunVirtualProcessor g_pfnWHvCancelRunVirtualProcessor
218# define WHvGetVirtualProcessorRegisters g_pfnWHvGetVirtualProcessorRegisters
219# define WHvSetVirtualProcessorRegisters g_pfnWHvSetVirtualProcessorRegisters
220
221# define VidMessageSlotHandleAndGetNext g_pfnVidMessageSlotHandleAndGetNext
222# define VidStartVirtualProcessor g_pfnVidStartVirtualProcessor
223# define VidStopVirtualProcessor g_pfnVidStopVirtualProcessor
224
225#endif
226
227/** WHV_MEMORY_ACCESS_TYPE names */
228static const char * const g_apszWHvMemAccesstypes[4] = { "read", "write", "exec", "!undefined!" };
229
230
231/*********************************************************************************************************************************
232* Internal Functions *
233*********************************************************************************************************************************/
234
235/*
236 * Instantate the code we share with ring-0.
237 */
238#ifdef NEM_WIN_USE_OUR_OWN_RUN_API
239# define NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
240#else
241# undef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
242#endif
243#include "../VMMAll/NEMAllNativeTemplate-win.cpp.h"
244
245
246
247#ifdef NEM_WIN_INTERCEPT_NT_IO_CTLS
248/**
249 * Wrapper that logs the call from VID.DLL.
250 *
251 * This is very handy for figuring out why an API call fails.
252 */
253static NTSTATUS WINAPI
254nemR3WinLogWrapper_NtDeviceIoControlFile(HANDLE hFile, HANDLE hEvt, PIO_APC_ROUTINE pfnApcCallback, PVOID pvApcCtx,
255 PIO_STATUS_BLOCK pIos, ULONG uFunction, PVOID pvInput, ULONG cbInput,
256 PVOID pvOutput, ULONG cbOutput)
257{
258
259 char szFunction[32];
260 const char *pszFunction;
261 if (uFunction == g_IoCtlMessageSlotHandleAndGetNext.uFunction)
262 pszFunction = "VidMessageSlotHandleAndGetNext";
263 else if (uFunction == g_IoCtlStartVirtualProcessor.uFunction)
264 pszFunction = "VidStartVirtualProcessor";
265 else if (uFunction == g_IoCtlStopVirtualProcessor.uFunction)
266 pszFunction = "VidStopVirtualProcessor";
267 else if (uFunction == g_IoCtlMessageSlotMap.uFunction)
268 pszFunction = "VidMessageSlotMap";
269 else if (uFunction == g_IoCtlGetVirtualProcessorState.uFunction)
270 pszFunction = "VidGetVirtualProcessorState";
271 else if (uFunction == g_IoCtlSetVirtualProcessorState.uFunction)
272 pszFunction = "VidSetVirtualProcessorState";
273 else
274 {
275 RTStrPrintf(szFunction, sizeof(szFunction), "%#x", uFunction);
276 pszFunction = szFunction;
277 }
278
279 if (cbInput > 0 && pvInput)
280 Log12(("VID!NtDeviceIoControlFile: %s/input: %.*Rhxs\n", pszFunction, RT_MIN(cbInput, 32), pvInput));
281 NTSTATUS rcNt = g_pfnNtDeviceIoControlFile(hFile, hEvt, pfnApcCallback, pvApcCtx, pIos, uFunction,
282 pvInput, cbInput, pvOutput, cbOutput);
283 if (!hEvt && !pfnApcCallback && !pvApcCtx)
284 Log12(("VID!NtDeviceIoControlFile: hFile=%#zx pIos=%p->{s:%#x, i:%#zx} uFunction=%s Input=%p LB %#x Output=%p LB %#x) -> %#x; Caller=%p\n",
285 hFile, pIos, pIos->Status, pIos->Information, pszFunction, pvInput, cbInput, pvOutput, cbOutput, rcNt, ASMReturnAddress()));
286 else
287 Log12(("VID!NtDeviceIoControlFile: hFile=%#zx hEvt=%#zx Apc=%p/%p pIos=%p->{s:%#x, i:%#zx} uFunction=%s Input=%p LB %#x Output=%p LB %#x) -> %#x; Caller=%p\n",
288 hFile, hEvt, pfnApcCallback, pvApcCtx, pIos, pIos->Status, pIos->Information, pszFunction,
289 pvInput, cbInput, pvOutput, cbOutput, rcNt, ASMReturnAddress()));
290 if (cbOutput > 0 && pvOutput)
291 {
292 Log12(("VID!NtDeviceIoControlFile: %s/output: %.*Rhxs\n", pszFunction, RT_MIN(cbOutput, 32), pvOutput));
293 if (uFunction == 0x2210cc && g_pMsgSlotMapping == NULL && cbOutput >= sizeof(void *))
294 {
295 g_pMsgSlotMapping = *(VID_MESSAGE_MAPPING_HEADER **)pvOutput;
296 g_pHvMsgHdr = (const HV_MESSAGE_HEADER *)(g_pMsgSlotMapping + 1);
297 g_pX64MsgHdr = (const HV_X64_INTERCEPT_MESSAGE_HEADER *)(g_pHvMsgHdr + 1);
298 Log12(("VID!NtDeviceIoControlFile: Message slot mapping: %p\n", g_pMsgSlotMapping));
299 }
300 }
301 if ( g_pMsgSlotMapping
302 && ( uFunction == g_IoCtlMessageSlotHandleAndGetNext.uFunction
303 || uFunction == g_IoCtlStopVirtualProcessor.uFunction
304 || uFunction == g_IoCtlMessageSlotMap.uFunction
305 ))
306 Log12(("VID!NtDeviceIoControlFile: enmVidMsgType=%#x cb=%#x msg=%#x payload=%u cs:rip=%04x:%08RX64 (%s)\n",
307 g_pMsgSlotMapping->enmVidMsgType, g_pMsgSlotMapping->cbMessage,
308 g_pHvMsgHdr->MessageType, g_pHvMsgHdr->PayloadSize,
309 g_pX64MsgHdr->CsSegment.Selector, g_pX64MsgHdr->Rip, pszFunction));
310
311 return rcNt;
312}
313#endif /* NEM_WIN_INTERCEPT_NT_IO_CTLS */
314
315
316/**
317 * Patches the call table of VID.DLL so we can intercept NtDeviceIoControlFile.
318 *
319 * This is for used to figure out the I/O control codes and in logging builds
320 * for logging API calls that WinHvPlatform.dll does.
321 *
322 * @returns VBox status code.
323 * @param hLdrModVid The VID module handle.
324 * @param pErrInfo Where to return additional error information.
325 */
326static int nemR3WinInitVidIntercepts(RTLDRMOD hLdrModVid, PRTERRINFO pErrInfo)
327{
328 /*
329 * Locate the real API.
330 */
331 g_pfnNtDeviceIoControlFile = (decltype(NtDeviceIoControlFile) *)RTLdrGetSystemSymbol("NTDLL.DLL", "NtDeviceIoControlFile");
332 AssertReturn(g_pfnNtDeviceIoControlFile != NULL,
333 RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED, "Failed to resolve NtDeviceIoControlFile from NTDLL.DLL"));
334
335 /*
336 * Locate the PE header and get what we need from it.
337 */
338 uint8_t const *pbImage = (uint8_t const *)RTLdrGetNativeHandle(hLdrModVid);
339 IMAGE_DOS_HEADER const *pMzHdr = (IMAGE_DOS_HEADER const *)pbImage;
340 AssertReturn(pMzHdr->e_magic == IMAGE_DOS_SIGNATURE,
341 RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED, "VID.DLL mapping doesn't start with MZ signature: %#x", pMzHdr->e_magic));
342 IMAGE_NT_HEADERS const *pNtHdrs = (IMAGE_NT_HEADERS const *)&pbImage[pMzHdr->e_lfanew];
343 AssertReturn(pNtHdrs->Signature == IMAGE_NT_SIGNATURE,
344 RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED, "VID.DLL has invalid PE signaturre: %#x @%#x",
345 pNtHdrs->Signature, pMzHdr->e_lfanew));
346
347 uint32_t const cbImage = pNtHdrs->OptionalHeader.SizeOfImage;
348 IMAGE_DATA_DIRECTORY const ImportDir = pNtHdrs->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
349
350 /*
351 * Walk the import descriptor table looking for NTDLL.DLL.
352 */
353 AssertReturn( ImportDir.Size > 0
354 && ImportDir.Size < cbImage,
355 RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED, "VID.DLL bad import directory size: %#x", ImportDir.Size));
356 AssertReturn( ImportDir.VirtualAddress > 0
357 && ImportDir.VirtualAddress <= cbImage - ImportDir.Size,
358 RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED, "VID.DLL bad import directory RVA: %#x", ImportDir.VirtualAddress));
359
360 for (PIMAGE_IMPORT_DESCRIPTOR pImps = (PIMAGE_IMPORT_DESCRIPTOR)&pbImage[ImportDir.VirtualAddress];
361 pImps->Name != 0 && pImps->FirstThunk != 0;
362 pImps++)
363 {
364 AssertReturn(pImps->Name < cbImage,
365 RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED, "VID.DLL bad import directory entry name: %#x", pImps->Name));
366 const char *pszModName = (const char *)&pbImage[pImps->Name];
367 if (RTStrICmpAscii(pszModName, "ntdll.dll"))
368 continue;
369 AssertReturn(pImps->FirstThunk < cbImage,
370 RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED, "VID.DLL bad FirstThunk: %#x", pImps->FirstThunk));
371 AssertReturn(pImps->OriginalFirstThunk < cbImage,
372 RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED, "VID.DLL bad FirstThunk: %#x", pImps->FirstThunk));
373
374 /*
375 * Walk the thunks table(s) looking for NtDeviceIoControlFile.
376 */
377 PIMAGE_THUNK_DATA pFirstThunk = (PIMAGE_THUNK_DATA)&pbImage[pImps->FirstThunk]; /* update this. */
378 PIMAGE_THUNK_DATA pThunk = pImps->OriginalFirstThunk == 0 /* read from this. */
379 ? (PIMAGE_THUNK_DATA)&pbImage[pImps->FirstThunk]
380 : (PIMAGE_THUNK_DATA)&pbImage[pImps->OriginalFirstThunk];
381 while (pThunk->u1.Ordinal != 0)
382 {
383 if (!(pThunk->u1.Ordinal & IMAGE_ORDINAL_FLAG32))
384 {
385 AssertReturn(pThunk->u1.Ordinal > 0 && pThunk->u1.Ordinal < cbImage,
386 RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED, "VID.DLL bad FirstThunk: %#x", pImps->FirstThunk));
387
388 const char *pszSymbol = (const char *)&pbImage[(uintptr_t)pThunk->u1.AddressOfData + 2];
389 if (strcmp(pszSymbol, "NtDeviceIoControlFile") == 0)
390 {
391 DWORD fOldProt = PAGE_READONLY;
392 VirtualProtect(&pFirstThunk->u1.Function, sizeof(uintptr_t), PAGE_EXECUTE_READWRITE, &fOldProt);
393 g_ppfnVidNtDeviceIoControlFile = (decltype(NtDeviceIoControlFile) **)&pFirstThunk->u1.Function;
394 /* Don't restore the protection here, so we modify the NtDeviceIoControlFile pointer later. */
395 }
396 }
397
398 pThunk++;
399 pFirstThunk++;
400 }
401 }
402
403 if (*g_ppfnVidNtDeviceIoControlFile)
404 {
405#ifdef NEM_WIN_INTERCEPT_NT_IO_CTLS
406 *g_ppfnVidNtDeviceIoControlFile = nemR3WinLogWrapper_NtDeviceIoControlFile;
407#endif
408 return VINF_SUCCESS;
409 }
410 return RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED, "Failed to patch NtDeviceIoControlFile import in VID.DLL!");
411}
412
413
414/**
415 * Worker for nemR3NativeInit that probes and load the native API.
416 *
417 * @returns VBox status code.
418 * @param fForced Whether the HMForced flag is set and we should
419 * fail if we cannot initialize.
420 * @param pErrInfo Where to always return error info.
421 */
422static int nemR3WinInitProbeAndLoad(bool fForced, PRTERRINFO pErrInfo)
423{
424 /*
425 * Check that the DLL files we need are present, but without loading them.
426 * We'd like to avoid loading them unnecessarily.
427 */
428 WCHAR wszPath[MAX_PATH + 64];
429 UINT cwcPath = GetSystemDirectoryW(wszPath, MAX_PATH);
430 if (cwcPath >= MAX_PATH || cwcPath < 2)
431 return RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED, "GetSystemDirectoryW failed (%#x / %u)", cwcPath, GetLastError());
432
433 if (wszPath[cwcPath - 1] != '\\' || wszPath[cwcPath - 1] != '/')
434 wszPath[cwcPath++] = '\\';
435 RTUtf16CopyAscii(&wszPath[cwcPath], RT_ELEMENTS(wszPath) - cwcPath, "WinHvPlatform.dll");
436 if (GetFileAttributesW(wszPath) == INVALID_FILE_ATTRIBUTES)
437 return RTErrInfoSetF(pErrInfo, VERR_NEM_NOT_AVAILABLE, "The native API dll was not found (%ls)", wszPath);
438
439 /*
440 * Check that we're in a VM and that the hypervisor identifies itself as Hyper-V.
441 */
442 if (!ASMHasCpuId())
443 return RTErrInfoSet(pErrInfo, VERR_NEM_NOT_AVAILABLE, "No CPUID support");
444 if (!ASMIsValidStdRange(ASMCpuId_EAX(0)))
445 return RTErrInfoSet(pErrInfo, VERR_NEM_NOT_AVAILABLE, "No CPUID leaf #1");
446 if (!(ASMCpuId_ECX(1) & X86_CPUID_FEATURE_ECX_HVP))
447 return RTErrInfoSet(pErrInfo, VERR_NEM_NOT_AVAILABLE, "Not in a hypervisor partition (HVP=0)");
448
449 uint32_t cMaxHyperLeaf = 0;
450 uint32_t uEbx = 0;
451 uint32_t uEcx = 0;
452 uint32_t uEdx = 0;
453 ASMCpuIdExSlow(0x40000000, 0, 0, 0, &cMaxHyperLeaf, &uEbx, &uEcx, &uEdx);
454 if (!ASMIsValidHypervisorRange(cMaxHyperLeaf))
455 return RTErrInfoSetF(pErrInfo, VERR_NEM_NOT_AVAILABLE, "Invalid hypervisor CPUID range (%#x %#x %#x %#x)",
456 cMaxHyperLeaf, uEbx, uEcx, uEdx);
457 if ( uEbx != UINT32_C(0x7263694d) /* Micr */
458 || uEcx != UINT32_C(0x666f736f) /* osof */
459 || uEdx != UINT32_C(0x76482074) /* t Hv */)
460 return RTErrInfoSetF(pErrInfo, VERR_NEM_NOT_AVAILABLE,
461 "Not Hyper-V CPUID signature: %#x %#x %#x (expected %#x %#x %#x)",
462 uEbx, uEcx, uEdx, UINT32_C(0x7263694d), UINT32_C(0x666f736f), UINT32_C(0x76482074));
463 if (cMaxHyperLeaf < UINT32_C(0x40000005))
464 return RTErrInfoSetF(pErrInfo, VERR_NEM_NOT_AVAILABLE, "Too narrow hypervisor CPUID range (%#x)", cMaxHyperLeaf);
465
466 /** @todo would be great if we could recognize a root partition from the
467 * CPUID info, but I currently don't dare do that. */
468
469 /*
470 * Now try load the DLLs and resolve the APIs.
471 */
472 static const char * const s_apszDllNames[2] = { "WinHvPlatform.dll", "vid.dll" };
473 RTLDRMOD ahMods[2] = { NIL_RTLDRMOD, NIL_RTLDRMOD };
474 int rc = VINF_SUCCESS;
475 for (unsigned i = 0; i < RT_ELEMENTS(s_apszDllNames); i++)
476 {
477 int rc2 = RTLdrLoadSystem(s_apszDllNames[i], true /*fNoUnload*/, &ahMods[i]);
478 if (RT_FAILURE(rc2))
479 {
480 if (!RTErrInfoIsSet(pErrInfo))
481 RTErrInfoSetF(pErrInfo, rc2, "Failed to load API DLL: %s: %Rrc", s_apszDllNames[i], rc2);
482 else
483 RTErrInfoAddF(pErrInfo, rc2, "; %s: %Rrc", s_apszDllNames[i], rc2);
484 ahMods[i] = NIL_RTLDRMOD;
485 rc = VERR_NEM_INIT_FAILED;
486 }
487 }
488 if (RT_SUCCESS(rc))
489 rc = nemR3WinInitVidIntercepts(ahMods[1], pErrInfo);
490 if (RT_SUCCESS(rc))
491 {
492 for (unsigned i = 0; i < RT_ELEMENTS(g_aImports); i++)
493 {
494 int rc2 = RTLdrGetSymbol(ahMods[g_aImports[i].idxDll], g_aImports[i].pszName, (void **)g_aImports[i].ppfn);
495 if (RT_FAILURE(rc2))
496 {
497 *g_aImports[i].ppfn = NULL;
498
499 LogRel(("NEM: %s: Failed to import %s!%s: %Rrc",
500 g_aImports[i].fOptional ? "info" : fForced ? "fatal" : "error",
501 s_apszDllNames[g_aImports[i].idxDll], g_aImports[i].pszName, rc2));
502 if (!g_aImports[i].fOptional)
503 {
504 if (RTErrInfoIsSet(pErrInfo))
505 RTErrInfoAddF(pErrInfo, rc2, ", %s!%s",
506 s_apszDllNames[g_aImports[i].idxDll], g_aImports[i].pszName);
507 else
508 rc = RTErrInfoSetF(pErrInfo, rc2, "Failed to import: %s!%s",
509 s_apszDllNames[g_aImports[i].idxDll], g_aImports[i].pszName);
510 Assert(RT_FAILURE(rc));
511 }
512 }
513 }
514 if (RT_SUCCESS(rc))
515 {
516 Assert(!RTErrInfoIsSet(pErrInfo));
517 }
518 }
519
520 for (unsigned i = 0; i < RT_ELEMENTS(ahMods); i++)
521 RTLdrClose(ahMods[i]);
522 return rc;
523}
524
525
526/**
527 * Wrapper for different WHvGetCapability signatures.
528 */
529DECLINLINE(HRESULT) WHvGetCapabilityWrapper(WHV_CAPABILITY_CODE enmCap, WHV_CAPABILITY *pOutput, uint32_t cbOutput)
530{
531 return g_pfnWHvGetCapability(enmCap, pOutput, cbOutput, NULL);
532}
533
534
535/**
536 * Worker for nemR3NativeInit that gets the hypervisor capabilities.
537 *
538 * @returns VBox status code.
539 * @param pVM The cross context VM structure.
540 * @param pErrInfo Where to always return error info.
541 */
542static int nemR3WinInitCheckCapabilities(PVM pVM, PRTERRINFO pErrInfo)
543{
544#define NEM_LOG_REL_CAP_EX(a_szField, a_szFmt, a_Value) LogRel(("NEM: %-38s= " a_szFmt "\n", a_szField, a_Value))
545#define NEM_LOG_REL_CAP_SUB_EX(a_szField, a_szFmt, a_Value) LogRel(("NEM: %36s: " a_szFmt "\n", a_szField, a_Value))
546#define NEM_LOG_REL_CAP_SUB(a_szField, a_Value) NEM_LOG_REL_CAP_SUB_EX(a_szField, "%d", a_Value)
547
548 /*
549 * Is the hypervisor present with the desired capability?
550 *
551 * In build 17083 this translates into:
552 * - CPUID[0x00000001].HVP is set
553 * - CPUID[0x40000000] == "Microsoft Hv"
554 * - CPUID[0x40000001].eax == "Hv#1"
555 * - CPUID[0x40000003].ebx[12] is set.
556 * - VidGetExoPartitionProperty(INVALID_HANDLE_VALUE, 0x60000, &Ignored) returns
557 * a non-zero value.
558 */
559 /**
560 * @todo Someone at Microsoft please explain weird API design:
561 * 1. Pointless CapabilityCode duplication int the output;
562 * 2. No output size.
563 */
564 WHV_CAPABILITY Caps;
565 RT_ZERO(Caps);
566 SetLastError(0);
567 HRESULT hrc = WHvGetCapabilityWrapper(WHvCapabilityCodeHypervisorPresent, &Caps, sizeof(Caps));
568 DWORD rcWin = GetLastError();
569 if (FAILED(hrc))
570 return RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED,
571 "WHvGetCapability/WHvCapabilityCodeHypervisorPresent failed: %Rhrc (Last=%#x/%u)",
572 hrc, RTNtLastStatusValue(), RTNtLastErrorValue());
573 if (!Caps.HypervisorPresent)
574 {
575 if (!RTPathExists(RTPATH_NT_PASSTHRU_PREFIX "Device\\VidExo"))
576 return RTErrInfoSetF(pErrInfo, VERR_NEM_NOT_AVAILABLE,
577 "WHvCapabilityCodeHypervisorPresent is FALSE! Make sure you have enabled the 'Windows Hypervisor Platform' feature.");
578 return RTErrInfoSetF(pErrInfo, VERR_NEM_NOT_AVAILABLE, "WHvCapabilityCodeHypervisorPresent is FALSE! (%u)", rcWin);
579 }
580 LogRel(("NEM: WHvCapabilityCodeHypervisorPresent is TRUE, so this might work...\n"));
581
582
583 /*
584 * Check what extended VM exits are supported.
585 */
586 RT_ZERO(Caps);
587 hrc = WHvGetCapabilityWrapper(WHvCapabilityCodeExtendedVmExits, &Caps, sizeof(Caps));
588 if (FAILED(hrc))
589 return RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED,
590 "WHvGetCapability/WHvCapabilityCodeExtendedVmExits failed: %Rhrc (Last=%#x/%u)",
591 hrc, RTNtLastStatusValue(), RTNtLastErrorValue());
592 NEM_LOG_REL_CAP_EX("WHvCapabilityCodeExtendedVmExits", "%'#018RX64", Caps.ExtendedVmExits.AsUINT64);
593 pVM->nem.s.fExtendedMsrExit = RT_BOOL(Caps.ExtendedVmExits.X64MsrExit);
594 pVM->nem.s.fExtendedCpuIdExit = RT_BOOL(Caps.ExtendedVmExits.X64CpuidExit);
595 pVM->nem.s.fExtendedXcptExit = RT_BOOL(Caps.ExtendedVmExits.ExceptionExit);
596 NEM_LOG_REL_CAP_SUB("fExtendedMsrExit", pVM->nem.s.fExtendedMsrExit);
597 NEM_LOG_REL_CAP_SUB("fExtendedCpuIdExit", pVM->nem.s.fExtendedCpuIdExit);
598 NEM_LOG_REL_CAP_SUB("fExtendedXcptExit", pVM->nem.s.fExtendedXcptExit);
599 if (Caps.ExtendedVmExits.AsUINT64 & ~(uint64_t)7)
600 LogRel(("NEM: Warning! Unknown VM exit definitions: %#RX64\n", Caps.ExtendedVmExits.AsUINT64));
601 /** @todo RECHECK: WHV_EXTENDED_VM_EXITS typedef. */
602
603 /*
604 * Check features in case they end up defining any.
605 */
606 RT_ZERO(Caps);
607 hrc = WHvGetCapabilityWrapper(WHvCapabilityCodeFeatures, &Caps, sizeof(Caps));
608 if (FAILED(hrc))
609 return RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED,
610 "WHvGetCapability/WHvCapabilityCodeFeatures failed: %Rhrc (Last=%#x/%u)",
611 hrc, RTNtLastStatusValue(), RTNtLastErrorValue());
612 if (Caps.Features.AsUINT64 & ~(uint64_t)0)
613 LogRel(("NEM: Warning! Unknown feature definitions: %#RX64\n", Caps.Features.AsUINT64));
614 /** @todo RECHECK: WHV_CAPABILITY_FEATURES typedef. */
615
616 /*
617 * Check supported exception exit bitmap bits.
618 * We don't currently require this, so we just log failure.
619 */
620 RT_ZERO(Caps);
621 hrc = WHvGetCapabilityWrapper(WHvCapabilityCodeExceptionExitBitmap, &Caps, sizeof(Caps));
622 if (SUCCEEDED(hrc))
623 LogRel(("NEM: Supported exception exit bitmap: %#RX64\n", Caps.ExceptionExitBitmap));
624 else
625 LogRel(("NEM: Warning! WHvGetCapability/WHvCapabilityCodeExceptionExitBitmap failed: %Rhrc (Last=%#x/%u)",
626 hrc, RTNtLastStatusValue(), RTNtLastErrorValue()));
627
628 /*
629 * Check that the CPU vendor is supported.
630 */
631 RT_ZERO(Caps);
632 hrc = WHvGetCapabilityWrapper(WHvCapabilityCodeProcessorVendor, &Caps, sizeof(Caps));
633 if (FAILED(hrc))
634 return RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED,
635 "WHvGetCapability/WHvCapabilityCodeProcessorVendor failed: %Rhrc (Last=%#x/%u)",
636 hrc, RTNtLastStatusValue(), RTNtLastErrorValue());
637 switch (Caps.ProcessorVendor)
638 {
639 /** @todo RECHECK: WHV_PROCESSOR_VENDOR typedef. */
640 case WHvProcessorVendorIntel:
641 NEM_LOG_REL_CAP_EX("WHvCapabilityCodeProcessorVendor", "%d - Intel", Caps.ProcessorVendor);
642 pVM->nem.s.enmCpuVendor = CPUMCPUVENDOR_INTEL;
643 break;
644 case WHvProcessorVendorAmd:
645 NEM_LOG_REL_CAP_EX("WHvCapabilityCodeProcessorVendor", "%d - AMD", Caps.ProcessorVendor);
646 pVM->nem.s.enmCpuVendor = CPUMCPUVENDOR_AMD;
647 break;
648 default:
649 NEM_LOG_REL_CAP_EX("WHvCapabilityCodeProcessorVendor", "%d", Caps.ProcessorVendor);
650 return RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED, "Unknown processor vendor: %d", Caps.ProcessorVendor);
651 }
652
653 /*
654 * CPU features, guessing these are virtual CPU features?
655 */
656 RT_ZERO(Caps);
657 hrc = WHvGetCapabilityWrapper(WHvCapabilityCodeProcessorFeatures, &Caps, sizeof(Caps));
658 if (FAILED(hrc))
659 return RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED,
660 "WHvGetCapability/WHvCapabilityCodeProcessorFeatures failed: %Rhrc (Last=%#x/%u)",
661 hrc, RTNtLastStatusValue(), RTNtLastErrorValue());
662 NEM_LOG_REL_CAP_EX("WHvCapabilityCodeProcessorFeatures", "%'#018RX64", Caps.ProcessorFeatures.AsUINT64);
663#define NEM_LOG_REL_CPU_FEATURE(a_Field) NEM_LOG_REL_CAP_SUB(#a_Field, Caps.ProcessorFeatures.a_Field)
664 NEM_LOG_REL_CPU_FEATURE(Sse3Support);
665 NEM_LOG_REL_CPU_FEATURE(LahfSahfSupport);
666 NEM_LOG_REL_CPU_FEATURE(Ssse3Support);
667 NEM_LOG_REL_CPU_FEATURE(Sse4_1Support);
668 NEM_LOG_REL_CPU_FEATURE(Sse4_2Support);
669 NEM_LOG_REL_CPU_FEATURE(Sse4aSupport);
670 NEM_LOG_REL_CPU_FEATURE(XopSupport);
671 NEM_LOG_REL_CPU_FEATURE(PopCntSupport);
672 NEM_LOG_REL_CPU_FEATURE(Cmpxchg16bSupport);
673 NEM_LOG_REL_CPU_FEATURE(Altmovcr8Support);
674 NEM_LOG_REL_CPU_FEATURE(LzcntSupport);
675 NEM_LOG_REL_CPU_FEATURE(MisAlignSseSupport);
676 NEM_LOG_REL_CPU_FEATURE(MmxExtSupport);
677 NEM_LOG_REL_CPU_FEATURE(Amd3DNowSupport);
678 NEM_LOG_REL_CPU_FEATURE(ExtendedAmd3DNowSupport);
679 NEM_LOG_REL_CPU_FEATURE(Page1GbSupport);
680 NEM_LOG_REL_CPU_FEATURE(AesSupport);
681 NEM_LOG_REL_CPU_FEATURE(PclmulqdqSupport);
682 NEM_LOG_REL_CPU_FEATURE(PcidSupport);
683 NEM_LOG_REL_CPU_FEATURE(Fma4Support);
684 NEM_LOG_REL_CPU_FEATURE(F16CSupport);
685 NEM_LOG_REL_CPU_FEATURE(RdRandSupport);
686 NEM_LOG_REL_CPU_FEATURE(RdWrFsGsSupport);
687 NEM_LOG_REL_CPU_FEATURE(SmepSupport);
688 NEM_LOG_REL_CPU_FEATURE(EnhancedFastStringSupport);
689 NEM_LOG_REL_CPU_FEATURE(Bmi1Support);
690 NEM_LOG_REL_CPU_FEATURE(Bmi2Support);
691 /* two reserved bits here, see below */
692 NEM_LOG_REL_CPU_FEATURE(MovbeSupport);
693 NEM_LOG_REL_CPU_FEATURE(Npiep1Support);
694 NEM_LOG_REL_CPU_FEATURE(DepX87FPUSaveSupport);
695 NEM_LOG_REL_CPU_FEATURE(RdSeedSupport);
696 NEM_LOG_REL_CPU_FEATURE(AdxSupport);
697 NEM_LOG_REL_CPU_FEATURE(IntelPrefetchSupport);
698 NEM_LOG_REL_CPU_FEATURE(SmapSupport);
699 NEM_LOG_REL_CPU_FEATURE(HleSupport);
700 NEM_LOG_REL_CPU_FEATURE(RtmSupport);
701 NEM_LOG_REL_CPU_FEATURE(RdtscpSupport);
702 NEM_LOG_REL_CPU_FEATURE(ClflushoptSupport);
703 NEM_LOG_REL_CPU_FEATURE(ClwbSupport);
704 NEM_LOG_REL_CPU_FEATURE(ShaSupport);
705 NEM_LOG_REL_CPU_FEATURE(X87PointersSavedSupport);
706#undef NEM_LOG_REL_CPU_FEATURE
707 if (Caps.ProcessorFeatures.AsUINT64 & (~(RT_BIT_64(43) - 1) | RT_BIT_64(27) | RT_BIT_64(28)))
708 LogRel(("NEM: Warning! Unknown CPU features: %#RX64\n", Caps.ProcessorFeatures.AsUINT64));
709 pVM->nem.s.uCpuFeatures.u64 = Caps.ProcessorFeatures.AsUINT64;
710 /** @todo RECHECK: WHV_PROCESSOR_FEATURES typedef. */
711
712 /*
713 * The cache line flush size.
714 */
715 RT_ZERO(Caps);
716 hrc = WHvGetCapabilityWrapper(WHvCapabilityCodeProcessorClFlushSize, &Caps, sizeof(Caps));
717 if (FAILED(hrc))
718 return RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED,
719 "WHvGetCapability/WHvCapabilityCodeProcessorClFlushSize failed: %Rhrc (Last=%#x/%u)",
720 hrc, RTNtLastStatusValue(), RTNtLastErrorValue());
721 NEM_LOG_REL_CAP_EX("WHvCapabilityCodeProcessorClFlushSize", "2^%u", Caps.ProcessorClFlushSize);
722 if (Caps.ProcessorClFlushSize < 8 && Caps.ProcessorClFlushSize > 9)
723 return RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED, "Unsupported cache line flush size: %u", Caps.ProcessorClFlushSize);
724 pVM->nem.s.cCacheLineFlushShift = Caps.ProcessorClFlushSize;
725
726 /*
727 * See if they've added more properties that we're not aware of.
728 */
729 /** @todo RECHECK: WHV_CAPABILITY_CODE typedef. */
730 if (!IsDebuggerPresent()) /* Too noisy when in debugger, so skip. */
731 {
732 static const struct
733 {
734 uint32_t iMin, iMax; } s_aUnknowns[] =
735 {
736 { 0x0004, 0x000f },
737 { 0x1003, 0x100f },
738 { 0x2000, 0x200f },
739 { 0x3000, 0x300f },
740 { 0x4000, 0x400f },
741 };
742 for (uint32_t j = 0; j < RT_ELEMENTS(s_aUnknowns); j++)
743 for (uint32_t i = s_aUnknowns[j].iMin; i <= s_aUnknowns[j].iMax; i++)
744 {
745 RT_ZERO(Caps);
746 hrc = WHvGetCapabilityWrapper((WHV_CAPABILITY_CODE)i, &Caps, sizeof(Caps));
747 if (SUCCEEDED(hrc))
748 LogRel(("NEM: Warning! Unknown capability %#x returning: %.*Rhxs\n", i, sizeof(Caps), &Caps));
749 }
750 }
751
752 /*
753 * For proper operation, we require CPUID exits.
754 */
755 if (!pVM->nem.s.fExtendedCpuIdExit)
756 return RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED, "Missing required extended CPUID exit support");
757 if (!pVM->nem.s.fExtendedMsrExit)
758 return RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED, "Missing required extended MSR exit support");
759 if (!pVM->nem.s.fExtendedXcptExit)
760 return RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED, "Missing required extended exception exit support");
761
762#undef NEM_LOG_REL_CAP_EX
763#undef NEM_LOG_REL_CAP_SUB_EX
764#undef NEM_LOG_REL_CAP_SUB
765 return VINF_SUCCESS;
766}
767
768
769/**
770 * Used to fill in g_IoCtlGetHvPartitionId.
771 */
772static NTSTATUS WINAPI
773nemR3WinIoctlDetector_GetHvPartitionId(HANDLE hFile, HANDLE hEvt, PIO_APC_ROUTINE pfnApcCallback, PVOID pvApcCtx,
774 PIO_STATUS_BLOCK pIos, ULONG uFunction, PVOID pvInput, ULONG cbInput,
775 PVOID pvOutput, ULONG cbOutput)
776{
777 AssertLogRelMsgReturn(hFile == NEM_WIN_IOCTL_DETECTOR_FAKE_HANDLE, ("hFile=%p\n", hFile), STATUS_INVALID_PARAMETER_1);
778 RT_NOREF(hEvt); RT_NOREF(pfnApcCallback); RT_NOREF(pvApcCtx);
779 AssertLogRelMsgReturn(RT_VALID_PTR(pIos), ("pIos=%p\n", pIos), STATUS_INVALID_PARAMETER_5);
780 AssertLogRelMsgReturn(cbInput == 0, ("cbInput=%#x\n", cbInput), STATUS_INVALID_PARAMETER_8);
781 RT_NOREF(pvInput);
782
783 AssertLogRelMsgReturn(RT_VALID_PTR(pvOutput), ("pvOutput=%p\n", pvOutput), STATUS_INVALID_PARAMETER_9);
784 AssertLogRelMsgReturn(cbOutput == sizeof(HV_PARTITION_ID), ("cbInput=%#x\n", cbInput), STATUS_INVALID_PARAMETER_10);
785 *(HV_PARTITION_ID *)pvOutput = NEM_WIN_IOCTL_DETECTOR_FAKE_PARTITION_ID;
786
787 g_IoCtlGetHvPartitionId.cbInput = cbInput;
788 g_IoCtlGetHvPartitionId.cbOutput = cbOutput;
789 g_IoCtlGetHvPartitionId.uFunction = uFunction;
790
791 return STATUS_SUCCESS;
792}
793
794
795/**
796 * Used to fill in g_IoCtlStartVirtualProcessor.
797 */
798static NTSTATUS WINAPI
799nemR3WinIoctlDetector_StartVirtualProcessor(HANDLE hFile, HANDLE hEvt, PIO_APC_ROUTINE pfnApcCallback, PVOID pvApcCtx,
800 PIO_STATUS_BLOCK pIos, ULONG uFunction, PVOID pvInput, ULONG cbInput,
801 PVOID pvOutput, ULONG cbOutput)
802{
803 AssertLogRelMsgReturn(hFile == NEM_WIN_IOCTL_DETECTOR_FAKE_HANDLE, ("hFile=%p\n", hFile), STATUS_INVALID_PARAMETER_1);
804 RT_NOREF(hEvt); RT_NOREF(pfnApcCallback); RT_NOREF(pvApcCtx);
805 AssertLogRelMsgReturn(RT_VALID_PTR(pIos), ("pIos=%p\n", pIos), STATUS_INVALID_PARAMETER_5);
806 AssertLogRelMsgReturn(cbInput == sizeof(HV_VP_INDEX), ("cbInput=%#x\n", cbInput), STATUS_INVALID_PARAMETER_8);
807 AssertLogRelMsgReturn(RT_VALID_PTR(pvInput), ("pvInput=%p\n", pvInput), STATUS_INVALID_PARAMETER_9);
808 AssertLogRelMsgReturn(*(HV_VP_INDEX *)pvInput == NEM_WIN_IOCTL_DETECTOR_FAKE_VP_INDEX,
809 ("*piCpu=%u\n", *(HV_VP_INDEX *)pvInput), STATUS_INVALID_PARAMETER_9);
810 AssertLogRelMsgReturn(cbOutput == 0, ("cbInput=%#x\n", cbInput), STATUS_INVALID_PARAMETER_10);
811 RT_NOREF(pvOutput);
812
813 g_IoCtlStartVirtualProcessor.cbInput = cbInput;
814 g_IoCtlStartVirtualProcessor.cbOutput = cbOutput;
815 g_IoCtlStartVirtualProcessor.uFunction = uFunction;
816
817 return STATUS_SUCCESS;
818}
819
820
821/**
822 * Used to fill in g_IoCtlStartVirtualProcessor.
823 */
824static NTSTATUS WINAPI
825nemR3WinIoctlDetector_StopVirtualProcessor(HANDLE hFile, HANDLE hEvt, PIO_APC_ROUTINE pfnApcCallback, PVOID pvApcCtx,
826 PIO_STATUS_BLOCK pIos, ULONG uFunction, PVOID pvInput, ULONG cbInput,
827 PVOID pvOutput, ULONG cbOutput)
828{
829 AssertLogRelMsgReturn(hFile == NEM_WIN_IOCTL_DETECTOR_FAKE_HANDLE, ("hFile=%p\n", hFile), STATUS_INVALID_PARAMETER_1);
830 RT_NOREF(hEvt); RT_NOREF(pfnApcCallback); RT_NOREF(pvApcCtx);
831 AssertLogRelMsgReturn(RT_VALID_PTR(pIos), ("pIos=%p\n", pIos), STATUS_INVALID_PARAMETER_5);
832 AssertLogRelMsgReturn(cbInput == sizeof(HV_VP_INDEX), ("cbInput=%#x\n", cbInput), STATUS_INVALID_PARAMETER_8);
833 AssertLogRelMsgReturn(RT_VALID_PTR(pvInput), ("pvInput=%p\n", pvInput), STATUS_INVALID_PARAMETER_9);
834 AssertLogRelMsgReturn(*(HV_VP_INDEX *)pvInput == NEM_WIN_IOCTL_DETECTOR_FAKE_VP_INDEX,
835 ("*piCpu=%u\n", *(HV_VP_INDEX *)pvInput), STATUS_INVALID_PARAMETER_9);
836 AssertLogRelMsgReturn(cbOutput == 0, ("cbInput=%#x\n", cbInput), STATUS_INVALID_PARAMETER_10);
837 RT_NOREF(pvOutput);
838
839 g_IoCtlStopVirtualProcessor.cbInput = cbInput;
840 g_IoCtlStopVirtualProcessor.cbOutput = cbOutput;
841 g_IoCtlStopVirtualProcessor.uFunction = uFunction;
842
843 return STATUS_SUCCESS;
844}
845
846
847/**
848 * Used to fill in g_IoCtlMessageSlotHandleAndGetNext
849 */
850static NTSTATUS WINAPI
851nemR3WinIoctlDetector_MessageSlotHandleAndGetNext(HANDLE hFile, HANDLE hEvt, PIO_APC_ROUTINE pfnApcCallback, PVOID pvApcCtx,
852 PIO_STATUS_BLOCK pIos, ULONG uFunction, PVOID pvInput, ULONG cbInput,
853 PVOID pvOutput, ULONG cbOutput)
854{
855 AssertLogRelMsgReturn(hFile == NEM_WIN_IOCTL_DETECTOR_FAKE_HANDLE, ("hFile=%p\n", hFile), STATUS_INVALID_PARAMETER_1);
856 RT_NOREF(hEvt); RT_NOREF(pfnApcCallback); RT_NOREF(pvApcCtx);
857 AssertLogRelMsgReturn(RT_VALID_PTR(pIos), ("pIos=%p\n", pIos), STATUS_INVALID_PARAMETER_5);
858
859 if (g_uBuildNo >= 17758)
860 {
861 /* No timeout since about build 17758, it's now always an infinite wait. So, a somewhat compatible change. */
862 AssertLogRelMsgReturn(cbInput == RT_UOFFSETOF(VID_IOCTL_INPUT_MESSAGE_SLOT_HANDLE_AND_GET_NEXT, cMillies),
863 ("cbInput=%#x\n", cbInput),
864 STATUS_INVALID_PARAMETER_8);
865 AssertLogRelMsgReturn(RT_VALID_PTR(pvInput), ("pvInput=%p\n", pvInput), STATUS_INVALID_PARAMETER_9);
866 PCVID_IOCTL_INPUT_MESSAGE_SLOT_HANDLE_AND_GET_NEXT pVidIn = (PCVID_IOCTL_INPUT_MESSAGE_SLOT_HANDLE_AND_GET_NEXT)pvInput;
867 AssertLogRelMsgReturn( pVidIn->iCpu == NEM_WIN_IOCTL_DETECTOR_FAKE_VP_INDEX
868 && pVidIn->fFlags == VID_MSHAGN_F_HANDLE_MESSAGE,
869 ("iCpu=%u fFlags=%#x cMillies=%#x\n", pVidIn->iCpu, pVidIn->fFlags, pVidIn->cMillies),
870 STATUS_INVALID_PARAMETER_9);
871 AssertLogRelMsgReturn(cbOutput == 0, ("cbInput=%#x\n", cbInput), STATUS_INVALID_PARAMETER_10);
872 }
873 else
874 {
875 AssertLogRelMsgReturn(cbInput == sizeof(VID_IOCTL_INPUT_MESSAGE_SLOT_HANDLE_AND_GET_NEXT), ("cbInput=%#x\n", cbInput),
876 STATUS_INVALID_PARAMETER_8);
877 AssertLogRelMsgReturn(RT_VALID_PTR(pvInput), ("pvInput=%p\n", pvInput), STATUS_INVALID_PARAMETER_9);
878 PCVID_IOCTL_INPUT_MESSAGE_SLOT_HANDLE_AND_GET_NEXT pVidIn = (PCVID_IOCTL_INPUT_MESSAGE_SLOT_HANDLE_AND_GET_NEXT)pvInput;
879 AssertLogRelMsgReturn( pVidIn->iCpu == NEM_WIN_IOCTL_DETECTOR_FAKE_VP_INDEX
880 && pVidIn->fFlags == VID_MSHAGN_F_HANDLE_MESSAGE
881 && pVidIn->cMillies == NEM_WIN_IOCTL_DETECTOR_FAKE_TIMEOUT,
882 ("iCpu=%u fFlags=%#x cMillies=%#x\n", pVidIn->iCpu, pVidIn->fFlags, pVidIn->cMillies),
883 STATUS_INVALID_PARAMETER_9);
884 AssertLogRelMsgReturn(cbOutput == 0, ("cbInput=%#x\n", cbInput), STATUS_INVALID_PARAMETER_10);
885 RT_NOREF(pvOutput);
886 }
887
888 g_IoCtlMessageSlotHandleAndGetNext.cbInput = cbInput;
889 g_IoCtlMessageSlotHandleAndGetNext.cbOutput = cbOutput;
890 g_IoCtlMessageSlotHandleAndGetNext.uFunction = uFunction;
891
892 return STATUS_SUCCESS;
893}
894
895
896#ifdef LOG_ENABLED
897/**
898 * Used to fill in what g_pIoCtlDetectForLogging points to.
899 */
900static NTSTATUS WINAPI nemR3WinIoctlDetector_ForLogging(HANDLE hFile, HANDLE hEvt, PIO_APC_ROUTINE pfnApcCallback, PVOID pvApcCtx,
901 PIO_STATUS_BLOCK pIos, ULONG uFunction, PVOID pvInput, ULONG cbInput,
902 PVOID pvOutput, ULONG cbOutput)
903{
904 RT_NOREF(hFile, hEvt, pfnApcCallback, pvApcCtx, pIos, pvInput, pvOutput);
905
906 g_pIoCtlDetectForLogging->cbInput = cbInput;
907 g_pIoCtlDetectForLogging->cbOutput = cbOutput;
908 g_pIoCtlDetectForLogging->uFunction = uFunction;
909
910 return STATUS_SUCCESS;
911}
912#endif
913
914
915/**
916 * Worker for nemR3NativeInit that detect I/O control function numbers for VID.
917 *
918 * We use the function numbers directly in ring-0 and to name functions when
919 * logging NtDeviceIoControlFile calls.
920 *
921 * @note We could alternatively do this by disassembling the respective
922 * functions, but hooking NtDeviceIoControlFile and making fake calls
923 * more easily provides the desired information.
924 *
925 * @returns VBox status code.
926 * @param pVM The cross context VM structure. Will set I/O
927 * control info members.
928 * @param pErrInfo Where to always return error info.
929 */
930static int nemR3WinInitDiscoverIoControlProperties(PVM pVM, PRTERRINFO pErrInfo)
931{
932 /*
933 * Probe the I/O control information for select VID APIs so we can use
934 * them directly from ring-0 and better log them.
935 *
936 */
937 decltype(NtDeviceIoControlFile) * const pfnOrg = *g_ppfnVidNtDeviceIoControlFile;
938
939 /* VidGetHvPartitionId - must work due to memory. */
940 *g_ppfnVidNtDeviceIoControlFile = nemR3WinIoctlDetector_GetHvPartitionId;
941 HV_PARTITION_ID idHvPartition = HV_PARTITION_ID_INVALID;
942 BOOL fRet = g_pfnVidGetHvPartitionId(NEM_WIN_IOCTL_DETECTOR_FAKE_HANDLE, &idHvPartition);
943 *g_ppfnVidNtDeviceIoControlFile = pfnOrg;
944 AssertReturn(fRet && idHvPartition == NEM_WIN_IOCTL_DETECTOR_FAKE_PARTITION_ID && g_IoCtlGetHvPartitionId.uFunction != 0,
945 RTErrInfoSetF(pErrInfo, VERR_NEM_INIT_FAILED,
946 "Problem figuring out VidGetHvPartitionId: fRet=%u idHvPartition=%#x dwErr=%u",
947 fRet, idHvPartition, GetLastError()) );
948 LogRel(("NEM: VidGetHvPartitionId -> fun:%#x in:%#x out:%#x\n",
949 g_IoCtlGetHvPartitionId.uFunction, g_IoCtlGetHvPartitionId.cbInput, g_IoCtlGetHvPartitionId.cbOutput));
950
951 int rcRet = VINF_SUCCESS;
952 /* VidStartVirtualProcessor */
953 *g_ppfnVidNtDeviceIoControlFile = nemR3WinIoctlDetector_StartVirtualProcessor;
954 fRet = g_pfnVidStartVirtualProcessor(NEM_WIN_IOCTL_DETECTOR_FAKE_HANDLE, NEM_WIN_IOCTL_DETECTOR_FAKE_VP_INDEX);
955 *g_ppfnVidNtDeviceIoControlFile = pfnOrg;
956 AssertStmt(fRet && g_IoCtlStartVirtualProcessor.uFunction != 0,
957 rcRet = RTERRINFO_LOG_REL_SET_F(pErrInfo, VERR_NEM_RING3_ONLY,
958 "Problem figuring out VidStartVirtualProcessor: fRet=%u dwErr=%u",
959 fRet, GetLastError()) );
960 LogRel(("NEM: VidStartVirtualProcessor -> fun:%#x in:%#x out:%#x\n", g_IoCtlStartVirtualProcessor.uFunction,
961 g_IoCtlStartVirtualProcessor.cbInput, g_IoCtlStartVirtualProcessor.cbOutput));
962
963 /* VidStopVirtualProcessor */
964 *g_ppfnVidNtDeviceIoControlFile = nemR3WinIoctlDetector_StopVirtualProcessor;
965 fRet = g_pfnVidStopVirtualProcessor(NEM_WIN_IOCTL_DETECTOR_FAKE_HANDLE, NEM_WIN_IOCTL_DETECTOR_FAKE_VP_INDEX);
966 *g_ppfnVidNtDeviceIoControlFile = pfnOrg;
967 AssertStmt(fRet && g_IoCtlStopVirtualProcessor.uFunction != 0,
968 rcRet = RTERRINFO_LOG_REL_SET_F(pErrInfo, VERR_NEM_RING3_ONLY,
969 "Problem figuring out VidStopVirtualProcessor: fRet=%u dwErr=%u",
970 fRet, GetLastError()) );
971 LogRel(("NEM: VidStopVirtualProcessor -> fun:%#x in:%#x out:%#x\n", g_IoCtlStopVirtualProcessor.uFunction,
972 g_IoCtlStopVirtualProcessor.cbInput, g_IoCtlStopVirtualProcessor.cbOutput));
973
974 /* VidMessageSlotHandleAndGetNext */
975 *g_ppfnVidNtDeviceIoControlFile = nemR3WinIoctlDetector_MessageSlotHandleAndGetNext;
976 fRet = g_pfnVidMessageSlotHandleAndGetNext(NEM_WIN_IOCTL_DETECTOR_FAKE_HANDLE,
977 NEM_WIN_IOCTL_DETECTOR_FAKE_VP_INDEX, VID_MSHAGN_F_HANDLE_MESSAGE,
978 NEM_WIN_IOCTL_DETECTOR_FAKE_TIMEOUT);
979 *g_ppfnVidNtDeviceIoControlFile = pfnOrg;
980 AssertStmt(fRet && g_IoCtlMessageSlotHandleAndGetNext.uFunction != 0,
981 rcRet = RTERRINFO_LOG_REL_SET_F(pErrInfo, VERR_NEM_RING3_ONLY,
982 "Problem figuring out VidMessageSlotHandleAndGetNext: fRet=%u dwErr=%u",
983 fRet, GetLastError()) );
984 LogRel(("NEM: VidMessageSlotHandleAndGetNext -> fun:%#x in:%#x out:%#x\n",
985 g_IoCtlMessageSlotHandleAndGetNext.uFunction, g_IoCtlMessageSlotHandleAndGetNext.cbInput,
986 g_IoCtlMessageSlotHandleAndGetNext.cbOutput));
987
988#ifdef LOG_ENABLED
989 /* The following are only for logging: */
990 union
991 {
992 VID_MAPPED_MESSAGE_SLOT MapSlot;
993 HV_REGISTER_NAME Name;
994 HV_REGISTER_VALUE Value;
995 } uBuf;
996
997 /* VidMessageSlotMap */
998 g_pIoCtlDetectForLogging = &g_IoCtlMessageSlotMap;
999 *g_ppfnVidNtDeviceIoControlFile = nemR3WinIoctlDetector_ForLogging;
1000 fRet = g_pfnVidMessageSlotMap(NEM_WIN_IOCTL_DETECTOR_FAKE_HANDLE, &uBuf.MapSlot, NEM_WIN_IOCTL_DETECTOR_FAKE_VP_INDEX);
1001 *g_ppfnVidNtDeviceIoControlFile = pfnOrg;
1002 Assert(fRet);
1003 LogRel(("NEM: VidMessageSlotMap -> fun:%#x in:%#x out:%#x\n", g_pIoCtlDetectForLogging->uFunction,
1004 g_pIoCtlDetectForLogging->cbInput, g_pIoCtlDetectForLogging->cbOutput));
1005
1006 /* VidGetVirtualProcessorState */
1007 uBuf.Name = HvRegisterExplicitSuspend;
1008 g_pIoCtlDetectForLogging = &g_IoCtlGetVirtualProcessorState;
1009 *g_ppfnVidNtDeviceIoControlFile = nemR3WinIoctlDetector_ForLogging;
1010 fRet = g_pfnVidGetVirtualProcessorState(NEM_WIN_IOCTL_DETECTOR_FAKE_HANDLE, NEM_WIN_IOCTL_DETECTOR_FAKE_VP_INDEX,
1011 &uBuf.Name, 1, &uBuf.Value);
1012 *g_ppfnVidNtDeviceIoControlFile = pfnOrg;
1013 Assert(fRet);
1014 LogRel(("NEM: VidGetVirtualProcessorState -> fun:%#x in:%#x out:%#x\n", g_pIoCtlDetectForLogging->uFunction,
1015 g_pIoCtlDetectForLogging->cbInput, g_pIoCtlDetectForLogging->cbOutput));
1016
1017 /* VidSetVirtualProcessorState */
1018 uBuf.Name = HvRegisterExplicitSuspend;
1019 g_pIoCtlDetectForLogging = &g_IoCtlSetVirtualProcessorState;
1020 *g_ppfnVidNtDeviceIoControlFile = nemR3WinIoctlDetector_ForLogging;
1021 fRet = g_pfnVidSetVirtualProcessorState(NEM_WIN_IOCTL_DETECTOR_FAKE_HANDLE, NEM_WIN_IOCTL_DETECTOR_FAKE_VP_INDEX,
1022 &uBuf.Name, 1, &uBuf.Value);
1023 *g_ppfnVidNtDeviceIoControlFile = pfnOrg;
1024 Assert(fRet);
1025 LogRel(("NEM: VidSetVirtualProcessorState -> fun:%#x in:%#x out:%#x\n", g_pIoCtlDetectForLogging->uFunction,
1026 g_pIoCtlDetectForLogging->cbInput, g_pIoCtlDetectForLogging->cbOutput));
1027
1028 g_pIoCtlDetectForLogging = NULL;
1029#endif
1030
1031 /* Done. */
1032 pVM->nem.s.IoCtlGetHvPartitionId = g_IoCtlGetHvPartitionId;
1033 pVM->nem.s.IoCtlStartVirtualProcessor = g_IoCtlStartVirtualProcessor;
1034 pVM->nem.s.IoCtlStopVirtualProcessor = g_IoCtlStopVirtualProcessor;
1035 pVM->nem.s.IoCtlMessageSlotHandleAndGetNext = g_IoCtlMessageSlotHandleAndGetNext;
1036 return rcRet;
1037}
1038
1039
1040/**
1041 * Creates and sets up a Hyper-V (exo) partition.
1042 *
1043 * @returns VBox status code.
1044 * @param pVM The cross context VM structure.
1045 * @param pErrInfo Where to always return error info.
1046 */
1047static int nemR3WinInitCreatePartition(PVM pVM, PRTERRINFO pErrInfo)
1048{
1049 AssertReturn(!pVM->nem.s.hPartition, RTErrInfoSet(pErrInfo, VERR_WRONG_ORDER, "Wrong initalization order"));
1050 AssertReturn(!pVM->nem.s.hPartitionDevice, RTErrInfoSet(pErrInfo, VERR_WRONG_ORDER, "Wrong initalization order"));
1051
1052 /*
1053 * Create the partition.
1054 */
1055 WHV_PARTITION_HANDLE hPartition;
1056 HRESULT hrc = WHvCreatePartition(&hPartition);
1057 if (FAILED(hrc))
1058 return RTErrInfoSetF(pErrInfo, VERR_NEM_VM_CREATE_FAILED, "WHvCreatePartition failed with %Rhrc (Last=%#x/%u)",
1059 hrc, RTNtLastStatusValue(), RTNtLastErrorValue());
1060
1061 int rc;
1062
1063 /*
1064 * Set partition properties, most importantly the CPU count.
1065 */
1066 /**
1067 * @todo Someone at Microsoft please explain another weird API:
1068 * - Why this API doesn't take the WHV_PARTITION_PROPERTY_CODE value as an
1069 * argument rather than as part of the struct. That is so weird if you've
1070 * used any other NT or windows API, including WHvGetCapability().
1071 * - Why use PVOID when WHV_PARTITION_PROPERTY is what's expected. We
1072 * technically only need 9 bytes for setting/getting
1073 * WHVPartitionPropertyCodeProcessorClFlushSize, but the API insists on 16. */
1074 WHV_PARTITION_PROPERTY Property;
1075 RT_ZERO(Property);
1076 Property.ProcessorCount = pVM->cCpus;
1077 hrc = WHvSetPartitionProperty(hPartition, WHvPartitionPropertyCodeProcessorCount, &Property, sizeof(Property));
1078 if (SUCCEEDED(hrc))
1079 {
1080 RT_ZERO(Property);
1081 Property.ExtendedVmExits.X64CpuidExit = pVM->nem.s.fExtendedCpuIdExit; /** @todo Register fixed results and restrict cpuid exits */
1082 Property.ExtendedVmExits.X64MsrExit = pVM->nem.s.fExtendedMsrExit;
1083 Property.ExtendedVmExits.ExceptionExit = pVM->nem.s.fExtendedXcptExit;
1084 hrc = WHvSetPartitionProperty(hPartition, WHvPartitionPropertyCodeExtendedVmExits, &Property, sizeof(Property));
1085 if (SUCCEEDED(hrc))
1086 {
1087 /*
1088 * We'll continue setup in nemR3NativeInitAfterCPUM.
1089 */
1090 pVM->nem.s.fCreatedEmts = false;
1091 pVM->nem.s.hPartition = hPartition;
1092 LogRel(("NEM: Created partition %p.\n", hPartition));
1093 return VINF_SUCCESS;
1094 }
1095
1096 rc = RTErrInfoSetF(pErrInfo, VERR_NEM_VM_CREATE_FAILED,
1097 "Failed setting WHvPartitionPropertyCodeExtendedVmExits to %'#RX64: %Rhrc",
1098 Property.ExtendedVmExits.AsUINT64, hrc);
1099 }
1100 else
1101 rc = RTErrInfoSetF(pErrInfo, VERR_NEM_VM_CREATE_FAILED,
1102 "Failed setting WHvPartitionPropertyCodeProcessorCount to %u: %Rhrc (Last=%#x/%u)",
1103 pVM->cCpus, hrc, RTNtLastStatusValue(), RTNtLastErrorValue());
1104 WHvDeletePartition(hPartition);
1105
1106 Assert(!pVM->nem.s.hPartitionDevice);
1107 Assert(!pVM->nem.s.hPartition);
1108 return rc;
1109}
1110
1111
1112/**
1113 * Makes sure APIC and firmware will not allow X2APIC mode.
1114 *
1115 * This is rather ugly.
1116 *
1117 * @returns VBox status code
1118 * @param pVM The cross context VM structure.
1119 */
1120static int nemR3WinDisableX2Apic(PVM pVM)
1121{
1122 /*
1123 * First make sure the 'Mode' config value of the APIC isn't set to X2APIC.
1124 * This defaults to APIC, so no need to change unless it's X2APIC.
1125 */
1126 PCFGMNODE pCfg = CFGMR3GetChild(CFGMR3GetRoot(pVM), "/Devices/apic/0/Config");
1127 if (pCfg)
1128 {
1129 uint8_t bMode = 0;
1130 int rc = CFGMR3QueryU8(pCfg, "Mode", &bMode);
1131 AssertLogRelMsgReturn(RT_SUCCESS(rc) || rc == VERR_CFGM_VALUE_NOT_FOUND, ("%Rrc\n", rc), rc);
1132 if (RT_SUCCESS(rc) && bMode == PDMAPICMODE_X2APIC)
1133 {
1134 LogRel(("NEM: Adjusting APIC configuration from X2APIC to APIC max mode. X2APIC is not supported by the WinHvPlatform API!\n"));
1135 LogRel(("NEM: Disable Hyper-V if you need X2APIC for your guests!\n"));
1136 rc = CFGMR3RemoveValue(pCfg, "Mode");
1137 rc = CFGMR3InsertInteger(pCfg, "Mode", PDMAPICMODE_APIC);
1138 AssertLogRelRCReturn(rc, rc);
1139 }
1140 }
1141
1142 /*
1143 * Now the firmwares.
1144 * These also defaults to APIC and only needs adjusting if configured to X2APIC (2).
1145 */
1146 static const char * const s_apszFirmwareConfigs[] =
1147 {
1148 "/Devices/efi/0/Config",
1149 "/Devices/pcbios/0/Config",
1150 };
1151 for (unsigned i = 0; i < RT_ELEMENTS(s_apszFirmwareConfigs); i++)
1152 {
1153 pCfg = CFGMR3GetChild(CFGMR3GetRoot(pVM), "/Devices/APIC/0/Config");
1154 if (pCfg)
1155 {
1156 uint8_t bMode = 0;
1157 int rc = CFGMR3QueryU8(pCfg, "APIC", &bMode);
1158 AssertLogRelMsgReturn(RT_SUCCESS(rc) || rc == VERR_CFGM_VALUE_NOT_FOUND, ("%Rrc\n", rc), rc);
1159 if (RT_SUCCESS(rc) && bMode == 2)
1160 {
1161 LogRel(("NEM: Adjusting %s/Mode from 2 (X2APIC) to 1 (APIC).\n", s_apszFirmwareConfigs[i]));
1162 rc = CFGMR3RemoveValue(pCfg, "APIC");
1163 rc = CFGMR3InsertInteger(pCfg, "APIC", 1);
1164 AssertLogRelRCReturn(rc, rc);
1165 }
1166 }
1167 }
1168
1169 return VINF_SUCCESS;
1170}
1171
1172
1173/**
1174 * Try initialize the native API.
1175 *
1176 * This may only do part of the job, more can be done in
1177 * nemR3NativeInitAfterCPUM() and nemR3NativeInitCompleted().
1178 *
1179 * @returns VBox status code.
1180 * @param pVM The cross context VM structure.
1181 * @param fFallback Whether we're in fallback mode or use-NEM mode. In
1182 * the latter we'll fail if we cannot initialize.
1183 * @param fForced Whether the HMForced flag is set and we should
1184 * fail if we cannot initialize.
1185 */
1186int nemR3NativeInit(PVM pVM, bool fFallback, bool fForced)
1187{
1188 g_uBuildNo = RTSystemGetNtBuildNo();
1189
1190 /*
1191 * Some state init.
1192 */
1193 pVM->nem.s.fA20Enabled = true;
1194#if 0
1195 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
1196 {
1197 PNEMCPU pNemCpu = &pVM->apCpusR3[idCpu]->nem.s;
1198 }
1199#endif
1200
1201 /*
1202 * Error state.
1203 * The error message will be non-empty on failure and 'rc' will be set too.
1204 */
1205 RTERRINFOSTATIC ErrInfo;
1206 PRTERRINFO pErrInfo = RTErrInfoInitStatic(&ErrInfo);
1207 int rc = nemR3WinInitProbeAndLoad(fForced, pErrInfo);
1208 if (RT_SUCCESS(rc))
1209 {
1210 /*
1211 * Check the capabilties of the hypervisor, starting with whether it's present.
1212 */
1213 rc = nemR3WinInitCheckCapabilities(pVM, pErrInfo);
1214 if (RT_SUCCESS(rc))
1215 {
1216 /*
1217 * Discover the VID I/O control function numbers we need.
1218 */
1219 rc = nemR3WinInitDiscoverIoControlProperties(pVM, pErrInfo);
1220 if (rc == VERR_NEM_RING3_ONLY)
1221 {
1222 if (pVM->nem.s.fUseRing0Runloop)
1223 {
1224 LogRel(("NEM: Disabling UseRing0Runloop.\n"));
1225 pVM->nem.s.fUseRing0Runloop = false;
1226 }
1227 rc = VINF_SUCCESS;
1228 }
1229 if (RT_SUCCESS(rc))
1230 {
1231 /*
1232 * Check out our ring-0 capabilities.
1233 */
1234 rc = SUPR3CallVMMR0Ex(pVM->pVMR0, 0 /*idCpu*/, VMMR0_DO_NEM_INIT_VM, 0, NULL);
1235 if (RT_SUCCESS(rc))
1236 {
1237 /*
1238 * Create and initialize a partition.
1239 */
1240 rc = nemR3WinInitCreatePartition(pVM, pErrInfo);
1241 if (RT_SUCCESS(rc))
1242 {
1243 VM_SET_MAIN_EXECUTION_ENGINE(pVM, VM_EXEC_ENGINE_NATIVE_API);
1244 Log(("NEM: Marked active!\n"));
1245 nemR3WinDisableX2Apic(pVM);
1246
1247 /* Register release statistics */
1248 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
1249 {
1250 PNEMCPU pNemCpu = &pVM->apCpusR3[idCpu]->nem.s;
1251 STAMR3RegisterF(pVM, &pNemCpu->StatExitPortIo, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of port I/O exits", "/NEM/CPU%u/ExitPortIo", idCpu);
1252 STAMR3RegisterF(pVM, &pNemCpu->StatExitMemUnmapped, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of unmapped memory exits", "/NEM/CPU%u/ExitMemUnmapped", idCpu);
1253 STAMR3RegisterF(pVM, &pNemCpu->StatExitMemIntercept, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of intercepted memory exits", "/NEM/CPU%u/ExitMemIntercept", idCpu);
1254 STAMR3RegisterF(pVM, &pNemCpu->StatExitHalt, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of HLT exits", "/NEM/CPU%u/ExitHalt", idCpu);
1255 STAMR3RegisterF(pVM, &pNemCpu->StatExitInterruptWindow, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of HLT exits", "/NEM/CPU%u/ExitInterruptWindow", idCpu);
1256 STAMR3RegisterF(pVM, &pNemCpu->StatExitCpuId, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of CPUID exits", "/NEM/CPU%u/ExitCpuId", idCpu);
1257 STAMR3RegisterF(pVM, &pNemCpu->StatExitMsr, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of MSR access exits", "/NEM/CPU%u/ExitMsr", idCpu);
1258 STAMR3RegisterF(pVM, &pNemCpu->StatExitException, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of exception exits", "/NEM/CPU%u/ExitException", idCpu);
1259 STAMR3RegisterF(pVM, &pNemCpu->StatExitExceptionBp, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of #BP exits", "/NEM/CPU%u/ExitExceptionBp", idCpu);
1260 STAMR3RegisterF(pVM, &pNemCpu->StatExitExceptionDb, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of #DB exits", "/NEM/CPU%u/ExitExceptionDb", idCpu);
1261 STAMR3RegisterF(pVM, &pNemCpu->StatExitExceptionUd, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of #UD exits", "/NEM/CPU%u/ExitExceptionUd", idCpu);
1262 STAMR3RegisterF(pVM, &pNemCpu->StatExitExceptionUdHandled, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of handled #UD exits", "/NEM/CPU%u/ExitExceptionUdHandled", idCpu);
1263 STAMR3RegisterF(pVM, &pNemCpu->StatExitUnrecoverable, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of unrecoverable exits", "/NEM/CPU%u/ExitUnrecoverable", idCpu);
1264 STAMR3RegisterF(pVM, &pNemCpu->StatGetMsgTimeout, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of get message timeouts/alerts", "/NEM/CPU%u/GetMsgTimeout", idCpu);
1265 STAMR3RegisterF(pVM, &pNemCpu->StatStopCpuSuccess, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of successful CPU stops", "/NEM/CPU%u/StopCpuSuccess", idCpu);
1266 STAMR3RegisterF(pVM, &pNemCpu->StatStopCpuPending, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of pending CPU stops", "/NEM/CPU%u/StopCpuPending", idCpu);
1267 STAMR3RegisterF(pVM, &pNemCpu->StatStopCpuPendingAlerts,STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of pending CPU stop alerts", "/NEM/CPU%u/StopCpuPendingAlerts", idCpu);
1268 STAMR3RegisterF(pVM, &pNemCpu->StatStopCpuPendingOdd, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of odd pending CPU stops (see code)", "/NEM/CPU%u/StopCpuPendingOdd", idCpu);
1269 STAMR3RegisterF(pVM, &pNemCpu->StatCancelChangedState, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of cancel changed state", "/NEM/CPU%u/CancelChangedState", idCpu);
1270 STAMR3RegisterF(pVM, &pNemCpu->StatCancelAlertedThread, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of cancel alerted EMT", "/NEM/CPU%u/CancelAlertedEMT", idCpu);
1271 STAMR3RegisterF(pVM, &pNemCpu->StatBreakOnFFPre, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of pre execution FF breaks", "/NEM/CPU%u/BreakOnFFPre", idCpu);
1272 STAMR3RegisterF(pVM, &pNemCpu->StatBreakOnFFPost, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of post execution FF breaks", "/NEM/CPU%u/BreakOnFFPost", idCpu);
1273 STAMR3RegisterF(pVM, &pNemCpu->StatBreakOnCancel, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of cancel execution breaks", "/NEM/CPU%u/BreakOnCancel", idCpu);
1274 STAMR3RegisterF(pVM, &pNemCpu->StatBreakOnStatus, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of status code breaks", "/NEM/CPU%u/BreakOnStatus", idCpu);
1275 STAMR3RegisterF(pVM, &pNemCpu->StatImportOnDemand, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of on-demand state imports", "/NEM/CPU%u/ImportOnDemand", idCpu);
1276 STAMR3RegisterF(pVM, &pNemCpu->StatImportOnReturn, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of state imports on loop return", "/NEM/CPU%u/ImportOnReturn", idCpu);
1277 STAMR3RegisterF(pVM, &pNemCpu->StatImportOnReturnSkipped, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of skipped state imports on loop return", "/NEM/CPU%u/ImportOnReturnSkipped", idCpu);
1278 STAMR3RegisterF(pVM, &pNemCpu->StatQueryCpuTick, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of TSC queries", "/NEM/CPU%u/QueryCpuTick", idCpu);
1279 }
1280
1281 PUVM pUVM = pVM->pUVM;
1282 STAMR3RegisterRefresh(pUVM, &pVM->nem.s.R0Stats.cPagesAvailable, STAMTYPE_U64, STAMVISIBILITY_ALWAYS,
1283 STAMUNIT_PAGES, STAM_REFRESH_GRP_NEM, "Free pages available to the hypervisor",
1284 "/NEM/R0Stats/cPagesAvailable");
1285 STAMR3RegisterRefresh(pUVM, &pVM->nem.s.R0Stats.cPagesInUse, STAMTYPE_U64, STAMVISIBILITY_ALWAYS,
1286 STAMUNIT_PAGES, STAM_REFRESH_GRP_NEM, "Pages in use by hypervisor",
1287 "/NEM/R0Stats/cPagesInUse");
1288 }
1289 }
1290 }
1291 }
1292 }
1293
1294 /*
1295 * We only fail if in forced mode, otherwise just log the complaint and return.
1296 */
1297 Assert(pVM->bMainExecutionEngine == VM_EXEC_ENGINE_NATIVE_API || RTErrInfoIsSet(pErrInfo));
1298 if ( (fForced || !fFallback)
1299 && pVM->bMainExecutionEngine != VM_EXEC_ENGINE_NATIVE_API)
1300 return VMSetError(pVM, RT_SUCCESS_NP(rc) ? VERR_NEM_NOT_AVAILABLE : rc, RT_SRC_POS, "%s", pErrInfo->pszMsg);
1301
1302 if (RTErrInfoIsSet(pErrInfo))
1303 LogRel(("NEM: Not available: %s\n", pErrInfo->pszMsg));
1304 return VINF_SUCCESS;
1305}
1306
1307
1308/**
1309 * This is called after CPUMR3Init is done.
1310 *
1311 * @returns VBox status code.
1312 * @param pVM The VM handle..
1313 */
1314int nemR3NativeInitAfterCPUM(PVM pVM)
1315{
1316 /*
1317 * Validate sanity.
1318 */
1319 WHV_PARTITION_HANDLE hPartition = pVM->nem.s.hPartition;
1320 AssertReturn(hPartition != NULL, VERR_WRONG_ORDER);
1321 AssertReturn(!pVM->nem.s.hPartitionDevice, VERR_WRONG_ORDER);
1322 AssertReturn(!pVM->nem.s.fCreatedEmts, VERR_WRONG_ORDER);
1323 AssertReturn(pVM->bMainExecutionEngine == VM_EXEC_ENGINE_NATIVE_API, VERR_WRONG_ORDER);
1324
1325 /*
1326 * Continue setting up the partition now that we've got most of the CPUID feature stuff.
1327 */
1328 WHV_PARTITION_PROPERTY Property;
1329 HRESULT hrc;
1330
1331#if 0
1332 /* Not sure if we really need to set the vendor.
1333 Update: Apparently we don't. WHvPartitionPropertyCodeProcessorVendor was removed in 17110. */
1334 RT_ZERO(Property);
1335 Property.ProcessorVendor = pVM->nem.s.enmCpuVendor == CPUMCPUVENDOR_AMD ? WHvProcessorVendorAmd
1336 : WHvProcessorVendorIntel;
1337 hrc = WHvSetPartitionProperty(hPartition, WHvPartitionPropertyCodeProcessorVendor, &Property, sizeof(Property));
1338 if (FAILED(hrc))
1339 return VMSetError(pVM, VERR_NEM_VM_CREATE_FAILED, RT_SRC_POS,
1340 "Failed to set WHvPartitionPropertyCodeProcessorVendor to %u: %Rhrc (Last=%#x/%u)",
1341 Property.ProcessorVendor, hrc, RTNtLastStatusValue(), RTNtLastErrorValue());
1342#endif
1343
1344 /* Not sure if we really need to set the cache line flush size. */
1345 RT_ZERO(Property);
1346 Property.ProcessorClFlushSize = pVM->nem.s.cCacheLineFlushShift;
1347 hrc = WHvSetPartitionProperty(hPartition, WHvPartitionPropertyCodeProcessorClFlushSize, &Property, sizeof(Property));
1348 if (FAILED(hrc))
1349 return VMSetError(pVM, VERR_NEM_VM_CREATE_FAILED, RT_SRC_POS,
1350 "Failed to set WHvPartitionPropertyCodeProcessorClFlushSize to %u: %Rhrc (Last=%#x/%u)",
1351 pVM->nem.s.cCacheLineFlushShift, hrc, RTNtLastStatusValue(), RTNtLastErrorValue());
1352
1353 /* Intercept #DB, #BP and #UD exceptions. */
1354 RT_ZERO(Property);
1355 Property.ExceptionExitBitmap = RT_BIT_64(WHvX64ExceptionTypeDebugTrapOrFault)
1356 | RT_BIT_64(WHvX64ExceptionTypeBreakpointTrap)
1357 | RT_BIT_64(WHvX64ExceptionTypeInvalidOpcodeFault);
1358 hrc = WHvSetPartitionProperty(hPartition, WHvPartitionPropertyCodeExceptionExitBitmap, &Property, sizeof(Property));
1359 if (FAILED(hrc))
1360 return VMSetError(pVM, VERR_NEM_VM_CREATE_FAILED, RT_SRC_POS,
1361 "Failed to set WHvPartitionPropertyCodeExceptionExitBitmap to %#RX64: %Rhrc (Last=%#x/%u)",
1362 Property.ExceptionExitBitmap, hrc, RTNtLastStatusValue(), RTNtLastErrorValue());
1363
1364
1365 /*
1366 * Sync CPU features with CPUM.
1367 */
1368 /** @todo sync CPU features with CPUM. */
1369
1370 /* Set the partition property. */
1371 RT_ZERO(Property);
1372 Property.ProcessorFeatures.AsUINT64 = pVM->nem.s.uCpuFeatures.u64;
1373 hrc = WHvSetPartitionProperty(hPartition, WHvPartitionPropertyCodeProcessorFeatures, &Property, sizeof(Property));
1374 if (FAILED(hrc))
1375 return VMSetError(pVM, VERR_NEM_VM_CREATE_FAILED, RT_SRC_POS,
1376 "Failed to set WHvPartitionPropertyCodeProcessorFeatures to %'#RX64: %Rhrc (Last=%#x/%u)",
1377 pVM->nem.s.uCpuFeatures.u64, hrc, RTNtLastStatusValue(), RTNtLastErrorValue());
1378
1379 /*
1380 * Set up the partition and create EMTs.
1381 *
1382 * Seems like this is where the partition is actually instantiated and we get
1383 * a handle to it.
1384 */
1385 hrc = WHvSetupPartition(hPartition);
1386 if (FAILED(hrc))
1387 return VMSetError(pVM, VERR_NEM_VM_CREATE_FAILED, RT_SRC_POS,
1388 "Call to WHvSetupPartition failed: %Rhrc (Last=%#x/%u)",
1389 hrc, RTNtLastStatusValue(), RTNtLastErrorValue());
1390
1391 /* Get the handle. */
1392 HANDLE hPartitionDevice;
1393 __try
1394 {
1395 hPartitionDevice = ((HANDLE *)hPartition)[1];
1396 }
1397 __except(EXCEPTION_EXECUTE_HANDLER)
1398 {
1399 hrc = GetExceptionCode();
1400 hPartitionDevice = NULL;
1401 }
1402 if ( hPartitionDevice == NULL
1403 || hPartitionDevice == (HANDLE)(intptr_t)-1)
1404 return VMSetError(pVM, VERR_NEM_VM_CREATE_FAILED, RT_SRC_POS,
1405 "Failed to get device handle for partition %p: %Rhrc", hPartition, hrc);
1406
1407 HV_PARTITION_ID idHvPartition = HV_PARTITION_ID_INVALID;
1408 if (!g_pfnVidGetHvPartitionId(hPartitionDevice, &idHvPartition))
1409 return VMSetError(pVM, VERR_NEM_VM_CREATE_FAILED, RT_SRC_POS,
1410 "Failed to get device handle and/or partition ID for %p (hPartitionDevice=%p, Last=%#x/%u)",
1411 hPartition, hPartitionDevice, RTNtLastStatusValue(), RTNtLastErrorValue());
1412 pVM->nem.s.hPartitionDevice = hPartitionDevice;
1413 pVM->nem.s.idHvPartition = idHvPartition;
1414
1415 /*
1416 * Setup the EMTs.
1417 */
1418 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
1419 {
1420 PVMCPU pVCpu = pVM->apCpusR3[idCpu];
1421
1422 pVCpu->nem.s.hNativeThreadHandle = (RTR3PTR)RTThreadGetNativeHandle(VMR3GetThreadHandle(pVCpu->pUVCpu));
1423 Assert((HANDLE)pVCpu->nem.s.hNativeThreadHandle != INVALID_HANDLE_VALUE);
1424
1425#ifndef NEM_WIN_USE_OUR_OWN_RUN_API
1426# ifdef NEM_WIN_WITH_RING0_RUNLOOP
1427 if (!pVM->nem.s.fUseRing0Runloop)
1428# endif
1429 {
1430 hrc = WHvCreateVirtualProcessor(hPartition, idCpu, 0 /*fFlags*/);
1431 if (FAILED(hrc))
1432 {
1433 NTSTATUS const rcNtLast = RTNtLastStatusValue();
1434 DWORD const dwErrLast = RTNtLastErrorValue();
1435 while (idCpu-- > 0)
1436 {
1437 HRESULT hrc2 = WHvDeleteVirtualProcessor(hPartition, idCpu);
1438 AssertLogRelMsg(SUCCEEDED(hrc2), ("WHvDeleteVirtualProcessor(%p, %u) -> %Rhrc (Last=%#x/%u)\n",
1439 hPartition, idCpu, hrc2, RTNtLastStatusValue(),
1440 RTNtLastErrorValue()));
1441 }
1442 return VMSetError(pVM, VERR_NEM_VM_CREATE_FAILED, RT_SRC_POS,
1443 "Call to WHvSetupPartition failed: %Rhrc (Last=%#x/%u)", hrc, rcNtLast, dwErrLast);
1444 }
1445 }
1446# ifdef NEM_WIN_WITH_RING0_RUNLOOP
1447 else
1448# endif
1449#endif /* !NEM_WIN_USE_OUR_OWN_RUN_API */
1450#if defined(NEM_WIN_WITH_RING0_RUNLOOP) || defined(NEM_WIN_USE_OUR_OWN_RUN_API)
1451 {
1452 VID_MAPPED_MESSAGE_SLOT MappedMsgSlot = { NULL, UINT32_MAX, UINT32_MAX };
1453 if (g_pfnVidMessageSlotMap(hPartitionDevice, &MappedMsgSlot, idCpu))
1454 {
1455 AssertLogRelMsg(MappedMsgSlot.iCpu == idCpu && MappedMsgSlot.uParentAdvisory == UINT32_MAX,
1456 ("%#x %#x (iCpu=%#x)\n", MappedMsgSlot.iCpu, MappedMsgSlot.uParentAdvisory, idCpu));
1457 pVCpu->nem.s.pvMsgSlotMapping = MappedMsgSlot.pMsgBlock;
1458 }
1459 else
1460 {
1461 NTSTATUS const rcNtLast = RTNtLastStatusValue();
1462 DWORD const dwErrLast = RTNtLastErrorValue();
1463 return VMSetError(pVM, VERR_NEM_VM_CREATE_FAILED, RT_SRC_POS,
1464 "Call to WHvSetupPartition failed: %Rhrc (Last=%#x/%u)", hrc, rcNtLast, dwErrLast);
1465 }
1466 }
1467#endif
1468 }
1469 pVM->nem.s.fCreatedEmts = true;
1470
1471 /*
1472 * Do some more ring-0 initialization now that we've got the partition handle.
1473 */
1474 int rc = VMMR3CallR0Emt(pVM, pVM->apCpusR3[0], VMMR0_DO_NEM_INIT_VM_PART_2, 0, NULL);
1475 if (RT_SUCCESS(rc))
1476 {
1477 LogRel(("NEM: Successfully set up partition (device handle %p, partition ID %#llx)\n", hPartitionDevice, idHvPartition));
1478
1479#if 1
1480 VMMR3CallR0Emt(pVM, pVM->apCpusR3[0], VMMR0_DO_NEM_UPDATE_STATISTICS, 0, NULL);
1481 LogRel(("NEM: Memory balance: %#RX64 out of %#RX64 pages in use\n",
1482 pVM->nem.s.R0Stats.cPagesInUse, pVM->nem.s.R0Stats.cPagesAvailable));
1483#endif
1484
1485 /*
1486 * Register statistics on shared pages.
1487 */
1488 /** @todo HvCallMapStatsPage */
1489
1490 /*
1491 * Adjust features.
1492 * Note! We've already disabled X2APIC via CFGM during the first init call.
1493 */
1494
1495#if 0 && defined(DEBUG_bird)
1496 /*
1497 * Poke and probe a little.
1498 */
1499 PVMCPU pVCpu = pVM->apCpusR3[0];
1500 uint32_t aRegNames[1024];
1501 HV_REGISTER_VALUE aRegValues[1024];
1502 uint32_t aPropCodes[128];
1503 uint64_t aPropValues[128];
1504 for (int iOuter = 0; iOuter < 5; iOuter++)
1505 {
1506 LogRel(("\niOuter %d\n", iOuter));
1507# if 1
1508 /* registers */
1509 uint32_t iRegValue = 0;
1510 uint32_t cRegChanges = 0;
1511 for (uint32_t iReg = 0; iReg < 0x001101ff; iReg++)
1512 {
1513 if (iOuter != 0 && aRegNames[iRegValue] > iReg)
1514 continue;
1515 RT_ZERO(pVCpu->nem.s.Hypercall.Experiment);
1516 pVCpu->nem.s.Hypercall.Experiment.uItem = iReg;
1517 int rc2 = VMMR3CallR0Emt(pVM, pVCpu, VMMR0_DO_NEM_EXPERIMENT, 0, NULL);
1518 AssertLogRelRCBreak(rc2);
1519 if (pVCpu->nem.s.Hypercall.Experiment.fSuccess)
1520 {
1521 LogRel(("Register %#010x = %#18RX64, %#18RX64\n", iReg,
1522 pVCpu->nem.s.Hypercall.Experiment.uLoValue, pVCpu->nem.s.Hypercall.Experiment.uHiValue));
1523 if (iReg == HvX64RegisterTsc)
1524 {
1525 uint64_t uTsc = ASMReadTSC();
1526 LogRel(("TSC = %#18RX64; Delta %#18RX64 or %#18RX64\n",
1527 uTsc, pVCpu->nem.s.Hypercall.Experiment.uLoValue - uTsc, uTsc - pVCpu->nem.s.Hypercall.Experiment.uLoValue));
1528 }
1529
1530 if (iOuter == 0)
1531 aRegNames[iRegValue] = iReg;
1532 else if( aRegValues[iRegValue].Reg128.Low64 != pVCpu->nem.s.Hypercall.Experiment.uLoValue
1533 || aRegValues[iRegValue].Reg128.High64 != pVCpu->nem.s.Hypercall.Experiment.uHiValue)
1534 {
1535 LogRel(("Changed from %#18RX64, %#18RX64 !!\n",
1536 aRegValues[iRegValue].Reg128.Low64, aRegValues[iRegValue].Reg128.High64));
1537 LogRel(("Delta %#18RX64, %#18RX64 !!\n",
1538 pVCpu->nem.s.Hypercall.Experiment.uLoValue - aRegValues[iRegValue].Reg128.Low64,
1539 pVCpu->nem.s.Hypercall.Experiment.uHiValue - aRegValues[iRegValue].Reg128.High64));
1540 cRegChanges++;
1541 }
1542 aRegValues[iRegValue].Reg128.Low64 = pVCpu->nem.s.Hypercall.Experiment.uLoValue;
1543 aRegValues[iRegValue].Reg128.High64 = pVCpu->nem.s.Hypercall.Experiment.uHiValue;
1544 iRegValue++;
1545 AssertBreak(iRegValue < RT_ELEMENTS(aRegValues));
1546 }
1547 }
1548 LogRel(("Found %u registers, %u changed\n", iRegValue, cRegChanges));
1549# endif
1550# if 1
1551 /* partition properties */
1552 uint32_t iPropValue = 0;
1553 uint32_t cPropChanges = 0;
1554 for (uint32_t iProp = 0; iProp < 0xc11ff; iProp++)
1555 {
1556 if (iProp == HvPartitionPropertyDebugChannelId /* hangs host */)
1557 continue;
1558 if (iOuter != 0 && aPropCodes[iPropValue] > iProp)
1559 continue;
1560 RT_ZERO(pVCpu->nem.s.Hypercall.Experiment);
1561 pVCpu->nem.s.Hypercall.Experiment.uItem = iProp;
1562 int rc2 = VMMR3CallR0Emt(pVM, pVCpu, VMMR0_DO_NEM_EXPERIMENT, 1, NULL);
1563 AssertLogRelRCBreak(rc2);
1564 if (pVCpu->nem.s.Hypercall.Experiment.fSuccess)
1565 {
1566 LogRel(("Property %#010x = %#18RX64\n", iProp, pVCpu->nem.s.Hypercall.Experiment.uLoValue));
1567 if (iOuter == 0)
1568 aPropCodes[iPropValue] = iProp;
1569 else if (aPropValues[iPropValue] != pVCpu->nem.s.Hypercall.Experiment.uLoValue)
1570 {
1571 LogRel(("Changed from %#18RX64, delta %#18RX64!!\n",
1572 aPropValues[iPropValue], pVCpu->nem.s.Hypercall.Experiment.uLoValue - aPropValues[iPropValue]));
1573 cRegChanges++;
1574 }
1575 aPropValues[iPropValue] = pVCpu->nem.s.Hypercall.Experiment.uLoValue;
1576 iPropValue++;
1577 AssertBreak(iPropValue < RT_ELEMENTS(aPropValues));
1578 }
1579 }
1580 LogRel(("Found %u properties, %u changed\n", iPropValue, cPropChanges));
1581# endif
1582
1583 /* Modify the TSC register value and see what changes. */
1584 if (iOuter != 0)
1585 {
1586 RT_ZERO(pVCpu->nem.s.Hypercall.Experiment);
1587 pVCpu->nem.s.Hypercall.Experiment.uItem = HvX64RegisterTsc;
1588 pVCpu->nem.s.Hypercall.Experiment.uHiValue = UINT64_C(0x00000fffffffffff) >> iOuter;
1589 pVCpu->nem.s.Hypercall.Experiment.uLoValue = UINT64_C(0x0011100000000000) << iOuter;
1590 VMMR3CallR0Emt(pVM, pVCpu, VMMR0_DO_NEM_EXPERIMENT, 2, NULL);
1591 LogRel(("Setting HvX64RegisterTsc -> %RTbool (%#RX64)\n", pVCpu->nem.s.Hypercall.Experiment.fSuccess, pVCpu->nem.s.Hypercall.Experiment.uStatus));
1592 }
1593
1594 RT_ZERO(pVCpu->nem.s.Hypercall.Experiment);
1595 pVCpu->nem.s.Hypercall.Experiment.uItem = HvX64RegisterTsc;
1596 VMMR3CallR0Emt(pVM, pVCpu, VMMR0_DO_NEM_EXPERIMENT, 0, NULL);
1597 LogRel(("HvX64RegisterTsc = %#RX64, %#RX64\n", pVCpu->nem.s.Hypercall.Experiment.uLoValue, pVCpu->nem.s.Hypercall.Experiment.uHiValue));
1598 }
1599
1600#endif
1601 return VINF_SUCCESS;
1602 }
1603 return VMSetError(pVM, VERR_NEM_VM_CREATE_FAILED, RT_SRC_POS, "Call to NEMR0InitVMPart2 failed: %Rrc", rc);
1604}
1605
1606
1607int nemR3NativeInitCompleted(PVM pVM, VMINITCOMPLETED enmWhat)
1608{
1609 //BOOL fRet = SetThreadPriority(GetCurrentThread(), 0);
1610 //AssertLogRel(fRet);
1611
1612 NOREF(pVM); NOREF(enmWhat);
1613 return VINF_SUCCESS;
1614}
1615
1616
1617int nemR3NativeTerm(PVM pVM)
1618{
1619 /*
1620 * Delete the partition.
1621 */
1622 WHV_PARTITION_HANDLE hPartition = pVM->nem.s.hPartition;
1623 pVM->nem.s.hPartition = NULL;
1624 pVM->nem.s.hPartitionDevice = NULL;
1625 if (hPartition != NULL)
1626 {
1627 VMCPUID idCpu = pVM->nem.s.fCreatedEmts ? pVM->cCpus : 0;
1628 LogRel(("NEM: Destroying partition %p with its %u VCpus...\n", hPartition, idCpu));
1629 while (idCpu-- > 0)
1630 {
1631 PVMCPU pVCpu = pVM->apCpusR3[idCpu];
1632 pVCpu->nem.s.pvMsgSlotMapping = NULL;
1633#ifndef NEM_WIN_USE_OUR_OWN_RUN_API
1634# ifdef NEM_WIN_WITH_RING0_RUNLOOP
1635 if (!pVM->nem.s.fUseRing0Runloop)
1636# endif
1637 {
1638 HRESULT hrc = WHvDeleteVirtualProcessor(hPartition, idCpu);
1639 AssertLogRelMsg(SUCCEEDED(hrc), ("WHvDeleteVirtualProcessor(%p, %u) -> %Rhrc (Last=%#x/%u)\n",
1640 hPartition, idCpu, hrc, RTNtLastStatusValue(),
1641 RTNtLastErrorValue()));
1642 }
1643#endif
1644 }
1645 WHvDeletePartition(hPartition);
1646 }
1647 pVM->nem.s.fCreatedEmts = false;
1648 return VINF_SUCCESS;
1649}
1650
1651
1652/**
1653 * VM reset notification.
1654 *
1655 * @param pVM The cross context VM structure.
1656 */
1657void nemR3NativeReset(PVM pVM)
1658{
1659 /* Unfix the A20 gate. */
1660 pVM->nem.s.fA20Fixed = false;
1661}
1662
1663
1664/**
1665 * Reset CPU due to INIT IPI or hot (un)plugging.
1666 *
1667 * @param pVCpu The cross context virtual CPU structure of the CPU being
1668 * reset.
1669 * @param fInitIpi Whether this is the INIT IPI or hot (un)plugging case.
1670 */
1671void nemR3NativeResetCpu(PVMCPU pVCpu, bool fInitIpi)
1672{
1673 /* Lock the A20 gate if INIT IPI, make sure it's enabled. */
1674 if (fInitIpi && pVCpu->idCpu > 0)
1675 {
1676 PVM pVM = pVCpu->CTX_SUFF(pVM);
1677 if (!pVM->nem.s.fA20Enabled)
1678 nemR3NativeNotifySetA20(pVCpu, true);
1679 pVM->nem.s.fA20Enabled = true;
1680 pVM->nem.s.fA20Fixed = true;
1681 }
1682}
1683
1684
1685VBOXSTRICTRC nemR3NativeRunGC(PVM pVM, PVMCPU pVCpu)
1686{
1687#ifdef NEM_WIN_WITH_RING0_RUNLOOP
1688 if (pVM->nem.s.fUseRing0Runloop)
1689 {
1690 for (;;)
1691 {
1692 VBOXSTRICTRC rcStrict = VMMR3CallR0EmtFast(pVM, pVCpu, VMMR0_DO_NEM_RUN);
1693 if (RT_SUCCESS(rcStrict))
1694 {
1695 /*
1696 * We deal with VINF_NEM_FLUSH_TLB here, since we're running the risk of
1697 * getting these while we already got another RC (I/O ports).
1698 */
1699 /* Status codes: */
1700 VBOXSTRICTRC rcPending = pVCpu->nem.s.rcPending;
1701 pVCpu->nem.s.rcPending = VINF_SUCCESS;
1702 if (rcStrict == VINF_NEM_FLUSH_TLB || rcPending == VINF_NEM_FLUSH_TLB)
1703 {
1704 LogFlow(("nemR3NativeRunGC: calling PGMFlushTLB...\n"));
1705 int rc = PGMFlushTLB(pVCpu, CPUMGetGuestCR3(pVCpu), true);
1706 AssertRCReturn(rc, rc);
1707 if (rcStrict == VINF_NEM_FLUSH_TLB)
1708 {
1709 if ( !VM_FF_IS_ANY_SET(pVM, VM_FF_HIGH_PRIORITY_POST_MASK | VM_FF_HP_R0_PRE_HM_MASK)
1710 && !VMCPU_FF_IS_ANY_SET(pVCpu, (VMCPU_FF_HIGH_PRIORITY_POST_MASK | VMCPU_FF_HP_R0_PRE_HM_MASK)
1711 & ~VMCPU_FF_RESUME_GUEST_MASK))
1712 {
1713 VMCPU_FF_CLEAR_MASK(pVCpu, VMCPU_FF_RESUME_GUEST_MASK);
1714 continue;
1715 }
1716 rcStrict = VINF_SUCCESS;
1717 }
1718 }
1719 else
1720 AssertMsg(rcPending == VINF_SUCCESS, ("rcPending=%Rrc\n", VBOXSTRICTRC_VAL(rcPending) ));
1721 }
1722 LogFlow(("nemR3NativeRunGC: returns %Rrc\n", VBOXSTRICTRC_VAL(rcStrict) ));
1723 return rcStrict;
1724 }
1725 }
1726#endif
1727 return nemHCWinRunGC(pVM, pVCpu, NULL /*pGVM*/, NULL /*pGVCpu*/);
1728}
1729
1730
1731bool nemR3NativeCanExecuteGuest(PVM pVM, PVMCPU pVCpu)
1732{
1733 NOREF(pVM); NOREF(pVCpu);
1734 return true;
1735}
1736
1737
1738bool nemR3NativeSetSingleInstruction(PVM pVM, PVMCPU pVCpu, bool fEnable)
1739{
1740 NOREF(pVM); NOREF(pVCpu); NOREF(fEnable);
1741 return false;
1742}
1743
1744
1745/**
1746 * Forced flag notification call from VMEmt.h.
1747 *
1748 * This is only called when pVCpu is in the VMCPUSTATE_STARTED_EXEC_NEM state.
1749 *
1750 * @param pVM The cross context VM structure.
1751 * @param pVCpu The cross context virtual CPU structure of the CPU
1752 * to be notified.
1753 * @param fFlags Notification flags, VMNOTIFYFF_FLAGS_XXX.
1754 */
1755void nemR3NativeNotifyFF(PVM pVM, PVMCPU pVCpu, uint32_t fFlags)
1756{
1757#ifdef NEM_WIN_USE_OUR_OWN_RUN_API
1758 nemHCWinCancelRunVirtualProcessor(pVM, pVCpu);
1759#else
1760# ifdef NEM_WIN_WITH_RING0_RUNLOOP
1761 if (pVM->nem.s.fUseRing0Runloop)
1762 nemHCWinCancelRunVirtualProcessor(pVM, pVCpu);
1763 else
1764# endif
1765 {
1766 Log8(("nemR3NativeNotifyFF: canceling %u\n", pVCpu->idCpu));
1767 HRESULT hrc = WHvCancelRunVirtualProcessor(pVM->nem.s.hPartition, pVCpu->idCpu, 0);
1768 AssertMsg(SUCCEEDED(hrc), ("WHvCancelRunVirtualProcessor -> hrc=%Rhrc\n", hrc));
1769 RT_NOREF_PV(hrc);
1770 }
1771#endif
1772 RT_NOREF_PV(fFlags);
1773}
1774
1775
1776DECLINLINE(int) nemR3NativeGCPhys2R3PtrReadOnly(PVM pVM, RTGCPHYS GCPhys, const void **ppv)
1777{
1778 PGMPAGEMAPLOCK Lock;
1779 int rc = PGMPhysGCPhys2CCPtrReadOnly(pVM, GCPhys, ppv, &Lock);
1780 if (RT_SUCCESS(rc))
1781 PGMPhysReleasePageMappingLock(pVM, &Lock);
1782 return rc;
1783}
1784
1785
1786DECLINLINE(int) nemR3NativeGCPhys2R3PtrWriteable(PVM pVM, RTGCPHYS GCPhys, void **ppv)
1787{
1788 PGMPAGEMAPLOCK Lock;
1789 int rc = PGMPhysGCPhys2CCPtr(pVM, GCPhys, ppv, &Lock);
1790 if (RT_SUCCESS(rc))
1791 PGMPhysReleasePageMappingLock(pVM, &Lock);
1792 return rc;
1793}
1794
1795
1796int nemR3NativeNotifyPhysRamRegister(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb)
1797{
1798 Log5(("nemR3NativeNotifyPhysRamRegister: %RGp LB %RGp\n", GCPhys, cb));
1799 NOREF(pVM); NOREF(GCPhys); NOREF(cb);
1800 return VINF_SUCCESS;
1801}
1802
1803
1804int nemR3NativeNotifyPhysMmioExMap(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, uint32_t fFlags, void *pvMmio2)
1805{
1806 Log5(("nemR3NativeNotifyPhysMmioExMap: %RGp LB %RGp fFlags=%#x pvMmio2=%p\n", GCPhys, cb, fFlags, pvMmio2));
1807 NOREF(pVM); NOREF(GCPhys); NOREF(cb); NOREF(fFlags); NOREF(pvMmio2);
1808 return VINF_SUCCESS;
1809}
1810
1811
1812int nemR3NativeNotifyPhysMmioExUnmap(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, uint32_t fFlags)
1813{
1814 Log5(("nemR3NativeNotifyPhysMmioExUnmap: %RGp LB %RGp fFlags=%#x\n", GCPhys, cb, fFlags));
1815 NOREF(pVM); NOREF(GCPhys); NOREF(cb); NOREF(fFlags);
1816 return VINF_SUCCESS;
1817}
1818
1819
1820/**
1821 * Called early during ROM registration, right after the pages have been
1822 * allocated and the RAM range updated.
1823 *
1824 * This will be succeeded by a number of NEMHCNotifyPhysPageProtChanged() calls
1825 * and finally a NEMR3NotifyPhysRomRegisterEarly().
1826 *
1827 * @returns VBox status code
1828 * @param pVM The cross context VM structure.
1829 * @param GCPhys The ROM address (page aligned).
1830 * @param cb The size (page aligned).
1831 * @param fFlags NEM_NOTIFY_PHYS_ROM_F_XXX.
1832 */
1833int nemR3NativeNotifyPhysRomRegisterEarly(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, uint32_t fFlags)
1834{
1835 Log5(("nemR3NativeNotifyPhysRomRegisterEarly: %RGp LB %RGp fFlags=%#x\n", GCPhys, cb, fFlags));
1836#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. */
1837 RTGCPHYS const cPages = cb >> X86_PAGE_SHIFT;
1838 for (RTGCPHYS iPage = 0; iPage < cPages; iPage++, GCPhys += X86_PAGE_SIZE)
1839 {
1840 const void *pvPage;
1841 int rc = nemR3NativeGCPhys2R3PtrReadOnly(pVM, GCPhys, &pvPage);
1842 if (RT_SUCCESS(rc))
1843 {
1844 HRESULT hrc = WHvMapGpaRange(pVM->nem.s.hPartition, (void *)pvPage, GCPhys, X86_PAGE_SIZE,
1845 WHvMapGpaRangeFlagRead | WHvMapGpaRangeFlagExecute);
1846 if (SUCCEEDED(hrc))
1847 { /* likely */ }
1848 else
1849 {
1850 LogRel(("nemR3NativeNotifyPhysRomRegisterEarly: GCPhys=%RGp hrc=%Rhrc (%#x) Last=%#x/%u\n",
1851 GCPhys, hrc, hrc, RTNtLastStatusValue(), RTNtLastErrorValue()));
1852 return VERR_NEM_INIT_FAILED;
1853 }
1854 }
1855 else
1856 {
1857 LogRel(("nemR3NativeNotifyPhysRomRegisterEarly: GCPhys=%RGp rc=%Rrc\n", GCPhys, rc));
1858 return rc;
1859 }
1860 }
1861#else
1862 NOREF(pVM); NOREF(GCPhys); NOREF(cb);
1863#endif
1864 RT_NOREF_PV(fFlags);
1865 return VINF_SUCCESS;
1866}
1867
1868
1869/**
1870 * Called after the ROM range has been fully completed.
1871 *
1872 * This will be preceeded by a NEMR3NotifyPhysRomRegisterEarly() call as well a
1873 * number of NEMHCNotifyPhysPageProtChanged calls.
1874 *
1875 * @returns VBox status code
1876 * @param pVM The cross context VM structure.
1877 * @param GCPhys The ROM address (page aligned).
1878 * @param cb The size (page aligned).
1879 * @param fFlags NEM_NOTIFY_PHYS_ROM_F_XXX.
1880 */
1881int nemR3NativeNotifyPhysRomRegisterLate(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, uint32_t fFlags)
1882{
1883 Log5(("nemR3NativeNotifyPhysRomRegisterLate: %RGp LB %RGp fFlags=%#x\n", GCPhys, cb, fFlags));
1884 NOREF(pVM); NOREF(GCPhys); NOREF(cb); NOREF(fFlags);
1885 return VINF_SUCCESS;
1886}
1887
1888
1889/**
1890 * @callback_method_impl{FNPGMPHYSNEMCHECKPAGE}
1891 */
1892static DECLCALLBACK(int) nemR3WinUnsetForA20CheckerCallback(PVM pVM, PVMCPU pVCpu, RTGCPHYS GCPhys,
1893 PPGMPHYSNEMPAGEINFO pInfo, void *pvUser)
1894{
1895 /* We'll just unmap the memory. */
1896 if (pInfo->u2NemState > NEM_WIN_PAGE_STATE_UNMAPPED)
1897 {
1898#ifdef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
1899 int rc = nemHCWinHypercallUnmapPage(pVM, pVCpu, GCPhys);
1900 AssertRC(rc);
1901 if (RT_SUCCESS(rc))
1902#else
1903 HRESULT hrc = WHvUnmapGpaRange(pVM->nem.s.hPartition, GCPhys, X86_PAGE_SIZE);
1904 if (SUCCEEDED(hrc))
1905#endif
1906 {
1907 uint32_t cMappedPages = ASMAtomicDecU32(&pVM->nem.s.cMappedPages); NOREF(cMappedPages);
1908 Log5(("NEM GPA unmapped/A20: %RGp (was %s, cMappedPages=%u)\n", GCPhys, g_apszPageStates[pInfo->u2NemState], cMappedPages));
1909 pInfo->u2NemState = NEM_WIN_PAGE_STATE_UNMAPPED;
1910 }
1911 else
1912 {
1913#ifdef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
1914 LogRel(("nemR3WinUnsetForA20CheckerCallback/unmap: GCPhys=%RGp rc=%Rrc\n", GCPhys, rc));
1915 return rc;
1916#else
1917 LogRel(("nemR3WinUnsetForA20CheckerCallback/unmap: GCPhys=%RGp hrc=%Rhrc (%#x) Last=%#x/%u\n",
1918 GCPhys, hrc, hrc, RTNtLastStatusValue(), RTNtLastErrorValue()));
1919 return VERR_INTERNAL_ERROR_2;
1920#endif
1921 }
1922 }
1923 RT_NOREF(pVCpu, pvUser);
1924 return VINF_SUCCESS;
1925}
1926
1927
1928/**
1929 * Unmaps a page from Hyper-V for the purpose of emulating A20 gate behavior.
1930 *
1931 * @returns The PGMPhysNemQueryPageInfo result.
1932 * @param pVM The cross context VM structure.
1933 * @param pVCpu The cross context virtual CPU structure.
1934 * @param GCPhys The page to unmap.
1935 */
1936static int nemR3WinUnmapPageForA20Gate(PVM pVM, PVMCPU pVCpu, RTGCPHYS GCPhys)
1937{
1938 PGMPHYSNEMPAGEINFO Info;
1939 return PGMPhysNemPageInfoChecker(pVM, pVCpu, GCPhys, false /*fMakeWritable*/, &Info,
1940 nemR3WinUnsetForA20CheckerCallback, NULL);
1941}
1942
1943
1944/**
1945 * Called when the A20 state changes.
1946 *
1947 * Hyper-V doesn't seem to offer a simple way of implementing the A20 line
1948 * features of PCs. So, we do a very minimal emulation of the HMA to make DOS
1949 * happy.
1950 *
1951 * @param pVCpu The CPU the A20 state changed on.
1952 * @param fEnabled Whether it was enabled (true) or disabled.
1953 */
1954void nemR3NativeNotifySetA20(PVMCPU pVCpu, bool fEnabled)
1955{
1956 Log(("nemR3NativeNotifySetA20: fEnabled=%RTbool\n", fEnabled));
1957 PVM pVM = pVCpu->CTX_SUFF(pVM);
1958 if (!pVM->nem.s.fA20Fixed)
1959 {
1960 pVM->nem.s.fA20Enabled = fEnabled;
1961 for (RTGCPHYS GCPhys = _1M; GCPhys < _1M + _64K; GCPhys += X86_PAGE_SIZE)
1962 nemR3WinUnmapPageForA20Gate(pVM, pVCpu, GCPhys);
1963 }
1964}
1965
1966
1967/** @page pg_nem_win NEM/win - Native Execution Manager, Windows.
1968 *
1969 * On Windows the Hyper-V root partition (dom0 in zen terminology) does not have
1970 * nested VT-x or AMD-V capabilities. Early on raw-mode worked inside it, but
1971 * for a while now we've been getting \#GPs when trying to modify CR4 in the
1972 * world switcher. So, when Hyper-V is active on Windows we have little choice
1973 * but to use Hyper-V to run our VMs.
1974 *
1975 *
1976 * @section sub_nem_win_whv The WinHvPlatform API
1977 *
1978 * Since Windows 10 build 17083 there is a documented API for managing Hyper-V
1979 * VMs: header file WinHvPlatform.h and implementation in WinHvPlatform.dll.
1980 * This interface is a wrapper around the undocumented Virtualization
1981 * Infrastructure Driver (VID) API - VID.DLL and VID.SYS. The wrapper is
1982 * written in C++, namespaced, early versions (at least) was using standard C++
1983 * container templates in several places.
1984 *
1985 * When creating a VM using WHvCreatePartition, it will only create the
1986 * WinHvPlatform structures for it, to which you get an abstract pointer. The
1987 * VID API that actually creates the partition is first engaged when you call
1988 * WHvSetupPartition after first setting a lot of properties using
1989 * WHvSetPartitionProperty. Since the VID API is just a very thin wrapper
1990 * around CreateFile and NtDeviceIoControlFile, it returns an actual HANDLE for
1991 * the partition to WinHvPlatform. We fish this HANDLE out of the WinHvPlatform
1992 * partition structures because we need to talk directly to VID for reasons
1993 * we'll get to in a bit. (Btw. we could also intercept the CreateFileW or
1994 * NtDeviceIoControlFile calls from VID.DLL to get the HANDLE should fishing in
1995 * the partition structures become difficult.)
1996 *
1997 * The WinHvPlatform API requires us to both set the number of guest CPUs before
1998 * setting up the partition and call WHvCreateVirtualProcessor for each of them.
1999 * The CPU creation function boils down to a VidMessageSlotMap call that sets up
2000 * and maps a message buffer into ring-3 for async communication with hyper-V
2001 * and/or the VID.SYS thread actually running the CPU thru
2002 * WinHvRunVpDispatchLoop(). When for instance a VMEXIT is encountered, hyper-V
2003 * sends a message that the WHvRunVirtualProcessor API retrieves (and later
2004 * acknowledges) via VidMessageSlotHandleAndGetNext. Since or about build
2005 * 17757 a register page is also mapped into user space when creating the
2006 * virtual CPU. It should be noteded that WHvDeleteVirtualProcessor doesn't do
2007 * much as there seems to be no partner function VidMessagesSlotMap that
2008 * reverses what it did.
2009 *
2010 * Memory is managed thru calls to WHvMapGpaRange and WHvUnmapGpaRange (GPA does
2011 * not mean grade point average here, but rather guest physical addressspace),
2012 * which corresponds to VidCreateVaGpaRangeSpecifyUserVa and VidDestroyGpaRange
2013 * respectively. As 'UserVa' indicates, the functions works on user process
2014 * memory. The mappings are also subject to quota restrictions, so the number
2015 * of ranges are limited and probably their total size as well. Obviously
2016 * VID.SYS keeps track of the ranges, but so does WinHvPlatform, which means
2017 * there is a bit of overhead involved and quota restrctions makes sense.
2018 *
2019 * Running guest code is done through the WHvRunVirtualProcessor function. It
2020 * asynchronously starts or resumes hyper-V CPU execution and then waits for an
2021 * VMEXIT message. Hyper-V / VID.SYS will return information about the message
2022 * in the message buffer mapping, and WHvRunVirtualProcessor will convert that
2023 * finto it's own WHV_RUN_VP_EXIT_CONTEXT format.
2024 *
2025 * Other threads can interrupt the execution by using WHvCancelVirtualProcessor,
2026 * which since or about build 17757 uses VidMessageSlotHandleAndGetNext to do
2027 * the work (earlier builds would open the waiting thread, do a dummy
2028 * QueueUserAPC on it, and let it upon return use VidStopVirtualProcessor to
2029 * do the actual stopping). While there is certainly a race between cancelation
2030 * and the CPU causing a natural VMEXIT, it is not known whether this still
2031 * causes extra work on subsequent WHvRunVirtualProcessor calls (it did in and
2032 * earlier 17134).
2033 *
2034 * Registers are retrieved and set via WHvGetVirtualProcessorRegisters and
2035 * WHvSetVirtualProcessorRegisters. In addition, several VMEXITs include
2036 * essential register state in the exit context information, potentially making
2037 * it possible to emulate the instruction causing the exit without involving
2038 * WHvGetVirtualProcessorRegisters.
2039 *
2040 *
2041 * @subsection subsec_nem_win_whv_cons Issues & Feedback
2042 *
2043 * Here are some observations (mostly against build 17101):
2044 *
2045 * - The VMEXIT performance is dismal (build 17134).
2046 *
2047 * Our proof of concept implementation with a kernel runloop (i.e. not using
2048 * WHvRunVirtualProcessor and friends, but calling VID.SYS fast I/O control
2049 * entry point directly) delivers 9-10% of the port I/O performance and only
2050 * 6-7% of the MMIO performance that we have with our own hypervisor.
2051 *
2052 * When using the offical WinHvPlatform API, the numbers are %3 for port I/O
2053 * and 5% for MMIO.
2054 *
2055 * While the tests we've done are using tight tight loops only doing port I/O
2056 * and MMIO, the problem is clearly visible when running regular guest OSes.
2057 * Anything that hammers the VGA device would be suffering, for example:
2058 *
2059 * - Windows 2000 boot screen animation overloads us with MMIO exits
2060 * and won't even boot because all the time is spent in interrupt
2061 * handlers and redrawin the screen.
2062 *
2063 * - DSL 4.4 and its bootmenu logo is slower than molasses in january.
2064 *
2065 * We have not found a workaround for this yet.
2066 *
2067 * Something that might improve the issue a little is to detect blocks with
2068 * excessive MMIO and port I/O exits and emulate instructions to cover
2069 * multiple exits before letting Hyper-V have a go at the guest execution
2070 * again. This will only improve the situation under some circumstances,
2071 * since emulating instructions without recompilation can be expensive, so
2072 * there will only be real gains if the exitting instructions are tightly
2073 * packed.
2074 *
2075 * Update: Security fixes during the summer of 2018 caused the performance to
2076 * dropped even more.
2077 *
2078 * Update [build 17757]: Some performance improvements here, but they don't
2079 * yet make up for what was lost this summer.
2080 *
2081 *
2082 * - We need a way to directly modify the TSC offset (or bias if you like).
2083 *
2084 * The current approach of setting the WHvX64RegisterTsc register one by one
2085 * on each virtual CPU in sequence will introduce random inaccuracies,
2086 * especially if the thread doing the job is reschduled at a bad time.
2087 *
2088 *
2089 * - Unable to access WHvX64RegisterMsrMtrrCap (build 17134).
2090 *
2091 *
2092 * - On AMD Ryzen grub/debian 9.0 ends up with a unrecoverable exception
2093 * when IA32_MTRR_PHYSMASK0 is written.
2094 *
2095 *
2096 * - The IA32_APIC_BASE register does not work right:
2097 *
2098 * - Attempts by the guest to clear bit 11 (EN) are ignored, both the
2099 * guest and the VMM reads back the old value.
2100 *
2101 * - Attempts to modify the base address (bits NN:12) seems to be ignored
2102 * in the same way.
2103 *
2104 * - The VMM can modify both the base address as well as the the EN and
2105 * BSP bits, however this is useless if we cannot intercept the WRMSR.
2106 *
2107 * - Attempts by the guest to set the EXTD bit (X2APIC) result in \#GP(0),
2108 * while the VMM ends up with with ERROR_HV_INVALID_PARAMETER. Seems
2109 * there is no way to support X2APIC.
2110 *
2111 *
2112 * - Not sure if this is a thing, but WHvCancelVirtualProcessor seems to cause
2113 * cause a lot more spurious WHvRunVirtualProcessor returns that what we get
2114 * with the replacement code. By spurious returns we mean that the
2115 * subsequent call to WHvRunVirtualProcessor would return immediately.
2116 *
2117 * Update [build 17757]: New cancelation code might have addressed this, but
2118 * haven't had time to test it yet.
2119 *
2120 *
2121 * - There is no API for modifying protection of a page within a GPA range.
2122 *
2123 * From what we can tell, the only way to modify the protection (like readonly
2124 * -> writable, or vice versa) is to first unmap the range and then remap it
2125 * with the new protection.
2126 *
2127 * We are for instance doing this quite a bit in order to track dirty VRAM
2128 * pages. VRAM pages starts out as readonly, when the guest writes to a page
2129 * we take an exit, notes down which page it is, makes it writable and restart
2130 * the instruction. After refreshing the display, we reset all the writable
2131 * pages to readonly again, bulk fashion.
2132 *
2133 * Now to work around this issue, we do page sized GPA ranges. In addition to
2134 * add a lot of tracking overhead to WinHvPlatform and VID.SYS, this also
2135 * causes us to exceed our quota before we've even mapped a default sized
2136 * (128MB) VRAM page-by-page. So, to work around this quota issue we have to
2137 * lazily map pages and actively restrict the number of mappings.
2138 *
2139 * Our best workaround thus far is bypassing WinHvPlatform and VID entirely
2140 * when in comes to guest memory management and instead use the underlying
2141 * hypercalls (HvCallMapGpaPages, HvCallUnmapGpaPages) to do it ourselves.
2142 * (This also maps a whole lot better into our own guest page management
2143 * infrastructure.)
2144 *
2145 * Update [build 17757]: Introduces a KVM like dirty logging API which could
2146 * help tracking dirty VGA pages, while being useless for shadow ROM and
2147 * devices trying catch the guest updating descriptors and such.
2148 *
2149 *
2150 * - Observed problems doing WHvUnmapGpaRange immediately followed by
2151 * WHvMapGpaRange.
2152 *
2153 * As mentioned above, we've been forced to use this sequence when modifying
2154 * page protection. However, when transitioning from readonly to writable,
2155 * we've ended up looping forever with the same write to readonly memory
2156 * VMEXIT. We're wondering if this issue might be related to the lazy mapping
2157 * logic in WinHvPlatform.
2158 *
2159 * Workaround: Insert a WHvRunVirtualProcessor call and make sure to get a GPA
2160 * unmapped exit between the two calls. Not entirely great performance wise
2161 * (or the santity of our code).
2162 *
2163 *
2164 * - Implementing A20 gate behavior is tedious, where as correctly emulating the
2165 * A20M# pin (present on 486 and later) is near impossible for SMP setups
2166 * (e.g. possiblity of two CPUs with different A20 status).
2167 *
2168 * Workaround: Only do A20 on CPU 0, restricting the emulation to HMA. We
2169 * unmap all pages related to HMA (0x100000..0x10ffff) when the A20 state
2170 * changes, lazily syncing the right pages back when accessed.
2171 *
2172 *
2173 * - WHVRunVirtualProcessor wastes time converting VID/Hyper-V messages to its
2174 * own format (WHV_RUN_VP_EXIT_CONTEXT).
2175 *
2176 * We understand this might be because Microsoft wishes to remain free to
2177 * modify the VID/Hyper-V messages, but it's still rather silly and does slow
2178 * things down a little. We'd much rather just process the messages directly.
2179 *
2180 *
2181 * - WHVRunVirtualProcessor would've benefited from using a callback interface:
2182 *
2183 * - The potential size changes of the exit context structure wouldn't be
2184 * an issue, since the function could manage that itself.
2185 *
2186 * - State handling could probably be simplified (like cancelation).
2187 *
2188 *
2189 * - WHvGetVirtualProcessorRegisters and WHvSetVirtualProcessorRegisters
2190 * internally converts register names, probably using temporary heap buffers.
2191 *
2192 * From the looks of things, they are converting from WHV_REGISTER_NAME to
2193 * HV_REGISTER_NAME from in the "Virtual Processor Register Names" section in
2194 * the "Hypervisor Top-Level Functional Specification" document. This feels
2195 * like an awful waste of time.
2196 *
2197 * We simply cannot understand why HV_REGISTER_NAME isn't used directly here,
2198 * or at least the same values, making any conversion reduntant. Restricting
2199 * access to certain registers could easily be implement by scanning the
2200 * inputs.
2201 *
2202 * To avoid the heap + conversion overhead, we're currently using the
2203 * HvCallGetVpRegisters and HvCallSetVpRegisters calls directly, at least for
2204 * the ring-0 code.
2205 *
2206 * Update [build 17757]: Register translation has been very cleverly
2207 * optimized and made table driven (2 top level tables, 4 + 1 leaf tables).
2208 * Register information consists of the 32-bit HV register name, register page
2209 * offset, and flags (giving valid offset, size and more). Register
2210 * getting/settings seems to be done by hoping that the register page provides
2211 * it all, and falling back on the VidSetVirtualProcessorState if one or more
2212 * registers are not available there.
2213 *
2214 * Note! We have currently not updated our ring-0 code to take the register
2215 * page into account, so it's suffering a little compared to the ring-3 code
2216 * that now uses the offical APIs for registers.
2217 *
2218 *
2219 * - The YMM and XCR0 registers are not yet named (17083). This probably
2220 * wouldn't be a problem if HV_REGISTER_NAME was used, see previous point.
2221 *
2222 * Update [build 17757]: XCR0 is added. YMM register values seems to be put
2223 * into a yet undocumented XsaveState interface. Approach is a little bulky,
2224 * but saves number of enums and dispenses with register transation. Also,
2225 * the underlying Vid setter API duplicates the input buffer on the heap,
2226 * adding a 16 byte header.
2227 *
2228 *
2229 * - Why does VID.SYS only query/set 32 registers at the time thru the
2230 * HvCallGetVpRegisters and HvCallSetVpRegisters hypercalls?
2231 *
2232 * We've not trouble getting/setting all the registers defined by
2233 * WHV_REGISTER_NAME in one hypercall (around 80). Some kind of stack
2234 * buffering or similar?
2235 *
2236 *
2237 * - To handle the VMMCALL / VMCALL instructions, it seems we need to intercept
2238 * \#UD exceptions and inspect the opcodes. A dedicated exit for hypercalls
2239 * would be more efficient, esp. for guests using \#UD for other purposes..
2240 *
2241 *
2242 * - Wrong instruction length in the VpContext with unmapped GPA memory exit
2243 * contexts on 17115/AMD.
2244 *
2245 * One byte "PUSH CS" was reported as 2 bytes, while a two byte
2246 * "MOV [EBX],EAX" was reported with a 1 byte instruction length. Problem
2247 * naturally present in untranslated hyper-v messages.
2248 *
2249 *
2250 * - The I/O port exit context information seems to be missing the address size
2251 * information needed for correct string I/O emulation.
2252 *
2253 * VT-x provides this information in bits 7:9 in the instruction information
2254 * field on newer CPUs. AMD-V in bits 7:9 in the EXITINFO1 field in the VMCB.
2255 *
2256 * We can probably work around this by scanning the instruction bytes for
2257 * address size prefixes. Haven't investigated it any further yet.
2258 *
2259 *
2260 * - Querying WHvCapabilityCodeExceptionExitBitmap returns zero even when
2261 * intercepts demonstrably works (17134).
2262 *
2263 *
2264 * - Querying HvPartitionPropertyDebugChannelId via HvCallGetPartitionProperty
2265 * (hypercall) hangs the host (17134).
2266 *
2267 *
2268 *
2269 * Old concerns that have been addressed:
2270 *
2271 * - The WHvCancelVirtualProcessor API schedules a dummy usermode APC callback
2272 * in order to cancel any current or future alertable wait in VID.SYS during
2273 * the VidMessageSlotHandleAndGetNext call.
2274 *
2275 * IIRC this will make the kernel schedule the specified callback thru
2276 * NTDLL!KiUserApcDispatcher by modifying the thread context and quite
2277 * possibly the userland thread stack. When the APC callback returns to
2278 * KiUserApcDispatcher, it will call NtContinue to restore the old thread
2279 * context and resume execution from there. This naturally adds up to some
2280 * CPU cycles, ring transitions aren't for free, especially after Spectre &
2281 * Meltdown mitigations.
2282 *
2283 * Using NtAltertThread call could do the same without the thread context
2284 * modifications and the extra kernel call.
2285 *
2286 * Update: All concerns have addressed in or about build 17757.
2287 *
2288 * The WHvCancelVirtualProcessor API is now implemented using a new
2289 * VidMessageSlotHandleAndGetNext() flag (4). Codepath is slightly longer
2290 * than NtAlertThread, but has the added benefit that spurious wakeups can be
2291 * more easily reduced.
2292 *
2293 *
2294 * - When WHvRunVirtualProcessor returns without a message, or on a terse
2295 * VID message like HLT, it will make a kernel call to get some registers.
2296 * This is potentially inefficient if the caller decides he needs more
2297 * register state.
2298 *
2299 * It would be better to just return what's available and let the caller fetch
2300 * what is missing from his point of view in a single kernel call.
2301 *
2302 * Update: All concerns have been addressed in or about build 17757. Selected
2303 * registers are now available via shared memory and thus HLT should (not
2304 * verified) no longer require a system call to compose the exit context data.
2305 *
2306 *
2307 * - The WHvRunVirtualProcessor implementation does lazy GPA range mappings when
2308 * a unmapped GPA message is received from hyper-V.
2309 *
2310 * Since MMIO is currently realized as unmapped GPA, this will slow down all
2311 * MMIO accesses a tiny little bit as WHvRunVirtualProcessor looks up the
2312 * guest physical address to check if it is a pending lazy mapping.
2313 *
2314 * The lazy mapping feature makes no sense to us. We as API user have all the
2315 * information and can do lazy mapping ourselves if we want/have to (see next
2316 * point).
2317 *
2318 * Update: All concerns have been addressed in or about build 17757.
2319 *
2320 *
2321 * - The WHvGetCapability function has a weird design:
2322 * - The CapabilityCode parameter is pointlessly duplicated in the output
2323 * structure (WHV_CAPABILITY).
2324 *
2325 * - API takes void pointer, but everyone will probably be using
2326 * WHV_CAPABILITY due to WHV_CAPABILITY::CapabilityCode making it
2327 * impractical to use anything else.
2328 *
2329 * - No output size.
2330 *
2331 * - See GetFileAttributesEx, GetFileInformationByHandleEx,
2332 * FindFirstFileEx, and others for typical pattern for generic
2333 * information getters.
2334 *
2335 * Update: All concerns have been addressed in build 17110.
2336 *
2337 *
2338 * - The WHvGetPartitionProperty function uses the same weird design as
2339 * WHvGetCapability, see above.
2340 *
2341 * Update: All concerns have been addressed in build 17110.
2342 *
2343 *
2344 * - The WHvSetPartitionProperty function has a totally weird design too:
2345 * - In contrast to its partner WHvGetPartitionProperty, the property code
2346 * is not a separate input parameter here but part of the input
2347 * structure.
2348 *
2349 * - The input structure is a void pointer rather than a pointer to
2350 * WHV_PARTITION_PROPERTY which everyone probably will be using because
2351 * of the WHV_PARTITION_PROPERTY::PropertyCode field.
2352 *
2353 * - Really, why use PVOID for the input when the function isn't accepting
2354 * minimal sizes. E.g. WHVPartitionPropertyCodeProcessorClFlushSize only
2355 * requires a 9 byte input, but the function insists on 16 bytes (17083).
2356 *
2357 * - See GetFileAttributesEx, SetFileInformationByHandle, FindFirstFileEx,
2358 * and others for typical pattern for generic information setters and
2359 * getters.
2360 *
2361 * Update: All concerns have been addressed in build 17110.
2362 *
2363 *
2364 *
2365 * @section sec_nem_win_impl Our implementation.
2366 *
2367 * We set out with the goal of wanting to run as much as possible in ring-0,
2368 * reasoning that this would give use the best performance.
2369 *
2370 * This goal was approached gradually, starting out with a pure WinHvPlatform
2371 * implementation, gradually replacing parts: register access, guest memory
2372 * handling, running virtual processors. Then finally moving it all into
2373 * ring-0, while keeping most of it configurable so that we could make
2374 * comparisons (see NEMInternal.h and nemR3NativeRunGC()).
2375 *
2376 *
2377 * @subsection subsect_nem_win_impl_ioctl VID.SYS I/O control calls
2378 *
2379 * To run things in ring-0 we need to talk directly to VID.SYS thru its I/O
2380 * control interface. Looking at changes between like build 17083 and 17101 (if
2381 * memory serves) a set of the VID I/O control numbers shifted a little, which
2382 * means we need to determin them dynamically. We currently do this by hooking
2383 * the NtDeviceIoControlFile API call from VID.DLL and snooping up the
2384 * parameters when making dummy calls to relevant APIs. (We could also
2385 * disassemble the relevant APIs and try fish out the information from that, but
2386 * this is way simpler.)
2387 *
2388 * Issuing I/O control calls from ring-0 is facing a small challenge with
2389 * respect to direct buffering. When using direct buffering the device will
2390 * typically check that the buffer is actually in the user address space range
2391 * and reject kernel addresses. Fortunately, we've got the cross context VM
2392 * structure that is mapped into both kernel and user space, it's also locked
2393 * and safe to access from kernel space. So, we place the I/O control buffers
2394 * in the per-CPU part of it (NEMCPU::uIoCtlBuf) and give the driver the user
2395 * address if direct access buffering or kernel address if not.
2396 *
2397 * The I/O control calls are 'abstracted' in the support driver, see
2398 * SUPR0IoCtlSetupForHandle(), SUPR0IoCtlPerform() and SUPR0IoCtlCleanup().
2399 *
2400 *
2401 * @subsection subsect_nem_win_impl_cpumctx CPUMCTX
2402 *
2403 * Since the CPU state needs to live in Hyper-V when executing, we probably
2404 * should not transfer more than necessary when handling VMEXITs. To help us
2405 * manage this CPUMCTX got a new field CPUMCTX::fExtrn that to indicate which
2406 * part of the state is currently externalized (== in Hyper-V).
2407 *
2408 *
2409 * @subsection sec_nem_win_benchmarks Benchmarks.
2410 *
2411 * @subsubsection subsect_nem_win_benchmarks_bs2t1 17134/2018-06-22: Bootsector2-test1
2412 *
2413 * This is ValidationKit/bootsectors/bootsector2-test1.asm as of 2018-06-22
2414 * (internal r123172) running a the release build of VirtualBox from the same
2415 * source, though with exit optimizations disabled. Host is AMD Threadripper 1950X
2416 * running out an up to date 64-bit Windows 10 build 17134.
2417 *
2418 * The base line column is using the official WinHv API for everything but physical
2419 * memory mapping. The 2nd column is the default NEM/win configuration where we
2420 * put the main execution loop in ring-0, using hypercalls when we can and VID for
2421 * managing execution. The 3rd column is regular VirtualBox using AMD-V directly,
2422 * hyper-V is disabled, main execution loop in ring-0.
2423 *
2424 * @verbatim
2425TESTING... WinHv API Hypercalls + VID VirtualBox AMD-V
2426 32-bit paged protected mode, CPUID : 108 874 ins/sec 113% / 123 602 1198% / 1 305 113
2427 32-bit pae protected mode, CPUID : 106 722 ins/sec 115% / 122 740 1232% / 1 315 201
2428 64-bit long mode, CPUID : 106 798 ins/sec 114% / 122 111 1198% / 1 280 404
2429 16-bit unpaged protected mode, CPUID : 106 835 ins/sec 114% / 121 994 1216% / 1 299 665
2430 32-bit unpaged protected mode, CPUID : 105 257 ins/sec 115% / 121 772 1235% / 1 300 860
2431 real mode, CPUID : 104 507 ins/sec 116% / 121 800 1228% / 1 283 848
2432CPUID EAX=1 : PASSED
2433 32-bit paged protected mode, RDTSC : 99 581 834 ins/sec 100% / 100 323 307 93% / 93 473 299
2434 32-bit pae protected mode, RDTSC : 99 620 585 ins/sec 100% / 99 960 952 84% / 83 968 839
2435 64-bit long mode, RDTSC : 100 540 009 ins/sec 100% / 100 946 372 93% / 93 652 826
2436 16-bit unpaged protected mode, RDTSC : 99 688 473 ins/sec 100% / 100 097 751 76% / 76 281 287
2437 32-bit unpaged protected mode, RDTSC : 98 385 857 ins/sec 102% / 100 510 404 94% / 93 379 536
2438 real mode, RDTSC : 100 087 967 ins/sec 101% / 101 386 138 93% / 93 234 999
2439RDTSC : PASSED
2440 32-bit paged protected mode, Read CR4 : 2 156 102 ins/sec 98% / 2 121 967 17114% / 369 009 009
2441 32-bit pae protected mode, Read CR4 : 2 163 820 ins/sec 98% / 2 133 804 17469% / 377 999 261
2442 64-bit long mode, Read CR4 : 2 164 822 ins/sec 98% / 2 128 698 18875% / 408 619 313
2443 16-bit unpaged protected mode, Read CR4 : 2 162 367 ins/sec 100% / 2 168 508 17132% / 370 477 568
2444 32-bit unpaged protected mode, Read CR4 : 2 163 189 ins/sec 100% / 2 169 808 16768% / 362 734 679
2445 real mode, Read CR4 : 2 162 436 ins/sec 100% / 2 164 914 15551% / 336 288 998
2446Read CR4 : PASSED
2447 real mode, 32-bit IN : 104 649 ins/sec 118% / 123 513 1028% / 1 075 831
2448 real mode, 32-bit OUT : 107 102 ins/sec 115% / 123 660 982% / 1 052 259
2449 real mode, 32-bit IN-to-ring-3 : 105 697 ins/sec 98% / 104 471 201% / 213 216
2450 real mode, 32-bit OUT-to-ring-3 : 105 830 ins/sec 98% / 104 598 198% / 210 495
2451 16-bit unpaged protected mode, 32-bit IN : 104 855 ins/sec 117% / 123 174 1029% / 1 079 591
2452 16-bit unpaged protected mode, 32-bit OUT : 107 529 ins/sec 115% / 124 250 992% / 1 067 053
2453 16-bit unpaged protected mode, 32-bit IN-to-ring-3 : 106 337 ins/sec 103% / 109 565 196% / 209 367
2454 16-bit unpaged protected mode, 32-bit OUT-to-ring-3 : 107 558 ins/sec 100% / 108 237 191% / 206 387
2455 32-bit unpaged protected mode, 32-bit IN : 106 351 ins/sec 116% / 123 584 1016% / 1 081 325
2456 32-bit unpaged protected mode, 32-bit OUT : 106 424 ins/sec 116% / 124 252 995% / 1 059 408
2457 32-bit unpaged protected mode, 32-bit IN-to-ring-3 : 104 035 ins/sec 101% / 105 305 202% / 210 750
2458 32-bit unpaged protected mode, 32-bit OUT-to-ring-3 : 103 831 ins/sec 102% / 106 919 205% / 213 198
2459 32-bit paged protected mode, 32-bit IN : 103 356 ins/sec 119% / 123 870 1041% / 1 076 463
2460 32-bit paged protected mode, 32-bit OUT : 107 177 ins/sec 115% / 124 302 998% / 1 069 655
2461 32-bit paged protected mode, 32-bit IN-to-ring-3 : 104 491 ins/sec 100% / 104 744 200% / 209 264
2462 32-bit paged protected mode, 32-bit OUT-to-ring-3 : 106 603 ins/sec 97% / 103 849 197% / 210 219
2463 32-bit pae protected mode, 32-bit IN : 105 923 ins/sec 115% / 122 759 1041% / 1 103 261
2464 32-bit pae protected mode, 32-bit OUT : 107 083 ins/sec 117% / 126 057 1024% / 1 096 667
2465 32-bit pae protected mode, 32-bit IN-to-ring-3 : 106 114 ins/sec 97% / 103 496 199% / 211 312
2466 32-bit pae protected mode, 32-bit OUT-to-ring-3 : 105 675 ins/sec 96% / 102 096 198% / 209 890
2467 64-bit long mode, 32-bit IN : 105 800 ins/sec 113% / 120 006 1013% / 1 072 116
2468 64-bit long mode, 32-bit OUT : 105 635 ins/sec 113% / 120 375 997% / 1 053 655
2469 64-bit long mode, 32-bit IN-to-ring-3 : 105 274 ins/sec 95% / 100 763 197% / 208 026
2470 64-bit long mode, 32-bit OUT-to-ring-3 : 106 262 ins/sec 94% / 100 749 196% / 209 288
2471NOP I/O Port Access : PASSED
2472 32-bit paged protected mode, 32-bit read : 57 687 ins/sec 119% / 69 136 1197% / 690 548
2473 32-bit paged protected mode, 32-bit write : 57 957 ins/sec 118% / 68 935 1183% / 685 930
2474 32-bit paged protected mode, 32-bit read-to-ring-3 : 57 958 ins/sec 95% / 55 432 276% / 160 505
2475 32-bit paged protected mode, 32-bit write-to-ring-3 : 57 922 ins/sec 100% / 58 340 304% / 176 464
2476 32-bit pae protected mode, 32-bit read : 57 478 ins/sec 119% / 68 453 1141% / 656 159
2477 32-bit pae protected mode, 32-bit write : 57 226 ins/sec 118% / 68 097 1157% / 662 504
2478 32-bit pae protected mode, 32-bit read-to-ring-3 : 57 582 ins/sec 94% / 54 651 268% / 154 867
2479 32-bit pae protected mode, 32-bit write-to-ring-3 : 57 697 ins/sec 100% / 57 750 299% / 173 030
2480 64-bit long mode, 32-bit read : 57 128 ins/sec 118% / 67 779 1071% / 611 949
2481 64-bit long mode, 32-bit write : 57 127 ins/sec 118% / 67 632 1084% / 619 395
2482 64-bit long mode, 32-bit read-to-ring-3 : 57 181 ins/sec 94% / 54 123 265% / 151 937
2483 64-bit long mode, 32-bit write-to-ring-3 : 57 297 ins/sec 99% / 57 286 294% / 168 694
2484 16-bit unpaged protected mode, 32-bit read : 58 827 ins/sec 118% / 69 545 1185% / 697 602
2485 16-bit unpaged protected mode, 32-bit write : 58 678 ins/sec 118% / 69 442 1183% / 694 387
2486 16-bit unpaged protected mode, 32-bit read-to-ring-3 : 57 841 ins/sec 96% / 55 730 275% / 159 163
2487 16-bit unpaged protected mode, 32-bit write-to-ring-3 : 57 855 ins/sec 101% / 58 834 304% / 176 169
2488 32-bit unpaged protected mode, 32-bit read : 58 063 ins/sec 120% / 69 690 1233% / 716 444
2489 32-bit unpaged protected mode, 32-bit write : 57 936 ins/sec 120% / 69 633 1199% / 694 753
2490 32-bit unpaged protected mode, 32-bit read-to-ring-3 : 58 451 ins/sec 96% / 56 183 273% / 159 972
2491 32-bit unpaged protected mode, 32-bit write-to-ring-3 : 58 962 ins/sec 99% / 58 955 298% / 175 936
2492 real mode, 32-bit read : 58 571 ins/sec 118% / 69 478 1160% / 679 917
2493 real mode, 32-bit write : 58 418 ins/sec 118% / 69 320 1185% / 692 513
2494 real mode, 32-bit read-to-ring-3 : 58 072 ins/sec 96% / 55 751 274% / 159 145
2495 real mode, 32-bit write-to-ring-3 : 57 870 ins/sec 101% / 58 755 307% / 178 042
2496NOP MMIO Access : PASSED
2497SUCCESS
2498 * @endverbatim
2499 *
2500 * What we see here is:
2501 *
2502 * - The WinHv API approach is 10 to 12 times slower for exits we can
2503 * handle directly in ring-0 in the VBox AMD-V code.
2504 *
2505 * - The WinHv API approach is 2 to 3 times slower for exits we have to
2506 * go to ring-3 to handle with the VBox AMD-V code.
2507 *
2508 * - By using hypercalls and VID.SYS from ring-0 we gain between
2509 * 13% and 20% over the WinHv API on exits handled in ring-0.
2510 *
2511 * - For exits requiring ring-3 handling are between 6% slower and 3% faster
2512 * than the WinHv API.
2513 *
2514 *
2515 * As a side note, it looks like Hyper-V doesn't let the guest read CR4 but
2516 * triggers exits all the time. This isn't all that important these days since
2517 * OSes like Linux cache the CR4 value specifically to avoid these kinds of exits.
2518 *
2519 *
2520 * @subsubsection subsect_nem_win_benchmarks_bs2t1u1 17134/2018-10-02: Bootsector2-test1
2521 *
2522 * Update on 17134. While expectantly testing a couple of newer builds (17758,
2523 * 17763) hoping for some increases in performance, the numbers turned out
2524 * altogether worse than the June test run. So, we went back to the 1803
2525 * (17134) installation, made sure it was fully up to date (as per 2018-10-02)
2526 * and re-tested.
2527 *
2528 * The numbers had somehow turned significantly worse over the last 3-4 months,
2529 * dropping around 70% for the WinHv API test, more for Hypercalls + VID.
2530 *
2531 * @verbatim
2532TESTING... WinHv API Hypercalls + VID VirtualBox AMD-V *
2533 32-bit paged protected mode, CPUID : 33 270 ins/sec 33 154
2534 real mode, CPUID : 33 534 ins/sec 32 711
2535 [snip]
2536 32-bit paged protected mode, RDTSC : 102 216 011 ins/sec 98 225 419
2537 real mode, RDTSC : 102 492 243 ins/sec 98 225 419
2538 [snip]
2539 32-bit paged protected mode, Read CR4 : 2 096 165 ins/sec 2 123 815
2540 real mode, Read CR4 : 2 081 047 ins/sec 2 075 151
2541 [snip]
2542 32-bit paged protected mode, 32-bit IN : 32 739 ins/sec 33 655
2543 32-bit paged protected mode, 32-bit OUT : 32 702 ins/sec 33 777
2544 32-bit paged protected mode, 32-bit IN-to-ring-3 : 32 579 ins/sec 29 985
2545 32-bit paged protected mode, 32-bit OUT-to-ring-3 : 32 750 ins/sec 29 757
2546 [snip]
2547 32-bit paged protected mode, 32-bit read : 20 042 ins/sec 21 489
2548 32-bit paged protected mode, 32-bit write : 20 036 ins/sec 21 493
2549 32-bit paged protected mode, 32-bit read-to-ring-3 : 19 985 ins/sec 19 143
2550 32-bit paged protected mode, 32-bit write-to-ring-3 : 19 972 ins/sec 19 595
2551
2552 * @endverbatim
2553 *
2554 * Suspects are security updates and/or microcode updates installed since then.
2555 * Given that the RDTSC and CR4 numbers are reasonably unchanges, it seems that
2556 * the Hyper-V core loop (in hvax64.exe) aren't affected. Our ring-0 runloop
2557 * is equally affected as the ring-3 based runloop, so it cannot be ring
2558 * switching as such (unless the ring-0 loop is borked and we didn't notice yet).
2559 *
2560 * The issue is probably in the thread / process switching area, could be
2561 * something special for hyper-V interrupt delivery or worker thread switching.
2562 *
2563 * Really wish this thread ping-pong going on in VID.SYS could be eliminated!
2564 *
2565 *
2566 * @subsubsection subsect_nem_win_benchmarks_bs2t1u2 17763: Bootsector2-test1
2567 *
2568 * Some preliminary numbers for build 17763 on the 3.4 GHz AMD 1950X, the second
2569 * column will improve we get time to have a look the register page.
2570 *
2571 * There is a 50% performance loss here compared to the June numbers with
2572 * build 17134. The RDTSC numbers hits that it isn't in the Hyper-V core
2573 * (hvax64.exe), but something on the NT side.
2574 *
2575 * Clearing bit 20 in nt!KiSpeculationFeatures speeds things up (i.e. changing
2576 * the dword from 0x00300065 to 0x00200065 in windbg). This is checked by
2577 * nt!KePrepareToDispatchVirtualProcessor, making it a no-op if the flag is
2578 * clear. winhvr!WinHvpVpDispatchLoop call that function before making
2579 * hypercall 0xc2, which presumably does the heavy VCpu lifting in hvcax64.exe.
2580 *
2581 * @verbatim
2582TESTING... WinHv API Hypercalls + VID clr(bit-20) + WinHv API
2583 32-bit paged protected mode, CPUID : 54 145 ins/sec 51 436 130 076
2584 real mode, CPUID : 54 178 ins/sec 51 713 130 449
2585 [snip]
2586 32-bit paged protected mode, RDTSC : 98 927 639 ins/sec 100 254 552 100 549 882
2587 real mode, RDTSC : 99 601 206 ins/sec 100 886 699 100 470 957
2588 [snip]
2589 32-bit paged protected mode, 32-bit IN : 54 621 ins/sec 51 524 128 294
2590 32-bit paged protected mode, 32-bit OUT : 54 870 ins/sec 51 671 129 397
2591 32-bit paged protected mode, 32-bit IN-to-ring-3 : 54 624 ins/sec 43 964 127 874
2592 32-bit paged protected mode, 32-bit OUT-to-ring-3 : 54 803 ins/sec 44 087 129 443
2593 [snip]
2594 32-bit paged protected mode, 32-bit read : 28 230 ins/sec 34 042 48 113
2595 32-bit paged protected mode, 32-bit write : 27 962 ins/sec 34 050 48 069
2596 32-bit paged protected mode, 32-bit read-to-ring-3 : 27 841 ins/sec 28 397 48 146
2597 32-bit paged protected mode, 32-bit write-to-ring-3 : 27 896 ins/sec 29 455 47 970
2598 * @endverbatim
2599 *
2600 *
2601 * @subsubsection subsect_nem_win_benchmarks_w2k 17134/2018-06-22: Windows 2000 Boot & Shutdown
2602 *
2603 * Timing the startup and automatic shutdown of a Windows 2000 SP4 guest serves
2604 * as a real world benchmark and example of why exit performance is import. When
2605 * Windows 2000 boots up is doing a lot of VGA redrawing of the boot animation,
2606 * which is very costly. Not having installed guest additions leaves it in a VGA
2607 * mode after the bootup sequence is done, keep up the screen access expenses,
2608 * though the graphics driver more economical than the bootvid code.
2609 *
2610 * The VM was configured to automatically logon. A startup script was installed
2611 * to perform the automatic shuting down and powering off the VM (thru
2612 * vts_shutdown.exe -f -p). An offline snapshot of the VM was taken an restored
2613 * before each test run. The test time run time is calculated from the monotonic
2614 * VBox.log timestamps, starting with the state change to 'RUNNING' and stopping
2615 * at 'POWERING_OFF'.
2616 *
2617 * The host OS and VirtualBox build is the same as for the bootsector2-test1
2618 * scenario.
2619 *
2620 * Results:
2621 *
2622 * - WinHv API for all but physical page mappings:
2623 * 32 min 12.19 seconds
2624 *
2625 * - The default NEM/win configuration where we put the main execution loop
2626 * in ring-0, using hypercalls when we can and VID for managing execution:
2627 * 3 min 23.18 seconds
2628 *
2629 * - Regular VirtualBox using AMD-V directly, hyper-V is disabled, main
2630 * execution loop in ring-0:
2631 * 58.09 seconds
2632 *
2633 * - WinHv API with exit history based optimizations:
2634 * 58.66 seconds
2635 *
2636 * - Hypercall + VID.SYS with exit history base optimizations:
2637 * 58.94 seconds
2638 *
2639 * With a well above average machine needing over half an hour for booting a
2640 * nearly 20 year old guest kind of says it all. The 13%-20% exit performance
2641 * increase we get by using hypercalls and VID.SYS directly pays off a lot here.
2642 * The 3m23s is almost acceptable in comparison to the half an hour.
2643 *
2644 * The similarity between the last three results strongly hits at windows 2000
2645 * doing a lot of waiting during boot and shutdown and isn't the best testcase
2646 * once a basic performance level is reached.
2647 *
2648 *
2649 * @subsubsection subsection_iem_win_benchmarks_deb9_nat Debian 9 NAT performance
2650 *
2651 * This benchmark is about network performance over NAT from a 64-bit Debian 9
2652 * VM with a single CPU. For network performance measurements, we use our own
2653 * NetPerf tool (ValidationKit/utils/network/NetPerf.cpp) to measure latency
2654 * and throughput.
2655 *
2656 * The setups, builds and configurations are as in the previous benchmarks
2657 * (release r123172 on 1950X running 64-bit W10/17134 (2016-06-xx). Please note
2658 * that the exit optimizations hasn't yet been in tuned with NetPerf in mind.
2659 *
2660 * The NAT network setup was selected here since it's the default one and the
2661 * slowest one. There is quite a bit of IPC with worker threads and packet
2662 * processing involved.
2663 *
2664 * Latency test is first up. This is a classic back and forth between the two
2665 * NetPerf instances, where the key measurement is the roundrip latency. The
2666 * values here are the lowest result over 3-6 runs.
2667 *
2668 * Against host system:
2669 * - 152 258 ns/roundtrip - 100% - regular VirtualBox SVM
2670 * - 271 059 ns/roundtrip - 178% - Hypercalls + VID.SYS in ring-0 with exit optimizations.
2671 * - 280 149 ns/roundtrip - 184% - Hypercalls + VID.SYS in ring-0
2672 * - 317 735 ns/roundtrip - 209% - Win HV API with exit optimizations.
2673 * - 342 440 ns/roundtrip - 225% - Win HV API
2674 *
2675 * Against a remote Windows 10 system over a 10Gbps link:
2676 * - 243 969 ns/roundtrip - 100% - regular VirtualBox SVM
2677 * - 384 427 ns/roundtrip - 158% - Win HV API with exit optimizations.
2678 * - 402 411 ns/roundtrip - 165% - Hypercalls + VID.SYS in ring-0
2679 * - 406 313 ns/roundtrip - 167% - Win HV API
2680 * - 413 160 ns/roundtrip - 169% - Hypercalls + VID.SYS in ring-0 with exit optimizations.
2681 *
2682 * What we see here is:
2683 *
2684 * - Consistent and signficant latency increase using Hyper-V compared
2685 * to directly harnessing AMD-V ourselves.
2686 *
2687 * - When talking to the host, it's clear that the hypercalls + VID.SYS
2688 * in ring-0 method pays off.
2689 *
2690 * - When talking to a different host, the numbers are closer and it
2691 * is not longer clear which Hyper-V execution method is better.
2692 *
2693 *
2694 * Throughput benchmarks are performed by one side pushing data full throttle
2695 * for 10 seconds (minus a 1 second at each end of the test), then reversing
2696 * the roles and measuring it in the other direction. The tests ran 3-5 times
2697 * and below are the highest and lowest results in each direction.
2698 *
2699 * Receiving from host system:
2700 * - Regular VirtualBox SVM:
2701 * Max: 96 907 549 bytes/s - 100%
2702 * Min: 86 912 095 bytes/s - 100%
2703 * - Hypercalls + VID.SYS in ring-0:
2704 * Max: 84 036 544 bytes/s - 87%
2705 * Min: 64 978 112 bytes/s - 75%
2706 * - Hypercalls + VID.SYS in ring-0 with exit optimizations:
2707 * Max: 77 760 699 bytes/s - 80%
2708 * Min: 72 677 171 bytes/s - 84%
2709 * - Win HV API with exit optimizations:
2710 * Max: 64 465 905 bytes/s - 67%
2711 * Min: 62 286 369 bytes/s - 72%
2712 * - Win HV API:
2713 * Max: 62 466 631 bytes/s - 64%
2714 * Min: 61 362 782 bytes/s - 70%
2715 *
2716 * Sending to the host system:
2717 * - Regular VirtualBox SVM:
2718 * Max: 87 728 652 bytes/s - 100%
2719 * Min: 86 923 198 bytes/s - 100%
2720 * - Hypercalls + VID.SYS in ring-0:
2721 * Max: 84 280 749 bytes/s - 96%
2722 * Min: 78 369 842 bytes/s - 90%
2723 * - Hypercalls + VID.SYS in ring-0 with exit optimizations:
2724 * Max: 84 119 932 bytes/s - 96%
2725 * Min: 77 396 811 bytes/s - 89%
2726 * - Win HV API:
2727 * Max: 81 714 377 bytes/s - 93%
2728 * Min: 78 697 419 bytes/s - 91%
2729 * - Win HV API with exit optimizations:
2730 * Max: 80 502 488 bytes/s - 91%
2731 * Min: 71 164 978 bytes/s - 82%
2732 *
2733 * Receiving from a remote Windows 10 system over a 10Gbps link:
2734 * - Hypercalls + VID.SYS in ring-0:
2735 * Max: 115 346 922 bytes/s - 136%
2736 * Min: 112 912 035 bytes/s - 137%
2737 * - Regular VirtualBox SVM:
2738 * Max: 84 517 504 bytes/s - 100%
2739 * Min: 82 597 049 bytes/s - 100%
2740 * - Hypercalls + VID.SYS in ring-0 with exit optimizations:
2741 * Max: 77 736 251 bytes/s - 92%
2742 * Min: 73 813 784 bytes/s - 89%
2743 * - Win HV API with exit optimizations:
2744 * Max: 63 035 587 bytes/s - 75%
2745 * Min: 57 538 380 bytes/s - 70%
2746 * - Win HV API:
2747 * Max: 62 279 185 bytes/s - 74%
2748 * Min: 56 813 866 bytes/s - 69%
2749 *
2750 * Sending to a remote Windows 10 system over a 10Gbps link:
2751 * - Win HV API with exit optimizations:
2752 * Max: 116 502 357 bytes/s - 103%
2753 * Min: 49 046 550 bytes/s - 59%
2754 * - Regular VirtualBox SVM:
2755 * Max: 113 030 991 bytes/s - 100%
2756 * Min: 83 059 511 bytes/s - 100%
2757 * - Hypercalls + VID.SYS in ring-0:
2758 * Max: 106 435 031 bytes/s - 94%
2759 * Min: 47 253 510 bytes/s - 57%
2760 * - Hypercalls + VID.SYS in ring-0 with exit optimizations:
2761 * Max: 94 842 287 bytes/s - 84%
2762 * Min: 68 362 172 bytes/s - 82%
2763 * - Win HV API:
2764 * Max: 65 165 225 bytes/s - 58%
2765 * Min: 47 246 573 bytes/s - 57%
2766 *
2767 * What we see here is:
2768 *
2769 * - Again consistent numbers when talking to the host. Showing that the
2770 * ring-0 approach is preferable to the ring-3 one.
2771 *
2772 * - Again when talking to a remote host, things get more difficult to
2773 * make sense of. The spread is larger and direct AMD-V gets beaten by
2774 * a different the Hyper-V approaches in each direction.
2775 *
2776 * - However, if we treat the first entry (remote host) as weird spikes, the
2777 * other entries are consistently worse compared to direct AMD-V. For the
2778 * send case we get really bad results for WinHV.
2779 *
2780 */
2781
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

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