VirtualBox

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

Last change on this file since 57478 was 57478, checked in by vboxsync, 10 years ago

VMM/HM: typo.

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette