VirtualBox

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

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

VMM/PGM,GMM: Baked PGMR3PhysAllocateLargePage into PGMR0PhysAllocateLargePage eliminating VMMCALLRING3_PGM_ALLOCATE_LARGE_HANDY_PAGE; adjusted GMMR0AllocateLargePage to be ring-0 callable. Changed the large page allocation backoff logic a bit. Some more release stats. bugref:10093

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