VirtualBox

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

Last change on this file since 61574 was 61574, checked in by vboxsync, 9 years ago

VMM/HM: Run the exithistory info callback on all EMTs if a specific one isn't specified.

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