VirtualBox

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

Last change on this file since 93705 was 93650, checked in by vboxsync, 3 years ago

VMM/PGM,*: Split the physical access handler type registration into separate ring-0 and ring-3 steps, expanding the type to 64-bit. bugref:10094

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 134.5 KB
Line 
1/* $Id: VMMR0.cpp 93650 2022-02-08 10:43:53Z vboxsync $ */
2/** @file
3 * VMM - Host Context Ring 0.
4 */
5
6/*
7 * Copyright (C) 2006-2022 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_VMM
23#include <VBox/vmm/vmm.h>
24#include <VBox/sup.h>
25#include <VBox/vmm/iem.h>
26#include <VBox/vmm/iom.h>
27#include <VBox/vmm/trpm.h>
28#include <VBox/vmm/cpum.h>
29#include <VBox/vmm/pdmapi.h>
30#include <VBox/vmm/pgm.h>
31#ifdef VBOX_WITH_NEM_R0
32# include <VBox/vmm/nem.h>
33#endif
34#include <VBox/vmm/em.h>
35#include <VBox/vmm/stam.h>
36#include <VBox/vmm/tm.h>
37#include "VMMInternal.h"
38#include <VBox/vmm/vmcc.h>
39#include <VBox/vmm/gvm.h>
40#ifdef VBOX_WITH_PCI_PASSTHROUGH
41# include <VBox/vmm/pdmpci.h>
42#endif
43#include <VBox/vmm/apic.h>
44
45#include <VBox/vmm/gvmm.h>
46#include <VBox/vmm/gmm.h>
47#include <VBox/vmm/gim.h>
48#include <VBox/intnet.h>
49#include <VBox/vmm/hm.h>
50#include <VBox/param.h>
51#include <VBox/err.h>
52#include <VBox/version.h>
53#include <VBox/log.h>
54
55#include <iprt/asm-amd64-x86.h>
56#include <iprt/assert.h>
57#include <iprt/crc.h>
58#include <iprt/initterm.h>
59#include <iprt/mem.h>
60#include <iprt/memobj.h>
61#include <iprt/mp.h>
62#include <iprt/once.h>
63#include <iprt/semaphore.h>
64#include <iprt/spinlock.h>
65#include <iprt/stdarg.h>
66#include <iprt/string.h>
67#include <iprt/thread.h>
68#include <iprt/timer.h>
69#include <iprt/time.h>
70
71#include "dtrace/VBoxVMM.h"
72
73
74#if defined(_MSC_VER) && defined(RT_ARCH_AMD64) /** @todo check this with with VC7! */
75# pragma intrinsic(_AddressOfReturnAddress)
76#endif
77
78#if defined(RT_OS_DARWIN) && ARCH_BITS == 32
79# error "32-bit darwin is no longer supported. Go back to 4.3 or earlier!"
80#endif
81
82
83/*********************************************************************************************************************************
84* Internal Functions *
85*********************************************************************************************************************************/
86RT_C_DECLS_BEGIN
87#if defined(RT_ARCH_X86) && (defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD))
88extern uint64_t __udivdi3(uint64_t, uint64_t);
89extern uint64_t __umoddi3(uint64_t, uint64_t);
90#endif
91RT_C_DECLS_END
92static int vmmR0UpdateLoggers(PGVM pGVM, VMCPUID idCpu, PVMMR0UPDATELOGGERSREQ pReq, size_t idxLogger);
93static int vmmR0LogFlusher(PGVM pGVM);
94static int vmmR0LogWaitFlushed(PGVM pGVM, VMCPUID idCpu, size_t idxLogger);
95static int vmmR0InitLoggers(PGVM pGVM);
96static void vmmR0CleanupLoggers(PGVM pGVM);
97
98
99/*********************************************************************************************************************************
100* Global Variables *
101*********************************************************************************************************************************/
102/** Drag in necessary library bits.
103 * The runtime lives here (in VMMR0.r0) and VBoxDD*R0.r0 links against us. */
104struct CLANG11WEIRDNOTHROW { PFNRT pfn; } g_VMMR0Deps[] =
105{
106 { (PFNRT)RTCrc32 },
107 { (PFNRT)RTOnce },
108#if defined(RT_ARCH_X86) && (defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD))
109 { (PFNRT)__udivdi3 },
110 { (PFNRT)__umoddi3 },
111#endif
112 { NULL }
113};
114
115#ifdef RT_OS_SOLARIS
116/* Dependency information for the native solaris loader. */
117extern "C" { char _depends_on[] = "vboxdrv"; }
118#endif
119
120
121/**
122 * Initialize the module.
123 * This is called when we're first loaded.
124 *
125 * @returns 0 on success.
126 * @returns VBox status on failure.
127 * @param hMod Image handle for use in APIs.
128 */
129DECLEXPORT(int) ModuleInit(void *hMod)
130{
131#ifdef VBOX_WITH_DTRACE_R0
132 /*
133 * The first thing to do is register the static tracepoints.
134 * (Deregistration is automatic.)
135 */
136 int rc2 = SUPR0TracerRegisterModule(hMod, &g_VTGObjHeader);
137 if (RT_FAILURE(rc2))
138 return rc2;
139#endif
140 LogFlow(("ModuleInit:\n"));
141
142#ifdef VBOX_WITH_64ON32_CMOS_DEBUG
143 /*
144 * Display the CMOS debug code.
145 */
146 ASMOutU8(0x72, 0x03);
147 uint8_t bDebugCode = ASMInU8(0x73);
148 LogRel(("CMOS Debug Code: %#x (%d)\n", bDebugCode, bDebugCode));
149 RTLogComPrintf("CMOS Debug Code: %#x (%d)\n", bDebugCode, bDebugCode);
150#endif
151
152 /*
153 * Initialize the VMM, GVMM, GMM, HM, PGM (Darwin) and INTNET.
154 */
155 int rc = vmmInitFormatTypes();
156 if (RT_SUCCESS(rc))
157 {
158 rc = GVMMR0Init();
159 if (RT_SUCCESS(rc))
160 {
161 rc = GMMR0Init();
162 if (RT_SUCCESS(rc))
163 {
164 rc = HMR0Init();
165 if (RT_SUCCESS(rc))
166 {
167 PDMR0Init(hMod);
168
169 rc = PGMRegisterStringFormatTypes();
170 if (RT_SUCCESS(rc))
171 {
172 rc = IntNetR0Init();
173 if (RT_SUCCESS(rc))
174 {
175#ifdef VBOX_WITH_PCI_PASSTHROUGH
176 rc = PciRawR0Init();
177#endif
178 if (RT_SUCCESS(rc))
179 {
180 rc = CPUMR0ModuleInit();
181 if (RT_SUCCESS(rc))
182 {
183#ifdef VBOX_WITH_TRIPLE_FAULT_HACK
184 rc = vmmR0TripleFaultHackInit();
185 if (RT_SUCCESS(rc))
186#endif
187 {
188#ifdef VBOX_WITH_NEM_R0
189 rc = NEMR0Init();
190 if (RT_SUCCESS(rc))
191#endif
192 {
193 LogFlow(("ModuleInit: returns success\n"));
194 return VINF_SUCCESS;
195 }
196 }
197
198 /*
199 * Bail out.
200 */
201#ifdef VBOX_WITH_TRIPLE_FAULT_HACK
202 vmmR0TripleFaultHackTerm();
203#endif
204 }
205 else
206 LogRel(("ModuleInit: CPUMR0ModuleInit -> %Rrc\n", rc));
207#ifdef VBOX_WITH_PCI_PASSTHROUGH
208 PciRawR0Term();
209#endif
210 }
211 else
212 LogRel(("ModuleInit: PciRawR0Init -> %Rrc\n", rc));
213 IntNetR0Term();
214 }
215 else
216 LogRel(("ModuleInit: IntNetR0Init -> %Rrc\n", rc));
217 PGMDeregisterStringFormatTypes();
218 }
219 else
220 LogRel(("ModuleInit: PGMRegisterStringFormatTypes -> %Rrc\n", rc));
221 HMR0Term();
222 }
223 else
224 LogRel(("ModuleInit: HMR0Init -> %Rrc\n", rc));
225 GMMR0Term();
226 }
227 else
228 LogRel(("ModuleInit: GMMR0Init -> %Rrc\n", rc));
229 GVMMR0Term();
230 }
231 else
232 LogRel(("ModuleInit: GVMMR0Init -> %Rrc\n", rc));
233 vmmTermFormatTypes();
234 }
235 else
236 LogRel(("ModuleInit: vmmInitFormatTypes -> %Rrc\n", rc));
237
238 LogFlow(("ModuleInit: failed %Rrc\n", rc));
239 return rc;
240}
241
242
243/**
244 * Terminate the module.
245 * This is called when we're finally unloaded.
246 *
247 * @param hMod Image handle for use in APIs.
248 */
249DECLEXPORT(void) ModuleTerm(void *hMod)
250{
251 NOREF(hMod);
252 LogFlow(("ModuleTerm:\n"));
253
254 /*
255 * Terminate the CPUM module (Local APIC cleanup).
256 */
257 CPUMR0ModuleTerm();
258
259 /*
260 * Terminate the internal network service.
261 */
262 IntNetR0Term();
263
264 /*
265 * PGM (Darwin), HM and PciRaw global cleanup.
266 */
267#ifdef VBOX_WITH_PCI_PASSTHROUGH
268 PciRawR0Term();
269#endif
270 PGMDeregisterStringFormatTypes();
271 HMR0Term();
272#ifdef VBOX_WITH_TRIPLE_FAULT_HACK
273 vmmR0TripleFaultHackTerm();
274#endif
275#ifdef VBOX_WITH_NEM_R0
276 NEMR0Term();
277#endif
278
279 /*
280 * Destroy the GMM and GVMM instances.
281 */
282 GMMR0Term();
283 GVMMR0Term();
284
285 vmmTermFormatTypes();
286 RTTermRunCallbacks(RTTERMREASON_UNLOAD, 0);
287
288 LogFlow(("ModuleTerm: returns\n"));
289}
290
291
292/**
293 * Initializes VMM specific members when the GVM structure is created,
294 * allocating loggers and stuff.
295 *
296 * The loggers are allocated here so that we can update their settings before
297 * doing VMMR0_DO_VMMR0_INIT and have correct logging at that time.
298 *
299 * @returns VBox status code.
300 * @param pGVM The global (ring-0) VM structure.
301 */
302VMMR0_INT_DECL(int) VMMR0InitPerVMData(PGVM pGVM)
303{
304 AssertCompile(sizeof(pGVM->vmmr0.s) <= sizeof(pGVM->vmmr0.padding));
305
306 /*
307 * Initialize all members first.
308 */
309 pGVM->vmmr0.s.fCalledInitVm = false;
310 pGVM->vmmr0.s.hMemObjLogger = NIL_RTR0MEMOBJ;
311 pGVM->vmmr0.s.hMapObjLogger = NIL_RTR0MEMOBJ;
312 pGVM->vmmr0.s.hMemObjReleaseLogger = NIL_RTR0MEMOBJ;
313 pGVM->vmmr0.s.hMapObjReleaseLogger = NIL_RTR0MEMOBJ;
314 pGVM->vmmr0.s.LogFlusher.hSpinlock = NIL_RTSPINLOCK;
315 pGVM->vmmr0.s.LogFlusher.hThread = NIL_RTNATIVETHREAD;
316 pGVM->vmmr0.s.LogFlusher.hEvent = NIL_RTSEMEVENT;
317 pGVM->vmmr0.s.LogFlusher.idxRingHead = 0;
318 pGVM->vmmr0.s.LogFlusher.idxRingTail = 0;
319 pGVM->vmmr0.s.LogFlusher.fThreadWaiting = false;
320
321 for (VMCPUID idCpu = 0; idCpu < pGVM->cCpus; idCpu++)
322 {
323 PGVMCPU pGVCpu = &pGVM->aCpus[idCpu];
324 Assert(pGVCpu->idHostCpu == NIL_RTCPUID);
325 Assert(pGVCpu->iHostCpuSet == UINT32_MAX);
326 pGVCpu->vmmr0.s.pPreemptState = NULL;
327 pGVCpu->vmmr0.s.hCtxHook = NIL_RTTHREADCTXHOOK;
328 pGVCpu->vmmr0.s.AssertJmpBuf.pMirrorBuf = &pGVCpu->vmm.s.AssertJmpBuf;
329 pGVCpu->vmmr0.s.AssertJmpBuf.pvStackBuf = &pGVCpu->vmm.s.abAssertStack[0];
330 pGVCpu->vmmr0.s.AssertJmpBuf.cbStackBuf = sizeof(pGVCpu->vmm.s.abAssertStack);
331
332 for (size_t iLogger = 0; iLogger < RT_ELEMENTS(pGVCpu->vmmr0.s.u.aLoggers); iLogger++)
333 pGVCpu->vmmr0.s.u.aLoggers[iLogger].hEventFlushWait = NIL_RTSEMEVENT;
334 }
335
336 /*
337 * Create the loggers.
338 */
339 return vmmR0InitLoggers(pGVM);
340}
341
342
343/**
344 * Initiates the R0 driver for a particular VM instance.
345 *
346 * @returns VBox status code.
347 *
348 * @param pGVM The global (ring-0) VM structure.
349 * @param uSvnRev The SVN revision of the ring-3 part.
350 * @param uBuildType Build type indicator.
351 * @thread EMT(0)
352 */
353static int vmmR0InitVM(PGVM pGVM, uint32_t uSvnRev, uint32_t uBuildType)
354{
355 /*
356 * Match the SVN revisions and build type.
357 */
358 if (uSvnRev != VMMGetSvnRev())
359 {
360 LogRel(("VMMR0InitVM: Revision mismatch, r3=%d r0=%d\n", uSvnRev, VMMGetSvnRev()));
361 SUPR0Printf("VMMR0InitVM: Revision mismatch, r3=%d r0=%d\n", uSvnRev, VMMGetSvnRev());
362 return VERR_VMM_R0_VERSION_MISMATCH;
363 }
364 if (uBuildType != vmmGetBuildType())
365 {
366 LogRel(("VMMR0InitVM: Build type mismatch, r3=%#x r0=%#x\n", uBuildType, vmmGetBuildType()));
367 SUPR0Printf("VMMR0InitVM: Build type mismatch, r3=%#x r0=%#x\n", uBuildType, vmmGetBuildType());
368 return VERR_VMM_R0_VERSION_MISMATCH;
369 }
370
371 int rc = GVMMR0ValidateGVMandEMT(pGVM, 0 /*idCpu*/);
372 if (RT_FAILURE(rc))
373 return rc;
374
375 /* Don't allow this to be called more than once. */
376 if (!pGVM->vmmr0.s.fCalledInitVm)
377 pGVM->vmmr0.s.fCalledInitVm = true;
378 else
379 return VERR_ALREADY_INITIALIZED;
380
381#ifdef LOG_ENABLED
382
383 /*
384 * Register the EMT R0 logger instance for VCPU 0.
385 */
386 PVMCPUCC pVCpu = VMCC_GET_CPU_0(pGVM);
387 if (pVCpu->vmmr0.s.u.s.Logger.pLogger)
388 {
389# if 0 /* testing of the logger. */
390 LogCom(("vmmR0InitVM: before %p\n", RTLogDefaultInstance()));
391 LogCom(("vmmR0InitVM: pfnFlush=%p actual=%p\n", pR0Logger->Logger.pfnFlush, vmmR0LoggerFlush));
392 LogCom(("vmmR0InitVM: pfnLogger=%p actual=%p\n", pR0Logger->Logger.pfnLogger, vmmR0LoggerWrapper));
393 LogCom(("vmmR0InitVM: offScratch=%d fFlags=%#x fDestFlags=%#x\n", pR0Logger->Logger.offScratch, pR0Logger->Logger.fFlags, pR0Logger->Logger.fDestFlags));
394
395 RTLogSetDefaultInstanceThread(&pR0Logger->Logger, (uintptr_t)pGVM->pSession);
396 LogCom(("vmmR0InitVM: after %p reg\n", RTLogDefaultInstance()));
397 RTLogSetDefaultInstanceThread(NULL, pGVM->pSession);
398 LogCom(("vmmR0InitVM: after %p dereg\n", RTLogDefaultInstance()));
399
400 pR0Logger->Logger.pfnLogger("hello ring-0 logger\n");
401 LogCom(("vmmR0InitVM: returned successfully from direct logger call.\n"));
402 pR0Logger->Logger.pfnFlush(&pR0Logger->Logger);
403 LogCom(("vmmR0InitVM: returned successfully from direct flush call.\n"));
404
405 RTLogSetDefaultInstanceThread(&pR0Logger->Logger, (uintptr_t)pGVM->pSession);
406 LogCom(("vmmR0InitVM: after %p reg2\n", RTLogDefaultInstance()));
407 pR0Logger->Logger.pfnLogger("hello ring-0 logger\n");
408 LogCom(("vmmR0InitVM: returned successfully from direct logger call (2). offScratch=%d\n", pR0Logger->Logger.offScratch));
409 RTLogSetDefaultInstanceThread(NULL, pGVM->pSession);
410 LogCom(("vmmR0InitVM: after %p dereg2\n", RTLogDefaultInstance()));
411
412 RTLogLoggerEx(&pR0Logger->Logger, 0, ~0U, "hello ring-0 logger (RTLogLoggerEx)\n");
413 LogCom(("vmmR0InitVM: RTLogLoggerEx returned fine offScratch=%d\n", pR0Logger->Logger.offScratch));
414
415 RTLogSetDefaultInstanceThread(&pR0Logger->Logger, (uintptr_t)pGVM->pSession);
416 RTLogPrintf("hello ring-0 logger (RTLogPrintf)\n");
417 LogCom(("vmmR0InitVM: RTLogPrintf returned fine offScratch=%d\n", pR0Logger->Logger.offScratch));
418# endif
419# ifdef VBOX_WITH_R0_LOGGING
420 Log(("Switching to per-thread logging instance %p (key=%p)\n", pVCpu->vmmr0.s.u.s.Logger.pLogger, pGVM->pSession));
421 RTLogSetDefaultInstanceThread(pVCpu->vmmr0.s.u.s.Logger.pLogger, (uintptr_t)pGVM->pSession);
422 pVCpu->vmmr0.s.u.s.Logger.fRegistered = true;
423# endif
424 }
425#endif /* LOG_ENABLED */
426
427 /*
428 * Check if the host supports high resolution timers or not.
429 */
430 if ( pGVM->vmm.s.fUsePeriodicPreemptionTimers
431 && !RTTimerCanDoHighResolution())
432 pGVM->vmm.s.fUsePeriodicPreemptionTimers = false;
433
434 /*
435 * Initialize the per VM data for GVMM and GMM.
436 */
437 rc = GVMMR0InitVM(pGVM);
438 if (RT_SUCCESS(rc))
439 {
440 /*
441 * Init HM, CPUM and PGM.
442 */
443 rc = HMR0InitVM(pGVM);
444 if (RT_SUCCESS(rc))
445 {
446 rc = CPUMR0InitVM(pGVM);
447 if (RT_SUCCESS(rc))
448 {
449 rc = PGMR0InitVM(pGVM);
450 if (RT_SUCCESS(rc))
451 {
452 rc = EMR0InitVM(pGVM);
453 if (RT_SUCCESS(rc))
454 {
455 rc = IEMR0InitVM(pGVM);
456 if (RT_SUCCESS(rc))
457 {
458 rc = IOMR0InitVM(pGVM);
459 if (RT_SUCCESS(rc))
460 {
461#ifdef VBOX_WITH_PCI_PASSTHROUGH
462 rc = PciRawR0InitVM(pGVM);
463#endif
464 if (RT_SUCCESS(rc))
465 {
466 rc = GIMR0InitVM(pGVM);
467 if (RT_SUCCESS(rc))
468 {
469 GVMMR0DoneInitVM(pGVM);
470 PGMR0DoneInitVM(pGVM);
471
472 /*
473 * Collect a bit of info for the VM release log.
474 */
475 pGVM->vmm.s.fIsPreemptPendingApiTrusty = RTThreadPreemptIsPendingTrusty();
476 pGVM->vmm.s.fIsPreemptPossible = RTThreadPreemptIsPossible();;
477 return rc;
478
479 /* bail out*/
480 //GIMR0TermVM(pGVM);
481 }
482#ifdef VBOX_WITH_PCI_PASSTHROUGH
483 PciRawR0TermVM(pGVM);
484#endif
485 }
486 }
487 }
488 }
489 }
490 }
491 HMR0TermVM(pGVM);
492 }
493 }
494
495 RTLogSetDefaultInstanceThread(NULL, (uintptr_t)pGVM->pSession);
496 return rc;
497}
498
499
500/**
501 * Does EMT specific VM initialization.
502 *
503 * @returns VBox status code.
504 * @param pGVM The ring-0 VM structure.
505 * @param idCpu The EMT that's calling.
506 */
507static int vmmR0InitVMEmt(PGVM pGVM, VMCPUID idCpu)
508{
509 /* Paranoia (caller checked these already). */
510 AssertReturn(idCpu < pGVM->cCpus, VERR_INVALID_CPU_ID);
511 AssertReturn(pGVM->aCpus[idCpu].hEMT == RTThreadNativeSelf(), VERR_INVALID_CPU_ID);
512
513#if defined(LOG_ENABLED) && defined(VBOX_WITH_R0_LOGGING)
514 /*
515 * Registration of ring 0 loggers.
516 */
517 PVMCPUCC pVCpu = &pGVM->aCpus[idCpu];
518 if ( pVCpu->vmmr0.s.u.s.Logger.pLogger
519 && !pVCpu->vmmr0.s.u.s.Logger.fRegistered)
520 {
521 RTLogSetDefaultInstanceThread(pVCpu->vmmr0.s.u.s.Logger.pLogger, (uintptr_t)pGVM->pSession);
522 pVCpu->vmmr0.s.u.s.Logger.fRegistered = true;
523 }
524#endif
525
526 return VINF_SUCCESS;
527}
528
529
530
531/**
532 * Terminates the R0 bits for a particular VM instance.
533 *
534 * This is normally called by ring-3 as part of the VM termination process, but
535 * may alternatively be called during the support driver session cleanup when
536 * the VM object is destroyed (see GVMM).
537 *
538 * @returns VBox status code.
539 *
540 * @param pGVM The global (ring-0) VM structure.
541 * @param idCpu Set to 0 if EMT(0) or NIL_VMCPUID if session cleanup
542 * thread.
543 * @thread EMT(0) or session clean up thread.
544 */
545VMMR0_INT_DECL(int) VMMR0TermVM(PGVM pGVM, VMCPUID idCpu)
546{
547 /*
548 * Check EMT(0) claim if we're called from userland.
549 */
550 if (idCpu != NIL_VMCPUID)
551 {
552 AssertReturn(idCpu == 0, VERR_INVALID_CPU_ID);
553 int rc = GVMMR0ValidateGVMandEMT(pGVM, idCpu);
554 if (RT_FAILURE(rc))
555 return rc;
556 }
557
558#ifdef VBOX_WITH_PCI_PASSTHROUGH
559 PciRawR0TermVM(pGVM);
560#endif
561
562 /*
563 * Tell GVMM what we're up to and check that we only do this once.
564 */
565 if (GVMMR0DoingTermVM(pGVM))
566 {
567 GIMR0TermVM(pGVM);
568
569 /** @todo I wish to call PGMR0PhysFlushHandyPages(pGVM, &pGVM->aCpus[idCpu])
570 * here to make sure we don't leak any shared pages if we crash... */
571 HMR0TermVM(pGVM);
572 }
573
574 /*
575 * Deregister the logger for this EMT.
576 */
577 RTLogSetDefaultInstanceThread(NULL, (uintptr_t)pGVM->pSession);
578
579 /*
580 * Start log flusher thread termination.
581 */
582 ASMAtomicWriteBool(&pGVM->vmmr0.s.LogFlusher.fThreadShutdown, true);
583 if (pGVM->vmmr0.s.LogFlusher.hEvent != NIL_RTSEMEVENT)
584 RTSemEventSignal(pGVM->vmmr0.s.LogFlusher.hEvent);
585
586 return VINF_SUCCESS;
587}
588
589
590/**
591 * This is called at the end of gvmmR0CleanupVM().
592 *
593 * @param pGVM The global (ring-0) VM structure.
594 */
595VMMR0_INT_DECL(void) VMMR0CleanupVM(PGVM pGVM)
596{
597 AssertCompile(NIL_RTTHREADCTXHOOK == (RTTHREADCTXHOOK)0); /* Depends on zero initialized memory working for NIL at the moment. */
598 for (VMCPUID idCpu = 0; idCpu < pGVM->cCpus; idCpu++)
599 {
600 PGVMCPU pGVCpu = &pGVM->aCpus[idCpu];
601
602 /** @todo Can we busy wait here for all thread-context hooks to be
603 * deregistered before releasing (destroying) it? Only until we find a
604 * solution for not deregistering hooks everytime we're leaving HMR0
605 * context. */
606 VMMR0ThreadCtxHookDestroyForEmt(pGVCpu);
607 }
608
609 vmmR0CleanupLoggers(pGVM);
610}
611
612
613/**
614 * An interrupt or unhalt force flag is set, deal with it.
615 *
616 * @returns VINF_SUCCESS (or VINF_EM_HALT).
617 * @param pVCpu The cross context virtual CPU structure.
618 * @param uMWait Result from EMMonitorWaitIsActive().
619 * @param enmInterruptibility Guest CPU interruptbility level.
620 */
621static int vmmR0DoHaltInterrupt(PVMCPUCC pVCpu, unsigned uMWait, CPUMINTERRUPTIBILITY enmInterruptibility)
622{
623 Assert(!TRPMHasTrap(pVCpu));
624 Assert( enmInterruptibility > CPUMINTERRUPTIBILITY_INVALID
625 && enmInterruptibility < CPUMINTERRUPTIBILITY_END);
626
627 /*
628 * Pending interrupts w/o any SMIs or NMIs? That the usual case.
629 */
630 if ( VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC)
631 && !VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_INTERRUPT_SMI | VMCPU_FF_INTERRUPT_NMI))
632 {
633 if (enmInterruptibility <= CPUMINTERRUPTIBILITY_UNRESTRAINED)
634 {
635 uint8_t u8Interrupt = 0;
636 int rc = PDMGetInterrupt(pVCpu, &u8Interrupt);
637 Log(("vmmR0DoHaltInterrupt: CPU%d u8Interrupt=%d (%#x) rc=%Rrc\n", pVCpu->idCpu, u8Interrupt, u8Interrupt, rc));
638 if (RT_SUCCESS(rc))
639 {
640 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_UNHALT);
641
642 rc = TRPMAssertTrap(pVCpu, u8Interrupt, TRPM_HARDWARE_INT);
643 AssertRCSuccess(rc);
644 STAM_REL_COUNTER_INC(&pVCpu->vmm.s.StatR0HaltExec);
645 return rc;
646 }
647 }
648 }
649 /*
650 * SMI is not implemented yet, at least not here.
651 */
652 else if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INTERRUPT_SMI))
653 {
654 Log12(("vmmR0DoHaltInterrupt: CPU%d failed #3\n", pVCpu->idCpu));
655 STAM_REL_COUNTER_INC(&pVCpu->vmm.s.StatR0HaltToR3);
656 return VINF_EM_HALT;
657 }
658 /*
659 * NMI.
660 */
661 else if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INTERRUPT_NMI))
662 {
663 if (enmInterruptibility < CPUMINTERRUPTIBILITY_NMI_INHIBIT)
664 {
665 /** @todo later. */
666 Log12(("vmmR0DoHaltInterrupt: CPU%d failed #2 (uMWait=%u enmInt=%d)\n", pVCpu->idCpu, uMWait, enmInterruptibility));
667 STAM_REL_COUNTER_INC(&pVCpu->vmm.s.StatR0HaltToR3);
668 return VINF_EM_HALT;
669 }
670 }
671 /*
672 * Nested-guest virtual interrupt.
673 */
674 else if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INTERRUPT_NESTED_GUEST))
675 {
676 if (enmInterruptibility < CPUMINTERRUPTIBILITY_VIRT_INT_DISABLED)
677 {
678 /** @todo NSTVMX: NSTSVM: Remember, we might have to check and perform VM-exits
679 * here before injecting the virtual interrupt. See emR3ForcedActions
680 * for details. */
681 Log12(("vmmR0DoHaltInterrupt: CPU%d failed #1 (uMWait=%u enmInt=%d)\n", pVCpu->idCpu, uMWait, enmInterruptibility));
682 STAM_REL_COUNTER_INC(&pVCpu->vmm.s.StatR0HaltToR3);
683 return VINF_EM_HALT;
684 }
685 }
686
687 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_UNHALT))
688 {
689 STAM_REL_COUNTER_INC(&pVCpu->vmm.s.StatR0HaltExec);
690 Log11(("vmmR0DoHaltInterrupt: CPU%d success VINF_SUCCESS (UNHALT)\n", pVCpu->idCpu));
691 return VINF_SUCCESS;
692 }
693 if (uMWait > 1)
694 {
695 STAM_REL_COUNTER_INC(&pVCpu->vmm.s.StatR0HaltExec);
696 Log11(("vmmR0DoHaltInterrupt: CPU%d success VINF_SUCCESS (uMWait=%u > 1)\n", pVCpu->idCpu, uMWait));
697 return VINF_SUCCESS;
698 }
699
700 Log12(("vmmR0DoHaltInterrupt: CPU%d failed #0 (uMWait=%u enmInt=%d)\n", pVCpu->idCpu, uMWait, enmInterruptibility));
701 STAM_REL_COUNTER_INC(&pVCpu->vmm.s.StatR0HaltToR3);
702 return VINF_EM_HALT;
703}
704
705
706/**
707 * This does one round of vmR3HaltGlobal1Halt().
708 *
709 * The rational here is that we'll reduce latency in interrupt situations if we
710 * don't go to ring-3 immediately on a VINF_EM_HALT (guest executed HLT or
711 * MWAIT), but do one round of blocking here instead and hope the interrupt is
712 * raised in the meanwhile.
713 *
714 * If we go to ring-3 we'll quit the inner HM/NEM loop in EM and end up in the
715 * outer loop, which will then call VMR3WaitHalted() and that in turn will do a
716 * ring-0 call (unless we're too close to a timer event). When the interrupt
717 * wakes us up, we'll return from ring-0 and EM will by instinct do a
718 * rescheduling (because of raw-mode) before it resumes the HM/NEM loop and gets
719 * back to VMMR0EntryFast().
720 *
721 * @returns VINF_SUCCESS or VINF_EM_HALT.
722 * @param pGVM The ring-0 VM structure.
723 * @param pGVCpu The ring-0 virtual CPU structure.
724 *
725 * @todo r=bird: All the blocking/waiting and EMT managment should move out of
726 * the VM module, probably to VMM. Then this would be more weird wrt
727 * parameters and statistics.
728 */
729static int vmmR0DoHalt(PGVM pGVM, PGVMCPU pGVCpu)
730{
731 /*
732 * Do spin stat historization.
733 */
734 if (++pGVCpu->vmm.s.cR0Halts & 0xff)
735 { /* likely */ }
736 else if (pGVCpu->vmm.s.cR0HaltsSucceeded > pGVCpu->vmm.s.cR0HaltsToRing3)
737 {
738 pGVCpu->vmm.s.cR0HaltsSucceeded = 2;
739 pGVCpu->vmm.s.cR0HaltsToRing3 = 0;
740 }
741 else
742 {
743 pGVCpu->vmm.s.cR0HaltsSucceeded = 0;
744 pGVCpu->vmm.s.cR0HaltsToRing3 = 2;
745 }
746
747 /*
748 * Flags that makes us go to ring-3.
749 */
750 uint32_t const fVmFFs = VM_FF_TM_VIRTUAL_SYNC | VM_FF_PDM_QUEUES | VM_FF_PDM_DMA
751 | VM_FF_DBGF | VM_FF_REQUEST | VM_FF_CHECK_VM_STATE
752 | VM_FF_RESET | VM_FF_EMT_RENDEZVOUS | VM_FF_PGM_NEED_HANDY_PAGES
753 | VM_FF_PGM_NO_MEMORY | VM_FF_DEBUG_SUSPEND;
754 uint64_t const fCpuFFs = VMCPU_FF_TIMER | VMCPU_FF_PDM_CRITSECT | VMCPU_FF_IEM
755 | VMCPU_FF_REQUEST | VMCPU_FF_DBGF | VMCPU_FF_HM_UPDATE_CR3
756 | VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL
757 | VMCPU_FF_TO_R3 | VMCPU_FF_IOM;
758
759 /*
760 * Check preconditions.
761 */
762 unsigned const uMWait = EMMonitorWaitIsActive(pGVCpu);
763 CPUMINTERRUPTIBILITY const enmInterruptibility = CPUMGetGuestInterruptibility(pGVCpu);
764 if ( pGVCpu->vmm.s.fMayHaltInRing0
765 && !TRPMHasTrap(pGVCpu)
766 && ( enmInterruptibility == CPUMINTERRUPTIBILITY_UNRESTRAINED
767 || uMWait > 1))
768 {
769 if ( !VM_FF_IS_ANY_SET(pGVM, fVmFFs)
770 && !VMCPU_FF_IS_ANY_SET(pGVCpu, fCpuFFs))
771 {
772 /*
773 * Interrupts pending already?
774 */
775 if (VMCPU_FF_TEST_AND_CLEAR(pGVCpu, VMCPU_FF_UPDATE_APIC))
776 APICUpdatePendingInterrupts(pGVCpu);
777
778 /*
779 * Flags that wake up from the halted state.
780 */
781 uint64_t const fIntMask = VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC | VMCPU_FF_INTERRUPT_NESTED_GUEST
782 | VMCPU_FF_INTERRUPT_NMI | VMCPU_FF_INTERRUPT_SMI | VMCPU_FF_UNHALT;
783
784 if (VMCPU_FF_IS_ANY_SET(pGVCpu, fIntMask))
785 return vmmR0DoHaltInterrupt(pGVCpu, uMWait, enmInterruptibility);
786 ASMNopPause();
787
788 /*
789 * Check out how long till the next timer event.
790 */
791 uint64_t u64Delta;
792 uint64_t u64GipTime = TMTimerPollGIP(pGVM, pGVCpu, &u64Delta);
793
794 if ( !VM_FF_IS_ANY_SET(pGVM, fVmFFs)
795 && !VMCPU_FF_IS_ANY_SET(pGVCpu, fCpuFFs))
796 {
797 if (VMCPU_FF_TEST_AND_CLEAR(pGVCpu, VMCPU_FF_UPDATE_APIC))
798 APICUpdatePendingInterrupts(pGVCpu);
799
800 if (VMCPU_FF_IS_ANY_SET(pGVCpu, fIntMask))
801 return vmmR0DoHaltInterrupt(pGVCpu, uMWait, enmInterruptibility);
802
803 /*
804 * Wait if there is enough time to the next timer event.
805 */
806 if (u64Delta >= pGVCpu->vmm.s.cNsSpinBlockThreshold)
807 {
808 /* If there are few other CPU cores around, we will procrastinate a
809 little before going to sleep, hoping for some device raising an
810 interrupt or similar. Though, the best thing here would be to
811 dynamically adjust the spin count according to its usfulness or
812 something... */
813 if ( pGVCpu->vmm.s.cR0HaltsSucceeded > pGVCpu->vmm.s.cR0HaltsToRing3
814 && RTMpGetOnlineCount() >= 4)
815 {
816 /** @todo Figure out how we can skip this if it hasn't help recently...
817 * @bugref{9172#c12} */
818 uint32_t cSpinLoops = 42;
819 while (cSpinLoops-- > 0)
820 {
821 ASMNopPause();
822 if (VMCPU_FF_TEST_AND_CLEAR(pGVCpu, VMCPU_FF_UPDATE_APIC))
823 APICUpdatePendingInterrupts(pGVCpu);
824 ASMNopPause();
825 if (VM_FF_IS_ANY_SET(pGVM, fVmFFs))
826 {
827 STAM_REL_COUNTER_INC(&pGVCpu->vmm.s.StatR0HaltToR3FromSpin);
828 STAM_REL_COUNTER_INC(&pGVCpu->vmm.s.StatR0HaltToR3);
829 return VINF_EM_HALT;
830 }
831 ASMNopPause();
832 if (VMCPU_FF_IS_ANY_SET(pGVCpu, fCpuFFs))
833 {
834 STAM_REL_COUNTER_INC(&pGVCpu->vmm.s.StatR0HaltToR3FromSpin);
835 STAM_REL_COUNTER_INC(&pGVCpu->vmm.s.StatR0HaltToR3);
836 return VINF_EM_HALT;
837 }
838 ASMNopPause();
839 if (VMCPU_FF_IS_ANY_SET(pGVCpu, fIntMask))
840 {
841 STAM_REL_COUNTER_INC(&pGVCpu->vmm.s.StatR0HaltExecFromSpin);
842 return vmmR0DoHaltInterrupt(pGVCpu, uMWait, enmInterruptibility);
843 }
844 ASMNopPause();
845 }
846 }
847
848 /*
849 * We have to set the state to VMCPUSTATE_STARTED_HALTED here so ring-3
850 * knows when to notify us (cannot access VMINTUSERPERVMCPU::fWait from here).
851 * After changing the state we must recheck the force flags of course.
852 */
853 if (VMCPU_CMPXCHG_STATE(pGVCpu, VMCPUSTATE_STARTED_HALTED, VMCPUSTATE_STARTED))
854 {
855 if ( !VM_FF_IS_ANY_SET(pGVM, fVmFFs)
856 && !VMCPU_FF_IS_ANY_SET(pGVCpu, fCpuFFs))
857 {
858 if (VMCPU_FF_TEST_AND_CLEAR(pGVCpu, VMCPU_FF_UPDATE_APIC))
859 APICUpdatePendingInterrupts(pGVCpu);
860
861 if (VMCPU_FF_IS_ANY_SET(pGVCpu, fIntMask))
862 {
863 VMCPU_CMPXCHG_STATE(pGVCpu, VMCPUSTATE_STARTED, VMCPUSTATE_STARTED_HALTED);
864 return vmmR0DoHaltInterrupt(pGVCpu, uMWait, enmInterruptibility);
865 }
866
867 /* Okay, block! */
868 uint64_t const u64StartSchedHalt = RTTimeNanoTS();
869 int rc = GVMMR0SchedHalt(pGVM, pGVCpu, u64GipTime);
870 uint64_t const u64EndSchedHalt = RTTimeNanoTS();
871 uint64_t const cNsElapsedSchedHalt = u64EndSchedHalt - u64StartSchedHalt;
872 Log10(("vmmR0DoHalt: CPU%d: halted %llu ns\n", pGVCpu->idCpu, cNsElapsedSchedHalt));
873
874 VMCPU_CMPXCHG_STATE(pGVCpu, VMCPUSTATE_STARTED, VMCPUSTATE_STARTED_HALTED);
875 STAM_REL_PROFILE_ADD_PERIOD(&pGVCpu->vmm.s.StatR0HaltBlock, cNsElapsedSchedHalt);
876 if ( rc == VINF_SUCCESS
877 || rc == VERR_INTERRUPTED)
878 {
879 /* Keep some stats like ring-3 does. */
880 int64_t const cNsOverslept = u64EndSchedHalt - u64GipTime;
881 if (cNsOverslept > 50000)
882 STAM_REL_PROFILE_ADD_PERIOD(&pGVCpu->vmm.s.StatR0HaltBlockOverslept, cNsOverslept);
883 else if (cNsOverslept < -50000)
884 STAM_REL_PROFILE_ADD_PERIOD(&pGVCpu->vmm.s.StatR0HaltBlockInsomnia, cNsElapsedSchedHalt);
885 else
886 STAM_REL_PROFILE_ADD_PERIOD(&pGVCpu->vmm.s.StatR0HaltBlockOnTime, cNsElapsedSchedHalt);
887
888 /*
889 * Recheck whether we can resume execution or have to go to ring-3.
890 */
891 if ( !VM_FF_IS_ANY_SET(pGVM, fVmFFs)
892 && !VMCPU_FF_IS_ANY_SET(pGVCpu, fCpuFFs))
893 {
894 if (VMCPU_FF_TEST_AND_CLEAR(pGVCpu, VMCPU_FF_UPDATE_APIC))
895 APICUpdatePendingInterrupts(pGVCpu);
896 if (VMCPU_FF_IS_ANY_SET(pGVCpu, fIntMask))
897 {
898 STAM_REL_COUNTER_INC(&pGVCpu->vmm.s.StatR0HaltExecFromBlock);
899 return vmmR0DoHaltInterrupt(pGVCpu, uMWait, enmInterruptibility);
900 }
901 STAM_REL_COUNTER_INC(&pGVCpu->vmm.s.StatR0HaltToR3PostNoInt);
902 Log12(("vmmR0DoHalt: CPU%d post #2 - No pending interrupt\n", pGVCpu->idCpu));
903 }
904 else
905 {
906 STAM_REL_COUNTER_INC(&pGVCpu->vmm.s.StatR0HaltToR3PostPendingFF);
907 Log12(("vmmR0DoHalt: CPU%d post #1 - Pending FF\n", pGVCpu->idCpu));
908 }
909 }
910 else
911 {
912 STAM_REL_COUNTER_INC(&pGVCpu->vmm.s.StatR0HaltToR3Other);
913 Log12(("vmmR0DoHalt: CPU%d GVMMR0SchedHalt failed: %Rrc\n", pGVCpu->idCpu, rc));
914 }
915 }
916 else
917 {
918 VMCPU_CMPXCHG_STATE(pGVCpu, VMCPUSTATE_STARTED, VMCPUSTATE_STARTED_HALTED);
919 STAM_REL_COUNTER_INC(&pGVCpu->vmm.s.StatR0HaltToR3PendingFF);
920 Log12(("vmmR0DoHalt: CPU%d failed #5 - Pending FF\n", pGVCpu->idCpu));
921 }
922 }
923 else
924 {
925 STAM_REL_COUNTER_INC(&pGVCpu->vmm.s.StatR0HaltToR3Other);
926 Log12(("vmmR0DoHalt: CPU%d failed #4 - enmState=%d\n", pGVCpu->idCpu, VMCPU_GET_STATE(pGVCpu)));
927 }
928 }
929 else
930 {
931 STAM_REL_COUNTER_INC(&pGVCpu->vmm.s.StatR0HaltToR3SmallDelta);
932 Log12(("vmmR0DoHalt: CPU%d failed #3 - delta too small: %RU64\n", pGVCpu->idCpu, u64Delta));
933 }
934 }
935 else
936 {
937 STAM_REL_COUNTER_INC(&pGVCpu->vmm.s.StatR0HaltToR3PendingFF);
938 Log12(("vmmR0DoHalt: CPU%d failed #2 - Pending FF\n", pGVCpu->idCpu));
939 }
940 }
941 else
942 {
943 STAM_REL_COUNTER_INC(&pGVCpu->vmm.s.StatR0HaltToR3PendingFF);
944 Log12(("vmmR0DoHalt: CPU%d failed #1 - Pending FF\n", pGVCpu->idCpu));
945 }
946 }
947 else
948 {
949 STAM_REL_COUNTER_INC(&pGVCpu->vmm.s.StatR0HaltToR3Other);
950 Log12(("vmmR0DoHalt: CPU%d failed #0 - fMayHaltInRing0=%d TRPMHasTrap=%d enmInt=%d uMWait=%u\n",
951 pGVCpu->idCpu, pGVCpu->vmm.s.fMayHaltInRing0, TRPMHasTrap(pGVCpu), enmInterruptibility, uMWait));
952 }
953
954 STAM_REL_COUNTER_INC(&pGVCpu->vmm.s.StatR0HaltToR3);
955 return VINF_EM_HALT;
956}
957
958
959/**
960 * VMM ring-0 thread-context callback.
961 *
962 * This does common HM state updating and calls the HM-specific thread-context
963 * callback.
964 *
965 * This is used together with RTThreadCtxHookCreate() on platforms which
966 * supports it, and directly from VMMR0EmtPrepareForBlocking() and
967 * VMMR0EmtResumeAfterBlocking() on platforms which don't.
968 *
969 * @param enmEvent The thread-context event.
970 * @param pvUser Opaque pointer to the VMCPU.
971 *
972 * @thread EMT(pvUser)
973 */
974static DECLCALLBACK(void) vmmR0ThreadCtxCallback(RTTHREADCTXEVENT enmEvent, void *pvUser)
975{
976 PVMCPUCC pVCpu = (PVMCPUCC)pvUser;
977
978 switch (enmEvent)
979 {
980 case RTTHREADCTXEVENT_IN:
981 {
982 /*
983 * Linux may call us with preemption enabled (really!) but technically we
984 * cannot get preempted here, otherwise we end up in an infinite recursion
985 * scenario (i.e. preempted in resume hook -> preempt hook -> resume hook...
986 * ad infinitum). Let's just disable preemption for now...
987 */
988 /** @todo r=bird: I don't believe the above. The linux code is clearly enabling
989 * preemption after doing the callout (one or two functions up the
990 * call chain). */
991 /** @todo r=ramshankar: See @bugref{5313#c30}. */
992 RTTHREADPREEMPTSTATE ParanoidPreemptState = RTTHREADPREEMPTSTATE_INITIALIZER;
993 RTThreadPreemptDisable(&ParanoidPreemptState);
994
995 /* We need to update the VCPU <-> host CPU mapping. */
996 RTCPUID idHostCpu;
997 uint32_t iHostCpuSet = RTMpCurSetIndexAndId(&idHostCpu);
998 pVCpu->iHostCpuSet = iHostCpuSet;
999 ASMAtomicWriteU32(&pVCpu->idHostCpu, idHostCpu);
1000
1001 /* In the very unlikely event that the GIP delta for the CPU we're
1002 rescheduled needs calculating, try force a return to ring-3.
1003 We unfortunately cannot do the measurements right here. */
1004 if (RT_LIKELY(!SUPIsTscDeltaAvailableForCpuSetIndex(iHostCpuSet)))
1005 { /* likely */ }
1006 else
1007 VMCPU_FF_SET(pVCpu, VMCPU_FF_TO_R3);
1008
1009 /* Invoke the HM-specific thread-context callback. */
1010 HMR0ThreadCtxCallback(enmEvent, pvUser);
1011
1012 /* Restore preemption. */
1013 RTThreadPreemptRestore(&ParanoidPreemptState);
1014 break;
1015 }
1016
1017 case RTTHREADCTXEVENT_OUT:
1018 {
1019 /* Invoke the HM-specific thread-context callback. */
1020 HMR0ThreadCtxCallback(enmEvent, pvUser);
1021
1022 /*
1023 * Sigh. See VMMGetCpu() used by VMCPU_ASSERT_EMT(). We cannot let several VCPUs
1024 * have the same host CPU associated with it.
1025 */
1026 pVCpu->iHostCpuSet = UINT32_MAX;
1027 ASMAtomicWriteU32(&pVCpu->idHostCpu, NIL_RTCPUID);
1028 break;
1029 }
1030
1031 default:
1032 /* Invoke the HM-specific thread-context callback. */
1033 HMR0ThreadCtxCallback(enmEvent, pvUser);
1034 break;
1035 }
1036}
1037
1038
1039/**
1040 * Creates thread switching hook for the current EMT thread.
1041 *
1042 * This is called by GVMMR0CreateVM and GVMMR0RegisterVCpu. If the host
1043 * platform does not implement switcher hooks, no hooks will be create and the
1044 * member set to NIL_RTTHREADCTXHOOK.
1045 *
1046 * @returns VBox status code.
1047 * @param pVCpu The cross context virtual CPU structure.
1048 * @thread EMT(pVCpu)
1049 */
1050VMMR0_INT_DECL(int) VMMR0ThreadCtxHookCreateForEmt(PVMCPUCC pVCpu)
1051{
1052 VMCPU_ASSERT_EMT(pVCpu);
1053 Assert(pVCpu->vmmr0.s.hCtxHook == NIL_RTTHREADCTXHOOK);
1054
1055#if 1 /* To disable this stuff change to zero. */
1056 int rc = RTThreadCtxHookCreate(&pVCpu->vmmr0.s.hCtxHook, 0, vmmR0ThreadCtxCallback, pVCpu);
1057 if (RT_SUCCESS(rc))
1058 {
1059 pVCpu->pGVM->vmm.s.fIsUsingContextHooks = true;
1060 return rc;
1061 }
1062#else
1063 RT_NOREF(vmmR0ThreadCtxCallback);
1064 int rc = VERR_NOT_SUPPORTED;
1065#endif
1066
1067 pVCpu->vmmr0.s.hCtxHook = NIL_RTTHREADCTXHOOK;
1068 pVCpu->pGVM->vmm.s.fIsUsingContextHooks = false;
1069 if (rc == VERR_NOT_SUPPORTED)
1070 return VINF_SUCCESS;
1071
1072 LogRelMax(32, ("RTThreadCtxHookCreate failed! rc=%Rrc pVCpu=%p idCpu=%RU32\n", rc, pVCpu, pVCpu->idCpu));
1073 return VINF_SUCCESS; /* Just ignore it, we can live without context hooks. */
1074}
1075
1076
1077/**
1078 * Destroys the thread switching hook for the specified VCPU.
1079 *
1080 * @param pVCpu The cross context virtual CPU structure.
1081 * @remarks Can be called from any thread.
1082 */
1083VMMR0_INT_DECL(void) VMMR0ThreadCtxHookDestroyForEmt(PVMCPUCC pVCpu)
1084{
1085 int rc = RTThreadCtxHookDestroy(pVCpu->vmmr0.s.hCtxHook);
1086 AssertRC(rc);
1087 pVCpu->vmmr0.s.hCtxHook = NIL_RTTHREADCTXHOOK;
1088}
1089
1090
1091/**
1092 * Disables the thread switching hook for this VCPU (if we got one).
1093 *
1094 * @param pVCpu The cross context virtual CPU structure.
1095 * @thread EMT(pVCpu)
1096 *
1097 * @remarks This also clears GVMCPU::idHostCpu, so the mapping is invalid after
1098 * this call. This means you have to be careful with what you do!
1099 */
1100VMMR0_INT_DECL(void) VMMR0ThreadCtxHookDisable(PVMCPUCC pVCpu)
1101{
1102 /*
1103 * Clear the VCPU <-> host CPU mapping as we've left HM context.
1104 * @bugref{7726#c19} explains the need for this trick:
1105 *
1106 * VMXR0CallRing3Callback/SVMR0CallRing3Callback &
1107 * hmR0VmxLeaveSession/hmR0SvmLeaveSession disables context hooks during
1108 * longjmp & normal return to ring-3, which opens a window where we may be
1109 * rescheduled without changing GVMCPUID::idHostCpu and cause confusion if
1110 * the CPU starts executing a different EMT. Both functions first disables
1111 * preemption and then calls HMR0LeaveCpu which invalids idHostCpu, leaving
1112 * an opening for getting preempted.
1113 */
1114 /** @todo Make HM not need this API! Then we could leave the hooks enabled
1115 * all the time. */
1116
1117 /*
1118 * Disable the context hook, if we got one.
1119 */
1120 if (pVCpu->vmmr0.s.hCtxHook != NIL_RTTHREADCTXHOOK)
1121 {
1122 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1123 ASMAtomicWriteU32(&pVCpu->idHostCpu, NIL_RTCPUID);
1124 int rc = RTThreadCtxHookDisable(pVCpu->vmmr0.s.hCtxHook);
1125 AssertRC(rc);
1126 }
1127}
1128
1129
1130/**
1131 * Internal version of VMMR0ThreadCtxHooksAreRegistered.
1132 *
1133 * @returns true if registered, false otherwise.
1134 * @param pVCpu The cross context virtual CPU structure.
1135 */
1136DECLINLINE(bool) vmmR0ThreadCtxHookIsEnabled(PVMCPUCC pVCpu)
1137{
1138 return RTThreadCtxHookIsEnabled(pVCpu->vmmr0.s.hCtxHook);
1139}
1140
1141
1142/**
1143 * Whether thread-context hooks are registered for this VCPU.
1144 *
1145 * @returns true if registered, false otherwise.
1146 * @param pVCpu The cross context virtual CPU structure.
1147 */
1148VMMR0_INT_DECL(bool) VMMR0ThreadCtxHookIsEnabled(PVMCPUCC pVCpu)
1149{
1150 return vmmR0ThreadCtxHookIsEnabled(pVCpu);
1151}
1152
1153
1154/**
1155 * Returns the ring-0 release logger instance.
1156 *
1157 * @returns Pointer to release logger, NULL if not configured.
1158 * @param pVCpu The cross context virtual CPU structure of the caller.
1159 * @thread EMT(pVCpu)
1160 */
1161VMMR0_INT_DECL(PRTLOGGER) VMMR0GetReleaseLogger(PVMCPUCC pVCpu)
1162{
1163 return pVCpu->vmmr0.s.u.s.RelLogger.pLogger;
1164}
1165
1166
1167#ifdef VBOX_WITH_STATISTICS
1168/**
1169 * Record return code statistics
1170 * @param pVM The cross context VM structure.
1171 * @param pVCpu The cross context virtual CPU structure.
1172 * @param rc The status code.
1173 */
1174static void vmmR0RecordRC(PVMCC pVM, PVMCPUCC pVCpu, int rc)
1175{
1176 /*
1177 * Collect statistics.
1178 */
1179 switch (rc)
1180 {
1181 case VINF_SUCCESS:
1182 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetNormal);
1183 break;
1184 case VINF_EM_RAW_INTERRUPT:
1185 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetInterrupt);
1186 break;
1187 case VINF_EM_RAW_INTERRUPT_HYPER:
1188 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetInterruptHyper);
1189 break;
1190 case VINF_EM_RAW_GUEST_TRAP:
1191 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetGuestTrap);
1192 break;
1193 case VINF_EM_RAW_RING_SWITCH:
1194 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetRingSwitch);
1195 break;
1196 case VINF_EM_RAW_RING_SWITCH_INT:
1197 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetRingSwitchInt);
1198 break;
1199 case VINF_EM_RAW_STALE_SELECTOR:
1200 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetStaleSelector);
1201 break;
1202 case VINF_EM_RAW_IRET_TRAP:
1203 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetIRETTrap);
1204 break;
1205 case VINF_IOM_R3_IOPORT_READ:
1206 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetIORead);
1207 break;
1208 case VINF_IOM_R3_IOPORT_WRITE:
1209 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetIOWrite);
1210 break;
1211 case VINF_IOM_R3_IOPORT_COMMIT_WRITE:
1212 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetIOCommitWrite);
1213 break;
1214 case VINF_IOM_R3_MMIO_READ:
1215 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMMIORead);
1216 break;
1217 case VINF_IOM_R3_MMIO_WRITE:
1218 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMMIOWrite);
1219 break;
1220 case VINF_IOM_R3_MMIO_COMMIT_WRITE:
1221 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMMIOCommitWrite);
1222 break;
1223 case VINF_IOM_R3_MMIO_READ_WRITE:
1224 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMMIOReadWrite);
1225 break;
1226 case VINF_PATM_HC_MMIO_PATCH_READ:
1227 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMMIOPatchRead);
1228 break;
1229 case VINF_PATM_HC_MMIO_PATCH_WRITE:
1230 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMMIOPatchWrite);
1231 break;
1232 case VINF_CPUM_R3_MSR_READ:
1233 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMSRRead);
1234 break;
1235 case VINF_CPUM_R3_MSR_WRITE:
1236 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMSRWrite);
1237 break;
1238 case VINF_EM_RAW_EMULATE_INSTR:
1239 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetEmulate);
1240 break;
1241 case VINF_PATCH_EMULATE_INSTR:
1242 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPatchEmulate);
1243 break;
1244 case VINF_EM_RAW_EMULATE_INSTR_LDT_FAULT:
1245 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetLDTFault);
1246 break;
1247 case VINF_EM_RAW_EMULATE_INSTR_GDT_FAULT:
1248 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetGDTFault);
1249 break;
1250 case VINF_EM_RAW_EMULATE_INSTR_IDT_FAULT:
1251 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetIDTFault);
1252 break;
1253 case VINF_EM_RAW_EMULATE_INSTR_TSS_FAULT:
1254 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetTSSFault);
1255 break;
1256 case VINF_CSAM_PENDING_ACTION:
1257 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetCSAMTask);
1258 break;
1259 case VINF_PGM_SYNC_CR3:
1260 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetSyncCR3);
1261 break;
1262 case VINF_PATM_PATCH_INT3:
1263 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPatchInt3);
1264 break;
1265 case VINF_PATM_PATCH_TRAP_PF:
1266 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPatchPF);
1267 break;
1268 case VINF_PATM_PATCH_TRAP_GP:
1269 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPatchGP);
1270 break;
1271 case VINF_PATM_PENDING_IRQ_AFTER_IRET:
1272 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPatchIretIRQ);
1273 break;
1274 case VINF_EM_RESCHEDULE_REM:
1275 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetRescheduleREM);
1276 break;
1277 case VINF_EM_RAW_TO_R3:
1278 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3Total);
1279 if (VM_FF_IS_SET(pVM, VM_FF_TM_VIRTUAL_SYNC))
1280 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3TMVirt);
1281 else if (VM_FF_IS_SET(pVM, VM_FF_PGM_NEED_HANDY_PAGES))
1282 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3HandyPages);
1283 else if (VM_FF_IS_SET(pVM, VM_FF_PDM_QUEUES))
1284 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3PDMQueues);
1285 else if (VM_FF_IS_SET(pVM, VM_FF_EMT_RENDEZVOUS))
1286 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3Rendezvous);
1287 else if (VM_FF_IS_SET(pVM, VM_FF_PDM_DMA))
1288 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3DMA);
1289 else if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_TIMER))
1290 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3Timer);
1291 else if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_PDM_CRITSECT))
1292 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3CritSect);
1293 else if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_TO_R3))
1294 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3FF);
1295 else if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_IEM))
1296 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3Iem);
1297 else if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_IOM))
1298 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3Iom);
1299 else
1300 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3Unknown);
1301 break;
1302
1303 case VINF_EM_RAW_TIMER_PENDING:
1304 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetTimerPending);
1305 break;
1306 case VINF_EM_RAW_INTERRUPT_PENDING:
1307 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetInterruptPending);
1308 break;
1309 case VINF_PATM_DUPLICATE_FUNCTION:
1310 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPATMDuplicateFn);
1311 break;
1312 case VINF_PGM_POOL_FLUSH_PENDING:
1313 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPGMFlushPending);
1314 break;
1315 case VINF_EM_PENDING_REQUEST:
1316 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPendingRequest);
1317 break;
1318 case VINF_EM_HM_PATCH_TPR_INSTR:
1319 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPatchTPR);
1320 break;
1321 default:
1322 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMisc);
1323 break;
1324 }
1325}
1326#endif /* VBOX_WITH_STATISTICS */
1327
1328
1329/**
1330 * The Ring 0 entry point, called by the fast-ioctl path.
1331 *
1332 * @param pGVM The global (ring-0) VM structure.
1333 * @param pVMIgnored The cross context VM structure. The return code is
1334 * stored in pVM->vmm.s.iLastGZRc.
1335 * @param idCpu The Virtual CPU ID of the calling EMT.
1336 * @param enmOperation Which operation to execute.
1337 * @remarks Assume called with interrupts _enabled_.
1338 */
1339VMMR0DECL(void) VMMR0EntryFast(PGVM pGVM, PVMCC pVMIgnored, VMCPUID idCpu, VMMR0OPERATION enmOperation)
1340{
1341 RT_NOREF(pVMIgnored);
1342
1343 /*
1344 * Validation.
1345 */
1346 if ( idCpu < pGVM->cCpus
1347 && pGVM->cCpus == pGVM->cCpusUnsafe)
1348 { /*likely*/ }
1349 else
1350 {
1351 SUPR0Printf("VMMR0EntryFast: Bad idCpu=%#x cCpus=%#x cCpusUnsafe=%#x\n", idCpu, pGVM->cCpus, pGVM->cCpusUnsafe);
1352 return;
1353 }
1354
1355 PGVMCPU pGVCpu = &pGVM->aCpus[idCpu];
1356 RTNATIVETHREAD const hNativeThread = RTThreadNativeSelf();
1357 if (RT_LIKELY( pGVCpu->hEMT == hNativeThread
1358 && pGVCpu->hNativeThreadR0 == hNativeThread))
1359 { /* likely */ }
1360 else
1361 {
1362 SUPR0Printf("VMMR0EntryFast: Bad thread idCpu=%#x hNativeSelf=%p pGVCpu->hEmt=%p pGVCpu->hNativeThreadR0=%p\n",
1363 idCpu, hNativeThread, pGVCpu->hEMT, pGVCpu->hNativeThreadR0);
1364 return;
1365 }
1366
1367 /*
1368 * Perform requested operation.
1369 */
1370 switch (enmOperation)
1371 {
1372 /*
1373 * Run guest code using the available hardware acceleration technology.
1374 */
1375 case VMMR0_DO_HM_RUN:
1376 {
1377 for (;;) /* hlt loop */
1378 {
1379 /*
1380 * Disable ring-3 calls & blocking till we've successfully entered HM.
1381 * Otherwise we sometimes end up blocking at the finall Log4 statement
1382 * in VMXR0Enter, while still in a somewhat inbetween state.
1383 */
1384 VMMRZCallRing3Disable(pGVCpu);
1385
1386 /*
1387 * Disable preemption.
1388 */
1389 Assert(!vmmR0ThreadCtxHookIsEnabled(pGVCpu));
1390 RTTHREADPREEMPTSTATE PreemptState = RTTHREADPREEMPTSTATE_INITIALIZER;
1391 RTThreadPreemptDisable(&PreemptState);
1392 pGVCpu->vmmr0.s.pPreemptState = &PreemptState;
1393
1394 /*
1395 * Get the host CPU identifiers, make sure they are valid and that
1396 * we've got a TSC delta for the CPU.
1397 */
1398 RTCPUID idHostCpu;
1399 uint32_t iHostCpuSet = RTMpCurSetIndexAndId(&idHostCpu);
1400 if (RT_LIKELY( iHostCpuSet < RTCPUSET_MAX_CPUS
1401 && SUPIsTscDeltaAvailableForCpuSetIndex(iHostCpuSet)))
1402 {
1403 pGVCpu->iHostCpuSet = iHostCpuSet;
1404 ASMAtomicWriteU32(&pGVCpu->idHostCpu, idHostCpu);
1405
1406 /*
1407 * Update the periodic preemption timer if it's active.
1408 */
1409 if (pGVM->vmm.s.fUsePeriodicPreemptionTimers)
1410 GVMMR0SchedUpdatePeriodicPreemptionTimer(pGVM, pGVCpu->idHostCpu, TMCalcHostTimerFrequency(pGVM, pGVCpu));
1411
1412#ifdef VMM_R0_TOUCH_FPU
1413 /*
1414 * Make sure we've got the FPU state loaded so and we don't need to clear
1415 * CR0.TS and get out of sync with the host kernel when loading the guest
1416 * FPU state. @ref sec_cpum_fpu (CPUM.cpp) and @bugref{4053}.
1417 */
1418 CPUMR0TouchHostFpu();
1419#endif
1420 int rc;
1421 bool fPreemptRestored = false;
1422 if (!HMR0SuspendPending())
1423 {
1424 /*
1425 * Enable the context switching hook.
1426 */
1427 if (pGVCpu->vmmr0.s.hCtxHook != NIL_RTTHREADCTXHOOK)
1428 {
1429 Assert(!RTThreadCtxHookIsEnabled(pGVCpu->vmmr0.s.hCtxHook));
1430 int rc2 = RTThreadCtxHookEnable(pGVCpu->vmmr0.s.hCtxHook); AssertRC(rc2);
1431 }
1432
1433 /*
1434 * Enter HM context.
1435 */
1436 rc = HMR0Enter(pGVCpu);
1437 if (RT_SUCCESS(rc))
1438 {
1439 VMCPU_SET_STATE(pGVCpu, VMCPUSTATE_STARTED_HM);
1440
1441 /*
1442 * When preemption hooks are in place, enable preemption now that
1443 * we're in HM context.
1444 */
1445 if (vmmR0ThreadCtxHookIsEnabled(pGVCpu))
1446 {
1447 fPreemptRestored = true;
1448 pGVCpu->vmmr0.s.pPreemptState = NULL;
1449 RTThreadPreemptRestore(&PreemptState);
1450 }
1451 VMMRZCallRing3Enable(pGVCpu);
1452
1453 /*
1454 * Setup the longjmp machinery and execute guest code (calls HMR0RunGuestCode).
1455 */
1456 rc = vmmR0CallRing3SetJmp(&pGVCpu->vmmr0.s.AssertJmpBuf, HMR0RunGuestCode, pGVM, pGVCpu);
1457
1458 /*
1459 * Assert sanity on the way out. Using manual assertions code here as normal
1460 * assertions are going to panic the host since we're outside the setjmp/longjmp zone.
1461 */
1462 if (RT_UNLIKELY( VMCPU_GET_STATE(pGVCpu) != VMCPUSTATE_STARTED_HM
1463 && RT_SUCCESS_NP(rc)
1464 && rc != VERR_VMM_RING0_ASSERTION ))
1465 {
1466 pGVM->vmm.s.szRing0AssertMsg1[0] = '\0';
1467 RTStrPrintf(pGVM->vmm.s.szRing0AssertMsg2, sizeof(pGVM->vmm.s.szRing0AssertMsg2),
1468 "Got VMCPU state %d expected %d.\n", VMCPU_GET_STATE(pGVCpu), VMCPUSTATE_STARTED_HM);
1469 rc = VERR_VMM_WRONG_HM_VMCPU_STATE;
1470 }
1471#if 0
1472 /** @todo Get rid of this. HM shouldn't disable the context hook. */
1473 else if (RT_UNLIKELY(vmmR0ThreadCtxHookIsEnabled(pGVCpu)))
1474 {
1475 pGVM->vmm.s.szRing0AssertMsg1[0] = '\0';
1476 RTStrPrintf(pGVM->vmm.s.szRing0AssertMsg2, sizeof(pGVM->vmm.s.szRing0AssertMsg2),
1477 "Thread-context hooks still enabled! VCPU=%p Id=%u rc=%d.\n", pGVCpu, pGVCpu->idCpu, rc);
1478 rc = VERR_VMM_CONTEXT_HOOK_STILL_ENABLED;
1479 }
1480#endif
1481
1482 VMMRZCallRing3Disable(pGVCpu); /* Lazy bird: Simpler just disabling it again... */
1483 VMCPU_SET_STATE(pGVCpu, VMCPUSTATE_STARTED);
1484 }
1485 STAM_COUNTER_INC(&pGVM->vmm.s.StatRunGC);
1486
1487 /*
1488 * Invalidate the host CPU identifiers before we disable the context
1489 * hook / restore preemption.
1490 */
1491 pGVCpu->iHostCpuSet = UINT32_MAX;
1492 ASMAtomicWriteU32(&pGVCpu->idHostCpu, NIL_RTCPUID);
1493
1494 /*
1495 * Disable context hooks. Due to unresolved cleanup issues, we
1496 * cannot leave the hooks enabled when we return to ring-3.
1497 *
1498 * Note! At the moment HM may also have disabled the hook
1499 * when we get here, but the IPRT API handles that.
1500 */
1501 if (pGVCpu->vmmr0.s.hCtxHook != NIL_RTTHREADCTXHOOK)
1502 RTThreadCtxHookDisable(pGVCpu->vmmr0.s.hCtxHook);
1503 }
1504 /*
1505 * The system is about to go into suspend mode; go back to ring 3.
1506 */
1507 else
1508 {
1509 pGVCpu->iHostCpuSet = UINT32_MAX;
1510 ASMAtomicWriteU32(&pGVCpu->idHostCpu, NIL_RTCPUID);
1511 rc = VINF_EM_RAW_INTERRUPT;
1512 }
1513
1514 /** @todo When HM stops messing with the context hook state, we'll disable
1515 * preemption again before the RTThreadCtxHookDisable call. */
1516 if (!fPreemptRestored)
1517 {
1518 pGVCpu->vmmr0.s.pPreemptState = NULL;
1519 RTThreadPreemptRestore(&PreemptState);
1520 }
1521
1522 pGVCpu->vmm.s.iLastGZRc = rc;
1523
1524 /* Fire dtrace probe and collect statistics. */
1525 VBOXVMM_R0_VMM_RETURN_TO_RING3_HM(pGVCpu, CPUMQueryGuestCtxPtr(pGVCpu), rc);
1526#ifdef VBOX_WITH_STATISTICS
1527 vmmR0RecordRC(pGVM, pGVCpu, rc);
1528#endif
1529 VMMRZCallRing3Enable(pGVCpu);
1530
1531 /*
1532 * If this is a halt.
1533 */
1534 if (rc != VINF_EM_HALT)
1535 { /* we're not in a hurry for a HLT, so prefer this path */ }
1536 else
1537 {
1538 pGVCpu->vmm.s.iLastGZRc = rc = vmmR0DoHalt(pGVM, pGVCpu);
1539 if (rc == VINF_SUCCESS)
1540 {
1541 pGVCpu->vmm.s.cR0HaltsSucceeded++;
1542 continue;
1543 }
1544 pGVCpu->vmm.s.cR0HaltsToRing3++;
1545 }
1546 }
1547 /*
1548 * Invalid CPU set index or TSC delta in need of measuring.
1549 */
1550 else
1551 {
1552 pGVCpu->vmmr0.s.pPreemptState = NULL;
1553 pGVCpu->iHostCpuSet = UINT32_MAX;
1554 ASMAtomicWriteU32(&pGVCpu->idHostCpu, NIL_RTCPUID);
1555 RTThreadPreemptRestore(&PreemptState);
1556
1557 VMMRZCallRing3Enable(pGVCpu);
1558
1559 if (iHostCpuSet < RTCPUSET_MAX_CPUS)
1560 {
1561 int rc = SUPR0TscDeltaMeasureBySetIndex(pGVM->pSession, iHostCpuSet, 0 /*fFlags*/,
1562 2 /*cMsWaitRetry*/, 5*RT_MS_1SEC /*cMsWaitThread*/,
1563 0 /*default cTries*/);
1564 if (RT_SUCCESS(rc) || rc == VERR_CPU_OFFLINE)
1565 pGVCpu->vmm.s.iLastGZRc = VINF_EM_RAW_TO_R3;
1566 else
1567 pGVCpu->vmm.s.iLastGZRc = rc;
1568 }
1569 else
1570 pGVCpu->vmm.s.iLastGZRc = VERR_INVALID_CPU_INDEX;
1571 }
1572 break;
1573 } /* halt loop. */
1574 break;
1575 }
1576
1577#ifdef VBOX_WITH_NEM_R0
1578# if defined(RT_ARCH_AMD64) && defined(RT_OS_WINDOWS)
1579 case VMMR0_DO_NEM_RUN:
1580 {
1581 /*
1582 * Setup the longjmp machinery and execute guest code (calls NEMR0RunGuestCode).
1583 */
1584# ifdef VBOXSTRICTRC_STRICT_ENABLED
1585 int rc = vmmR0CallRing3SetJmp2(&pGVCpu->vmmr0.s.AssertJmpBuf, (PFNVMMR0SETJMP2)NEMR0RunGuestCode, pGVM, idCpu);
1586# else
1587 int rc = vmmR0CallRing3SetJmp2(&pGVCpu->vmmr0.s.AssertJmpBuf, NEMR0RunGuestCode, pGVM, idCpu);
1588# endif
1589 STAM_COUNTER_INC(&pGVM->vmm.s.StatRunGC);
1590
1591 pGVCpu->vmm.s.iLastGZRc = rc;
1592
1593 /*
1594 * Fire dtrace probe and collect statistics.
1595 */
1596 VBOXVMM_R0_VMM_RETURN_TO_RING3_NEM(pGVCpu, CPUMQueryGuestCtxPtr(pGVCpu), rc);
1597# ifdef VBOX_WITH_STATISTICS
1598 vmmR0RecordRC(pGVM, pGVCpu, rc);
1599# endif
1600 break;
1601 }
1602# endif
1603#endif
1604
1605 /*
1606 * For profiling.
1607 */
1608 case VMMR0_DO_NOP:
1609 pGVCpu->vmm.s.iLastGZRc = VINF_SUCCESS;
1610 break;
1611
1612 /*
1613 * Shouldn't happen.
1614 */
1615 default:
1616 AssertMsgFailed(("%#x\n", enmOperation));
1617 pGVCpu->vmm.s.iLastGZRc = VERR_NOT_SUPPORTED;
1618 break;
1619 }
1620}
1621
1622
1623/**
1624 * Validates a session or VM session argument.
1625 *
1626 * @returns true / false accordingly.
1627 * @param pGVM The global (ring-0) VM structure.
1628 * @param pClaimedSession The session claim to validate.
1629 * @param pSession The session argument.
1630 */
1631DECLINLINE(bool) vmmR0IsValidSession(PGVM pGVM, PSUPDRVSESSION pClaimedSession, PSUPDRVSESSION pSession)
1632{
1633 /* This must be set! */
1634 if (!pSession)
1635 return false;
1636
1637 /* Only one out of the two. */
1638 if (pGVM && pClaimedSession)
1639 return false;
1640 if (pGVM)
1641 pClaimedSession = pGVM->pSession;
1642 return pClaimedSession == pSession;
1643}
1644
1645
1646/**
1647 * VMMR0EntryEx worker function, either called directly or when ever possible
1648 * called thru a longjmp so we can exit safely on failure.
1649 *
1650 * @returns VBox status code.
1651 * @param pGVM The global (ring-0) VM structure.
1652 * @param idCpu Virtual CPU ID argument. Must be NIL_VMCPUID if pVM
1653 * is NIL_RTR0PTR, and may be NIL_VMCPUID if it isn't
1654 * @param enmOperation Which operation to execute.
1655 * @param pReqHdr This points to a SUPVMMR0REQHDR packet. Optional.
1656 * The support driver validates this if it's present.
1657 * @param u64Arg Some simple constant argument.
1658 * @param pSession The session of the caller.
1659 *
1660 * @remarks Assume called with interrupts _enabled_.
1661 */
1662DECL_NO_INLINE(static, int) vmmR0EntryExWorker(PGVM pGVM, VMCPUID idCpu, VMMR0OPERATION enmOperation,
1663 PSUPVMMR0REQHDR pReqHdr, uint64_t u64Arg, PSUPDRVSESSION pSession)
1664{
1665 /*
1666 * Validate pGVM and idCpu for consistency and validity.
1667 */
1668 if (pGVM != NULL)
1669 {
1670 if (RT_LIKELY(((uintptr_t)pGVM & HOST_PAGE_OFFSET_MASK) == 0))
1671 { /* likely */ }
1672 else
1673 {
1674 SUPR0Printf("vmmR0EntryExWorker: Invalid pGVM=%p! (op=%d)\n", pGVM, enmOperation);
1675 return VERR_INVALID_POINTER;
1676 }
1677
1678 if (RT_LIKELY(idCpu == NIL_VMCPUID || idCpu < pGVM->cCpus))
1679 { /* likely */ }
1680 else
1681 {
1682 SUPR0Printf("vmmR0EntryExWorker: Invalid idCpu %#x (cCpus=%#x)\n", idCpu, pGVM->cCpus);
1683 return VERR_INVALID_PARAMETER;
1684 }
1685
1686 if (RT_LIKELY( pGVM->enmVMState >= VMSTATE_CREATING
1687 && pGVM->enmVMState <= VMSTATE_TERMINATED
1688 && pGVM->pSession == pSession
1689 && pGVM->pSelf == pGVM))
1690 { /* likely */ }
1691 else
1692 {
1693 SUPR0Printf("vmmR0EntryExWorker: Invalid pGVM=%p:{.enmVMState=%d, .cCpus=%#x, .pSession=%p(==%p), .pSelf=%p(==%p)}! (op=%d)\n",
1694 pGVM, pGVM->enmVMState, pGVM->cCpus, pGVM->pSession, pSession, pGVM->pSelf, pGVM, enmOperation);
1695 return VERR_INVALID_POINTER;
1696 }
1697 }
1698 else if (RT_LIKELY(idCpu == NIL_VMCPUID))
1699 { /* likely */ }
1700 else
1701 {
1702 SUPR0Printf("vmmR0EntryExWorker: Invalid idCpu=%u\n", idCpu);
1703 return VERR_INVALID_PARAMETER;
1704 }
1705
1706 /*
1707 * Process the request.
1708 */
1709 int rc;
1710 switch (enmOperation)
1711 {
1712 /*
1713 * GVM requests
1714 */
1715 case VMMR0_DO_GVMM_CREATE_VM:
1716 if (pGVM == NULL && u64Arg == 0 && idCpu == NIL_VMCPUID)
1717 rc = GVMMR0CreateVMReq((PGVMMCREATEVMREQ)pReqHdr, pSession);
1718 else
1719 rc = VERR_INVALID_PARAMETER;
1720 break;
1721
1722 case VMMR0_DO_GVMM_DESTROY_VM:
1723 if (pReqHdr == NULL && u64Arg == 0)
1724 rc = GVMMR0DestroyVM(pGVM);
1725 else
1726 rc = VERR_INVALID_PARAMETER;
1727 break;
1728
1729 case VMMR0_DO_GVMM_REGISTER_VMCPU:
1730 if (pGVM != NULL)
1731 rc = GVMMR0RegisterVCpu(pGVM, idCpu);
1732 else
1733 rc = VERR_INVALID_PARAMETER;
1734 break;
1735
1736 case VMMR0_DO_GVMM_DEREGISTER_VMCPU:
1737 if (pGVM != NULL)
1738 rc = GVMMR0DeregisterVCpu(pGVM, idCpu);
1739 else
1740 rc = VERR_INVALID_PARAMETER;
1741 break;
1742
1743 case VMMR0_DO_GVMM_REGISTER_WORKER_THREAD:
1744 if (pGVM != NULL && pReqHdr && pReqHdr->cbReq == sizeof(GVMMREGISTERWORKERTHREADREQ))
1745 rc = GVMMR0RegisterWorkerThread(pGVM, (GVMMWORKERTHREAD)(unsigned)u64Arg,
1746 ((PGVMMREGISTERWORKERTHREADREQ)(pReqHdr))->hNativeThreadR3);
1747 else
1748 rc = VERR_INVALID_PARAMETER;
1749 break;
1750
1751 case VMMR0_DO_GVMM_DEREGISTER_WORKER_THREAD:
1752 if (pGVM != NULL)
1753 rc = GVMMR0DeregisterWorkerThread(pGVM, (GVMMWORKERTHREAD)(unsigned)u64Arg);
1754 else
1755 rc = VERR_INVALID_PARAMETER;
1756 break;
1757
1758 case VMMR0_DO_GVMM_SCHED_HALT:
1759 if (pReqHdr)
1760 return VERR_INVALID_PARAMETER;
1761 rc = GVMMR0SchedHaltReq(pGVM, idCpu, u64Arg);
1762 break;
1763
1764 case VMMR0_DO_GVMM_SCHED_WAKE_UP:
1765 if (pReqHdr || u64Arg)
1766 return VERR_INVALID_PARAMETER;
1767 rc = GVMMR0SchedWakeUp(pGVM, idCpu);
1768 break;
1769
1770 case VMMR0_DO_GVMM_SCHED_POKE:
1771 if (pReqHdr || u64Arg)
1772 return VERR_INVALID_PARAMETER;
1773 rc = GVMMR0SchedPoke(pGVM, idCpu);
1774 break;
1775
1776 case VMMR0_DO_GVMM_SCHED_WAKE_UP_AND_POKE_CPUS:
1777 if (u64Arg)
1778 return VERR_INVALID_PARAMETER;
1779 rc = GVMMR0SchedWakeUpAndPokeCpusReq(pGVM, (PGVMMSCHEDWAKEUPANDPOKECPUSREQ)pReqHdr);
1780 break;
1781
1782 case VMMR0_DO_GVMM_SCHED_POLL:
1783 if (pReqHdr || u64Arg > 1)
1784 return VERR_INVALID_PARAMETER;
1785 rc = GVMMR0SchedPoll(pGVM, idCpu, !!u64Arg);
1786 break;
1787
1788 case VMMR0_DO_GVMM_QUERY_STATISTICS:
1789 if (u64Arg)
1790 return VERR_INVALID_PARAMETER;
1791 rc = GVMMR0QueryStatisticsReq(pGVM, (PGVMMQUERYSTATISTICSSREQ)pReqHdr, pSession);
1792 break;
1793
1794 case VMMR0_DO_GVMM_RESET_STATISTICS:
1795 if (u64Arg)
1796 return VERR_INVALID_PARAMETER;
1797 rc = GVMMR0ResetStatisticsReq(pGVM, (PGVMMRESETSTATISTICSSREQ)pReqHdr, pSession);
1798 break;
1799
1800 /*
1801 * Initialize the R0 part of a VM instance.
1802 */
1803 case VMMR0_DO_VMMR0_INIT:
1804 rc = vmmR0InitVM(pGVM, RT_LODWORD(u64Arg), RT_HIDWORD(u64Arg));
1805 break;
1806
1807 /*
1808 * Does EMT specific ring-0 init.
1809 */
1810 case VMMR0_DO_VMMR0_INIT_EMT:
1811 if (idCpu == NIL_VMCPUID)
1812 return VERR_INVALID_CPU_ID;
1813 rc = vmmR0InitVMEmt(pGVM, idCpu);
1814 break;
1815
1816 /*
1817 * Terminate the R0 part of a VM instance.
1818 */
1819 case VMMR0_DO_VMMR0_TERM:
1820 rc = VMMR0TermVM(pGVM, 0 /*idCpu*/);
1821 break;
1822
1823 /*
1824 * Update release or debug logger instances.
1825 */
1826 case VMMR0_DO_VMMR0_UPDATE_LOGGERS:
1827 if (idCpu == NIL_VMCPUID)
1828 return VERR_INVALID_CPU_ID;
1829 if (u64Arg < VMMLOGGER_IDX_MAX && pReqHdr != NULL)
1830 rc = vmmR0UpdateLoggers(pGVM, idCpu /*idCpu*/, (PVMMR0UPDATELOGGERSREQ)pReqHdr, (size_t)u64Arg);
1831 else
1832 return VERR_INVALID_PARAMETER;
1833 break;
1834
1835 /*
1836 * Log flusher thread.
1837 */
1838 case VMMR0_DO_VMMR0_LOG_FLUSHER:
1839 if (idCpu != NIL_VMCPUID)
1840 return VERR_INVALID_CPU_ID;
1841 if (pReqHdr == NULL && pGVM != NULL)
1842 rc = vmmR0LogFlusher(pGVM);
1843 else
1844 return VERR_INVALID_PARAMETER;
1845 break;
1846
1847 /*
1848 * Wait for the flush to finish with all the buffers for the given logger.
1849 */
1850 case VMMR0_DO_VMMR0_LOG_WAIT_FLUSHED:
1851 if (idCpu == NIL_VMCPUID)
1852 return VERR_INVALID_CPU_ID;
1853 if (u64Arg < VMMLOGGER_IDX_MAX && pReqHdr == NULL)
1854 rc = vmmR0LogWaitFlushed(pGVM, idCpu /*idCpu*/, (size_t)u64Arg);
1855 else
1856 return VERR_INVALID_PARAMETER;
1857 break;
1858
1859 /*
1860 * Attempt to enable hm mode and check the current setting.
1861 */
1862 case VMMR0_DO_HM_ENABLE:
1863 rc = HMR0EnableAllCpus(pGVM);
1864 break;
1865
1866 /*
1867 * Setup the hardware accelerated session.
1868 */
1869 case VMMR0_DO_HM_SETUP_VM:
1870 rc = HMR0SetupVM(pGVM);
1871 break;
1872
1873 /*
1874 * PGM wrappers.
1875 */
1876 case VMMR0_DO_PGM_ALLOCATE_HANDY_PAGES:
1877 if (idCpu == NIL_VMCPUID)
1878 return VERR_INVALID_CPU_ID;
1879 rc = PGMR0PhysAllocateHandyPages(pGVM, idCpu);
1880 break;
1881
1882 case VMMR0_DO_PGM_FLUSH_HANDY_PAGES:
1883 if (idCpu == NIL_VMCPUID)
1884 return VERR_INVALID_CPU_ID;
1885 rc = PGMR0PhysFlushHandyPages(pGVM, idCpu);
1886 break;
1887
1888 case VMMR0_DO_PGM_ALLOCATE_LARGE_PAGE:
1889 if (idCpu == NIL_VMCPUID)
1890 return VERR_INVALID_CPU_ID;
1891 rc = PGMR0PhysAllocateLargePage(pGVM, idCpu, u64Arg);
1892 break;
1893
1894 case VMMR0_DO_PGM_PHYS_SETUP_IOMMU:
1895 if (idCpu != 0)
1896 return VERR_INVALID_CPU_ID;
1897 rc = PGMR0PhysSetupIoMmu(pGVM);
1898 break;
1899
1900 case VMMR0_DO_PGM_POOL_GROW:
1901 if (idCpu == NIL_VMCPUID)
1902 return VERR_INVALID_CPU_ID;
1903 rc = PGMR0PoolGrow(pGVM, idCpu);
1904 break;
1905
1906 /*
1907 * GMM wrappers.
1908 */
1909 case VMMR0_DO_GMM_INITIAL_RESERVATION:
1910 if (u64Arg)
1911 return VERR_INVALID_PARAMETER;
1912 rc = GMMR0InitialReservationReq(pGVM, idCpu, (PGMMINITIALRESERVATIONREQ)pReqHdr);
1913 break;
1914
1915 case VMMR0_DO_GMM_UPDATE_RESERVATION:
1916 if (u64Arg)
1917 return VERR_INVALID_PARAMETER;
1918 rc = GMMR0UpdateReservationReq(pGVM, idCpu, (PGMMUPDATERESERVATIONREQ)pReqHdr);
1919 break;
1920
1921 case VMMR0_DO_GMM_ALLOCATE_PAGES:
1922 if (u64Arg)
1923 return VERR_INVALID_PARAMETER;
1924 rc = GMMR0AllocatePagesReq(pGVM, idCpu, (PGMMALLOCATEPAGESREQ)pReqHdr);
1925 break;
1926
1927 case VMMR0_DO_GMM_FREE_PAGES:
1928 if (u64Arg)
1929 return VERR_INVALID_PARAMETER;
1930 rc = GMMR0FreePagesReq(pGVM, idCpu, (PGMMFREEPAGESREQ)pReqHdr);
1931 break;
1932
1933 case VMMR0_DO_GMM_FREE_LARGE_PAGE:
1934 if (u64Arg)
1935 return VERR_INVALID_PARAMETER;
1936 rc = GMMR0FreeLargePageReq(pGVM, idCpu, (PGMMFREELARGEPAGEREQ)pReqHdr);
1937 break;
1938
1939 case VMMR0_DO_GMM_QUERY_HYPERVISOR_MEM_STATS:
1940 if (u64Arg)
1941 return VERR_INVALID_PARAMETER;
1942 rc = GMMR0QueryHypervisorMemoryStatsReq((PGMMMEMSTATSREQ)pReqHdr);
1943 break;
1944
1945 case VMMR0_DO_GMM_QUERY_MEM_STATS:
1946 if (idCpu == NIL_VMCPUID)
1947 return VERR_INVALID_CPU_ID;
1948 if (u64Arg)
1949 return VERR_INVALID_PARAMETER;
1950 rc = GMMR0QueryMemoryStatsReq(pGVM, idCpu, (PGMMMEMSTATSREQ)pReqHdr);
1951 break;
1952
1953 case VMMR0_DO_GMM_BALLOONED_PAGES:
1954 if (u64Arg)
1955 return VERR_INVALID_PARAMETER;
1956 rc = GMMR0BalloonedPagesReq(pGVM, idCpu, (PGMMBALLOONEDPAGESREQ)pReqHdr);
1957 break;
1958
1959 case VMMR0_DO_GMM_MAP_UNMAP_CHUNK:
1960 if (u64Arg)
1961 return VERR_INVALID_PARAMETER;
1962 rc = GMMR0MapUnmapChunkReq(pGVM, (PGMMMAPUNMAPCHUNKREQ)pReqHdr);
1963 break;
1964
1965 case VMMR0_DO_GMM_REGISTER_SHARED_MODULE:
1966 if (idCpu == NIL_VMCPUID)
1967 return VERR_INVALID_CPU_ID;
1968 if (u64Arg)
1969 return VERR_INVALID_PARAMETER;
1970 rc = GMMR0RegisterSharedModuleReq(pGVM, idCpu, (PGMMREGISTERSHAREDMODULEREQ)pReqHdr);
1971 break;
1972
1973 case VMMR0_DO_GMM_UNREGISTER_SHARED_MODULE:
1974 if (idCpu == NIL_VMCPUID)
1975 return VERR_INVALID_CPU_ID;
1976 if (u64Arg)
1977 return VERR_INVALID_PARAMETER;
1978 rc = GMMR0UnregisterSharedModuleReq(pGVM, idCpu, (PGMMUNREGISTERSHAREDMODULEREQ)pReqHdr);
1979 break;
1980
1981 case VMMR0_DO_GMM_RESET_SHARED_MODULES:
1982 if (idCpu == NIL_VMCPUID)
1983 return VERR_INVALID_CPU_ID;
1984 if ( u64Arg
1985 || pReqHdr)
1986 return VERR_INVALID_PARAMETER;
1987 rc = GMMR0ResetSharedModules(pGVM, idCpu);
1988 break;
1989
1990#ifdef VBOX_WITH_PAGE_SHARING
1991 case VMMR0_DO_GMM_CHECK_SHARED_MODULES:
1992 {
1993 if (idCpu == NIL_VMCPUID)
1994 return VERR_INVALID_CPU_ID;
1995 if ( u64Arg
1996 || pReqHdr)
1997 return VERR_INVALID_PARAMETER;
1998 rc = GMMR0CheckSharedModules(pGVM, idCpu);
1999 break;
2000 }
2001#endif
2002
2003#if defined(VBOX_STRICT) && HC_ARCH_BITS == 64
2004 case VMMR0_DO_GMM_FIND_DUPLICATE_PAGE:
2005 if (u64Arg)
2006 return VERR_INVALID_PARAMETER;
2007 rc = GMMR0FindDuplicatePageReq(pGVM, (PGMMFINDDUPLICATEPAGEREQ)pReqHdr);
2008 break;
2009#endif
2010
2011 case VMMR0_DO_GMM_QUERY_STATISTICS:
2012 if (u64Arg)
2013 return VERR_INVALID_PARAMETER;
2014 rc = GMMR0QueryStatisticsReq(pGVM, (PGMMQUERYSTATISTICSSREQ)pReqHdr);
2015 break;
2016
2017 case VMMR0_DO_GMM_RESET_STATISTICS:
2018 if (u64Arg)
2019 return VERR_INVALID_PARAMETER;
2020 rc = GMMR0ResetStatisticsReq(pGVM, (PGMMRESETSTATISTICSSREQ)pReqHdr);
2021 break;
2022
2023 /*
2024 * A quick GCFGM mock-up.
2025 */
2026 /** @todo GCFGM with proper access control, ring-3 management interface and all that. */
2027 case VMMR0_DO_GCFGM_SET_VALUE:
2028 case VMMR0_DO_GCFGM_QUERY_VALUE:
2029 {
2030 if (pGVM || !pReqHdr || u64Arg || idCpu != NIL_VMCPUID)
2031 return VERR_INVALID_PARAMETER;
2032 PGCFGMVALUEREQ pReq = (PGCFGMVALUEREQ)pReqHdr;
2033 if (pReq->Hdr.cbReq != sizeof(*pReq))
2034 return VERR_INVALID_PARAMETER;
2035 if (enmOperation == VMMR0_DO_GCFGM_SET_VALUE)
2036 {
2037 rc = GVMMR0SetConfig(pReq->pSession, &pReq->szName[0], pReq->u64Value);
2038 //if (rc == VERR_CFGM_VALUE_NOT_FOUND)
2039 // rc = GMMR0SetConfig(pReq->pSession, &pReq->szName[0], pReq->u64Value);
2040 }
2041 else
2042 {
2043 rc = GVMMR0QueryConfig(pReq->pSession, &pReq->szName[0], &pReq->u64Value);
2044 //if (rc == VERR_CFGM_VALUE_NOT_FOUND)
2045 // rc = GMMR0QueryConfig(pReq->pSession, &pReq->szName[0], &pReq->u64Value);
2046 }
2047 break;
2048 }
2049
2050 /*
2051 * PDM Wrappers.
2052 */
2053 case VMMR0_DO_PDM_DRIVER_CALL_REQ_HANDLER:
2054 {
2055 if (!pReqHdr || u64Arg || idCpu != NIL_VMCPUID)
2056 return VERR_INVALID_PARAMETER;
2057 rc = PDMR0DriverCallReqHandler(pGVM, (PPDMDRIVERCALLREQHANDLERREQ)pReqHdr);
2058 break;
2059 }
2060
2061 case VMMR0_DO_PDM_DEVICE_CREATE:
2062 {
2063 if (!pReqHdr || u64Arg || idCpu != 0)
2064 return VERR_INVALID_PARAMETER;
2065 rc = PDMR0DeviceCreateReqHandler(pGVM, (PPDMDEVICECREATEREQ)pReqHdr);
2066 break;
2067 }
2068
2069 case VMMR0_DO_PDM_DEVICE_GEN_CALL:
2070 {
2071 if (!pReqHdr || u64Arg)
2072 return VERR_INVALID_PARAMETER;
2073 rc = PDMR0DeviceGenCallReqHandler(pGVM, (PPDMDEVICEGENCALLREQ)pReqHdr, idCpu);
2074 break;
2075 }
2076
2077 /** @todo Remove the once all devices has been converted to new style! @bugref{9218} */
2078 case VMMR0_DO_PDM_DEVICE_COMPAT_SET_CRITSECT:
2079 {
2080 if (!pReqHdr || u64Arg || idCpu != 0)
2081 return VERR_INVALID_PARAMETER;
2082 rc = PDMR0DeviceCompatSetCritSectReqHandler(pGVM, (PPDMDEVICECOMPATSETCRITSECTREQ)pReqHdr);
2083 break;
2084 }
2085
2086 case VMMR0_DO_PDM_QUEUE_CREATE:
2087 {
2088 if (!pReqHdr || u64Arg || idCpu != 0)
2089 return VERR_INVALID_PARAMETER;
2090 rc = PDMR0QueueCreateReqHandler(pGVM, (PPDMQUEUECREATEREQ)pReqHdr);
2091 break;
2092 }
2093
2094 /*
2095 * Requests to the internal networking service.
2096 */
2097 case VMMR0_DO_INTNET_OPEN:
2098 {
2099 PINTNETOPENREQ pReq = (PINTNETOPENREQ)pReqHdr;
2100 if (u64Arg || !pReq || !vmmR0IsValidSession(pGVM, pReq->pSession, pSession) || idCpu != NIL_VMCPUID)
2101 return VERR_INVALID_PARAMETER;
2102 rc = IntNetR0OpenReq(pSession, pReq);
2103 break;
2104 }
2105
2106 case VMMR0_DO_INTNET_IF_CLOSE:
2107 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pGVM, ((PINTNETIFCLOSEREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
2108 return VERR_INVALID_PARAMETER;
2109 rc = IntNetR0IfCloseReq(pSession, (PINTNETIFCLOSEREQ)pReqHdr);
2110 break;
2111
2112
2113 case VMMR0_DO_INTNET_IF_GET_BUFFER_PTRS:
2114 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pGVM, ((PINTNETIFGETBUFFERPTRSREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
2115 return VERR_INVALID_PARAMETER;
2116 rc = IntNetR0IfGetBufferPtrsReq(pSession, (PINTNETIFGETBUFFERPTRSREQ)pReqHdr);
2117 break;
2118
2119 case VMMR0_DO_INTNET_IF_SET_PROMISCUOUS_MODE:
2120 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pGVM, ((PINTNETIFSETPROMISCUOUSMODEREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
2121 return VERR_INVALID_PARAMETER;
2122 rc = IntNetR0IfSetPromiscuousModeReq(pSession, (PINTNETIFSETPROMISCUOUSMODEREQ)pReqHdr);
2123 break;
2124
2125 case VMMR0_DO_INTNET_IF_SET_MAC_ADDRESS:
2126 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pGVM, ((PINTNETIFSETMACADDRESSREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
2127 return VERR_INVALID_PARAMETER;
2128 rc = IntNetR0IfSetMacAddressReq(pSession, (PINTNETIFSETMACADDRESSREQ)pReqHdr);
2129 break;
2130
2131 case VMMR0_DO_INTNET_IF_SET_ACTIVE:
2132 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pGVM, ((PINTNETIFSETACTIVEREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
2133 return VERR_INVALID_PARAMETER;
2134 rc = IntNetR0IfSetActiveReq(pSession, (PINTNETIFSETACTIVEREQ)pReqHdr);
2135 break;
2136
2137 case VMMR0_DO_INTNET_IF_SEND:
2138 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pGVM, ((PINTNETIFSENDREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
2139 return VERR_INVALID_PARAMETER;
2140 rc = IntNetR0IfSendReq(pSession, (PINTNETIFSENDREQ)pReqHdr);
2141 break;
2142
2143 case VMMR0_DO_INTNET_IF_WAIT:
2144 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pGVM, ((PINTNETIFWAITREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
2145 return VERR_INVALID_PARAMETER;
2146 rc = IntNetR0IfWaitReq(pSession, (PINTNETIFWAITREQ)pReqHdr);
2147 break;
2148
2149 case VMMR0_DO_INTNET_IF_ABORT_WAIT:
2150 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pGVM, ((PINTNETIFWAITREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
2151 return VERR_INVALID_PARAMETER;
2152 rc = IntNetR0IfAbortWaitReq(pSession, (PINTNETIFABORTWAITREQ)pReqHdr);
2153 break;
2154
2155#if 0 //def VBOX_WITH_PCI_PASSTHROUGH
2156 /*
2157 * Requests to host PCI driver service.
2158 */
2159 case VMMR0_DO_PCIRAW_REQ:
2160 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pGVM, ((PPCIRAWSENDREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
2161 return VERR_INVALID_PARAMETER;
2162 rc = PciRawR0ProcessReq(pGVM, pSession, (PPCIRAWSENDREQ)pReqHdr);
2163 break;
2164#endif
2165
2166 /*
2167 * NEM requests.
2168 */
2169#ifdef VBOX_WITH_NEM_R0
2170# if defined(RT_ARCH_AMD64) && defined(RT_OS_WINDOWS)
2171 case VMMR0_DO_NEM_INIT_VM:
2172 if (u64Arg || pReqHdr || idCpu != 0)
2173 return VERR_INVALID_PARAMETER;
2174 rc = NEMR0InitVM(pGVM);
2175 break;
2176
2177 case VMMR0_DO_NEM_INIT_VM_PART_2:
2178 if (u64Arg || pReqHdr || idCpu != 0)
2179 return VERR_INVALID_PARAMETER;
2180 rc = NEMR0InitVMPart2(pGVM);
2181 break;
2182
2183 case VMMR0_DO_NEM_MAP_PAGES:
2184 if (u64Arg || pReqHdr || idCpu == NIL_VMCPUID)
2185 return VERR_INVALID_PARAMETER;
2186 rc = NEMR0MapPages(pGVM, idCpu);
2187 break;
2188
2189 case VMMR0_DO_NEM_UNMAP_PAGES:
2190 if (u64Arg || pReqHdr || idCpu == NIL_VMCPUID)
2191 return VERR_INVALID_PARAMETER;
2192 rc = NEMR0UnmapPages(pGVM, idCpu);
2193 break;
2194
2195 case VMMR0_DO_NEM_EXPORT_STATE:
2196 if (u64Arg || pReqHdr || idCpu == NIL_VMCPUID)
2197 return VERR_INVALID_PARAMETER;
2198 rc = NEMR0ExportState(pGVM, idCpu);
2199 break;
2200
2201 case VMMR0_DO_NEM_IMPORT_STATE:
2202 if (pReqHdr || idCpu == NIL_VMCPUID)
2203 return VERR_INVALID_PARAMETER;
2204 rc = NEMR0ImportState(pGVM, idCpu, u64Arg);
2205 break;
2206
2207 case VMMR0_DO_NEM_QUERY_CPU_TICK:
2208 if (u64Arg || pReqHdr || idCpu == NIL_VMCPUID)
2209 return VERR_INVALID_PARAMETER;
2210 rc = NEMR0QueryCpuTick(pGVM, idCpu);
2211 break;
2212
2213 case VMMR0_DO_NEM_RESUME_CPU_TICK_ON_ALL:
2214 if (pReqHdr || idCpu == NIL_VMCPUID)
2215 return VERR_INVALID_PARAMETER;
2216 rc = NEMR0ResumeCpuTickOnAll(pGVM, idCpu, u64Arg);
2217 break;
2218
2219 case VMMR0_DO_NEM_UPDATE_STATISTICS:
2220 if (u64Arg || pReqHdr)
2221 return VERR_INVALID_PARAMETER;
2222 rc = NEMR0UpdateStatistics(pGVM, idCpu);
2223 break;
2224
2225# if 1 && defined(DEBUG_bird)
2226 case VMMR0_DO_NEM_EXPERIMENT:
2227 if (pReqHdr)
2228 return VERR_INVALID_PARAMETER;
2229 rc = NEMR0DoExperiment(pGVM, idCpu, u64Arg);
2230 break;
2231# endif
2232# endif
2233#endif
2234
2235 /*
2236 * IOM requests.
2237 */
2238 case VMMR0_DO_IOM_GROW_IO_PORTS:
2239 {
2240 if (pReqHdr || idCpu != 0)
2241 return VERR_INVALID_PARAMETER;
2242 rc = IOMR0IoPortGrowRegistrationTables(pGVM, u64Arg);
2243 break;
2244 }
2245
2246 case VMMR0_DO_IOM_GROW_IO_PORT_STATS:
2247 {
2248 if (pReqHdr || idCpu != 0)
2249 return VERR_INVALID_PARAMETER;
2250 rc = IOMR0IoPortGrowStatisticsTable(pGVM, u64Arg);
2251 break;
2252 }
2253
2254 case VMMR0_DO_IOM_GROW_MMIO_REGS:
2255 {
2256 if (pReqHdr || idCpu != 0)
2257 return VERR_INVALID_PARAMETER;
2258 rc = IOMR0MmioGrowRegistrationTables(pGVM, u64Arg);
2259 break;
2260 }
2261
2262 case VMMR0_DO_IOM_GROW_MMIO_STATS:
2263 {
2264 if (pReqHdr || idCpu != 0)
2265 return VERR_INVALID_PARAMETER;
2266 rc = IOMR0MmioGrowStatisticsTable(pGVM, u64Arg);
2267 break;
2268 }
2269
2270 case VMMR0_DO_IOM_SYNC_STATS_INDICES:
2271 {
2272 if (pReqHdr || idCpu != 0)
2273 return VERR_INVALID_PARAMETER;
2274 rc = IOMR0IoPortSyncStatisticsIndices(pGVM);
2275 if (RT_SUCCESS(rc))
2276 rc = IOMR0MmioSyncStatisticsIndices(pGVM);
2277 break;
2278 }
2279
2280 /*
2281 * DBGF requests.
2282 */
2283#ifdef VBOX_WITH_DBGF_TRACING
2284 case VMMR0_DO_DBGF_TRACER_CREATE:
2285 {
2286 if (!pReqHdr || u64Arg || idCpu != 0)
2287 return VERR_INVALID_PARAMETER;
2288 rc = DBGFR0TracerCreateReqHandler(pGVM, (PDBGFTRACERCREATEREQ)pReqHdr);
2289 break;
2290 }
2291
2292 case VMMR0_DO_DBGF_TRACER_CALL_REQ_HANDLER:
2293 {
2294 if (!pReqHdr || u64Arg)
2295 return VERR_INVALID_PARAMETER;
2296# if 0 /** @todo */
2297 rc = DBGFR0TracerGenCallReqHandler(pGVM, (PDBGFTRACERGENCALLREQ)pReqHdr, idCpu);
2298# else
2299 rc = VERR_NOT_IMPLEMENTED;
2300# endif
2301 break;
2302 }
2303#endif
2304
2305 case VMMR0_DO_DBGF_BP_INIT:
2306 {
2307 if (!pReqHdr || u64Arg || idCpu != 0)
2308 return VERR_INVALID_PARAMETER;
2309 rc = DBGFR0BpInitReqHandler(pGVM, (PDBGFBPINITREQ)pReqHdr);
2310 break;
2311 }
2312
2313 case VMMR0_DO_DBGF_BP_CHUNK_ALLOC:
2314 {
2315 if (!pReqHdr || u64Arg || idCpu != 0)
2316 return VERR_INVALID_PARAMETER;
2317 rc = DBGFR0BpChunkAllocReqHandler(pGVM, (PDBGFBPCHUNKALLOCREQ)pReqHdr);
2318 break;
2319 }
2320
2321 case VMMR0_DO_DBGF_BP_L2_TBL_CHUNK_ALLOC:
2322 {
2323 if (!pReqHdr || u64Arg || idCpu != 0)
2324 return VERR_INVALID_PARAMETER;
2325 rc = DBGFR0BpL2TblChunkAllocReqHandler(pGVM, (PDBGFBPL2TBLCHUNKALLOCREQ)pReqHdr);
2326 break;
2327 }
2328
2329 case VMMR0_DO_DBGF_BP_OWNER_INIT:
2330 {
2331 if (!pReqHdr || u64Arg || idCpu != 0)
2332 return VERR_INVALID_PARAMETER;
2333 rc = DBGFR0BpOwnerInitReqHandler(pGVM, (PDBGFBPOWNERINITREQ)pReqHdr);
2334 break;
2335 }
2336
2337 case VMMR0_DO_DBGF_BP_PORTIO_INIT:
2338 {
2339 if (!pReqHdr || u64Arg || idCpu != 0)
2340 return VERR_INVALID_PARAMETER;
2341 rc = DBGFR0BpPortIoInitReqHandler(pGVM, (PDBGFBPINITREQ)pReqHdr);
2342 break;
2343 }
2344
2345
2346 /*
2347 * TM requests.
2348 */
2349 case VMMR0_DO_TM_GROW_TIMER_QUEUE:
2350 {
2351 if (pReqHdr || idCpu == NIL_VMCPUID)
2352 return VERR_INVALID_PARAMETER;
2353 rc = TMR0TimerQueueGrow(pGVM, RT_HI_U32(u64Arg), RT_LO_U32(u64Arg));
2354 break;
2355 }
2356
2357 /*
2358 * For profiling.
2359 */
2360 case VMMR0_DO_NOP:
2361 case VMMR0_DO_SLOW_NOP:
2362 return VINF_SUCCESS;
2363
2364 /*
2365 * For testing Ring-0 APIs invoked in this environment.
2366 */
2367 case VMMR0_DO_TESTS:
2368 /** @todo make new test */
2369 return VINF_SUCCESS;
2370
2371 default:
2372 /*
2373 * We're returning VERR_NOT_SUPPORT here so we've got something else
2374 * than -1 which the interrupt gate glue code might return.
2375 */
2376 Log(("operation %#x is not supported\n", enmOperation));
2377 return VERR_NOT_SUPPORTED;
2378 }
2379 return rc;
2380}
2381
2382
2383/**
2384 * This is just a longjmp wrapper function for VMMR0EntryEx calls.
2385 *
2386 * @returns VBox status code.
2387 * @param pvArgs The argument package
2388 */
2389static DECLCALLBACK(int) vmmR0EntryExWrapper(void *pvArgs)
2390{
2391 PGVMCPU pGVCpu = (PGVMCPU)pvArgs;
2392 return vmmR0EntryExWorker(pGVCpu->vmmr0.s.pGVM,
2393 pGVCpu->vmmr0.s.idCpu,
2394 pGVCpu->vmmr0.s.enmOperation,
2395 pGVCpu->vmmr0.s.pReq,
2396 pGVCpu->vmmr0.s.u64Arg,
2397 pGVCpu->vmmr0.s.pSession);
2398}
2399
2400
2401/**
2402 * The Ring 0 entry point, called by the support library (SUP).
2403 *
2404 * @returns VBox status code.
2405 * @param pGVM The global (ring-0) VM structure.
2406 * @param pVM The cross context VM structure.
2407 * @param idCpu Virtual CPU ID argument. Must be NIL_VMCPUID if pVM
2408 * is NIL_RTR0PTR, and may be NIL_VMCPUID if it isn't
2409 * @param enmOperation Which operation to execute.
2410 * @param pReq Pointer to the SUPVMMR0REQHDR packet. Optional.
2411 * @param u64Arg Some simple constant argument.
2412 * @param pSession The session of the caller.
2413 * @remarks Assume called with interrupts _enabled_.
2414 */
2415VMMR0DECL(int) VMMR0EntryEx(PGVM pGVM, PVMCC pVM, VMCPUID idCpu, VMMR0OPERATION enmOperation,
2416 PSUPVMMR0REQHDR pReq, uint64_t u64Arg, PSUPDRVSESSION pSession)
2417{
2418 /*
2419 * Requests that should only happen on the EMT thread will be
2420 * wrapped in a setjmp so we can assert without causing too much trouble.
2421 */
2422 if ( pVM != NULL
2423 && pGVM != NULL
2424 && pVM == pGVM /** @todo drop pVM or pGVM */
2425 && idCpu < pGVM->cCpus
2426 && pGVM->pSession == pSession
2427 && pGVM->pSelf == pGVM
2428 && enmOperation != VMMR0_DO_GVMM_DESTROY_VM
2429 && enmOperation != VMMR0_DO_GVMM_REGISTER_VMCPU
2430 && enmOperation != VMMR0_DO_GVMM_SCHED_WAKE_UP /* idCpu is not caller but target. Sigh. */ /** @todo fix*/
2431 && enmOperation != VMMR0_DO_GVMM_SCHED_POKE /* idCpu is not caller but target. Sigh. */ /** @todo fix*/
2432 )
2433 {
2434 PGVMCPU pGVCpu = &pGVM->aCpus[idCpu];
2435 RTNATIVETHREAD hNativeThread = RTThreadNativeSelf();
2436 if (RT_LIKELY( pGVCpu->hEMT == hNativeThread
2437 && pGVCpu->hNativeThreadR0 == hNativeThread))
2438 {
2439 pGVCpu->vmmr0.s.pGVM = pGVM;
2440 pGVCpu->vmmr0.s.idCpu = idCpu;
2441 pGVCpu->vmmr0.s.enmOperation = enmOperation;
2442 pGVCpu->vmmr0.s.pReq = pReq;
2443 pGVCpu->vmmr0.s.u64Arg = u64Arg;
2444 pGVCpu->vmmr0.s.pSession = pSession;
2445 return vmmR0CallRing3SetJmpEx(&pGVCpu->vmmr0.s.AssertJmpBuf, vmmR0EntryExWrapper, pGVCpu,
2446 ((uintptr_t)u64Arg << 16) | (uintptr_t)enmOperation);
2447 }
2448 return VERR_VM_THREAD_NOT_EMT;
2449 }
2450 return vmmR0EntryExWorker(pGVM, idCpu, enmOperation, pReq, u64Arg, pSession);
2451}
2452
2453
2454/*********************************************************************************************************************************
2455* EMT Blocking *
2456*********************************************************************************************************************************/
2457
2458/**
2459 * Checks whether we've armed the ring-0 long jump machinery.
2460 *
2461 * @returns @c true / @c false
2462 * @param pVCpu The cross context virtual CPU structure.
2463 * @thread EMT
2464 * @sa VMMIsLongJumpArmed
2465 */
2466VMMR0_INT_DECL(bool) VMMR0IsLongJumpArmed(PVMCPUCC pVCpu)
2467{
2468#ifdef RT_ARCH_X86
2469 return pVCpu->vmmr0.s.AssertJmpBuf.eip != 0;
2470#else
2471 return pVCpu->vmmr0.s.AssertJmpBuf.rip != 0;
2472#endif
2473}
2474
2475
2476/**
2477 * Locking helper that deals with HM context and checks if the thread can block.
2478 *
2479 * @returns VINF_SUCCESS if we can block. Returns @a rcBusy or
2480 * VERR_VMM_CANNOT_BLOCK if not able to block.
2481 * @param pVCpu The cross context virtual CPU structure of the calling
2482 * thread.
2483 * @param rcBusy What to return in case of a blocking problem. Will IPE
2484 * if VINF_SUCCESS and we cannot block.
2485 * @param pszCaller The caller (for logging problems).
2486 * @param pvLock The lock address (for logging problems).
2487 * @param pCtx Where to return context info for the resume call.
2488 * @thread EMT(pVCpu)
2489 */
2490VMMR0_INT_DECL(int) VMMR0EmtPrepareToBlock(PVMCPUCC pVCpu, int rcBusy, const char *pszCaller, void *pvLock,
2491 PVMMR0EMTBLOCKCTX pCtx)
2492{
2493 const char *pszMsg;
2494
2495 /*
2496 * Check that we are allowed to block.
2497 */
2498 if (RT_LIKELY(VMMRZCallRing3IsEnabled(pVCpu)))
2499 {
2500 /*
2501 * Are we in HM context and w/o a context hook? If so work the context hook.
2502 */
2503 if (pVCpu->idHostCpu != NIL_RTCPUID)
2504 {
2505 Assert(pVCpu->iHostCpuSet != UINT32_MAX);
2506
2507 if (pVCpu->vmmr0.s.hCtxHook == NIL_RTTHREADCTXHOOK)
2508 {
2509 vmmR0ThreadCtxCallback(RTTHREADCTXEVENT_OUT, pVCpu);
2510 if (pVCpu->vmmr0.s.pPreemptState)
2511 RTThreadPreemptRestore(pVCpu->vmmr0.s.pPreemptState);
2512
2513 pCtx->uMagic = VMMR0EMTBLOCKCTX_MAGIC;
2514 pCtx->fWasInHmContext = true;
2515 return VINF_SUCCESS;
2516 }
2517 }
2518
2519 if (RT_LIKELY(!pVCpu->vmmr0.s.pPreemptState))
2520 {
2521 /*
2522 * Not in HM context or we've got hooks, so just check that preemption
2523 * is enabled.
2524 */
2525 if (RT_LIKELY(RTThreadPreemptIsEnabled(NIL_RTTHREAD)))
2526 {
2527 pCtx->uMagic = VMMR0EMTBLOCKCTX_MAGIC;
2528 pCtx->fWasInHmContext = false;
2529 return VINF_SUCCESS;
2530 }
2531 pszMsg = "Preemption is disabled!";
2532 }
2533 else
2534 pszMsg = "Preemption state w/o HM state!";
2535 }
2536 else
2537 pszMsg = "Ring-3 calls are disabled!";
2538
2539 static uint32_t volatile s_cWarnings = 0;
2540 if (++s_cWarnings < 50)
2541 SUPR0Printf("VMMR0EmtPrepareToBlock: %s pvLock=%p pszCaller=%s rcBusy=%p\n", pszMsg, pvLock, pszCaller, rcBusy);
2542 pCtx->uMagic = VMMR0EMTBLOCKCTX_MAGIC_DEAD;
2543 pCtx->fWasInHmContext = false;
2544 return rcBusy != VINF_SUCCESS ? rcBusy : VERR_VMM_CANNOT_BLOCK;
2545}
2546
2547
2548/**
2549 * Counterpart to VMMR0EmtPrepareToBlock.
2550 *
2551 * @param pVCpu The cross context virtual CPU structure of the calling
2552 * thread.
2553 * @param pCtx The context structure used with VMMR0EmtPrepareToBlock.
2554 * @thread EMT(pVCpu)
2555 */
2556VMMR0_INT_DECL(void) VMMR0EmtResumeAfterBlocking(PVMCPUCC pVCpu, PVMMR0EMTBLOCKCTX pCtx)
2557{
2558 AssertReturnVoid(pCtx->uMagic == VMMR0EMTBLOCKCTX_MAGIC);
2559 if (pCtx->fWasInHmContext)
2560 {
2561 if (pVCpu->vmmr0.s.pPreemptState)
2562 RTThreadPreemptDisable(pVCpu->vmmr0.s.pPreemptState);
2563
2564 pCtx->fWasInHmContext = false;
2565 vmmR0ThreadCtxCallback(RTTHREADCTXEVENT_IN, pVCpu);
2566 }
2567 pCtx->uMagic = VMMR0EMTBLOCKCTX_MAGIC_DEAD;
2568}
2569
2570
2571/**
2572 * Helper for waiting on an RTSEMEVENT, caller did VMMR0EmtPrepareToBlock.
2573 *
2574 * @returns
2575 * @retval VERR_THREAD_IS_TERMINATING
2576 * @retval VERR_TIMEOUT if we ended up waiting too long, either according to
2577 * @a cMsTimeout or to maximum wait values.
2578 *
2579 * @param pGVCpu The ring-0 virtual CPU structure.
2580 * @param fFlags VMMR0EMTWAIT_F_XXX.
2581 * @param hEvent The event to wait on.
2582 * @param cMsTimeout The timeout or RT_INDEFINITE_WAIT.
2583 */
2584VMMR0_INT_DECL(int) VMMR0EmtWaitEventInner(PGVMCPU pGVCpu, uint32_t fFlags, RTSEMEVENT hEvent, RTMSINTERVAL cMsTimeout)
2585{
2586 AssertReturn(pGVCpu->hEMT == RTThreadNativeSelf(), VERR_VM_THREAD_NOT_EMT);
2587
2588 /*
2589 * Note! Similar code is found in the PDM critical sections too.
2590 */
2591 uint64_t const nsStart = RTTimeNanoTS();
2592 uint64_t cNsMaxTotal = cMsTimeout == RT_INDEFINITE_WAIT
2593 ? RT_NS_5MIN : RT_MIN(RT_NS_5MIN, RT_NS_1MS_64 * cMsTimeout);
2594 uint32_t cMsMaxOne = RT_MS_5SEC;
2595 bool fNonInterruptible = false;
2596 for (;;)
2597 {
2598 /* Wait. */
2599 int rcWait = !fNonInterruptible
2600 ? RTSemEventWaitNoResume(hEvent, cMsMaxOne)
2601 : RTSemEventWait(hEvent, cMsMaxOne);
2602 if (RT_SUCCESS(rcWait))
2603 return rcWait;
2604
2605 if (rcWait == VERR_TIMEOUT || rcWait == VERR_INTERRUPTED)
2606 {
2607 uint64_t const cNsElapsed = RTTimeNanoTS() - nsStart;
2608
2609 /*
2610 * Check the thread termination status.
2611 */
2612 int const rcTerm = RTThreadQueryTerminationStatus(NIL_RTTHREAD);
2613 AssertMsg(rcTerm == VINF_SUCCESS || rcTerm == VERR_NOT_SUPPORTED || rcTerm == VINF_THREAD_IS_TERMINATING,
2614 ("rcTerm=%Rrc\n", rcTerm));
2615 if ( rcTerm == VERR_NOT_SUPPORTED
2616 && !fNonInterruptible
2617 && cNsMaxTotal > RT_NS_1MIN)
2618 cNsMaxTotal = RT_NS_1MIN;
2619
2620 /* We return immediately if it looks like the thread is terminating. */
2621 if (rcTerm == VINF_THREAD_IS_TERMINATING)
2622 return VERR_THREAD_IS_TERMINATING;
2623
2624 /* We may suppress VERR_INTERRUPTED if VMMR0EMTWAIT_F_TRY_SUPPRESS_INTERRUPTED was
2625 specified, otherwise we'll just return it. */
2626 if (rcWait == VERR_INTERRUPTED)
2627 {
2628 if (!(fFlags & VMMR0EMTWAIT_F_TRY_SUPPRESS_INTERRUPTED))
2629 return VERR_INTERRUPTED;
2630 if (!fNonInterruptible)
2631 {
2632 /* First time: Adjust down the wait parameters and make sure we get at least
2633 one non-interruptible wait before timing out. */
2634 fNonInterruptible = true;
2635 cMsMaxOne = 32;
2636 uint64_t const cNsLeft = cNsMaxTotal - cNsElapsed;
2637 if (cNsLeft > RT_NS_10SEC)
2638 cNsMaxTotal = cNsElapsed + RT_NS_10SEC;
2639 continue;
2640 }
2641 }
2642
2643 /* Check for timeout. */
2644 if (cNsElapsed > cNsMaxTotal)
2645 return VERR_TIMEOUT;
2646 }
2647 else
2648 return rcWait;
2649 }
2650 /* not reached */
2651}
2652
2653
2654/**
2655 * Helper for signalling an SUPSEMEVENT.
2656 *
2657 * This may temporarily leave the HM context if the host requires that for
2658 * signalling SUPSEMEVENT objects.
2659 *
2660 * @returns VBox status code (see VMMR0EmtPrepareToBlock)
2661 * @param pGVM The ring-0 VM structure.
2662 * @param pGVCpu The ring-0 virtual CPU structure.
2663 * @param hEvent The event to signal.
2664 */
2665VMMR0_INT_DECL(int) VMMR0EmtSignalSupEvent(PGVM pGVM, PGVMCPU pGVCpu, SUPSEMEVENT hEvent)
2666{
2667 AssertReturn(pGVCpu->hEMT == RTThreadNativeSelf(), VERR_VM_THREAD_NOT_EMT);
2668 if (RTSemEventIsSignalSafe())
2669 return SUPSemEventSignal(pGVM->pSession, hEvent);
2670
2671 VMMR0EMTBLOCKCTX Ctx;
2672 int rc = VMMR0EmtPrepareToBlock(pGVCpu, VINF_SUCCESS, __FUNCTION__, (void *)(uintptr_t)hEvent, &Ctx);
2673 if (RT_SUCCESS(rc))
2674 {
2675 rc = SUPSemEventSignal(pGVM->pSession, hEvent);
2676 VMMR0EmtResumeAfterBlocking(pGVCpu, &Ctx);
2677 }
2678 return rc;
2679}
2680
2681
2682/**
2683 * Helper for signalling an SUPSEMEVENT, variant supporting non-EMTs.
2684 *
2685 * This may temporarily leave the HM context if the host requires that for
2686 * signalling SUPSEMEVENT objects.
2687 *
2688 * @returns VBox status code (see VMMR0EmtPrepareToBlock)
2689 * @param pGVM The ring-0 VM structure.
2690 * @param hEvent The event to signal.
2691 */
2692VMMR0_INT_DECL(int) VMMR0EmtSignalSupEventByGVM(PGVM pGVM, SUPSEMEVENT hEvent)
2693{
2694 if (!RTSemEventIsSignalSafe())
2695 {
2696 PGVMCPU pGVCpu = GVMMR0GetGVCpuByGVMandEMT(pGVM, NIL_RTNATIVETHREAD);
2697 if (pGVCpu)
2698 {
2699 VMMR0EMTBLOCKCTX Ctx;
2700 int rc = VMMR0EmtPrepareToBlock(pGVCpu, VINF_SUCCESS, __FUNCTION__, (void *)(uintptr_t)hEvent, &Ctx);
2701 if (RT_SUCCESS(rc))
2702 {
2703 rc = SUPSemEventSignal(pGVM->pSession, hEvent);
2704 VMMR0EmtResumeAfterBlocking(pGVCpu, &Ctx);
2705 }
2706 return rc;
2707 }
2708 }
2709 return SUPSemEventSignal(pGVM->pSession, hEvent);
2710}
2711
2712
2713/*********************************************************************************************************************************
2714* Logging. *
2715*********************************************************************************************************************************/
2716
2717/**
2718 * VMMR0_DO_VMMR0_UPDATE_LOGGERS: Updates the EMT loggers for the VM.
2719 *
2720 * @returns VBox status code.
2721 * @param pGVM The global (ring-0) VM structure.
2722 * @param idCpu The ID of the calling EMT.
2723 * @param pReq The request data.
2724 * @param idxLogger Which logger set to update.
2725 * @thread EMT(idCpu)
2726 */
2727static int vmmR0UpdateLoggers(PGVM pGVM, VMCPUID idCpu, PVMMR0UPDATELOGGERSREQ pReq, size_t idxLogger)
2728{
2729 /*
2730 * Check sanity. First we require EMT to be calling us.
2731 */
2732 AssertReturn(idCpu < pGVM->cCpus, VERR_INVALID_CPU_ID);
2733 AssertReturn(pGVM->aCpus[idCpu].hEMT == RTThreadNativeSelf(), VERR_INVALID_CPU_ID);
2734
2735 AssertReturn(pReq->Hdr.cbReq >= RT_UOFFSETOF_DYN(VMMR0UPDATELOGGERSREQ, afGroups[0]), VERR_INVALID_PARAMETER);
2736 AssertReturn(pReq->cGroups < _8K, VERR_INVALID_PARAMETER);
2737 AssertReturn(pReq->Hdr.cbReq == RT_UOFFSETOF_DYN(VMMR0UPDATELOGGERSREQ, afGroups[pReq->cGroups]), VERR_INVALID_PARAMETER);
2738
2739 AssertReturn(idxLogger < VMMLOGGER_IDX_MAX, VERR_OUT_OF_RANGE);
2740
2741 /*
2742 * Adjust flags.
2743 */
2744 /* Always buffered: */
2745 pReq->fFlags |= RTLOGFLAGS_BUFFERED;
2746 /* These doesn't make sense at present: */
2747 pReq->fFlags &= ~(RTLOGFLAGS_FLUSH | RTLOGFLAGS_WRITE_THROUGH);
2748 /* We've traditionally skipped the group restrictions. */
2749 pReq->fFlags &= ~RTLOGFLAGS_RESTRICT_GROUPS;
2750
2751 /*
2752 * Do the updating.
2753 */
2754 int rc = VINF_SUCCESS;
2755 for (idCpu = 0; idCpu < pGVM->cCpus; idCpu++)
2756 {
2757 PGVMCPU pGVCpu = &pGVM->aCpus[idCpu];
2758 PRTLOGGER pLogger = pGVCpu->vmmr0.s.u.aLoggers[idxLogger].pLogger;
2759 if (pLogger)
2760 {
2761 RTLogSetR0ProgramStart(pLogger, pGVM->vmm.s.nsProgramStart);
2762 rc = RTLogBulkUpdate(pLogger, pReq->fFlags, pReq->uGroupCrc32, pReq->cGroups, pReq->afGroups);
2763 }
2764 }
2765
2766 return rc;
2767}
2768
2769
2770/**
2771 * VMMR0_DO_VMMR0_LOG_FLUSHER: Get the next log flushing job.
2772 *
2773 * The job info is copied into VMM::LogFlusherItem.
2774 *
2775 * @returns VBox status code.
2776 * @retval VERR_OBJECT_DESTROYED if we're shutting down.
2777 * @retval VERR_NOT_OWNER if the calling thread is not the flusher thread.
2778 * @param pGVM The global (ring-0) VM structure.
2779 * @thread The log flusher thread (first caller automatically becomes the log
2780 * flusher).
2781 */
2782static int vmmR0LogFlusher(PGVM pGVM)
2783{
2784 /*
2785 * Check that this really is the flusher thread.
2786 */
2787 RTNATIVETHREAD const hNativeSelf = RTThreadNativeSelf();
2788 AssertReturn(hNativeSelf != NIL_RTNATIVETHREAD, VERR_INTERNAL_ERROR_3);
2789 if (RT_LIKELY(pGVM->vmmr0.s.LogFlusher.hThread == hNativeSelf))
2790 { /* likely */ }
2791 else
2792 {
2793 /* The first caller becomes the flusher thread. */
2794 bool fOk;
2795 ASMAtomicCmpXchgHandle(&pGVM->vmmr0.s.LogFlusher.hThread, hNativeSelf, NIL_RTNATIVETHREAD, fOk);
2796 if (!fOk)
2797 return VERR_NOT_OWNER;
2798 pGVM->vmmr0.s.LogFlusher.fThreadRunning = true;
2799 }
2800
2801 /*
2802 * Acknowledge flush, waking up waiting EMT.
2803 */
2804 RTSpinlockAcquire(pGVM->vmmr0.s.LogFlusher.hSpinlock);
2805
2806 uint32_t idxTail = pGVM->vmmr0.s.LogFlusher.idxRingTail % RT_ELEMENTS(pGVM->vmmr0.s.LogFlusher.aRing);
2807 uint32_t idxHead = pGVM->vmmr0.s.LogFlusher.idxRingHead % RT_ELEMENTS(pGVM->vmmr0.s.LogFlusher.aRing);
2808 if ( idxTail != idxHead
2809 && pGVM->vmmr0.s.LogFlusher.aRing[idxHead].s.fProcessing)
2810 {
2811 /* Pop the head off the ring buffer. */
2812 uint32_t const idCpu = pGVM->vmmr0.s.LogFlusher.aRing[idxHead].s.idCpu;
2813 uint32_t const idxLogger = pGVM->vmmr0.s.LogFlusher.aRing[idxHead].s.idxLogger;
2814 uint32_t const idxBuffer = pGVM->vmmr0.s.LogFlusher.aRing[idxHead].s.idxBuffer;
2815
2816 pGVM->vmmr0.s.LogFlusher.aRing[idxHead].u32 = UINT32_MAX >> 1; /* invalidate the entry */
2817 pGVM->vmmr0.s.LogFlusher.idxRingHead = (idxHead + 1) % RT_ELEMENTS(pGVM->vmmr0.s.LogFlusher.aRing);
2818
2819 /* Validate content. */
2820 if ( idCpu < pGVM->cCpus
2821 && idxLogger < VMMLOGGER_IDX_MAX
2822 && idxBuffer < VMMLOGGER_BUFFER_COUNT)
2823 {
2824 PGVMCPU pGVCpu = &pGVM->aCpus[idCpu];
2825 PVMMR0PERVCPULOGGER pR0Log = &pGVCpu->vmmr0.s.u.aLoggers[idxLogger];
2826 PVMMR3CPULOGGER pShared = &pGVCpu->vmm.s.u.aLoggers[idxLogger];
2827
2828 /*
2829 * Accounting.
2830 */
2831 uint32_t cFlushing = pR0Log->cFlushing - 1;
2832 if (RT_LIKELY(cFlushing < VMMLOGGER_BUFFER_COUNT))
2833 { /*likely*/ }
2834 else
2835 cFlushing = 0;
2836 pR0Log->cFlushing = cFlushing;
2837 ASMAtomicWriteU32(&pShared->cFlushing, cFlushing);
2838
2839 /*
2840 * Wake up the EMT if it's waiting.
2841 */
2842 if (!pR0Log->fEmtWaiting)
2843 RTSpinlockRelease(pGVM->vmmr0.s.LogFlusher.hSpinlock);
2844 else
2845 {
2846 pR0Log->fEmtWaiting = false;
2847 RTSpinlockRelease(pGVM->vmmr0.s.LogFlusher.hSpinlock);
2848
2849 int rc = RTSemEventSignal(pR0Log->hEventFlushWait);
2850 if (RT_FAILURE(rc))
2851 LogRelMax(64, ("vmmR0LogFlusher: RTSemEventSignal failed ACKing entry #%u (%u/%u/%u): %Rrc!\n",
2852 idxHead, idCpu, idxLogger, idxBuffer, rc));
2853 }
2854 }
2855 else
2856 {
2857 RTSpinlockRelease(pGVM->vmmr0.s.LogFlusher.hSpinlock);
2858 LogRelMax(64, ("vmmR0LogFlusher: Bad ACK entry #%u: %u/%u/%u!\n", idxHead, idCpu, idxLogger, idxBuffer));
2859 }
2860
2861 RTSpinlockAcquire(pGVM->vmmr0.s.LogFlusher.hSpinlock);
2862 }
2863
2864 /*
2865 * The wait loop.
2866 */
2867 int rc;
2868 for (;;)
2869 {
2870 /*
2871 * Work pending?
2872 */
2873 idxTail = pGVM->vmmr0.s.LogFlusher.idxRingTail % RT_ELEMENTS(pGVM->vmmr0.s.LogFlusher.aRing);
2874 idxHead = pGVM->vmmr0.s.LogFlusher.idxRingHead % RT_ELEMENTS(pGVM->vmmr0.s.LogFlusher.aRing);
2875 if (idxTail != idxHead)
2876 {
2877 pGVM->vmmr0.s.LogFlusher.aRing[idxHead].s.fProcessing = true;
2878 pGVM->vmm.s.LogFlusherItem.u32 = pGVM->vmmr0.s.LogFlusher.aRing[idxHead].u32;
2879
2880 RTSpinlockRelease(pGVM->vmmr0.s.LogFlusher.hSpinlock);
2881 return VINF_SUCCESS;
2882 }
2883
2884 /*
2885 * Nothing to do, so, check for termination and go to sleep.
2886 */
2887 if (!pGVM->vmmr0.s.LogFlusher.fThreadShutdown)
2888 { /* likely */ }
2889 else
2890 {
2891 rc = VERR_OBJECT_DESTROYED;
2892 break;
2893 }
2894
2895 pGVM->vmmr0.s.LogFlusher.fThreadWaiting = true;
2896 RTSpinlockRelease(pGVM->vmmr0.s.LogFlusher.hSpinlock);
2897
2898 rc = RTSemEventWaitNoResume(pGVM->vmmr0.s.LogFlusher.hEvent, RT_MS_5MIN);
2899
2900 RTSpinlockAcquire(pGVM->vmmr0.s.LogFlusher.hSpinlock);
2901 pGVM->vmmr0.s.LogFlusher.fThreadWaiting = false;
2902
2903 if (RT_SUCCESS(rc) || rc == VERR_TIMEOUT)
2904 { /* likely */ }
2905 else if (rc == VERR_INTERRUPTED)
2906 {
2907 RTSpinlockRelease(pGVM->vmmr0.s.LogFlusher.hSpinlock);
2908 return rc;
2909 }
2910 else if (rc == VERR_SEM_DESTROYED || rc == VERR_INVALID_HANDLE)
2911 break;
2912 else
2913 {
2914 LogRel(("vmmR0LogFlusher: RTSemEventWaitNoResume returned unexpected status %Rrc\n", rc));
2915 break;
2916 }
2917 }
2918
2919 /*
2920 * Terminating - prevent further calls and indicate to the EMTs that we're no longer around.
2921 */
2922 pGVM->vmmr0.s.LogFlusher.hThread = ~pGVM->vmmr0.s.LogFlusher.hThread; /* (should be reasonably safe) */
2923 pGVM->vmmr0.s.LogFlusher.fThreadRunning = false;
2924
2925 RTSpinlockRelease(pGVM->vmmr0.s.LogFlusher.hSpinlock);
2926 return rc;
2927}
2928
2929
2930/**
2931 * VMMR0_DO_VMMR0_LOG_WAIT_FLUSHED: Waits for the flusher thread to finish all
2932 * buffers for logger @a idxLogger.
2933 *
2934 * @returns VBox status code.
2935 * @param pGVM The global (ring-0) VM structure.
2936 * @param idCpu The ID of the calling EMT.
2937 * @param idxLogger Which logger to wait on.
2938 * @thread EMT(idCpu)
2939 */
2940static int vmmR0LogWaitFlushed(PGVM pGVM, VMCPUID idCpu, size_t idxLogger)
2941{
2942 /*
2943 * Check sanity. First we require EMT to be calling us.
2944 */
2945 AssertReturn(idCpu < pGVM->cCpus, VERR_INVALID_CPU_ID);
2946 PGVMCPU pGVCpu = &pGVM->aCpus[idCpu];
2947 AssertReturn(pGVCpu->hEMT == RTThreadNativeSelf(), VERR_INVALID_CPU_ID);
2948 AssertReturn(idxLogger < VMMLOGGER_IDX_MAX, VERR_OUT_OF_RANGE);
2949 PVMMR0PERVCPULOGGER const pR0Log = &pGVCpu->vmmr0.s.u.aLoggers[idxLogger];
2950
2951 /*
2952 * Do the waiting.
2953 */
2954 int rc = VINF_SUCCESS;
2955 RTSpinlockAcquire(pGVM->vmmr0.s.LogFlusher.hSpinlock);
2956 uint32_t cFlushing = pR0Log->cFlushing;
2957 while (cFlushing > 0)
2958 {
2959 pR0Log->fEmtWaiting = true;
2960 RTSpinlockRelease(pGVM->vmmr0.s.LogFlusher.hSpinlock);
2961
2962 rc = RTSemEventWaitNoResume(pR0Log->hEventFlushWait, RT_MS_5MIN);
2963
2964 RTSpinlockAcquire(pGVM->vmmr0.s.LogFlusher.hSpinlock);
2965 pR0Log->fEmtWaiting = false;
2966 if (RT_SUCCESS(rc))
2967 {
2968 /* Read the new count, make sure it decreased before looping. That
2969 way we can guarentee that we will only wait more than 5 min * buffers. */
2970 uint32_t const cPrevFlushing = cFlushing;
2971 cFlushing = pR0Log->cFlushing;
2972 if (cFlushing < cPrevFlushing)
2973 continue;
2974 rc = VERR_INTERNAL_ERROR_3;
2975 }
2976 break;
2977 }
2978 RTSpinlockRelease(pGVM->vmmr0.s.LogFlusher.hSpinlock);
2979 return rc;
2980}
2981
2982
2983/**
2984 * Inner worker for vmmR0LoggerFlushCommon.
2985 */
2986static bool vmmR0LoggerFlushInner(PGVM pGVM, PGVMCPU pGVCpu, uint32_t idxLogger, size_t idxBuffer, uint32_t cbToFlush)
2987{
2988 PVMMR0PERVCPULOGGER const pR0Log = &pGVCpu->vmmr0.s.u.aLoggers[idxLogger];
2989 PVMMR3CPULOGGER const pShared = &pGVCpu->vmm.s.u.aLoggers[idxLogger];
2990
2991 /*
2992 * Figure out what we need to do and whether we can.
2993 */
2994 enum { kJustSignal, kPrepAndSignal, kPrepSignalAndWait } enmAction;
2995#if VMMLOGGER_BUFFER_COUNT >= 2
2996 if (pR0Log->cFlushing < VMMLOGGER_BUFFER_COUNT - 1)
2997 {
2998 if (RTSemEventIsSignalSafe())
2999 enmAction = kJustSignal;
3000 else if (VMMRZCallRing3IsEnabled(pGVCpu))
3001 enmAction = kPrepAndSignal;
3002 else
3003 {
3004 /** @todo This is a bit simplistic. We could introduce a FF to signal the
3005 * thread or similar. */
3006 STAM_REL_COUNTER_INC(&pShared->StatCannotBlock);
3007# if defined(RT_OS_LINUX)
3008 SUP_DPRINTF(("vmmR0LoggerFlush: Signalling not safe and EMT blocking disabled! (%u bytes)\n", cbToFlush));
3009# endif
3010 pShared->cbDropped += cbToFlush;
3011 return true;
3012 }
3013 }
3014 else
3015#endif
3016 if (VMMRZCallRing3IsEnabled(pGVCpu))
3017 enmAction = kPrepSignalAndWait;
3018 else
3019 {
3020 STAM_REL_COUNTER_INC(&pShared->StatCannotBlock);
3021# if defined(RT_OS_LINUX)
3022 SUP_DPRINTF(("vmmR0LoggerFlush: EMT blocking disabled! (%u bytes)\n", cbToFlush));
3023# endif
3024 pShared->cbDropped += cbToFlush;
3025 return true;
3026 }
3027
3028 /*
3029 * Prepare for blocking if necessary.
3030 */
3031 VMMR0EMTBLOCKCTX Ctx;
3032 if (enmAction != kJustSignal)
3033 {
3034 int rc = VMMR0EmtPrepareToBlock(pGVCpu, VINF_SUCCESS, "vmmR0LoggerFlushInner", pR0Log->hEventFlushWait, &Ctx);
3035 if (RT_SUCCESS(rc))
3036 { /* likely */ }
3037 else
3038 {
3039 STAM_REL_COUNTER_INC(&pShared->StatCannotBlock);
3040 SUP_DPRINTF(("vmmR0LoggerFlush: VMMR0EmtPrepareToBlock failed! rc=%d\n", rc));
3041 return false;
3042 }
3043 }
3044
3045 /*
3046 * Queue the flush job.
3047 */
3048 bool fFlushedBuffer;
3049 RTSpinlockAcquire(pGVM->vmmr0.s.LogFlusher.hSpinlock);
3050 if (pGVM->vmmr0.s.LogFlusher.fThreadRunning)
3051 {
3052 uint32_t const idxHead = pGVM->vmmr0.s.LogFlusher.idxRingHead % RT_ELEMENTS(pGVM->vmmr0.s.LogFlusher.aRing);
3053 uint32_t const idxTail = pGVM->vmmr0.s.LogFlusher.idxRingTail % RT_ELEMENTS(pGVM->vmmr0.s.LogFlusher.aRing);
3054 uint32_t const idxNewTail = (idxTail + 1) % RT_ELEMENTS(pGVM->vmmr0.s.LogFlusher.aRing);
3055 if (idxNewTail != idxHead)
3056 {
3057 /* Queue it. */
3058 pGVM->vmmr0.s.LogFlusher.aRing[idxTail].s.idCpu = pGVCpu->idCpu;
3059 pGVM->vmmr0.s.LogFlusher.aRing[idxTail].s.idxLogger = idxLogger;
3060 pGVM->vmmr0.s.LogFlusher.aRing[idxTail].s.idxBuffer = (uint32_t)idxBuffer;
3061 pGVM->vmmr0.s.LogFlusher.aRing[idxTail].s.fProcessing = 0;
3062 pGVM->vmmr0.s.LogFlusher.idxRingTail = idxNewTail;
3063
3064 /* Update the number of buffers currently being flushed. */
3065 uint32_t cFlushing = pR0Log->cFlushing;
3066 cFlushing = RT_MIN(cFlushing + 1, VMMLOGGER_BUFFER_COUNT);
3067 pShared->cFlushing = pR0Log->cFlushing = cFlushing;
3068
3069 /* We must wait if all buffers are currently being flushed. */
3070 bool const fEmtWaiting = cFlushing >= VMMLOGGER_BUFFER_COUNT && enmAction != kJustSignal /* paranoia */;
3071 pR0Log->fEmtWaiting = fEmtWaiting;
3072
3073 /* Stats. */
3074 STAM_REL_COUNTER_INC(&pShared->StatFlushes);
3075 STAM_REL_COUNTER_INC(&pGVM->vmm.s.StatLogFlusherFlushes);
3076
3077 /* Signal the worker thread. */
3078 if (pGVM->vmmr0.s.LogFlusher.fThreadWaiting)
3079 {
3080 RTSpinlockRelease(pGVM->vmmr0.s.LogFlusher.hSpinlock);
3081 RTSemEventSignal(pGVM->vmmr0.s.LogFlusher.hEvent);
3082 }
3083 else
3084 {
3085 STAM_REL_COUNTER_INC(&pGVM->vmm.s.StatLogFlusherNoWakeUp);
3086 RTSpinlockRelease(pGVM->vmmr0.s.LogFlusher.hSpinlock);
3087 }
3088
3089 /*
3090 * Wait for a buffer to finish flushing.
3091 *
3092 * Note! Lazy bird is ignoring the status code here. The result is
3093 * that we might end up with an extra even signalling and the
3094 * next time we need to wait we won't and end up with some log
3095 * corruption. However, it's too much hazzle right now for
3096 * a scenario which would most likely end the process rather
3097 * than causing log corruption.
3098 */
3099 if (fEmtWaiting)
3100 {
3101 STAM_REL_PROFILE_START(&pShared->StatWait, a);
3102 VMMR0EmtWaitEventInner(pGVCpu, VMMR0EMTWAIT_F_TRY_SUPPRESS_INTERRUPTED,
3103 pR0Log->hEventFlushWait, RT_INDEFINITE_WAIT);
3104 STAM_REL_PROFILE_STOP(&pShared->StatWait, a);
3105 }
3106
3107 /*
3108 * We always switch buffer if we have more than one.
3109 */
3110#if VMMLOGGER_BUFFER_COUNT == 1
3111 fFlushedBuffer = true;
3112#else
3113 AssertCompile(VMMLOGGER_BUFFER_COUNT >= 1);
3114 pShared->idxBuf = (idxBuffer + 1) % VMMLOGGER_BUFFER_COUNT;
3115 fFlushedBuffer = false;
3116#endif
3117 }
3118 else
3119 {
3120 RTSpinlockRelease(pGVM->vmmr0.s.LogFlusher.hSpinlock);
3121 SUP_DPRINTF(("vmmR0LoggerFlush: ring buffer is full!\n"));
3122 fFlushedBuffer = true;
3123 }
3124 }
3125 else
3126 {
3127 RTSpinlockRelease(pGVM->vmmr0.s.LogFlusher.hSpinlock);
3128 SUP_DPRINTF(("vmmR0LoggerFlush: flusher not active - dropping %u bytes\n", cbToFlush));
3129 fFlushedBuffer = true;
3130 }
3131
3132 /*
3133 * Restore the HM context.
3134 */
3135 if (enmAction != kJustSignal)
3136 VMMR0EmtResumeAfterBlocking(pGVCpu, &Ctx);
3137
3138 return fFlushedBuffer;
3139}
3140
3141
3142/**
3143 * Common worker for vmmR0LogFlush and vmmR0LogRelFlush.
3144 */
3145static bool vmmR0LoggerFlushCommon(PRTLOGGER pLogger, PRTLOGBUFFERDESC pBufDesc, uint32_t idxLogger)
3146{
3147 /*
3148 * Convert the pLogger into a GVMCPU handle and 'call' back to Ring-3.
3149 * (This is a bit paranoid code.)
3150 */
3151 if (RT_VALID_PTR(pLogger))
3152 {
3153 if ( pLogger->u32Magic == RTLOGGER_MAGIC
3154 && (pLogger->u32UserValue1 & VMMR0_LOGGER_FLAGS_MAGIC_MASK) == VMMR0_LOGGER_FLAGS_MAGIC_VALUE
3155 && pLogger->u64UserValue2 == pLogger->u64UserValue3)
3156 {
3157 PGVMCPU const pGVCpu = (PGVMCPU)(uintptr_t)pLogger->u64UserValue2;
3158 if ( RT_VALID_PTR(pGVCpu)
3159 && ((uintptr_t)pGVCpu & HOST_PAGE_OFFSET_MASK) == 0)
3160 {
3161 RTNATIVETHREAD const hNativeSelf = RTThreadNativeSelf();
3162 PGVM const pGVM = pGVCpu->pGVM;
3163 if ( hNativeSelf == pGVCpu->hEMT
3164 && RT_VALID_PTR(pGVM))
3165 {
3166 PVMMR0PERVCPULOGGER const pR0Log = &pGVCpu->vmmr0.s.u.aLoggers[idxLogger];
3167 size_t const idxBuffer = pBufDesc - &pR0Log->aBufDescs[0];
3168 if (idxBuffer < VMMLOGGER_BUFFER_COUNT)
3169 {
3170 /*
3171 * Make sure we don't recurse forever here should something in the
3172 * following code trigger logging or an assertion. Do the rest in
3173 * an inner work to avoid hitting the right margin too hard.
3174 */
3175 if (!pR0Log->fFlushing)
3176 {
3177 pR0Log->fFlushing = true;
3178 bool fFlushed = vmmR0LoggerFlushInner(pGVM, pGVCpu, idxLogger, idxBuffer, pBufDesc->offBuf);
3179 pR0Log->fFlushing = false;
3180 return fFlushed;
3181 }
3182
3183 SUP_DPRINTF(("vmmR0LoggerFlush: Recursive flushing!\n"));
3184 }
3185 else
3186 SUP_DPRINTF(("vmmR0LoggerFlush: pLogger=%p pGVCpu=%p: idxBuffer=%#zx\n", pLogger, pGVCpu, idxBuffer));
3187 }
3188 else
3189 SUP_DPRINTF(("vmmR0LoggerFlush: pLogger=%p pGVCpu=%p hEMT=%p hNativeSelf=%p!\n",
3190 pLogger, pGVCpu, pGVCpu->hEMT, hNativeSelf));
3191 }
3192 else
3193 SUP_DPRINTF(("vmmR0LoggerFlush: pLogger=%p pGVCpu=%p!\n", pLogger, pGVCpu));
3194 }
3195 else
3196 SUP_DPRINTF(("vmmR0LoggerFlush: pLogger=%p u32Magic=%#x u32UserValue1=%#x u64UserValue2=%#RX64 u64UserValue3=%#RX64!\n",
3197 pLogger, pLogger->u32Magic, pLogger->u32UserValue1, pLogger->u64UserValue2, pLogger->u64UserValue3));
3198 }
3199 else
3200 SUP_DPRINTF(("vmmR0LoggerFlush: pLogger=%p!\n", pLogger));
3201 return true;
3202}
3203
3204
3205/**
3206 * @callback_method_impl{FNRTLOGFLUSH, Release logger buffer flush callback.}
3207 */
3208static DECLCALLBACK(bool) vmmR0LogRelFlush(PRTLOGGER pLogger, PRTLOGBUFFERDESC pBufDesc)
3209{
3210 return vmmR0LoggerFlushCommon(pLogger, pBufDesc, VMMLOGGER_IDX_RELEASE);
3211}
3212
3213
3214/**
3215 * @callback_method_impl{FNRTLOGFLUSH, Logger (debug) buffer flush callback.}
3216 */
3217static DECLCALLBACK(bool) vmmR0LogFlush(PRTLOGGER pLogger, PRTLOGBUFFERDESC pBufDesc)
3218{
3219#ifdef LOG_ENABLED
3220 return vmmR0LoggerFlushCommon(pLogger, pBufDesc, VMMLOGGER_IDX_REGULAR);
3221#else
3222 RT_NOREF(pLogger, pBufDesc);
3223 return true;
3224#endif
3225}
3226
3227
3228/*
3229 * Override RTLogDefaultInstanceEx so we can do logging from EMTs in ring-0.
3230 */
3231DECLEXPORT(PRTLOGGER) RTLogDefaultInstanceEx(uint32_t fFlagsAndGroup)
3232{
3233#ifdef LOG_ENABLED
3234 PGVMCPU pGVCpu = GVMMR0GetGVCpuByEMT(NIL_RTNATIVETHREAD);
3235 if (pGVCpu)
3236 {
3237 PRTLOGGER pLogger = pGVCpu->vmmr0.s.u.s.Logger.pLogger;
3238 if (RT_VALID_PTR(pLogger))
3239 {
3240 if ( pLogger->u64UserValue2 == (uintptr_t)pGVCpu
3241 && pLogger->u64UserValue3 == (uintptr_t)pGVCpu)
3242 {
3243 if (!pGVCpu->vmmr0.s.u.s.Logger.fFlushing)
3244 {
3245 if (!(pGVCpu->vmmr0.s.fLogFlushingDisabled))
3246 return RTLogCheckGroupFlags(pLogger, fFlagsAndGroup);
3247 return NULL;
3248 }
3249
3250 /*
3251 * When we're flushing we _must_ return NULL here to suppress any
3252 * attempts at using the logger while in vmmR0LoggerFlushCommon.
3253 * The VMMR0EmtPrepareToBlock code may trigger logging in HM,
3254 * which will reset the buffer content before we even get to queue
3255 * the flush request. (Only an issue when VBOX_WITH_R0_LOGGING
3256 * is enabled.)
3257 */
3258 return NULL;
3259 }
3260 }
3261 }
3262#endif
3263 return SUPR0DefaultLogInstanceEx(fFlagsAndGroup);
3264}
3265
3266
3267/*
3268 * Override RTLogRelGetDefaultInstanceEx so we can do LogRel to VBox.log from EMTs in ring-0.
3269 */
3270DECLEXPORT(PRTLOGGER) RTLogRelGetDefaultInstanceEx(uint32_t fFlagsAndGroup)
3271{
3272 PGVMCPU pGVCpu = GVMMR0GetGVCpuByEMT(NIL_RTNATIVETHREAD);
3273 if (pGVCpu)
3274 {
3275 PRTLOGGER pLogger = pGVCpu->vmmr0.s.u.s.RelLogger.pLogger;
3276 if (RT_VALID_PTR(pLogger))
3277 {
3278 if ( pLogger->u64UserValue2 == (uintptr_t)pGVCpu
3279 && pLogger->u64UserValue3 == (uintptr_t)pGVCpu)
3280 {
3281 if (!pGVCpu->vmmr0.s.u.s.RelLogger.fFlushing)
3282 {
3283 if (!(pGVCpu->vmmr0.s.fLogFlushingDisabled))
3284 return RTLogCheckGroupFlags(pLogger, fFlagsAndGroup);
3285 return NULL;
3286 }
3287 }
3288 }
3289 }
3290 return SUPR0GetDefaultLogRelInstanceEx(fFlagsAndGroup);
3291}
3292
3293
3294/**
3295 * Helper for vmmR0InitLoggerSet
3296 */
3297static int vmmR0InitLoggerOne(PGVMCPU pGVCpu, bool fRelease, PVMMR0PERVCPULOGGER pR0Log, PVMMR3CPULOGGER pShared,
3298 uint32_t cbBuf, char *pchBuf, RTR3PTR pchBufR3)
3299{
3300 /*
3301 * Create and configure the logger.
3302 */
3303 for (size_t i = 0; i < VMMLOGGER_BUFFER_COUNT; i++)
3304 {
3305 pR0Log->aBufDescs[i].u32Magic = RTLOGBUFFERDESC_MAGIC;
3306 pR0Log->aBufDescs[i].uReserved = 0;
3307 pR0Log->aBufDescs[i].cbBuf = cbBuf;
3308 pR0Log->aBufDescs[i].offBuf = 0;
3309 pR0Log->aBufDescs[i].pchBuf = pchBuf + i * cbBuf;
3310 pR0Log->aBufDescs[i].pAux = &pShared->aBufs[i].AuxDesc;
3311
3312 pShared->aBufs[i].AuxDesc.fFlushedIndicator = false;
3313 pShared->aBufs[i].AuxDesc.afPadding[0] = 0;
3314 pShared->aBufs[i].AuxDesc.afPadding[1] = 0;
3315 pShared->aBufs[i].AuxDesc.afPadding[2] = 0;
3316 pShared->aBufs[i].AuxDesc.offBuf = 0;
3317 pShared->aBufs[i].pchBufR3 = pchBufR3 + i * cbBuf;
3318 }
3319 pShared->cbBuf = cbBuf;
3320
3321 static const char * const s_apszGroups[] = VBOX_LOGGROUP_NAMES;
3322 int rc = RTLogCreateEx(&pR0Log->pLogger, fRelease ? "VBOX_RELEASE_LOG" : "VBOX_LOG", RTLOG_F_NO_LOCKING | RTLOGFLAGS_BUFFERED,
3323 "all", RT_ELEMENTS(s_apszGroups), s_apszGroups, UINT32_MAX,
3324 VMMLOGGER_BUFFER_COUNT, pR0Log->aBufDescs, RTLOGDEST_DUMMY,
3325 NULL /*pfnPhase*/, 0 /*cHistory*/, 0 /*cbHistoryFileMax*/, 0 /*cSecsHistoryTimeSlot*/,
3326 NULL /*pErrInfo*/, NULL /*pszFilenameFmt*/);
3327 if (RT_SUCCESS(rc))
3328 {
3329 PRTLOGGER pLogger = pR0Log->pLogger;
3330 pLogger->u32UserValue1 = VMMR0_LOGGER_FLAGS_MAGIC_VALUE;
3331 pLogger->u64UserValue2 = (uintptr_t)pGVCpu;
3332 pLogger->u64UserValue3 = (uintptr_t)pGVCpu;
3333
3334 rc = RTLogSetFlushCallback(pLogger, fRelease ? vmmR0LogRelFlush : vmmR0LogFlush);
3335 if (RT_SUCCESS(rc))
3336 {
3337 RTLogSetR0ThreadNameF(pLogger, "EMT-%u-R0", pGVCpu->idCpu);
3338
3339 /*
3340 * Create the event sem the EMT waits on while flushing is happening.
3341 */
3342 rc = RTSemEventCreate(&pR0Log->hEventFlushWait);
3343 if (RT_SUCCESS(rc))
3344 return VINF_SUCCESS;
3345 pR0Log->hEventFlushWait = NIL_RTSEMEVENT;
3346 }
3347 RTLogDestroy(pLogger);
3348 }
3349 pR0Log->pLogger = NULL;
3350 return rc;
3351}
3352
3353
3354/**
3355 * Worker for VMMR0CleanupVM and vmmR0InitLoggerSet that destroys one logger.
3356 */
3357static void vmmR0TermLoggerOne(PVMMR0PERVCPULOGGER pR0Log, PVMMR3CPULOGGER pShared)
3358{
3359 RTLogDestroy(pR0Log->pLogger);
3360 pR0Log->pLogger = NULL;
3361
3362 for (size_t i = 0; i < VMMLOGGER_BUFFER_COUNT; i++)
3363 pShared->aBufs[i].pchBufR3 = NIL_RTR3PTR;
3364
3365 RTSemEventDestroy(pR0Log->hEventFlushWait);
3366 pR0Log->hEventFlushWait = NIL_RTSEMEVENT;
3367}
3368
3369
3370/**
3371 * Initializes one type of loggers for each EMT.
3372 */
3373static int vmmR0InitLoggerSet(PGVM pGVM, uint8_t idxLogger, uint32_t cbBuf, PRTR0MEMOBJ phMemObj, PRTR0MEMOBJ phMapObj)
3374{
3375 /* Allocate buffers first. */
3376 int rc = RTR0MemObjAllocPage(phMemObj, cbBuf * pGVM->cCpus * VMMLOGGER_BUFFER_COUNT, false /*fExecutable*/);
3377 if (RT_SUCCESS(rc))
3378 {
3379 rc = RTR0MemObjMapUser(phMapObj, *phMemObj, (RTR3PTR)-1, 0 /*uAlignment*/, RTMEM_PROT_READ, NIL_RTR0PROCESS);
3380 if (RT_SUCCESS(rc))
3381 {
3382 char * const pchBuf = (char *)RTR0MemObjAddress(*phMemObj);
3383 AssertPtrReturn(pchBuf, VERR_INTERNAL_ERROR_2);
3384
3385 RTR3PTR const pchBufR3 = RTR0MemObjAddressR3(*phMapObj);
3386 AssertReturn(pchBufR3 != NIL_RTR3PTR, VERR_INTERNAL_ERROR_3);
3387
3388 /* Initialize the per-CPU loggers. */
3389 for (uint32_t i = 0; i < pGVM->cCpus; i++)
3390 {
3391 PGVMCPU pGVCpu = &pGVM->aCpus[i];
3392 PVMMR0PERVCPULOGGER pR0Log = &pGVCpu->vmmr0.s.u.aLoggers[idxLogger];
3393 PVMMR3CPULOGGER pShared = &pGVCpu->vmm.s.u.aLoggers[idxLogger];
3394 rc = vmmR0InitLoggerOne(pGVCpu, idxLogger == VMMLOGGER_IDX_RELEASE, pR0Log, pShared, cbBuf,
3395 pchBuf + i * cbBuf * VMMLOGGER_BUFFER_COUNT,
3396 pchBufR3 + i * cbBuf * VMMLOGGER_BUFFER_COUNT);
3397 if (RT_FAILURE(rc))
3398 {
3399 vmmR0TermLoggerOne(pR0Log, pShared);
3400 while (i-- > 0)
3401 {
3402 pGVCpu = &pGVM->aCpus[i];
3403 vmmR0TermLoggerOne(&pGVCpu->vmmr0.s.u.aLoggers[idxLogger], &pGVCpu->vmm.s.u.aLoggers[idxLogger]);
3404 }
3405 break;
3406 }
3407 }
3408 if (RT_SUCCESS(rc))
3409 return VINF_SUCCESS;
3410
3411 /* Bail out. */
3412 RTR0MemObjFree(*phMapObj, false /*fFreeMappings*/);
3413 *phMapObj = NIL_RTR0MEMOBJ;
3414 }
3415 RTR0MemObjFree(*phMemObj, true /*fFreeMappings*/);
3416 *phMemObj = NIL_RTR0MEMOBJ;
3417 }
3418 return rc;
3419}
3420
3421
3422/**
3423 * Worker for VMMR0InitPerVMData that initializes all the logging related stuff.
3424 *
3425 * @returns VBox status code.
3426 * @param pGVM The global (ring-0) VM structure.
3427 */
3428static int vmmR0InitLoggers(PGVM pGVM)
3429{
3430 /*
3431 * Invalidate the ring buffer (not really necessary).
3432 */
3433 for (size_t idx = 0; idx < RT_ELEMENTS(pGVM->vmmr0.s.LogFlusher.aRing); idx++)
3434 pGVM->vmmr0.s.LogFlusher.aRing[idx].u32 = UINT32_MAX >> 1; /* (all bits except fProcessing set) */
3435
3436 /*
3437 * Create the spinlock and flusher event semaphore.
3438 */
3439 int rc = RTSpinlockCreate(&pGVM->vmmr0.s.LogFlusher.hSpinlock, RTSPINLOCK_FLAGS_INTERRUPT_SAFE, "VM-Log-Flusher");
3440 if (RT_SUCCESS(rc))
3441 {
3442 rc = RTSemEventCreate(&pGVM->vmmr0.s.LogFlusher.hEvent);
3443 if (RT_SUCCESS(rc))
3444 {
3445 /*
3446 * Create the ring-0 release loggers.
3447 */
3448 rc = vmmR0InitLoggerSet(pGVM, VMMLOGGER_IDX_RELEASE, _4K,
3449 &pGVM->vmmr0.s.hMemObjReleaseLogger, &pGVM->vmmr0.s.hMapObjReleaseLogger);
3450#ifdef LOG_ENABLED
3451 if (RT_SUCCESS(rc))
3452 {
3453 /*
3454 * Create debug loggers.
3455 */
3456 rc = vmmR0InitLoggerSet(pGVM, VMMLOGGER_IDX_REGULAR, _64K,
3457 &pGVM->vmmr0.s.hMemObjLogger, &pGVM->vmmr0.s.hMapObjLogger);
3458 }
3459#endif
3460 }
3461 }
3462 return rc;
3463}
3464
3465
3466/**
3467 * Worker for VMMR0InitPerVMData that initializes all the logging related stuff.
3468 *
3469 * @param pGVM The global (ring-0) VM structure.
3470 */
3471static void vmmR0CleanupLoggers(PGVM pGVM)
3472{
3473 for (VMCPUID idCpu = 0; idCpu < pGVM->cCpus; idCpu++)
3474 {
3475 PGVMCPU pGVCpu = &pGVM->aCpus[idCpu];
3476 for (size_t iLogger = 0; iLogger < RT_ELEMENTS(pGVCpu->vmmr0.s.u.aLoggers); iLogger++)
3477 vmmR0TermLoggerOne(&pGVCpu->vmmr0.s.u.aLoggers[iLogger], &pGVCpu->vmm.s.u.aLoggers[iLogger]);
3478 }
3479
3480 /*
3481 * Free logger buffer memory.
3482 */
3483 RTR0MemObjFree(pGVM->vmmr0.s.hMapObjReleaseLogger, false /*fFreeMappings*/);
3484 pGVM->vmmr0.s.hMapObjReleaseLogger = NIL_RTR0MEMOBJ;
3485 RTR0MemObjFree(pGVM->vmmr0.s.hMemObjReleaseLogger, true /*fFreeMappings*/);
3486 pGVM->vmmr0.s.hMemObjReleaseLogger = NIL_RTR0MEMOBJ;
3487
3488 RTR0MemObjFree(pGVM->vmmr0.s.hMapObjLogger, false /*fFreeMappings*/);
3489 pGVM->vmmr0.s.hMapObjLogger = NIL_RTR0MEMOBJ;
3490 RTR0MemObjFree(pGVM->vmmr0.s.hMemObjLogger, true /*fFreeMappings*/);
3491 pGVM->vmmr0.s.hMemObjLogger = NIL_RTR0MEMOBJ;
3492
3493 /*
3494 * Free log flusher related stuff.
3495 */
3496 RTSpinlockDestroy(pGVM->vmmr0.s.LogFlusher.hSpinlock);
3497 pGVM->vmmr0.s.LogFlusher.hSpinlock = NIL_RTSPINLOCK;
3498 RTSemEventDestroy(pGVM->vmmr0.s.LogFlusher.hEvent);
3499 pGVM->vmmr0.s.LogFlusher.hEvent = NIL_RTSEMEVENT;
3500}
3501
3502
3503/*********************************************************************************************************************************
3504* Assertions *
3505*********************************************************************************************************************************/
3506
3507/**
3508 * Installs a notification callback for ring-0 assertions.
3509 *
3510 * @param pVCpu The cross context virtual CPU structure.
3511 * @param pfnCallback Pointer to the callback.
3512 * @param pvUser The user argument.
3513 *
3514 * @return VBox status code.
3515 */
3516VMMR0_INT_DECL(int) VMMR0AssertionSetNotification(PVMCPUCC pVCpu, PFNVMMR0ASSERTIONNOTIFICATION pfnCallback, RTR0PTR pvUser)
3517{
3518 AssertPtrReturn(pVCpu, VERR_INVALID_POINTER);
3519 AssertPtrReturn(pfnCallback, VERR_INVALID_POINTER);
3520
3521 if (!pVCpu->vmmr0.s.pfnAssertCallback)
3522 {
3523 pVCpu->vmmr0.s.pfnAssertCallback = pfnCallback;
3524 pVCpu->vmmr0.s.pvAssertCallbackUser = pvUser;
3525 return VINF_SUCCESS;
3526 }
3527 return VERR_ALREADY_EXISTS;
3528}
3529
3530
3531/**
3532 * Removes the ring-0 callback.
3533 *
3534 * @param pVCpu The cross context virtual CPU structure.
3535 */
3536VMMR0_INT_DECL(void) VMMR0AssertionRemoveNotification(PVMCPUCC pVCpu)
3537{
3538 pVCpu->vmmr0.s.pfnAssertCallback = NULL;
3539 pVCpu->vmmr0.s.pvAssertCallbackUser = NULL;
3540}
3541
3542
3543/**
3544 * Checks whether there is a ring-0 callback notification active.
3545 *
3546 * @param pVCpu The cross context virtual CPU structure.
3547 * @returns true if there the notification is active, false otherwise.
3548 */
3549VMMR0_INT_DECL(bool) VMMR0AssertionIsNotificationSet(PVMCPUCC pVCpu)
3550{
3551 return pVCpu->vmmr0.s.pfnAssertCallback != NULL;
3552}
3553
3554
3555/*
3556 * Jump back to ring-3 if we're the EMT and the longjmp is armed.
3557 *
3558 * @returns true if the breakpoint should be hit, false if it should be ignored.
3559 */
3560DECLEXPORT(bool) RTCALL RTAssertShouldPanic(void)
3561{
3562#if 0
3563 return true;
3564#else
3565 PVMCC pVM = GVMMR0GetVMByEMT(NIL_RTNATIVETHREAD);
3566 if (pVM)
3567 {
3568 PVMCPUCC pVCpu = VMMGetCpu(pVM);
3569
3570 if (pVCpu)
3571 {
3572# ifdef RT_ARCH_X86
3573 if (pVCpu->vmmr0.s.AssertJmpBuf.eip)
3574# else
3575 if (pVCpu->vmmr0.s.AssertJmpBuf.rip)
3576# endif
3577 {
3578 if (pVCpu->vmmr0.s.pfnAssertCallback)
3579 pVCpu->vmmr0.s.pfnAssertCallback(pVCpu, pVCpu->vmmr0.s.pvAssertCallbackUser);
3580 int rc = vmmR0CallRing3LongJmp(&pVCpu->vmmr0.s.AssertJmpBuf, VERR_VMM_RING0_ASSERTION);
3581 return RT_FAILURE_NP(rc);
3582 }
3583 }
3584 }
3585# ifdef RT_OS_LINUX
3586 return true;
3587# else
3588 return false;
3589# endif
3590#endif
3591}
3592
3593
3594/*
3595 * Override this so we can push it up to ring-3.
3596 */
3597DECLEXPORT(void) RTCALL RTAssertMsg1Weak(const char *pszExpr, unsigned uLine, const char *pszFile, const char *pszFunction)
3598{
3599 /*
3600 * To host kernel log/whatever.
3601 */
3602 SUPR0Printf("!!R0-Assertion Failed!!\n"
3603 "Expression: %s\n"
3604 "Location : %s(%d) %s\n",
3605 pszExpr, pszFile, uLine, pszFunction);
3606
3607 /*
3608 * To the log.
3609 */
3610 LogAlways(("\n!!R0-Assertion Failed!!\n"
3611 "Expression: %s\n"
3612 "Location : %s(%d) %s\n",
3613 pszExpr, pszFile, uLine, pszFunction));
3614
3615 /*
3616 * To the global VMM buffer.
3617 */
3618 PVMCC pVM = GVMMR0GetVMByEMT(NIL_RTNATIVETHREAD);
3619 if (pVM)
3620 RTStrPrintf(pVM->vmm.s.szRing0AssertMsg1, sizeof(pVM->vmm.s.szRing0AssertMsg1),
3621 "\n!!R0-Assertion Failed!!\n"
3622 "Expression: %.*s\n"
3623 "Location : %s(%d) %s\n",
3624 sizeof(pVM->vmm.s.szRing0AssertMsg1) / 4 * 3, pszExpr,
3625 pszFile, uLine, pszFunction);
3626
3627 /*
3628 * Continue the normal way.
3629 */
3630 RTAssertMsg1(pszExpr, uLine, pszFile, pszFunction);
3631}
3632
3633
3634/**
3635 * Callback for RTLogFormatV which writes to the ring-3 log port.
3636 * See PFNLOGOUTPUT() for details.
3637 */
3638static DECLCALLBACK(size_t) rtLogOutput(void *pv, const char *pachChars, size_t cbChars)
3639{
3640 for (size_t i = 0; i < cbChars; i++)
3641 {
3642 LogAlways(("%c", pachChars[i])); NOREF(pachChars);
3643 }
3644
3645 NOREF(pv);
3646 return cbChars;
3647}
3648
3649
3650/*
3651 * Override this so we can push it up to ring-3.
3652 */
3653DECLEXPORT(void) RTCALL RTAssertMsg2WeakV(const char *pszFormat, va_list va)
3654{
3655 va_list vaCopy;
3656
3657 /*
3658 * Push the message to the loggers.
3659 */
3660 PRTLOGGER pLog = RTLogRelGetDefaultInstance();
3661 if (pLog)
3662 {
3663 va_copy(vaCopy, va);
3664 RTLogFormatV(rtLogOutput, pLog, pszFormat, vaCopy);
3665 va_end(vaCopy);
3666 }
3667 pLog = RTLogGetDefaultInstance(); /* Don't initialize it here... */
3668 if (pLog)
3669 {
3670 va_copy(vaCopy, va);
3671 RTLogFormatV(rtLogOutput, pLog, pszFormat, vaCopy);
3672 va_end(vaCopy);
3673 }
3674
3675 /*
3676 * Push it to the global VMM buffer.
3677 */
3678 PVMCC pVM = GVMMR0GetVMByEMT(NIL_RTNATIVETHREAD);
3679 if (pVM)
3680 {
3681 va_copy(vaCopy, va);
3682 RTStrPrintfV(pVM->vmm.s.szRing0AssertMsg2, sizeof(pVM->vmm.s.szRing0AssertMsg2), pszFormat, vaCopy);
3683 va_end(vaCopy);
3684 }
3685
3686 /*
3687 * Continue the normal way.
3688 */
3689 RTAssertMsg2V(pszFormat, va);
3690}
3691
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