VirtualBox

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

Last change on this file since 93444 was 93355, checked in by vboxsync, 3 years ago

VMM/NEM-win: We now require the PGM NEM mode so kicked out code not related to it, see bugref:10118 bugref:10162. bugref:10122

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

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