VirtualBox

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

Last change on this file since 54375 was 54339, checked in by vboxsync, 10 years ago

SUPDrv,VMM: Added SUPR0TscDeltaMeasureBySetIndex to SUPDrv (bumping version req) so that VMMR0.cpp can, if necessary, trigger a delta measurement prior to doing RC and HM stuff. Also, made the context hook set the return-to-ring3 force flag if we're rescheduled on a CPU with an TSC delta needing measuring. This is probably code that will almost never get called...

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 70.1 KB
Line 
1/* $Id: VMMR0.cpp 54339 2015-02-20 18:10:12Z vboxsync $ */
2/** @file
3 * VMM - Host Context Ring 0.
4 */
5
6/*
7 * Copyright (C) 2006-2012 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* Header Files *
20*******************************************************************************/
21#define LOG_GROUP LOG_GROUP_VMM
22#include <VBox/vmm/vmm.h>
23#include <VBox/sup.h>
24#include <VBox/vmm/trpm.h>
25#include <VBox/vmm/cpum.h>
26#include <VBox/vmm/pdmapi.h>
27#include <VBox/vmm/pgm.h>
28#include <VBox/vmm/stam.h>
29#include <VBox/vmm/tm.h>
30#include "VMMInternal.h"
31#include <VBox/vmm/vm.h>
32#ifdef VBOX_WITH_PCI_PASSTHROUGH
33# include <VBox/vmm/pdmpci.h>
34#endif
35
36#include <VBox/vmm/gvmm.h>
37#include <VBox/vmm/gmm.h>
38#include <VBox/vmm/gim.h>
39#include <VBox/intnet.h>
40#include <VBox/vmm/hm.h>
41#include <VBox/param.h>
42#include <VBox/err.h>
43#include <VBox/version.h>
44#include <VBox/log.h>
45
46#include <iprt/asm-amd64-x86.h>
47#include <iprt/assert.h>
48#include <iprt/crc.h>
49#include <iprt/mp.h>
50#include <iprt/once.h>
51#include <iprt/stdarg.h>
52#include <iprt/string.h>
53#include <iprt/thread.h>
54#include <iprt/timer.h>
55
56#include "dtrace/VBoxVMM.h"
57
58
59#if defined(_MSC_VER) && defined(RT_ARCH_AMD64) /** @todo check this with with VC7! */
60# pragma intrinsic(_AddressOfReturnAddress)
61#endif
62
63
64/*******************************************************************************
65* Internal Functions *
66*******************************************************************************/
67RT_C_DECLS_BEGIN
68#if defined(RT_ARCH_X86) && (defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD))
69extern uint64_t __udivdi3(uint64_t, uint64_t);
70extern uint64_t __umoddi3(uint64_t, uint64_t);
71#endif
72RT_C_DECLS_END
73
74
75/*******************************************************************************
76* Global Variables *
77*******************************************************************************/
78/** Drag in necessary library bits.
79 * The runtime lives here (in VMMR0.r0) and VBoxDD*R0.r0 links against us. */
80PFNRT g_VMMGCDeps[] =
81{
82 (PFNRT)RTCrc32,
83 (PFNRT)RTOnce,
84#if defined(RT_ARCH_X86) && (defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD))
85 (PFNRT)__udivdi3,
86 (PFNRT)__umoddi3,
87#endif
88 NULL
89};
90
91#ifdef RT_OS_SOLARIS
92/* Dependency information for the native solaris loader. */
93extern "C" { char _depends_on[] = "vboxdrv"; }
94#endif
95
96
97
98/**
99 * Initialize the module.
100 * This is called when we're first loaded.
101 *
102 * @returns 0 on success.
103 * @returns VBox status on failure.
104 * @param hMod Image handle for use in APIs.
105 */
106DECLEXPORT(int) ModuleInit(void *hMod)
107{
108#ifdef VBOX_WITH_DTRACE_R0
109 /*
110 * The first thing to do is register the static tracepoints.
111 * (Deregistration is automatic.)
112 */
113 int rc2 = SUPR0TracerRegisterModule(hMod, &g_VTGObjHeader);
114 if (RT_FAILURE(rc2))
115 return rc2;
116#endif
117 LogFlow(("ModuleInit:\n"));
118
119#ifdef VBOX_WITH_64ON32_CMOS_DEBUG
120 /*
121 * Display the CMOS debug code.
122 */
123 ASMOutU8(0x72, 0x03);
124 uint8_t bDebugCode = ASMInU8(0x73);
125 LogRel(("CMOS Debug Code: %#x (%d)\n", bDebugCode, bDebugCode));
126 RTLogComPrintf("CMOS Debug Code: %#x (%d)\n", bDebugCode, bDebugCode);
127#endif
128
129 /*
130 * Initialize the VMM, GVMM, GMM, HM, PGM (Darwin) and INTNET.
131 */
132 int rc = vmmInitFormatTypes();
133 if (RT_SUCCESS(rc))
134 {
135 rc = GVMMR0Init();
136 if (RT_SUCCESS(rc))
137 {
138 rc = GMMR0Init();
139 if (RT_SUCCESS(rc))
140 {
141 rc = HMR0Init();
142 if (RT_SUCCESS(rc))
143 {
144 rc = PGMRegisterStringFormatTypes();
145 if (RT_SUCCESS(rc))
146 {
147#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
148 rc = PGMR0DynMapInit();
149#endif
150 if (RT_SUCCESS(rc))
151 {
152 rc = IntNetR0Init();
153 if (RT_SUCCESS(rc))
154 {
155#ifdef VBOX_WITH_PCI_PASSTHROUGH
156 rc = PciRawR0Init();
157#endif
158 if (RT_SUCCESS(rc))
159 {
160 rc = CPUMR0ModuleInit();
161 if (RT_SUCCESS(rc))
162 {
163#ifdef VBOX_WITH_TRIPLE_FAULT_HACK
164 rc = vmmR0TripleFaultHackInit();
165 if (RT_SUCCESS(rc))
166#endif
167 {
168 LogFlow(("ModuleInit: returns success.\n"));
169 return VINF_SUCCESS;
170 }
171
172 /*
173 * Bail out.
174 */
175#ifdef VBOX_WITH_TRIPLE_FAULT_HACK
176 vmmR0TripleFaultHackTerm();
177#endif
178 }
179 else
180 LogRel(("ModuleInit: CPUMR0ModuleInit -> %Rrc\n", rc));
181#ifdef VBOX_WITH_PCI_PASSTHROUGH
182 PciRawR0Term();
183#endif
184 }
185 else
186 LogRel(("ModuleInit: PciRawR0Init -> %Rrc\n", rc));
187 IntNetR0Term();
188 }
189 else
190 LogRel(("ModuleInit: IntNetR0Init -> %Rrc\n", rc));
191#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
192 PGMR0DynMapTerm();
193#endif
194 }
195 else
196 LogRel(("ModuleInit: PGMR0DynMapInit -> %Rrc\n", rc));
197 PGMDeregisterStringFormatTypes();
198 }
199 else
200 LogRel(("ModuleInit: PGMRegisterStringFormatTypes -> %Rrc\n", rc));
201 HMR0Term();
202 }
203 else
204 LogRel(("ModuleInit: HMR0Init -> %Rrc\n", rc));
205 GMMR0Term();
206 }
207 else
208 LogRel(("ModuleInit: GMMR0Init -> %Rrc\n", rc));
209 GVMMR0Term();
210 }
211 else
212 LogRel(("ModuleInit: GVMMR0Init -> %Rrc\n", rc));
213 vmmTermFormatTypes();
214 }
215 else
216 LogRel(("ModuleInit: vmmInitFormatTypes -> %Rrc\n", rc));
217
218 LogFlow(("ModuleInit: failed %Rrc\n", rc));
219 return rc;
220}
221
222
223/**
224 * Terminate the module.
225 * This is called when we're finally unloaded.
226 *
227 * @param hMod Image handle for use in APIs.
228 */
229DECLEXPORT(void) ModuleTerm(void *hMod)
230{
231 NOREF(hMod);
232 LogFlow(("ModuleTerm:\n"));
233
234 /*
235 * Terminate the CPUM module (Local APIC cleanup).
236 */
237 CPUMR0ModuleTerm();
238
239 /*
240 * Terminate the internal network service.
241 */
242 IntNetR0Term();
243
244 /*
245 * PGM (Darwin), HM and PciRaw global cleanup.
246 */
247#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
248 PGMR0DynMapTerm();
249#endif
250#ifdef VBOX_WITH_PCI_PASSTHROUGH
251 PciRawR0Term();
252#endif
253 PGMDeregisterStringFormatTypes();
254 HMR0Term();
255#ifdef VBOX_WITH_TRIPLE_FAULT_HACK
256 vmmR0TripleFaultHackTerm();
257#endif
258
259 /*
260 * Destroy the GMM and GVMM instances.
261 */
262 GMMR0Term();
263 GVMMR0Term();
264
265 vmmTermFormatTypes();
266
267 LogFlow(("ModuleTerm: returns\n"));
268}
269
270
271/**
272 * Initiates the R0 driver for a particular VM instance.
273 *
274 * @returns VBox status code.
275 *
276 * @param pVM Pointer to the VM.
277 * @param uSvnRev The SVN revision of the ring-3 part.
278 * @param uBuildType Build type indicator.
279 * @thread EMT.
280 */
281static int vmmR0InitVM(PVM pVM, uint32_t uSvnRev, uint32_t uBuildType)
282{
283 /*
284 * Match the SVN revisions and build type.
285 */
286 if (uSvnRev != VMMGetSvnRev())
287 {
288 LogRel(("VMMR0InitVM: Revision mismatch, r3=%d r0=%d\n", uSvnRev, VMMGetSvnRev()));
289 SUPR0Printf("VMMR0InitVM: Revision mismatch, r3=%d r0=%d\n", uSvnRev, VMMGetSvnRev());
290 return VERR_VMM_R0_VERSION_MISMATCH;
291 }
292 if (uBuildType != vmmGetBuildType())
293 {
294 LogRel(("VMMR0InitVM: Build type mismatch, r3=%#x r0=%#x\n", uBuildType, vmmGetBuildType()));
295 SUPR0Printf("VMMR0InitVM: Build type mismatch, r3=%#x r0=%#x\n", uBuildType, vmmGetBuildType());
296 return VERR_VMM_R0_VERSION_MISMATCH;
297 }
298 if ( !VALID_PTR(pVM)
299 || pVM->pVMR0 != pVM)
300 return VERR_INVALID_PARAMETER;
301
302
303#ifdef LOG_ENABLED
304 /*
305 * Register the EMT R0 logger instance for VCPU 0.
306 */
307 PVMCPU pVCpu = &pVM->aCpus[0];
308
309 PVMMR0LOGGER pR0Logger = pVCpu->vmm.s.pR0LoggerR0;
310 if (pR0Logger)
311 {
312# if 0 /* testing of the logger. */
313 LogCom(("vmmR0InitVM: before %p\n", RTLogDefaultInstance()));
314 LogCom(("vmmR0InitVM: pfnFlush=%p actual=%p\n", pR0Logger->Logger.pfnFlush, vmmR0LoggerFlush));
315 LogCom(("vmmR0InitVM: pfnLogger=%p actual=%p\n", pR0Logger->Logger.pfnLogger, vmmR0LoggerWrapper));
316 LogCom(("vmmR0InitVM: offScratch=%d fFlags=%#x fDestFlags=%#x\n", pR0Logger->Logger.offScratch, pR0Logger->Logger.fFlags, pR0Logger->Logger.fDestFlags));
317
318 RTLogSetDefaultInstanceThread(&pR0Logger->Logger, (uintptr_t)pVM->pSession);
319 LogCom(("vmmR0InitVM: after %p reg\n", RTLogDefaultInstance()));
320 RTLogSetDefaultInstanceThread(NULL, pVM->pSession);
321 LogCom(("vmmR0InitVM: after %p dereg\n", RTLogDefaultInstance()));
322
323 pR0Logger->Logger.pfnLogger("hello ring-0 logger\n");
324 LogCom(("vmmR0InitVM: returned successfully from direct logger call.\n"));
325 pR0Logger->Logger.pfnFlush(&pR0Logger->Logger);
326 LogCom(("vmmR0InitVM: returned successfully from direct flush call.\n"));
327
328 RTLogSetDefaultInstanceThread(&pR0Logger->Logger, (uintptr_t)pVM->pSession);
329 LogCom(("vmmR0InitVM: after %p reg2\n", RTLogDefaultInstance()));
330 pR0Logger->Logger.pfnLogger("hello ring-0 logger\n");
331 LogCom(("vmmR0InitVM: returned successfully from direct logger call (2). offScratch=%d\n", pR0Logger->Logger.offScratch));
332 RTLogSetDefaultInstanceThread(NULL, pVM->pSession);
333 LogCom(("vmmR0InitVM: after %p dereg2\n", RTLogDefaultInstance()));
334
335 RTLogLoggerEx(&pR0Logger->Logger, 0, ~0U, "hello ring-0 logger (RTLogLoggerEx)\n");
336 LogCom(("vmmR0InitVM: RTLogLoggerEx returned fine offScratch=%d\n", pR0Logger->Logger.offScratch));
337
338 RTLogSetDefaultInstanceThread(&pR0Logger->Logger, (uintptr_t)pVM->pSession);
339 RTLogPrintf("hello ring-0 logger (RTLogPrintf)\n");
340 LogCom(("vmmR0InitVM: RTLogPrintf returned fine offScratch=%d\n", pR0Logger->Logger.offScratch));
341# endif
342 Log(("Switching to per-thread logging instance %p (key=%p)\n", &pR0Logger->Logger, pVM->pSession));
343 RTLogSetDefaultInstanceThread(&pR0Logger->Logger, (uintptr_t)pVM->pSession);
344 pR0Logger->fRegistered = true;
345 }
346#endif /* LOG_ENABLED */
347
348 /*
349 * Check if the host supports high resolution timers or not.
350 */
351 if ( pVM->vmm.s.fUsePeriodicPreemptionTimers
352 && !RTTimerCanDoHighResolution())
353 pVM->vmm.s.fUsePeriodicPreemptionTimers = false;
354
355 /*
356 * Initialize the per VM data for GVMM and GMM.
357 */
358 int rc = GVMMR0InitVM(pVM);
359// if (RT_SUCCESS(rc))
360// rc = GMMR0InitPerVMData(pVM);
361 if (RT_SUCCESS(rc))
362 {
363 /*
364 * Init HM, CPUM and PGM (Darwin only).
365 */
366 rc = HMR0InitVM(pVM);
367 if (RT_SUCCESS(rc))
368 {
369 rc = CPUMR0InitVM(pVM);
370 if (RT_SUCCESS(rc))
371 {
372#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
373 rc = PGMR0DynMapInitVM(pVM);
374#endif
375 if (RT_SUCCESS(rc))
376 {
377#ifdef VBOX_WITH_PCI_PASSTHROUGH
378 rc = PciRawR0InitVM(pVM);
379#endif
380 if (RT_SUCCESS(rc))
381 {
382 rc = GIMR0InitVM(pVM);
383 if (RT_SUCCESS(rc))
384 {
385 GVMMR0DoneInitVM(pVM);
386 return rc;
387 }
388
389 /* bail out*/
390#ifdef VBOX_WITH_PCI_PASSTHROUGH
391 PciRawR0TermVM(pVM);
392#endif
393 }
394 }
395 }
396 HMR0TermVM(pVM);
397 }
398 }
399
400
401 RTLogSetDefaultInstanceThread(NULL, (uintptr_t)pVM->pSession);
402 return rc;
403}
404
405
406/**
407 * Terminates the R0 bits for a particular VM instance.
408 *
409 * This is normally called by ring-3 as part of the VM termination process, but
410 * may alternatively be called during the support driver session cleanup when
411 * the VM object is destroyed (see GVMM).
412 *
413 * @returns VBox status code.
414 *
415 * @param pVM Pointer to the VM.
416 * @param pGVM Pointer to the global VM structure. Optional.
417 * @thread EMT or session clean up thread.
418 */
419VMMR0DECL(int) VMMR0TermVM(PVM pVM, PGVM pGVM)
420{
421#ifdef VBOX_WITH_PCI_PASSTHROUGH
422 PciRawR0TermVM(pVM);
423#endif
424
425 /*
426 * Tell GVMM what we're up to and check that we only do this once.
427 */
428 if (GVMMR0DoingTermVM(pVM, pGVM))
429 {
430 GIMR0TermVM(pVM);
431
432 /** @todo I wish to call PGMR0PhysFlushHandyPages(pVM, &pVM->aCpus[idCpu])
433 * here to make sure we don't leak any shared pages if we crash... */
434#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
435 PGMR0DynMapTermVM(pVM);
436#endif
437 HMR0TermVM(pVM);
438 }
439
440 /*
441 * Deregister the logger.
442 */
443 RTLogSetDefaultInstanceThread(NULL, (uintptr_t)pVM->pSession);
444 return VINF_SUCCESS;
445}
446
447
448/**
449 * Creates R0 thread-context hooks for the current EMT thread.
450 *
451 * @returns VBox status code.
452 * @param pVCpu Pointer to the VMCPU.
453 *
454 * @thread EMT(pVCpu)
455 */
456VMMR0DECL(int) VMMR0ThreadCtxHooksCreate(PVMCPU pVCpu)
457{
458 VMCPU_ASSERT_EMT(pVCpu);
459 Assert(pVCpu->vmm.s.hR0ThreadCtx == NIL_RTTHREADCTX);
460#if defined(RT_OS_LINUX) || defined(RT_OS_SOLARIS)
461 int rc = RTThreadCtxHooksCreate(&pVCpu->vmm.s.hR0ThreadCtx);
462 if ( RT_FAILURE(rc)
463 && rc != VERR_NOT_SUPPORTED)
464 {
465 Log(("RTThreadCtxHooksCreate failed! rc=%Rrc pVCpu=%p idCpu=%RU32\n", rc, pVCpu, pVCpu->idCpu));
466 return rc;
467 }
468#endif
469
470 return VINF_SUCCESS;
471}
472
473
474/**
475 * Releases the object reference for the thread-context hook.
476 *
477 * @param pVCpu Pointer to the VMCPU.
478 * @remarks Can be called from any thread.
479 */
480VMMR0DECL(void) VMMR0ThreadCtxHooksRelease(PVMCPU pVCpu)
481{
482 RTThreadCtxHooksRelease(pVCpu->vmm.s.hR0ThreadCtx);
483}
484
485
486/**
487 * Registers the thread-context hook for this VCPU.
488 *
489 * @returns VBox status code.
490 * @param pVCpu Pointer to the VMCPU.
491 * @param pfnThreadHook Pointer to the thread-context callback.
492 *
493 * @thread EMT(pVCpu)
494 */
495VMMR0DECL(int) VMMR0ThreadCtxHooksRegister(PVMCPU pVCpu, PFNRTTHREADCTXHOOK pfnThreadHook)
496{
497 VMCPU_ASSERT_EMT(pVCpu);
498 return RTThreadCtxHooksRegister(pVCpu->vmm.s.hR0ThreadCtx, pfnThreadHook, pVCpu);
499}
500
501
502/**
503 * Deregisters the thread-context hook for this VCPU.
504 *
505 * @returns VBox status code.
506 * @param pVCpu Pointer to the VMCPU.
507 *
508 * @thread EMT(pVCpu)
509 */
510VMMR0DECL(int) VMMR0ThreadCtxHooksDeregister(PVMCPU pVCpu)
511{
512 return RTThreadCtxHooksDeregister(pVCpu->vmm.s.hR0ThreadCtx);
513}
514
515
516/**
517 * Whether thread-context hooks are created (implying they're supported) on this
518 * platform.
519 *
520 * @returns true if the hooks are created, false otherwise.
521 * @param pVCpu Pointer to the VMCPU.
522 */
523VMMR0DECL(bool) VMMR0ThreadCtxHooksAreCreated(PVMCPU pVCpu)
524{
525 return pVCpu->vmm.s.hR0ThreadCtx != NIL_RTTHREADCTX;
526}
527
528
529/**
530 * Whether thread-context hooks are registered for this VCPU.
531 *
532 * @returns true if registered, false otherwise.
533 * @param pVCpu Pointer to the VMCPU.
534 */
535VMMR0DECL(bool) VMMR0ThreadCtxHooksAreRegistered(PVMCPU pVCpu)
536{
537 return RTThreadCtxHooksAreRegistered(pVCpu->vmm.s.hR0ThreadCtx);
538}
539
540
541/**
542 * VMM ring-0 thread-context callback.
543 *
544 * This does common HM state updating and calls the HM-specific thread-context
545 * callback.
546 *
547 * @param enmEvent The thread-context event.
548 * @param pvUser Opaque pointer to the VMCPU.
549 *
550 * @thread EMT(pvUser)
551 */
552static DECLCALLBACK(void) vmmR0ThreadCtxCallback(RTTHREADCTXEVENT enmEvent, void *pvUser)
553{
554 PVMCPU pVCpu = (PVMCPU)pvUser;
555
556 switch (enmEvent)
557 {
558 case RTTHREADCTXEVENT_RESUMED:
559 {
560 /** @todo Linux may call us with preemption enabled (really!) but technically we
561 * cannot get preempted here, otherwise we end up in an infinite recursion
562 * scenario (i.e. preempted in resume hook -> preempt hook -> resume hook... ad
563 * infinitum). Let's just disable preemption for now...
564 */
565 HM_DISABLE_PREEMPT_IF_NEEDED();
566
567 /* We need to update the VCPU <-> host CPU mapping. */
568 RTCPUID idHostCpu = RTMpCpuId();
569 uint32_t iHostCpuSet = RTMpCpuIdToSetIndex(idHostCpu);
570 pVCpu->iHostCpuSet = iHostCpuSet;
571 ASMAtomicWriteU32(&pVCpu->idHostCpu, idHostCpu);
572
573 /* In the very unlikely event that the GIP delta for the CPU we're
574 rescheduled needs calculating, try force a return to ring-3.
575 We unfortunately cannot do the measurements right here. */
576 if (RT_UNLIKELY(SUPIsTscDeltaAvailableForCpuSetIndex(iHostCpuSet)))
577 VMCPU_FF_SET(pVCpu, VMCPU_FF_TO_R3);
578
579 /* Invoke the HM-specific thread-context callback. */
580 HMR0ThreadCtxCallback(enmEvent, pvUser);
581
582 /* Restore preemption. */
583 HM_RESTORE_PREEMPT_IF_NEEDED();
584 break;
585 }
586
587 case RTTHREADCTXEVENT_PREEMPTING:
588 {
589 /* Invoke the HM-specific thread-context callback. */
590 HMR0ThreadCtxCallback(enmEvent, pvUser);
591
592 /*
593 * Sigh. See VMMGetCpu() used by VMCPU_ASSERT_EMT(). We cannot let several VCPUs
594 * have the same host CPU associated with it.
595 */
596 pVCpu->iHostCpuSet = UINT32_MAX;
597 ASMAtomicWriteU32(&pVCpu->idHostCpu, NIL_RTCPUID);
598 break;
599 }
600
601 default:
602 /* Invoke the HM-specific thread-context callback. */
603 HMR0ThreadCtxCallback(enmEvent, pvUser);
604 break;
605 }
606}
607
608
609#ifdef VBOX_WITH_STATISTICS
610/**
611 * Record return code statistics
612 * @param pVM Pointer to the VM.
613 * @param pVCpu Pointer to the VMCPU.
614 * @param rc The status code.
615 */
616static void vmmR0RecordRC(PVM pVM, PVMCPU pVCpu, int rc)
617{
618 /*
619 * Collect statistics.
620 */
621 switch (rc)
622 {
623 case VINF_SUCCESS:
624 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetNormal);
625 break;
626 case VINF_EM_RAW_INTERRUPT:
627 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetInterrupt);
628 break;
629 case VINF_EM_RAW_INTERRUPT_HYPER:
630 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetInterruptHyper);
631 break;
632 case VINF_EM_RAW_GUEST_TRAP:
633 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetGuestTrap);
634 break;
635 case VINF_EM_RAW_RING_SWITCH:
636 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetRingSwitch);
637 break;
638 case VINF_EM_RAW_RING_SWITCH_INT:
639 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetRingSwitchInt);
640 break;
641 case VINF_EM_RAW_STALE_SELECTOR:
642 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetStaleSelector);
643 break;
644 case VINF_EM_RAW_IRET_TRAP:
645 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetIRETTrap);
646 break;
647 case VINF_IOM_R3_IOPORT_READ:
648 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetIORead);
649 break;
650 case VINF_IOM_R3_IOPORT_WRITE:
651 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetIOWrite);
652 break;
653 case VINF_IOM_R3_MMIO_READ:
654 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMMIORead);
655 break;
656 case VINF_IOM_R3_MMIO_WRITE:
657 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMMIOWrite);
658 break;
659 case VINF_IOM_R3_MMIO_READ_WRITE:
660 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMMIOReadWrite);
661 break;
662 case VINF_PATM_HC_MMIO_PATCH_READ:
663 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMMIOPatchRead);
664 break;
665 case VINF_PATM_HC_MMIO_PATCH_WRITE:
666 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMMIOPatchWrite);
667 break;
668 case VINF_CPUM_R3_MSR_READ:
669 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMSRRead);
670 break;
671 case VINF_CPUM_R3_MSR_WRITE:
672 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMSRWrite);
673 break;
674 case VINF_EM_RAW_EMULATE_INSTR:
675 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetEmulate);
676 break;
677 case VINF_EM_RAW_EMULATE_IO_BLOCK:
678 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetIOBlockEmulate);
679 break;
680 case VINF_PATCH_EMULATE_INSTR:
681 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPatchEmulate);
682 break;
683 case VINF_EM_RAW_EMULATE_INSTR_LDT_FAULT:
684 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetLDTFault);
685 break;
686 case VINF_EM_RAW_EMULATE_INSTR_GDT_FAULT:
687 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetGDTFault);
688 break;
689 case VINF_EM_RAW_EMULATE_INSTR_IDT_FAULT:
690 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetIDTFault);
691 break;
692 case VINF_EM_RAW_EMULATE_INSTR_TSS_FAULT:
693 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetTSSFault);
694 break;
695 case VINF_EM_RAW_EMULATE_INSTR_PD_FAULT:
696 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPDFault);
697 break;
698 case VINF_CSAM_PENDING_ACTION:
699 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetCSAMTask);
700 break;
701 case VINF_PGM_SYNC_CR3:
702 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetSyncCR3);
703 break;
704 case VINF_PATM_PATCH_INT3:
705 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPatchInt3);
706 break;
707 case VINF_PATM_PATCH_TRAP_PF:
708 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPatchPF);
709 break;
710 case VINF_PATM_PATCH_TRAP_GP:
711 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPatchGP);
712 break;
713 case VINF_PATM_PENDING_IRQ_AFTER_IRET:
714 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPatchIretIRQ);
715 break;
716 case VINF_EM_RESCHEDULE_REM:
717 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetRescheduleREM);
718 break;
719 case VINF_EM_RAW_TO_R3:
720 if (VM_FF_IS_PENDING(pVM, VM_FF_TM_VIRTUAL_SYNC))
721 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3TMVirt);
722 else if (VM_FF_IS_PENDING(pVM, VM_FF_PGM_NEED_HANDY_PAGES))
723 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3HandyPages);
724 else if (VM_FF_IS_PENDING(pVM, VM_FF_PDM_QUEUES))
725 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3PDMQueues);
726 else if (VM_FF_IS_PENDING(pVM, VM_FF_EMT_RENDEZVOUS))
727 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3Rendezvous);
728 else if (VM_FF_IS_PENDING(pVM, VM_FF_PDM_DMA))
729 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3DMA);
730 else if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_TIMER))
731 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3Timer);
732 else if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_PDM_CRITSECT))
733 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3CritSect);
734 else if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_TO_R3))
735 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3);
736 else
737 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3Unknown);
738 break;
739
740 case VINF_EM_RAW_TIMER_PENDING:
741 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetTimerPending);
742 break;
743 case VINF_EM_RAW_INTERRUPT_PENDING:
744 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetInterruptPending);
745 break;
746 case VINF_VMM_CALL_HOST:
747 switch (pVCpu->vmm.s.enmCallRing3Operation)
748 {
749 case VMMCALLRING3_PDM_CRIT_SECT_ENTER:
750 STAM_COUNTER_INC(&pVM->vmm.s.StatRZCallPDMCritSectEnter);
751 break;
752 case VMMCALLRING3_PDM_LOCK:
753 STAM_COUNTER_INC(&pVM->vmm.s.StatRZCallPDMLock);
754 break;
755 case VMMCALLRING3_PGM_POOL_GROW:
756 STAM_COUNTER_INC(&pVM->vmm.s.StatRZCallPGMPoolGrow);
757 break;
758 case VMMCALLRING3_PGM_LOCK:
759 STAM_COUNTER_INC(&pVM->vmm.s.StatRZCallPGMLock);
760 break;
761 case VMMCALLRING3_PGM_MAP_CHUNK:
762 STAM_COUNTER_INC(&pVM->vmm.s.StatRZCallPGMMapChunk);
763 break;
764 case VMMCALLRING3_PGM_ALLOCATE_HANDY_PAGES:
765 STAM_COUNTER_INC(&pVM->vmm.s.StatRZCallPGMAllocHandy);
766 break;
767 case VMMCALLRING3_REM_REPLAY_HANDLER_NOTIFICATIONS:
768 STAM_COUNTER_INC(&pVM->vmm.s.StatRZCallRemReplay);
769 break;
770 case VMMCALLRING3_VMM_LOGGER_FLUSH:
771 STAM_COUNTER_INC(&pVM->vmm.s.StatRZCallLogFlush);
772 break;
773 case VMMCALLRING3_VM_SET_ERROR:
774 STAM_COUNTER_INC(&pVM->vmm.s.StatRZCallVMSetError);
775 break;
776 case VMMCALLRING3_VM_SET_RUNTIME_ERROR:
777 STAM_COUNTER_INC(&pVM->vmm.s.StatRZCallVMSetRuntimeError);
778 break;
779 case VMMCALLRING3_VM_R0_ASSERTION:
780 default:
781 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetCallRing3);
782 break;
783 }
784 break;
785 case VINF_PATM_DUPLICATE_FUNCTION:
786 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPATMDuplicateFn);
787 break;
788 case VINF_PGM_CHANGE_MODE:
789 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPGMChangeMode);
790 break;
791 case VINF_PGM_POOL_FLUSH_PENDING:
792 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPGMFlushPending);
793 break;
794 case VINF_EM_PENDING_REQUEST:
795 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPendingRequest);
796 break;
797 case VINF_EM_HM_PATCH_TPR_INSTR:
798 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPatchTPR);
799 break;
800 default:
801 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMisc);
802 break;
803 }
804}
805#endif /* VBOX_WITH_STATISTICS */
806
807
808/**
809 * Unused ring-0 entry point that used to be called from the interrupt gate.
810 *
811 * Will be removed one of the next times we do a major SUPDrv version bump.
812 *
813 * @returns VBox status code.
814 * @param pVM Pointer to the VM.
815 * @param enmOperation Which operation to execute.
816 * @param pvArg Argument to the operation.
817 * @remarks Assume called with interrupts disabled.
818 */
819VMMR0DECL(int) VMMR0EntryInt(PVM pVM, VMMR0OPERATION enmOperation, void *pvArg)
820{
821 /*
822 * We're returning VERR_NOT_SUPPORT here so we've got something else
823 * than -1 which the interrupt gate glue code might return.
824 */
825 Log(("operation %#x is not supported\n", enmOperation));
826 NOREF(enmOperation); NOREF(pvArg); NOREF(pVM);
827 return VERR_NOT_SUPPORTED;
828}
829
830
831/**
832 * The Ring 0 entry point, called by the fast-ioctl path.
833 *
834 * @param pVM Pointer to the VM.
835 * The return code is stored in pVM->vmm.s.iLastGZRc.
836 * @param idCpu The Virtual CPU ID of the calling EMT.
837 * @param enmOperation Which operation to execute.
838 * @remarks Assume called with interrupts _enabled_.
839 */
840VMMR0DECL(void) VMMR0EntryFast(PVM pVM, VMCPUID idCpu, VMMR0OPERATION enmOperation)
841{
842 /*
843 * Validation.
844 */
845 if (RT_UNLIKELY(idCpu >= pVM->cCpus))
846 return;
847 PVMCPU pVCpu = &pVM->aCpus[idCpu];
848 if (RT_UNLIKELY(pVCpu->hNativeThreadR0 != RTThreadNativeSelf()))
849 return;
850
851 /*
852 * Perform requested operation.
853 */
854 switch (enmOperation)
855 {
856 /*
857 * Switch to GC and run guest raw mode code.
858 * Disable interrupts before doing the world switch.
859 */
860 case VMMR0_DO_RAW_RUN:
861 {
862#ifndef VBOX_WITH_2X_4GB_ADDR_SPACE_IN_R0
863 /* Some safety precautions first. */
864 if (RT_UNLIKELY(!PGMGetHyperCR3(pVCpu)))
865 {
866 pVCpu->vmm.s.iLastGZRc = VERR_PGM_NO_CR3_SHADOW_ROOT;
867 break;
868 }
869#endif
870
871 /*
872 * Disable preemption.
873 */
874 RTTHREADPREEMPTSTATE PreemptState = RTTHREADPREEMPTSTATE_INITIALIZER;
875 RTThreadPreemptDisable(&PreemptState);
876
877 /*
878 * Get the host CPU identifiers, make sure they are valid and that
879 * we've got a TSC delta for the CPU.
880 */
881 RTCPUID idHostCpu = RTMpCpuId();
882 uint32_t iHostCpuSet = RTMpCpuIdToSetIndex(idHostCpu);
883 if (RT_LIKELY( iHostCpuSet < RTCPUSET_MAX_CPUS
884 && SUPIsTscDeltaAvailableForCpuSetIndex(iHostCpuSet)))
885 {
886 /*
887 * Commit the CPU identifiers and update the periodict preemption timer if it's active.
888 */
889#ifdef VBOX_WITH_VMMR0_DISABLE_LAPIC_NMI
890 CPUMR0SetLApic(pVCpu, iHostCpuSet);
891#endif
892 pVCpu->iHostCpuSet = iHostCpuSet;
893 ASMAtomicWriteU32(&pVCpu->idHostCpu, idHostCpu);
894
895 if (pVM->vmm.s.fUsePeriodicPreemptionTimers)
896 GVMMR0SchedUpdatePeriodicPreemptionTimer(pVM, pVCpu->idHostCpu, TMCalcHostTimerFrequency(pVM, pVCpu));
897
898 /*
899 * We might need to disable VT-x if the active switcher turns off paging.
900 */
901 bool fVTxDisabled;
902 int rc = HMR0EnterSwitcher(pVM, pVM->vmm.s.enmSwitcher, &fVTxDisabled);
903 if (RT_SUCCESS(rc))
904 {
905 /*
906 * Disable interrupts and run raw-mode code. The loop is for efficiently
907 * dispatching tracepoints that fired in raw-mode context.
908 */
909 RTCCUINTREG uFlags = ASMIntDisableFlags();
910
911 for (;;)
912 {
913 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC);
914 TMNotifyStartOfExecution(pVCpu);
915
916 rc = pVM->vmm.s.pfnR0ToRawMode(pVM);
917 pVCpu->vmm.s.iLastGZRc = rc;
918
919 TMNotifyEndOfExecution(pVCpu);
920 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED);
921
922 if (rc != VINF_VMM_CALL_TRACER)
923 break;
924 SUPR0TracerUmodProbeFire(pVM->pSession, &pVCpu->vmm.s.TracerCtx);
925 }
926
927 /*
928 * Re-enable VT-x before we dispatch any pending host interrupts and
929 * re-enables interrupts.
930 */
931 HMR0LeaveSwitcher(pVM, fVTxDisabled);
932
933 if ( rc == VINF_EM_RAW_INTERRUPT
934 || rc == VINF_EM_RAW_INTERRUPT_HYPER)
935 TRPMR0DispatchHostInterrupt(pVM);
936
937 ASMSetFlags(uFlags);
938
939 /* Fire dtrace probe and collect statistics. */
940 VBOXVMM_R0_VMM_RETURN_TO_RING3_RC(pVCpu, CPUMQueryGuestCtxPtr(pVCpu), rc);
941#ifdef VBOX_WITH_STATISTICS
942 STAM_COUNTER_INC(&pVM->vmm.s.StatRunRC);
943 vmmR0RecordRC(pVM, pVCpu, rc);
944#endif
945 }
946 else
947 pVCpu->vmm.s.iLastGZRc = rc;
948
949 /*
950 * Invalidate the host CPU identifiers as we restore preemption.
951 */
952 pVCpu->iHostCpuSet = UINT32_MAX;
953 ASMAtomicWriteU32(&pVCpu->idHostCpu, NIL_RTCPUID);
954
955 RTThreadPreemptRestore(&PreemptState);
956 }
957 /*
958 * Invalid CPU set index or TSC delta in need of measuring.
959 */
960 else
961 {
962 RTThreadPreemptRestore(&PreemptState);
963 if (iHostCpuSet < RTCPUSET_MAX_CPUS)
964 {
965 int rc = SUPR0TscDeltaMeasureBySetIndex(pVM->pSession, iHostCpuSet, 0 /*fFlags*/,
966 2 /*cMsWaitRetry*/, 5*RT_MS_1SEC /*cMsWaitThread*/,
967 0 /*default cTries*/);
968 if (RT_SUCCESS(rc) || rc == VERR_CPU_OFFLINE)
969 pVCpu->vmm.s.iLastGZRc = VINF_EM_RAW_TO_R3;
970 else
971 pVCpu->vmm.s.iLastGZRc = rc;
972 }
973 else
974 pVCpu->vmm.s.iLastGZRc = VERR_INVALID_CPU_INDEX;
975 }
976 break;
977 }
978
979 /*
980 * Run guest code using the available hardware acceleration technology.
981 */
982 case VMMR0_DO_HM_RUN:
983 {
984 /*
985 * Disable preemption.
986 */
987 Assert(!VMMR0ThreadCtxHooksAreRegistered(pVCpu));
988 RTTHREADPREEMPTSTATE PreemptState = RTTHREADPREEMPTSTATE_INITIALIZER;
989 RTThreadPreemptDisable(&PreemptState);
990
991 /*
992 * Get the host CPU identifiers, make sure they are valid and that
993 * we've got a TSC delta for the CPU.
994 */
995 RTCPUID idHostCpu = RTMpCpuId();
996 uint32_t iHostCpuSet = RTMpCpuIdToSetIndex(idHostCpu);
997 if (RT_LIKELY( iHostCpuSet < RTCPUSET_MAX_CPUS
998 && SUPIsTscDeltaAvailableForCpuSetIndex(iHostCpuSet)))
999 {
1000 pVCpu->iHostCpuSet = iHostCpuSet;
1001 ASMAtomicWriteU32(&pVCpu->idHostCpu, idHostCpu);
1002
1003 /*
1004 * Update the periodict preemption timer if it's active.
1005 */
1006 if (pVM->vmm.s.fUsePeriodicPreemptionTimers)
1007 GVMMR0SchedUpdatePeriodicPreemptionTimer(pVM, pVCpu->idHostCpu, TMCalcHostTimerFrequency(pVM, pVCpu));
1008
1009#ifdef LOG_ENABLED
1010 /*
1011 * Ugly: Lazy registration of ring 0 loggers.
1012 */
1013 if (pVCpu->idCpu > 0)
1014 {
1015 PVMMR0LOGGER pR0Logger = pVCpu->vmm.s.pR0LoggerR0;
1016 if ( pR0Logger
1017 && RT_UNLIKELY(!pR0Logger->fRegistered))
1018 {
1019 RTLogSetDefaultInstanceThread(&pR0Logger->Logger, (uintptr_t)pVM->pSession);
1020 pR0Logger->fRegistered = true;
1021 }
1022 }
1023#endif
1024
1025 int rc;
1026 bool fPreemptRestored = false;
1027 if (!HMR0SuspendPending())
1028 {
1029 /*
1030 * Register thread-context hooks if required.
1031 */
1032 if ( VMMR0ThreadCtxHooksAreCreated(pVCpu)
1033 && !VMMR0ThreadCtxHooksAreRegistered(pVCpu))
1034 {
1035 rc = VMMR0ThreadCtxHooksRegister(pVCpu, vmmR0ThreadCtxCallback);
1036 AssertRC(rc);
1037 }
1038
1039 /*
1040 * Enter HM context.
1041 */
1042 rc = HMR0Enter(pVM, pVCpu);
1043 if (RT_SUCCESS(rc))
1044 {
1045 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
1046
1047 /*
1048 * When preemption hooks are in place, enable preemption now that
1049 * we're in HM context.
1050 */
1051 if (VMMR0ThreadCtxHooksAreRegistered(pVCpu))
1052 {
1053 fPreemptRestored = true;
1054 RTThreadPreemptRestore(&PreemptState);
1055 }
1056
1057 /*
1058 * Setup the longjmp machinery and execute guest code (calls HMR0RunGuestCode).
1059 */
1060 rc = vmmR0CallRing3SetJmp(&pVCpu->vmm.s.CallRing3JmpBufR0, HMR0RunGuestCode, pVM, pVCpu);
1061
1062 /*
1063 * Assert sanity on the way out. Using manual assertions code here as normal
1064 * assertions are going to panic the host since we're outside the setjmp/longjmp zone.
1065 */
1066 if (RT_UNLIKELY( VMCPU_GET_STATE(pVCpu) != VMCPUSTATE_STARTED_HM
1067 && RT_SUCCESS_NP(rc) && rc != VINF_VMM_CALL_HOST ))
1068 {
1069 pVM->vmm.s.szRing0AssertMsg1[0] = '\0';
1070 RTStrPrintf(pVM->vmm.s.szRing0AssertMsg2, sizeof(pVM->vmm.s.szRing0AssertMsg2),
1071 "Got VMCPU state %d expected %d.\n", VMCPU_GET_STATE(pVCpu), VMCPUSTATE_STARTED_HM);
1072 rc = VERR_VMM_WRONG_HM_VMCPU_STATE;
1073 }
1074 else if (RT_UNLIKELY(VMMR0ThreadCtxHooksAreRegistered(pVCpu)))
1075 {
1076 pVM->vmm.s.szRing0AssertMsg1[0] = '\0';
1077 RTStrPrintf(pVM->vmm.s.szRing0AssertMsg2, sizeof(pVM->vmm.s.szRing0AssertMsg2),
1078 "Thread-context hooks still registered! VCPU=%p Id=%u rc=%d.\n", pVCpu, pVCpu->idCpu, rc);
1079 rc = VERR_INVALID_STATE;
1080 }
1081
1082 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED);
1083 }
1084 STAM_COUNTER_INC(&pVM->vmm.s.StatRunRC);
1085 }
1086 /*
1087 * The system is about to go into suspend mode; go back to ring 3.
1088 */
1089 else
1090 rc = VINF_EM_RAW_INTERRUPT;
1091
1092 pVCpu->vmm.s.iLastGZRc = rc;
1093
1094 /*
1095 * Invalidate the host CPU identifiers as we restore preemption.
1096 */
1097 pVCpu->iHostCpuSet = UINT32_MAX;
1098 ASMAtomicWriteU32(&pVCpu->idHostCpu, NIL_RTCPUID);
1099
1100 if (!fPreemptRestored)
1101 RTThreadPreemptRestore(&PreemptState);
1102
1103 /* Fire dtrace probe and collect statistics. */
1104 VBOXVMM_R0_VMM_RETURN_TO_RING3_HM(pVCpu, CPUMQueryGuestCtxPtr(pVCpu), rc);
1105#ifdef VBOX_WITH_STATISTICS
1106 vmmR0RecordRC(pVM, pVCpu, rc);
1107#endif
1108 }
1109 /*
1110 * Invalid CPU set index or TSC delta in need of measuring.
1111 */
1112 else
1113 {
1114 RTThreadPreemptRestore(&PreemptState);
1115 if (iHostCpuSet < RTCPUSET_MAX_CPUS)
1116 {
1117 int rc = SUPR0TscDeltaMeasureBySetIndex(pVM->pSession, iHostCpuSet, 0 /*fFlags*/,
1118 2 /*cMsWaitRetry*/, 5*RT_MS_1SEC /*cMsWaitThread*/,
1119 0 /*default cTries*/);
1120 if (RT_SUCCESS(rc) || rc == VERR_CPU_OFFLINE)
1121 pVCpu->vmm.s.iLastGZRc = VINF_EM_RAW_TO_R3;
1122 else
1123 pVCpu->vmm.s.iLastGZRc = rc;
1124 }
1125 else
1126 pVCpu->vmm.s.iLastGZRc = VERR_INVALID_CPU_INDEX;
1127 }
1128 break;
1129 }
1130
1131 /*
1132 * For profiling.
1133 */
1134 case VMMR0_DO_NOP:
1135 pVCpu->vmm.s.iLastGZRc = VINF_SUCCESS;
1136 break;
1137
1138 /*
1139 * Impossible.
1140 */
1141 default:
1142 AssertMsgFailed(("%#x\n", enmOperation));
1143 pVCpu->vmm.s.iLastGZRc = VERR_NOT_SUPPORTED;
1144 break;
1145 }
1146}
1147
1148
1149/**
1150 * Validates a session or VM session argument.
1151 *
1152 * @returns true / false accordingly.
1153 * @param pVM Pointer to the VM.
1154 * @param pSession The session argument.
1155 */
1156DECLINLINE(bool) vmmR0IsValidSession(PVM pVM, PSUPDRVSESSION pClaimedSession, PSUPDRVSESSION pSession)
1157{
1158 /* This must be set! */
1159 if (!pSession)
1160 return false;
1161
1162 /* Only one out of the two. */
1163 if (pVM && pClaimedSession)
1164 return false;
1165 if (pVM)
1166 pClaimedSession = pVM->pSession;
1167 return pClaimedSession == pSession;
1168}
1169
1170
1171/**
1172 * VMMR0EntryEx worker function, either called directly or when ever possible
1173 * called thru a longjmp so we can exit safely on failure.
1174 *
1175 * @returns VBox status code.
1176 * @param pVM Pointer to the VM.
1177 * @param idCpu Virtual CPU ID argument. Must be NIL_VMCPUID if pVM
1178 * is NIL_RTR0PTR, and may be NIL_VMCPUID if it isn't
1179 * @param enmOperation Which operation to execute.
1180 * @param pReqHdr This points to a SUPVMMR0REQHDR packet. Optional.
1181 * The support driver validates this if it's present.
1182 * @param u64Arg Some simple constant argument.
1183 * @param pSession The session of the caller.
1184 * @remarks Assume called with interrupts _enabled_.
1185 */
1186static int vmmR0EntryExWorker(PVM pVM, VMCPUID idCpu, VMMR0OPERATION enmOperation, PSUPVMMR0REQHDR pReqHdr, uint64_t u64Arg, PSUPDRVSESSION pSession)
1187{
1188 /*
1189 * Common VM pointer validation.
1190 */
1191 if (pVM)
1192 {
1193 if (RT_UNLIKELY( !VALID_PTR(pVM)
1194 || ((uintptr_t)pVM & PAGE_OFFSET_MASK)))
1195 {
1196 SUPR0Printf("vmmR0EntryExWorker: Invalid pVM=%p! (op=%d)\n", pVM, enmOperation);
1197 return VERR_INVALID_POINTER;
1198 }
1199 if (RT_UNLIKELY( pVM->enmVMState < VMSTATE_CREATING
1200 || pVM->enmVMState > VMSTATE_TERMINATED
1201 || pVM->pVMR0 != pVM))
1202 {
1203 SUPR0Printf("vmmR0EntryExWorker: Invalid pVM=%p:{enmVMState=%d, .pVMR0=%p}! (op=%d)\n",
1204 pVM, pVM->enmVMState, pVM->pVMR0, enmOperation);
1205 return VERR_INVALID_POINTER;
1206 }
1207
1208 if (RT_UNLIKELY(idCpu >= pVM->cCpus && idCpu != NIL_VMCPUID))
1209 {
1210 SUPR0Printf("vmmR0EntryExWorker: Invalid idCpu (%u vs cCpus=%u)\n", idCpu, pVM->cCpus);
1211 return VERR_INVALID_PARAMETER;
1212 }
1213 }
1214 else if (RT_UNLIKELY(idCpu != NIL_VMCPUID))
1215 {
1216 SUPR0Printf("vmmR0EntryExWorker: Invalid idCpu=%u\n", idCpu);
1217 return VERR_INVALID_PARAMETER;
1218 }
1219
1220
1221 switch (enmOperation)
1222 {
1223 /*
1224 * GVM requests
1225 */
1226 case VMMR0_DO_GVMM_CREATE_VM:
1227 if (pVM || u64Arg || idCpu != NIL_VMCPUID)
1228 return VERR_INVALID_PARAMETER;
1229 return GVMMR0CreateVMReq((PGVMMCREATEVMREQ)pReqHdr);
1230
1231 case VMMR0_DO_GVMM_DESTROY_VM:
1232 if (pReqHdr || u64Arg)
1233 return VERR_INVALID_PARAMETER;
1234 return GVMMR0DestroyVM(pVM);
1235
1236 case VMMR0_DO_GVMM_REGISTER_VMCPU:
1237 {
1238 if (!pVM)
1239 return VERR_INVALID_PARAMETER;
1240 return GVMMR0RegisterVCpu(pVM, idCpu);
1241 }
1242
1243 case VMMR0_DO_GVMM_SCHED_HALT:
1244 if (pReqHdr)
1245 return VERR_INVALID_PARAMETER;
1246 return GVMMR0SchedHalt(pVM, idCpu, u64Arg);
1247
1248 case VMMR0_DO_GVMM_SCHED_WAKE_UP:
1249 if (pReqHdr || u64Arg)
1250 return VERR_INVALID_PARAMETER;
1251 return GVMMR0SchedWakeUp(pVM, idCpu);
1252
1253 case VMMR0_DO_GVMM_SCHED_POKE:
1254 if (pReqHdr || u64Arg)
1255 return VERR_INVALID_PARAMETER;
1256 return GVMMR0SchedPoke(pVM, idCpu);
1257
1258 case VMMR0_DO_GVMM_SCHED_WAKE_UP_AND_POKE_CPUS:
1259 if (u64Arg)
1260 return VERR_INVALID_PARAMETER;
1261 return GVMMR0SchedWakeUpAndPokeCpusReq(pVM, (PGVMMSCHEDWAKEUPANDPOKECPUSREQ)pReqHdr);
1262
1263 case VMMR0_DO_GVMM_SCHED_POLL:
1264 if (pReqHdr || u64Arg > 1)
1265 return VERR_INVALID_PARAMETER;
1266 return GVMMR0SchedPoll(pVM, idCpu, !!u64Arg);
1267
1268 case VMMR0_DO_GVMM_QUERY_STATISTICS:
1269 if (u64Arg)
1270 return VERR_INVALID_PARAMETER;
1271 return GVMMR0QueryStatisticsReq(pVM, (PGVMMQUERYSTATISTICSSREQ)pReqHdr);
1272
1273 case VMMR0_DO_GVMM_RESET_STATISTICS:
1274 if (u64Arg)
1275 return VERR_INVALID_PARAMETER;
1276 return GVMMR0ResetStatisticsReq(pVM, (PGVMMRESETSTATISTICSSREQ)pReqHdr);
1277
1278 /*
1279 * Initialize the R0 part of a VM instance.
1280 */
1281 case VMMR0_DO_VMMR0_INIT:
1282 return vmmR0InitVM(pVM, RT_LODWORD(u64Arg), RT_HIDWORD(u64Arg));
1283
1284 /*
1285 * Terminate the R0 part of a VM instance.
1286 */
1287 case VMMR0_DO_VMMR0_TERM:
1288 return VMMR0TermVM(pVM, NULL);
1289
1290 /*
1291 * Attempt to enable hm mode and check the current setting.
1292 */
1293 case VMMR0_DO_HM_ENABLE:
1294 return HMR0EnableAllCpus(pVM);
1295
1296 /*
1297 * Setup the hardware accelerated session.
1298 */
1299 case VMMR0_DO_HM_SETUP_VM:
1300 return HMR0SetupVM(pVM);
1301
1302 /*
1303 * Switch to RC to execute Hypervisor function.
1304 */
1305 case VMMR0_DO_CALL_HYPERVISOR:
1306 {
1307 /*
1308 * Validate input / context.
1309 */
1310 if (RT_UNLIKELY(idCpu != 0))
1311 return VERR_INVALID_CPU_ID;
1312 if (RT_UNLIKELY(pVM->cCpus != 1))
1313 return VERR_INVALID_PARAMETER;
1314 PVMCPU pVCpu = &pVM->aCpus[idCpu];
1315#ifndef VBOX_WITH_2X_4GB_ADDR_SPACE_IN_R0
1316 if (RT_UNLIKELY(!PGMGetHyperCR3(pVCpu)))
1317 return VERR_PGM_NO_CR3_SHADOW_ROOT;
1318#endif
1319
1320 /*
1321 * Disable interrupts.
1322 */
1323 RTCCUINTREG fFlags = ASMIntDisableFlags();
1324
1325 /*
1326 * Get the host CPU identifiers, make sure they are valid and that
1327 * we've got a TSC delta for the CPU.
1328 */
1329 RTCPUID idHostCpu = RTMpCpuId();
1330 uint32_t iHostCpuSet = RTMpCpuIdToSetIndex(idHostCpu);
1331 if (RT_UNLIKELY(iHostCpuSet >= RTCPUSET_MAX_CPUS))
1332 {
1333 ASMSetFlags(fFlags);
1334 return VERR_INVALID_CPU_INDEX;
1335 }
1336 if (RT_UNLIKELY(!SUPIsTscDeltaAvailableForCpuSetIndex(iHostCpuSet)))
1337 {
1338 ASMSetFlags(fFlags);
1339 int rc = SUPR0TscDeltaMeasureBySetIndex(pVM->pSession, iHostCpuSet, 0 /*fFlags*/,
1340 2 /*cMsWaitRetry*/, 5*RT_MS_1SEC /*cMsWaitThread*/,
1341 0 /*default cTries*/);
1342 if (RT_FAILURE(rc) && rc != VERR_CPU_OFFLINE)
1343 return rc;
1344 }
1345
1346 /*
1347 * Commit the CPU identifiers.
1348 */
1349#ifdef VBOX_WITH_VMMR0_DISABLE_LAPIC_NMI
1350 CPUMR0SetLApic(pVCpu, iHostCpuSet);
1351#endif
1352 pVCpu->iHostCpuSet = iHostCpuSet;
1353 ASMAtomicWriteU32(&pVCpu->idHostCpu, idHostCpu);
1354
1355 /*
1356 * We might need to disable VT-x if the active switcher turns off paging.
1357 */
1358 bool fVTxDisabled;
1359 int rc = HMR0EnterSwitcher(pVM, pVM->vmm.s.enmSwitcher, &fVTxDisabled);
1360 if (RT_SUCCESS(rc))
1361 {
1362 /*
1363 * Go through the wormhole...
1364 */
1365 rc = pVM->vmm.s.pfnR0ToRawMode(pVM);
1366
1367 /*
1368 * Re-enable VT-x before we dispatch any pending host interrupts.
1369 */
1370 HMR0LeaveSwitcher(pVM, fVTxDisabled);
1371
1372 if ( rc == VINF_EM_RAW_INTERRUPT
1373 || rc == VINF_EM_RAW_INTERRUPT_HYPER)
1374 TRPMR0DispatchHostInterrupt(pVM);
1375 }
1376
1377 /*
1378 * Invalidate the host CPU identifiers as we restore interrupts.
1379 */
1380 pVCpu->iHostCpuSet = UINT32_MAX;
1381 ASMAtomicWriteU32(&pVCpu->idHostCpu, NIL_RTCPUID);
1382 ASMSetFlags(fFlags);
1383 return rc;
1384 }
1385
1386 /*
1387 * PGM wrappers.
1388 */
1389 case VMMR0_DO_PGM_ALLOCATE_HANDY_PAGES:
1390 if (idCpu == NIL_VMCPUID)
1391 return VERR_INVALID_CPU_ID;
1392 return PGMR0PhysAllocateHandyPages(pVM, &pVM->aCpus[idCpu]);
1393
1394 case VMMR0_DO_PGM_FLUSH_HANDY_PAGES:
1395 if (idCpu == NIL_VMCPUID)
1396 return VERR_INVALID_CPU_ID;
1397 return PGMR0PhysFlushHandyPages(pVM, &pVM->aCpus[idCpu]);
1398
1399 case VMMR0_DO_PGM_ALLOCATE_LARGE_HANDY_PAGE:
1400 if (idCpu == NIL_VMCPUID)
1401 return VERR_INVALID_CPU_ID;
1402 return PGMR0PhysAllocateLargeHandyPage(pVM, &pVM->aCpus[idCpu]);
1403
1404 case VMMR0_DO_PGM_PHYS_SETUP_IOMMU:
1405 if (idCpu != 0)
1406 return VERR_INVALID_CPU_ID;
1407 return PGMR0PhysSetupIommu(pVM);
1408
1409 /*
1410 * GMM wrappers.
1411 */
1412 case VMMR0_DO_GMM_INITIAL_RESERVATION:
1413 if (u64Arg)
1414 return VERR_INVALID_PARAMETER;
1415 return GMMR0InitialReservationReq(pVM, idCpu, (PGMMINITIALRESERVATIONREQ)pReqHdr);
1416
1417 case VMMR0_DO_GMM_UPDATE_RESERVATION:
1418 if (u64Arg)
1419 return VERR_INVALID_PARAMETER;
1420 return GMMR0UpdateReservationReq(pVM, idCpu, (PGMMUPDATERESERVATIONREQ)pReqHdr);
1421
1422 case VMMR0_DO_GMM_ALLOCATE_PAGES:
1423 if (u64Arg)
1424 return VERR_INVALID_PARAMETER;
1425 return GMMR0AllocatePagesReq(pVM, idCpu, (PGMMALLOCATEPAGESREQ)pReqHdr);
1426
1427 case VMMR0_DO_GMM_FREE_PAGES:
1428 if (u64Arg)
1429 return VERR_INVALID_PARAMETER;
1430 return GMMR0FreePagesReq(pVM, idCpu, (PGMMFREEPAGESREQ)pReqHdr);
1431
1432 case VMMR0_DO_GMM_FREE_LARGE_PAGE:
1433 if (u64Arg)
1434 return VERR_INVALID_PARAMETER;
1435 return GMMR0FreeLargePageReq(pVM, idCpu, (PGMMFREELARGEPAGEREQ)pReqHdr);
1436
1437 case VMMR0_DO_GMM_QUERY_HYPERVISOR_MEM_STATS:
1438 if (u64Arg)
1439 return VERR_INVALID_PARAMETER;
1440 return GMMR0QueryHypervisorMemoryStatsReq(pVM, (PGMMMEMSTATSREQ)pReqHdr);
1441
1442 case VMMR0_DO_GMM_QUERY_MEM_STATS:
1443 if (idCpu == NIL_VMCPUID)
1444 return VERR_INVALID_CPU_ID;
1445 if (u64Arg)
1446 return VERR_INVALID_PARAMETER;
1447 return GMMR0QueryMemoryStatsReq(pVM, idCpu, (PGMMMEMSTATSREQ)pReqHdr);
1448
1449 case VMMR0_DO_GMM_BALLOONED_PAGES:
1450 if (u64Arg)
1451 return VERR_INVALID_PARAMETER;
1452 return GMMR0BalloonedPagesReq(pVM, idCpu, (PGMMBALLOONEDPAGESREQ)pReqHdr);
1453
1454 case VMMR0_DO_GMM_MAP_UNMAP_CHUNK:
1455 if (u64Arg)
1456 return VERR_INVALID_PARAMETER;
1457 return GMMR0MapUnmapChunkReq(pVM, (PGMMMAPUNMAPCHUNKREQ)pReqHdr);
1458
1459 case VMMR0_DO_GMM_SEED_CHUNK:
1460 if (pReqHdr)
1461 return VERR_INVALID_PARAMETER;
1462 return GMMR0SeedChunk(pVM, idCpu, (RTR3PTR)u64Arg);
1463
1464 case VMMR0_DO_GMM_REGISTER_SHARED_MODULE:
1465 if (idCpu == NIL_VMCPUID)
1466 return VERR_INVALID_CPU_ID;
1467 if (u64Arg)
1468 return VERR_INVALID_PARAMETER;
1469 return GMMR0RegisterSharedModuleReq(pVM, idCpu, (PGMMREGISTERSHAREDMODULEREQ)pReqHdr);
1470
1471 case VMMR0_DO_GMM_UNREGISTER_SHARED_MODULE:
1472 if (idCpu == NIL_VMCPUID)
1473 return VERR_INVALID_CPU_ID;
1474 if (u64Arg)
1475 return VERR_INVALID_PARAMETER;
1476 return GMMR0UnregisterSharedModuleReq(pVM, idCpu, (PGMMUNREGISTERSHAREDMODULEREQ)pReqHdr);
1477
1478 case VMMR0_DO_GMM_RESET_SHARED_MODULES:
1479 if (idCpu == NIL_VMCPUID)
1480 return VERR_INVALID_CPU_ID;
1481 if ( u64Arg
1482 || pReqHdr)
1483 return VERR_INVALID_PARAMETER;
1484 return GMMR0ResetSharedModules(pVM, idCpu);
1485
1486#ifdef VBOX_WITH_PAGE_SHARING
1487 case VMMR0_DO_GMM_CHECK_SHARED_MODULES:
1488 {
1489 if (idCpu == NIL_VMCPUID)
1490 return VERR_INVALID_CPU_ID;
1491 if ( u64Arg
1492 || pReqHdr)
1493 return VERR_INVALID_PARAMETER;
1494
1495 PVMCPU pVCpu = &pVM->aCpus[idCpu];
1496 Assert(pVCpu->hNativeThreadR0 == RTThreadNativeSelf());
1497
1498# ifdef DEBUG_sandervl
1499 /* Make sure that log flushes can jump back to ring-3; annoying to get an incomplete log (this is risky though as the code doesn't take this into account). */
1500 /* Todo: this can have bad side effects for unexpected jumps back to r3. */
1501 int rc = GMMR0CheckSharedModulesStart(pVM);
1502 if (rc == VINF_SUCCESS)
1503 {
1504 rc = vmmR0CallRing3SetJmp(&pVCpu->vmm.s.CallRing3JmpBufR0, GMMR0CheckSharedModules, pVM, pVCpu); /* this may resume code. */
1505 Assert( rc == VINF_SUCCESS
1506 || (rc == VINF_VMM_CALL_HOST && pVCpu->vmm.s.enmCallRing3Operation == VMMCALLRING3_VMM_LOGGER_FLUSH));
1507 GMMR0CheckSharedModulesEnd(pVM);
1508 }
1509# else
1510 int rc = GMMR0CheckSharedModules(pVM, pVCpu);
1511# endif
1512 return rc;
1513 }
1514#endif
1515
1516#if defined(VBOX_STRICT) && HC_ARCH_BITS == 64
1517 case VMMR0_DO_GMM_FIND_DUPLICATE_PAGE:
1518 if (u64Arg)
1519 return VERR_INVALID_PARAMETER;
1520 return GMMR0FindDuplicatePageReq(pVM, (PGMMFINDDUPLICATEPAGEREQ)pReqHdr);
1521#endif
1522
1523 case VMMR0_DO_GMM_QUERY_STATISTICS:
1524 if (u64Arg)
1525 return VERR_INVALID_PARAMETER;
1526 return GMMR0QueryStatisticsReq(pVM, (PGMMQUERYSTATISTICSSREQ)pReqHdr);
1527
1528 case VMMR0_DO_GMM_RESET_STATISTICS:
1529 if (u64Arg)
1530 return VERR_INVALID_PARAMETER;
1531 return GMMR0ResetStatisticsReq(pVM, (PGMMRESETSTATISTICSSREQ)pReqHdr);
1532
1533 /*
1534 * A quick GCFGM mock-up.
1535 */
1536 /** @todo GCFGM with proper access control, ring-3 management interface and all that. */
1537 case VMMR0_DO_GCFGM_SET_VALUE:
1538 case VMMR0_DO_GCFGM_QUERY_VALUE:
1539 {
1540 if (pVM || !pReqHdr || u64Arg || idCpu != NIL_VMCPUID)
1541 return VERR_INVALID_PARAMETER;
1542 PGCFGMVALUEREQ pReq = (PGCFGMVALUEREQ)pReqHdr;
1543 if (pReq->Hdr.cbReq != sizeof(*pReq))
1544 return VERR_INVALID_PARAMETER;
1545 int rc;
1546 if (enmOperation == VMMR0_DO_GCFGM_SET_VALUE)
1547 {
1548 rc = GVMMR0SetConfig(pReq->pSession, &pReq->szName[0], pReq->u64Value);
1549 //if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1550 // rc = GMMR0SetConfig(pReq->pSession, &pReq->szName[0], pReq->u64Value);
1551 }
1552 else
1553 {
1554 rc = GVMMR0QueryConfig(pReq->pSession, &pReq->szName[0], &pReq->u64Value);
1555 //if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1556 // rc = GMMR0QueryConfig(pReq->pSession, &pReq->szName[0], &pReq->u64Value);
1557 }
1558 return rc;
1559 }
1560
1561 /*
1562 * PDM Wrappers.
1563 */
1564 case VMMR0_DO_PDM_DRIVER_CALL_REQ_HANDLER:
1565 {
1566 if (!pVM || !pReqHdr || u64Arg || idCpu != NIL_VMCPUID)
1567 return VERR_INVALID_PARAMETER;
1568 return PDMR0DriverCallReqHandler(pVM, (PPDMDRIVERCALLREQHANDLERREQ)pReqHdr);
1569 }
1570
1571 case VMMR0_DO_PDM_DEVICE_CALL_REQ_HANDLER:
1572 {
1573 if (!pVM || !pReqHdr || u64Arg || idCpu != NIL_VMCPUID)
1574 return VERR_INVALID_PARAMETER;
1575 return PDMR0DeviceCallReqHandler(pVM, (PPDMDEVICECALLREQHANDLERREQ)pReqHdr);
1576 }
1577
1578 /*
1579 * Requests to the internal networking service.
1580 */
1581 case VMMR0_DO_INTNET_OPEN:
1582 {
1583 PINTNETOPENREQ pReq = (PINTNETOPENREQ)pReqHdr;
1584 if (u64Arg || !pReq || !vmmR0IsValidSession(pVM, pReq->pSession, pSession) || idCpu != NIL_VMCPUID)
1585 return VERR_INVALID_PARAMETER;
1586 return IntNetR0OpenReq(pSession, pReq);
1587 }
1588
1589 case VMMR0_DO_INTNET_IF_CLOSE:
1590 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pVM, ((PINTNETIFCLOSEREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
1591 return VERR_INVALID_PARAMETER;
1592 return IntNetR0IfCloseReq(pSession, (PINTNETIFCLOSEREQ)pReqHdr);
1593
1594 case VMMR0_DO_INTNET_IF_GET_BUFFER_PTRS:
1595 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pVM, ((PINTNETIFGETBUFFERPTRSREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
1596 return VERR_INVALID_PARAMETER;
1597 return IntNetR0IfGetBufferPtrsReq(pSession, (PINTNETIFGETBUFFERPTRSREQ)pReqHdr);
1598
1599 case VMMR0_DO_INTNET_IF_SET_PROMISCUOUS_MODE:
1600 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pVM, ((PINTNETIFSETPROMISCUOUSMODEREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
1601 return VERR_INVALID_PARAMETER;
1602 return IntNetR0IfSetPromiscuousModeReq(pSession, (PINTNETIFSETPROMISCUOUSMODEREQ)pReqHdr);
1603
1604 case VMMR0_DO_INTNET_IF_SET_MAC_ADDRESS:
1605 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pVM, ((PINTNETIFSETMACADDRESSREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
1606 return VERR_INVALID_PARAMETER;
1607 return IntNetR0IfSetMacAddressReq(pSession, (PINTNETIFSETMACADDRESSREQ)pReqHdr);
1608
1609 case VMMR0_DO_INTNET_IF_SET_ACTIVE:
1610 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pVM, ((PINTNETIFSETACTIVEREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
1611 return VERR_INVALID_PARAMETER;
1612 return IntNetR0IfSetActiveReq(pSession, (PINTNETIFSETACTIVEREQ)pReqHdr);
1613
1614 case VMMR0_DO_INTNET_IF_SEND:
1615 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pVM, ((PINTNETIFSENDREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
1616 return VERR_INVALID_PARAMETER;
1617 return IntNetR0IfSendReq(pSession, (PINTNETIFSENDREQ)pReqHdr);
1618
1619 case VMMR0_DO_INTNET_IF_WAIT:
1620 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pVM, ((PINTNETIFWAITREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
1621 return VERR_INVALID_PARAMETER;
1622 return IntNetR0IfWaitReq(pSession, (PINTNETIFWAITREQ)pReqHdr);
1623
1624 case VMMR0_DO_INTNET_IF_ABORT_WAIT:
1625 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pVM, ((PINTNETIFWAITREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
1626 return VERR_INVALID_PARAMETER;
1627 return IntNetR0IfAbortWaitReq(pSession, (PINTNETIFABORTWAITREQ)pReqHdr);
1628
1629#ifdef VBOX_WITH_PCI_PASSTHROUGH
1630 /*
1631 * Requests to host PCI driver service.
1632 */
1633 case VMMR0_DO_PCIRAW_REQ:
1634 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pVM, ((PPCIRAWSENDREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
1635 return VERR_INVALID_PARAMETER;
1636 return PciRawR0ProcessReq(pSession, pVM, (PPCIRAWSENDREQ)pReqHdr);
1637#endif
1638 /*
1639 * For profiling.
1640 */
1641 case VMMR0_DO_NOP:
1642 case VMMR0_DO_SLOW_NOP:
1643 return VINF_SUCCESS;
1644
1645 /*
1646 * For testing Ring-0 APIs invoked in this environment.
1647 */
1648 case VMMR0_DO_TESTS:
1649 /** @todo make new test */
1650 return VINF_SUCCESS;
1651
1652
1653#if HC_ARCH_BITS == 32 && defined(VBOX_WITH_64_BITS_GUESTS) && !defined(VBOX_WITH_HYBRID_32BIT_KERNEL)
1654 case VMMR0_DO_TEST_SWITCHER3264:
1655 if (idCpu == NIL_VMCPUID)
1656 return VERR_INVALID_CPU_ID;
1657 return HMR0TestSwitcher3264(pVM);
1658#endif
1659 default:
1660 /*
1661 * We're returning VERR_NOT_SUPPORT here so we've got something else
1662 * than -1 which the interrupt gate glue code might return.
1663 */
1664 Log(("operation %#x is not supported\n", enmOperation));
1665 return VERR_NOT_SUPPORTED;
1666 }
1667}
1668
1669
1670/**
1671 * Argument for vmmR0EntryExWrapper containing the arguments for VMMR0EntryEx.
1672 */
1673typedef struct VMMR0ENTRYEXARGS
1674{
1675 PVM pVM;
1676 VMCPUID idCpu;
1677 VMMR0OPERATION enmOperation;
1678 PSUPVMMR0REQHDR pReq;
1679 uint64_t u64Arg;
1680 PSUPDRVSESSION pSession;
1681} VMMR0ENTRYEXARGS;
1682/** Pointer to a vmmR0EntryExWrapper argument package. */
1683typedef VMMR0ENTRYEXARGS *PVMMR0ENTRYEXARGS;
1684
1685/**
1686 * This is just a longjmp wrapper function for VMMR0EntryEx calls.
1687 *
1688 * @returns VBox status code.
1689 * @param pvArgs The argument package
1690 */
1691static DECLCALLBACK(int) vmmR0EntryExWrapper(void *pvArgs)
1692{
1693 return vmmR0EntryExWorker(((PVMMR0ENTRYEXARGS)pvArgs)->pVM,
1694 ((PVMMR0ENTRYEXARGS)pvArgs)->idCpu,
1695 ((PVMMR0ENTRYEXARGS)pvArgs)->enmOperation,
1696 ((PVMMR0ENTRYEXARGS)pvArgs)->pReq,
1697 ((PVMMR0ENTRYEXARGS)pvArgs)->u64Arg,
1698 ((PVMMR0ENTRYEXARGS)pvArgs)->pSession);
1699}
1700
1701
1702/**
1703 * The Ring 0 entry point, called by the support library (SUP).
1704 *
1705 * @returns VBox status code.
1706 * @param pVM Pointer to the VM.
1707 * @param idCpu Virtual CPU ID argument. Must be NIL_VMCPUID if pVM
1708 * is NIL_RTR0PTR, and may be NIL_VMCPUID if it isn't
1709 * @param enmOperation Which operation to execute.
1710 * @param pReq Pointer to the SUPVMMR0REQHDR packet. Optional.
1711 * @param u64Arg Some simple constant argument.
1712 * @param pSession The session of the caller.
1713 * @remarks Assume called with interrupts _enabled_.
1714 */
1715VMMR0DECL(int) VMMR0EntryEx(PVM pVM, VMCPUID idCpu, VMMR0OPERATION enmOperation, PSUPVMMR0REQHDR pReq, uint64_t u64Arg, PSUPDRVSESSION pSession)
1716{
1717 /*
1718 * Requests that should only happen on the EMT thread will be
1719 * wrapped in a setjmp so we can assert without causing trouble.
1720 */
1721 if ( VALID_PTR(pVM)
1722 && pVM->pVMR0
1723 && idCpu < pVM->cCpus)
1724 {
1725 switch (enmOperation)
1726 {
1727 /* These might/will be called before VMMR3Init. */
1728 case VMMR0_DO_GMM_INITIAL_RESERVATION:
1729 case VMMR0_DO_GMM_UPDATE_RESERVATION:
1730 case VMMR0_DO_GMM_ALLOCATE_PAGES:
1731 case VMMR0_DO_GMM_FREE_PAGES:
1732 case VMMR0_DO_GMM_BALLOONED_PAGES:
1733 /* On the mac we might not have a valid jmp buf, so check these as well. */
1734 case VMMR0_DO_VMMR0_INIT:
1735 case VMMR0_DO_VMMR0_TERM:
1736 {
1737 PVMCPU pVCpu = &pVM->aCpus[idCpu];
1738
1739 if (!pVCpu->vmm.s.CallRing3JmpBufR0.pvSavedStack)
1740 break;
1741
1742 /** @todo validate this EMT claim... GVM knows. */
1743 VMMR0ENTRYEXARGS Args;
1744 Args.pVM = pVM;
1745 Args.idCpu = idCpu;
1746 Args.enmOperation = enmOperation;
1747 Args.pReq = pReq;
1748 Args.u64Arg = u64Arg;
1749 Args.pSession = pSession;
1750 return vmmR0CallRing3SetJmpEx(&pVCpu->vmm.s.CallRing3JmpBufR0, vmmR0EntryExWrapper, &Args);
1751 }
1752
1753 default:
1754 break;
1755 }
1756 }
1757 return vmmR0EntryExWorker(pVM, idCpu, enmOperation, pReq, u64Arg, pSession);
1758}
1759
1760
1761/**
1762 * Checks whether we've armed the ring-0 long jump machinery.
1763 *
1764 * @returns @c true / @c false
1765 * @param pVCpu Pointer to the VMCPU.
1766 * @thread EMT
1767 * @sa VMMIsLongJumpArmed
1768 */
1769VMMR0_INT_DECL(bool) VMMR0IsLongJumpArmed(PVMCPU pVCpu)
1770{
1771#ifdef RT_ARCH_X86
1772 return pVCpu->vmm.s.CallRing3JmpBufR0.eip
1773 && !pVCpu->vmm.s.CallRing3JmpBufR0.fInRing3Call;
1774#else
1775 return pVCpu->vmm.s.CallRing3JmpBufR0.rip
1776 && !pVCpu->vmm.s.CallRing3JmpBufR0.fInRing3Call;
1777#endif
1778}
1779
1780
1781/**
1782 * Checks whether we've done a ring-3 long jump.
1783 *
1784 * @returns @c true / @c false
1785 * @param pVCpu Pointer to the VMCPU.
1786 * @thread EMT
1787 */
1788VMMR0_INT_DECL(bool) VMMR0IsInRing3LongJump(PVMCPU pVCpu)
1789{
1790 return pVCpu->vmm.s.CallRing3JmpBufR0.fInRing3Call;
1791}
1792
1793
1794/**
1795 * Internal R0 logger worker: Flush logger.
1796 *
1797 * @param pLogger The logger instance to flush.
1798 * @remark This function must be exported!
1799 */
1800VMMR0DECL(void) vmmR0LoggerFlush(PRTLOGGER pLogger)
1801{
1802#ifdef LOG_ENABLED
1803 /*
1804 * Convert the pLogger into a VM handle and 'call' back to Ring-3.
1805 * (This is a bit paranoid code.)
1806 */
1807 PVMMR0LOGGER pR0Logger = (PVMMR0LOGGER)((uintptr_t)pLogger - RT_OFFSETOF(VMMR0LOGGER, Logger));
1808 if ( !VALID_PTR(pR0Logger)
1809 || !VALID_PTR(pR0Logger + 1)
1810 || pLogger->u32Magic != RTLOGGER_MAGIC)
1811 {
1812# ifdef DEBUG
1813 SUPR0Printf("vmmR0LoggerFlush: pLogger=%p!\n", pLogger);
1814# endif
1815 return;
1816 }
1817 if (pR0Logger->fFlushingDisabled)
1818 return; /* quietly */
1819
1820 PVM pVM = pR0Logger->pVM;
1821 if ( !VALID_PTR(pVM)
1822 || pVM->pVMR0 != pVM)
1823 {
1824# ifdef DEBUG
1825 SUPR0Printf("vmmR0LoggerFlush: pVM=%p! pVMR0=%p! pLogger=%p\n", pVM, pVM->pVMR0, pLogger);
1826# endif
1827 return;
1828 }
1829
1830 PVMCPU pVCpu = VMMGetCpu(pVM);
1831 if (pVCpu)
1832 {
1833 /*
1834 * Check that the jump buffer is armed.
1835 */
1836# ifdef RT_ARCH_X86
1837 if ( !pVCpu->vmm.s.CallRing3JmpBufR0.eip
1838 || pVCpu->vmm.s.CallRing3JmpBufR0.fInRing3Call)
1839# else
1840 if ( !pVCpu->vmm.s.CallRing3JmpBufR0.rip
1841 || pVCpu->vmm.s.CallRing3JmpBufR0.fInRing3Call)
1842# endif
1843 {
1844# ifdef DEBUG
1845 SUPR0Printf("vmmR0LoggerFlush: Jump buffer isn't armed!\n");
1846# endif
1847 return;
1848 }
1849 VMMRZCallRing3(pVM, pVCpu, VMMCALLRING3_VMM_LOGGER_FLUSH, 0);
1850 }
1851# ifdef DEBUG
1852 else
1853 SUPR0Printf("vmmR0LoggerFlush: invalid VCPU context!\n");
1854# endif
1855#endif
1856}
1857
1858/**
1859 * Internal R0 logger worker: Custom prefix.
1860 *
1861 * @returns Number of chars written.
1862 *
1863 * @param pLogger The logger instance.
1864 * @param pchBuf The output buffer.
1865 * @param cchBuf The size of the buffer.
1866 * @param pvUser User argument (ignored).
1867 */
1868VMMR0DECL(size_t) vmmR0LoggerPrefix(PRTLOGGER pLogger, char *pchBuf, size_t cchBuf, void *pvUser)
1869{
1870 NOREF(pvUser);
1871#ifdef LOG_ENABLED
1872 PVMMR0LOGGER pR0Logger = (PVMMR0LOGGER)((uintptr_t)pLogger - RT_OFFSETOF(VMMR0LOGGER, Logger));
1873 if ( !VALID_PTR(pR0Logger)
1874 || !VALID_PTR(pR0Logger + 1)
1875 || pLogger->u32Magic != RTLOGGER_MAGIC
1876 || cchBuf < 2)
1877 return 0;
1878
1879 static const char s_szHex[17] = "0123456789abcdef";
1880 VMCPUID const idCpu = pR0Logger->idCpu;
1881 pchBuf[1] = s_szHex[ idCpu & 15];
1882 pchBuf[0] = s_szHex[(idCpu >> 4) & 15];
1883
1884 return 2;
1885#else
1886 return 0;
1887#endif
1888}
1889
1890#ifdef LOG_ENABLED
1891
1892/**
1893 * Disables flushing of the ring-0 debug log.
1894 *
1895 * @param pVCpu Pointer to the VMCPU.
1896 */
1897VMMR0DECL(void) VMMR0LogFlushDisable(PVMCPU pVCpu)
1898{
1899 if (pVCpu->vmm.s.pR0LoggerR0)
1900 pVCpu->vmm.s.pR0LoggerR0->fFlushingDisabled = true;
1901}
1902
1903
1904/**
1905 * Enables flushing of the ring-0 debug log.
1906 *
1907 * @param pVCpu Pointer to the VMCPU.
1908 */
1909VMMR0DECL(void) VMMR0LogFlushEnable(PVMCPU pVCpu)
1910{
1911 if (pVCpu->vmm.s.pR0LoggerR0)
1912 pVCpu->vmm.s.pR0LoggerR0->fFlushingDisabled = false;
1913}
1914
1915
1916/**
1917 * Checks if log flushing is disabled or not.
1918 *
1919 * @param pVCpu Pointer to the VMCPU.
1920 */
1921VMMR0DECL(bool) VMMR0IsLogFlushDisabled(PVMCPU pVCpu)
1922{
1923 if (pVCpu->vmm.s.pR0LoggerR0)
1924 return pVCpu->vmm.s.pR0LoggerR0->fFlushingDisabled;
1925 return true;
1926}
1927#endif /* LOG_ENABLED */
1928
1929/**
1930 * Jump back to ring-3 if we're the EMT and the longjmp is armed.
1931 *
1932 * @returns true if the breakpoint should be hit, false if it should be ignored.
1933 */
1934DECLEXPORT(bool) RTCALL RTAssertShouldPanic(void)
1935{
1936#if 0
1937 return true;
1938#else
1939 PVM pVM = GVMMR0GetVMByEMT(NIL_RTNATIVETHREAD);
1940 if (pVM)
1941 {
1942 PVMCPU pVCpu = VMMGetCpu(pVM);
1943
1944 if (pVCpu)
1945 {
1946#ifdef RT_ARCH_X86
1947 if ( pVCpu->vmm.s.CallRing3JmpBufR0.eip
1948 && !pVCpu->vmm.s.CallRing3JmpBufR0.fInRing3Call)
1949#else
1950 if ( pVCpu->vmm.s.CallRing3JmpBufR0.rip
1951 && !pVCpu->vmm.s.CallRing3JmpBufR0.fInRing3Call)
1952#endif
1953 {
1954 int rc = VMMRZCallRing3(pVM, pVCpu, VMMCALLRING3_VM_R0_ASSERTION, 0);
1955 return RT_FAILURE_NP(rc);
1956 }
1957 }
1958 }
1959#ifdef RT_OS_LINUX
1960 return true;
1961#else
1962 return false;
1963#endif
1964#endif
1965}
1966
1967
1968/**
1969 * Override this so we can push it up to ring-3.
1970 *
1971 * @param pszExpr Expression. Can be NULL.
1972 * @param uLine Location line number.
1973 * @param pszFile Location file name.
1974 * @param pszFunction Location function name.
1975 */
1976DECLEXPORT(void) RTCALL RTAssertMsg1Weak(const char *pszExpr, unsigned uLine, const char *pszFile, const char *pszFunction)
1977{
1978 /*
1979 * To the log.
1980 */
1981 LogAlways(("\n!!R0-Assertion Failed!!\n"
1982 "Expression: %s\n"
1983 "Location : %s(%d) %s\n",
1984 pszExpr, pszFile, uLine, pszFunction));
1985
1986 /*
1987 * To the global VMM buffer.
1988 */
1989 PVM pVM = GVMMR0GetVMByEMT(NIL_RTNATIVETHREAD);
1990 if (pVM)
1991 RTStrPrintf(pVM->vmm.s.szRing0AssertMsg1, sizeof(pVM->vmm.s.szRing0AssertMsg1),
1992 "\n!!R0-Assertion Failed!!\n"
1993 "Expression: %s\n"
1994 "Location : %s(%d) %s\n",
1995 pszExpr, pszFile, uLine, pszFunction);
1996
1997 /*
1998 * Continue the normal way.
1999 */
2000 RTAssertMsg1(pszExpr, uLine, pszFile, pszFunction);
2001}
2002
2003
2004/**
2005 * Callback for RTLogFormatV which writes to the ring-3 log port.
2006 * See PFNLOGOUTPUT() for details.
2007 */
2008static DECLCALLBACK(size_t) rtLogOutput(void *pv, const char *pachChars, size_t cbChars)
2009{
2010 for (size_t i = 0; i < cbChars; i++)
2011 LogAlways(("%c", pachChars[i]));
2012
2013 NOREF(pv);
2014 return cbChars;
2015}
2016
2017
2018/**
2019 * Override this so we can push it up to ring-3.
2020 *
2021 * @param pszFormat The format string.
2022 * @param va Arguments.
2023 */
2024DECLEXPORT(void) RTCALL RTAssertMsg2WeakV(const char *pszFormat, va_list va)
2025{
2026 va_list vaCopy;
2027
2028 /*
2029 * Push the message to the loggers.
2030 */
2031 PRTLOGGER pLog = RTLogGetDefaultInstance(); /* Don't initialize it here... */
2032 if (pLog)
2033 {
2034 va_copy(vaCopy, va);
2035 RTLogFormatV(rtLogOutput, pLog, pszFormat, vaCopy);
2036 va_end(vaCopy);
2037 }
2038 pLog = RTLogRelDefaultInstance();
2039 if (pLog)
2040 {
2041 va_copy(vaCopy, va);
2042 RTLogFormatV(rtLogOutput, pLog, pszFormat, vaCopy);
2043 va_end(vaCopy);
2044 }
2045
2046 /*
2047 * Push it to the global VMM buffer.
2048 */
2049 PVM pVM = GVMMR0GetVMByEMT(NIL_RTNATIVETHREAD);
2050 if (pVM)
2051 {
2052 va_copy(vaCopy, va);
2053 RTStrPrintfV(pVM->vmm.s.szRing0AssertMsg2, sizeof(pVM->vmm.s.szRing0AssertMsg2), pszFormat, vaCopy);
2054 va_end(vaCopy);
2055 }
2056
2057 /*
2058 * Continue the normal way.
2059 */
2060 RTAssertMsg2V(pszFormat, va);
2061}
2062
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