VirtualBox

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

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

HM.cpp: Fix assertion in HMIsEnabledNotMacro during vm startup.

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

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