VirtualBox

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

Last change on this file since 78402 was 78254, checked in by vboxsync, 6 years ago

VMM/HM: const bits.

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