VirtualBox

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

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

VMM/HM: Implement last-branch-record (LBR) support for guests executed using hardware-assisted VT-x. Enable per-VM using CFGM.

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