VirtualBox

source: vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp@ 80844

Last change on this file since 80844 was 80844, checked in by vboxsync, 5 years ago

VMM/HMR0: Avoid clearing CR4.VMXE if the for some reason the host already has it set when we try to set-VMXON-clear probe for VMX availability.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 69.5 KB
Line 
1/* $Id: HMR0.cpp 80844 2019-09-17 08:44:53Z vboxsync $ */
2/** @file
3 * Hardware Assisted Virtualization Manager (HM) - Host Context Ring-0.
4 */
5
6/*
7 * Copyright (C) 2006-2019 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_HM
23#define VMCPU_INCL_CPUM_GST_CTX
24#include <VBox/vmm/hm.h>
25#include <VBox/vmm/pgm.h>
26#include "HMInternal.h"
27#include <VBox/vmm/vmcc.h>
28#include <VBox/vmm/hm_svm.h>
29#include <VBox/vmm/hmvmxinline.h>
30#include <VBox/err.h>
31#include <VBox/log.h>
32#include <iprt/assert.h>
33#include <iprt/asm.h>
34#include <iprt/asm-amd64-x86.h>
35#include <iprt/cpuset.h>
36#include <iprt/mem.h>
37#include <iprt/memobj.h>
38#include <iprt/once.h>
39#include <iprt/param.h>
40#include <iprt/power.h>
41#include <iprt/string.h>
42#include <iprt/thread.h>
43#include <iprt/x86.h>
44#include "HMVMXR0.h"
45#include "HMSVMR0.h"
46
47
48/*********************************************************************************************************************************
49* Internal Functions *
50*********************************************************************************************************************************/
51static DECLCALLBACK(void) hmR0EnableCpuCallback(RTCPUID idCpu, void *pvUser1, void *pvUser2);
52static DECLCALLBACK(void) hmR0DisableCpuCallback(RTCPUID idCpu, void *pvUser1, void *pvUser2);
53static DECLCALLBACK(void) hmR0InitIntelCpu(RTCPUID idCpu, void *pvUser1, void *pvUser2);
54static DECLCALLBACK(void) hmR0InitAmdCpu(RTCPUID idCpu, void *pvUser1, void *pvUser2);
55static DECLCALLBACK(void) hmR0PowerCallback(RTPOWEREVENT enmEvent, void *pvUser);
56static DECLCALLBACK(void) hmR0MpEventCallback(RTMPEVENT enmEvent, RTCPUID idCpu, void *pvData);
57
58
59/*********************************************************************************************************************************
60* Structures and Typedefs *
61*********************************************************************************************************************************/
62/**
63 * This is used to manage the status code of a RTMpOnAll in HM.
64 */
65typedef struct HMR0FIRSTRC
66{
67 /** The status code. */
68 int32_t volatile rc;
69 /** The ID of the CPU reporting the first failure. */
70 RTCPUID volatile idCpu;
71} HMR0FIRSTRC;
72/** Pointer to a first return code structure. */
73typedef HMR0FIRSTRC *PHMR0FIRSTRC;
74
75
76/*********************************************************************************************************************************
77* Global Variables *
78*********************************************************************************************************************************/
79/**
80 * Global data.
81 */
82static struct
83{
84 /** Per CPU globals. */
85 HMPHYSCPU aCpuInfo[RTCPUSET_MAX_CPUS];
86
87 /** @name Ring-0 method table for AMD-V and VT-x specific operations.
88 * @{ */
89 DECLR0CALLBACKMEMBER(int, pfnEnterSession, (PVMCPUCC pVCpu));
90 DECLR0CALLBACKMEMBER(void, pfnThreadCtxCallback, (RTTHREADCTXEVENT enmEvent, PVMCPUCC pVCpu, bool fGlobalInit));
91 DECLR0CALLBACKMEMBER(int, pfnCallRing3Callback, (PVMCPUCC pVCpu, VMMCALLRING3 enmOperation));
92 DECLR0CALLBACKMEMBER(int, pfnExportHostState, (PVMCPUCC pVCpu));
93 DECLR0CALLBACKMEMBER(VBOXSTRICTRC, pfnRunGuestCode, (PVMCPUCC pVCpu));
94 DECLR0CALLBACKMEMBER(int, pfnEnableCpu, (PHMPHYSCPU pHostCpu, PVMCC pVM, void *pvCpuPage, RTHCPHYS HCPhysCpuPage,
95 bool fEnabledByHost, PCSUPHWVIRTMSRS pHwvirtMsrs));
96 DECLR0CALLBACKMEMBER(int, pfnDisableCpu, (void *pvCpuPage, RTHCPHYS HCPhysCpuPage));
97 DECLR0CALLBACKMEMBER(int, pfnInitVM, (PVMCC pVM));
98 DECLR0CALLBACKMEMBER(int, pfnTermVM, (PVMCC pVM));
99 DECLR0CALLBACKMEMBER(int, pfnSetupVM, (PVMCC pVM));
100 /** @} */
101
102 /** Hardware-virtualization data. */
103 struct
104 {
105 union
106 {
107 /** VT-x data. */
108 struct
109 {
110 /** Host CR4 value (set by ring-0 VMX init) */
111 uint64_t u64HostCr4;
112 /** Host EFER value (set by ring-0 VMX init) */
113 uint64_t u64HostMsrEfer;
114 /** Host SMM monitor control (used for logging/diagnostics) */
115 uint64_t u64HostSmmMonitorCtl;
116 /** Last instruction error. */
117 uint32_t ulLastInstrError;
118 /** The shift mask employed by the VMX-Preemption timer. */
119 uint8_t cPreemptTimerShift;
120 /** Padding. */
121 uint8_t abPadding[3];
122 /** Whether we're using the preemption timer or not. */
123 bool fUsePreemptTimer;
124 /** Whether we're using SUPR0EnableVTx or not. */
125 bool fUsingSUPR0EnableVTx;
126 /** Set if we've called SUPR0EnableVTx(true) and should disable it during
127 * module termination. */
128 bool fCalledSUPR0EnableVTx;
129 /** Set to by us to indicate VMX is supported by the CPU. */
130 bool fSupported;
131 } vmx;
132
133 /** AMD-V data. */
134 struct
135 {
136 /** SVM revision. */
137 uint32_t u32Rev;
138 /** SVM feature bits from cpuid 0x8000000a */
139 uint32_t u32Features;
140 /** Padding. */
141 bool afPadding[3];
142 /** Set by us to indicate SVM is supported by the CPU. */
143 bool fSupported;
144 } svm;
145 } u;
146 /** Maximum allowed ASID/VPID (inclusive). */
147 uint32_t uMaxAsid;
148 /** MSRs. */
149 SUPHWVIRTMSRS Msrs;
150 } hwvirt;
151
152 /** Last recorded error code during HM ring-0 init. */
153 int32_t rcInit;
154
155 /** If set, VT-x/AMD-V is enabled globally at init time, otherwise it's
156 * enabled and disabled each time it's used to execute guest code. */
157 bool fGlobalInit;
158 /** Indicates whether the host is suspending or not. We'll refuse a few
159 * actions when the host is being suspended to speed up the suspending and
160 * avoid trouble. */
161 bool volatile fSuspended;
162
163 /** Whether we've already initialized all CPUs.
164 * @remarks We could check the EnableAllCpusOnce state, but this is
165 * simpler and hopefully easier to understand. */
166 bool fEnabled;
167 /** Serialize initialization in HMR0EnableAllCpus. */
168 RTONCE EnableAllCpusOnce;
169} g_HmR0;
170
171
172/**
173 * Initializes a first return code structure.
174 *
175 * @param pFirstRc The structure to init.
176 */
177static void hmR0FirstRcInit(PHMR0FIRSTRC pFirstRc)
178{
179 pFirstRc->rc = VINF_SUCCESS;
180 pFirstRc->idCpu = NIL_RTCPUID;
181}
182
183
184/**
185 * Try set the status code (success ignored).
186 *
187 * @param pFirstRc The first return code structure.
188 * @param rc The status code.
189 */
190static void hmR0FirstRcSetStatus(PHMR0FIRSTRC pFirstRc, int rc)
191{
192 if ( RT_FAILURE(rc)
193 && ASMAtomicCmpXchgS32(&pFirstRc->rc, rc, VINF_SUCCESS))
194 pFirstRc->idCpu = RTMpCpuId();
195}
196
197
198/**
199 * Get the status code of a first return code structure.
200 *
201 * @returns The status code; VINF_SUCCESS or error status, no informational or
202 * warning errors.
203 * @param pFirstRc The first return code structure.
204 */
205static int hmR0FirstRcGetStatus(PHMR0FIRSTRC pFirstRc)
206{
207 return pFirstRc->rc;
208}
209
210
211#ifdef VBOX_STRICT
212# ifndef DEBUG_bird
213/**
214 * Get the CPU ID on which the failure status code was reported.
215 *
216 * @returns The CPU ID, NIL_RTCPUID if no failure was reported.
217 * @param pFirstRc The first return code structure.
218 */
219static RTCPUID hmR0FirstRcGetCpuId(PHMR0FIRSTRC pFirstRc)
220{
221 return pFirstRc->idCpu;
222}
223# endif
224#endif /* VBOX_STRICT */
225
226
227/** @name Dummy callback handlers.
228 * @{ */
229
230static DECLCALLBACK(int) hmR0DummyEnter(PVMCPUCC pVCpu)
231{
232 RT_NOREF1(pVCpu);
233 return VINF_SUCCESS;
234}
235
236static DECLCALLBACK(void) hmR0DummyThreadCtxCallback(RTTHREADCTXEVENT enmEvent, PVMCPUCC pVCpu, bool fGlobalInit)
237{
238 RT_NOREF3(enmEvent, pVCpu, fGlobalInit);
239}
240
241static DECLCALLBACK(int) hmR0DummyEnableCpu(PHMPHYSCPU pHostCpu, PVMCC pVM, void *pvCpuPage, RTHCPHYS HCPhysCpuPage,
242 bool fEnabledBySystem, PCSUPHWVIRTMSRS pHwvirtMsrs)
243{
244 RT_NOREF6(pHostCpu, pVM, pvCpuPage, HCPhysCpuPage, fEnabledBySystem, pHwvirtMsrs);
245 return VINF_SUCCESS;
246}
247
248static DECLCALLBACK(int) hmR0DummyDisableCpu(void *pvCpuPage, RTHCPHYS HCPhysCpuPage)
249{
250 RT_NOREF2(pvCpuPage, HCPhysCpuPage);
251 return VINF_SUCCESS;
252}
253
254static DECLCALLBACK(int) hmR0DummyInitVM(PVMCC pVM)
255{
256 RT_NOREF1(pVM);
257 return VINF_SUCCESS;
258}
259
260static DECLCALLBACK(int) hmR0DummyTermVM(PVMCC pVM)
261{
262 RT_NOREF1(pVM);
263 return VINF_SUCCESS;
264}
265
266static DECLCALLBACK(int) hmR0DummySetupVM(PVMCC pVM)
267{
268 RT_NOREF1(pVM);
269 return VINF_SUCCESS;
270}
271
272static DECLCALLBACK(int) hmR0DummyCallRing3Callback(PVMCPUCC pVCpu, VMMCALLRING3 enmOperation)
273{
274 RT_NOREF2(pVCpu, enmOperation);
275 return VINF_SUCCESS;
276}
277
278static DECLCALLBACK(VBOXSTRICTRC) hmR0DummyRunGuestCode(PVMCPUCC pVCpu)
279{
280 RT_NOREF(pVCpu);
281 return VINF_SUCCESS;
282}
283
284static DECLCALLBACK(int) hmR0DummyExportHostState(PVMCPUCC pVCpu)
285{
286 RT_NOREF1(pVCpu);
287 return VINF_SUCCESS;
288}
289
290/** @} */
291
292
293/**
294 * Checks if the CPU is subject to the "VMX-Preemption Timer Does Not Count
295 * Down at the Rate Specified" erratum.
296 *
297 * Errata names and related steppings:
298 * - BA86 - D0.
299 * - AAX65 - C2.
300 * - AAU65 - C2, K0.
301 * - AAO95 - B1.
302 * - AAT59 - C2.
303 * - AAK139 - D0.
304 * - AAM126 - C0, C1, D0.
305 * - AAN92 - B1.
306 * - AAJ124 - C0, D0.
307 * - AAP86 - B1.
308 *
309 * Steppings: B1, C0, C1, C2, D0, K0.
310 *
311 * @returns true if subject to it, false if not.
312 */
313static bool hmR0InitIntelIsSubjectToVmxPreemptTimerErratum(void)
314{
315 uint32_t u = ASMCpuId_EAX(1);
316 u &= ~(RT_BIT_32(14) | RT_BIT_32(15) | RT_BIT_32(28) | RT_BIT_32(29) | RT_BIT_32(30) | RT_BIT_32(31));
317 if ( u == UINT32_C(0x000206E6) /* 323344.pdf - BA86 - D0 - Intel Xeon Processor 7500 Series */
318 || u == UINT32_C(0x00020652) /* 323056.pdf - AAX65 - C2 - Intel Xeon Processor L3406 */
319 /* 322814.pdf - AAT59 - C2 - Intel CoreTM i7-600, i5-500, i5-400 and i3-300 Mobile Processor Series */
320 /* 322911.pdf - AAU65 - C2 - Intel CoreTM i5-600, i3-500 Desktop Processor Series and Intel Pentium Processor G6950 */
321 || u == UINT32_C(0x00020655) /* 322911.pdf - AAU65 - K0 - Intel CoreTM i5-600, i3-500 Desktop Processor Series and Intel Pentium Processor G6950 */
322 || u == UINT32_C(0x000106E5) /* 322373.pdf - AAO95 - B1 - Intel Xeon Processor 3400 Series */
323 /* 322166.pdf - AAN92 - B1 - Intel CoreTM i7-800 and i5-700 Desktop Processor Series */
324 /* 320767.pdf - AAP86 - B1 - Intel Core i7-900 Mobile Processor Extreme Edition Series, Intel Core i7-800 and i7-700 Mobile Processor Series */
325 || u == UINT32_C(0x000106A0) /* 321333.pdf - AAM126 - C0 - Intel Xeon Processor 3500 Series Specification */
326 || u == UINT32_C(0x000106A1) /* 321333.pdf - AAM126 - C1 - Intel Xeon Processor 3500 Series Specification */
327 || u == UINT32_C(0x000106A4) /* 320836.pdf - AAJ124 - C0 - Intel Core i7-900 Desktop Processor Extreme Edition Series and Intel Core i7-900 Desktop Processor Series */
328 || u == UINT32_C(0x000106A5) /* 321333.pdf - AAM126 - D0 - Intel Xeon Processor 3500 Series Specification */
329 /* 321324.pdf - AAK139 - D0 - Intel Xeon Processor 5500 Series Specification */
330 /* 320836.pdf - AAJ124 - D0 - Intel Core i7-900 Desktop Processor Extreme Edition Series and Intel Core i7-900 Desktop Processor Series */
331 )
332 return true;
333 return false;
334}
335
336
337/**
338 * Intel specific initialization code.
339 *
340 * @returns VBox status code (will only fail if out of memory).
341 */
342static int hmR0InitIntel(void)
343{
344 /* Read this MSR now as it may be useful for error reporting when initializing VT-x fails. */
345 g_HmR0.hwvirt.Msrs.u.vmx.u64FeatCtrl = ASMRdMsr(MSR_IA32_FEATURE_CONTROL);
346
347 /*
348 * First try use native kernel API for controlling VT-x.
349 * (This is only supported by some Mac OS X kernels atm.)
350 */
351 int rc = g_HmR0.rcInit = SUPR0EnableVTx(true /* fEnable */);
352 g_HmR0.hwvirt.u.vmx.fUsingSUPR0EnableVTx = rc != VERR_NOT_SUPPORTED;
353 if (g_HmR0.hwvirt.u.vmx.fUsingSUPR0EnableVTx)
354 {
355 AssertLogRelMsg(rc == VINF_SUCCESS || rc == VERR_VMX_IN_VMX_ROOT_MODE || rc == VERR_VMX_NO_VMX, ("%Rrc\n", rc));
356 if (RT_SUCCESS(rc))
357 {
358 g_HmR0.hwvirt.u.vmx.fSupported = true;
359 rc = SUPR0EnableVTx(false /* fEnable */);
360 AssertLogRelRC(rc);
361 }
362 }
363 else
364 {
365 HMR0FIRSTRC FirstRc;
366 hmR0FirstRcInit(&FirstRc);
367 g_HmR0.rcInit = RTMpOnAll(hmR0InitIntelCpu, &FirstRc, NULL);
368 if (RT_SUCCESS(g_HmR0.rcInit))
369 g_HmR0.rcInit = hmR0FirstRcGetStatus(&FirstRc);
370 }
371
372 if (RT_SUCCESS(g_HmR0.rcInit))
373 {
374 /* Read CR4 and EFER for logging/diagnostic purposes. */
375 g_HmR0.hwvirt.u.vmx.u64HostCr4 = ASMGetCR4();
376 g_HmR0.hwvirt.u.vmx.u64HostMsrEfer = ASMRdMsr(MSR_K6_EFER);
377
378 /* Get VMX MSRs for determining VMX features we can ultimately use. */
379 SUPR0GetHwvirtMsrs(&g_HmR0.hwvirt.Msrs, SUPVTCAPS_VT_X, false /* fForce */);
380
381 /*
382 * Nested KVM workaround: Intel SDM section 34.15.5 describes that
383 * MSR_IA32_SMM_MONITOR_CTL depends on bit 49 of MSR_IA32_VMX_BASIC while
384 * table 35-2 says that this MSR is available if either VMX or SMX is supported.
385 */
386 uint64_t const uVmxBasicMsr = g_HmR0.hwvirt.Msrs.u.vmx.u64Basic;
387 if (RT_BF_GET(uVmxBasicMsr, VMX_BF_BASIC_DUAL_MON))
388 g_HmR0.hwvirt.u.vmx.u64HostSmmMonitorCtl = ASMRdMsr(MSR_IA32_SMM_MONITOR_CTL);
389
390 /* Initialize VPID - 16 bits ASID. */
391 g_HmR0.hwvirt.uMaxAsid = 0x10000; /* exclusive */
392
393 /*
394 * If the host OS has not enabled VT-x for us, try enter VMX root mode
395 * to really verify if VT-x is usable.
396 */
397 if (!g_HmR0.hwvirt.u.vmx.fUsingSUPR0EnableVTx)
398 {
399 /* Allocate a temporary VMXON region. */
400 RTR0MEMOBJ hScatchMemObj;
401 rc = RTR0MemObjAllocCont(&hScatchMemObj, PAGE_SIZE, false /* fExecutable */);
402 if (RT_FAILURE(rc))
403 {
404 LogRel(("hmR0InitIntel: RTR0MemObjAllocCont(,PAGE_SIZE,false) -> %Rrc\n", rc));
405 return rc;
406 }
407 void *pvScatchPage = RTR0MemObjAddress(hScatchMemObj);
408 RTHCPHYS const HCPhysScratchPage = RTR0MemObjGetPagePhysAddr(hScatchMemObj, 0);
409 ASMMemZeroPage(pvScatchPage);
410
411 /* Set revision dword at the beginning of the VMXON structure. */
412 *(uint32_t *)pvScatchPage = RT_BF_GET(uVmxBasicMsr, VMX_BF_BASIC_VMCS_ID);
413
414 /* Make sure we don't get rescheduled to another CPU during this probe. */
415 RTCCUINTREG const fEFlags = ASMIntDisableFlags();
416
417 /* Enable CR4.VMXE if it isn't already set. */
418 RTCCUINTREG const uOldCr4 = SUPR0ChangeCR4(X86_CR4_VMXE, RTCCUINTREG_MAX);
419
420 /*
421 * The only way of checking if we're in VMX root mode or not is to try and enter it.
422 * There is no instruction or control bit that tells us if we're in VMX root mode.
423 * Therefore, try and enter VMX root mode here.
424 */
425 rc = VMXEnable(HCPhysScratchPage);
426 if (RT_SUCCESS(rc))
427 {
428 g_HmR0.hwvirt.u.vmx.fSupported = true;
429 VMXDisable();
430 }
431 else
432 {
433 /*
434 * KVM leaves the CPU in VMX root mode. Not only is this not allowed,
435 * it will crash the host when we enter raw mode, because:
436 *
437 * (a) clearing X86_CR4_VMXE in CR4 causes a #GP (we no longer modify
438 * this bit), and
439 * (b) turning off paging causes a #GP (unavoidable when switching
440 * from long to 32 bits mode or 32 bits to PAE).
441 *
442 * They should fix their code, but until they do we simply refuse to run.
443 */
444 g_HmR0.rcInit = VERR_VMX_IN_VMX_ROOT_MODE;
445 Assert(g_HmR0.hwvirt.u.vmx.fSupported == false);
446 }
447
448 /* Restore CR4.VMXE if it wasn't set prior to us setting it above. */
449 if (!(uOldCr4 & X86_CR4_VMXE))
450 SUPR0ChangeCR4(0 /* fOrMask */, ~X86_CR4_VMXE);
451
452 /* Restore interrupts. */
453 ASMSetFlags(fEFlags);
454
455 RTR0MemObjFree(hScatchMemObj, false);
456 }
457
458 if (g_HmR0.hwvirt.u.vmx.fSupported)
459 {
460 rc = VMXR0GlobalInit();
461 if (RT_FAILURE(rc))
462 g_HmR0.rcInit = rc;
463
464 /*
465 * Install the VT-x methods.
466 */
467 g_HmR0.pfnEnterSession = VMXR0Enter;
468 g_HmR0.pfnThreadCtxCallback = VMXR0ThreadCtxCallback;
469 g_HmR0.pfnCallRing3Callback = VMXR0CallRing3Callback;
470 g_HmR0.pfnExportHostState = VMXR0ExportHostState;
471 g_HmR0.pfnRunGuestCode = VMXR0RunGuestCode;
472 g_HmR0.pfnEnableCpu = VMXR0EnableCpu;
473 g_HmR0.pfnDisableCpu = VMXR0DisableCpu;
474 g_HmR0.pfnInitVM = VMXR0InitVM;
475 g_HmR0.pfnTermVM = VMXR0TermVM;
476 g_HmR0.pfnSetupVM = VMXR0SetupVM;
477
478 /*
479 * Check for the VMX-Preemption Timer and adjust for the "VMX-Preemption
480 * Timer Does Not Count Down at the Rate Specified" CPU erratum.
481 */
482 VMXCTLSMSR PinCtls;
483 PinCtls.u = g_HmR0.hwvirt.Msrs.u.vmx.u64PinCtls;
484 if (PinCtls.n.allowed1 & VMX_PIN_CTLS_PREEMPT_TIMER)
485 {
486 uint64_t const uVmxMiscMsr = g_HmR0.hwvirt.Msrs.u.vmx.u64Misc;
487 g_HmR0.hwvirt.u.vmx.fUsePreemptTimer = true;
488 g_HmR0.hwvirt.u.vmx.cPreemptTimerShift = RT_BF_GET(uVmxMiscMsr, VMX_BF_MISC_PREEMPT_TIMER_TSC);
489 if (hmR0InitIntelIsSubjectToVmxPreemptTimerErratum())
490 g_HmR0.hwvirt.u.vmx.cPreemptTimerShift = 0; /* This is about right most of the time here. */
491 }
492 }
493 }
494#ifdef LOG_ENABLED
495 else
496 SUPR0Printf("hmR0InitIntelCpu failed with rc=%Rrc\n", g_HmR0.rcInit);
497#endif
498 return VINF_SUCCESS;
499}
500
501
502/**
503 * AMD-specific initialization code.
504 *
505 * @returns VBox status code (will only fail if out of memory).
506 */
507static int hmR0InitAmd(void)
508{
509 /* Call the global AMD-V initialization routine (should only fail in out-of-memory situations). */
510 int rc = SVMR0GlobalInit();
511 if (RT_FAILURE(rc))
512 {
513 g_HmR0.rcInit = rc;
514 return rc;
515 }
516
517 /*
518 * Install the AMD-V methods.
519 */
520 g_HmR0.pfnEnterSession = SVMR0Enter;
521 g_HmR0.pfnThreadCtxCallback = SVMR0ThreadCtxCallback;
522 g_HmR0.pfnCallRing3Callback = SVMR0CallRing3Callback;
523 g_HmR0.pfnExportHostState = SVMR0ExportHostState;
524 g_HmR0.pfnRunGuestCode = SVMR0RunGuestCode;
525 g_HmR0.pfnEnableCpu = SVMR0EnableCpu;
526 g_HmR0.pfnDisableCpu = SVMR0DisableCpu;
527 g_HmR0.pfnInitVM = SVMR0InitVM;
528 g_HmR0.pfnTermVM = SVMR0TermVM;
529 g_HmR0.pfnSetupVM = SVMR0SetupVM;
530
531 /* Query AMD features. */
532 uint32_t u32Dummy;
533 ASMCpuId(0x8000000a, &g_HmR0.hwvirt.u.svm.u32Rev, &g_HmR0.hwvirt.uMaxAsid, &u32Dummy, &g_HmR0.hwvirt.u.svm.u32Features);
534
535 /*
536 * We need to check if AMD-V has been properly initialized on all CPUs.
537 * Some BIOSes might do a poor job.
538 */
539 HMR0FIRSTRC FirstRc;
540 hmR0FirstRcInit(&FirstRc);
541 rc = RTMpOnAll(hmR0InitAmdCpu, &FirstRc, NULL);
542 AssertRC(rc);
543 if (RT_SUCCESS(rc))
544 rc = hmR0FirstRcGetStatus(&FirstRc);
545#ifndef DEBUG_bird
546 AssertMsg(rc == VINF_SUCCESS || rc == VERR_SVM_IN_USE,
547 ("hmR0InitAmdCpu failed for cpu %d with rc=%Rrc\n", hmR0FirstRcGetCpuId(&FirstRc), rc));
548#endif
549 if (RT_SUCCESS(rc))
550 {
551 SUPR0GetHwvirtMsrs(&g_HmR0.hwvirt.Msrs, SUPVTCAPS_AMD_V, false /* fForce */);
552 g_HmR0.hwvirt.u.svm.fSupported = true;
553 }
554 else
555 {
556 g_HmR0.rcInit = rc;
557 if (rc == VERR_SVM_DISABLED || rc == VERR_SVM_IN_USE)
558 rc = VINF_SUCCESS; /* Don't fail if AMD-V is disabled or in use. */
559 }
560 return rc;
561}
562
563
564/**
565 * Does global Ring-0 HM initialization (at module init).
566 *
567 * @returns VBox status code.
568 */
569VMMR0_INT_DECL(int) HMR0Init(void)
570{
571 /*
572 * Initialize the globals.
573 */
574 g_HmR0.fEnabled = false;
575 static RTONCE s_OnceInit = RTONCE_INITIALIZER;
576 g_HmR0.EnableAllCpusOnce = s_OnceInit;
577 for (unsigned i = 0; i < RT_ELEMENTS(g_HmR0.aCpuInfo); i++)
578 {
579 g_HmR0.aCpuInfo[i].idCpu = NIL_RTCPUID;
580 g_HmR0.aCpuInfo[i].hMemObj = NIL_RTR0MEMOBJ;
581 g_HmR0.aCpuInfo[i].HCPhysMemObj = NIL_RTHCPHYS;
582 g_HmR0.aCpuInfo[i].pvMemObj = NULL;
583#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
584 g_HmR0.aCpuInfo[i].n.svm.hNstGstMsrpm = NIL_RTR0MEMOBJ;
585 g_HmR0.aCpuInfo[i].n.svm.HCPhysNstGstMsrpm = NIL_RTHCPHYS;
586 g_HmR0.aCpuInfo[i].n.svm.pvNstGstMsrpm = NULL;
587#endif
588 }
589
590 /* Fill in all callbacks with placeholders. */
591 g_HmR0.pfnEnterSession = hmR0DummyEnter;
592 g_HmR0.pfnThreadCtxCallback = hmR0DummyThreadCtxCallback;
593 g_HmR0.pfnCallRing3Callback = hmR0DummyCallRing3Callback;
594 g_HmR0.pfnExportHostState = hmR0DummyExportHostState;
595 g_HmR0.pfnRunGuestCode = hmR0DummyRunGuestCode;
596 g_HmR0.pfnEnableCpu = hmR0DummyEnableCpu;
597 g_HmR0.pfnDisableCpu = hmR0DummyDisableCpu;
598 g_HmR0.pfnInitVM = hmR0DummyInitVM;
599 g_HmR0.pfnTermVM = hmR0DummyTermVM;
600 g_HmR0.pfnSetupVM = hmR0DummySetupVM;
601
602 /* Default is global VT-x/AMD-V init. */
603 g_HmR0.fGlobalInit = true;
604
605 /*
606 * Make sure aCpuInfo is big enough for all the CPUs on this system.
607 */
608 if (RTMpGetArraySize() > RT_ELEMENTS(g_HmR0.aCpuInfo))
609 {
610 LogRel(("HM: Too many real CPUs/cores/threads - %u, max %u\n", RTMpGetArraySize(), RT_ELEMENTS(g_HmR0.aCpuInfo)));
611 return VERR_TOO_MANY_CPUS;
612 }
613
614 /*
615 * Check for VT-x or AMD-V support.
616 * Return failure only in out-of-memory situations.
617 */
618 uint32_t fCaps = 0;
619 int rc = SUPR0GetVTSupport(&fCaps);
620 if (RT_SUCCESS(rc))
621 {
622 if (fCaps & SUPVTCAPS_VT_X)
623 {
624 rc = hmR0InitIntel();
625 if (RT_FAILURE(rc))
626 return rc;
627 }
628 else
629 {
630 Assert(fCaps & SUPVTCAPS_AMD_V);
631 rc = hmR0InitAmd();
632 if (RT_FAILURE(rc))
633 return rc;
634 }
635 }
636 else
637 g_HmR0.rcInit = VERR_UNSUPPORTED_CPU;
638
639 /*
640 * Register notification callbacks that we can use to disable/enable CPUs
641 * when brought offline/online or suspending/resuming.
642 */
643 if (!g_HmR0.hwvirt.u.vmx.fUsingSUPR0EnableVTx)
644 {
645 rc = RTMpNotificationRegister(hmR0MpEventCallback, NULL);
646 AssertRC(rc);
647
648 rc = RTPowerNotificationRegister(hmR0PowerCallback, NULL);
649 AssertRC(rc);
650 }
651
652 /* We return success here because module init shall not fail if HM fails to initialize. */
653 return VINF_SUCCESS;
654}
655
656
657/**
658 * Does global Ring-0 HM termination (at module termination).
659 *
660 * @returns VBox status code.
661 */
662VMMR0_INT_DECL(int) HMR0Term(void)
663{
664 int rc;
665 if ( g_HmR0.hwvirt.u.vmx.fSupported
666 && g_HmR0.hwvirt.u.vmx.fUsingSUPR0EnableVTx)
667 {
668 /*
669 * Simple if the host OS manages VT-x.
670 */
671 Assert(g_HmR0.fGlobalInit);
672
673 if (g_HmR0.hwvirt.u.vmx.fCalledSUPR0EnableVTx)
674 {
675 rc = SUPR0EnableVTx(false /* fEnable */);
676 g_HmR0.hwvirt.u.vmx.fCalledSUPR0EnableVTx = false;
677 }
678 else
679 rc = VINF_SUCCESS;
680
681 for (unsigned iCpu = 0; iCpu < RT_ELEMENTS(g_HmR0.aCpuInfo); iCpu++)
682 {
683 g_HmR0.aCpuInfo[iCpu].fConfigured = false;
684 Assert(g_HmR0.aCpuInfo[iCpu].hMemObj == NIL_RTR0MEMOBJ);
685 }
686 }
687 else
688 {
689 Assert(!g_HmR0.hwvirt.u.vmx.fSupported || !g_HmR0.hwvirt.u.vmx.fUsingSUPR0EnableVTx);
690
691 /* Doesn't really matter if this fails. */
692 rc = RTMpNotificationDeregister(hmR0MpEventCallback, NULL); AssertRC(rc);
693 rc = RTPowerNotificationDeregister(hmR0PowerCallback, NULL); AssertRC(rc);
694
695 /*
696 * Disable VT-x/AMD-V on all CPUs if we enabled it before.
697 */
698 if (g_HmR0.fGlobalInit)
699 {
700 HMR0FIRSTRC FirstRc;
701 hmR0FirstRcInit(&FirstRc);
702 rc = RTMpOnAll(hmR0DisableCpuCallback, NULL /* pvUser 1 */, &FirstRc);
703 Assert(RT_SUCCESS(rc) || rc == VERR_NOT_SUPPORTED);
704 if (RT_SUCCESS(rc))
705 rc = hmR0FirstRcGetStatus(&FirstRc);
706 }
707
708 /*
709 * Free the per-cpu pages used for VT-x and AMD-V.
710 */
711 for (unsigned i = 0; i < RT_ELEMENTS(g_HmR0.aCpuInfo); i++)
712 {
713 if (g_HmR0.aCpuInfo[i].hMemObj != NIL_RTR0MEMOBJ)
714 {
715 RTR0MemObjFree(g_HmR0.aCpuInfo[i].hMemObj, false);
716 g_HmR0.aCpuInfo[i].hMemObj = NIL_RTR0MEMOBJ;
717 g_HmR0.aCpuInfo[i].HCPhysMemObj = NIL_RTHCPHYS;
718 g_HmR0.aCpuInfo[i].pvMemObj = NULL;
719 }
720#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
721 if (g_HmR0.aCpuInfo[i].n.svm.hNstGstMsrpm != NIL_RTR0MEMOBJ)
722 {
723 RTR0MemObjFree(g_HmR0.aCpuInfo[i].n.svm.hNstGstMsrpm, false);
724 g_HmR0.aCpuInfo[i].n.svm.hNstGstMsrpm = NIL_RTR0MEMOBJ;
725 g_HmR0.aCpuInfo[i].n.svm.HCPhysNstGstMsrpm = NIL_RTHCPHYS;
726 g_HmR0.aCpuInfo[i].n.svm.pvNstGstMsrpm = NULL;
727 }
728#endif
729 }
730 }
731
732 /** @todo This needs cleaning up. There's no matching
733 * hmR0TermIntel()/hmR0TermAmd() and all the VT-x/AMD-V specific bits
734 * should move into their respective modules. */
735 /* Finally, call global VT-x/AMD-V termination. */
736 if (g_HmR0.hwvirt.u.vmx.fSupported)
737 VMXR0GlobalTerm();
738 else if (g_HmR0.hwvirt.u.svm.fSupported)
739 SVMR0GlobalTerm();
740
741 return rc;
742}
743
744
745/**
746 * Worker function used by hmR0PowerCallback() and HMR0Init() to initalize VT-x
747 * on a CPU.
748 *
749 * @param idCpu The identifier for the CPU the function is called on.
750 * @param pvUser1 Pointer to the first RC structure.
751 * @param pvUser2 Ignored.
752 */
753static DECLCALLBACK(void) hmR0InitIntelCpu(RTCPUID idCpu, void *pvUser1, void *pvUser2)
754{
755 PHMR0FIRSTRC pFirstRc = (PHMR0FIRSTRC)pvUser1;
756 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
757 Assert(idCpu == (RTCPUID)RTMpCpuIdToSetIndex(idCpu)); /** @todo fix idCpu == index assumption (rainy day) */
758 NOREF(idCpu); NOREF(pvUser2);
759
760 int rc = SUPR0GetVmxUsability(NULL /* pfIsSmxModeAmbiguous */);
761 hmR0FirstRcSetStatus(pFirstRc, rc);
762}
763
764
765/**
766 * Worker function used by hmR0PowerCallback() and HMR0Init() to initalize AMD-V
767 * on a CPU.
768 *
769 * @param idCpu The identifier for the CPU the function is called on.
770 * @param pvUser1 Pointer to the first RC structure.
771 * @param pvUser2 Ignored.
772 */
773static DECLCALLBACK(void) hmR0InitAmdCpu(RTCPUID idCpu, void *pvUser1, void *pvUser2)
774{
775 PHMR0FIRSTRC pFirstRc = (PHMR0FIRSTRC)pvUser1;
776 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
777 Assert(idCpu == (RTCPUID)RTMpCpuIdToSetIndex(idCpu)); /** @todo fix idCpu == index assumption (rainy day) */
778 NOREF(idCpu); NOREF(pvUser2);
779
780 int rc = SUPR0GetSvmUsability(true /* fInitSvm */);
781 hmR0FirstRcSetStatus(pFirstRc, rc);
782}
783
784
785/**
786 * Enable VT-x or AMD-V on the current CPU
787 *
788 * @returns VBox status code.
789 * @param pVM The cross context VM structure. Can be NULL.
790 * @param idCpu The identifier for the CPU the function is called on.
791 *
792 * @remarks Maybe called with interrupts disabled!
793 */
794static int hmR0EnableCpu(PVMCC pVM, RTCPUID idCpu)
795{
796 PHMPHYSCPU pHostCpu = &g_HmR0.aCpuInfo[idCpu];
797
798 Assert(idCpu == (RTCPUID)RTMpCpuIdToSetIndex(idCpu)); /** @todo fix idCpu == index assumption (rainy day) */
799 Assert(idCpu < RT_ELEMENTS(g_HmR0.aCpuInfo));
800 Assert(!pHostCpu->fConfigured);
801 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
802
803 pHostCpu->idCpu = idCpu;
804 /* Do NOT reset cTlbFlushes here, see @bugref{6255}. */
805
806 int rc;
807 if ( g_HmR0.hwvirt.u.vmx.fSupported
808 && g_HmR0.hwvirt.u.vmx.fUsingSUPR0EnableVTx)
809 rc = g_HmR0.pfnEnableCpu(pHostCpu, pVM, NULL /* pvCpuPage */, NIL_RTHCPHYS, true, &g_HmR0.hwvirt.Msrs);
810 else
811 {
812 AssertLogRelMsgReturn(pHostCpu->hMemObj != NIL_RTR0MEMOBJ, ("hmR0EnableCpu failed idCpu=%u.\n", idCpu), VERR_HM_IPE_1);
813 rc = g_HmR0.pfnEnableCpu(pHostCpu, pVM, pHostCpu->pvMemObj, pHostCpu->HCPhysMemObj, false, &g_HmR0.hwvirt.Msrs);
814 }
815 if (RT_SUCCESS(rc))
816 pHostCpu->fConfigured = true;
817 return rc;
818}
819
820
821/**
822 * Worker function passed to RTMpOnAll() that is to be called on all CPUs.
823 *
824 * @param idCpu The identifier for the CPU the function is called on.
825 * @param pvUser1 Opaque pointer to the VM (can be NULL!).
826 * @param pvUser2 The 2nd user argument.
827 */
828static DECLCALLBACK(void) hmR0EnableCpuCallback(RTCPUID idCpu, void *pvUser1, void *pvUser2)
829{
830 PVMCC pVM = (PVMCC)pvUser1; /* can be NULL! */
831 PHMR0FIRSTRC pFirstRc = (PHMR0FIRSTRC)pvUser2;
832 AssertReturnVoid(g_HmR0.fGlobalInit);
833 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
834 hmR0FirstRcSetStatus(pFirstRc, hmR0EnableCpu(pVM, idCpu));
835}
836
837
838/**
839 * RTOnce callback employed by HMR0EnableAllCpus.
840 *
841 * @returns VBox status code.
842 * @param pvUser Pointer to the VM.
843 */
844static DECLCALLBACK(int32_t) hmR0EnableAllCpuOnce(void *pvUser)
845{
846 PVMCC pVM = (PVMCC)pvUser;
847
848 /*
849 * Indicate that we've initialized.
850 *
851 * Note! There is a potential race between this function and the suspend
852 * notification. Kind of unlikely though, so ignored for now.
853 */
854 AssertReturn(!g_HmR0.fEnabled, VERR_HM_ALREADY_ENABLED_IPE);
855 ASMAtomicWriteBool(&g_HmR0.fEnabled, true);
856
857 /*
858 * The global init variable is set by the first VM.
859 */
860 g_HmR0.fGlobalInit = pVM->hm.s.fGlobalInit;
861
862#ifdef VBOX_STRICT
863 for (unsigned i = 0; i < RT_ELEMENTS(g_HmR0.aCpuInfo); i++)
864 {
865 Assert(g_HmR0.aCpuInfo[i].hMemObj == NIL_RTR0MEMOBJ);
866 Assert(g_HmR0.aCpuInfo[i].HCPhysMemObj == NIL_RTHCPHYS);
867 Assert(g_HmR0.aCpuInfo[i].pvMemObj == NULL);
868 Assert(!g_HmR0.aCpuInfo[i].fConfigured);
869 Assert(!g_HmR0.aCpuInfo[i].cTlbFlushes);
870 Assert(!g_HmR0.aCpuInfo[i].uCurrentAsid);
871# ifdef VBOX_WITH_NESTED_HWVIRT_SVM
872 Assert(g_HmR0.aCpuInfo[i].n.svm.hNstGstMsrpm == NIL_RTR0MEMOBJ);
873 Assert(g_HmR0.aCpuInfo[i].n.svm.HCPhysNstGstMsrpm == NIL_RTHCPHYS);
874 Assert(g_HmR0.aCpuInfo[i].n.svm.pvNstGstMsrpm == NULL);
875# endif
876 }
877#endif
878
879 int rc;
880 if ( g_HmR0.hwvirt.u.vmx.fSupported
881 && g_HmR0.hwvirt.u.vmx.fUsingSUPR0EnableVTx)
882 {
883 /*
884 * Global VT-x initialization API (only darwin for now).
885 */
886 rc = SUPR0EnableVTx(true /* fEnable */);
887 if (RT_SUCCESS(rc))
888 {
889 g_HmR0.hwvirt.u.vmx.fCalledSUPR0EnableVTx = true;
890 /* If the host provides a VT-x init API, then we'll rely on that for global init. */
891 g_HmR0.fGlobalInit = pVM->hm.s.fGlobalInit = true;
892 }
893 else
894 AssertMsgFailed(("hmR0EnableAllCpuOnce/SUPR0EnableVTx: rc=%Rrc\n", rc));
895 }
896 else
897 {
898 /*
899 * We're doing the job ourselves.
900 */
901 /* Allocate one page per cpu for the global VT-x and AMD-V pages */
902 for (unsigned i = 0; i < RT_ELEMENTS(g_HmR0.aCpuInfo); i++)
903 {
904 Assert(g_HmR0.aCpuInfo[i].hMemObj == NIL_RTR0MEMOBJ);
905#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
906 Assert(g_HmR0.aCpuInfo[i].n.svm.hNstGstMsrpm == NIL_RTR0MEMOBJ);
907#endif
908 if (RTMpIsCpuPossible(RTMpCpuIdFromSetIndex(i)))
909 {
910 /** @todo NUMA */
911 rc = RTR0MemObjAllocCont(&g_HmR0.aCpuInfo[i].hMemObj, PAGE_SIZE, false /* executable R0 mapping */);
912 AssertLogRelRCReturn(rc, rc);
913
914 g_HmR0.aCpuInfo[i].HCPhysMemObj = RTR0MemObjGetPagePhysAddr(g_HmR0.aCpuInfo[i].hMemObj, 0);
915 Assert(g_HmR0.aCpuInfo[i].HCPhysMemObj != NIL_RTHCPHYS);
916 Assert(!(g_HmR0.aCpuInfo[i].HCPhysMemObj & PAGE_OFFSET_MASK));
917
918 g_HmR0.aCpuInfo[i].pvMemObj = RTR0MemObjAddress(g_HmR0.aCpuInfo[i].hMemObj);
919 AssertPtr(g_HmR0.aCpuInfo[i].pvMemObj);
920 ASMMemZeroPage(g_HmR0.aCpuInfo[i].pvMemObj);
921
922#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
923 rc = RTR0MemObjAllocCont(&g_HmR0.aCpuInfo[i].n.svm.hNstGstMsrpm, SVM_MSRPM_PAGES << X86_PAGE_4K_SHIFT,
924 false /* executable R0 mapping */);
925 AssertLogRelRCReturn(rc, rc);
926
927 g_HmR0.aCpuInfo[i].n.svm.HCPhysNstGstMsrpm = RTR0MemObjGetPagePhysAddr(g_HmR0.aCpuInfo[i].n.svm.hNstGstMsrpm, 0);
928 Assert(g_HmR0.aCpuInfo[i].n.svm.HCPhysNstGstMsrpm != NIL_RTHCPHYS);
929 Assert(!(g_HmR0.aCpuInfo[i].n.svm.HCPhysNstGstMsrpm & PAGE_OFFSET_MASK));
930
931 g_HmR0.aCpuInfo[i].n.svm.pvNstGstMsrpm = RTR0MemObjAddress(g_HmR0.aCpuInfo[i].n.svm.hNstGstMsrpm);
932 AssertPtr(g_HmR0.aCpuInfo[i].n.svm.pvNstGstMsrpm);
933 ASMMemFill32(g_HmR0.aCpuInfo[i].n.svm.pvNstGstMsrpm, SVM_MSRPM_PAGES << X86_PAGE_4K_SHIFT, UINT32_C(0xffffffff));
934#endif
935 }
936 }
937
938 rc = VINF_SUCCESS;
939 }
940
941 if ( RT_SUCCESS(rc)
942 && g_HmR0.fGlobalInit)
943 {
944 /* First time, so initialize each cpu/core. */
945 HMR0FIRSTRC FirstRc;
946 hmR0FirstRcInit(&FirstRc);
947 rc = RTMpOnAll(hmR0EnableCpuCallback, (void *)pVM, &FirstRc);
948 if (RT_SUCCESS(rc))
949 rc = hmR0FirstRcGetStatus(&FirstRc);
950 }
951
952 return rc;
953}
954
955
956/**
957 * Sets up HM on all cpus.
958 *
959 * @returns VBox status code.
960 * @param pVM The cross context VM structure.
961 */
962VMMR0_INT_DECL(int) HMR0EnableAllCpus(PVMCC pVM)
963{
964 /* Make sure we don't touch HM after we've disabled HM in preparation of a suspend. */
965 if (ASMAtomicReadBool(&g_HmR0.fSuspended))
966 return VERR_HM_SUSPEND_PENDING;
967
968 return RTOnce(&g_HmR0.EnableAllCpusOnce, hmR0EnableAllCpuOnce, pVM);
969}
970
971
972/**
973 * Disable VT-x or AMD-V on the current CPU.
974 *
975 * @returns VBox status code.
976 * @param idCpu The identifier for the CPU this function is called on.
977 *
978 * @remarks Must be called with preemption disabled.
979 */
980static int hmR0DisableCpu(RTCPUID idCpu)
981{
982 PHMPHYSCPU pHostCpu = &g_HmR0.aCpuInfo[idCpu];
983
984 Assert(!g_HmR0.hwvirt.u.vmx.fSupported || !g_HmR0.hwvirt.u.vmx.fUsingSUPR0EnableVTx);
985 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
986 Assert(idCpu == (RTCPUID)RTMpCpuIdToSetIndex(idCpu)); /** @todo fix idCpu == index assumption (rainy day) */
987 Assert(idCpu < RT_ELEMENTS(g_HmR0.aCpuInfo));
988 Assert(!pHostCpu->fConfigured || pHostCpu->hMemObj != NIL_RTR0MEMOBJ);
989 AssertRelease(idCpu == RTMpCpuId());
990
991 if (pHostCpu->hMemObj == NIL_RTR0MEMOBJ)
992 return pHostCpu->fConfigured ? VERR_NO_MEMORY : VINF_SUCCESS /* not initialized. */;
993 AssertPtr(pHostCpu->pvMemObj);
994 Assert(pHostCpu->HCPhysMemObj != NIL_RTHCPHYS);
995
996 int rc;
997 if (pHostCpu->fConfigured)
998 {
999 rc = g_HmR0.pfnDisableCpu(pHostCpu->pvMemObj, pHostCpu->HCPhysMemObj);
1000 AssertRCReturn(rc, rc);
1001
1002 pHostCpu->fConfigured = false;
1003 pHostCpu->idCpu = NIL_RTCPUID;
1004 }
1005 else
1006 rc = VINF_SUCCESS; /* nothing to do */
1007 return rc;
1008}
1009
1010
1011/**
1012 * Worker function passed to RTMpOnAll() that is to be called on the target
1013 * CPUs.
1014 *
1015 * @param idCpu The identifier for the CPU the function is called on.
1016 * @param pvUser1 The 1st user argument.
1017 * @param pvUser2 Opaque pointer to the FirstRc.
1018 */
1019static DECLCALLBACK(void) hmR0DisableCpuCallback(RTCPUID idCpu, void *pvUser1, void *pvUser2)
1020{
1021 PHMR0FIRSTRC pFirstRc = (PHMR0FIRSTRC)pvUser2; NOREF(pvUser1);
1022 AssertReturnVoid(g_HmR0.fGlobalInit);
1023 hmR0FirstRcSetStatus(pFirstRc, hmR0DisableCpu(idCpu));
1024}
1025
1026
1027/**
1028 * Worker function passed to RTMpOnSpecific() that is to be called on the target
1029 * CPU.
1030 *
1031 * @param idCpu The identifier for the CPU the function is called on.
1032 * @param pvUser1 Null, not used.
1033 * @param pvUser2 Null, not used.
1034 */
1035static DECLCALLBACK(void) hmR0DisableCpuOnSpecificCallback(RTCPUID idCpu, void *pvUser1, void *pvUser2)
1036{
1037 NOREF(pvUser1);
1038 NOREF(pvUser2);
1039 hmR0DisableCpu(idCpu);
1040}
1041
1042
1043/**
1044 * Callback function invoked when a cpu goes online or offline.
1045 *
1046 * @param enmEvent The Mp event.
1047 * @param idCpu The identifier for the CPU the function is called on.
1048 * @param pvData Opaque data (PVMCC pointer).
1049 */
1050static DECLCALLBACK(void) hmR0MpEventCallback(RTMPEVENT enmEvent, RTCPUID idCpu, void *pvData)
1051{
1052 NOREF(pvData);
1053 Assert(!g_HmR0.hwvirt.u.vmx.fSupported || !g_HmR0.hwvirt.u.vmx.fUsingSUPR0EnableVTx);
1054
1055 /*
1056 * We only care about uninitializing a CPU that is going offline. When a
1057 * CPU comes online, the initialization is done lazily in HMR0Enter().
1058 */
1059 switch (enmEvent)
1060 {
1061 case RTMPEVENT_OFFLINE:
1062 {
1063 RTTHREADPREEMPTSTATE PreemptState = RTTHREADPREEMPTSTATE_INITIALIZER;
1064 RTThreadPreemptDisable(&PreemptState);
1065 if (idCpu == RTMpCpuId())
1066 {
1067 int rc = hmR0DisableCpu(idCpu);
1068 AssertRC(rc);
1069 RTThreadPreemptRestore(&PreemptState);
1070 }
1071 else
1072 {
1073 RTThreadPreemptRestore(&PreemptState);
1074 RTMpOnSpecific(idCpu, hmR0DisableCpuOnSpecificCallback, NULL /* pvUser1 */, NULL /* pvUser2 */);
1075 }
1076 break;
1077 }
1078
1079 default:
1080 break;
1081 }
1082}
1083
1084
1085/**
1086 * Called whenever a system power state change occurs.
1087 *
1088 * @param enmEvent The Power event.
1089 * @param pvUser User argument.
1090 */
1091static DECLCALLBACK(void) hmR0PowerCallback(RTPOWEREVENT enmEvent, void *pvUser)
1092{
1093 NOREF(pvUser);
1094 Assert(!g_HmR0.hwvirt.u.vmx.fSupported || !g_HmR0.hwvirt.u.vmx.fUsingSUPR0EnableVTx);
1095
1096#ifdef LOG_ENABLED
1097 if (enmEvent == RTPOWEREVENT_SUSPEND)
1098 SUPR0Printf("hmR0PowerCallback RTPOWEREVENT_SUSPEND\n");
1099 else
1100 SUPR0Printf("hmR0PowerCallback RTPOWEREVENT_RESUME\n");
1101#endif
1102
1103 if (enmEvent == RTPOWEREVENT_SUSPEND)
1104 ASMAtomicWriteBool(&g_HmR0.fSuspended, true);
1105
1106 if (g_HmR0.fEnabled)
1107 {
1108 int rc;
1109 HMR0FIRSTRC FirstRc;
1110 hmR0FirstRcInit(&FirstRc);
1111
1112 if (enmEvent == RTPOWEREVENT_SUSPEND)
1113 {
1114 if (g_HmR0.fGlobalInit)
1115 {
1116 /* Turn off VT-x or AMD-V on all CPUs. */
1117 rc = RTMpOnAll(hmR0DisableCpuCallback, NULL /* pvUser 1 */, &FirstRc);
1118 Assert(RT_SUCCESS(rc) || rc == VERR_NOT_SUPPORTED);
1119 }
1120 /* else nothing to do here for the local init case */
1121 }
1122 else
1123 {
1124 /* Reinit the CPUs from scratch as the suspend state might have
1125 messed with the MSRs. (lousy BIOSes as usual) */
1126 if (g_HmR0.hwvirt.u.vmx.fSupported)
1127 rc = RTMpOnAll(hmR0InitIntelCpu, &FirstRc, NULL);
1128 else
1129 rc = RTMpOnAll(hmR0InitAmdCpu, &FirstRc, NULL);
1130 Assert(RT_SUCCESS(rc) || rc == VERR_NOT_SUPPORTED);
1131 if (RT_SUCCESS(rc))
1132 rc = hmR0FirstRcGetStatus(&FirstRc);
1133#ifdef LOG_ENABLED
1134 if (RT_FAILURE(rc))
1135 SUPR0Printf("hmR0PowerCallback hmR0InitXxxCpu failed with %Rc\n", rc);
1136#endif
1137 if (g_HmR0.fGlobalInit)
1138 {
1139 /* Turn VT-x or AMD-V back on on all CPUs. */
1140 rc = RTMpOnAll(hmR0EnableCpuCallback, NULL /* pVM */, &FirstRc /* output ignored */);
1141 Assert(RT_SUCCESS(rc) || rc == VERR_NOT_SUPPORTED);
1142 }
1143 /* else nothing to do here for the local init case */
1144 }
1145 }
1146
1147 if (enmEvent == RTPOWEREVENT_RESUME)
1148 ASMAtomicWriteBool(&g_HmR0.fSuspended, false);
1149}
1150
1151
1152/**
1153 * Does ring-0 per-VM HM initialization.
1154 *
1155 * This will call the CPU specific init. routine which may initialize and allocate
1156 * resources for virtual CPUs.
1157 *
1158 * @returns VBox status code.
1159 * @param pVM The cross context VM structure.
1160 *
1161 * @remarks This is called after HMR3Init(), see vmR3CreateU() and
1162 * vmR3InitRing3().
1163 */
1164VMMR0_INT_DECL(int) HMR0InitVM(PVMCC pVM)
1165{
1166 AssertReturn(pVM, VERR_INVALID_PARAMETER);
1167
1168 /* Make sure we don't touch HM after we've disabled HM in preparation of a suspend. */
1169 if (ASMAtomicReadBool(&g_HmR0.fSuspended))
1170 return VERR_HM_SUSPEND_PENDING;
1171
1172 /*
1173 * Copy globals to the VM structure.
1174 */
1175 Assert(!(pVM->hm.s.vmx.fSupported && pVM->hm.s.svm.fSupported));
1176 if (pVM->hm.s.vmx.fSupported)
1177 {
1178 pVM->hm.s.vmx.fUsePreemptTimer &= g_HmR0.hwvirt.u.vmx.fUsePreemptTimer; /* Can be overridden by CFGM in HMR3Init(). */
1179 pVM->hm.s.vmx.cPreemptTimerShift = g_HmR0.hwvirt.u.vmx.cPreemptTimerShift;
1180 pVM->hm.s.vmx.u64HostCr4 = g_HmR0.hwvirt.u.vmx.u64HostCr4;
1181 pVM->hm.s.vmx.u64HostMsrEfer = g_HmR0.hwvirt.u.vmx.u64HostMsrEfer;
1182 pVM->hm.s.vmx.u64HostSmmMonitorCtl = g_HmR0.hwvirt.u.vmx.u64HostSmmMonitorCtl;
1183 HMGetVmxMsrsFromHwvirtMsrs(&g_HmR0.hwvirt.Msrs, &pVM->hm.s.vmx.Msrs);
1184 /* If you need to tweak host MSRs for testing VMX R0 code, do it here. */
1185
1186 /* Enable VPID if supported and configured. */
1187 if (pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_VPID)
1188 pVM->hm.s.vmx.fVpid = pVM->hm.s.vmx.fAllowVpid; /* Can be overridden by CFGM in HMR3Init(). */
1189
1190 /* Use VMCS shadowing if supported. */
1191 Assert(!pVM->hm.s.vmx.fUseVmcsShadowing);
1192 if ( pVM->cpum.ro.GuestFeatures.fVmx
1193 && (pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_VMCS_SHADOWING))
1194 pVM->hm.s.vmx.fUseVmcsShadowing = true;
1195
1196 /* Use the VMCS controls for swapping the EFER MSR if supported. */
1197 Assert(!pVM->hm.s.vmx.fSupportsVmcsEfer);
1198 if ( (pVM->hm.s.vmx.Msrs.EntryCtls.n.allowed1 & VMX_ENTRY_CTLS_LOAD_EFER_MSR)
1199 && (pVM->hm.s.vmx.Msrs.ExitCtls.n.allowed1 & VMX_EXIT_CTLS_LOAD_EFER_MSR)
1200 && (pVM->hm.s.vmx.Msrs.ExitCtls.n.allowed1 & VMX_EXIT_CTLS_SAVE_EFER_MSR))
1201 pVM->hm.s.vmx.fSupportsVmcsEfer = true;
1202
1203#if 0
1204 /* Enable APIC register virtualization and virtual-interrupt delivery if supported. */
1205 if ( (pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_APIC_REG_VIRT)
1206 && (pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_VIRT_INTR_DELIVERY))
1207 pVM->hm.s.fVirtApicRegs = true;
1208
1209 /* Enable posted-interrupt processing if supported. */
1210 /** @todo Add and query IPRT API for host OS support for posted-interrupt IPI
1211 * here. */
1212 if ( (pVM->hm.s.vmx.Msrs.PinCtls.n.allowed1 & VMX_PIN_CTLS_POSTED_INT)
1213 && (pVM->hm.s.vmx.Msrs.ExitCtls.n.allowed1 & VMX_EXIT_CTLS_ACK_EXT_INT))
1214 pVM->hm.s.fPostedIntrs = true;
1215#endif
1216 }
1217 else if (pVM->hm.s.svm.fSupported)
1218 {
1219 pVM->hm.s.svm.u32Rev = g_HmR0.hwvirt.u.svm.u32Rev;
1220 pVM->hm.s.svm.u32Features = g_HmR0.hwvirt.u.svm.u32Features;
1221 pVM->hm.s.svm.u64MsrHwcr = g_HmR0.hwvirt.Msrs.u.svm.u64MsrHwcr;
1222 /* If you need to tweak host MSRs for testing SVM R0 code, do it here. */
1223 }
1224 pVM->hm.s.rcInit = g_HmR0.rcInit;
1225 pVM->hm.s.uMaxAsid = g_HmR0.hwvirt.uMaxAsid;
1226
1227 /*
1228 * Set default maximum inner loops in ring-0 before returning to ring-3.
1229 * Can be overriden using CFGM.
1230 */
1231 if (!pVM->hm.s.cMaxResumeLoops)
1232 {
1233 pVM->hm.s.cMaxResumeLoops = 1024;
1234 if (RTThreadPreemptIsPendingTrusty())
1235 pVM->hm.s.cMaxResumeLoops = 8192;
1236 }
1237
1238 /*
1239 * Initialize some per-VCPU fields.
1240 */
1241 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
1242 {
1243 PVMCPUCC pVCpu = VMCC_GET_CPU(pVM, idCpu);
1244 pVCpu->hm.s.idEnteredCpu = NIL_RTCPUID;
1245 pVCpu->hm.s.idLastCpu = NIL_RTCPUID;
1246
1247 /* We'll aways increment this the first time (host uses ASID 0). */
1248 AssertReturn(!pVCpu->hm.s.uCurrentAsid, VERR_HM_IPE_3);
1249 }
1250
1251 /*
1252 * Get host kernel features that HM might need to know in order
1253 * to co-operate and function properly with the host OS (e.g. SMAP).
1254 *
1255 * Technically, we could do this as part of the pre-init VM procedure
1256 * but it shouldn't be done later than this point so we do it here.
1257 */
1258 pVM->hm.s.fHostKernelFeatures = SUPR0GetKernelFeatures();
1259
1260 /*
1261 * Call the hardware specific initialization method.
1262 */
1263 return g_HmR0.pfnInitVM(pVM);
1264}
1265
1266
1267/**
1268 * Does ring-0 per VM HM termination.
1269 *
1270 * @returns VBox status code.
1271 * @param pVM The cross context VM structure.
1272 */
1273VMMR0_INT_DECL(int) HMR0TermVM(PVMCC pVM)
1274{
1275 Log(("HMR0TermVM: %p\n", pVM));
1276 AssertReturn(pVM, VERR_INVALID_PARAMETER);
1277
1278 /*
1279 * Call the hardware specific method.
1280 *
1281 * Note! We might be preparing for a suspend, so the pfnTermVM() functions should probably not
1282 * mess with VT-x/AMD-V features on the CPU, currently all they do is free memory so this is safe.
1283 */
1284 return g_HmR0.pfnTermVM(pVM);
1285}
1286
1287
1288/**
1289 * Sets up a VT-x or AMD-V session.
1290 *
1291 * This is mostly about setting up the hardware VM state.
1292 *
1293 * @returns VBox status code.
1294 * @param pVM The cross context VM structure.
1295 */
1296VMMR0_INT_DECL(int) HMR0SetupVM(PVMCC pVM)
1297{
1298 Log(("HMR0SetupVM: %p\n", pVM));
1299 AssertReturn(pVM, VERR_INVALID_PARAMETER);
1300
1301 /* Make sure we don't touch HM after we've disabled HM in preparation of a suspend. */
1302 AssertReturn(!ASMAtomicReadBool(&g_HmR0.fSuspended), VERR_HM_SUSPEND_PENDING);
1303
1304 /* On first entry we'll sync everything. */
1305 VMCC_FOR_EACH_VMCPU_STMT(pVM, pVCpu->hm.s.fCtxChanged |= HM_CHANGED_HOST_CONTEXT | HM_CHANGED_ALL_GUEST);
1306
1307 /*
1308 * Call the hardware specific setup VM method. This requires the CPU to be
1309 * enabled for AMD-V/VT-x and preemption to be prevented.
1310 */
1311 RTTHREADPREEMPTSTATE PreemptState = RTTHREADPREEMPTSTATE_INITIALIZER;
1312 RTThreadPreemptDisable(&PreemptState);
1313 RTCPUID const idCpu = RTMpCpuId();
1314
1315 /* Enable VT-x or AMD-V if local init is required. */
1316 int rc;
1317 if (!g_HmR0.fGlobalInit)
1318 {
1319 Assert(!g_HmR0.hwvirt.u.vmx.fSupported || !g_HmR0.hwvirt.u.vmx.fUsingSUPR0EnableVTx);
1320 rc = hmR0EnableCpu(pVM, idCpu);
1321 if (RT_FAILURE(rc))
1322 {
1323 RTThreadPreemptRestore(&PreemptState);
1324 return rc;
1325 }
1326 }
1327
1328 /* Setup VT-x or AMD-V. */
1329 rc = g_HmR0.pfnSetupVM(pVM);
1330
1331 /* Disable VT-x or AMD-V if local init was done before. */
1332 if (!g_HmR0.fGlobalInit)
1333 {
1334 Assert(!g_HmR0.hwvirt.u.vmx.fSupported || !g_HmR0.hwvirt.u.vmx.fUsingSUPR0EnableVTx);
1335 int rc2 = hmR0DisableCpu(idCpu);
1336 AssertRC(rc2);
1337 }
1338
1339 RTThreadPreemptRestore(&PreemptState);
1340 return rc;
1341}
1342
1343
1344/**
1345 * Notification callback before performing a longjump to ring-3.
1346 *
1347 * @returns VBox status code.
1348 * @param pVCpu The cross context virtual CPU structure.
1349 * @param enmOperation The operation causing the ring-3 longjump.
1350 * @param pvUser User argument, currently unused, NULL.
1351 */
1352static DECLCALLBACK(int) hmR0CallRing3Callback(PVMCPUCC pVCpu, VMMCALLRING3 enmOperation, void *pvUser)
1353{
1354 RT_NOREF(pvUser);
1355 Assert(pVCpu);
1356 Assert(g_HmR0.pfnCallRing3Callback);
1357 return g_HmR0.pfnCallRing3Callback(pVCpu, enmOperation);
1358}
1359
1360
1361/**
1362 * Turns on HM on the CPU if necessary and initializes the bare minimum state
1363 * required for entering HM context.
1364 *
1365 * @returns VBox status code.
1366 * @param pVCpu The cross context virtual CPU structure.
1367 *
1368 * @remarks No-long-jump zone!!!
1369 */
1370VMMR0_INT_DECL(int) hmR0EnterCpu(PVMCPUCC pVCpu)
1371{
1372 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1373
1374 int rc = VINF_SUCCESS;
1375 RTCPUID const idCpu = RTMpCpuId();
1376 PHMPHYSCPU pHostCpu = &g_HmR0.aCpuInfo[idCpu];
1377 AssertPtr(pHostCpu);
1378
1379 /* Enable VT-x or AMD-V if local init is required, or enable if it's a freshly onlined CPU. */
1380 if (!pHostCpu->fConfigured)
1381 rc = hmR0EnableCpu(pVCpu->CTX_SUFF(pVM), idCpu);
1382
1383 /* Register a callback to fire prior to performing a longjmp to ring-3 so HM can disable VT-x/AMD-V if needed. */
1384 VMMRZCallRing3SetNotification(pVCpu, hmR0CallRing3Callback, NULL /* pvUser */);
1385
1386 /* Reload host-state (back from ring-3/migrated CPUs) and shared guest/host bits. */
1387 if (g_HmR0.hwvirt.u.vmx.fSupported)
1388 pVCpu->hm.s.fCtxChanged |= HM_CHANGED_HOST_CONTEXT | HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE;
1389 else
1390 pVCpu->hm.s.fCtxChanged |= HM_CHANGED_HOST_CONTEXT | HM_CHANGED_SVM_HOST_GUEST_SHARED_STATE;
1391
1392 Assert(pHostCpu->idCpu == idCpu && pHostCpu->idCpu != NIL_RTCPUID);
1393 pVCpu->hm.s.idEnteredCpu = idCpu;
1394 return rc;
1395}
1396
1397
1398/**
1399 * Enters the VT-x or AMD-V session.
1400 *
1401 * @returns VBox status code.
1402 * @param pVCpu The cross context virtual CPU structure.
1403 *
1404 * @remarks This is called with preemption disabled.
1405 */
1406VMMR0_INT_DECL(int) HMR0Enter(PVMCPUCC pVCpu)
1407{
1408 /* Make sure we can't enter a session after we've disabled HM in preparation of a suspend. */
1409 AssertReturn(!ASMAtomicReadBool(&g_HmR0.fSuspended), VERR_HM_SUSPEND_PENDING);
1410 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1411
1412 /* Load the bare minimum state required for entering HM. */
1413 int rc = hmR0EnterCpu(pVCpu);
1414 if (RT_SUCCESS(rc))
1415 {
1416 if (g_HmR0.hwvirt.u.vmx.fSupported)
1417 {
1418 Assert((pVCpu->hm.s.fCtxChanged & (HM_CHANGED_HOST_CONTEXT | HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE))
1419 == (HM_CHANGED_HOST_CONTEXT | HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE));
1420 }
1421 else
1422 {
1423 Assert((pVCpu->hm.s.fCtxChanged & (HM_CHANGED_HOST_CONTEXT | HM_CHANGED_SVM_HOST_GUEST_SHARED_STATE))
1424 == (HM_CHANGED_HOST_CONTEXT | HM_CHANGED_SVM_HOST_GUEST_SHARED_STATE));
1425 }
1426
1427#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
1428 AssertReturn(!VMMR0ThreadCtxHookIsEnabled(pVCpu), VERR_HM_IPE_5);
1429 bool const fStartedSet = PGMR0DynMapStartOrMigrateAutoSet(pVCpu);
1430#endif
1431
1432 /* Keep track of the CPU owning the VMCS for debugging scheduling weirdness and ring-3 calls. */
1433 rc = g_HmR0.pfnEnterSession(pVCpu);
1434 AssertMsgRCReturnStmt(rc, ("rc=%Rrc pVCpu=%p\n", rc, pVCpu), pVCpu->hm.s.idEnteredCpu = NIL_RTCPUID, rc);
1435
1436 /* Exports the host-state as we may be resuming code after a longjmp and quite
1437 possibly now be scheduled on a different CPU. */
1438 rc = g_HmR0.pfnExportHostState(pVCpu);
1439 AssertMsgRCReturnStmt(rc, ("rc=%Rrc pVCpu=%p\n", rc, pVCpu), pVCpu->hm.s.idEnteredCpu = NIL_RTCPUID, rc);
1440
1441#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
1442 if (fStartedSet)
1443 PGMRZDynMapReleaseAutoSet(pVCpu);
1444#endif
1445 }
1446 return rc;
1447}
1448
1449
1450/**
1451 * Deinitializes the bare minimum state used for HM context and if necessary
1452 * disable HM on the CPU.
1453 *
1454 * @returns VBox status code.
1455 * @param pVCpu The cross context virtual CPU structure.
1456 *
1457 * @remarks No-long-jump zone!!!
1458 */
1459VMMR0_INT_DECL(int) HMR0LeaveCpu(PVMCPUCC pVCpu)
1460{
1461 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1462 VMCPU_ASSERT_EMT_RETURN(pVCpu, VERR_HM_WRONG_CPU);
1463
1464 RTCPUID const idCpu = RTMpCpuId();
1465 PCHMPHYSCPU pHostCpu = &g_HmR0.aCpuInfo[idCpu];
1466
1467 if ( !g_HmR0.fGlobalInit
1468 && pHostCpu->fConfigured)
1469 {
1470 int rc = hmR0DisableCpu(idCpu);
1471 AssertRCReturn(rc, rc);
1472 Assert(!pHostCpu->fConfigured);
1473 Assert(pHostCpu->idCpu == NIL_RTCPUID);
1474
1475 /* For obtaining a non-zero ASID/VPID on next re-entry. */
1476 pVCpu->hm.s.idLastCpu = NIL_RTCPUID;
1477 }
1478
1479 /* Clear it while leaving HM context, hmPokeCpuForTlbFlush() relies on this. */
1480 pVCpu->hm.s.idEnteredCpu = NIL_RTCPUID;
1481
1482 /* De-register the longjmp-to-ring 3 callback now that we have reliquished hardware resources. */
1483 VMMRZCallRing3RemoveNotification(pVCpu);
1484 return VINF_SUCCESS;
1485}
1486
1487
1488/**
1489 * Thread-context hook for HM.
1490 *
1491 * @param enmEvent The thread-context event.
1492 * @param pvUser Opaque pointer to the VMCPU.
1493 */
1494VMMR0_INT_DECL(void) HMR0ThreadCtxCallback(RTTHREADCTXEVENT enmEvent, void *pvUser)
1495{
1496 PVMCPUCC pVCpu = (PVMCPUCC)pvUser;
1497 Assert(pVCpu);
1498 Assert(g_HmR0.pfnThreadCtxCallback);
1499
1500 g_HmR0.pfnThreadCtxCallback(enmEvent, pVCpu, g_HmR0.fGlobalInit);
1501}
1502
1503
1504/**
1505 * Runs guest code in a hardware accelerated VM.
1506 *
1507 * @returns Strict VBox status code. (VBOXSTRICTRC isn't used because it's
1508 * called from setjmp assembly.)
1509 * @param pVM The cross context VM structure.
1510 * @param pVCpu The cross context virtual CPU structure.
1511 *
1512 * @remarks Can be called with preemption enabled if thread-context hooks are
1513 * used!!!
1514 */
1515VMMR0_INT_DECL(int) HMR0RunGuestCode(PVMCC pVM, PVMCPUCC pVCpu)
1516{
1517 RT_NOREF(pVM);
1518
1519#ifdef VBOX_STRICT
1520 /* With thread-context hooks we would be running this code with preemption enabled. */
1521 if (!RTThreadPreemptIsEnabled(NIL_RTTHREAD))
1522 {
1523 PCHMPHYSCPU pHostCpu = &g_HmR0.aCpuInfo[RTMpCpuId()];
1524 Assert(!VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL));
1525 Assert(pHostCpu->fConfigured);
1526 AssertReturn(!ASMAtomicReadBool(&g_HmR0.fSuspended), VERR_HM_SUSPEND_PENDING);
1527 }
1528#endif
1529
1530#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
1531 AssertReturn(!VMMR0ThreadCtxHookIsEnabled(pVCpu), VERR_HM_IPE_4);
1532 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1533 PGMRZDynMapStartAutoSet(pVCpu);
1534#endif
1535
1536 VBOXSTRICTRC rcStrict = g_HmR0.pfnRunGuestCode(pVCpu);
1537
1538#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
1539 PGMRZDynMapReleaseAutoSet(pVCpu);
1540#endif
1541 return VBOXSTRICTRC_VAL(rcStrict);
1542}
1543
1544
1545/**
1546 * Notification from CPUM that it has unloaded the guest FPU/SSE/AVX state from
1547 * the host CPU and that guest access to it must be intercepted.
1548 *
1549 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
1550 */
1551VMMR0_INT_DECL(void) HMR0NotifyCpumUnloadedGuestFpuState(PVMCPUCC pVCpu)
1552{
1553 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_CR0);
1554}
1555
1556
1557/**
1558 * Notification from CPUM that it has modified the host CR0 (because of FPU).
1559 *
1560 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
1561 */
1562VMMR0_INT_DECL(void) HMR0NotifyCpumModifiedHostCr0(PVMCPUCC pVCpu)
1563{
1564 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_HOST_CONTEXT);
1565}
1566
1567
1568/**
1569 * Returns suspend status of the host.
1570 *
1571 * @returns Suspend pending or not.
1572 */
1573VMMR0_INT_DECL(bool) HMR0SuspendPending(void)
1574{
1575 return ASMAtomicReadBool(&g_HmR0.fSuspended);
1576}
1577
1578
1579/**
1580 * Invalidates a guest page from the host TLB.
1581 *
1582 * @param pVCpu The cross context virtual CPU structure.
1583 * @param GCVirt Page to invalidate.
1584 */
1585VMMR0_INT_DECL(int) HMR0InvalidatePage(PVMCPUCC pVCpu, RTGCPTR GCVirt)
1586{
1587 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
1588 if (pVM->hm.s.vmx.fSupported)
1589 return VMXR0InvalidatePage(pVCpu, GCVirt);
1590 return SVMR0InvalidatePage(pVCpu, GCVirt);
1591}
1592
1593
1594/**
1595 * Returns the cpu structure for the current cpu.
1596 * Keep in mind that there is no guarantee it will stay the same (long jumps to ring 3!!!).
1597 *
1598 * @returns The cpu structure pointer.
1599 */
1600VMMR0_INT_DECL(PHMPHYSCPU) hmR0GetCurrentCpu(void)
1601{
1602 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1603 RTCPUID const idCpu = RTMpCpuId();
1604 Assert(idCpu < RT_ELEMENTS(g_HmR0.aCpuInfo));
1605 return &g_HmR0.aCpuInfo[idCpu];
1606}
1607
1608
1609/**
1610 * Interface for importing state on demand (used by IEM).
1611 *
1612 * @returns VBox status code.
1613 * @param pVCpu The cross context CPU structure.
1614 * @param fWhat What to import, CPUMCTX_EXTRN_XXX.
1615 */
1616VMMR0_INT_DECL(int) HMR0ImportStateOnDemand(PVMCPUCC pVCpu, uint64_t fWhat)
1617{
1618 if (pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fSupported)
1619 return VMXR0ImportStateOnDemand(pVCpu, fWhat);
1620 return SVMR0ImportStateOnDemand(pVCpu, fWhat);
1621}
1622
1623#ifdef VBOX_STRICT
1624
1625/**
1626 * Dumps a descriptor.
1627 *
1628 * @param pDesc Descriptor to dump.
1629 * @param Sel The selector.
1630 * @param pszSel The name of the selector.
1631 */
1632VMMR0_INT_DECL(void) hmR0DumpDescriptor(PCX86DESCHC pDesc, RTSEL Sel, const char *pszSel)
1633{
1634 /*
1635 * Make variable description string.
1636 */
1637 static struct
1638 {
1639 unsigned cch;
1640 const char *psz;
1641 } const s_aTypes[32] =
1642 {
1643# define STRENTRY(str) { sizeof(str) - 1, str }
1644
1645 /* system */
1646# if HC_ARCH_BITS == 64
1647 STRENTRY("Reserved0 "), /* 0x00 */
1648 STRENTRY("Reserved1 "), /* 0x01 */
1649 STRENTRY("LDT "), /* 0x02 */
1650 STRENTRY("Reserved3 "), /* 0x03 */
1651 STRENTRY("Reserved4 "), /* 0x04 */
1652 STRENTRY("Reserved5 "), /* 0x05 */
1653 STRENTRY("Reserved6 "), /* 0x06 */
1654 STRENTRY("Reserved7 "), /* 0x07 */
1655 STRENTRY("Reserved8 "), /* 0x08 */
1656 STRENTRY("TSS64Avail "), /* 0x09 */
1657 STRENTRY("ReservedA "), /* 0x0a */
1658 STRENTRY("TSS64Busy "), /* 0x0b */
1659 STRENTRY("Call64 "), /* 0x0c */
1660 STRENTRY("ReservedD "), /* 0x0d */
1661 STRENTRY("Int64 "), /* 0x0e */
1662 STRENTRY("Trap64 "), /* 0x0f */
1663# else
1664 STRENTRY("Reserved0 "), /* 0x00 */
1665 STRENTRY("TSS16Avail "), /* 0x01 */
1666 STRENTRY("LDT "), /* 0x02 */
1667 STRENTRY("TSS16Busy "), /* 0x03 */
1668 STRENTRY("Call16 "), /* 0x04 */
1669 STRENTRY("Task "), /* 0x05 */
1670 STRENTRY("Int16 "), /* 0x06 */
1671 STRENTRY("Trap16 "), /* 0x07 */
1672 STRENTRY("Reserved8 "), /* 0x08 */
1673 STRENTRY("TSS32Avail "), /* 0x09 */
1674 STRENTRY("ReservedA "), /* 0x0a */
1675 STRENTRY("TSS32Busy "), /* 0x0b */
1676 STRENTRY("Call32 "), /* 0x0c */
1677 STRENTRY("ReservedD "), /* 0x0d */
1678 STRENTRY("Int32 "), /* 0x0e */
1679 STRENTRY("Trap32 "), /* 0x0f */
1680# endif
1681 /* non system */
1682 STRENTRY("DataRO "), /* 0x10 */
1683 STRENTRY("DataRO Accessed "), /* 0x11 */
1684 STRENTRY("DataRW "), /* 0x12 */
1685 STRENTRY("DataRW Accessed "), /* 0x13 */
1686 STRENTRY("DataDownRO "), /* 0x14 */
1687 STRENTRY("DataDownRO Accessed "), /* 0x15 */
1688 STRENTRY("DataDownRW "), /* 0x16 */
1689 STRENTRY("DataDownRW Accessed "), /* 0x17 */
1690 STRENTRY("CodeEO "), /* 0x18 */
1691 STRENTRY("CodeEO Accessed "), /* 0x19 */
1692 STRENTRY("CodeER "), /* 0x1a */
1693 STRENTRY("CodeER Accessed "), /* 0x1b */
1694 STRENTRY("CodeConfEO "), /* 0x1c */
1695 STRENTRY("CodeConfEO Accessed "), /* 0x1d */
1696 STRENTRY("CodeConfER "), /* 0x1e */
1697 STRENTRY("CodeConfER Accessed ") /* 0x1f */
1698# undef SYSENTRY
1699 };
1700# define ADD_STR(psz, pszAdd) do { strcpy(psz, pszAdd); psz += strlen(pszAdd); } while (0)
1701 char szMsg[128];
1702 char *psz = &szMsg[0];
1703 unsigned i = pDesc->Gen.u1DescType << 4 | pDesc->Gen.u4Type;
1704 memcpy(psz, s_aTypes[i].psz, s_aTypes[i].cch);
1705 psz += s_aTypes[i].cch;
1706
1707 if (pDesc->Gen.u1Present)
1708 ADD_STR(psz, "Present ");
1709 else
1710 ADD_STR(psz, "Not-Present ");
1711# if HC_ARCH_BITS == 64
1712 if (pDesc->Gen.u1Long)
1713 ADD_STR(psz, "64-bit ");
1714 else
1715 ADD_STR(psz, "Comp ");
1716# else
1717 if (pDesc->Gen.u1Granularity)
1718 ADD_STR(psz, "Page ");
1719 if (pDesc->Gen.u1DefBig)
1720 ADD_STR(psz, "32-bit ");
1721 else
1722 ADD_STR(psz, "16-bit ");
1723# endif
1724# undef ADD_STR
1725 *psz = '\0';
1726
1727 /*
1728 * Limit and Base and format the output.
1729 */
1730#ifdef LOG_ENABLED
1731 uint32_t u32Limit = X86DESC_LIMIT_G(pDesc);
1732
1733# if HC_ARCH_BITS == 64
1734 uint64_t const u64Base = X86DESC64_BASE(pDesc);
1735 Log((" %s { %#04x - %#RX64 %#RX64 - base=%#RX64 limit=%#08x dpl=%d } %s\n", pszSel,
1736 Sel, pDesc->au64[0], pDesc->au64[1], u64Base, u32Limit, pDesc->Gen.u2Dpl, szMsg));
1737# else
1738 uint32_t const u32Base = X86DESC_BASE(pDesc);
1739 Log((" %s { %#04x - %#08x %#08x - base=%#08x limit=%#08x dpl=%d } %s\n", pszSel,
1740 Sel, pDesc->au32[0], pDesc->au32[1], u32Base, u32Limit, pDesc->Gen.u2Dpl, szMsg));
1741# endif
1742#else
1743 NOREF(Sel); NOREF(pszSel);
1744#endif
1745}
1746
1747
1748/**
1749 * Formats a full register dump.
1750 *
1751 * @param pVCpu The cross context virtual CPU structure.
1752 * @param fFlags The dumping flags (HM_DUMP_REG_FLAGS_XXX).
1753 */
1754VMMR0_INT_DECL(void) hmR0DumpRegs(PVMCPUCC pVCpu, uint32_t fFlags)
1755{
1756 /*
1757 * Format the flags.
1758 */
1759 static struct
1760 {
1761 const char *pszSet;
1762 const char *pszClear;
1763 uint32_t fFlag;
1764 } const s_aFlags[] =
1765 {
1766 { "vip", NULL, X86_EFL_VIP },
1767 { "vif", NULL, X86_EFL_VIF },
1768 { "ac", NULL, X86_EFL_AC },
1769 { "vm", NULL, X86_EFL_VM },
1770 { "rf", NULL, X86_EFL_RF },
1771 { "nt", NULL, X86_EFL_NT },
1772 { "ov", "nv", X86_EFL_OF },
1773 { "dn", "up", X86_EFL_DF },
1774 { "ei", "di", X86_EFL_IF },
1775 { "tf", NULL, X86_EFL_TF },
1776 { "nt", "pl", X86_EFL_SF },
1777 { "nz", "zr", X86_EFL_ZF },
1778 { "ac", "na", X86_EFL_AF },
1779 { "po", "pe", X86_EFL_PF },
1780 { "cy", "nc", X86_EFL_CF },
1781 };
1782 char szEFlags[80];
1783 char *psz = szEFlags;
1784 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
1785 uint32_t uEFlags = pCtx->eflags.u32;
1786 for (unsigned i = 0; i < RT_ELEMENTS(s_aFlags); i++)
1787 {
1788 const char *pszAdd = s_aFlags[i].fFlag & uEFlags ? s_aFlags[i].pszSet : s_aFlags[i].pszClear;
1789 if (pszAdd)
1790 {
1791 strcpy(psz, pszAdd);
1792 psz += strlen(pszAdd);
1793 *psz++ = ' ';
1794 }
1795 }
1796 psz[-1] = '\0';
1797
1798 if (fFlags & HM_DUMP_REG_FLAGS_GPRS)
1799 {
1800 /*
1801 * Format the registers.
1802 */
1803 if (CPUMIsGuestIn64BitCode(pVCpu))
1804 {
1805 Log(("rax=%016RX64 rbx=%016RX64 rcx=%016RX64 rdx=%016RX64\n"
1806 "rsi=%016RX64 rdi=%016RX64 r8 =%016RX64 r9 =%016RX64\n"
1807 "r10=%016RX64 r11=%016RX64 r12=%016RX64 r13=%016RX64\n"
1808 "r14=%016RX64 r15=%016RX64\n"
1809 "rip=%016RX64 rsp=%016RX64 rbp=%016RX64 iopl=%d %*s\n"
1810 "cs={%04x base=%016RX64 limit=%08x flags=%08x}\n"
1811 "ds={%04x base=%016RX64 limit=%08x flags=%08x}\n"
1812 "es={%04x base=%016RX64 limit=%08x flags=%08x}\n"
1813 "fs={%04x base=%016RX64 limit=%08x flags=%08x}\n"
1814 "gs={%04x base=%016RX64 limit=%08x flags=%08x}\n"
1815 "ss={%04x base=%016RX64 limit=%08x flags=%08x}\n"
1816 "cr0=%016RX64 cr2=%016RX64 cr3=%016RX64 cr4=%016RX64\n"
1817 "dr0=%016RX64 dr1=%016RX64 dr2=%016RX64 dr3=%016RX64\n"
1818 "dr4=%016RX64 dr5=%016RX64 dr6=%016RX64 dr7=%016RX64\n"
1819 "gdtr=%016RX64:%04x idtr=%016RX64:%04x eflags=%08x\n"
1820 "ldtr={%04x base=%08RX64 limit=%08x flags=%08x}\n"
1821 "tr ={%04x base=%08RX64 limit=%08x flags=%08x}\n"
1822 "SysEnter={cs=%04llx eip=%08llx esp=%08llx}\n"
1823 ,
1824 pCtx->rax, pCtx->rbx, pCtx->rcx, pCtx->rdx, pCtx->rsi, pCtx->rdi,
1825 pCtx->r8, pCtx->r9, pCtx->r10, pCtx->r11, pCtx->r12, pCtx->r13,
1826 pCtx->r14, pCtx->r15,
1827 pCtx->rip, pCtx->rsp, pCtx->rbp, X86_EFL_GET_IOPL(uEFlags), 31, szEFlags,
1828 pCtx->cs.Sel, pCtx->cs.u64Base, pCtx->cs.u32Limit, pCtx->cs.Attr.u,
1829 pCtx->ds.Sel, pCtx->ds.u64Base, pCtx->ds.u32Limit, pCtx->ds.Attr.u,
1830 pCtx->es.Sel, pCtx->es.u64Base, pCtx->es.u32Limit, pCtx->es.Attr.u,
1831 pCtx->fs.Sel, pCtx->fs.u64Base, pCtx->fs.u32Limit, pCtx->fs.Attr.u,
1832 pCtx->gs.Sel, pCtx->gs.u64Base, pCtx->gs.u32Limit, pCtx->gs.Attr.u,
1833 pCtx->ss.Sel, pCtx->ss.u64Base, pCtx->ss.u32Limit, pCtx->ss.Attr.u,
1834 pCtx->cr0, pCtx->cr2, pCtx->cr3, pCtx->cr4,
1835 pCtx->dr[0], pCtx->dr[1], pCtx->dr[2], pCtx->dr[3],
1836 pCtx->dr[4], pCtx->dr[5], pCtx->dr[6], pCtx->dr[7],
1837 pCtx->gdtr.pGdt, pCtx->gdtr.cbGdt, pCtx->idtr.pIdt, pCtx->idtr.cbIdt, uEFlags,
1838 pCtx->ldtr.Sel, pCtx->ldtr.u64Base, pCtx->ldtr.u32Limit, pCtx->ldtr.Attr.u,
1839 pCtx->tr.Sel, pCtx->tr.u64Base, pCtx->tr.u32Limit, pCtx->tr.Attr.u,
1840 pCtx->SysEnter.cs, pCtx->SysEnter.eip, pCtx->SysEnter.esp));
1841 }
1842 else
1843 Log(("eax=%08x ebx=%08x ecx=%08x edx=%08x esi=%08x edi=%08x\n"
1844 "eip=%08x esp=%08x ebp=%08x iopl=%d %*s\n"
1845 "cs={%04x base=%016RX64 limit=%08x flags=%08x} dr0=%08RX64 dr1=%08RX64\n"
1846 "ds={%04x base=%016RX64 limit=%08x flags=%08x} dr2=%08RX64 dr3=%08RX64\n"
1847 "es={%04x base=%016RX64 limit=%08x flags=%08x} dr4=%08RX64 dr5=%08RX64\n"
1848 "fs={%04x base=%016RX64 limit=%08x flags=%08x} dr6=%08RX64 dr7=%08RX64\n"
1849 "gs={%04x base=%016RX64 limit=%08x flags=%08x} cr0=%08RX64 cr2=%08RX64\n"
1850 "ss={%04x base=%016RX64 limit=%08x flags=%08x} cr3=%08RX64 cr4=%08RX64\n"
1851 "gdtr=%016RX64:%04x idtr=%016RX64:%04x eflags=%08x\n"
1852 "ldtr={%04x base=%08RX64 limit=%08x flags=%08x}\n"
1853 "tr ={%04x base=%08RX64 limit=%08x flags=%08x}\n"
1854 "SysEnter={cs=%04llx eip=%08llx esp=%08llx}\n"
1855 ,
1856 pCtx->eax, pCtx->ebx, pCtx->ecx, pCtx->edx, pCtx->esi, pCtx->edi,
1857 pCtx->eip, pCtx->esp, pCtx->ebp, X86_EFL_GET_IOPL(uEFlags), 31, szEFlags,
1858 pCtx->cs.Sel, pCtx->cs.u64Base, pCtx->cs.u32Limit, pCtx->cs.Attr.u, pCtx->dr[0], pCtx->dr[1],
1859 pCtx->ds.Sel, pCtx->ds.u64Base, pCtx->ds.u32Limit, pCtx->ds.Attr.u, pCtx->dr[2], pCtx->dr[3],
1860 pCtx->es.Sel, pCtx->es.u64Base, pCtx->es.u32Limit, pCtx->es.Attr.u, pCtx->dr[4], pCtx->dr[5],
1861 pCtx->fs.Sel, pCtx->fs.u64Base, pCtx->fs.u32Limit, pCtx->fs.Attr.u, pCtx->dr[6], pCtx->dr[7],
1862 pCtx->gs.Sel, pCtx->gs.u64Base, pCtx->gs.u32Limit, pCtx->gs.Attr.u, pCtx->cr0, pCtx->cr2,
1863 pCtx->ss.Sel, pCtx->ss.u64Base, pCtx->ss.u32Limit, pCtx->ss.Attr.u, pCtx->cr3, pCtx->cr4,
1864 pCtx->gdtr.pGdt, pCtx->gdtr.cbGdt, pCtx->idtr.pIdt, pCtx->idtr.cbIdt, uEFlags,
1865 pCtx->ldtr.Sel, pCtx->ldtr.u64Base, pCtx->ldtr.u32Limit, pCtx->ldtr.Attr.u,
1866 pCtx->tr.Sel, pCtx->tr.u64Base, pCtx->tr.u32Limit, pCtx->tr.Attr.u,
1867 pCtx->SysEnter.cs, pCtx->SysEnter.eip, pCtx->SysEnter.esp));
1868 }
1869
1870 if (fFlags & HM_DUMP_REG_FLAGS_FPU)
1871 {
1872 PCX86FXSTATE pFpuCtx = &pCtx->CTX_SUFF(pXState)->x87;
1873 Log(("FPU:\n"
1874 "FCW=%04x FSW=%04x FTW=%02x\n"
1875 "FOP=%04x FPUIP=%08x CS=%04x Rsrvd1=%04x\n"
1876 "FPUDP=%04x DS=%04x Rsvrd2=%04x MXCSR=%08x MXCSR_MASK=%08x\n"
1877 ,
1878 pFpuCtx->FCW, pFpuCtx->FSW, pFpuCtx->FTW,
1879 pFpuCtx->FOP, pFpuCtx->FPUIP, pFpuCtx->CS, pFpuCtx->Rsrvd1,
1880 pFpuCtx->FPUDP, pFpuCtx->DS, pFpuCtx->Rsrvd2,
1881 pFpuCtx->MXCSR, pFpuCtx->MXCSR_MASK));
1882 NOREF(pFpuCtx);
1883 }
1884
1885 if (fFlags & HM_DUMP_REG_FLAGS_MSRS)
1886 {
1887 Log(("MSR:\n"
1888 "EFER =%016RX64\n"
1889 "PAT =%016RX64\n"
1890 "STAR =%016RX64\n"
1891 "CSTAR =%016RX64\n"
1892 "LSTAR =%016RX64\n"
1893 "SFMASK =%016RX64\n"
1894 "KERNELGSBASE =%016RX64\n",
1895 pCtx->msrEFER,
1896 pCtx->msrPAT,
1897 pCtx->msrSTAR,
1898 pCtx->msrCSTAR,
1899 pCtx->msrLSTAR,
1900 pCtx->msrSFMASK,
1901 pCtx->msrKERNELGSBASE));
1902 }
1903}
1904
1905#endif /* VBOX_STRICT */
1906
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