VirtualBox

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

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

VMM: Kicking out 32-bit host support - VMX [drop VMCSCACHE]. bugref:9511

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