VirtualBox

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

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

VMM/HM: Log IA32_SMM_MONITOR_CTL for VT-x hosts, useful diagnostic info.

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