VirtualBox

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

Last change on this file since 71189 was 71108, checked in by vboxsync, 7 years ago

Added speculation control settings to API, refined implementation.

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