VirtualBox

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

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

HM: Determine VT-x, AMD-V, nested paging and unhindered guest execution support+config earlier so CPUM can make decisions based on it.

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