VirtualBox

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

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

VMM/HM: Nested VMX: bugref:9180 space.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 152.7 KB
Line 
1/* $Id: HM.cpp 79117 2019-06-13 06:03:32Z 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 * Enable VPID if configured and supported.
1600 */
1601 if (pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_VPID)
1602 pVM->hm.s.vmx.fVpid = pVM->hm.s.vmx.fAllowVpid;
1603
1604#if 0
1605 /*
1606 * Enable APIC register virtualization and virtual-interrupt delivery if supported.
1607 */
1608 if ( (pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_APIC_REG_VIRT)
1609 && (pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_VIRT_INTR_DELIVERY))
1610 pVM->hm.s.fVirtApicRegs = true;
1611
1612 /*
1613 * Enable posted-interrupt processing if supported.
1614 */
1615 /** @todo Add and query IPRT API for host OS support for posted-interrupt IPI
1616 * here. */
1617 if ( (pVM->hm.s.vmx.Msrs.PinCtls.n.allowed1 & VMX_PIN_CTLS_POSTED_INT)
1618 && (pVM->hm.s.vmx.Msrs.ExitCtls.n.allowed1 & VMX_EXIT_CTLS_ACK_EXT_INT))
1619 pVM->hm.s.fPostedIntrs = true;
1620#endif
1621
1622 /*
1623 * Disallow RDTSCP in the guest if there is no secondary process-based VM execution controls as otherwise
1624 * RDTSCP would cause a #UD. There might be no CPUs out there where this happens, as RDTSCP was introduced
1625 * in Nehalems and secondary VM exec. controls should be supported in all of them, but nonetheless it's Intel...
1626 */
1627 if ( !(pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_SECONDARY_CTLS)
1628 && CPUMR3GetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_RDTSCP))
1629 {
1630 CPUMR3ClearGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_RDTSCP);
1631 LogRel(("HM: Disabled RDTSCP\n"));
1632 }
1633
1634 if (!pVM->hm.s.vmx.fUnrestrictedGuest)
1635 {
1636 /* Allocate three pages for the TSS we need for real mode emulation. (2 pages for the IO bitmap) */
1637 rc = PDMR3VmmDevHeapAlloc(pVM, HM_VTX_TOTAL_DEVHEAP_MEM, hmR3VmmDevHeapNotify, (RTR3PTR *)&pVM->hm.s.vmx.pRealModeTSS);
1638 if (RT_SUCCESS(rc))
1639 {
1640 /* The IO bitmap starts right after the virtual interrupt redirection bitmap.
1641 Refer Intel spec. 20.3.3 "Software Interrupt Handling in Virtual-8086 mode"
1642 esp. Figure 20-5.*/
1643 ASMMemZero32(pVM->hm.s.vmx.pRealModeTSS, sizeof(*pVM->hm.s.vmx.pRealModeTSS));
1644 pVM->hm.s.vmx.pRealModeTSS->offIoBitmap = sizeof(*pVM->hm.s.vmx.pRealModeTSS);
1645
1646 /* Bit set to 0 means software interrupts are redirected to the
1647 8086 program interrupt handler rather than switching to
1648 protected-mode handler. */
1649 memset(pVM->hm.s.vmx.pRealModeTSS->IntRedirBitmap, 0, sizeof(pVM->hm.s.vmx.pRealModeTSS->IntRedirBitmap));
1650
1651 /* Allow all port IO, so that port IO instructions do not cause
1652 exceptions and would instead cause a VM-exit (based on VT-x's
1653 IO bitmap which we currently configure to always cause an exit). */
1654 memset(pVM->hm.s.vmx.pRealModeTSS + 1, 0, PAGE_SIZE * 2);
1655 *((unsigned char *)pVM->hm.s.vmx.pRealModeTSS + HM_VTX_TSS_SIZE - 2) = 0xff;
1656
1657 /*
1658 * Construct a 1024 element page directory with 4 MB pages for the identity mapped
1659 * page table used in real and protected mode without paging with EPT.
1660 */
1661 pVM->hm.s.vmx.pNonPagingModeEPTPageTable = (PX86PD)((char *)pVM->hm.s.vmx.pRealModeTSS + PAGE_SIZE * 3);
1662 for (uint32_t i = 0; i < X86_PG_ENTRIES; i++)
1663 {
1664 pVM->hm.s.vmx.pNonPagingModeEPTPageTable->a[i].u = _4M * i;
1665 pVM->hm.s.vmx.pNonPagingModeEPTPageTable->a[i].u |= X86_PDE4M_P | X86_PDE4M_RW | X86_PDE4M_US
1666 | X86_PDE4M_A | X86_PDE4M_D | X86_PDE4M_PS
1667 | X86_PDE4M_G;
1668 }
1669
1670 /* We convert it here every time as PCI regions could be reconfigured. */
1671 if (PDMVmmDevHeapIsEnabled(pVM))
1672 {
1673 RTGCPHYS GCPhys;
1674 rc = PDMVmmDevHeapR3ToGCPhys(pVM, pVM->hm.s.vmx.pRealModeTSS, &GCPhys);
1675 AssertRCReturn(rc, rc);
1676 LogRel(("HM: Real Mode TSS guest physaddr = %#RGp\n", GCPhys));
1677
1678 rc = PDMVmmDevHeapR3ToGCPhys(pVM, pVM->hm.s.vmx.pNonPagingModeEPTPageTable, &GCPhys);
1679 AssertRCReturn(rc, rc);
1680 LogRel(("HM: Non-Paging Mode EPT CR3 = %#RGp\n", GCPhys));
1681 }
1682 }
1683 else
1684 {
1685 LogRel(("HM: No real mode VT-x support (PDMR3VMMDevHeapAlloc returned %Rrc)\n", rc));
1686 pVM->hm.s.vmx.pRealModeTSS = NULL;
1687 pVM->hm.s.vmx.pNonPagingModeEPTPageTable = NULL;
1688 return VMSetError(pVM, rc, RT_SRC_POS,
1689 "HM failure: No real mode VT-x support (PDMR3VMMDevHeapAlloc returned %Rrc)", rc);
1690 }
1691 }
1692
1693 LogRel((pVM->hm.s.fAllow64BitGuests
1694 ? "HM: Guest support: 32-bit and 64-bit\n"
1695 : "HM: Guest support: 32-bit only\n"));
1696
1697 /*
1698 * Call ring-0 to set up the VM.
1699 */
1700 rc = SUPR3CallVMMR0Ex(pVM->pVMR0, 0 /* idCpu */, VMMR0_DO_HM_SETUP_VM, 0 /* u64Arg */, NULL /* pReqHdr */);
1701 if (rc != VINF_SUCCESS)
1702 {
1703 LogRel(("HM: VMX setup failed with rc=%Rrc!\n", rc));
1704 for (VMCPUID i = 0; i < pVM->cCpus; i++)
1705 {
1706 PVMCPU pVCpu = &pVM->aCpus[i];
1707 LogRel(("HM: CPU[%u] Last instruction error %#x\n", i, pVCpu->hm.s.vmx.LastError.u32InstrError));
1708 LogRel(("HM: CPU[%u] HM error %#x (%u)\n", i, pVCpu->hm.s.u32HMError, pVCpu->hm.s.u32HMError));
1709 }
1710 HMR3CheckError(pVM, rc);
1711 return VMSetError(pVM, rc, RT_SRC_POS, "VT-x setup failed: %Rrc", rc);
1712 }
1713
1714 LogRel(("HM: Supports VMCS EFER fields = %RTbool\n", pVM->hm.s.vmx.fSupportsVmcsEfer));
1715 LogRel(("HM: Enabled VMX\n"));
1716 pVM->hm.s.vmx.fEnabled = true;
1717
1718 hmR3DisableRawMode(pVM); /** @todo make this go away! */
1719
1720 /*
1721 * Change the CPU features.
1722 */
1723 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_SEP);
1724 if (pVM->hm.s.fAllow64BitGuests)
1725 {
1726 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_PAE);
1727 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_LONG_MODE);
1728 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_SYSCALL); /* 64 bits only on Intel CPUs */
1729 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_LAHF);
1730 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_NX);
1731 }
1732 /* Turn on NXE if PAE has been enabled *and* the host has turned on NXE
1733 (we reuse the host EFER in the switcher). */
1734 /** @todo this needs to be fixed properly!! */
1735 else if (CPUMR3GetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_PAE))
1736 {
1737 if (pVM->hm.s.vmx.u64HostMsrEfer & MSR_K6_EFER_NXE)
1738 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_NX);
1739 else
1740 LogRel(("HM: NX not enabled on the host, unavailable to PAE guest\n"));
1741 }
1742
1743 /*
1744 * Log configuration details.
1745 */
1746 if (pVM->hm.s.fNestedPaging)
1747 {
1748 LogRel(("HM: Enabled nested paging\n"));
1749 if (pVM->hm.s.vmx.enmTlbFlushEpt == VMXTLBFLUSHEPT_SINGLE_CONTEXT)
1750 LogRel(("HM: EPT flush type = Single context\n"));
1751 else if (pVM->hm.s.vmx.enmTlbFlushEpt == VMXTLBFLUSHEPT_ALL_CONTEXTS)
1752 LogRel(("HM: EPT flush type = All contexts\n"));
1753 else if (pVM->hm.s.vmx.enmTlbFlushEpt == VMXTLBFLUSHEPT_NOT_SUPPORTED)
1754 LogRel(("HM: EPT flush type = Not supported\n"));
1755 else
1756 LogRel(("HM: EPT flush type = %#x\n", pVM->hm.s.vmx.enmTlbFlushEpt));
1757
1758 if (pVM->hm.s.vmx.fUnrestrictedGuest)
1759 LogRel(("HM: Enabled unrestricted guest execution\n"));
1760
1761#if HC_ARCH_BITS == 64
1762 if (pVM->hm.s.fLargePages)
1763 {
1764 /* Use large (2 MB) pages for our EPT PDEs where possible. */
1765 PGMSetLargePageUsage(pVM, true);
1766 LogRel(("HM: Enabled large page support\n"));
1767 }
1768#endif
1769 }
1770 else
1771 Assert(!pVM->hm.s.vmx.fUnrestrictedGuest);
1772
1773 if (pVM->hm.s.fVirtApicRegs)
1774 LogRel(("HM: Enabled APIC-register virtualization support\n"));
1775
1776 if (pVM->hm.s.fPostedIntrs)
1777 LogRel(("HM: Enabled posted-interrupt processing support\n"));
1778
1779 if (pVM->hm.s.vmx.fVpid)
1780 {
1781 LogRel(("HM: Enabled VPID\n"));
1782 if (pVM->hm.s.vmx.enmTlbFlushVpid == VMXTLBFLUSHVPID_INDIV_ADDR)
1783 LogRel(("HM: VPID flush type = Individual addresses\n"));
1784 else if (pVM->hm.s.vmx.enmTlbFlushVpid == VMXTLBFLUSHVPID_SINGLE_CONTEXT)
1785 LogRel(("HM: VPID flush type = Single context\n"));
1786 else if (pVM->hm.s.vmx.enmTlbFlushVpid == VMXTLBFLUSHVPID_ALL_CONTEXTS)
1787 LogRel(("HM: VPID flush type = All contexts\n"));
1788 else if (pVM->hm.s.vmx.enmTlbFlushVpid == VMXTLBFLUSHVPID_SINGLE_CONTEXT_RETAIN_GLOBALS)
1789 LogRel(("HM: VPID flush type = Single context retain globals\n"));
1790 else
1791 LogRel(("HM: VPID flush type = %#x\n", pVM->hm.s.vmx.enmTlbFlushVpid));
1792 }
1793 else if (pVM->hm.s.vmx.enmTlbFlushVpid == VMXTLBFLUSHVPID_NOT_SUPPORTED)
1794 LogRel(("HM: Ignoring VPID capabilities of CPU\n"));
1795
1796 if (pVM->hm.s.vmx.fUsePreemptTimer)
1797 LogRel(("HM: Enabled VMX-preemption timer (cPreemptTimerShift=%u)\n", pVM->hm.s.vmx.cPreemptTimerShift));
1798 else
1799 LogRel(("HM: Disabled VMX-preemption timer\n"));
1800
1801 return VINF_SUCCESS;
1802}
1803
1804
1805/**
1806 * Finish AMD-V initialization (after ring-0 init).
1807 *
1808 * @returns VBox status code.
1809 * @param pVM The cross context VM structure.
1810 */
1811static int hmR3InitFinalizeR0Amd(PVM pVM)
1812{
1813 Log(("pVM->hm.s.svm.fSupported = %d\n", pVM->hm.s.svm.fSupported));
1814
1815 LogRel(("HM: Using AMD-V implementation 2.0\n"));
1816
1817 uint32_t u32Family;
1818 uint32_t u32Model;
1819 uint32_t u32Stepping;
1820 if (HMIsSubjectToSvmErratum170(&u32Family, &u32Model, &u32Stepping))
1821 LogRel(("HM: AMD Cpu with erratum 170 family %#x model %#x stepping %#x\n", u32Family, u32Model, u32Stepping));
1822 LogRel(("HM: Max resume loops = %u\n", pVM->hm.s.cMaxResumeLoops));
1823 LogRel(("HM: AMD HWCR MSR = %#RX64\n", pVM->hm.s.svm.u64MsrHwcr));
1824 LogRel(("HM: AMD-V revision = %#x\n", pVM->hm.s.svm.u32Rev));
1825 LogRel(("HM: AMD-V max ASID = %RU32\n", pVM->hm.s.uMaxAsid));
1826 LogRel(("HM: AMD-V features = %#x\n", pVM->hm.s.svm.u32Features));
1827
1828 /*
1829 * Enumerate AMD-V features.
1830 */
1831 static const struct { uint32_t fFlag; const char *pszName; } s_aSvmFeatures[] =
1832 {
1833#define HMSVM_REPORT_FEATURE(a_StrDesc, a_Define) { a_Define, a_StrDesc }
1834 HMSVM_REPORT_FEATURE("NESTED_PAGING", X86_CPUID_SVM_FEATURE_EDX_NESTED_PAGING),
1835 HMSVM_REPORT_FEATURE("LBR_VIRT", X86_CPUID_SVM_FEATURE_EDX_LBR_VIRT),
1836 HMSVM_REPORT_FEATURE("SVM_LOCK", X86_CPUID_SVM_FEATURE_EDX_SVM_LOCK),
1837 HMSVM_REPORT_FEATURE("NRIP_SAVE", X86_CPUID_SVM_FEATURE_EDX_NRIP_SAVE),
1838 HMSVM_REPORT_FEATURE("TSC_RATE_MSR", X86_CPUID_SVM_FEATURE_EDX_TSC_RATE_MSR),
1839 HMSVM_REPORT_FEATURE("VMCB_CLEAN", X86_CPUID_SVM_FEATURE_EDX_VMCB_CLEAN),
1840 HMSVM_REPORT_FEATURE("FLUSH_BY_ASID", X86_CPUID_SVM_FEATURE_EDX_FLUSH_BY_ASID),
1841 HMSVM_REPORT_FEATURE("DECODE_ASSISTS", X86_CPUID_SVM_FEATURE_EDX_DECODE_ASSISTS),
1842 HMSVM_REPORT_FEATURE("PAUSE_FILTER", X86_CPUID_SVM_FEATURE_EDX_PAUSE_FILTER),
1843 HMSVM_REPORT_FEATURE("PAUSE_FILTER_THRESHOLD", X86_CPUID_SVM_FEATURE_EDX_PAUSE_FILTER_THRESHOLD),
1844 HMSVM_REPORT_FEATURE("AVIC", X86_CPUID_SVM_FEATURE_EDX_AVIC),
1845 HMSVM_REPORT_FEATURE("VIRT_VMSAVE_VMLOAD", X86_CPUID_SVM_FEATURE_EDX_VIRT_VMSAVE_VMLOAD),
1846 HMSVM_REPORT_FEATURE("VGIF", X86_CPUID_SVM_FEATURE_EDX_VGIF),
1847#undef HMSVM_REPORT_FEATURE
1848 };
1849
1850 uint32_t fSvmFeatures = pVM->hm.s.svm.u32Features;
1851 for (unsigned i = 0; i < RT_ELEMENTS(s_aSvmFeatures); i++)
1852 if (fSvmFeatures & s_aSvmFeatures[i].fFlag)
1853 {
1854 LogRel(("HM: %s\n", s_aSvmFeatures[i].pszName));
1855 fSvmFeatures &= ~s_aSvmFeatures[i].fFlag;
1856 }
1857 if (fSvmFeatures)
1858 for (unsigned iBit = 0; iBit < 32; iBit++)
1859 if (RT_BIT_32(iBit) & fSvmFeatures)
1860 LogRel(("HM: Reserved bit %u\n", iBit));
1861
1862 /*
1863 * Nested paging is determined in HMR3Init, verify the sanity of that.
1864 */
1865 AssertLogRelReturn( !pVM->hm.s.fNestedPaging
1866 || (pVM->hm.s.svm.u32Features & X86_CPUID_SVM_FEATURE_EDX_NESTED_PAGING),
1867 VERR_HM_IPE_1);
1868
1869#if 0
1870 /** @todo Add and query IPRT API for host OS support for posted-interrupt IPI
1871 * here. */
1872 if (RTR0IsPostIpiSupport())
1873 pVM->hm.s.fPostedIntrs = true;
1874#endif
1875
1876 /*
1877 * Call ring-0 to set up the VM.
1878 */
1879 int rc = SUPR3CallVMMR0Ex(pVM->pVMR0, 0 /*idCpu*/, VMMR0_DO_HM_SETUP_VM, 0, NULL);
1880 if (rc != VINF_SUCCESS)
1881 {
1882 AssertMsgFailed(("%Rrc\n", rc));
1883 LogRel(("HM: AMD-V setup failed with rc=%Rrc!\n", rc));
1884 return VMSetError(pVM, rc, RT_SRC_POS, "AMD-V setup failed: %Rrc", rc);
1885 }
1886
1887 LogRel(("HM: Enabled SVM\n"));
1888 pVM->hm.s.svm.fEnabled = true;
1889
1890 if (pVM->hm.s.fNestedPaging)
1891 {
1892 LogRel(("HM: Enabled nested paging\n"));
1893
1894 /*
1895 * Enable large pages (2 MB) if applicable.
1896 */
1897#if HC_ARCH_BITS == 64
1898 if (pVM->hm.s.fLargePages)
1899 {
1900 PGMSetLargePageUsage(pVM, true);
1901 LogRel(("HM: Enabled large page support\n"));
1902 }
1903#endif
1904 }
1905
1906 if (pVM->hm.s.fVirtApicRegs)
1907 LogRel(("HM: Enabled APIC-register virtualization support\n"));
1908
1909 if (pVM->hm.s.fPostedIntrs)
1910 LogRel(("HM: Enabled posted-interrupt processing support\n"));
1911
1912 hmR3DisableRawMode(pVM);
1913
1914 /*
1915 * Change the CPU features.
1916 */
1917 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_SEP);
1918 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_SYSCALL);
1919 if (pVM->hm.s.fAllow64BitGuests)
1920 {
1921 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_PAE);
1922 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_LONG_MODE);
1923 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_NX);
1924 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_LAHF);
1925 }
1926 /* Turn on NXE if PAE has been enabled. */
1927 else if (CPUMR3GetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_PAE))
1928 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_NX);
1929
1930 LogRel(("HM: %s TPR patching\n", (pVM->hm.s.fTprPatchingAllowed) ? "Enabled" : "Disabled"));
1931
1932 LogRel((pVM->hm.s.fAllow64BitGuests
1933 ? "HM: Guest support: 32-bit and 64-bit\n"
1934 : "HM: Guest support: 32-bit only\n"));
1935
1936 return VINF_SUCCESS;
1937}
1938
1939
1940/**
1941 * Applies relocations to data and code managed by this
1942 * component. This function will be called at init and
1943 * whenever the VMM need to relocate it self inside the GC.
1944 *
1945 * @param pVM The cross context VM structure.
1946 */
1947VMMR3_INT_DECL(void) HMR3Relocate(PVM pVM)
1948{
1949 Log(("HMR3Relocate to %RGv\n", MMHyperGetArea(pVM, 0)));
1950
1951 /* Fetch the current paging mode during the relocate callback during state loading. */
1952 if (VMR3GetState(pVM) == VMSTATE_LOADING)
1953 {
1954 for (VMCPUID i = 0; i < pVM->cCpus; i++)
1955 {
1956 PVMCPU pVCpu = &pVM->aCpus[i];
1957 pVCpu->hm.s.enmShadowMode = PGMGetShadowMode(pVCpu);
1958 }
1959 }
1960#if HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS)
1961 if (HMIsEnabled(pVM))
1962 {
1963 switch (PGMGetHostMode(pVM))
1964 {
1965 case PGMMODE_32_BIT:
1966 pVM->hm.s.pfnHost32ToGuest64R0 = VMMR3GetHostToGuestSwitcher(pVM, VMMSWITCHER_32_TO_AMD64);
1967 break;
1968
1969 case PGMMODE_PAE:
1970 case PGMMODE_PAE_NX:
1971 pVM->hm.s.pfnHost32ToGuest64R0 = VMMR3GetHostToGuestSwitcher(pVM, VMMSWITCHER_PAE_TO_AMD64);
1972 break;
1973
1974 default:
1975 AssertFailed();
1976 break;
1977 }
1978 }
1979#endif
1980 return;
1981}
1982
1983
1984/**
1985 * Terminates the HM.
1986 *
1987 * Termination means cleaning up and freeing all resources,
1988 * the VM itself is, at this point, powered off or suspended.
1989 *
1990 * @returns VBox status code.
1991 * @param pVM The cross context VM structure.
1992 */
1993VMMR3_INT_DECL(int) HMR3Term(PVM pVM)
1994{
1995 if (pVM->hm.s.vmx.pRealModeTSS)
1996 {
1997 PDMR3VmmDevHeapFree(pVM, pVM->hm.s.vmx.pRealModeTSS);
1998 pVM->hm.s.vmx.pRealModeTSS = 0;
1999 }
2000 hmR3TermCPU(pVM);
2001 return 0;
2002}
2003
2004
2005/**
2006 * Terminates the per-VCPU HM.
2007 *
2008 * @returns VBox status code.
2009 * @param pVM The cross context VM structure.
2010 */
2011static int hmR3TermCPU(PVM pVM)
2012{
2013 for (VMCPUID i = 0; i < pVM->cCpus; i++)
2014 {
2015 PVMCPU pVCpu = &pVM->aCpus[i]; NOREF(pVCpu);
2016
2017#ifdef VBOX_WITH_STATISTICS
2018 if (pVCpu->hm.s.paStatExitReason)
2019 {
2020 MMHyperFree(pVM, pVCpu->hm.s.paStatExitReason);
2021 pVCpu->hm.s.paStatExitReason = NULL;
2022 pVCpu->hm.s.paStatExitReasonR0 = NIL_RTR0PTR;
2023 }
2024 if (pVCpu->hm.s.paStatInjectedIrqs)
2025 {
2026 MMHyperFree(pVM, pVCpu->hm.s.paStatInjectedIrqs);
2027 pVCpu->hm.s.paStatInjectedIrqs = NULL;
2028 pVCpu->hm.s.paStatInjectedIrqsR0 = NIL_RTR0PTR;
2029 }
2030# if defined(VBOX_WITH_NESTED_HWVIRT_SVM) || defined(VBOX_WITH_NESTED_HWVIRT_VMX)
2031 if (pVCpu->hm.s.paStatNestedExitReason)
2032 {
2033 MMHyperFree(pVM, pVCpu->hm.s.paStatNestedExitReason);
2034 pVCpu->hm.s.paStatNestedExitReason = NULL;
2035 pVCpu->hm.s.paStatNestedExitReasonR0 = NIL_RTR0PTR;
2036 }
2037# endif
2038#endif
2039
2040#ifdef VBOX_WITH_CRASHDUMP_MAGIC
2041 memset(pVCpu->hm.s.vmx.VmcsCache.aMagic, 0, sizeof(pVCpu->hm.s.vmx.VmcsCache.aMagic));
2042 pVCpu->hm.s.vmx.VmcsCache.uMagic = 0;
2043 pVCpu->hm.s.vmx.VmcsCache.uPos = 0xffffffff;
2044#endif
2045 }
2046 return 0;
2047}
2048
2049
2050/**
2051 * Resets a virtual CPU.
2052 *
2053 * Used by HMR3Reset and CPU hot plugging.
2054 *
2055 * @param pVCpu The cross context virtual CPU structure to reset.
2056 */
2057VMMR3_INT_DECL(void) HMR3ResetCpu(PVMCPU pVCpu)
2058{
2059 /* Sync. entire state on VM reset ring-0 re-entry. It's safe to reset
2060 the HM flags here, all other EMTs are in ring-3. See VMR3Reset(). */
2061 pVCpu->hm.s.fCtxChanged |= HM_CHANGED_HOST_CONTEXT | HM_CHANGED_ALL_GUEST;
2062
2063 pVCpu->hm.s.fActive = false;
2064 pVCpu->hm.s.Event.fPending = false;
2065 pVCpu->hm.s.vmx.u64GstMsrApicBase = 0;
2066 pVCpu->hm.s.vmx.VmcsInfo.fSwitchedTo64on32 = false;
2067 pVCpu->hm.s.vmx.VmcsInfo.fWasInRealMode = true;
2068#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
2069 if (pVCpu->CTX_SUFF(pVM)->cpum.ro.GuestFeatures.fVmx)
2070 {
2071 pVCpu->hm.s.vmx.VmcsInfoNstGst.fSwitchedTo64on32 = false;
2072 pVCpu->hm.s.vmx.VmcsInfoNstGst.fWasInRealMode = true;
2073 }
2074#endif
2075
2076 /* Reset the contents of the read cache. */
2077 PVMXVMCSCACHE pVmcsCache = &pVCpu->hm.s.vmx.VmcsCache;
2078 for (unsigned j = 0; j < pVmcsCache->Read.cValidEntries; j++)
2079 pVmcsCache->Read.aFieldVal[j] = 0;
2080
2081#ifdef VBOX_WITH_CRASHDUMP_MAGIC
2082 /* Magic marker for searching in crash dumps. */
2083 strcpy((char *)pVmcsCache->aMagic, "VMCSCACHE Magic");
2084 pVmcsCache->uMagic = UINT64_C(0xdeadbeefdeadbeef);
2085#endif
2086}
2087
2088
2089/**
2090 * The VM is being reset.
2091 *
2092 * For the HM component this means that any GDT/LDT/TSS monitors
2093 * needs to be removed.
2094 *
2095 * @param pVM The cross context VM structure.
2096 */
2097VMMR3_INT_DECL(void) HMR3Reset(PVM pVM)
2098{
2099 LogFlow(("HMR3Reset:\n"));
2100
2101 if (HMIsEnabled(pVM))
2102 hmR3DisableRawMode(pVM);
2103
2104 for (VMCPUID i = 0; i < pVM->cCpus; i++)
2105 {
2106 PVMCPU pVCpu = &pVM->aCpus[i];
2107
2108 HMR3ResetCpu(pVCpu);
2109 }
2110
2111 /* Clear all patch information. */
2112 pVM->hm.s.pGuestPatchMem = 0;
2113 pVM->hm.s.pFreeGuestPatchMem = 0;
2114 pVM->hm.s.cbGuestPatchMem = 0;
2115 pVM->hm.s.cPatches = 0;
2116 pVM->hm.s.PatchTree = 0;
2117 pVM->hm.s.fTPRPatchingActive = false;
2118 ASMMemZero32(pVM->hm.s.aPatches, sizeof(pVM->hm.s.aPatches));
2119}
2120
2121
2122/**
2123 * Callback to patch a TPR instruction (vmmcall or mov cr8).
2124 *
2125 * @returns VBox strict status code.
2126 * @param pVM The cross context VM structure.
2127 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
2128 * @param pvUser Unused.
2129 */
2130static DECLCALLBACK(VBOXSTRICTRC) hmR3RemovePatches(PVM pVM, PVMCPU pVCpu, void *pvUser)
2131{
2132 VMCPUID idCpu = (VMCPUID)(uintptr_t)pvUser;
2133
2134 /* Only execute the handler on the VCPU the original patch request was issued. */
2135 if (pVCpu->idCpu != idCpu)
2136 return VINF_SUCCESS;
2137
2138 Log(("hmR3RemovePatches\n"));
2139 for (unsigned i = 0; i < pVM->hm.s.cPatches; i++)
2140 {
2141 uint8_t abInstr[15];
2142 PHMTPRPATCH pPatch = &pVM->hm.s.aPatches[i];
2143 RTGCPTR pInstrGC = (RTGCPTR)pPatch->Core.Key;
2144 int rc;
2145
2146#ifdef LOG_ENABLED
2147 char szOutput[256];
2148 rc = DBGFR3DisasInstrEx(pVM->pUVM, pVCpu->idCpu, CPUMGetGuestCS(pVCpu), pInstrGC, DBGF_DISAS_FLAGS_DEFAULT_MODE,
2149 szOutput, sizeof(szOutput), NULL);
2150 if (RT_SUCCESS(rc))
2151 Log(("Patched instr: %s\n", szOutput));
2152#endif
2153
2154 /* Check if the instruction is still the same. */
2155 rc = PGMPhysSimpleReadGCPtr(pVCpu, abInstr, pInstrGC, pPatch->cbNewOp);
2156 if (rc != VINF_SUCCESS)
2157 {
2158 Log(("Patched code removed? (rc=%Rrc0\n", rc));
2159 continue; /* swapped out or otherwise removed; skip it. */
2160 }
2161
2162 if (memcmp(abInstr, pPatch->aNewOpcode, pPatch->cbNewOp))
2163 {
2164 Log(("Patched instruction was changed! (rc=%Rrc0\n", rc));
2165 continue; /* skip it. */
2166 }
2167
2168 rc = PGMPhysSimpleWriteGCPtr(pVCpu, pInstrGC, pPatch->aOpcode, pPatch->cbOp);
2169 AssertRC(rc);
2170
2171#ifdef LOG_ENABLED
2172 rc = DBGFR3DisasInstrEx(pVM->pUVM, pVCpu->idCpu, CPUMGetGuestCS(pVCpu), pInstrGC, DBGF_DISAS_FLAGS_DEFAULT_MODE,
2173 szOutput, sizeof(szOutput), NULL);
2174 if (RT_SUCCESS(rc))
2175 Log(("Original instr: %s\n", szOutput));
2176#endif
2177 }
2178 pVM->hm.s.cPatches = 0;
2179 pVM->hm.s.PatchTree = 0;
2180 pVM->hm.s.pFreeGuestPatchMem = pVM->hm.s.pGuestPatchMem;
2181 pVM->hm.s.fTPRPatchingActive = false;
2182 return VINF_SUCCESS;
2183}
2184
2185
2186/**
2187 * Worker for enabling patching in a VT-x/AMD-V guest.
2188 *
2189 * @returns VBox status code.
2190 * @param pVM The cross context VM structure.
2191 * @param idCpu VCPU to execute hmR3RemovePatches on.
2192 * @param pPatchMem Patch memory range.
2193 * @param cbPatchMem Size of the memory range.
2194 */
2195static int hmR3EnablePatching(PVM pVM, VMCPUID idCpu, RTRCPTR pPatchMem, unsigned cbPatchMem)
2196{
2197 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONE_BY_ONE, hmR3RemovePatches, (void *)(uintptr_t)idCpu);
2198 AssertRC(rc);
2199
2200 pVM->hm.s.pGuestPatchMem = pPatchMem;
2201 pVM->hm.s.pFreeGuestPatchMem = pPatchMem;
2202 pVM->hm.s.cbGuestPatchMem = cbPatchMem;
2203 return VINF_SUCCESS;
2204}
2205
2206
2207/**
2208 * Enable patching in a VT-x/AMD-V guest
2209 *
2210 * @returns VBox status code.
2211 * @param pVM The cross context VM structure.
2212 * @param pPatchMem Patch memory range.
2213 * @param cbPatchMem Size of the memory range.
2214 */
2215VMMR3_INT_DECL(int) HMR3EnablePatching(PVM pVM, RTGCPTR pPatchMem, unsigned cbPatchMem)
2216{
2217 VM_ASSERT_EMT(pVM);
2218 Log(("HMR3EnablePatching %RGv size %x\n", pPatchMem, cbPatchMem));
2219 if (pVM->cCpus > 1)
2220 {
2221 /* We own the IOM lock here and could cause a deadlock by waiting for a VCPU that is blocking on the IOM lock. */
2222 int rc = VMR3ReqCallNoWait(pVM, VMCPUID_ANY_QUEUE,
2223 (PFNRT)hmR3EnablePatching, 4, pVM, VMMGetCpuId(pVM), (RTRCPTR)pPatchMem, cbPatchMem);
2224 AssertRC(rc);
2225 return rc;
2226 }
2227 return hmR3EnablePatching(pVM, VMMGetCpuId(pVM), (RTRCPTR)pPatchMem, cbPatchMem);
2228}
2229
2230
2231/**
2232 * Disable patching in a VT-x/AMD-V guest.
2233 *
2234 * @returns VBox status code.
2235 * @param pVM The cross context VM structure.
2236 * @param pPatchMem Patch memory range.
2237 * @param cbPatchMem Size of the memory range.
2238 */
2239VMMR3_INT_DECL(int) HMR3DisablePatching(PVM pVM, RTGCPTR pPatchMem, unsigned cbPatchMem)
2240{
2241 Log(("HMR3DisablePatching %RGv size %x\n", pPatchMem, cbPatchMem));
2242 RT_NOREF2(pPatchMem, cbPatchMem);
2243
2244 Assert(pVM->hm.s.pGuestPatchMem == pPatchMem);
2245 Assert(pVM->hm.s.cbGuestPatchMem == cbPatchMem);
2246
2247 /** @todo Potential deadlock when other VCPUs are waiting on the IOM lock (we own it)!! */
2248 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONE_BY_ONE, hmR3RemovePatches,
2249 (void *)(uintptr_t)VMMGetCpuId(pVM));
2250 AssertRC(rc);
2251
2252 pVM->hm.s.pGuestPatchMem = 0;
2253 pVM->hm.s.pFreeGuestPatchMem = 0;
2254 pVM->hm.s.cbGuestPatchMem = 0;
2255 pVM->hm.s.fTPRPatchingActive = false;
2256 return VINF_SUCCESS;
2257}
2258
2259
2260/**
2261 * Callback to patch a TPR instruction (vmmcall or mov cr8).
2262 *
2263 * @returns VBox strict status code.
2264 * @param pVM The cross context VM structure.
2265 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
2266 * @param pvUser User specified CPU context.
2267 *
2268 */
2269static DECLCALLBACK(VBOXSTRICTRC) hmR3ReplaceTprInstr(PVM pVM, PVMCPU pVCpu, void *pvUser)
2270{
2271 /*
2272 * Only execute the handler on the VCPU the original patch request was
2273 * issued. (The other CPU(s) might not yet have switched to protected
2274 * mode, nor have the correct memory context.)
2275 */
2276 VMCPUID idCpu = (VMCPUID)(uintptr_t)pvUser;
2277 if (pVCpu->idCpu != idCpu)
2278 return VINF_SUCCESS;
2279
2280 /*
2281 * We're racing other VCPUs here, so don't try patch the instruction twice
2282 * and make sure there is still room for our patch record.
2283 */
2284 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
2285 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
2286 if (pPatch)
2287 {
2288 Log(("hmR3ReplaceTprInstr: already patched %RGv\n", pCtx->rip));
2289 return VINF_SUCCESS;
2290 }
2291 uint32_t const idx = pVM->hm.s.cPatches;
2292 if (idx >= RT_ELEMENTS(pVM->hm.s.aPatches))
2293 {
2294 Log(("hmR3ReplaceTprInstr: no available patch slots (%RGv)\n", pCtx->rip));
2295 return VINF_SUCCESS;
2296 }
2297 pPatch = &pVM->hm.s.aPatches[idx];
2298
2299 Log(("hmR3ReplaceTprInstr: rip=%RGv idxPatch=%u\n", pCtx->rip, idx));
2300
2301 /*
2302 * Disassembler the instruction and get cracking.
2303 */
2304 DBGFR3_DISAS_INSTR_CUR_LOG(pVCpu, "hmR3ReplaceTprInstr");
2305 PDISCPUSTATE pDis = &pVCpu->hm.s.DisState;
2306 uint32_t cbOp;
2307 int rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, &cbOp);
2308 AssertRC(rc);
2309 if ( rc == VINF_SUCCESS
2310 && pDis->pCurInstr->uOpcode == OP_MOV
2311 && cbOp >= 3)
2312 {
2313 static uint8_t const s_abVMMCall[3] = { 0x0f, 0x01, 0xd9 };
2314
2315 rc = PGMPhysSimpleReadGCPtr(pVCpu, pPatch->aOpcode, pCtx->rip, cbOp);
2316 AssertRC(rc);
2317
2318 pPatch->cbOp = cbOp;
2319
2320 if (pDis->Param1.fUse == DISUSE_DISPLACEMENT32)
2321 {
2322 /* write. */
2323 if (pDis->Param2.fUse == DISUSE_REG_GEN32)
2324 {
2325 pPatch->enmType = HMTPRINSTR_WRITE_REG;
2326 pPatch->uSrcOperand = pDis->Param2.Base.idxGenReg;
2327 Log(("hmR3ReplaceTprInstr: HMTPRINSTR_WRITE_REG %u\n", pDis->Param2.Base.idxGenReg));
2328 }
2329 else
2330 {
2331 Assert(pDis->Param2.fUse == DISUSE_IMMEDIATE32);
2332 pPatch->enmType = HMTPRINSTR_WRITE_IMM;
2333 pPatch->uSrcOperand = pDis->Param2.uValue;
2334 Log(("hmR3ReplaceTprInstr: HMTPRINSTR_WRITE_IMM %#llx\n", pDis->Param2.uValue));
2335 }
2336 rc = PGMPhysSimpleWriteGCPtr(pVCpu, pCtx->rip, s_abVMMCall, sizeof(s_abVMMCall));
2337 AssertRC(rc);
2338
2339 memcpy(pPatch->aNewOpcode, s_abVMMCall, sizeof(s_abVMMCall));
2340 pPatch->cbNewOp = sizeof(s_abVMMCall);
2341 STAM_COUNTER_INC(&pVM->hm.s.StatTprReplaceSuccessVmc);
2342 }
2343 else
2344 {
2345 /*
2346 * TPR Read.
2347 *
2348 * Found:
2349 * mov eax, dword [fffe0080] (5 bytes)
2350 * Check if next instruction is:
2351 * shr eax, 4
2352 */
2353 Assert(pDis->Param1.fUse == DISUSE_REG_GEN32);
2354
2355 uint8_t const idxMmioReg = pDis->Param1.Base.idxGenReg;
2356 uint8_t const cbOpMmio = cbOp;
2357 uint64_t const uSavedRip = pCtx->rip;
2358
2359 pCtx->rip += cbOp;
2360 rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, &cbOp);
2361 DBGFR3_DISAS_INSTR_CUR_LOG(pVCpu, "Following read");
2362 pCtx->rip = uSavedRip;
2363
2364 if ( rc == VINF_SUCCESS
2365 && pDis->pCurInstr->uOpcode == OP_SHR
2366 && pDis->Param1.fUse == DISUSE_REG_GEN32
2367 && pDis->Param1.Base.idxGenReg == idxMmioReg
2368 && pDis->Param2.fUse == DISUSE_IMMEDIATE8
2369 && pDis->Param2.uValue == 4
2370 && cbOpMmio + cbOp < sizeof(pVM->hm.s.aPatches[idx].aOpcode))
2371 {
2372 uint8_t abInstr[15];
2373
2374 /* Replacing the two instructions above with an AMD-V specific lock-prefixed 32-bit MOV CR8 instruction so as to
2375 access CR8 in 32-bit mode and not cause a #VMEXIT. */
2376 rc = PGMPhysSimpleReadGCPtr(pVCpu, &pPatch->aOpcode, pCtx->rip, cbOpMmio + cbOp);
2377 AssertRC(rc);
2378
2379 pPatch->cbOp = cbOpMmio + cbOp;
2380
2381 /* 0xf0, 0x0f, 0x20, 0xc0 = mov eax, cr8 */
2382 abInstr[0] = 0xf0;
2383 abInstr[1] = 0x0f;
2384 abInstr[2] = 0x20;
2385 abInstr[3] = 0xc0 | pDis->Param1.Base.idxGenReg;
2386 for (unsigned i = 4; i < pPatch->cbOp; i++)
2387 abInstr[i] = 0x90; /* nop */
2388
2389 rc = PGMPhysSimpleWriteGCPtr(pVCpu, pCtx->rip, abInstr, pPatch->cbOp);
2390 AssertRC(rc);
2391
2392 memcpy(pPatch->aNewOpcode, abInstr, pPatch->cbOp);
2393 pPatch->cbNewOp = pPatch->cbOp;
2394 STAM_COUNTER_INC(&pVM->hm.s.StatTprReplaceSuccessCr8);
2395
2396 Log(("Acceptable read/shr candidate!\n"));
2397 pPatch->enmType = HMTPRINSTR_READ_SHR4;
2398 }
2399 else
2400 {
2401 pPatch->enmType = HMTPRINSTR_READ;
2402 pPatch->uDstOperand = idxMmioReg;
2403
2404 rc = PGMPhysSimpleWriteGCPtr(pVCpu, pCtx->rip, s_abVMMCall, sizeof(s_abVMMCall));
2405 AssertRC(rc);
2406
2407 memcpy(pPatch->aNewOpcode, s_abVMMCall, sizeof(s_abVMMCall));
2408 pPatch->cbNewOp = sizeof(s_abVMMCall);
2409 STAM_COUNTER_INC(&pVM->hm.s.StatTprReplaceSuccessVmc);
2410 Log(("hmR3ReplaceTprInstr: HMTPRINSTR_READ %u\n", pPatch->uDstOperand));
2411 }
2412 }
2413
2414 pPatch->Core.Key = pCtx->eip;
2415 rc = RTAvloU32Insert(&pVM->hm.s.PatchTree, &pPatch->Core);
2416 AssertRC(rc);
2417
2418 pVM->hm.s.cPatches++;
2419 return VINF_SUCCESS;
2420 }
2421
2422 /*
2423 * Save invalid patch, so we will not try again.
2424 */
2425 Log(("hmR3ReplaceTprInstr: Failed to patch instr!\n"));
2426 pPatch->Core.Key = pCtx->eip;
2427 pPatch->enmType = HMTPRINSTR_INVALID;
2428 rc = RTAvloU32Insert(&pVM->hm.s.PatchTree, &pPatch->Core);
2429 AssertRC(rc);
2430 pVM->hm.s.cPatches++;
2431 STAM_COUNTER_INC(&pVM->hm.s.StatTprReplaceFailure);
2432 return VINF_SUCCESS;
2433}
2434
2435
2436/**
2437 * Callback to patch a TPR instruction (jump to generated code).
2438 *
2439 * @returns VBox strict status code.
2440 * @param pVM The cross context VM structure.
2441 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
2442 * @param pvUser User specified CPU context.
2443 *
2444 */
2445static DECLCALLBACK(VBOXSTRICTRC) hmR3PatchTprInstr(PVM pVM, PVMCPU pVCpu, void *pvUser)
2446{
2447 /*
2448 * Only execute the handler on the VCPU the original patch request was
2449 * issued. (The other CPU(s) might not yet have switched to protected
2450 * mode, nor have the correct memory context.)
2451 */
2452 VMCPUID idCpu = (VMCPUID)(uintptr_t)pvUser;
2453 if (pVCpu->idCpu != idCpu)
2454 return VINF_SUCCESS;
2455
2456 /*
2457 * We're racing other VCPUs here, so don't try patch the instruction twice
2458 * and make sure there is still room for our patch record.
2459 */
2460 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
2461 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
2462 if (pPatch)
2463 {
2464 Log(("hmR3PatchTprInstr: already patched %RGv\n", pCtx->rip));
2465 return VINF_SUCCESS;
2466 }
2467 uint32_t const idx = pVM->hm.s.cPatches;
2468 if (idx >= RT_ELEMENTS(pVM->hm.s.aPatches))
2469 {
2470 Log(("hmR3PatchTprInstr: no available patch slots (%RGv)\n", pCtx->rip));
2471 return VINF_SUCCESS;
2472 }
2473 pPatch = &pVM->hm.s.aPatches[idx];
2474
2475 Log(("hmR3PatchTprInstr: rip=%RGv idxPatch=%u\n", pCtx->rip, idx));
2476 DBGFR3_DISAS_INSTR_CUR_LOG(pVCpu, "hmR3PatchTprInstr");
2477
2478 /*
2479 * Disassemble the instruction and get cracking.
2480 */
2481 PDISCPUSTATE pDis = &pVCpu->hm.s.DisState;
2482 uint32_t cbOp;
2483 int rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, &cbOp);
2484 AssertRC(rc);
2485 if ( rc == VINF_SUCCESS
2486 && pDis->pCurInstr->uOpcode == OP_MOV
2487 && cbOp >= 5)
2488 {
2489 uint8_t aPatch[64];
2490 uint32_t off = 0;
2491
2492 rc = PGMPhysSimpleReadGCPtr(pVCpu, pPatch->aOpcode, pCtx->rip, cbOp);
2493 AssertRC(rc);
2494
2495 pPatch->cbOp = cbOp;
2496 pPatch->enmType = HMTPRINSTR_JUMP_REPLACEMENT;
2497
2498 if (pDis->Param1.fUse == DISUSE_DISPLACEMENT32)
2499 {
2500 /*
2501 * TPR write:
2502 *
2503 * push ECX [51]
2504 * push EDX [52]
2505 * push EAX [50]
2506 * xor EDX,EDX [31 D2]
2507 * mov EAX,EAX [89 C0]
2508 * or
2509 * mov EAX,0000000CCh [B8 CC 00 00 00]
2510 * mov ECX,0C0000082h [B9 82 00 00 C0]
2511 * wrmsr [0F 30]
2512 * pop EAX [58]
2513 * pop EDX [5A]
2514 * pop ECX [59]
2515 * jmp return_address [E9 return_address]
2516 */
2517 bool fUsesEax = (pDis->Param2.fUse == DISUSE_REG_GEN32 && pDis->Param2.Base.idxGenReg == DISGREG_EAX);
2518
2519 aPatch[off++] = 0x51; /* push ecx */
2520 aPatch[off++] = 0x52; /* push edx */
2521 if (!fUsesEax)
2522 aPatch[off++] = 0x50; /* push eax */
2523 aPatch[off++] = 0x31; /* xor edx, edx */
2524 aPatch[off++] = 0xd2;
2525 if (pDis->Param2.fUse == DISUSE_REG_GEN32)
2526 {
2527 if (!fUsesEax)
2528 {
2529 aPatch[off++] = 0x89; /* mov eax, src_reg */
2530 aPatch[off++] = MAKE_MODRM(3, pDis->Param2.Base.idxGenReg, DISGREG_EAX);
2531 }
2532 }
2533 else
2534 {
2535 Assert(pDis->Param2.fUse == DISUSE_IMMEDIATE32);
2536 aPatch[off++] = 0xb8; /* mov eax, immediate */
2537 *(uint32_t *)&aPatch[off] = pDis->Param2.uValue;
2538 off += sizeof(uint32_t);
2539 }
2540 aPatch[off++] = 0xb9; /* mov ecx, 0xc0000082 */
2541 *(uint32_t *)&aPatch[off] = MSR_K8_LSTAR;
2542 off += sizeof(uint32_t);
2543
2544 aPatch[off++] = 0x0f; /* wrmsr */
2545 aPatch[off++] = 0x30;
2546 if (!fUsesEax)
2547 aPatch[off++] = 0x58; /* pop eax */
2548 aPatch[off++] = 0x5a; /* pop edx */
2549 aPatch[off++] = 0x59; /* pop ecx */
2550 }
2551 else
2552 {
2553 /*
2554 * TPR read:
2555 *
2556 * push ECX [51]
2557 * push EDX [52]
2558 * push EAX [50]
2559 * mov ECX,0C0000082h [B9 82 00 00 C0]
2560 * rdmsr [0F 32]
2561 * mov EAX,EAX [89 C0]
2562 * pop EAX [58]
2563 * pop EDX [5A]
2564 * pop ECX [59]
2565 * jmp return_address [E9 return_address]
2566 */
2567 Assert(pDis->Param1.fUse == DISUSE_REG_GEN32);
2568
2569 if (pDis->Param1.Base.idxGenReg != DISGREG_ECX)
2570 aPatch[off++] = 0x51; /* push ecx */
2571 if (pDis->Param1.Base.idxGenReg != DISGREG_EDX )
2572 aPatch[off++] = 0x52; /* push edx */
2573 if (pDis->Param1.Base.idxGenReg != DISGREG_EAX)
2574 aPatch[off++] = 0x50; /* push eax */
2575
2576 aPatch[off++] = 0x31; /* xor edx, edx */
2577 aPatch[off++] = 0xd2;
2578
2579 aPatch[off++] = 0xb9; /* mov ecx, 0xc0000082 */
2580 *(uint32_t *)&aPatch[off] = MSR_K8_LSTAR;
2581 off += sizeof(uint32_t);
2582
2583 aPatch[off++] = 0x0f; /* rdmsr */
2584 aPatch[off++] = 0x32;
2585
2586 if (pDis->Param1.Base.idxGenReg != DISGREG_EAX)
2587 {
2588 aPatch[off++] = 0x89; /* mov dst_reg, eax */
2589 aPatch[off++] = MAKE_MODRM(3, DISGREG_EAX, pDis->Param1.Base.idxGenReg);
2590 }
2591
2592 if (pDis->Param1.Base.idxGenReg != DISGREG_EAX)
2593 aPatch[off++] = 0x58; /* pop eax */
2594 if (pDis->Param1.Base.idxGenReg != DISGREG_EDX )
2595 aPatch[off++] = 0x5a; /* pop edx */
2596 if (pDis->Param1.Base.idxGenReg != DISGREG_ECX)
2597 aPatch[off++] = 0x59; /* pop ecx */
2598 }
2599 aPatch[off++] = 0xe9; /* jmp return_address */
2600 *(RTRCUINTPTR *)&aPatch[off] = ((RTRCUINTPTR)pCtx->eip + cbOp) - ((RTRCUINTPTR)pVM->hm.s.pFreeGuestPatchMem + off + 4);
2601 off += sizeof(RTRCUINTPTR);
2602
2603 if (pVM->hm.s.pFreeGuestPatchMem + off <= pVM->hm.s.pGuestPatchMem + pVM->hm.s.cbGuestPatchMem)
2604 {
2605 /* Write new code to the patch buffer. */
2606 rc = PGMPhysSimpleWriteGCPtr(pVCpu, pVM->hm.s.pFreeGuestPatchMem, aPatch, off);
2607 AssertRC(rc);
2608
2609#ifdef LOG_ENABLED
2610 uint32_t cbCurInstr;
2611 for (RTGCPTR GCPtrInstr = pVM->hm.s.pFreeGuestPatchMem;
2612 GCPtrInstr < pVM->hm.s.pFreeGuestPatchMem + off;
2613 GCPtrInstr += RT_MAX(cbCurInstr, 1))
2614 {
2615 char szOutput[256];
2616 rc = DBGFR3DisasInstrEx(pVM->pUVM, pVCpu->idCpu, pCtx->cs.Sel, GCPtrInstr, DBGF_DISAS_FLAGS_DEFAULT_MODE,
2617 szOutput, sizeof(szOutput), &cbCurInstr);
2618 if (RT_SUCCESS(rc))
2619 Log(("Patch instr %s\n", szOutput));
2620 else
2621 Log(("%RGv: rc=%Rrc\n", GCPtrInstr, rc));
2622 }
2623#endif
2624
2625 pPatch->aNewOpcode[0] = 0xE9;
2626 *(RTRCUINTPTR *)&pPatch->aNewOpcode[1] = ((RTRCUINTPTR)pVM->hm.s.pFreeGuestPatchMem) - ((RTRCUINTPTR)pCtx->eip + 5);
2627
2628 /* Overwrite the TPR instruction with a jump. */
2629 rc = PGMPhysSimpleWriteGCPtr(pVCpu, pCtx->eip, pPatch->aNewOpcode, 5);
2630 AssertRC(rc);
2631
2632 DBGFR3_DISAS_INSTR_CUR_LOG(pVCpu, "Jump");
2633
2634 pVM->hm.s.pFreeGuestPatchMem += off;
2635 pPatch->cbNewOp = 5;
2636
2637 pPatch->Core.Key = pCtx->eip;
2638 rc = RTAvloU32Insert(&pVM->hm.s.PatchTree, &pPatch->Core);
2639 AssertRC(rc);
2640
2641 pVM->hm.s.cPatches++;
2642 pVM->hm.s.fTPRPatchingActive = true;
2643 STAM_COUNTER_INC(&pVM->hm.s.StatTprPatchSuccess);
2644 return VINF_SUCCESS;
2645 }
2646
2647 Log(("Ran out of space in our patch buffer!\n"));
2648 }
2649 else
2650 Log(("hmR3PatchTprInstr: Failed to patch instr!\n"));
2651
2652
2653 /*
2654 * Save invalid patch, so we will not try again.
2655 */
2656 pPatch = &pVM->hm.s.aPatches[idx];
2657 pPatch->Core.Key = pCtx->eip;
2658 pPatch->enmType = HMTPRINSTR_INVALID;
2659 rc = RTAvloU32Insert(&pVM->hm.s.PatchTree, &pPatch->Core);
2660 AssertRC(rc);
2661 pVM->hm.s.cPatches++;
2662 STAM_COUNTER_INC(&pVM->hm.s.StatTprPatchFailure);
2663 return VINF_SUCCESS;
2664}
2665
2666
2667/**
2668 * Attempt to patch TPR mmio instructions.
2669 *
2670 * @returns VBox status code.
2671 * @param pVM The cross context VM structure.
2672 * @param pVCpu The cross context virtual CPU structure.
2673 */
2674VMMR3_INT_DECL(int) HMR3PatchTprInstr(PVM pVM, PVMCPU pVCpu)
2675{
2676 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONE_BY_ONE,
2677 pVM->hm.s.pGuestPatchMem ? hmR3PatchTprInstr : hmR3ReplaceTprInstr,
2678 (void *)(uintptr_t)pVCpu->idCpu);
2679 AssertRC(rc);
2680 return rc;
2681}
2682
2683
2684/**
2685 * Checks if we need to reschedule due to VMM device heap changes.
2686 *
2687 * @returns true if a reschedule is required, otherwise false.
2688 * @param pVM The cross context VM structure.
2689 * @param pCtx VM execution context.
2690 */
2691VMMR3_INT_DECL(bool) HMR3IsRescheduleRequired(PVM pVM, PCCPUMCTX pCtx)
2692{
2693 /*
2694 * The VMM device heap is a requirement for emulating real-mode or protected-mode without paging
2695 * when the unrestricted guest execution feature is missing (VT-x only).
2696 */
2697 if ( pVM->hm.s.vmx.fEnabled
2698 && !pVM->hm.s.vmx.fUnrestrictedGuest
2699 && CPUMIsGuestInRealModeEx(pCtx)
2700 && !PDMVmmDevHeapIsEnabled(pVM))
2701 return true;
2702
2703 return false;
2704}
2705
2706
2707/**
2708 * Noticiation callback from DBGF when interrupt breakpoints or generic debug
2709 * event settings changes.
2710 *
2711 * DBGF will call HMR3NotifyDebugEventChangedPerCpu on each CPU afterwards, this
2712 * function is just updating the VM globals.
2713 *
2714 * @param pVM The VM cross context VM structure.
2715 * @thread EMT(0)
2716 */
2717VMMR3_INT_DECL(void) HMR3NotifyDebugEventChanged(PVM pVM)
2718{
2719 /* Interrupts. */
2720 bool fUseDebugLoop = pVM->dbgf.ro.cSoftIntBreakpoints > 0
2721 || pVM->dbgf.ro.cHardIntBreakpoints > 0;
2722
2723 /* CPU Exceptions. */
2724 for (DBGFEVENTTYPE enmEvent = DBGFEVENT_XCPT_FIRST;
2725 !fUseDebugLoop && enmEvent <= DBGFEVENT_XCPT_LAST;
2726 enmEvent = (DBGFEVENTTYPE)(enmEvent + 1))
2727 fUseDebugLoop = DBGF_IS_EVENT_ENABLED(pVM, enmEvent);
2728
2729 /* Common VM exits. */
2730 for (DBGFEVENTTYPE enmEvent = DBGFEVENT_EXIT_FIRST;
2731 !fUseDebugLoop && enmEvent <= DBGFEVENT_EXIT_LAST_COMMON;
2732 enmEvent = (DBGFEVENTTYPE)(enmEvent + 1))
2733 fUseDebugLoop = DBGF_IS_EVENT_ENABLED(pVM, enmEvent);
2734
2735 /* Vendor specific VM exits. */
2736 if (HMR3IsVmxEnabled(pVM->pUVM))
2737 for (DBGFEVENTTYPE enmEvent = DBGFEVENT_EXIT_VMX_FIRST;
2738 !fUseDebugLoop && enmEvent <= DBGFEVENT_EXIT_VMX_LAST;
2739 enmEvent = (DBGFEVENTTYPE)(enmEvent + 1))
2740 fUseDebugLoop = DBGF_IS_EVENT_ENABLED(pVM, enmEvent);
2741 else
2742 for (DBGFEVENTTYPE enmEvent = DBGFEVENT_EXIT_SVM_FIRST;
2743 !fUseDebugLoop && enmEvent <= DBGFEVENT_EXIT_SVM_LAST;
2744 enmEvent = (DBGFEVENTTYPE)(enmEvent + 1))
2745 fUseDebugLoop = DBGF_IS_EVENT_ENABLED(pVM, enmEvent);
2746
2747 /* Done. */
2748 pVM->hm.s.fUseDebugLoop = fUseDebugLoop;
2749}
2750
2751
2752/**
2753 * Follow up notification callback to HMR3NotifyDebugEventChanged for each CPU.
2754 *
2755 * HM uses this to combine the decision made by HMR3NotifyDebugEventChanged with
2756 * per CPU settings.
2757 *
2758 * @param pVM The VM cross context VM structure.
2759 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
2760 */
2761VMMR3_INT_DECL(void) HMR3NotifyDebugEventChangedPerCpu(PVM pVM, PVMCPU pVCpu)
2762{
2763 pVCpu->hm.s.fUseDebugLoop = pVCpu->hm.s.fSingleInstruction | pVM->hm.s.fUseDebugLoop;
2764}
2765
2766
2767/**
2768 * Checks if we are currently using hardware acceleration.
2769 *
2770 * @returns true if hardware acceleration is being used, otherwise false.
2771 * @param pVCpu The cross context virtual CPU structure.
2772 */
2773VMMR3_INT_DECL(bool) HMR3IsActive(PCVMCPU pVCpu)
2774{
2775 return pVCpu->hm.s.fActive;
2776}
2777
2778
2779/**
2780 * External interface for querying whether hardware acceleration is enabled.
2781 *
2782 * @returns true if VT-x or AMD-V is being used, otherwise false.
2783 * @param pUVM The user mode VM handle.
2784 * @sa HMIsEnabled, HMIsEnabledNotMacro.
2785 */
2786VMMR3DECL(bool) HMR3IsEnabled(PUVM pUVM)
2787{
2788 UVM_ASSERT_VALID_EXT_RETURN(pUVM, false);
2789 PVM pVM = pUVM->pVM;
2790 VM_ASSERT_VALID_EXT_RETURN(pVM, false);
2791 return pVM->fHMEnabled; /* Don't use the macro as the GUI may query us very very early. */
2792}
2793
2794
2795/**
2796 * External interface for querying whether VT-x 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 HMR3IsSvmEnabled, HMIsEnabled
2801 */
2802VMMR3DECL(bool) HMR3IsVmxEnabled(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.vmx.fEnabled
2808 && pVM->hm.s.vmx.fSupported
2809 && pVM->fHMEnabled;
2810}
2811
2812
2813/**
2814 * External interface for querying whether AMD-V is being used.
2815 *
2816 * @returns true if VT-x is being used, otherwise false.
2817 * @param pUVM The user mode VM handle.
2818 * @sa HMR3IsVmxEnabled, HMIsEnabled
2819 */
2820VMMR3DECL(bool) HMR3IsSvmEnabled(PUVM pUVM)
2821{
2822 UVM_ASSERT_VALID_EXT_RETURN(pUVM, false);
2823 PVM pVM = pUVM->pVM;
2824 VM_ASSERT_VALID_EXT_RETURN(pVM, false);
2825 return pVM->hm.s.svm.fEnabled
2826 && pVM->hm.s.svm.fSupported
2827 && pVM->fHMEnabled;
2828}
2829
2830
2831/**
2832 * Checks if we are currently using nested paging.
2833 *
2834 * @returns true if nested paging is being used, otherwise false.
2835 * @param pUVM The user mode VM handle.
2836 */
2837VMMR3DECL(bool) HMR3IsNestedPagingActive(PUVM pUVM)
2838{
2839 UVM_ASSERT_VALID_EXT_RETURN(pUVM, false);
2840 PVM pVM = pUVM->pVM;
2841 VM_ASSERT_VALID_EXT_RETURN(pVM, false);
2842 return pVM->hm.s.fNestedPaging;
2843}
2844
2845
2846/**
2847 * Checks if virtualized APIC registers is enabled.
2848 *
2849 * When enabled this feature allows the hardware to access most of the
2850 * APIC registers in the virtual-APIC page without causing VM-exits. See
2851 * Intel spec. 29.1.1 "Virtualized APIC Registers".
2852 *
2853 * @returns true if virtualized APIC registers is enabled, otherwise
2854 * false.
2855 * @param pUVM The user mode VM handle.
2856 */
2857VMMR3DECL(bool) HMR3IsVirtApicRegsEnabled(PUVM pUVM)
2858{
2859 UVM_ASSERT_VALID_EXT_RETURN(pUVM, false);
2860 PVM pVM = pUVM->pVM;
2861 VM_ASSERT_VALID_EXT_RETURN(pVM, false);
2862 return pVM->hm.s.fVirtApicRegs;
2863}
2864
2865
2866/**
2867 * Checks if APIC posted-interrupt processing is enabled.
2868 *
2869 * This returns whether we can deliver interrupts to the guest without
2870 * leaving guest-context by updating APIC state from host-context.
2871 *
2872 * @returns true if APIC posted-interrupt processing is enabled,
2873 * otherwise false.
2874 * @param pUVM The user mode VM handle.
2875 */
2876VMMR3DECL(bool) HMR3IsPostedIntrsEnabled(PUVM pUVM)
2877{
2878 UVM_ASSERT_VALID_EXT_RETURN(pUVM, false);
2879 PVM pVM = pUVM->pVM;
2880 VM_ASSERT_VALID_EXT_RETURN(pVM, false);
2881 return pVM->hm.s.fPostedIntrs;
2882}
2883
2884
2885/**
2886 * Checks if we are currently using VPID in VT-x mode.
2887 *
2888 * @returns true if VPID is being used, otherwise false.
2889 * @param pUVM The user mode VM handle.
2890 */
2891VMMR3DECL(bool) HMR3IsVpidActive(PUVM pUVM)
2892{
2893 UVM_ASSERT_VALID_EXT_RETURN(pUVM, false);
2894 PVM pVM = pUVM->pVM;
2895 VM_ASSERT_VALID_EXT_RETURN(pVM, false);
2896 return pVM->hm.s.vmx.fVpid;
2897}
2898
2899
2900/**
2901 * Checks if we are currently using VT-x unrestricted execution,
2902 * aka UX.
2903 *
2904 * @returns true if UX is being used, otherwise false.
2905 * @param pUVM The user mode VM handle.
2906 */
2907VMMR3DECL(bool) HMR3IsUXActive(PUVM pUVM)
2908{
2909 UVM_ASSERT_VALID_EXT_RETURN(pUVM, false);
2910 PVM pVM = pUVM->pVM;
2911 VM_ASSERT_VALID_EXT_RETURN(pVM, false);
2912 return pVM->hm.s.vmx.fUnrestrictedGuest
2913 || pVM->hm.s.svm.fSupported;
2914}
2915
2916
2917/**
2918 * Checks if the VMX-preemption timer is being used.
2919 *
2920 * @returns true if the VMX-preemption timer is being used, otherwise false.
2921 * @param pVM The cross context VM structure.
2922 */
2923VMMR3_INT_DECL(bool) HMR3IsVmxPreemptionTimerUsed(PVM pVM)
2924{
2925 return HMIsEnabled(pVM)
2926 && pVM->hm.s.vmx.fEnabled
2927 && pVM->hm.s.vmx.fUsePreemptTimer;
2928}
2929
2930
2931/**
2932 * Check fatal VT-x/AMD-V error and produce some meaningful
2933 * log release message.
2934 *
2935 * @param pVM The cross context VM structure.
2936 * @param iStatusCode VBox status code.
2937 */
2938VMMR3_INT_DECL(void) HMR3CheckError(PVM pVM, int iStatusCode)
2939{
2940 for (VMCPUID i = 0; i < pVM->cCpus; i++)
2941 {
2942 PVMCPU pVCpu = &pVM->aCpus[i];
2943 PCVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
2944 bool const fNstGstVmcsActive = pVCpu->hm.s.vmx.fSwitchedToNstGstVmcs;
2945 switch (iStatusCode)
2946 {
2947 /** @todo r=ramshankar: Are all EMTs out of ring-0 at this point!? If not, we
2948 * might be getting inaccurate values for non-guru'ing EMTs. */
2949 case VERR_VMX_INVALID_VMCS_FIELD:
2950 break;
2951
2952 case VERR_VMX_INVALID_VMCS_PTR:
2953 {
2954 LogRel(("HM: VERR_VMX_INVALID_VMCS_PTR:\n"));
2955 LogRel(("HM: CPU[%u] %s VMCS active\n", i, fNstGstVmcsActive ? "Nested-guest" : "Guest"));
2956 LogRel(("HM: CPU[%u] Current pointer %#RHp vs %#RHp\n", i, pVCpu->hm.s.vmx.LastError.HCPhysCurrentVmcs,
2957 pVmcsInfo->HCPhysVmcs));
2958 LogRel(("HM: CPU[%u] Current VMCS version %#x\n", i, pVCpu->hm.s.vmx.LastError.u32VmcsRev));
2959 LogRel(("HM: CPU[%u] Entered Host Cpu %u\n", i, pVCpu->hm.s.vmx.LastError.idEnteredCpu));
2960 LogRel(("HM: CPU[%u] Current Host Cpu %u\n", i, pVCpu->hm.s.vmx.LastError.idCurrentCpu));
2961 break;
2962 }
2963
2964 case VERR_VMX_UNABLE_TO_START_VM:
2965 LogRel(("HM: VERR_VMX_UNABLE_TO_START_VM:\n"));
2966 LogRel(("HM: CPU[%u] %s VMCS active\n", i, fNstGstVmcsActive ? "Nested-guest" : "Guest"));
2967 LogRel(("HM: CPU[%u] Instruction error %#x\n", i, pVCpu->hm.s.vmx.LastError.u32InstrError));
2968 LogRel(("HM: CPU[%u] Exit reason %#x\n", i, pVCpu->hm.s.vmx.LastError.u32ExitReason));
2969
2970 if ( pVCpu->hm.s.vmx.LastError.u32InstrError == VMXINSTRERR_VMLAUNCH_NON_CLEAR_VMCS
2971 || pVCpu->hm.s.vmx.LastError.u32InstrError == VMXINSTRERR_VMRESUME_NON_LAUNCHED_VMCS)
2972 {
2973 LogRel(("HM: CPU[%u] Entered Host Cpu %u\n", i, pVCpu->hm.s.vmx.LastError.idEnteredCpu));
2974 LogRel(("HM: CPU[%u] Current Host Cpu %u\n", i, pVCpu->hm.s.vmx.LastError.idCurrentCpu));
2975 }
2976 else if (pVCpu->hm.s.vmx.LastError.u32InstrError == VMXINSTRERR_VMENTRY_INVALID_CTLS)
2977 {
2978 LogRel(("HM: CPU[%u] PinCtls %#RX32\n", i, pVmcsInfo->u32PinCtls));
2979 {
2980 uint32_t const u32Val = pVmcsInfo->u32PinCtls;
2981 HMVMX_LOGREL_FEAT(u32Val, VMX_PIN_CTLS_EXT_INT_EXIT );
2982 HMVMX_LOGREL_FEAT(u32Val, VMX_PIN_CTLS_NMI_EXIT );
2983 HMVMX_LOGREL_FEAT(u32Val, VMX_PIN_CTLS_VIRT_NMI );
2984 HMVMX_LOGREL_FEAT(u32Val, VMX_PIN_CTLS_PREEMPT_TIMER);
2985 HMVMX_LOGREL_FEAT(u32Val, VMX_PIN_CTLS_POSTED_INT );
2986 }
2987 LogRel(("HM: CPU[%u] ProcCtls %#RX32\n", i, pVmcsInfo->u32ProcCtls));
2988 {
2989 uint32_t const u32Val = pVmcsInfo->u32ProcCtls;
2990 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_INT_WINDOW_EXIT );
2991 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_USE_TSC_OFFSETTING);
2992 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_HLT_EXIT );
2993 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_INVLPG_EXIT );
2994 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_MWAIT_EXIT );
2995 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_RDPMC_EXIT );
2996 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_RDTSC_EXIT );
2997 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_CR3_LOAD_EXIT );
2998 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_CR3_STORE_EXIT );
2999 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_CR8_LOAD_EXIT );
3000 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_CR8_STORE_EXIT );
3001 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_USE_TPR_SHADOW );
3002 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_NMI_WINDOW_EXIT );
3003 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_MOV_DR_EXIT );
3004 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_UNCOND_IO_EXIT );
3005 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_USE_IO_BITMAPS );
3006 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_MONITOR_TRAP_FLAG );
3007 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_USE_MSR_BITMAPS );
3008 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_MONITOR_EXIT );
3009 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_PAUSE_EXIT );
3010 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS_USE_SECONDARY_CTLS);
3011 }
3012 LogRel(("HM: CPU[%u] ProcCtls2 %#RX32\n", i, pVmcsInfo->u32ProcCtls2));
3013 {
3014 uint32_t const u32Val = pVmcsInfo->u32ProcCtls2;
3015 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_VIRT_APIC_ACCESS );
3016 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_EPT );
3017 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_DESC_TABLE_EXIT );
3018 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_RDTSCP );
3019 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_VIRT_X2APIC_MODE );
3020 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_VPID );
3021 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_WBINVD_EXIT );
3022 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_UNRESTRICTED_GUEST );
3023 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_APIC_REG_VIRT );
3024 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_VIRT_INT_DELIVERY );
3025 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_PAUSE_LOOP_EXIT );
3026 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_RDRAND_EXIT );
3027 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_INVPCID );
3028 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_VMFUNC );
3029 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_VMCS_SHADOWING );
3030 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_ENCLS_EXIT );
3031 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_RDSEED_EXIT );
3032 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_PML );
3033 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_EPT_VE );
3034 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_CONCEAL_VMX_FROM_PT);
3035 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_XSAVES_XRSTORS );
3036 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_MODE_BASED_EPT_PERM);
3037 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_SPPTP_EPT );
3038 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_PT_EPT );
3039 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_TSC_SCALING );
3040 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_USER_WAIT_PAUSE );
3041 HMVMX_LOGREL_FEAT(u32Val, VMX_PROC_CTLS2_ENCLV_EXIT );
3042 }
3043 LogRel(("HM: CPU[%u] EntryCtls %#RX32\n", i, pVmcsInfo->u32EntryCtls));
3044 {
3045 uint32_t const u32Val = pVmcsInfo->u32EntryCtls;
3046 HMVMX_LOGREL_FEAT(u32Val, VMX_ENTRY_CTLS_LOAD_DEBUG );
3047 HMVMX_LOGREL_FEAT(u32Val, VMX_ENTRY_CTLS_IA32E_MODE_GUEST );
3048 HMVMX_LOGREL_FEAT(u32Val, VMX_ENTRY_CTLS_ENTRY_TO_SMM );
3049 HMVMX_LOGREL_FEAT(u32Val, VMX_ENTRY_CTLS_DEACTIVATE_DUAL_MON);
3050 HMVMX_LOGREL_FEAT(u32Val, VMX_ENTRY_CTLS_LOAD_PERF_MSR );
3051 HMVMX_LOGREL_FEAT(u32Val, VMX_ENTRY_CTLS_LOAD_PAT_MSR );
3052 HMVMX_LOGREL_FEAT(u32Val, VMX_ENTRY_CTLS_LOAD_EFER_MSR );
3053 HMVMX_LOGREL_FEAT(u32Val, VMX_ENTRY_CTLS_LOAD_BNDCFGS_MSR );
3054 HMVMX_LOGREL_FEAT(u32Val, VMX_ENTRY_CTLS_CONCEAL_VMX_FROM_PT);
3055 HMVMX_LOGREL_FEAT(u32Val, VMX_ENTRY_CTLS_LOAD_RTIT_CTL_MSR );
3056 }
3057 LogRel(("HM: CPU[%u] ExitCtls %#RX32\n", i, pVmcsInfo->u32ExitCtls));
3058 {
3059 uint32_t const u32Val = pVmcsInfo->u32ExitCtls;
3060 HMVMX_LOGREL_FEAT(u32Val, VMX_EXIT_CTLS_SAVE_DEBUG );
3061 HMVMX_LOGREL_FEAT(u32Val, VMX_EXIT_CTLS_HOST_ADDR_SPACE_SIZE );
3062 HMVMX_LOGREL_FEAT(u32Val, VMX_EXIT_CTLS_LOAD_PERF_MSR );
3063 HMVMX_LOGREL_FEAT(u32Val, VMX_EXIT_CTLS_ACK_EXT_INT );
3064 HMVMX_LOGREL_FEAT(u32Val, VMX_EXIT_CTLS_SAVE_PAT_MSR );
3065 HMVMX_LOGREL_FEAT(u32Val, VMX_EXIT_CTLS_LOAD_PAT_MSR );
3066 HMVMX_LOGREL_FEAT(u32Val, VMX_EXIT_CTLS_SAVE_EFER_MSR );
3067 HMVMX_LOGREL_FEAT(u32Val, VMX_EXIT_CTLS_LOAD_EFER_MSR );
3068 HMVMX_LOGREL_FEAT(u32Val, VMX_EXIT_CTLS_SAVE_PREEMPT_TIMER );
3069 HMVMX_LOGREL_FEAT(u32Val, VMX_EXIT_CTLS_CLEAR_BNDCFGS_MSR );
3070 HMVMX_LOGREL_FEAT(u32Val, VMX_EXIT_CTLS_CONCEAL_VMX_FROM_PT );
3071 HMVMX_LOGREL_FEAT(u32Val, VMX_EXIT_CTLS_CLEAR_RTIT_CTL_MSR );
3072 }
3073 LogRel(("HM: CPU[%u] HCPhysMsrBitmap %#RHp\n", i, pVmcsInfo->HCPhysMsrBitmap));
3074 LogRel(("HM: CPU[%u] HCPhysGuestMsrLoad %#RHp\n", i, pVmcsInfo->HCPhysGuestMsrLoad));
3075 LogRel(("HM: CPU[%u] HCPhysGuestMsrStore %#RHp\n", i, pVmcsInfo->HCPhysGuestMsrStore));
3076 LogRel(("HM: CPU[%u] HCPhysHostMsrLoad %#RHp\n", i, pVmcsInfo->HCPhysHostMsrLoad));
3077 LogRel(("HM: CPU[%u] cEntryMsrLoad %u\n", i, pVmcsInfo->cEntryMsrLoad));
3078 LogRel(("HM: CPU[%u] cExitMsrStore %u\n", i, pVmcsInfo->cExitMsrStore));
3079 LogRel(("HM: CPU[%u] cExitMsrLoad %u\n", i, pVmcsInfo->cExitMsrLoad));
3080 }
3081 /** @todo Log VM-entry event injection control fields
3082 * VMX_VMCS_CTRL_ENTRY_IRQ_INFO, VMX_VMCS_CTRL_ENTRY_EXCEPTION_ERRCODE
3083 * and VMX_VMCS_CTRL_ENTRY_INSTR_LENGTH from the VMCS. */
3084 break;
3085
3086 /* The guru will dump the HM error and exit history. Nothing extra to report for these errors. */
3087 case VERR_VMX_INVALID_VMXON_PTR:
3088 case VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO:
3089 case VERR_VMX_INVALID_GUEST_STATE:
3090 case VERR_VMX_UNEXPECTED_EXIT:
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.

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