VirtualBox

source: vbox/trunk/src/VBox/VMM/VMMAll/NEMAllNativeTemplate-win.cpp.h@ 91634

Last change on this file since 91634 was 91580, checked in by vboxsync, 3 years ago

VMM: Nested VMX: bugref:10092 Made changes to PGM++ to handle invalid PAE PDPEs being loaded.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 233.9 KB
Line 
1/* $Id: NEMAllNativeTemplate-win.cpp.h 91580 2021-10-06 07:22:04Z vboxsync $ */
2/** @file
3 * NEM - Native execution manager, Windows code template ring-0/3.
4 */
5
6/*
7 * Copyright (C) 2018-2020 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Defined Constants And Macros *
21*********************************************************************************************************************************/
22/** Copy back a segment from hyper-V. */
23#define NEM_WIN_COPY_BACK_SEG(a_Dst, a_Src) \
24 do { \
25 (a_Dst).u64Base = (a_Src).Base; \
26 (a_Dst).u32Limit = (a_Src).Limit; \
27 (a_Dst).ValidSel = (a_Dst).Sel = (a_Src).Selector; \
28 (a_Dst).Attr.u = (a_Src).Attributes; \
29 (a_Dst).fFlags = CPUMSELREG_FLAGS_VALID; \
30 } while (0)
31
32/** @def NEMWIN_ASSERT_MSG_REG_VAL
33 * Asserts the correctness of a register value in a message/context.
34 */
35#if 0
36# define NEMWIN_NEED_GET_REGISTER
37# if defined(IN_RING0) || defined(NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS)
38# define NEMWIN_ASSERT_MSG_REG_VAL(a_pVCpu, a_enmReg, a_Expr, a_Msg) \
39 do { \
40 HV_REGISTER_VALUE TmpVal; \
41 nemHCWinGetRegister(a_pVCpu, a_enmReg, &TmpVal); \
42 AssertMsg(a_Expr, a_Msg); \
43 } while (0)
44# else
45# define NEMWIN_ASSERT_MSG_REG_VAL(a_pVCpu, a_enmReg, a_Expr, a_Msg) \
46 do { \
47 WHV_REGISTER_VALUE TmpVal; \
48 nemR3WinGetRegister(a_pVCpu, a_enmReg, &TmpVal); \
49 AssertMsg(a_Expr, a_Msg); \
50 } while (0)
51# endif
52#else
53# define NEMWIN_ASSERT_MSG_REG_VAL(a_pVCpu, a_enmReg, a_Expr, a_Msg) do { } while (0)
54#endif
55
56/** @def NEMWIN_ASSERT_MSG_REG_VAL
57 * Asserts the correctness of a 64-bit register value in a message/context.
58 */
59#define NEMWIN_ASSERT_MSG_REG_VAL64(a_pVCpu, a_enmReg, a_u64Val) \
60 NEMWIN_ASSERT_MSG_REG_VAL(a_pVCpu, a_enmReg, (a_u64Val) == TmpVal.Reg64, \
61 (#a_u64Val "=%#RX64, expected %#RX64\n", (a_u64Val), TmpVal.Reg64))
62/** @def NEMWIN_ASSERT_MSG_REG_VAL
63 * Asserts the correctness of a segment register value in a message/context.
64 */
65#define NEMWIN_ASSERT_MSG_REG_SEG(a_pVCpu, a_enmReg, a_SReg) \
66 NEMWIN_ASSERT_MSG_REG_VAL(a_pVCpu, a_enmReg, \
67 (a_SReg).Base == TmpVal.Segment.Base \
68 && (a_SReg).Limit == TmpVal.Segment.Limit \
69 && (a_SReg).Selector == TmpVal.Segment.Selector \
70 && (a_SReg).Attributes == TmpVal.Segment.Attributes, \
71 ( #a_SReg "=%#RX16 {%#RX64 LB %#RX32,%#RX16} expected %#RX16 {%#RX64 LB %#RX32,%#RX16}\n", \
72 (a_SReg).Selector, (a_SReg).Base, (a_SReg).Limit, (a_SReg).Attributes, \
73 TmpVal.Segment.Selector, TmpVal.Segment.Base, TmpVal.Segment.Limit, TmpVal.Segment.Attributes))
74
75
76/*********************************************************************************************************************************
77* Global Variables *
78*********************************************************************************************************************************/
79/** NEM_WIN_PAGE_STATE_XXX names. */
80NEM_TMPL_STATIC const char * const g_apszPageStates[4] = { "not-set", "unmapped", "readable", "writable" };
81
82/** HV_INTERCEPT_ACCESS_TYPE names. */
83static const char * const g_apszHvInterceptAccessTypes[4] = { "read", "write", "exec", "!undefined!" };
84
85
86/*********************************************************************************************************************************
87* Internal Functions *
88*********************************************************************************************************************************/
89NEM_TMPL_STATIC int nemHCNativeSetPhysPage(PVMCC pVM, PVMCPUCC pVCpu, RTGCPHYS GCPhysSrc, RTGCPHYS GCPhysDst,
90 uint32_t fPageProt, uint8_t *pu2State, bool fBackingChanged);
91
92
93
94#ifdef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
95
96/**
97 * Wrapper around VMMR0_DO_NEM_MAP_PAGES for a single page.
98 *
99 * @returns VBox status code.
100 * @param pVM The cross context VM structure.
101 * @param pVCpu The cross context virtual CPU structure of the caller.
102 * @param GCPhysSrc The source page. Does not need to be page aligned.
103 * @param GCPhysDst The destination page. Same as @a GCPhysSrc except for
104 * when A20 is disabled.
105 * @param fFlags HV_MAP_GPA_XXX.
106 */
107DECLINLINE(int) nemHCWinHypercallMapPage(PVMCC pVM, PVMCPUCC pVCpu, RTGCPHYS GCPhysSrc, RTGCPHYS GCPhysDst, uint32_t fFlags)
108{
109#ifdef IN_RING0
110 /** @todo optimize further, caller generally has the physical address. */
111 return nemR0WinMapPages(pVM, pVCpu,
112 GCPhysSrc & ~(RTGCPHYS)X86_PAGE_OFFSET_MASK,
113 GCPhysDst & ~(RTGCPHYS)X86_PAGE_OFFSET_MASK,
114 1, fFlags);
115#else
116 pVCpu->nem.s.Hypercall.MapPages.GCPhysSrc = GCPhysSrc & ~(RTGCPHYS)X86_PAGE_OFFSET_MASK;
117 pVCpu->nem.s.Hypercall.MapPages.GCPhysDst = GCPhysDst & ~(RTGCPHYS)X86_PAGE_OFFSET_MASK;
118 pVCpu->nem.s.Hypercall.MapPages.cPages = 1;
119 pVCpu->nem.s.Hypercall.MapPages.fFlags = fFlags;
120 return VMMR3CallR0Emt(pVM, pVCpu, VMMR0_DO_NEM_MAP_PAGES, 0, NULL);
121#endif
122}
123
124
125/**
126 * Wrapper around VMMR0_DO_NEM_UNMAP_PAGES for a single page.
127 *
128 * @returns VBox status code.
129 * @param pVM The cross context VM structure.
130 * @param pVCpu The cross context virtual CPU structure of the caller.
131 * @param GCPhys The page to unmap. Does not need to be page aligned.
132 */
133DECLINLINE(int) nemHCWinHypercallUnmapPage(PVMCC pVM, PVMCPUCC pVCpu, RTGCPHYS GCPhys)
134{
135# ifdef IN_RING0
136 return nemR0WinUnmapPages(pVM, pVCpu, GCPhys & ~(RTGCPHYS)X86_PAGE_OFFSET_MASK, 1);
137# else
138 pVCpu->nem.s.Hypercall.UnmapPages.GCPhys = GCPhys & ~(RTGCPHYS)X86_PAGE_OFFSET_MASK;
139 pVCpu->nem.s.Hypercall.UnmapPages.cPages = 1;
140 return VMMR3CallR0Emt(pVM, pVCpu, VMMR0_DO_NEM_UNMAP_PAGES, 0, NULL);
141# endif
142}
143
144#endif /* NEM_WIN_USE_HYPERCALLS_FOR_PAGES */
145#ifndef IN_RING0
146
147NEM_TMPL_STATIC int nemHCWinCopyStateToHyperV(PVMCC pVM, PVMCPUCC pVCpu)
148{
149# if defined(NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS) || defined(NEM_WIN_WITH_RING0_RUNLOOP)
150# if !defined(NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS) && defined(NEM_WIN_WITH_RING0_RUNLOOP)
151 if (pVM->nem.s.fUseRing0Runloop)
152# endif
153 {
154 int rc = VMMR3CallR0Emt(pVM, pVCpu, VMMR0_DO_NEM_EXPORT_STATE, 0, NULL);
155 AssertLogRelRCReturn(rc, rc);
156 return rc;
157 }
158# endif
159# ifndef NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS
160
161 /*
162 * The following is very similar to what nemR0WinExportState() does.
163 */
164 WHV_REGISTER_NAME aenmNames[128];
165 WHV_REGISTER_VALUE aValues[128];
166
167 uint64_t const fWhat = ~pVCpu->cpum.GstCtx.fExtrn & (CPUMCTX_EXTRN_ALL | CPUMCTX_EXTRN_NEM_WIN_MASK);
168 if ( !fWhat
169 && pVCpu->nem.s.fCurrentInterruptWindows == pVCpu->nem.s.fDesiredInterruptWindows)
170 return VINF_SUCCESS;
171 uintptr_t iReg = 0;
172
173# define ADD_REG64(a_enmName, a_uValue) do { \
174 aenmNames[iReg] = (a_enmName); \
175 aValues[iReg].Reg128.High64 = 0; \
176 aValues[iReg].Reg64 = (a_uValue); \
177 iReg++; \
178 } while (0)
179# define ADD_REG128(a_enmName, a_uValueLo, a_uValueHi) do { \
180 aenmNames[iReg] = (a_enmName); \
181 aValues[iReg].Reg128.Low64 = (a_uValueLo); \
182 aValues[iReg].Reg128.High64 = (a_uValueHi); \
183 iReg++; \
184 } while (0)
185
186 /* GPRs */
187 if (fWhat & CPUMCTX_EXTRN_GPRS_MASK)
188 {
189 if (fWhat & CPUMCTX_EXTRN_RAX)
190 ADD_REG64(WHvX64RegisterRax, pVCpu->cpum.GstCtx.rax);
191 if (fWhat & CPUMCTX_EXTRN_RCX)
192 ADD_REG64(WHvX64RegisterRcx, pVCpu->cpum.GstCtx.rcx);
193 if (fWhat & CPUMCTX_EXTRN_RDX)
194 ADD_REG64(WHvX64RegisterRdx, pVCpu->cpum.GstCtx.rdx);
195 if (fWhat & CPUMCTX_EXTRN_RBX)
196 ADD_REG64(WHvX64RegisterRbx, pVCpu->cpum.GstCtx.rbx);
197 if (fWhat & CPUMCTX_EXTRN_RSP)
198 ADD_REG64(WHvX64RegisterRsp, pVCpu->cpum.GstCtx.rsp);
199 if (fWhat & CPUMCTX_EXTRN_RBP)
200 ADD_REG64(WHvX64RegisterRbp, pVCpu->cpum.GstCtx.rbp);
201 if (fWhat & CPUMCTX_EXTRN_RSI)
202 ADD_REG64(WHvX64RegisterRsi, pVCpu->cpum.GstCtx.rsi);
203 if (fWhat & CPUMCTX_EXTRN_RDI)
204 ADD_REG64(WHvX64RegisterRdi, pVCpu->cpum.GstCtx.rdi);
205 if (fWhat & CPUMCTX_EXTRN_R8_R15)
206 {
207 ADD_REG64(WHvX64RegisterR8, pVCpu->cpum.GstCtx.r8);
208 ADD_REG64(WHvX64RegisterR9, pVCpu->cpum.GstCtx.r9);
209 ADD_REG64(WHvX64RegisterR10, pVCpu->cpum.GstCtx.r10);
210 ADD_REG64(WHvX64RegisterR11, pVCpu->cpum.GstCtx.r11);
211 ADD_REG64(WHvX64RegisterR12, pVCpu->cpum.GstCtx.r12);
212 ADD_REG64(WHvX64RegisterR13, pVCpu->cpum.GstCtx.r13);
213 ADD_REG64(WHvX64RegisterR14, pVCpu->cpum.GstCtx.r14);
214 ADD_REG64(WHvX64RegisterR15, pVCpu->cpum.GstCtx.r15);
215 }
216 }
217
218 /* RIP & Flags */
219 if (fWhat & CPUMCTX_EXTRN_RIP)
220 ADD_REG64(WHvX64RegisterRip, pVCpu->cpum.GstCtx.rip);
221 if (fWhat & CPUMCTX_EXTRN_RFLAGS)
222 ADD_REG64(WHvX64RegisterRflags, pVCpu->cpum.GstCtx.rflags.u);
223
224 /* Segments */
225# define ADD_SEG(a_enmName, a_SReg) \
226 do { \
227 aenmNames[iReg] = a_enmName; \
228 aValues[iReg].Segment.Base = (a_SReg).u64Base; \
229 aValues[iReg].Segment.Limit = (a_SReg).u32Limit; \
230 aValues[iReg].Segment.Selector = (a_SReg).Sel; \
231 aValues[iReg].Segment.Attributes = (a_SReg).Attr.u; \
232 iReg++; \
233 } while (0)
234 if (fWhat & CPUMCTX_EXTRN_SREG_MASK)
235 {
236 if (fWhat & CPUMCTX_EXTRN_ES)
237 ADD_SEG(WHvX64RegisterEs, pVCpu->cpum.GstCtx.es);
238 if (fWhat & CPUMCTX_EXTRN_CS)
239 ADD_SEG(WHvX64RegisterCs, pVCpu->cpum.GstCtx.cs);
240 if (fWhat & CPUMCTX_EXTRN_SS)
241 ADD_SEG(WHvX64RegisterSs, pVCpu->cpum.GstCtx.ss);
242 if (fWhat & CPUMCTX_EXTRN_DS)
243 ADD_SEG(WHvX64RegisterDs, pVCpu->cpum.GstCtx.ds);
244 if (fWhat & CPUMCTX_EXTRN_FS)
245 ADD_SEG(WHvX64RegisterFs, pVCpu->cpum.GstCtx.fs);
246 if (fWhat & CPUMCTX_EXTRN_GS)
247 ADD_SEG(WHvX64RegisterGs, pVCpu->cpum.GstCtx.gs);
248 }
249
250 /* Descriptor tables & task segment. */
251 if (fWhat & CPUMCTX_EXTRN_TABLE_MASK)
252 {
253 if (fWhat & CPUMCTX_EXTRN_LDTR)
254 ADD_SEG(WHvX64RegisterLdtr, pVCpu->cpum.GstCtx.ldtr);
255 if (fWhat & CPUMCTX_EXTRN_TR)
256 ADD_SEG(WHvX64RegisterTr, pVCpu->cpum.GstCtx.tr);
257 if (fWhat & CPUMCTX_EXTRN_IDTR)
258 {
259 aenmNames[iReg] = WHvX64RegisterIdtr;
260 aValues[iReg].Table.Limit = pVCpu->cpum.GstCtx.idtr.cbIdt;
261 aValues[iReg].Table.Base = pVCpu->cpum.GstCtx.idtr.pIdt;
262 iReg++;
263 }
264 if (fWhat & CPUMCTX_EXTRN_GDTR)
265 {
266 aenmNames[iReg] = WHvX64RegisterGdtr;
267 aValues[iReg].Table.Limit = pVCpu->cpum.GstCtx.gdtr.cbGdt;
268 aValues[iReg].Table.Base = pVCpu->cpum.GstCtx.gdtr.pGdt;
269 iReg++;
270 }
271 }
272
273 /* Control registers. */
274 if (fWhat & CPUMCTX_EXTRN_CR_MASK)
275 {
276 if (fWhat & CPUMCTX_EXTRN_CR0)
277 ADD_REG64(WHvX64RegisterCr0, pVCpu->cpum.GstCtx.cr0);
278 if (fWhat & CPUMCTX_EXTRN_CR2)
279 ADD_REG64(WHvX64RegisterCr2, pVCpu->cpum.GstCtx.cr2);
280 if (fWhat & CPUMCTX_EXTRN_CR3)
281 ADD_REG64(WHvX64RegisterCr3, pVCpu->cpum.GstCtx.cr3);
282 if (fWhat & CPUMCTX_EXTRN_CR4)
283 ADD_REG64(WHvX64RegisterCr4, pVCpu->cpum.GstCtx.cr4);
284 }
285 if (fWhat & CPUMCTX_EXTRN_APIC_TPR)
286 ADD_REG64(WHvX64RegisterCr8, CPUMGetGuestCR8(pVCpu));
287
288 /* Debug registers. */
289/** @todo fixme. Figure out what the hyper-v version of KVM_SET_GUEST_DEBUG would be. */
290 if (fWhat & CPUMCTX_EXTRN_DR0_DR3)
291 {
292 ADD_REG64(WHvX64RegisterDr0, pVCpu->cpum.GstCtx.dr[0]); // CPUMGetHyperDR0(pVCpu));
293 ADD_REG64(WHvX64RegisterDr1, pVCpu->cpum.GstCtx.dr[1]); // CPUMGetHyperDR1(pVCpu));
294 ADD_REG64(WHvX64RegisterDr2, pVCpu->cpum.GstCtx.dr[2]); // CPUMGetHyperDR2(pVCpu));
295 ADD_REG64(WHvX64RegisterDr3, pVCpu->cpum.GstCtx.dr[3]); // CPUMGetHyperDR3(pVCpu));
296 }
297 if (fWhat & CPUMCTX_EXTRN_DR6)
298 ADD_REG64(WHvX64RegisterDr6, pVCpu->cpum.GstCtx.dr[6]); // CPUMGetHyperDR6(pVCpu));
299 if (fWhat & CPUMCTX_EXTRN_DR7)
300 ADD_REG64(WHvX64RegisterDr7, pVCpu->cpum.GstCtx.dr[7]); // CPUMGetHyperDR7(pVCpu));
301
302 /* Floating point state. */
303 if (fWhat & CPUMCTX_EXTRN_X87)
304 {
305 ADD_REG128(WHvX64RegisterFpMmx0, pVCpu->cpum.GstCtx.XState.x87.aRegs[0].au64[0], pVCpu->cpum.GstCtx.XState.x87.aRegs[0].au64[1]);
306 ADD_REG128(WHvX64RegisterFpMmx1, pVCpu->cpum.GstCtx.XState.x87.aRegs[1].au64[0], pVCpu->cpum.GstCtx.XState.x87.aRegs[1].au64[1]);
307 ADD_REG128(WHvX64RegisterFpMmx2, pVCpu->cpum.GstCtx.XState.x87.aRegs[2].au64[0], pVCpu->cpum.GstCtx.XState.x87.aRegs[2].au64[1]);
308 ADD_REG128(WHvX64RegisterFpMmx3, pVCpu->cpum.GstCtx.XState.x87.aRegs[3].au64[0], pVCpu->cpum.GstCtx.XState.x87.aRegs[3].au64[1]);
309 ADD_REG128(WHvX64RegisterFpMmx4, pVCpu->cpum.GstCtx.XState.x87.aRegs[4].au64[0], pVCpu->cpum.GstCtx.XState.x87.aRegs[4].au64[1]);
310 ADD_REG128(WHvX64RegisterFpMmx5, pVCpu->cpum.GstCtx.XState.x87.aRegs[5].au64[0], pVCpu->cpum.GstCtx.XState.x87.aRegs[5].au64[1]);
311 ADD_REG128(WHvX64RegisterFpMmx6, pVCpu->cpum.GstCtx.XState.x87.aRegs[6].au64[0], pVCpu->cpum.GstCtx.XState.x87.aRegs[6].au64[1]);
312 ADD_REG128(WHvX64RegisterFpMmx7, pVCpu->cpum.GstCtx.XState.x87.aRegs[7].au64[0], pVCpu->cpum.GstCtx.XState.x87.aRegs[7].au64[1]);
313
314 aenmNames[iReg] = WHvX64RegisterFpControlStatus;
315 aValues[iReg].FpControlStatus.FpControl = pVCpu->cpum.GstCtx.XState.x87.FCW;
316 aValues[iReg].FpControlStatus.FpStatus = pVCpu->cpum.GstCtx.XState.x87.FSW;
317 aValues[iReg].FpControlStatus.FpTag = pVCpu->cpum.GstCtx.XState.x87.FTW;
318 aValues[iReg].FpControlStatus.Reserved = pVCpu->cpum.GstCtx.XState.x87.FTW >> 8;
319 aValues[iReg].FpControlStatus.LastFpOp = pVCpu->cpum.GstCtx.XState.x87.FOP;
320 aValues[iReg].FpControlStatus.LastFpRip = (pVCpu->cpum.GstCtx.XState.x87.FPUIP)
321 | ((uint64_t)pVCpu->cpum.GstCtx.XState.x87.CS << 32)
322 | ((uint64_t)pVCpu->cpum.GstCtx.XState.x87.Rsrvd1 << 48);
323 iReg++;
324
325 aenmNames[iReg] = WHvX64RegisterXmmControlStatus;
326 aValues[iReg].XmmControlStatus.LastFpRdp = (pVCpu->cpum.GstCtx.XState.x87.FPUDP)
327 | ((uint64_t)pVCpu->cpum.GstCtx.XState.x87.DS << 32)
328 | ((uint64_t)pVCpu->cpum.GstCtx.XState.x87.Rsrvd2 << 48);
329 aValues[iReg].XmmControlStatus.XmmStatusControl = pVCpu->cpum.GstCtx.XState.x87.MXCSR;
330 aValues[iReg].XmmControlStatus.XmmStatusControlMask = pVCpu->cpum.GstCtx.XState.x87.MXCSR_MASK; /** @todo ??? (Isn't this an output field?) */
331 iReg++;
332 }
333
334 /* Vector state. */
335 if (fWhat & CPUMCTX_EXTRN_SSE_AVX)
336 {
337 ADD_REG128(WHvX64RegisterXmm0, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 0].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 0].uXmm.s.Hi);
338 ADD_REG128(WHvX64RegisterXmm1, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 1].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 1].uXmm.s.Hi);
339 ADD_REG128(WHvX64RegisterXmm2, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 2].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 2].uXmm.s.Hi);
340 ADD_REG128(WHvX64RegisterXmm3, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 3].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 3].uXmm.s.Hi);
341 ADD_REG128(WHvX64RegisterXmm4, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 4].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 4].uXmm.s.Hi);
342 ADD_REG128(WHvX64RegisterXmm5, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 5].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 5].uXmm.s.Hi);
343 ADD_REG128(WHvX64RegisterXmm6, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 6].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 6].uXmm.s.Hi);
344 ADD_REG128(WHvX64RegisterXmm7, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 7].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 7].uXmm.s.Hi);
345 ADD_REG128(WHvX64RegisterXmm8, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 8].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 8].uXmm.s.Hi);
346 ADD_REG128(WHvX64RegisterXmm9, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 9].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 9].uXmm.s.Hi);
347 ADD_REG128(WHvX64RegisterXmm10, pVCpu->cpum.GstCtx.XState.x87.aXMM[10].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[10].uXmm.s.Hi);
348 ADD_REG128(WHvX64RegisterXmm11, pVCpu->cpum.GstCtx.XState.x87.aXMM[11].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[11].uXmm.s.Hi);
349 ADD_REG128(WHvX64RegisterXmm12, pVCpu->cpum.GstCtx.XState.x87.aXMM[12].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[12].uXmm.s.Hi);
350 ADD_REG128(WHvX64RegisterXmm13, pVCpu->cpum.GstCtx.XState.x87.aXMM[13].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[13].uXmm.s.Hi);
351 ADD_REG128(WHvX64RegisterXmm14, pVCpu->cpum.GstCtx.XState.x87.aXMM[14].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[14].uXmm.s.Hi);
352 ADD_REG128(WHvX64RegisterXmm15, pVCpu->cpum.GstCtx.XState.x87.aXMM[15].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[15].uXmm.s.Hi);
353 }
354
355 /* MSRs */
356 // WHvX64RegisterTsc - don't touch
357 if (fWhat & CPUMCTX_EXTRN_EFER)
358 ADD_REG64(WHvX64RegisterEfer, pVCpu->cpum.GstCtx.msrEFER);
359 if (fWhat & CPUMCTX_EXTRN_KERNEL_GS_BASE)
360 ADD_REG64(WHvX64RegisterKernelGsBase, pVCpu->cpum.GstCtx.msrKERNELGSBASE);
361 if (fWhat & CPUMCTX_EXTRN_SYSENTER_MSRS)
362 {
363 ADD_REG64(WHvX64RegisterSysenterCs, pVCpu->cpum.GstCtx.SysEnter.cs);
364 ADD_REG64(WHvX64RegisterSysenterEip, pVCpu->cpum.GstCtx.SysEnter.eip);
365 ADD_REG64(WHvX64RegisterSysenterEsp, pVCpu->cpum.GstCtx.SysEnter.esp);
366 }
367 if (fWhat & CPUMCTX_EXTRN_SYSCALL_MSRS)
368 {
369 ADD_REG64(WHvX64RegisterStar, pVCpu->cpum.GstCtx.msrSTAR);
370 ADD_REG64(WHvX64RegisterLstar, pVCpu->cpum.GstCtx.msrLSTAR);
371 ADD_REG64(WHvX64RegisterCstar, pVCpu->cpum.GstCtx.msrCSTAR);
372 ADD_REG64(WHvX64RegisterSfmask, pVCpu->cpum.GstCtx.msrSFMASK);
373 }
374 if (fWhat & CPUMCTX_EXTRN_OTHER_MSRS)
375 {
376 ADD_REG64(WHvX64RegisterApicBase, APICGetBaseMsrNoCheck(pVCpu));
377 ADD_REG64(WHvX64RegisterPat, pVCpu->cpum.GstCtx.msrPAT);
378#if 0 /** @todo check if WHvX64RegisterMsrMtrrCap works here... */
379 ADD_REG64(WHvX64RegisterMsrMtrrCap, CPUMGetGuestIa32MtrrCap(pVCpu));
380#endif
381 PCPUMCTXMSRS pCtxMsrs = CPUMQueryGuestCtxMsrsPtr(pVCpu);
382 ADD_REG64(WHvX64RegisterMsrMtrrDefType, pCtxMsrs->msr.MtrrDefType);
383 ADD_REG64(WHvX64RegisterMsrMtrrFix64k00000, pCtxMsrs->msr.MtrrFix64K_00000);
384 ADD_REG64(WHvX64RegisterMsrMtrrFix16k80000, pCtxMsrs->msr.MtrrFix16K_80000);
385 ADD_REG64(WHvX64RegisterMsrMtrrFix16kA0000, pCtxMsrs->msr.MtrrFix16K_A0000);
386 ADD_REG64(WHvX64RegisterMsrMtrrFix4kC0000, pCtxMsrs->msr.MtrrFix4K_C0000);
387 ADD_REG64(WHvX64RegisterMsrMtrrFix4kC8000, pCtxMsrs->msr.MtrrFix4K_C8000);
388 ADD_REG64(WHvX64RegisterMsrMtrrFix4kD0000, pCtxMsrs->msr.MtrrFix4K_D0000);
389 ADD_REG64(WHvX64RegisterMsrMtrrFix4kD8000, pCtxMsrs->msr.MtrrFix4K_D8000);
390 ADD_REG64(WHvX64RegisterMsrMtrrFix4kE0000, pCtxMsrs->msr.MtrrFix4K_E0000);
391 ADD_REG64(WHvX64RegisterMsrMtrrFix4kE8000, pCtxMsrs->msr.MtrrFix4K_E8000);
392 ADD_REG64(WHvX64RegisterMsrMtrrFix4kF0000, pCtxMsrs->msr.MtrrFix4K_F0000);
393 ADD_REG64(WHvX64RegisterMsrMtrrFix4kF8000, pCtxMsrs->msr.MtrrFix4K_F8000);
394 ADD_REG64(WHvX64RegisterTscAux, pCtxMsrs->msr.TscAux);
395#if 0 /** @todo these registers aren't available? Might explain something.. .*/
396 const CPUMCPUVENDOR enmCpuVendor = CPUMGetHostCpuVendor(pVM);
397 if (enmCpuVendor != CPUMCPUVENDOR_AMD)
398 {
399 ADD_REG64(HvX64RegisterIa32MiscEnable, pCtxMsrs->msr.MiscEnable);
400 ADD_REG64(HvX64RegisterIa32FeatureControl, CPUMGetGuestIa32FeatureControl(pVCpu));
401 }
402#endif
403 }
404
405 /* event injection (clear it). */
406 if (fWhat & CPUMCTX_EXTRN_NEM_WIN_EVENT_INJECT)
407 ADD_REG64(WHvRegisterPendingInterruption, 0);
408
409 /* Interruptibility state. This can get a little complicated since we get
410 half of the state via HV_X64_VP_EXECUTION_STATE. */
411 if ( (fWhat & (CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT | CPUMCTX_EXTRN_NEM_WIN_INHIBIT_NMI))
412 == (CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT | CPUMCTX_EXTRN_NEM_WIN_INHIBIT_NMI) )
413 {
414 ADD_REG64(WHvRegisterInterruptState, 0);
415 if ( VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS)
416 && EMGetInhibitInterruptsPC(pVCpu) == pVCpu->cpum.GstCtx.rip)
417 aValues[iReg - 1].InterruptState.InterruptShadow = 1;
418 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_BLOCK_NMIS))
419 aValues[iReg - 1].InterruptState.NmiMasked = 1;
420 }
421 else if (fWhat & CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT)
422 {
423 if ( pVCpu->nem.s.fLastInterruptShadow
424 || ( VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS)
425 && EMGetInhibitInterruptsPC(pVCpu) == pVCpu->cpum.GstCtx.rip))
426 {
427 ADD_REG64(WHvRegisterInterruptState, 0);
428 if ( VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS)
429 && EMGetInhibitInterruptsPC(pVCpu) == pVCpu->cpum.GstCtx.rip)
430 aValues[iReg - 1].InterruptState.InterruptShadow = 1;
431 /** @todo Retrieve NMI state, currently assuming it's zero. (yes this may happen on I/O) */
432 //if (VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_BLOCK_NMIS))
433 // aValues[iReg - 1].InterruptState.NmiMasked = 1;
434 }
435 }
436 else
437 Assert(!(fWhat & CPUMCTX_EXTRN_NEM_WIN_INHIBIT_NMI));
438
439 /* Interrupt windows. Always set if active as Hyper-V seems to be forgetful. */
440 uint8_t const fDesiredIntWin = pVCpu->nem.s.fDesiredInterruptWindows;
441 if ( fDesiredIntWin
442 || pVCpu->nem.s.fCurrentInterruptWindows != fDesiredIntWin)
443 {
444 pVCpu->nem.s.fCurrentInterruptWindows = pVCpu->nem.s.fDesiredInterruptWindows;
445 Log8(("Setting WHvX64RegisterDeliverabilityNotifications, fDesiredIntWin=%X\n", fDesiredIntWin));
446 ADD_REG64(WHvX64RegisterDeliverabilityNotifications, fDesiredIntWin);
447 Assert(aValues[iReg - 1].DeliverabilityNotifications.NmiNotification == RT_BOOL(fDesiredIntWin & NEM_WIN_INTW_F_NMI));
448 Assert(aValues[iReg - 1].DeliverabilityNotifications.InterruptNotification == RT_BOOL(fDesiredIntWin & NEM_WIN_INTW_F_REGULAR));
449 Assert(aValues[iReg - 1].DeliverabilityNotifications.InterruptPriority == (unsigned)((fDesiredIntWin & NEM_WIN_INTW_F_PRIO_MASK) >> NEM_WIN_INTW_F_PRIO_SHIFT));
450 }
451
452 /// @todo WHvRegisterPendingEvent
453
454 /*
455 * Set the registers.
456 */
457 Assert(iReg < RT_ELEMENTS(aValues));
458 Assert(iReg < RT_ELEMENTS(aenmNames));
459# ifdef NEM_WIN_INTERCEPT_NT_IO_CTLS
460 Log12(("Calling WHvSetVirtualProcessorRegisters(%p, %u, %p, %u, %p)\n",
461 pVM->nem.s.hPartition, pVCpu->idCpu, aenmNames, iReg, aValues));
462# endif
463 HRESULT hrc = WHvSetVirtualProcessorRegisters(pVM->nem.s.hPartition, pVCpu->idCpu, aenmNames, iReg, aValues);
464 if (SUCCEEDED(hrc))
465 {
466 pVCpu->cpum.GstCtx.fExtrn |= CPUMCTX_EXTRN_ALL | CPUMCTX_EXTRN_NEM_WIN_MASK | CPUMCTX_EXTRN_KEEPER_NEM;
467 return VINF_SUCCESS;
468 }
469 AssertLogRelMsgFailed(("WHvSetVirtualProcessorRegisters(%p, %u,,%u,) -> %Rhrc (Last=%#x/%u)\n",
470 pVM->nem.s.hPartition, pVCpu->idCpu, iReg,
471 hrc, RTNtLastStatusValue(), RTNtLastErrorValue()));
472 return VERR_INTERNAL_ERROR;
473
474# undef ADD_REG64
475# undef ADD_REG128
476# undef ADD_SEG
477
478# endif /* !NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS */
479}
480
481
482NEM_TMPL_STATIC int nemHCWinCopyStateFromHyperV(PVMCC pVM, PVMCPUCC pVCpu, uint64_t fWhat)
483{
484# if defined(NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS) || defined(NEM_WIN_WITH_RING0_RUNLOOP)
485# if !defined(NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS) && defined(NEM_WIN_WITH_RING0_RUNLOOP)
486 if (pVM->nem.s.fUseRing0Runloop)
487# endif
488 {
489 /* See NEMR0ImportState */
490 int rc = VMMR3CallR0Emt(pVM, pVCpu, VMMR0_DO_NEM_IMPORT_STATE, fWhat, NULL);
491 if (RT_SUCCESS(rc))
492 return rc;
493 if (rc == VERR_NEM_FLUSH_TLB)
494 {
495 rc = PGMFlushTLB(pVCpu, pVCpu->cpum.GstCtx.cr3, true /*fGlobal*/, false /*fPdpesMapped*/);
496 return rc;
497 }
498 AssertLogRelRCReturn(rc, rc);
499 return rc;
500 }
501# endif
502# ifndef NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS
503 WHV_REGISTER_NAME aenmNames[128];
504
505 fWhat &= pVCpu->cpum.GstCtx.fExtrn;
506 uintptr_t iReg = 0;
507
508 /* GPRs */
509 if (fWhat & CPUMCTX_EXTRN_GPRS_MASK)
510 {
511 if (fWhat & CPUMCTX_EXTRN_RAX)
512 aenmNames[iReg++] = WHvX64RegisterRax;
513 if (fWhat & CPUMCTX_EXTRN_RCX)
514 aenmNames[iReg++] = WHvX64RegisterRcx;
515 if (fWhat & CPUMCTX_EXTRN_RDX)
516 aenmNames[iReg++] = WHvX64RegisterRdx;
517 if (fWhat & CPUMCTX_EXTRN_RBX)
518 aenmNames[iReg++] = WHvX64RegisterRbx;
519 if (fWhat & CPUMCTX_EXTRN_RSP)
520 aenmNames[iReg++] = WHvX64RegisterRsp;
521 if (fWhat & CPUMCTX_EXTRN_RBP)
522 aenmNames[iReg++] = WHvX64RegisterRbp;
523 if (fWhat & CPUMCTX_EXTRN_RSI)
524 aenmNames[iReg++] = WHvX64RegisterRsi;
525 if (fWhat & CPUMCTX_EXTRN_RDI)
526 aenmNames[iReg++] = WHvX64RegisterRdi;
527 if (fWhat & CPUMCTX_EXTRN_R8_R15)
528 {
529 aenmNames[iReg++] = WHvX64RegisterR8;
530 aenmNames[iReg++] = WHvX64RegisterR9;
531 aenmNames[iReg++] = WHvX64RegisterR10;
532 aenmNames[iReg++] = WHvX64RegisterR11;
533 aenmNames[iReg++] = WHvX64RegisterR12;
534 aenmNames[iReg++] = WHvX64RegisterR13;
535 aenmNames[iReg++] = WHvX64RegisterR14;
536 aenmNames[iReg++] = WHvX64RegisterR15;
537 }
538 }
539
540 /* RIP & Flags */
541 if (fWhat & CPUMCTX_EXTRN_RIP)
542 aenmNames[iReg++] = WHvX64RegisterRip;
543 if (fWhat & CPUMCTX_EXTRN_RFLAGS)
544 aenmNames[iReg++] = WHvX64RegisterRflags;
545
546 /* Segments */
547 if (fWhat & CPUMCTX_EXTRN_SREG_MASK)
548 {
549 if (fWhat & CPUMCTX_EXTRN_ES)
550 aenmNames[iReg++] = WHvX64RegisterEs;
551 if (fWhat & CPUMCTX_EXTRN_CS)
552 aenmNames[iReg++] = WHvX64RegisterCs;
553 if (fWhat & CPUMCTX_EXTRN_SS)
554 aenmNames[iReg++] = WHvX64RegisterSs;
555 if (fWhat & CPUMCTX_EXTRN_DS)
556 aenmNames[iReg++] = WHvX64RegisterDs;
557 if (fWhat & CPUMCTX_EXTRN_FS)
558 aenmNames[iReg++] = WHvX64RegisterFs;
559 if (fWhat & CPUMCTX_EXTRN_GS)
560 aenmNames[iReg++] = WHvX64RegisterGs;
561 }
562
563 /* Descriptor tables. */
564 if (fWhat & CPUMCTX_EXTRN_TABLE_MASK)
565 {
566 if (fWhat & CPUMCTX_EXTRN_LDTR)
567 aenmNames[iReg++] = WHvX64RegisterLdtr;
568 if (fWhat & CPUMCTX_EXTRN_TR)
569 aenmNames[iReg++] = WHvX64RegisterTr;
570 if (fWhat & CPUMCTX_EXTRN_IDTR)
571 aenmNames[iReg++] = WHvX64RegisterIdtr;
572 if (fWhat & CPUMCTX_EXTRN_GDTR)
573 aenmNames[iReg++] = WHvX64RegisterGdtr;
574 }
575
576 /* Control registers. */
577 if (fWhat & CPUMCTX_EXTRN_CR_MASK)
578 {
579 if (fWhat & CPUMCTX_EXTRN_CR0)
580 aenmNames[iReg++] = WHvX64RegisterCr0;
581 if (fWhat & CPUMCTX_EXTRN_CR2)
582 aenmNames[iReg++] = WHvX64RegisterCr2;
583 if (fWhat & CPUMCTX_EXTRN_CR3)
584 aenmNames[iReg++] = WHvX64RegisterCr3;
585 if (fWhat & CPUMCTX_EXTRN_CR4)
586 aenmNames[iReg++] = WHvX64RegisterCr4;
587 }
588 if (fWhat & CPUMCTX_EXTRN_APIC_TPR)
589 aenmNames[iReg++] = WHvX64RegisterCr8;
590
591 /* Debug registers. */
592 if (fWhat & CPUMCTX_EXTRN_DR7)
593 aenmNames[iReg++] = WHvX64RegisterDr7;
594 if (fWhat & CPUMCTX_EXTRN_DR0_DR3)
595 {
596 if (!(fWhat & CPUMCTX_EXTRN_DR7) && (pVCpu->cpum.GstCtx.fExtrn & CPUMCTX_EXTRN_DR7))
597 {
598 fWhat |= CPUMCTX_EXTRN_DR7;
599 aenmNames[iReg++] = WHvX64RegisterDr7;
600 }
601 aenmNames[iReg++] = WHvX64RegisterDr0;
602 aenmNames[iReg++] = WHvX64RegisterDr1;
603 aenmNames[iReg++] = WHvX64RegisterDr2;
604 aenmNames[iReg++] = WHvX64RegisterDr3;
605 }
606 if (fWhat & CPUMCTX_EXTRN_DR6)
607 aenmNames[iReg++] = WHvX64RegisterDr6;
608
609 /* Floating point state. */
610 if (fWhat & CPUMCTX_EXTRN_X87)
611 {
612 aenmNames[iReg++] = WHvX64RegisterFpMmx0;
613 aenmNames[iReg++] = WHvX64RegisterFpMmx1;
614 aenmNames[iReg++] = WHvX64RegisterFpMmx2;
615 aenmNames[iReg++] = WHvX64RegisterFpMmx3;
616 aenmNames[iReg++] = WHvX64RegisterFpMmx4;
617 aenmNames[iReg++] = WHvX64RegisterFpMmx5;
618 aenmNames[iReg++] = WHvX64RegisterFpMmx6;
619 aenmNames[iReg++] = WHvX64RegisterFpMmx7;
620 aenmNames[iReg++] = WHvX64RegisterFpControlStatus;
621 }
622 if (fWhat & (CPUMCTX_EXTRN_X87 | CPUMCTX_EXTRN_SSE_AVX))
623 aenmNames[iReg++] = WHvX64RegisterXmmControlStatus;
624
625 /* Vector state. */
626 if (fWhat & CPUMCTX_EXTRN_SSE_AVX)
627 {
628 aenmNames[iReg++] = WHvX64RegisterXmm0;
629 aenmNames[iReg++] = WHvX64RegisterXmm1;
630 aenmNames[iReg++] = WHvX64RegisterXmm2;
631 aenmNames[iReg++] = WHvX64RegisterXmm3;
632 aenmNames[iReg++] = WHvX64RegisterXmm4;
633 aenmNames[iReg++] = WHvX64RegisterXmm5;
634 aenmNames[iReg++] = WHvX64RegisterXmm6;
635 aenmNames[iReg++] = WHvX64RegisterXmm7;
636 aenmNames[iReg++] = WHvX64RegisterXmm8;
637 aenmNames[iReg++] = WHvX64RegisterXmm9;
638 aenmNames[iReg++] = WHvX64RegisterXmm10;
639 aenmNames[iReg++] = WHvX64RegisterXmm11;
640 aenmNames[iReg++] = WHvX64RegisterXmm12;
641 aenmNames[iReg++] = WHvX64RegisterXmm13;
642 aenmNames[iReg++] = WHvX64RegisterXmm14;
643 aenmNames[iReg++] = WHvX64RegisterXmm15;
644 }
645
646 /* MSRs */
647 // WHvX64RegisterTsc - don't touch
648 if (fWhat & CPUMCTX_EXTRN_EFER)
649 aenmNames[iReg++] = WHvX64RegisterEfer;
650 if (fWhat & CPUMCTX_EXTRN_KERNEL_GS_BASE)
651 aenmNames[iReg++] = WHvX64RegisterKernelGsBase;
652 if (fWhat & CPUMCTX_EXTRN_SYSENTER_MSRS)
653 {
654 aenmNames[iReg++] = WHvX64RegisterSysenterCs;
655 aenmNames[iReg++] = WHvX64RegisterSysenterEip;
656 aenmNames[iReg++] = WHvX64RegisterSysenterEsp;
657 }
658 if (fWhat & CPUMCTX_EXTRN_SYSCALL_MSRS)
659 {
660 aenmNames[iReg++] = WHvX64RegisterStar;
661 aenmNames[iReg++] = WHvX64RegisterLstar;
662 aenmNames[iReg++] = WHvX64RegisterCstar;
663 aenmNames[iReg++] = WHvX64RegisterSfmask;
664 }
665
666//#ifdef LOG_ENABLED
667// const CPUMCPUVENDOR enmCpuVendor = CPUMGetHostCpuVendor(pVM);
668//#endif
669 if (fWhat & CPUMCTX_EXTRN_OTHER_MSRS)
670 {
671 aenmNames[iReg++] = WHvX64RegisterApicBase; /// @todo APIC BASE
672 aenmNames[iReg++] = WHvX64RegisterPat;
673#if 0 /*def LOG_ENABLED*/ /** @todo Check if WHvX64RegisterMsrMtrrCap works... */
674 aenmNames[iReg++] = WHvX64RegisterMsrMtrrCap;
675#endif
676 aenmNames[iReg++] = WHvX64RegisterMsrMtrrDefType;
677 aenmNames[iReg++] = WHvX64RegisterMsrMtrrFix64k00000;
678 aenmNames[iReg++] = WHvX64RegisterMsrMtrrFix16k80000;
679 aenmNames[iReg++] = WHvX64RegisterMsrMtrrFix16kA0000;
680 aenmNames[iReg++] = WHvX64RegisterMsrMtrrFix4kC0000;
681 aenmNames[iReg++] = WHvX64RegisterMsrMtrrFix4kC8000;
682 aenmNames[iReg++] = WHvX64RegisterMsrMtrrFix4kD0000;
683 aenmNames[iReg++] = WHvX64RegisterMsrMtrrFix4kD8000;
684 aenmNames[iReg++] = WHvX64RegisterMsrMtrrFix4kE0000;
685 aenmNames[iReg++] = WHvX64RegisterMsrMtrrFix4kE8000;
686 aenmNames[iReg++] = WHvX64RegisterMsrMtrrFix4kF0000;
687 aenmNames[iReg++] = WHvX64RegisterMsrMtrrFix4kF8000;
688 aenmNames[iReg++] = WHvX64RegisterTscAux;
689 /** @todo look for HvX64RegisterIa32MiscEnable and HvX64RegisterIa32FeatureControl? */
690//#ifdef LOG_ENABLED
691// if (enmCpuVendor != CPUMCPUVENDOR_AMD)
692// aenmNames[iReg++] = HvX64RegisterIa32FeatureControl;
693//#endif
694 }
695
696 /* Interruptibility. */
697 if (fWhat & (CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT | CPUMCTX_EXTRN_NEM_WIN_INHIBIT_NMI))
698 {
699 aenmNames[iReg++] = WHvRegisterInterruptState;
700 aenmNames[iReg++] = WHvX64RegisterRip;
701 }
702
703 /* event injection */
704 aenmNames[iReg++] = WHvRegisterPendingInterruption;
705 aenmNames[iReg++] = WHvRegisterPendingEvent0; /** @todo renamed to WHvRegisterPendingEvent */
706
707 size_t const cRegs = iReg;
708 Assert(cRegs < RT_ELEMENTS(aenmNames));
709
710 /*
711 * Get the registers.
712 */
713 WHV_REGISTER_VALUE aValues[128];
714 RT_ZERO(aValues);
715 Assert(RT_ELEMENTS(aValues) >= cRegs);
716 Assert(RT_ELEMENTS(aenmNames) >= cRegs);
717# ifdef NEM_WIN_INTERCEPT_NT_IO_CTLS
718 Log12(("Calling WHvGetVirtualProcessorRegisters(%p, %u, %p, %u, %p)\n",
719 pVM->nem.s.hPartition, pVCpu->idCpu, aenmNames, cRegs, aValues));
720# endif
721 HRESULT hrc = WHvGetVirtualProcessorRegisters(pVM->nem.s.hPartition, pVCpu->idCpu, aenmNames, (uint32_t)cRegs, aValues);
722 AssertLogRelMsgReturn(SUCCEEDED(hrc),
723 ("WHvGetVirtualProcessorRegisters(%p, %u,,%u,) -> %Rhrc (Last=%#x/%u)\n",
724 pVM->nem.s.hPartition, pVCpu->idCpu, cRegs, hrc, RTNtLastStatusValue(), RTNtLastErrorValue())
725 , VERR_NEM_GET_REGISTERS_FAILED);
726
727 iReg = 0;
728# define GET_REG64(a_DstVar, a_enmName) do { \
729 Assert(aenmNames[iReg] == (a_enmName)); \
730 (a_DstVar) = aValues[iReg].Reg64; \
731 iReg++; \
732 } while (0)
733# define GET_REG64_LOG7(a_DstVar, a_enmName, a_szLogName) do { \
734 Assert(aenmNames[iReg] == (a_enmName)); \
735 if ((a_DstVar) != aValues[iReg].Reg64) \
736 Log7(("NEM/%u: " a_szLogName " changed %RX64 -> %RX64\n", pVCpu->idCpu, (a_DstVar), aValues[iReg].Reg64)); \
737 (a_DstVar) = aValues[iReg].Reg64; \
738 iReg++; \
739 } while (0)
740# define GET_REG128(a_DstVarLo, a_DstVarHi, a_enmName) do { \
741 Assert(aenmNames[iReg] == a_enmName); \
742 (a_DstVarLo) = aValues[iReg].Reg128.Low64; \
743 (a_DstVarHi) = aValues[iReg].Reg128.High64; \
744 iReg++; \
745 } while (0)
746# define GET_SEG(a_SReg, a_enmName) do { \
747 Assert(aenmNames[iReg] == (a_enmName)); \
748 NEM_WIN_COPY_BACK_SEG(a_SReg, aValues[iReg].Segment); \
749 iReg++; \
750 } while (0)
751
752 /* GPRs */
753 if (fWhat & CPUMCTX_EXTRN_GPRS_MASK)
754 {
755 if (fWhat & CPUMCTX_EXTRN_RAX)
756 GET_REG64(pVCpu->cpum.GstCtx.rax, WHvX64RegisterRax);
757 if (fWhat & CPUMCTX_EXTRN_RCX)
758 GET_REG64(pVCpu->cpum.GstCtx.rcx, WHvX64RegisterRcx);
759 if (fWhat & CPUMCTX_EXTRN_RDX)
760 GET_REG64(pVCpu->cpum.GstCtx.rdx, WHvX64RegisterRdx);
761 if (fWhat & CPUMCTX_EXTRN_RBX)
762 GET_REG64(pVCpu->cpum.GstCtx.rbx, WHvX64RegisterRbx);
763 if (fWhat & CPUMCTX_EXTRN_RSP)
764 GET_REG64(pVCpu->cpum.GstCtx.rsp, WHvX64RegisterRsp);
765 if (fWhat & CPUMCTX_EXTRN_RBP)
766 GET_REG64(pVCpu->cpum.GstCtx.rbp, WHvX64RegisterRbp);
767 if (fWhat & CPUMCTX_EXTRN_RSI)
768 GET_REG64(pVCpu->cpum.GstCtx.rsi, WHvX64RegisterRsi);
769 if (fWhat & CPUMCTX_EXTRN_RDI)
770 GET_REG64(pVCpu->cpum.GstCtx.rdi, WHvX64RegisterRdi);
771 if (fWhat & CPUMCTX_EXTRN_R8_R15)
772 {
773 GET_REG64(pVCpu->cpum.GstCtx.r8, WHvX64RegisterR8);
774 GET_REG64(pVCpu->cpum.GstCtx.r9, WHvX64RegisterR9);
775 GET_REG64(pVCpu->cpum.GstCtx.r10, WHvX64RegisterR10);
776 GET_REG64(pVCpu->cpum.GstCtx.r11, WHvX64RegisterR11);
777 GET_REG64(pVCpu->cpum.GstCtx.r12, WHvX64RegisterR12);
778 GET_REG64(pVCpu->cpum.GstCtx.r13, WHvX64RegisterR13);
779 GET_REG64(pVCpu->cpum.GstCtx.r14, WHvX64RegisterR14);
780 GET_REG64(pVCpu->cpum.GstCtx.r15, WHvX64RegisterR15);
781 }
782 }
783
784 /* RIP & Flags */
785 if (fWhat & CPUMCTX_EXTRN_RIP)
786 GET_REG64(pVCpu->cpum.GstCtx.rip, WHvX64RegisterRip);
787 if (fWhat & CPUMCTX_EXTRN_RFLAGS)
788 GET_REG64(pVCpu->cpum.GstCtx.rflags.u, WHvX64RegisterRflags);
789
790 /* Segments */
791 if (fWhat & CPUMCTX_EXTRN_SREG_MASK)
792 {
793 if (fWhat & CPUMCTX_EXTRN_ES)
794 GET_SEG(pVCpu->cpum.GstCtx.es, WHvX64RegisterEs);
795 if (fWhat & CPUMCTX_EXTRN_CS)
796 GET_SEG(pVCpu->cpum.GstCtx.cs, WHvX64RegisterCs);
797 if (fWhat & CPUMCTX_EXTRN_SS)
798 GET_SEG(pVCpu->cpum.GstCtx.ss, WHvX64RegisterSs);
799 if (fWhat & CPUMCTX_EXTRN_DS)
800 GET_SEG(pVCpu->cpum.GstCtx.ds, WHvX64RegisterDs);
801 if (fWhat & CPUMCTX_EXTRN_FS)
802 GET_SEG(pVCpu->cpum.GstCtx.fs, WHvX64RegisterFs);
803 if (fWhat & CPUMCTX_EXTRN_GS)
804 GET_SEG(pVCpu->cpum.GstCtx.gs, WHvX64RegisterGs);
805 }
806
807 /* Descriptor tables and the task segment. */
808 if (fWhat & CPUMCTX_EXTRN_TABLE_MASK)
809 {
810 if (fWhat & CPUMCTX_EXTRN_LDTR)
811 GET_SEG(pVCpu->cpum.GstCtx.ldtr, WHvX64RegisterLdtr);
812
813 if (fWhat & CPUMCTX_EXTRN_TR)
814 {
815 /* AMD-V likes loading TR with in AVAIL state, whereas intel insists on BUSY. So,
816 avoid to trigger sanity assertions around the code, always fix this. */
817 GET_SEG(pVCpu->cpum.GstCtx.tr, WHvX64RegisterTr);
818 switch (pVCpu->cpum.GstCtx.tr.Attr.n.u4Type)
819 {
820 case X86_SEL_TYPE_SYS_386_TSS_BUSY:
821 case X86_SEL_TYPE_SYS_286_TSS_BUSY:
822 break;
823 case X86_SEL_TYPE_SYS_386_TSS_AVAIL:
824 pVCpu->cpum.GstCtx.tr.Attr.n.u4Type = X86_SEL_TYPE_SYS_386_TSS_BUSY;
825 break;
826 case X86_SEL_TYPE_SYS_286_TSS_AVAIL:
827 pVCpu->cpum.GstCtx.tr.Attr.n.u4Type = X86_SEL_TYPE_SYS_286_TSS_BUSY;
828 break;
829 }
830 }
831 if (fWhat & CPUMCTX_EXTRN_IDTR)
832 {
833 Assert(aenmNames[iReg] == WHvX64RegisterIdtr);
834 pVCpu->cpum.GstCtx.idtr.cbIdt = aValues[iReg].Table.Limit;
835 pVCpu->cpum.GstCtx.idtr.pIdt = aValues[iReg].Table.Base;
836 iReg++;
837 }
838 if (fWhat & CPUMCTX_EXTRN_GDTR)
839 {
840 Assert(aenmNames[iReg] == WHvX64RegisterGdtr);
841 pVCpu->cpum.GstCtx.gdtr.cbGdt = aValues[iReg].Table.Limit;
842 pVCpu->cpum.GstCtx.gdtr.pGdt = aValues[iReg].Table.Base;
843 iReg++;
844 }
845 }
846
847 /* Control registers. */
848 bool fMaybeChangedMode = false;
849 bool fUpdateCr3 = false;
850 if (fWhat & CPUMCTX_EXTRN_CR_MASK)
851 {
852 if (fWhat & CPUMCTX_EXTRN_CR0)
853 {
854 Assert(aenmNames[iReg] == WHvX64RegisterCr0);
855 if (pVCpu->cpum.GstCtx.cr0 != aValues[iReg].Reg64)
856 {
857 CPUMSetGuestCR0(pVCpu, aValues[iReg].Reg64);
858 fMaybeChangedMode = true;
859 }
860 iReg++;
861 }
862 if (fWhat & CPUMCTX_EXTRN_CR2)
863 GET_REG64(pVCpu->cpum.GstCtx.cr2, WHvX64RegisterCr2);
864 if (fWhat & CPUMCTX_EXTRN_CR3)
865 {
866 if (pVCpu->cpum.GstCtx.cr3 != aValues[iReg].Reg64)
867 {
868 CPUMSetGuestCR3(pVCpu, aValues[iReg].Reg64);
869 fUpdateCr3 = true;
870 }
871 iReg++;
872 }
873 if (fWhat & CPUMCTX_EXTRN_CR4)
874 {
875 if (pVCpu->cpum.GstCtx.cr4 != aValues[iReg].Reg64)
876 {
877 CPUMSetGuestCR4(pVCpu, aValues[iReg].Reg64);
878 fMaybeChangedMode = true;
879 }
880 iReg++;
881 }
882 }
883 if (fWhat & CPUMCTX_EXTRN_APIC_TPR)
884 {
885 Assert(aenmNames[iReg] == WHvX64RegisterCr8);
886 APICSetTpr(pVCpu, (uint8_t)aValues[iReg].Reg64 << 4);
887 iReg++;
888 }
889
890 /* Debug registers. */
891 if (fWhat & CPUMCTX_EXTRN_DR7)
892 {
893 Assert(aenmNames[iReg] == WHvX64RegisterDr7);
894 if (pVCpu->cpum.GstCtx.dr[7] != aValues[iReg].Reg64)
895 CPUMSetGuestDR7(pVCpu, aValues[iReg].Reg64);
896 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_DR7; /* Hack alert! Avoids asserting when processing CPUMCTX_EXTRN_DR0_DR3. */
897 iReg++;
898 }
899 if (fWhat & CPUMCTX_EXTRN_DR0_DR3)
900 {
901 Assert(aenmNames[iReg] == WHvX64RegisterDr0);
902 Assert(aenmNames[iReg+3] == WHvX64RegisterDr3);
903 if (pVCpu->cpum.GstCtx.dr[0] != aValues[iReg].Reg64)
904 CPUMSetGuestDR0(pVCpu, aValues[iReg].Reg64);
905 iReg++;
906 if (pVCpu->cpum.GstCtx.dr[1] != aValues[iReg].Reg64)
907 CPUMSetGuestDR1(pVCpu, aValues[iReg].Reg64);
908 iReg++;
909 if (pVCpu->cpum.GstCtx.dr[2] != aValues[iReg].Reg64)
910 CPUMSetGuestDR2(pVCpu, aValues[iReg].Reg64);
911 iReg++;
912 if (pVCpu->cpum.GstCtx.dr[3] != aValues[iReg].Reg64)
913 CPUMSetGuestDR3(pVCpu, aValues[iReg].Reg64);
914 iReg++;
915 }
916 if (fWhat & CPUMCTX_EXTRN_DR6)
917 {
918 Assert(aenmNames[iReg] == WHvX64RegisterDr6);
919 if (pVCpu->cpum.GstCtx.dr[6] != aValues[iReg].Reg64)
920 CPUMSetGuestDR6(pVCpu, aValues[iReg].Reg64);
921 iReg++;
922 }
923
924 /* Floating point state. */
925 if (fWhat & CPUMCTX_EXTRN_X87)
926 {
927 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aRegs[0].au64[0], pVCpu->cpum.GstCtx.XState.x87.aRegs[0].au64[1], WHvX64RegisterFpMmx0);
928 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aRegs[1].au64[0], pVCpu->cpum.GstCtx.XState.x87.aRegs[1].au64[1], WHvX64RegisterFpMmx1);
929 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aRegs[2].au64[0], pVCpu->cpum.GstCtx.XState.x87.aRegs[2].au64[1], WHvX64RegisterFpMmx2);
930 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aRegs[3].au64[0], pVCpu->cpum.GstCtx.XState.x87.aRegs[3].au64[1], WHvX64RegisterFpMmx3);
931 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aRegs[4].au64[0], pVCpu->cpum.GstCtx.XState.x87.aRegs[4].au64[1], WHvX64RegisterFpMmx4);
932 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aRegs[5].au64[0], pVCpu->cpum.GstCtx.XState.x87.aRegs[5].au64[1], WHvX64RegisterFpMmx5);
933 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aRegs[6].au64[0], pVCpu->cpum.GstCtx.XState.x87.aRegs[6].au64[1], WHvX64RegisterFpMmx6);
934 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aRegs[7].au64[0], pVCpu->cpum.GstCtx.XState.x87.aRegs[7].au64[1], WHvX64RegisterFpMmx7);
935
936 Assert(aenmNames[iReg] == WHvX64RegisterFpControlStatus);
937 pVCpu->cpum.GstCtx.XState.x87.FCW = aValues[iReg].FpControlStatus.FpControl;
938 pVCpu->cpum.GstCtx.XState.x87.FSW = aValues[iReg].FpControlStatus.FpStatus;
939 pVCpu->cpum.GstCtx.XState.x87.FTW = aValues[iReg].FpControlStatus.FpTag
940 /*| (aValues[iReg].FpControlStatus.Reserved << 8)*/;
941 pVCpu->cpum.GstCtx.XState.x87.FOP = aValues[iReg].FpControlStatus.LastFpOp;
942 pVCpu->cpum.GstCtx.XState.x87.FPUIP = (uint32_t)aValues[iReg].FpControlStatus.LastFpRip;
943 pVCpu->cpum.GstCtx.XState.x87.CS = (uint16_t)(aValues[iReg].FpControlStatus.LastFpRip >> 32);
944 pVCpu->cpum.GstCtx.XState.x87.Rsrvd1 = (uint16_t)(aValues[iReg].FpControlStatus.LastFpRip >> 48);
945 iReg++;
946 }
947
948 if (fWhat & (CPUMCTX_EXTRN_X87 | CPUMCTX_EXTRN_SSE_AVX))
949 {
950 Assert(aenmNames[iReg] == WHvX64RegisterXmmControlStatus);
951 if (fWhat & CPUMCTX_EXTRN_X87)
952 {
953 pVCpu->cpum.GstCtx.XState.x87.FPUDP = (uint32_t)aValues[iReg].XmmControlStatus.LastFpRdp;
954 pVCpu->cpum.GstCtx.XState.x87.DS = (uint16_t)(aValues[iReg].XmmControlStatus.LastFpRdp >> 32);
955 pVCpu->cpum.GstCtx.XState.x87.Rsrvd2 = (uint16_t)(aValues[iReg].XmmControlStatus.LastFpRdp >> 48);
956 }
957 pVCpu->cpum.GstCtx.XState.x87.MXCSR = aValues[iReg].XmmControlStatus.XmmStatusControl;
958 pVCpu->cpum.GstCtx.XState.x87.MXCSR_MASK = aValues[iReg].XmmControlStatus.XmmStatusControlMask; /** @todo ??? (Isn't this an output field?) */
959 iReg++;
960 }
961
962 /* Vector state. */
963 if (fWhat & CPUMCTX_EXTRN_SSE_AVX)
964 {
965 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aXMM[ 0].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 0].uXmm.s.Hi, WHvX64RegisterXmm0);
966 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aXMM[ 1].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 1].uXmm.s.Hi, WHvX64RegisterXmm1);
967 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aXMM[ 2].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 2].uXmm.s.Hi, WHvX64RegisterXmm2);
968 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aXMM[ 3].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 3].uXmm.s.Hi, WHvX64RegisterXmm3);
969 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aXMM[ 4].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 4].uXmm.s.Hi, WHvX64RegisterXmm4);
970 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aXMM[ 5].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 5].uXmm.s.Hi, WHvX64RegisterXmm5);
971 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aXMM[ 6].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 6].uXmm.s.Hi, WHvX64RegisterXmm6);
972 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aXMM[ 7].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 7].uXmm.s.Hi, WHvX64RegisterXmm7);
973 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aXMM[ 8].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 8].uXmm.s.Hi, WHvX64RegisterXmm8);
974 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aXMM[ 9].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 9].uXmm.s.Hi, WHvX64RegisterXmm9);
975 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aXMM[10].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[10].uXmm.s.Hi, WHvX64RegisterXmm10);
976 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aXMM[11].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[11].uXmm.s.Hi, WHvX64RegisterXmm11);
977 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aXMM[12].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[12].uXmm.s.Hi, WHvX64RegisterXmm12);
978 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aXMM[13].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[13].uXmm.s.Hi, WHvX64RegisterXmm13);
979 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aXMM[14].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[14].uXmm.s.Hi, WHvX64RegisterXmm14);
980 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aXMM[15].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[15].uXmm.s.Hi, WHvX64RegisterXmm15);
981 }
982
983 /* MSRs */
984 // WHvX64RegisterTsc - don't touch
985 if (fWhat & CPUMCTX_EXTRN_EFER)
986 {
987 Assert(aenmNames[iReg] == WHvX64RegisterEfer);
988 if (aValues[iReg].Reg64 != pVCpu->cpum.GstCtx.msrEFER)
989 {
990 Log7(("NEM/%u: MSR EFER changed %RX64 -> %RX64\n", pVCpu->idCpu, pVCpu->cpum.GstCtx.msrEFER, aValues[iReg].Reg64));
991 if ((aValues[iReg].Reg64 ^ pVCpu->cpum.GstCtx.msrEFER) & MSR_K6_EFER_NXE)
992 PGMNotifyNxeChanged(pVCpu, RT_BOOL(aValues[iReg].Reg64 & MSR_K6_EFER_NXE));
993 pVCpu->cpum.GstCtx.msrEFER = aValues[iReg].Reg64;
994 fMaybeChangedMode = true;
995 }
996 iReg++;
997 }
998 if (fWhat & CPUMCTX_EXTRN_KERNEL_GS_BASE)
999 GET_REG64_LOG7(pVCpu->cpum.GstCtx.msrKERNELGSBASE, WHvX64RegisterKernelGsBase, "MSR KERNEL_GS_BASE");
1000 if (fWhat & CPUMCTX_EXTRN_SYSENTER_MSRS)
1001 {
1002 GET_REG64_LOG7(pVCpu->cpum.GstCtx.SysEnter.cs, WHvX64RegisterSysenterCs, "MSR SYSENTER.CS");
1003 GET_REG64_LOG7(pVCpu->cpum.GstCtx.SysEnter.eip, WHvX64RegisterSysenterEip, "MSR SYSENTER.EIP");
1004 GET_REG64_LOG7(pVCpu->cpum.GstCtx.SysEnter.esp, WHvX64RegisterSysenterEsp, "MSR SYSENTER.ESP");
1005 }
1006 if (fWhat & CPUMCTX_EXTRN_SYSCALL_MSRS)
1007 {
1008 GET_REG64_LOG7(pVCpu->cpum.GstCtx.msrSTAR, WHvX64RegisterStar, "MSR STAR");
1009 GET_REG64_LOG7(pVCpu->cpum.GstCtx.msrLSTAR, WHvX64RegisterLstar, "MSR LSTAR");
1010 GET_REG64_LOG7(pVCpu->cpum.GstCtx.msrCSTAR, WHvX64RegisterCstar, "MSR CSTAR");
1011 GET_REG64_LOG7(pVCpu->cpum.GstCtx.msrSFMASK, WHvX64RegisterSfmask, "MSR SFMASK");
1012 }
1013 if (fWhat & CPUMCTX_EXTRN_OTHER_MSRS)
1014 {
1015 Assert(aenmNames[iReg] == WHvX64RegisterApicBase);
1016 const uint64_t uOldBase = APICGetBaseMsrNoCheck(pVCpu);
1017 if (aValues[iReg].Reg64 != uOldBase)
1018 {
1019 Log7(("NEM/%u: MSR APICBase changed %RX64 -> %RX64 (%RX64)\n",
1020 pVCpu->idCpu, uOldBase, aValues[iReg].Reg64, aValues[iReg].Reg64 ^ uOldBase));
1021 int rc2 = APICSetBaseMsr(pVCpu, aValues[iReg].Reg64);
1022 AssertLogRelMsg(rc2 == VINF_SUCCESS, ("%Rrc %RX64\n", rc2, aValues[iReg].Reg64));
1023 }
1024 iReg++;
1025
1026 GET_REG64_LOG7(pVCpu->cpum.GstCtx.msrPAT, WHvX64RegisterPat, "MSR PAT");
1027#if 0 /*def LOG_ENABLED*/ /** @todo something's wrong with HvX64RegisterMtrrCap? (AMD) */
1028 GET_REG64_LOG7(pVCpu->cpum.GstCtx.msrPAT, WHvX64RegisterMsrMtrrCap);
1029#endif
1030 PCPUMCTXMSRS pCtxMsrs = CPUMQueryGuestCtxMsrsPtr(pVCpu);
1031 GET_REG64_LOG7(pCtxMsrs->msr.MtrrDefType, WHvX64RegisterMsrMtrrDefType, "MSR MTRR_DEF_TYPE");
1032 GET_REG64_LOG7(pCtxMsrs->msr.MtrrFix64K_00000, WHvX64RegisterMsrMtrrFix64k00000, "MSR MTRR_FIX_64K_00000");
1033 GET_REG64_LOG7(pCtxMsrs->msr.MtrrFix16K_80000, WHvX64RegisterMsrMtrrFix16k80000, "MSR MTRR_FIX_16K_80000");
1034 GET_REG64_LOG7(pCtxMsrs->msr.MtrrFix16K_A0000, WHvX64RegisterMsrMtrrFix16kA0000, "MSR MTRR_FIX_16K_A0000");
1035 GET_REG64_LOG7(pCtxMsrs->msr.MtrrFix4K_C0000, WHvX64RegisterMsrMtrrFix4kC0000, "MSR MTRR_FIX_4K_C0000");
1036 GET_REG64_LOG7(pCtxMsrs->msr.MtrrFix4K_C8000, WHvX64RegisterMsrMtrrFix4kC8000, "MSR MTRR_FIX_4K_C8000");
1037 GET_REG64_LOG7(pCtxMsrs->msr.MtrrFix4K_D0000, WHvX64RegisterMsrMtrrFix4kD0000, "MSR MTRR_FIX_4K_D0000");
1038 GET_REG64_LOG7(pCtxMsrs->msr.MtrrFix4K_D8000, WHvX64RegisterMsrMtrrFix4kD8000, "MSR MTRR_FIX_4K_D8000");
1039 GET_REG64_LOG7(pCtxMsrs->msr.MtrrFix4K_E0000, WHvX64RegisterMsrMtrrFix4kE0000, "MSR MTRR_FIX_4K_E0000");
1040 GET_REG64_LOG7(pCtxMsrs->msr.MtrrFix4K_E8000, WHvX64RegisterMsrMtrrFix4kE8000, "MSR MTRR_FIX_4K_E8000");
1041 GET_REG64_LOG7(pCtxMsrs->msr.MtrrFix4K_F0000, WHvX64RegisterMsrMtrrFix4kF0000, "MSR MTRR_FIX_4K_F0000");
1042 GET_REG64_LOG7(pCtxMsrs->msr.MtrrFix4K_F8000, WHvX64RegisterMsrMtrrFix4kF8000, "MSR MTRR_FIX_4K_F8000");
1043 GET_REG64_LOG7(pCtxMsrs->msr.TscAux, WHvX64RegisterTscAux, "MSR TSC_AUX");
1044 /** @todo look for HvX64RegisterIa32MiscEnable and HvX64RegisterIa32FeatureControl? */
1045 }
1046
1047 /* Interruptibility. */
1048 if (fWhat & (CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT | CPUMCTX_EXTRN_NEM_WIN_INHIBIT_NMI))
1049 {
1050 Assert(aenmNames[iReg] == WHvRegisterInterruptState);
1051 Assert(aenmNames[iReg + 1] == WHvX64RegisterRip);
1052
1053 if (!(pVCpu->cpum.GstCtx.fExtrn & CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT))
1054 {
1055 pVCpu->nem.s.fLastInterruptShadow = aValues[iReg].InterruptState.InterruptShadow;
1056 if (aValues[iReg].InterruptState.InterruptShadow)
1057 EMSetInhibitInterruptsPC(pVCpu, aValues[iReg + 1].Reg64);
1058 else
1059 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
1060 }
1061
1062 if (!(pVCpu->cpum.GstCtx.fExtrn & CPUMCTX_EXTRN_NEM_WIN_INHIBIT_NMI))
1063 {
1064 if (aValues[iReg].InterruptState.NmiMasked)
1065 VMCPU_FF_SET(pVCpu, VMCPU_FF_BLOCK_NMIS);
1066 else
1067 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_BLOCK_NMIS);
1068 }
1069
1070 fWhat |= CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT | CPUMCTX_EXTRN_NEM_WIN_INHIBIT_NMI;
1071 iReg += 2;
1072 }
1073
1074 /* Event injection. */
1075 /// @todo WHvRegisterPendingInterruption
1076 Assert(aenmNames[iReg] == WHvRegisterPendingInterruption);
1077 if (aValues[iReg].PendingInterruption.InterruptionPending)
1078 {
1079 Log7(("PendingInterruption: type=%u vector=%#x errcd=%RTbool/%#x instr-len=%u nested=%u\n",
1080 aValues[iReg].PendingInterruption.InterruptionType, aValues[iReg].PendingInterruption.InterruptionVector,
1081 aValues[iReg].PendingInterruption.DeliverErrorCode, aValues[iReg].PendingInterruption.ErrorCode,
1082 aValues[iReg].PendingInterruption.InstructionLength, aValues[iReg].PendingInterruption.NestedEvent));
1083 AssertMsg((aValues[iReg].PendingInterruption.AsUINT64 & UINT64_C(0xfc00)) == 0,
1084 ("%#RX64\n", aValues[iReg].PendingInterruption.AsUINT64));
1085 }
1086
1087 /// @todo WHvRegisterPendingEvent0 (renamed to WHvRegisterPendingEvent).
1088
1089 /* Almost done, just update extrn flags and maybe change PGM mode. */
1090 pVCpu->cpum.GstCtx.fExtrn &= ~fWhat;
1091 if (!(pVCpu->cpum.GstCtx.fExtrn & (CPUMCTX_EXTRN_ALL | (CPUMCTX_EXTRN_NEM_WIN_MASK & ~CPUMCTX_EXTRN_NEM_WIN_EVENT_INJECT))))
1092 pVCpu->cpum.GstCtx.fExtrn = 0;
1093
1094 /* Typical. */
1095 if (!fMaybeChangedMode && !fUpdateCr3)
1096 return VINF_SUCCESS;
1097
1098 /*
1099 * Slow.
1100 */
1101 if (fMaybeChangedMode)
1102 {
1103 int rc = PGMChangeMode(pVCpu, pVCpu->cpum.GstCtx.cr0, pVCpu->cpum.GstCtx.cr4, pVCpu->cpum.GstCtx.msrEFER);
1104 AssertMsgReturn(rc == VINF_SUCCESS, ("rc=%Rrc\n", rc), RT_FAILURE_NP(rc) ? rc : VERR_NEM_IPE_1);
1105 }
1106
1107 if (fUpdateCr3)
1108 {
1109 int rc = PGMUpdateCR3(pVCpu, pVCpu->cpum.GstCtx.cr3, false /*fPdpesMapped*/);
1110 if (rc == VINF_SUCCESS)
1111 { /* likely */ }
1112 else
1113 AssertMsgFailedReturn(("rc=%Rrc\n", rc), RT_FAILURE_NP(rc) ? rc : VERR_NEM_IPE_2);
1114 }
1115
1116 return VINF_SUCCESS;
1117# endif /* !NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS */
1118}
1119
1120#endif /* !IN_RING0 */
1121
1122
1123/**
1124 * Interface for importing state on demand (used by IEM).
1125 *
1126 * @returns VBox status code.
1127 * @param pVCpu The cross context CPU structure.
1128 * @param fWhat What to import, CPUMCTX_EXTRN_XXX.
1129 */
1130VMM_INT_DECL(int) NEMImportStateOnDemand(PVMCPUCC pVCpu, uint64_t fWhat)
1131{
1132 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatImportOnDemand);
1133
1134#ifdef IN_RING0
1135# ifdef NEM_WIN_WITH_RING0_RUNLOOP
1136 return nemR0WinImportState(pVCpu->pGVM, pVCpu, &pVCpu->cpum.GstCtx, fWhat, true /*fCanUpdateCr3*/);
1137# else
1138 RT_NOREF(pVCpu, fWhat);
1139 return VERR_NOT_IMPLEMENTED;
1140# endif
1141#else
1142 return nemHCWinCopyStateFromHyperV(pVCpu->pVMR3, pVCpu, fWhat);
1143#endif
1144}
1145
1146
1147/**
1148 * Query the CPU tick counter and optionally the TSC_AUX MSR value.
1149 *
1150 * @returns VBox status code.
1151 * @param pVCpu The cross context CPU structure.
1152 * @param pcTicks Where to return the CPU tick count.
1153 * @param puAux Where to return the TSC_AUX register value.
1154 */
1155VMM_INT_DECL(int) NEMHCQueryCpuTick(PVMCPUCC pVCpu, uint64_t *pcTicks, uint32_t *puAux)
1156{
1157 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatQueryCpuTick);
1158
1159#ifdef IN_RING3
1160 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
1161 VMCPU_ASSERT_EMT_RETURN(pVCpu, VERR_VM_THREAD_NOT_EMT);
1162 AssertReturn(VM_IS_NEM_ENABLED(pVM), VERR_NEM_IPE_9);
1163
1164# if defined(NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS) || defined(NEM_WIN_WITH_RING0_RUNLOOP)
1165# if !defined(NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS) && defined(NEM_WIN_WITH_RING0_RUNLOOP)
1166 if (pVM->nem.s.fUseRing0Runloop)
1167# endif
1168 {
1169 /* Call ring-0 and get the values. */
1170 int rc = VMMR3CallR0Emt(pVM, pVCpu, VMMR0_DO_NEM_QUERY_CPU_TICK, 0, NULL);
1171 AssertLogRelRCReturn(rc, rc);
1172 *pcTicks = pVCpu->nem.s.Hypercall.QueryCpuTick.cTicks;
1173 if (puAux)
1174 *puAux = pVCpu->cpum.GstCtx.fExtrn & CPUMCTX_EXTRN_TSC_AUX
1175 ? pVCpu->nem.s.Hypercall.QueryCpuTick.uAux : CPUMGetGuestTscAux(pVCpu);
1176 return VINF_SUCCESS;
1177 }
1178# endif
1179# ifndef NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS
1180 /* Call the offical API. */
1181 WHV_REGISTER_NAME aenmNames[2] = { WHvX64RegisterTsc, WHvX64RegisterTscAux };
1182 WHV_REGISTER_VALUE aValues[2] = { {0, 0}, {0, 0} };
1183 Assert(RT_ELEMENTS(aenmNames) == RT_ELEMENTS(aValues));
1184 HRESULT hrc = WHvGetVirtualProcessorRegisters(pVM->nem.s.hPartition, pVCpu->idCpu, aenmNames, 2, aValues);
1185 AssertLogRelMsgReturn(SUCCEEDED(hrc),
1186 ("WHvGetVirtualProcessorRegisters(%p, %u,{tsc,tsc_aux},2,) -> %Rhrc (Last=%#x/%u)\n",
1187 pVM->nem.s.hPartition, pVCpu->idCpu, hrc, RTNtLastStatusValue(), RTNtLastErrorValue())
1188 , VERR_NEM_GET_REGISTERS_FAILED);
1189 *pcTicks = aValues[0].Reg64;
1190 if (puAux)
1191 *pcTicks = pVCpu->cpum.GstCtx.fExtrn & CPUMCTX_EXTRN_TSC_AUX ? aValues[0].Reg64 : CPUMGetGuestTscAux(pVCpu);
1192 return VINF_SUCCESS;
1193# endif /* !NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS */
1194#else /* IN_RING0 */
1195# ifdef NEM_WIN_WITH_RING0_RUNLOOP
1196 int rc = nemR0WinQueryCpuTick(pVCpu->pGVM, pVCpu, pcTicks, puAux);
1197 if (RT_SUCCESS(rc) && puAux && !(pVCpu->cpum.GstCtx.fExtrn & CPUMCTX_EXTRN_TSC_AUX))
1198 *puAux = CPUMGetGuestTscAux(pVCpu);
1199 return rc;
1200# else
1201 RT_NOREF(pVCpu, pcTicks, puAux);
1202 return VERR_NOT_IMPLEMENTED;
1203# endif
1204#endif /* IN_RING0 */
1205}
1206
1207
1208/**
1209 * Resumes CPU clock (TSC) on all virtual CPUs.
1210 *
1211 * This is called by TM when the VM is started, restored, resumed or similar.
1212 *
1213 * @returns VBox status code.
1214 * @param pVM The cross context VM structure.
1215 * @param pVCpu The cross context CPU structure of the calling EMT.
1216 * @param uPausedTscValue The TSC value at the time of pausing.
1217 */
1218VMM_INT_DECL(int) NEMHCResumeCpuTickOnAll(PVMCC pVM, PVMCPUCC pVCpu, uint64_t uPausedTscValue)
1219{
1220#ifdef IN_RING0
1221# ifdef NEM_WIN_WITH_RING0_RUNLOOP
1222 return nemR0WinResumeCpuTickOnAll(pVM, pVCpu, uPausedTscValue);
1223# else
1224 RT_NOREF(pVM, pVCpu, uPausedTscValue);
1225 return VERR_NOT_IMPLEMENTED;
1226# endif
1227#else /* IN_RING3 */
1228 VMCPU_ASSERT_EMT_RETURN(pVCpu, VERR_VM_THREAD_NOT_EMT);
1229 AssertReturn(VM_IS_NEM_ENABLED(pVM), VERR_NEM_IPE_9);
1230
1231# if defined(NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS) || defined(NEM_WIN_WITH_RING0_RUNLOOP)
1232# if !defined(NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS) && defined(NEM_WIN_WITH_RING0_RUNLOOP)
1233 if (pVM->nem.s.fUseRing0Runloop)
1234# endif
1235 {
1236 /* Call ring-0 and do it all there. */
1237 return VMMR3CallR0Emt(pVM, pVCpu, VMMR0_DO_NEM_RESUME_CPU_TICK_ON_ALL, uPausedTscValue, NULL);
1238 }
1239# endif
1240# ifndef NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS
1241 /*
1242 * Call the offical API to do the job.
1243 */
1244 if (pVM->cCpus > 1)
1245 RTThreadYield(); /* Try decrease the chance that we get rescheduled in the middle. */
1246
1247 /* Start with the first CPU. */
1248 WHV_REGISTER_NAME enmName = WHvX64RegisterTsc;
1249 WHV_REGISTER_VALUE Value = {0, 0};
1250 Value.Reg64 = uPausedTscValue;
1251 uint64_t const uFirstTsc = ASMReadTSC();
1252 HRESULT hrc = WHvSetVirtualProcessorRegisters(pVM->nem.s.hPartition, 0 /*iCpu*/, &enmName, 1, &Value);
1253 AssertLogRelMsgReturn(SUCCEEDED(hrc),
1254 ("WHvSetVirtualProcessorRegisters(%p, 0,{tsc},2,%#RX64) -> %Rhrc (Last=%#x/%u)\n",
1255 pVM->nem.s.hPartition, uPausedTscValue, hrc, RTNtLastStatusValue(), RTNtLastErrorValue())
1256 , VERR_NEM_SET_TSC);
1257
1258 /* Do the other CPUs, adjusting for elapsed TSC and keeping finger crossed
1259 that we don't introduce too much drift here. */
1260 for (VMCPUID iCpu = 1; iCpu < pVM->cCpus; iCpu++)
1261 {
1262 Assert(enmName == WHvX64RegisterTsc);
1263 const uint64_t offDelta = (ASMReadTSC() - uFirstTsc);
1264 Value.Reg64 = uPausedTscValue + offDelta;
1265 hrc = WHvSetVirtualProcessorRegisters(pVM->nem.s.hPartition, iCpu, &enmName, 1, &Value);
1266 AssertLogRelMsgReturn(SUCCEEDED(hrc),
1267 ("WHvSetVirtualProcessorRegisters(%p, 0,{tsc},2,%#RX64 + %#RX64) -> %Rhrc (Last=%#x/%u)\n",
1268 pVM->nem.s.hPartition, iCpu, uPausedTscValue, offDelta, hrc, RTNtLastStatusValue(), RTNtLastErrorValue())
1269 , VERR_NEM_SET_TSC);
1270 }
1271
1272 return VINF_SUCCESS;
1273# endif /* !NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS */
1274#endif /* IN_RING3 */
1275}
1276
1277#ifdef NEMWIN_NEED_GET_REGISTER
1278# if defined(IN_RING0) || defined(NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS)
1279/** Worker for assertion macro. */
1280NEM_TMPL_STATIC int nemHCWinGetRegister(PVMCPUCC pVCpu, PGVMCPU pGVCpu, uint32_t enmReg, HV_REGISTER_VALUE *pRetValue)
1281{
1282 RT_ZERO(*pRetValue);
1283# ifdef IN_RING3
1284 RT_NOREF(pVCpu, pGVCpu, enmReg);
1285 return VERR_NOT_IMPLEMENTED;
1286# else
1287 NOREF(pVCpu);
1288
1289 /*
1290 * Hypercall parameters.
1291 */
1292 HV_INPUT_GET_VP_REGISTERS *pInput = (HV_INPUT_GET_VP_REGISTERS *)pGVCpu->nem.s.HypercallData.pbPage;
1293 AssertPtrReturn(pInput, VERR_INTERNAL_ERROR_3);
1294 AssertReturn(g_pfnHvlInvokeHypercall, VERR_NEM_MISSING_KERNEL_API);
1295
1296 pInput->PartitionId = pVCpu->pGVM->nemr0.s.idHvPartition;
1297 pInput->VpIndex = pVCpu->idCpu;
1298 pInput->fFlags = 0;
1299 pInput->Names[0] = (HV_REGISTER_NAME)enmReg;
1300
1301 size_t const cbInput = RT_ALIGN_Z(RT_UOFFSETOF(HV_INPUT_GET_VP_REGISTERS, Names[1]), 32);
1302 HV_REGISTER_VALUE *paValues = (HV_REGISTER_VALUE *)((uint8_t *)pInput + cbInput);
1303 RT_BZERO(paValues, sizeof(paValues[0]) * 1);
1304
1305 /*
1306 * Make the hypercall and copy out the value.
1307 */
1308 uint64_t uResult = g_pfnHvlInvokeHypercall(HV_MAKE_CALL_INFO(HvCallGetVpRegisters, 1),
1309 pGVCpu->nem.s.HypercallData.HCPhysPage,
1310 pGVCpu->nem.s.HypercallData.HCPhysPage + cbInput);
1311 AssertLogRelMsgReturn(uResult == HV_MAKE_CALL_REP_RET(1), ("uResult=%RX64 cRegs=%#x\n", uResult, 1),
1312 VERR_NEM_GET_REGISTERS_FAILED);
1313
1314 *pRetValue = paValues[0];
1315 return VINF_SUCCESS;
1316# endif
1317}
1318# else
1319/** Worker for assertion macro. */
1320NEM_TMPL_STATIC int nemR3WinGetRegister(PVMCPUCC a_pVCpu, uint32_t a_enmReg, WHV_REGISTER_VALUE pValue)
1321{
1322 RT_ZERO(*pRetValue);
1323 RT_NOREF(pVCpu, pGVCpu, enmReg);
1324 return VERR_NOT_IMPLEMENTED;
1325}
1326# endif
1327#endif
1328
1329
1330#ifdef LOG_ENABLED
1331/**
1332 * Get the virtual processor running status.
1333 */
1334DECLINLINE(VID_PROCESSOR_STATUS) nemHCWinCpuGetRunningStatus(PVMCPUCC pVCpu)
1335{
1336# ifdef IN_RING0
1337 NOREF(pVCpu);
1338 return VidProcessorStatusUndefined;
1339# else
1340 RTERRVARS Saved;
1341 RTErrVarsSave(&Saved);
1342
1343 /*
1344 * This API is disabled in release builds, it seems. On build 17101 it requires
1345 * the following patch to be enabled (windbg): eb vid+12180 0f 84 98 00 00 00
1346 */
1347 VID_PROCESSOR_STATUS enmCpuStatus = VidProcessorStatusUndefined;
1348 NTSTATUS rcNt = g_pfnVidGetVirtualProcessorRunningStatus(pVCpu->pVMR3->nem.s.hPartitionDevice, pVCpu->idCpu, &enmCpuStatus);
1349 AssertRC(rcNt);
1350
1351 RTErrVarsRestore(&Saved);
1352 return enmCpuStatus;
1353# endif
1354}
1355#endif /* LOG_ENABLED */
1356
1357
1358#if defined(NEM_WIN_USE_OUR_OWN_RUN_API) || defined(NEM_WIN_WITH_RING0_RUNLOOP)
1359# ifdef IN_RING3 /* hopefully not needed in ring-0, as we'd need KTHREADs and KeAlertThread. */
1360/**
1361 * Our own WHvCancelRunVirtualProcessor that can later be moved to ring-0.
1362 *
1363 * This is an experiment only.
1364 *
1365 * @returns VBox status code.
1366 * @param pVM The cross context VM structure.
1367 * @param pVCpu The cross context virtual CPU structure of the
1368 * calling EMT.
1369 */
1370NEM_TMPL_STATIC int nemHCWinCancelRunVirtualProcessor(PVMCC pVM, PVMCPUCC pVCpu)
1371{
1372 /*
1373 * Work the state.
1374 *
1375 * From the looks of things, we should let the EMT call VidStopVirtualProcessor.
1376 * So, we just need to modify the state and kick the EMT if it's waiting on
1377 * messages. For the latter we use QueueUserAPC / KeAlterThread.
1378 */
1379 for (;;)
1380 {
1381 VMCPUSTATE enmState = VMCPU_GET_STATE(pVCpu);
1382 switch (enmState)
1383 {
1384 case VMCPUSTATE_STARTED_EXEC_NEM:
1385 if (VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC_NEM_CANCELED, VMCPUSTATE_STARTED_EXEC_NEM))
1386 {
1387 DBGFTRACE_CUSTOM(pVM, "VMCPUSTATE_STARTED_EXEC_NEM -> CANCELED");
1388 Log8(("nemHCWinCancelRunVirtualProcessor: Switched %u to canceled state\n", pVCpu->idCpu));
1389 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatCancelChangedState);
1390 return VINF_SUCCESS;
1391 }
1392 break;
1393
1394 case VMCPUSTATE_STARTED_EXEC_NEM_WAIT:
1395 if (VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC_NEM_CANCELED, VMCPUSTATE_STARTED_EXEC_NEM_WAIT))
1396 {
1397 DBGFTRACE_CUSTOM(pVM, "VMCPUSTATE_STARTED_EXEC_NEM_WAIT -> CANCELED");
1398# ifdef IN_RING0
1399 NTSTATUS rcNt = KeAlertThread(??);
1400 DBGFTRACE_CUSTOM(pVM, "KeAlertThread -> %#x", rcNt);
1401# else
1402 NTSTATUS rcNt = NtAlertThread(pVCpu->nem.s.hNativeThreadHandle);
1403 DBGFTRACE_CUSTOM(pVM, "NtAlertThread -> %#x", rcNt);
1404# endif
1405 Log8(("nemHCWinCancelRunVirtualProcessor: Alerted %u: %#x\n", pVCpu->idCpu, rcNt));
1406 Assert(rcNt == STATUS_SUCCESS);
1407 if (NT_SUCCESS(rcNt))
1408 {
1409 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatCancelAlertedThread);
1410 return VINF_SUCCESS;
1411 }
1412 AssertLogRelMsgFailedReturn(("NtAlertThread failed: %#x\n", rcNt), RTErrConvertFromNtStatus(rcNt));
1413 }
1414 break;
1415
1416 default:
1417 return VINF_SUCCESS;
1418 }
1419
1420 ASMNopPause();
1421 RT_NOREF(pVM);
1422 }
1423}
1424# endif /* IN_RING3 */
1425#endif /* NEM_WIN_USE_OUR_OWN_RUN_API || NEM_WIN_WITH_RING0_RUNLOOP */
1426
1427
1428#ifdef LOG_ENABLED
1429/**
1430 * Logs the current CPU state.
1431 */
1432NEM_TMPL_STATIC void nemHCWinLogState(PVMCC pVM, PVMCPUCC pVCpu)
1433{
1434 if (LogIs3Enabled())
1435 {
1436# if 0 // def IN_RING3 - causes lazy state import assertions all over CPUM.
1437 char szRegs[4096];
1438 DBGFR3RegPrintf(pVM->pUVM, pVCpu->idCpu, &szRegs[0], sizeof(szRegs),
1439 "rax=%016VR{rax} rbx=%016VR{rbx} rcx=%016VR{rcx} rdx=%016VR{rdx}\n"
1440 "rsi=%016VR{rsi} rdi=%016VR{rdi} r8 =%016VR{r8} r9 =%016VR{r9}\n"
1441 "r10=%016VR{r10} r11=%016VR{r11} r12=%016VR{r12} r13=%016VR{r13}\n"
1442 "r14=%016VR{r14} r15=%016VR{r15} %VRF{rflags}\n"
1443 "rip=%016VR{rip} rsp=%016VR{rsp} rbp=%016VR{rbp}\n"
1444 "cs={%04VR{cs} base=%016VR{cs_base} limit=%08VR{cs_lim} flags=%04VR{cs_attr}} cr0=%016VR{cr0}\n"
1445 "ds={%04VR{ds} base=%016VR{ds_base} limit=%08VR{ds_lim} flags=%04VR{ds_attr}} cr2=%016VR{cr2}\n"
1446 "es={%04VR{es} base=%016VR{es_base} limit=%08VR{es_lim} flags=%04VR{es_attr}} cr3=%016VR{cr3}\n"
1447 "fs={%04VR{fs} base=%016VR{fs_base} limit=%08VR{fs_lim} flags=%04VR{fs_attr}} cr4=%016VR{cr4}\n"
1448 "gs={%04VR{gs} base=%016VR{gs_base} limit=%08VR{gs_lim} flags=%04VR{gs_attr}} cr8=%016VR{cr8}\n"
1449 "ss={%04VR{ss} base=%016VR{ss_base} limit=%08VR{ss_lim} flags=%04VR{ss_attr}}\n"
1450 "dr0=%016VR{dr0} dr1=%016VR{dr1} dr2=%016VR{dr2} dr3=%016VR{dr3}\n"
1451 "dr6=%016VR{dr6} dr7=%016VR{dr7}\n"
1452 "gdtr=%016VR{gdtr_base}:%04VR{gdtr_lim} idtr=%016VR{idtr_base}:%04VR{idtr_lim} rflags=%08VR{rflags}\n"
1453 "ldtr={%04VR{ldtr} base=%016VR{ldtr_base} limit=%08VR{ldtr_lim} flags=%08VR{ldtr_attr}}\n"
1454 "tr ={%04VR{tr} base=%016VR{tr_base} limit=%08VR{tr_lim} flags=%08VR{tr_attr}}\n"
1455 " sysenter={cs=%04VR{sysenter_cs} eip=%08VR{sysenter_eip} esp=%08VR{sysenter_esp}}\n"
1456 " efer=%016VR{efer}\n"
1457 " pat=%016VR{pat}\n"
1458 " sf_mask=%016VR{sf_mask}\n"
1459 "krnl_gs_base=%016VR{krnl_gs_base}\n"
1460 " lstar=%016VR{lstar}\n"
1461 " star=%016VR{star} cstar=%016VR{cstar}\n"
1462 "fcw=%04VR{fcw} fsw=%04VR{fsw} ftw=%04VR{ftw} mxcsr=%04VR{mxcsr} mxcsr_mask=%04VR{mxcsr_mask}\n"
1463 );
1464
1465 char szInstr[256];
1466 DBGFR3DisasInstrEx(pVM->pUVM, pVCpu->idCpu, 0, 0,
1467 DBGF_DISAS_FLAGS_CURRENT_GUEST | DBGF_DISAS_FLAGS_DEFAULT_MODE,
1468 szInstr, sizeof(szInstr), NULL);
1469 Log3(("%s%s\n", szRegs, szInstr));
1470# else
1471 /** @todo stat logging in ring-0 */
1472 RT_NOREF(pVM, pVCpu);
1473# endif
1474 }
1475}
1476#endif /* LOG_ENABLED */
1477
1478
1479/** Macro used by nemHCWinExecStateToLogStr and nemR3WinExecStateToLogStr. */
1480#define SWITCH_IT(a_szPrefix) \
1481 do \
1482 switch (u)\
1483 { \
1484 case 0x00: return a_szPrefix ""; \
1485 case 0x01: return a_szPrefix ",Pnd"; \
1486 case 0x02: return a_szPrefix ",Dbg"; \
1487 case 0x03: return a_szPrefix ",Pnd,Dbg"; \
1488 case 0x04: return a_szPrefix ",Shw"; \
1489 case 0x05: return a_szPrefix ",Pnd,Shw"; \
1490 case 0x06: return a_szPrefix ",Shw,Dbg"; \
1491 case 0x07: return a_szPrefix ",Pnd,Shw,Dbg"; \
1492 default: AssertFailedReturn("WTF?"); \
1493 } \
1494 while (0)
1495
1496#ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
1497/**
1498 * Translates the execution stat bitfield into a short log string, VID version.
1499 *
1500 * @returns Read-only log string.
1501 * @param pMsgHdr The header which state to summarize.
1502 */
1503static const char *nemHCWinExecStateToLogStr(HV_X64_INTERCEPT_MESSAGE_HEADER const *pMsgHdr)
1504{
1505 unsigned u = (unsigned)pMsgHdr->ExecutionState.InterruptionPending
1506 | ((unsigned)pMsgHdr->ExecutionState.DebugActive << 1)
1507 | ((unsigned)pMsgHdr->ExecutionState.InterruptShadow << 2);
1508 if (pMsgHdr->ExecutionState.EferLma)
1509 SWITCH_IT("LM");
1510 else if (pMsgHdr->ExecutionState.Cr0Pe)
1511 SWITCH_IT("PM");
1512 else
1513 SWITCH_IT("RM");
1514}
1515#elif defined(IN_RING3)
1516/**
1517 * Translates the execution stat bitfield into a short log string, WinHv version.
1518 *
1519 * @returns Read-only log string.
1520 * @param pExitCtx The exit context which state to summarize.
1521 */
1522static const char *nemR3WinExecStateToLogStr(WHV_VP_EXIT_CONTEXT const *pExitCtx)
1523{
1524 unsigned u = (unsigned)pExitCtx->ExecutionState.InterruptionPending
1525 | ((unsigned)pExitCtx->ExecutionState.DebugActive << 1)
1526 | ((unsigned)pExitCtx->ExecutionState.InterruptShadow << 2);
1527 if (pExitCtx->ExecutionState.EferLma)
1528 SWITCH_IT("LM");
1529 else if (pExitCtx->ExecutionState.Cr0Pe)
1530 SWITCH_IT("PM");
1531 else
1532 SWITCH_IT("RM");
1533}
1534#endif /* IN_RING3 && !NEM_WIN_TEMPLATE_MODE_OWN_RUN_API */
1535#undef SWITCH_IT
1536
1537
1538#ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
1539/**
1540 * Advances the guest RIP and clear EFLAGS.RF, VID version.
1541 *
1542 * This may clear VMCPU_FF_INHIBIT_INTERRUPTS.
1543 *
1544 * @param pVCpu The cross context virtual CPU structure.
1545 * @param pExitCtx The exit context.
1546 * @param cbMinInstr The minimum instruction length, or 1 if not unknown.
1547 */
1548DECLINLINE(void)
1549nemHCWinAdvanceGuestRipAndClearRF(PVMCPUCC pVCpu, HV_X64_INTERCEPT_MESSAGE_HEADER const *pMsgHdr, uint8_t cbMinInstr)
1550{
1551 Assert(!(pVCpu->cpum.GstCtx.fExtrn & (CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS)));
1552
1553 /* Advance the RIP. */
1554 Assert(pMsgHdr->InstructionLength >= cbMinInstr); RT_NOREF_PV(cbMinInstr);
1555 pVCpu->cpum.GstCtx.rip += pMsgHdr->InstructionLength;
1556 pVCpu->cpum.GstCtx.rflags.Bits.u1RF = 0;
1557
1558 /* Update interrupt inhibition. */
1559 if (!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
1560 { /* likely */ }
1561 else if (pVCpu->cpum.GstCtx.rip != EMGetInhibitInterruptsPC(pVCpu))
1562 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
1563}
1564#elif defined(IN_RING3)
1565/**
1566 * Advances the guest RIP and clear EFLAGS.RF, WinHv version.
1567 *
1568 * This may clear VMCPU_FF_INHIBIT_INTERRUPTS.
1569 *
1570 * @param pVCpu The cross context virtual CPU structure.
1571 * @param pExitCtx The exit context.
1572 * @param cbMinInstr The minimum instruction length, or 1 if not unknown.
1573 */
1574DECLINLINE(void) nemR3WinAdvanceGuestRipAndClearRF(PVMCPUCC pVCpu, WHV_VP_EXIT_CONTEXT const *pExitCtx, uint8_t cbMinInstr)
1575{
1576 Assert(!(pVCpu->cpum.GstCtx.fExtrn & (CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS)));
1577
1578 /* Advance the RIP. */
1579 Assert(pExitCtx->InstructionLength >= cbMinInstr); RT_NOREF_PV(cbMinInstr);
1580 pVCpu->cpum.GstCtx.rip += pExitCtx->InstructionLength;
1581 pVCpu->cpum.GstCtx.rflags.Bits.u1RF = 0;
1582
1583 /* Update interrupt inhibition. */
1584 if (!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
1585 { /* likely */ }
1586 else if (pVCpu->cpum.GstCtx.rip != EMGetInhibitInterruptsPC(pVCpu))
1587 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
1588}
1589#endif /* IN_RING3 && !NEM_WIN_TEMPLATE_MODE_OWN_RUN_API */
1590
1591
1592
1593NEM_TMPL_STATIC DECLCALLBACK(int)
1594nemHCWinUnmapOnePageCallback(PVMCC pVM, PVMCPUCC pVCpu, RTGCPHYS GCPhys, uint8_t *pu2NemState, void *pvUser)
1595{
1596 RT_NOREF_PV(pvUser);
1597#ifdef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
1598 int rc = nemHCWinHypercallUnmapPage(pVM, pVCpu, GCPhys);
1599 AssertRC(rc);
1600 if (RT_SUCCESS(rc))
1601#else
1602 RT_NOREF_PV(pVCpu);
1603 HRESULT hrc = WHvUnmapGpaRange(pVM->nem.s.hPartition, GCPhys, X86_PAGE_SIZE);
1604 if (SUCCEEDED(hrc))
1605#endif
1606 {
1607 Log5(("NEM GPA unmap all: %RGp (cMappedPages=%u)\n", GCPhys, pVM->nem.s.cMappedPages - 1));
1608 *pu2NemState = NEM_WIN_PAGE_STATE_UNMAPPED;
1609 }
1610 else
1611 {
1612#ifdef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
1613 LogRel(("nemR3WinUnmapOnePageCallback: GCPhys=%RGp rc=%Rrc\n", GCPhys, rc));
1614#else
1615 LogRel(("nemR3WinUnmapOnePageCallback: GCPhys=%RGp %s hrc=%Rhrc (%#x) Last=%#x/%u (cMappedPages=%u)\n",
1616 GCPhys, g_apszPageStates[*pu2NemState], hrc, hrc, RTNtLastStatusValue(),
1617 RTNtLastErrorValue(), pVM->nem.s.cMappedPages));
1618#endif
1619 *pu2NemState = NEM_WIN_PAGE_STATE_NOT_SET;
1620 }
1621 if (pVM->nem.s.cMappedPages > 0)
1622 ASMAtomicDecU32(&pVM->nem.s.cMappedPages);
1623 return VINF_SUCCESS;
1624}
1625
1626
1627/**
1628 * State to pass between nemHCWinHandleMemoryAccess / nemR3WinWHvHandleMemoryAccess
1629 * and nemHCWinHandleMemoryAccessPageCheckerCallback.
1630 */
1631typedef struct NEMHCWINHMACPCCSTATE
1632{
1633 /** Input: Write access. */
1634 bool fWriteAccess;
1635 /** Output: Set if we did something. */
1636 bool fDidSomething;
1637 /** Output: Set it we should resume. */
1638 bool fCanResume;
1639} NEMHCWINHMACPCCSTATE;
1640
1641/**
1642 * @callback_method_impl{FNPGMPHYSNEMCHECKPAGE,
1643 * Worker for nemR3WinHandleMemoryAccess; pvUser points to a
1644 * NEMHCWINHMACPCCSTATE structure. }
1645 */
1646NEM_TMPL_STATIC DECLCALLBACK(int)
1647nemHCWinHandleMemoryAccessPageCheckerCallback(PVMCC pVM, PVMCPUCC pVCpu, RTGCPHYS GCPhys, PPGMPHYSNEMPAGEINFO pInfo, void *pvUser)
1648{
1649 NEMHCWINHMACPCCSTATE *pState = (NEMHCWINHMACPCCSTATE *)pvUser;
1650 pState->fDidSomething = false;
1651 pState->fCanResume = false;
1652
1653 /* If A20 is disabled, we may need to make another query on the masked
1654 page to get the correct protection information. */
1655 uint8_t u2State = pInfo->u2NemState;
1656 RTGCPHYS GCPhysSrc;
1657 if ( pVM->nem.s.fA20Enabled
1658 || !NEM_WIN_IS_SUBJECT_TO_A20(GCPhys))
1659 GCPhysSrc = GCPhys;
1660 else
1661 {
1662 GCPhysSrc = GCPhys & ~(RTGCPHYS)RT_BIT_32(20);
1663 PGMPHYSNEMPAGEINFO Info2;
1664 int rc = PGMPhysNemPageInfoChecker(pVM, pVCpu, GCPhysSrc, pState->fWriteAccess, &Info2, NULL, NULL);
1665 AssertRCReturn(rc, rc);
1666
1667 *pInfo = Info2;
1668 pInfo->u2NemState = u2State;
1669 }
1670
1671 /*
1672 * Consolidate current page state with actual page protection and access type.
1673 * We don't really consider downgrades here, as they shouldn't happen.
1674 */
1675#ifndef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
1676 /** @todo Someone at microsoft please explain:
1677 * I'm not sure WTF was going on, but I ended up in a loop if I remapped a
1678 * readonly page as writable (unmap, then map again). Specifically, this was an
1679 * issue with the big VRAM mapping at 0xe0000000 when booing DSL 4.4.1. So, in
1680 * a hope to work around that we no longer pre-map anything, just unmap stuff
1681 * and do it lazily here. And here we will first unmap, restart, and then remap
1682 * with new protection or backing.
1683 */
1684#endif
1685 int rc;
1686 switch (u2State)
1687 {
1688 case NEM_WIN_PAGE_STATE_UNMAPPED:
1689 case NEM_WIN_PAGE_STATE_NOT_SET:
1690 if (pInfo->fNemProt == NEM_PAGE_PROT_NONE)
1691 {
1692 Log4(("nemHCWinHandleMemoryAccessPageCheckerCallback: %RGp - #1\n", GCPhys));
1693 return VINF_SUCCESS;
1694 }
1695
1696 /* Don't bother remapping it if it's a write request to a non-writable page. */
1697 if ( pState->fWriteAccess
1698 && !(pInfo->fNemProt & NEM_PAGE_PROT_WRITE))
1699 {
1700 Log4(("nemHCWinHandleMemoryAccessPageCheckerCallback: %RGp - #1w\n", GCPhys));
1701 return VINF_SUCCESS;
1702 }
1703
1704 /* Map the page. */
1705 rc = nemHCNativeSetPhysPage(pVM,
1706 pVCpu,
1707 GCPhysSrc & ~(RTGCPHYS)X86_PAGE_OFFSET_MASK,
1708 GCPhys & ~(RTGCPHYS)X86_PAGE_OFFSET_MASK,
1709 pInfo->fNemProt,
1710 &u2State,
1711 true /*fBackingState*/);
1712 pInfo->u2NemState = u2State;
1713 Log4(("nemHCWinHandleMemoryAccessPageCheckerCallback: %RGp - synced => %s + %Rrc\n",
1714 GCPhys, g_apszPageStates[u2State], rc));
1715 pState->fDidSomething = true;
1716 pState->fCanResume = true;
1717 return rc;
1718
1719 case NEM_WIN_PAGE_STATE_READABLE:
1720 if ( !(pInfo->fNemProt & NEM_PAGE_PROT_WRITE)
1721 && (pInfo->fNemProt & (NEM_PAGE_PROT_READ | NEM_PAGE_PROT_EXECUTE)))
1722 {
1723 Log4(("nemHCWinHandleMemoryAccessPageCheckerCallback: %RGp - #2\n", GCPhys));
1724 return VINF_SUCCESS;
1725 }
1726
1727#ifdef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
1728 /* Upgrade page to writable. */
1729/** @todo test this*/
1730 if ( (pInfo->fNemProt & NEM_PAGE_PROT_WRITE)
1731 && pState->fWriteAccess)
1732 {
1733 rc = nemHCWinHypercallMapPage(pVM, pVCpu, GCPhysSrc, GCPhys,
1734 HV_MAP_GPA_READABLE | HV_MAP_GPA_WRITABLE
1735 | HV_MAP_GPA_EXECUTABLE | HV_MAP_GPA_EXECUTABLE_AGAIN);
1736 AssertRC(rc);
1737 if (RT_SUCCESS(rc))
1738 {
1739 pInfo->u2NemState = NEM_WIN_PAGE_STATE_WRITABLE;
1740 pState->fDidSomething = true;
1741 pState->fCanResume = true;
1742 Log5(("NEM GPA write-upgrade/exit: %RGp (was %s, cMappedPages=%u)\n",
1743 GCPhys, g_apszPageStates[u2State], pVM->nem.s.cMappedPages));
1744 }
1745 }
1746 else
1747 {
1748 /* Need to emulate the acces. */
1749 AssertBreak(pInfo->fNemProt != NEM_PAGE_PROT_NONE); /* There should be no downgrades. */
1750 rc = VINF_SUCCESS;
1751 }
1752 return rc;
1753#else
1754 break;
1755#endif
1756
1757 case NEM_WIN_PAGE_STATE_WRITABLE:
1758 if (pInfo->fNemProt & NEM_PAGE_PROT_WRITE)
1759 {
1760 if (pInfo->u2OldNemState == NEM_WIN_PAGE_STATE_WRITABLE)
1761 Log4(("nemHCWinHandleMemoryAccessPageCheckerCallback: %RGp - #3a\n", GCPhys));
1762 else
1763 {
1764 pState->fCanResume = true;
1765 Log4(("nemHCWinHandleMemoryAccessPageCheckerCallback: %RGp - #3b (%s -> %s)\n",
1766 GCPhys, g_apszPageStates[pInfo->u2OldNemState], g_apszPageStates[u2State]));
1767 }
1768 return VINF_SUCCESS;
1769 }
1770#ifdef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
1771 AssertFailed(); /* There should be no downgrades. */
1772#endif
1773 break;
1774
1775 default:
1776 AssertLogRelMsgFailedReturn(("u2State=%#x\n", u2State), VERR_NEM_IPE_4);
1777 }
1778
1779 /*
1780 * Unmap and restart the instruction.
1781 * If this fails, which it does every so often, just unmap everything for now.
1782 */
1783#ifdef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
1784 rc = nemHCWinHypercallUnmapPage(pVM, pVCpu, GCPhys);
1785 AssertRC(rc);
1786 if (RT_SUCCESS(rc))
1787#else
1788 /** @todo figure out whether we mess up the state or if it's WHv. */
1789 HRESULT hrc = WHvUnmapGpaRange(pVM->nem.s.hPartition, GCPhys, X86_PAGE_SIZE);
1790 if (SUCCEEDED(hrc))
1791#endif
1792 {
1793 pState->fDidSomething = true;
1794 pState->fCanResume = true;
1795 pInfo->u2NemState = NEM_WIN_PAGE_STATE_UNMAPPED;
1796 uint32_t cMappedPages = ASMAtomicDecU32(&pVM->nem.s.cMappedPages); NOREF(cMappedPages);
1797 Log5(("NEM GPA unmapped/exit: %RGp (was %s, cMappedPages=%u)\n", GCPhys, g_apszPageStates[u2State], cMappedPages));
1798 return VINF_SUCCESS;
1799 }
1800#ifdef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
1801 LogRel(("nemHCWinHandleMemoryAccessPageCheckerCallback/unmap: GCPhysDst=%RGp rc=%Rrc\n", GCPhys, rc));
1802 return rc;
1803#else
1804 LogRel(("nemHCWinHandleMemoryAccessPageCheckerCallback/unmap: GCPhysDst=%RGp %s hrc=%Rhrc (%#x) Last=%#x/%u (cMappedPages=%u)\n",
1805 GCPhys, g_apszPageStates[u2State], hrc, hrc, RTNtLastStatusValue(), RTNtLastErrorValue(),
1806 pVM->nem.s.cMappedPages));
1807
1808 PGMPhysNemEnumPagesByState(pVM, pVCpu, NEM_WIN_PAGE_STATE_READABLE, nemR3WinUnmapOnePageCallback, NULL);
1809 Log(("nemHCWinHandleMemoryAccessPageCheckerCallback: Unmapped all (cMappedPages=%u)\n", pVM->nem.s.cMappedPages));
1810
1811 pState->fDidSomething = true;
1812 pState->fCanResume = true;
1813 pInfo->u2NemState = NEM_WIN_PAGE_STATE_UNMAPPED;
1814 return VINF_SUCCESS;
1815#endif
1816}
1817
1818
1819
1820#if defined(IN_RING0) && defined(NEM_WIN_TEMPLATE_MODE_OWN_RUN_API)
1821/**
1822 * Wrapper around nemR0WinImportState that converts VERR_NEM_FLUSH_TLB
1823 * into informational status codes and logs+asserts statuses.
1824 *
1825 * @returns VBox strict status code.
1826 * @param pGVM The global (ring-0) VM structure.
1827 * @param pGVCpu The global (ring-0) per CPU structure.
1828 * @param fWhat What to import.
1829 * @param pszCaller Who is doing the importing.
1830 */
1831DECLINLINE(VBOXSTRICTRC) nemR0WinImportStateStrict(PGVM pGVM, PGVMCPU pGVCpu, uint64_t fWhat, const char *pszCaller)
1832{
1833 int rc = nemR0WinImportState(pGVM, pGVCpu, &pGVCpu->cpum.GstCtx, fWhat, true /*fCanUpdateCr3*/);
1834 if (RT_SUCCESS(rc))
1835 {
1836 Assert(rc == VINF_SUCCESS);
1837 return VINF_SUCCESS;
1838 }
1839
1840 if (rc == VERR_NEM_FLUSH_TLB)
1841 {
1842 Log4(("%s/%u: nemR0WinImportState -> %Rrc\n", pszCaller, pGVCpu->idCpu, -rc));
1843 return -rc;
1844 }
1845 RT_NOREF(pszCaller);
1846 AssertMsgFailedReturn(("%s/%u: nemR0WinImportState failed: %Rrc\n", pszCaller, pGVCpu->idCpu, rc), rc);
1847}
1848#endif /* IN_RING0 && NEM_WIN_TEMPLATE_MODE_OWN_RUN_API*/
1849
1850#if defined(NEM_WIN_TEMPLATE_MODE_OWN_RUN_API) || defined(IN_RING3)
1851/**
1852 * Wrapper around nemR0WinImportStateStrict and nemHCWinCopyStateFromHyperV.
1853 *
1854 * Unlike the wrapped APIs, this checks whether it's necessary.
1855 *
1856 * @returns VBox strict status code.
1857 * @param pVCpu The cross context per CPU structure.
1858 * @param fWhat What to import.
1859 * @param pszCaller Who is doing the importing.
1860 */
1861DECLINLINE(VBOXSTRICTRC) nemHCWinImportStateIfNeededStrict(PVMCPUCC pVCpu, uint64_t fWhat, const char *pszCaller)
1862{
1863 if (pVCpu->cpum.GstCtx.fExtrn & fWhat)
1864 {
1865# ifdef IN_RING0
1866 return nemR0WinImportStateStrict(pVCpu->pGVM, pVCpu, fWhat, pszCaller);
1867# else
1868 RT_NOREF(pszCaller);
1869 int rc = nemHCWinCopyStateFromHyperV(pVCpu->pVMR3, pVCpu, fWhat);
1870 AssertRCReturn(rc, rc);
1871# endif
1872 }
1873 return VINF_SUCCESS;
1874}
1875#endif /* NEM_WIN_TEMPLATE_MODE_OWN_RUN_API || IN_RING3 */
1876
1877#ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
1878/**
1879 * Copies register state from the X64 intercept message header.
1880 *
1881 * ASSUMES no state copied yet.
1882 *
1883 * @param pVCpu The cross context per CPU structure.
1884 * @param pHdr The X64 intercept message header.
1885 * @sa nemR3WinCopyStateFromX64Header
1886 */
1887DECLINLINE(void) nemHCWinCopyStateFromX64Header(PVMCPUCC pVCpu, HV_X64_INTERCEPT_MESSAGE_HEADER const *pHdr)
1888{
1889 Assert( (pVCpu->cpum.GstCtx.fExtrn & (CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT))
1890 == (CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT));
1891 NEM_WIN_COPY_BACK_SEG(pVCpu->cpum.GstCtx.cs, pHdr->CsSegment);
1892 pVCpu->cpum.GstCtx.rip = pHdr->Rip;
1893 pVCpu->cpum.GstCtx.rflags.u = pHdr->Rflags;
1894
1895 pVCpu->nem.s.fLastInterruptShadow = pHdr->ExecutionState.InterruptShadow;
1896 if (!pHdr->ExecutionState.InterruptShadow)
1897 {
1898 if (!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
1899 { /* likely */ }
1900 else
1901 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
1902 }
1903 else
1904 EMSetInhibitInterruptsPC(pVCpu, pHdr->Rip);
1905
1906 APICSetTpr(pVCpu, pHdr->Cr8 << 4);
1907
1908 pVCpu->cpum.GstCtx.fExtrn &= ~(CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT | CPUMCTX_EXTRN_APIC_TPR);
1909}
1910#elif defined(IN_RING3)
1911/**
1912 * Copies register state from the (common) exit context.
1913 *
1914 * ASSUMES no state copied yet.
1915 *
1916 * @param pVCpu The cross context per CPU structure.
1917 * @param pExitCtx The common exit context.
1918 * @sa nemHCWinCopyStateFromX64Header
1919 */
1920DECLINLINE(void) nemR3WinCopyStateFromX64Header(PVMCPUCC pVCpu, WHV_VP_EXIT_CONTEXT const *pExitCtx)
1921{
1922 Assert( (pVCpu->cpum.GstCtx.fExtrn & (CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT))
1923 == (CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT));
1924 NEM_WIN_COPY_BACK_SEG(pVCpu->cpum.GstCtx.cs, pExitCtx->Cs);
1925 pVCpu->cpum.GstCtx.rip = pExitCtx->Rip;
1926 pVCpu->cpum.GstCtx.rflags.u = pExitCtx->Rflags;
1927
1928 pVCpu->nem.s.fLastInterruptShadow = pExitCtx->ExecutionState.InterruptShadow;
1929 if (!pExitCtx->ExecutionState.InterruptShadow)
1930 {
1931 if (!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
1932 { /* likely */ }
1933 else
1934 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
1935 }
1936 else
1937 EMSetInhibitInterruptsPC(pVCpu, pExitCtx->Rip);
1938
1939 APICSetTpr(pVCpu, pExitCtx->Cr8 << 4);
1940
1941 pVCpu->cpum.GstCtx.fExtrn &= ~(CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT | CPUMCTX_EXTRN_APIC_TPR);
1942}
1943#endif /* IN_RING3 && !NEM_WIN_TEMPLATE_MODE_OWN_RUN_API */
1944
1945
1946#ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
1947/**
1948 * Deals with memory intercept message.
1949 *
1950 * @returns Strict VBox status code.
1951 * @param pVM The cross context VM structure.
1952 * @param pVCpu The cross context per CPU structure.
1953 * @param pMsg The message.
1954 * @sa nemR3WinHandleExitMemory
1955 */
1956NEM_TMPL_STATIC VBOXSTRICTRC
1957nemHCWinHandleMessageMemory(PVMCC pVM, PVMCPUCC pVCpu, HV_X64_MEMORY_INTERCEPT_MESSAGE const *pMsg)
1958{
1959 uint64_t const uHostTsc = ASMReadTSC();
1960 Assert( pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_READ
1961 || pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE
1962 || pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_EXECUTE);
1963
1964 /*
1965 * Whatever we do, we must clear pending event injection upon resume.
1966 */
1967 if (pMsg->Header.ExecutionState.InterruptionPending)
1968 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_NEM_WIN_EVENT_INJECT;
1969
1970# if 0 /* Experiment: 20K -> 34K exit/s. */
1971 if ( pMsg->Header.ExecutionState.EferLma
1972 && pMsg->Header.CsSegment.Long
1973 && pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE)
1974 {
1975 if ( pMsg->Header.Rip - (uint64_t)0xf65a < (uint64_t)(0xf662 - 0xf65a)
1976 && pMsg->InstructionBytes[0] == 0x89
1977 && pMsg->InstructionBytes[1] == 0x03)
1978 {
1979 pVCpu->cpum.GstCtx.rip = pMsg->Header.Rip + 2;
1980 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_RIP;
1981 AssertMsg(pMsg->Header.InstructionLength == 2, ("%#x\n", pMsg->Header.InstructionLength));
1982 //Log(("%RX64 msg:\n%.80Rhxd\n", pVCpu->cpum.GstCtx.rip, pMsg));
1983 return VINF_SUCCESS;
1984 }
1985 }
1986# endif
1987
1988 /*
1989 * Ask PGM for information about the given GCPhys. We need to check if we're
1990 * out of sync first.
1991 */
1992 NEMHCWINHMACPCCSTATE State = { pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE, false, false };
1993 PGMPHYSNEMPAGEINFO Info;
1994 int rc = PGMPhysNemPageInfoChecker(pVM, pVCpu, pMsg->GuestPhysicalAddress, State.fWriteAccess, &Info,
1995 nemHCWinHandleMemoryAccessPageCheckerCallback, &State);
1996 if (RT_SUCCESS(rc))
1997 {
1998 if (Info.fNemProt & ( pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE
1999 ? NEM_PAGE_PROT_WRITE : NEM_PAGE_PROT_READ))
2000 {
2001 if (State.fCanResume)
2002 {
2003 Log4(("MemExit/%u: %04x:%08RX64/%s: %RGp (=>%RHp) %s fProt=%u%s%s%s; restarting (%s)\n",
2004 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2005 pMsg->GuestPhysicalAddress, Info.HCPhys, g_apszPageStates[Info.u2NemState], Info.fNemProt,
2006 Info.fHasHandlers ? " handlers" : "", Info.fZeroPage ? " zero-pg" : "",
2007 State.fDidSomething ? "" : " no-change", g_apszHvInterceptAccessTypes[pMsg->Header.InterceptAccessType]));
2008 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_MEMORY_ACCESS),
2009 pMsg->Header.Rip + pMsg->Header.CsSegment.Base, uHostTsc);
2010 return VINF_SUCCESS;
2011 }
2012 }
2013 Log4(("MemExit/%u: %04x:%08RX64/%s: %RGp (=>%RHp) %s fProt=%u%s%s%s; emulating (%s)\n",
2014 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2015 pMsg->GuestPhysicalAddress, Info.HCPhys, g_apszPageStates[Info.u2NemState], Info.fNemProt,
2016 Info.fHasHandlers ? " handlers" : "", Info.fZeroPage ? " zero-pg" : "",
2017 State.fDidSomething ? "" : " no-change", g_apszHvInterceptAccessTypes[pMsg->Header.InterceptAccessType]));
2018 }
2019 else
2020 Log4(("MemExit/%u: %04x:%08RX64/%s: %RGp rc=%Rrc%s; emulating (%s)\n",
2021 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2022 pMsg->GuestPhysicalAddress, rc, State.fDidSomething ? " modified-backing" : "",
2023 g_apszHvInterceptAccessTypes[pMsg->Header.InterceptAccessType]));
2024
2025 /*
2026 * Emulate the memory access, either access handler or special memory.
2027 */
2028 PCEMEXITREC pExitRec = EMHistoryAddExit(pVCpu,
2029 pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE
2030 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_MMIO_WRITE)
2031 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_MMIO_READ),
2032 pMsg->Header.Rip + pMsg->Header.CsSegment.Base, uHostTsc);
2033 nemHCWinCopyStateFromX64Header(pVCpu, &pMsg->Header);
2034 VBOXSTRICTRC rcStrict;
2035# ifdef IN_RING0
2036 rcStrict = nemR0WinImportStateStrict(pVM, pVCpu,
2037 NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM | CPUMCTX_EXTRN_DS | CPUMCTX_EXTRN_ES, "MemExit");
2038 if (rcStrict != VINF_SUCCESS)
2039 return rcStrict;
2040# else
2041 rc = nemHCWinCopyStateFromHyperV(pVM, pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM | CPUMCTX_EXTRN_DS | CPUMCTX_EXTRN_ES);
2042 AssertRCReturn(rc, rc);
2043# endif
2044
2045 if (pMsg->Reserved1)
2046 Log(("MemExit/Reserved1=%#x\n", pMsg->Reserved1));
2047 if (pMsg->Header.ExecutionState.Reserved0 || pMsg->Header.ExecutionState.Reserved1)
2048 Log(("MemExit/Hdr/State: Reserved0=%#x Reserved1=%#x\n", pMsg->Header.ExecutionState.Reserved0, pMsg->Header.ExecutionState.Reserved1));
2049
2050 if (!pExitRec)
2051 {
2052 //if (pMsg->InstructionByteCount > 0)
2053 // Log4(("InstructionByteCount=%#x %.16Rhxs\n", pMsg->InstructionByteCount, pMsg->InstructionBytes));
2054 if (pMsg->InstructionByteCount > 0)
2055 rcStrict = IEMExecOneWithPrefetchedByPC(pVCpu, CPUMCTX2CORE(&pVCpu->cpum.GstCtx), pMsg->Header.Rip,
2056 pMsg->InstructionBytes, pMsg->InstructionByteCount);
2057 else
2058 rcStrict = IEMExecOne(pVCpu);
2059 /** @todo do we need to do anything wrt debugging here? */
2060 }
2061 else
2062 {
2063 /* Frequent access or probing. */
2064 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
2065 Log4(("MemExit/%u: %04x:%08RX64/%s: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
2066 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2067 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
2068 }
2069 return rcStrict;
2070}
2071#elif defined(IN_RING3)
2072/**
2073 * Deals with memory access exits (WHvRunVpExitReasonMemoryAccess).
2074 *
2075 * @returns Strict VBox status code.
2076 * @param pVM The cross context VM structure.
2077 * @param pVCpu The cross context per CPU structure.
2078 * @param pExit The VM exit information to handle.
2079 * @sa nemHCWinHandleMessageMemory
2080 */
2081NEM_TMPL_STATIC VBOXSTRICTRC
2082nemR3WinHandleExitMemory(PVMCC pVM, PVMCPUCC pVCpu, WHV_RUN_VP_EXIT_CONTEXT const *pExit)
2083{
2084 uint64_t const uHostTsc = ASMReadTSC();
2085 Assert(pExit->MemoryAccess.AccessInfo.AccessType != 3);
2086
2087 /*
2088 * Whatever we do, we must clear pending event injection upon resume.
2089 */
2090 if (pExit->VpContext.ExecutionState.InterruptionPending)
2091 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_NEM_WIN_EVENT_INJECT;
2092
2093 /*
2094 * Ask PGM for information about the given GCPhys. We need to check if we're
2095 * out of sync first.
2096 */
2097 NEMHCWINHMACPCCSTATE State = { pExit->MemoryAccess.AccessInfo.AccessType == WHvMemoryAccessWrite, false, false };
2098 PGMPHYSNEMPAGEINFO Info;
2099 int rc = PGMPhysNemPageInfoChecker(pVM, pVCpu, pExit->MemoryAccess.Gpa, State.fWriteAccess, &Info,
2100 nemHCWinHandleMemoryAccessPageCheckerCallback, &State);
2101 if (RT_SUCCESS(rc))
2102 {
2103 if (Info.fNemProt & ( pExit->MemoryAccess.AccessInfo.AccessType == WHvMemoryAccessWrite
2104 ? NEM_PAGE_PROT_WRITE : NEM_PAGE_PROT_READ))
2105 {
2106 if (State.fCanResume)
2107 {
2108 Log4(("MemExit/%u: %04x:%08RX64/%s: %RGp (=>%RHp) %s fProt=%u%s%s%s; restarting (%s)\n",
2109 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
2110 pExit->MemoryAccess.Gpa, Info.HCPhys, g_apszPageStates[Info.u2NemState], Info.fNemProt,
2111 Info.fHasHandlers ? " handlers" : "", Info.fZeroPage ? " zero-pg" : "",
2112 State.fDidSomething ? "" : " no-change", g_apszHvInterceptAccessTypes[pExit->MemoryAccess.AccessInfo.AccessType]));
2113 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_MEMORY_ACCESS),
2114 pExit->VpContext.Rip + pExit->VpContext.Cs.Base, uHostTsc);
2115 return VINF_SUCCESS;
2116 }
2117 }
2118 Log4(("MemExit/%u: %04x:%08RX64/%s: %RGp (=>%RHp) %s fProt=%u%s%s%s; emulating (%s)\n",
2119 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
2120 pExit->MemoryAccess.Gpa, Info.HCPhys, g_apszPageStates[Info.u2NemState], Info.fNemProt,
2121 Info.fHasHandlers ? " handlers" : "", Info.fZeroPage ? " zero-pg" : "",
2122 State.fDidSomething ? "" : " no-change", g_apszHvInterceptAccessTypes[pExit->MemoryAccess.AccessInfo.AccessType]));
2123 }
2124 else
2125 Log4(("MemExit/%u: %04x:%08RX64/%s: %RGp rc=%Rrc%s; emulating (%s)\n",
2126 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
2127 pExit->MemoryAccess.Gpa, rc, State.fDidSomething ? " modified-backing" : "",
2128 g_apszHvInterceptAccessTypes[pExit->MemoryAccess.AccessInfo.AccessType]));
2129
2130 /*
2131 * Emulate the memory access, either access handler or special memory.
2132 */
2133 PCEMEXITREC pExitRec = EMHistoryAddExit(pVCpu,
2134 pExit->MemoryAccess.AccessInfo.AccessType == WHvMemoryAccessWrite
2135 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_MMIO_WRITE)
2136 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_MMIO_READ),
2137 pExit->VpContext.Rip + pExit->VpContext.Cs.Base, uHostTsc);
2138 nemR3WinCopyStateFromX64Header(pVCpu, &pExit->VpContext);
2139 rc = nemHCWinCopyStateFromHyperV(pVM, pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM | CPUMCTX_EXTRN_DS | CPUMCTX_EXTRN_ES);
2140 AssertRCReturn(rc, rc);
2141 if (pExit->VpContext.ExecutionState.Reserved0 || pExit->VpContext.ExecutionState.Reserved1)
2142 Log(("MemExit/Hdr/State: Reserved0=%#x Reserved1=%#x\n", pExit->VpContext.ExecutionState.Reserved0, pExit->VpContext.ExecutionState.Reserved1));
2143
2144 VBOXSTRICTRC rcStrict;
2145 if (!pExitRec)
2146 {
2147 //if (pMsg->InstructionByteCount > 0)
2148 // Log4(("InstructionByteCount=%#x %.16Rhxs\n", pMsg->InstructionByteCount, pMsg->InstructionBytes));
2149 if (pExit->MemoryAccess.InstructionByteCount > 0)
2150 rcStrict = IEMExecOneWithPrefetchedByPC(pVCpu, CPUMCTX2CORE(&pVCpu->cpum.GstCtx), pExit->VpContext.Rip,
2151 pExit->MemoryAccess.InstructionBytes, pExit->MemoryAccess.InstructionByteCount);
2152 else
2153 rcStrict = IEMExecOne(pVCpu);
2154 /** @todo do we need to do anything wrt debugging here? */
2155 }
2156 else
2157 {
2158 /* Frequent access or probing. */
2159 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
2160 Log4(("MemExit/%u: %04x:%08RX64/%s: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
2161 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
2162 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
2163 }
2164 return rcStrict;
2165}
2166#endif /* IN_RING3 && !NEM_WIN_TEMPLATE_MODE_OWN_RUN_API */
2167
2168
2169#ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
2170/**
2171 * Deals with I/O port intercept message.
2172 *
2173 * @returns Strict VBox status code.
2174 * @param pVM The cross context VM structure.
2175 * @param pVCpu The cross context per CPU structure.
2176 * @param pMsg The message.
2177 */
2178NEM_TMPL_STATIC VBOXSTRICTRC
2179nemHCWinHandleMessageIoPort(PVMCC pVM, PVMCPUCC pVCpu, HV_X64_IO_PORT_INTERCEPT_MESSAGE const *pMsg)
2180{
2181 /*
2182 * Assert message sanity.
2183 */
2184 Assert( pMsg->AccessInfo.AccessSize == 1
2185 || pMsg->AccessInfo.AccessSize == 2
2186 || pMsg->AccessInfo.AccessSize == 4);
2187 Assert( pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_READ
2188 || pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE);
2189 NEMWIN_ASSERT_MSG_REG_SEG( pVCpu, HvX64RegisterCs, pMsg->Header.CsSegment);
2190 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRip, pMsg->Header.Rip);
2191 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRflags, pMsg->Header.Rflags);
2192 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterCr8, (uint64_t)pMsg->Header.Cr8);
2193 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRax, pMsg->Rax);
2194 if (pMsg->AccessInfo.StringOp)
2195 {
2196 NEMWIN_ASSERT_MSG_REG_SEG( pVCpu, HvX64RegisterDs, pMsg->DsSegment);
2197 NEMWIN_ASSERT_MSG_REG_SEG( pVCpu, HvX64RegisterEs, pMsg->EsSegment);
2198 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRcx, pMsg->Rcx);
2199 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRsi, pMsg->Rsi);
2200 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRdi, pMsg->Rdi);
2201 }
2202
2203 /*
2204 * Whatever we do, we must clear pending event injection upon resume.
2205 */
2206 if (pMsg->Header.ExecutionState.InterruptionPending)
2207 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_NEM_WIN_EVENT_INJECT;
2208
2209 /*
2210 * Add history first to avoid two paths doing EMHistoryExec calls.
2211 */
2212 VBOXSTRICTRC rcStrict;
2213 PCEMEXITREC pExitRec = EMHistoryAddExit(pVCpu,
2214 !pMsg->AccessInfo.StringOp
2215 ? ( pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE
2216 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_IO_PORT_WRITE)
2217 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_IO_PORT_READ))
2218 : ( pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE
2219 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_IO_PORT_STR_WRITE)
2220 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_IO_PORT_STR_READ)),
2221 pMsg->Header.Rip + pMsg->Header.CsSegment.Base, ASMReadTSC());
2222 if (!pExitRec)
2223 {
2224 if (!pMsg->AccessInfo.StringOp)
2225 {
2226 /*
2227 * Simple port I/O.
2228 */
2229 static uint32_t const s_fAndMask[8] =
2230 { UINT32_MAX, UINT32_C(0xff), UINT32_C(0xffff), UINT32_MAX, UINT32_MAX, UINT32_MAX, UINT32_MAX, UINT32_MAX };
2231 uint32_t const fAndMask = s_fAndMask[pMsg->AccessInfo.AccessSize];
2232
2233 nemHCWinCopyStateFromX64Header(pVCpu, &pMsg->Header);
2234 if (pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE)
2235 {
2236 rcStrict = IOMIOPortWrite(pVM, pVCpu, pMsg->PortNumber, (uint32_t)pMsg->Rax & fAndMask, pMsg->AccessInfo.AccessSize);
2237 Log4(("IOExit/%u: %04x:%08RX64/%s: OUT %#x, %#x LB %u rcStrict=%Rrc\n",
2238 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2239 pMsg->PortNumber, (uint32_t)pMsg->Rax & fAndMask, pMsg->AccessInfo.AccessSize, VBOXSTRICTRC_VAL(rcStrict) ));
2240 if (IOM_SUCCESS(rcStrict))
2241 nemHCWinAdvanceGuestRipAndClearRF(pVCpu, &pMsg->Header, 1);
2242# ifdef IN_RING0
2243 else if ( rcStrict == VINF_IOM_R3_IOPORT_WRITE
2244 && !pVCpu->cpum.GstCtx.rflags.Bits.u1TF
2245 /** @todo check for debug breakpoints */ )
2246 return EMRZSetPendingIoPortWrite(pVCpu, pMsg->PortNumber, pMsg->Header.InstructionLength,
2247 pMsg->AccessInfo.AccessSize, (uint32_t)pMsg->Rax & fAndMask);
2248# endif
2249 else
2250 {
2251 pVCpu->cpum.GstCtx.rax = pMsg->Rax;
2252 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_RAX;
2253 }
2254 }
2255 else
2256 {
2257 uint32_t uValue = 0;
2258 rcStrict = IOMIOPortRead(pVM, pVCpu, pMsg->PortNumber, &uValue, pMsg->AccessInfo.AccessSize);
2259 Log4(("IOExit/%u: %04x:%08RX64/%s: IN %#x LB %u -> %#x, rcStrict=%Rrc\n",
2260 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2261 pMsg->PortNumber, pMsg->AccessInfo.AccessSize, uValue, VBOXSTRICTRC_VAL(rcStrict) ));
2262 if (IOM_SUCCESS(rcStrict))
2263 {
2264 if (pMsg->AccessInfo.AccessSize != 4)
2265 pVCpu->cpum.GstCtx.rax = (pMsg->Rax & ~(uint64_t)fAndMask) | (uValue & fAndMask);
2266 else
2267 pVCpu->cpum.GstCtx.rax = uValue;
2268 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_RAX;
2269 Log4(("IOExit/%u: RAX %#RX64 -> %#RX64\n", pVCpu->idCpu, pMsg->Rax, pVCpu->cpum.GstCtx.rax));
2270 nemHCWinAdvanceGuestRipAndClearRF(pVCpu, &pMsg->Header, 1);
2271 }
2272 else
2273 {
2274 pVCpu->cpum.GstCtx.rax = pMsg->Rax;
2275 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_RAX;
2276# ifdef IN_RING0
2277 if ( rcStrict == VINF_IOM_R3_IOPORT_READ
2278 && !pVCpu->cpum.GstCtx.rflags.Bits.u1TF
2279 /** @todo check for debug breakpoints */ )
2280 return EMRZSetPendingIoPortRead(pVCpu, pMsg->PortNumber, pMsg->Header.InstructionLength,
2281 pMsg->AccessInfo.AccessSize);
2282# endif
2283 }
2284 }
2285 }
2286 else
2287 {
2288 /*
2289 * String port I/O.
2290 */
2291 /** @todo Someone at Microsoft please explain how we can get the address mode
2292 * from the IoPortAccess.VpContext. CS.Attributes is only sufficient for
2293 * getting the default mode, it can always be overridden by a prefix. This
2294 * forces us to interpret the instruction from opcodes, which is suboptimal.
2295 * Both AMD-V and VT-x includes the address size in the exit info, at least on
2296 * CPUs that are reasonably new.
2297 *
2298 * Of course, it's possible this is an undocumented and we just need to do some
2299 * experiments to figure out how it's communicated. Alternatively, we can scan
2300 * the opcode bytes for possible evil prefixes.
2301 */
2302 nemHCWinCopyStateFromX64Header(pVCpu, &pMsg->Header);
2303 pVCpu->cpum.GstCtx.fExtrn &= ~( CPUMCTX_EXTRN_RAX | CPUMCTX_EXTRN_RCX | CPUMCTX_EXTRN_RDI | CPUMCTX_EXTRN_RSI
2304 | CPUMCTX_EXTRN_DS | CPUMCTX_EXTRN_ES);
2305 NEM_WIN_COPY_BACK_SEG(pVCpu->cpum.GstCtx.ds, pMsg->DsSegment);
2306 NEM_WIN_COPY_BACK_SEG(pVCpu->cpum.GstCtx.es, pMsg->EsSegment);
2307 pVCpu->cpum.GstCtx.rax = pMsg->Rax;
2308 pVCpu->cpum.GstCtx.rcx = pMsg->Rcx;
2309 pVCpu->cpum.GstCtx.rdi = pMsg->Rdi;
2310 pVCpu->cpum.GstCtx.rsi = pMsg->Rsi;
2311# ifdef IN_RING0
2312 rcStrict = nemR0WinImportStateStrict(pVM, pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM, "IOExit");
2313 if (rcStrict != VINF_SUCCESS)
2314 return rcStrict;
2315# else
2316 int rc = nemHCWinCopyStateFromHyperV(pVM, pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM);
2317 AssertRCReturn(rc, rc);
2318# endif
2319
2320 Log4(("IOExit/%u: %04x:%08RX64/%s: %s%s %#x LB %u (emulating)\n",
2321 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2322 pMsg->AccessInfo.RepPrefix ? "REP " : "",
2323 pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE ? "OUTS" : "INS",
2324 pMsg->PortNumber, pMsg->AccessInfo.AccessSize ));
2325 rcStrict = IEMExecOne(pVCpu);
2326 }
2327 if (IOM_SUCCESS(rcStrict))
2328 {
2329 /*
2330 * Do debug checks.
2331 */
2332 if ( pMsg->Header.ExecutionState.DebugActive /** @todo Microsoft: Does DebugActive this only reflect DR7? */
2333 || (pMsg->Header.Rflags & X86_EFL_TF)
2334 || DBGFBpIsHwIoArmed(pVM) )
2335 {
2336 /** @todo Debugging. */
2337 }
2338 }
2339 return rcStrict;
2340 }
2341
2342 /*
2343 * Frequent exit or something needing probing.
2344 * Get state and call EMHistoryExec.
2345 */
2346 nemHCWinCopyStateFromX64Header(pVCpu, &pMsg->Header);
2347 if (!pMsg->AccessInfo.StringOp)
2348 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_RAX;
2349 else
2350 {
2351 pVCpu->cpum.GstCtx.fExtrn &= ~( CPUMCTX_EXTRN_RAX | CPUMCTX_EXTRN_RCX | CPUMCTX_EXTRN_RDI | CPUMCTX_EXTRN_RSI
2352 | CPUMCTX_EXTRN_DS | CPUMCTX_EXTRN_ES);
2353 NEM_WIN_COPY_BACK_SEG(pVCpu->cpum.GstCtx.ds, pMsg->DsSegment);
2354 NEM_WIN_COPY_BACK_SEG(pVCpu->cpum.GstCtx.es, pMsg->EsSegment);
2355 pVCpu->cpum.GstCtx.rcx = pMsg->Rcx;
2356 pVCpu->cpum.GstCtx.rdi = pMsg->Rdi;
2357 pVCpu->cpum.GstCtx.rsi = pMsg->Rsi;
2358 }
2359 pVCpu->cpum.GstCtx.rax = pMsg->Rax;
2360
2361# ifdef IN_RING0
2362 rcStrict = nemR0WinImportStateStrict(pVM, pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM, "IOExit");
2363 if (rcStrict != VINF_SUCCESS)
2364 return rcStrict;
2365# else
2366 int rc = nemHCWinCopyStateFromHyperV(pVM, pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM);
2367 AssertRCReturn(rc, rc);
2368# endif
2369
2370 Log4(("IOExit/%u: %04x:%08RX64/%s: %s%s%s %#x LB %u -> EMHistoryExec\n",
2371 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2372 pMsg->AccessInfo.RepPrefix ? "REP " : "",
2373 pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE ? "OUT" : "IN",
2374 pMsg->AccessInfo.StringOp ? "S" : "",
2375 pMsg->PortNumber, pMsg->AccessInfo.AccessSize));
2376 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
2377 Log4(("IOExit/%u: %04x:%08RX64/%s: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
2378 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2379 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
2380 return rcStrict;
2381}
2382#elif defined(IN_RING3)
2383/**
2384 * Deals with I/O port access exits (WHvRunVpExitReasonX64IoPortAccess).
2385 *
2386 * @returns Strict VBox status code.
2387 * @param pVM The cross context VM structure.
2388 * @param pVCpu The cross context per CPU structure.
2389 * @param pExit The VM exit information to handle.
2390 * @sa nemHCWinHandleMessageIoPort
2391 */
2392NEM_TMPL_STATIC VBOXSTRICTRC nemR3WinHandleExitIoPort(PVMCC pVM, PVMCPUCC pVCpu, WHV_RUN_VP_EXIT_CONTEXT const *pExit)
2393{
2394 Assert( pExit->IoPortAccess.AccessInfo.AccessSize == 1
2395 || pExit->IoPortAccess.AccessInfo.AccessSize == 2
2396 || pExit->IoPortAccess.AccessInfo.AccessSize == 4);
2397
2398 /*
2399 * Whatever we do, we must clear pending event injection upon resume.
2400 */
2401 if (pExit->VpContext.ExecutionState.InterruptionPending)
2402 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_NEM_WIN_EVENT_INJECT;
2403
2404 /*
2405 * Add history first to avoid two paths doing EMHistoryExec calls.
2406 */
2407 PCEMEXITREC pExitRec = EMHistoryAddExit(pVCpu,
2408 !pExit->IoPortAccess.AccessInfo.StringOp
2409 ? ( pExit->MemoryAccess.AccessInfo.AccessType == WHvMemoryAccessWrite
2410 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_IO_PORT_WRITE)
2411 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_IO_PORT_READ))
2412 : ( pExit->MemoryAccess.AccessInfo.AccessType == WHvMemoryAccessWrite
2413 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_IO_PORT_STR_WRITE)
2414 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_IO_PORT_STR_READ)),
2415 pExit->VpContext.Rip + pExit->VpContext.Cs.Base, ASMReadTSC());
2416 if (!pExitRec)
2417 {
2418 VBOXSTRICTRC rcStrict;
2419 if (!pExit->IoPortAccess.AccessInfo.StringOp)
2420 {
2421 /*
2422 * Simple port I/O.
2423 */
2424 static uint32_t const s_fAndMask[8] =
2425 { UINT32_MAX, UINT32_C(0xff), UINT32_C(0xffff), UINT32_MAX, UINT32_MAX, UINT32_MAX, UINT32_MAX, UINT32_MAX };
2426 uint32_t const fAndMask = s_fAndMask[pExit->IoPortAccess.AccessInfo.AccessSize];
2427 if (pExit->IoPortAccess.AccessInfo.IsWrite)
2428 {
2429 rcStrict = IOMIOPortWrite(pVM, pVCpu, pExit->IoPortAccess.PortNumber,
2430 (uint32_t)pExit->IoPortAccess.Rax & fAndMask,
2431 pExit->IoPortAccess.AccessInfo.AccessSize);
2432 Log4(("IOExit/%u: %04x:%08RX64/%s: OUT %#x, %#x LB %u rcStrict=%Rrc\n",
2433 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
2434 pExit->IoPortAccess.PortNumber, (uint32_t)pExit->IoPortAccess.Rax & fAndMask,
2435 pExit->IoPortAccess.AccessInfo.AccessSize, VBOXSTRICTRC_VAL(rcStrict) ));
2436 if (IOM_SUCCESS(rcStrict))
2437 {
2438 nemR3WinCopyStateFromX64Header(pVCpu, &pExit->VpContext);
2439 nemR3WinAdvanceGuestRipAndClearRF(pVCpu, &pExit->VpContext, 1);
2440 }
2441 }
2442 else
2443 {
2444 uint32_t uValue = 0;
2445 rcStrict = IOMIOPortRead(pVM, pVCpu, pExit->IoPortAccess.PortNumber, &uValue,
2446 pExit->IoPortAccess.AccessInfo.AccessSize);
2447 Log4(("IOExit/%u: %04x:%08RX64/%s: IN %#x LB %u -> %#x, rcStrict=%Rrc\n",
2448 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
2449 pExit->IoPortAccess.PortNumber, pExit->IoPortAccess.AccessInfo.AccessSize, uValue, VBOXSTRICTRC_VAL(rcStrict) ));
2450 if (IOM_SUCCESS(rcStrict))
2451 {
2452 if (pExit->IoPortAccess.AccessInfo.AccessSize != 4)
2453 pVCpu->cpum.GstCtx.rax = (pExit->IoPortAccess.Rax & ~(uint64_t)fAndMask) | (uValue & fAndMask);
2454 else
2455 pVCpu->cpum.GstCtx.rax = uValue;
2456 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_RAX;
2457 Log4(("IOExit/%u: RAX %#RX64 -> %#RX64\n", pVCpu->idCpu, pExit->IoPortAccess.Rax, pVCpu->cpum.GstCtx.rax));
2458 nemR3WinCopyStateFromX64Header(pVCpu, &pExit->VpContext);
2459 nemR3WinAdvanceGuestRipAndClearRF(pVCpu, &pExit->VpContext, 1);
2460 }
2461 }
2462 }
2463 else
2464 {
2465 /*
2466 * String port I/O.
2467 */
2468 /** @todo Someone at Microsoft please explain how we can get the address mode
2469 * from the IoPortAccess.VpContext. CS.Attributes is only sufficient for
2470 * getting the default mode, it can always be overridden by a prefix. This
2471 * forces us to interpret the instruction from opcodes, which is suboptimal.
2472 * Both AMD-V and VT-x includes the address size in the exit info, at least on
2473 * CPUs that are reasonably new.
2474 *
2475 * Of course, it's possible this is an undocumented and we just need to do some
2476 * experiments to figure out how it's communicated. Alternatively, we can scan
2477 * the opcode bytes for possible evil prefixes.
2478 */
2479 nemR3WinCopyStateFromX64Header(pVCpu, &pExit->VpContext);
2480 pVCpu->cpum.GstCtx.fExtrn &= ~( CPUMCTX_EXTRN_RAX | CPUMCTX_EXTRN_RCX | CPUMCTX_EXTRN_RDI | CPUMCTX_EXTRN_RSI
2481 | CPUMCTX_EXTRN_DS | CPUMCTX_EXTRN_ES);
2482 NEM_WIN_COPY_BACK_SEG(pVCpu->cpum.GstCtx.ds, pExit->IoPortAccess.Ds);
2483 NEM_WIN_COPY_BACK_SEG(pVCpu->cpum.GstCtx.es, pExit->IoPortAccess.Es);
2484 pVCpu->cpum.GstCtx.rax = pExit->IoPortAccess.Rax;
2485 pVCpu->cpum.GstCtx.rcx = pExit->IoPortAccess.Rcx;
2486 pVCpu->cpum.GstCtx.rdi = pExit->IoPortAccess.Rdi;
2487 pVCpu->cpum.GstCtx.rsi = pExit->IoPortAccess.Rsi;
2488 int rc = nemHCWinCopyStateFromHyperV(pVM, pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM);
2489 AssertRCReturn(rc, rc);
2490
2491 Log4(("IOExit/%u: %04x:%08RX64/%s: %s%s %#x LB %u (emulating)\n",
2492 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
2493 pExit->IoPortAccess.AccessInfo.RepPrefix ? "REP " : "",
2494 pExit->IoPortAccess.AccessInfo.IsWrite ? "OUTS" : "INS",
2495 pExit->IoPortAccess.PortNumber, pExit->IoPortAccess.AccessInfo.AccessSize ));
2496 rcStrict = IEMExecOne(pVCpu);
2497 }
2498 if (IOM_SUCCESS(rcStrict))
2499 {
2500 /*
2501 * Do debug checks.
2502 */
2503 if ( pExit->VpContext.ExecutionState.DebugActive /** @todo Microsoft: Does DebugActive this only reflect DR7? */
2504 || (pExit->VpContext.Rflags & X86_EFL_TF)
2505 || DBGFBpIsHwIoArmed(pVM) )
2506 {
2507 /** @todo Debugging. */
2508 }
2509 }
2510 return rcStrict;
2511 }
2512
2513 /*
2514 * Frequent exit or something needing probing.
2515 * Get state and call EMHistoryExec.
2516 */
2517 nemR3WinCopyStateFromX64Header(pVCpu, &pExit->VpContext);
2518 if (!pExit->IoPortAccess.AccessInfo.StringOp)
2519 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_RAX;
2520 else
2521 {
2522 pVCpu->cpum.GstCtx.fExtrn &= ~( CPUMCTX_EXTRN_RAX | CPUMCTX_EXTRN_RCX | CPUMCTX_EXTRN_RDI | CPUMCTX_EXTRN_RSI
2523 | CPUMCTX_EXTRN_DS | CPUMCTX_EXTRN_ES);
2524 NEM_WIN_COPY_BACK_SEG(pVCpu->cpum.GstCtx.ds, pExit->IoPortAccess.Ds);
2525 NEM_WIN_COPY_BACK_SEG(pVCpu->cpum.GstCtx.es, pExit->IoPortAccess.Es);
2526 pVCpu->cpum.GstCtx.rcx = pExit->IoPortAccess.Rcx;
2527 pVCpu->cpum.GstCtx.rdi = pExit->IoPortAccess.Rdi;
2528 pVCpu->cpum.GstCtx.rsi = pExit->IoPortAccess.Rsi;
2529 }
2530 pVCpu->cpum.GstCtx.rax = pExit->IoPortAccess.Rax;
2531 int rc = nemHCWinCopyStateFromHyperV(pVM, pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM);
2532 AssertRCReturn(rc, rc);
2533 Log4(("IOExit/%u: %04x:%08RX64/%s: %s%s%s %#x LB %u -> EMHistoryExec\n",
2534 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
2535 pExit->IoPortAccess.AccessInfo.RepPrefix ? "REP " : "",
2536 pExit->IoPortAccess.AccessInfo.IsWrite ? "OUT" : "IN",
2537 pExit->IoPortAccess.AccessInfo.StringOp ? "S" : "",
2538 pExit->IoPortAccess.PortNumber, pExit->IoPortAccess.AccessInfo.AccessSize));
2539 VBOXSTRICTRC rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
2540 Log4(("IOExit/%u: %04x:%08RX64/%s: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
2541 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
2542 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
2543 return rcStrict;
2544}
2545#endif /* IN_RING3 && !NEM_WIN_TEMPLATE_MODE_OWN_RUN_API */
2546
2547
2548#ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
2549/**
2550 * Deals with interrupt window message.
2551 *
2552 * @returns Strict VBox status code.
2553 * @param pVM The cross context VM structure.
2554 * @param pVCpu The cross context per CPU structure.
2555 * @param pMsg The message.
2556 * @sa nemR3WinHandleExitInterruptWindow
2557 */
2558NEM_TMPL_STATIC VBOXSTRICTRC
2559nemHCWinHandleMessageInterruptWindow(PVMCC pVM, PVMCPUCC pVCpu, HV_X64_INTERRUPT_WINDOW_MESSAGE const *pMsg)
2560{
2561 /*
2562 * Assert message sanity.
2563 */
2564 Assert( pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_EXECUTE
2565 || pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_READ // READ & WRITE are probably not used here
2566 || pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE);
2567 AssertMsg(pMsg->Type == HvX64PendingInterrupt || pMsg->Type == HvX64PendingNmi, ("%#x\n", pMsg->Type));
2568
2569 /*
2570 * Just copy the state we've got and handle it in the loop for now.
2571 */
2572 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_INTTERRUPT_WINDOW),
2573 pMsg->Header.Rip + pMsg->Header.CsSegment.Base, ASMReadTSC());
2574
2575 nemHCWinCopyStateFromX64Header(pVCpu, &pMsg->Header);
2576 Log4(("IntWinExit/%u: %04x:%08RX64/%s: %u IF=%d InterruptShadow=%d\n",
2577 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2578 pMsg->Type, RT_BOOL(pMsg->Header.Rflags & X86_EFL_IF), pMsg->Header.ExecutionState.InterruptShadow));
2579
2580 /** @todo call nemHCWinHandleInterruptFF */
2581 RT_NOREF(pVM);
2582 return VINF_SUCCESS;
2583}
2584#elif defined(IN_RING3)
2585/**
2586 * Deals with interrupt window exits (WHvRunVpExitReasonX64InterruptWindow).
2587 *
2588 * @returns Strict VBox status code.
2589 * @param pVM The cross context VM structure.
2590 * @param pVCpu The cross context per CPU structure.
2591 * @param pExit The VM exit information to handle.
2592 * @sa nemHCWinHandleMessageInterruptWindow
2593 */
2594NEM_TMPL_STATIC VBOXSTRICTRC nemR3WinHandleExitInterruptWindow(PVMCC pVM, PVMCPUCC pVCpu, WHV_RUN_VP_EXIT_CONTEXT const *pExit)
2595{
2596 /*
2597 * Assert message sanity.
2598 */
2599 AssertMsg( pExit->InterruptWindow.DeliverableType == WHvX64PendingInterrupt
2600 || pExit->InterruptWindow.DeliverableType == WHvX64PendingNmi,
2601 ("%#x\n", pExit->InterruptWindow.DeliverableType));
2602
2603 /*
2604 * Just copy the state we've got and handle it in the loop for now.
2605 */
2606 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_INTTERRUPT_WINDOW),
2607 pExit->VpContext.Rip + pExit->VpContext.Cs.Base, ASMReadTSC());
2608
2609 nemR3WinCopyStateFromX64Header(pVCpu, &pExit->VpContext);
2610 Log4(("IntWinExit/%u: %04x:%08RX64/%s: %u IF=%d InterruptShadow=%d CR8=%#x\n",
2611 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
2612 pExit->InterruptWindow.DeliverableType, RT_BOOL(pExit->VpContext.Rflags & X86_EFL_IF),
2613 pExit->VpContext.ExecutionState.InterruptShadow, pExit->VpContext.Cr8));
2614
2615 /** @todo call nemHCWinHandleInterruptFF */
2616 RT_NOREF(pVM);
2617 return VINF_SUCCESS;
2618}
2619#endif /* IN_RING3 && !NEM_WIN_TEMPLATE_MODE_OWN_RUN_API */
2620
2621
2622#ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
2623/**
2624 * Deals with CPUID intercept message.
2625 *
2626 * @returns Strict VBox status code.
2627 * @param pVM The cross context VM structure.
2628 * @param pVCpu The cross context per CPU structure.
2629 * @param pMsg The message.
2630 * @sa nemR3WinHandleExitCpuId
2631 */
2632NEM_TMPL_STATIC VBOXSTRICTRC nemHCWinHandleMessageCpuId(PVMCC pVM, PVMCPUCC pVCpu, HV_X64_CPUID_INTERCEPT_MESSAGE const *pMsg)
2633{
2634 /* Check message register value sanity. */
2635 NEMWIN_ASSERT_MSG_REG_SEG( pVCpu, HvX64RegisterCs, pMsg->Header.CsSegment);
2636 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRip, pMsg->Header.Rip);
2637 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRflags, pMsg->Header.Rflags);
2638 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterCr8, (uint64_t)pMsg->Header.Cr8);
2639 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRax, pMsg->Rax);
2640 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRcx, pMsg->Rcx);
2641 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRdx, pMsg->Rdx);
2642 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRbx, pMsg->Rbx);
2643
2644 /* Do exit history. */
2645 PCEMEXITREC pExitRec = EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_CPUID),
2646 pMsg->Header.Rip + pMsg->Header.CsSegment.Base, ASMReadTSC());
2647 if (!pExitRec)
2648 {
2649 /*
2650 * Soak up state and execute the instruction.
2651 *
2652 * Note! If this grows slightly more complicated, combine into an IEMExecDecodedCpuId
2653 * function and make everyone use it.
2654 */
2655 /** @todo Combine implementations into IEMExecDecodedCpuId as this will
2656 * only get weirder with nested VT-x and AMD-V support. */
2657 nemHCWinCopyStateFromX64Header(pVCpu, &pMsg->Header);
2658
2659 /* Copy in the low register values (top is always cleared). */
2660 pVCpu->cpum.GstCtx.rax = (uint32_t)pMsg->Rax;
2661 pVCpu->cpum.GstCtx.rcx = (uint32_t)pMsg->Rcx;
2662 pVCpu->cpum.GstCtx.rdx = (uint32_t)pMsg->Rdx;
2663 pVCpu->cpum.GstCtx.rbx = (uint32_t)pMsg->Rbx;
2664 pVCpu->cpum.GstCtx.fExtrn &= ~(CPUMCTX_EXTRN_RAX | CPUMCTX_EXTRN_RCX | CPUMCTX_EXTRN_RDX | CPUMCTX_EXTRN_RBX);
2665
2666 /* Get the correct values. */
2667 CPUMGetGuestCpuId(pVCpu, pVCpu->cpum.GstCtx.eax, pVCpu->cpum.GstCtx.ecx,
2668 &pVCpu->cpum.GstCtx.eax, &pVCpu->cpum.GstCtx.ebx, &pVCpu->cpum.GstCtx.ecx, &pVCpu->cpum.GstCtx.edx);
2669
2670 Log4(("CpuIdExit/%u: %04x:%08RX64/%s: rax=%08RX64 / rcx=%08RX64 / rdx=%08RX64 / rbx=%08RX64 -> %08RX32 / %08RX32 / %08RX32 / %08RX32 (hv: %08RX64 / %08RX64 / %08RX64 / %08RX64)\n",
2671 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2672 pMsg->Rax, pMsg->Rcx, pMsg->Rdx, pMsg->Rbx,
2673 pVCpu->cpum.GstCtx.eax, pVCpu->cpum.GstCtx.ecx, pVCpu->cpum.GstCtx.edx, pVCpu->cpum.GstCtx.ebx,
2674 pMsg->DefaultResultRax, pMsg->DefaultResultRcx, pMsg->DefaultResultRdx, pMsg->DefaultResultRbx));
2675
2676 /* Move RIP and we're done. */
2677 nemHCWinAdvanceGuestRipAndClearRF(pVCpu, &pMsg->Header, 2);
2678
2679 return VINF_SUCCESS;
2680 }
2681
2682 /*
2683 * Frequent exit or something needing probing.
2684 * Get state and call EMHistoryExec.
2685 */
2686 nemHCWinCopyStateFromX64Header(pVCpu, &pMsg->Header);
2687 pVCpu->cpum.GstCtx.rax = pMsg->Rax;
2688 pVCpu->cpum.GstCtx.rcx = pMsg->Rcx;
2689 pVCpu->cpum.GstCtx.rdx = pMsg->Rdx;
2690 pVCpu->cpum.GstCtx.rbx = pMsg->Rbx;
2691 pVCpu->cpum.GstCtx.fExtrn &= ~(CPUMCTX_EXTRN_RAX | CPUMCTX_EXTRN_RCX | CPUMCTX_EXTRN_RDX | CPUMCTX_EXTRN_RBX);
2692 Log4(("CpuIdExit/%u: %04x:%08RX64/%s: rax=%08RX64 / rcx=%08RX64 / rdx=%08RX64 / rbx=%08RX64 (hv: %08RX64 / %08RX64 / %08RX64 / %08RX64) ==> EMHistoryExec\n",
2693 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2694 pMsg->Rax, pMsg->Rcx, pMsg->Rdx, pMsg->Rbx,
2695 pMsg->DefaultResultRax, pMsg->DefaultResultRcx, pMsg->DefaultResultRdx, pMsg->DefaultResultRbx));
2696# ifdef IN_RING0
2697 VBOXSTRICTRC rcStrict = nemR0WinImportStateStrict(pVM, pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM, "CpuIdExit");
2698 if (rcStrict != VINF_SUCCESS)
2699 return rcStrict;
2700 RT_NOREF(pVM);
2701# else
2702 int rc = nemHCWinCopyStateFromHyperV(pVM, pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM);
2703 AssertRCReturn(rc, rc);
2704# endif
2705 VBOXSTRICTRC rcStrictExec = EMHistoryExec(pVCpu, pExitRec, 0);
2706 Log4(("CpuIdExit/%u: %04x:%08RX64/%s: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
2707 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2708 VBOXSTRICTRC_VAL(rcStrictExec), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
2709 return rcStrictExec;
2710}
2711#elif defined(IN_RING3)
2712/**
2713 * Deals with CPUID exits (WHvRunVpExitReasonX64Cpuid).
2714 *
2715 * @returns Strict VBox status code.
2716 * @param pVM The cross context VM structure.
2717 * @param pVCpu The cross context per CPU structure.
2718 * @param pExit The VM exit information to handle.
2719 * @sa nemHCWinHandleMessageCpuId
2720 */
2721NEM_TMPL_STATIC VBOXSTRICTRC
2722nemR3WinHandleExitCpuId(PVMCC pVM, PVMCPUCC pVCpu, WHV_RUN_VP_EXIT_CONTEXT const *pExit)
2723{
2724 PCEMEXITREC pExitRec = EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_CPUID),
2725 pExit->VpContext.Rip + pExit->VpContext.Cs.Base, ASMReadTSC());
2726 if (!pExitRec)
2727 {
2728 /*
2729 * Soak up state and execute the instruction.
2730 *
2731 * Note! If this grows slightly more complicated, combine into an IEMExecDecodedCpuId
2732 * function and make everyone use it.
2733 */
2734 /** @todo Combine implementations into IEMExecDecodedCpuId as this will
2735 * only get weirder with nested VT-x and AMD-V support. */
2736 nemR3WinCopyStateFromX64Header(pVCpu, &pExit->VpContext);
2737
2738 /* Copy in the low register values (top is always cleared). */
2739 pVCpu->cpum.GstCtx.rax = (uint32_t)pExit->CpuidAccess.Rax;
2740 pVCpu->cpum.GstCtx.rcx = (uint32_t)pExit->CpuidAccess.Rcx;
2741 pVCpu->cpum.GstCtx.rdx = (uint32_t)pExit->CpuidAccess.Rdx;
2742 pVCpu->cpum.GstCtx.rbx = (uint32_t)pExit->CpuidAccess.Rbx;
2743 pVCpu->cpum.GstCtx.fExtrn &= ~(CPUMCTX_EXTRN_RAX | CPUMCTX_EXTRN_RCX | CPUMCTX_EXTRN_RDX | CPUMCTX_EXTRN_RBX);
2744
2745 /* Get the correct values. */
2746 CPUMGetGuestCpuId(pVCpu, pVCpu->cpum.GstCtx.eax, pVCpu->cpum.GstCtx.ecx,
2747 &pVCpu->cpum.GstCtx.eax, &pVCpu->cpum.GstCtx.ebx, &pVCpu->cpum.GstCtx.ecx, &pVCpu->cpum.GstCtx.edx);
2748
2749 Log4(("CpuIdExit/%u: %04x:%08RX64/%s: rax=%08RX64 / rcx=%08RX64 / rdx=%08RX64 / rbx=%08RX64 -> %08RX32 / %08RX32 / %08RX32 / %08RX32 (hv: %08RX64 / %08RX64 / %08RX64 / %08RX64)\n",
2750 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
2751 pExit->CpuidAccess.Rax, pExit->CpuidAccess.Rcx, pExit->CpuidAccess.Rdx, pExit->CpuidAccess.Rbx,
2752 pVCpu->cpum.GstCtx.eax, pVCpu->cpum.GstCtx.ecx, pVCpu->cpum.GstCtx.edx, pVCpu->cpum.GstCtx.ebx,
2753 pExit->CpuidAccess.DefaultResultRax, pExit->CpuidAccess.DefaultResultRcx, pExit->CpuidAccess.DefaultResultRdx, pExit->CpuidAccess.DefaultResultRbx));
2754
2755 /* Move RIP and we're done. */
2756 nemR3WinAdvanceGuestRipAndClearRF(pVCpu, &pExit->VpContext, 2);
2757
2758 RT_NOREF_PV(pVM);
2759 return VINF_SUCCESS;
2760 }
2761
2762 /*
2763 * Frequent exit or something needing probing.
2764 * Get state and call EMHistoryExec.
2765 */
2766 nemR3WinCopyStateFromX64Header(pVCpu, &pExit->VpContext);
2767 pVCpu->cpum.GstCtx.rax = pExit->CpuidAccess.Rax;
2768 pVCpu->cpum.GstCtx.rcx = pExit->CpuidAccess.Rcx;
2769 pVCpu->cpum.GstCtx.rdx = pExit->CpuidAccess.Rdx;
2770 pVCpu->cpum.GstCtx.rbx = pExit->CpuidAccess.Rbx;
2771 pVCpu->cpum.GstCtx.fExtrn &= ~(CPUMCTX_EXTRN_RAX | CPUMCTX_EXTRN_RCX | CPUMCTX_EXTRN_RDX | CPUMCTX_EXTRN_RBX);
2772 Log4(("CpuIdExit/%u: %04x:%08RX64/%s: rax=%08RX64 / rcx=%08RX64 / rdx=%08RX64 / rbx=%08RX64 (hv: %08RX64 / %08RX64 / %08RX64 / %08RX64) ==> EMHistoryExec\n",
2773 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
2774 pExit->CpuidAccess.Rax, pExit->CpuidAccess.Rcx, pExit->CpuidAccess.Rdx, pExit->CpuidAccess.Rbx,
2775 pExit->CpuidAccess.DefaultResultRax, pExit->CpuidAccess.DefaultResultRcx, pExit->CpuidAccess.DefaultResultRdx, pExit->CpuidAccess.DefaultResultRbx));
2776 int rc = nemHCWinCopyStateFromHyperV(pVM, pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM);
2777 AssertRCReturn(rc, rc);
2778 VBOXSTRICTRC rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
2779 Log4(("CpuIdExit/%u: %04x:%08RX64/%s: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
2780 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
2781 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
2782 return rcStrict;
2783}
2784#endif /* IN_RING3 && !NEM_WIN_TEMPLATE_MODE_OWN_RUN_API */
2785
2786
2787#ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
2788/**
2789 * Deals with MSR intercept message.
2790 *
2791 * @returns Strict VBox status code.
2792 * @param pVCpu The cross context per CPU structure.
2793 * @param pMsg The message.
2794 * @sa nemR3WinHandleExitMsr
2795 */
2796NEM_TMPL_STATIC VBOXSTRICTRC nemHCWinHandleMessageMsr(PVMCPUCC pVCpu, HV_X64_MSR_INTERCEPT_MESSAGE const *pMsg)
2797{
2798 /*
2799 * A wee bit of sanity first.
2800 */
2801 Assert( pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_READ
2802 || pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE);
2803 NEMWIN_ASSERT_MSG_REG_SEG( pVCpu, HvX64RegisterCs, pMsg->Header.CsSegment);
2804 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRip, pMsg->Header.Rip);
2805 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRflags, pMsg->Header.Rflags);
2806 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterCr8, (uint64_t)pMsg->Header.Cr8);
2807 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRax, pMsg->Rax);
2808 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRdx, pMsg->Rdx);
2809
2810 /*
2811 * Check CPL as that's common to both RDMSR and WRMSR.
2812 */
2813 VBOXSTRICTRC rcStrict;
2814 if (pMsg->Header.ExecutionState.Cpl == 0)
2815 {
2816 /*
2817 * Get all the MSR state. Since we're getting EFER, we also need to
2818 * get CR0, CR4 and CR3.
2819 */
2820 PCEMEXITREC pExitRec = EMHistoryAddExit(pVCpu,
2821 pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE
2822 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_MSR_WRITE)
2823 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_MSR_READ),
2824 pMsg->Header.Rip + pMsg->Header.CsSegment.Base, ASMReadTSC());
2825
2826 nemHCWinCopyStateFromX64Header(pVCpu, &pMsg->Header);
2827 rcStrict = nemHCWinImportStateIfNeededStrict(pVCpu,
2828 (!pExitRec ? 0 : IEM_CPUMCTX_EXTRN_MUST_MASK)
2829 | CPUMCTX_EXTRN_ALL_MSRS | CPUMCTX_EXTRN_CR0
2830 | CPUMCTX_EXTRN_CR3 | CPUMCTX_EXTRN_CR4,
2831 "MSRs");
2832 if (rcStrict == VINF_SUCCESS)
2833 {
2834 if (!pExitRec)
2835 {
2836 /*
2837 * Handle writes.
2838 */
2839 if (pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE)
2840 {
2841 rcStrict = CPUMSetGuestMsr(pVCpu, pMsg->MsrNumber, RT_MAKE_U64((uint32_t)pMsg->Rax, (uint32_t)pMsg->Rdx));
2842 Log4(("MsrExit/%u: %04x:%08RX64/%s: WRMSR %08x, %08x:%08x -> %Rrc\n",
2843 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2844 pMsg->MsrNumber, (uint32_t)pMsg->Rax, (uint32_t)pMsg->Rdx, VBOXSTRICTRC_VAL(rcStrict) ));
2845 if (rcStrict == VINF_SUCCESS)
2846 {
2847 nemHCWinAdvanceGuestRipAndClearRF(pVCpu, &pMsg->Header, 2);
2848 return VINF_SUCCESS;
2849 }
2850# ifndef IN_RING3
2851 /* move to ring-3 and handle the trap/whatever there, as we want to LogRel this. */
2852 if (rcStrict == VERR_CPUM_RAISE_GP_0)
2853 rcStrict = VINF_CPUM_R3_MSR_WRITE;
2854 return rcStrict;
2855# else
2856 LogRel(("MsrExit/%u: %04x:%08RX64/%s: WRMSR %08x, %08x:%08x -> %Rrc!\n",
2857 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2858 pMsg->MsrNumber, (uint32_t)pMsg->Rax, (uint32_t)pMsg->Rdx, VBOXSTRICTRC_VAL(rcStrict) ));
2859# endif
2860 }
2861 /*
2862 * Handle reads.
2863 */
2864 else
2865 {
2866 uint64_t uValue = 0;
2867 rcStrict = CPUMQueryGuestMsr(pVCpu, pMsg->MsrNumber, &uValue);
2868 Log4(("MsrExit/%u: %04x:%08RX64/%s: RDMSR %08x -> %08RX64 / %Rrc\n",
2869 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2870 pMsg->MsrNumber, uValue, VBOXSTRICTRC_VAL(rcStrict) ));
2871 if (rcStrict == VINF_SUCCESS)
2872 {
2873 pVCpu->cpum.GstCtx.rax = (uint32_t)uValue;
2874 pVCpu->cpum.GstCtx.rdx = uValue >> 32;
2875 pVCpu->cpum.GstCtx.fExtrn &= ~(CPUMCTX_EXTRN_RAX | CPUMCTX_EXTRN_RDX);
2876 nemHCWinAdvanceGuestRipAndClearRF(pVCpu, &pMsg->Header, 2);
2877 return VINF_SUCCESS;
2878 }
2879# ifndef IN_RING3
2880 /* move to ring-3 and handle the trap/whatever there, as we want to LogRel this. */
2881 if (rcStrict == VERR_CPUM_RAISE_GP_0)
2882 rcStrict = VINF_CPUM_R3_MSR_READ;
2883 return rcStrict;
2884# else
2885 LogRel(("MsrExit/%u: %04x:%08RX64/%s: RDMSR %08x -> %08RX64 / %Rrc\n",
2886 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2887 pMsg->MsrNumber, uValue, VBOXSTRICTRC_VAL(rcStrict) ));
2888# endif
2889 }
2890 }
2891 else
2892 {
2893 /*
2894 * Handle frequent exit or something needing probing.
2895 */
2896 Log4(("MsrExit/%u: %04x:%08RX64/%s: %sMSR %#08x\n",
2897 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2898 pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE ? "WR" : "RD", pMsg->MsrNumber));
2899 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
2900 Log4(("MsrExit/%u: %04x:%08RX64/%s: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
2901 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2902 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
2903 return rcStrict;
2904 }
2905 }
2906 else
2907 {
2908 LogRel(("MsrExit/%u: %04x:%08RX64/%s: %sMSR %08x -> %Rrc - msr state import\n",
2909 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2910 pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE ? "WR" : "RD",
2911 pMsg->MsrNumber, VBOXSTRICTRC_VAL(rcStrict) ));
2912 return rcStrict;
2913 }
2914 }
2915 else if (pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE)
2916 Log4(("MsrExit/%u: %04x:%08RX64/%s: CPL %u -> #GP(0); WRMSR %08x, %08x:%08x\n",
2917 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2918 pMsg->Header.ExecutionState.Cpl, pMsg->MsrNumber, (uint32_t)pMsg->Rax, (uint32_t)pMsg->Rdx ));
2919 else
2920 Log4(("MsrExit/%u: %04x:%08RX64/%s: CPL %u -> #GP(0); RDMSR %08x\n",
2921 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2922 pMsg->Header.ExecutionState.Cpl, pMsg->MsrNumber));
2923
2924 /*
2925 * If we get down here, we're supposed to #GP(0).
2926 */
2927 rcStrict = nemHCWinImportStateIfNeededStrict(pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM | CPUMCTX_EXTRN_ALL_MSRS, "MSR");
2928 if (rcStrict == VINF_SUCCESS)
2929 {
2930 rcStrict = IEMInjectTrap(pVCpu, X86_XCPT_GP, TRPM_TRAP, 0, 0, 0);
2931 if (rcStrict == VINF_IEM_RAISED_XCPT)
2932 rcStrict = VINF_SUCCESS;
2933 else if (rcStrict != VINF_SUCCESS)
2934 Log4(("MsrExit/%u: Injecting #GP(0) failed: %Rrc\n", VBOXSTRICTRC_VAL(rcStrict) ));
2935 }
2936 return rcStrict;
2937}
2938#elif defined(IN_RING3)
2939/**
2940 * Deals with MSR access exits (WHvRunVpExitReasonX64MsrAccess).
2941 *
2942 * @returns Strict VBox status code.
2943 * @param pVM The cross context VM structure.
2944 * @param pVCpu The cross context per CPU structure.
2945 * @param pExit The VM exit information to handle.
2946 * @sa nemHCWinHandleMessageMsr
2947 */
2948NEM_TMPL_STATIC VBOXSTRICTRC nemR3WinHandleExitMsr(PVMCC pVM, PVMCPUCC pVCpu, WHV_RUN_VP_EXIT_CONTEXT const *pExit)
2949{
2950 /*
2951 * Check CPL as that's common to both RDMSR and WRMSR.
2952 */
2953 VBOXSTRICTRC rcStrict;
2954 if (pExit->VpContext.ExecutionState.Cpl == 0)
2955 {
2956 /*
2957 * Get all the MSR state. Since we're getting EFER, we also need to
2958 * get CR0, CR4 and CR3.
2959 */
2960 PCEMEXITREC pExitRec = EMHistoryAddExit(pVCpu,
2961 pExit->MsrAccess.AccessInfo.IsWrite
2962 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_MSR_WRITE)
2963 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_MSR_READ),
2964 pExit->VpContext.Rip + pExit->VpContext.Cs.Base, ASMReadTSC());
2965 nemR3WinCopyStateFromX64Header(pVCpu, &pExit->VpContext);
2966 rcStrict = nemHCWinImportStateIfNeededStrict(pVCpu,
2967 (!pExitRec ? 0 : IEM_CPUMCTX_EXTRN_MUST_MASK)
2968 | CPUMCTX_EXTRN_ALL_MSRS | CPUMCTX_EXTRN_CR0
2969 | CPUMCTX_EXTRN_CR3 | CPUMCTX_EXTRN_CR4,
2970 "MSRs");
2971 if (rcStrict == VINF_SUCCESS)
2972 {
2973 if (!pExitRec)
2974 {
2975 /*
2976 * Handle writes.
2977 */
2978 if (pExit->MsrAccess.AccessInfo.IsWrite)
2979 {
2980 rcStrict = CPUMSetGuestMsr(pVCpu, pExit->MsrAccess.MsrNumber,
2981 RT_MAKE_U64((uint32_t)pExit->MsrAccess.Rax, (uint32_t)pExit->MsrAccess.Rdx));
2982 Log4(("MsrExit/%u: %04x:%08RX64/%s: WRMSR %08x, %08x:%08x -> %Rrc\n", pVCpu->idCpu, pExit->VpContext.Cs.Selector,
2983 pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext), pExit->MsrAccess.MsrNumber,
2984 (uint32_t)pExit->MsrAccess.Rax, (uint32_t)pExit->MsrAccess.Rdx, VBOXSTRICTRC_VAL(rcStrict) ));
2985 if (rcStrict == VINF_SUCCESS)
2986 {
2987 nemR3WinAdvanceGuestRipAndClearRF(pVCpu, &pExit->VpContext, 2);
2988 return VINF_SUCCESS;
2989 }
2990 LogRel(("MsrExit/%u: %04x:%08RX64/%s: WRMSR %08x, %08x:%08x -> %Rrc!\n", pVCpu->idCpu,
2991 pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
2992 pExit->MsrAccess.MsrNumber, (uint32_t)pExit->MsrAccess.Rax, (uint32_t)pExit->MsrAccess.Rdx,
2993 VBOXSTRICTRC_VAL(rcStrict) ));
2994 }
2995 /*
2996 * Handle reads.
2997 */
2998 else
2999 {
3000 uint64_t uValue = 0;
3001 rcStrict = CPUMQueryGuestMsr(pVCpu, pExit->MsrAccess.MsrNumber, &uValue);
3002 Log4(("MsrExit/%u: %04x:%08RX64/%s: RDMSR %08x -> %08RX64 / %Rrc\n", pVCpu->idCpu,
3003 pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
3004 pExit->MsrAccess.MsrNumber, uValue, VBOXSTRICTRC_VAL(rcStrict) ));
3005 if (rcStrict == VINF_SUCCESS)
3006 {
3007 pVCpu->cpum.GstCtx.rax = (uint32_t)uValue;
3008 pVCpu->cpum.GstCtx.rdx = uValue >> 32;
3009 pVCpu->cpum.GstCtx.fExtrn &= ~(CPUMCTX_EXTRN_RAX | CPUMCTX_EXTRN_RDX);
3010 nemR3WinAdvanceGuestRipAndClearRF(pVCpu, &pExit->VpContext, 2);
3011 return VINF_SUCCESS;
3012 }
3013 LogRel(("MsrExit/%u: %04x:%08RX64/%s: RDMSR %08x -> %08RX64 / %Rrc\n", pVCpu->idCpu, pExit->VpContext.Cs.Selector,
3014 pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext), pExit->MsrAccess.MsrNumber,
3015 uValue, VBOXSTRICTRC_VAL(rcStrict) ));
3016 }
3017 }
3018 else
3019 {
3020 /*
3021 * Handle frequent exit or something needing probing.
3022 */
3023 Log4(("MsrExit/%u: %04x:%08RX64/%s: %sMSR %#08x\n",
3024 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
3025 pExit->MsrAccess.AccessInfo.IsWrite ? "WR" : "RD", pExit->MsrAccess.MsrNumber));
3026 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
3027 Log4(("MsrExit/%u: %04x:%08RX64/%s: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
3028 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
3029 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
3030 return rcStrict;
3031 }
3032 }
3033 else
3034 {
3035 LogRel(("MsrExit/%u: %04x:%08RX64/%s: %sMSR %08x -> %Rrc - msr state import\n",
3036 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
3037 pExit->MsrAccess.AccessInfo.IsWrite ? "WR" : "RD", pExit->MsrAccess.MsrNumber, VBOXSTRICTRC_VAL(rcStrict) ));
3038 return rcStrict;
3039 }
3040 }
3041 else if (pExit->MsrAccess.AccessInfo.IsWrite)
3042 Log4(("MsrExit/%u: %04x:%08RX64/%s: CPL %u -> #GP(0); WRMSR %08x, %08x:%08x\n", pVCpu->idCpu, pExit->VpContext.Cs.Selector,
3043 pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext), pExit->VpContext.ExecutionState.Cpl,
3044 pExit->MsrAccess.MsrNumber, (uint32_t)pExit->MsrAccess.Rax, (uint32_t)pExit->MsrAccess.Rdx ));
3045 else
3046 Log4(("MsrExit/%u: %04x:%08RX64/%s: CPL %u -> #GP(0); RDMSR %08x\n", pVCpu->idCpu, pExit->VpContext.Cs.Selector,
3047 pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext), pExit->VpContext.ExecutionState.Cpl,
3048 pExit->MsrAccess.MsrNumber));
3049
3050 /*
3051 * If we get down here, we're supposed to #GP(0).
3052 */
3053 rcStrict = nemHCWinImportStateIfNeededStrict(pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM | CPUMCTX_EXTRN_ALL_MSRS, "MSR");
3054 if (rcStrict == VINF_SUCCESS)
3055 {
3056 rcStrict = IEMInjectTrap(pVCpu, X86_XCPT_GP, TRPM_TRAP, 0, 0, 0);
3057 if (rcStrict == VINF_IEM_RAISED_XCPT)
3058 rcStrict = VINF_SUCCESS;
3059 else if (rcStrict != VINF_SUCCESS)
3060 Log4(("MsrExit/%u: Injecting #GP(0) failed: %Rrc\n", VBOXSTRICTRC_VAL(rcStrict) ));
3061 }
3062
3063 RT_NOREF_PV(pVM);
3064 return rcStrict;
3065}
3066#endif /* IN_RING3 && !NEM_WIN_TEMPLATE_MODE_OWN_RUN_API */
3067
3068
3069/**
3070 * Worker for nemHCWinHandleMessageException & nemR3WinHandleExitException that
3071 * checks if the given opcodes are of interest at all.
3072 *
3073 * @returns true if interesting, false if not.
3074 * @param cbOpcodes Number of opcode bytes available.
3075 * @param pbOpcodes The opcode bytes.
3076 * @param f64BitMode Whether we're in 64-bit mode.
3077 */
3078DECLINLINE(bool) nemHcWinIsInterestingUndefinedOpcode(uint8_t cbOpcodes, uint8_t const *pbOpcodes, bool f64BitMode)
3079{
3080 /*
3081 * Currently only interested in VMCALL and VMMCALL.
3082 */
3083 while (cbOpcodes >= 3)
3084 {
3085 switch (pbOpcodes[0])
3086 {
3087 case 0x0f:
3088 switch (pbOpcodes[1])
3089 {
3090 case 0x01:
3091 switch (pbOpcodes[2])
3092 {
3093 case 0xc1: /* 0f 01 c1 VMCALL */
3094 return true;
3095 case 0xd9: /* 0f 01 d9 VMMCALL */
3096 return true;
3097 default:
3098 break;
3099 }
3100 break;
3101 }
3102 break;
3103
3104 default:
3105 return false;
3106
3107 /* prefixes */
3108 case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: case 0x46: case 0x47:
3109 case 0x48: case 0x49: case 0x4a: case 0x4b: case 0x4c: case 0x4d: case 0x4e: case 0x4f:
3110 if (!f64BitMode)
3111 return false;
3112 RT_FALL_THRU();
3113 case X86_OP_PRF_CS:
3114 case X86_OP_PRF_SS:
3115 case X86_OP_PRF_DS:
3116 case X86_OP_PRF_ES:
3117 case X86_OP_PRF_FS:
3118 case X86_OP_PRF_GS:
3119 case X86_OP_PRF_SIZE_OP:
3120 case X86_OP_PRF_SIZE_ADDR:
3121 case X86_OP_PRF_LOCK:
3122 case X86_OP_PRF_REPZ:
3123 case X86_OP_PRF_REPNZ:
3124 cbOpcodes--;
3125 pbOpcodes++;
3126 continue;
3127 }
3128 break;
3129 }
3130 return false;
3131}
3132
3133
3134#ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
3135/**
3136 * Copies state included in a exception intercept message.
3137 *
3138 * @param pVCpu The cross context per CPU structure.
3139 * @param pMsg The message.
3140 * @param fClearXcpt Clear pending exception.
3141 */
3142DECLINLINE(void)
3143nemHCWinCopyStateFromExceptionMessage(PVMCPUCC pVCpu, HV_X64_EXCEPTION_INTERCEPT_MESSAGE const *pMsg, bool fClearXcpt)
3144{
3145 nemHCWinCopyStateFromX64Header(pVCpu, &pMsg->Header);
3146 pVCpu->cpum.GstCtx.fExtrn &= ~( CPUMCTX_EXTRN_GPRS_MASK | CPUMCTX_EXTRN_SS | CPUMCTX_EXTRN_DS
3147 | (fClearXcpt ? CPUMCTX_EXTRN_NEM_WIN_EVENT_INJECT : 0) );
3148 pVCpu->cpum.GstCtx.rax = pMsg->Rax;
3149 pVCpu->cpum.GstCtx.rcx = pMsg->Rcx;
3150 pVCpu->cpum.GstCtx.rdx = pMsg->Rdx;
3151 pVCpu->cpum.GstCtx.rbx = pMsg->Rbx;
3152 pVCpu->cpum.GstCtx.rsp = pMsg->Rsp;
3153 pVCpu->cpum.GstCtx.rbp = pMsg->Rbp;
3154 pVCpu->cpum.GstCtx.rsi = pMsg->Rsi;
3155 pVCpu->cpum.GstCtx.rdi = pMsg->Rdi;
3156 pVCpu->cpum.GstCtx.r8 = pMsg->R8;
3157 pVCpu->cpum.GstCtx.r9 = pMsg->R9;
3158 pVCpu->cpum.GstCtx.r10 = pMsg->R10;
3159 pVCpu->cpum.GstCtx.r11 = pMsg->R11;
3160 pVCpu->cpum.GstCtx.r12 = pMsg->R12;
3161 pVCpu->cpum.GstCtx.r13 = pMsg->R13;
3162 pVCpu->cpum.GstCtx.r14 = pMsg->R14;
3163 pVCpu->cpum.GstCtx.r15 = pMsg->R15;
3164 NEM_WIN_COPY_BACK_SEG(pVCpu->cpum.GstCtx.ds, pMsg->DsSegment);
3165 NEM_WIN_COPY_BACK_SEG(pVCpu->cpum.GstCtx.ss, pMsg->SsSegment);
3166}
3167#elif defined(IN_RING3)
3168/**
3169 * Copies state included in a exception intercept exit.
3170 *
3171 * @param pVCpu The cross context per CPU structure.
3172 * @param pExit The VM exit information.
3173 * @param fClearXcpt Clear pending exception.
3174 */
3175DECLINLINE(void) nemR3WinCopyStateFromExceptionMessage(PVMCPUCC pVCpu, WHV_RUN_VP_EXIT_CONTEXT const *pExit, bool fClearXcpt)
3176{
3177 nemR3WinCopyStateFromX64Header(pVCpu, &pExit->VpContext);
3178 if (fClearXcpt)
3179 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_NEM_WIN_EVENT_INJECT;
3180}
3181#endif /* IN_RING3 && !NEM_WIN_TEMPLATE_MODE_OWN_RUN_API */
3182
3183
3184/**
3185 * Advances the guest RIP by the number of bytes specified in @a cb.
3186 *
3187 * @param pVCpu The cross context virtual CPU structure.
3188 * @param cb RIP increment value in bytes.
3189 */
3190DECLINLINE(void) nemHcWinAdvanceRip(PVMCPUCC pVCpu, uint32_t cb)
3191{
3192 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
3193 pCtx->rip += cb;
3194
3195 /* Update interrupt shadow. */
3196 if ( VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS)
3197 && pCtx->rip != EMGetInhibitInterruptsPC(pVCpu))
3198 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
3199}
3200
3201
3202/**
3203 * Hacks its way around the lovely mesa driver's backdoor accesses.
3204 *
3205 * @sa hmR0VmxHandleMesaDrvGp
3206 * @sa hmR0SvmHandleMesaDrvGp
3207 */
3208static int nemHcWinHandleMesaDrvGp(PVMCPUCC pVCpu, PCPUMCTX pCtx)
3209{
3210 Assert(!(pCtx->fExtrn & (CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_GPRS_MASK)));
3211 RT_NOREF(pCtx);
3212
3213 /* For now we'll just skip the instruction. */
3214 nemHcWinAdvanceRip(pVCpu, 1);
3215 return VINF_SUCCESS;
3216}
3217
3218
3219/**
3220 * Checks if the \#GP'ing instruction is the mesa driver doing it's lovely
3221 * backdoor logging w/o checking what it is running inside.
3222 *
3223 * This recognizes an "IN EAX,DX" instruction executed in flat ring-3, with the
3224 * backdoor port and magic numbers loaded in registers.
3225 *
3226 * @returns true if it is, false if it isn't.
3227 * @sa hmR0VmxIsMesaDrvGp
3228 * @sa hmR0SvmIsMesaDrvGp
3229 */
3230DECLINLINE(bool) nemHcWinIsMesaDrvGp(PVMCPUCC pVCpu, PCPUMCTX pCtx, const uint8_t *pbInsn, uint32_t cbInsn)
3231{
3232 /* #GP(0) is already checked by caller. */
3233
3234 /* Check magic and port. */
3235 Assert(!(pCtx->fExtrn & (CPUMCTX_EXTRN_RDX | CPUMCTX_EXTRN_RAX)));
3236 if (pCtx->dx != UINT32_C(0x5658))
3237 return false;
3238 if (pCtx->rax != UINT32_C(0x564d5868))
3239 return false;
3240
3241 /* Flat ring-3 CS. */
3242 if (CPUMGetGuestCPL(pVCpu) != 3)
3243 return false;
3244 if (pCtx->cs.u64Base != 0)
3245 return false;
3246
3247 /* 0xed: IN eAX,dx */
3248 if (cbInsn < 1) /* Play safe (shouldn't happen). */
3249 {
3250 uint8_t abInstr[1];
3251 int rc = PGMPhysSimpleReadGCPtr(pVCpu, abInstr, pCtx->rip, sizeof(abInstr));
3252 if (RT_FAILURE(rc))
3253 return false;
3254 if (abInstr[0] != 0xed)
3255 return false;
3256 }
3257 else
3258 {
3259 if (pbInsn[0] != 0xed)
3260 return false;
3261 }
3262
3263 return true;
3264}
3265
3266
3267#ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
3268/**
3269 * Deals with exception intercept message (HvMessageTypeX64ExceptionIntercept).
3270 *
3271 * @returns Strict VBox status code.
3272 * @param pVCpu The cross context per CPU structure.
3273 * @param pMsg The message.
3274 * @sa nemR3WinHandleExitMsr
3275 */
3276NEM_TMPL_STATIC VBOXSTRICTRC
3277nemHCWinHandleMessageException(PVMCPUCC pVCpu, HV_X64_EXCEPTION_INTERCEPT_MESSAGE const *pMsg)
3278{
3279 /*
3280 * Assert sanity.
3281 */
3282 Assert( pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_READ
3283 || pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE
3284 || pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_EXECUTE);
3285 NEMWIN_ASSERT_MSG_REG_SEG( pVCpu, HvX64RegisterCs, pMsg->Header.CsSegment);
3286 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRip, pMsg->Header.Rip);
3287 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRflags, pMsg->Header.Rflags);
3288 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterCr8, (uint64_t)pMsg->Header.Cr8);
3289 NEMWIN_ASSERT_MSG_REG_SEG( pVCpu, HvX64RegisterDs, pMsg->DsSegment);
3290 NEMWIN_ASSERT_MSG_REG_SEG( pVCpu, HvX64RegisterSs, pMsg->SsSegment);
3291 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRax, pMsg->Rax);
3292 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRcx, pMsg->Rcx);
3293 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRdx, pMsg->Rdx);
3294 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRbx, pMsg->Rbx);
3295 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRsp, pMsg->Rsp);
3296 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRbp, pMsg->Rbp);
3297 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRsi, pMsg->Rsi);
3298 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRdi, pMsg->Rdi);
3299 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterR8, pMsg->R8);
3300 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterR9, pMsg->R9);
3301 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterR10, pMsg->R10);
3302 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterR11, pMsg->R11);
3303 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterR12, pMsg->R12);
3304 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterR13, pMsg->R13);
3305 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterR14, pMsg->R14);
3306 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterR15, pMsg->R15);
3307
3308 /*
3309 * Get most of the register state since we'll end up making IEM inject the
3310 * event. The exception isn't normally flaged as a pending event, so duh.
3311 *
3312 * Note! We can optimize this later with event injection.
3313 */
3314 Log4(("XcptExit/%u: %04x:%08RX64/%s: %x errcd=%#x parm=%RX64\n",
3315 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
3316 pMsg->ExceptionVector, pMsg->ErrorCode, pMsg->ExceptionParameter));
3317 nemHCWinCopyStateFromExceptionMessage(pVCpu, pMsg, true /*fClearXcpt*/);
3318 uint64_t fWhat = NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM;
3319 if (pMsg->ExceptionVector == X86_XCPT_DB)
3320 fWhat |= CPUMCTX_EXTRN_DR0_DR3 | CPUMCTX_EXTRN_DR7 | CPUMCTX_EXTRN_DR6;
3321 VBOXSTRICTRC rcStrict = nemHCWinImportStateIfNeededStrict(pVCpu, fWhat, "Xcpt");
3322 if (rcStrict != VINF_SUCCESS)
3323 return rcStrict;
3324
3325 /*
3326 * Handle the intercept.
3327 */
3328 TRPMEVENT enmEvtType = TRPM_TRAP;
3329 switch (pMsg->ExceptionVector)
3330 {
3331 /*
3332 * We get undefined opcodes on VMMCALL(AMD) & VMCALL(Intel) instructions
3333 * and need to turn them over to GIM.
3334 *
3335 * Note! We do not check fGIMTrapXcptUD here ASSUMING that GIM only wants
3336 * #UD for handling non-native hypercall instructions. (IEM will
3337 * decode both and let the GIM provider decide whether to accept it.)
3338 */
3339 case X86_XCPT_UD:
3340 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitExceptionUd);
3341 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_XCPT_UD),
3342 pMsg->Header.Rip + pMsg->Header.CsSegment.Base, ASMReadTSC());
3343
3344 if (nemHcWinIsInterestingUndefinedOpcode(pMsg->InstructionByteCount, pMsg->InstructionBytes,
3345 pMsg->Header.ExecutionState.EferLma && pMsg->Header.CsSegment.Long ))
3346 {
3347 rcStrict = IEMExecOneWithPrefetchedByPC(pVCpu, CPUMCTX2CORE(&pVCpu->cpum.GstCtx), pMsg->Header.Rip,
3348 pMsg->InstructionBytes, pMsg->InstructionByteCount);
3349 Log4(("XcptExit/%u: %04x:%08RX64/%s: #UD -> emulated -> %Rrc\n",
3350 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip,
3351 nemHCWinExecStateToLogStr(&pMsg->Header), VBOXSTRICTRC_VAL(rcStrict) ));
3352 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitExceptionUdHandled);
3353 return rcStrict;
3354 }
3355 Log4(("XcptExit/%u: %04x:%08RX64/%s: #UD [%.*Rhxs] -> re-injected\n", pVCpu->idCpu, pMsg->Header.CsSegment.Selector,
3356 pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header), pMsg->InstructionByteCount, pMsg->InstructionBytes ));
3357 break;
3358
3359 /*
3360 * Workaround the lovely mesa driver assuming that vmsvga means vmware
3361 * hypervisor and tries to log stuff to the host.
3362 */
3363 case X86_XCPT_GP:
3364 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitExceptionGp);
3365 /** @todo r=bird: Need workaround in IEM for this, right?
3366 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_XCPT_GP),
3367 pMsg->Header.Rip + pMsg->Header.CsSegment.Base, ASMReadTSC()); */
3368 if ( !pVCpu->hm.s.fTrapXcptGpForLovelyMesaDrv
3369 || !nemHcWinIsMesaDrvGp(pVCpu, &pVCpu->cpum.GstCtx, pMsg->InstructionBytes, pMsg->InstructionByteCount))
3370 {
3371# if 1 /** @todo Need to emulate instruction or we get a triple fault when trying to inject the #GP... */
3372 rcStrict = IEMExecOneWithPrefetchedByPC(pVCpu, CPUMCTX2CORE(&pVCpu->cpum.GstCtx), pMsg->Header.Rip,
3373 pMsg->InstructionBytes, pMsg->InstructionByteCount);
3374 Log4(("XcptExit/%u: %04x:%08RX64/%s: #GP -> emulated -> %Rrc\n",
3375 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip,
3376 nemHCWinExecStateToLogStr(&pMsg->Header), VBOXSTRICTRC_VAL(rcStrict) ));
3377 return rcStrict;
3378# else
3379 break;
3380# endif
3381 }
3382 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitExceptionGpMesa);
3383 return nemHcWinHandleMesaDrvGp(pVCpu, &pVCpu->cpum.GstCtx);
3384
3385 /*
3386 * Filter debug exceptions.
3387 */
3388 case X86_XCPT_DB:
3389 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitExceptionDb);
3390 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_XCPT_DB),
3391 pMsg->Header.Rip + pMsg->Header.CsSegment.Base, ASMReadTSC());
3392 Log4(("XcptExit/%u: %04x:%08RX64/%s: #DB - TODO\n",
3393 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header) ));
3394 break;
3395
3396 case X86_XCPT_BP:
3397 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitExceptionBp);
3398 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_XCPT_BP),
3399 pMsg->Header.Rip + pMsg->Header.CsSegment.Base, ASMReadTSC());
3400 Log4(("XcptExit/%u: %04x:%08RX64/%s: #BP - TODO - %u\n", pVCpu->idCpu, pMsg->Header.CsSegment.Selector,
3401 pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header), pMsg->Header.InstructionLength));
3402 enmEvtType = TRPM_SOFTWARE_INT; /* We're at the INT3 instruction, not after it. */
3403 break;
3404
3405 /* This shouldn't happen. */
3406 default:
3407 AssertLogRelMsgFailedReturn(("ExceptionVector=%#x\n", pMsg->ExceptionVector), VERR_IEM_IPE_6);
3408 }
3409
3410 /*
3411 * Inject it.
3412 */
3413 rcStrict = IEMInjectTrap(pVCpu, pMsg->ExceptionVector, enmEvtType, pMsg->ErrorCode,
3414 pMsg->ExceptionParameter /*??*/, pMsg->Header.InstructionLength);
3415 Log4(("XcptExit/%u: %04x:%08RX64/%s: %#u -> injected -> %Rrc\n",
3416 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip,
3417 nemHCWinExecStateToLogStr(&pMsg->Header), pMsg->ExceptionVector, VBOXSTRICTRC_VAL(rcStrict) ));
3418 return rcStrict;
3419}
3420#elif defined(IN_RING3)
3421/**
3422 * Deals with MSR access exits (WHvRunVpExitReasonException).
3423 *
3424 * @returns Strict VBox status code.
3425 * @param pVM The cross context VM structure.
3426 * @param pVCpu The cross context per CPU structure.
3427 * @param pExit The VM exit information to handle.
3428 * @sa nemR3WinHandleExitException
3429 */
3430NEM_TMPL_STATIC VBOXSTRICTRC nemR3WinHandleExitException(PVMCC pVM, PVMCPUCC pVCpu, WHV_RUN_VP_EXIT_CONTEXT const *pExit)
3431{
3432 /*
3433 * Get most of the register state since we'll end up making IEM inject the
3434 * event. The exception isn't normally flaged as a pending event, so duh.
3435 *
3436 * Note! We can optimize this later with event injection.
3437 */
3438 Log4(("XcptExit/%u: %04x:%08RX64/%s: %x errcd=%#x parm=%RX64\n", pVCpu->idCpu, pExit->VpContext.Cs.Selector,
3439 pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext), pExit->VpException.ExceptionType,
3440 pExit->VpException.ErrorCode, pExit->VpException.ExceptionParameter ));
3441 nemR3WinCopyStateFromExceptionMessage(pVCpu, pExit, true /*fClearXcpt*/);
3442 uint64_t fWhat = NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM;
3443 if (pExit->VpException.ExceptionType == X86_XCPT_DB)
3444 fWhat |= CPUMCTX_EXTRN_DR0_DR3 | CPUMCTX_EXTRN_DR7 | CPUMCTX_EXTRN_DR6;
3445 VBOXSTRICTRC rcStrict = nemHCWinImportStateIfNeededStrict(pVCpu, fWhat, "Xcpt");
3446 if (rcStrict != VINF_SUCCESS)
3447 return rcStrict;
3448
3449 /*
3450 * Handle the intercept.
3451 */
3452 TRPMEVENT enmEvtType = TRPM_TRAP;
3453 switch (pExit->VpException.ExceptionType)
3454 {
3455 /*
3456 * We get undefined opcodes on VMMCALL(AMD) & VMCALL(Intel) instructions
3457 * and need to turn them over to GIM.
3458 *
3459 * Note! We do not check fGIMTrapXcptUD here ASSUMING that GIM only wants
3460 * #UD for handling non-native hypercall instructions. (IEM will
3461 * decode both and let the GIM provider decide whether to accept it.)
3462 */
3463 case X86_XCPT_UD:
3464 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitExceptionUd);
3465 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_XCPT_UD),
3466 pExit->VpContext.Rip + pExit->VpContext.Cs.Base, ASMReadTSC());
3467 if (nemHcWinIsInterestingUndefinedOpcode(pExit->VpException.InstructionByteCount, pExit->VpException.InstructionBytes,
3468 pExit->VpContext.ExecutionState.EferLma && pExit->VpContext.Cs.Long ))
3469 {
3470 rcStrict = IEMExecOneWithPrefetchedByPC(pVCpu, CPUMCTX2CORE(&pVCpu->cpum.GstCtx), pExit->VpContext.Rip,
3471 pExit->VpException.InstructionBytes,
3472 pExit->VpException.InstructionByteCount);
3473 Log4(("XcptExit/%u: %04x:%08RX64/%s: #UD -> emulated -> %Rrc\n",
3474 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip,
3475 nemR3WinExecStateToLogStr(&pExit->VpContext), VBOXSTRICTRC_VAL(rcStrict) ));
3476 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitExceptionUdHandled);
3477 return rcStrict;
3478 }
3479
3480 Log4(("XcptExit/%u: %04x:%08RX64/%s: #UD [%.*Rhxs] -> re-injected\n", pVCpu->idCpu,
3481 pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
3482 pExit->VpException.InstructionByteCount, pExit->VpException.InstructionBytes ));
3483 break;
3484
3485 /*
3486 * Workaround the lovely mesa driver assuming that vmsvga means vmware
3487 * hypervisor and tries to log stuff to the host.
3488 */
3489 case X86_XCPT_GP:
3490 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitExceptionGp);
3491 /** @todo r=bird: Need workaround in IEM for this, right?
3492 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_XCPT_GP),
3493 pExit->VpContext.Rip + pExit->VpContext.Cs.Base, ASMReadTSC()); */
3494 if ( !pVCpu->nem.s.fTrapXcptGpForLovelyMesaDrv
3495 || !nemHcWinIsMesaDrvGp(pVCpu, &pVCpu->cpum.GstCtx, pExit->VpException.InstructionBytes,
3496 pExit->VpException.InstructionByteCount))
3497 {
3498# if 1 /** @todo Need to emulate instruction or we get a triple fault when trying to inject the #GP... */
3499 rcStrict = IEMExecOneWithPrefetchedByPC(pVCpu, CPUMCTX2CORE(&pVCpu->cpum.GstCtx), pExit->VpContext.Rip,
3500 pExit->VpException.InstructionBytes,
3501 pExit->VpException.InstructionByteCount);
3502 Log4(("XcptExit/%u: %04x:%08RX64/%s: #GP -> emulated -> %Rrc\n",
3503 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip,
3504 nemR3WinExecStateToLogStr(&pExit->VpContext), VBOXSTRICTRC_VAL(rcStrict) ));
3505 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitExceptionUdHandled);
3506 return rcStrict;
3507# else
3508 break;
3509# endif
3510 }
3511 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitExceptionGpMesa);
3512 return nemHcWinHandleMesaDrvGp(pVCpu, &pVCpu->cpum.GstCtx);
3513
3514 /*
3515 * Filter debug exceptions.
3516 */
3517 case X86_XCPT_DB:
3518 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitExceptionDb);
3519 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_XCPT_DB),
3520 pExit->VpContext.Rip + pExit->VpContext.Cs.Base, ASMReadTSC());
3521 Log4(("XcptExit/%u: %04x:%08RX64/%s: #DB - TODO\n",
3522 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext) ));
3523 break;
3524
3525 case X86_XCPT_BP:
3526 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitExceptionBp);
3527 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_XCPT_BP),
3528 pExit->VpContext.Rip + pExit->VpContext.Cs.Base, ASMReadTSC());
3529 Log4(("XcptExit/%u: %04x:%08RX64/%s: #BP - TODO - %u\n", pVCpu->idCpu, pExit->VpContext.Cs.Selector,
3530 pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext), pExit->VpContext.InstructionLength));
3531 enmEvtType = TRPM_SOFTWARE_INT; /* We're at the INT3 instruction, not after it. */
3532 break;
3533
3534 /* This shouldn't happen. */
3535 default:
3536 AssertLogRelMsgFailedReturn(("ExceptionType=%#x\n", pExit->VpException.ExceptionType), VERR_IEM_IPE_6);
3537 }
3538
3539 /*
3540 * Inject it.
3541 */
3542 rcStrict = IEMInjectTrap(pVCpu, pExit->VpException.ExceptionType, enmEvtType, pExit->VpException.ErrorCode,
3543 pExit->VpException.ExceptionParameter /*??*/, pExit->VpContext.InstructionLength);
3544 Log4(("XcptExit/%u: %04x:%08RX64/%s: %#u -> injected -> %Rrc\n",
3545 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip,
3546 nemR3WinExecStateToLogStr(&pExit->VpContext), pExit->VpException.ExceptionType, VBOXSTRICTRC_VAL(rcStrict) ));
3547
3548 RT_NOREF_PV(pVM);
3549 return rcStrict;
3550}
3551#endif /* IN_RING3 && !NEM_WIN_TEMPLATE_MODE_OWN_RUN_API */
3552
3553
3554#ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
3555/**
3556 * Deals with unrecoverable exception (triple fault).
3557 *
3558 * Seen WRMSR 0x201 (IA32_MTRR_PHYSMASK0) writes from grub / debian9 ending up
3559 * here too. So we'll leave it to IEM to decide.
3560 *
3561 * @returns Strict VBox status code.
3562 * @param pVCpu The cross context per CPU structure.
3563 * @param pMsgHdr The message header.
3564 * @sa nemR3WinHandleExitUnrecoverableException
3565 */
3566NEM_TMPL_STATIC VBOXSTRICTRC
3567nemHCWinHandleMessageUnrecoverableException(PVMCPUCC pVCpu, HV_X64_INTERCEPT_MESSAGE_HEADER const *pMsgHdr)
3568{
3569 /* Check message register value sanity. */
3570 NEMWIN_ASSERT_MSG_REG_SEG( pVCpu, HvX64RegisterCs, pMsgHdr->CsSegment);
3571 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRip, pMsgHdr->Rip);
3572 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRflags, pMsgHdr->Rflags);
3573 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterCr8, (uint64_t)pMsgHdr->Cr8);
3574
3575# if 0
3576 /*
3577 * Just copy the state we've got and handle it in the loop for now.
3578 */
3579 nemHCWinCopyStateFromX64Header(pVCpu, pMsgHdr);
3580 Log(("TripleExit/%u: %04x:%08RX64/%s: RFL=%#RX64 -> VINF_EM_TRIPLE_FAULT\n",
3581 pVCpu->idCpu, pMsgHdr->CsSegment.Selector, pMsgHdr->Rip, nemHCWinExecStateToLogStr(&pMsg->Header), pMsgHdr->Rflags));
3582 return VINF_EM_TRIPLE_FAULT;
3583# else
3584 /*
3585 * Let IEM decide whether this is really it.
3586 */
3587 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_UNRECOVERABLE_EXCEPTION),
3588 pMsgHdr->Rip + pMsgHdr->CsSegment.Base, ASMReadTSC());
3589 nemHCWinCopyStateFromX64Header(pVCpu, pMsgHdr);
3590 VBOXSTRICTRC rcStrict = nemHCWinImportStateIfNeededStrict(pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM | CPUMCTX_EXTRN_ALL, "TripleExit");
3591 if (rcStrict == VINF_SUCCESS)
3592 {
3593 rcStrict = IEMExecOne(pVCpu);
3594 if (rcStrict == VINF_SUCCESS)
3595 {
3596 Log(("UnrecovExit/%u: %04x:%08RX64/%s: RFL=%#RX64 -> VINF_SUCCESS\n", pVCpu->idCpu, pMsgHdr->CsSegment.Selector,
3597 pMsgHdr->Rip, nemHCWinExecStateToLogStr(pMsgHdr), pMsgHdr->Rflags ));
3598 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_NEM_WIN_EVENT_INJECT; /* Make sure to reset pending #DB(0). */
3599 return VINF_SUCCESS;
3600 }
3601 if (rcStrict == VINF_EM_TRIPLE_FAULT)
3602 Log(("UnrecovExit/%u: %04x:%08RX64/%s: RFL=%#RX64 -> VINF_EM_TRIPLE_FAULT!\n", pVCpu->idCpu, pMsgHdr->CsSegment.Selector,
3603 pMsgHdr->Rip, nemHCWinExecStateToLogStr(pMsgHdr), pMsgHdr->Rflags, VBOXSTRICTRC_VAL(rcStrict) ));
3604 else
3605 Log(("UnrecovExit/%u: %04x:%08RX64/%s: RFL=%#RX64 -> %Rrc (IEMExecOne)\n", pVCpu->idCpu, pMsgHdr->CsSegment.Selector,
3606 pMsgHdr->Rip, nemHCWinExecStateToLogStr(pMsgHdr), pMsgHdr->Rflags, VBOXSTRICTRC_VAL(rcStrict) ));
3607 }
3608 else
3609 Log(("UnrecovExit/%u: %04x:%08RX64/%s: RFL=%#RX64 -> %Rrc (state import)\n", pVCpu->idCpu, pMsgHdr->CsSegment.Selector,
3610 pMsgHdr->Rip, nemHCWinExecStateToLogStr(pMsgHdr), pMsgHdr->Rflags, VBOXSTRICTRC_VAL(rcStrict) ));
3611 return rcStrict;
3612# endif
3613}
3614#elif defined(IN_RING3)
3615/**
3616 * Deals with MSR access exits (WHvRunVpExitReasonUnrecoverableException).
3617 *
3618 * @returns Strict VBox status code.
3619 * @param pVM The cross context VM structure.
3620 * @param pVCpu The cross context per CPU structure.
3621 * @param pExit The VM exit information to handle.
3622 * @sa nemHCWinHandleMessageUnrecoverableException
3623 */
3624NEM_TMPL_STATIC VBOXSTRICTRC nemR3WinHandleExitUnrecoverableException(PVMCC pVM, PVMCPUCC pVCpu, WHV_RUN_VP_EXIT_CONTEXT const *pExit)
3625{
3626# if 0
3627 /*
3628 * Just copy the state we've got and handle it in the loop for now.
3629 */
3630 nemR3WinCopyStateFromX64Header(pVCpu, &pExit->VpContext);
3631 Log(("TripleExit/%u: %04x:%08RX64/%s: RFL=%#RX64 -> VINF_EM_TRIPLE_FAULT\n", pVCpu->idCpu, pExit->VpContext.Cs.Selector,
3632 pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext), pExit->VpContext.Rflags));
3633 RT_NOREF_PV(pVM);
3634 return VINF_EM_TRIPLE_FAULT;
3635# else
3636 /*
3637 * Let IEM decide whether this is really it.
3638 */
3639 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_UNRECOVERABLE_EXCEPTION),
3640 pExit->VpContext.Rip + pExit->VpContext.Cs.Base, ASMReadTSC());
3641 nemR3WinCopyStateFromX64Header(pVCpu, &pExit->VpContext);
3642 VBOXSTRICTRC rcStrict = nemHCWinImportStateIfNeededStrict(pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM | CPUMCTX_EXTRN_ALL, "TripleExit");
3643 if (rcStrict == VINF_SUCCESS)
3644 {
3645 rcStrict = IEMExecOne(pVCpu);
3646 if (rcStrict == VINF_SUCCESS)
3647 {
3648 Log(("UnrecovExit/%u: %04x:%08RX64/%s: RFL=%#RX64 -> VINF_SUCCESS\n", pVCpu->idCpu, pExit->VpContext.Cs.Selector,
3649 pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext), pExit->VpContext.Rflags));
3650 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_NEM_WIN_EVENT_INJECT; /* Make sure to reset pending #DB(0). */
3651 return VINF_SUCCESS;
3652 }
3653 if (rcStrict == VINF_EM_TRIPLE_FAULT)
3654 Log(("UnrecovExit/%u: %04x:%08RX64/%s: RFL=%#RX64 -> VINF_EM_TRIPLE_FAULT!\n", pVCpu->idCpu, pExit->VpContext.Cs.Selector,
3655 pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext), pExit->VpContext.Rflags, VBOXSTRICTRC_VAL(rcStrict) ));
3656 else
3657 Log(("UnrecovExit/%u: %04x:%08RX64/%s: RFL=%#RX64 -> %Rrc (IEMExecOne)\n", pVCpu->idCpu, pExit->VpContext.Cs.Selector,
3658 pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext), pExit->VpContext.Rflags, VBOXSTRICTRC_VAL(rcStrict) ));
3659 }
3660 else
3661 Log(("UnrecovExit/%u: %04x:%08RX64/%s: RFL=%#RX64 -> %Rrc (state import)\n", pVCpu->idCpu, pExit->VpContext.Cs.Selector,
3662 pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext), pExit->VpContext.Rflags, VBOXSTRICTRC_VAL(rcStrict) ));
3663 RT_NOREF_PV(pVM);
3664 return rcStrict;
3665# endif
3666
3667}
3668#endif /* IN_RING3 && !NEM_WIN_TEMPLATE_MODE_OWN_RUN_API */
3669
3670
3671#ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
3672/**
3673 * Handles messages (VM exits).
3674 *
3675 * @returns Strict VBox status code.
3676 * @param pVM The cross context VM structure.
3677 * @param pVCpu The cross context per CPU structure.
3678 * @param pMappingHeader The message slot mapping.
3679 * @sa nemR3WinHandleExit
3680 */
3681NEM_TMPL_STATIC VBOXSTRICTRC
3682nemHCWinHandleMessage(PVMCC pVM, PVMCPUCC pVCpu, VID_MESSAGE_MAPPING_HEADER volatile *pMappingHeader)
3683{
3684 if (pMappingHeader->enmVidMsgType == VidMessageHypervisorMessage)
3685 {
3686 AssertMsg(pMappingHeader->cbMessage == HV_MESSAGE_SIZE, ("%#x\n", pMappingHeader->cbMessage));
3687 HV_MESSAGE const *pMsg = (HV_MESSAGE const *)(pMappingHeader + 1);
3688 switch (pMsg->Header.MessageType)
3689 {
3690 case HvMessageTypeUnmappedGpa:
3691 Assert(pMsg->Header.PayloadSize == RT_UOFFSETOF(HV_X64_MEMORY_INTERCEPT_MESSAGE, DsSegment));
3692 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitMemUnmapped);
3693 return nemHCWinHandleMessageMemory(pVM, pVCpu, &pMsg->X64MemoryIntercept);
3694
3695 case HvMessageTypeGpaIntercept:
3696 Assert(pMsg->Header.PayloadSize == RT_UOFFSETOF(HV_X64_MEMORY_INTERCEPT_MESSAGE, DsSegment));
3697 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitMemIntercept);
3698 return nemHCWinHandleMessageMemory(pVM, pVCpu, &pMsg->X64MemoryIntercept);
3699
3700 case HvMessageTypeX64IoPortIntercept:
3701 Assert(pMsg->Header.PayloadSize == sizeof(pMsg->X64IoPortIntercept));
3702 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitPortIo);
3703 return nemHCWinHandleMessageIoPort(pVM, pVCpu, &pMsg->X64IoPortIntercept);
3704
3705 case HvMessageTypeX64Halt:
3706 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitHalt);
3707 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_HALT),
3708 pMsg->X64InterceptHeader.Rip + pMsg->X64InterceptHeader.CsSegment.Base, ASMReadTSC());
3709 Log4(("HaltExit\n"));
3710 return VINF_EM_HALT;
3711
3712 case HvMessageTypeX64InterruptWindow:
3713 Assert(pMsg->Header.PayloadSize == sizeof(pMsg->X64InterruptWindow));
3714 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitInterruptWindow);
3715 return nemHCWinHandleMessageInterruptWindow(pVM, pVCpu, &pMsg->X64InterruptWindow);
3716
3717 case HvMessageTypeX64CpuidIntercept:
3718 Assert(pMsg->Header.PayloadSize == sizeof(pMsg->X64CpuIdIntercept));
3719 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitCpuId);
3720 return nemHCWinHandleMessageCpuId(pVM, pVCpu, &pMsg->X64CpuIdIntercept);
3721
3722 case HvMessageTypeX64MsrIntercept:
3723 Assert(pMsg->Header.PayloadSize == sizeof(pMsg->X64MsrIntercept));
3724 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitMsr);
3725 return nemHCWinHandleMessageMsr(pVCpu, &pMsg->X64MsrIntercept);
3726
3727 case HvMessageTypeX64ExceptionIntercept:
3728 Assert(pMsg->Header.PayloadSize == sizeof(pMsg->X64ExceptionIntercept));
3729 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitException);
3730 return nemHCWinHandleMessageException(pVCpu, &pMsg->X64ExceptionIntercept);
3731
3732 case HvMessageTypeUnrecoverableException:
3733 Assert(pMsg->Header.PayloadSize == sizeof(pMsg->X64InterceptHeader));
3734 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitUnrecoverable);
3735 return nemHCWinHandleMessageUnrecoverableException(pVCpu, &pMsg->X64InterceptHeader);
3736
3737 case HvMessageTypeInvalidVpRegisterValue:
3738 case HvMessageTypeUnsupportedFeature:
3739 case HvMessageTypeTlbPageSizeMismatch:
3740 LogRel(("Unimplemented msg:\n%.*Rhxd\n", (int)sizeof(*pMsg), pMsg));
3741 AssertLogRelMsgFailedReturn(("Message type %#x not implemented!\n%.32Rhxd\n", pMsg->Header.MessageType, pMsg),
3742 VERR_NEM_IPE_3);
3743
3744 case HvMessageTypeX64ApicEoi:
3745 case HvMessageTypeX64LegacyFpError:
3746 case HvMessageTypeX64RegisterIntercept:
3747 case HvMessageTypeApicEoi:
3748 case HvMessageTypeFerrAsserted:
3749 case HvMessageTypeEventLogBufferComplete:
3750 case HvMessageTimerExpired:
3751 LogRel(("Unexpected msg:\n%.*Rhxd\n", (int)sizeof(*pMsg), pMsg));
3752 AssertLogRelMsgFailedReturn(("Unexpected message on CPU #%u: %#x\n", pVCpu->idCpu, pMsg->Header.MessageType),
3753 VERR_NEM_IPE_3);
3754
3755 default:
3756 LogRel(("Unknown msg:\n%.*Rhxd\n", (int)sizeof(*pMsg), pMsg));
3757 AssertLogRelMsgFailedReturn(("Unknown message on CPU #%u: %#x\n", pVCpu->idCpu, pMsg->Header.MessageType),
3758 VERR_NEM_IPE_3);
3759 }
3760 }
3761 else
3762 AssertLogRelMsgFailedReturn(("Unexpected VID message type on CPU #%u: %#x LB %u\n",
3763 pVCpu->idCpu, pMappingHeader->enmVidMsgType, pMappingHeader->cbMessage),
3764 VERR_NEM_IPE_4);
3765}
3766#elif defined(IN_RING3)
3767/**
3768 * Handles VM exits.
3769 *
3770 * @returns Strict VBox status code.
3771 * @param pVM The cross context VM structure.
3772 * @param pVCpu The cross context per CPU structure.
3773 * @param pExit The VM exit information to handle.
3774 * @sa nemHCWinHandleMessage
3775 */
3776NEM_TMPL_STATIC VBOXSTRICTRC nemR3WinHandleExit(PVMCC pVM, PVMCPUCC pVCpu, WHV_RUN_VP_EXIT_CONTEXT const *pExit)
3777{
3778 switch (pExit->ExitReason)
3779 {
3780 case WHvRunVpExitReasonMemoryAccess:
3781 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitMemUnmapped);
3782 return nemR3WinHandleExitMemory(pVM, pVCpu, pExit);
3783
3784 case WHvRunVpExitReasonX64IoPortAccess:
3785 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitPortIo);
3786 return nemR3WinHandleExitIoPort(pVM, pVCpu, pExit);
3787
3788 case WHvRunVpExitReasonX64Halt:
3789 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitHalt);
3790 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_HALT),
3791 pExit->VpContext.Rip + pExit->VpContext.Cs.Base, ASMReadTSC());
3792 Log4(("HaltExit/%u\n", pVCpu->idCpu));
3793 return VINF_EM_HALT;
3794
3795 case WHvRunVpExitReasonCanceled:
3796 Log4(("CanceledExit/%u\n", pVCpu->idCpu));
3797 return VINF_SUCCESS;
3798
3799 case WHvRunVpExitReasonX64InterruptWindow:
3800 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitInterruptWindow);
3801 return nemR3WinHandleExitInterruptWindow(pVM, pVCpu, pExit);
3802
3803 case WHvRunVpExitReasonX64Cpuid:
3804 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitCpuId);
3805 return nemR3WinHandleExitCpuId(pVM, pVCpu, pExit);
3806
3807 case WHvRunVpExitReasonX64MsrAccess:
3808 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitMsr);
3809 return nemR3WinHandleExitMsr(pVM, pVCpu, pExit);
3810
3811 case WHvRunVpExitReasonException:
3812 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitException);
3813 return nemR3WinHandleExitException(pVM, pVCpu, pExit);
3814
3815 case WHvRunVpExitReasonUnrecoverableException:
3816 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitUnrecoverable);
3817 return nemR3WinHandleExitUnrecoverableException(pVM, pVCpu, pExit);
3818
3819 case WHvRunVpExitReasonUnsupportedFeature:
3820 case WHvRunVpExitReasonInvalidVpRegisterValue:
3821 LogRel(("Unimplemented exit:\n%.*Rhxd\n", (int)sizeof(*pExit), pExit));
3822 AssertLogRelMsgFailedReturn(("Unexpected exit on CPU #%u: %#x\n%.32Rhxd\n",
3823 pVCpu->idCpu, pExit->ExitReason, pExit), VERR_NEM_IPE_3);
3824
3825 /* Undesired exits: */
3826 case WHvRunVpExitReasonNone:
3827 default:
3828 LogRel(("Unknown exit:\n%.*Rhxd\n", (int)sizeof(*pExit), pExit));
3829 AssertLogRelMsgFailedReturn(("Unknown exit on CPU #%u: %#x!\n", pVCpu->idCpu, pExit->ExitReason), VERR_NEM_IPE_3);
3830 }
3831}
3832#endif /* IN_RING3 && !NEM_WIN_TEMPLATE_MODE_OWN_RUN_API */
3833
3834
3835#ifdef IN_RING0
3836/**
3837 * Perform an I/O control operation on the partition handle (VID.SYS),
3838 * restarting on alert-like behaviour.
3839 *
3840 * @returns NT status code.
3841 * @param pGVM The ring-0 VM structure.
3842 * @param pGVCpu The global (ring-0) per CPU structure.
3843 * @param fFlags The wait flags.
3844 * @param cMillies The timeout in milliseconds
3845 */
3846static NTSTATUS nemR0NtPerformIoCtlMessageSlotHandleAndGetNext(PGVM pGVM, PGVMCPU pGVCpu, uint32_t fFlags, uint32_t cMillies)
3847{
3848 pGVCpu->nem.s.uIoCtlBuf.MsgSlotHandleAndGetNext.iCpu = pGVCpu->idCpu;
3849 pGVCpu->nem.s.uIoCtlBuf.MsgSlotHandleAndGetNext.fFlags = fFlags;
3850 pGVCpu->nem.s.uIoCtlBuf.MsgSlotHandleAndGetNext.cMillies = cMillies;
3851 NTSTATUS rcNt = nemR0NtPerformIoControl(pGVM, pGVCpu, pGVM->nemr0.s.IoCtlMessageSlotHandleAndGetNext.uFunction,
3852 &pGVCpu->nem.s.uIoCtlBuf.MsgSlotHandleAndGetNext,
3853 pGVM->nemr0.s.IoCtlMessageSlotHandleAndGetNext.cbInput,
3854 NULL, 0);
3855 if (rcNt == STATUS_SUCCESS)
3856 { /* likely */ }
3857 /*
3858 * Generally, if we get down here, we have been interrupted between ACK'ing
3859 * a message and waiting for the next due to a NtAlertThread call. So, we
3860 * should stop ACK'ing the previous message and get on waiting on the next.
3861 * See similar stuff in nemHCWinRunGC().
3862 */
3863 else if ( rcNt == STATUS_TIMEOUT
3864 || rcNt == STATUS_ALERTED /* just in case */
3865 || rcNt == STATUS_KERNEL_APC /* just in case */
3866 || rcNt == STATUS_USER_APC /* just in case */)
3867 {
3868 DBGFTRACE_CUSTOM(pGVCpu->CTX_SUFF(pVM), "IoCtlMessageSlotHandleAndGetNextRestart/1 %#x (f=%#x)", rcNt, fFlags);
3869 STAM_REL_COUNTER_INC(&pGVCpu->nem.s.StatStopCpuPendingAlerts);
3870 Assert(fFlags & VID_MSHAGN_F_GET_NEXT_MESSAGE);
3871
3872 pGVCpu->nem.s.uIoCtlBuf.MsgSlotHandleAndGetNext.iCpu = pGVCpu->idCpu;
3873 pGVCpu->nem.s.uIoCtlBuf.MsgSlotHandleAndGetNext.fFlags = fFlags & ~VID_MSHAGN_F_HANDLE_MESSAGE;
3874 pGVCpu->nem.s.uIoCtlBuf.MsgSlotHandleAndGetNext.cMillies = cMillies;
3875 rcNt = nemR0NtPerformIoControl(pGVM, pGVCpu, pGVM->nemr0.s.IoCtlMessageSlotHandleAndGetNext.uFunction,
3876 &pGVCpu->nem.s.uIoCtlBuf.MsgSlotHandleAndGetNext,
3877 pGVM->nemr0.s.IoCtlMessageSlotHandleAndGetNext.cbInput,
3878 NULL, 0);
3879 DBGFTRACE_CUSTOM(pGVM, "IoCtlMessageSlotHandleAndGetNextRestart/2 %#x", rcNt);
3880 }
3881 return rcNt;
3882}
3883#endif /* IN_RING0 */
3884
3885
3886#ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
3887/**
3888 * Worker for nemHCWinRunGC that stops the execution on the way out.
3889 *
3890 * The CPU was running the last time we checked, no there are no messages that
3891 * needs being marked handled/whatever. Caller checks this.
3892 *
3893 * @returns rcStrict on success, error status on failure.
3894 * @param pVM The cross context VM structure.
3895 * @param pVCpu The cross context per CPU structure.
3896 * @param rcStrict The nemHCWinRunGC return status. This is a little
3897 * bit unnecessary, except in internal error cases,
3898 * since we won't need to stop the CPU if we took an
3899 * exit.
3900 * @param pMappingHeader The message slot mapping.
3901 */
3902NEM_TMPL_STATIC VBOXSTRICTRC nemHCWinStopCpu(PVMCC pVM, PVMCPUCC pVCpu, VBOXSTRICTRC rcStrict,
3903 VID_MESSAGE_MAPPING_HEADER volatile *pMappingHeader)
3904{
3905# ifdef DBGFTRACE_ENABLED
3906 HV_MESSAGE const volatile *pMsgForTrace = (HV_MESSAGE const volatile *)(pMappingHeader + 1);
3907# endif
3908
3909 /*
3910 * Try stopping the processor. If we're lucky we manage to do this before it
3911 * does another VM exit.
3912 */
3913 DBGFTRACE_CUSTOM(pVM, "nemStop#0");
3914# ifdef IN_RING0
3915 pVCpu->nem.s.uIoCtlBuf.idCpu = pVCpu->idCpu;
3916 NTSTATUS rcNt = nemR0NtPerformIoControl(pVM, pVCpu, pVM->nemr0.s.IoCtlStopVirtualProcessor.uFunction,
3917 &pVCpu->nem.s.uIoCtlBuf.idCpu, sizeof(pVCpu->nem.s.uIoCtlBuf.idCpu),
3918 NULL, 0);
3919 if (NT_SUCCESS(rcNt))
3920 {
3921 DBGFTRACE_CUSTOM(pVM, "nemStop#0: okay (%#x)", rcNt);
3922 Log8(("nemHCWinStopCpu: Stopping CPU succeeded (cpu status %u)\n", nemHCWinCpuGetRunningStatus(pVCpu) ));
3923 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatStopCpuSuccess);
3924 return rcStrict;
3925 }
3926# else
3927 BOOL fRet = VidStopVirtualProcessor(pVM->nem.s.hPartitionDevice, pVCpu->idCpu);
3928 if (fRet)
3929 {
3930 DBGFTRACE_CUSTOM(pVM, "nemStop#0: okay");
3931 Log8(("nemHCWinStopCpu: Stopping CPU succeeded (cpu status %u)\n", nemHCWinCpuGetRunningStatus(pVCpu) ));
3932 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatStopCpuSuccess);
3933 return rcStrict;
3934 }
3935# endif
3936
3937 /*
3938 * Dang. The CPU stopped by itself and we got a couple of message to deal with.
3939 */
3940# ifdef IN_RING0
3941 DBGFTRACE_CUSTOM(pVM, "nemStop#0: pending (%#x)", rcNt);
3942 AssertLogRelMsgReturn(rcNt == ERROR_VID_STOP_PENDING, ("rcNt=%#x\n", rcNt),
3943 RT_SUCCESS(rcStrict) ? VERR_NEM_IPE_5 : rcStrict);
3944# else
3945 DWORD dwErr = RTNtLastErrorValue();
3946 DBGFTRACE_CUSTOM(pVM, "nemStop#0: pending (%#x)", dwErr);
3947 AssertLogRelMsgReturn(dwErr == ERROR_VID_STOP_PENDING, ("dwErr=%#u (%#x)\n", dwErr, dwErr),
3948 RT_SUCCESS(rcStrict) ? VERR_NEM_IPE_5 : rcStrict);
3949# endif
3950 Log8(("nemHCWinStopCpu: Stopping CPU #%u pending...\n", pVCpu->idCpu));
3951 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatStopCpuPending);
3952
3953 /*
3954 * First message: Exit or similar, sometimes VidMessageStopRequestComplete.
3955 * Note! We can safely ASSUME that rcStrict isn't an important information one.
3956 */
3957# ifdef IN_RING0
3958 rcNt = nemR0NtPerformIoCtlMessageSlotHandleAndGetNext(pVM, pVCpu, VID_MSHAGN_F_GET_NEXT_MESSAGE, 30000 /*ms*/);
3959 DBGFTRACE_CUSTOM(pVM, "nemStop#1: %#x / %#x %#x %#x", rcNt, pMappingHeader->enmVidMsgType, pMappingHeader->cbMessage,
3960 pMsgForTrace->Header.MessageType);
3961 AssertLogRelMsgReturn(rcNt == STATUS_SUCCESS,
3962 ("1st VidMessageSlotHandleAndGetNext after ERROR_VID_STOP_PENDING failed: %#x\n", rcNt),
3963 RT_SUCCESS(rcStrict) ? VERR_NEM_IPE_5 : rcStrict);
3964# else
3965 BOOL fWait = g_pfnVidMessageSlotHandleAndGetNext(pVM->nem.s.hPartitionDevice, pVCpu->idCpu,
3966 VID_MSHAGN_F_GET_NEXT_MESSAGE, 30000 /*ms*/);
3967 DBGFTRACE_CUSTOM(pVM, "nemStop#1: %d+%#x / %#x %#x %#x", fWait, RTNtLastErrorValue(), pMappingHeader->enmVidMsgType,
3968 pMappingHeader->cbMessage, pMsgForTrace->Header.MessageType);
3969 AssertLogRelMsgReturn(fWait, ("1st VidMessageSlotHandleAndGetNext after ERROR_VID_STOP_PENDING failed: %u\n", RTNtLastErrorValue()),
3970 RT_SUCCESS(rcStrict) ? VERR_NEM_IPE_5 : rcStrict);
3971# endif
3972
3973 VID_MESSAGE_TYPE enmVidMsgType = pMappingHeader->enmVidMsgType;
3974 if (enmVidMsgType != VidMessageStopRequestComplete)
3975 {
3976 VBOXSTRICTRC rcStrict2 = nemHCWinHandleMessage(pVM, pVCpu, pMappingHeader);
3977 if (rcStrict2 != VINF_SUCCESS && RT_SUCCESS(rcStrict))
3978 rcStrict = rcStrict2;
3979 DBGFTRACE_CUSTOM(pVM, "nemStop#1: handled %#x -> %d", pMsgForTrace->Header.MessageType, VBOXSTRICTRC_VAL(rcStrict));
3980
3981 /*
3982 * Mark it as handled and get the stop request completed message, then mark
3983 * that as handled too. CPU is back into fully stopped stated then.
3984 */
3985# ifdef IN_RING0
3986 rcNt = nemR0NtPerformIoCtlMessageSlotHandleAndGetNext(pVM, pVCpu,
3987 VID_MSHAGN_F_HANDLE_MESSAGE | VID_MSHAGN_F_GET_NEXT_MESSAGE,
3988 30000 /*ms*/);
3989 DBGFTRACE_CUSTOM(pVM, "nemStop#2: %#x / %#x %#x %#x", rcNt, pMappingHeader->enmVidMsgType, pMappingHeader->cbMessage,
3990 pMsgForTrace->Header.MessageType);
3991 AssertLogRelMsgReturn(rcNt == STATUS_SUCCESS,
3992 ("2nd VidMessageSlotHandleAndGetNext after ERROR_VID_STOP_PENDING failed: %#x\n", rcNt),
3993 RT_SUCCESS(rcStrict) ? VERR_NEM_IPE_5 : rcStrict);
3994# else
3995 fWait = g_pfnVidMessageSlotHandleAndGetNext(pVM->nem.s.hPartitionDevice, pVCpu->idCpu,
3996 VID_MSHAGN_F_HANDLE_MESSAGE | VID_MSHAGN_F_GET_NEXT_MESSAGE, 30000 /*ms*/);
3997 DBGFTRACE_CUSTOM(pVM, "nemStop#2: %d+%#x / %#x %#x %#x", fWait, RTNtLastErrorValue(), pMappingHeader->enmVidMsgType,
3998 pMappingHeader->cbMessage, pMsgForTrace->Header.MessageType);
3999 AssertLogRelMsgReturn(fWait, ("2nd VidMessageSlotHandleAndGetNext after ERROR_VID_STOP_PENDING failed: %u\n", RTNtLastErrorValue()),
4000 RT_SUCCESS(rcStrict) ? VERR_NEM_IPE_5 : rcStrict);
4001# endif
4002
4003 /* It should be a stop request completed message. */
4004 enmVidMsgType = pMappingHeader->enmVidMsgType;
4005 AssertLogRelMsgReturn(enmVidMsgType == VidMessageStopRequestComplete,
4006 ("Unexpected 2nd message following ERROR_VID_STOP_PENDING: %#x LB %#x\n",
4007 enmVidMsgType, pMappingHeader->cbMessage),
4008 RT_SUCCESS(rcStrict) ? VERR_NEM_IPE_5 : rcStrict);
4009
4010 /*
4011 * Mark the VidMessageStopRequestComplete message as handled.
4012 */
4013# ifdef IN_RING0
4014 rcNt = nemR0NtPerformIoCtlMessageSlotHandleAndGetNext(pVM, pVCpu, VID_MSHAGN_F_HANDLE_MESSAGE, 30000 /*ms*/);
4015 DBGFTRACE_CUSTOM(pVM, "nemStop#3: %#x / %#x %#x %#x", rcNt, pMappingHeader->enmVidMsgType,
4016 pMsgForTrace->Header.MessageType, pMappingHeader->cbMessage, pMsgForTrace->Header.MessageType);
4017 AssertLogRelMsgReturn(rcNt == STATUS_SUCCESS,
4018 ("3rd VidMessageSlotHandleAndGetNext after ERROR_VID_STOP_PENDING failed: %#x\n", rcNt),
4019 RT_SUCCESS(rcStrict) ? VERR_NEM_IPE_5 : rcStrict);
4020# else
4021 fWait = g_pfnVidMessageSlotHandleAndGetNext(pVM->nem.s.hPartitionDevice, pVCpu->idCpu, VID_MSHAGN_F_HANDLE_MESSAGE, 30000 /*ms*/);
4022 DBGFTRACE_CUSTOM(pVM, "nemStop#3: %d+%#x / %#x %#x %#x", fWait, RTNtLastErrorValue(), pMappingHeader->enmVidMsgType,
4023 pMsgForTrace->Header.MessageType, pMappingHeader->cbMessage, pMsgForTrace->Header.MessageType);
4024 AssertLogRelMsgReturn(fWait, ("3rd VidMessageSlotHandleAndGetNext after ERROR_VID_STOP_PENDING failed: %u\n", RTNtLastErrorValue()),
4025 RT_SUCCESS(rcStrict) ? VERR_NEM_IPE_5 : rcStrict);
4026# endif
4027 Log8(("nemHCWinStopCpu: Stopped the CPU (rcStrict=%Rrc)\n", VBOXSTRICTRC_VAL(rcStrict) ));
4028 }
4029 else
4030 {
4031 /** @todo I'm not so sure about this now... */
4032 DBGFTRACE_CUSTOM(pVM, "nemStop#9: %#x %#x %#x", pMappingHeader->enmVidMsgType,
4033 pMappingHeader->cbMessage, pMsgForTrace->Header.MessageType);
4034 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatStopCpuPendingOdd);
4035 Log8(("nemHCWinStopCpu: Stopped the CPU (rcStrict=%Rrc) - 1st VidMessageSlotHandleAndGetNext got VidMessageStopRequestComplete.\n",
4036 VBOXSTRICTRC_VAL(rcStrict) ));
4037 }
4038 return rcStrict;
4039}
4040#endif /* NEM_WIN_TEMPLATE_MODE_OWN_RUN_API */
4041
4042#if defined(NEM_WIN_TEMPLATE_MODE_OWN_RUN_API) || defined(IN_RING3)
4043
4044/**
4045 * Deals with pending interrupt related force flags, may inject interrupt.
4046 *
4047 * @returns VBox strict status code.
4048 * @param pVM The cross context VM structure.
4049 * @param pVCpu The cross context per CPU structure.
4050 * @param pfInterruptWindows Where to return interrupt window flags.
4051 */
4052NEM_TMPL_STATIC VBOXSTRICTRC nemHCWinHandleInterruptFF(PVMCC pVM, PVMCPUCC pVCpu, uint8_t *pfInterruptWindows)
4053{
4054 Assert(!TRPMHasTrap(pVCpu));
4055 RT_NOREF_PV(pVM);
4056
4057 /*
4058 * First update APIC. We ASSUME this won't need TPR/CR8.
4059 */
4060 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_UPDATE_APIC))
4061 {
4062 APICUpdatePendingInterrupts(pVCpu);
4063 if (!VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC
4064 | VMCPU_FF_INTERRUPT_NMI | VMCPU_FF_INTERRUPT_SMI))
4065 return VINF_SUCCESS;
4066 }
4067
4068 /*
4069 * We don't currently implement SMIs.
4070 */
4071 AssertReturn(!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INTERRUPT_SMI), VERR_NEM_IPE_0);
4072
4073 /*
4074 * Check if we've got the minimum of state required for deciding whether we
4075 * can inject interrupts and NMIs. If we don't have it, get all we might require
4076 * for injection via IEM.
4077 */
4078 bool const fPendingNmi = VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INTERRUPT_NMI);
4079 uint64_t fNeedExtrn = CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT | CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS
4080 | (fPendingNmi ? CPUMCTX_EXTRN_NEM_WIN_INHIBIT_NMI : 0);
4081 if (pVCpu->cpum.GstCtx.fExtrn & fNeedExtrn)
4082 {
4083 VBOXSTRICTRC rcStrict = nemHCWinImportStateIfNeededStrict(pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM_XCPT, "IntFF");
4084 if (rcStrict != VINF_SUCCESS)
4085 return rcStrict;
4086 }
4087 bool const fInhibitInterrupts = VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS)
4088 && EMGetInhibitInterruptsPC(pVCpu) == pVCpu->cpum.GstCtx.rip;
4089
4090 /*
4091 * NMI? Try deliver it first.
4092 */
4093 if (fPendingNmi)
4094 {
4095 if ( !fInhibitInterrupts
4096 && !VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_BLOCK_NMIS))
4097 {
4098 VBOXSTRICTRC rcStrict = nemHCWinImportStateIfNeededStrict(pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM_XCPT, "NMI");
4099 if (rcStrict == VINF_SUCCESS)
4100 {
4101 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INTERRUPT_NMI);
4102 rcStrict = IEMInjectTrap(pVCpu, X86_XCPT_NMI, TRPM_HARDWARE_INT, 0, 0, 0);
4103 Log8(("Injected NMI on %u (%d)\n", pVCpu->idCpu, VBOXSTRICTRC_VAL(rcStrict) ));
4104 }
4105 return rcStrict;
4106 }
4107 *pfInterruptWindows |= NEM_WIN_INTW_F_NMI;
4108 Log8(("NMI window pending on %u\n", pVCpu->idCpu));
4109 }
4110
4111 /*
4112 * APIC or PIC interrupt?
4113 */
4114 if (VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC))
4115 {
4116 if ( !fInhibitInterrupts
4117 && pVCpu->cpum.GstCtx.rflags.Bits.u1IF)
4118 {
4119 AssertCompile(NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM_XCPT & CPUMCTX_EXTRN_APIC_TPR);
4120 VBOXSTRICTRC rcStrict = nemHCWinImportStateIfNeededStrict(pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM_XCPT, "NMI");
4121 if (rcStrict == VINF_SUCCESS)
4122 {
4123 uint8_t bInterrupt;
4124 int rc = PDMGetInterrupt(pVCpu, &bInterrupt);
4125 if (RT_SUCCESS(rc))
4126 {
4127 rcStrict = IEMInjectTrap(pVCpu, bInterrupt, TRPM_HARDWARE_INT, 0, 0, 0);
4128 Log8(("Injected interrupt %#x on %u (%d)\n", bInterrupt, pVCpu->idCpu, VBOXSTRICTRC_VAL(rcStrict) ));
4129 }
4130 else if (rc == VERR_APIC_INTR_MASKED_BY_TPR)
4131 {
4132 *pfInterruptWindows |= ((bInterrupt >> 4) << NEM_WIN_INTW_F_PRIO_SHIFT) | NEM_WIN_INTW_F_REGULAR;
4133 Log8(("VERR_APIC_INTR_MASKED_BY_TPR: *pfInterruptWindows=%#x\n", *pfInterruptWindows));
4134 }
4135 else
4136 Log8(("PDMGetInterrupt failed -> %d\n", rc));
4137 }
4138 return rcStrict;
4139 }
4140 else if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INTERRUPT_APIC) && !VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INTERRUPT_PIC))
4141 {
4142 /* If only an APIC interrupt is pending, we need to know its priority. Otherwise we'll
4143 * likely get pointless deliverability notifications with IF=1 but TPR still too high.
4144 */
4145 bool fPendingIntr;
4146 uint8_t u8Tpr, u8PendingIntr;
4147 int rc = APICGetTpr(pVCpu, &u8Tpr, &fPendingIntr, &u8PendingIntr);
4148 AssertRC(rc);
4149 *pfInterruptWindows |= (u8PendingIntr >> 4) << NEM_WIN_INTW_F_PRIO_SHIFT;
4150 }
4151 *pfInterruptWindows |= NEM_WIN_INTW_F_REGULAR;
4152 Log8(("Interrupt window pending on %u\n", pVCpu->idCpu));
4153 }
4154
4155 return VINF_SUCCESS;
4156}
4157
4158
4159/**
4160 * Inner NEM runloop for windows.
4161 *
4162 * @returns Strict VBox status code.
4163 * @param pVM The cross context VM structure.
4164 * @param pVCpu The cross context per CPU structure.
4165 */
4166NEM_TMPL_STATIC VBOXSTRICTRC nemHCWinRunGC(PVMCC pVM, PVMCPUCC pVCpu)
4167{
4168 LogFlow(("NEM/%u: %04x:%08RX64 efl=%#08RX64 <=\n", pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, pVCpu->cpum.GstCtx.rflags));
4169# ifdef LOG_ENABLED
4170 if (LogIs3Enabled())
4171 nemHCWinLogState(pVM, pVCpu);
4172# endif
4173
4174 /*
4175 * Try switch to NEM runloop state.
4176 */
4177 if (VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC_NEM, VMCPUSTATE_STARTED))
4178 { /* likely */ }
4179 else
4180 {
4181 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC_NEM, VMCPUSTATE_STARTED_EXEC_NEM_CANCELED);
4182 LogFlow(("NEM/%u: returning immediately because canceled\n", pVCpu->idCpu));
4183 return VINF_SUCCESS;
4184 }
4185
4186 /*
4187 * The run loop.
4188 *
4189 * Current approach to state updating to use the sledgehammer and sync
4190 * everything every time. This will be optimized later.
4191 */
4192# ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
4193 VID_MESSAGE_MAPPING_HEADER volatile *pMappingHeader = (VID_MESSAGE_MAPPING_HEADER volatile *)pVCpu->nem.s.pvMsgSlotMapping;
4194# endif
4195 const bool fSingleStepping = DBGFIsStepping(pVCpu);
4196// const uint32_t fCheckVmFFs = !fSingleStepping ? VM_FF_HP_R0_PRE_HM_MASK
4197// : VM_FF_HP_R0_PRE_HM_STEP_MASK;
4198// const uint32_t fCheckCpuFFs = !fSingleStepping ? VMCPU_FF_HP_R0_PRE_HM_MASK : VMCPU_FF_HP_R0_PRE_HM_STEP_MASK;
4199 VBOXSTRICTRC rcStrict = VINF_SUCCESS;
4200 for (unsigned iLoop = 0;; iLoop++)
4201 {
4202# ifndef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
4203 /*
4204 * Hack alert!
4205 */
4206 uint32_t const cMappedPages = pVM->nem.s.cMappedPages;
4207 if (cMappedPages >= 4000)
4208 {
4209 PGMPhysNemEnumPagesByState(pVM, pVCpu, NEM_WIN_PAGE_STATE_READABLE, nemHCWinUnmapOnePageCallback, NULL);
4210 Log(("nemHCWinRunGC: Unmapped all; cMappedPages=%u -> %u\n", cMappedPages, pVM->nem.s.cMappedPages));
4211 }
4212# endif
4213
4214 /*
4215 * Pending interrupts or such? Need to check and deal with this prior
4216 * to the state syncing.
4217 */
4218 pVCpu->nem.s.fDesiredInterruptWindows = 0;
4219 if (VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_UPDATE_APIC | VMCPU_FF_INTERRUPT_PIC
4220 | VMCPU_FF_INTERRUPT_NMI | VMCPU_FF_INTERRUPT_SMI))
4221 {
4222# ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
4223 /* Make sure the CPU isn't executing. */
4224 if (pVCpu->nem.s.fHandleAndGetFlags == VID_MSHAGN_F_GET_NEXT_MESSAGE)
4225 {
4226 pVCpu->nem.s.fHandleAndGetFlags = 0;
4227 rcStrict = nemHCWinStopCpu(pVM, pVCpu, rcStrict, pMappingHeader);
4228 if (rcStrict == VINF_SUCCESS)
4229 { /* likely */ }
4230 else
4231 {
4232 LogFlow(("NEM/%u: breaking: nemHCWinStopCpu -> %Rrc\n", pVCpu->idCpu, VBOXSTRICTRC_VAL(rcStrict) ));
4233 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatBreakOnStatus);
4234 break;
4235 }
4236 }
4237# endif
4238
4239 /* Try inject interrupt. */
4240 rcStrict = nemHCWinHandleInterruptFF(pVM, pVCpu, &pVCpu->nem.s.fDesiredInterruptWindows);
4241 if (rcStrict == VINF_SUCCESS)
4242 { /* likely */ }
4243 else
4244 {
4245 LogFlow(("NEM/%u: breaking: nemHCWinHandleInterruptFF -> %Rrc\n", pVCpu->idCpu, VBOXSTRICTRC_VAL(rcStrict) ));
4246 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatBreakOnStatus);
4247 break;
4248 }
4249 }
4250
4251 /*
4252 * Ensure that hyper-V has the whole state.
4253 * (We always update the interrupt windows settings when active as hyper-V seems
4254 * to forget about it after an exit.)
4255 */
4256 if ( (pVCpu->cpum.GstCtx.fExtrn & (CPUMCTX_EXTRN_ALL | CPUMCTX_EXTRN_NEM_WIN_MASK))
4257 != (CPUMCTX_EXTRN_ALL | CPUMCTX_EXTRN_NEM_WIN_MASK)
4258 || ( ( pVCpu->nem.s.fDesiredInterruptWindows
4259 || pVCpu->nem.s.fCurrentInterruptWindows != pVCpu->nem.s.fDesiredInterruptWindows)
4260# ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
4261 && pVCpu->nem.s.fHandleAndGetFlags != VID_MSHAGN_F_GET_NEXT_MESSAGE /* not running */
4262# endif
4263 )
4264 )
4265 {
4266# ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
4267 AssertMsg(pVCpu->nem.s.fHandleAndGetFlags != VID_MSHAGN_F_GET_NEXT_MESSAGE /* not running */,
4268 ("%#x fExtrn=%#RX64 (%#RX64) fDesiredInterruptWindows=%d fCurrentInterruptWindows=%#x vs %#x\n",
4269 pVCpu->nem.s.fHandleAndGetFlags, pVCpu->cpum.GstCtx.fExtrn, ~pVCpu->cpum.GstCtx.fExtrn & (CPUMCTX_EXTRN_ALL | CPUMCTX_EXTRN_NEM_WIN_MASK),
4270 pVCpu->nem.s.fDesiredInterruptWindows, pVCpu->nem.s.fCurrentInterruptWindows, pVCpu->nem.s.fDesiredInterruptWindows));
4271# endif
4272# ifdef IN_RING0
4273 int rc2 = nemR0WinExportState(pVM, pVCpu, &pVCpu->cpum.GstCtx);
4274# else
4275 int rc2 = nemHCWinCopyStateToHyperV(pVM, pVCpu);
4276# endif
4277 AssertRCReturn(rc2, rc2);
4278 }
4279
4280 /*
4281 * Poll timers and run for a bit.
4282 *
4283 * With the VID approach (ring-0 or ring-3) we can specify a timeout here,
4284 * so we take the time of the next timer event and uses that as a deadline.
4285 * The rounding heuristics are "tuned" so that rhel5 (1K timer) will boot fine.
4286 */
4287 /** @todo See if we cannot optimize this TMTimerPollGIP by only redoing
4288 * the whole polling job when timers have changed... */
4289 uint64_t offDeltaIgnored;
4290 uint64_t const nsNextTimerEvt = TMTimerPollGIP(pVM, pVCpu, &offDeltaIgnored); NOREF(nsNextTimerEvt);
4291 if ( !VM_FF_IS_ANY_SET(pVM, VM_FF_EMT_RENDEZVOUS | VM_FF_TM_VIRTUAL_SYNC)
4292 && !VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
4293 {
4294# ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
4295 if (pVCpu->nem.s.fHandleAndGetFlags)
4296 { /* Very likely that the CPU does NOT need starting (pending msg, running). */ }
4297 else
4298 {
4299# ifdef IN_RING0
4300 pVCpu->nem.s.uIoCtlBuf.idCpu = pVCpu->idCpu;
4301 NTSTATUS rcNt = nemR0NtPerformIoControl(pVM, pVCpu, pVM->nemr0.s.IoCtlStartVirtualProcessor.uFunction,
4302 &pVCpu->nem.s.uIoCtlBuf.idCpu, sizeof(pVCpu->nem.s.uIoCtlBuf.idCpu),
4303 NULL, 0);
4304 LogFlow(("NEM/%u: IoCtlStartVirtualProcessor -> %#x\n", pVCpu->idCpu, rcNt));
4305 AssertLogRelMsgReturn(NT_SUCCESS(rcNt), ("VidStartVirtualProcessor failed for CPU #%u: %#x\n", pVCpu->idCpu, rcNt),
4306 VERR_NEM_IPE_5);
4307# else
4308 AssertLogRelMsgReturn(g_pfnVidStartVirtualProcessor(pVM->nem.s.hPartitionDevice, pVCpu->idCpu),
4309 ("VidStartVirtualProcessor failed for CPU #%u: %u (%#x, rcNt=%#x)\n",
4310 pVCpu->idCpu, RTNtLastErrorValue(), RTNtLastErrorValue(), RTNtLastStatusValue()),
4311 VERR_NEM_IPE_5);
4312# endif
4313 pVCpu->nem.s.fHandleAndGetFlags = VID_MSHAGN_F_GET_NEXT_MESSAGE;
4314 }
4315# endif /* NEM_WIN_TEMPLATE_MODE_OWN_RUN_API */
4316
4317 if (VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC_NEM_WAIT, VMCPUSTATE_STARTED_EXEC_NEM))
4318 {
4319# ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
4320 uint64_t const nsNow = RTTimeNanoTS();
4321 int64_t const cNsNextTimerEvt = nsNow - nsNextTimerEvt;
4322 uint32_t cMsWait;
4323 if (cNsNextTimerEvt < 100000 /* ns */)
4324 cMsWait = 0;
4325 else if ((uint64_t)cNsNextTimerEvt < RT_NS_1SEC)
4326 {
4327 if ((uint32_t)cNsNextTimerEvt < 2*RT_NS_1MS)
4328 cMsWait = 1;
4329 else
4330 cMsWait = ((uint32_t)cNsNextTimerEvt - 100000 /*ns*/) / RT_NS_1MS;
4331 }
4332 else
4333 cMsWait = RT_MS_1SEC;
4334# ifdef IN_RING0
4335 pVCpu->nem.s.uIoCtlBuf.MsgSlotHandleAndGetNext.iCpu = pVCpu->idCpu;
4336 pVCpu->nem.s.uIoCtlBuf.MsgSlotHandleAndGetNext.fFlags = pVCpu->nem.s.fHandleAndGetFlags;
4337 pVCpu->nem.s.uIoCtlBuf.MsgSlotHandleAndGetNext.cMillies = cMsWait;
4338 NTSTATUS rcNt = nemR0NtPerformIoControl(pVM, pVCpu, pVM->nemr0.s.IoCtlMessageSlotHandleAndGetNext.uFunction,
4339 &pVCpu->nem.s.uIoCtlBuf.MsgSlotHandleAndGetNext,
4340 pVM->nemr0.s.IoCtlMessageSlotHandleAndGetNext.cbInput,
4341 NULL, 0);
4342 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC_NEM, VMCPUSTATE_STARTED_EXEC_NEM_WAIT);
4343 if (rcNt == STATUS_SUCCESS)
4344# else
4345 BOOL fRet = VidMessageSlotHandleAndGetNext(pVM->nem.s.hPartitionDevice, pVCpu->idCpu,
4346 pVCpu->nem.s.fHandleAndGetFlags, cMsWait);
4347 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC_NEM, VMCPUSTATE_STARTED_EXEC_NEM_WAIT);
4348 if (fRet)
4349# endif
4350# else
4351 WHV_RUN_VP_EXIT_CONTEXT ExitReason;
4352 RT_ZERO(ExitReason);
4353 LogFlow(("NEM/%u: Entry @ %04X:%08RX64 IF=%d (~~may be stale~~)\n", pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, pVCpu->cpum.GstCtx.rflags.Bits.u1IF));
4354 TMNotifyStartOfExecution(pVM, pVCpu);
4355 HRESULT hrc = WHvRunVirtualProcessor(pVM->nem.s.hPartition, pVCpu->idCpu, &ExitReason, sizeof(ExitReason));
4356 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC_NEM, VMCPUSTATE_STARTED_EXEC_NEM_WAIT);
4357 TMNotifyEndOfExecution(pVM, pVCpu, ASMReadTSC());
4358 LogFlow(("NEM/%u: Exit @ %04X:%08RX64 IF=%d CR8=%#x \n", pVCpu->idCpu, ExitReason.VpContext.Cs.Selector, ExitReason.VpContext.Rip, RT_BOOL(ExitReason.VpContext.Rflags & X86_EFL_IF), ExitReason.VpContext.Cr8));
4359 if (SUCCEEDED(hrc))
4360# endif
4361 {
4362 /*
4363 * Deal with the message.
4364 */
4365# ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
4366 rcStrict = nemHCWinHandleMessage(pVM, pVCpu, pMappingHeader);
4367 pVCpu->nem.s.fHandleAndGetFlags |= VID_MSHAGN_F_HANDLE_MESSAGE;
4368# else
4369 rcStrict = nemR3WinHandleExit(pVM, pVCpu, &ExitReason);
4370# endif
4371 if (rcStrict == VINF_SUCCESS)
4372 { /* hopefully likely */ }
4373 else
4374 {
4375 LogFlow(("NEM/%u: breaking: nemHCWinHandleMessage -> %Rrc\n", pVCpu->idCpu, VBOXSTRICTRC_VAL(rcStrict) ));
4376 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatBreakOnStatus);
4377 break;
4378 }
4379 }
4380 else
4381 {
4382# ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
4383
4384 /* VID.SYS merges STATUS_ALERTED and STATUS_USER_APC into STATUS_TIMEOUT,
4385 so after NtAlertThread we end up here with a STATUS_TIMEOUT. And yeah,
4386 the error code conversion is into WAIT_XXX, i.e. NT status codes. */
4387# ifndef IN_RING0
4388 DWORD rcNt = GetLastError();
4389# endif
4390 LogFlow(("NEM/%u: VidMessageSlotHandleAndGetNext -> %#x\n", pVCpu->idCpu, rcNt));
4391 AssertLogRelMsgReturn( rcNt == STATUS_TIMEOUT
4392 || rcNt == STATUS_ALERTED /* just in case */
4393 || rcNt == STATUS_USER_APC /* ditto */
4394 || rcNt == STATUS_KERNEL_APC /* ditto */
4395 , ("VidMessageSlotHandleAndGetNext failed for CPU #%u: %#x (%u)\n",
4396 pVCpu->idCpu, rcNt, rcNt),
4397 VERR_NEM_IPE_0);
4398 pVCpu->nem.s.fHandleAndGetFlags = VID_MSHAGN_F_GET_NEXT_MESSAGE;
4399 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatGetMsgTimeout);
4400# else
4401 AssertLogRelMsgFailedReturn(("WHvRunVirtualProcessor failed for CPU #%u: %#x (%u)\n",
4402 pVCpu->idCpu, hrc, GetLastError()),
4403 VERR_NEM_IPE_0);
4404# endif
4405 }
4406
4407 /*
4408 * If no relevant FFs are pending, loop.
4409 */
4410 if ( !VM_FF_IS_ANY_SET( pVM, !fSingleStepping ? VM_FF_HP_R0_PRE_HM_MASK : VM_FF_HP_R0_PRE_HM_STEP_MASK)
4411 && !VMCPU_FF_IS_ANY_SET(pVCpu, !fSingleStepping ? VMCPU_FF_HP_R0_PRE_HM_MASK : VMCPU_FF_HP_R0_PRE_HM_STEP_MASK) )
4412 continue;
4413
4414 /** @todo Try handle pending flags, not just return to EM loops. Take care
4415 * not to set important RCs here unless we've handled a message. */
4416 LogFlow(("NEM/%u: breaking: pending FF (%#x / %#RX64)\n",
4417 pVCpu->idCpu, pVM->fGlobalForcedActions, (uint64_t)pVCpu->fLocalForcedActions));
4418 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatBreakOnFFPost);
4419 }
4420 else
4421 {
4422 LogFlow(("NEM/%u: breaking: canceled %d (pre exec)\n", pVCpu->idCpu, VMCPU_GET_STATE(pVCpu) ));
4423 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatBreakOnCancel);
4424 }
4425 }
4426 else
4427 {
4428 LogFlow(("NEM/%u: breaking: pending FF (pre exec)\n", pVCpu->idCpu));
4429 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatBreakOnFFPre);
4430 }
4431 break;
4432 } /* the run loop */
4433
4434
4435 /*
4436 * If the CPU is running, make sure to stop it before we try sync back the
4437 * state and return to EM. We don't sync back the whole state if we can help it.
4438 */
4439# ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
4440 if (pVCpu->nem.s.fHandleAndGetFlags == VID_MSHAGN_F_GET_NEXT_MESSAGE)
4441 {
4442 pVCpu->nem.s.fHandleAndGetFlags = 0;
4443 rcStrict = nemHCWinStopCpu(pVM, pVCpu, rcStrict, pMappingHeader);
4444 }
4445# endif
4446
4447 if (!VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED, VMCPUSTATE_STARTED_EXEC_NEM))
4448 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED, VMCPUSTATE_STARTED_EXEC_NEM_CANCELED);
4449
4450 if (pVCpu->cpum.GstCtx.fExtrn & (CPUMCTX_EXTRN_ALL | (CPUMCTX_EXTRN_NEM_WIN_MASK & ~CPUMCTX_EXTRN_NEM_WIN_EVENT_INJECT)))
4451 {
4452 /* Try anticipate what we might need. */
4453 uint64_t fImport = IEM_CPUMCTX_EXTRN_MUST_MASK | CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT | CPUMCTX_EXTRN_NEM_WIN_INHIBIT_NMI;
4454 if ( (rcStrict >= VINF_EM_FIRST && rcStrict <= VINF_EM_LAST)
4455 || RT_FAILURE(rcStrict))
4456 fImport = CPUMCTX_EXTRN_ALL | (CPUMCTX_EXTRN_NEM_WIN_MASK & ~CPUMCTX_EXTRN_NEM_WIN_EVENT_INJECT);
4457# ifdef IN_RING0 /* Ring-3 I/O port access optimizations: */
4458 else if ( rcStrict == VINF_IOM_R3_IOPORT_COMMIT_WRITE
4459 || rcStrict == VINF_EM_PENDING_R3_IOPORT_WRITE)
4460 fImport = CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT;
4461 else if (rcStrict == VINF_EM_PENDING_R3_IOPORT_READ)
4462 fImport = CPUMCTX_EXTRN_RAX | CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT;
4463# endif
4464 else if (VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_INTERRUPT_PIC | VMCPU_FF_INTERRUPT_APIC
4465 | VMCPU_FF_INTERRUPT_NMI | VMCPU_FF_INTERRUPT_SMI))
4466 fImport |= IEM_CPUMCTX_EXTRN_XCPT_MASK;
4467
4468 if (pVCpu->cpum.GstCtx.fExtrn & fImport)
4469 {
4470# ifdef IN_RING0
4471 int rc2 = nemR0WinImportState(pVM, pVCpu, &pVCpu->cpum.GstCtx, fImport | CPUMCTX_EXTRN_NEM_WIN_EVENT_INJECT,
4472 true /*fCanUpdateCr3*/);
4473 if (RT_SUCCESS(rc2))
4474 pVCpu->cpum.GstCtx.fExtrn &= ~fImport;
4475 else if (rc2 == VERR_NEM_FLUSH_TLB)
4476 {
4477 pVCpu->cpum.GstCtx.fExtrn &= ~fImport;
4478 if (rcStrict == VINF_SUCCESS || rcStrict == -rc2)
4479 rcStrict = -rc2;
4480 else
4481 {
4482 pVCpu->nem.s.rcPending = -rc2;
4483 LogFlow(("NEM/%u: rcPending=%Rrc (rcStrict=%Rrc)\n", pVCpu->idCpu, rc2, VBOXSTRICTRC_VAL(rcStrict) ));
4484 }
4485 }
4486# else
4487 int rc2 = nemHCWinCopyStateFromHyperV(pVM, pVCpu, fImport | CPUMCTX_EXTRN_NEM_WIN_EVENT_INJECT);
4488 if (RT_SUCCESS(rc2))
4489 pVCpu->cpum.GstCtx.fExtrn &= ~fImport;
4490# endif
4491 else if (RT_SUCCESS(rcStrict))
4492 rcStrict = rc2;
4493 if (!(pVCpu->cpum.GstCtx.fExtrn & (CPUMCTX_EXTRN_ALL | (CPUMCTX_EXTRN_NEM_WIN_MASK & ~CPUMCTX_EXTRN_NEM_WIN_EVENT_INJECT))))
4494 pVCpu->cpum.GstCtx.fExtrn = 0;
4495 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatImportOnReturn);
4496 }
4497 else
4498 {
4499 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatImportOnReturnSkipped);
4500 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_NEM_WIN_EVENT_INJECT;
4501 }
4502 }
4503 else
4504 {
4505 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatImportOnReturnSkipped);
4506 pVCpu->cpum.GstCtx.fExtrn = 0;
4507 }
4508
4509 LogFlow(("NEM/%u: %04x:%08RX64 efl=%#08RX64 => %Rrc\n",
4510 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, pVCpu->cpum.GstCtx.rflags, VBOXSTRICTRC_VAL(rcStrict) ));
4511 return rcStrict;
4512}
4513
4514#endif /* defined(NEM_WIN_TEMPLATE_MODE_OWN_RUN_API) || defined(IN_RING3) */
4515
4516/**
4517 * @callback_method_impl{FNPGMPHYSNEMCHECKPAGE}
4518 */
4519NEM_TMPL_STATIC DECLCALLBACK(int) nemHCWinUnsetForA20CheckerCallback(PVMCC pVM, PVMCPUCC pVCpu, RTGCPHYS GCPhys,
4520 PPGMPHYSNEMPAGEINFO pInfo, void *pvUser)
4521{
4522 /* We'll just unmap the memory. */
4523 if (pInfo->u2NemState > NEM_WIN_PAGE_STATE_UNMAPPED)
4524 {
4525#ifdef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
4526 int rc = nemHCWinHypercallUnmapPage(pVM, pVCpu, GCPhys);
4527 AssertRC(rc);
4528 if (RT_SUCCESS(rc))
4529#else
4530 HRESULT hrc = WHvUnmapGpaRange(pVM->nem.s.hPartition, GCPhys, X86_PAGE_SIZE);
4531 if (SUCCEEDED(hrc))
4532#endif
4533 {
4534 uint32_t cMappedPages = ASMAtomicDecU32(&pVM->nem.s.cMappedPages); NOREF(cMappedPages);
4535 Log5(("NEM GPA unmapped/A20: %RGp (was %s, cMappedPages=%u)\n", GCPhys, g_apszPageStates[pInfo->u2NemState], cMappedPages));
4536 pInfo->u2NemState = NEM_WIN_PAGE_STATE_UNMAPPED;
4537 }
4538 else
4539 {
4540#ifdef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
4541 LogRel(("nemHCWinUnsetForA20CheckerCallback/unmap: GCPhys=%RGp rc=%Rrc\n", GCPhys, rc));
4542 return rc;
4543#else
4544 LogRel(("nemHCWinUnsetForA20CheckerCallback/unmap: GCPhys=%RGp hrc=%Rhrc (%#x) Last=%#x/%u\n",
4545 GCPhys, hrc, hrc, RTNtLastStatusValue(), RTNtLastErrorValue()));
4546 return VERR_NEM_IPE_2;
4547#endif
4548 }
4549 }
4550 RT_NOREF(pVCpu, pvUser);
4551 return VINF_SUCCESS;
4552}
4553
4554
4555/**
4556 * Unmaps a page from Hyper-V for the purpose of emulating A20 gate behavior.
4557 *
4558 * @returns The PGMPhysNemQueryPageInfo result.
4559 * @param pVM The cross context VM structure.
4560 * @param pVCpu The cross context virtual CPU structure.
4561 * @param GCPhys The page to unmap.
4562 */
4563NEM_TMPL_STATIC int nemHCWinUnmapPageForA20Gate(PVMCC pVM, PVMCPUCC pVCpu, RTGCPHYS GCPhys)
4564{
4565 PGMPHYSNEMPAGEINFO Info;
4566 return PGMPhysNemPageInfoChecker(pVM, pVCpu, GCPhys, false /*fMakeWritable*/, &Info,
4567 nemHCWinUnsetForA20CheckerCallback, NULL);
4568}
4569
4570
4571void nemHCNativeNotifyHandlerPhysicalRegister(PVMCC pVM, PGMPHYSHANDLERKIND enmKind, RTGCPHYS GCPhys, RTGCPHYS cb)
4572{
4573 Log5(("nemHCNativeNotifyHandlerPhysicalRegister: %RGp LB %RGp enmKind=%d\n", GCPhys, cb, enmKind));
4574 NOREF(pVM); NOREF(enmKind); NOREF(GCPhys); NOREF(cb);
4575}
4576
4577
4578void nemHCNativeNotifyHandlerPhysicalDeregister(PVMCC pVM, PGMPHYSHANDLERKIND enmKind, RTGCPHYS GCPhys, RTGCPHYS cb,
4579 int fRestoreAsRAM, bool fRestoreAsRAM2)
4580{
4581 Log5(("nemHCNativeNotifyHandlerPhysicalDeregister: %RGp LB %RGp enmKind=%d fRestoreAsRAM=%d fRestoreAsRAM2=%d\n",
4582 GCPhys, cb, enmKind, fRestoreAsRAM, fRestoreAsRAM2));
4583 NOREF(pVM); NOREF(enmKind); NOREF(GCPhys); NOREF(cb); NOREF(fRestoreAsRAM); NOREF(fRestoreAsRAM2);
4584}
4585
4586
4587void nemHCNativeNotifyHandlerPhysicalModify(PVMCC pVM, PGMPHYSHANDLERKIND enmKind, RTGCPHYS GCPhysOld,
4588 RTGCPHYS GCPhysNew, RTGCPHYS cb, bool fRestoreAsRAM)
4589{
4590 Log5(("nemHCNativeNotifyHandlerPhysicalModify: %RGp LB %RGp -> %RGp enmKind=%d fRestoreAsRAM=%d\n",
4591 GCPhysOld, cb, GCPhysNew, enmKind, fRestoreAsRAM));
4592 NOREF(pVM); NOREF(enmKind); NOREF(GCPhysOld); NOREF(GCPhysNew); NOREF(cb); NOREF(fRestoreAsRAM);
4593}
4594
4595
4596/**
4597 * Worker that maps pages into Hyper-V.
4598 *
4599 * This is used by the PGM physical page notifications as well as the memory
4600 * access VMEXIT handlers.
4601 *
4602 * @returns VBox status code.
4603 * @param pVM The cross context VM structure.
4604 * @param pVCpu The cross context virtual CPU structure of the
4605 * calling EMT.
4606 * @param GCPhysSrc The source page address.
4607 * @param GCPhysDst The hyper-V destination page. This may differ from
4608 * GCPhysSrc when A20 is disabled.
4609 * @param fPageProt NEM_PAGE_PROT_XXX.
4610 * @param pu2State Our page state (input/output).
4611 * @param fBackingChanged Set if the page backing is being changed.
4612 * @thread EMT(pVCpu)
4613 */
4614NEM_TMPL_STATIC int nemHCNativeSetPhysPage(PVMCC pVM, PVMCPUCC pVCpu, RTGCPHYS GCPhysSrc, RTGCPHYS GCPhysDst,
4615 uint32_t fPageProt, uint8_t *pu2State, bool fBackingChanged)
4616{
4617#ifdef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
4618 /*
4619 * When using the hypercalls instead of the ring-3 APIs, we don't need to
4620 * unmap memory before modifying it. We still want to track the state though,
4621 * since unmap will fail when called an unmapped page and we don't want to redo
4622 * upgrades/downgrades.
4623 */
4624 uint8_t const u2OldState = *pu2State;
4625 int rc;
4626 if (fPageProt == NEM_PAGE_PROT_NONE)
4627 {
4628 if (u2OldState > NEM_WIN_PAGE_STATE_UNMAPPED)
4629 {
4630 rc = nemHCWinHypercallUnmapPage(pVM, pVCpu, GCPhysDst);
4631 if (RT_SUCCESS(rc))
4632 {
4633 *pu2State = NEM_WIN_PAGE_STATE_UNMAPPED;
4634 uint32_t cMappedPages = ASMAtomicDecU32(&pVM->nem.s.cMappedPages); NOREF(cMappedPages);
4635 Log5(("NEM GPA unmapped/set: %RGp (was %s, cMappedPages=%u)\n", GCPhysDst, g_apszPageStates[u2OldState], cMappedPages));
4636 }
4637 else
4638 AssertLogRelMsgFailed(("nemHCNativeSetPhysPage/unmap: GCPhysDst=%RGp rc=%Rrc\n", GCPhysDst, rc));
4639 }
4640 else
4641 rc = VINF_SUCCESS;
4642 }
4643 else if (fPageProt & NEM_PAGE_PROT_WRITE)
4644 {
4645 if (u2OldState != NEM_WIN_PAGE_STATE_WRITABLE || fBackingChanged)
4646 {
4647 rc = nemHCWinHypercallMapPage(pVM, pVCpu, GCPhysSrc, GCPhysDst,
4648 HV_MAP_GPA_READABLE | HV_MAP_GPA_WRITABLE
4649 | HV_MAP_GPA_EXECUTABLE | HV_MAP_GPA_EXECUTABLE_AGAIN);
4650 if (RT_SUCCESS(rc))
4651 {
4652 *pu2State = NEM_WIN_PAGE_STATE_WRITABLE;
4653 uint32_t cMappedPages = u2OldState <= NEM_WIN_PAGE_STATE_UNMAPPED
4654 ? ASMAtomicIncU32(&pVM->nem.s.cMappedPages) : pVM->nem.s.cMappedPages;
4655 Log5(("NEM GPA writable/set: %RGp (was %s, cMappedPages=%u)\n", GCPhysDst, g_apszPageStates[u2OldState], cMappedPages));
4656 NOREF(cMappedPages);
4657 }
4658 else
4659 AssertLogRelMsgFailed(("nemHCNativeSetPhysPage/writable: GCPhysDst=%RGp rc=%Rrc\n", GCPhysDst, rc));
4660 }
4661 else
4662 rc = VINF_SUCCESS;
4663 }
4664 else
4665 {
4666 if (u2OldState != NEM_WIN_PAGE_STATE_READABLE || fBackingChanged)
4667 {
4668 rc = nemHCWinHypercallMapPage(pVM, pVCpu, GCPhysSrc, GCPhysDst,
4669 HV_MAP_GPA_READABLE | HV_MAP_GPA_EXECUTABLE | HV_MAP_GPA_EXECUTABLE_AGAIN);
4670 if (RT_SUCCESS(rc))
4671 {
4672 *pu2State = NEM_WIN_PAGE_STATE_READABLE;
4673 uint32_t cMappedPages = u2OldState <= NEM_WIN_PAGE_STATE_UNMAPPED
4674 ? ASMAtomicIncU32(&pVM->nem.s.cMappedPages) : pVM->nem.s.cMappedPages;
4675 Log5(("NEM GPA read+exec/set: %RGp (was %s, cMappedPages=%u)\n", GCPhysDst, g_apszPageStates[u2OldState], cMappedPages));
4676 NOREF(cMappedPages);
4677 }
4678 else
4679 AssertLogRelMsgFailed(("nemHCNativeSetPhysPage/writable: GCPhysDst=%RGp rc=%Rrc\n", GCPhysDst, rc));
4680 }
4681 else
4682 rc = VINF_SUCCESS;
4683 }
4684
4685 return VINF_SUCCESS;
4686
4687#else
4688 /*
4689 * Looks like we need to unmap a page before we can change the backing
4690 * or even modify the protection. This is going to be *REALLY* efficient.
4691 * PGM lends us two bits to keep track of the state here.
4692 */
4693 uint8_t const u2OldState = *pu2State;
4694 uint8_t const u2NewState = fPageProt & NEM_PAGE_PROT_WRITE ? NEM_WIN_PAGE_STATE_WRITABLE
4695 : fPageProt & NEM_PAGE_PROT_READ ? NEM_WIN_PAGE_STATE_READABLE : NEM_WIN_PAGE_STATE_UNMAPPED;
4696 if ( fBackingChanged
4697 || u2NewState != u2OldState)
4698 {
4699 if (u2OldState > NEM_WIN_PAGE_STATE_UNMAPPED)
4700 {
4701# ifdef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
4702 int rc = nemHCWinHypercallUnmapPage(pVM, pVCpu, GCPhysDst);
4703 AssertRC(rc);
4704 if (RT_SUCCESS(rc))
4705 {
4706 *pu2State = NEM_WIN_PAGE_STATE_UNMAPPED;
4707 uint32_t cMappedPages = ASMAtomicDecU32(&pVM->nem.s.cMappedPages); NOREF(cMappedPages);
4708 if (u2NewState == NEM_WIN_PAGE_STATE_UNMAPPED)
4709 {
4710 Log5(("NEM GPA unmapped/set: %RGp (was %s, cMappedPages=%u)\n",
4711 GCPhysDst, g_apszPageStates[u2OldState], cMappedPages));
4712 return VINF_SUCCESS;
4713 }
4714 }
4715 else
4716 {
4717 LogRel(("nemHCNativeSetPhysPage/unmap: GCPhysDst=%RGp rc=%Rrc\n", GCPhysDst, rc));
4718 return rc;
4719 }
4720# else
4721 HRESULT hrc = WHvUnmapGpaRange(pVM->nem.s.hPartition, GCPhysDst, X86_PAGE_SIZE);
4722 if (SUCCEEDED(hrc))
4723 {
4724 *pu2State = NEM_WIN_PAGE_STATE_UNMAPPED;
4725 uint32_t cMappedPages = ASMAtomicDecU32(&pVM->nem.s.cMappedPages); NOREF(cMappedPages);
4726 if (u2NewState == NEM_WIN_PAGE_STATE_UNMAPPED)
4727 {
4728 Log5(("NEM GPA unmapped/set: %RGp (was %s, cMappedPages=%u)\n",
4729 GCPhysDst, g_apszPageStates[u2OldState], cMappedPages));
4730 return VINF_SUCCESS;
4731 }
4732 }
4733 else
4734 {
4735 LogRel(("nemHCNativeSetPhysPage/unmap: GCPhysDst=%RGp hrc=%Rhrc (%#x) Last=%#x/%u\n",
4736 GCPhysDst, hrc, hrc, RTNtLastStatusValue(), RTNtLastErrorValue()));
4737 return VERR_NEM_INIT_FAILED;
4738 }
4739# endif
4740 }
4741 }
4742
4743 /*
4744 * Writeable mapping?
4745 */
4746 if (fPageProt & NEM_PAGE_PROT_WRITE)
4747 {
4748# ifdef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
4749 int rc = nemHCWinHypercallMapPage(pVM, pVCpu, GCPhysSrc, GCPhysDst,
4750 HV_MAP_GPA_READABLE | HV_MAP_GPA_WRITABLE
4751 | HV_MAP_GPA_EXECUTABLE | HV_MAP_GPA_EXECUTABLE_AGAIN);
4752 AssertRC(rc);
4753 if (RT_SUCCESS(rc))
4754 {
4755 *pu2State = NEM_WIN_PAGE_STATE_WRITABLE;
4756 uint32_t cMappedPages = ASMAtomicIncU32(&pVM->nem.s.cMappedPages); NOREF(cMappedPages);
4757 Log5(("NEM GPA mapped/set: %RGp %s (was %s, cMappedPages=%u)\n",
4758 GCPhysDst, g_apszPageStates[u2NewState], g_apszPageStates[u2OldState], cMappedPages));
4759 return VINF_SUCCESS;
4760 }
4761 LogRel(("nemHCNativeSetPhysPage/writable: GCPhysDst=%RGp rc=%Rrc\n", GCPhysDst, rc));
4762 return rc;
4763# else
4764 void *pvPage;
4765 int rc = nemR3NativeGCPhys2R3PtrWriteable(pVM, GCPhysSrc, &pvPage);
4766 if (RT_SUCCESS(rc))
4767 {
4768 HRESULT hrc = WHvMapGpaRange(pVM->nem.s.hPartition, pvPage, GCPhysDst, X86_PAGE_SIZE,
4769 WHvMapGpaRangeFlagRead | WHvMapGpaRangeFlagExecute | WHvMapGpaRangeFlagWrite);
4770 if (SUCCEEDED(hrc))
4771 {
4772 *pu2State = NEM_WIN_PAGE_STATE_WRITABLE;
4773 uint32_t cMappedPages = ASMAtomicIncU32(&pVM->nem.s.cMappedPages); NOREF(cMappedPages);
4774 Log5(("NEM GPA mapped/set: %RGp %s (was %s, cMappedPages=%u)\n",
4775 GCPhysDst, g_apszPageStates[u2NewState], g_apszPageStates[u2OldState], cMappedPages));
4776 return VINF_SUCCESS;
4777 }
4778 LogRel(("nemHCNativeSetPhysPage/writable: GCPhysDst=%RGp hrc=%Rhrc (%#x) Last=%#x/%u\n",
4779 GCPhysDst, hrc, hrc, RTNtLastStatusValue(), RTNtLastErrorValue()));
4780 return VERR_NEM_INIT_FAILED;
4781 }
4782 LogRel(("nemHCNativeSetPhysPage/writable: GCPhysSrc=%RGp rc=%Rrc\n", GCPhysSrc, rc));
4783 return rc;
4784# endif
4785 }
4786
4787 if (fPageProt & NEM_PAGE_PROT_READ)
4788 {
4789# ifdef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
4790 int rc = nemHCWinHypercallMapPage(pVM, pVCpu, GCPhysSrc, GCPhysDst,
4791 HV_MAP_GPA_READABLE | HV_MAP_GPA_EXECUTABLE | HV_MAP_GPA_EXECUTABLE_AGAIN);
4792 AssertRC(rc);
4793 if (RT_SUCCESS(rc))
4794 {
4795 *pu2State = NEM_WIN_PAGE_STATE_READABLE;
4796 uint32_t cMappedPages = ASMAtomicIncU32(&pVM->nem.s.cMappedPages); NOREF(cMappedPages);
4797 Log5(("NEM GPA mapped/set: %RGp %s (was %s, cMappedPages=%u)\n",
4798 GCPhysDst, g_apszPageStates[u2NewState], g_apszPageStates[u2OldState], cMappedPages));
4799 return VINF_SUCCESS;
4800 }
4801 LogRel(("nemHCNativeSetPhysPage/readonly: GCPhysDst=%RGp rc=%Rrc\n", GCPhysDst, rc));
4802 return rc;
4803# else
4804 const void *pvPage;
4805 int rc = nemR3NativeGCPhys2R3PtrReadOnly(pVM, GCPhysSrc, &pvPage);
4806 if (RT_SUCCESS(rc))
4807 {
4808 HRESULT hrc = WHvMapGpaRange(pVM->nem.s.hPartition, (void *)pvPage, GCPhysDst, X86_PAGE_SIZE,
4809 WHvMapGpaRangeFlagRead | WHvMapGpaRangeFlagExecute);
4810 if (SUCCEEDED(hrc))
4811 {
4812 *pu2State = NEM_WIN_PAGE_STATE_READABLE;
4813 uint32_t cMappedPages = ASMAtomicIncU32(&pVM->nem.s.cMappedPages); NOREF(cMappedPages);
4814 Log5(("NEM GPA mapped/set: %RGp %s (was %s, cMappedPages=%u)\n",
4815 GCPhysDst, g_apszPageStates[u2NewState], g_apszPageStates[u2OldState], cMappedPages));
4816 return VINF_SUCCESS;
4817 }
4818 LogRel(("nemHCNativeSetPhysPage/readonly: GCPhysDst=%RGp hrc=%Rhrc (%#x) Last=%#x/%u\n",
4819 GCPhysDst, hrc, hrc, RTNtLastStatusValue(), RTNtLastErrorValue()));
4820 return VERR_NEM_INIT_FAILED;
4821 }
4822 LogRel(("nemHCNativeSetPhysPage/readonly: GCPhysSrc=%RGp rc=%Rrc\n", GCPhysSrc, rc));
4823 return rc;
4824# endif
4825 }
4826
4827 /* We already unmapped it above. */
4828 *pu2State = NEM_WIN_PAGE_STATE_UNMAPPED;
4829 return VINF_SUCCESS;
4830#endif /* !NEM_WIN_USE_HYPERCALLS_FOR_PAGES */
4831}
4832
4833
4834NEM_TMPL_STATIC int nemHCJustUnmapPageFromHyperV(PVMCC pVM, RTGCPHYS GCPhysDst, uint8_t *pu2State)
4835{
4836 if (*pu2State <= NEM_WIN_PAGE_STATE_UNMAPPED)
4837 {
4838 Log5(("nemHCJustUnmapPageFromHyperV: %RGp == unmapped\n", GCPhysDst));
4839 *pu2State = NEM_WIN_PAGE_STATE_UNMAPPED;
4840 return VINF_SUCCESS;
4841 }
4842
4843#if defined(NEM_WIN_USE_HYPERCALLS_FOR_PAGES) || defined(IN_RING0)
4844 PVMCPUCC pVCpu = VMMGetCpu(pVM);
4845 int rc = nemHCWinHypercallUnmapPage(pVM, pVCpu, GCPhysDst);
4846 AssertRC(rc);
4847 if (RT_SUCCESS(rc))
4848 {
4849 uint32_t cMappedPages = ASMAtomicDecU32(&pVM->nem.s.cMappedPages); NOREF(cMappedPages);
4850 Log5(("NEM GPA unmapped/just: %RGp (was %s, cMappedPages=%u)\n", GCPhysDst, g_apszPageStates[*pu2State], cMappedPages));
4851 *pu2State = NEM_WIN_PAGE_STATE_UNMAPPED;
4852 return VINF_SUCCESS;
4853 }
4854 LogRel(("nemHCJustUnmapPageFromHyperV/unmap: GCPhysDst=%RGp rc=%Rrc\n", GCPhysDst, rc));
4855 return rc;
4856#else
4857 HRESULT hrc = WHvUnmapGpaRange(pVM->nem.s.hPartition, GCPhysDst & ~(RTGCPHYS)X86_PAGE_OFFSET_MASK, X86_PAGE_SIZE);
4858 if (SUCCEEDED(hrc))
4859 {
4860 uint32_t cMappedPages = ASMAtomicDecU32(&pVM->nem.s.cMappedPages); NOREF(cMappedPages);
4861 *pu2State = NEM_WIN_PAGE_STATE_UNMAPPED;
4862 Log5(("nemHCJustUnmapPageFromHyperV: %RGp => unmapped (total %u)\n", GCPhysDst, cMappedPages));
4863 return VINF_SUCCESS;
4864 }
4865 LogRel(("nemHCJustUnmapPageFromHyperV(%RGp): failed! hrc=%Rhrc (%#x) Last=%#x/%u\n",
4866 GCPhysDst, hrc, hrc, RTNtLastStatusValue(), RTNtLastErrorValue()));
4867 return VERR_NEM_IPE_6;
4868#endif
4869}
4870
4871
4872int nemHCNativeNotifyPhysPageAllocated(PVMCC pVM, RTGCPHYS GCPhys, RTHCPHYS HCPhys, uint32_t fPageProt,
4873 PGMPAGETYPE enmType, uint8_t *pu2State)
4874{
4875 Log5(("nemHCNativeNotifyPhysPageAllocated: %RGp HCPhys=%RHp fPageProt=%#x enmType=%d *pu2State=%d\n",
4876 GCPhys, HCPhys, fPageProt, enmType, *pu2State));
4877 RT_NOREF_PV(HCPhys); RT_NOREF_PV(enmType);
4878
4879 int rc;
4880#if defined(NEM_WIN_USE_HYPERCALLS_FOR_PAGES) || defined(IN_RING0)
4881 PVMCPUCC pVCpu = VMMGetCpu(pVM);
4882 if ( pVM->nem.s.fA20Enabled
4883 || !NEM_WIN_IS_RELEVANT_TO_A20(GCPhys))
4884 rc = nemHCNativeSetPhysPage(pVM, pVCpu, GCPhys, GCPhys, fPageProt, pu2State, true /*fBackingChanged*/);
4885 else
4886 {
4887 /* To keep effort at a minimum, we unmap the HMA page alias and resync it lazily when needed. */
4888 rc = nemHCWinUnmapPageForA20Gate(pVM, pVCpu, GCPhys | RT_BIT_32(20));
4889 if (!NEM_WIN_IS_SUBJECT_TO_A20(GCPhys) && RT_SUCCESS(rc))
4890 rc = nemHCNativeSetPhysPage(pVM, pVCpu, GCPhys, GCPhys, fPageProt, pu2State, true /*fBackingChanged*/);
4891
4892 }
4893#else
4894 RT_NOREF_PV(fPageProt);
4895 if ( pVM->nem.s.fA20Enabled
4896 || !NEM_WIN_IS_RELEVANT_TO_A20(GCPhys))
4897 rc = nemR3JustUnmapPageFromHyperV(pVM, GCPhys, pu2State);
4898 else if (!NEM_WIN_IS_SUBJECT_TO_A20(GCPhys))
4899 rc = nemR3JustUnmapPageFromHyperV(pVM, GCPhys, pu2State);
4900 else
4901 rc = VINF_SUCCESS; /* ignore since we've got the alias page at this address. */
4902#endif
4903 return rc;
4904}
4905
4906
4907void nemHCNativeNotifyPhysPageProtChanged(PVMCC pVM, RTGCPHYS GCPhys, RTHCPHYS HCPhys, uint32_t fPageProt,
4908 PGMPAGETYPE enmType, uint8_t *pu2State)
4909{
4910 Log5(("nemHCNativeNotifyPhysPageProtChanged: %RGp HCPhys=%RHp fPageProt=%#x enmType=%d *pu2State=%d\n",
4911 GCPhys, HCPhys, fPageProt, enmType, *pu2State));
4912 RT_NOREF_PV(HCPhys); RT_NOREF_PV(enmType);
4913
4914#if defined(NEM_WIN_USE_HYPERCALLS_FOR_PAGES) || defined(IN_RING0)
4915 PVMCPUCC pVCpu = VMMGetCpu(pVM);
4916 if ( pVM->nem.s.fA20Enabled
4917 || !NEM_WIN_IS_RELEVANT_TO_A20(GCPhys))
4918 nemHCNativeSetPhysPage(pVM, pVCpu, GCPhys, GCPhys, fPageProt, pu2State, false /*fBackingChanged*/);
4919 else
4920 {
4921 /* To keep effort at a minimum, we unmap the HMA page alias and resync it lazily when needed. */
4922 nemHCWinUnmapPageForA20Gate(pVM, pVCpu, GCPhys | RT_BIT_32(20));
4923 if (!NEM_WIN_IS_SUBJECT_TO_A20(GCPhys))
4924 nemHCNativeSetPhysPage(pVM, pVCpu, GCPhys, GCPhys, fPageProt, pu2State, false /*fBackingChanged*/);
4925 }
4926#else
4927 RT_NOREF_PV(fPageProt);
4928 if ( pVM->nem.s.fA20Enabled
4929 || !NEM_WIN_IS_RELEVANT_TO_A20(GCPhys))
4930 nemR3JustUnmapPageFromHyperV(pVM, GCPhys, pu2State);
4931 else if (!NEM_WIN_IS_SUBJECT_TO_A20(GCPhys))
4932 nemR3JustUnmapPageFromHyperV(pVM, GCPhys, pu2State);
4933 /* else: ignore since we've got the alias page at this address. */
4934#endif
4935}
4936
4937
4938void nemHCNativeNotifyPhysPageChanged(PVMCC pVM, RTGCPHYS GCPhys, RTHCPHYS HCPhysPrev, RTHCPHYS HCPhysNew,
4939 uint32_t fPageProt, PGMPAGETYPE enmType, uint8_t *pu2State)
4940{
4941 Log5(("nemHCNativeNotifyPhysPageChanged: %RGp HCPhys=%RHp->%RHp fPageProt=%#x enmType=%d *pu2State=%d\n",
4942 GCPhys, HCPhysPrev, HCPhysNew, fPageProt, enmType, *pu2State));
4943 RT_NOREF_PV(HCPhysPrev); RT_NOREF_PV(HCPhysNew); RT_NOREF_PV(enmType);
4944
4945#if defined(NEM_WIN_USE_HYPERCALLS_FOR_PAGES) || defined(IN_RING0)
4946 PVMCPUCC pVCpu = VMMGetCpu(pVM);
4947 if ( pVM->nem.s.fA20Enabled
4948 || !NEM_WIN_IS_RELEVANT_TO_A20(GCPhys))
4949 nemHCNativeSetPhysPage(pVM, pVCpu, GCPhys, GCPhys, fPageProt, pu2State, true /*fBackingChanged*/);
4950 else
4951 {
4952 /* To keep effort at a minimum, we unmap the HMA page alias and resync it lazily when needed. */
4953 nemHCWinUnmapPageForA20Gate(pVM, pVCpu, GCPhys | RT_BIT_32(20));
4954 if (!NEM_WIN_IS_SUBJECT_TO_A20(GCPhys))
4955 nemHCNativeSetPhysPage(pVM, pVCpu, GCPhys, GCPhys, fPageProt, pu2State, true /*fBackingChanged*/);
4956 }
4957#else
4958 RT_NOREF_PV(fPageProt);
4959 if ( pVM->nem.s.fA20Enabled
4960 || !NEM_WIN_IS_RELEVANT_TO_A20(GCPhys))
4961 nemR3JustUnmapPageFromHyperV(pVM, GCPhys, pu2State);
4962 else if (!NEM_WIN_IS_SUBJECT_TO_A20(GCPhys))
4963 nemR3JustUnmapPageFromHyperV(pVM, GCPhys, pu2State);
4964 /* else: ignore since we've got the alias page at this address. */
4965#endif
4966}
4967
Note: See TracBrowser for help on using the repository browser.

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