VirtualBox

source: vbox/trunk/src/VBox/VMM/VMMR3/HM.cpp@ 80239

Last change on this file since 80239 was 80202, checked in by vboxsync, 5 years ago

VMM/HM: Build fix bugref:9217 bugref:9517

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 147.5 KB
Line 
1/* $Id: HM.cpp 80202 2019-08-09 05:02:52Z vboxsync $ */
2/** @file
3 * HM - Intel/AMD VM Hardware Support Manager.
4 */
5
6/*
7 * Copyright (C) 2006-2019 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18/** @page pg_hm HM - Hardware Assisted Virtualization Manager
19 *
20 * The HM manages guest execution using the VT-x and AMD-V CPU hardware
21 * extensions.
22 *
23 * {summary of what HM does}
24 *
25 * Hardware assisted virtualization manager was originally abbreviated HWACCM,
26 * however that was cumbersome to write and parse for such a central component,
27 * so it was shortened to HM when refactoring the code in the 4.3 development
28 * cycle.
29 *
30 * {add sections with more details}
31 *
32 * @sa @ref grp_hm
33 */
34
35
36/*********************************************************************************************************************************
37* Header Files *
38*********************************************************************************************************************************/
39#define VBOX_BUGREF_9217_PART_I
40#define LOG_GROUP LOG_GROUP_HM
41#define VMCPU_INCL_CPUM_GST_CTX
42#include <VBox/vmm/cpum.h>
43#include <VBox/vmm/stam.h>
44#include <VBox/vmm/mm.h>
45#include <VBox/vmm/em.h>
46#include <VBox/vmm/pdmapi.h>
47#include <VBox/vmm/pgm.h>
48#include <VBox/vmm/ssm.h>
49#include <VBox/vmm/gim.h>
50#include <VBox/vmm/trpm.h>
51#include <VBox/vmm/dbgf.h>
52#include <VBox/vmm/iom.h>
53#include <VBox/vmm/iem.h>
54#include <VBox/vmm/selm.h>
55#include <VBox/vmm/nem.h>
56#ifdef VBOX_WITH_REM
57# include <VBox/vmm/rem.h>
58#endif
59#include <VBox/vmm/hm_vmx.h>
60#include <VBox/vmm/hm_svm.h>
61#include "HMInternal.h"
62#include <VBox/vmm/vm.h>
63#include <VBox/vmm/uvm.h>
64#include <VBox/err.h>
65#include <VBox/param.h>
66
67#include <iprt/assert.h>
68#include <VBox/log.h>
69#include <iprt/asm.h>
70#include <iprt/asm-amd64-x86.h>
71#include <iprt/env.h>
72#include <iprt/thread.h>
73
74
75/*********************************************************************************************************************************
76* Defined Constants And Macros *
77*********************************************************************************************************************************/
78/** @def HMVMX_REPORT_FEAT
79 * Reports VT-x feature to the release log.
80 *
81 * @param a_uAllowed1 Mask of allowed-1 feature bits.
82 * @param a_uAllowed0 Mask of allowed-0 feature bits.
83 * @param a_StrDesc The description string to report.
84 * @param a_Featflag Mask of the feature to report.
85 */
86#define HMVMX_REPORT_FEAT(a_uAllowed1, a_uAllowed0, a_StrDesc, a_Featflag) \
87 do { \
88 if ((a_uAllowed1) & (a_Featflag)) \
89 { \
90 if ((a_uAllowed0) & (a_Featflag)) \
91 LogRel(("HM: " a_StrDesc " (must be set)\n")); \
92 else \
93 LogRel(("HM: " a_StrDesc "\n")); \
94 } \
95 else \
96 LogRel(("HM: " a_StrDesc " (must be cleared)\n")); \
97 } while (0)
98
99/** @def HMVMX_REPORT_ALLOWED_FEAT
100 * Reports an allowed VT-x feature to the release log.
101 *
102 * @param a_uAllowed1 Mask of allowed-1 feature bits.
103 * @param a_StrDesc The description string to report.
104 * @param a_FeatFlag Mask of the feature to report.
105 */
106#define HMVMX_REPORT_ALLOWED_FEAT(a_uAllowed1, a_StrDesc, a_FeatFlag) \
107 do { \
108 if ((a_uAllowed1) & (a_FeatFlag)) \
109 LogRel(("HM: " a_StrDesc "\n")); \
110 else \
111 LogRel(("HM: " a_StrDesc " not supported\n")); \
112 } while (0)
113
114/** @def HMVMX_REPORT_MSR_CAP
115 * Reports MSR feature capability.
116 *
117 * @param a_MsrCaps Mask of MSR feature bits.
118 * @param a_StrDesc The description string to report.
119 * @param a_fCap Mask of the feature to report.
120 */
121#define HMVMX_REPORT_MSR_CAP(a_MsrCaps, a_StrDesc, a_fCap) \
122 do { \
123 if ((a_MsrCaps) & (a_fCap)) \
124 LogRel(("HM: " a_StrDesc "\n")); \
125 } while (0)
126
127/** @def HMVMX_LOGREL_FEAT
128 * Dumps a feature flag from a bitmap of features to the release log.
129 *
130 * @param a_fVal The value of all the features.
131 * @param a_fMask The specific bitmask of the feature.
132 */
133#define HMVMX_LOGREL_FEAT(a_fVal, a_fMask) \
134 do { \
135 if ((a_fVal) & (a_fMask)) \
136 LogRel(("HM: %s\n", #a_fMask)); \
137 } while (0)
138
139
140/*********************************************************************************************************************************
141* Internal Functions *
142*********************************************************************************************************************************/
143static DECLCALLBACK(int) hmR3Save(PVM pVM, PSSMHANDLE pSSM);
144static DECLCALLBACK(int) hmR3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass);
145static DECLCALLBACK(void) hmR3InfoSvmNstGstVmcbCache(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs);
146static DECLCALLBACK(void) hmR3Info(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs);
147static DECLCALLBACK(void) hmR3InfoEventPending(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs);
148static int hmR3InitFinalizeR3(PVM pVM);
149static int hmR3InitFinalizeR0(PVM pVM);
150static int hmR3InitFinalizeR0Intel(PVM pVM);
151static int hmR3InitFinalizeR0Amd(PVM pVM);
152static int hmR3TermCPU(PVM pVM);
153
154
155
156/**
157 * Initializes the HM.
158 *
159 * This is the very first component to really do init after CFGM so that we can
160 * establish the predominant execution engine for the VM prior to initializing
161 * other modules. It takes care of NEM initialization if needed (HM disabled or
162 * not available in HW).
163 *
164 * If VT-x or AMD-V hardware isn't available, HM will try fall back on a native
165 * hypervisor API via NEM, and then back on raw-mode if that isn't available
166 * either. The fallback to raw-mode will not happen if /HM/HMForced is set
167 * (like for guest using SMP or 64-bit as well as for complicated guest like OS
168 * X, OS/2 and others).
169 *
170 * Note that a lot of the set up work is done in ring-0 and thus postponed till
171 * the ring-3 and ring-0 callback to HMR3InitCompleted.
172 *
173 * @returns VBox status code.
174 * @param pVM The cross context VM structure.
175 *
176 * @remarks Be careful with what we call here, since most of the VMM components
177 * are uninitialized.
178 */
179VMMR3_INT_DECL(int) HMR3Init(PVM pVM)
180{
181 LogFlowFunc(("\n"));
182
183 /*
184 * Assert alignment and sizes.
185 */
186 AssertCompileMemberAlignment(VM, hm.s, 32);
187 AssertCompile(sizeof(pVM->hm.s) <= sizeof(pVM->hm.padding));
188
189 /*
190 * Register the saved state data unit.
191 */
192 int rc = SSMR3RegisterInternal(pVM, "HWACCM", 0, HM_SAVED_STATE_VERSION, sizeof(HM),
193 NULL, NULL, NULL,
194 NULL, hmR3Save, NULL,
195 NULL, hmR3Load, NULL);
196 if (RT_FAILURE(rc))
197 return rc;
198
199 /*
200 * Register info handlers.
201 */
202 rc = DBGFR3InfoRegisterInternalEx(pVM, "hm", "Dumps HM info.", hmR3Info, DBGFINFO_FLAGS_ALL_EMTS);
203 AssertRCReturn(rc, rc);
204
205 rc = DBGFR3InfoRegisterInternalEx(pVM, "hmeventpending", "Dumps the pending HM event.", hmR3InfoEventPending,
206 DBGFINFO_FLAGS_ALL_EMTS);
207 AssertRCReturn(rc, rc);
208
209 rc = DBGFR3InfoRegisterInternalEx(pVM, "svmvmcbcache", "Dumps the HM SVM nested-guest VMCB cache.",
210 hmR3InfoSvmNstGstVmcbCache, DBGFINFO_FLAGS_ALL_EMTS);
211 AssertRCReturn(rc, rc);
212
213 /*
214 * Read configuration.
215 */
216 PCFGMNODE pCfgHm = CFGMR3GetChild(CFGMR3GetRoot(pVM), "HM/");
217
218 /*
219 * Validate the HM settings.
220 */
221 rc = CFGMR3ValidateConfig(pCfgHm, "/HM/",
222 "HMForced" /* implied 'true' these days */
223 "|UseNEMInstead"
224 "|FallbackToNEM"
225 "|EnableNestedPaging"
226 "|EnableUX"
227 "|EnableLargePages"
228 "|EnableVPID"
229 "|IBPBOnVMExit"
230 "|IBPBOnVMEntry"
231 "|SpecCtrlByHost"
232 "|L1DFlushOnSched"
233 "|L1DFlushOnVMEntry"
234 "|MDSClearOnSched"
235 "|MDSClearOnVMEntry"
236 "|TPRPatchingEnabled"
237 "|64bitEnabled"
238 "|Exclusive"
239 "|MaxResumeLoops"
240 "|VmxPleGap"
241 "|VmxPleWindow"
242 "|UseVmxPreemptTimer"
243 "|SvmPauseFilter"
244 "|SvmPauseFilterThreshold"
245 "|SvmVirtVmsaveVmload"
246 "|SvmVGif"
247 "|LovelyMesaDrvWorkaround",
248 "" /* pszValidNodes */, "HM" /* pszWho */, 0 /* uInstance */);
249 if (RT_FAILURE(rc))
250 return rc;
251
252 /** @cfgm{/HM/HMForced, bool, false}
253 * Forces hardware virtualization, no falling back on raw-mode. HM must be
254 * enabled, i.e. /HMEnabled must be true. */
255 bool fHMForced;
256 AssertRelease(pVM->fHMEnabled);
257 fHMForced = true;
258
259 /** @cfgm{/HM/UseNEMInstead, bool, true}
260 * Don't use HM, use NEM instead. */
261 bool fUseNEMInstead = false;
262 rc = CFGMR3QueryBoolDef(pCfgHm, "UseNEMInstead", &fUseNEMInstead, false);
263 AssertRCReturn(rc, rc);
264 if (fUseNEMInstead && pVM->fHMEnabled)
265 {
266 LogRel(("HM: Setting fHMEnabled to false because fUseNEMInstead is set.\n"));
267 pVM->fHMEnabled = false;
268 }
269
270 /** @cfgm{/HM/FallbackToNEM, bool, true}
271 * Enables fallback on NEM. */
272 bool fFallbackToNEM = true;
273 rc = CFGMR3QueryBoolDef(pCfgHm, "FallbackToNEM", &fFallbackToNEM, true);
274 AssertRCReturn(rc, rc);
275
276 /** @cfgm{/HM/EnableNestedPaging, bool, false}
277 * Enables nested paging (aka extended page tables). */
278 rc = CFGMR3QueryBoolDef(pCfgHm, "EnableNestedPaging", &pVM->hm.s.fAllowNestedPaging, false);
279 AssertRCReturn(rc, rc);
280
281 /** @cfgm{/HM/EnableUX, bool, true}
282 * Enables the VT-x unrestricted execution feature. */
283 rc = CFGMR3QueryBoolDef(pCfgHm, "EnableUX", &pVM->hm.s.vmx.fAllowUnrestricted, true);
284 AssertRCReturn(rc, rc);
285
286 /** @cfgm{/HM/EnableLargePages, bool, false}
287 * Enables using large pages (2 MB) for guest memory, thus saving on (nested)
288 * page table walking and maybe better TLB hit rate in some cases. */
289 rc = CFGMR3QueryBoolDef(pCfgHm, "EnableLargePages", &pVM->hm.s.fLargePages, false);
290 AssertRCReturn(rc, rc);
291
292 /** @cfgm{/HM/EnableVPID, bool, false}
293 * Enables the VT-x VPID feature. */
294 rc = CFGMR3QueryBoolDef(pCfgHm, "EnableVPID", &pVM->hm.s.vmx.fAllowVpid, false);
295 AssertRCReturn(rc, rc);
296
297 /** @cfgm{/HM/TPRPatchingEnabled, bool, false}
298 * Enables TPR patching for 32-bit windows guests with IO-APIC. */
299 rc = CFGMR3QueryBoolDef(pCfgHm, "TPRPatchingEnabled", &pVM->hm.s.fTprPatchingAllowed, false);
300 AssertRCReturn(rc, rc);
301
302 /** @cfgm{/HM/64bitEnabled, bool, 32-bit:false, 64-bit:true}
303 * Enables AMD64 cpu features.
304 * On 32-bit hosts this isn't default and require host CPU support. 64-bit hosts
305 * already have the support. */
306#ifdef VBOX_WITH_64_BITS_GUESTS
307 rc = CFGMR3QueryBoolDef(pCfgHm, "64bitEnabled", &pVM->hm.s.fAllow64BitGuests, HC_ARCH_BITS == 64);
308 AssertLogRelRCReturn(rc, rc);
309#else
310 pVM->hm.s.fAllow64BitGuests = false;
311#endif
312
313 /** @cfgm{/HM/VmxPleGap, uint32_t, 0}
314 * The pause-filter exiting gap in TSC ticks. When the number of ticks between
315 * two successive PAUSE instructions exceeds VmxPleGap, the CPU considers the
316 * latest PAUSE instruction to be start of a new PAUSE loop.
317 */
318 rc = CFGMR3QueryU32Def(pCfgHm, "VmxPleGap", &pVM->hm.s.vmx.cPleGapTicks, 0);
319 AssertRCReturn(rc, rc);
320
321 /** @cfgm{/HM/VmxPleWindow, uint32_t, 0}
322 * The pause-filter exiting window in TSC ticks. When the number of ticks
323 * between the current PAUSE instruction and first PAUSE of a loop exceeds
324 * VmxPleWindow, a VM-exit is triggered.
325 *
326 * Setting VmxPleGap and VmxPleGap to 0 disables pause-filter exiting.
327 */
328 rc = CFGMR3QueryU32Def(pCfgHm, "VmxPleWindow", &pVM->hm.s.vmx.cPleWindowTicks, 0);
329 AssertRCReturn(rc, rc);
330
331 /** @cfgm{/HM/SvmPauseFilterCount, uint16_t, 0}
332 * A counter that is decrement each time a PAUSE instruction is executed by the
333 * guest. When the counter is 0, a \#VMEXIT is triggered.
334 *
335 * Setting SvmPauseFilterCount to 0 disables pause-filter exiting.
336 */
337 rc = CFGMR3QueryU16Def(pCfgHm, "SvmPauseFilter", &pVM->hm.s.svm.cPauseFilter, 0);
338 AssertRCReturn(rc, rc);
339
340 /** @cfgm{/HM/SvmPauseFilterThreshold, uint16_t, 0}
341 * The pause filter threshold in ticks. When the elapsed time (in ticks) between
342 * two successive PAUSE instructions exceeds SvmPauseFilterThreshold, the
343 * PauseFilter count is reset to its initial value. However, if PAUSE is
344 * executed PauseFilter times within PauseFilterThreshold ticks, a VM-exit will
345 * be triggered.
346 *
347 * Requires SvmPauseFilterCount to be non-zero for pause-filter threshold to be
348 * activated.
349 */
350 rc = CFGMR3QueryU16Def(pCfgHm, "SvmPauseFilterThreshold", &pVM->hm.s.svm.cPauseFilterThresholdTicks, 0);
351 AssertRCReturn(rc, rc);
352
353 /** @cfgm{/HM/SvmVirtVmsaveVmload, bool, true}
354 * Whether to make use of virtualized VMSAVE/VMLOAD feature of the CPU if it's
355 * available. */
356 rc = CFGMR3QueryBoolDef(pCfgHm, "SvmVirtVmsaveVmload", &pVM->hm.s.svm.fVirtVmsaveVmload, true);
357 AssertRCReturn(rc, rc);
358
359 /** @cfgm{/HM/SvmVGif, bool, true}
360 * Whether to make use of Virtual GIF (Global Interrupt Flag) feature of the CPU
361 * if it's available. */
362 rc = CFGMR3QueryBoolDef(pCfgHm, "SvmVGif", &pVM->hm.s.svm.fVGif, true);
363 AssertRCReturn(rc, rc);
364
365 /** @cfgm{/HM/Exclusive, bool}
366 * Determines the init method for AMD-V and VT-x. If set to true, HM will do a
367 * global init for each host CPU. If false, we do local init each time we wish
368 * to execute guest code.
369 *
370 * On Windows, default is false due to the higher risk of conflicts with other
371 * hypervisors.
372 *
373 * On Mac OS X, this setting is ignored since the code does not handle local
374 * init when it utilizes the OS provided VT-x function, SUPR0EnableVTx().
375 */
376#if defined(RT_OS_DARWIN)
377 pVM->hm.s.fGlobalInit = true;
378#else
379 rc = CFGMR3QueryBoolDef(pCfgHm, "Exclusive", &pVM->hm.s.fGlobalInit,
380# if defined(RT_OS_WINDOWS)
381 false
382# else
383 true
384# endif
385 );
386 AssertLogRelRCReturn(rc, rc);
387#endif
388
389 /** @cfgm{/HM/MaxResumeLoops, uint32_t}
390 * The number of times to resume guest execution before we forcibly return to
391 * ring-3. The return value of RTThreadPreemptIsPendingTrusty in ring-0
392 * determines the default value. */
393 rc = CFGMR3QueryU32Def(pCfgHm, "MaxResumeLoops", &pVM->hm.s.cMaxResumeLoops, 0 /* set by R0 later */);
394 AssertLogRelRCReturn(rc, rc);
395
396 /** @cfgm{/HM/UseVmxPreemptTimer, bool}
397 * Whether to make use of the VMX-preemption timer feature of the CPU if it's
398 * available. */
399 rc = CFGMR3QueryBoolDef(pCfgHm, "UseVmxPreemptTimer", &pVM->hm.s.vmx.fUsePreemptTimer, true);
400 AssertLogRelRCReturn(rc, rc);
401
402 /** @cfgm{/HM/IBPBOnVMExit, bool}
403 * Costly paranoia setting. */
404 rc = CFGMR3QueryBoolDef(pCfgHm, "IBPBOnVMExit", &pVM->hm.s.fIbpbOnVmExit, false);
405 AssertLogRelRCReturn(rc, rc);
406
407 /** @cfgm{/HM/IBPBOnVMEntry, bool}
408 * Costly paranoia setting. */
409 rc = CFGMR3QueryBoolDef(pCfgHm, "IBPBOnVMEntry", &pVM->hm.s.fIbpbOnVmEntry, false);
410 AssertLogRelRCReturn(rc, rc);
411
412 /** @cfgm{/HM/L1DFlushOnSched, bool, true}
413 * CVE-2018-3646 workaround, ignored on CPUs that aren't affected. */
414 rc = CFGMR3QueryBoolDef(pCfgHm, "L1DFlushOnSched", &pVM->hm.s.fL1dFlushOnSched, true);
415 AssertLogRelRCReturn(rc, rc);
416
417 /** @cfgm{/HM/L1DFlushOnVMEntry, bool}
418 * CVE-2018-3646 workaround, ignored on CPUs that aren't affected. */
419 rc = CFGMR3QueryBoolDef(pCfgHm, "L1DFlushOnVMEntry", &pVM->hm.s.fL1dFlushOnVmEntry, false);
420 AssertLogRelRCReturn(rc, rc);
421
422 /* Disable L1DFlushOnSched if L1DFlushOnVMEntry is enabled. */
423 if (pVM->hm.s.fL1dFlushOnVmEntry)
424 pVM->hm.s.fL1dFlushOnSched = false;
425
426 /** @cfgm{/HM/SpecCtrlByHost, bool}
427 * Another expensive paranoia setting. */
428 rc = CFGMR3QueryBoolDef(pCfgHm, "SpecCtrlByHost", &pVM->hm.s.fSpecCtrlByHost, false);
429 AssertLogRelRCReturn(rc, rc);
430
431 /** @cfgm{/HM/MDSClearOnSched, bool, true}
432 * CVE-2018-12126, CVE-2018-12130, CVE-2018-12127, CVE-2019-11091 workaround,
433 * ignored on CPUs that aren't affected. */
434 rc = CFGMR3QueryBoolDef(pCfgHm, "MDSClearOnSched", &pVM->hm.s.fMdsClearOnSched, true);
435 AssertLogRelRCReturn(rc, rc);
436
437 /** @cfgm{/HM/MDSClearOnVmEntry, bool, false}
438 * CVE-2018-12126, CVE-2018-12130, CVE-2018-12127, CVE-2019-11091 workaround,
439 * ignored on CPUs that aren't affected. */
440 rc = CFGMR3QueryBoolDef(pCfgHm, "MDSClearOnVmEntry", &pVM->hm.s.fMdsClearOnVmEntry, false);
441 AssertLogRelRCReturn(rc, rc);
442
443 /* Disable MDSClearOnSched if MDSClearOnVmEntry is enabled. */
444 if (pVM->hm.s.fMdsClearOnVmEntry)
445 pVM->hm.s.fMdsClearOnSched = false;
446
447 /** @cfgm{/HM/LovelyMesaDrvWorkaround,bool}
448 * Workaround for mesa vmsvga 3d driver making incorrect assumptions about
449 * the hypervisor it is running under. */
450 bool f;
451 rc = CFGMR3QueryBoolDef(pCfgHm, "LovelyMesaDrvWorkaround", &f, false);
452 AssertLogRelRCReturn(rc, rc);
453 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
454 {
455 PVMCPU pVCpu = pVM->apCpusR3[idCpu];
456 pVCpu->hm.s.fTrapXcptGpForLovelyMesaDrv = f;
457 }
458
459 /*
460 * Check if VT-x or AMD-v support according to the users wishes.
461 */
462 /** @todo SUPR3QueryVTCaps won't catch VERR_VMX_IN_VMX_ROOT_MODE or
463 * VERR_SVM_IN_USE. */
464 if (pVM->fHMEnabled)
465 {
466 uint32_t fCaps;
467 rc = SUPR3QueryVTCaps(&fCaps);
468 if (RT_SUCCESS(rc))
469 {
470 if (fCaps & SUPVTCAPS_AMD_V)
471 {
472 pVM->hm.s.svm.fSupported = true;
473 LogRel(("HM: HMR3Init: AMD-V%s\n", fCaps & SUPVTCAPS_NESTED_PAGING ? " w/ nested paging" : ""));
474 VM_SET_MAIN_EXECUTION_ENGINE(pVM, VM_EXEC_ENGINE_HW_VIRT);
475 }
476 else if (fCaps & SUPVTCAPS_VT_X)
477 {
478 const char *pszWhy;
479 rc = SUPR3QueryVTxSupported(&pszWhy);
480 if (RT_SUCCESS(rc))
481 {
482 pVM->hm.s.vmx.fSupported = true;
483 LogRel(("HM: HMR3Init: VT-x%s%s%s\n",
484 fCaps & SUPVTCAPS_NESTED_PAGING ? " w/ nested paging" : "",
485 fCaps & SUPVTCAPS_VTX_UNRESTRICTED_GUEST ? " and unrestricted guest execution" : "",
486 (fCaps & (SUPVTCAPS_NESTED_PAGING | SUPVTCAPS_VTX_UNRESTRICTED_GUEST)) ? " hw support" : ""));
487 VM_SET_MAIN_EXECUTION_ENGINE(pVM, VM_EXEC_ENGINE_HW_VIRT);
488 }
489 else
490 {
491 /*
492 * Before failing, try fallback to NEM if we're allowed to do that.
493 */
494 pVM->fHMEnabled = false;
495 Assert(pVM->bMainExecutionEngine == VM_EXEC_ENGINE_NOT_SET);
496 if (fFallbackToNEM)
497 {
498 LogRel(("HM: HMR3Init: Attempting fall back to NEM: The host kernel does not support VT-x - %s\n", pszWhy));
499 int rc2 = NEMR3Init(pVM, true /*fFallback*/, fHMForced);
500
501 ASMCompilerBarrier(); /* NEMR3Init may have changed bMainExecutionEngine. */
502 if ( RT_SUCCESS(rc2)
503 && pVM->bMainExecutionEngine != VM_EXEC_ENGINE_NOT_SET)
504 rc = VINF_SUCCESS;
505 }
506 if (RT_FAILURE(rc))
507 return VMSetError(pVM, rc, RT_SRC_POS, "The host kernel does not support VT-x: %s\n", pszWhy);
508 }
509 }
510 else
511 AssertLogRelMsgFailedReturn(("SUPR3QueryVTCaps didn't return either AMD-V or VT-x flag set (%#x)!\n", fCaps),
512 VERR_INTERNAL_ERROR_5);
513
514 /*
515 * Disable nested paging and unrestricted guest execution now if they're
516 * configured so that CPUM can make decisions based on our configuration.
517 */
518 Assert(!pVM->hm.s.fNestedPaging);
519 if (pVM->hm.s.fAllowNestedPaging)
520 {
521 if (fCaps & SUPVTCAPS_NESTED_PAGING)
522 pVM->hm.s.fNestedPaging = true;
523 else
524 pVM->hm.s.fAllowNestedPaging = false;
525 }
526
527 if (fCaps & SUPVTCAPS_VT_X)
528 {
529 Assert(!pVM->hm.s.vmx.fUnrestrictedGuest);
530 if (pVM->hm.s.vmx.fAllowUnrestricted)
531 {
532 if ( (fCaps & SUPVTCAPS_VTX_UNRESTRICTED_GUEST)
533 && pVM->hm.s.fNestedPaging)
534 pVM->hm.s.vmx.fUnrestrictedGuest = true;
535 else
536 pVM->hm.s.vmx.fAllowUnrestricted = false;
537 }
538 }
539 }
540 else
541 {
542 const char *pszMsg;
543 switch (rc)
544 {
545 case VERR_UNSUPPORTED_CPU: pszMsg = "Unknown CPU, VT-x or AMD-v features cannot be ascertained"; break;
546 case VERR_VMX_NO_VMX: pszMsg = "VT-x is not available"; break;
547 case VERR_VMX_MSR_VMX_DISABLED: pszMsg = "VT-x is disabled in the BIOS"; break;
548 case VERR_VMX_MSR_ALL_VMX_DISABLED: pszMsg = "VT-x is disabled in the BIOS for all CPU modes"; break;
549 case VERR_VMX_MSR_LOCKING_FAILED: pszMsg = "Failed to enable and lock VT-x features"; break;
550 case VERR_SVM_NO_SVM: pszMsg = "AMD-V is not available"; break;
551 case VERR_SVM_DISABLED: pszMsg = "AMD-V is disabled in the BIOS (or by the host OS)"; break;
552 default:
553 return VMSetError(pVM, rc, RT_SRC_POS, "SUPR3QueryVTCaps failed with %Rrc", rc);
554 }
555
556 /*
557 * Before failing, try fallback to NEM if we're allowed to do that.
558 */
559 pVM->fHMEnabled = false;
560 if (fFallbackToNEM)
561 {
562 LogRel(("HM: HMR3Init: Attempting fall back to NEM: %s\n", pszMsg));
563 int rc2 = NEMR3Init(pVM, true /*fFallback*/, fHMForced);
564 ASMCompilerBarrier(); /* NEMR3Init may have changed bMainExecutionEngine. */
565 if ( RT_SUCCESS(rc2)
566 && pVM->bMainExecutionEngine != VM_EXEC_ENGINE_NOT_SET)
567 rc = VINF_SUCCESS;
568 }
569 if (RT_FAILURE(rc))
570 return VM_SET_ERROR(pVM, rc, pszMsg);
571 }
572 }
573 else
574 {
575 /*
576 * Disabled HM mean raw-mode, unless NEM is supposed to be used.
577 */
578 if (fUseNEMInstead)
579 {
580 rc = NEMR3Init(pVM, false /*fFallback*/, true);
581 ASMCompilerBarrier(); /* NEMR3Init may have changed bMainExecutionEngine. */
582 if (RT_FAILURE(rc))
583 return rc;
584 }
585 if ( pVM->bMainExecutionEngine == VM_EXEC_ENGINE_NOT_SET
586 || pVM->bMainExecutionEngine == VM_EXEC_ENGINE_RAW_MODE
587 || pVM->bMainExecutionEngine == VM_EXEC_ENGINE_HW_VIRT /* paranoia */)
588 return VM_SET_ERROR(pVM, rc, "Misconfigured VM: No guest execution engine available!");
589 }
590
591 Assert(pVM->bMainExecutionEngine != VM_EXEC_ENGINE_NOT_SET);
592 Assert(pVM->bMainExecutionEngine != VM_EXEC_ENGINE_RAW_MODE);
593 return VINF_SUCCESS;
594}
595
596
597/**
598 * Initializes HM components after ring-3 phase has been fully initialized.
599 *
600 * @returns VBox status code.
601 * @param pVM The cross context VM structure.
602 */
603static int hmR3InitFinalizeR3(PVM pVM)
604{
605 LogFlowFunc(("\n"));
606
607 if (!HMIsEnabled(pVM))
608 return VINF_SUCCESS;
609
610 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
611 {
612 PVMCPU pVCpu = pVM->apCpusR3[idCpu];
613 pVCpu->hm.s.fActive = false;
614 pVCpu->hm.s.fGIMTrapXcptUD = GIMShouldTrapXcptUD(pVCpu); /* Is safe to call now since GIMR3Init() has completed. */
615 }
616
617#ifdef VBOX_WITH_STATISTICS
618 STAM_REG(pVM, &pVM->hm.s.StatTprPatchSuccess, STAMTYPE_COUNTER, "/HM/TPR/Patch/Success", STAMUNIT_OCCURENCES, "Number of times an instruction was successfully patched.");
619 STAM_REG(pVM, &pVM->hm.s.StatTprPatchFailure, STAMTYPE_COUNTER, "/HM/TPR/Patch/Failed", STAMUNIT_OCCURENCES, "Number of unsuccessful patch attempts.");
620 STAM_REG(pVM, &pVM->hm.s.StatTprReplaceSuccessCr8, STAMTYPE_COUNTER, "/HM/TPR/Replace/SuccessCR8", STAMUNIT_OCCURENCES, "Number of instruction replacements by MOV CR8.");
621 STAM_REG(pVM, &pVM->hm.s.StatTprReplaceSuccessVmc, STAMTYPE_COUNTER, "/HM/TPR/Replace/SuccessVMC", STAMUNIT_OCCURENCES, "Number of instruction replacements by VMMCALL.");
622 STAM_REG(pVM, &pVM->hm.s.StatTprReplaceFailure, STAMTYPE_COUNTER, "/HM/TPR/Replace/Failed", STAMUNIT_OCCURENCES, "Number of unsuccessful replace attempts.");
623#endif
624
625 /*
626 * Statistics.
627 */
628 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
629 {
630 PVMCPU pVCpu = pVM->apCpusR3[idCpu];
631 PHMCPU pHmCpu = &pVCpu->hm.s;
632 int rc;
633
634# define HM_REG_STAT(a_pVar, a_enmType, s_enmVisibility, a_enmUnit, a_szNmFmt, a_szDesc) do { \
635 rc = STAMR3RegisterF(pVM, a_pVar, a_enmType, s_enmVisibility, a_enmUnit, a_szDesc, a_szNmFmt, idCpu); \
636 AssertRC(rc); \
637 } while (0)
638# define HM_REG_PROFILE(a_pVar, a_szNmFmt, a_szDesc) \
639 HM_REG_STAT(a_pVar, STAMTYPE_PROFILE, STAMVISIBILITY_USED, STAMUNIT_TICKS_PER_CALL, a_szNmFmt, a_szDesc)
640
641#ifdef VBOX_WITH_STATISTICS
642
643 HM_REG_PROFILE(&pHmCpu->StatPoke, "/PROF/CPU%u/HM/Poke", "Profiling of RTMpPokeCpu.");
644 HM_REG_PROFILE(&pHmCpu->StatSpinPoke, "/PROF/CPU%u/HM/PokeWait", "Profiling of poke wait.");
645 HM_REG_PROFILE(&pHmCpu->StatSpinPokeFailed, "/PROF/CPU%u/HM/PokeWaitFailed", "Profiling of poke wait when RTMpPokeCpu fails.");
646 HM_REG_PROFILE(&pHmCpu->StatEntry, "/PROF/CPU%u/HM/Entry", "Profiling of entry until entering GC.");
647 HM_REG_PROFILE(&pHmCpu->StatPreExit, "/PROF/CPU%u/HM/SwitchFromGC_1", "Profiling of pre-exit processing after returning from GC.");
648 HM_REG_PROFILE(&pHmCpu->StatExitHandling, "/PROF/CPU%u/HM/SwitchFromGC_2", "Profiling of exit handling (longjmps not included!)");
649 HM_REG_PROFILE(&pHmCpu->StatExitIO, "/PROF/CPU%u/HM/SwitchFromGC_2/IO", "I/O.");
650 HM_REG_PROFILE(&pHmCpu->StatExitMovCRx, "/PROF/CPU%u/HM/SwitchFromGC_2/MovCRx", "MOV CRx.");
651 HM_REG_PROFILE(&pHmCpu->StatExitXcptNmi, "/PROF/CPU%u/HM/SwitchFromGC_2/XcptNmi", "Exceptions, NMIs.");
652 HM_REG_PROFILE(&pHmCpu->StatExitVmentry, "/PROF/CPU%u/HM/SwitchFromGC_2/Vmentry", "VMLAUNCH/VMRESUME on Intel or VMRUN on AMD.");
653 HM_REG_PROFILE(&pHmCpu->StatImportGuestState, "/PROF/CPU%u/HM/ImportGuestState", "Profiling of importing guest state from hardware after VM-exit.");
654 HM_REG_PROFILE(&pHmCpu->StatExportGuestState, "/PROF/CPU%u/HM/ExportGuestState", "Profiling of exporting guest state to hardware before VM-entry.");
655 HM_REG_PROFILE(&pHmCpu->StatLoadGuestFpuState, "/PROF/CPU%u/HM/LoadGuestFpuState", "Profiling of CPUMR0LoadGuestFPU.");
656 HM_REG_PROFILE(&pHmCpu->StatInGC, "/PROF/CPU%u/HM/InGC", "Profiling of execution of guest-code in hardware.");
657# ifdef HM_PROFILE_EXIT_DISPATCH
658 HM_REG_STAT(&pHmCpu->StatExitDispatch, STAMTYPE_PROFILE_ADV, STAMVISIBILITY_USED, STAMUNIT_TICKS_PER_CALL,
659 "/PROF/CPU%u/HM/ExitDispatch", "Profiling the dispatching of exit handlers.");
660# endif
661#endif
662# define HM_REG_COUNTER(a, b, desc) HM_REG_STAT(a, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, b, desc)
663
664#ifdef VBOX_WITH_STATISTICS
665 HM_REG_COUNTER(&pHmCpu->StatExitAll, "/HM/CPU%u/Exit/All", "Total exits (including nested-guest exits).");
666 HM_REG_COUNTER(&pHmCpu->StatNestedExitAll, "/HM/CPU%u/Exit/NestedGuest/All", "Total nested-guest exits.");
667 HM_REG_COUNTER(&pHmCpu->StatExitShadowNM, "/HM/CPU%u/Exit/Trap/Shw/#NM", "Shadow #NM (device not available, no math co-processor) exception.");
668 HM_REG_COUNTER(&pHmCpu->StatExitGuestNM, "/HM/CPU%u/Exit/Trap/Gst/#NM", "Guest #NM (device not available, no math co-processor) exception.");
669 HM_REG_COUNTER(&pHmCpu->StatExitShadowPF, "/HM/CPU%u/Exit/Trap/Shw/#PF", "Shadow #PF (page fault) exception.");
670 HM_REG_COUNTER(&pHmCpu->StatExitShadowPFEM, "/HM/CPU%u/Exit/Trap/Shw/#PF-EM", "#PF (page fault) exception going back to ring-3 for emulating the instruction.");
671 HM_REG_COUNTER(&pHmCpu->StatExitGuestPF, "/HM/CPU%u/Exit/Trap/Gst/#PF", "Guest #PF (page fault) exception.");
672 HM_REG_COUNTER(&pHmCpu->StatExitGuestUD, "/HM/CPU%u/Exit/Trap/Gst/#UD", "Guest #UD (undefined opcode) exception.");
673 HM_REG_COUNTER(&pHmCpu->StatExitGuestSS, "/HM/CPU%u/Exit/Trap/Gst/#SS", "Guest #SS (stack-segment fault) exception.");
674 HM_REG_COUNTER(&pHmCpu->StatExitGuestNP, "/HM/CPU%u/Exit/Trap/Gst/#NP", "Guest #NP (segment not present) exception.");
675 HM_REG_COUNTER(&pHmCpu->StatExitGuestTS, "/HM/CPU%u/Exit/Trap/Gst/#TS", "Guest #TS (task switch) exception.");
676 HM_REG_COUNTER(&pHmCpu->StatExitGuestOF, "/HM/CPU%u/Exit/Trap/Gst/#OF", "Guest #OF (overflow) exception.");
677 HM_REG_COUNTER(&pHmCpu->StatExitGuestGP, "/HM/CPU%u/Exit/Trap/Gst/#GP", "Guest #GP (general protection) exception.");
678 HM_REG_COUNTER(&pHmCpu->StatExitGuestDE, "/HM/CPU%u/Exit/Trap/Gst/#DE", "Guest #DE (divide error) exception.");
679 HM_REG_COUNTER(&pHmCpu->StatExitGuestDF, "/HM/CPU%u/Exit/Trap/Gst/#DF", "Guest #DF (double fault) exception.");
680 HM_REG_COUNTER(&pHmCpu->StatExitGuestBR, "/HM/CPU%u/Exit/Trap/Gst/#BR", "Guest #BR (boundary range exceeded) exception.");
681 HM_REG_COUNTER(&pHmCpu->StatExitGuestAC, "/HM/CPU%u/Exit/Trap/Gst/#AC", "Guest #AC (alignment check) exception.");
682 HM_REG_COUNTER(&pHmCpu->StatExitGuestDB, "/HM/CPU%u/Exit/Trap/Gst/#DB", "Guest #DB (debug) exception.");
683 HM_REG_COUNTER(&pHmCpu->StatExitGuestMF, "/HM/CPU%u/Exit/Trap/Gst/#MF", "Guest #MF (x87 FPU error, math fault) exception.");
684 HM_REG_COUNTER(&pHmCpu->StatExitGuestBP, "/HM/CPU%u/Exit/Trap/Gst/#BP", "Guest #BP (breakpoint) exception.");
685 HM_REG_COUNTER(&pHmCpu->StatExitGuestXF, "/HM/CPU%u/Exit/Trap/Gst/#XF", "Guest #XF (extended math fault, SIMD FPU) exception.");
686 HM_REG_COUNTER(&pHmCpu->StatExitGuestXcpUnk, "/HM/CPU%u/Exit/Trap/Gst/Other", "Other guest exceptions.");
687 HM_REG_COUNTER(&pHmCpu->StatExitRdmsr, "/HM/CPU%u/Exit/Instr/Rdmsr", "MSR read.");
688 HM_REG_COUNTER(&pHmCpu->StatExitWrmsr, "/HM/CPU%u/Exit/Instr/Wrmsr", "MSR write.");
689 HM_REG_COUNTER(&pHmCpu->StatExitDRxWrite, "/HM/CPU%u/Exit/Instr/DR-Write", "Debug register write.");
690 HM_REG_COUNTER(&pHmCpu->StatExitDRxRead, "/HM/CPU%u/Exit/Instr/DR-Read", "Debug register read.");
691 HM_REG_COUNTER(&pHmCpu->StatExitCR0Read, "/HM/CPU%u/Exit/Instr/CR-Read/CR0", "CR0 read.");
692 HM_REG_COUNTER(&pHmCpu->StatExitCR2Read, "/HM/CPU%u/Exit/Instr/CR-Read/CR2", "CR2 read.");
693 HM_REG_COUNTER(&pHmCpu->StatExitCR3Read, "/HM/CPU%u/Exit/Instr/CR-Read/CR3", "CR3 read.");
694 HM_REG_COUNTER(&pHmCpu->StatExitCR4Read, "/HM/CPU%u/Exit/Instr/CR-Read/CR4", "CR4 read.");
695 HM_REG_COUNTER(&pHmCpu->StatExitCR8Read, "/HM/CPU%u/Exit/Instr/CR-Read/CR8", "CR8 read.");
696 HM_REG_COUNTER(&pHmCpu->StatExitCR0Write, "/HM/CPU%u/Exit/Instr/CR-Write/CR0", "CR0 write.");
697 HM_REG_COUNTER(&pHmCpu->StatExitCR2Write, "/HM/CPU%u/Exit/Instr/CR-Write/CR2", "CR2 write.");
698 HM_REG_COUNTER(&pHmCpu->StatExitCR3Write, "/HM/CPU%u/Exit/Instr/CR-Write/CR3", "CR3 write.");
699 HM_REG_COUNTER(&pHmCpu->StatExitCR4Write, "/HM/CPU%u/Exit/Instr/CR-Write/CR4", "CR4 write.");
700 HM_REG_COUNTER(&pHmCpu->StatExitCR8Write, "/HM/CPU%u/Exit/Instr/CR-Write/CR8", "CR8 write.");
701 HM_REG_COUNTER(&pHmCpu->StatExitClts, "/HM/CPU%u/Exit/Instr/CLTS", "CLTS instruction.");
702 HM_REG_COUNTER(&pHmCpu->StatExitLmsw, "/HM/CPU%u/Exit/Instr/LMSW", "LMSW instruction.");
703 HM_REG_COUNTER(&pHmCpu->StatExitXdtrAccess, "/HM/CPU%u/Exit/Instr/XdtrAccess", "GDTR, IDTR, LDTR access.");
704 HM_REG_COUNTER(&pHmCpu->StatExitIOWrite, "/HM/CPU%u/Exit/Instr/IO/Write", "I/O write.");
705 HM_REG_COUNTER(&pHmCpu->StatExitIORead, "/HM/CPU%u/Exit/Instr/IO/Read", "I/O read.");
706 HM_REG_COUNTER(&pHmCpu->StatExitIOStringWrite, "/HM/CPU%u/Exit/Instr/IO/WriteString", "String I/O write.");
707 HM_REG_COUNTER(&pHmCpu->StatExitIOStringRead, "/HM/CPU%u/Exit/Instr/IO/ReadString", "String I/O read.");
708 HM_REG_COUNTER(&pHmCpu->StatExitIntWindow, "/HM/CPU%u/Exit/IntWindow", "Interrupt-window exit. Guest is ready to receive interrupts.");
709 HM_REG_COUNTER(&pHmCpu->StatExitExtInt, "/HM/CPU%u/Exit/ExtInt", "Physical maskable interrupt (host).");
710#endif
711 HM_REG_COUNTER(&pHmCpu->StatExitHostNmiInGC, "/HM/CPU%u/Exit/HostNmiInGC", "Host NMI received while in guest context.");
712 HM_REG_COUNTER(&pHmCpu->StatExitHostNmiInGCIpi, "/HM/CPU%u/Exit/HostNmiInGCIpi", "Host NMI received while in guest context dispatched using IPIs.");
713#ifdef VBOX_WITH_STATISTICS
714 HM_REG_COUNTER(&pHmCpu->StatExitPreemptTimer, "/HM/CPU%u/Exit/PreemptTimer", "VMX-preemption timer expired.");
715 HM_REG_COUNTER(&pHmCpu->StatExitTprBelowThreshold, "/HM/CPU%u/Exit/TprBelowThreshold", "TPR lowered below threshold by the guest.");
716 HM_REG_COUNTER(&pHmCpu->StatExitTaskSwitch, "/HM/CPU%u/Exit/TaskSwitch", "Task switch caused through task gate in IDT.");
717 HM_REG_COUNTER(&pHmCpu->StatExitApicAccess, "/HM/CPU%u/Exit/ApicAccess", "APIC access. Guest attempted to access memory at a physical address on the APIC-access page.");
718
719 HM_REG_COUNTER(&pHmCpu->StatSwitchTprMaskedIrq, "/HM/CPU%u/Switch/TprMaskedIrq", "PDMGetInterrupt() signals TPR masks pending Irq.");
720 HM_REG_COUNTER(&pHmCpu->StatSwitchGuestIrq, "/HM/CPU%u/Switch/IrqPending", "PDMGetInterrupt() cleared behind our back!?!.");
721 HM_REG_COUNTER(&pHmCpu->StatSwitchPendingHostIrq, "/HM/CPU%u/Switch/PendingHostIrq", "Exit to ring-3 due to pending host interrupt before executing guest code.");
722 HM_REG_COUNTER(&pHmCpu->StatSwitchHmToR3FF, "/HM/CPU%u/Switch/HmToR3FF", "Exit to ring-3 due to pending timers, EMT rendezvous, critical section etc.");
723 HM_REG_COUNTER(&pHmCpu->StatSwitchVmReq, "/HM/CPU%u/Switch/VmReq", "Exit to ring-3 due to pending VM requests.");
724 HM_REG_COUNTER(&pHmCpu->StatSwitchPgmPoolFlush, "/HM/CPU%u/Switch/PgmPoolFlush", "Exit to ring-3 due to pending PGM pool flush.");
725 HM_REG_COUNTER(&pHmCpu->StatSwitchDma, "/HM/CPU%u/Switch/PendingDma", "Exit to ring-3 due to pending DMA requests.");
726 HM_REG_COUNTER(&pHmCpu->StatSwitchExitToR3, "/HM/CPU%u/Switch/ExitToR3", "Exit to ring-3 (total).");
727 HM_REG_COUNTER(&pHmCpu->StatSwitchLongJmpToR3, "/HM/CPU%u/Switch/LongJmpToR3", "Longjump to ring-3.");
728 HM_REG_COUNTER(&pHmCpu->StatSwitchMaxResumeLoops, "/HM/CPU%u/Switch/MaxResumeLoops", "Maximum VMRESUME inner-loop counter reached.");
729 HM_REG_COUNTER(&pHmCpu->StatSwitchHltToR3, "/HM/CPU%u/Switch/HltToR3", "HLT causing us to go to ring-3.");
730 HM_REG_COUNTER(&pHmCpu->StatSwitchApicAccessToR3, "/HM/CPU%u/Switch/ApicAccessToR3", "APIC access causing us to go to ring-3.");
731#endif
732 HM_REG_COUNTER(&pHmCpu->StatSwitchPreempt, "/HM/CPU%u/Switch/Preempting", "EMT has been preempted while in HM context.");
733#ifdef VBOX_WITH_STATISTICS
734 HM_REG_COUNTER(&pHmCpu->StatSwitchNstGstVmexit, "/HM/CPU%u/Switch/NstGstVmexit", "Nested-guest VM-exit occurred.");
735
736 HM_REG_COUNTER(&pHmCpu->StatInjectInterrupt, "/HM/CPU%u/EventInject/Interrupt", "Injected an external interrupt into the guest.");
737 HM_REG_COUNTER(&pHmCpu->StatInjectXcpt, "/HM/CPU%u/EventInject/Trap", "Injected an exception into the guest.");
738 HM_REG_COUNTER(&pHmCpu->StatInjectReflect, "/HM/CPU%u/EventInject/Reflect", "Reflecting an exception caused due to event injection.");
739 HM_REG_COUNTER(&pHmCpu->StatInjectConvertDF, "/HM/CPU%u/EventInject/ReflectDF", "Injected a converted #DF caused due to event injection.");
740 HM_REG_COUNTER(&pHmCpu->StatInjectInterpret, "/HM/CPU%u/EventInject/Interpret", "Falling back to interpreter for handling exception caused due to event injection.");
741 HM_REG_COUNTER(&pHmCpu->StatInjectReflectNPF, "/HM/CPU%u/EventInject/ReflectNPF", "Reflecting event that caused an EPT violation / nested #PF.");
742
743 HM_REG_COUNTER(&pHmCpu->StatFlushPage, "/HM/CPU%u/Flush/Page", "Invalidating a guest page on all guest CPUs.");
744 HM_REG_COUNTER(&pHmCpu->StatFlushPageManual, "/HM/CPU%u/Flush/Page/Virt", "Invalidating a guest page using guest-virtual address.");
745 HM_REG_COUNTER(&pHmCpu->StatFlushPhysPageManual, "/HM/CPU%u/Flush/Page/Phys", "Invalidating a guest page using guest-physical address.");
746 HM_REG_COUNTER(&pHmCpu->StatFlushTlb, "/HM/CPU%u/Flush/TLB", "Forcing a full guest-TLB flush (ring-0).");
747 HM_REG_COUNTER(&pHmCpu->StatFlushTlbManual, "/HM/CPU%u/Flush/TLB/Manual", "Request a full guest-TLB flush.");
748 HM_REG_COUNTER(&pHmCpu->StatFlushTlbNstGst, "/HM/CPU%u/Flush/TLB/NestedGuest", "Request a nested-guest-TLB flush.");
749 HM_REG_COUNTER(&pHmCpu->StatFlushTlbWorldSwitch, "/HM/CPU%u/Flush/TLB/CpuSwitch", "Forcing a full guest-TLB flush due to host-CPU reschedule or ASID-limit hit by another guest-VCPU.");
750 HM_REG_COUNTER(&pHmCpu->StatNoFlushTlbWorldSwitch, "/HM/CPU%u/Flush/TLB/Skipped", "No TLB flushing required.");
751 HM_REG_COUNTER(&pHmCpu->StatFlushEntire, "/HM/CPU%u/Flush/TLB/Entire", "Flush the entire TLB (host + guest).");
752 HM_REG_COUNTER(&pHmCpu->StatFlushAsid, "/HM/CPU%u/Flush/TLB/ASID", "Flushed guest-TLB entries for the current VPID.");
753 HM_REG_COUNTER(&pHmCpu->StatFlushNestedPaging, "/HM/CPU%u/Flush/TLB/NestedPaging", "Flushed guest-TLB entries for the current EPT.");
754 HM_REG_COUNTER(&pHmCpu->StatFlushTlbInvlpgVirt, "/HM/CPU%u/Flush/TLB/InvlpgVirt", "Invalidated a guest-TLB entry for a guest-virtual address.");
755 HM_REG_COUNTER(&pHmCpu->StatFlushTlbInvlpgPhys, "/HM/CPU%u/Flush/TLB/InvlpgPhys", "Currently not possible, flushes entire guest-TLB.");
756 HM_REG_COUNTER(&pHmCpu->StatTlbShootdown, "/HM/CPU%u/Flush/Shootdown/Page", "Inter-VCPU request to flush queued guest page.");
757 HM_REG_COUNTER(&pHmCpu->StatTlbShootdownFlush, "/HM/CPU%u/Flush/Shootdown/TLB", "Inter-VCPU request to flush entire guest-TLB.");
758
759 HM_REG_COUNTER(&pHmCpu->StatTscParavirt, "/HM/CPU%u/TSC/Paravirt", "Paravirtualized TSC in effect.");
760 HM_REG_COUNTER(&pHmCpu->StatTscOffset, "/HM/CPU%u/TSC/Offset", "TSC offsetting is in effect.");
761 HM_REG_COUNTER(&pHmCpu->StatTscIntercept, "/HM/CPU%u/TSC/Intercept", "Intercept TSC accesses.");
762
763 HM_REG_COUNTER(&pHmCpu->StatDRxArmed, "/HM/CPU%u/Debug/Armed", "Loaded guest-debug state while loading guest-state.");
764 HM_REG_COUNTER(&pHmCpu->StatDRxContextSwitch, "/HM/CPU%u/Debug/ContextSwitch", "Loaded guest-debug state on MOV DRx.");
765 HM_REG_COUNTER(&pHmCpu->StatDRxIoCheck, "/HM/CPU%u/Debug/IOCheck", "Checking for I/O breakpoint.");
766
767 HM_REG_COUNTER(&pHmCpu->StatExportMinimal, "/HM/CPU%u/Export/Minimal", "VM-entry exporting minimal guest-state.");
768 HM_REG_COUNTER(&pHmCpu->StatExportFull, "/HM/CPU%u/Export/Full", "VM-entry exporting the full guest-state.");
769 HM_REG_COUNTER(&pHmCpu->StatLoadGuestFpu, "/HM/CPU%u/Export/GuestFpu", "VM-entry loading the guest-FPU state.");
770 HM_REG_COUNTER(&pHmCpu->StatExportHostState, "/HM/CPU%u/Export/HostState", "VM-entry exporting host-state.");
771
772 HM_REG_COUNTER(&pHmCpu->StatVmxCheckBadRmSelBase, "/HM/CPU%u/VMXCheck/RMSelBase", "Could not use VMX due to unsuitable real-mode selector base.");
773 HM_REG_COUNTER(&pHmCpu->StatVmxCheckBadRmSelLimit, "/HM/CPU%u/VMXCheck/RMSelLimit", "Could not use VMX due to unsuitable real-mode selector limit.");
774 HM_REG_COUNTER(&pHmCpu->StatVmxCheckBadRmSelAttr, "/HM/CPU%u/VMXCheck/RMSelAttrs", "Could not use VMX due to unsuitable real-mode selector attributes.");
775
776 HM_REG_COUNTER(&pHmCpu->StatVmxCheckBadV86SelBase, "/HM/CPU%u/VMXCheck/V86SelBase", "Could not use VMX due to unsuitable v8086-mode selector base.");
777 HM_REG_COUNTER(&pHmCpu->StatVmxCheckBadV86SelLimit, "/HM/CPU%u/VMXCheck/V86SelLimit", "Could not use VMX due to unsuitable v8086-mode selector limit.");
778 HM_REG_COUNTER(&pHmCpu->StatVmxCheckBadV86SelAttr, "/HM/CPU%u/VMXCheck/V86SelAttrs", "Could not use VMX due to unsuitable v8086-mode selector attributes.");
779
780 HM_REG_COUNTER(&pHmCpu->StatVmxCheckRmOk, "/HM/CPU%u/VMXCheck/VMX_RM", "VMX execution in real (V86) mode OK.");
781 HM_REG_COUNTER(&pHmCpu->StatVmxCheckBadSel, "/HM/CPU%u/VMXCheck/Selector", "Could not use VMX due to unsuitable selector.");
782 HM_REG_COUNTER(&pHmCpu->StatVmxCheckBadRpl, "/HM/CPU%u/VMXCheck/RPL", "Could not use VMX due to unsuitable RPL.");
783 HM_REG_COUNTER(&pHmCpu->StatVmxCheckPmOk, "/HM/CPU%u/VMXCheck/VMX_PM", "VMX execution in protected mode OK.");
784
785 bool const fCpuSupportsVmx = ASMIsIntelCpu() || ASMIsViaCentaurCpu() || ASMIsShanghaiCpu();
786
787 /*
788 * Guest Exit reason stats.
789 */
790 pHmCpu->paStatExitReason = NULL;
791 rc = MMHyperAlloc(pVM, MAX_EXITREASON_STAT * sizeof(*pHmCpu->paStatExitReason), 0 /* uAlignment */, MM_TAG_HM,
792 (void **)&pHmCpu->paStatExitReason);
793 AssertRCReturn(rc, rc);
794
795 if (fCpuSupportsVmx)
796 {
797 for (int j = 0; j < MAX_EXITREASON_STAT; j++)
798 {
799 const char *pszExitName = HMGetVmxExitName(j);
800 if (pszExitName)
801 {
802 rc = STAMR3RegisterF(pVM, &pHmCpu->paStatExitReason[j], STAMTYPE_COUNTER, STAMVISIBILITY_USED,
803 STAMUNIT_OCCURENCES, pszExitName, "/HM/CPU%u/Exit/Reason/%02x", idCpu, j);
804 AssertRCReturn(rc, rc);
805 }
806 }
807 }
808 else
809 {
810 for (int j = 0; j < MAX_EXITREASON_STAT; j++)
811 {
812 const char *pszExitName = HMGetSvmExitName(j);
813 if (pszExitName)
814 {
815 rc = STAMR3RegisterF(pVM, &pHmCpu->paStatExitReason[j], STAMTYPE_COUNTER, STAMVISIBILITY_USED,
816 STAMUNIT_OCCURENCES, pszExitName, "/HM/CPU%u/Exit/Reason/%02x", idCpu, j);
817 AssertRC(rc);
818 }
819 }
820 }
821 HM_REG_COUNTER(&pHmCpu->StatExitReasonNpf, "/HM/CPU%u/Exit/Reason/#NPF", "Nested page faults");
822
823 pHmCpu->paStatExitReasonR0 = MMHyperR3ToR0(pVM, pHmCpu->paStatExitReason);
824 Assert(pHmCpu->paStatExitReasonR0 != NIL_RTR0PTR);
825
826#if defined(VBOX_WITH_NESTED_HWVIRT_SVM) || defined(VBOX_WITH_NESTED_HWVIRT_VMX)
827 /*
828 * Nested-guest VM-exit reason stats.
829 */
830 pHmCpu->paStatNestedExitReason = NULL;
831 rc = MMHyperAlloc(pVM, MAX_EXITREASON_STAT * sizeof(*pHmCpu->paStatNestedExitReason), 0 /* uAlignment */, MM_TAG_HM,
832 (void **)&pHmCpu->paStatNestedExitReason);
833 AssertRCReturn(rc, rc);
834 if (fCpuSupportsVmx)
835 {
836 for (int j = 0; j < MAX_EXITREASON_STAT; j++)
837 {
838 const char *pszExitName = HMGetVmxExitName(j);
839 if (pszExitName)
840 {
841 rc = STAMR3RegisterF(pVM, &pHmCpu->paStatNestedExitReason[j], STAMTYPE_COUNTER, STAMVISIBILITY_USED,
842 STAMUNIT_OCCURENCES, pszExitName, "/HM/CPU%u/Exit/NestedGuest/Reason/%02x", idCpu, j);
843 AssertRC(rc);
844 }
845 }
846 }
847 else
848 {
849 for (int j = 0; j < MAX_EXITREASON_STAT; j++)
850 {
851 const char *pszExitName = HMGetSvmExitName(j);
852 if (pszExitName)
853 {
854 rc = STAMR3RegisterF(pVM, &pHmCpu->paStatNestedExitReason[j], STAMTYPE_COUNTER, STAMVISIBILITY_USED,
855 STAMUNIT_OCCURENCES, pszExitName, "/HM/CPU%u/Exit/NestedGuest/Reason/%02x", idCpu, j);
856 AssertRC(rc);
857 }
858 }
859 }
860 HM_REG_COUNTER(&pHmCpu->StatNestedExitReasonNpf, "/HM/CPU%u/Exit/NestedGuest/Reason/#NPF", "Nested page faults");
861 pHmCpu->paStatNestedExitReasonR0 = MMHyperR3ToR0(pVM, pHmCpu->paStatNestedExitReason);
862 Assert(pHmCpu->paStatNestedExitReasonR0 != NIL_RTR0PTR);
863#endif
864
865 /*
866 * Injected events stats.
867 */
868 rc = MMHyperAlloc(pVM, sizeof(STAMCOUNTER) * 256, 8, MM_TAG_HM, (void **)&pHmCpu->paStatInjectedIrqs);
869 AssertRCReturn(rc, rc);
870 pHmCpu->paStatInjectedIrqsR0 = MMHyperR3ToR0(pVM, pHmCpu->paStatInjectedIrqs);
871 Assert(pHmCpu->paStatInjectedIrqsR0 != NIL_RTR0PTR);
872 for (unsigned j = 0; j < 255; j++)
873 {
874 rc = STAMR3RegisterF(pVM, &pHmCpu->paStatInjectedIrqs[j], STAMTYPE_COUNTER, STAMVISIBILITY_USED,
875 STAMUNIT_OCCURENCES, "Injected events.",
876 j < 0x20 ? "/HM/CPU%u/EventInject/InjectTrap/%02X" : "/HM/CPU%u/EventInject/InjectIRQ/%02X",
877 idCpu, j);
878 AssertRC(rc);
879 }
880
881#endif /* VBOX_WITH_STATISTICS */
882#undef HM_REG_COUNTER
883#undef HM_REG_PROFILE
884#undef HM_REG_STAT
885 }
886
887 return VINF_SUCCESS;
888}
889
890
891/**
892 * Called when a init phase has completed.
893 *
894 * @returns VBox status code.
895 * @param pVM The cross context VM structure.
896 * @param enmWhat The phase that completed.
897 */
898VMMR3_INT_DECL(int) HMR3InitCompleted(PVM pVM, VMINITCOMPLETED enmWhat)
899{
900 switch (enmWhat)
901 {
902 case VMINITCOMPLETED_RING3:
903 return hmR3InitFinalizeR3(pVM);
904 case VMINITCOMPLETED_RING0:
905 return hmR3InitFinalizeR0(pVM);
906 default:
907 return VINF_SUCCESS;
908 }
909}
910
911
912/**
913 * Turns off normal raw mode features.
914 *
915 * @param pVM The cross context VM structure.
916 */
917static void hmR3DisableRawMode(PVM pVM)
918{
919/** @todo r=bird: HM shouldn't be doing this crap. */
920 /* Reinit the paging mode to force the new shadow mode. */
921 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
922 {
923 PVMCPU pVCpu = pVM->apCpusR3[idCpu];
924 PGMHCChangeMode(pVM, pVCpu, PGMMODE_REAL);
925 }
926}
927
928
929/**
930 * Initialize VT-x or AMD-V.
931 *
932 * @returns VBox status code.
933 * @param pVM The cross context VM structure.
934 */
935static int hmR3InitFinalizeR0(PVM pVM)
936{
937 int rc;
938
939 if (!HMIsEnabled(pVM))
940 return VINF_SUCCESS;
941
942 /*
943 * Hack to allow users to work around broken BIOSes that incorrectly set
944 * EFER.SVME, which makes us believe somebody else is already using AMD-V.
945 */
946 if ( !pVM->hm.s.vmx.fSupported
947 && !pVM->hm.s.svm.fSupported
948 && pVM->hm.s.rcInit == VERR_SVM_IN_USE /* implies functional AMD-V */
949 && RTEnvExist("VBOX_HWVIRTEX_IGNORE_SVM_IN_USE"))
950 {
951 LogRel(("HM: VBOX_HWVIRTEX_IGNORE_SVM_IN_USE active!\n"));
952 pVM->hm.s.svm.fSupported = true;
953 pVM->hm.s.svm.fIgnoreInUseError = true;
954 pVM->hm.s.rcInit = VINF_SUCCESS;
955 }
956
957 /*
958 * Report ring-0 init errors.
959 */
960 if ( !pVM->hm.s.vmx.fSupported
961 && !pVM->hm.s.svm.fSupported)
962 {
963 LogRel(("HM: Failed to initialize VT-x / AMD-V: %Rrc\n", pVM->hm.s.rcInit));
964 LogRel(("HM: VMX MSR_IA32_FEATURE_CONTROL=%RX64\n", pVM->hm.s.vmx.Msrs.u64FeatCtrl));
965 switch (pVM->hm.s.rcInit)
966 {
967 case VERR_VMX_IN_VMX_ROOT_MODE:
968 return VM_SET_ERROR(pVM, VERR_VMX_IN_VMX_ROOT_MODE, "VT-x is being used by another hypervisor");
969 case VERR_VMX_NO_VMX:
970 return VM_SET_ERROR(pVM, VERR_VMX_NO_VMX, "VT-x is not available");
971 case VERR_VMX_MSR_VMX_DISABLED:
972 return VM_SET_ERROR(pVM, VERR_VMX_MSR_VMX_DISABLED, "VT-x is disabled in the BIOS");
973 case VERR_VMX_MSR_ALL_VMX_DISABLED:
974 return VM_SET_ERROR(pVM, VERR_VMX_MSR_ALL_VMX_DISABLED, "VT-x is disabled in the BIOS for all CPU modes");
975 case VERR_VMX_MSR_LOCKING_FAILED:
976 return VM_SET_ERROR(pVM, VERR_VMX_MSR_LOCKING_FAILED, "Failed to lock VT-x features while trying to enable VT-x");
977 case VERR_VMX_MSR_VMX_ENABLE_FAILED:
978 return VM_SET_ERROR(pVM, VERR_VMX_MSR_VMX_ENABLE_FAILED, "Failed to enable VT-x features");
979 case VERR_VMX_MSR_SMX_VMX_ENABLE_FAILED:
980 return VM_SET_ERROR(pVM, VERR_VMX_MSR_SMX_VMX_ENABLE_FAILED, "Failed to enable VT-x features in SMX mode");
981
982 case VERR_SVM_IN_USE:
983 return VM_SET_ERROR(pVM, VERR_SVM_IN_USE, "AMD-V is being used by another hypervisor");
984 case VERR_SVM_NO_SVM:
985 return VM_SET_ERROR(pVM, VERR_SVM_NO_SVM, "AMD-V is not available");
986 case VERR_SVM_DISABLED:
987 return VM_SET_ERROR(pVM, VERR_SVM_DISABLED, "AMD-V is disabled in the BIOS");
988 }
989 return VMSetError(pVM, pVM->hm.s.rcInit, RT_SRC_POS, "HM ring-0 init failed: %Rrc", pVM->hm.s.rcInit);
990 }
991
992 /*
993 * Enable VT-x or AMD-V on all host CPUs.
994 */
995 rc = SUPR3CallVMMR0Ex(pVM->pVMR0, 0 /*idCpu*/, VMMR0_DO_HM_ENABLE, 0, NULL);
996 if (RT_FAILURE(rc))
997 {
998 LogRel(("HM: Failed to enable, error %Rrc\n", rc));
999 HMR3CheckError(pVM, rc);
1000 return rc;
1001 }
1002
1003 /*
1004 * No TPR patching is required when the IO-APIC is not enabled for this VM.
1005 * (Main should have taken care of this already)
1006 */
1007 if (!PDMHasIoApic(pVM))
1008 {
1009 Assert(!pVM->hm.s.fTprPatchingAllowed); /* paranoia */
1010 pVM->hm.s.fTprPatchingAllowed = false;
1011 }
1012
1013 /*
1014 * Check if L1D flush is needed/possible.
1015 */
1016 if ( !pVM->cpum.ro.HostFeatures.fFlushCmd
1017 || pVM->cpum.ro.HostFeatures.enmMicroarch < kCpumMicroarch_Intel_Core7_Nehalem
1018 || pVM->cpum.ro.HostFeatures.enmMicroarch >= kCpumMicroarch_Intel_Core7_End
1019 || pVM->cpum.ro.HostFeatures.fArchVmmNeedNotFlushL1d
1020 || pVM->cpum.ro.HostFeatures.fArchRdclNo)
1021 pVM->hm.s.fL1dFlushOnSched = pVM->hm.s.fL1dFlushOnVmEntry = false;
1022
1023 /*
1024 * Check if MDS flush is needed/possible.
1025 * On atoms and knight family CPUs, we will only allow clearing on scheduling.
1026 */
1027 if ( !pVM->cpum.ro.HostFeatures.fMdsClear
1028 || pVM->cpum.ro.HostFeatures.fArchMdsNo)
1029 pVM->hm.s.fMdsClearOnSched = pVM->hm.s.fMdsClearOnVmEntry = false;
1030 else if ( ( pVM->cpum.ro.HostFeatures.enmMicroarch >= kCpumMicroarch_Intel_Atom_Airmount
1031 && pVM->cpum.ro.HostFeatures.enmMicroarch < kCpumMicroarch_Intel_Atom_End)
1032 || ( pVM->cpum.ro.HostFeatures.enmMicroarch >= kCpumMicroarch_Intel_Phi_KnightsLanding
1033 && pVM->cpum.ro.HostFeatures.enmMicroarch < kCpumMicroarch_Intel_Phi_End))
1034 {
1035 if (!pVM->hm.s.fMdsClearOnSched)
1036 pVM->hm.s.fMdsClearOnSched = pVM->hm.s.fMdsClearOnVmEntry;
1037 pVM->hm.s.fMdsClearOnVmEntry = false;
1038 }
1039 else if ( pVM->cpum.ro.HostFeatures.enmMicroarch < kCpumMicroarch_Intel_Core7_Nehalem
1040 || pVM->cpum.ro.HostFeatures.enmMicroarch >= kCpumMicroarch_Intel_Core7_End)
1041 pVM->hm.s.fMdsClearOnSched = pVM->hm.s.fMdsClearOnVmEntry = false;
1042
1043 /*
1044 * Sync options.
1045 */
1046 /** @todo Move this out of of CPUMCTX and into some ring-0 only HM structure.
1047 * That will require a little bit of work, of course. */
1048 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
1049 {
1050 PVMCPU pVCpu = pVM->apCpusR3[idCpu];
1051 PCPUMCTX pCpuCtx = &pVCpu->cpum.GstCtx;
1052 pCpuCtx->fWorldSwitcher &= ~(CPUMCTX_WSF_IBPB_EXIT | CPUMCTX_WSF_IBPB_ENTRY);
1053 if (pVM->cpum.ro.HostFeatures.fIbpb)
1054 {
1055 if (pVM->hm.s.fIbpbOnVmExit)
1056 pCpuCtx->fWorldSwitcher |= CPUMCTX_WSF_IBPB_EXIT;
1057 if (pVM->hm.s.fIbpbOnVmEntry)
1058 pCpuCtx->fWorldSwitcher |= CPUMCTX_WSF_IBPB_ENTRY;
1059 }
1060 if (pVM->cpum.ro.HostFeatures.fFlushCmd && pVM->hm.s.fL1dFlushOnVmEntry)
1061 pCpuCtx->fWorldSwitcher |= CPUMCTX_WSF_L1D_ENTRY;
1062 if (pVM->cpum.ro.HostFeatures.fMdsClear && pVM->hm.s.fMdsClearOnVmEntry)
1063 pCpuCtx->fWorldSwitcher |= CPUMCTX_WSF_MDS_ENTRY;
1064 if (idCpu == 0)
1065 LogRel(("HM: fWorldSwitcher=%#x (fIbpbOnVmExit=%RTbool fIbpbOnVmEntry=%RTbool fL1dFlushOnVmEntry=%RTbool); fL1dFlushOnSched=%RTbool fMdsClearOnVmEntry=%RTbool\n",
1066 pCpuCtx->fWorldSwitcher, pVM->hm.s.fIbpbOnVmExit, pVM->hm.s.fIbpbOnVmEntry, pVM->hm.s.fL1dFlushOnVmEntry,
1067 pVM->hm.s.fL1dFlushOnSched, pVM->hm.s.fMdsClearOnVmEntry));
1068 }
1069
1070 /*
1071 * Do the vendor specific initialization
1072 *
1073 * Note! We disable release log buffering here since we're doing relatively
1074 * lot of logging and doesn't want to hit the disk with each LogRel
1075 * statement.
1076 */
1077 AssertLogRelReturn(!pVM->hm.s.fInitialized, VERR_HM_IPE_5);
1078 bool fOldBuffered = RTLogRelSetBuffering(true /*fBuffered*/);
1079 if (pVM->hm.s.vmx.fSupported)
1080 rc = hmR3InitFinalizeR0Intel(pVM);
1081 else
1082 rc = hmR3InitFinalizeR0Amd(pVM);
1083 LogRel((pVM->hm.s.fGlobalInit ? "HM: VT-x/AMD-V init method: Global\n"
1084 : "HM: VT-x/AMD-V init method: Local\n"));
1085 RTLogRelSetBuffering(fOldBuffered);
1086 pVM->hm.s.fInitialized = true;
1087
1088 return rc;
1089}
1090
1091
1092/**
1093 * @callback_method_impl{FNPDMVMMDEVHEAPNOTIFY}
1094 */
1095static DECLCALLBACK(void) hmR3VmmDevHeapNotify(PVM pVM, void *pvAllocation, RTGCPHYS GCPhysAllocation)
1096{
1097 NOREF(pVM);
1098 NOREF(pvAllocation);
1099 NOREF(GCPhysAllocation);
1100}
1101
1102
1103/**
1104 * Returns a description of the VMCS (and associated regions') memory type given the
1105 * IA32_VMX_BASIC MSR.
1106 *
1107 * @returns The descriptive memory type.
1108 * @param uMsrVmxBasic IA32_VMX_BASIC MSR value.
1109 */
1110static const char *hmR3VmxGetMemTypeDesc(uint64_t uMsrVmxBasic)
1111{
1112 uint8_t const uMemType = RT_BF_GET(uMsrVmxBasic, VMX_BF_BASIC_VMCS_MEM_TYPE);
1113 switch (uMemType)
1114 {
1115 case VMX_BASIC_MEM_TYPE_WB: return "Write Back (WB)";
1116 case VMX_BASIC_MEM_TYPE_UC: return "Uncacheable (UC)";
1117 }
1118 return "Unknown";
1119}
1120
1121
1122/**
1123 * Returns a single-line description of all the activity-states supported by the CPU
1124 * given the IA32_VMX_MISC MSR.
1125 *
1126 * @returns All supported activity states.
1127 * @param uMsrMisc IA32_VMX_MISC MSR value.
1128 */
1129static const char *hmR3VmxGetActivityStateAllDesc(uint64_t uMsrMisc)
1130{
1131 static const char * const s_apszActStates[] =
1132 {
1133 "",
1134 " ( HLT )",
1135 " ( SHUTDOWN )",
1136 " ( HLT SHUTDOWN )",
1137 " ( SIPI_WAIT )",
1138 " ( HLT SIPI_WAIT )",
1139 " ( SHUTDOWN SIPI_WAIT )",
1140 " ( HLT SHUTDOWN SIPI_WAIT )"
1141 };
1142 uint8_t const idxActStates = RT_BF_GET(uMsrMisc, VMX_BF_MISC_ACTIVITY_STATES);
1143 Assert(idxActStates < RT_ELEMENTS(s_apszActStates));
1144 return s_apszActStates[idxActStates];
1145}
1146
1147
1148/**
1149 * Reports MSR_IA32_FEATURE_CONTROL MSR to the log.
1150 *
1151 * @param fFeatMsr The feature control MSR value.
1152 */
1153static void hmR3VmxReportFeatCtlMsr(uint64_t fFeatMsr)
1154{
1155 uint64_t const val = fFeatMsr;
1156 LogRel(("HM: MSR_IA32_FEATURE_CONTROL = %#RX64\n", val));
1157 HMVMX_REPORT_MSR_CAP(val, "LOCK", MSR_IA32_FEATURE_CONTROL_LOCK);
1158 HMVMX_REPORT_MSR_CAP(val, "SMX_VMXON", MSR_IA32_FEATURE_CONTROL_SMX_VMXON);
1159 HMVMX_REPORT_MSR_CAP(val, "VMXON", MSR_IA32_FEATURE_CONTROL_VMXON);
1160 HMVMX_REPORT_MSR_CAP(val, "SENTER_LOCAL_FN0", MSR_IA32_FEATURE_CONTROL_SENTER_LOCAL_FN_0);
1161 HMVMX_REPORT_MSR_CAP(val, "SENTER_LOCAL_FN1", MSR_IA32_FEATURE_CONTROL_SENTER_LOCAL_FN_1);
1162 HMVMX_REPORT_MSR_CAP(val, "SENTER_LOCAL_FN2", MSR_IA32_FEATURE_CONTROL_SENTER_LOCAL_FN_2);
1163 HMVMX_REPORT_MSR_CAP(val, "SENTER_LOCAL_FN3", MSR_IA32_FEATURE_CONTROL_SENTER_LOCAL_FN_3);
1164 HMVMX_REPORT_MSR_CAP(val, "SENTER_LOCAL_FN4", MSR_IA32_FEATURE_CONTROL_SENTER_LOCAL_FN_4);
1165 HMVMX_REPORT_MSR_CAP(val, "SENTER_LOCAL_FN5", MSR_IA32_FEATURE_CONTROL_SENTER_LOCAL_FN_5);
1166 HMVMX_REPORT_MSR_CAP(val, "SENTER_LOCAL_FN6", MSR_IA32_FEATURE_CONTROL_SENTER_LOCAL_FN_6);
1167 HMVMX_REPORT_MSR_CAP(val, "SENTER_GLOBAL_EN", MSR_IA32_FEATURE_CONTROL_SENTER_GLOBAL_EN);
1168 HMVMX_REPORT_MSR_CAP(val, "SGX_LAUNCH_EN", MSR_IA32_FEATURE_CONTROL_SGX_LAUNCH_EN);
1169 HMVMX_REPORT_MSR_CAP(val, "SGX_GLOBAL_EN", MSR_IA32_FEATURE_CONTROL_SGX_GLOBAL_EN);
1170 HMVMX_REPORT_MSR_CAP(val, "LMCE", MSR_IA32_FEATURE_CONTROL_LMCE);
1171 if (!(val & MSR_IA32_FEATURE_CONTROL_LOCK))
1172 LogRel(("HM: MSR_IA32_FEATURE_CONTROL lock bit not set, possibly bad hardware!\n"));
1173}
1174
1175
1176/**
1177 * Reports MSR_IA32_VMX_BASIC MSR to the log.
1178 *
1179 * @param uBasicMsr The VMX basic MSR value.
1180 */
1181static void hmR3VmxReportBasicMsr(uint64_t uBasicMsr)
1182{
1183 LogRel(("HM: MSR_IA32_VMX_BASIC = %#RX64\n", uBasicMsr));
1184 LogRel(("HM: VMCS id = %#x\n", RT_BF_GET(uBasicMsr, VMX_BF_BASIC_VMCS_ID)));
1185 LogRel(("HM: VMCS size = %u bytes\n", RT_BF_GET(uBasicMsr, VMX_BF_BASIC_VMCS_SIZE)));
1186 LogRel(("HM: VMCS physical address limit = %s\n", RT_BF_GET(uBasicMsr, VMX_BF_BASIC_PHYSADDR_WIDTH) ?
1187 "< 4 GB" : "None"));
1188 LogRel(("HM: VMCS memory type = %s\n", hmR3VmxGetMemTypeDesc(uBasicMsr)));
1189 LogRel(("HM: Dual-monitor treatment support = %RTbool\n", RT_BF_GET(uBasicMsr, VMX_BF_BASIC_DUAL_MON)));
1190 LogRel(("HM: OUTS & INS instruction-info = %RTbool\n", RT_BF_GET(uBasicMsr, VMX_BF_BASIC_VMCS_INS_OUTS)));
1191 LogRel(("HM: Supports true capability MSRs = %RTbool\n", RT_BF_GET(uBasicMsr, VMX_BF_BASIC_TRUE_CTLS)));
1192}
1193
1194
1195/**
1196 * Reports MSR_IA32_PINBASED_CTLS to the log.
1197 *
1198 * @param pVmxMsr Pointer to the VMX MSR.
1199 */
1200static void hmR3VmxReportPinBasedCtlsMsr(PCVMXCTLSMSR pVmxMsr)
1201{
1202 uint64_t const fAllowed1 = pVmxMsr->n.allowed1;
1203 uint64_t const fAllowed0 = pVmxMsr->n.allowed0;
1204 LogRel(("HM: MSR_IA32_VMX_PINBASED_CTLS = %#RX64\n", pVmxMsr->u));
1205 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "EXT_INT_EXIT", VMX_PIN_CTLS_EXT_INT_EXIT);
1206 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "NMI_EXIT", VMX_PIN_CTLS_NMI_EXIT);
1207 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "VIRTUAL_NMI", VMX_PIN_CTLS_VIRT_NMI);
1208 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "PREEMPT_TIMER", VMX_PIN_CTLS_PREEMPT_TIMER);
1209 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "POSTED_INT", VMX_PIN_CTLS_POSTED_INT);
1210}
1211
1212
1213/**
1214 * Reports MSR_IA32_VMX_PROCBASED_CTLS MSR to the log.
1215 *
1216 * @param pVmxMsr Pointer to the VMX MSR.
1217 */
1218static void hmR3VmxReportProcBasedCtlsMsr(PCVMXCTLSMSR pVmxMsr)
1219{
1220 uint64_t const fAllowed1 = pVmxMsr->n.allowed1;
1221 uint64_t const fAllowed0 = pVmxMsr->n.allowed0;
1222 LogRel(("HM: MSR_IA32_VMX_PROCBASED_CTLS = %#RX64\n", pVmxMsr->u));
1223 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "INT_WINDOW_EXIT", VMX_PROC_CTLS_INT_WINDOW_EXIT);
1224 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "USE_TSC_OFFSETTING", VMX_PROC_CTLS_USE_TSC_OFFSETTING);
1225 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "HLT_EXIT", VMX_PROC_CTLS_HLT_EXIT);
1226 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "INVLPG_EXIT", VMX_PROC_CTLS_INVLPG_EXIT);
1227 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "MWAIT_EXIT", VMX_PROC_CTLS_MWAIT_EXIT);
1228 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "RDPMC_EXIT", VMX_PROC_CTLS_RDPMC_EXIT);
1229 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "RDTSC_EXIT", VMX_PROC_CTLS_RDTSC_EXIT);
1230 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "CR3_LOAD_EXIT", VMX_PROC_CTLS_CR3_LOAD_EXIT);
1231 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "CR3_STORE_EXIT", VMX_PROC_CTLS_CR3_STORE_EXIT);
1232 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "CR8_LOAD_EXIT", VMX_PROC_CTLS_CR8_LOAD_EXIT);
1233 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "CR8_STORE_EXIT", VMX_PROC_CTLS_CR8_STORE_EXIT);
1234 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "USE_TPR_SHADOW", VMX_PROC_CTLS_USE_TPR_SHADOW);
1235 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "NMI_WINDOW_EXIT", VMX_PROC_CTLS_NMI_WINDOW_EXIT);
1236 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "MOV_DR_EXIT", VMX_PROC_CTLS_MOV_DR_EXIT);
1237 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "UNCOND_IO_EXIT", VMX_PROC_CTLS_UNCOND_IO_EXIT);
1238 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "USE_IO_BITMAPS", VMX_PROC_CTLS_USE_IO_BITMAPS);
1239 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "MONITOR_TRAP_FLAG", VMX_PROC_CTLS_MONITOR_TRAP_FLAG);
1240 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "USE_MSR_BITMAPS", VMX_PROC_CTLS_USE_MSR_BITMAPS);
1241 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "MONITOR_EXIT", VMX_PROC_CTLS_MONITOR_EXIT);
1242 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "PAUSE_EXIT", VMX_PROC_CTLS_PAUSE_EXIT);
1243 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "USE_SECONDARY_CTLS", VMX_PROC_CTLS_USE_SECONDARY_CTLS);
1244}
1245
1246
1247/**
1248 * Reports MSR_IA32_VMX_PROCBASED_CTLS2 MSR to the log.
1249 *
1250 * @param pVmxMsr Pointer to the VMX MSR.
1251 */
1252static void hmR3VmxReportProcBasedCtls2Msr(PCVMXCTLSMSR pVmxMsr)
1253{
1254 uint64_t const fAllowed1 = pVmxMsr->n.allowed1;
1255 uint64_t const fAllowed0 = pVmxMsr->n.allowed0;
1256 LogRel(("HM: MSR_IA32_VMX_PROCBASED_CTLS2 = %#RX64\n", pVmxMsr->u));
1257 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "VIRT_APIC_ACCESS", VMX_PROC_CTLS2_VIRT_APIC_ACCESS);
1258 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "EPT", VMX_PROC_CTLS2_EPT);
1259 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "DESC_TABLE_EXIT", VMX_PROC_CTLS2_DESC_TABLE_EXIT);
1260 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "RDTSCP", VMX_PROC_CTLS2_RDTSCP);
1261 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "VIRT_X2APIC_MODE", VMX_PROC_CTLS2_VIRT_X2APIC_MODE);
1262 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "VPID", VMX_PROC_CTLS2_VPID);
1263 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "WBINVD_EXIT", VMX_PROC_CTLS2_WBINVD_EXIT);
1264 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "UNRESTRICTED_GUEST", VMX_PROC_CTLS2_UNRESTRICTED_GUEST);
1265 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "APIC_REG_VIRT", VMX_PROC_CTLS2_APIC_REG_VIRT);
1266 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "VIRT_INT_DELIVERY", VMX_PROC_CTLS2_VIRT_INT_DELIVERY);
1267 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "PAUSE_LOOP_EXIT", VMX_PROC_CTLS2_PAUSE_LOOP_EXIT);
1268 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "RDRAND_EXIT", VMX_PROC_CTLS2_RDRAND_EXIT);
1269 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "INVPCID", VMX_PROC_CTLS2_INVPCID);
1270 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "VMFUNC", VMX_PROC_CTLS2_VMFUNC);
1271 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "VMCS_SHADOWING", VMX_PROC_CTLS2_VMCS_SHADOWING);
1272 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "ENCLS_EXIT", VMX_PROC_CTLS2_ENCLS_EXIT);
1273 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "RDSEED_EXIT", VMX_PROC_CTLS2_RDSEED_EXIT);
1274 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "PML", VMX_PROC_CTLS2_PML);
1275 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "EPT_VE", VMX_PROC_CTLS2_EPT_VE);
1276 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "CONCEAL_VMX_FROM_PT", VMX_PROC_CTLS2_CONCEAL_VMX_FROM_PT);
1277 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "XSAVES_XRSTORS", VMX_PROC_CTLS2_XSAVES_XRSTORS);
1278 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "MODE_BASED_EPT_PERM", VMX_PROC_CTLS2_MODE_BASED_EPT_PERM);
1279 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "SPPTP_EPT", VMX_PROC_CTLS2_SPPTP_EPT);
1280 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "PT_EPT", VMX_PROC_CTLS2_PT_EPT);
1281 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "TSC_SCALING", VMX_PROC_CTLS2_TSC_SCALING);
1282 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "USER_WAIT_PAUSE", VMX_PROC_CTLS2_USER_WAIT_PAUSE);
1283 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "ENCLV_EXIT", VMX_PROC_CTLS2_ENCLV_EXIT);
1284}
1285
1286
1287/**
1288 * Reports MSR_IA32_VMX_ENTRY_CTLS to the log.
1289 *
1290 * @param pVmxMsr Pointer to the VMX MSR.
1291 */
1292static void hmR3VmxReportEntryCtlsMsr(PCVMXCTLSMSR pVmxMsr)
1293{
1294 uint64_t const fAllowed1 = pVmxMsr->n.allowed1;
1295 uint64_t const fAllowed0 = pVmxMsr->n.allowed0;
1296 LogRel(("HM: MSR_IA32_VMX_ENTRY_CTLS = %#RX64\n", pVmxMsr->u));
1297 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "LOAD_DEBUG", VMX_ENTRY_CTLS_LOAD_DEBUG);
1298 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "IA32E_MODE_GUEST", VMX_ENTRY_CTLS_IA32E_MODE_GUEST);
1299 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "ENTRY_TO_SMM", VMX_ENTRY_CTLS_ENTRY_TO_SMM);
1300 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "DEACTIVATE_DUAL_MON", VMX_ENTRY_CTLS_DEACTIVATE_DUAL_MON);
1301 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "LOAD_PERF_MSR", VMX_ENTRY_CTLS_LOAD_PERF_MSR);
1302 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "LOAD_PAT_MSR", VMX_ENTRY_CTLS_LOAD_PAT_MSR);
1303 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "LOAD_EFER_MSR", VMX_ENTRY_CTLS_LOAD_EFER_MSR);
1304 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "LOAD_BNDCFGS_MSR", VMX_ENTRY_CTLS_LOAD_BNDCFGS_MSR);
1305 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "CONCEAL_VMX_FROM_PT", VMX_ENTRY_CTLS_CONCEAL_VMX_FROM_PT);
1306 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "LOAD_RTIT_CTL_MSR", VMX_ENTRY_CTLS_LOAD_RTIT_CTL_MSR);
1307}
1308
1309
1310/**
1311 * Reports MSR_IA32_VMX_EXIT_CTLS to the log.
1312 *
1313 * @param pVmxMsr Pointer to the VMX MSR.
1314 */
1315static void hmR3VmxReportExitCtlsMsr(PCVMXCTLSMSR pVmxMsr)
1316{
1317 uint64_t const fAllowed1 = pVmxMsr->n.allowed1;
1318 uint64_t const fAllowed0 = pVmxMsr->n.allowed0;
1319 LogRel(("HM: MSR_IA32_VMX_EXIT_CTLS = %#RX64\n", pVmxMsr->u));
1320 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "SAVE_DEBUG", VMX_EXIT_CTLS_SAVE_DEBUG);
1321 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "HOST_ADDR_SPACE_SIZE", VMX_EXIT_CTLS_HOST_ADDR_SPACE_SIZE);
1322 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "LOAD_PERF_MSR", VMX_EXIT_CTLS_LOAD_PERF_MSR);
1323 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "ACK_EXT_INT", VMX_EXIT_CTLS_ACK_EXT_INT);
1324 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "SAVE_PAT_MSR", VMX_EXIT_CTLS_SAVE_PAT_MSR);
1325 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "LOAD_PAT_MSR", VMX_EXIT_CTLS_LOAD_PAT_MSR);
1326 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "SAVE_EFER_MSR", VMX_EXIT_CTLS_SAVE_EFER_MSR);
1327 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "LOAD_EFER_MSR", VMX_EXIT_CTLS_LOAD_EFER_MSR);
1328 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "SAVE_PREEMPT_TIMER", VMX_EXIT_CTLS_SAVE_PREEMPT_TIMER);
1329 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "CLEAR_BNDCFGS_MSR", VMX_EXIT_CTLS_CLEAR_BNDCFGS_MSR);
1330 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "CONCEAL_VMX_FROM_PT", VMX_EXIT_CTLS_CONCEAL_VMX_FROM_PT);
1331 HMVMX_REPORT_FEAT(fAllowed1, fAllowed0, "CLEAR_RTIT_CTL_MSR", VMX_EXIT_CTLS_CLEAR_RTIT_CTL_MSR);
1332}
1333
1334
1335/**
1336 * Reports MSR_IA32_VMX_EPT_VPID_CAP MSR to the log.
1337 *
1338 * @param fCaps The VMX EPT/VPID capability MSR value.
1339 */
1340static void hmR3VmxReportEptVpidCapsMsr(uint64_t fCaps)
1341{
1342 LogRel(("HM: MSR_IA32_VMX_EPT_VPID_CAP = %#RX64\n", fCaps));
1343 HMVMX_REPORT_MSR_CAP(fCaps, "RWX_X_ONLY", MSR_IA32_VMX_EPT_VPID_CAP_RWX_X_ONLY);
1344 HMVMX_REPORT_MSR_CAP(fCaps, "PAGE_WALK_LENGTH_4", MSR_IA32_VMX_EPT_VPID_CAP_PAGE_WALK_LENGTH_4);
1345 HMVMX_REPORT_MSR_CAP(fCaps, "EMT_UC", MSR_IA32_VMX_EPT_VPID_CAP_EMT_UC);
1346 HMVMX_REPORT_MSR_CAP(fCaps, "EMT_WB", MSR_IA32_VMX_EPT_VPID_CAP_EMT_WB);
1347 HMVMX_REPORT_MSR_CAP(fCaps, "PDE_2M", MSR_IA32_VMX_EPT_VPID_CAP_PDE_2M);
1348 HMVMX_REPORT_MSR_CAP(fCaps, "PDPTE_1G", MSR_IA32_VMX_EPT_VPID_CAP_PDPTE_1G);
1349 HMVMX_REPORT_MSR_CAP(fCaps, "INVEPT", MSR_IA32_VMX_EPT_VPID_CAP_INVEPT);
1350 HMVMX_REPORT_MSR_CAP(fCaps, "EPT_ACCESS_DIRTY", MSR_IA32_VMX_EPT_VPID_CAP_EPT_ACCESS_DIRTY);
1351 HMVMX_REPORT_MSR_CAP(fCaps, "INVEPT_SINGLE_CONTEXT", MSR_IA32_VMX_EPT_VPID_CAP_INVEPT_SINGLE_CONTEXT);
1352 HMVMX_REPORT_MSR_CAP(fCaps, "INVEPT_ALL_CONTEXTS", MSR_IA32_VMX_EPT_VPID_CAP_INVEPT_ALL_CONTEXTS);
1353 HMVMX_REPORT_MSR_CAP(fCaps, "INVVPID", MSR_IA32_VMX_EPT_VPID_CAP_INVVPID);
1354 HMVMX_REPORT_MSR_CAP(fCaps, "INVVPID_INDIV_ADDR", MSR_IA32_VMX_EPT_VPID_CAP_INVVPID_INDIV_ADDR);
1355 HMVMX_REPORT_MSR_CAP(fCaps, "INVVPID_SINGLE_CONTEXT", MSR_IA32_VMX_EPT_VPID_CAP_INVVPID_SINGLE_CONTEXT);
1356 HMVMX_REPORT_MSR_CAP(fCaps, "INVVPID_ALL_CONTEXTS", MSR_IA32_VMX_EPT_VPID_CAP_INVVPID_ALL_CONTEXTS);
1357 HMVMX_REPORT_MSR_CAP(fCaps, "INVVPID_SINGLE_CONTEXT_RETAIN_GLOBALS", MSR_IA32_VMX_EPT_VPID_CAP_INVVPID_SINGLE_CONTEXT_RETAIN_GLOBALS);
1358}
1359
1360
1361/**
1362 * Reports MSR_IA32_VMX_MISC MSR to the log.
1363 *
1364 * @param pVM Pointer to the VM.
1365 * @param fMisc The VMX misc. MSR value.
1366 */
1367static void hmR3VmxReportMiscMsr(PVM pVM, uint64_t fMisc)
1368{
1369 LogRel(("HM: MSR_IA32_VMX_MISC = %#RX64\n", fMisc));
1370 uint8_t const cPreemptTimerShift = RT_BF_GET(fMisc, VMX_BF_MISC_PREEMPT_TIMER_TSC);
1371 if (cPreemptTimerShift == pVM->hm.s.vmx.cPreemptTimerShift)
1372 LogRel(("HM: PREEMPT_TIMER_TSC = %#x\n", cPreemptTimerShift));
1373 else
1374 {
1375 LogRel(("HM: PREEMPT_TIMER_TSC = %#x - erratum detected, using %#x instead\n", cPreemptTimerShift,
1376 pVM->hm.s.vmx.cPreemptTimerShift));
1377 }
1378 LogRel(("HM: EXIT_SAVE_EFER_LMA = %RTbool\n", RT_BF_GET(fMisc, VMX_BF_MISC_EXIT_SAVE_EFER_LMA)));
1379 LogRel(("HM: ACTIVITY_STATES = %#x%s\n", RT_BF_GET(fMisc, VMX_BF_MISC_ACTIVITY_STATES),
1380 hmR3VmxGetActivityStateAllDesc(fMisc)));
1381 LogRel(("HM: INTEL_PT = %RTbool\n", RT_BF_GET(fMisc, VMX_BF_MISC_INTEL_PT)));
1382 LogRel(("HM: SMM_READ_SMBASE_MSR = %RTbool\n", RT_BF_GET(fMisc, VMX_BF_MISC_SMM_READ_SMBASE_MSR)));
1383 LogRel(("HM: CR3_TARGET = %#x\n", RT_BF_GET(fMisc, VMX_BF_MISC_CR3_TARGET)));
1384 LogRel(("HM: MAX_MSR = %#x ( %u )\n", RT_BF_GET(fMisc, VMX_BF_MISC_MAX_MSRS),
1385 VMX_MISC_MAX_MSRS(fMisc)));
1386 LogRel(("HM: VMXOFF_BLOCK_SMI = %RTbool\n", RT_BF_GET(fMisc, VMX_BF_MISC_VMXOFF_BLOCK_SMI)));
1387 LogRel(("HM: VMWRITE_ALL = %RTbool\n", RT_BF_GET(fMisc, VMX_BF_MISC_VMWRITE_ALL)));
1388 LogRel(("HM: ENTRY_INJECT_SOFT_INT = %#x\n", RT_BF_GET(fMisc, VMX_BF_MISC_ENTRY_INJECT_SOFT_INT)));
1389 LogRel(("HM: MSEG_ID = %#x\n", RT_BF_GET(fMisc, VMX_BF_MISC_MSEG_ID)));
1390}
1391
1392
1393/**
1394 * Reports MSR_IA32_VMX_VMCS_ENUM MSR to the log.
1395 *
1396 * @param uVmcsEnum The VMX VMCS enum MSR value.
1397 */
1398static void hmR3VmxReportVmcsEnumMsr(uint64_t uVmcsEnum)
1399{
1400 LogRel(("HM: MSR_IA32_VMX_VMCS_ENUM = %#RX64\n", uVmcsEnum));
1401 LogRel(("HM: HIGHEST_IDX = %#x\n", RT_BF_GET(uVmcsEnum, VMX_BF_VMCS_ENUM_HIGHEST_IDX)));
1402}
1403
1404
1405/**
1406 * Reports MSR_IA32_VMX_VMFUNC MSR to the log.
1407 *
1408 * @param uVmFunc The VMX VMFUNC MSR value.
1409 */
1410static void hmR3VmxReportVmFuncMsr(uint64_t uVmFunc)
1411{
1412 LogRel(("HM: MSR_IA32_VMX_VMFUNC = %#RX64\n", uVmFunc));
1413 HMVMX_REPORT_ALLOWED_FEAT(uVmFunc, "EPTP_SWITCHING", RT_BF_GET(uVmFunc, VMX_BF_VMFUNC_EPTP_SWITCHING));
1414}
1415
1416
1417/**
1418 * Reports VMX CR0, CR4 fixed MSRs.
1419 *
1420 * @param pMsrs Pointer to the VMX MSRs.
1421 */
1422static void hmR3VmxReportCrFixedMsrs(PVMXMSRS pMsrs)
1423{
1424 LogRel(("HM: MSR_IA32_VMX_CR0_FIXED0 = %#RX64\n", pMsrs->u64Cr0Fixed0));
1425 LogRel(("HM: MSR_IA32_VMX_CR0_FIXED1 = %#RX64\n", pMsrs->u64Cr0Fixed1));
1426 LogRel(("HM: MSR_IA32_VMX_CR4_FIXED0 = %#RX64\n", pMsrs->u64Cr4Fixed0));
1427 LogRel(("HM: MSR_IA32_VMX_CR4_FIXED1 = %#RX64\n", pMsrs->u64Cr4Fixed1));
1428}
1429
1430
1431/**
1432 * Finish VT-x initialization (after ring-0 init).
1433 *
1434 * @returns VBox status code.
1435 * @param pVM The cross context VM structure.
1436 */
1437static int hmR3InitFinalizeR0Intel(PVM pVM)
1438{
1439 int rc;
1440
1441 Log(("pVM->hm.s.vmx.fSupported = %d\n", pVM->hm.s.vmx.fSupported));
1442 AssertLogRelReturn(pVM->hm.s.vmx.Msrs.u64FeatCtrl != 0, VERR_HM_IPE_4);
1443
1444 LogRel(("HM: Using VT-x implementation 3.0\n"));
1445 LogRel(("HM: Max resume loops = %u\n", pVM->hm.s.cMaxResumeLoops));
1446 LogRel(("HM: Host CR4 = %#RX64\n", pVM->hm.s.vmx.u64HostCr4));
1447 LogRel(("HM: Host EFER = %#RX64\n", pVM->hm.s.vmx.u64HostMsrEfer));
1448 LogRel(("HM: MSR_IA32_SMM_MONITOR_CTL = %#RX64\n", pVM->hm.s.vmx.u64HostSmmMonitorCtl));
1449
1450 hmR3VmxReportFeatCtlMsr(pVM->hm.s.vmx.Msrs.u64FeatCtrl);
1451 hmR3VmxReportBasicMsr(pVM->hm.s.vmx.Msrs.u64Basic);
1452
1453 hmR3VmxReportPinBasedCtlsMsr(&pVM->hm.s.vmx.Msrs.PinCtls);
1454 hmR3VmxReportProcBasedCtlsMsr(&pVM->hm.s.vmx.Msrs.ProcCtls);
1455 if (pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_SECONDARY_CTLS)
1456 hmR3VmxReportProcBasedCtls2Msr(&pVM->hm.s.vmx.Msrs.ProcCtls2);
1457
1458 hmR3VmxReportEntryCtlsMsr(&pVM->hm.s.vmx.Msrs.EntryCtls);
1459 hmR3VmxReportExitCtlsMsr(&pVM->hm.s.vmx.Msrs.ExitCtls);
1460
1461 if (RT_BF_GET(pVM->hm.s.vmx.Msrs.u64Basic, VMX_BF_BASIC_TRUE_CTLS))
1462 {
1463 /* We don't extensively dump the true capability MSRs as we don't use them, see @bugref{9180#c5}. */
1464 LogRel(("HM: MSR_IA32_VMX_TRUE_PINBASED_CTLS = %#RX64\n", pVM->hm.s.vmx.Msrs.TruePinCtls));
1465 LogRel(("HM: MSR_IA32_VMX_TRUE_PROCBASED_CTLS = %#RX64\n", pVM->hm.s.vmx.Msrs.TrueProcCtls));
1466 LogRel(("HM: MSR_IA32_VMX_TRUE_ENTRY_CTLS = %#RX64\n", pVM->hm.s.vmx.Msrs.TrueEntryCtls));
1467 LogRel(("HM: MSR_IA32_VMX_TRUE_EXIT_CTLS = %#RX64\n", pVM->hm.s.vmx.Msrs.TrueExitCtls));
1468 }
1469
1470 hmR3VmxReportMiscMsr(pVM, pVM->hm.s.vmx.Msrs.u64Misc);
1471 hmR3VmxReportVmcsEnumMsr(pVM->hm.s.vmx.Msrs.u64VmcsEnum);
1472 if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps)
1473 hmR3VmxReportEptVpidCapsMsr(pVM->hm.s.vmx.Msrs.u64EptVpidCaps);
1474 if (pVM->hm.s.vmx.Msrs.u64VmFunc)
1475 hmR3VmxReportVmFuncMsr(pVM->hm.s.vmx.Msrs.u64VmFunc);
1476 hmR3VmxReportCrFixedMsrs(&pVM->hm.s.vmx.Msrs);
1477
1478 LogRel(("HM: APIC-access page physaddr = %#RHp\n", pVM->hm.s.vmx.HCPhysApicAccess));
1479 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
1480 {
1481 PCVMXVMCSINFO pVmcsInfo = &pVM->apCpusR3[idCpu]->hm.s.vmx.VmcsInfo;
1482 LogRel(("HM: VCPU%3d: MSR bitmap physaddr = %#RHp\n", idCpu, pVmcsInfo->HCPhysMsrBitmap));
1483 LogRel(("HM: VCPU%3d: VMCS physaddr = %#RHp\n", idCpu, pVmcsInfo->HCPhysVmcs));
1484 }
1485#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
1486 if (pVM->cpum.ro.GuestFeatures.fVmx)
1487 {
1488 LogRel(("HM: Nested-guest:\n"));
1489 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
1490 {
1491 PCVMXVMCSINFO pVmcsInfoNstGst = &pVM->apCpusR3[idCpu]->hm.s.vmx.VmcsInfoNstGst;
1492 LogRel(("HM: VCPU%3d: MSR bitmap physaddr = %#RHp\n", idCpu, pVmcsInfoNstGst->HCPhysMsrBitmap));
1493 LogRel(("HM: VCPU%3d: VMCS physaddr = %#RHp\n", idCpu, pVmcsInfoNstGst->HCPhysVmcs));
1494 }
1495 }
1496#endif
1497
1498 /*
1499 * EPT and unrestricted guest execution are determined in HMR3Init, verify the sanity of that.
1500 */
1501 AssertLogRelReturn( !pVM->hm.s.fNestedPaging
1502 || (pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_EPT),
1503 VERR_HM_IPE_1);
1504 AssertLogRelReturn( !pVM->hm.s.vmx.fUnrestrictedGuest
1505 || ( (pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_UNRESTRICTED_GUEST)
1506 && pVM->hm.s.fNestedPaging),
1507 VERR_HM_IPE_1);
1508
1509 /*
1510 * Disallow RDTSCP in the guest if there is no secondary process-based VM execution controls as otherwise
1511 * RDTSCP would cause a #UD. There might be no CPUs out there where this happens, as RDTSCP was introduced
1512 * in Nehalems and secondary VM exec. controls should be supported in all of them, but nonetheless it's Intel...
1513 */
1514 if ( !(pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_SECONDARY_CTLS)
1515 && CPUMR3GetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_RDTSCP))
1516 {
1517 CPUMR3ClearGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_RDTSCP);
1518 LogRel(("HM: Disabled RDTSCP\n"));
1519 }
1520
1521 if (!pVM->hm.s.vmx.fUnrestrictedGuest)
1522 {
1523 /* Allocate three pages for the TSS we need for real mode emulation. (2 pages for the IO bitmap) */
1524 rc = PDMR3VmmDevHeapAlloc(pVM, HM_VTX_TOTAL_DEVHEAP_MEM, hmR3VmmDevHeapNotify, (RTR3PTR *)&pVM->hm.s.vmx.pRealModeTSS);
1525 if (RT_SUCCESS(rc))
1526 {
1527 /* The IO bitmap starts right after the virtual interrupt redirection bitmap.
1528 Refer Intel spec. 20.3.3 "Software Interrupt Handling in Virtual-8086 mode"
1529 esp. Figure 20-5.*/
1530 ASMMemZero32(pVM->hm.s.vmx.pRealModeTSS, sizeof(*pVM->hm.s.vmx.pRealModeTSS));
1531 pVM->hm.s.vmx.pRealModeTSS->offIoBitmap = sizeof(*pVM->hm.s.vmx.pRealModeTSS);
1532
1533 /* Bit set to 0 means software interrupts are redirected to the
1534 8086 program interrupt handler rather than switching to
1535 protected-mode handler. */
1536 memset(pVM->hm.s.vmx.pRealModeTSS->IntRedirBitmap, 0, sizeof(pVM->hm.s.vmx.pRealModeTSS->IntRedirBitmap));
1537
1538 /* Allow all port IO, so that port IO instructions do not cause
1539 exceptions and would instead cause a VM-exit (based on VT-x's
1540 IO bitmap which we currently configure to always cause an exit). */
1541 memset(pVM->hm.s.vmx.pRealModeTSS + 1, 0, PAGE_SIZE * 2);
1542 *((unsigned char *)pVM->hm.s.vmx.pRealModeTSS + HM_VTX_TSS_SIZE - 2) = 0xff;
1543
1544 /*
1545 * Construct a 1024 element page directory with 4 MB pages for the identity mapped
1546 * page table used in real and protected mode without paging with EPT.
1547 */
1548 pVM->hm.s.vmx.pNonPagingModeEPTPageTable = (PX86PD)((char *)pVM->hm.s.vmx.pRealModeTSS + PAGE_SIZE * 3);
1549 for (uint32_t i = 0; i < X86_PG_ENTRIES; i++)
1550 {
1551 pVM->hm.s.vmx.pNonPagingModeEPTPageTable->a[i].u = _4M * i;
1552 pVM->hm.s.vmx.pNonPagingModeEPTPageTable->a[i].u |= X86_PDE4M_P | X86_PDE4M_RW | X86_PDE4M_US
1553 | X86_PDE4M_A | X86_PDE4M_D | X86_PDE4M_PS
1554 | X86_PDE4M_G;
1555 }
1556
1557 /* We convert it here every time as PCI regions could be reconfigured. */
1558 if (PDMVmmDevHeapIsEnabled(pVM))
1559 {
1560 RTGCPHYS GCPhys;
1561 rc = PDMVmmDevHeapR3ToGCPhys(pVM, pVM->hm.s.vmx.pRealModeTSS, &GCPhys);
1562 AssertRCReturn(rc, rc);
1563 LogRel(("HM: Real Mode TSS guest physaddr = %#RGp\n", GCPhys));
1564
1565 rc = PDMVmmDevHeapR3ToGCPhys(pVM, pVM->hm.s.vmx.pNonPagingModeEPTPageTable, &GCPhys);
1566 AssertRCReturn(rc, rc);
1567 LogRel(("HM: Non-Paging Mode EPT CR3 = %#RGp\n", GCPhys));
1568 }
1569 }
1570 else
1571 {
1572 LogRel(("HM: No real mode VT-x support (PDMR3VMMDevHeapAlloc returned %Rrc)\n", rc));
1573 pVM->hm.s.vmx.pRealModeTSS = NULL;
1574 pVM->hm.s.vmx.pNonPagingModeEPTPageTable = NULL;
1575 return VMSetError(pVM, rc, RT_SRC_POS,
1576 "HM failure: No real mode VT-x support (PDMR3VMMDevHeapAlloc returned %Rrc)", rc);
1577 }
1578 }
1579
1580 LogRel((pVM->hm.s.fAllow64BitGuests ? "HM: Guest support: 32-bit and 64-bit\n"
1581 : "HM: Guest support: 32-bit only\n"));
1582
1583 /*
1584 * Call ring-0 to set up the VM.
1585 */
1586 rc = SUPR3CallVMMR0Ex(pVM->pVMR0, 0 /* idCpu */, VMMR0_DO_HM_SETUP_VM, 0 /* u64Arg */, NULL /* pReqHdr */);
1587 if (rc != VINF_SUCCESS)
1588 {
1589 LogRel(("HM: VMX setup failed with rc=%Rrc!\n", rc));
1590 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
1591 {
1592 PVMCPU pVCpu = pVM->apCpusR3[idCpu];
1593 LogRel(("HM: CPU[%u] Last instruction error %#x\n", idCpu, pVCpu->hm.s.vmx.LastError.u32InstrError));
1594 LogRel(("HM: CPU[%u] HM error %#x (%u)\n", idCpu, pVCpu->hm.s.u32HMError, pVCpu->hm.s.u32HMError));
1595 }
1596 HMR3CheckError(pVM, rc);
1597 return VMSetError(pVM, rc, RT_SRC_POS, "VT-x setup failed: %Rrc", rc);
1598 }
1599
1600 LogRel(("HM: Supports VMCS EFER fields = %RTbool\n", pVM->hm.s.vmx.fSupportsVmcsEfer));
1601 LogRel(("HM: Enabled VMX\n"));
1602 pVM->hm.s.vmx.fEnabled = true;
1603
1604 hmR3DisableRawMode(pVM); /** @todo make this go away! */
1605
1606 /*
1607 * Change the CPU features.
1608 */
1609 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_SEP);
1610 if (pVM->hm.s.fAllow64BitGuests)
1611 {
1612 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_PAE);
1613 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_LONG_MODE);
1614 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_SYSCALL); /* 64 bits only on Intel CPUs */
1615 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_LAHF);
1616 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_NX);
1617 }
1618 /* Turn on NXE if PAE has been enabled *and* the host has turned on NXE
1619 (we reuse the host EFER in the switcher). */
1620 /** @todo this needs to be fixed properly!! */
1621 else if (CPUMR3GetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_PAE))
1622 {
1623 if (pVM->hm.s.vmx.u64HostMsrEfer & MSR_K6_EFER_NXE)
1624 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_NX);
1625 else
1626 LogRel(("HM: NX not enabled on the host, unavailable to PAE guest\n"));
1627 }
1628
1629 /*
1630 * Log configuration details.
1631 */
1632 if (pVM->hm.s.fNestedPaging)
1633 {
1634 LogRel(("HM: Enabled nested paging\n"));
1635 if (pVM->hm.s.vmx.enmTlbFlushEpt == VMXTLBFLUSHEPT_SINGLE_CONTEXT)
1636 LogRel(("HM: EPT flush type = Single context\n"));
1637 else if (pVM->hm.s.vmx.enmTlbFlushEpt == VMXTLBFLUSHEPT_ALL_CONTEXTS)
1638 LogRel(("HM: EPT flush type = All contexts\n"));
1639 else if (pVM->hm.s.vmx.enmTlbFlushEpt == VMXTLBFLUSHEPT_NOT_SUPPORTED)
1640 LogRel(("HM: EPT flush type = Not supported\n"));
1641 else
1642 LogRel(("HM: EPT flush type = %#x\n", pVM->hm.s.vmx.enmTlbFlushEpt));
1643
1644 if (pVM->hm.s.vmx.fUnrestrictedGuest)
1645 LogRel(("HM: Enabled unrestricted guest execution\n"));
1646
1647 if (pVM->hm.s.fLargePages)
1648 {
1649 /* Use large (2 MB) pages for our EPT PDEs where possible. */
1650 PGMSetLargePageUsage(pVM, true);
1651 LogRel(("HM: Enabled large page support\n"));
1652 }
1653 }
1654 else
1655 Assert(!pVM->hm.s.vmx.fUnrestrictedGuest);
1656
1657 if (pVM->hm.s.vmx.fVpid)
1658 {
1659 LogRel(("HM: Enabled VPID\n"));
1660 if (pVM->hm.s.vmx.enmTlbFlushVpid == VMXTLBFLUSHVPID_INDIV_ADDR)
1661 LogRel(("HM: VPID flush type = Individual addresses\n"));
1662 else if (pVM->hm.s.vmx.enmTlbFlushVpid == VMXTLBFLUSHVPID_SINGLE_CONTEXT)
1663 LogRel(("HM: VPID flush type = Single context\n"));
1664 else if (pVM->hm.s.vmx.enmTlbFlushVpid == VMXTLBFLUSHVPID_ALL_CONTEXTS)
1665 LogRel(("HM: VPID flush type = All contexts\n"));
1666 else if (pVM->hm.s.vmx.enmTlbFlushVpid == VMXTLBFLUSHVPID_SINGLE_CONTEXT_RETAIN_GLOBALS)
1667 LogRel(("HM: VPID flush type = Single context retain globals\n"));
1668 else
1669 LogRel(("HM: VPID flush type = %#x\n", pVM->hm.s.vmx.enmTlbFlushVpid));
1670 }
1671 else if (pVM->hm.s.vmx.enmTlbFlushVpid == VMXTLBFLUSHVPID_NOT_SUPPORTED)
1672 LogRel(("HM: Ignoring VPID capabilities of CPU\n"));
1673
1674 if (pVM->hm.s.vmx.fUsePreemptTimer)
1675 LogRel(("HM: Enabled VMX-preemption timer (cPreemptTimerShift=%u)\n", pVM->hm.s.vmx.cPreemptTimerShift));
1676 else
1677 LogRel(("HM: Disabled VMX-preemption timer\n"));
1678
1679 if (pVM->hm.s.fVirtApicRegs)
1680 LogRel(("HM: Enabled APIC-register virtualization support\n"));
1681
1682 if (pVM->hm.s.fPostedIntrs)
1683 LogRel(("HM: Enabled posted-interrupt processing support\n"));
1684
1685 if (pVM->hm.s.vmx.fUseVmcsShadowing)
1686 {
1687 bool const fFullVmcsShadow = RT_BOOL(pVM->hm.s.vmx.Msrs.u64Misc & VMX_MISC_VMWRITE_ALL);
1688 LogRel(("HM: Enabled %s VMCS shadowing\n", fFullVmcsShadow ? "full" : "partial"));
1689 }
1690
1691 return VINF_SUCCESS;
1692}
1693
1694
1695/**
1696 * Finish AMD-V initialization (after ring-0 init).
1697 *
1698 * @returns VBox status code.
1699 * @param pVM The cross context VM structure.
1700 */
1701static int hmR3InitFinalizeR0Amd(PVM pVM)
1702{
1703 Log(("pVM->hm.s.svm.fSupported = %d\n", pVM->hm.s.svm.fSupported));
1704
1705 LogRel(("HM: Using AMD-V implementation 2.0\n"));
1706
1707 uint32_t u32Family;
1708 uint32_t u32Model;
1709 uint32_t u32Stepping;
1710 if (HMIsSubjectToSvmErratum170(&u32Family, &u32Model, &u32Stepping))
1711 LogRel(("HM: AMD Cpu with erratum 170 family %#x model %#x stepping %#x\n", u32Family, u32Model, u32Stepping));
1712 LogRel(("HM: Max resume loops = %u\n", pVM->hm.s.cMaxResumeLoops));
1713 LogRel(("HM: AMD HWCR MSR = %#RX64\n", pVM->hm.s.svm.u64MsrHwcr));
1714 LogRel(("HM: AMD-V revision = %#x\n", pVM->hm.s.svm.u32Rev));
1715 LogRel(("HM: AMD-V max ASID = %RU32\n", pVM->hm.s.uMaxAsid));
1716 LogRel(("HM: AMD-V features = %#x\n", pVM->hm.s.svm.u32Features));
1717
1718 /*
1719 * Enumerate AMD-V features.
1720 */
1721 static const struct { uint32_t fFlag; const char *pszName; } s_aSvmFeatures[] =
1722 {
1723#define HMSVM_REPORT_FEATURE(a_StrDesc, a_Define) { a_Define, a_StrDesc }
1724 HMSVM_REPORT_FEATURE("NESTED_PAGING", X86_CPUID_SVM_FEATURE_EDX_NESTED_PAGING),
1725 HMSVM_REPORT_FEATURE("LBR_VIRT", X86_CPUID_SVM_FEATURE_EDX_LBR_VIRT),
1726 HMSVM_REPORT_FEATURE("SVM_LOCK", X86_CPUID_SVM_FEATURE_EDX_SVM_LOCK),
1727 HMSVM_REPORT_FEATURE("NRIP_SAVE", X86_CPUID_SVM_FEATURE_EDX_NRIP_SAVE),
1728 HMSVM_REPORT_FEATURE("TSC_RATE_MSR", X86_CPUID_SVM_FEATURE_EDX_TSC_RATE_MSR),
1729 HMSVM_REPORT_FEATURE("VMCB_CLEAN", X86_CPUID_SVM_FEATURE_EDX_VMCB_CLEAN),
1730 HMSVM_REPORT_FEATURE("FLUSH_BY_ASID", X86_CPUID_SVM_FEATURE_EDX_FLUSH_BY_ASID),
1731 HMSVM_REPORT_FEATURE("DECODE_ASSISTS", X86_CPUID_SVM_FEATURE_EDX_DECODE_ASSISTS),
1732 HMSVM_REPORT_FEATURE("PAUSE_FILTER", X86_CPUID_SVM_FEATURE_EDX_PAUSE_FILTER),
1733 HMSVM_REPORT_FEATURE("PAUSE_FILTER_THRESHOLD", X86_CPUID_SVM_FEATURE_EDX_PAUSE_FILTER_THRESHOLD),
1734 HMSVM_REPORT_FEATURE("AVIC", X86_CPUID_SVM_FEATURE_EDX_AVIC),
1735 HMSVM_REPORT_FEATURE("VIRT_VMSAVE_VMLOAD", X86_CPUID_SVM_FEATURE_EDX_VIRT_VMSAVE_VMLOAD),
1736 HMSVM_REPORT_FEATURE("VGIF", X86_CPUID_SVM_FEATURE_EDX_VGIF),
1737#undef HMSVM_REPORT_FEATURE
1738 };
1739
1740 uint32_t fSvmFeatures = pVM->hm.s.svm.u32Features;
1741 for (unsigned i = 0; i < RT_ELEMENTS(s_aSvmFeatures); i++)
1742 if (fSvmFeatures & s_aSvmFeatures[i].fFlag)
1743 {
1744 LogRel(("HM: %s\n", s_aSvmFeatures[i].pszName));
1745 fSvmFeatures &= ~s_aSvmFeatures[i].fFlag;
1746 }
1747 if (fSvmFeatures)
1748 for (unsigned iBit = 0; iBit < 32; iBit++)
1749 if (RT_BIT_32(iBit) & fSvmFeatures)
1750 LogRel(("HM: Reserved bit %u\n", iBit));
1751
1752 /*
1753 * Nested paging is determined in HMR3Init, verify the sanity of that.
1754 */
1755 AssertLogRelReturn( !pVM->hm.s.fNestedPaging
1756 || (pVM->hm.s.svm.u32Features & X86_CPUID_SVM_FEATURE_EDX_NESTED_PAGING),
1757 VERR_HM_IPE_1);
1758
1759#if 0
1760 /** @todo Add and query IPRT API for host OS support for posted-interrupt IPI
1761 * here. */
1762 if (RTR0IsPostIpiSupport())
1763 pVM->hm.s.fPostedIntrs = true;
1764#endif
1765
1766 /*
1767 * Call ring-0 to set up the VM.
1768 */
1769 int rc = SUPR3CallVMMR0Ex(pVM->pVMR0, 0 /*idCpu*/, VMMR0_DO_HM_SETUP_VM, 0, NULL);
1770 if (rc != VINF_SUCCESS)
1771 {
1772 AssertMsgFailed(("%Rrc\n", rc));
1773 LogRel(("HM: AMD-V setup failed with rc=%Rrc!\n", rc));
1774 return VMSetError(pVM, rc, RT_SRC_POS, "AMD-V setup failed: %Rrc", rc);
1775 }
1776
1777 LogRel(("HM: Enabled SVM\n"));
1778 pVM->hm.s.svm.fEnabled = true;
1779
1780 if (pVM->hm.s.fNestedPaging)
1781 {
1782 LogRel(("HM: Enabled nested paging\n"));
1783
1784 /*
1785 * Enable large pages (2 MB) if applicable.
1786 */
1787 if (pVM->hm.s.fLargePages)
1788 {
1789 PGMSetLargePageUsage(pVM, true);
1790 LogRel(("HM: Enabled large page support\n"));
1791 }
1792 }
1793
1794 if (pVM->hm.s.fVirtApicRegs)
1795 LogRel(("HM: Enabled APIC-register virtualization support\n"));
1796
1797 if (pVM->hm.s.fPostedIntrs)
1798 LogRel(("HM: Enabled posted-interrupt processing support\n"));
1799
1800 hmR3DisableRawMode(pVM);
1801
1802 /*
1803 * Change the CPU features.
1804 */
1805 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_SEP);
1806 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_SYSCALL);
1807 if (pVM->hm.s.fAllow64BitGuests)
1808 {
1809 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_PAE);
1810 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_LONG_MODE);
1811 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_NX);
1812 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_LAHF);
1813 }
1814 /* Turn on NXE if PAE has been enabled. */
1815 else if (CPUMR3GetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_PAE))
1816 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_NX);
1817
1818 LogRel((pVM->hm.s.fTprPatchingAllowed ? "HM: Enabled TPR patching\n"
1819 : "HM: Disabled TPR patching\n"));
1820
1821 LogRel((pVM->hm.s.fAllow64BitGuests ? "HM: Guest support: 32-bit and 64-bit\n"
1822 : "HM: Guest support: 32-bit only\n"));
1823 return VINF_SUCCESS;
1824}
1825
1826
1827/**
1828 * Applies relocations to data and code managed by this
1829 * component. This function will be called at init and
1830 * whenever the VMM need to relocate it self inside the GC.
1831 *
1832 * @param pVM The cross context VM structure.
1833 */
1834VMMR3_INT_DECL(void) HMR3Relocate(PVM pVM)
1835{
1836 Log(("HMR3Relocate to %RGv\n", MMHyperGetArea(pVM, 0)));
1837
1838 /* Fetch the current paging mode during the relocate callback during state loading. */
1839 if (VMR3GetState(pVM) == VMSTATE_LOADING)
1840 {
1841 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
1842 {
1843 PVMCPU pVCpu = pVM->apCpusR3[idCpu];
1844 pVCpu->hm.s.enmShadowMode = PGMGetShadowMode(pVCpu);
1845 }
1846 }
1847}
1848
1849
1850/**
1851 * Terminates the HM.
1852 *
1853 * Termination means cleaning up and freeing all resources,
1854 * the VM itself is, at this point, powered off or suspended.
1855 *
1856 * @returns VBox status code.
1857 * @param pVM The cross context VM structure.
1858 */
1859VMMR3_INT_DECL(int) HMR3Term(PVM pVM)
1860{
1861 if (pVM->hm.s.vmx.pRealModeTSS)
1862 {
1863 PDMR3VmmDevHeapFree(pVM, pVM->hm.s.vmx.pRealModeTSS);
1864 pVM->hm.s.vmx.pRealModeTSS = 0;
1865 }
1866 hmR3TermCPU(pVM);
1867 return 0;
1868}
1869
1870
1871/**
1872 * Terminates the per-VCPU HM.
1873 *
1874 * @returns VBox status code.
1875 * @param pVM The cross context VM structure.
1876 */
1877static int hmR3TermCPU(PVM pVM)
1878{
1879#ifdef VBOX_WITH_STATISTICS
1880 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
1881 {
1882 PVMCPU pVCpu = pVM->apCpusR3[idCpu]; NOREF(pVCpu);
1883 if (pVCpu->hm.s.paStatExitReason)
1884 {
1885 MMHyperFree(pVM, pVCpu->hm.s.paStatExitReason);
1886 pVCpu->hm.s.paStatExitReason = NULL;
1887 pVCpu->hm.s.paStatExitReasonR0 = NIL_RTR0PTR;
1888 }
1889 if (pVCpu->hm.s.paStatInjectedIrqs)
1890 {
1891 MMHyperFree(pVM, pVCpu->hm.s.paStatInjectedIrqs);
1892 pVCpu->hm.s.paStatInjectedIrqs = NULL;
1893 pVCpu->hm.s.paStatInjectedIrqsR0 = NIL_RTR0PTR;
1894 }
1895# if defined(VBOX_WITH_NESTED_HWVIRT_SVM) || defined(VBOX_WITH_NESTED_HWVIRT_VMX)
1896 if (pVCpu->hm.s.paStatNestedExitReason)
1897 {
1898 MMHyperFree(pVM, pVCpu->hm.s.paStatNestedExitReason);
1899 pVCpu->hm.s.paStatNestedExitReason = NULL;
1900 pVCpu->hm.s.paStatNestedExitReasonR0 = NIL_RTR0PTR;
1901 }
1902# endif
1903 }
1904#else
1905 RT_NOREF(pVM);
1906#endif
1907 return VINF_SUCCESS;
1908}
1909
1910
1911/**
1912 * Resets a virtual CPU.
1913 *
1914 * Used by HMR3Reset and CPU hot plugging.
1915 *
1916 * @param pVCpu The cross context virtual CPU structure to reset.
1917 */
1918VMMR3_INT_DECL(void) HMR3ResetCpu(PVMCPU pVCpu)
1919{
1920 /* Sync. entire state on VM reset ring-0 re-entry. It's safe to reset
1921 the HM flags here, all other EMTs are in ring-3. See VMR3Reset(). */
1922 pVCpu->hm.s.fCtxChanged |= HM_CHANGED_HOST_CONTEXT | HM_CHANGED_ALL_GUEST;
1923
1924 pVCpu->hm.s.fActive = false;
1925 pVCpu->hm.s.Event.fPending = false;
1926 pVCpu->hm.s.vmx.u64GstMsrApicBase = 0;
1927 pVCpu->hm.s.vmx.VmcsInfo.fSwitchedTo64on32Obsolete = false;
1928 pVCpu->hm.s.vmx.VmcsInfo.fWasInRealMode = true;
1929#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
1930 if (pVCpu->CTX_SUFF(pVM)->cpum.ro.GuestFeatures.fVmx)
1931 {
1932 pVCpu->hm.s.vmx.VmcsInfoNstGst.fSwitchedTo64on32Obsolete = false;
1933 pVCpu->hm.s.vmx.VmcsInfoNstGst.fWasInRealMode = true;
1934 }
1935#endif
1936}
1937
1938
1939/**
1940 * The VM is being reset.
1941 *
1942 * For the HM component this means that any GDT/LDT/TSS monitors
1943 * needs to be removed.
1944 *
1945 * @param pVM The cross context VM structure.
1946 */
1947VMMR3_INT_DECL(void) HMR3Reset(PVM pVM)
1948{
1949 LogFlow(("HMR3Reset:\n"));
1950
1951 if (HMIsEnabled(pVM))
1952 hmR3DisableRawMode(pVM);
1953
1954 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
1955 HMR3ResetCpu(pVM->apCpusR3[idCpu]);
1956
1957 /* Clear all patch information. */
1958 pVM->hm.s.pGuestPatchMem = 0;
1959 pVM->hm.s.pFreeGuestPatchMem = 0;
1960 pVM->hm.s.cbGuestPatchMem = 0;
1961 pVM->hm.s.cPatches = 0;
1962 pVM->hm.s.PatchTree = 0;
1963 pVM->hm.s.fTPRPatchingActive = false;
1964 ASMMemZero32(pVM->hm.s.aPatches, sizeof(pVM->hm.s.aPatches));
1965}
1966
1967
1968/**
1969 * Callback to patch a TPR instruction (vmmcall or mov cr8).
1970 *
1971 * @returns VBox strict status code.
1972 * @param pVM The cross context VM structure.
1973 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
1974 * @param pvUser Unused.
1975 */
1976static DECLCALLBACK(VBOXSTRICTRC) hmR3RemovePatches(PVM pVM, PVMCPU pVCpu, void *pvUser)
1977{
1978 VMCPUID idCpu = (VMCPUID)(uintptr_t)pvUser;
1979
1980 /* Only execute the handler on the VCPU the original patch request was issued. */
1981 if (pVCpu->idCpu != idCpu)
1982 return VINF_SUCCESS;
1983
1984 Log(("hmR3RemovePatches\n"));
1985 for (unsigned i = 0; i < pVM->hm.s.cPatches; i++)
1986 {
1987 uint8_t abInstr[15];
1988 PHMTPRPATCH pPatch = &pVM->hm.s.aPatches[i];
1989 RTGCPTR pInstrGC = (RTGCPTR)pPatch->Core.Key;
1990 int rc;
1991
1992#ifdef LOG_ENABLED
1993 char szOutput[256];
1994 rc = DBGFR3DisasInstrEx(pVM->pUVM, pVCpu->idCpu, CPUMGetGuestCS(pVCpu), pInstrGC, DBGF_DISAS_FLAGS_DEFAULT_MODE,
1995 szOutput, sizeof(szOutput), NULL);
1996 if (RT_SUCCESS(rc))
1997 Log(("Patched instr: %s\n", szOutput));
1998#endif
1999
2000 /* Check if the instruction is still the same. */
2001 rc = PGMPhysSimpleReadGCPtr(pVCpu, abInstr, pInstrGC, pPatch->cbNewOp);
2002 if (rc != VINF_SUCCESS)
2003 {
2004 Log(("Patched code removed? (rc=%Rrc0\n", rc));
2005 continue; /* swapped out or otherwise removed; skip it. */
2006 }
2007
2008 if (memcmp(abInstr, pPatch->aNewOpcode, pPatch->cbNewOp))
2009 {
2010 Log(("Patched instruction was changed! (rc=%Rrc0\n", rc));
2011 continue; /* skip it. */
2012 }
2013
2014 rc = PGMPhysSimpleWriteGCPtr(pVCpu, pInstrGC, pPatch->aOpcode, pPatch->cbOp);
2015 AssertRC(rc);
2016
2017#ifdef LOG_ENABLED
2018 rc = DBGFR3DisasInstrEx(pVM->pUVM, pVCpu->idCpu, CPUMGetGuestCS(pVCpu), pInstrGC, DBGF_DISAS_FLAGS_DEFAULT_MODE,
2019 szOutput, sizeof(szOutput), NULL);
2020 if (RT_SUCCESS(rc))
2021 Log(("Original instr: %s\n", szOutput));
2022#endif
2023 }
2024 pVM->hm.s.cPatches = 0;
2025 pVM->hm.s.PatchTree = 0;
2026 pVM->hm.s.pFreeGuestPatchMem = pVM->hm.s.pGuestPatchMem;
2027 pVM->hm.s.fTPRPatchingActive = false;
2028 return VINF_SUCCESS;
2029}
2030
2031
2032/**
2033 * Worker for enabling patching in a VT-x/AMD-V guest.
2034 *
2035 * @returns VBox status code.
2036 * @param pVM The cross context VM structure.
2037 * @param idCpu VCPU to execute hmR3RemovePatches on.
2038 * @param pPatchMem Patch memory range.
2039 * @param cbPatchMem Size of the memory range.
2040 */
2041static int hmR3EnablePatching(PVM pVM, VMCPUID idCpu, RTRCPTR pPatchMem, unsigned cbPatchMem)
2042{
2043 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONE_BY_ONE, hmR3RemovePatches, (void *)(uintptr_t)idCpu);
2044 AssertRC(rc);
2045
2046 pVM->hm.s.pGuestPatchMem = pPatchMem;
2047 pVM->hm.s.pFreeGuestPatchMem = pPatchMem;
2048 pVM->hm.s.cbGuestPatchMem = cbPatchMem;
2049 return VINF_SUCCESS;
2050}
2051
2052
2053/**
2054 * Enable patching in a VT-x/AMD-V guest
2055 *
2056 * @returns VBox status code.
2057 * @param pVM The cross context VM structure.
2058 * @param pPatchMem Patch memory range.
2059 * @param cbPatchMem Size of the memory range.
2060 */
2061VMMR3_INT_DECL(int) HMR3EnablePatching(PVM pVM, RTGCPTR pPatchMem, unsigned cbPatchMem)
2062{
2063 VM_ASSERT_EMT(pVM);
2064 Log(("HMR3EnablePatching %RGv size %x\n", pPatchMem, cbPatchMem));
2065 if (pVM->cCpus > 1)
2066 {
2067 /* We own the IOM lock here and could cause a deadlock by waiting for a VCPU that is blocking on the IOM lock. */
2068 int rc = VMR3ReqCallNoWait(pVM, VMCPUID_ANY_QUEUE,
2069 (PFNRT)hmR3EnablePatching, 4, pVM, VMMGetCpuId(pVM), (RTRCPTR)pPatchMem, cbPatchMem);
2070 AssertRC(rc);
2071 return rc;
2072 }
2073 return hmR3EnablePatching(pVM, VMMGetCpuId(pVM), (RTRCPTR)pPatchMem, cbPatchMem);
2074}
2075
2076
2077/**
2078 * Disable patching in a VT-x/AMD-V guest.
2079 *
2080 * @returns VBox status code.
2081 * @param pVM The cross context VM structure.
2082 * @param pPatchMem Patch memory range.
2083 * @param cbPatchMem Size of the memory range.
2084 */
2085VMMR3_INT_DECL(int) HMR3DisablePatching(PVM pVM, RTGCPTR pPatchMem, unsigned cbPatchMem)
2086{
2087 Log(("HMR3DisablePatching %RGv size %x\n", pPatchMem, cbPatchMem));
2088 RT_NOREF2(pPatchMem, cbPatchMem);
2089
2090 Assert(pVM->hm.s.pGuestPatchMem == pPatchMem);
2091 Assert(pVM->hm.s.cbGuestPatchMem == cbPatchMem);
2092
2093 /** @todo Potential deadlock when other VCPUs are waiting on the IOM lock (we own it)!! */
2094 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONE_BY_ONE, hmR3RemovePatches,
2095 (void *)(uintptr_t)VMMGetCpuId(pVM));
2096 AssertRC(rc);
2097
2098 pVM->hm.s.pGuestPatchMem = 0;
2099 pVM->hm.s.pFreeGuestPatchMem = 0;
2100 pVM->hm.s.cbGuestPatchMem = 0;
2101 pVM->hm.s.fTPRPatchingActive = false;
2102 return VINF_SUCCESS;
2103}
2104
2105
2106/**
2107 * Callback to patch a TPR instruction (vmmcall or mov cr8).
2108 *
2109 * @returns VBox strict status code.
2110 * @param pVM The cross context VM structure.
2111 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
2112 * @param pvUser User specified CPU context.
2113 *
2114 */
2115static DECLCALLBACK(VBOXSTRICTRC) hmR3ReplaceTprInstr(PVM pVM, PVMCPU pVCpu, void *pvUser)
2116{
2117 /*
2118 * Only execute the handler on the VCPU the original patch request was
2119 * issued. (The other CPU(s) might not yet have switched to protected
2120 * mode, nor have the correct memory context.)
2121 */
2122 VMCPUID idCpu = (VMCPUID)(uintptr_t)pvUser;
2123 if (pVCpu->idCpu != idCpu)
2124 return VINF_SUCCESS;
2125
2126 /*
2127 * We're racing other VCPUs here, so don't try patch the instruction twice
2128 * and make sure there is still room for our patch record.
2129 */
2130 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
2131 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
2132 if (pPatch)
2133 {
2134 Log(("hmR3ReplaceTprInstr: already patched %RGv\n", pCtx->rip));
2135 return VINF_SUCCESS;
2136 }
2137 uint32_t const idx = pVM->hm.s.cPatches;
2138 if (idx >= RT_ELEMENTS(pVM->hm.s.aPatches))
2139 {
2140 Log(("hmR3ReplaceTprInstr: no available patch slots (%RGv)\n", pCtx->rip));
2141 return VINF_SUCCESS;
2142 }
2143 pPatch = &pVM->hm.s.aPatches[idx];
2144
2145 Log(("hmR3ReplaceTprInstr: rip=%RGv idxPatch=%u\n", pCtx->rip, idx));
2146
2147 /*
2148 * Disassembler the instruction and get cracking.
2149 */
2150 DBGFR3_DISAS_INSTR_CUR_LOG(pVCpu, "hmR3ReplaceTprInstr");
2151 PDISCPUSTATE pDis = &pVCpu->hm.s.DisState;
2152 uint32_t cbOp;
2153 int rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, &cbOp);
2154 AssertRC(rc);
2155 if ( rc == VINF_SUCCESS
2156 && pDis->pCurInstr->uOpcode == OP_MOV
2157 && cbOp >= 3)
2158 {
2159 static uint8_t const s_abVMMCall[3] = { 0x0f, 0x01, 0xd9 };
2160
2161 rc = PGMPhysSimpleReadGCPtr(pVCpu, pPatch->aOpcode, pCtx->rip, cbOp);
2162 AssertRC(rc);
2163
2164 pPatch->cbOp = cbOp;
2165
2166 if (pDis->Param1.fUse == DISUSE_DISPLACEMENT32)
2167 {
2168 /* write. */
2169 if (pDis->Param2.fUse == DISUSE_REG_GEN32)
2170 {
2171 pPatch->enmType = HMTPRINSTR_WRITE_REG;
2172 pPatch->uSrcOperand = pDis->Param2.Base.idxGenReg;
2173 Log(("hmR3ReplaceTprInstr: HMTPRINSTR_WRITE_REG %u\n", pDis->Param2.Base.idxGenReg));
2174 }
2175 else
2176 {
2177 Assert(pDis->Param2.fUse == DISUSE_IMMEDIATE32);
2178 pPatch->enmType = HMTPRINSTR_WRITE_IMM;
2179 pPatch->uSrcOperand = pDis->Param2.uValue;
2180 Log(("hmR3ReplaceTprInstr: HMTPRINSTR_WRITE_IMM %#llx\n", pDis->Param2.uValue));
2181 }
2182 rc = PGMPhysSimpleWriteGCPtr(pVCpu, pCtx->rip, s_abVMMCall, sizeof(s_abVMMCall));
2183 AssertRC(rc);
2184
2185 memcpy(pPatch->aNewOpcode, s_abVMMCall, sizeof(s_abVMMCall));
2186 pPatch->cbNewOp = sizeof(s_abVMMCall);
2187 STAM_COUNTER_INC(&pVM->hm.s.StatTprReplaceSuccessVmc);
2188 }
2189 else
2190 {
2191 /*
2192 * TPR Read.
2193 *
2194 * Found:
2195 * mov eax, dword [fffe0080] (5 bytes)
2196 * Check if next instruction is:
2197 * shr eax, 4
2198 */
2199 Assert(pDis->Param1.fUse == DISUSE_REG_GEN32);
2200
2201 uint8_t const idxMmioReg = pDis->Param1.Base.idxGenReg;
2202 uint8_t const cbOpMmio = cbOp;
2203 uint64_t const uSavedRip = pCtx->rip;
2204
2205 pCtx->rip += cbOp;
2206 rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, &cbOp);
2207 DBGFR3_DISAS_INSTR_CUR_LOG(pVCpu, "Following read");
2208 pCtx->rip = uSavedRip;
2209
2210 if ( rc == VINF_SUCCESS
2211 && pDis->pCurInstr->uOpcode == OP_SHR
2212 && pDis->Param1.fUse == DISUSE_REG_GEN32
2213 && pDis->Param1.Base.idxGenReg == idxMmioReg
2214 && pDis->Param2.fUse == DISUSE_IMMEDIATE8
2215 && pDis->Param2.uValue == 4
2216 && cbOpMmio + cbOp < sizeof(pVM->hm.s.aPatches[idx].aOpcode))
2217 {
2218 uint8_t abInstr[15];
2219
2220 /* Replacing the two instructions above with an AMD-V specific lock-prefixed 32-bit MOV CR8 instruction so as to
2221 access CR8 in 32-bit mode and not cause a #VMEXIT. */
2222 rc = PGMPhysSimpleReadGCPtr(pVCpu, &pPatch->aOpcode, pCtx->rip, cbOpMmio + cbOp);
2223 AssertRC(rc);
2224
2225 pPatch->cbOp = cbOpMmio + cbOp;
2226
2227 /* 0xf0, 0x0f, 0x20, 0xc0 = mov eax, cr8 */
2228 abInstr[0] = 0xf0;
2229 abInstr[1] = 0x0f;
2230 abInstr[2] = 0x20;
2231 abInstr[3] = 0xc0 | pDis->Param1.Base.idxGenReg;
2232 for (unsigned i = 4; i < pPatch->cbOp; i++)
2233 abInstr[i] = 0x90; /* nop */
2234
2235 rc = PGMPhysSimpleWriteGCPtr(pVCpu, pCtx->rip, abInstr, pPatch->cbOp);
2236 AssertRC(rc);
2237
2238 memcpy(pPatch->aNewOpcode, abInstr, pPatch->cbOp);
2239 pPatch->cbNewOp = pPatch->cbOp;
2240 STAM_COUNTER_INC(&pVM->hm.s.StatTprReplaceSuccessCr8);
2241
2242 Log(("Acceptable read/shr candidate!\n"));
2243 pPatch->enmType = HMTPRINSTR_READ_SHR4;
2244 }
2245 else
2246 {
2247 pPatch->enmType = HMTPRINSTR_READ;
2248 pPatch->uDstOperand = idxMmioReg;
2249
2250 rc = PGMPhysSimpleWriteGCPtr(pVCpu, pCtx->rip, s_abVMMCall, sizeof(s_abVMMCall));
2251 AssertRC(rc);
2252
2253 memcpy(pPatch->aNewOpcode, s_abVMMCall, sizeof(s_abVMMCall));
2254 pPatch->cbNewOp = sizeof(s_abVMMCall);
2255 STAM_COUNTER_INC(&pVM->hm.s.StatTprReplaceSuccessVmc);
2256 Log(("hmR3ReplaceTprInstr: HMTPRINSTR_READ %u\n", pPatch->uDstOperand));
2257 }
2258 }
2259
2260 pPatch->Core.Key = pCtx->eip;
2261 rc = RTAvloU32Insert(&pVM->hm.s.PatchTree, &pPatch->Core);
2262 AssertRC(rc);
2263
2264 pVM->hm.s.cPatches++;
2265 return VINF_SUCCESS;
2266 }
2267
2268 /*
2269 * Save invalid patch, so we will not try again.
2270 */
2271 Log(("hmR3ReplaceTprInstr: Failed to patch instr!\n"));
2272 pPatch->Core.Key = pCtx->eip;
2273 pPatch->enmType = HMTPRINSTR_INVALID;
2274 rc = RTAvloU32Insert(&pVM->hm.s.PatchTree, &pPatch->Core);
2275 AssertRC(rc);
2276 pVM->hm.s.cPatches++;
2277 STAM_COUNTER_INC(&pVM->hm.s.StatTprReplaceFailure);
2278 return VINF_SUCCESS;
2279}
2280
2281
2282/**
2283 * Callback to patch a TPR instruction (jump to generated code).
2284 *
2285 * @returns VBox strict status code.
2286 * @param pVM The cross context VM structure.
2287 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
2288 * @param pvUser User specified CPU context.
2289 *
2290 */
2291static DECLCALLBACK(VBOXSTRICTRC) hmR3PatchTprInstr(PVM pVM, PVMCPU pVCpu, void *pvUser)
2292{
2293 /*
2294 * Only execute the handler on the VCPU the original patch request was
2295 * issued. (The other CPU(s) might not yet have switched to protected
2296 * mode, nor have the correct memory context.)
2297 */
2298 VMCPUID idCpu = (VMCPUID)(uintptr_t)pvUser;
2299 if (pVCpu->idCpu != idCpu)
2300 return VINF_SUCCESS;
2301
2302 /*
2303 * We're racing other VCPUs here, so don't try patch the instruction twice
2304 * and make sure there is still room for our patch record.
2305 */
2306 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
2307 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
2308 if (pPatch)
2309 {
2310 Log(("hmR3PatchTprInstr: already patched %RGv\n", pCtx->rip));
2311 return VINF_SUCCESS;
2312 }
2313 uint32_t const idx = pVM->hm.s.cPatches;
2314 if (idx >= RT_ELEMENTS(pVM->hm.s.aPatches))
2315 {
2316 Log(("hmR3PatchTprInstr: no available patch slots (%RGv)\n", pCtx->rip));
2317 return VINF_SUCCESS;
2318 }
2319 pPatch = &pVM->hm.s.aPatches[idx];
2320
2321 Log(("hmR3PatchTprInstr: rip=%RGv idxPatch=%u\n", pCtx->rip, idx));
2322 DBGFR3_DISAS_INSTR_CUR_LOG(pVCpu, "hmR3PatchTprInstr");
2323
2324 /*
2325 * Disassemble the instruction and get cracking.
2326 */
2327 PDISCPUSTATE pDis = &pVCpu->hm.s.DisState;
2328 uint32_t cbOp;
2329 int rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, &cbOp);
2330 AssertRC(rc);
2331 if ( rc == VINF_SUCCESS
2332 && pDis->pCurInstr->uOpcode == OP_MOV
2333 && cbOp >= 5)
2334 {
2335 uint8_t aPatch[64];
2336 uint32_t off = 0;
2337
2338 rc = PGMPhysSimpleReadGCPtr(pVCpu, pPatch->aOpcode, pCtx->rip, cbOp);
2339 AssertRC(rc);
2340
2341 pPatch->cbOp = cbOp;
2342 pPatch->enmType = HMTPRINSTR_JUMP_REPLACEMENT;
2343
2344 if (pDis->Param1.fUse == DISUSE_DISPLACEMENT32)
2345 {
2346 /*
2347 * TPR write:
2348 *
2349 * push ECX [51]
2350 * push EDX [52]
2351 * push EAX [50]
2352 * xor EDX,EDX [31 D2]
2353 * mov EAX,EAX [89 C0]
2354 * or
2355 * mov EAX,0000000CCh [B8 CC 00 00 00]
2356 * mov ECX,0C0000082h [B9 82 00 00 C0]
2357 * wrmsr [0F 30]
2358 * pop EAX [58]
2359 * pop EDX [5A]
2360 * pop ECX [59]
2361 * jmp return_address [E9 return_address]
2362 */
2363 bool fUsesEax = (pDis->Param2.fUse == DISUSE_REG_GEN32 && pDis->Param2.Base.idxGenReg == DISGREG_EAX);
2364
2365 aPatch[off++] = 0x51; /* push ecx */
2366 aPatch[off++] = 0x52; /* push edx */
2367 if (!fUsesEax)
2368 aPatch[off++] = 0x50; /* push eax */
2369 aPatch[off++] = 0x31; /* xor edx, edx */
2370 aPatch[off++] = 0xd2;
2371 if (pDis->Param2.fUse == DISUSE_REG_GEN32)
2372 {
2373 if (!fUsesEax)
2374 {
2375 aPatch[off++] = 0x89; /* mov eax, src_reg */
2376 aPatch[off++] = MAKE_MODRM(3, pDis->Param2.Base.idxGenReg, DISGREG_EAX);
2377 }
2378 }
2379 else
2380 {
2381 Assert(pDis->Param2.fUse == DISUSE_IMMEDIATE32);
2382 aPatch[off++] = 0xb8; /* mov eax, immediate */
2383 *(uint32_t *)&aPatch[off] = pDis->Param2.uValue;
2384 off += sizeof(uint32_t);
2385 }
2386 aPatch[off++] = 0xb9; /* mov ecx, 0xc0000082 */
2387 *(uint32_t *)&aPatch[off] = MSR_K8_LSTAR;
2388 off += sizeof(uint32_t);
2389
2390 aPatch[off++] = 0x0f; /* wrmsr */
2391 aPatch[off++] = 0x30;
2392 if (!fUsesEax)
2393 aPatch[off++] = 0x58; /* pop eax */
2394 aPatch[off++] = 0x5a; /* pop edx */
2395 aPatch[off++] = 0x59; /* pop ecx */
2396 }
2397 else
2398 {
2399 /*
2400 * TPR read:
2401 *
2402 * push ECX [51]
2403 * push EDX [52]
2404 * push EAX [50]
2405 * mov ECX,0C0000082h [B9 82 00 00 C0]
2406 * rdmsr [0F 32]
2407 * mov EAX,EAX [89 C0]
2408 * pop EAX [58]
2409 * pop EDX [5A]
2410 * pop ECX [59]
2411 * jmp return_address [E9 return_address]
2412 */
2413 Assert(pDis->Param1.fUse == DISUSE_REG_GEN32);
2414
2415 if (pDis->Param1.Base.idxGenReg != DISGREG_ECX)
2416 aPatch[off++] = 0x51; /* push ecx */
2417 if (pDis->Param1.Base.idxGenReg != DISGREG_EDX )
2418 aPatch[off++] = 0x52; /* push edx */
2419 if (pDis->Param1.Base.idxGenReg != DISGREG_EAX)
2420 aPatch[off++] = 0x50; /* push eax */
2421
2422 aPatch[off++] = 0x31; /* xor edx, edx */
2423 aPatch[off++] = 0xd2;
2424
2425 aPatch[off++] = 0xb9; /* mov ecx, 0xc0000082 */
2426 *(uint32_t *)&aPatch[off] = MSR_K8_LSTAR;
2427 off += sizeof(uint32_t);
2428
2429 aPatch[off++] = 0x0f; /* rdmsr */
2430 aPatch[off++] = 0x32;
2431
2432 if (pDis->Param1.Base.idxGenReg != DISGREG_EAX)
2433 {
2434 aPatch[off++] = 0x89; /* mov dst_reg, eax */
2435 aPatch[off++] = MAKE_MODRM(3, DISGREG_EAX, pDis->Param1.Base.idxGenReg);
2436 }
2437
2438 if (pDis->Param1.Base.idxGenReg != DISGREG_EAX)
2439 aPatch[off++] = 0x58; /* pop eax */
2440 if (pDis->Param1.Base.idxGenReg != DISGREG_EDX )
2441 aPatch[off++] = 0x5a; /* pop edx */
2442 if (pDis->Param1.Base.idxGenReg != DISGREG_ECX)
2443 aPatch[off++] = 0x59; /* pop ecx */
2444 }
2445 aPatch[off++] = 0xe9; /* jmp return_address */
2446 *(RTRCUINTPTR *)&aPatch[off] = ((RTRCUINTPTR)pCtx->eip + cbOp) - ((RTRCUINTPTR)pVM->hm.s.pFreeGuestPatchMem + off + 4);
2447 off += sizeof(RTRCUINTPTR);
2448
2449 if (pVM->hm.s.pFreeGuestPatchMem + off <= pVM->hm.s.pGuestPatchMem + pVM->hm.s.cbGuestPatchMem)
2450 {
2451 /* Write new code to the patch buffer. */
2452 rc = PGMPhysSimpleWriteGCPtr(pVCpu, pVM->hm.s.pFreeGuestPatchMem, aPatch, off);
2453 AssertRC(rc);
2454
2455#ifdef LOG_ENABLED
2456 uint32_t cbCurInstr;
2457 for (RTGCPTR GCPtrInstr = pVM->hm.s.pFreeGuestPatchMem;
2458 GCPtrInstr < pVM->hm.s.pFreeGuestPatchMem + off;
2459 GCPtrInstr += RT_MAX(cbCurInstr, 1))
2460 {
2461 char szOutput[256];
2462 rc = DBGFR3DisasInstrEx(pVM->pUVM, pVCpu->idCpu, pCtx->cs.Sel, GCPtrInstr, DBGF_DISAS_FLAGS_DEFAULT_MODE,
2463 szOutput, sizeof(szOutput), &cbCurInstr);
2464 if (RT_SUCCESS(rc))
2465 Log(("Patch instr %s\n", szOutput));
2466 else
2467 Log(("%RGv: rc=%Rrc\n", GCPtrInstr, rc));
2468 }
2469#endif
2470
2471 pPatch->aNewOpcode[0] = 0xE9;
2472 *(RTRCUINTPTR *)&pPatch->aNewOpcode[1] = ((RTRCUINTPTR)pVM->hm.s.pFreeGuestPatchMem) - ((RTRCUINTPTR)pCtx->eip + 5);
2473
2474 /* Overwrite the TPR instruction with a jump. */
2475 rc = PGMPhysSimpleWriteGCPtr(pVCpu, pCtx->eip, pPatch->aNewOpcode, 5);
2476 AssertRC(rc);
2477
2478 DBGFR3_DISAS_INSTR_CUR_LOG(pVCpu, "Jump");
2479
2480 pVM->hm.s.pFreeGuestPatchMem += off;
2481 pPatch->cbNewOp = 5;
2482
2483 pPatch->Core.Key = pCtx->eip;
2484 rc = RTAvloU32Insert(&pVM->hm.s.PatchTree, &pPatch->Core);
2485 AssertRC(rc);
2486
2487 pVM->hm.s.cPatches++;
2488 pVM->hm.s.fTPRPatchingActive = true;
2489 STAM_COUNTER_INC(&pVM->hm.s.StatTprPatchSuccess);
2490 return VINF_SUCCESS;
2491 }
2492
2493 Log(("Ran out of space in our patch buffer!\n"));
2494 }
2495 else
2496 Log(("hmR3PatchTprInstr: Failed to patch instr!\n"));
2497
2498
2499 /*
2500 * Save invalid patch, so we will not try again.
2501 */
2502 pPatch = &pVM->hm.s.aPatches[idx];
2503 pPatch->Core.Key = pCtx->eip;
2504 pPatch->enmType = HMTPRINSTR_INVALID;
2505 rc = RTAvloU32Insert(&pVM->hm.s.PatchTree, &pPatch->Core);
2506 AssertRC(rc);
2507 pVM->hm.s.cPatches++;
2508 STAM_COUNTER_INC(&pVM->hm.s.StatTprPatchFailure);
2509 return VINF_SUCCESS;
2510}
2511
2512
2513/**
2514 * Attempt to patch TPR mmio instructions.
2515 *
2516 * @returns VBox status code.
2517 * @param pVM The cross context VM structure.
2518 * @param pVCpu The cross context virtual CPU structure.
2519 */
2520VMMR3_INT_DECL(int) HMR3PatchTprInstr(PVM pVM, PVMCPU pVCpu)
2521{
2522 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONE_BY_ONE,
2523 pVM->hm.s.pGuestPatchMem ? hmR3PatchTprInstr : hmR3ReplaceTprInstr,
2524 (void *)(uintptr_t)pVCpu->idCpu);
2525 AssertRC(rc);
2526 return rc;
2527}
2528
2529
2530/**
2531 * Checks if we need to reschedule due to VMM device heap changes.
2532 *
2533 * @returns true if a reschedule is required, otherwise false.
2534 * @param pVM The cross context VM structure.
2535 * @param pCtx VM execution context.
2536 */
2537VMMR3_INT_DECL(bool) HMR3IsRescheduleRequired(PVM pVM, PCCPUMCTX pCtx)
2538{
2539 /*
2540 * The VMM device heap is a requirement for emulating real-mode or protected-mode without paging
2541 * when the unrestricted guest execution feature is missing (VT-x only).
2542 */
2543 if ( pVM->hm.s.vmx.fEnabled
2544 && !pVM->hm.s.vmx.fUnrestrictedGuest
2545 && CPUMIsGuestInRealModeEx(pCtx)
2546 && !PDMVmmDevHeapIsEnabled(pVM))
2547 return true;
2548
2549 return false;
2550}
2551
2552
2553/**
2554 * Noticiation callback from DBGF when interrupt breakpoints or generic debug
2555 * event settings changes.
2556 *
2557 * DBGF will call HMR3NotifyDebugEventChangedPerCpu on each CPU afterwards, this
2558 * function is just updating the VM globals.
2559 *
2560 * @param pVM The VM cross context VM structure.
2561 * @thread EMT(0)
2562 */
2563VMMR3_INT_DECL(void) HMR3NotifyDebugEventChanged(PVM pVM)
2564{
2565 /* Interrupts. */
2566 bool fUseDebugLoop = pVM->dbgf.ro.cSoftIntBreakpoints > 0
2567 || pVM->dbgf.ro.cHardIntBreakpoints > 0;
2568
2569 /* CPU Exceptions. */
2570 for (DBGFEVENTTYPE enmEvent = DBGFEVENT_XCPT_FIRST;
2571 !fUseDebugLoop && enmEvent <= DBGFEVENT_XCPT_LAST;
2572 enmEvent = (DBGFEVENTTYPE)(enmEvent + 1))
2573 fUseDebugLoop = DBGF_IS_EVENT_ENABLED(pVM, enmEvent);
2574
2575 /* Common VM exits. */
2576 for (DBGFEVENTTYPE enmEvent = DBGFEVENT_EXIT_FIRST;
2577 !fUseDebugLoop && enmEvent <= DBGFEVENT_EXIT_LAST_COMMON;
2578 enmEvent = (DBGFEVENTTYPE)(enmEvent + 1))
2579 fUseDebugLoop = DBGF_IS_EVENT_ENABLED(pVM, enmEvent);
2580
2581 /* Vendor specific VM exits. */
2582 if (HMR3IsVmxEnabled(pVM->pUVM))
2583 for (DBGFEVENTTYPE enmEvent = DBGFEVENT_EXIT_VMX_FIRST;
2584 !fUseDebugLoop && enmEvent <= DBGFEVENT_EXIT_VMX_LAST;
2585 enmEvent = (DBGFEVENTTYPE)(enmEvent + 1))
2586 fUseDebugLoop = DBGF_IS_EVENT_ENABLED(pVM, enmEvent);
2587 else
2588 for (DBGFEVENTTYPE enmEvent = DBGFEVENT_EXIT_SVM_FIRST;
2589 !fUseDebugLoop && enmEvent <= DBGFEVENT_EXIT_SVM_LAST;
2590 enmEvent = (DBGFEVENTTYPE)(enmEvent + 1))
2591 fUseDebugLoop = DBGF_IS_EVENT_ENABLED(pVM, enmEvent);
2592
2593 /* Done. */
2594 pVM->hm.s.fUseDebugLoop = fUseDebugLoop;
2595}
2596
2597
2598/**
2599 * Follow up notification callback to HMR3NotifyDebugEventChanged for each CPU.
2600 *
2601 * HM uses this to combine the decision made by HMR3NotifyDebugEventChanged with
2602 * per CPU settings.
2603 *
2604 * @param pVM The VM cross context VM structure.
2605 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
2606 */
2607VMMR3_INT_DECL(void) HMR3NotifyDebugEventChangedPerCpu(PVM pVM, PVMCPU pVCpu)
2608{
2609 pVCpu->hm.s.fUseDebugLoop = pVCpu->hm.s.fSingleInstruction | pVM->hm.s.fUseDebugLoop;
2610}
2611
2612
2613/**
2614 * Checks if we are currently using hardware acceleration.
2615 *
2616 * @returns true if hardware acceleration is being used, otherwise false.
2617 * @param pVCpu The cross context virtual CPU structure.
2618 */
2619VMMR3_INT_DECL(bool) HMR3IsActive(PCVMCPU pVCpu)
2620{
2621 return pVCpu->hm.s.fActive;
2622}
2623
2624
2625/**
2626 * External interface for querying whether hardware acceleration is enabled.
2627 *
2628 * @returns true if VT-x or AMD-V is being used, otherwise false.
2629 * @param pUVM The user mode VM handle.
2630 * @sa HMIsEnabled, HMIsEnabledNotMacro.
2631 */
2632VMMR3DECL(bool) HMR3IsEnabled(PUVM pUVM)
2633{
2634 UVM_ASSERT_VALID_EXT_RETURN(pUVM, false);
2635 PVM pVM = pUVM->pVM;
2636 VM_ASSERT_VALID_EXT_RETURN(pVM, false);
2637 return pVM->fHMEnabled; /* Don't use the macro as the GUI may query us very very early. */
2638}
2639
2640
2641/**
2642 * External interface for querying whether VT-x is being used.
2643 *
2644 * @returns true if VT-x is being used, otherwise false.
2645 * @param pUVM The user mode VM handle.
2646 * @sa HMR3IsSvmEnabled, HMIsEnabled
2647 */
2648VMMR3DECL(bool) HMR3IsVmxEnabled(PUVM pUVM)
2649{
2650 UVM_ASSERT_VALID_EXT_RETURN(pUVM, false);
2651 PVM pVM = pUVM->pVM;
2652 VM_ASSERT_VALID_EXT_RETURN(pVM, false);
2653 return pVM->hm.s.vmx.fEnabled
2654 && pVM->hm.s.vmx.fSupported
2655 && pVM->fHMEnabled;
2656}
2657
2658
2659/**
2660 * External interface for querying whether AMD-V is being used.
2661 *
2662 * @returns true if VT-x is being used, otherwise false.
2663 * @param pUVM The user mode VM handle.
2664 * @sa HMR3IsVmxEnabled, HMIsEnabled
2665 */
2666VMMR3DECL(bool) HMR3IsSvmEnabled(PUVM pUVM)
2667{
2668 UVM_ASSERT_VALID_EXT_RETURN(pUVM, false);
2669 PVM pVM = pUVM->pVM;
2670 VM_ASSERT_VALID_EXT_RETURN(pVM, false);
2671 return pVM->hm.s.svm.fEnabled
2672 && pVM->hm.s.svm.fSupported
2673 && pVM->fHMEnabled;
2674}
2675
2676
2677/**
2678 * Checks if we are currently using nested paging.
2679 *
2680 * @returns true if nested paging is being used, otherwise false.
2681 * @param pUVM The user mode VM handle.
2682 */
2683VMMR3DECL(bool) HMR3IsNestedPagingActive(PUVM pUVM)
2684{
2685 UVM_ASSERT_VALID_EXT_RETURN(pUVM, false);
2686 PVM pVM = pUVM->pVM;
2687 VM_ASSERT_VALID_EXT_RETURN(pVM, false);
2688 return pVM->hm.s.fNestedPaging;
2689}
2690
2691
2692/**
2693 * Checks if virtualized APIC registers is enabled.
2694 *
2695 * When enabled this feature allows the hardware to access most of the
2696 * APIC registers in the virtual-APIC page without causing VM-exits. See
2697 * Intel spec. 29.1.1 "Virtualized APIC Registers".
2698 *
2699 * @returns true if virtualized APIC registers is enabled, otherwise
2700 * false.
2701 * @param pUVM The user mode VM handle.
2702 */
2703VMMR3DECL(bool) HMR3IsVirtApicRegsEnabled(PUVM pUVM)
2704{
2705 UVM_ASSERT_VALID_EXT_RETURN(pUVM, false);
2706 PVM pVM = pUVM->pVM;
2707 VM_ASSERT_VALID_EXT_RETURN(pVM, false);
2708 return pVM->hm.s.fVirtApicRegs;
2709}
2710
2711
2712/**
2713 * Checks if APIC posted-interrupt processing is enabled.
2714 *
2715 * This returns whether we can deliver interrupts to the guest without
2716 * leaving guest-context by updating APIC state from host-context.
2717 *
2718 * @returns true if APIC posted-interrupt processing is enabled,
2719 * otherwise false.
2720 * @param pUVM The user mode VM handle.
2721 */
2722VMMR3DECL(bool) HMR3IsPostedIntrsEnabled(PUVM pUVM)
2723{
2724 UVM_ASSERT_VALID_EXT_RETURN(pUVM, false);
2725 PVM pVM = pUVM->pVM;
2726 VM_ASSERT_VALID_EXT_RETURN(pVM, false);
2727 return pVM->hm.s.fPostedIntrs;
2728}
2729
2730
2731/**
2732 * Checks if we are currently using VPID in VT-x mode.
2733 *
2734 * @returns true if VPID is being used, otherwise false.
2735 * @param pUVM The user mode VM handle.
2736 */
2737VMMR3DECL(bool) HMR3IsVpidActive(PUVM pUVM)
2738{
2739 UVM_ASSERT_VALID_EXT_RETURN(pUVM, false);
2740 PVM pVM = pUVM->pVM;
2741 VM_ASSERT_VALID_EXT_RETURN(pVM, false);
2742 return pVM->hm.s.vmx.fVpid;
2743}
2744
2745
2746/**
2747 * Checks if we are currently using VT-x unrestricted execution,
2748 * aka UX.
2749 *
2750 * @returns true if UX is being used, otherwise false.
2751 * @param pUVM The user mode VM handle.
2752 */
2753VMMR3DECL(bool) HMR3IsUXActive(PUVM pUVM)
2754{
2755 UVM_ASSERT_VALID_EXT_RETURN(pUVM, false);
2756 PVM pVM = pUVM->pVM;
2757 VM_ASSERT_VALID_EXT_RETURN(pVM, false);
2758 return pVM->hm.s.vmx.fUnrestrictedGuest
2759 || pVM->hm.s.svm.fSupported;
2760}
2761
2762
2763/**
2764 * Checks if the VMX-preemption timer is being used.
2765 *
2766 * @returns true if the VMX-preemption timer is being used, otherwise false.
2767 * @param pVM The cross context VM structure.
2768 */
2769VMMR3_INT_DECL(bool) HMR3IsVmxPreemptionTimerUsed(PVM pVM)
2770{
2771 return HMIsEnabled(pVM)
2772 && pVM->hm.s.vmx.fEnabled
2773 && pVM->hm.s.vmx.fUsePreemptTimer;
2774}
2775
2776
2777/**
2778 * Helper for HMR3CheckError to log VMCS controls to the release log.
2779 *
2780 * @param idCpu The Virtual CPU ID.
2781 * @param pVmcsInfo The VMCS info. object.
2782 */
2783static void hmR3CheckErrorLogVmcsCtls(VMCPUID idCpu, PCVMXVMCSINFO pVmcsInfo)
2784{
2785 LogRel(("HM: CPU[%u] PinCtls %#RX32\n", idCpu, pVmcsInfo->u32PinCtls));
2786 {
2787 uint32_t const u32Val = pVmcsInfo->u32PinCtls;
2788 HMVMX_LOGREL_FEAT(u32Val, VMX_PIN_CTLS_EXT_INT_EXIT );
2789 HMVMX_LOGREL_FEAT(u32Val, VMX_PIN_CTLS_NMI_EXIT );
2790 HMVMX_LOGREL_FEAT(u32Val, VMX_PIN_CTLS_VIRT_NMI );
2791 HMVMX_LOGREL_FEAT(u32Val, VMX_PIN_CTLS_PREEMPT_TIMER);
2792 HMVMX_LOGREL_FEAT(u32Val, VMX_PIN_CTLS_POSTED_INT );
2793 }
2794 LogRel(("HM: CPU[%u] ProcCtls %#RX32\n", idCpu, pVmcsInfo->u32ProcCtls));
2795 {
2796 uint32_t const u32Val = pVmcsInfo->u32ProcCtls;
2797 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_INT_WINDOW_EXIT );
2798 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_USE_TSC_OFFSETTING);
2799 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_HLT_EXIT );
2800 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_INVLPG_EXIT );
2801 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_MWAIT_EXIT );
2802 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_RDPMC_EXIT );
2803 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_RDTSC_EXIT );
2804 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_CR3_LOAD_EXIT );
2805 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_CR3_STORE_EXIT );
2806 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_CR8_LOAD_EXIT );
2807 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_CR8_STORE_EXIT );
2808 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_USE_TPR_SHADOW );
2809 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_NMI_WINDOW_EXIT );
2810 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_MOV_DR_EXIT );
2811 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_UNCOND_IO_EXIT );
2812 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_USE_IO_BITMAPS );
2813 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_MONITOR_TRAP_FLAG );
2814 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_USE_MSR_BITMAPS );
2815 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_MONITOR_EXIT );
2816 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_PAUSE_EXIT );
2817 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_USE_SECONDARY_CTLS);
2818 }
2819 LogRel(("HM: CPU[%u] ProcCtls2 %#RX32\n", idCpu, pVmcsInfo->u32ProcCtls2));
2820 {
2821 uint32_t const u32Val = pVmcsInfo->u32ProcCtls2;
2822 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_VIRT_APIC_ACCESS );
2823 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_EPT );
2824 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_DESC_TABLE_EXIT );
2825 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_RDTSCP );
2826 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_VIRT_X2APIC_MODE );
2827 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_VPID );
2828 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_WBINVD_EXIT );
2829 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_UNRESTRICTED_GUEST );
2830 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_APIC_REG_VIRT );
2831 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_VIRT_INT_DELIVERY );
2832 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_PAUSE_LOOP_EXIT );
2833 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_RDRAND_EXIT );
2834 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_INVPCID );
2835 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_VMFUNC );
2836 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_VMCS_SHADOWING );
2837 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_ENCLS_EXIT );
2838 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_RDSEED_EXIT );
2839 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_PML );
2840 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_EPT_VE );
2841 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_CONCEAL_VMX_FROM_PT);
2842 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_XSAVES_XRSTORS );
2843 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_MODE_BASED_EPT_PERM);
2844 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_SPPTP_EPT );
2845 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_PT_EPT );
2846 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_TSC_SCALING );
2847 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_USER_WAIT_PAUSE );
2848 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_ENCLV_EXIT );
2849 }
2850 LogRel(("HM: CPU[%u] EntryCtls %#RX32\n", idCpu, pVmcsInfo->u32EntryCtls));
2851 {
2852 uint32_t const u32Val = pVmcsInfo->u32EntryCtls;
2853 HMVMX_LOGREL_FEAT(u32Val, VMX_ENTRY_CTLS_LOAD_DEBUG );
2854 HMVMX_LOGREL_FEAT(u32Val, VMX_ENTRY_CTLS_IA32E_MODE_GUEST );
2855 HMVMX_LOGREL_FEAT(u32Val, VMX_ENTRY_CTLS_ENTRY_TO_SMM );
2856 HMVMX_LOGREL_FEAT(u32Val, VMX_ENTRY_CTLS_DEACTIVATE_DUAL_MON);
2857 HMVMX_LOGREL_FEAT(u32Val, VMX_ENTRY_CTLS_LOAD_PERF_MSR );
2858 HMVMX_LOGREL_FEAT(u32Val, VMX_ENTRY_CTLS_LOAD_PAT_MSR );
2859 HMVMX_LOGREL_FEAT(u32Val, VMX_ENTRY_CTLS_LOAD_EFER_MSR );
2860 HMVMX_LOGREL_FEAT(u32Val, VMX_ENTRY_CTLS_LOAD_BNDCFGS_MSR );
2861 HMVMX_LOGREL_FEAT(u32Val, VMX_ENTRY_CTLS_CONCEAL_VMX_FROM_PT);
2862 HMVMX_LOGREL_FEAT(u32Val, VMX_ENTRY_CTLS_LOAD_RTIT_CTL_MSR );
2863 }
2864 LogRel(("HM: CPU[%u] ExitCtls %#RX32\n", idCpu, pVmcsInfo->u32ExitCtls));
2865 {
2866 uint32_t const u32Val = pVmcsInfo->u32ExitCtls;
2867 HMVMX_LOGREL_FEAT(u32Val, VMX_EXIT_CTLS_SAVE_DEBUG );
2868 HMVMX_LOGREL_FEAT(u32Val, VMX_EXIT_CTLS_HOST_ADDR_SPACE_SIZE );
2869 HMVMX_LOGREL_FEAT(u32Val, VMX_EXIT_CTLS_LOAD_PERF_MSR );
2870 HMVMX_LOGREL_FEAT(u32Val, VMX_EXIT_CTLS_ACK_EXT_INT );
2871 HMVMX_LOGREL_FEAT(u32Val, VMX_EXIT_CTLS_SAVE_PAT_MSR );
2872 HMVMX_LOGREL_FEAT(u32Val, VMX_EXIT_CTLS_LOAD_PAT_MSR );
2873 HMVMX_LOGREL_FEAT(u32Val, VMX_EXIT_CTLS_SAVE_EFER_MSR );
2874 HMVMX_LOGREL_FEAT(u32Val, VMX_EXIT_CTLS_LOAD_EFER_MSR );
2875 HMVMX_LOGREL_FEAT(u32Val, VMX_EXIT_CTLS_SAVE_PREEMPT_TIMER );
2876 HMVMX_LOGREL_FEAT(u32Val, VMX_EXIT_CTLS_CLEAR_BNDCFGS_MSR );
2877 HMVMX_LOGREL_FEAT(u32Val, VMX_EXIT_CTLS_CONCEAL_VMX_FROM_PT );
2878 HMVMX_LOGREL_FEAT(u32Val, VMX_EXIT_CTLS_CLEAR_RTIT_CTL_MSR );
2879 }
2880}
2881
2882
2883/**
2884 * Check fatal VT-x/AMD-V error and produce some meaningful
2885 * log release message.
2886 *
2887 * @param pVM The cross context VM structure.
2888 * @param iStatusCode VBox status code.
2889 */
2890VMMR3_INT_DECL(void) HMR3CheckError(PVM pVM, int iStatusCode)
2891{
2892 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
2893 {
2894 /** @todo r=ramshankar: Are all EMTs out of ring-0 at this point!? If not, we
2895 * might be getting inaccurate values for non-guru'ing EMTs. */
2896 PVMCPU pVCpu = pVM->apCpusR3[idCpu];
2897 PCVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
2898 bool const fNstGstVmcsActive = pVCpu->hm.s.vmx.fSwitchedToNstGstVmcs;
2899 switch (iStatusCode)
2900 {
2901 case VERR_VMX_INVALID_VMCS_PTR:
2902 {
2903 LogRel(("HM: VERR_VMX_INVALID_VMCS_PTR:\n"));
2904 LogRel(("HM: CPU[%u] %s VMCS active\n", idCpu, fNstGstVmcsActive ? "Nested-guest" : "Guest"));
2905 LogRel(("HM: CPU[%u] Current pointer %#RHp vs %#RHp\n", idCpu, pVCpu->hm.s.vmx.LastError.HCPhysCurrentVmcs,
2906 pVmcsInfo->HCPhysVmcs));
2907 LogRel(("HM: CPU[%u] Current VMCS version %#x\n", idCpu, pVCpu->hm.s.vmx.LastError.u32VmcsRev));
2908 LogRel(("HM: CPU[%u] Entered Host Cpu %u\n", idCpu, pVCpu->hm.s.vmx.LastError.idEnteredCpu));
2909 LogRel(("HM: CPU[%u] Current Host Cpu %u\n", idCpu, pVCpu->hm.s.vmx.LastError.idCurrentCpu));
2910 break;
2911 }
2912
2913 case VERR_VMX_UNABLE_TO_START_VM:
2914 {
2915 LogRel(("HM: VERR_VMX_UNABLE_TO_START_VM:\n"));
2916 LogRel(("HM: CPU[%u] %s VMCS active\n", idCpu, fNstGstVmcsActive ? "Nested-guest" : "Guest"));
2917 LogRel(("HM: CPU[%u] Instruction error %#x\n", idCpu, pVCpu->hm.s.vmx.LastError.u32InstrError));
2918 LogRel(("HM: CPU[%u] Exit reason %#x\n", idCpu, pVCpu->hm.s.vmx.LastError.u32ExitReason));
2919
2920 if ( pVCpu->hm.s.vmx.LastError.u32InstrError == VMXINSTRERR_VMLAUNCH_NON_CLEAR_VMCS
2921 || pVCpu->hm.s.vmx.LastError.u32InstrError == VMXINSTRERR_VMRESUME_NON_LAUNCHED_VMCS)
2922 {
2923 LogRel(("HM: CPU[%u] Entered Host Cpu %u\n", idCpu, pVCpu->hm.s.vmx.LastError.idEnteredCpu));
2924 LogRel(("HM: CPU[%u] Current Host Cpu %u\n", idCpu, pVCpu->hm.s.vmx.LastError.idCurrentCpu));
2925 }
2926 else if (pVCpu->hm.s.vmx.LastError.u32InstrError == VMXINSTRERR_VMENTRY_INVALID_CTLS)
2927 {
2928 hmR3CheckErrorLogVmcsCtls(idCpu, pVmcsInfo);
2929 LogRel(("HM: CPU[%u] HCPhysMsrBitmap %#RHp\n", idCpu, pVmcsInfo->HCPhysMsrBitmap));
2930 LogRel(("HM: CPU[%u] HCPhysGuestMsrLoad %#RHp\n", idCpu, pVmcsInfo->HCPhysGuestMsrLoad));
2931 LogRel(("HM: CPU[%u] HCPhysGuestMsrStore %#RHp\n", idCpu, pVmcsInfo->HCPhysGuestMsrStore));
2932 LogRel(("HM: CPU[%u] HCPhysHostMsrLoad %#RHp\n", idCpu, pVmcsInfo->HCPhysHostMsrLoad));
2933 LogRel(("HM: CPU[%u] cEntryMsrLoad %u\n", idCpu, pVmcsInfo->cEntryMsrLoad));
2934 LogRel(("HM: CPU[%u] cExitMsrStore %u\n", idCpu, pVmcsInfo->cExitMsrStore));
2935 LogRel(("HM: CPU[%u] cExitMsrLoad %u\n", idCpu, pVmcsInfo->cExitMsrLoad));
2936 }
2937 /** @todo Log VM-entry event injection control fields
2938 * VMX_VMCS_CTRL_ENTRY_IRQ_INFO, VMX_VMCS_CTRL_ENTRY_EXCEPTION_ERRCODE
2939 * and VMX_VMCS_CTRL_ENTRY_INSTR_LENGTH from the VMCS. */
2940 break;
2941 }
2942
2943 case VERR_VMX_INVALID_GUEST_STATE:
2944 {
2945 LogRel(("HM: VERR_VMX_INVALID_GUEST_STATE:\n"));
2946 hmR3CheckErrorLogVmcsCtls(idCpu, pVmcsInfo);
2947 break;
2948 }
2949
2950 /* The guru will dump the HM error and exit history. Nothing extra to report for these errors. */
2951 case VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO:
2952 case VERR_VMX_INVALID_VMXON_PTR:
2953 case VERR_VMX_UNEXPECTED_EXIT:
2954 case VERR_VMX_INVALID_VMCS_FIELD:
2955 case VERR_SVM_UNKNOWN_EXIT:
2956 case VERR_SVM_UNEXPECTED_EXIT:
2957 case VERR_SVM_UNEXPECTED_PATCH_TYPE:
2958 case VERR_SVM_UNEXPECTED_XCPT_EXIT:
2959 case VERR_VMX_UNEXPECTED_INTERRUPTION_EXIT_TYPE:
2960 break;
2961 }
2962 }
2963
2964 if (iStatusCode == VERR_VMX_UNABLE_TO_START_VM)
2965 {
2966 LogRel(("HM: VERR_VMX_UNABLE_TO_START_VM: VM-entry allowed-1 %#RX32\n", pVM->hm.s.vmx.Msrs.EntryCtls.n.allowed1));
2967 LogRel(("HM: VERR_VMX_UNABLE_TO_START_VM: VM-entry allowed-0 %#RX32\n", pVM->hm.s.vmx.Msrs.EntryCtls.n.allowed0));
2968 }
2969 else if (iStatusCode == VERR_VMX_INVALID_VMXON_PTR)
2970 LogRel(("HM: HCPhysVmxEnableError = %#RHp\n", pVM->hm.s.vmx.HCPhysVmxEnableError));
2971}
2972
2973
2974/**
2975 * Execute state save operation.
2976 *
2977 * Save only data that cannot be re-loaded while entering HM ring-0 code. This
2978 * is because we always save the VM state from ring-3 and thus most HM state
2979 * will be re-synced dynamically at runtime and don't need to be part of the VM
2980 * saved state.
2981 *
2982 * @returns VBox status code.
2983 * @param pVM The cross context VM structure.
2984 * @param pSSM SSM operation handle.
2985 */
2986static DECLCALLBACK(int) hmR3Save(PVM pVM, PSSMHANDLE pSSM)
2987{
2988 int rc;
2989
2990 Log(("hmR3Save:\n"));
2991
2992 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
2993 {
2994 PVMCPU pVCpu = pVM->apCpusR3[idCpu];
2995 Assert(!pVCpu->hm.s.Event.fPending);
2996 if (pVM->cpum.ro.GuestFeatures.fSvm)
2997 {
2998 PCSVMNESTEDVMCBCACHE pVmcbNstGstCache = &pVCpu->hm.s.svm.NstGstVmcbCache;
2999 rc = SSMR3PutBool(pSSM, pVmcbNstGstCache->fCacheValid);
3000 rc |= SSMR3PutU16(pSSM, pVmcbNstGstCache->u16InterceptRdCRx);
3001 rc |= SSMR3PutU16(pSSM, pVmcbNstGstCache->u16InterceptWrCRx);
3002 rc |= SSMR3PutU16(pSSM, pVmcbNstGstCache->u16InterceptRdDRx);
3003 rc |= SSMR3PutU16(pSSM, pVmcbNstGstCache->u16InterceptWrDRx);
3004 rc |= SSMR3PutU16(pSSM, pVmcbNstGstCache->u16PauseFilterThreshold);
3005 rc |= SSMR3PutU16(pSSM, pVmcbNstGstCache->u16PauseFilterCount);
3006 rc |= SSMR3PutU32(pSSM, pVmcbNstGstCache->u32InterceptXcpt);
3007 rc |= SSMR3PutU64(pSSM, pVmcbNstGstCache->u64InterceptCtrl);
3008 rc |= SSMR3PutU64(pSSM, pVmcbNstGstCache->u64TSCOffset);
3009 rc |= SSMR3PutBool(pSSM, pVmcbNstGstCache->fVIntrMasking);
3010 rc |= SSMR3PutBool(pSSM, pVmcbNstGstCache->fNestedPaging);
3011 rc |= SSMR3PutBool(pSSM, pVmcbNstGstCache->fLbrVirt);
3012 AssertRCReturn(rc, rc);
3013 }
3014 }
3015
3016 /* Save the guest patch data. */
3017 rc = SSMR3PutGCPtr(pSSM, pVM->hm.s.pGuestPatchMem);
3018 rc |= SSMR3PutGCPtr(pSSM, pVM->hm.s.pFreeGuestPatchMem);
3019 rc |= SSMR3PutU32(pSSM, pVM->hm.s.cbGuestPatchMem);
3020
3021 /* Store all the guest patch records too. */
3022 rc |= SSMR3PutU32(pSSM, pVM->hm.s.cPatches);
3023 AssertRCReturn(rc, rc);
3024
3025 for (uint32_t i = 0; i < pVM->hm.s.cPatches; i++)
3026 {
3027 AssertCompileSize(HMTPRINSTR, 4);
3028 PCHMTPRPATCH pPatch = &pVM->hm.s.aPatches[i];
3029 rc = SSMR3PutU32(pSSM, pPatch->Core.Key);
3030 rc |= SSMR3PutMem(pSSM, pPatch->aOpcode, sizeof(pPatch->aOpcode));
3031 rc |= SSMR3PutU32(pSSM, pPatch->cbOp);
3032 rc |= SSMR3PutMem(pSSM, pPatch->aNewOpcode, sizeof(pPatch->aNewOpcode));
3033 rc |= SSMR3PutU32(pSSM, pPatch->cbNewOp);
3034 rc |= SSMR3PutU32(pSSM, (uint32_t)pPatch->enmType);
3035 rc |= SSMR3PutU32(pSSM, pPatch->uSrcOperand);
3036 rc |= SSMR3PutU32(pSSM, pPatch->uDstOperand);
3037 rc |= SSMR3PutU32(pSSM, pPatch->pJumpTarget);
3038 rc |= SSMR3PutU32(pSSM, pPatch->cFaults);
3039 AssertRCReturn(rc, rc);
3040 }
3041
3042 return VINF_SUCCESS;
3043}
3044
3045
3046/**
3047 * Execute state load operation.
3048 *
3049 * @returns VBox status code.
3050 * @param pVM The cross context VM structure.
3051 * @param pSSM SSM operation handle.
3052 * @param uVersion Data layout version.
3053 * @param uPass The data pass.
3054 */
3055static DECLCALLBACK(int) hmR3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
3056{
3057 int rc;
3058
3059 LogFlowFunc(("uVersion=%u\n", uVersion));
3060 Assert(uPass == SSM_PASS_FINAL); NOREF(uPass);
3061
3062 /*
3063 * Validate version.
3064 */
3065 if ( uVersion != HM_SAVED_STATE_VERSION_SVM_NESTED_HWVIRT
3066 && uVersion != HM_SAVED_STATE_VERSION_TPR_PATCHING
3067 && uVersion != HM_SAVED_STATE_VERSION_NO_TPR_PATCHING
3068 && uVersion != HM_SAVED_STATE_VERSION_2_0_X)
3069 {
3070 AssertMsgFailed(("hmR3Load: Invalid version uVersion=%d!\n", uVersion));
3071 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
3072 }
3073
3074 /*
3075 * Load per-VCPU state.
3076 */
3077 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
3078 {
3079 PVMCPU pVCpu = pVM->apCpusR3[idCpu];
3080 if (uVersion >= HM_SAVED_STATE_VERSION_SVM_NESTED_HWVIRT)
3081 {
3082 /* Load the SVM nested hw.virt state if the VM is configured for it. */
3083 if (pVM->cpum.ro.GuestFeatures.fSvm)
3084 {
3085 PSVMNESTEDVMCBCACHE pVmcbNstGstCache = &pVCpu->hm.s.svm.NstGstVmcbCache;
3086 rc = SSMR3GetBool(pSSM, &pVmcbNstGstCache->fCacheValid);
3087 rc |= SSMR3GetU16(pSSM, &pVmcbNstGstCache->u16InterceptRdCRx);
3088 rc |= SSMR3GetU16(pSSM, &pVmcbNstGstCache->u16InterceptWrCRx);
3089 rc |= SSMR3GetU16(pSSM, &pVmcbNstGstCache->u16InterceptRdDRx);
3090 rc |= SSMR3GetU16(pSSM, &pVmcbNstGstCache->u16InterceptWrDRx);
3091 rc |= SSMR3GetU16(pSSM, &pVmcbNstGstCache->u16PauseFilterThreshold);
3092 rc |= SSMR3GetU16(pSSM, &pVmcbNstGstCache->u16PauseFilterCount);
3093 rc |= SSMR3GetU32(pSSM, &pVmcbNstGstCache->u32InterceptXcpt);
3094 rc |= SSMR3GetU64(pSSM, &pVmcbNstGstCache->u64InterceptCtrl);
3095 rc |= SSMR3GetU64(pSSM, &pVmcbNstGstCache->u64TSCOffset);
3096 rc |= SSMR3GetBool(pSSM, &pVmcbNstGstCache->fVIntrMasking);
3097 rc |= SSMR3GetBool(pSSM, &pVmcbNstGstCache->fNestedPaging);
3098 rc |= SSMR3GetBool(pSSM, &pVmcbNstGstCache->fLbrVirt);
3099 AssertRCReturn(rc, rc);
3100 }
3101 }
3102 else
3103 {
3104 /* Pending HM event (obsolete for a long time since TPRM holds the info.) */
3105 rc = SSMR3GetU32(pSSM, &pVCpu->hm.s.Event.fPending);
3106 rc |= SSMR3GetU32(pSSM, &pVCpu->hm.s.Event.u32ErrCode);
3107 rc |= SSMR3GetU64(pSSM, &pVCpu->hm.s.Event.u64IntInfo);
3108
3109 /* VMX fWasInRealMode related data. */
3110 uint32_t uDummy;
3111 rc |= SSMR3GetU32(pSSM, &uDummy); AssertRCReturn(rc, rc);
3112 rc |= SSMR3GetU32(pSSM, &uDummy); AssertRCReturn(rc, rc);
3113 rc |= SSMR3GetU32(pSSM, &uDummy); AssertRCReturn(rc, rc);
3114 AssertRCReturn(rc, rc);
3115 }
3116 }
3117
3118 /*
3119 * Load TPR patching data.
3120 */
3121 if (uVersion >= HM_SAVED_STATE_VERSION_TPR_PATCHING)
3122 {
3123 rc = SSMR3GetGCPtr(pSSM, &pVM->hm.s.pGuestPatchMem);
3124 rc |= SSMR3GetGCPtr(pSSM, &pVM->hm.s.pFreeGuestPatchMem);
3125 rc |= SSMR3GetU32(pSSM, &pVM->hm.s.cbGuestPatchMem);
3126
3127 /* Fetch all TPR patch records. */
3128 rc |= SSMR3GetU32(pSSM, &pVM->hm.s.cPatches);
3129 AssertRCReturn(rc, rc);
3130 for (uint32_t i = 0; i < pVM->hm.s.cPatches; i++)
3131 {
3132 PHMTPRPATCH pPatch = &pVM->hm.s.aPatches[i];
3133 rc = SSMR3GetU32(pSSM, &pPatch->Core.Key);
3134 rc |= SSMR3GetMem(pSSM, pPatch->aOpcode, sizeof(pPatch->aOpcode));
3135 rc |= SSMR3GetU32(pSSM, &pPatch->cbOp);
3136 rc |= SSMR3GetMem(pSSM, pPatch->aNewOpcode, sizeof(pPatch->aNewOpcode));
3137 rc |= SSMR3GetU32(pSSM, &pPatch->cbNewOp);
3138 rc |= SSMR3GetU32(pSSM, (uint32_t *)&pPatch->enmType);
3139
3140 if (pPatch->enmType == HMTPRINSTR_JUMP_REPLACEMENT)
3141 pVM->hm.s.fTPRPatchingActive = true;
3142 Assert(pPatch->enmType == HMTPRINSTR_JUMP_REPLACEMENT || pVM->hm.s.fTPRPatchingActive == false);
3143
3144 rc |= SSMR3GetU32(pSSM, &pPatch->uSrcOperand);
3145 rc |= SSMR3GetU32(pSSM, &pPatch->uDstOperand);
3146 rc |= SSMR3GetU32(pSSM, &pPatch->cFaults);
3147 rc |= SSMR3GetU32(pSSM, &pPatch->pJumpTarget);
3148 AssertRCReturn(rc, rc);
3149
3150 LogFlow(("hmR3Load: patch %d\n", i));
3151 LogFlow(("Key = %x\n", pPatch->Core.Key));
3152 LogFlow(("cbOp = %d\n", pPatch->cbOp));
3153 LogFlow(("cbNewOp = %d\n", pPatch->cbNewOp));
3154 LogFlow(("type = %d\n", pPatch->enmType));
3155 LogFlow(("srcop = %d\n", pPatch->uSrcOperand));
3156 LogFlow(("dstop = %d\n", pPatch->uDstOperand));
3157 LogFlow(("cFaults = %d\n", pPatch->cFaults));
3158 LogFlow(("target = %x\n", pPatch->pJumpTarget));
3159
3160 rc = RTAvloU32Insert(&pVM->hm.s.PatchTree, &pPatch->Core);
3161 AssertRCReturn(rc, rc);
3162 }
3163 }
3164
3165 return VINF_SUCCESS;
3166}
3167
3168
3169/**
3170 * Displays HM info.
3171 *
3172 * @param pVM The cross context VM structure.
3173 * @param pHlp The info helper functions.
3174 * @param pszArgs Arguments, ignored.
3175 */
3176static DECLCALLBACK(void) hmR3Info(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
3177{
3178 NOREF(pszArgs);
3179 PVMCPU pVCpu = VMMGetCpu(pVM);
3180 if (!pVCpu)
3181 pVCpu = pVM->apCpusR3[0];
3182
3183 if (HMIsEnabled(pVM))
3184 {
3185 if (pVM->hm.s.vmx.fSupported)
3186 pHlp->pfnPrintf(pHlp, "CPU[%u]: VT-x info:\n", pVCpu->idCpu);
3187 else
3188 pHlp->pfnPrintf(pHlp, "CPU[%u]: AMD-V info:\n", pVCpu->idCpu);
3189 pHlp->pfnPrintf(pHlp, " HM error = %#x (%u)\n", pVCpu->hm.s.u32HMError, pVCpu->hm.s.u32HMError);
3190 pHlp->pfnPrintf(pHlp, " rcLastExitToR3 = %Rrc\n", pVCpu->hm.s.rcLastExitToR3);
3191 if (pVM->hm.s.vmx.fSupported)
3192 {
3193 PCVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
3194 bool const fRealOnV86Active = pVmcsInfo->RealMode.fRealOnV86Active;
3195 bool const fNstGstVmcsActive = pVCpu->hm.s.vmx.fSwitchedToNstGstVmcs;
3196
3197 pHlp->pfnPrintf(pHlp, " %s VMCS active\n", fNstGstVmcsActive ? "Nested-guest" : "Guest");
3198 pHlp->pfnPrintf(pHlp, " Real-on-v86 active = %RTbool\n", fRealOnV86Active);
3199 if (fRealOnV86Active)
3200 {
3201 pHlp->pfnPrintf(pHlp, " EFlags = %#x\n", pVmcsInfo->RealMode.Eflags.u32);
3202 pHlp->pfnPrintf(pHlp, " Attr CS = %#x\n", pVmcsInfo->RealMode.AttrCS.u);
3203 pHlp->pfnPrintf(pHlp, " Attr SS = %#x\n", pVmcsInfo->RealMode.AttrSS.u);
3204 pHlp->pfnPrintf(pHlp, " Attr DS = %#x\n", pVmcsInfo->RealMode.AttrDS.u);
3205 pHlp->pfnPrintf(pHlp, " Attr ES = %#x\n", pVmcsInfo->RealMode.AttrES.u);
3206 pHlp->pfnPrintf(pHlp, " Attr FS = %#x\n", pVmcsInfo->RealMode.AttrFS.u);
3207 pHlp->pfnPrintf(pHlp, " Attr GS = %#x\n", pVmcsInfo->RealMode.AttrGS.u);
3208 }
3209 }
3210 }
3211 else
3212 pHlp->pfnPrintf(pHlp, "HM is not enabled for this VM!\n");
3213}
3214
3215
3216/**
3217 * Displays the HM pending event.
3218 *
3219 * @param pVM The cross context VM structure.
3220 * @param pHlp The info helper functions.
3221 * @param pszArgs Arguments, ignored.
3222 */
3223static DECLCALLBACK(void) hmR3InfoEventPending(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
3224{
3225 NOREF(pszArgs);
3226 PVMCPU pVCpu = VMMGetCpu(pVM);
3227 if (!pVCpu)
3228 pVCpu = pVM->apCpusR3[0];
3229
3230 if (HMIsEnabled(pVM))
3231 {
3232 pHlp->pfnPrintf(pHlp, "CPU[%u]: HM event (fPending=%RTbool)\n", pVCpu->idCpu, pVCpu->hm.s.Event.fPending);
3233 if (pVCpu->hm.s.Event.fPending)
3234 {
3235 pHlp->pfnPrintf(pHlp, " u64IntInfo = %#RX64\n", pVCpu->hm.s.Event.u64IntInfo);
3236 pHlp->pfnPrintf(pHlp, " u32ErrCode = %#RX64\n", pVCpu->hm.s.Event.u32ErrCode);
3237 pHlp->pfnPrintf(pHlp, " cbInstr = %u bytes\n", pVCpu->hm.s.Event.cbInstr);
3238 pHlp->pfnPrintf(pHlp, " GCPtrFaultAddress = %#RGp\n", pVCpu->hm.s.Event.GCPtrFaultAddress);
3239 }
3240 }
3241 else
3242 pHlp->pfnPrintf(pHlp, "HM is not enabled for this VM!\n");
3243}
3244
3245
3246/**
3247 * Displays the SVM nested-guest VMCB cache.
3248 *
3249 * @param pVM The cross context VM structure.
3250 * @param pHlp The info helper functions.
3251 * @param pszArgs Arguments, ignored.
3252 */
3253static DECLCALLBACK(void) hmR3InfoSvmNstGstVmcbCache(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
3254{
3255 NOREF(pszArgs);
3256 PVMCPU pVCpu = VMMGetCpu(pVM);
3257 if (!pVCpu)
3258 pVCpu = pVM->apCpusR3[0];
3259
3260 bool const fSvmEnabled = HMR3IsSvmEnabled(pVM->pUVM);
3261 if ( fSvmEnabled
3262 && pVM->cpum.ro.GuestFeatures.fSvm)
3263 {
3264 PCSVMNESTEDVMCBCACHE pVmcbNstGstCache = &pVCpu->hm.s.svm.NstGstVmcbCache;
3265 pHlp->pfnPrintf(pHlp, "CPU[%u]: HM SVM nested-guest VMCB cache\n", pVCpu->idCpu);
3266 pHlp->pfnPrintf(pHlp, " fCacheValid = %#RTbool\n", pVmcbNstGstCache->fCacheValid);
3267 pHlp->pfnPrintf(pHlp, " u16InterceptRdCRx = %#RX16\n", pVmcbNstGstCache->u16InterceptRdCRx);
3268 pHlp->pfnPrintf(pHlp, " u16InterceptWrCRx = %#RX16\n", pVmcbNstGstCache->u16InterceptWrCRx);
3269 pHlp->pfnPrintf(pHlp, " u16InterceptRdDRx = %#RX16\n", pVmcbNstGstCache->u16InterceptRdDRx);
3270 pHlp->pfnPrintf(pHlp, " u16InterceptWrDRx = %#RX16\n", pVmcbNstGstCache->u16InterceptWrDRx);
3271 pHlp->pfnPrintf(pHlp, " u16PauseFilterThreshold = %#RX16\n", pVmcbNstGstCache->u16PauseFilterThreshold);
3272 pHlp->pfnPrintf(pHlp, " u16PauseFilterCount = %#RX16\n", pVmcbNstGstCache->u16PauseFilterCount);
3273 pHlp->pfnPrintf(pHlp, " u32InterceptXcpt = %#RX32\n", pVmcbNstGstCache->u32InterceptXcpt);
3274 pHlp->pfnPrintf(pHlp, " u64InterceptCtrl = %#RX64\n", pVmcbNstGstCache->u64InterceptCtrl);
3275 pHlp->pfnPrintf(pHlp, " u64TSCOffset = %#RX64\n", pVmcbNstGstCache->u64TSCOffset);
3276 pHlp->pfnPrintf(pHlp, " fVIntrMasking = %RTbool\n", pVmcbNstGstCache->fVIntrMasking);
3277 pHlp->pfnPrintf(pHlp, " fNestedPaging = %RTbool\n", pVmcbNstGstCache->fNestedPaging);
3278 pHlp->pfnPrintf(pHlp, " fLbrVirt = %RTbool\n", pVmcbNstGstCache->fLbrVirt);
3279 }
3280 else
3281 {
3282 if (!fSvmEnabled)
3283 pHlp->pfnPrintf(pHlp, "HM SVM is not enabled for this VM!\n");
3284 else
3285 pHlp->pfnPrintf(pHlp, "SVM feature is not exposed to the guest!\n");
3286 }
3287}
3288
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