VirtualBox

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

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

VMM/HM: group preempt STAM counters under 'HM/Switch'.

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