VirtualBox

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

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

VMM: Stubbed the csam, patm, rem and hm documentation @pages.

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