VirtualBox

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

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

VMM/HM: Nested VMX: bugref:9180 Comment on where to tweak host MSRs for testing VMX/SVM R0 code. Added 'full' or 'partial' VMCS shadowing support to the release log.

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

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