VirtualBox

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

Last change on this file since 72515 was 72488, checked in by vboxsync, 7 years ago

NEM,CPUM,EM: Don't sync in/out the entire state when leaving the inner NEM loop, only what IEM/TRPM might need. Speeds up MMIO and I/O requiring return to ring-3. bugref:9044

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

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