VirtualBox

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

Last change on this file since 107862 was 107862, checked in by vboxsync, 4 months ago

VMM/NEM-win: Export & import IA32_SPEC_CTRL state. jiraref:VBP-947 bugref:10738

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

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