VirtualBox

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

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

VMM: Reordering some STAT counters, spaces and nits.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 170.7 KB
Line 
1/* $Id: HM.cpp 73287 2018-07-21 04:50:51Z vboxsync $ */
2/** @file
3 * HM - Intel/AMD VM Hardware Support Manager.
4 */
5
6/*
7 * Copyright (C) 2006-2017 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/pdmapi.h>
45#include <VBox/vmm/pgm.h>
46#include <VBox/vmm/ssm.h>
47#include <VBox/vmm/trpm.h>
48#include <VBox/vmm/dbgf.h>
49#include <VBox/vmm/iom.h>
50#include <VBox/vmm/iem.h>
51#include <VBox/vmm/patm.h>
52#include <VBox/vmm/csam.h>
53#include <VBox/vmm/selm.h>
54#include <VBox/vmm/nem.h>
55#ifdef VBOX_WITH_REM
56# include <VBox/vmm/rem.h>
57#endif
58#include <VBox/vmm/hm_vmx.h>
59#include <VBox/vmm/hm_svm.h>
60#include "HMInternal.h"
61#include <VBox/vmm/vm.h>
62#include <VBox/vmm/uvm.h>
63#include <VBox/err.h>
64#include <VBox/param.h>
65
66#include <iprt/assert.h>
67#include <VBox/log.h>
68#include <iprt/asm.h>
69#include <iprt/asm-amd64-x86.h>
70#include <iprt/env.h>
71#include <iprt/thread.h>
72
73
74/*********************************************************************************************************************************
75* Global Variables *
76*********************************************************************************************************************************/
77#define EXIT_REASON(def, val, str) #def " - " #val " - " str
78#define EXIT_REASON_NIL() NULL
79/** Exit reason descriptions for VT-x, used to describe statistics. */
80static const char * const g_apszVTxExitReasons[MAX_EXITREASON_STAT] =
81{
82 EXIT_REASON(VMX_EXIT_XCPT_OR_NMI , 0, "Exception or non-maskable interrupt (NMI)."),
83 EXIT_REASON(VMX_EXIT_EXT_INT , 1, "External interrupt."),
84 EXIT_REASON(VMX_EXIT_TRIPLE_FAULT , 2, "Triple fault."),
85 EXIT_REASON(VMX_EXIT_INIT_SIGNAL , 3, "INIT signal."),
86 EXIT_REASON(VMX_EXIT_SIPI , 4, "Start-up IPI (SIPI)."),
87 EXIT_REASON(VMX_EXIT_IO_SMI_IRQ , 5, "I/O system-management interrupt (SMI)."),
88 EXIT_REASON(VMX_EXIT_SMI_IRQ , 6, "Other SMI."),
89 EXIT_REASON(VMX_EXIT_INT_WINDOW , 7, "Interrupt window."),
90 EXIT_REASON(VMX_EXIT_NMI_WINDOW , 8, "NMI window."),
91 EXIT_REASON(VMX_EXIT_TASK_SWITCH , 9, "Task switch."),
92 EXIT_REASON(VMX_EXIT_CPUID , 10, "CPUID instruction."),
93 EXIT_REASON(VMX_EXIT_GETSEC , 11, "GETSEC instrunction."),
94 EXIT_REASON(VMX_EXIT_HLT , 12, "HLT instruction."),
95 EXIT_REASON(VMX_EXIT_INVD , 13, "INVD instruction."),
96 EXIT_REASON(VMX_EXIT_INVLPG , 14, "INVLPG instruction."),
97 EXIT_REASON(VMX_EXIT_RDPMC , 15, "RDPMCinstruction."),
98 EXIT_REASON(VMX_EXIT_RDTSC , 16, "RDTSC instruction."),
99 EXIT_REASON(VMX_EXIT_RSM , 17, "RSM instruction in SMM."),
100 EXIT_REASON(VMX_EXIT_VMCALL , 18, "VMCALL instruction."),
101 EXIT_REASON(VMX_EXIT_VMCLEAR , 19, "VMCLEAR instruction."),
102 EXIT_REASON(VMX_EXIT_VMLAUNCH , 20, "VMLAUNCH instruction."),
103 EXIT_REASON(VMX_EXIT_VMPTRLD , 21, "VMPTRLD instruction."),
104 EXIT_REASON(VMX_EXIT_VMPTRST , 22, "VMPTRST instruction."),
105 EXIT_REASON(VMX_EXIT_VMREAD , 23, "VMREAD instruction."),
106 EXIT_REASON(VMX_EXIT_VMRESUME , 24, "VMRESUME instruction."),
107 EXIT_REASON(VMX_EXIT_VMWRITE , 25, "VMWRITE instruction."),
108 EXIT_REASON(VMX_EXIT_VMXOFF , 26, "VMXOFF instruction."),
109 EXIT_REASON(VMX_EXIT_VMXON , 27, "VMXON instruction."),
110 EXIT_REASON(VMX_EXIT_MOV_CRX , 28, "Control-register accesses."),
111 EXIT_REASON(VMX_EXIT_MOV_DRX , 29, "Debug-register accesses."),
112 EXIT_REASON(VMX_EXIT_PORT_IO , 30, "I/O instruction."),
113 EXIT_REASON(VMX_EXIT_RDMSR , 31, "RDMSR instruction."),
114 EXIT_REASON(VMX_EXIT_WRMSR , 32, "WRMSR instruction."),
115 EXIT_REASON(VMX_EXIT_ERR_INVALID_GUEST_STATE, 33, "VM-entry failure due to invalid guest state."),
116 EXIT_REASON(VMX_EXIT_ERR_MSR_LOAD , 34, "VM-entry failure due to MSR loading."),
117 EXIT_REASON_NIL(),
118 EXIT_REASON(VMX_EXIT_MWAIT , 36, "MWAIT instruction."),
119 EXIT_REASON(VMX_EXIT_MTF , 37, "Monitor Trap Flag."),
120 EXIT_REASON_NIL(),
121 EXIT_REASON(VMX_EXIT_MONITOR , 39, "MONITOR instruction."),
122 EXIT_REASON(VMX_EXIT_PAUSE , 40, "PAUSE instruction."),
123 EXIT_REASON(VMX_EXIT_ERR_MACHINE_CHECK , 41, "VM-entry failure due to machine-check."),
124 EXIT_REASON_NIL(),
125 EXIT_REASON(VMX_EXIT_TPR_BELOW_THRESHOLD , 43, "TPR below threshold (MOV to CR8)."),
126 EXIT_REASON(VMX_EXIT_APIC_ACCESS , 44, "APIC access."),
127 EXIT_REASON(VMX_EXIT_VIRTUALIZED_EOI , 45, "Virtualized EOI."),
128 EXIT_REASON(VMX_EXIT_XDTR_ACCESS , 46, "GDTR/IDTR access using LGDT/SGDT/LIDT/SIDT."),
129 EXIT_REASON(VMX_EXIT_TR_ACCESS , 47, "LDTR/TR access using LLDT/SLDT/LTR/STR."),
130 EXIT_REASON(VMX_EXIT_EPT_VIOLATION , 48, "EPT violation."),
131 EXIT_REASON(VMX_EXIT_EPT_MISCONFIG , 49, "EPT misconfiguration."),
132 EXIT_REASON(VMX_EXIT_INVEPT , 50, "INVEPT instruction."),
133 EXIT_REASON(VMX_EXIT_RDTSCP , 51, "RDTSCP instruction."),
134 EXIT_REASON(VMX_EXIT_PREEMPT_TIMER , 52, "VMX-preemption timer expired."),
135 EXIT_REASON(VMX_EXIT_INVVPID , 53, "INVVPID instruction."),
136 EXIT_REASON(VMX_EXIT_WBINVD , 54, "WBINVD instruction."),
137 EXIT_REASON(VMX_EXIT_XSETBV , 55, "XSETBV instruction."),
138 EXIT_REASON(VMX_EXIT_APIC_WRITE , 56, "APIC write completed to virtual-APIC page."),
139 EXIT_REASON(VMX_EXIT_RDRAND , 57, "RDRAND instruction."),
140 EXIT_REASON(VMX_EXIT_INVPCID , 58, "INVPCID instruction."),
141 EXIT_REASON(VMX_EXIT_VMFUNC , 59, "VMFUNC instruction."),
142 EXIT_REASON(VMX_EXIT_ENCLS , 60, "ENCLS instruction."),
143 EXIT_REASON(VMX_EXIT_RDSEED , 61, "RDSEED instruction."),
144 EXIT_REASON(VMX_EXIT_PML_FULL , 62, "Page-modification log full."),
145 EXIT_REASON(VMX_EXIT_XSAVES , 63, "XSAVES instruction."),
146 EXIT_REASON(VMX_EXIT_XRSTORS , 64, "XRSTORS instruction.")
147};
148/** Array index of the last valid VT-x exit reason. */
149#define MAX_EXITREASON_VTX 64
150
151/** A partial list of Exit reason descriptions for AMD-V, used to describe
152 * statistics.
153 *
154 * @note AMD-V have annoyingly large gaps (e.g. \#NPF VMEXIT comes at 1024),
155 * this array doesn't contain the entire set of exit reasons, we
156 * handle them via hmSvmGetSpecialExitReasonDesc(). */
157static const char * const g_apszAmdVExitReasons[MAX_EXITREASON_STAT] =
158{
159 EXIT_REASON(SVM_EXIT_READ_CR0 , 0, "Read CR0."),
160 EXIT_REASON(SVM_EXIT_READ_CR1 , 1, "Read CR1."),
161 EXIT_REASON(SVM_EXIT_READ_CR2 , 2, "Read CR2."),
162 EXIT_REASON(SVM_EXIT_READ_CR3 , 3, "Read CR3."),
163 EXIT_REASON(SVM_EXIT_READ_CR4 , 4, "Read CR4."),
164 EXIT_REASON(SVM_EXIT_READ_CR5 , 5, "Read CR5."),
165 EXIT_REASON(SVM_EXIT_READ_CR6 , 6, "Read CR6."),
166 EXIT_REASON(SVM_EXIT_READ_CR7 , 7, "Read CR7."),
167 EXIT_REASON(SVM_EXIT_READ_CR8 , 8, "Read CR8."),
168 EXIT_REASON(SVM_EXIT_READ_CR9 , 9, "Read CR9."),
169 EXIT_REASON(SVM_EXIT_READ_CR10 , 10, "Read CR10."),
170 EXIT_REASON(SVM_EXIT_READ_CR11 , 11, "Read CR11."),
171 EXIT_REASON(SVM_EXIT_READ_CR12 , 12, "Read CR12."),
172 EXIT_REASON(SVM_EXIT_READ_CR13 , 13, "Read CR13."),
173 EXIT_REASON(SVM_EXIT_READ_CR14 , 14, "Read CR14."),
174 EXIT_REASON(SVM_EXIT_READ_CR15 , 15, "Read CR15."),
175 EXIT_REASON(SVM_EXIT_WRITE_CR0 , 16, "Write CR0."),
176 EXIT_REASON(SVM_EXIT_WRITE_CR1 , 17, "Write CR1."),
177 EXIT_REASON(SVM_EXIT_WRITE_CR2 , 18, "Write CR2."),
178 EXIT_REASON(SVM_EXIT_WRITE_CR3 , 19, "Write CR3."),
179 EXIT_REASON(SVM_EXIT_WRITE_CR4 , 20, "Write CR4."),
180 EXIT_REASON(SVM_EXIT_WRITE_CR5 , 21, "Write CR5."),
181 EXIT_REASON(SVM_EXIT_WRITE_CR6 , 22, "Write CR6."),
182 EXIT_REASON(SVM_EXIT_WRITE_CR7 , 23, "Write CR7."),
183 EXIT_REASON(SVM_EXIT_WRITE_CR8 , 24, "Write CR8."),
184 EXIT_REASON(SVM_EXIT_WRITE_CR9 , 25, "Write CR9."),
185 EXIT_REASON(SVM_EXIT_WRITE_CR10 , 26, "Write CR10."),
186 EXIT_REASON(SVM_EXIT_WRITE_CR11 , 27, "Write CR11."),
187 EXIT_REASON(SVM_EXIT_WRITE_CR12 , 28, "Write CR12."),
188 EXIT_REASON(SVM_EXIT_WRITE_CR13 , 29, "Write CR13."),
189 EXIT_REASON(SVM_EXIT_WRITE_CR14 , 30, "Write CR14."),
190 EXIT_REASON(SVM_EXIT_WRITE_CR15 , 31, "Write CR15."),
191 EXIT_REASON(SVM_EXIT_READ_DR0 , 32, "Read DR0."),
192 EXIT_REASON(SVM_EXIT_READ_DR1 , 33, "Read DR1."),
193 EXIT_REASON(SVM_EXIT_READ_DR2 , 34, "Read DR2."),
194 EXIT_REASON(SVM_EXIT_READ_DR3 , 35, "Read DR3."),
195 EXIT_REASON(SVM_EXIT_READ_DR4 , 36, "Read DR4."),
196 EXIT_REASON(SVM_EXIT_READ_DR5 , 37, "Read DR5."),
197 EXIT_REASON(SVM_EXIT_READ_DR6 , 38, "Read DR6."),
198 EXIT_REASON(SVM_EXIT_READ_DR7 , 39, "Read DR7."),
199 EXIT_REASON(SVM_EXIT_READ_DR8 , 40, "Read DR8."),
200 EXIT_REASON(SVM_EXIT_READ_DR9 , 41, "Read DR9."),
201 EXIT_REASON(SVM_EXIT_READ_DR10 , 42, "Read DR10."),
202 EXIT_REASON(SVM_EXIT_READ_DR11 , 43, "Read DR11"),
203 EXIT_REASON(SVM_EXIT_READ_DR12 , 44, "Read DR12."),
204 EXIT_REASON(SVM_EXIT_READ_DR13 , 45, "Read DR13."),
205 EXIT_REASON(SVM_EXIT_READ_DR14 , 46, "Read DR14."),
206 EXIT_REASON(SVM_EXIT_READ_DR15 , 47, "Read DR15."),
207 EXIT_REASON(SVM_EXIT_WRITE_DR0 , 48, "Write DR0."),
208 EXIT_REASON(SVM_EXIT_WRITE_DR1 , 49, "Write DR1."),
209 EXIT_REASON(SVM_EXIT_WRITE_DR2 , 50, "Write DR2."),
210 EXIT_REASON(SVM_EXIT_WRITE_DR3 , 51, "Write DR3."),
211 EXIT_REASON(SVM_EXIT_WRITE_DR4 , 52, "Write DR4."),
212 EXIT_REASON(SVM_EXIT_WRITE_DR5 , 53, "Write DR5."),
213 EXIT_REASON(SVM_EXIT_WRITE_DR6 , 54, "Write DR6."),
214 EXIT_REASON(SVM_EXIT_WRITE_DR7 , 55, "Write DR7."),
215 EXIT_REASON(SVM_EXIT_WRITE_DR8 , 56, "Write DR8."),
216 EXIT_REASON(SVM_EXIT_WRITE_DR9 , 57, "Write DR9."),
217 EXIT_REASON(SVM_EXIT_WRITE_DR10 , 58, "Write DR10."),
218 EXIT_REASON(SVM_EXIT_WRITE_DR11 , 59, "Write DR11."),
219 EXIT_REASON(SVM_EXIT_WRITE_DR12 , 60, "Write DR12."),
220 EXIT_REASON(SVM_EXIT_WRITE_DR13 , 61, "Write DR13."),
221 EXIT_REASON(SVM_EXIT_WRITE_DR14 , 62, "Write DR14."),
222 EXIT_REASON(SVM_EXIT_WRITE_DR15 , 63, "Write DR15."),
223 EXIT_REASON(SVM_EXIT_XCPT_0 , 64, "Exception 0 (#DE)."),
224 EXIT_REASON(SVM_EXIT_XCPT_1 , 65, "Exception 1 (#DB)."),
225 EXIT_REASON(SVM_EXIT_XCPT_2 , 66, "Exception 2 (#NMI)."),
226 EXIT_REASON(SVM_EXIT_XCPT_3 , 67, "Exception 3 (#BP)."),
227 EXIT_REASON(SVM_EXIT_XCPT_4 , 68, "Exception 4 (#OF)."),
228 EXIT_REASON(SVM_EXIT_XCPT_5 , 69, "Exception 5 (#BR)."),
229 EXIT_REASON(SVM_EXIT_XCPT_6 , 70, "Exception 6 (#UD)."),
230 EXIT_REASON(SVM_EXIT_XCPT_7 , 71, "Exception 7 (#NM)."),
231 EXIT_REASON(SVM_EXIT_XCPT_8 , 72, "Exception 8 (#DF)."),
232 EXIT_REASON(SVM_EXIT_XCPT_9 , 73, "Exception 9 (#CO_SEG_OVERRUN)."),
233 EXIT_REASON(SVM_EXIT_XCPT_10 , 74, "Exception 10 (#TS)."),
234 EXIT_REASON(SVM_EXIT_XCPT_11 , 75, "Exception 11 (#NP)."),
235 EXIT_REASON(SVM_EXIT_XCPT_12 , 76, "Exception 12 (#SS)."),
236 EXIT_REASON(SVM_EXIT_XCPT_13 , 77, "Exception 13 (#GP)."),
237 EXIT_REASON(SVM_EXIT_XCPT_14 , 78, "Exception 14 (#PF)."),
238 EXIT_REASON(SVM_EXIT_XCPT_15 , 79, "Exception 15 (0x0f)."),
239 EXIT_REASON(SVM_EXIT_XCPT_16 , 80, "Exception 16 (#MF)."),
240 EXIT_REASON(SVM_EXIT_XCPT_17 , 81, "Exception 17 (#AC)."),
241 EXIT_REASON(SVM_EXIT_XCPT_18 , 82, "Exception 18 (#MC)."),
242 EXIT_REASON(SVM_EXIT_XCPT_19 , 83, "Exception 19 (#XF)."),
243 EXIT_REASON(SVM_EXIT_XCPT_20 , 84, "Exception 20 (#VE)."),
244 EXIT_REASON(SVM_EXIT_XCPT_21 , 85, "Exception 22 (0x15)."),
245 EXIT_REASON(SVM_EXIT_XCPT_22 , 86, "Exception 22 (0x16)."),
246 EXIT_REASON(SVM_EXIT_XCPT_23 , 87, "Exception 23 (0x17)."),
247 EXIT_REASON(SVM_EXIT_XCPT_24 , 88, "Exception 24 (0x18)."),
248 EXIT_REASON(SVM_EXIT_XCPT_25 , 89, "Exception 25 (0x19)."),
249 EXIT_REASON(SVM_EXIT_XCPT_26 , 90, "Exception 26 (0x1A)."),
250 EXIT_REASON(SVM_EXIT_XCPT_27 , 91, "Exception 27 (0x1B)."),
251 EXIT_REASON(SVM_EXIT_XCPT_28 , 92, "Exception 28 (0x1C)."),
252 EXIT_REASON(SVM_EXIT_XCPT_29 , 93, "Exception 29 (0x1D)."),
253 EXIT_REASON(SVM_EXIT_XCPT_30 , 94, "Exception 30 (#SX)."),
254 EXIT_REASON(SVM_EXIT_XCPT_31 , 95, "Exception 31 (0x1F)."),
255 EXIT_REASON(SVM_EXIT_INTR , 96, "Physical maskable interrupt (host)."),
256 EXIT_REASON(SVM_EXIT_NMI , 97, "Physical non-maskable interrupt (host)."),
257 EXIT_REASON(SVM_EXIT_SMI , 98, "System management interrupt (host)."),
258 EXIT_REASON(SVM_EXIT_INIT , 99, "Physical INIT signal (host)."),
259 EXIT_REASON(SVM_EXIT_VINTR , 100, "Virtual interrupt-window exit."),
260 EXIT_REASON(SVM_EXIT_CR0_SEL_WRITE, 101, "Selective CR0 Write (to bits other than CR0.TS and CR0.MP)."),
261 EXIT_REASON(SVM_EXIT_IDTR_READ , 102, "Read IDTR."),
262 EXIT_REASON(SVM_EXIT_GDTR_READ , 103, "Read GDTR."),
263 EXIT_REASON(SVM_EXIT_LDTR_READ , 104, "Read LDTR."),
264 EXIT_REASON(SVM_EXIT_TR_READ , 105, "Read TR."),
265 EXIT_REASON(SVM_EXIT_IDTR_WRITE , 106, "Write IDTR."),
266 EXIT_REASON(SVM_EXIT_GDTR_WRITE , 107, "Write GDTR."),
267 EXIT_REASON(SVM_EXIT_LDTR_WRITE , 108, "Write LDTR."),
268 EXIT_REASON(SVM_EXIT_TR_WRITE , 109, "Write TR."),
269 EXIT_REASON(SVM_EXIT_RDTSC , 110, "RDTSC instruction."),
270 EXIT_REASON(SVM_EXIT_RDPMC , 111, "RDPMC instruction."),
271 EXIT_REASON(SVM_EXIT_PUSHF , 112, "PUSHF instruction."),
272 EXIT_REASON(SVM_EXIT_POPF , 113, "POPF instruction."),
273 EXIT_REASON(SVM_EXIT_CPUID , 114, "CPUID instruction."),
274 EXIT_REASON(SVM_EXIT_RSM , 115, "RSM instruction."),
275 EXIT_REASON(SVM_EXIT_IRET , 116, "IRET instruction."),
276 EXIT_REASON(SVM_EXIT_SWINT , 117, "Software interrupt (INTn instructions)."),
277 EXIT_REASON(SVM_EXIT_INVD , 118, "INVD instruction."),
278 EXIT_REASON(SVM_EXIT_PAUSE , 119, "PAUSE instruction."),
279 EXIT_REASON(SVM_EXIT_HLT , 120, "HLT instruction."),
280 EXIT_REASON(SVM_EXIT_INVLPG , 121, "INVLPG instruction."),
281 EXIT_REASON(SVM_EXIT_INVLPGA , 122, "INVLPGA instruction."),
282 EXIT_REASON(SVM_EXIT_IOIO , 123, "IN/OUT/INS/OUTS instruction."),
283 EXIT_REASON(SVM_EXIT_MSR , 124, "RDMSR or WRMSR access to protected MSR."),
284 EXIT_REASON(SVM_EXIT_TASK_SWITCH , 125, "Task switch."),
285 EXIT_REASON(SVM_EXIT_FERR_FREEZE , 126, "FERR Freeze; CPU frozen in an x87/mmx instruction waiting for interrupt."),
286 EXIT_REASON(SVM_EXIT_SHUTDOWN , 127, "Shutdown."),
287 EXIT_REASON(SVM_EXIT_VMRUN , 128, "VMRUN instruction."),
288 EXIT_REASON(SVM_EXIT_VMMCALL , 129, "VMCALL instruction."),
289 EXIT_REASON(SVM_EXIT_VMLOAD , 130, "VMLOAD instruction."),
290 EXIT_REASON(SVM_EXIT_VMSAVE , 131, "VMSAVE instruction."),
291 EXIT_REASON(SVM_EXIT_STGI , 132, "STGI instruction."),
292 EXIT_REASON(SVM_EXIT_CLGI , 133, "CLGI instruction."),
293 EXIT_REASON(SVM_EXIT_SKINIT , 134, "SKINIT instruction."),
294 EXIT_REASON(SVM_EXIT_RDTSCP , 135, "RDTSCP instruction."),
295 EXIT_REASON(SVM_EXIT_ICEBP , 136, "ICEBP instruction."),
296 EXIT_REASON(SVM_EXIT_WBINVD , 137, "WBINVD instruction."),
297 EXIT_REASON(SVM_EXIT_MONITOR , 138, "MONITOR instruction."),
298 EXIT_REASON(SVM_EXIT_MWAIT , 139, "MWAIT instruction."),
299 EXIT_REASON(SVM_EXIT_MWAIT_ARMED , 140, "MWAIT instruction when armed."),
300 EXIT_REASON(SVM_EXIT_XSETBV , 141, "XSETBV instruction."),
301};
302/** Array index of the last valid AMD-V exit reason. */
303#define MAX_EXITREASON_AMDV 141
304
305/** Special exit reasons not covered in the array above. */
306#define SVM_EXIT_REASON_NPF EXIT_REASON(SVM_EXIT_NPF , 1024, "Nested Page Fault.")
307#define SVM_EXIT_REASON_AVIC_INCOMPLETE_IPI EXIT_REASON(SVM_EXIT_AVIC_INCOMPLETE_IPI, 1025, "AVIC - Incomplete IPI delivery.")
308#define SVM_EXIT_REASON_AVIC_NOACCEL EXIT_REASON(SVM_EXIT_AVIC_NOACCEL , 1026, "AVIC - Unhandled register.")
309
310/**
311 * Gets the SVM exit reason if it's one of the reasons not present in the @c
312 * g_apszAmdVExitReasons array.
313 *
314 * @returns The exit reason or NULL if unknown.
315 * @param uExit The exit.
316 */
317DECLINLINE(const char *) hmSvmGetSpecialExitReasonDesc(uint16_t uExit)
318{
319 switch (uExit)
320 {
321 case SVM_EXIT_NPF: return SVM_EXIT_REASON_NPF;
322 case SVM_EXIT_AVIC_INCOMPLETE_IPI: return SVM_EXIT_REASON_AVIC_INCOMPLETE_IPI;
323 case SVM_EXIT_AVIC_NOACCEL: return SVM_EXIT_REASON_AVIC_NOACCEL;
324 }
325 return EXIT_REASON_NIL();
326}
327#undef EXIT_REASON_NIL
328#undef EXIT_REASON
329
330/** @def HMVMX_REPORT_FEAT
331 * Reports VT-x feature to the release log.
332 *
333 * @param allowed1 Mask of allowed feature bits.
334 * @param disallowed0 Mask of disallowed feature bits.
335 * @param strdesc The description string to report.
336 * @param featflag Mask of the feature to report.
337 */
338#define HMVMX_REPORT_FEAT(allowed1, disallowed0, strdesc, featflag) \
339 do { \
340 if ((allowed1) & (featflag)) \
341 { \
342 if ((disallowed0) & (featflag)) \
343 LogRel(("HM: " strdesc " (must be set)\n")); \
344 else \
345 LogRel(("HM: " strdesc "\n")); \
346 } \
347 else \
348 LogRel(("HM: " strdesc " (must be cleared)\n")); \
349 } while (0)
350
351/** @def HMVMX_REPORT_ALLOWED_FEAT
352 * Reports an allowed VT-x feature to the release log.
353 *
354 * @param allowed1 Mask of allowed feature bits.
355 * @param strdesc The description string to report.
356 * @param featflag Mask of the feature to report.
357 */
358#define HMVMX_REPORT_ALLOWED_FEAT(allowed1, strdesc, featflag) \
359 do { \
360 if ((allowed1) & (featflag)) \
361 LogRel(("HM: " strdesc "\n")); \
362 else \
363 LogRel(("HM: " strdesc " not supported\n")); \
364 } while (0)
365
366/** @def HMVMX_REPORT_MSR_CAP
367 * Reports MSR feature capability.
368 *
369 * @param msrcaps Mask of MSR feature bits.
370 * @param strdesc The description string to report.
371 * @param cap Mask of the feature to report.
372 */
373#define HMVMX_REPORT_MSR_CAP(msrcaps, strdesc, cap) \
374 do { \
375 if ((msrcaps) & (cap)) \
376 LogRel(("HM: " strdesc "\n")); \
377 } while (0)
378
379/** @def HMVMX_LOGREL_FEAT
380 * Dumps a feature flag from a bitmap of features to the release log.
381 *
382 * @param a_fVal The value of all the features.
383 * @param a_fMask The specific bitmask of the feature.
384 */
385#define HMVMX_LOGREL_FEAT(a_fVal, a_fMask) \
386 do { \
387 if ((a_fVal) & (a_fMask)) \
388 LogRel(("HM: %s\n", #a_fMask)); \
389 } while (0)
390
391
392/*********************************************************************************************************************************
393* Internal Functions *
394*********************************************************************************************************************************/
395static DECLCALLBACK(int) hmR3Save(PVM pVM, PSSMHANDLE pSSM);
396static DECLCALLBACK(int) hmR3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass);
397static DECLCALLBACK(void) hmR3InfoSvmNstGstVmcbCache(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs);
398static DECLCALLBACK(void) hmR3Info(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs);
399static DECLCALLBACK(void) hmR3InfoEventPending(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs);
400static int hmR3InitCPU(PVM pVM);
401static int hmR3InitFinalizeR0(PVM pVM);
402static int hmR3InitFinalizeR0Intel(PVM pVM);
403static int hmR3InitFinalizeR0Amd(PVM pVM);
404static int hmR3TermCPU(PVM pVM);
405
406
407
408/**
409 * Initializes the HM.
410 *
411 * This is the very first component to really do init after CFGM so that we can
412 * establish the predominat execution engine for the VM prior to initializing
413 * other modules. It takes care of NEM initialization if needed (HM disabled or
414 * not available in HW).
415 *
416 * If VT-x or AMD-V hardware isn't available, HM will try fall back on a native
417 * hypervisor API via NEM, and then back on raw-mode if that isn't available
418 * either. The fallback to raw-mode will not happen if /HM/HMForced is set
419 * (like for guest using SMP or 64-bit as well as for complicated guest like OS
420 * X, OS/2 and others).
421 *
422 * Note that a lot of the set up work is done in ring-0 and thus postponed till
423 * the ring-3 and ring-0 callback to HMR3InitCompleted.
424 *
425 * @returns VBox status code.
426 * @param pVM The cross context VM structure.
427 *
428 * @remarks Be careful with what we call here, since most of the VMM components
429 * are uninitialized.
430 */
431VMMR3_INT_DECL(int) HMR3Init(PVM pVM)
432{
433 LogFlow(("HMR3Init\n"));
434
435 /*
436 * Assert alignment and sizes.
437 */
438 AssertCompileMemberAlignment(VM, hm.s, 32);
439 AssertCompile(sizeof(pVM->hm.s) <= sizeof(pVM->hm.padding));
440
441 /*
442 * Register the saved state data unit.
443 */
444 int rc = SSMR3RegisterInternal(pVM, "HWACCM", 0, HM_SAVED_STATE_VERSION, sizeof(HM),
445 NULL, NULL, NULL,
446 NULL, hmR3Save, NULL,
447 NULL, hmR3Load, NULL);
448 if (RT_FAILURE(rc))
449 return rc;
450
451 /*
452 * Register info handlers.
453 */
454 rc = DBGFR3InfoRegisterInternalEx(pVM, "hm", "Dumps HM info.", hmR3Info, DBGFINFO_FLAGS_ALL_EMTS);
455 AssertRCReturn(rc, rc);
456
457 rc = DBGFR3InfoRegisterInternalEx(pVM, "hmeventpending", "Dumps the pending HM event.", hmR3InfoEventPending,
458 DBGFINFO_FLAGS_ALL_EMTS);
459 AssertRCReturn(rc, rc);
460
461 rc = DBGFR3InfoRegisterInternalEx(pVM, "svmvmcbcache", "Dumps the HM SVM nested-guest VMCB cache.",
462 hmR3InfoSvmNstGstVmcbCache, DBGFINFO_FLAGS_ALL_EMTS);
463 AssertRCReturn(rc, rc);
464
465 /*
466 * Read configuration.
467 */
468 PCFGMNODE pCfgHm = CFGMR3GetChild(CFGMR3GetRoot(pVM), "HM/");
469
470 /*
471 * Validate the HM settings.
472 */
473 rc = CFGMR3ValidateConfig(pCfgHm, "/HM/",
474 "HMForced"
475 "|UseNEMInstead"
476 "|FallbackToNEM"
477 "|EnableNestedPaging"
478 "|EnableUX"
479 "|EnableLargePages"
480 "|EnableVPID"
481 "|IBPBOnVMExit"
482 "|IBPBOnVMEntry"
483 "|SpecCtrlByHost"
484 "|TPRPatchingEnabled"
485 "|64bitEnabled"
486 "|Exclusive"
487 "|MaxResumeLoops"
488 "|VmxPleGap"
489 "|VmxPleWindow"
490 "|UseVmxPreemptTimer"
491 "|SvmPauseFilter"
492 "|SvmPauseFilterThreshold"
493 "|SvmVirtVmsaveVmload"
494 "|SvmVGif",
495 "" /* pszValidNodes */, "HM" /* pszWho */, 0 /* uInstance */);
496 if (RT_FAILURE(rc))
497 return rc;
498
499 /** @cfgm{/HM/HMForced, bool, false}
500 * Forces hardware virtualization, no falling back on raw-mode. HM must be
501 * enabled, i.e. /HMEnabled must be true. */
502 bool fHMForced;
503#ifdef VBOX_WITH_RAW_MODE
504 rc = CFGMR3QueryBoolDef(pCfgHm, "HMForced", &fHMForced, false);
505 AssertRCReturn(rc, rc);
506 AssertLogRelMsgReturn(!fHMForced || pVM->fHMEnabled, ("Configuration error: HM forced but not enabled!\n"),
507 VERR_INVALID_PARAMETER);
508# if defined(RT_OS_DARWIN)
509 if (pVM->fHMEnabled)
510 fHMForced = true;
511# endif
512 AssertLogRelMsgReturn(pVM->cCpus == 1 || pVM->fHMEnabled, ("Configuration error: SMP requires HM to be enabled!\n"),
513 VERR_INVALID_PARAMETER);
514 if (pVM->cCpus > 1)
515 fHMForced = true;
516#else /* !VBOX_WITH_RAW_MODE */
517 AssertRelease(pVM->fHMEnabled);
518 fHMForced = true;
519#endif /* !VBOX_WITH_RAW_MODE */
520
521 /** @cfgm{/HM/UseNEMInstead, bool, true}
522 * Don't use HM, use NEM instead. */
523 bool fUseNEMInstead = false;
524 rc = CFGMR3QueryBoolDef(pCfgHm, "UseNEMInstead", &fUseNEMInstead, false);
525 AssertRCReturn(rc, rc);
526 if (fUseNEMInstead && pVM->fHMEnabled)
527 {
528 LogRel(("HM: Setting fHMEnabled to false because fUseNEMInstead is set.\n"));
529 pVM->fHMEnabled = false;
530 }
531
532 /** @cfgm{/HM/FallbackToNEM, bool, true}
533 * Enables fallback on NEM. */
534 bool fFallbackToNEM = true;
535 rc = CFGMR3QueryBoolDef(pCfgHm, "FallbackToNEM", &fFallbackToNEM, true);
536 AssertRCReturn(rc, rc);
537
538 /** @cfgm{/HM/EnableNestedPaging, bool, false}
539 * Enables nested paging (aka extended page tables). */
540 rc = CFGMR3QueryBoolDef(pCfgHm, "EnableNestedPaging", &pVM->hm.s.fAllowNestedPaging, false);
541 AssertRCReturn(rc, rc);
542
543 /** @cfgm{/HM/EnableUX, bool, true}
544 * Enables the VT-x unrestricted execution feature. */
545 rc = CFGMR3QueryBoolDef(pCfgHm, "EnableUX", &pVM->hm.s.vmx.fAllowUnrestricted, true);
546 AssertRCReturn(rc, rc);
547
548 /** @cfgm{/HM/EnableLargePages, bool, false}
549 * Enables using large pages (2 MB) for guest memory, thus saving on (nested)
550 * page table walking and maybe better TLB hit rate in some cases. */
551 rc = CFGMR3QueryBoolDef(pCfgHm, "EnableLargePages", &pVM->hm.s.fLargePages, false);
552 AssertRCReturn(rc, rc);
553
554 /** @cfgm{/HM/EnableVPID, bool, false}
555 * Enables the VT-x VPID feature. */
556 rc = CFGMR3QueryBoolDef(pCfgHm, "EnableVPID", &pVM->hm.s.vmx.fAllowVpid, false);
557 AssertRCReturn(rc, rc);
558
559 /** @cfgm{/HM/TPRPatchingEnabled, bool, false}
560 * Enables TPR patching for 32-bit windows guests with IO-APIC. */
561 rc = CFGMR3QueryBoolDef(pCfgHm, "TPRPatchingEnabled", &pVM->hm.s.fTprPatchingAllowed, false);
562 AssertRCReturn(rc, rc);
563
564 /** @cfgm{/HM/64bitEnabled, bool, 32-bit:false, 64-bit:true}
565 * Enables AMD64 cpu features.
566 * On 32-bit hosts this isn't default and require host CPU support. 64-bit hosts
567 * already have the support. */
568#ifdef VBOX_ENABLE_64_BITS_GUESTS
569 rc = CFGMR3QueryBoolDef(pCfgHm, "64bitEnabled", &pVM->hm.s.fAllow64BitGuests, HC_ARCH_BITS == 64);
570 AssertLogRelRCReturn(rc, rc);
571#else
572 pVM->hm.s.fAllow64BitGuests = false;
573#endif
574
575 /** @cfgm{/HM/VmxPleGap, uint32_t, 0}
576 * The pause-filter exiting gap in TSC ticks. When the number of ticks between
577 * two successive PAUSE instructions exceeds VmxPleGap, the CPU considers the
578 * latest PAUSE instruction to be start of a new PAUSE loop.
579 */
580 rc = CFGMR3QueryU32Def(pCfgHm, "VmxPleGap", &pVM->hm.s.vmx.cPleGapTicks, 0);
581 AssertRCReturn(rc, rc);
582
583 /** @cfgm{/HM/VmxPleWindow, uint32_t, 0}
584 * The pause-filter exiting window in TSC ticks. When the number of ticks
585 * between the current PAUSE instruction and first PAUSE of a loop exceeds
586 * VmxPleWindow, a VM-exit is triggered.
587 *
588 * Setting VmxPleGap and VmxPleGap to 0 disables pause-filter exiting.
589 */
590 rc = CFGMR3QueryU32Def(pCfgHm, "VmxPleWindow", &pVM->hm.s.vmx.cPleWindowTicks, 0);
591 AssertRCReturn(rc, rc);
592
593 /** @cfgm{/HM/SvmPauseFilterCount, uint16_t, 0}
594 * A counter that is decrement each time a PAUSE instruction is executed by the
595 * guest. When the counter is 0, a \#VMEXIT is triggered.
596 *
597 * Setting SvmPauseFilterCount to 0 disables pause-filter exiting.
598 */
599 rc = CFGMR3QueryU16Def(pCfgHm, "SvmPauseFilter", &pVM->hm.s.svm.cPauseFilter, 0);
600 AssertRCReturn(rc, rc);
601
602 /** @cfgm{/HM/SvmPauseFilterThreshold, uint16_t, 0}
603 * The pause filter threshold in ticks. When the elapsed time (in ticks) between
604 * two successive PAUSE instructions exceeds SvmPauseFilterThreshold, the
605 * PauseFilter count is reset to its initial value. However, if PAUSE is
606 * executed PauseFilter times within PauseFilterThreshold ticks, a VM-exit will
607 * be triggered.
608 *
609 * Requires SvmPauseFilterCount to be non-zero for pause-filter threshold to be
610 * activated.
611 */
612 rc = CFGMR3QueryU16Def(pCfgHm, "SvmPauseFilterThreshold", &pVM->hm.s.svm.cPauseFilterThresholdTicks, 0);
613 AssertRCReturn(rc, rc);
614
615 /** @cfgm{/HM/SvmVirtVmsaveVmload, bool, true}
616 * Whether to make use of virtualized VMSAVE/VMLOAD feature of the CPU if it's
617 * available. */
618 rc = CFGMR3QueryBoolDef(pCfgHm, "SvmVirtVmsaveVmload", &pVM->hm.s.svm.fVirtVmsaveVmload, true);
619 AssertRCReturn(rc, rc);
620
621 /** @cfgm{/HM/SvmVGif, bool, true}
622 * Whether to make use of Virtual GIF (Global Interrupt Flag) feature of the CPU
623 * if it's available. */
624 rc = CFGMR3QueryBoolDef(pCfgHm, "SvmVGif", &pVM->hm.s.svm.fVGif, true);
625 AssertRCReturn(rc, rc);
626
627 /** @cfgm{/HM/Exclusive, bool}
628 * Determines the init method for AMD-V and VT-x. If set to true, HM will do a
629 * global init for each host CPU. If false, we do local init each time we wish
630 * to execute guest code.
631 *
632 * On Windows, default is false due to the higher risk of conflicts with other
633 * hypervisors.
634 *
635 * On Mac OS X, this setting is ignored since the code does not handle local
636 * init when it utilizes the OS provided VT-x function, SUPR0EnableVTx().
637 */
638#if defined(RT_OS_DARWIN)
639 pVM->hm.s.fGlobalInit = true;
640#else
641 rc = CFGMR3QueryBoolDef(pCfgHm, "Exclusive", &pVM->hm.s.fGlobalInit,
642# if defined(RT_OS_WINDOWS)
643 false
644# else
645 true
646# endif
647 );
648 AssertLogRelRCReturn(rc, rc);
649#endif
650
651 /** @cfgm{/HM/MaxResumeLoops, uint32_t}
652 * The number of times to resume guest execution before we forcibly return to
653 * ring-3. The return value of RTThreadPreemptIsPendingTrusty in ring-0
654 * determines the default value. */
655 rc = CFGMR3QueryU32Def(pCfgHm, "MaxResumeLoops", &pVM->hm.s.cMaxResumeLoops, 0 /* set by R0 later */);
656 AssertLogRelRCReturn(rc, rc);
657
658 /** @cfgm{/HM/UseVmxPreemptTimer, bool}
659 * Whether to make use of the VMX-preemption timer feature of the CPU if it's
660 * available. */
661 rc = CFGMR3QueryBoolDef(pCfgHm, "UseVmxPreemptTimer", &pVM->hm.s.vmx.fUsePreemptTimer, true);
662 AssertLogRelRCReturn(rc, rc);
663
664 /** @cfgm{/HM/IBPBOnVMExit, bool}
665 * Costly paranoia setting. */
666 rc = CFGMR3QueryBoolDef(pCfgHm, "IBPBOnVMExit", &pVM->hm.s.fIbpbOnVmExit, false);
667 AssertLogRelRCReturn(rc, rc);
668
669 /** @cfgm{/HM/IBPBOnVMEntry, bool}
670 * Costly paranoia setting. */
671 rc = CFGMR3QueryBoolDef(pCfgHm, "IBPBOnVMEntry", &pVM->hm.s.fIbpbOnVmEntry, false);
672 AssertLogRelRCReturn(rc, rc);
673
674 /** @cfgm{/HM/SpecCtrlByHost, bool}
675 * Another expensive paranoia setting. */
676 rc = CFGMR3QueryBoolDef(pCfgHm, "SpecCtrlByHost", &pVM->hm.s.fSpecCtrlByHost, false);
677 AssertLogRelRCReturn(rc, rc);
678
679 /*
680 * Check if VT-x or AMD-v support according to the users wishes.
681 */
682 /** @todo SUPR3QueryVTCaps won't catch VERR_VMX_IN_VMX_ROOT_MODE or
683 * VERR_SVM_IN_USE. */
684 if (pVM->fHMEnabled)
685 {
686 uint32_t fCaps;
687 rc = SUPR3QueryVTCaps(&fCaps);
688 if (RT_SUCCESS(rc))
689 {
690 if (fCaps & SUPVTCAPS_AMD_V)
691 {
692 LogRel(("HM: HMR3Init: AMD-V%s\n", fCaps & SUPVTCAPS_NESTED_PAGING ? " w/ nested paging" : ""));
693 pVM->hm.s.svm.fSupported = true;
694 VM_SET_MAIN_EXECUTION_ENGINE(pVM, VM_EXEC_ENGINE_HW_VIRT);
695 }
696 else if (fCaps & SUPVTCAPS_VT_X)
697 {
698 const char *pszWhy;
699 rc = SUPR3QueryVTxSupported(&pszWhy);
700 if (RT_SUCCESS(rc))
701 {
702 LogRel(("HM: HMR3Init: VT-x%s%s%s\n",
703 fCaps & SUPVTCAPS_NESTED_PAGING ? " w/ nested paging" : "",
704 fCaps & SUPVTCAPS_VTX_UNRESTRICTED_GUEST ? " and unrestricted guest execution" : "",
705 (fCaps & (SUPVTCAPS_NESTED_PAGING | SUPVTCAPS_VTX_UNRESTRICTED_GUEST)) ? " hw support" : ""));
706 pVM->hm.s.vmx.fSupported = true;
707 VM_SET_MAIN_EXECUTION_ENGINE(pVM, VM_EXEC_ENGINE_HW_VIRT);
708 }
709 else
710 {
711 /*
712 * Before failing, try fallback to NEM if we're allowed to do that.
713 */
714 pVM->fHMEnabled = false;
715 Assert(pVM->bMainExecutionEngine == VM_EXEC_ENGINE_NOT_SET);
716 if (fFallbackToNEM)
717 {
718 LogRel(("HM: HMR3Init: Attempting fall back to NEM: The host kernel does not support VT-x - %s\n", pszWhy));
719 int rc2 = NEMR3Init(pVM, true /*fFallback*/, fHMForced);
720
721 ASMCompilerBarrier(); /* NEMR3Init may have changed bMainExecutionEngine. */
722 if ( RT_SUCCESS(rc2)
723 && pVM->bMainExecutionEngine != VM_EXEC_ENGINE_NOT_SET)
724 rc = VINF_SUCCESS;
725 }
726 if (RT_FAILURE(rc))
727 {
728 if (fHMForced)
729 return VMSetError(pVM, rc, RT_SRC_POS, "The host kernel does not support VT-x: %s\n", pszWhy);
730
731 /* Fall back to raw-mode. */
732 LogRel(("HM: HMR3Init: Falling back to raw-mode: The host kernel does not support VT-x - %s\n", pszWhy));
733 VM_SET_MAIN_EXECUTION_ENGINE(pVM, VM_EXEC_ENGINE_RAW_MODE);
734 }
735 }
736 }
737 else
738 AssertLogRelMsgFailedReturn(("SUPR3QueryVTCaps didn't return either AMD-V or VT-x flag set (%#x)!\n", fCaps),
739 VERR_INTERNAL_ERROR_5);
740
741 /*
742 * Do we require a little bit or raw-mode for 64-bit guest execution?
743 */
744 pVM->fHMNeedRawModeCtx = HC_ARCH_BITS == 32
745 && pVM->fHMEnabled
746 && pVM->hm.s.fAllow64BitGuests;
747
748 /*
749 * Disable nested paging and unrestricted guest execution now if they're
750 * configured so that CPUM can make decisions based on our configuration.
751 */
752 Assert(!pVM->hm.s.fNestedPaging);
753 if (pVM->hm.s.fAllowNestedPaging)
754 {
755 if (fCaps & SUPVTCAPS_NESTED_PAGING)
756 pVM->hm.s.fNestedPaging = true;
757 else
758 pVM->hm.s.fAllowNestedPaging = false;
759 }
760
761 if (fCaps & SUPVTCAPS_VT_X)
762 {
763 Assert(!pVM->hm.s.vmx.fUnrestrictedGuest);
764 if (pVM->hm.s.vmx.fAllowUnrestricted)
765 {
766 if ( (fCaps & SUPVTCAPS_VTX_UNRESTRICTED_GUEST)
767 && pVM->hm.s.fNestedPaging)
768 pVM->hm.s.vmx.fUnrestrictedGuest = true;
769 else
770 pVM->hm.s.vmx.fAllowUnrestricted = false;
771 }
772 }
773 }
774 else
775 {
776 const char *pszMsg;
777 switch (rc)
778 {
779 case VERR_UNSUPPORTED_CPU: pszMsg = "Unknown CPU, VT-x or AMD-v features cannot be ascertained"; break;
780 case VERR_VMX_NO_VMX: pszMsg = "VT-x is not available"; break;
781 case VERR_VMX_MSR_VMX_DISABLED: pszMsg = "VT-x is disabled in the BIOS"; break;
782 case VERR_VMX_MSR_ALL_VMX_DISABLED: pszMsg = "VT-x is disabled in the BIOS for all CPU modes"; break;
783 case VERR_VMX_MSR_LOCKING_FAILED: pszMsg = "Failed to enable and lock VT-x features"; break;
784 case VERR_SVM_NO_SVM: pszMsg = "AMD-V is not available"; break;
785 case VERR_SVM_DISABLED: pszMsg = "AMD-V is disabled in the BIOS (or by the host OS)"; break;
786 default:
787 return VMSetError(pVM, rc, RT_SRC_POS, "SUPR3QueryVTCaps failed with %Rrc", rc);
788 }
789
790 /*
791 * Before failing, try fallback to NEM if we're allowed to do that.
792 */
793 pVM->fHMEnabled = false;
794 if (fFallbackToNEM)
795 {
796 LogRel(("HM: HMR3Init: Attempting fall back to NEM: %s\n", pszMsg));
797 int rc2 = NEMR3Init(pVM, true /*fFallback*/, fHMForced);
798 ASMCompilerBarrier(); /* NEMR3Init may have changed bMainExecutionEngine. */
799 if ( RT_SUCCESS(rc2)
800 && pVM->bMainExecutionEngine != VM_EXEC_ENGINE_NOT_SET)
801 rc = VINF_SUCCESS;
802 }
803 if (RT_FAILURE(rc))
804 {
805 if (fHMForced)
806 return VM_SET_ERROR(pVM, rc, pszMsg);
807
808 LogRel(("HM: HMR3Init: Falling back to raw-mode: %s\n", pszMsg));
809 VM_SET_MAIN_EXECUTION_ENGINE(pVM, VM_EXEC_ENGINE_RAW_MODE);
810 }
811 }
812 }
813 else
814 {
815 /*
816 * Disabled HM mean raw-mode, unless NEM is supposed to be used.
817 */
818 if (!fUseNEMInstead)
819 VM_SET_MAIN_EXECUTION_ENGINE(pVM, VM_EXEC_ENGINE_RAW_MODE);
820 else
821 {
822 rc = NEMR3Init(pVM, false /*fFallback*/, true);
823 ASMCompilerBarrier(); /* NEMR3Init may have changed bMainExecutionEngine. */
824 if (RT_FAILURE(rc))
825 return rc;
826 }
827 }
828
829 return VINF_SUCCESS;
830}
831
832
833/**
834 * Initializes the per-VCPU HM.
835 *
836 * @returns VBox status code.
837 * @param pVM The cross context VM structure.
838 */
839static int hmR3InitCPU(PVM pVM)
840{
841 LogFlow(("HMR3InitCPU\n"));
842
843 if (!HMIsEnabled(pVM))
844 return VINF_SUCCESS;
845
846 for (VMCPUID i = 0; i < pVM->cCpus; i++)
847 {
848 PVMCPU pVCpu = &pVM->aCpus[i];
849 pVCpu->hm.s.fActive = false;
850 }
851
852#ifdef VBOX_WITH_STATISTICS
853 STAM_REG(pVM, &pVM->hm.s.StatTprPatchSuccess, STAMTYPE_COUNTER, "/HM/TPR/Patch/Success", STAMUNIT_OCCURENCES, "Number of times an instruction was successfully patched.");
854 STAM_REG(pVM, &pVM->hm.s.StatTprPatchFailure, STAMTYPE_COUNTER, "/HM/TPR/Patch/Failed", STAMUNIT_OCCURENCES, "Number of unsuccessful patch attempts.");
855 STAM_REG(pVM, &pVM->hm.s.StatTprReplaceSuccessCr8, STAMTYPE_COUNTER, "/HM/TPR/Replace/SuccessCR8",STAMUNIT_OCCURENCES, "Number of instruction replacements by MOV CR8.");
856 STAM_REG(pVM, &pVM->hm.s.StatTprReplaceSuccessVmc, STAMTYPE_COUNTER, "/HM/TPR/Replace/SuccessVMC",STAMUNIT_OCCURENCES, "Number of instruction replacements by VMMCALL.");
857 STAM_REG(pVM, &pVM->hm.s.StatTprReplaceFailure, STAMTYPE_COUNTER, "/HM/TPR/Replace/Failed", STAMUNIT_OCCURENCES, "Number of unsuccessful replace attempts.");
858#endif
859
860 /*
861 * Statistics.
862 */
863 for (VMCPUID i = 0; i < pVM->cCpus; i++)
864 {
865 PVMCPU pVCpu = &pVM->aCpus[i];
866 int rc;
867
868#ifdef VBOX_WITH_STATISTICS
869 rc = STAMR3RegisterF(pVM, &pVCpu->hm.s.StatPoke, STAMTYPE_PROFILE, STAMVISIBILITY_USED, STAMUNIT_TICKS_PER_CALL,
870 "Profiling of RTMpPokeCpu.",
871 "/PROF/CPU%d/HM/Poke", i);
872 AssertRC(rc);
873 rc = STAMR3RegisterF(pVM, &pVCpu->hm.s.StatSpinPoke, STAMTYPE_PROFILE, STAMVISIBILITY_USED, STAMUNIT_TICKS_PER_CALL,
874 "Profiling of poke wait.",
875 "/PROF/CPU%d/HM/PokeWait", i);
876 AssertRC(rc);
877 rc = STAMR3RegisterF(pVM, &pVCpu->hm.s.StatSpinPokeFailed, STAMTYPE_PROFILE, STAMVISIBILITY_USED, STAMUNIT_TICKS_PER_CALL,
878 "Profiling of poke wait when RTMpPokeCpu fails.",
879 "/PROF/CPU%d/HM/PokeWaitFailed", i);
880 AssertRC(rc);
881 rc = STAMR3RegisterF(pVM, &pVCpu->hm.s.StatEntry, STAMTYPE_PROFILE, STAMVISIBILITY_USED, STAMUNIT_TICKS_PER_CALL,
882 "Profiling of entry until entering GC.",
883 "/PROF/CPU%d/HM/Entry", i);
884 AssertRC(rc);
885 rc = STAMR3RegisterF(pVM, &pVCpu->hm.s.StatPreExit, STAMTYPE_PROFILE, STAMVISIBILITY_USED, STAMUNIT_TICKS_PER_CALL,
886 "Profiling of pre-exit processing after returning from GC.",
887 "/PROF/CPU%d/HM/SwitchFromGC_1", i);
888 AssertRC(rc);
889 rc = STAMR3RegisterF(pVM, &pVCpu->hm.s.StatExitHandling, STAMTYPE_PROFILE, STAMVISIBILITY_USED, STAMUNIT_TICKS_PER_CALL,
890 "Profiling of exit handling (longjmps not included!)",
891 "/PROF/CPU%d/HM/SwitchFromGC_2", i);
892 AssertRC(rc);
893
894 rc = STAMR3RegisterF(pVM, &pVCpu->hm.s.StatExitIO, STAMTYPE_PROFILE, STAMVISIBILITY_USED, STAMUNIT_TICKS_PER_CALL,
895 "I/O.",
896 "/PROF/CPU%d/HM/SwitchFromGC_2/IO", i);
897 AssertRC(rc);
898 rc = STAMR3RegisterF(pVM, &pVCpu->hm.s.StatExitMovCRx, STAMTYPE_PROFILE, STAMVISIBILITY_USED, STAMUNIT_TICKS_PER_CALL,
899 "MOV CRx.",
900 "/PROF/CPU%d/HM/SwitchFromGC_2/MovCRx", i);
901 AssertRC(rc);
902 rc = STAMR3RegisterF(pVM, &pVCpu->hm.s.StatExitXcptNmi, STAMTYPE_PROFILE, STAMVISIBILITY_USED, STAMUNIT_TICKS_PER_CALL,
903 "Exceptions, NMIs.",
904 "/PROF/CPU%d/HM/SwitchFromGC_2/XcptNmi", i);
905 AssertRC(rc);
906
907 rc = STAMR3RegisterF(pVM, &pVCpu->hm.s.StatImportGuestState, STAMTYPE_PROFILE, STAMVISIBILITY_USED, STAMUNIT_TICKS_PER_CALL,
908 "Profiling of importing guest state from hardware after VM-exit.",
909 "/PROF/CPU%d/HM/ImportGuestState", i);
910 AssertRC(rc);
911 rc = STAMR3RegisterF(pVM, &pVCpu->hm.s.StatExportGuestState, STAMTYPE_PROFILE, STAMVISIBILITY_USED, STAMUNIT_TICKS_PER_CALL,
912 "Profiling of exporting guest state to hardware before VM-entry.",
913 "/PROF/CPU%d/HM/ExportGuestState", i);
914 AssertRC(rc);
915 rc = STAMR3RegisterF(pVM, &pVCpu->hm.s.StatLoadGuestFpuState, STAMTYPE_PROFILE, STAMVISIBILITY_USED, STAMUNIT_TICKS_PER_CALL,
916 "Profiling of CPUMR0LoadGuestFPU.",
917 "/PROF/CPU%d/HM/LoadGuestFpuState", i);
918 AssertRC(rc);
919 rc = STAMR3RegisterF(pVM, &pVCpu->hm.s.StatInGC, STAMTYPE_PROFILE, STAMVISIBILITY_USED, STAMUNIT_TICKS_PER_CALL,
920 "Profiling of execution of guest-code in hardware.",
921 "/PROF/CPU%d/HM/InGC", i);
922 AssertRC(rc);
923
924# if HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS)
925 rc = STAMR3RegisterF(pVM, &pVCpu->hm.s.StatWorldSwitch3264, STAMTYPE_PROFILE, STAMVISIBILITY_USED,
926 STAMUNIT_TICKS_PER_CALL, "Profiling of the 32/64 switcher.",
927 "/PROF/CPU%d/HM/Switcher3264", i);
928 AssertRC(rc);
929# endif
930
931# ifdef HM_PROFILE_EXIT_DISPATCH
932 rc = STAMR3RegisterF(pVM, &pVCpu->hm.s.StatExitDispatch, STAMTYPE_PROFILE_ADV, STAMVISIBILITY_USED,
933 STAMUNIT_TICKS_PER_CALL, "Profiling the dispatching of exit handlers.",
934 "/PROF/CPU%d/HM/ExitDispatch", i);
935 AssertRC(rc);
936# endif
937
938#endif
939# define HM_REG_COUNTER(a, b, desc) \
940 rc = STAMR3RegisterF(pVM, a, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, desc, b, i); \
941 AssertRC(rc);
942
943#ifdef VBOX_WITH_STATISTICS
944 HM_REG_COUNTER(&pVCpu->hm.s.StatExitAll, "/HM/CPU%d/Exit/All", "Exits (total).");
945 HM_REG_COUNTER(&pVCpu->hm.s.StatExitShadowNM, "/HM/CPU%d/Exit/Trap/Shw/#NM", "Shadow #NM (device not available, no math co-processor) exception.");
946 HM_REG_COUNTER(&pVCpu->hm.s.StatExitGuestNM, "/HM/CPU%d/Exit/Trap/Gst/#NM", "Guest #NM (device not available, no math co-processor) exception.");
947 HM_REG_COUNTER(&pVCpu->hm.s.StatExitShadowPF, "/HM/CPU%d/Exit/Trap/Shw/#PF", "Shadow #PF (page fault) exception.");
948 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.");
949 HM_REG_COUNTER(&pVCpu->hm.s.StatExitGuestPF, "/HM/CPU%d/Exit/Trap/Gst/#PF", "Guest #PF (page fault) exception.");
950 HM_REG_COUNTER(&pVCpu->hm.s.StatExitGuestUD, "/HM/CPU%d/Exit/Trap/Gst/#UD", "Guest #UD (undefined opcode) exception.");
951 HM_REG_COUNTER(&pVCpu->hm.s.StatExitGuestSS, "/HM/CPU%d/Exit/Trap/Gst/#SS", "Guest #SS (stack-segment fault) exception.");
952 HM_REG_COUNTER(&pVCpu->hm.s.StatExitGuestNP, "/HM/CPU%d/Exit/Trap/Gst/#NP", "Guest #NP (segment not present) exception.");
953 HM_REG_COUNTER(&pVCpu->hm.s.StatExitGuestGP, "/HM/CPU%d/Exit/Trap/Gst/#GP", "Guest #GP (general protection) exception.");
954 HM_REG_COUNTER(&pVCpu->hm.s.StatExitGuestMF, "/HM/CPU%d/Exit/Trap/Gst/#MF", "Guest #MF (x87 FPU error, math fault) exception.");
955 HM_REG_COUNTER(&pVCpu->hm.s.StatExitGuestDE, "/HM/CPU%d/Exit/Trap/Gst/#DE", "Guest #DE (divide error) exception.");
956 HM_REG_COUNTER(&pVCpu->hm.s.StatExitGuestDB, "/HM/CPU%d/Exit/Trap/Gst/#DB", "Guest #DB (debug) exception.");
957 HM_REG_COUNTER(&pVCpu->hm.s.StatExitGuestBP, "/HM/CPU%d/Exit/Trap/Gst/#BP", "Guest #BP (breakpoint) exception.");
958 HM_REG_COUNTER(&pVCpu->hm.s.StatExitGuestXF, "/HM/CPU%d/Exit/Trap/Gst/#XF", "Guest #XF (extended math fault, SIMD FPU) exception.");
959 HM_REG_COUNTER(&pVCpu->hm.s.StatExitGuestXcpUnk, "/HM/CPU%d/Exit/Trap/Gst/Other", "Other guest exceptions.");
960 HM_REG_COUNTER(&pVCpu->hm.s.StatExitHlt, "/HM/CPU%d/Exit/Instr/Hlt", "HLT instruction.");
961 HM_REG_COUNTER(&pVCpu->hm.s.StatExitRdmsr, "/HM/CPU%d/Exit/Instr/Rdmsr", "RDMSR instruction.");
962 HM_REG_COUNTER(&pVCpu->hm.s.StatExitWrmsr, "/HM/CPU%d/Exit/Instr/Wrmsr", "WRMSR instruction.");
963 HM_REG_COUNTER(&pVCpu->hm.s.StatExitMwait, "/HM/CPU%d/Exit/Instr/Mwait", "MWAIT instruction.");
964 HM_REG_COUNTER(&pVCpu->hm.s.StatExitMonitor, "/HM/CPU%d/Exit/Instr/Monitor", "MONITOR instruction.");
965 HM_REG_COUNTER(&pVCpu->hm.s.StatExitDRxWrite, "/HM/CPU%d/Exit/Instr/DR-Write", "Debug register write.");
966 HM_REG_COUNTER(&pVCpu->hm.s.StatExitDRxRead, "/HM/CPU%d/Exit/Instr/DR-Read", "Debug register read.");
967 HM_REG_COUNTER(&pVCpu->hm.s.StatExitCR0Read, "/HM/CPU%d/Exit/Instr/CR-Read/CR0", "CR0 read.");
968 HM_REG_COUNTER(&pVCpu->hm.s.StatExitCR2Read, "/HM/CPU%d/Exit/Instr/CR-Read/CR2", "CR2 read.");
969 HM_REG_COUNTER(&pVCpu->hm.s.StatExitCR3Read, "/HM/CPU%d/Exit/Instr/CR-Read/CR3", "CR3 read.");
970 HM_REG_COUNTER(&pVCpu->hm.s.StatExitCR4Read, "/HM/CPU%d/Exit/Instr/CR-Read/CR4", "CR4 read.");
971 HM_REG_COUNTER(&pVCpu->hm.s.StatExitCR8Read, "/HM/CPU%d/Exit/Instr/CR-Read/CR8", "CR8 read.");
972 HM_REG_COUNTER(&pVCpu->hm.s.StatExitCR0Write, "/HM/CPU%d/Exit/Instr/CR-Write/CR0", "CR0 write.");
973 HM_REG_COUNTER(&pVCpu->hm.s.StatExitCR2Write, "/HM/CPU%d/Exit/Instr/CR-Write/CR2", "CR2 write.");
974 HM_REG_COUNTER(&pVCpu->hm.s.StatExitCR3Write, "/HM/CPU%d/Exit/Instr/CR-Write/CR3", "CR3 write.");
975 HM_REG_COUNTER(&pVCpu->hm.s.StatExitCR4Write, "/HM/CPU%d/Exit/Instr/CR-Write/CR4", "CR4 write.");
976 HM_REG_COUNTER(&pVCpu->hm.s.StatExitCR8Write, "/HM/CPU%d/Exit/Instr/CR-Write/CR8", "CR8 write.");
977 HM_REG_COUNTER(&pVCpu->hm.s.StatExitClts, "/HM/CPU%d/Exit/Instr/CLTS", "CLTS instruction.");
978 HM_REG_COUNTER(&pVCpu->hm.s.StatExitLmsw, "/HM/CPU%d/Exit/Instr/LMSW", "LMSW instruction.");
979 HM_REG_COUNTER(&pVCpu->hm.s.StatExitCli, "/HM/CPU%d/Exit/Instr/Cli", "CLI instruction.");
980 HM_REG_COUNTER(&pVCpu->hm.s.StatExitSti, "/HM/CPU%d/Exit/Instr/Sti", "STI instruction.");
981 HM_REG_COUNTER(&pVCpu->hm.s.StatExitPushf, "/HM/CPU%d/Exit/Instr/Pushf", "PUSHF instruction.");
982 HM_REG_COUNTER(&pVCpu->hm.s.StatExitPopf, "/HM/CPU%d/Exit/Instr/Popf", "POPF instruction.");
983 HM_REG_COUNTER(&pVCpu->hm.s.StatExitIret, "/HM/CPU%d/Exit/Instr/Iret", "IRET instruction.");
984 HM_REG_COUNTER(&pVCpu->hm.s.StatExitInt, "/HM/CPU%d/Exit/Instr/Int", "INT instruction.");
985 HM_REG_COUNTER(&pVCpu->hm.s.StatExitXdtrAccess, "/HM/CPU%d/Exit/Instr/XdtrAccess", "GDTR, IDTR, LDTR access.");
986 HM_REG_COUNTER(&pVCpu->hm.s.StatExitIOWrite, "/HM/CPU%d/Exit/IO/Write", "I/O write.");
987 HM_REG_COUNTER(&pVCpu->hm.s.StatExitIORead, "/HM/CPU%d/Exit/IO/Read", "I/O read.");
988 HM_REG_COUNTER(&pVCpu->hm.s.StatExitIOStringWrite, "/HM/CPU%d/Exit/IO/WriteString", "String I/O write.");
989 HM_REG_COUNTER(&pVCpu->hm.s.StatExitIOStringRead, "/HM/CPU%d/Exit/IO/ReadString", "String I/O read.");
990 HM_REG_COUNTER(&pVCpu->hm.s.StatExitIntWindow, "/HM/CPU%d/Exit/IntWindow", "Interrupt-window exit. Guest is ready to receive interrupts again.");
991 HM_REG_COUNTER(&pVCpu->hm.s.StatExitExtInt, "/HM/CPU%d/Exit/ExtInt", "Physical maskable interrupt (host).");
992#endif
993 HM_REG_COUNTER(&pVCpu->hm.s.StatExitHostNmiInGC, "/HM/CPU%d/Exit/HostNmiInGC", "Host NMI received while in guest context.");
994#ifdef VBOX_WITH_STATISTICS
995 HM_REG_COUNTER(&pVCpu->hm.s.StatExitPreemptTimer, "/HM/CPU%d/Exit/PreemptTimer", "VMX-preemption timer expired.");
996 HM_REG_COUNTER(&pVCpu->hm.s.StatExitTprBelowThreshold, "/HM/CPU%d/Exit/TprBelowThreshold", "TPR lowered below threshold by the guest.");
997 HM_REG_COUNTER(&pVCpu->hm.s.StatExitTaskSwitch, "/HM/CPU%d/Exit/TaskSwitch", "Task switch.");
998 HM_REG_COUNTER(&pVCpu->hm.s.StatExitMtf, "/HM/CPU%d/Exit/MonitorTrapFlag", "Monitor Trap Flag.");
999 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.");
1000
1001 HM_REG_COUNTER(&pVCpu->hm.s.StatSwitchTprMaskedIrq, "/HM/CPU%d/Switch/TprMaskedIrq", "PDMGetInterrupt() signals TPR masks pending Irq.");
1002 HM_REG_COUNTER(&pVCpu->hm.s.StatSwitchGuestIrq, "/HM/CPU%d/Switch/IrqPending", "PDMGetInterrupt() cleared behind our back!?!.");
1003 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.");
1004 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.");
1005 HM_REG_COUNTER(&pVCpu->hm.s.StatSwitchExitToR3, "/HM/CPU%d/Switch/ExitToR3", "Exit to ring-3 (total).");
1006 HM_REG_COUNTER(&pVCpu->hm.s.StatSwitchLongJmpToR3, "/HM/CPU%d/Switch/LongJmpToR3", "Longjump to ring-3.");
1007 HM_REG_COUNTER(&pVCpu->hm.s.StatSwitchMaxResumeLoops, "/HM/CPU%d/Switch/MaxResumeToR3", "Maximum VMRESUME inner-loop counter reached.");
1008 HM_REG_COUNTER(&pVCpu->hm.s.StatSwitchHltToR3, "/HM/CPU%d/Switch/HltToR3", "HLT causing us to go to ring-3.");
1009 HM_REG_COUNTER(&pVCpu->hm.s.StatSwitchApicAccessToR3, "/HM/CPU%d/Switch/ApicAccessToR3", "APIC access causing us to go to ring-3.");
1010#endif
1011 HM_REG_COUNTER(&pVCpu->hm.s.StatSwitchPreempt, "/HM/CPU%d/Switch/Preempting", "EMT has been preempted while in HM context.");
1012#ifdef VBOX_WITH_STATISTICS
1013 HM_REG_COUNTER(&pVCpu->hm.s.StatSwitchPreemptExportHostState, "/HM/CPU%d/Switch/ExportHostState", "Preemption caused us to re-export the host state.");
1014
1015 HM_REG_COUNTER(&pVCpu->hm.s.StatInjectInterrupt, "/HM/CPU%d/EventInject/Interrupt", "Injected an external interrupt into the guest.");
1016 HM_REG_COUNTER(&pVCpu->hm.s.StatInjectXcpt, "/HM/CPU%d/EventInject/Trap", "Injected an exception into the guest.");
1017 HM_REG_COUNTER(&pVCpu->hm.s.StatInjectPendingReflect, "/HM/CPU%d/EventInject/PendingReflect", "Reflecting an exception (or #DF) caused due to event injection.");
1018 HM_REG_COUNTER(&pVCpu->hm.s.StatInjectPendingInterpret, "/HM/CPU%d/EventInject/PendingInterpret", "Falling to interpreter for handling exception caused due to event injection.");
1019
1020 HM_REG_COUNTER(&pVCpu->hm.s.StatFlushPage, "/HM/CPU%d/Flush/Page", "Invalidating a guest page on all guest CPUs.");
1021 HM_REG_COUNTER(&pVCpu->hm.s.StatFlushPageManual, "/HM/CPU%d/Flush/Page/Virt", "Invalidating a guest page using guest-virtual address.");
1022 HM_REG_COUNTER(&pVCpu->hm.s.StatFlushPhysPageManual, "/HM/CPU%d/Flush/Page/Phys", "Invalidating a guest page using guest-physical address.");
1023 HM_REG_COUNTER(&pVCpu->hm.s.StatFlushTlb, "/HM/CPU%d/Flush/TLB", "Forcing a full guest-TLB flush (ring-0).");
1024 HM_REG_COUNTER(&pVCpu->hm.s.StatFlushTlbManual, "/HM/CPU%d/Flush/TLB/Manual", "Request a full guest-TLB flush.");
1025 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.");
1026 HM_REG_COUNTER(&pVCpu->hm.s.StatNoFlushTlbWorldSwitch, "/HM/CPU%d/Flush/TLB/Skipped", "No TLB flushing required.");
1027 HM_REG_COUNTER(&pVCpu->hm.s.StatFlushEntire, "/HM/CPU%d/Flush/TLB/Entire", "Flush the entire TLB (host + guest).");
1028 HM_REG_COUNTER(&pVCpu->hm.s.StatFlushAsid, "/HM/CPU%d/Flush/TLB/ASID", "Flushed guest-TLB entries for the current VPID.");
1029 HM_REG_COUNTER(&pVCpu->hm.s.StatFlushNestedPaging, "/HM/CPU%d/Flush/TLB/NestedPaging", "Flushed guest-TLB entries for the current EPT.");
1030 HM_REG_COUNTER(&pVCpu->hm.s.StatFlushTlbInvlpgVirt, "/HM/CPU%d/Flush/TLB/InvlpgVirt", "Invalidated a guest-TLB entry for a guest-virtual address.");
1031 HM_REG_COUNTER(&pVCpu->hm.s.StatFlushTlbInvlpgPhys, "/HM/CPU%d/Flush/TLB/InvlpgPhys", "Currently not possible, flushes entire guest-TLB.");
1032 HM_REG_COUNTER(&pVCpu->hm.s.StatTlbShootdown, "/HM/CPU%d/Flush/Shootdown/Page", "Inter-VCPU request to flush queued guest page.");
1033 HM_REG_COUNTER(&pVCpu->hm.s.StatTlbShootdownFlush, "/HM/CPU%d/Flush/Shootdown/TLB", "Inter-VCPU request to flush entire guest-TLB.");
1034
1035 HM_REG_COUNTER(&pVCpu->hm.s.StatTscParavirt, "/HM/CPU%d/TSC/Paravirt", "Paravirtualized TSC in effect.");
1036 HM_REG_COUNTER(&pVCpu->hm.s.StatTscOffset, "/HM/CPU%d/TSC/Offset", "TSC offsetting is in effect.");
1037 HM_REG_COUNTER(&pVCpu->hm.s.StatTscIntercept, "/HM/CPU%d/TSC/Intercept", "Intercept TSC accesses.");
1038
1039 HM_REG_COUNTER(&pVCpu->hm.s.StatDRxArmed, "/HM/CPU%d/Debug/Armed", "Loaded guest-debug state while loading guest-state.");
1040 HM_REG_COUNTER(&pVCpu->hm.s.StatDRxContextSwitch, "/HM/CPU%d/Debug/ContextSwitch", "Loaded guest-debug state on MOV DRx.");
1041 HM_REG_COUNTER(&pVCpu->hm.s.StatDRxIoCheck, "/HM/CPU%d/Debug/IOCheck", "Checking for I/O breakpoint.");
1042
1043 HM_REG_COUNTER(&pVCpu->hm.s.StatExportMinimal, "/HM/CPU%d/Export/Minimal", "VM-entry exporting minimal guest-state.");
1044 HM_REG_COUNTER(&pVCpu->hm.s.StatExportFull, "/HM/CPU%d/Export/Full", "VM-entry exporting the full guest-state.");
1045 HM_REG_COUNTER(&pVCpu->hm.s.StatLoadGuestFpu, "/HM/CPU%d/Export/GuestFpu", "VM-entry loading the guest-FPU state.");
1046
1047 HM_REG_COUNTER(&pVCpu->hm.s.StatVmxCheckBadRmSelBase, "/HM/CPU%d/VMXCheck/RMSelBase", "Could not use VMX due to unsuitable real-mode selector base.");
1048 HM_REG_COUNTER(&pVCpu->hm.s.StatVmxCheckBadRmSelLimit, "/HM/CPU%d/VMXCheck/RMSelLimit", "Could not use VMX due to unsuitable real-mode selector limit.");
1049 HM_REG_COUNTER(&pVCpu->hm.s.StatVmxCheckRmOk, "/HM/CPU%d/VMXCheck/VMX_RM", "VMX execution in real (V86) mode OK.");
1050 HM_REG_COUNTER(&pVCpu->hm.s.StatVmxCheckBadSel, "/HM/CPU%d/VMXCheck/Selector", "Could not use VMX due to unsuitable selector.");
1051 HM_REG_COUNTER(&pVCpu->hm.s.StatVmxCheckBadRpl, "/HM/CPU%d/VMXCheck/RPL", "Could not use VMX due to unsuitable RPL.");
1052 HM_REG_COUNTER(&pVCpu->hm.s.StatVmxCheckBadLdt, "/HM/CPU%d/VMXCheck/LDT", "Could not use VMX due to unsuitable LDT.");
1053 HM_REG_COUNTER(&pVCpu->hm.s.StatVmxCheckBadTr, "/HM/CPU%d/VMXCheck/TR", "Could not use VMX due to unsuitable TR.");
1054 HM_REG_COUNTER(&pVCpu->hm.s.StatVmxCheckPmOk, "/HM/CPU%d/VMXCheck/VMX_PM", "VMX execution in protected mode OK.");
1055
1056#if HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS)
1057 HM_REG_COUNTER(&pVCpu->hm.s.StatFpu64SwitchBack, "/HM/CPU%d/Switch64/Fpu", "Saving guest FPU/XMM state.");
1058 HM_REG_COUNTER(&pVCpu->hm.s.StatDebug64SwitchBack, "/HM/CPU%d/Switch64/Debug", "Saving guest debug state.");
1059#endif
1060
1061#undef HM_REG_COUNTER
1062
1063 const char *const *papszDesc = ASMIsIntelCpu() || ASMIsViaCentaurCpu() ? &g_apszVTxExitReasons[0]
1064 : &g_apszAmdVExitReasons[0];
1065
1066 /*
1067 * Guest Exit reason stats.
1068 */
1069 pVCpu->hm.s.paStatExitReason = NULL;
1070 rc = MMHyperAlloc(pVM, MAX_EXITREASON_STAT * sizeof(*pVCpu->hm.s.paStatExitReason), 0 /* uAlignment */, MM_TAG_HM,
1071 (void **)&pVCpu->hm.s.paStatExitReason);
1072 AssertRCReturn(rc, rc);
1073 for (int j = 0; j < MAX_EXITREASON_STAT; j++)
1074 {
1075 if (papszDesc[j])
1076 {
1077 rc = STAMR3RegisterF(pVM, &pVCpu->hm.s.paStatExitReason[j], STAMTYPE_COUNTER, STAMVISIBILITY_USED,
1078 STAMUNIT_OCCURENCES, papszDesc[j], "/HM/CPU%d/Exit/Reason/%02x", i, j);
1079 AssertRCReturn(rc, rc);
1080 }
1081 }
1082 rc = STAMR3RegisterF(pVM, &pVCpu->hm.s.StatExitReasonNpf, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_OCCURENCES,
1083 "Nested page fault", "/HM/CPU%d/Exit/Reason/#NPF", i);
1084 AssertRCReturn(rc, rc);
1085 pVCpu->hm.s.paStatExitReasonR0 = MMHyperR3ToR0(pVM, pVCpu->hm.s.paStatExitReason);
1086# ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
1087 Assert(pVCpu->hm.s.paStatExitReasonR0 != NIL_RTR0PTR || !HMIsEnabled(pVM));
1088# else
1089 Assert(pVCpu->hm.s.paStatExitReasonR0 != NIL_RTR0PTR);
1090# endif
1091
1092#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
1093 /*
1094 * Nested-guest Exit reason stats.
1095 */
1096 pVCpu->hm.s.paStatNestedExitReason = NULL;
1097 rc = MMHyperAlloc(pVM, MAX_EXITREASON_STAT * sizeof(*pVCpu->hm.s.paStatNestedExitReason), 0 /* uAlignment */, MM_TAG_HM,
1098 (void **)&pVCpu->hm.s.paStatNestedExitReason);
1099 AssertRCReturn(rc, rc);
1100 for (int j = 0; j < MAX_EXITREASON_STAT; j++)
1101 {
1102 if (papszDesc[j])
1103 {
1104 rc = STAMR3RegisterF(pVM, &pVCpu->hm.s.paStatNestedExitReason[j], STAMTYPE_COUNTER, STAMVISIBILITY_USED,
1105 STAMUNIT_OCCURENCES, papszDesc[j], "/HM/CPU%d/NestedExit/Reason/%02x", i, j);
1106 AssertRC(rc);
1107 }
1108 }
1109 rc = STAMR3RegisterF(pVM, &pVCpu->hm.s.StatNestedExitReasonNpf, STAMTYPE_COUNTER, STAMVISIBILITY_USED,
1110 STAMUNIT_OCCURENCES, "Nested page fault", "/HM/CPU%d/NestedExit/Reason/#NPF", i);
1111 AssertRCReturn(rc, rc);
1112 pVCpu->hm.s.paStatNestedExitReasonR0 = MMHyperR3ToR0(pVM, pVCpu->hm.s.paStatNestedExitReason);
1113# ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
1114 Assert(pVCpu->hm.s.paStatNestedExitReasonR0 != NIL_RTR0PTR || !HMIsEnabled(pVM));
1115# else
1116 Assert(pVCpu->hm.s.paStatNestedExitReasonR0 != NIL_RTR0PTR);
1117# endif
1118#endif
1119
1120 /*
1121 * Injected events stats.
1122 */
1123 rc = MMHyperAlloc(pVM, sizeof(STAMCOUNTER) * 256, 8, MM_TAG_HM, (void **)&pVCpu->hm.s.paStatInjectedIrqs);
1124 AssertRCReturn(rc, rc);
1125 pVCpu->hm.s.paStatInjectedIrqsR0 = MMHyperR3ToR0(pVM, pVCpu->hm.s.paStatInjectedIrqs);
1126# ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
1127 Assert(pVCpu->hm.s.paStatInjectedIrqsR0 != NIL_RTR0PTR || !HMIsEnabled(pVM));
1128# else
1129 Assert(pVCpu->hm.s.paStatInjectedIrqsR0 != NIL_RTR0PTR);
1130# endif
1131 for (unsigned j = 0; j < 255; j++)
1132 {
1133 STAMR3RegisterF(pVM, &pVCpu->hm.s.paStatInjectedIrqs[j], STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_OCCURENCES,
1134 "Injected event.",
1135 (j < 0x20) ? "/HM/CPU%d/EventInject/InjectTrap/%02X" : "/HM/CPU%d/EventInject/InjectIRQ/%02X", i, j);
1136 }
1137
1138#endif /* VBOX_WITH_STATISTICS */
1139 }
1140
1141#ifdef VBOX_WITH_CRASHDUMP_MAGIC
1142 /*
1143 * Magic marker for searching in crash dumps.
1144 */
1145 for (VMCPUID i = 0; i < pVM->cCpus; i++)
1146 {
1147 PVMCPU pVCpu = &pVM->aCpus[i];
1148
1149 PVMCSCACHE pCache = &pVCpu->hm.s.vmx.VMCSCache;
1150 strcpy((char *)pCache->aMagic, "VMCSCACHE Magic");
1151 pCache->uMagic = UINT64_C(0xDEADBEEFDEADBEEF);
1152 }
1153#endif
1154
1155 return VINF_SUCCESS;
1156}
1157
1158
1159/**
1160 * Called when a init phase has completed.
1161 *
1162 * @returns VBox status code.
1163 * @param pVM The cross context VM structure.
1164 * @param enmWhat The phase that completed.
1165 */
1166VMMR3_INT_DECL(int) HMR3InitCompleted(PVM pVM, VMINITCOMPLETED enmWhat)
1167{
1168 switch (enmWhat)
1169 {
1170 case VMINITCOMPLETED_RING3:
1171 return hmR3InitCPU(pVM);
1172 case VMINITCOMPLETED_RING0:
1173 return hmR3InitFinalizeR0(pVM);
1174 default:
1175 return VINF_SUCCESS;
1176 }
1177}
1178
1179
1180/**
1181 * Turns off normal raw mode features.
1182 *
1183 * @param pVM The cross context VM structure.
1184 */
1185static void hmR3DisableRawMode(PVM pVM)
1186{
1187/** @todo r=bird: HM shouldn't be doing this crap. */
1188 /* Reinit the paging mode to force the new shadow mode. */
1189 for (VMCPUID i = 0; i < pVM->cCpus; i++)
1190 {
1191 PVMCPU pVCpu = &pVM->aCpus[i];
1192 PGMHCChangeMode(pVM, pVCpu, PGMMODE_REAL);
1193 }
1194}
1195
1196
1197/**
1198 * Initialize VT-x or AMD-V.
1199 *
1200 * @returns VBox status code.
1201 * @param pVM The cross context VM structure.
1202 */
1203static int hmR3InitFinalizeR0(PVM pVM)
1204{
1205 int rc;
1206
1207 if (!HMIsEnabled(pVM))
1208 return VINF_SUCCESS;
1209
1210 /*
1211 * Hack to allow users to work around broken BIOSes that incorrectly set
1212 * EFER.SVME, which makes us believe somebody else is already using AMD-V.
1213 */
1214 if ( !pVM->hm.s.vmx.fSupported
1215 && !pVM->hm.s.svm.fSupported
1216 && pVM->hm.s.rcInit == VERR_SVM_IN_USE /* implies functional AMD-V */
1217 && RTEnvExist("VBOX_HWVIRTEX_IGNORE_SVM_IN_USE"))
1218 {
1219 LogRel(("HM: VBOX_HWVIRTEX_IGNORE_SVM_IN_USE active!\n"));
1220 pVM->hm.s.svm.fSupported = true;
1221 pVM->hm.s.svm.fIgnoreInUseError = true;
1222 pVM->hm.s.rcInit = VINF_SUCCESS;
1223 }
1224
1225 /*
1226 * Report ring-0 init errors.
1227 */
1228 if ( !pVM->hm.s.vmx.fSupported
1229 && !pVM->hm.s.svm.fSupported)
1230 {
1231 LogRel(("HM: Failed to initialize VT-x / AMD-V: %Rrc\n", pVM->hm.s.rcInit));
1232 LogRel(("HM: VMX MSR_IA32_FEATURE_CONTROL=%RX64\n", pVM->hm.s.vmx.Msrs.u64FeatureCtrl));
1233 switch (pVM->hm.s.rcInit)
1234 {
1235 case VERR_VMX_IN_VMX_ROOT_MODE:
1236 return VM_SET_ERROR(pVM, VERR_VMX_IN_VMX_ROOT_MODE, "VT-x is being used by another hypervisor");
1237 case VERR_VMX_NO_VMX:
1238 return VM_SET_ERROR(pVM, VERR_VMX_NO_VMX, "VT-x is not available");
1239 case VERR_VMX_MSR_VMX_DISABLED:
1240 return VM_SET_ERROR(pVM, VERR_VMX_MSR_VMX_DISABLED, "VT-x is disabled in the BIOS");
1241 case VERR_VMX_MSR_ALL_VMX_DISABLED:
1242 return VM_SET_ERROR(pVM, VERR_VMX_MSR_ALL_VMX_DISABLED, "VT-x is disabled in the BIOS for all CPU modes");
1243 case VERR_VMX_MSR_LOCKING_FAILED:
1244 return VM_SET_ERROR(pVM, VERR_VMX_MSR_LOCKING_FAILED, "Failed to lock VT-x features while trying to enable VT-x");
1245 case VERR_VMX_MSR_VMX_ENABLE_FAILED:
1246 return VM_SET_ERROR(pVM, VERR_VMX_MSR_VMX_ENABLE_FAILED, "Failed to enable VT-x features");
1247 case VERR_VMX_MSR_SMX_VMX_ENABLE_FAILED:
1248 return VM_SET_ERROR(pVM, VERR_VMX_MSR_SMX_VMX_ENABLE_FAILED, "Failed to enable VT-x features in SMX mode");
1249
1250 case VERR_SVM_IN_USE:
1251 return VM_SET_ERROR(pVM, VERR_SVM_IN_USE, "AMD-V is being used by another hypervisor");
1252 case VERR_SVM_NO_SVM:
1253 return VM_SET_ERROR(pVM, VERR_SVM_NO_SVM, "AMD-V is not available");
1254 case VERR_SVM_DISABLED:
1255 return VM_SET_ERROR(pVM, VERR_SVM_DISABLED, "AMD-V is disabled in the BIOS");
1256 }
1257 return VMSetError(pVM, pVM->hm.s.rcInit, RT_SRC_POS, "HM ring-0 init failed: %Rrc", pVM->hm.s.rcInit);
1258 }
1259
1260 /*
1261 * Enable VT-x or AMD-V on all host CPUs.
1262 */
1263 rc = SUPR3CallVMMR0Ex(pVM->pVMR0, 0 /*idCpu*/, VMMR0_DO_HM_ENABLE, 0, NULL);
1264 if (RT_FAILURE(rc))
1265 {
1266 LogRel(("HM: Failed to enable, error %Rrc\n", rc));
1267 HMR3CheckError(pVM, rc);
1268 return rc;
1269 }
1270
1271 /*
1272 * No TPR patching is required when the IO-APIC is not enabled for this VM.
1273 * (Main should have taken care of this already)
1274 */
1275 if (!PDMHasIoApic(pVM))
1276 {
1277 Assert(!pVM->hm.s.fTprPatchingAllowed); /* paranoia */
1278 pVM->hm.s.fTprPatchingAllowed = false;
1279 }
1280
1281 /*
1282 * Sync options.
1283 */
1284 /** @todo Move this out of of CPUMCTX and into some ring-0 only HM structure.
1285 * That will require a little bit of work, of course. */
1286 for (VMCPUID iCpu = 0; iCpu < pVM->cCpus; iCpu++)
1287 {
1288 PVMCPU pVCpu = &pVM->aCpus[iCpu];
1289 PCPUMCTX pCpuCtx = &pVCpu->cpum.GstCtx;
1290 pCpuCtx->fWorldSwitcher &= ~(CPUMCTX_WSF_IBPB_EXIT | CPUMCTX_WSF_IBPB_ENTRY);
1291 if (pVM->cpum.ro.HostFeatures.fIbpb)
1292 {
1293 if (pVM->hm.s.fIbpbOnVmExit)
1294 pCpuCtx->fWorldSwitcher |= CPUMCTX_WSF_IBPB_EXIT;
1295 if (pVM->hm.s.fIbpbOnVmEntry)
1296 pCpuCtx->fWorldSwitcher |= CPUMCTX_WSF_IBPB_ENTRY;
1297 }
1298 if (iCpu == 0)
1299 LogRel(("HM: fWorldSwitcher=%#x (fIbpbOnVmExit=%RTbool fIbpbOnVmEntry=%RTbool)\n",
1300 pCpuCtx->fWorldSwitcher, pVM->hm.s.fIbpbOnVmExit, pVM->hm.s.fIbpbOnVmEntry));
1301 }
1302
1303 /*
1304 * Do the vendor specific initialization
1305 *
1306 * Note! We disable release log buffering here since we're doing relatively
1307 * lot of logging and doesn't want to hit the disk with each LogRel
1308 * statement.
1309 */
1310 AssertLogRelReturn(!pVM->hm.s.fInitialized, VERR_HM_IPE_5);
1311 bool fOldBuffered = RTLogRelSetBuffering(true /*fBuffered*/);
1312 if (pVM->hm.s.vmx.fSupported)
1313 rc = hmR3InitFinalizeR0Intel(pVM);
1314 else
1315 rc = hmR3InitFinalizeR0Amd(pVM);
1316 LogRel(("HM: VT-x/AMD-V init method: %s\n", (pVM->hm.s.fGlobalInit) ? "GLOBAL" : "LOCAL"));
1317 RTLogRelSetBuffering(fOldBuffered);
1318 pVM->hm.s.fInitialized = true;
1319
1320 return rc;
1321}
1322
1323
1324/**
1325 * @callback_method_impl{FNPDMVMMDEVHEAPNOTIFY}
1326 */
1327static DECLCALLBACK(void) hmR3VmmDevHeapNotify(PVM pVM, void *pvAllocation, RTGCPHYS GCPhysAllocation)
1328{
1329 NOREF(pVM);
1330 NOREF(pvAllocation);
1331 NOREF(GCPhysAllocation);
1332}
1333
1334
1335/**
1336 * Returns the VMCS (and associated regions') memory type given the IA32_VMX_BASIC
1337 * MSR.
1338 *
1339 * @returns The descriptive memory type.
1340 * @param uMsrVmxBasic IA32_VMX_BASIC MSR value.
1341 */
1342static const char *hmR3VmxGetMemTypeDesc(uint64_t uMsrVmxBasic)
1343{
1344 uint8_t const uMemType = MSR_IA32_VMX_BASIC_VMCS_MEM_TYPE(uMsrVmxBasic);
1345 switch (uMemType)
1346 {
1347 case VMX_VMCS_MEM_TYPE_WB: return "Write Back (WB)";
1348 case VMX_VMCS_MEM_TYPE_UC: return "Uncacheable (UC)";
1349 }
1350 return "Unknown";
1351}
1352
1353
1354/**
1355 * Finish VT-x initialization (after ring-0 init).
1356 *
1357 * @returns VBox status code.
1358 * @param pVM The cross context VM structure.
1359 */
1360static int hmR3InitFinalizeR0Intel(PVM pVM)
1361{
1362 int rc;
1363
1364 Log(("pVM->hm.s.vmx.fSupported = %d\n", pVM->hm.s.vmx.fSupported));
1365 AssertLogRelReturn(pVM->hm.s.vmx.Msrs.u64FeatureCtrl != 0, VERR_HM_IPE_4);
1366
1367 uint64_t val;
1368 uint64_t zap;
1369
1370 LogRel(("HM: Using VT-x implementation 2.0\n"));
1371 LogRel(("HM: Host CR4 = %#RX64\n", pVM->hm.s.vmx.u64HostCr4));
1372 LogRel(("HM: Host EFER = %#RX64\n", pVM->hm.s.vmx.u64HostEfer));
1373 LogRel(("HM: MSR_IA32_SMM_MONITOR_CTL = %#RX64\n", pVM->hm.s.vmx.u64HostSmmMonitorCtl));
1374
1375 val = pVM->hm.s.vmx.Msrs.u64FeatureCtrl;
1376 LogRel(("HM: MSR_IA32_FEATURE_CONTROL = %#RX64\n", val));
1377 HMVMX_REPORT_MSR_CAP(val, "LOCK", MSR_IA32_FEATURE_CONTROL_LOCK);
1378 HMVMX_REPORT_MSR_CAP(val, "SMX_VMXON", MSR_IA32_FEATURE_CONTROL_SMX_VMXON);
1379 HMVMX_REPORT_MSR_CAP(val, "VMXON", MSR_IA32_FEATURE_CONTROL_VMXON);
1380 HMVMX_REPORT_MSR_CAP(val, "SENTER_LOCAL_FN0", MSR_IA32_FEATURE_CONTROL_SENTER_LOCAL_FN_0);
1381 HMVMX_REPORT_MSR_CAP(val, "SENTER_LOCAL_FN1", MSR_IA32_FEATURE_CONTROL_SENTER_LOCAL_FN_1);
1382 HMVMX_REPORT_MSR_CAP(val, "SENTER_LOCAL_FN2", MSR_IA32_FEATURE_CONTROL_SENTER_LOCAL_FN_2);
1383 HMVMX_REPORT_MSR_CAP(val, "SENTER_LOCAL_FN3", MSR_IA32_FEATURE_CONTROL_SENTER_LOCAL_FN_3);
1384 HMVMX_REPORT_MSR_CAP(val, "SENTER_LOCAL_FN4", MSR_IA32_FEATURE_CONTROL_SENTER_LOCAL_FN_4);
1385 HMVMX_REPORT_MSR_CAP(val, "SENTER_LOCAL_FN5", MSR_IA32_FEATURE_CONTROL_SENTER_LOCAL_FN_5);
1386 HMVMX_REPORT_MSR_CAP(val, "SENTER_LOCAL_FN6", MSR_IA32_FEATURE_CONTROL_SENTER_LOCAL_FN_6);
1387 HMVMX_REPORT_MSR_CAP(val, "SENTER_GLOBAL_EN", MSR_IA32_FEATURE_CONTROL_SENTER_GLOBAL_EN);
1388 HMVMX_REPORT_MSR_CAP(val, "SGX_LAUNCH_EN", MSR_IA32_FEATURE_CONTROL_SGX_LAUNCH_EN);
1389 HMVMX_REPORT_MSR_CAP(val, "SGX_GLOBAL_EN", MSR_IA32_FEATURE_CONTROL_SGX_GLOBAL_EN);
1390 HMVMX_REPORT_MSR_CAP(val, "LMCE", MSR_IA32_FEATURE_CONTROL_LMCE);
1391 if (!(pVM->hm.s.vmx.Msrs.u64FeatureCtrl & MSR_IA32_FEATURE_CONTROL_LOCK))
1392 LogRel(("HM: MSR_IA32_FEATURE_CONTROL lock bit not set, possibly bad hardware!\n"));
1393
1394 LogRel(("HM: MSR_IA32_VMX_BASIC = %#RX64\n", pVM->hm.s.vmx.Msrs.u64BasicInfo));
1395 LogRel(("HM: VMCS id = %#x\n", MSR_IA32_VMX_BASIC_VMCS_ID(pVM->hm.s.vmx.Msrs.u64BasicInfo)));
1396 LogRel(("HM: VMCS size = %u bytes\n", MSR_IA32_VMX_BASIC_VMCS_SIZE(pVM->hm.s.vmx.Msrs.u64BasicInfo)));
1397 LogRel(("HM: VMCS physical address limit = %s\n", MSR_IA32_VMX_BASIC_VMCS_PHYS_WIDTH(pVM->hm.s.vmx.Msrs.u64BasicInfo) ? "< 4 GB" : "None"));
1398 LogRel(("HM: VMCS memory type = %s\n", hmR3VmxGetMemTypeDesc(pVM->hm.s.vmx.Msrs.u64BasicInfo)));
1399 LogRel(("HM: Dual-monitor treatment support = %RTbool\n", MSR_IA32_VMX_BASIC_DUAL_MON(pVM->hm.s.vmx.Msrs.u64BasicInfo)));
1400 LogRel(("HM: OUTS & INS instruction-info = %RTbool\n", MSR_IA32_VMX_BASIC_VMCS_INS_OUTS(pVM->hm.s.vmx.Msrs.u64BasicInfo)));
1401 LogRel(("HM: Supports true capability MSRs = %RTbool\n", MSR_IA32_VMX_BASIC_TRUE_CONTROLS(pVM->hm.s.vmx.Msrs.u64BasicInfo)));
1402 LogRel(("HM: Max resume loops = %u\n", pVM->hm.s.cMaxResumeLoops));
1403
1404 LogRel(("HM: MSR_IA32_VMX_PINBASED_CTLS = %#RX64\n", pVM->hm.s.vmx.Msrs.VmxPinCtls.u));
1405 val = pVM->hm.s.vmx.Msrs.VmxPinCtls.n.allowed1;
1406 zap = pVM->hm.s.vmx.Msrs.VmxPinCtls.n.disallowed0;
1407 HMVMX_REPORT_FEAT(val, zap, "EXT_INT_EXIT", VMX_VMCS_CTRL_PIN_EXEC_EXT_INT_EXIT);
1408 HMVMX_REPORT_FEAT(val, zap, "NMI_EXIT", VMX_VMCS_CTRL_PIN_EXEC_NMI_EXIT);
1409 HMVMX_REPORT_FEAT(val, zap, "VIRTUAL_NMI", VMX_VMCS_CTRL_PIN_EXEC_VIRTUAL_NMI);
1410 HMVMX_REPORT_FEAT(val, zap, "PREEMPT_TIMER", VMX_VMCS_CTRL_PIN_EXEC_PREEMPT_TIMER);
1411 HMVMX_REPORT_FEAT(val, zap, "POSTED_INTR", VMX_VMCS_CTRL_PIN_EXEC_POSTED_INTR);
1412
1413 LogRel(("HM: MSR_IA32_VMX_PROCBASED_CTLS = %#RX64\n", pVM->hm.s.vmx.Msrs.VmxProcCtls.u));
1414 val = pVM->hm.s.vmx.Msrs.VmxProcCtls.n.allowed1;
1415 zap = pVM->hm.s.vmx.Msrs.VmxProcCtls.n.disallowed0;
1416 HMVMX_REPORT_FEAT(val, zap, "INT_WINDOW_EXIT", VMX_VMCS_CTRL_PROC_EXEC_INT_WINDOW_EXIT);
1417 HMVMX_REPORT_FEAT(val, zap, "USE_TSC_OFFSETTING", VMX_VMCS_CTRL_PROC_EXEC_USE_TSC_OFFSETTING);
1418 HMVMX_REPORT_FEAT(val, zap, "HLT_EXIT", VMX_VMCS_CTRL_PROC_EXEC_HLT_EXIT);
1419 HMVMX_REPORT_FEAT(val, zap, "INVLPG_EXIT", VMX_VMCS_CTRL_PROC_EXEC_INVLPG_EXIT);
1420 HMVMX_REPORT_FEAT(val, zap, "MWAIT_EXIT", VMX_VMCS_CTRL_PROC_EXEC_MWAIT_EXIT);
1421 HMVMX_REPORT_FEAT(val, zap, "RDPMC_EXIT", VMX_VMCS_CTRL_PROC_EXEC_RDPMC_EXIT);
1422 HMVMX_REPORT_FEAT(val, zap, "RDTSC_EXIT", VMX_VMCS_CTRL_PROC_EXEC_RDTSC_EXIT);
1423 HMVMX_REPORT_FEAT(val, zap, "CR3_LOAD_EXIT", VMX_VMCS_CTRL_PROC_EXEC_CR3_LOAD_EXIT);
1424 HMVMX_REPORT_FEAT(val, zap, "CR3_STORE_EXIT", VMX_VMCS_CTRL_PROC_EXEC_CR3_STORE_EXIT);
1425 HMVMX_REPORT_FEAT(val, zap, "CR8_LOAD_EXIT", VMX_VMCS_CTRL_PROC_EXEC_CR8_LOAD_EXIT);
1426 HMVMX_REPORT_FEAT(val, zap, "CR8_STORE_EXIT", VMX_VMCS_CTRL_PROC_EXEC_CR8_STORE_EXIT);
1427 HMVMX_REPORT_FEAT(val, zap, "USE_TPR_SHADOW", VMX_VMCS_CTRL_PROC_EXEC_USE_TPR_SHADOW);
1428 HMVMX_REPORT_FEAT(val, zap, "NMI_WINDOW_EXIT", VMX_VMCS_CTRL_PROC_EXEC_NMI_WINDOW_EXIT);
1429 HMVMX_REPORT_FEAT(val, zap, "MOV_DR_EXIT", VMX_VMCS_CTRL_PROC_EXEC_MOV_DR_EXIT);
1430 HMVMX_REPORT_FEAT(val, zap, "UNCOND_IO_EXIT", VMX_VMCS_CTRL_PROC_EXEC_UNCOND_IO_EXIT);
1431 HMVMX_REPORT_FEAT(val, zap, "USE_IO_BITMAPS", VMX_VMCS_CTRL_PROC_EXEC_USE_IO_BITMAPS);
1432 HMVMX_REPORT_FEAT(val, zap, "MONITOR_TRAP_FLAG", VMX_VMCS_CTRL_PROC_EXEC_MONITOR_TRAP_FLAG);
1433 HMVMX_REPORT_FEAT(val, zap, "USE_MSR_BITMAPS", VMX_VMCS_CTRL_PROC_EXEC_USE_MSR_BITMAPS);
1434 HMVMX_REPORT_FEAT(val, zap, "MONITOR_EXIT", VMX_VMCS_CTRL_PROC_EXEC_MONITOR_EXIT);
1435 HMVMX_REPORT_FEAT(val, zap, "PAUSE_EXIT", VMX_VMCS_CTRL_PROC_EXEC_PAUSE_EXIT);
1436 HMVMX_REPORT_FEAT(val, zap, "USE_SECONDARY_EXEC_CTRL", VMX_VMCS_CTRL_PROC_EXEC_USE_SECONDARY_EXEC_CTRL);
1437 if (pVM->hm.s.vmx.Msrs.VmxProcCtls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_USE_SECONDARY_EXEC_CTRL)
1438 {
1439 LogRel(("HM: MSR_IA32_VMX_PROCBASED_CTLS2 = %#RX64\n", pVM->hm.s.vmx.Msrs.VmxProcCtls2.u));
1440 val = pVM->hm.s.vmx.Msrs.VmxProcCtls2.n.allowed1;
1441 zap = pVM->hm.s.vmx.Msrs.VmxProcCtls2.n.disallowed0;
1442 HMVMX_REPORT_FEAT(val, zap, "VIRT_APIC", VMX_VMCS_CTRL_PROC_EXEC2_VIRT_APIC);
1443 HMVMX_REPORT_FEAT(val, zap, "EPT", VMX_VMCS_CTRL_PROC_EXEC2_EPT);
1444 HMVMX_REPORT_FEAT(val, zap, "DESCRIPTOR_TABLE_EXIT", VMX_VMCS_CTRL_PROC_EXEC2_DESCRIPTOR_TABLE_EXIT);
1445 HMVMX_REPORT_FEAT(val, zap, "RDTSCP", VMX_VMCS_CTRL_PROC_EXEC2_RDTSCP);
1446 HMVMX_REPORT_FEAT(val, zap, "VIRT_X2APIC", VMX_VMCS_CTRL_PROC_EXEC2_VIRT_X2APIC);
1447 HMVMX_REPORT_FEAT(val, zap, "VPID", VMX_VMCS_CTRL_PROC_EXEC2_VPID);
1448 HMVMX_REPORT_FEAT(val, zap, "WBINVD_EXIT", VMX_VMCS_CTRL_PROC_EXEC2_WBINVD_EXIT);
1449 HMVMX_REPORT_FEAT(val, zap, "UNRESTRICTED_GUEST", VMX_VMCS_CTRL_PROC_EXEC2_UNRESTRICTED_GUEST);
1450 HMVMX_REPORT_FEAT(val, zap, "APIC_REG_VIRT", VMX_VMCS_CTRL_PROC_EXEC2_APIC_REG_VIRT);
1451 HMVMX_REPORT_FEAT(val, zap, "VIRT_INTR_DELIVERY", VMX_VMCS_CTRL_PROC_EXEC2_VIRT_INTR_DELIVERY);
1452 HMVMX_REPORT_FEAT(val, zap, "PAUSE_LOOP_EXIT", VMX_VMCS_CTRL_PROC_EXEC2_PAUSE_LOOP_EXIT);
1453 HMVMX_REPORT_FEAT(val, zap, "RDRAND_EXIT", VMX_VMCS_CTRL_PROC_EXEC2_RDRAND_EXIT);
1454 HMVMX_REPORT_FEAT(val, zap, "INVPCID", VMX_VMCS_CTRL_PROC_EXEC2_INVPCID);
1455 HMVMX_REPORT_FEAT(val, zap, "VMFUNC", VMX_VMCS_CTRL_PROC_EXEC2_VMFUNC);
1456 HMVMX_REPORT_FEAT(val, zap, "VMCS_SHADOWING", VMX_VMCS_CTRL_PROC_EXEC2_VMCS_SHADOWING);
1457 HMVMX_REPORT_FEAT(val, zap, "ENCLS_EXIT", VMX_VMCS_CTRL_PROC_EXEC2_ENCLS_EXIT);
1458 HMVMX_REPORT_FEAT(val, zap, "RDSEED_EXIT", VMX_VMCS_CTRL_PROC_EXEC2_RDSEED_EXIT);
1459 HMVMX_REPORT_FEAT(val, zap, "PML", VMX_VMCS_CTRL_PROC_EXEC2_PML);
1460 HMVMX_REPORT_FEAT(val, zap, "EPT_VE", VMX_VMCS_CTRL_PROC_EXEC2_EPT_VE);
1461 HMVMX_REPORT_FEAT(val, zap, "CONCEAL_FROM_PT", VMX_VMCS_CTRL_PROC_EXEC2_CONCEAL_FROM_PT);
1462 HMVMX_REPORT_FEAT(val, zap, "XSAVES_XRSTORS", VMX_VMCS_CTRL_PROC_EXEC2_XSAVES_XRSTORS);
1463 HMVMX_REPORT_FEAT(val, zap, "TSC_SCALING", VMX_VMCS_CTRL_PROC_EXEC2_TSC_SCALING);
1464 }
1465
1466 LogRel(("HM: MSR_IA32_VMX_ENTRY_CTLS = %#RX64\n", pVM->hm.s.vmx.Msrs.VmxEntry.u));
1467 val = pVM->hm.s.vmx.Msrs.VmxEntry.n.allowed1;
1468 zap = pVM->hm.s.vmx.Msrs.VmxEntry.n.disallowed0;
1469 HMVMX_REPORT_FEAT(val, zap, "LOAD_DEBUG", VMX_VMCS_CTRL_ENTRY_LOAD_DEBUG);
1470 HMVMX_REPORT_FEAT(val, zap, "IA32E_MODE_GUEST", VMX_VMCS_CTRL_ENTRY_IA32E_MODE_GUEST);
1471 HMVMX_REPORT_FEAT(val, zap, "ENTRY_SMM", VMX_VMCS_CTRL_ENTRY_ENTRY_SMM);
1472 HMVMX_REPORT_FEAT(val, zap, "DEACTIVATE_DUALMON", VMX_VMCS_CTRL_ENTRY_DEACTIVATE_DUALMON);
1473 HMVMX_REPORT_FEAT(val, zap, "LOAD_GUEST_PERF_MSR", VMX_VMCS_CTRL_ENTRY_LOAD_GUEST_PERF_MSR);
1474 HMVMX_REPORT_FEAT(val, zap, "LOAD_GUEST_PAT_MSR", VMX_VMCS_CTRL_ENTRY_LOAD_GUEST_PAT_MSR);
1475 HMVMX_REPORT_FEAT(val, zap, "LOAD_GUEST_EFER_MSR", VMX_VMCS_CTRL_ENTRY_LOAD_GUEST_EFER_MSR);
1476
1477 LogRel(("HM: MSR_IA32_VMX_EXIT_CTLS = %#RX64\n", pVM->hm.s.vmx.Msrs.VmxExit.u));
1478 val = pVM->hm.s.vmx.Msrs.VmxExit.n.allowed1;
1479 zap = pVM->hm.s.vmx.Msrs.VmxExit.n.disallowed0;
1480 HMVMX_REPORT_FEAT(val, zap, "SAVE_DEBUG", VMX_VMCS_CTRL_EXIT_SAVE_DEBUG);
1481 HMVMX_REPORT_FEAT(val, zap, "HOST_ADDR_SPACE_SIZE", VMX_VMCS_CTRL_EXIT_HOST_ADDR_SPACE_SIZE);
1482 HMVMX_REPORT_FEAT(val, zap, "LOAD_PERF_MSR", VMX_VMCS_CTRL_EXIT_LOAD_PERF_MSR);
1483 HMVMX_REPORT_FEAT(val, zap, "ACK_EXT_INT", VMX_VMCS_CTRL_EXIT_ACK_EXT_INT);
1484 HMVMX_REPORT_FEAT(val, zap, "SAVE_GUEST_PAT_MSR", VMX_VMCS_CTRL_EXIT_SAVE_GUEST_PAT_MSR);
1485 HMVMX_REPORT_FEAT(val, zap, "LOAD_HOST_PAT_MSR", VMX_VMCS_CTRL_EXIT_LOAD_HOST_PAT_MSR);
1486 HMVMX_REPORT_FEAT(val, zap, "SAVE_GUEST_EFER_MSR", VMX_VMCS_CTRL_EXIT_SAVE_GUEST_EFER_MSR);
1487 HMVMX_REPORT_FEAT(val, zap, "LOAD_HOST_EFER_MSR", VMX_VMCS_CTRL_EXIT_LOAD_HOST_EFER_MSR);
1488 HMVMX_REPORT_FEAT(val, zap, "SAVE_VMX_PREEMPT_TIMER", VMX_VMCS_CTRL_EXIT_SAVE_VMX_PREEMPT_TIMER);
1489
1490 if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps)
1491 {
1492 val = pVM->hm.s.vmx.Msrs.u64EptVpidCaps;
1493 LogRel(("HM: MSR_IA32_VMX_EPT_VPID_CAP = %#RX64\n", val));
1494 HMVMX_REPORT_MSR_CAP(val, "RWX_X_ONLY", MSR_IA32_VMX_EPT_VPID_CAP_RWX_X_ONLY);
1495 HMVMX_REPORT_MSR_CAP(val, "PAGE_WALK_LENGTH_4", MSR_IA32_VMX_EPT_VPID_CAP_PAGE_WALK_LENGTH_4);
1496 HMVMX_REPORT_MSR_CAP(val, "EMT_UC", MSR_IA32_VMX_EPT_VPID_CAP_EMT_UC);
1497 HMVMX_REPORT_MSR_CAP(val, "EMT_WB", MSR_IA32_VMX_EPT_VPID_CAP_EMT_WB);
1498 HMVMX_REPORT_MSR_CAP(val, "PDE_2M", MSR_IA32_VMX_EPT_VPID_CAP_PDE_2M);
1499 HMVMX_REPORT_MSR_CAP(val, "PDPTE_1G", MSR_IA32_VMX_EPT_VPID_CAP_PDPTE_1G);
1500 HMVMX_REPORT_MSR_CAP(val, "INVEPT", MSR_IA32_VMX_EPT_VPID_CAP_INVEPT);
1501 HMVMX_REPORT_MSR_CAP(val, "EPT_ACCESS_DIRTY", MSR_IA32_VMX_EPT_VPID_CAP_EPT_ACCESS_DIRTY);
1502 HMVMX_REPORT_MSR_CAP(val, "INVEPT_SINGLE_CONTEXT", MSR_IA32_VMX_EPT_VPID_CAP_INVEPT_SINGLE_CONTEXT);
1503 HMVMX_REPORT_MSR_CAP(val, "INVEPT_ALL_CONTEXTS", MSR_IA32_VMX_EPT_VPID_CAP_INVEPT_ALL_CONTEXTS);
1504 HMVMX_REPORT_MSR_CAP(val, "INVVPID", MSR_IA32_VMX_EPT_VPID_CAP_INVVPID);
1505 HMVMX_REPORT_MSR_CAP(val, "INVVPID_INDIV_ADDR", MSR_IA32_VMX_EPT_VPID_CAP_INVVPID_INDIV_ADDR);
1506 HMVMX_REPORT_MSR_CAP(val, "INVVPID_SINGLE_CONTEXT", MSR_IA32_VMX_EPT_VPID_CAP_INVVPID_SINGLE_CONTEXT);
1507 HMVMX_REPORT_MSR_CAP(val, "INVVPID_ALL_CONTEXTS", MSR_IA32_VMX_EPT_VPID_CAP_INVVPID_ALL_CONTEXTS);
1508 HMVMX_REPORT_MSR_CAP(val, "INVVPID_SINGLE_CONTEXT_RETAIN_GLOBALS", MSR_IA32_VMX_EPT_VPID_CAP_INVVPID_SINGLE_CONTEXT_RETAIN_GLOBALS);
1509 }
1510
1511 val = pVM->hm.s.vmx.Msrs.u64Misc;
1512 LogRel(("HM: MSR_IA32_VMX_MISC = %#RX64\n", val));
1513 if (MSR_IA32_VMX_MISC_PREEMPT_TSC_BIT(val) == pVM->hm.s.vmx.cPreemptTimerShift)
1514 LogRel(("HM: PREEMPT_TSC_BIT = %#x\n", MSR_IA32_VMX_MISC_PREEMPT_TSC_BIT(val)));
1515 else
1516 {
1517 LogRel(("HM: PREEMPT_TSC_BIT = %#x - erratum detected, using %#x instead\n",
1518 MSR_IA32_VMX_MISC_PREEMPT_TSC_BIT(val), pVM->hm.s.vmx.cPreemptTimerShift));
1519 }
1520
1521 LogRel(("HM: STORE_EFERLMA_VMEXIT = %RTbool\n", RT_BOOL(MSR_IA32_VMX_MISC_STORE_EFERLMA_VMEXIT(val))));
1522 LogRel(("HM: ACTIVITY_STATES = %#x\n", MSR_IA32_VMX_MISC_ACTIVITY_STATES(val)));
1523 LogRel(("HM: CR3_TARGET = %#x\n", MSR_IA32_VMX_MISC_CR3_TARGET(val)));
1524 LogRel(("HM: MAX_MSR = %u\n", MSR_IA32_VMX_MISC_MAX_MSR(val)));
1525 LogRel(("HM: RDMSR_SMBASE_MSR_SMM = %RTbool\n", RT_BOOL(MSR_IA32_VMX_MISC_RDMSR_SMBASE_MSR_SMM(val))));
1526 LogRel(("HM: SMM_MONITOR_CTL_B2 = %RTbool\n", RT_BOOL(MSR_IA32_VMX_MISC_SMM_MONITOR_CTL_B2(val))));
1527 LogRel(("HM: VMWRITE_VMEXIT_INFO = %RTbool\n", RT_BOOL(MSR_IA32_VMX_MISC_VMWRITE_VMEXIT_INFO(val))));
1528 LogRel(("HM: MSEG_ID = %#x\n", MSR_IA32_VMX_MISC_MSEG_ID(val)));
1529
1530 /* Paranoia */
1531 AssertRelease(MSR_IA32_VMX_MISC_MAX_MSR(pVM->hm.s.vmx.Msrs.u64Misc) >= 512);
1532
1533 LogRel(("HM: MSR_IA32_VMX_CR0_FIXED0 = %#RX64\n", pVM->hm.s.vmx.Msrs.u64Cr0Fixed0));
1534 LogRel(("HM: MSR_IA32_VMX_CR0_FIXED1 = %#RX64\n", pVM->hm.s.vmx.Msrs.u64Cr0Fixed1));
1535 LogRel(("HM: MSR_IA32_VMX_CR4_FIXED0 = %#RX64\n", pVM->hm.s.vmx.Msrs.u64Cr4Fixed0));
1536 LogRel(("HM: MSR_IA32_VMX_CR4_FIXED1 = %#RX64\n", pVM->hm.s.vmx.Msrs.u64Cr4Fixed1));
1537
1538 val = pVM->hm.s.vmx.Msrs.u64VmcsEnum;
1539 LogRel(("HM: MSR_IA32_VMX_VMCS_ENUM = %#RX64\n", val));
1540 LogRel(("HM: HIGHEST_INDEX = %#x\n", MSR_IA32_VMX_VMCS_ENUM_HIGHEST_INDEX(val)));
1541
1542 val = pVM->hm.s.vmx.Msrs.u64Vmfunc;
1543 if (val)
1544 {
1545 LogRel(("HM: MSR_IA32_VMX_VMFUNC = %#RX64\n", val));
1546 HMVMX_REPORT_ALLOWED_FEAT(val, "EPTP_SWITCHING", VMX_VMCS_CTRL_VMFUNC_EPTP_SWITCHING);
1547 }
1548
1549 LogRel(("HM: APIC-access page physaddr = %#RHp\n", pVM->hm.s.vmx.HCPhysApicAccess));
1550
1551 for (VMCPUID i = 0; i < pVM->cCpus; i++)
1552 {
1553 LogRel(("HM: VCPU%3d: MSR bitmap physaddr = %#RHp\n", i, pVM->aCpus[i].hm.s.vmx.HCPhysMsrBitmap));
1554 LogRel(("HM: VCPU%3d: VMCS physaddr = %#RHp\n", i, pVM->aCpus[i].hm.s.vmx.HCPhysVmcs));
1555 }
1556
1557 /*
1558 * EPT and unhampered guest execution are determined in HMR3Init, verify the sanity of that.
1559 */
1560 AssertLogRelReturn( !pVM->hm.s.fNestedPaging
1561 || (pVM->hm.s.vmx.Msrs.VmxProcCtls2.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_EPT),
1562 VERR_HM_IPE_1);
1563 AssertLogRelReturn( !pVM->hm.s.vmx.fUnrestrictedGuest
1564 || ( (pVM->hm.s.vmx.Msrs.VmxProcCtls2.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_UNRESTRICTED_GUEST)
1565 && pVM->hm.s.fNestedPaging),
1566 VERR_HM_IPE_1);
1567
1568 /*
1569 * Enable VPID if configured and supported.
1570 */
1571 if (pVM->hm.s.vmx.Msrs.VmxProcCtls2.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_VPID)
1572 pVM->hm.s.vmx.fVpid = pVM->hm.s.vmx.fAllowVpid;
1573
1574#if 0
1575 /*
1576 * Enable APIC register virtualization and virtual-interrupt delivery if supported.
1577 */
1578 if ( (pVM->hm.s.vmx.Msrs.VmxProcCtls2.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_APIC_REG_VIRT)
1579 && (pVM->hm.s.vmx.Msrs.VmxProcCtls2.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_VIRT_INTR_DELIVERY))
1580 pVM->hm.s.fVirtApicRegs = true;
1581
1582 /*
1583 * Enable posted-interrupt processing if supported.
1584 */
1585 /** @todo Add and query IPRT API for host OS support for posted-interrupt IPI
1586 * here. */
1587 if ( (pVM->hm.s.vmx.Msrs.VmxPinCtls.n.allowed1 & VMX_VMCS_CTRL_PIN_EXEC_POSTED_INTR)
1588 && (pVM->hm.s.vmx.Msrs.VmxExit.n.allowed1 & VMX_VMCS_CTRL_EXIT_ACK_EXT_INT))
1589 pVM->hm.s.fPostedIntrs = true;
1590#endif
1591
1592 /*
1593 * Disallow RDTSCP in the guest if there is no secondary process-based VM execution controls as otherwise
1594 * RDTSCP would cause a #UD. There might be no CPUs out there where this happens, as RDTSCP was introduced
1595 * in Nehalems and secondary VM exec. controls should be supported in all of them, but nonetheless it's Intel...
1596 */
1597 if ( !(pVM->hm.s.vmx.Msrs.VmxProcCtls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_USE_SECONDARY_EXEC_CTRL)
1598 && CPUMR3GetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_RDTSCP))
1599 {
1600 CPUMR3ClearGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_RDTSCP);
1601 LogRel(("HM: Disabled RDTSCP\n"));
1602 }
1603
1604 if (!pVM->hm.s.vmx.fUnrestrictedGuest)
1605 {
1606 /* Allocate three pages for the TSS we need for real mode emulation. (2 pages for the IO bitmap) */
1607 rc = PDMR3VmmDevHeapAlloc(pVM, HM_VTX_TOTAL_DEVHEAP_MEM, hmR3VmmDevHeapNotify, (RTR3PTR *)&pVM->hm.s.vmx.pRealModeTSS);
1608 if (RT_SUCCESS(rc))
1609 {
1610 /* The IO bitmap starts right after the virtual interrupt redirection bitmap.
1611 Refer Intel spec. 20.3.3 "Software Interrupt Handling in Virtual-8086 mode"
1612 esp. Figure 20-5.*/
1613 ASMMemZero32(pVM->hm.s.vmx.pRealModeTSS, sizeof(*pVM->hm.s.vmx.pRealModeTSS));
1614 pVM->hm.s.vmx.pRealModeTSS->offIoBitmap = sizeof(*pVM->hm.s.vmx.pRealModeTSS);
1615
1616 /* Bit set to 0 means software interrupts are redirected to the
1617 8086 program interrupt handler rather than switching to
1618 protected-mode handler. */
1619 memset(pVM->hm.s.vmx.pRealModeTSS->IntRedirBitmap, 0, sizeof(pVM->hm.s.vmx.pRealModeTSS->IntRedirBitmap));
1620
1621 /* Allow all port IO, so that port IO instructions do not cause
1622 exceptions and would instead cause a VM-exit (based on VT-x's
1623 IO bitmap which we currently configure to always cause an exit). */
1624 memset(pVM->hm.s.vmx.pRealModeTSS + 1, 0, PAGE_SIZE * 2);
1625 *((unsigned char *)pVM->hm.s.vmx.pRealModeTSS + HM_VTX_TSS_SIZE - 2) = 0xff;
1626
1627 /*
1628 * Construct a 1024 element page directory with 4 MB pages for the identity mapped
1629 * page table used in real and protected mode without paging with EPT.
1630 */
1631 pVM->hm.s.vmx.pNonPagingModeEPTPageTable = (PX86PD)((char *)pVM->hm.s.vmx.pRealModeTSS + PAGE_SIZE * 3);
1632 for (uint32_t i = 0; i < X86_PG_ENTRIES; i++)
1633 {
1634 pVM->hm.s.vmx.pNonPagingModeEPTPageTable->a[i].u = _4M * i;
1635 pVM->hm.s.vmx.pNonPagingModeEPTPageTable->a[i].u |= X86_PDE4M_P | X86_PDE4M_RW | X86_PDE4M_US
1636 | X86_PDE4M_A | X86_PDE4M_D | X86_PDE4M_PS
1637 | X86_PDE4M_G;
1638 }
1639
1640 /* We convert it here every time as PCI regions could be reconfigured. */
1641 if (PDMVmmDevHeapIsEnabled(pVM))
1642 {
1643 RTGCPHYS GCPhys;
1644 rc = PDMVmmDevHeapR3ToGCPhys(pVM, pVM->hm.s.vmx.pRealModeTSS, &GCPhys);
1645 AssertRCReturn(rc, rc);
1646 LogRel(("HM: Real Mode TSS guest physaddr = %#RGp\n", GCPhys));
1647
1648 rc = PDMVmmDevHeapR3ToGCPhys(pVM, pVM->hm.s.vmx.pNonPagingModeEPTPageTable, &GCPhys);
1649 AssertRCReturn(rc, rc);
1650 LogRel(("HM: Non-Paging Mode EPT CR3 = %#RGp\n", GCPhys));
1651 }
1652 }
1653 else
1654 {
1655 LogRel(("HM: No real mode VT-x support (PDMR3VMMDevHeapAlloc returned %Rrc)\n", rc));
1656 pVM->hm.s.vmx.pRealModeTSS = NULL;
1657 pVM->hm.s.vmx.pNonPagingModeEPTPageTable = NULL;
1658 return VMSetError(pVM, rc, RT_SRC_POS,
1659 "HM failure: No real mode VT-x support (PDMR3VMMDevHeapAlloc returned %Rrc)", rc);
1660 }
1661 }
1662
1663 LogRel((pVM->hm.s.fAllow64BitGuests
1664 ? "HM: Guest support: 32-bit and 64-bit\n"
1665 : "HM: Guest support: 32-bit only\n"));
1666
1667 /*
1668 * Call ring-0 to set up the VM.
1669 */
1670 rc = SUPR3CallVMMR0Ex(pVM->pVMR0, 0 /* idCpu */, VMMR0_DO_HM_SETUP_VM, 0 /* u64Arg */, NULL /* pReqHdr */);
1671 if (rc != VINF_SUCCESS)
1672 {
1673 AssertMsgFailed(("%Rrc\n", rc));
1674 LogRel(("HM: VMX setup failed with rc=%Rrc!\n", rc));
1675 for (VMCPUID i = 0; i < pVM->cCpus; i++)
1676 {
1677 PVMCPU pVCpu = &pVM->aCpus[i];
1678 LogRel(("HM: CPU[%u] Last instruction error %#x\n", i, pVCpu->hm.s.vmx.LastError.u32InstrError));
1679 LogRel(("HM: CPU[%u] HM error %#x (%u)\n", i, pVCpu->hm.s.u32HMError, pVCpu->hm.s.u32HMError));
1680 }
1681 HMR3CheckError(pVM, rc);
1682 return VMSetError(pVM, rc, RT_SRC_POS, "VT-x setup failed: %Rrc", rc);
1683 }
1684
1685 LogRel(("HM: Supports VMCS EFER fields = %RTbool\n", pVM->hm.s.vmx.fSupportsVmcsEfer));
1686 LogRel(("HM: Enabled VMX\n"));
1687 pVM->hm.s.vmx.fEnabled = true;
1688
1689 hmR3DisableRawMode(pVM); /** @todo make this go away! */
1690
1691 /*
1692 * Change the CPU features.
1693 */
1694 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_SEP);
1695 if (pVM->hm.s.fAllow64BitGuests)
1696 {
1697 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_PAE);
1698 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_LONG_MODE);
1699 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_SYSCALL); /* 64 bits only on Intel CPUs */
1700 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_LAHF);
1701 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_NX);
1702 }
1703 /* Turn on NXE if PAE has been enabled *and* the host has turned on NXE
1704 (we reuse the host EFER in the switcher). */
1705 /** @todo this needs to be fixed properly!! */
1706 else if (CPUMR3GetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_PAE))
1707 {
1708 if (pVM->hm.s.vmx.u64HostEfer & MSR_K6_EFER_NXE)
1709 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_NX);
1710 else
1711 LogRel(("HM: NX not enabled on the host, unavailable to PAE guest\n"));
1712 }
1713
1714 /*
1715 * Log configuration details.
1716 */
1717 if (pVM->hm.s.fNestedPaging)
1718 {
1719 LogRel(("HM: Enabled nested paging\n"));
1720 if (pVM->hm.s.vmx.enmTlbFlushEpt == VMXTLBFLUSHEPT_SINGLE_CONTEXT)
1721 LogRel(("HM: EPT flush type = Single context\n"));
1722 else if (pVM->hm.s.vmx.enmTlbFlushEpt == VMXTLBFLUSHEPT_ALL_CONTEXTS)
1723 LogRel(("HM: EPT flush type = All contexts\n"));
1724 else if (pVM->hm.s.vmx.enmTlbFlushEpt == VMXTLBFLUSHEPT_NOT_SUPPORTED)
1725 LogRel(("HM: EPT flush type = Not supported\n"));
1726 else
1727 LogRel(("HM: EPT flush type = %#x\n", pVM->hm.s.vmx.enmTlbFlushEpt));
1728
1729 if (pVM->hm.s.vmx.fUnrestrictedGuest)
1730 LogRel(("HM: Enabled unrestricted guest execution\n"));
1731
1732#if HC_ARCH_BITS == 64
1733 if (pVM->hm.s.fLargePages)
1734 {
1735 /* Use large (2 MB) pages for our EPT PDEs where possible. */
1736 PGMSetLargePageUsage(pVM, true);
1737 LogRel(("HM: Enabled large page support\n"));
1738 }
1739#endif
1740 }
1741 else
1742 Assert(!pVM->hm.s.vmx.fUnrestrictedGuest);
1743
1744 if (pVM->hm.s.fVirtApicRegs)
1745 LogRel(("HM: Enabled APIC-register virtualization support\n"));
1746
1747 if (pVM->hm.s.fPostedIntrs)
1748 LogRel(("HM: Enabled posted-interrupt processing support\n"));
1749
1750 if (pVM->hm.s.vmx.fVpid)
1751 {
1752 LogRel(("HM: Enabled VPID\n"));
1753 if (pVM->hm.s.vmx.enmTlbFlushVpid == VMXTLBFLUSHVPID_INDIV_ADDR)
1754 LogRel(("HM: VPID flush type = Individual addresses\n"));
1755 else if (pVM->hm.s.vmx.enmTlbFlushVpid == VMXTLBFLUSHVPID_SINGLE_CONTEXT)
1756 LogRel(("HM: VPID flush type = Single context\n"));
1757 else if (pVM->hm.s.vmx.enmTlbFlushVpid == VMXTLBFLUSHVPID_ALL_CONTEXTS)
1758 LogRel(("HM: VPID flush type = All contexts\n"));
1759 else if (pVM->hm.s.vmx.enmTlbFlushVpid == VMXTLBFLUSHVPID_SINGLE_CONTEXT_RETAIN_GLOBALS)
1760 LogRel(("HM: VPID flush type = Single context retain globals\n"));
1761 else
1762 LogRel(("HM: VPID flush type = %#x\n", pVM->hm.s.vmx.enmTlbFlushVpid));
1763 }
1764 else if (pVM->hm.s.vmx.enmTlbFlushVpid == VMXTLBFLUSHVPID_NOT_SUPPORTED)
1765 LogRel(("HM: Ignoring VPID capabilities of CPU\n"));
1766
1767 if (pVM->hm.s.vmx.fUsePreemptTimer)
1768 LogRel(("HM: Enabled VMX-preemption timer (cPreemptTimerShift=%u)\n", pVM->hm.s.vmx.cPreemptTimerShift));
1769 else
1770 LogRel(("HM: Disabled VMX-preemption timer\n"));
1771
1772 return VINF_SUCCESS;
1773}
1774
1775
1776/**
1777 * Finish AMD-V initialization (after ring-0 init).
1778 *
1779 * @returns VBox status code.
1780 * @param pVM The cross context VM structure.
1781 */
1782static int hmR3InitFinalizeR0Amd(PVM pVM)
1783{
1784 Log(("pVM->hm.s.svm.fSupported = %d\n", pVM->hm.s.svm.fSupported));
1785
1786 LogRel(("HM: Using AMD-V implementation 2.0\n"));
1787
1788 uint32_t u32Family;
1789 uint32_t u32Model;
1790 uint32_t u32Stepping;
1791 if (HMAmdIsSubjectToErratum170(&u32Family, &u32Model, &u32Stepping))
1792 LogRel(("HM: AMD Cpu with erratum 170 family %#x model %#x stepping %#x\n", u32Family, u32Model, u32Stepping));
1793 LogRel(("HM: Max resume loops = %u\n", pVM->hm.s.cMaxResumeLoops));
1794 LogRel(("HM: CPUID 0x80000001.u32AMDFeatureECX = %#RX32\n", pVM->hm.s.cpuid.u32AMDFeatureECX));
1795 LogRel(("HM: CPUID 0x80000001.u32AMDFeatureEDX = %#RX32\n", pVM->hm.s.cpuid.u32AMDFeatureEDX));
1796 LogRel(("HM: AMD HWCR MSR = %#RX64\n", pVM->hm.s.svm.u64MsrHwcr));
1797 LogRel(("HM: AMD-V revision = %#x\n", pVM->hm.s.svm.u32Rev));
1798 LogRel(("HM: AMD-V max ASID = %RU32\n", pVM->hm.s.uMaxAsid));
1799 LogRel(("HM: AMD-V features = %#x\n", pVM->hm.s.svm.u32Features));
1800
1801 /*
1802 * Enumerate AMD-V features.
1803 */
1804 static const struct { uint32_t fFlag; const char *pszName; } s_aSvmFeatures[] =
1805 {
1806#define HMSVM_REPORT_FEATURE(a_StrDesc, a_Define) { a_Define, a_StrDesc }
1807 HMSVM_REPORT_FEATURE("NESTED_PAGING", X86_CPUID_SVM_FEATURE_EDX_NESTED_PAGING),
1808 HMSVM_REPORT_FEATURE("LBR_VIRT", X86_CPUID_SVM_FEATURE_EDX_LBR_VIRT),
1809 HMSVM_REPORT_FEATURE("SVM_LOCK", X86_CPUID_SVM_FEATURE_EDX_SVM_LOCK),
1810 HMSVM_REPORT_FEATURE("NRIP_SAVE", X86_CPUID_SVM_FEATURE_EDX_NRIP_SAVE),
1811 HMSVM_REPORT_FEATURE("TSC_RATE_MSR", X86_CPUID_SVM_FEATURE_EDX_TSC_RATE_MSR),
1812 HMSVM_REPORT_FEATURE("VMCB_CLEAN", X86_CPUID_SVM_FEATURE_EDX_VMCB_CLEAN),
1813 HMSVM_REPORT_FEATURE("FLUSH_BY_ASID", X86_CPUID_SVM_FEATURE_EDX_FLUSH_BY_ASID),
1814 HMSVM_REPORT_FEATURE("DECODE_ASSISTS", X86_CPUID_SVM_FEATURE_EDX_DECODE_ASSISTS),
1815 HMSVM_REPORT_FEATURE("PAUSE_FILTER", X86_CPUID_SVM_FEATURE_EDX_PAUSE_FILTER),
1816 HMSVM_REPORT_FEATURE("PAUSE_FILTER_THRESHOLD", X86_CPUID_SVM_FEATURE_EDX_PAUSE_FILTER_THRESHOLD),
1817 HMSVM_REPORT_FEATURE("AVIC", X86_CPUID_SVM_FEATURE_EDX_AVIC),
1818 HMSVM_REPORT_FEATURE("VIRT_VMSAVE_VMLOAD", X86_CPUID_SVM_FEATURE_EDX_VIRT_VMSAVE_VMLOAD),
1819 HMSVM_REPORT_FEATURE("VGIF", X86_CPUID_SVM_FEATURE_EDX_VGIF),
1820#undef HMSVM_REPORT_FEATURE
1821 };
1822
1823 uint32_t fSvmFeatures = pVM->hm.s.svm.u32Features;
1824 for (unsigned i = 0; i < RT_ELEMENTS(s_aSvmFeatures); i++)
1825 if (fSvmFeatures & s_aSvmFeatures[i].fFlag)
1826 {
1827 LogRel(("HM: %s\n", s_aSvmFeatures[i].pszName));
1828 fSvmFeatures &= ~s_aSvmFeatures[i].fFlag;
1829 }
1830 if (fSvmFeatures)
1831 for (unsigned iBit = 0; iBit < 32; iBit++)
1832 if (RT_BIT_32(iBit) & fSvmFeatures)
1833 LogRel(("HM: Reserved bit %u\n", iBit));
1834
1835 /*
1836 * Nested paging is determined in HMR3Init, verify the sanity of that.
1837 */
1838 AssertLogRelReturn( !pVM->hm.s.fNestedPaging
1839 || (pVM->hm.s.svm.u32Features & X86_CPUID_SVM_FEATURE_EDX_NESTED_PAGING),
1840 VERR_HM_IPE_1);
1841
1842#if 0
1843 /** @todo Add and query IPRT API for host OS support for posted-interrupt IPI
1844 * here. */
1845 if (RTR0IsPostIpiSupport())
1846 pVM->hm.s.fPostedIntrs = true;
1847#endif
1848
1849 /*
1850 * Call ring-0 to set up the VM.
1851 */
1852 int rc = SUPR3CallVMMR0Ex(pVM->pVMR0, 0 /*idCpu*/, VMMR0_DO_HM_SETUP_VM, 0, NULL);
1853 if (rc != VINF_SUCCESS)
1854 {
1855 AssertMsgFailed(("%Rrc\n", rc));
1856 LogRel(("HM: AMD-V setup failed with rc=%Rrc!\n", rc));
1857 return VMSetError(pVM, rc, RT_SRC_POS, "AMD-V setup failed: %Rrc", rc);
1858 }
1859
1860 LogRel(("HM: Enabled SVM\n"));
1861 pVM->hm.s.svm.fEnabled = true;
1862
1863 if (pVM->hm.s.fNestedPaging)
1864 {
1865 LogRel(("HM: Enabled nested paging\n"));
1866
1867 /*
1868 * Enable large pages (2 MB) if applicable.
1869 */
1870#if HC_ARCH_BITS == 64
1871 if (pVM->hm.s.fLargePages)
1872 {
1873 PGMSetLargePageUsage(pVM, true);
1874 LogRel(("HM: Enabled large page support\n"));
1875 }
1876#endif
1877 }
1878
1879 if (pVM->hm.s.fVirtApicRegs)
1880 LogRel(("HM: Enabled APIC-register virtualization support\n"));
1881
1882 if (pVM->hm.s.fPostedIntrs)
1883 LogRel(("HM: Enabled posted-interrupt processing support\n"));
1884
1885 hmR3DisableRawMode(pVM);
1886
1887 /*
1888 * Change the CPU features.
1889 */
1890 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_SEP);
1891 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_SYSCALL);
1892 if (pVM->hm.s.fAllow64BitGuests)
1893 {
1894 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_PAE);
1895 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_LONG_MODE);
1896 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_NX);
1897 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_LAHF);
1898 }
1899 /* Turn on NXE if PAE has been enabled. */
1900 else if (CPUMR3GetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_PAE))
1901 CPUMR3SetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_NX);
1902
1903 LogRel(("HM: %s TPR patching\n", (pVM->hm.s.fTprPatchingAllowed) ? "Enabled" : "Disabled"));
1904
1905 LogRel((pVM->hm.s.fAllow64BitGuests
1906 ? "HM: Guest support: 32-bit and 64-bit\n"
1907 : "HM: Guest support: 32-bit only\n"));
1908
1909 return VINF_SUCCESS;
1910}
1911
1912
1913/**
1914 * Applies relocations to data and code managed by this
1915 * component. This function will be called at init and
1916 * whenever the VMM need to relocate it self inside the GC.
1917 *
1918 * @param pVM The cross context VM structure.
1919 */
1920VMMR3_INT_DECL(void) HMR3Relocate(PVM pVM)
1921{
1922 Log(("HMR3Relocate to %RGv\n", MMHyperGetArea(pVM, 0)));
1923
1924 /* Fetch the current paging mode during the relocate callback during state loading. */
1925 if (VMR3GetState(pVM) == VMSTATE_LOADING)
1926 {
1927 for (VMCPUID i = 0; i < pVM->cCpus; i++)
1928 {
1929 PVMCPU pVCpu = &pVM->aCpus[i];
1930 pVCpu->hm.s.enmShadowMode = PGMGetShadowMode(pVCpu);
1931 }
1932 }
1933#if HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS)
1934 if (HMIsEnabled(pVM))
1935 {
1936 switch (PGMGetHostMode(pVM))
1937 {
1938 case PGMMODE_32_BIT:
1939 pVM->hm.s.pfnHost32ToGuest64R0 = VMMR3GetHostToGuestSwitcher(pVM, VMMSWITCHER_32_TO_AMD64);
1940 break;
1941
1942 case PGMMODE_PAE:
1943 case PGMMODE_PAE_NX:
1944 pVM->hm.s.pfnHost32ToGuest64R0 = VMMR3GetHostToGuestSwitcher(pVM, VMMSWITCHER_PAE_TO_AMD64);
1945 break;
1946
1947 default:
1948 AssertFailed();
1949 break;
1950 }
1951 }
1952#endif
1953 return;
1954}
1955
1956
1957/**
1958 * Terminates the HM.
1959 *
1960 * Termination means cleaning up and freeing all resources,
1961 * the VM itself is, at this point, powered off or suspended.
1962 *
1963 * @returns VBox status code.
1964 * @param pVM The cross context VM structure.
1965 */
1966VMMR3_INT_DECL(int) HMR3Term(PVM pVM)
1967{
1968 if (pVM->hm.s.vmx.pRealModeTSS)
1969 {
1970 PDMR3VmmDevHeapFree(pVM, pVM->hm.s.vmx.pRealModeTSS);
1971 pVM->hm.s.vmx.pRealModeTSS = 0;
1972 }
1973 hmR3TermCPU(pVM);
1974 return 0;
1975}
1976
1977
1978/**
1979 * Terminates the per-VCPU HM.
1980 *
1981 * @returns VBox status code.
1982 * @param pVM The cross context VM structure.
1983 */
1984static int hmR3TermCPU(PVM pVM)
1985{
1986 for (VMCPUID i = 0; i < pVM->cCpus; i++)
1987 {
1988 PVMCPU pVCpu = &pVM->aCpus[i]; NOREF(pVCpu);
1989
1990#ifdef VBOX_WITH_STATISTICS
1991 if (pVCpu->hm.s.paStatExitReason)
1992 {
1993 MMHyperFree(pVM, pVCpu->hm.s.paStatExitReason);
1994 pVCpu->hm.s.paStatExitReason = NULL;
1995 pVCpu->hm.s.paStatExitReasonR0 = NIL_RTR0PTR;
1996 }
1997 if (pVCpu->hm.s.paStatInjectedIrqs)
1998 {
1999 MMHyperFree(pVM, pVCpu->hm.s.paStatInjectedIrqs);
2000 pVCpu->hm.s.paStatInjectedIrqs = NULL;
2001 pVCpu->hm.s.paStatInjectedIrqsR0 = NIL_RTR0PTR;
2002 }
2003#endif
2004
2005#ifdef VBOX_WITH_CRASHDUMP_MAGIC
2006 memset(pVCpu->hm.s.vmx.VMCSCache.aMagic, 0, sizeof(pVCpu->hm.s.vmx.VMCSCache.aMagic));
2007 pVCpu->hm.s.vmx.VMCSCache.uMagic = 0;
2008 pVCpu->hm.s.vmx.VMCSCache.uPos = 0xffffffff;
2009#endif
2010 }
2011 return 0;
2012}
2013
2014
2015/**
2016 * Resets a virtual CPU.
2017 *
2018 * Used by HMR3Reset and CPU hot plugging.
2019 *
2020 * @param pVCpu The cross context virtual CPU structure to reset.
2021 */
2022VMMR3_INT_DECL(void) HMR3ResetCpu(PVMCPU pVCpu)
2023{
2024 /* Sync. entire state on VM reset R0-reentry. It's safe to reset
2025 the HM flags here, all other EMTs are in ring-3. See VMR3Reset(). */
2026 pVCpu->hm.s.fCtxChanged |= HM_CHANGED_HOST_CONTEXT | HM_CHANGED_ALL_GUEST;
2027
2028 pVCpu->hm.s.fActive = false;
2029 pVCpu->hm.s.Event.fPending = false;
2030 pVCpu->hm.s.vmx.fWasInRealMode = true;
2031 pVCpu->hm.s.vmx.u64MsrApicBase = 0;
2032 pVCpu->hm.s.vmx.fSwitchedTo64on32 = false;
2033
2034 /* Reset the contents of the read cache. */
2035 PVMCSCACHE pCache = &pVCpu->hm.s.vmx.VMCSCache;
2036 for (unsigned j = 0; j < pCache->Read.cValidEntries; j++)
2037 pCache->Read.aFieldVal[j] = 0;
2038
2039#ifdef VBOX_WITH_CRASHDUMP_MAGIC
2040 /* Magic marker for searching in crash dumps. */
2041 strcpy((char *)pCache->aMagic, "VMCSCACHE Magic");
2042 pCache->uMagic = UINT64_C(0xDEADBEEFDEADBEEF);
2043#endif
2044}
2045
2046
2047/**
2048 * The VM is being reset.
2049 *
2050 * For the HM component this means that any GDT/LDT/TSS monitors
2051 * needs to be removed.
2052 *
2053 * @param pVM The cross context VM structure.
2054 */
2055VMMR3_INT_DECL(void) HMR3Reset(PVM pVM)
2056{
2057 LogFlow(("HMR3Reset:\n"));
2058
2059 if (HMIsEnabled(pVM))
2060 hmR3DisableRawMode(pVM);
2061
2062 for (VMCPUID i = 0; i < pVM->cCpus; i++)
2063 {
2064 PVMCPU pVCpu = &pVM->aCpus[i];
2065
2066 HMR3ResetCpu(pVCpu);
2067 }
2068
2069 /* Clear all patch information. */
2070 pVM->hm.s.pGuestPatchMem = 0;
2071 pVM->hm.s.pFreeGuestPatchMem = 0;
2072 pVM->hm.s.cbGuestPatchMem = 0;
2073 pVM->hm.s.cPatches = 0;
2074 pVM->hm.s.PatchTree = 0;
2075 pVM->hm.s.fTPRPatchingActive = false;
2076 ASMMemZero32(pVM->hm.s.aPatches, sizeof(pVM->hm.s.aPatches));
2077}
2078
2079
2080/**
2081 * Callback to patch a TPR instruction (vmmcall or mov cr8).
2082 *
2083 * @returns VBox strict status code.
2084 * @param pVM The cross context VM structure.
2085 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
2086 * @param pvUser Unused.
2087 */
2088static DECLCALLBACK(VBOXSTRICTRC) hmR3RemovePatches(PVM pVM, PVMCPU pVCpu, void *pvUser)
2089{
2090 VMCPUID idCpu = (VMCPUID)(uintptr_t)pvUser;
2091
2092 /* Only execute the handler on the VCPU the original patch request was issued. */
2093 if (pVCpu->idCpu != idCpu)
2094 return VINF_SUCCESS;
2095
2096 Log(("hmR3RemovePatches\n"));
2097 for (unsigned i = 0; i < pVM->hm.s.cPatches; i++)
2098 {
2099 uint8_t abInstr[15];
2100 PHMTPRPATCH pPatch = &pVM->hm.s.aPatches[i];
2101 RTGCPTR pInstrGC = (RTGCPTR)pPatch->Core.Key;
2102 int rc;
2103
2104#ifdef LOG_ENABLED
2105 char szOutput[256];
2106 rc = DBGFR3DisasInstrEx(pVM->pUVM, pVCpu->idCpu, CPUMGetGuestCS(pVCpu), pInstrGC, DBGF_DISAS_FLAGS_DEFAULT_MODE,
2107 szOutput, sizeof(szOutput), NULL);
2108 if (RT_SUCCESS(rc))
2109 Log(("Patched instr: %s\n", szOutput));
2110#endif
2111
2112 /* Check if the instruction is still the same. */
2113 rc = PGMPhysSimpleReadGCPtr(pVCpu, abInstr, pInstrGC, pPatch->cbNewOp);
2114 if (rc != VINF_SUCCESS)
2115 {
2116 Log(("Patched code removed? (rc=%Rrc0\n", rc));
2117 continue; /* swapped out or otherwise removed; skip it. */
2118 }
2119
2120 if (memcmp(abInstr, pPatch->aNewOpcode, pPatch->cbNewOp))
2121 {
2122 Log(("Patched instruction was changed! (rc=%Rrc0\n", rc));
2123 continue; /* skip it. */
2124 }
2125
2126 rc = PGMPhysSimpleWriteGCPtr(pVCpu, pInstrGC, pPatch->aOpcode, pPatch->cbOp);
2127 AssertRC(rc);
2128
2129#ifdef LOG_ENABLED
2130 rc = DBGFR3DisasInstrEx(pVM->pUVM, pVCpu->idCpu, CPUMGetGuestCS(pVCpu), pInstrGC, DBGF_DISAS_FLAGS_DEFAULT_MODE,
2131 szOutput, sizeof(szOutput), NULL);
2132 if (RT_SUCCESS(rc))
2133 Log(("Original instr: %s\n", szOutput));
2134#endif
2135 }
2136 pVM->hm.s.cPatches = 0;
2137 pVM->hm.s.PatchTree = 0;
2138 pVM->hm.s.pFreeGuestPatchMem = pVM->hm.s.pGuestPatchMem;
2139 pVM->hm.s.fTPRPatchingActive = false;
2140 return VINF_SUCCESS;
2141}
2142
2143
2144/**
2145 * Worker for enabling patching in a VT-x/AMD-V guest.
2146 *
2147 * @returns VBox status code.
2148 * @param pVM The cross context VM structure.
2149 * @param idCpu VCPU to execute hmR3RemovePatches on.
2150 * @param pPatchMem Patch memory range.
2151 * @param cbPatchMem Size of the memory range.
2152 */
2153static int hmR3EnablePatching(PVM pVM, VMCPUID idCpu, RTRCPTR pPatchMem, unsigned cbPatchMem)
2154{
2155 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONE_BY_ONE, hmR3RemovePatches, (void *)(uintptr_t)idCpu);
2156 AssertRC(rc);
2157
2158 pVM->hm.s.pGuestPatchMem = pPatchMem;
2159 pVM->hm.s.pFreeGuestPatchMem = pPatchMem;
2160 pVM->hm.s.cbGuestPatchMem = cbPatchMem;
2161 return VINF_SUCCESS;
2162}
2163
2164
2165/**
2166 * Enable patching in a VT-x/AMD-V guest
2167 *
2168 * @returns VBox status code.
2169 * @param pVM The cross context VM structure.
2170 * @param pPatchMem Patch memory range.
2171 * @param cbPatchMem Size of the memory range.
2172 */
2173VMMR3_INT_DECL(int) HMR3EnablePatching(PVM pVM, RTGCPTR pPatchMem, unsigned cbPatchMem)
2174{
2175 VM_ASSERT_EMT(pVM);
2176 Log(("HMR3EnablePatching %RGv size %x\n", pPatchMem, cbPatchMem));
2177 if (pVM->cCpus > 1)
2178 {
2179 /* We own the IOM lock here and could cause a deadlock by waiting for a VCPU that is blocking on the IOM lock. */
2180 int rc = VMR3ReqCallNoWait(pVM, VMCPUID_ANY_QUEUE,
2181 (PFNRT)hmR3EnablePatching, 4, pVM, VMMGetCpuId(pVM), (RTRCPTR)pPatchMem, cbPatchMem);
2182 AssertRC(rc);
2183 return rc;
2184 }
2185 return hmR3EnablePatching(pVM, VMMGetCpuId(pVM), (RTRCPTR)pPatchMem, cbPatchMem);
2186}
2187
2188
2189/**
2190 * Disable patching in a VT-x/AMD-V guest.
2191 *
2192 * @returns VBox status code.
2193 * @param pVM The cross context VM structure.
2194 * @param pPatchMem Patch memory range.
2195 * @param cbPatchMem Size of the memory range.
2196 */
2197VMMR3_INT_DECL(int) HMR3DisablePatching(PVM pVM, RTGCPTR pPatchMem, unsigned cbPatchMem)
2198{
2199 Log(("HMR3DisablePatching %RGv size %x\n", pPatchMem, cbPatchMem));
2200 RT_NOREF2(pPatchMem, cbPatchMem);
2201
2202 Assert(pVM->hm.s.pGuestPatchMem == pPatchMem);
2203 Assert(pVM->hm.s.cbGuestPatchMem == cbPatchMem);
2204
2205 /** @todo Potential deadlock when other VCPUs are waiting on the IOM lock (we own it)!! */
2206 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONE_BY_ONE, hmR3RemovePatches,
2207 (void *)(uintptr_t)VMMGetCpuId(pVM));
2208 AssertRC(rc);
2209
2210 pVM->hm.s.pGuestPatchMem = 0;
2211 pVM->hm.s.pFreeGuestPatchMem = 0;
2212 pVM->hm.s.cbGuestPatchMem = 0;
2213 pVM->hm.s.fTPRPatchingActive = false;
2214 return VINF_SUCCESS;
2215}
2216
2217
2218/**
2219 * Callback to patch a TPR instruction (vmmcall or mov cr8).
2220 *
2221 * @returns VBox strict status code.
2222 * @param pVM The cross context VM structure.
2223 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
2224 * @param pvUser User specified CPU context.
2225 *
2226 */
2227static DECLCALLBACK(VBOXSTRICTRC) hmR3ReplaceTprInstr(PVM pVM, PVMCPU pVCpu, void *pvUser)
2228{
2229 /*
2230 * Only execute the handler on the VCPU the original patch request was
2231 * issued. (The other CPU(s) might not yet have switched to protected
2232 * mode, nor have the correct memory context.)
2233 */
2234 VMCPUID idCpu = (VMCPUID)(uintptr_t)pvUser;
2235 if (pVCpu->idCpu != idCpu)
2236 return VINF_SUCCESS;
2237
2238 /*
2239 * We're racing other VCPUs here, so don't try patch the instruction twice
2240 * and make sure there is still room for our patch record.
2241 */
2242 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
2243 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
2244 if (pPatch)
2245 {
2246 Log(("hmR3ReplaceTprInstr: already patched %RGv\n", pCtx->rip));
2247 return VINF_SUCCESS;
2248 }
2249 uint32_t const idx = pVM->hm.s.cPatches;
2250 if (idx >= RT_ELEMENTS(pVM->hm.s.aPatches))
2251 {
2252 Log(("hmR3ReplaceTprInstr: no available patch slots (%RGv)\n", pCtx->rip));
2253 return VINF_SUCCESS;
2254 }
2255 pPatch = &pVM->hm.s.aPatches[idx];
2256
2257 Log(("hmR3ReplaceTprInstr: rip=%RGv idxPatch=%u\n", pCtx->rip, idx));
2258
2259 /*
2260 * Disassembler the instruction and get cracking.
2261 */
2262 DBGFR3_DISAS_INSTR_CUR_LOG(pVCpu, "hmR3ReplaceTprInstr");
2263 PDISCPUSTATE pDis = &pVCpu->hm.s.DisState;
2264 uint32_t cbOp;
2265 int rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, &cbOp);
2266 AssertRC(rc);
2267 if ( rc == VINF_SUCCESS
2268 && pDis->pCurInstr->uOpcode == OP_MOV
2269 && cbOp >= 3)
2270 {
2271 static uint8_t const s_abVMMCall[3] = { 0x0f, 0x01, 0xd9 };
2272
2273 rc = PGMPhysSimpleReadGCPtr(pVCpu, pPatch->aOpcode, pCtx->rip, cbOp);
2274 AssertRC(rc);
2275
2276 pPatch->cbOp = cbOp;
2277
2278 if (pDis->Param1.fUse == DISUSE_DISPLACEMENT32)
2279 {
2280 /* write. */
2281 if (pDis->Param2.fUse == DISUSE_REG_GEN32)
2282 {
2283 pPatch->enmType = HMTPRINSTR_WRITE_REG;
2284 pPatch->uSrcOperand = pDis->Param2.Base.idxGenReg;
2285 Log(("hmR3ReplaceTprInstr: HMTPRINSTR_WRITE_REG %u\n", pDis->Param2.Base.idxGenReg));
2286 }
2287 else
2288 {
2289 Assert(pDis->Param2.fUse == DISUSE_IMMEDIATE32);
2290 pPatch->enmType = HMTPRINSTR_WRITE_IMM;
2291 pPatch->uSrcOperand = pDis->Param2.uValue;
2292 Log(("hmR3ReplaceTprInstr: HMTPRINSTR_WRITE_IMM %#llx\n", pDis->Param2.uValue));
2293 }
2294 rc = PGMPhysSimpleWriteGCPtr(pVCpu, pCtx->rip, s_abVMMCall, sizeof(s_abVMMCall));
2295 AssertRC(rc);
2296
2297 memcpy(pPatch->aNewOpcode, s_abVMMCall, sizeof(s_abVMMCall));
2298 pPatch->cbNewOp = sizeof(s_abVMMCall);
2299 STAM_COUNTER_INC(&pVM->hm.s.StatTprReplaceSuccessVmc);
2300 }
2301 else
2302 {
2303 /*
2304 * TPR Read.
2305 *
2306 * Found:
2307 * mov eax, dword [fffe0080] (5 bytes)
2308 * Check if next instruction is:
2309 * shr eax, 4
2310 */
2311 Assert(pDis->Param1.fUse == DISUSE_REG_GEN32);
2312
2313 uint8_t const idxMmioReg = pDis->Param1.Base.idxGenReg;
2314 uint8_t const cbOpMmio = cbOp;
2315 uint64_t const uSavedRip = pCtx->rip;
2316
2317 pCtx->rip += cbOp;
2318 rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, &cbOp);
2319 DBGFR3_DISAS_INSTR_CUR_LOG(pVCpu, "Following read");
2320 pCtx->rip = uSavedRip;
2321
2322 if ( rc == VINF_SUCCESS
2323 && pDis->pCurInstr->uOpcode == OP_SHR
2324 && pDis->Param1.fUse == DISUSE_REG_GEN32
2325 && pDis->Param1.Base.idxGenReg == idxMmioReg
2326 && pDis->Param2.fUse == DISUSE_IMMEDIATE8
2327 && pDis->Param2.uValue == 4
2328 && cbOpMmio + cbOp < sizeof(pVM->hm.s.aPatches[idx].aOpcode))
2329 {
2330 uint8_t abInstr[15];
2331
2332 /* Replacing the two instructions above with an AMD-V specific lock-prefixed 32-bit MOV CR8 instruction so as to
2333 access CR8 in 32-bit mode and not cause a #VMEXIT. */
2334 rc = PGMPhysSimpleReadGCPtr(pVCpu, &pPatch->aOpcode, pCtx->rip, cbOpMmio + cbOp);
2335 AssertRC(rc);
2336
2337 pPatch->cbOp = cbOpMmio + cbOp;
2338
2339 /* 0xF0, 0x0F, 0x20, 0xC0 = mov eax, cr8 */
2340 abInstr[0] = 0xF0;
2341 abInstr[1] = 0x0F;
2342 abInstr[2] = 0x20;
2343 abInstr[3] = 0xC0 | pDis->Param1.Base.idxGenReg;
2344 for (unsigned i = 4; i < pPatch->cbOp; i++)
2345 abInstr[i] = 0x90; /* nop */
2346
2347 rc = PGMPhysSimpleWriteGCPtr(pVCpu, pCtx->rip, abInstr, pPatch->cbOp);
2348 AssertRC(rc);
2349
2350 memcpy(pPatch->aNewOpcode, abInstr, pPatch->cbOp);
2351 pPatch->cbNewOp = pPatch->cbOp;
2352 STAM_COUNTER_INC(&pVM->hm.s.StatTprReplaceSuccessCr8);
2353
2354 Log(("Acceptable read/shr candidate!\n"));
2355 pPatch->enmType = HMTPRINSTR_READ_SHR4;
2356 }
2357 else
2358 {
2359 pPatch->enmType = HMTPRINSTR_READ;
2360 pPatch->uDstOperand = idxMmioReg;
2361
2362 rc = PGMPhysSimpleWriteGCPtr(pVCpu, pCtx->rip, s_abVMMCall, sizeof(s_abVMMCall));
2363 AssertRC(rc);
2364
2365 memcpy(pPatch->aNewOpcode, s_abVMMCall, sizeof(s_abVMMCall));
2366 pPatch->cbNewOp = sizeof(s_abVMMCall);
2367 STAM_COUNTER_INC(&pVM->hm.s.StatTprReplaceSuccessVmc);
2368 Log(("hmR3ReplaceTprInstr: HMTPRINSTR_READ %u\n", pPatch->uDstOperand));
2369 }
2370 }
2371
2372 pPatch->Core.Key = pCtx->eip;
2373 rc = RTAvloU32Insert(&pVM->hm.s.PatchTree, &pPatch->Core);
2374 AssertRC(rc);
2375
2376 pVM->hm.s.cPatches++;
2377 return VINF_SUCCESS;
2378 }
2379
2380 /*
2381 * Save invalid patch, so we will not try again.
2382 */
2383 Log(("hmR3ReplaceTprInstr: Failed to patch instr!\n"));
2384 pPatch->Core.Key = pCtx->eip;
2385 pPatch->enmType = HMTPRINSTR_INVALID;
2386 rc = RTAvloU32Insert(&pVM->hm.s.PatchTree, &pPatch->Core);
2387 AssertRC(rc);
2388 pVM->hm.s.cPatches++;
2389 STAM_COUNTER_INC(&pVM->hm.s.StatTprReplaceFailure);
2390 return VINF_SUCCESS;
2391}
2392
2393
2394/**
2395 * Callback to patch a TPR instruction (jump to generated code).
2396 *
2397 * @returns VBox strict status code.
2398 * @param pVM The cross context VM structure.
2399 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
2400 * @param pvUser User specified CPU context.
2401 *
2402 */
2403static DECLCALLBACK(VBOXSTRICTRC) hmR3PatchTprInstr(PVM pVM, PVMCPU pVCpu, void *pvUser)
2404{
2405 /*
2406 * Only execute the handler on the VCPU the original patch request was
2407 * issued. (The other CPU(s) might not yet have switched to protected
2408 * mode, nor have the correct memory context.)
2409 */
2410 VMCPUID idCpu = (VMCPUID)(uintptr_t)pvUser;
2411 if (pVCpu->idCpu != idCpu)
2412 return VINF_SUCCESS;
2413
2414 /*
2415 * We're racing other VCPUs here, so don't try patch the instruction twice
2416 * and make sure there is still room for our patch record.
2417 */
2418 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
2419 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
2420 if (pPatch)
2421 {
2422 Log(("hmR3PatchTprInstr: already patched %RGv\n", pCtx->rip));
2423 return VINF_SUCCESS;
2424 }
2425 uint32_t const idx = pVM->hm.s.cPatches;
2426 if (idx >= RT_ELEMENTS(pVM->hm.s.aPatches))
2427 {
2428 Log(("hmR3PatchTprInstr: no available patch slots (%RGv)\n", pCtx->rip));
2429 return VINF_SUCCESS;
2430 }
2431 pPatch = &pVM->hm.s.aPatches[idx];
2432
2433 Log(("hmR3PatchTprInstr: rip=%RGv idxPatch=%u\n", pCtx->rip, idx));
2434 DBGFR3_DISAS_INSTR_CUR_LOG(pVCpu, "hmR3PatchTprInstr");
2435
2436 /*
2437 * Disassemble the instruction and get cracking.
2438 */
2439 PDISCPUSTATE pDis = &pVCpu->hm.s.DisState;
2440 uint32_t cbOp;
2441 int rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, &cbOp);
2442 AssertRC(rc);
2443 if ( rc == VINF_SUCCESS
2444 && pDis->pCurInstr->uOpcode == OP_MOV
2445 && cbOp >= 5)
2446 {
2447 uint8_t aPatch[64];
2448 uint32_t off = 0;
2449
2450 rc = PGMPhysSimpleReadGCPtr(pVCpu, pPatch->aOpcode, pCtx->rip, cbOp);
2451 AssertRC(rc);
2452
2453 pPatch->cbOp = cbOp;
2454 pPatch->enmType = HMTPRINSTR_JUMP_REPLACEMENT;
2455
2456 if (pDis->Param1.fUse == DISUSE_DISPLACEMENT32)
2457 {
2458 /*
2459 * TPR write:
2460 *
2461 * push ECX [51]
2462 * push EDX [52]
2463 * push EAX [50]
2464 * xor EDX,EDX [31 D2]
2465 * mov EAX,EAX [89 C0]
2466 * or
2467 * mov EAX,0000000CCh [B8 CC 00 00 00]
2468 * mov ECX,0C0000082h [B9 82 00 00 C0]
2469 * wrmsr [0F 30]
2470 * pop EAX [58]
2471 * pop EDX [5A]
2472 * pop ECX [59]
2473 * jmp return_address [E9 return_address]
2474 */
2475 bool fUsesEax = (pDis->Param2.fUse == DISUSE_REG_GEN32 && pDis->Param2.Base.idxGenReg == DISGREG_EAX);
2476
2477 aPatch[off++] = 0x51; /* push ecx */
2478 aPatch[off++] = 0x52; /* push edx */
2479 if (!fUsesEax)
2480 aPatch[off++] = 0x50; /* push eax */
2481 aPatch[off++] = 0x31; /* xor edx, edx */
2482 aPatch[off++] = 0xD2;
2483 if (pDis->Param2.fUse == DISUSE_REG_GEN32)
2484 {
2485 if (!fUsesEax)
2486 {
2487 aPatch[off++] = 0x89; /* mov eax, src_reg */
2488 aPatch[off++] = MAKE_MODRM(3, pDis->Param2.Base.idxGenReg, DISGREG_EAX);
2489 }
2490 }
2491 else
2492 {
2493 Assert(pDis->Param2.fUse == DISUSE_IMMEDIATE32);
2494 aPatch[off++] = 0xB8; /* mov eax, immediate */
2495 *(uint32_t *)&aPatch[off] = pDis->Param2.uValue;
2496 off += sizeof(uint32_t);
2497 }
2498 aPatch[off++] = 0xB9; /* mov ecx, 0xc0000082 */
2499 *(uint32_t *)&aPatch[off] = MSR_K8_LSTAR;
2500 off += sizeof(uint32_t);
2501
2502 aPatch[off++] = 0x0F; /* wrmsr */
2503 aPatch[off++] = 0x30;
2504 if (!fUsesEax)
2505 aPatch[off++] = 0x58; /* pop eax */
2506 aPatch[off++] = 0x5A; /* pop edx */
2507 aPatch[off++] = 0x59; /* pop ecx */
2508 }
2509 else
2510 {
2511 /*
2512 * TPR read:
2513 *
2514 * push ECX [51]
2515 * push EDX [52]
2516 * push EAX [50]
2517 * mov ECX,0C0000082h [B9 82 00 00 C0]
2518 * rdmsr [0F 32]
2519 * mov EAX,EAX [89 C0]
2520 * pop EAX [58]
2521 * pop EDX [5A]
2522 * pop ECX [59]
2523 * jmp return_address [E9 return_address]
2524 */
2525 Assert(pDis->Param1.fUse == DISUSE_REG_GEN32);
2526
2527 if (pDis->Param1.Base.idxGenReg != DISGREG_ECX)
2528 aPatch[off++] = 0x51; /* push ecx */
2529 if (pDis->Param1.Base.idxGenReg != DISGREG_EDX )
2530 aPatch[off++] = 0x52; /* push edx */
2531 if (pDis->Param1.Base.idxGenReg != DISGREG_EAX)
2532 aPatch[off++] = 0x50; /* push eax */
2533
2534 aPatch[off++] = 0x31; /* xor edx, edx */
2535 aPatch[off++] = 0xD2;
2536
2537 aPatch[off++] = 0xB9; /* mov ecx, 0xc0000082 */
2538 *(uint32_t *)&aPatch[off] = MSR_K8_LSTAR;
2539 off += sizeof(uint32_t);
2540
2541 aPatch[off++] = 0x0F; /* rdmsr */
2542 aPatch[off++] = 0x32;
2543
2544 if (pDis->Param1.Base.idxGenReg != DISGREG_EAX)
2545 {
2546 aPatch[off++] = 0x89; /* mov dst_reg, eax */
2547 aPatch[off++] = MAKE_MODRM(3, DISGREG_EAX, pDis->Param1.Base.idxGenReg);
2548 }
2549
2550 if (pDis->Param1.Base.idxGenReg != DISGREG_EAX)
2551 aPatch[off++] = 0x58; /* pop eax */
2552 if (pDis->Param1.Base.idxGenReg != DISGREG_EDX )
2553 aPatch[off++] = 0x5A; /* pop edx */
2554 if (pDis->Param1.Base.idxGenReg != DISGREG_ECX)
2555 aPatch[off++] = 0x59; /* pop ecx */
2556 }
2557 aPatch[off++] = 0xE9; /* jmp return_address */
2558 *(RTRCUINTPTR *)&aPatch[off] = ((RTRCUINTPTR)pCtx->eip + cbOp) - ((RTRCUINTPTR)pVM->hm.s.pFreeGuestPatchMem + off + 4);
2559 off += sizeof(RTRCUINTPTR);
2560
2561 if (pVM->hm.s.pFreeGuestPatchMem + off <= pVM->hm.s.pGuestPatchMem + pVM->hm.s.cbGuestPatchMem)
2562 {
2563 /* Write new code to the patch buffer. */
2564 rc = PGMPhysSimpleWriteGCPtr(pVCpu, pVM->hm.s.pFreeGuestPatchMem, aPatch, off);
2565 AssertRC(rc);
2566
2567#ifdef LOG_ENABLED
2568 uint32_t cbCurInstr;
2569 for (RTGCPTR GCPtrInstr = pVM->hm.s.pFreeGuestPatchMem;
2570 GCPtrInstr < pVM->hm.s.pFreeGuestPatchMem + off;
2571 GCPtrInstr += RT_MAX(cbCurInstr, 1))
2572 {
2573 char szOutput[256];
2574 rc = DBGFR3DisasInstrEx(pVM->pUVM, pVCpu->idCpu, pCtx->cs.Sel, GCPtrInstr, DBGF_DISAS_FLAGS_DEFAULT_MODE,
2575 szOutput, sizeof(szOutput), &cbCurInstr);
2576 if (RT_SUCCESS(rc))
2577 Log(("Patch instr %s\n", szOutput));
2578 else
2579 Log(("%RGv: rc=%Rrc\n", GCPtrInstr, rc));
2580 }
2581#endif
2582
2583 pPatch->aNewOpcode[0] = 0xE9;
2584 *(RTRCUINTPTR *)&pPatch->aNewOpcode[1] = ((RTRCUINTPTR)pVM->hm.s.pFreeGuestPatchMem) - ((RTRCUINTPTR)pCtx->eip + 5);
2585
2586 /* Overwrite the TPR instruction with a jump. */
2587 rc = PGMPhysSimpleWriteGCPtr(pVCpu, pCtx->eip, pPatch->aNewOpcode, 5);
2588 AssertRC(rc);
2589
2590 DBGFR3_DISAS_INSTR_CUR_LOG(pVCpu, "Jump");
2591
2592 pVM->hm.s.pFreeGuestPatchMem += off;
2593 pPatch->cbNewOp = 5;
2594
2595 pPatch->Core.Key = pCtx->eip;
2596 rc = RTAvloU32Insert(&pVM->hm.s.PatchTree, &pPatch->Core);
2597 AssertRC(rc);
2598
2599 pVM->hm.s.cPatches++;
2600 pVM->hm.s.fTPRPatchingActive = true;
2601 STAM_COUNTER_INC(&pVM->hm.s.StatTprPatchSuccess);
2602 return VINF_SUCCESS;
2603 }
2604
2605 Log(("Ran out of space in our patch buffer!\n"));
2606 }
2607 else
2608 Log(("hmR3PatchTprInstr: Failed to patch instr!\n"));
2609
2610
2611 /*
2612 * Save invalid patch, so we will not try again.
2613 */
2614 pPatch = &pVM->hm.s.aPatches[idx];
2615 pPatch->Core.Key = pCtx->eip;
2616 pPatch->enmType = HMTPRINSTR_INVALID;
2617 rc = RTAvloU32Insert(&pVM->hm.s.PatchTree, &pPatch->Core);
2618 AssertRC(rc);
2619 pVM->hm.s.cPatches++;
2620 STAM_COUNTER_INC(&pVM->hm.s.StatTprPatchFailure);
2621 return VINF_SUCCESS;
2622}
2623
2624
2625/**
2626 * Attempt to patch TPR mmio instructions.
2627 *
2628 * @returns VBox status code.
2629 * @param pVM The cross context VM structure.
2630 * @param pVCpu The cross context virtual CPU structure.
2631 */
2632VMMR3_INT_DECL(int) HMR3PatchTprInstr(PVM pVM, PVMCPU pVCpu)
2633{
2634 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONE_BY_ONE,
2635 pVM->hm.s.pGuestPatchMem ? hmR3PatchTprInstr : hmR3ReplaceTprInstr,
2636 (void *)(uintptr_t)pVCpu->idCpu);
2637 AssertRC(rc);
2638 return rc;
2639}
2640
2641
2642/**
2643 * Checks if a code selector (CS) is suitable for execution
2644 * within VMX when unrestricted execution isn't available.
2645 *
2646 * @returns true if selector is suitable for VMX, otherwise
2647 * false.
2648 * @param pSel Pointer to the selector to check (CS).
2649 * @param uStackDpl The CPL, aka the DPL of the stack segment.
2650 */
2651static bool hmR3IsCodeSelectorOkForVmx(PCPUMSELREG pSel, unsigned uStackDpl)
2652{
2653 /*
2654 * Segment must be an accessed code segment, it must be present and it must
2655 * be usable.
2656 * Note! These are all standard requirements and if CS holds anything else
2657 * we've got buggy code somewhere!
2658 */
2659 AssertCompile(X86DESCATTR_TYPE == 0xf);
2660 AssertMsgReturn( (pSel->Attr.u & (X86_SEL_TYPE_ACCESSED | X86_SEL_TYPE_CODE | X86DESCATTR_DT | X86DESCATTR_P | X86DESCATTR_UNUSABLE))
2661 == (X86_SEL_TYPE_ACCESSED | X86_SEL_TYPE_CODE | X86DESCATTR_DT | X86DESCATTR_P),
2662 ("%#x\n", pSel->Attr.u),
2663 false);
2664
2665 /* For conforming segments, CS.DPL must be <= SS.DPL, while CS.DPL
2666 must equal SS.DPL for non-confroming segments.
2667 Note! This is also a hard requirement like above. */
2668 AssertMsgReturn( pSel->Attr.n.u4Type & X86_SEL_TYPE_CONF
2669 ? pSel->Attr.n.u2Dpl <= uStackDpl
2670 : pSel->Attr.n.u2Dpl == uStackDpl,
2671 ("u4Type=%#x u2Dpl=%u uStackDpl=%u\n", pSel->Attr.n.u4Type, pSel->Attr.n.u2Dpl, uStackDpl),
2672 false);
2673
2674 /*
2675 * The following two requirements are VT-x specific:
2676 * - G bit must be set if any high limit bits are set.
2677 * - G bit must be clear if any low limit bits are clear.
2678 */
2679 if ( ((pSel->u32Limit & 0xfff00000) == 0x00000000 || pSel->Attr.n.u1Granularity)
2680 && ((pSel->u32Limit & 0x00000fff) == 0x00000fff || !pSel->Attr.n.u1Granularity))
2681 return true;
2682 return false;
2683}
2684
2685
2686/**
2687 * Checks if a data selector (DS/ES/FS/GS) is suitable for
2688 * execution within VMX when unrestricted execution isn't
2689 * available.
2690 *
2691 * @returns true if selector is suitable for VMX, otherwise
2692 * false.
2693 * @param pSel Pointer to the selector to check
2694 * (DS/ES/FS/GS).
2695 */
2696static bool hmR3IsDataSelectorOkForVmx(PCPUMSELREG pSel)
2697{
2698 /*
2699 * Unusable segments are OK. These days they should be marked as such, as
2700 * but as an alternative we for old saved states and AMD<->VT-x migration
2701 * we also treat segments with all the attributes cleared as unusable.
2702 */
2703 if (pSel->Attr.n.u1Unusable || !pSel->Attr.u)
2704 return true;
2705
2706 /** @todo tighten these checks. Will require CPUM load adjusting. */
2707
2708 /* Segment must be accessed. */
2709 if (pSel->Attr.u & X86_SEL_TYPE_ACCESSED)
2710 {
2711 /* Code segments must also be readable. */
2712 if ( !(pSel->Attr.u & X86_SEL_TYPE_CODE)
2713 || (pSel->Attr.u & X86_SEL_TYPE_READ))
2714 {
2715 /* The S bit must be set. */
2716 if (pSel->Attr.n.u1DescType)
2717 {
2718 /* Except for conforming segments, DPL >= RPL. */
2719 if ( pSel->Attr.n.u2Dpl >= (pSel->Sel & X86_SEL_RPL)
2720 || pSel->Attr.n.u4Type >= X86_SEL_TYPE_ER_ACC)
2721 {
2722 /* Segment must be present. */
2723 if (pSel->Attr.n.u1Present)
2724 {
2725 /*
2726 * The following two requirements are VT-x specific:
2727 * - G bit must be set if any high limit bits are set.
2728 * - G bit must be clear if any low limit bits are clear.
2729 */
2730 if ( ((pSel->u32Limit & 0xfff00000) == 0x00000000 || pSel->Attr.n.u1Granularity)
2731 && ((pSel->u32Limit & 0x00000fff) == 0x00000fff || !pSel->Attr.n.u1Granularity))
2732 return true;
2733 }
2734 }
2735 }
2736 }
2737 }
2738
2739 return false;
2740}
2741
2742
2743/**
2744 * Checks if the stack selector (SS) is suitable for execution
2745 * within VMX when unrestricted execution isn't available.
2746 *
2747 * @returns true if selector is suitable for VMX, otherwise
2748 * false.
2749 * @param pSel Pointer to the selector to check (SS).
2750 */
2751static bool hmR3IsStackSelectorOkForVmx(PCPUMSELREG pSel)
2752{
2753 /*
2754 * Unusable segments are OK. These days they should be marked as such, as
2755 * but as an alternative we for old saved states and AMD<->VT-x migration
2756 * we also treat segments with all the attributes cleared as unusable.
2757 */
2758 /** @todo r=bird: actually all zeroes isn't gonna cut it... SS.DPL == CPL. */
2759 if (pSel->Attr.n.u1Unusable || !pSel->Attr.u)
2760 return true;
2761
2762 /*
2763 * Segment must be an accessed writable segment, it must be present.
2764 * Note! These are all standard requirements and if SS holds anything else
2765 * we've got buggy code somewhere!
2766 */
2767 AssertCompile(X86DESCATTR_TYPE == 0xf);
2768 AssertMsgReturn( (pSel->Attr.u & (X86_SEL_TYPE_ACCESSED | X86_SEL_TYPE_WRITE | X86DESCATTR_DT | X86DESCATTR_P | X86_SEL_TYPE_CODE))
2769 == (X86_SEL_TYPE_ACCESSED | X86_SEL_TYPE_WRITE | X86DESCATTR_DT | X86DESCATTR_P),
2770 ("%#x\n", pSel->Attr.u), false);
2771
2772 /* DPL must equal RPL.
2773 Note! This is also a hard requirement like above. */
2774 AssertMsgReturn(pSel->Attr.n.u2Dpl == (pSel->Sel & X86_SEL_RPL),
2775 ("u2Dpl=%u Sel=%#x\n", pSel->Attr.n.u2Dpl, pSel->Sel), false);
2776
2777 /*
2778 * The following two requirements are VT-x specific:
2779 * - G bit must be set if any high limit bits are set.
2780 * - G bit must be clear if any low limit bits are clear.
2781 */
2782 if ( ((pSel->u32Limit & 0xfff00000) == 0x00000000 || pSel->Attr.n.u1Granularity)
2783 && ((pSel->u32Limit & 0x00000fff) == 0x00000fff || !pSel->Attr.n.u1Granularity))
2784 return true;
2785 return false;
2786}
2787
2788
2789/**
2790 * Checks if we can currently use hardware accelerated raw mode.
2791 *
2792 * @returns true if we can currently use hardware acceleration, otherwise false.
2793 * @param pVM The cross context VM structure.
2794 * @param pCtx Partial VM execution context.
2795 */
2796VMMR3DECL(bool) HMR3CanExecuteGuest(PVM pVM, PCPUMCTX pCtx)
2797{
2798 PVMCPU pVCpu = VMMGetCpu(pVM);
2799
2800 Assert(HMIsEnabled(pVM));
2801
2802#ifdef VBOX_WITH_NESTED_HWVIRT_ONLY_IN_IEM
2803 if (CPUMIsGuestInNestedHwVirtMode(pCtx))
2804 {
2805 Log(("HMR3CanExecuteGuest: In nested-guest mode - returning false"));
2806 return false;
2807 }
2808#endif
2809
2810 /* AMD-V supports real & protected mode with or without paging. */
2811 if (pVM->hm.s.svm.fEnabled)
2812 {
2813 pVCpu->hm.s.fActive = true;
2814 return true;
2815 }
2816
2817 pVCpu->hm.s.fActive = false;
2818
2819 /* Note! The context supplied by REM is partial. If we add more checks here, be sure to verify that REM provides this info! */
2820 Assert( (pVM->hm.s.vmx.fUnrestrictedGuest && !pVM->hm.s.vmx.pRealModeTSS)
2821 || (!pVM->hm.s.vmx.fUnrestrictedGuest && pVM->hm.s.vmx.pRealModeTSS));
2822
2823 bool fSupportsRealMode = pVM->hm.s.vmx.fUnrestrictedGuest || PDMVmmDevHeapIsEnabled(pVM);
2824 if (!pVM->hm.s.vmx.fUnrestrictedGuest)
2825 {
2826 /*
2827 * The VMM device heap is a requirement for emulating real mode or protected mode without paging with the unrestricted
2828 * guest execution feature is missing (VT-x only).
2829 */
2830 if (fSupportsRealMode)
2831 {
2832 if (CPUMIsGuestInRealModeEx(pCtx))
2833 {
2834 /*
2835 * In V86 mode (VT-x or not), the CPU enforces real-mode compatible selector
2836 * bases and limits, i.e. limit must be 64K and base must be selector * 16.
2837 * If this is not true, we cannot execute real mode as V86 and have to fall
2838 * back to emulation.
2839 */
2840 if ( pCtx->cs.Sel != (pCtx->cs.u64Base >> 4)
2841 || pCtx->ds.Sel != (pCtx->ds.u64Base >> 4)
2842 || pCtx->es.Sel != (pCtx->es.u64Base >> 4)
2843 || pCtx->ss.Sel != (pCtx->ss.u64Base >> 4)
2844 || pCtx->fs.Sel != (pCtx->fs.u64Base >> 4)
2845 || pCtx->gs.Sel != (pCtx->gs.u64Base >> 4))
2846 {
2847 STAM_COUNTER_INC(&pVCpu->hm.s.StatVmxCheckBadRmSelBase);
2848 return false;
2849 }
2850 if ( (pCtx->cs.u32Limit != 0xffff)
2851 || (pCtx->ds.u32Limit != 0xffff)
2852 || (pCtx->es.u32Limit != 0xffff)
2853 || (pCtx->ss.u32Limit != 0xffff)
2854 || (pCtx->fs.u32Limit != 0xffff)
2855 || (pCtx->gs.u32Limit != 0xffff))
2856 {
2857 STAM_COUNTER_INC(&pVCpu->hm.s.StatVmxCheckBadRmSelLimit);
2858 return false;
2859 }
2860 STAM_COUNTER_INC(&pVCpu->hm.s.StatVmxCheckRmOk);
2861 }
2862 else
2863 {
2864 /*
2865 * Verify the requirements for executing code in protected mode. VT-x can't
2866 * handle the CPU state right after a switch from real to protected mode
2867 * (all sorts of RPL & DPL assumptions).
2868 */
2869 if (pVCpu->hm.s.vmx.fWasInRealMode)
2870 {
2871 /** @todo If guest is in V86 mode, these checks should be different! */
2872 if ((pCtx->cs.Sel & X86_SEL_RPL) != (pCtx->ss.Sel & X86_SEL_RPL))
2873 {
2874 STAM_COUNTER_INC(&pVCpu->hm.s.StatVmxCheckBadRpl);
2875 return false;
2876 }
2877 if ( !hmR3IsCodeSelectorOkForVmx(&pCtx->cs, pCtx->ss.Attr.n.u2Dpl)
2878 || !hmR3IsDataSelectorOkForVmx(&pCtx->ds)
2879 || !hmR3IsDataSelectorOkForVmx(&pCtx->es)
2880 || !hmR3IsDataSelectorOkForVmx(&pCtx->fs)
2881 || !hmR3IsDataSelectorOkForVmx(&pCtx->gs)
2882 || !hmR3IsStackSelectorOkForVmx(&pCtx->ss))
2883 {
2884 STAM_COUNTER_INC(&pVCpu->hm.s.StatVmxCheckBadSel);
2885 return false;
2886 }
2887 }
2888 /* VT-x also chokes on invalid TR or LDTR selectors (minix). */
2889 if (pCtx->gdtr.cbGdt)
2890 {
2891 if ((pCtx->tr.Sel | X86_SEL_RPL_LDT) > pCtx->gdtr.cbGdt)
2892 {
2893 STAM_COUNTER_INC(&pVCpu->hm.s.StatVmxCheckBadTr);
2894 return false;
2895 }
2896 else if ((pCtx->ldtr.Sel | X86_SEL_RPL_LDT) > pCtx->gdtr.cbGdt)
2897 {
2898 STAM_COUNTER_INC(&pVCpu->hm.s.StatVmxCheckBadLdt);
2899 return false;
2900 }
2901 }
2902 STAM_COUNTER_INC(&pVCpu->hm.s.StatVmxCheckPmOk);
2903 }
2904 }
2905 else
2906 {
2907 if ( !CPUMIsGuestInLongModeEx(pCtx)
2908 && !pVM->hm.s.vmx.fUnrestrictedGuest)
2909 {
2910 if ( !pVM->hm.s.fNestedPaging /* Requires a fake PD for real *and* protected mode without paging - stored in the VMM device heap */
2911 || CPUMIsGuestInRealModeEx(pCtx)) /* Requires a fake TSS for real mode - stored in the VMM device heap */
2912 return false;
2913
2914 /* Too early for VT-x; Solaris guests will fail with a guru meditation otherwise; same for XP. */
2915 if (pCtx->idtr.pIdt == 0 || pCtx->idtr.cbIdt == 0 || pCtx->tr.Sel == 0)
2916 return false;
2917
2918 /*
2919 * The guest is about to complete the switch to protected mode. Wait a bit longer.
2920 * Windows XP; switch to protected mode; all selectors are marked not present
2921 * in the hidden registers (possible recompiler bug; see load_seg_vm).
2922 */
2923 /** @todo Is this supposed recompiler bug still relevant with IEM? */
2924 if (pCtx->cs.Attr.n.u1Present == 0)
2925 return false;
2926 if (pCtx->ss.Attr.n.u1Present == 0)
2927 return false;
2928
2929 /*
2930 * Windows XP: possible same as above, but new recompiler requires new
2931 * heuristics? VT-x doesn't seem to like something about the guest state and
2932 * this stuff avoids it.
2933 */
2934 /** @todo This check is actually wrong, it doesn't take the direction of the
2935 * stack segment into account. But, it does the job for now. */
2936 if (pCtx->rsp >= pCtx->ss.u32Limit)
2937 return false;
2938 }
2939 }
2940 }
2941
2942 if (pVM->hm.s.vmx.fEnabled)
2943 {
2944 uint32_t uCR0Mask;
2945
2946 /* If bit N is set in cr0_fixed0, then it must be set in the guest's cr0. */
2947 uCR0Mask = (uint32_t)pVM->hm.s.vmx.Msrs.u64Cr0Fixed0;
2948
2949 /* We ignore the NE bit here on purpose; see HMR0.cpp for details. */
2950 uCR0Mask &= ~X86_CR0_NE;
2951
2952 if (fSupportsRealMode)
2953 {
2954 /* We ignore the PE & PG bits here on purpose; we emulate real and protected mode without paging. */
2955 uCR0Mask &= ~(X86_CR0_PG|X86_CR0_PE);
2956 }
2957 else
2958 {
2959 /* We support protected mode without paging using identity mapping. */
2960 uCR0Mask &= ~X86_CR0_PG;
2961 }
2962 if ((pCtx->cr0 & uCR0Mask) != uCR0Mask)
2963 return false;
2964
2965 /* If bit N is cleared in cr0_fixed1, then it must be zero in the guest's cr0. */
2966 uCR0Mask = (uint32_t)~pVM->hm.s.vmx.Msrs.u64Cr0Fixed1;
2967 if ((pCtx->cr0 & uCR0Mask) != 0)
2968 return false;
2969
2970 /* If bit N is set in cr4_fixed0, then it must be set in the guest's cr4. */
2971 uCR0Mask = (uint32_t)pVM->hm.s.vmx.Msrs.u64Cr4Fixed0;
2972 uCR0Mask &= ~X86_CR4_VMXE;
2973 if ((pCtx->cr4 & uCR0Mask) != uCR0Mask)
2974 return false;
2975
2976 /* If bit N is cleared in cr4_fixed1, then it must be zero in the guest's cr4. */
2977 uCR0Mask = (uint32_t)~pVM->hm.s.vmx.Msrs.u64Cr4Fixed1;
2978 if ((pCtx->cr4 & uCR0Mask) != 0)
2979 return false;
2980
2981 pVCpu->hm.s.fActive = true;
2982 return true;
2983 }
2984
2985 return false;
2986}
2987
2988
2989/**
2990 * Checks if we need to reschedule due to VMM device heap changes.
2991 *
2992 * @returns true if a reschedule is required, otherwise false.
2993 * @param pVM The cross context VM structure.
2994 * @param pCtx VM execution context.
2995 */
2996VMMR3_INT_DECL(bool) HMR3IsRescheduleRequired(PVM pVM, PCPUMCTX pCtx)
2997{
2998 /*
2999 * The VMM device heap is a requirement for emulating real-mode or protected-mode without paging
3000 * when the unrestricted guest execution feature is missing (VT-x only).
3001 */
3002 if ( pVM->hm.s.vmx.fEnabled
3003 && !pVM->hm.s.vmx.fUnrestrictedGuest
3004 && CPUMIsGuestInRealModeEx(pCtx)
3005 && !PDMVmmDevHeapIsEnabled(pVM))
3006 {
3007 return true;
3008 }
3009
3010 return false;
3011}
3012
3013
3014/**
3015 * Noticiation callback from DBGF when interrupt breakpoints or generic debug
3016 * event settings changes.
3017 *
3018 * DBGF will call HMR3NotifyDebugEventChangedPerCpu on each CPU afterwards, this
3019 * function is just updating the VM globals.
3020 *
3021 * @param pVM The VM cross context VM structure.
3022 * @thread EMT(0)
3023 */
3024VMMR3_INT_DECL(void) HMR3NotifyDebugEventChanged(PVM pVM)
3025{
3026 /* Interrupts. */
3027 bool fUseDebugLoop = pVM->dbgf.ro.cSoftIntBreakpoints > 0
3028 || pVM->dbgf.ro.cHardIntBreakpoints > 0;
3029
3030 /* CPU Exceptions. */
3031 for (DBGFEVENTTYPE enmEvent = DBGFEVENT_XCPT_FIRST;
3032 !fUseDebugLoop && enmEvent <= DBGFEVENT_XCPT_LAST;
3033 enmEvent = (DBGFEVENTTYPE)(enmEvent + 1))
3034 fUseDebugLoop = DBGF_IS_EVENT_ENABLED(pVM, enmEvent);
3035
3036 /* Common VM exits. */
3037 for (DBGFEVENTTYPE enmEvent = DBGFEVENT_EXIT_FIRST;
3038 !fUseDebugLoop && enmEvent <= DBGFEVENT_EXIT_LAST_COMMON;
3039 enmEvent = (DBGFEVENTTYPE)(enmEvent + 1))
3040 fUseDebugLoop = DBGF_IS_EVENT_ENABLED(pVM, enmEvent);
3041
3042 /* Vendor specific VM exits. */
3043 if (HMR3IsVmxEnabled(pVM->pUVM))
3044 for (DBGFEVENTTYPE enmEvent = DBGFEVENT_EXIT_VMX_FIRST;
3045 !fUseDebugLoop && enmEvent <= DBGFEVENT_EXIT_VMX_LAST;
3046 enmEvent = (DBGFEVENTTYPE)(enmEvent + 1))
3047 fUseDebugLoop = DBGF_IS_EVENT_ENABLED(pVM, enmEvent);
3048 else
3049 for (DBGFEVENTTYPE enmEvent = DBGFEVENT_EXIT_SVM_FIRST;
3050 !fUseDebugLoop && enmEvent <= DBGFEVENT_EXIT_SVM_LAST;
3051 enmEvent = (DBGFEVENTTYPE)(enmEvent + 1))
3052 fUseDebugLoop = DBGF_IS_EVENT_ENABLED(pVM, enmEvent);
3053
3054 /* Done. */
3055 pVM->hm.s.fUseDebugLoop = fUseDebugLoop;
3056}
3057
3058
3059/**
3060 * Follow up notification callback to HMR3NotifyDebugEventChanged for each CPU.
3061 *
3062 * HM uses this to combine the decision made by HMR3NotifyDebugEventChanged with
3063 * per CPU settings.
3064 *
3065 * @param pVM The VM cross context VM structure.
3066 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
3067 */
3068VMMR3_INT_DECL(void) HMR3NotifyDebugEventChangedPerCpu(PVM pVM, PVMCPU pVCpu)
3069{
3070 pVCpu->hm.s.fUseDebugLoop = pVCpu->hm.s.fSingleInstruction | pVM->hm.s.fUseDebugLoop;
3071}
3072
3073
3074/**
3075 * Checks if we are currently using hardware acceleration.
3076 *
3077 * @returns true if hardware acceleration is being used, otherwise false.
3078 * @param pVCpu The cross context virtual CPU structure.
3079 */
3080VMMR3_INT_DECL(bool) HMR3IsActive(PVMCPU pVCpu)
3081{
3082 return pVCpu->hm.s.fActive;
3083}
3084
3085
3086/**
3087 * External interface for querying whether hardware acceleration is enabled.
3088 *
3089 * @returns true if VT-x or AMD-V is being used, otherwise false.
3090 * @param pUVM The user mode VM handle.
3091 * @sa HMIsEnabled, HMIsEnabledNotMacro.
3092 */
3093VMMR3DECL(bool) HMR3IsEnabled(PUVM pUVM)
3094{
3095 UVM_ASSERT_VALID_EXT_RETURN(pUVM, false);
3096 PVM pVM = pUVM->pVM;
3097 VM_ASSERT_VALID_EXT_RETURN(pVM, false);
3098 return pVM->fHMEnabled; /* Don't use the macro as the GUI may query us very very early. */
3099}
3100
3101
3102/**
3103 * External interface for querying whether VT-x is being used.
3104 *
3105 * @returns true if VT-x is being used, otherwise false.
3106 * @param pUVM The user mode VM handle.
3107 * @sa HMR3IsSvmEnabled, HMIsEnabled
3108 */
3109VMMR3DECL(bool) HMR3IsVmxEnabled(PUVM pUVM)
3110{
3111 UVM_ASSERT_VALID_EXT_RETURN(pUVM, false);
3112 PVM pVM = pUVM->pVM;
3113 VM_ASSERT_VALID_EXT_RETURN(pVM, false);
3114 return pVM->hm.s.vmx.fEnabled
3115 && pVM->hm.s.vmx.fSupported
3116 && pVM->fHMEnabled;
3117}
3118
3119
3120/**
3121 * External interface for querying whether AMD-V is being used.
3122 *
3123 * @returns true if VT-x is being used, otherwise false.
3124 * @param pUVM The user mode VM handle.
3125 * @sa HMR3IsVmxEnabled, HMIsEnabled
3126 */
3127VMMR3DECL(bool) HMR3IsSvmEnabled(PUVM pUVM)
3128{
3129 UVM_ASSERT_VALID_EXT_RETURN(pUVM, false);
3130 PVM pVM = pUVM->pVM;
3131 VM_ASSERT_VALID_EXT_RETURN(pVM, false);
3132 return pVM->hm.s.svm.fEnabled
3133 && pVM->hm.s.svm.fSupported
3134 && pVM->fHMEnabled;
3135}
3136
3137
3138/**
3139 * Checks if we are currently using nested paging.
3140 *
3141 * @returns true if nested paging is being used, otherwise false.
3142 * @param pUVM The user mode VM handle.
3143 */
3144VMMR3DECL(bool) HMR3IsNestedPagingActive(PUVM pUVM)
3145{
3146 UVM_ASSERT_VALID_EXT_RETURN(pUVM, false);
3147 PVM pVM = pUVM->pVM;
3148 VM_ASSERT_VALID_EXT_RETURN(pVM, false);
3149 return pVM->hm.s.fNestedPaging;
3150}
3151
3152
3153/**
3154 * Checks if virtualized APIC registers is enabled.
3155 *
3156 * When enabled this feature allows the hardware to access most of the
3157 * APIC registers in the virtual-APIC page without causing VM-exits. See
3158 * Intel spec. 29.1.1 "Virtualized APIC Registers".
3159 *
3160 * @returns true if virtualized APIC registers is enabled, otherwise
3161 * false.
3162 * @param pUVM The user mode VM handle.
3163 */
3164VMMR3DECL(bool) HMR3IsVirtApicRegsEnabled(PUVM pUVM)
3165{
3166 UVM_ASSERT_VALID_EXT_RETURN(pUVM, false);
3167 PVM pVM = pUVM->pVM;
3168 VM_ASSERT_VALID_EXT_RETURN(pVM, false);
3169 return pVM->hm.s.fVirtApicRegs;
3170}
3171
3172
3173/**
3174 * Checks if APIC posted-interrupt processing is enabled.
3175 *
3176 * This returns whether we can deliver interrupts to the guest without
3177 * leaving guest-context by updating APIC state from host-context.
3178 *
3179 * @returns true if APIC posted-interrupt processing is enabled,
3180 * otherwise false.
3181 * @param pUVM The user mode VM handle.
3182 */
3183VMMR3DECL(bool) HMR3IsPostedIntrsEnabled(PUVM pUVM)
3184{
3185 UVM_ASSERT_VALID_EXT_RETURN(pUVM, false);
3186 PVM pVM = pUVM->pVM;
3187 VM_ASSERT_VALID_EXT_RETURN(pVM, false);
3188 return pVM->hm.s.fPostedIntrs;
3189}
3190
3191
3192/**
3193 * Checks if we are currently using VPID in VT-x mode.
3194 *
3195 * @returns true if VPID is being used, otherwise false.
3196 * @param pUVM The user mode VM handle.
3197 */
3198VMMR3DECL(bool) HMR3IsVpidActive(PUVM pUVM)
3199{
3200 UVM_ASSERT_VALID_EXT_RETURN(pUVM, false);
3201 PVM pVM = pUVM->pVM;
3202 VM_ASSERT_VALID_EXT_RETURN(pVM, false);
3203 return pVM->hm.s.vmx.fVpid;
3204}
3205
3206
3207/**
3208 * Checks if we are currently using VT-x unrestricted execution,
3209 * aka UX.
3210 *
3211 * @returns true if UX is being used, otherwise false.
3212 * @param pUVM The user mode VM handle.
3213 */
3214VMMR3DECL(bool) HMR3IsUXActive(PUVM pUVM)
3215{
3216 UVM_ASSERT_VALID_EXT_RETURN(pUVM, false);
3217 PVM pVM = pUVM->pVM;
3218 VM_ASSERT_VALID_EXT_RETURN(pVM, false);
3219 return pVM->hm.s.vmx.fUnrestrictedGuest
3220 || pVM->hm.s.svm.fSupported;
3221}
3222
3223
3224/**
3225 * Checks if internal events are pending. In that case we are not allowed to dispatch interrupts.
3226 *
3227 * @returns true if an internal event is pending, otherwise false.
3228 * @param pVCpu The cross context virtual CPU structure.
3229 */
3230VMMR3_INT_DECL(bool) HMR3IsEventPending(PVMCPU pVCpu)
3231{
3232 return HMIsEnabled(pVCpu->pVMR3) && pVCpu->hm.s.Event.fPending;
3233}
3234
3235
3236/**
3237 * Checks if the VMX-preemption timer is being used.
3238 *
3239 * @returns true if the VMX-preemption timer is being used, otherwise false.
3240 * @param pVM The cross context VM structure.
3241 */
3242VMMR3_INT_DECL(bool) HMR3IsVmxPreemptionTimerUsed(PVM pVM)
3243{
3244 return HMIsEnabled(pVM)
3245 && pVM->hm.s.vmx.fEnabled
3246 && pVM->hm.s.vmx.fUsePreemptTimer;
3247}
3248
3249
3250/**
3251 * Check fatal VT-x/AMD-V error and produce some meaningful
3252 * log release message.
3253 *
3254 * @param pVM The cross context VM structure.
3255 * @param iStatusCode VBox status code.
3256 */
3257VMMR3_INT_DECL(void) HMR3CheckError(PVM pVM, int iStatusCode)
3258{
3259 for (VMCPUID i = 0; i < pVM->cCpus; i++)
3260 {
3261 PVMCPU pVCpu = &pVM->aCpus[i];
3262 switch (iStatusCode)
3263 {
3264 /** @todo r=ramshankar: Are all EMTs out of ring-0 at this point!? If not, we
3265 * might be getting inaccurate values for non-guru'ing EMTs. */
3266 case VERR_VMX_INVALID_VMCS_FIELD:
3267 break;
3268
3269 case VERR_VMX_INVALID_VMCS_PTR:
3270 LogRel(("HM: VERR_VMX_INVALID_VMCS_PTR:\n"));
3271 LogRel(("HM: CPU[%u] Current pointer %#RGp vs %#RGp\n", i, pVCpu->hm.s.vmx.LastError.u64VMCSPhys,
3272 pVCpu->hm.s.vmx.HCPhysVmcs));
3273 LogRel(("HM: CPU[%u] Current VMCS version %#x\n", i, pVCpu->hm.s.vmx.LastError.u32VMCSRevision));
3274 LogRel(("HM: CPU[%u] Entered Host Cpu %u\n", i, pVCpu->hm.s.vmx.LastError.idEnteredCpu));
3275 LogRel(("HM: CPU[%u] Current Host Cpu %u\n", i, pVCpu->hm.s.vmx.LastError.idCurrentCpu));
3276 break;
3277
3278 case VERR_VMX_UNABLE_TO_START_VM:
3279 LogRel(("HM: VERR_VMX_UNABLE_TO_START_VM:\n"));
3280 LogRel(("HM: CPU[%u] Instruction error %#x\n", i, pVCpu->hm.s.vmx.LastError.u32InstrError));
3281 LogRel(("HM: CPU[%u] Exit reason %#x\n", i, pVCpu->hm.s.vmx.LastError.u32ExitReason));
3282
3283 if ( pVM->aCpus[i].hm.s.vmx.LastError.u32InstrError == VMX_ERROR_VMLAUCH_NON_CLEAR_VMCS
3284 || pVM->aCpus[i].hm.s.vmx.LastError.u32InstrError == VMX_ERROR_VMRESUME_NON_LAUNCHED_VMCS)
3285 {
3286 LogRel(("HM: CPU[%u] Entered Host Cpu %u\n", i, pVCpu->hm.s.vmx.LastError.idEnteredCpu));
3287 LogRel(("HM: CPU[%u] Current Host Cpu %u\n", i, pVCpu->hm.s.vmx.LastError.idCurrentCpu));
3288 }
3289 else if (pVM->aCpus[i].hm.s.vmx.LastError.u32InstrError == VMX_ERROR_VMENTRY_INVALID_CONTROL_FIELDS)
3290 {
3291 LogRel(("HM: CPU[%u] PinCtls %#RX32\n", i, pVCpu->hm.s.vmx.u32PinCtls));
3292 {
3293 uint32_t const u32Val = pVCpu->hm.s.vmx.u32PinCtls;
3294 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PIN_EXEC_EXT_INT_EXIT );
3295 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PIN_EXEC_NMI_EXIT );
3296 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PIN_EXEC_VIRTUAL_NMI );
3297 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PIN_EXEC_PREEMPT_TIMER);
3298 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PIN_EXEC_POSTED_INTR );
3299 }
3300 LogRel(("HM: CPU[%u] ProcCtls %#RX32\n", i, pVCpu->hm.s.vmx.u32ProcCtls));
3301 {
3302 uint32_t const u32Val = pVCpu->hm.s.vmx.u32ProcCtls;
3303 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC_INT_WINDOW_EXIT );
3304 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC_USE_TSC_OFFSETTING);
3305 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC_HLT_EXIT );
3306 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC_INVLPG_EXIT );
3307 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC_MWAIT_EXIT );
3308 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC_RDPMC_EXIT );
3309 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC_RDTSC_EXIT );
3310 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC_CR3_LOAD_EXIT );
3311 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC_CR3_STORE_EXIT );
3312 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC_CR8_LOAD_EXIT );
3313 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC_CR8_STORE_EXIT );
3314 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC_USE_TPR_SHADOW );
3315 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC_NMI_WINDOW_EXIT );
3316 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC_MOV_DR_EXIT );
3317 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC_UNCOND_IO_EXIT );
3318 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC_USE_IO_BITMAPS );
3319 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC_MONITOR_TRAP_FLAG );
3320 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC_USE_MSR_BITMAPS );
3321 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC_MONITOR_EXIT );
3322 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC_PAUSE_EXIT );
3323 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC_USE_SECONDARY_EXEC_CTRL);
3324 }
3325 LogRel(("HM: CPU[%u] ProcCtls2 %#RX32\n", i, pVCpu->hm.s.vmx.u32ProcCtls2));
3326 {
3327 uint32_t const u32Val = pVCpu->hm.s.vmx.u32ProcCtls2;
3328 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC2_VIRT_APIC );
3329 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC2_EPT );
3330 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC2_DESCRIPTOR_TABLE_EXIT);
3331 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC2_RDTSCP );
3332 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC2_VIRT_X2APIC );
3333 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC2_VPID );
3334 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC2_WBINVD_EXIT );
3335 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC2_UNRESTRICTED_GUEST );
3336 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC2_APIC_REG_VIRT );
3337 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC2_VIRT_INTR_DELIVERY );
3338 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC2_PAUSE_LOOP_EXIT );
3339 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC2_RDRAND_EXIT );
3340 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC2_INVPCID );
3341 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC2_VMFUNC );
3342 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC2_VMCS_SHADOWING );
3343 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC2_ENCLS_EXIT );
3344 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC2_RDSEED_EXIT );
3345 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC2_PML );
3346 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC2_EPT_VE );
3347 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC2_CONCEAL_FROM_PT );
3348 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC2_XSAVES_XRSTORS );
3349 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_PROC_EXEC2_TSC_SCALING );
3350 }
3351 LogRel(("HM: CPU[%u] EntryCtls %#RX32\n", i, pVCpu->hm.s.vmx.u32EntryCtls));
3352 {
3353 uint32_t const u32Val = pVCpu->hm.s.vmx.u32EntryCtls;
3354 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_ENTRY_LOAD_DEBUG );
3355 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_ENTRY_IA32E_MODE_GUEST );
3356 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_ENTRY_ENTRY_SMM );
3357 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_ENTRY_DEACTIVATE_DUALMON );
3358 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_ENTRY_LOAD_GUEST_PERF_MSR);
3359 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_ENTRY_LOAD_GUEST_PAT_MSR );
3360 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_ENTRY_LOAD_GUEST_EFER_MSR);
3361 }
3362 LogRel(("HM: CPU[%u] ExitCtls %#RX32\n", i, pVCpu->hm.s.vmx.u32ExitCtls));
3363 {
3364 uint32_t const u32Val = pVCpu->hm.s.vmx.u32ExitCtls;
3365 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_EXIT_SAVE_DEBUG );
3366 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_EXIT_HOST_ADDR_SPACE_SIZE );
3367 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_EXIT_LOAD_PERF_MSR );
3368 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_EXIT_ACK_EXT_INT );
3369 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_EXIT_SAVE_GUEST_PAT_MSR );
3370 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_EXIT_LOAD_HOST_PAT_MSR );
3371 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_EXIT_SAVE_GUEST_EFER_MSR );
3372 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_EXIT_LOAD_HOST_EFER_MSR );
3373 HMVMX_LOGREL_FEAT(u32Val, VMX_VMCS_CTRL_EXIT_SAVE_VMX_PREEMPT_TIMER);
3374 }
3375 LogRel(("HM: CPU[%u] HCPhysMsrBitmap %#RHp\n", i, pVCpu->hm.s.vmx.HCPhysMsrBitmap));
3376 LogRel(("HM: CPU[%u] HCPhysGuestMsr %#RHp\n", i, pVCpu->hm.s.vmx.HCPhysGuestMsr));
3377 LogRel(("HM: CPU[%u] HCPhysHostMsr %#RHp\n", i, pVCpu->hm.s.vmx.HCPhysHostMsr));
3378 LogRel(("HM: CPU[%u] cMsrs %u\n", i, pVCpu->hm.s.vmx.cMsrs));
3379 }
3380 /** @todo Log VM-entry event injection control fields
3381 * VMX_VMCS_CTRL_ENTRY_IRQ_INFO, VMX_VMCS_CTRL_ENTRY_EXCEPTION_ERRCODE
3382 * and VMX_VMCS_CTRL_ENTRY_INSTR_LENGTH from the VMCS. */
3383 break;
3384
3385 /* The guru will dump the HM error and exit history. Nothing extra to report for these errors. */
3386 case VERR_VMX_INVALID_VMXON_PTR:
3387 case VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO:
3388 case VERR_VMX_INVALID_GUEST_STATE:
3389 case VERR_VMX_UNEXPECTED_EXIT:
3390 case VERR_SVM_UNKNOWN_EXIT:
3391 case VERR_SVM_UNEXPECTED_EXIT:
3392 case VERR_SVM_UNEXPECTED_PATCH_TYPE:
3393 case VERR_SVM_UNEXPECTED_XCPT_EXIT:
3394 case VERR_VMX_UNEXPECTED_INTERRUPTION_EXIT_TYPE:
3395 break;
3396 }
3397 }
3398
3399 if (iStatusCode == VERR_VMX_UNABLE_TO_START_VM)
3400 {
3401 LogRel(("HM: VERR_VMX_UNABLE_TO_START_VM: VM-entry allowed %#RX32\n", pVM->hm.s.vmx.Msrs.VmxEntry.n.allowed1));
3402 LogRel(("HM: VERR_VMX_UNABLE_TO_START_VM: VM-entry disallowed %#RX32\n", pVM->hm.s.vmx.Msrs.VmxEntry.n.disallowed0));
3403 }
3404 else if (iStatusCode == VERR_VMX_INVALID_VMXON_PTR)
3405 LogRel(("HM: HCPhysVmxEnableError = %#RHp\n", pVM->hm.s.vmx.HCPhysVmxEnableError));
3406}
3407
3408
3409/**
3410 * Execute state save operation.
3411 *
3412 * Save only data that cannot be re-loaded while entering HM ring-0 code. This
3413 * is because we always save the VM state from ring-3 and thus most HM state
3414 * will be re-synced dynamically at runtime and don't need to be part of the VM
3415 * saved state.
3416 *
3417 * @returns VBox status code.
3418 * @param pVM The cross context VM structure.
3419 * @param pSSM SSM operation handle.
3420 */
3421static DECLCALLBACK(int) hmR3Save(PVM pVM, PSSMHANDLE pSSM)
3422{
3423 int rc;
3424
3425 Log(("hmR3Save:\n"));
3426
3427 for (VMCPUID i = 0; i < pVM->cCpus; i++)
3428 {
3429 Assert(!pVM->aCpus[i].hm.s.Event.fPending);
3430 if (pVM->cpum.ro.GuestFeatures.fSvm)
3431 {
3432 PCSVMNESTEDVMCBCACHE pVmcbNstGstCache = &pVM->aCpus[i].hm.s.svm.NstGstVmcbCache;
3433 rc = SSMR3PutBool(pSSM, pVmcbNstGstCache->fCacheValid);
3434 rc |= SSMR3PutU16(pSSM, pVmcbNstGstCache->u16InterceptRdCRx);
3435 rc |= SSMR3PutU16(pSSM, pVmcbNstGstCache->u16InterceptWrCRx);
3436 rc |= SSMR3PutU16(pSSM, pVmcbNstGstCache->u16InterceptRdDRx);
3437 rc |= SSMR3PutU16(pSSM, pVmcbNstGstCache->u16InterceptWrDRx);
3438 rc |= SSMR3PutU16(pSSM, pVmcbNstGstCache->u16PauseFilterThreshold);
3439 rc |= SSMR3PutU16(pSSM, pVmcbNstGstCache->u16PauseFilterCount);
3440 rc |= SSMR3PutU32(pSSM, pVmcbNstGstCache->u32InterceptXcpt);
3441 rc |= SSMR3PutU64(pSSM, pVmcbNstGstCache->u64InterceptCtrl);
3442 rc |= SSMR3PutU64(pSSM, pVmcbNstGstCache->u64TSCOffset);
3443 rc |= SSMR3PutBool(pSSM, pVmcbNstGstCache->fVIntrMasking);
3444 rc |= SSMR3PutBool(pSSM, pVmcbNstGstCache->fNestedPaging);
3445 rc |= SSMR3PutBool(pSSM, pVmcbNstGstCache->fLbrVirt);
3446 AssertRCReturn(rc, rc);
3447 }
3448 }
3449
3450 /* Save the guest patch data. */
3451 rc = SSMR3PutGCPtr(pSSM, pVM->hm.s.pGuestPatchMem);
3452 rc |= SSMR3PutGCPtr(pSSM, pVM->hm.s.pFreeGuestPatchMem);
3453 rc |= SSMR3PutU32(pSSM, pVM->hm.s.cbGuestPatchMem);
3454
3455 /* Store all the guest patch records too. */
3456 rc |= SSMR3PutU32(pSSM, pVM->hm.s.cPatches);
3457 AssertRCReturn(rc, rc);
3458
3459 for (uint32_t i = 0; i < pVM->hm.s.cPatches; i++)
3460 {
3461 AssertCompileSize(HMTPRINSTR, 4);
3462 PCHMTPRPATCH pPatch = &pVM->hm.s.aPatches[i];
3463 rc = SSMR3PutU32(pSSM, pPatch->Core.Key);
3464 rc |= SSMR3PutMem(pSSM, pPatch->aOpcode, sizeof(pPatch->aOpcode));
3465 rc |= SSMR3PutU32(pSSM, pPatch->cbOp);
3466 rc |= SSMR3PutMem(pSSM, pPatch->aNewOpcode, sizeof(pPatch->aNewOpcode));
3467 rc |= SSMR3PutU32(pSSM, pPatch->cbNewOp);
3468 rc |= SSMR3PutU32(pSSM, (uint32_t)pPatch->enmType);
3469 rc |= SSMR3PutU32(pSSM, pPatch->uSrcOperand);
3470 rc |= SSMR3PutU32(pSSM, pPatch->uDstOperand);
3471 rc |= SSMR3PutU32(pSSM, pPatch->pJumpTarget);
3472 rc |= SSMR3PutU32(pSSM, pPatch->cFaults);
3473 AssertRCReturn(rc, rc);
3474 }
3475
3476 return VINF_SUCCESS;
3477}
3478
3479
3480/**
3481 * Execute state load operation.
3482 *
3483 * @returns VBox status code.
3484 * @param pVM The cross context VM structure.
3485 * @param pSSM SSM operation handle.
3486 * @param uVersion Data layout version.
3487 * @param uPass The data pass.
3488 */
3489static DECLCALLBACK(int) hmR3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
3490{
3491 int rc;
3492
3493 LogFlowFunc(("uVersion=%u\n", uVersion));
3494 Assert(uPass == SSM_PASS_FINAL); NOREF(uPass);
3495
3496 /*
3497 * Validate version.
3498 */
3499 if ( uVersion != HM_SAVED_STATE_VERSION_SVM_NESTED_HWVIRT
3500 && uVersion != HM_SAVED_STATE_VERSION_TPR_PATCHING
3501 && uVersion != HM_SAVED_STATE_VERSION_NO_TPR_PATCHING
3502 && uVersion != HM_SAVED_STATE_VERSION_2_0_X)
3503 {
3504 AssertMsgFailed(("hmR3Load: Invalid version uVersion=%d!\n", uVersion));
3505 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
3506 }
3507
3508 /*
3509 * Load per-VCPU state.
3510 */
3511 for (VMCPUID i = 0; i < pVM->cCpus; i++)
3512 {
3513 if (uVersion >= HM_SAVED_STATE_VERSION_SVM_NESTED_HWVIRT)
3514 {
3515 /* Load the SVM nested hw.virt state if the VM is configured for it. */
3516 if (pVM->cpum.ro.GuestFeatures.fSvm)
3517 {
3518 PSVMNESTEDVMCBCACHE pVmcbNstGstCache = &pVM->aCpus[i].hm.s.svm.NstGstVmcbCache;
3519 rc = SSMR3GetBool(pSSM, &pVmcbNstGstCache->fCacheValid);
3520 rc |= SSMR3GetU16(pSSM, &pVmcbNstGstCache->u16InterceptRdCRx);
3521 rc |= SSMR3GetU16(pSSM, &pVmcbNstGstCache->u16InterceptWrCRx);
3522 rc |= SSMR3GetU16(pSSM, &pVmcbNstGstCache->u16InterceptRdDRx);
3523 rc |= SSMR3GetU16(pSSM, &pVmcbNstGstCache->u16InterceptWrDRx);
3524 rc |= SSMR3GetU16(pSSM, &pVmcbNstGstCache->u16PauseFilterThreshold);
3525 rc |= SSMR3GetU16(pSSM, &pVmcbNstGstCache->u16PauseFilterCount);
3526 rc |= SSMR3GetU32(pSSM, &pVmcbNstGstCache->u32InterceptXcpt);
3527 rc |= SSMR3GetU64(pSSM, &pVmcbNstGstCache->u64InterceptCtrl);
3528 rc |= SSMR3GetU64(pSSM, &pVmcbNstGstCache->u64TSCOffset);
3529 rc |= SSMR3GetBool(pSSM, &pVmcbNstGstCache->fVIntrMasking);
3530 rc |= SSMR3GetBool(pSSM, &pVmcbNstGstCache->fNestedPaging);
3531 rc |= SSMR3GetBool(pSSM, &pVmcbNstGstCache->fLbrVirt);
3532 AssertRCReturn(rc, rc);
3533 }
3534 }
3535 else
3536 {
3537 /* Pending HM event (obsolete for a long time since TPRM holds the info.) */
3538 rc = SSMR3GetU32(pSSM, &pVM->aCpus[i].hm.s.Event.fPending);
3539 rc |= SSMR3GetU32(pSSM, &pVM->aCpus[i].hm.s.Event.u32ErrCode);
3540 rc |= SSMR3GetU64(pSSM, &pVM->aCpus[i].hm.s.Event.u64IntInfo);
3541
3542 /* VMX fWasInRealMode related data. */
3543 uint32_t uDummy;
3544 rc |= SSMR3GetU32(pSSM, &uDummy); AssertRCReturn(rc, rc);
3545 rc |= SSMR3GetU32(pSSM, &uDummy); AssertRCReturn(rc, rc);
3546 rc |= SSMR3GetU32(pSSM, &uDummy); AssertRCReturn(rc, rc);
3547 AssertRCReturn(rc, rc);
3548 }
3549 }
3550
3551 /*
3552 * Load TPR patching data.
3553 */
3554 if (uVersion >= HM_SAVED_STATE_VERSION_TPR_PATCHING)
3555 {
3556 rc = SSMR3GetGCPtr(pSSM, &pVM->hm.s.pGuestPatchMem);
3557 rc |= SSMR3GetGCPtr(pSSM, &pVM->hm.s.pFreeGuestPatchMem);
3558 rc |= SSMR3GetU32(pSSM, &pVM->hm.s.cbGuestPatchMem);
3559
3560 /* Fetch all TPR patch records. */
3561 rc |= SSMR3GetU32(pSSM, &pVM->hm.s.cPatches);
3562 AssertRCReturn(rc, rc);
3563 for (uint32_t i = 0; i < pVM->hm.s.cPatches; i++)
3564 {
3565 PHMTPRPATCH pPatch = &pVM->hm.s.aPatches[i];
3566 rc = SSMR3GetU32(pSSM, &pPatch->Core.Key);
3567 rc |= SSMR3GetMem(pSSM, pPatch->aOpcode, sizeof(pPatch->aOpcode));
3568 rc |= SSMR3GetU32(pSSM, &pPatch->cbOp);
3569 rc |= SSMR3GetMem(pSSM, pPatch->aNewOpcode, sizeof(pPatch->aNewOpcode));
3570 rc |= SSMR3GetU32(pSSM, &pPatch->cbNewOp);
3571 rc |= SSMR3GetU32(pSSM, (uint32_t *)&pPatch->enmType);
3572
3573 if (pPatch->enmType == HMTPRINSTR_JUMP_REPLACEMENT)
3574 pVM->hm.s.fTPRPatchingActive = true;
3575 Assert(pPatch->enmType == HMTPRINSTR_JUMP_REPLACEMENT || pVM->hm.s.fTPRPatchingActive == false);
3576
3577 rc |= SSMR3GetU32(pSSM, &pPatch->uSrcOperand);
3578 rc |= SSMR3GetU32(pSSM, &pPatch->uDstOperand);
3579 rc |= SSMR3GetU32(pSSM, &pPatch->cFaults);
3580 rc |= SSMR3GetU32(pSSM, &pPatch->pJumpTarget);
3581 AssertRCReturn(rc, rc);
3582
3583 LogFlow(("hmR3Load: patch %d\n", i));
3584 LogFlow(("Key = %x\n", pPatch->Core.Key));
3585 LogFlow(("cbOp = %d\n", pPatch->cbOp));
3586 LogFlow(("cbNewOp = %d\n", pPatch->cbNewOp));
3587 LogFlow(("type = %d\n", pPatch->enmType));
3588 LogFlow(("srcop = %d\n", pPatch->uSrcOperand));
3589 LogFlow(("dstop = %d\n", pPatch->uDstOperand));
3590 LogFlow(("cFaults = %d\n", pPatch->cFaults));
3591 LogFlow(("target = %x\n", pPatch->pJumpTarget));
3592
3593 rc = RTAvloU32Insert(&pVM->hm.s.PatchTree, &pPatch->Core);
3594 AssertRCReturn(rc, rc);
3595 }
3596 }
3597
3598 return VINF_SUCCESS;
3599}
3600
3601
3602/**
3603 * Gets the name of a VT-x exit code.
3604 *
3605 * @returns Pointer to read only string if @a uExit is known, otherwise NULL.
3606 * @param uExit The VT-x exit to name.
3607 */
3608VMMR3DECL(const char *) HMR3GetVmxExitName(uint32_t uExit)
3609{
3610 if (uExit < RT_ELEMENTS(g_apszVTxExitReasons))
3611 return g_apszVTxExitReasons[uExit];
3612 return NULL;
3613}
3614
3615
3616/**
3617 * Gets the name of an AMD-V exit code.
3618 *
3619 * @returns Pointer to read only string if @a uExit is known, otherwise NULL.
3620 * @param uExit The AMD-V exit to name.
3621 */
3622VMMR3DECL(const char *) HMR3GetSvmExitName(uint32_t uExit)
3623{
3624 if (uExit < RT_ELEMENTS(g_apszAmdVExitReasons))
3625 return g_apszAmdVExitReasons[uExit];
3626 return hmSvmGetSpecialExitReasonDesc(uExit);
3627}
3628
3629
3630/**
3631 * Displays HM info.
3632 *
3633 * @param pVM The cross context VM structure.
3634 * @param pHlp The info helper functions.
3635 * @param pszArgs Arguments, ignored.
3636 */
3637static DECLCALLBACK(void) hmR3Info(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
3638{
3639 NOREF(pszArgs);
3640 PVMCPU pVCpu = VMMGetCpu(pVM);
3641 if (!pVCpu)
3642 pVCpu = &pVM->aCpus[0];
3643
3644 if (HMIsEnabled(pVM))
3645 {
3646 if (pVM->hm.s.vmx.fSupported)
3647 pHlp->pfnPrintf(pHlp, "CPU[%u]: VT-x info:\n", pVCpu->idCpu);
3648 else
3649 pHlp->pfnPrintf(pHlp, "CPU[%u]: AMD-V info:\n", pVCpu->idCpu);
3650 pHlp->pfnPrintf(pHlp, " HM error = %#x (%u)\n", pVCpu->hm.s.u32HMError, pVCpu->hm.s.u32HMError);
3651 pHlp->pfnPrintf(pHlp, " rcLastExitToR3 = %Rrc\n", pVCpu->hm.s.rcLastExitToR3);
3652 }
3653 else
3654 pHlp->pfnPrintf(pHlp, "HM is not enabled for this VM!\n");
3655}
3656
3657
3658/**
3659 * Displays the HM pending event.
3660 *
3661 * @param pVM The cross context VM structure.
3662 * @param pHlp The info helper functions.
3663 * @param pszArgs Arguments, ignored.
3664 */
3665static DECLCALLBACK(void) hmR3InfoEventPending(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
3666{
3667 NOREF(pszArgs);
3668 PVMCPU pVCpu = VMMGetCpu(pVM);
3669 if (!pVCpu)
3670 pVCpu = &pVM->aCpus[0];
3671
3672 if (HMIsEnabled(pVM))
3673 {
3674 pHlp->pfnPrintf(pHlp, "CPU[%u]: HM event (fPending=%RTbool)\n", pVCpu->idCpu, pVCpu->hm.s.Event.fPending);
3675 if (pVCpu->hm.s.Event.fPending)
3676 {
3677 pHlp->pfnPrintf(pHlp, " u64IntInfo = %#RX64\n", pVCpu->hm.s.Event.u64IntInfo);
3678 pHlp->pfnPrintf(pHlp, " u32ErrCode = %#RX64\n", pVCpu->hm.s.Event.u32ErrCode);
3679 pHlp->pfnPrintf(pHlp, " cbInstr = %u bytes\n", pVCpu->hm.s.Event.cbInstr);
3680 pHlp->pfnPrintf(pHlp, " GCPtrFaultAddress = %#RGp\n", pVCpu->hm.s.Event.GCPtrFaultAddress);
3681 }
3682 }
3683 else
3684 pHlp->pfnPrintf(pHlp, "HM is not enabled for this VM!\n");
3685}
3686
3687
3688/**
3689 * Displays the SVM nested-guest VMCB cache.
3690 *
3691 * @param pVM The cross context VM structure.
3692 * @param pHlp The info helper functions.
3693 * @param pszArgs Arguments, ignored.
3694 */
3695static DECLCALLBACK(void) hmR3InfoSvmNstGstVmcbCache(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
3696{
3697 NOREF(pszArgs);
3698 PVMCPU pVCpu = VMMGetCpu(pVM);
3699 if (!pVCpu)
3700 pVCpu = &pVM->aCpus[0];
3701
3702 bool const fSvmEnabled = HMR3IsSvmEnabled(pVM->pUVM);
3703 if ( fSvmEnabled
3704 && pVM->cpum.ro.GuestFeatures.fSvm)
3705 {
3706 PCSVMNESTEDVMCBCACHE pVmcbNstGstCache = &pVCpu->hm.s.svm.NstGstVmcbCache;
3707 pHlp->pfnPrintf(pHlp, "CPU[%u]: HM SVM nested-guest VMCB cache\n", pVCpu->idCpu);
3708 pHlp->pfnPrintf(pHlp, " fCacheValid = %#RTbool\n", pVmcbNstGstCache->fCacheValid);
3709 pHlp->pfnPrintf(pHlp, " u16InterceptRdCRx = %#RX16\n", pVmcbNstGstCache->u16InterceptRdCRx);
3710 pHlp->pfnPrintf(pHlp, " u16InterceptWrCRx = %#RX16\n", pVmcbNstGstCache->u16InterceptWrCRx);
3711 pHlp->pfnPrintf(pHlp, " u16InterceptRdDRx = %#RX16\n", pVmcbNstGstCache->u16InterceptRdDRx);
3712 pHlp->pfnPrintf(pHlp, " u16InterceptWrDRx = %#RX16\n", pVmcbNstGstCache->u16InterceptWrDRx);
3713 pHlp->pfnPrintf(pHlp, " u16PauseFilterThreshold = %#RX16\n", pVmcbNstGstCache->u16PauseFilterThreshold);
3714 pHlp->pfnPrintf(pHlp, " u16PauseFilterCount = %#RX16\n", pVmcbNstGstCache->u16PauseFilterCount);
3715 pHlp->pfnPrintf(pHlp, " u32InterceptXcpt = %#RX32\n", pVmcbNstGstCache->u32InterceptXcpt);
3716 pHlp->pfnPrintf(pHlp, " u64InterceptCtrl = %#RX64\n", pVmcbNstGstCache->u64InterceptCtrl);
3717 pHlp->pfnPrintf(pHlp, " u64TSCOffset = %#RX64\n", pVmcbNstGstCache->u64TSCOffset);
3718 pHlp->pfnPrintf(pHlp, " fVIntrMasking = %RTbool\n", pVmcbNstGstCache->fVIntrMasking);
3719 pHlp->pfnPrintf(pHlp, " fNestedPaging = %RTbool\n", pVmcbNstGstCache->fNestedPaging);
3720 pHlp->pfnPrintf(pHlp, " fLbrVirt = %RTbool\n", pVmcbNstGstCache->fLbrVirt);
3721 }
3722 else
3723 {
3724 if (!fSvmEnabled)
3725 pHlp->pfnPrintf(pHlp, "HM SVM is not enabled for this VM!\n");
3726 else
3727 pHlp->pfnPrintf(pHlp, "SVM feature is not exposed to the guest!\n");
3728 }
3729}
3730
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