VirtualBox

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

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

VMM/HM: consistency in error reporting.

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

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