VirtualBox

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

最後變更 在這個檔案從57036是 57036,由 vboxsync 提交於 10 年 前

VMM/HM: Log when we IA32_FEATURE_CONTROL MSR does not have the lock bit set.

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

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