VirtualBox

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

Last change on this file since 70714 was 70606, checked in by vboxsync, 7 years ago

updates (bugref:9087)

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