VirtualBox

source: vbox/trunk/src/VBox/VMM/VMMR3/VMEmt.cpp@ 71040

Last change on this file since 71040 was 71040, checked in by vboxsync, 7 years ago

NEM: More code - DSL is getting somewhere now, but VRAM access sucks. bugref:9044

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 49.7 KB
Line 
1/* $Id: VMEmt.cpp 71040 2018-02-16 16:24:43Z vboxsync $ */
2/** @file
3 * VM - Virtual Machine, The Emulation Thread.
4 */
5
6/*
7 * Copyright (C) 2006-2017 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_VM
23#include <VBox/vmm/tm.h>
24#include <VBox/vmm/dbgf.h>
25#include <VBox/vmm/em.h>
26#include <VBox/vmm/nem.h>
27#include <VBox/vmm/pdmapi.h>
28#ifdef VBOX_WITH_REM
29# include <VBox/vmm/rem.h>
30#endif
31#include <VBox/vmm/tm.h>
32#include "VMInternal.h"
33#include <VBox/vmm/vm.h>
34#include <VBox/vmm/uvm.h>
35
36#include <VBox/err.h>
37#include <VBox/log.h>
38#include <iprt/assert.h>
39#include <iprt/asm.h>
40#include <iprt/asm-math.h>
41#include <iprt/semaphore.h>
42#include <iprt/string.h>
43#include <iprt/thread.h>
44#include <iprt/time.h>
45
46
47/*********************************************************************************************************************************
48* Internal Functions *
49*********************************************************************************************************************************/
50int vmR3EmulationThreadWithId(RTTHREAD hThreadSelf, PUVMCPU pUVCpu, VMCPUID idCpu);
51
52
53/**
54 * The emulation thread main function.
55 *
56 * @returns Thread exit code.
57 * @param hThreadSelf The handle to the executing thread.
58 * @param pvArgs Pointer to the user mode per-VCpu structure (UVMPCU).
59 */
60DECLCALLBACK(int) vmR3EmulationThread(RTTHREAD hThreadSelf, void *pvArgs)
61{
62 PUVMCPU pUVCpu = (PUVMCPU)pvArgs;
63 return vmR3EmulationThreadWithId(hThreadSelf, pUVCpu, pUVCpu->idCpu);
64}
65
66
67/**
68 * The emulation thread main function, with Virtual CPU ID for debugging.
69 *
70 * @returns Thread exit code.
71 * @param hThreadSelf The handle to the executing thread.
72 * @param pUVCpu Pointer to the user mode per-VCpu structure.
73 * @param idCpu The virtual CPU ID, for backtrace purposes.
74 */
75int vmR3EmulationThreadWithId(RTTHREAD hThreadSelf, PUVMCPU pUVCpu, VMCPUID idCpu)
76{
77 PUVM pUVM = pUVCpu->pUVM;
78 int rc;
79 RT_NOREF_PV(hThreadSelf);
80
81 AssertReleaseMsg(VALID_PTR(pUVM) && pUVM->u32Magic == UVM_MAGIC,
82 ("Invalid arguments to the emulation thread!\n"));
83
84 rc = RTTlsSet(pUVM->vm.s.idxTLS, pUVCpu);
85 AssertReleaseMsgRCReturn(rc, ("RTTlsSet %x failed with %Rrc\n", pUVM->vm.s.idxTLS, rc), rc);
86
87 if ( pUVM->pVmm2UserMethods
88 && pUVM->pVmm2UserMethods->pfnNotifyEmtInit)
89 pUVM->pVmm2UserMethods->pfnNotifyEmtInit(pUVM->pVmm2UserMethods, pUVM, pUVCpu);
90
91 /*
92 * The request loop.
93 */
94 rc = VINF_SUCCESS;
95 Log(("vmR3EmulationThread: Emulation thread starting the days work... Thread=%#x pUVM=%p\n", hThreadSelf, pUVM));
96 VMSTATE enmBefore = VMSTATE_CREATED; /* (only used for logging atm.) */
97 ASMAtomicIncU32(&pUVM->vm.s.cActiveEmts);
98 for (;;)
99 {
100 /*
101 * During early init there is no pVM and/or pVCpu, so make a special path
102 * for that to keep things clearly separate.
103 */
104 PVM pVM = pUVM->pVM;
105 PVMCPU pVCpu = pUVCpu->pVCpu;
106 if (!pVCpu || !pVM)
107 {
108 /*
109 * Check for termination first.
110 */
111 if (pUVM->vm.s.fTerminateEMT)
112 {
113 rc = VINF_EM_TERMINATE;
114 break;
115 }
116
117 /*
118 * Only the first VCPU may initialize the VM during early init
119 * and must therefore service all VMCPUID_ANY requests.
120 * See also VMR3Create
121 */
122 if ( (pUVM->vm.s.pNormalReqs || pUVM->vm.s.pPriorityReqs)
123 && pUVCpu->idCpu == 0)
124 {
125 /*
126 * Service execute in any EMT request.
127 */
128 rc = VMR3ReqProcessU(pUVM, VMCPUID_ANY, false /*fPriorityOnly*/);
129 Log(("vmR3EmulationThread: Req rc=%Rrc, VM state %s -> %s\n", rc, VMR3GetStateName(enmBefore), pUVM->pVM ? VMR3GetStateName(pUVM->pVM->enmVMState) : "CREATING"));
130 }
131 else if (pUVCpu->vm.s.pNormalReqs || pUVCpu->vm.s.pPriorityReqs)
132 {
133 /*
134 * Service execute in specific EMT request.
135 */
136 rc = VMR3ReqProcessU(pUVM, pUVCpu->idCpu, false /*fPriorityOnly*/);
137 Log(("vmR3EmulationThread: Req (cpu=%u) rc=%Rrc, VM state %s -> %s\n", pUVCpu->idCpu, rc, VMR3GetStateName(enmBefore), pUVM->pVM ? VMR3GetStateName(pUVM->pVM->enmVMState) : "CREATING"));
138 }
139 else
140 {
141 /*
142 * Nothing important is pending, so wait for something.
143 */
144 rc = VMR3WaitU(pUVCpu);
145 if (RT_FAILURE(rc))
146 {
147 AssertLogRelMsgFailed(("VMR3WaitU failed with %Rrc\n", rc));
148 break;
149 }
150 }
151 }
152 else
153 {
154 /*
155 * Pending requests which needs servicing?
156 *
157 * We check for state changes in addition to status codes when
158 * servicing requests. (Look after the ifs.)
159 */
160 enmBefore = pVM->enmVMState;
161 if (pUVM->vm.s.fTerminateEMT)
162 {
163 rc = VINF_EM_TERMINATE;
164 break;
165 }
166
167 if (VM_FF_IS_PENDING(pVM, VM_FF_EMT_RENDEZVOUS))
168 {
169 rc = VMMR3EmtRendezvousFF(pVM, &pVM->aCpus[idCpu]);
170 Log(("vmR3EmulationThread: Rendezvous rc=%Rrc, VM state %s -> %s\n", rc, VMR3GetStateName(enmBefore), VMR3GetStateName(pVM->enmVMState)));
171 }
172 else if (pUVM->vm.s.pNormalReqs || pUVM->vm.s.pPriorityReqs)
173 {
174 /*
175 * Service execute in any EMT request.
176 */
177 rc = VMR3ReqProcessU(pUVM, VMCPUID_ANY, false /*fPriorityOnly*/);
178 Log(("vmR3EmulationThread: Req rc=%Rrc, VM state %s -> %s\n", rc, VMR3GetStateName(enmBefore), VMR3GetStateName(pVM->enmVMState)));
179 }
180 else if (pUVCpu->vm.s.pNormalReqs || pUVCpu->vm.s.pPriorityReqs)
181 {
182 /*
183 * Service execute in specific EMT request.
184 */
185 rc = VMR3ReqProcessU(pUVM, pUVCpu->idCpu, false /*fPriorityOnly*/);
186 Log(("vmR3EmulationThread: Req (cpu=%u) rc=%Rrc, VM state %s -> %s\n", pUVCpu->idCpu, rc, VMR3GetStateName(enmBefore), VMR3GetStateName(pVM->enmVMState)));
187 }
188 else if ( VM_FF_IS_SET(pVM, VM_FF_DBGF)
189 || VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_DBGF))
190 {
191 /*
192 * Service the debugger request.
193 */
194 rc = DBGFR3VMMForcedAction(pVM, pVCpu);
195 Log(("vmR3EmulationThread: Dbg rc=%Rrc, VM state %s -> %s\n", rc, VMR3GetStateName(enmBefore), VMR3GetStateName(pVM->enmVMState)));
196 }
197 else if (VM_FF_TEST_AND_CLEAR(pVM, VM_FF_RESET))
198 {
199 /*
200 * Service a delayed reset request.
201 */
202 rc = VBOXSTRICTRC_VAL(VMR3ResetFF(pVM));
203 VM_FF_CLEAR(pVM, VM_FF_RESET);
204 Log(("vmR3EmulationThread: Reset rc=%Rrc, VM state %s -> %s\n", rc, VMR3GetStateName(enmBefore), VMR3GetStateName(pVM->enmVMState)));
205 }
206 else
207 {
208 /*
209 * Nothing important is pending, so wait for something.
210 */
211 rc = VMR3WaitU(pUVCpu);
212 if (RT_FAILURE(rc))
213 {
214 AssertLogRelMsgFailed(("VMR3WaitU failed with %Rrc\n", rc));
215 break;
216 }
217 }
218
219 /*
220 * Check for termination requests, these have extremely high priority.
221 */
222 if ( rc == VINF_EM_TERMINATE
223 || pUVM->vm.s.fTerminateEMT)
224 break;
225 }
226
227 /*
228 * Some requests (both VMR3Req* and the DBGF) can potentially resume
229 * or start the VM, in that case we'll get a change in VM status
230 * indicating that we're now running.
231 */
232 if (RT_SUCCESS(rc))
233 {
234 pVM = pUVM->pVM;
235 if (pVM)
236 {
237 pVCpu = &pVM->aCpus[idCpu];
238 if ( pVM->enmVMState == VMSTATE_RUNNING
239 && VMCPUSTATE_IS_STARTED(VMCPU_GET_STATE(pVCpu)))
240 {
241 rc = EMR3ExecuteVM(pVM, pVCpu);
242 Log(("vmR3EmulationThread: EMR3ExecuteVM() -> rc=%Rrc, enmVMState=%d\n", rc, pVM->enmVMState));
243 }
244 }
245 }
246
247 } /* forever */
248
249
250 /*
251 * Decrement the active EMT count if we haven't done it yet in vmR3Destroy.
252 */
253 if (!pUVCpu->vm.s.fBeenThruVmDestroy)
254 ASMAtomicDecU32(&pUVM->vm.s.cActiveEmts);
255
256
257 /*
258 * Cleanup and exit.
259 * EMT0 does the VM destruction after all other EMTs have deregistered and terminated.
260 */
261 Log(("vmR3EmulationThread: Terminating emulation thread! Thread=%#x pUVM=%p rc=%Rrc enmBefore=%d enmVMState=%d\n",
262 hThreadSelf, pUVM, rc, enmBefore, pUVM->pVM ? pUVM->pVM->enmVMState : VMSTATE_TERMINATED));
263 PVM pVM;
264 if ( idCpu == 0
265 && (pVM = pUVM->pVM) != NULL)
266 {
267 /* Wait for any other EMTs to terminate before we destroy the VM (see vmR3DestroyVM). */
268 for (VMCPUID iCpu = 1; iCpu < pUVM->cCpus; iCpu++)
269 {
270 RTTHREAD hThread;
271 ASMAtomicXchgHandle(&pUVM->aCpus[iCpu].vm.s.ThreadEMT, NIL_RTTHREAD, &hThread);
272 if (hThread != NIL_RTTHREAD)
273 {
274 int rc2 = RTThreadWait(hThread, 5 * RT_MS_1SEC, NULL);
275 AssertLogRelMsgRC(rc2, ("iCpu=%u rc=%Rrc\n", iCpu, rc2));
276 if (RT_FAILURE(rc2))
277 pUVM->aCpus[iCpu].vm.s.ThreadEMT = hThread;
278 }
279 }
280
281 /* Switch to the terminated state, clearing the VM pointer and finally destroy the VM. */
282 vmR3SetTerminated(pVM);
283
284 pUVM->pVM = NULL;
285
286 int rc2 = SUPR3CallVMMR0Ex(pVM->pVMR0, 0 /*idCpu*/, VMMR0_DO_GVMM_DESTROY_VM, 0, NULL);
287 AssertLogRelRC(rc2);
288 }
289 /* Deregister the EMT with VMMR0. */
290 else if ( idCpu != 0
291 && (pVM = pUVM->pVM) != NULL)
292 {
293 int rc2 = SUPR3CallVMMR0Ex(pVM->pVMR0, idCpu, VMMR0_DO_GVMM_DEREGISTER_VMCPU, 0, NULL);
294 AssertLogRelRC(rc2);
295 }
296
297 if ( pUVM->pVmm2UserMethods
298 && pUVM->pVmm2UserMethods->pfnNotifyEmtTerm)
299 pUVM->pVmm2UserMethods->pfnNotifyEmtTerm(pUVM->pVmm2UserMethods, pUVM, pUVCpu);
300
301 pUVCpu->vm.s.NativeThreadEMT = NIL_RTNATIVETHREAD;
302 Log(("vmR3EmulationThread: EMT is terminated.\n"));
303 return rc;
304}
305
306
307/**
308 * Gets the name of a halt method.
309 *
310 * @returns Pointer to a read only string.
311 * @param enmMethod The method.
312 */
313static const char *vmR3GetHaltMethodName(VMHALTMETHOD enmMethod)
314{
315 switch (enmMethod)
316 {
317 case VMHALTMETHOD_BOOTSTRAP: return "bootstrap";
318 case VMHALTMETHOD_DEFAULT: return "default";
319 case VMHALTMETHOD_OLD: return "old";
320 case VMHALTMETHOD_1: return "method1";
321 //case VMHALTMETHOD_2: return "method2";
322 case VMHALTMETHOD_GLOBAL_1: return "global1";
323 default: return "unknown";
324 }
325}
326
327
328/**
329 * Signal a fatal wait error.
330 *
331 * @returns Fatal error code to be propagated up the call stack.
332 * @param pUVCpu The user mode per CPU structure of the calling
333 * EMT.
334 * @param pszFmt The error format with a single %Rrc in it.
335 * @param rcFmt The status code to format.
336 */
337static int vmR3FatalWaitError(PUVMCPU pUVCpu, const char *pszFmt, int rcFmt)
338{
339 /** @todo This is wrong ... raise a fatal error / guru meditation
340 * instead. */
341 AssertLogRelMsgFailed((pszFmt, rcFmt));
342 ASMAtomicUoWriteBool(&pUVCpu->pUVM->vm.s.fTerminateEMT, true);
343 if (pUVCpu->pVM)
344 VM_FF_SET(pUVCpu->pVM, VM_FF_CHECK_VM_STATE);
345 return VERR_VM_FATAL_WAIT_ERROR;
346}
347
348
349/**
350 * The old halt loop.
351 */
352static DECLCALLBACK(int) vmR3HaltOldDoHalt(PUVMCPU pUVCpu, const uint32_t fMask, uint64_t /* u64Now*/)
353{
354 /*
355 * Halt loop.
356 */
357 PVM pVM = pUVCpu->pVM;
358 PVMCPU pVCpu = pUVCpu->pVCpu;
359
360 int rc = VINF_SUCCESS;
361 ASMAtomicWriteBool(&pUVCpu->vm.s.fWait, true);
362 //unsigned cLoops = 0;
363 for (;;)
364 {
365 /*
366 * Work the timers and check if we can exit.
367 * The poll call gives us the ticks left to the next event in
368 * addition to perhaps set an FF.
369 */
370 uint64_t const u64StartTimers = RTTimeNanoTS();
371 TMR3TimerQueuesDo(pVM);
372 uint64_t const cNsElapsedTimers = RTTimeNanoTS() - u64StartTimers;
373 STAM_REL_PROFILE_ADD_PERIOD(&pUVCpu->vm.s.StatHaltTimers, cNsElapsedTimers);
374 if ( VM_FF_IS_PENDING(pVM, VM_FF_EXTERNAL_HALTED_MASK)
375 || VMCPU_FF_IS_PENDING(pVCpu, fMask))
376 break;
377 uint64_t u64NanoTS;
378 TMTimerPollGIP(pVM, pVCpu, &u64NanoTS);
379 if ( VM_FF_IS_PENDING(pVM, VM_FF_EXTERNAL_HALTED_MASK)
380 || VMCPU_FF_IS_PENDING(pVCpu, fMask))
381 break;
382
383 /*
384 * Wait for a while. Someone will wake us up or interrupt the call if
385 * anything needs our attention.
386 */
387 if (u64NanoTS < 50000)
388 {
389 //RTLogPrintf("u64NanoTS=%RI64 cLoops=%d spin\n", u64NanoTS, cLoops++);
390 /* spin */;
391 }
392 else
393 {
394 VMMR3YieldStop(pVM);
395 //uint64_t u64Start = RTTimeNanoTS();
396 if (u64NanoTS < 870000) /* this is a bit speculative... works fine on linux. */
397 {
398 //RTLogPrintf("u64NanoTS=%RI64 cLoops=%d yield", u64NanoTS, cLoops++);
399 uint64_t const u64StartSchedYield = RTTimeNanoTS();
400 RTThreadYield(); /* this is the best we can do here */
401 uint64_t const cNsElapsedSchedYield = RTTimeNanoTS() - u64StartSchedYield;
402 STAM_REL_PROFILE_ADD_PERIOD(&pUVCpu->vm.s.StatHaltYield, cNsElapsedSchedYield);
403 }
404 else if (u64NanoTS < 2000000)
405 {
406 //RTLogPrintf("u64NanoTS=%RI64 cLoops=%d sleep 1ms", u64NanoTS, cLoops++);
407 uint64_t const u64StartSchedHalt = RTTimeNanoTS();
408 rc = RTSemEventWait(pUVCpu->vm.s.EventSemWait, 1);
409 uint64_t const cNsElapsedSchedHalt = RTTimeNanoTS() - u64StartSchedHalt;
410 STAM_REL_PROFILE_ADD_PERIOD(&pUVCpu->vm.s.StatHaltBlock, cNsElapsedSchedHalt);
411 }
412 else
413 {
414 //RTLogPrintf("u64NanoTS=%RI64 cLoops=%d sleep %dms", u64NanoTS, cLoops++, (uint32_t)RT_MIN((u64NanoTS - 500000) / 1000000, 15));
415 uint64_t const u64StartSchedHalt = RTTimeNanoTS();
416 rc = RTSemEventWait(pUVCpu->vm.s.EventSemWait, RT_MIN((u64NanoTS - 1000000) / 1000000, 15));
417 uint64_t const cNsElapsedSchedHalt = RTTimeNanoTS() - u64StartSchedHalt;
418 STAM_REL_PROFILE_ADD_PERIOD(&pUVCpu->vm.s.StatHaltBlock, cNsElapsedSchedHalt);
419 }
420 //uint64_t u64Slept = RTTimeNanoTS() - u64Start;
421 //RTLogPrintf(" -> rc=%Rrc in %RU64 ns / %RI64 ns delta\n", rc, u64Slept, u64NanoTS - u64Slept);
422 }
423 if (rc == VERR_TIMEOUT)
424 rc = VINF_SUCCESS;
425 else if (RT_FAILURE(rc))
426 {
427 rc = vmR3FatalWaitError(pUVCpu, "RTSemEventWait->%Rrc\n", rc);
428 break;
429 }
430 }
431
432 ASMAtomicUoWriteBool(&pUVCpu->vm.s.fWait, false);
433 return rc;
434}
435
436
437/**
438 * Initialize the configuration of halt method 1 & 2.
439 *
440 * @return VBox status code. Failure on invalid CFGM data.
441 * @param pUVM The user mode VM structure.
442 */
443static int vmR3HaltMethod12ReadConfigU(PUVM pUVM)
444{
445 /*
446 * The defaults.
447 */
448#if 1 /* DEBUGGING STUFF - REMOVE LATER */
449 pUVM->vm.s.Halt.Method12.u32LagBlockIntervalDivisorCfg = 4;
450 pUVM->vm.s.Halt.Method12.u32MinBlockIntervalCfg = 2*1000000;
451 pUVM->vm.s.Halt.Method12.u32MaxBlockIntervalCfg = 75*1000000;
452 pUVM->vm.s.Halt.Method12.u32StartSpinningCfg = 30*1000000;
453 pUVM->vm.s.Halt.Method12.u32StopSpinningCfg = 20*1000000;
454#else
455 pUVM->vm.s.Halt.Method12.u32LagBlockIntervalDivisorCfg = 4;
456 pUVM->vm.s.Halt.Method12.u32MinBlockIntervalCfg = 5*1000000;
457 pUVM->vm.s.Halt.Method12.u32MaxBlockIntervalCfg = 200*1000000;
458 pUVM->vm.s.Halt.Method12.u32StartSpinningCfg = 20*1000000;
459 pUVM->vm.s.Halt.Method12.u32StopSpinningCfg = 2*1000000;
460#endif
461
462 /*
463 * Query overrides.
464 *
465 * I don't have time to bother with niceties such as invalid value checks
466 * here right now. sorry.
467 */
468 PCFGMNODE pCfg = CFGMR3GetChild(CFGMR3GetRoot(pUVM->pVM), "/VMM/HaltedMethod1");
469 if (pCfg)
470 {
471 uint32_t u32;
472 if (RT_SUCCESS(CFGMR3QueryU32(pCfg, "LagBlockIntervalDivisor", &u32)))
473 pUVM->vm.s.Halt.Method12.u32LagBlockIntervalDivisorCfg = u32;
474 if (RT_SUCCESS(CFGMR3QueryU32(pCfg, "MinBlockInterval", &u32)))
475 pUVM->vm.s.Halt.Method12.u32MinBlockIntervalCfg = u32;
476 if (RT_SUCCESS(CFGMR3QueryU32(pCfg, "MaxBlockInterval", &u32)))
477 pUVM->vm.s.Halt.Method12.u32MaxBlockIntervalCfg = u32;
478 if (RT_SUCCESS(CFGMR3QueryU32(pCfg, "StartSpinning", &u32)))
479 pUVM->vm.s.Halt.Method12.u32StartSpinningCfg = u32;
480 if (RT_SUCCESS(CFGMR3QueryU32(pCfg, "StopSpinning", &u32)))
481 pUVM->vm.s.Halt.Method12.u32StopSpinningCfg = u32;
482 LogRel(("VMEmt: HaltedMethod1 config: %d/%d/%d/%d/%d\n",
483 pUVM->vm.s.Halt.Method12.u32LagBlockIntervalDivisorCfg,
484 pUVM->vm.s.Halt.Method12.u32MinBlockIntervalCfg,
485 pUVM->vm.s.Halt.Method12.u32MaxBlockIntervalCfg,
486 pUVM->vm.s.Halt.Method12.u32StartSpinningCfg,
487 pUVM->vm.s.Halt.Method12.u32StopSpinningCfg));
488 }
489
490 return VINF_SUCCESS;
491}
492
493
494/**
495 * Initialize halt method 1.
496 *
497 * @return VBox status code.
498 * @param pUVM Pointer to the user mode VM structure.
499 */
500static DECLCALLBACK(int) vmR3HaltMethod1Init(PUVM pUVM)
501{
502 return vmR3HaltMethod12ReadConfigU(pUVM);
503}
504
505
506/**
507 * Method 1 - Block whenever possible, and when lagging behind
508 * switch to spinning for 10-30ms with occasional blocking until
509 * the lag has been eliminated.
510 */
511static DECLCALLBACK(int) vmR3HaltMethod1Halt(PUVMCPU pUVCpu, const uint32_t fMask, uint64_t u64Now)
512{
513 PUVM pUVM = pUVCpu->pUVM;
514 PVMCPU pVCpu = pUVCpu->pVCpu;
515 PVM pVM = pUVCpu->pVM;
516
517 /*
518 * To simplify things, we decide up-front whether we should switch to spinning or
519 * not. This makes some ASSUMPTIONS about the cause of the spinning (PIT/RTC/PCNet)
520 * and that it will generate interrupts or other events that will cause us to exit
521 * the halt loop.
522 */
523 bool fBlockOnce = false;
524 bool fSpinning = false;
525 uint32_t u32CatchUpPct = TMVirtualSyncGetCatchUpPct(pVM);
526 if (u32CatchUpPct /* non-zero if catching up */)
527 {
528 if (pUVCpu->vm.s.Halt.Method12.u64StartSpinTS)
529 {
530 fSpinning = TMVirtualSyncGetLag(pVM) >= pUVM->vm.s.Halt.Method12.u32StopSpinningCfg;
531 if (fSpinning)
532 {
533 uint64_t u64Lag = TMVirtualSyncGetLag(pVM);
534 fBlockOnce = u64Now - pUVCpu->vm.s.Halt.Method12.u64LastBlockTS
535 > RT_MAX(pUVM->vm.s.Halt.Method12.u32MinBlockIntervalCfg,
536 RT_MIN(u64Lag / pUVM->vm.s.Halt.Method12.u32LagBlockIntervalDivisorCfg,
537 pUVM->vm.s.Halt.Method12.u32MaxBlockIntervalCfg));
538 }
539 else
540 {
541 //RTLogRelPrintf("Stopped spinning (%u ms)\n", (u64Now - pUVCpu->vm.s.Halt.Method12.u64StartSpinTS) / 1000000);
542 pUVCpu->vm.s.Halt.Method12.u64StartSpinTS = 0;
543 }
544 }
545 else
546 {
547 fSpinning = TMVirtualSyncGetLag(pVM) >= pUVM->vm.s.Halt.Method12.u32StartSpinningCfg;
548 if (fSpinning)
549 pUVCpu->vm.s.Halt.Method12.u64StartSpinTS = u64Now;
550 }
551 }
552 else if (pUVCpu->vm.s.Halt.Method12.u64StartSpinTS)
553 {
554 //RTLogRelPrintf("Stopped spinning (%u ms)\n", (u64Now - pUVCpu->vm.s.Halt.Method12.u64StartSpinTS) / 1000000);
555 pUVCpu->vm.s.Halt.Method12.u64StartSpinTS = 0;
556 }
557
558 /*
559 * Halt loop.
560 */
561 int rc = VINF_SUCCESS;
562 ASMAtomicWriteBool(&pUVCpu->vm.s.fWait, true);
563 unsigned cLoops = 0;
564 for (;; cLoops++)
565 {
566 /*
567 * Work the timers and check if we can exit.
568 */
569 uint64_t const u64StartTimers = RTTimeNanoTS();
570 TMR3TimerQueuesDo(pVM);
571 uint64_t const cNsElapsedTimers = RTTimeNanoTS() - u64StartTimers;
572 STAM_REL_PROFILE_ADD_PERIOD(&pUVCpu->vm.s.StatHaltTimers, cNsElapsedTimers);
573 if ( VM_FF_IS_PENDING(pVM, VM_FF_EXTERNAL_HALTED_MASK)
574 || VMCPU_FF_IS_PENDING(pVCpu, fMask))
575 break;
576
577 /*
578 * Estimate time left to the next event.
579 */
580 uint64_t u64NanoTS;
581 TMTimerPollGIP(pVM, pVCpu, &u64NanoTS);
582 if ( VM_FF_IS_PENDING(pVM, VM_FF_EXTERNAL_HALTED_MASK)
583 || VMCPU_FF_IS_PENDING(pVCpu, fMask))
584 break;
585
586 /*
587 * Block if we're not spinning and the interval isn't all that small.
588 */
589 if ( ( !fSpinning
590 || fBlockOnce)
591#if 1 /* DEBUGGING STUFF - REMOVE LATER */
592 && u64NanoTS >= 100000) /* 0.100 ms */
593#else
594 && u64NanoTS >= 250000) /* 0.250 ms */
595#endif
596 {
597 const uint64_t Start = pUVCpu->vm.s.Halt.Method12.u64LastBlockTS = RTTimeNanoTS();
598 VMMR3YieldStop(pVM);
599
600 uint32_t cMilliSecs = RT_MIN(u64NanoTS / 1000000, 15);
601 if (cMilliSecs <= pUVCpu->vm.s.Halt.Method12.cNSBlockedTooLongAvg)
602 cMilliSecs = 1;
603 else
604 cMilliSecs -= pUVCpu->vm.s.Halt.Method12.cNSBlockedTooLongAvg;
605
606 //RTLogRelPrintf("u64NanoTS=%RI64 cLoops=%3d sleep %02dms (%7RU64) ", u64NanoTS, cLoops, cMilliSecs, u64NanoTS);
607 uint64_t const u64StartSchedHalt = RTTimeNanoTS();
608 rc = RTSemEventWait(pUVCpu->vm.s.EventSemWait, cMilliSecs);
609 uint64_t const cNsElapsedSchedHalt = RTTimeNanoTS() - u64StartSchedHalt;
610 STAM_REL_PROFILE_ADD_PERIOD(&pUVCpu->vm.s.StatHaltBlock, cNsElapsedSchedHalt);
611
612 if (rc == VERR_TIMEOUT)
613 rc = VINF_SUCCESS;
614 else if (RT_FAILURE(rc))
615 {
616 rc = vmR3FatalWaitError(pUVCpu, "RTSemEventWait->%Rrc\n", rc);
617 break;
618 }
619
620 /*
621 * Calc the statistics.
622 * Update averages every 16th time, and flush parts of the history every 64th time.
623 */
624 const uint64_t Elapsed = RTTimeNanoTS() - Start;
625 pUVCpu->vm.s.Halt.Method12.cNSBlocked += Elapsed;
626 if (Elapsed > u64NanoTS)
627 pUVCpu->vm.s.Halt.Method12.cNSBlockedTooLong += Elapsed - u64NanoTS;
628 pUVCpu->vm.s.Halt.Method12.cBlocks++;
629 if (!(pUVCpu->vm.s.Halt.Method12.cBlocks & 0xf))
630 {
631 pUVCpu->vm.s.Halt.Method12.cNSBlockedTooLongAvg = pUVCpu->vm.s.Halt.Method12.cNSBlockedTooLong / pUVCpu->vm.s.Halt.Method12.cBlocks;
632 if (!(pUVCpu->vm.s.Halt.Method12.cBlocks & 0x3f))
633 {
634 pUVCpu->vm.s.Halt.Method12.cNSBlockedTooLong = pUVCpu->vm.s.Halt.Method12.cNSBlockedTooLongAvg * 0x40;
635 pUVCpu->vm.s.Halt.Method12.cBlocks = 0x40;
636 }
637 }
638 //RTLogRelPrintf(" -> %7RU64 ns / %7RI64 ns delta%s\n", Elapsed, Elapsed - u64NanoTS, fBlockOnce ? " (block once)" : "");
639
640 /*
641 * Clear the block once flag if we actually blocked.
642 */
643 if ( fBlockOnce
644 && Elapsed > 100000 /* 0.1 ms */)
645 fBlockOnce = false;
646 }
647 }
648 //if (fSpinning) RTLogRelPrintf("spun for %RU64 ns %u loops; lag=%RU64 pct=%d\n", RTTimeNanoTS() - u64Now, cLoops, TMVirtualSyncGetLag(pVM), u32CatchUpPct);
649
650 ASMAtomicUoWriteBool(&pUVCpu->vm.s.fWait, false);
651 return rc;
652}
653
654
655/**
656 * Initialize the global 1 halt method.
657 *
658 * @return VBox status code.
659 * @param pUVM Pointer to the user mode VM structure.
660 */
661static DECLCALLBACK(int) vmR3HaltGlobal1Init(PUVM pUVM)
662{
663 /*
664 * The defaults.
665 */
666 uint32_t cNsResolution = SUPSemEventMultiGetResolution(pUVM->vm.s.pSession);
667 if (cNsResolution > 5*RT_NS_100US)
668 pUVM->vm.s.Halt.Global1.cNsSpinBlockThresholdCfg = 50000;
669 else if (cNsResolution > RT_NS_100US)
670 pUVM->vm.s.Halt.Global1.cNsSpinBlockThresholdCfg = cNsResolution / 4;
671 else
672 pUVM->vm.s.Halt.Global1.cNsSpinBlockThresholdCfg = 2000;
673
674 /*
675 * Query overrides.
676 *
677 * I don't have time to bother with niceties such as invalid value checks
678 * here right now. sorry.
679 */
680 PCFGMNODE pCfg = CFGMR3GetChild(CFGMR3GetRoot(pUVM->pVM), "/VMM/HaltedGlobal1");
681 if (pCfg)
682 {
683 uint32_t u32;
684 if (RT_SUCCESS(CFGMR3QueryU32(pCfg, "SpinBlockThreshold", &u32)))
685 pUVM->vm.s.Halt.Global1.cNsSpinBlockThresholdCfg = u32;
686 }
687 LogRel(("VMEmt: HaltedGlobal1 config: cNsSpinBlockThresholdCfg=%u\n",
688 pUVM->vm.s.Halt.Global1.cNsSpinBlockThresholdCfg));
689 return VINF_SUCCESS;
690}
691
692
693/**
694 * The global 1 halt method - Block in GMM (ring-0) and let it
695 * try take care of the global scheduling of EMT threads.
696 */
697static DECLCALLBACK(int) vmR3HaltGlobal1Halt(PUVMCPU pUVCpu, const uint32_t fMask, uint64_t u64Now)
698{
699 PUVM pUVM = pUVCpu->pUVM;
700 PVMCPU pVCpu = pUVCpu->pVCpu;
701 PVM pVM = pUVCpu->pVM;
702 Assert(VMMGetCpu(pVM) == pVCpu);
703 NOREF(u64Now);
704
705 /*
706 * Halt loop.
707 */
708 //uint64_t u64NowLog, u64Start;
709 //u64Start = u64NowLog = RTTimeNanoTS();
710 int rc = VINF_SUCCESS;
711 ASMAtomicWriteBool(&pUVCpu->vm.s.fWait, true);
712 unsigned cLoops = 0;
713 for (;; cLoops++)
714 {
715 /*
716 * Work the timers and check if we can exit.
717 */
718 uint64_t const u64StartTimers = RTTimeNanoTS();
719 TMR3TimerQueuesDo(pVM);
720 uint64_t const cNsElapsedTimers = RTTimeNanoTS() - u64StartTimers;
721 STAM_REL_PROFILE_ADD_PERIOD(&pUVCpu->vm.s.StatHaltTimers, cNsElapsedTimers);
722 if ( VM_FF_IS_PENDING(pVM, VM_FF_EXTERNAL_HALTED_MASK)
723 || VMCPU_FF_IS_PENDING(pVCpu, fMask))
724 break;
725
726 /*
727 * Estimate time left to the next event.
728 */
729 //u64NowLog = RTTimeNanoTS();
730 uint64_t u64Delta;
731 uint64_t u64GipTime = TMTimerPollGIP(pVM, pVCpu, &u64Delta);
732 if ( VM_FF_IS_PENDING(pVM, VM_FF_EXTERNAL_HALTED_MASK)
733 || VMCPU_FF_IS_PENDING(pVCpu, fMask))
734 break;
735
736 /*
737 * Block if we're not spinning and the interval isn't all that small.
738 */
739 if (u64Delta >= pUVM->vm.s.Halt.Global1.cNsSpinBlockThresholdCfg)
740 {
741 VMMR3YieldStop(pVM);
742 if ( VM_FF_IS_PENDING(pVM, VM_FF_EXTERNAL_HALTED_MASK)
743 || VMCPU_FF_IS_PENDING(pVCpu, fMask))
744 break;
745
746 //RTLogPrintf("loop=%-3d u64GipTime=%'llu / %'llu now=%'llu / %'llu\n", cLoops, u64GipTime, u64Delta, u64NowLog, u64GipTime - u64NowLog);
747 uint64_t const u64StartSchedHalt = RTTimeNanoTS();
748 rc = SUPR3CallVMMR0Ex(pVM->pVMR0, pVCpu->idCpu, VMMR0_DO_GVMM_SCHED_HALT, u64GipTime, NULL);
749 uint64_t const u64EndSchedHalt = RTTimeNanoTS();
750 uint64_t const cNsElapsedSchedHalt = u64EndSchedHalt - u64StartSchedHalt;
751 STAM_REL_PROFILE_ADD_PERIOD(&pUVCpu->vm.s.StatHaltBlock, cNsElapsedSchedHalt);
752
753 if (rc == VERR_INTERRUPTED)
754 rc = VINF_SUCCESS;
755 else if (RT_FAILURE(rc))
756 {
757 rc = vmR3FatalWaitError(pUVCpu, "vmR3HaltGlobal1Halt: VMMR0_DO_GVMM_SCHED_HALT->%Rrc\n", rc);
758 break;
759 }
760 else
761 {
762 int64_t const cNsOverslept = u64EndSchedHalt - u64GipTime;
763 if (cNsOverslept > 50000)
764 STAM_PROFILE_ADD_PERIOD(&pUVCpu->vm.s.StatHaltBlockOverslept, cNsOverslept);
765 else if (cNsOverslept < -50000)
766 STAM_PROFILE_ADD_PERIOD(&pUVCpu->vm.s.StatHaltBlockInsomnia, cNsElapsedSchedHalt);
767 else
768 STAM_PROFILE_ADD_PERIOD(&pUVCpu->vm.s.StatHaltBlockOnTime, cNsElapsedSchedHalt);
769 }
770 }
771 /*
772 * When spinning call upon the GVMM and do some wakups once
773 * in a while, it's not like we're actually busy or anything.
774 */
775 else if (!(cLoops & 0x1fff))
776 {
777 uint64_t const u64StartSchedYield = RTTimeNanoTS();
778 rc = SUPR3CallVMMR0Ex(pVM->pVMR0, pVCpu->idCpu, VMMR0_DO_GVMM_SCHED_POLL, false /* don't yield */, NULL);
779 uint64_t const cNsElapsedSchedYield = RTTimeNanoTS() - u64StartSchedYield;
780 STAM_REL_PROFILE_ADD_PERIOD(&pUVCpu->vm.s.StatHaltYield, cNsElapsedSchedYield);
781 }
782 }
783 //RTLogPrintf("*** %u loops %'llu; lag=%RU64\n", cLoops, u64NowLog - u64Start, TMVirtualSyncGetLag(pVM));
784
785 ASMAtomicUoWriteBool(&pUVCpu->vm.s.fWait, false);
786 return rc;
787}
788
789
790/**
791 * The global 1 halt method - VMR3Wait() worker.
792 *
793 * @returns VBox status code.
794 * @param pUVCpu Pointer to the user mode VMCPU structure.
795 */
796static DECLCALLBACK(int) vmR3HaltGlobal1Wait(PUVMCPU pUVCpu)
797{
798 ASMAtomicWriteBool(&pUVCpu->vm.s.fWait, true);
799
800 PVM pVM = pUVCpu->pUVM->pVM;
801 PVMCPU pVCpu = VMMGetCpu(pVM);
802 Assert(pVCpu->idCpu == pUVCpu->idCpu);
803
804 int rc = VINF_SUCCESS;
805 for (;;)
806 {
807 /*
808 * Check Relevant FFs.
809 */
810 if ( VM_FF_IS_PENDING(pVM, VM_FF_EXTERNAL_SUSPENDED_MASK)
811 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_EXTERNAL_SUSPENDED_MASK))
812 break;
813
814 /*
815 * Wait for a while. Someone will wake us up or interrupt the call if
816 * anything needs our attention.
817 */
818 rc = SUPR3CallVMMR0Ex(pVM->pVMR0, pVCpu->idCpu, VMMR0_DO_GVMM_SCHED_HALT, RTTimeNanoTS() + 1000000000 /* +1s */, NULL);
819 if (rc == VERR_INTERRUPTED)
820 rc = VINF_SUCCESS;
821 else if (RT_FAILURE(rc))
822 {
823 rc = vmR3FatalWaitError(pUVCpu, "vmR3HaltGlobal1Wait: VMMR0_DO_GVMM_SCHED_HALT->%Rrc\n", rc);
824 break;
825 }
826 }
827
828 ASMAtomicUoWriteBool(&pUVCpu->vm.s.fWait, false);
829 return rc;
830}
831
832
833/**
834 * The global 1 halt method - VMR3NotifyFF() worker.
835 *
836 * @param pUVCpu Pointer to the user mode VMCPU structure.
837 * @param fFlags Notification flags, VMNOTIFYFF_FLAGS_*.
838 */
839static DECLCALLBACK(void) vmR3HaltGlobal1NotifyCpuFF(PUVMCPU pUVCpu, uint32_t fFlags)
840{
841 if (pUVCpu->vm.s.fWait)
842 {
843 int rc = SUPR3CallVMMR0Ex(pUVCpu->pVM->pVMR0, pUVCpu->idCpu, VMMR0_DO_GVMM_SCHED_WAKE_UP, 0, NULL);
844 AssertRC(rc);
845 }
846 else if ( (fFlags & VMNOTIFYFF_FLAGS_POKE)
847 || !(fFlags & VMNOTIFYFF_FLAGS_DONE_REM))
848 {
849 PVMCPU pVCpu = pUVCpu->pVCpu;
850 if (pVCpu)
851 {
852 VMCPUSTATE enmState = VMCPU_GET_STATE(pVCpu);
853 if (enmState == VMCPUSTATE_STARTED_EXEC)
854 {
855 if (fFlags & VMNOTIFYFF_FLAGS_POKE)
856 {
857 int rc = SUPR3CallVMMR0Ex(pUVCpu->pVM->pVMR0, pUVCpu->idCpu, VMMR0_DO_GVMM_SCHED_POKE, 0, NULL);
858 AssertRC(rc);
859 }
860 }
861 else if (enmState == VMCPUSTATE_STARTED_EXEC_NEM)
862 NEMR3NotifyFF(pUVCpu->pVM, pVCpu, fFlags);
863#ifdef VBOX_WITH_REM
864 else if (enmState == VMCPUSTATE_STARTED_EXEC_REM)
865 {
866 if (!(fFlags & VMNOTIFYFF_FLAGS_DONE_REM))
867 REMR3NotifyFF(pUVCpu->pVM);
868 }
869#endif
870 }
871 }
872}
873
874
875/**
876 * Bootstrap VMR3Wait() worker.
877 *
878 * @returns VBox status code.
879 * @param pUVCpu Pointer to the user mode VMCPU structure.
880 */
881static DECLCALLBACK(int) vmR3BootstrapWait(PUVMCPU pUVCpu)
882{
883 PUVM pUVM = pUVCpu->pUVM;
884
885 ASMAtomicWriteBool(&pUVCpu->vm.s.fWait, true);
886
887 int rc = VINF_SUCCESS;
888 for (;;)
889 {
890 /*
891 * Check Relevant FFs.
892 */
893 if (pUVM->vm.s.pNormalReqs || pUVM->vm.s.pPriorityReqs) /* global requests pending? */
894 break;
895 if (pUVCpu->vm.s.pNormalReqs || pUVCpu->vm.s.pPriorityReqs) /* local requests pending? */
896 break;
897
898 if ( pUVCpu->pVM
899 && ( VM_FF_IS_PENDING(pUVCpu->pVM, VM_FF_EXTERNAL_SUSPENDED_MASK)
900 || VMCPU_FF_IS_PENDING(VMMGetCpu(pUVCpu->pVM), VMCPU_FF_EXTERNAL_SUSPENDED_MASK)
901 )
902 )
903 break;
904 if (pUVM->vm.s.fTerminateEMT)
905 break;
906
907 /*
908 * Wait for a while. Someone will wake us up or interrupt the call if
909 * anything needs our attention.
910 */
911 rc = RTSemEventWait(pUVCpu->vm.s.EventSemWait, 1000);
912 if (rc == VERR_TIMEOUT)
913 rc = VINF_SUCCESS;
914 else if (RT_FAILURE(rc))
915 {
916 rc = vmR3FatalWaitError(pUVCpu, "RTSemEventWait->%Rrc\n", rc);
917 break;
918 }
919 }
920
921 ASMAtomicUoWriteBool(&pUVCpu->vm.s.fWait, false);
922 return rc;
923}
924
925
926/**
927 * Bootstrap VMR3NotifyFF() worker.
928 *
929 * @param pUVCpu Pointer to the user mode VMCPU structure.
930 * @param fFlags Notification flags, VMNOTIFYFF_FLAGS_*.
931 */
932static DECLCALLBACK(void) vmR3BootstrapNotifyCpuFF(PUVMCPU pUVCpu, uint32_t fFlags)
933{
934 if (pUVCpu->vm.s.fWait)
935 {
936 int rc = RTSemEventSignal(pUVCpu->vm.s.EventSemWait);
937 AssertRC(rc);
938 }
939 NOREF(fFlags);
940}
941
942
943/**
944 * Default VMR3Wait() worker.
945 *
946 * @returns VBox status code.
947 * @param pUVCpu Pointer to the user mode VMCPU structure.
948 */
949static DECLCALLBACK(int) vmR3DefaultWait(PUVMCPU pUVCpu)
950{
951 ASMAtomicWriteBool(&pUVCpu->vm.s.fWait, true);
952
953 PVM pVM = pUVCpu->pVM;
954 PVMCPU pVCpu = pUVCpu->pVCpu;
955 int rc = VINF_SUCCESS;
956 for (;;)
957 {
958 /*
959 * Check Relevant FFs.
960 */
961 if ( VM_FF_IS_PENDING(pVM, VM_FF_EXTERNAL_SUSPENDED_MASK)
962 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_EXTERNAL_SUSPENDED_MASK))
963 break;
964
965 /*
966 * Wait for a while. Someone will wake us up or interrupt the call if
967 * anything needs our attention.
968 */
969 rc = RTSemEventWait(pUVCpu->vm.s.EventSemWait, 1000);
970 if (rc == VERR_TIMEOUT)
971 rc = VINF_SUCCESS;
972 else if (RT_FAILURE(rc))
973 {
974 rc = vmR3FatalWaitError(pUVCpu, "RTSemEventWait->%Rrc", rc);
975 break;
976 }
977 }
978
979 ASMAtomicUoWriteBool(&pUVCpu->vm.s.fWait, false);
980 return rc;
981}
982
983
984/**
985 * Default VMR3NotifyFF() worker.
986 *
987 * @param pUVCpu Pointer to the user mode VMCPU structure.
988 * @param fFlags Notification flags, VMNOTIFYFF_FLAGS_*.
989 */
990static DECLCALLBACK(void) vmR3DefaultNotifyCpuFF(PUVMCPU pUVCpu, uint32_t fFlags)
991{
992 if (pUVCpu->vm.s.fWait)
993 {
994 int rc = RTSemEventSignal(pUVCpu->vm.s.EventSemWait);
995 AssertRC(rc);
996 }
997 else
998 {
999 PVMCPU pVCpu = pUVCpu->pVCpu;
1000 if (pVCpu)
1001 {
1002 VMCPUSTATE enmState = pVCpu->enmState;
1003 if (enmState == VMCPUSTATE_STARTED_EXEC_NEM)
1004 NEMR3NotifyFF(pUVCpu->pVM, pVCpu, fFlags);
1005#ifdef VBOX_WITH_REM
1006 else if ( !(fFlags & VMNOTIFYFF_FLAGS_DONE_REM)
1007 && enmState == VMCPUSTATE_STARTED_EXEC_REM)
1008 REMR3NotifyFF(pUVCpu->pVM);
1009#endif
1010 }
1011 }
1012}
1013
1014
1015/**
1016 * Array with halt method descriptors.
1017 * VMINT::iHaltMethod contains an index into this array.
1018 */
1019static const struct VMHALTMETHODDESC
1020{
1021 /** The halt method id. */
1022 VMHALTMETHOD enmHaltMethod;
1023 /** The init function for loading config and initialize variables. */
1024 DECLR3CALLBACKMEMBER(int, pfnInit,(PUVM pUVM));
1025 /** The term function. */
1026 DECLR3CALLBACKMEMBER(void, pfnTerm,(PUVM pUVM));
1027 /** The VMR3WaitHaltedU function. */
1028 DECLR3CALLBACKMEMBER(int, pfnHalt,(PUVMCPU pUVCpu, const uint32_t fMask, uint64_t u64Now));
1029 /** The VMR3WaitU function. */
1030 DECLR3CALLBACKMEMBER(int, pfnWait,(PUVMCPU pUVCpu));
1031 /** The VMR3NotifyCpuFFU function. */
1032 DECLR3CALLBACKMEMBER(void, pfnNotifyCpuFF,(PUVMCPU pUVCpu, uint32_t fFlags));
1033 /** The VMR3NotifyGlobalFFU function. */
1034 DECLR3CALLBACKMEMBER(void, pfnNotifyGlobalFF,(PUVM pUVM, uint32_t fFlags));
1035} g_aHaltMethods[] =
1036{
1037 { VMHALTMETHOD_BOOTSTRAP, NULL, NULL, NULL, vmR3BootstrapWait, vmR3BootstrapNotifyCpuFF, NULL },
1038 { VMHALTMETHOD_OLD, NULL, NULL, vmR3HaltOldDoHalt, vmR3DefaultWait, vmR3DefaultNotifyCpuFF, NULL },
1039 { VMHALTMETHOD_1, vmR3HaltMethod1Init, NULL, vmR3HaltMethod1Halt, vmR3DefaultWait, vmR3DefaultNotifyCpuFF, NULL },
1040 { VMHALTMETHOD_GLOBAL_1, vmR3HaltGlobal1Init, NULL, vmR3HaltGlobal1Halt, vmR3HaltGlobal1Wait, vmR3HaltGlobal1NotifyCpuFF, NULL },
1041};
1042
1043
1044/**
1045 * Notify the emulation thread (EMT) about pending Forced Action (FF).
1046 *
1047 * This function is called by thread other than EMT to make
1048 * sure EMT wakes up and promptly service an FF request.
1049 *
1050 * @param pUVM Pointer to the user mode VM structure.
1051 * @param fFlags Notification flags, VMNOTIFYFF_FLAGS_*.
1052 * @internal
1053 */
1054VMMR3_INT_DECL(void) VMR3NotifyGlobalFFU(PUVM pUVM, uint32_t fFlags)
1055{
1056 LogFlow(("VMR3NotifyGlobalFFU:\n"));
1057 uint32_t iHaldMethod = pUVM->vm.s.iHaltMethod;
1058
1059 if (g_aHaltMethods[iHaldMethod].pfnNotifyGlobalFF) /** @todo make mandatory. */
1060 g_aHaltMethods[iHaldMethod].pfnNotifyGlobalFF(pUVM, fFlags);
1061 else
1062 for (VMCPUID iCpu = 0; iCpu < pUVM->cCpus; iCpu++)
1063 g_aHaltMethods[iHaldMethod].pfnNotifyCpuFF(&pUVM->aCpus[iCpu], fFlags);
1064}
1065
1066
1067/**
1068 * Notify the emulation thread (EMT) about pending Forced Action (FF).
1069 *
1070 * This function is called by thread other than EMT to make
1071 * sure EMT wakes up and promptly service an FF request.
1072 *
1073 * @param pUVCpu Pointer to the user mode per CPU VM structure.
1074 * @param fFlags Notification flags, VMNOTIFYFF_FLAGS_*.
1075 * @internal
1076 */
1077VMMR3_INT_DECL(void) VMR3NotifyCpuFFU(PUVMCPU pUVCpu, uint32_t fFlags)
1078{
1079 PUVM pUVM = pUVCpu->pUVM;
1080
1081 LogFlow(("VMR3NotifyCpuFFU:\n"));
1082 g_aHaltMethods[pUVM->vm.s.iHaltMethod].pfnNotifyCpuFF(pUVCpu, fFlags);
1083}
1084
1085
1086/**
1087 * Halted VM Wait.
1088 * Any external event will unblock the thread.
1089 *
1090 * @returns VINF_SUCCESS unless a fatal error occurred. In the latter
1091 * case an appropriate status code is returned.
1092 * @param pVM The cross context VM structure.
1093 * @param pVCpu The cross context virtual CPU structure.
1094 * @param fIgnoreInterrupts If set the VM_FF_INTERRUPT flags is ignored.
1095 * @thread The emulation thread.
1096 * @remarks Made visible for implementing vmsvga sync register.
1097 * @internal
1098 */
1099VMMR3_INT_DECL(int) VMR3WaitHalted(PVM pVM, PVMCPU pVCpu, bool fIgnoreInterrupts)
1100{
1101 LogFlow(("VMR3WaitHalted: fIgnoreInterrupts=%d\n", fIgnoreInterrupts));
1102
1103 /*
1104 * Check Relevant FFs.
1105 */
1106 const uint32_t fMask = !fIgnoreInterrupts
1107 ? VMCPU_FF_EXTERNAL_HALTED_MASK
1108 : VMCPU_FF_EXTERNAL_HALTED_MASK & ~(VMCPU_FF_UPDATE_APIC | VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC);
1109 if ( VM_FF_IS_PENDING(pVM, VM_FF_EXTERNAL_HALTED_MASK)
1110 || VMCPU_FF_IS_PENDING(pVCpu, fMask))
1111 {
1112 LogFlow(("VMR3WaitHalted: returns VINF_SUCCESS (FF %#x FFCPU %#x)\n", pVM->fGlobalForcedActions, pVCpu->fLocalForcedActions));
1113 return VINF_SUCCESS;
1114 }
1115
1116 /*
1117 * The yielder is suspended while we're halting, while TM might have clock(s) running
1118 * only at certain times and need to be notified..
1119 */
1120 if (pVCpu->idCpu == 0)
1121 VMMR3YieldSuspend(pVM);
1122 TMNotifyStartOfHalt(pVCpu);
1123
1124 /*
1125 * Record halt averages for the last second.
1126 */
1127 PUVMCPU pUVCpu = pVCpu->pUVCpu;
1128 uint64_t u64Now = RTTimeNanoTS();
1129 int64_t off = u64Now - pUVCpu->vm.s.u64HaltsStartTS;
1130 if (off > 1000000000)
1131 {
1132 if (off > _4G || !pUVCpu->vm.s.cHalts)
1133 {
1134 pUVCpu->vm.s.HaltInterval = 1000000000 /* 1 sec */;
1135 pUVCpu->vm.s.HaltFrequency = 1;
1136 }
1137 else
1138 {
1139 pUVCpu->vm.s.HaltInterval = (uint32_t)off / pUVCpu->vm.s.cHalts;
1140 pUVCpu->vm.s.HaltFrequency = ASMMultU64ByU32DivByU32(pUVCpu->vm.s.cHalts, 1000000000, (uint32_t)off);
1141 }
1142 pUVCpu->vm.s.u64HaltsStartTS = u64Now;
1143 pUVCpu->vm.s.cHalts = 0;
1144 }
1145 pUVCpu->vm.s.cHalts++;
1146
1147 /*
1148 * Do the halt.
1149 */
1150 VMCPU_ASSERT_STATE(pVCpu, VMCPUSTATE_STARTED);
1151 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_HALTED);
1152 PUVM pUVM = pUVCpu->pUVM;
1153 int rc = g_aHaltMethods[pUVM->vm.s.iHaltMethod].pfnHalt(pUVCpu, fMask, u64Now);
1154 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED);
1155
1156 /*
1157 * Notify TM and resume the yielder
1158 */
1159 TMNotifyEndOfHalt(pVCpu);
1160 if (pVCpu->idCpu == 0)
1161 VMMR3YieldResume(pVM);
1162
1163 LogFlow(("VMR3WaitHalted: returns %Rrc (FF %#x)\n", rc, pVM->fGlobalForcedActions));
1164 return rc;
1165}
1166
1167
1168/**
1169 * Suspended VM Wait.
1170 * Only a handful of forced actions will cause the function to
1171 * return to the caller.
1172 *
1173 * @returns VINF_SUCCESS unless a fatal error occurred. In the latter
1174 * case an appropriate status code is returned.
1175 * @param pUVCpu Pointer to the user mode VMCPU structure.
1176 * @thread The emulation thread.
1177 * @internal
1178 */
1179VMMR3_INT_DECL(int) VMR3WaitU(PUVMCPU pUVCpu)
1180{
1181 LogFlow(("VMR3WaitU:\n"));
1182
1183 /*
1184 * Check Relevant FFs.
1185 */
1186 PVM pVM = pUVCpu->pVM;
1187 PVMCPU pVCpu = pUVCpu->pVCpu;
1188
1189 if ( pVM
1190 && ( VM_FF_IS_PENDING(pVM, VM_FF_EXTERNAL_SUSPENDED_MASK)
1191 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_EXTERNAL_SUSPENDED_MASK)
1192 )
1193 )
1194 {
1195 LogFlow(("VMR3Wait: returns VINF_SUCCESS (FF %#x)\n", pVM->fGlobalForcedActions));
1196 return VINF_SUCCESS;
1197 }
1198
1199 /*
1200 * Do waiting according to the halt method (so VMR3NotifyFF
1201 * doesn't have to special case anything).
1202 */
1203 PUVM pUVM = pUVCpu->pUVM;
1204 int rc = g_aHaltMethods[pUVM->vm.s.iHaltMethod].pfnWait(pUVCpu);
1205 LogFlow(("VMR3WaitU: returns %Rrc (FF %#x)\n", rc, pUVM->pVM ? pUVM->pVM->fGlobalForcedActions : 0));
1206 return rc;
1207}
1208
1209
1210/**
1211 * Interface that PDMR3Suspend, PDMR3PowerOff and PDMR3Reset uses when they wait
1212 * for the handling of asynchronous notifications to complete.
1213 *
1214 * @returns VINF_SUCCESS unless a fatal error occurred. In the latter
1215 * case an appropriate status code is returned.
1216 * @param pUVCpu Pointer to the user mode VMCPU structure.
1217 * @thread The emulation thread.
1218 */
1219VMMR3_INT_DECL(int) VMR3AsyncPdmNotificationWaitU(PUVMCPU pUVCpu)
1220{
1221 LogFlow(("VMR3AsyncPdmNotificationWaitU:\n"));
1222 return VMR3WaitU(pUVCpu);
1223}
1224
1225
1226/**
1227 * Interface that PDM the helper asynchronous notification completed methods
1228 * uses for EMT0 when it is waiting inside VMR3AsyncPdmNotificationWaitU().
1229 *
1230 * @param pUVM Pointer to the user mode VM structure.
1231 */
1232VMMR3_INT_DECL(void) VMR3AsyncPdmNotificationWakeupU(PUVM pUVM)
1233{
1234 LogFlow(("VMR3AsyncPdmNotificationWakeupU:\n"));
1235 VM_FF_SET(pUVM->pVM, VM_FF_REQUEST); /* this will have to do for now. */
1236 g_aHaltMethods[pUVM->vm.s.iHaltMethod].pfnNotifyCpuFF(&pUVM->aCpus[0], 0 /*fFlags*/);
1237}
1238
1239
1240/**
1241 * Rendezvous callback that will be called once.
1242 *
1243 * @returns VBox strict status code.
1244 * @param pVM The cross context VM structure.
1245 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
1246 * @param pvUser The new g_aHaltMethods index.
1247 */
1248static DECLCALLBACK(VBOXSTRICTRC) vmR3SetHaltMethodCallback(PVM pVM, PVMCPU pVCpu, void *pvUser)
1249{
1250 PUVM pUVM = pVM->pUVM;
1251 uintptr_t i = (uintptr_t)pvUser;
1252 Assert(i < RT_ELEMENTS(g_aHaltMethods));
1253 NOREF(pVCpu);
1254
1255 /*
1256 * Terminate the old one.
1257 */
1258 if ( pUVM->vm.s.enmHaltMethod != VMHALTMETHOD_INVALID
1259 && g_aHaltMethods[pUVM->vm.s.iHaltMethod].pfnTerm)
1260 {
1261 g_aHaltMethods[pUVM->vm.s.iHaltMethod].pfnTerm(pUVM);
1262 pUVM->vm.s.enmHaltMethod = VMHALTMETHOD_INVALID;
1263 }
1264
1265 /* Assert that the failure fallback is where we expect. */
1266 Assert(g_aHaltMethods[0].enmHaltMethod == VMHALTMETHOD_BOOTSTRAP);
1267 Assert(!g_aHaltMethods[0].pfnTerm && !g_aHaltMethods[0].pfnInit);
1268
1269 /*
1270 * Init the new one.
1271 */
1272 int rc = VINF_SUCCESS;
1273 memset(&pUVM->vm.s.Halt, 0, sizeof(pUVM->vm.s.Halt));
1274 if (g_aHaltMethods[i].pfnInit)
1275 {
1276 rc = g_aHaltMethods[i].pfnInit(pUVM);
1277 if (RT_FAILURE(rc))
1278 {
1279 /* Fall back on the bootstrap method. This requires no
1280 init/term (see assertion above), and will always work. */
1281 AssertLogRelRC(rc);
1282 i = 0;
1283 }
1284 }
1285
1286 /*
1287 * Commit it.
1288 */
1289 pUVM->vm.s.enmHaltMethod = g_aHaltMethods[i].enmHaltMethod;
1290 ASMAtomicWriteU32(&pUVM->vm.s.iHaltMethod, i);
1291
1292 return rc;
1293}
1294
1295
1296/**
1297 * Changes the halt method.
1298 *
1299 * @returns VBox status code.
1300 * @param pUVM Pointer to the user mode VM structure.
1301 * @param enmHaltMethod The new halt method.
1302 * @thread EMT.
1303 */
1304int vmR3SetHaltMethodU(PUVM pUVM, VMHALTMETHOD enmHaltMethod)
1305{
1306 PVM pVM = pUVM->pVM; Assert(pVM);
1307 VM_ASSERT_EMT(pVM);
1308 AssertReturn(enmHaltMethod > VMHALTMETHOD_INVALID && enmHaltMethod < VMHALTMETHOD_END, VERR_INVALID_PARAMETER);
1309
1310 /*
1311 * Resolve default (can be overridden in the configuration).
1312 */
1313 if (enmHaltMethod == VMHALTMETHOD_DEFAULT)
1314 {
1315 uint32_t u32;
1316 int rc = CFGMR3QueryU32(CFGMR3GetChild(CFGMR3GetRoot(pVM), "VM"), "HaltMethod", &u32);
1317 if (RT_SUCCESS(rc))
1318 {
1319 enmHaltMethod = (VMHALTMETHOD)u32;
1320 if (enmHaltMethod <= VMHALTMETHOD_INVALID || enmHaltMethod >= VMHALTMETHOD_END)
1321 return VMSetError(pVM, VERR_INVALID_PARAMETER, RT_SRC_POS, N_("Invalid VM/HaltMethod value %d"), enmHaltMethod);
1322 }
1323 else if (rc == VERR_CFGM_VALUE_NOT_FOUND || rc == VERR_CFGM_CHILD_NOT_FOUND)
1324 return VMSetError(pVM, rc, RT_SRC_POS, N_("Failed to Query VM/HaltMethod as uint32_t"));
1325 else
1326 enmHaltMethod = VMHALTMETHOD_GLOBAL_1;
1327 //enmHaltMethod = VMHALTMETHOD_1;
1328 //enmHaltMethod = VMHALTMETHOD_OLD;
1329 }
1330 LogRel(("VMEmt: Halt method %s (%d)\n", vmR3GetHaltMethodName(enmHaltMethod), enmHaltMethod));
1331
1332 /*
1333 * Find the descriptor.
1334 */
1335 unsigned i = 0;
1336 while ( i < RT_ELEMENTS(g_aHaltMethods)
1337 && g_aHaltMethods[i].enmHaltMethod != enmHaltMethod)
1338 i++;
1339 AssertReturn(i < RT_ELEMENTS(g_aHaltMethods), VERR_INVALID_PARAMETER);
1340
1341 /*
1342 * This needs to be done while the other EMTs are not sleeping or otherwise messing around.
1343 */
1344 return VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, vmR3SetHaltMethodCallback, (void *)(uintptr_t)i);
1345}
1346
1347
1348/**
1349 * Special interface for implementing a HLT-like port on a device.
1350 *
1351 * This can be called directly from device code, provide the device is trusted
1352 * to access the VMM directly. Since we may not have an accurate register set
1353 * and the caller certainly shouldn't (device code does not access CPU
1354 * registers), this function will return when interrupts are pending regardless
1355 * of the actual EFLAGS.IF state.
1356 *
1357 * @returns VBox error status (never informational statuses).
1358 * @param pVM The cross context VM structure.
1359 * @param idCpu The id of the calling EMT.
1360 */
1361VMMR3DECL(int) VMR3WaitForDeviceReady(PVM pVM, VMCPUID idCpu)
1362{
1363 /*
1364 * Validate caller and resolve the CPU ID.
1365 */
1366 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
1367 AssertReturn(idCpu < pVM->cCpus, VERR_INVALID_CPU_ID);
1368 PVMCPU pVCpu = &pVM->aCpus[idCpu];
1369 VMCPU_ASSERT_EMT_RETURN(pVCpu, VERR_VM_THREAD_NOT_EMT);
1370
1371 /*
1372 * Tag along with the HLT mechanics for now.
1373 */
1374 int rc = VMR3WaitHalted(pVM, pVCpu, false /*fIgnoreInterrupts*/);
1375 if (RT_SUCCESS(rc))
1376 return VINF_SUCCESS;
1377 return rc;
1378}
1379
1380
1381/**
1382 * Wakes up a CPU that has called VMR3WaitForDeviceReady.
1383 *
1384 * @returns VBox error status (never informational statuses).
1385 * @param pVM The cross context VM structure.
1386 * @param idCpu The id of the calling EMT.
1387 */
1388VMMR3DECL(int) VMR3NotifyCpuDeviceReady(PVM pVM, VMCPUID idCpu)
1389{
1390 /*
1391 * Validate caller and resolve the CPU ID.
1392 */
1393 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
1394 AssertReturn(idCpu < pVM->cCpus, VERR_INVALID_CPU_ID);
1395 PVMCPU pVCpu = &pVM->aCpus[idCpu];
1396
1397 /*
1398 * Pretend it was an FF that got set since we've got logic for that already.
1399 */
1400 VMR3NotifyCpuFFU(pVCpu->pUVCpu, VMNOTIFYFF_FLAGS_DONE_REM);
1401 return VINF_SUCCESS;
1402}
1403
1404
1405/**
1406 * Returns the number of active EMTs.
1407 *
1408 * This is used by the rendezvous code during VM destruction to avoid waiting
1409 * for EMTs that aren't around any more.
1410 *
1411 * @returns Number of active EMTs. 0 if invalid parameter.
1412 * @param pUVM The user mode VM structure.
1413 */
1414VMMR3_INT_DECL(uint32_t) VMR3GetActiveEmts(PUVM pUVM)
1415{
1416 UVM_ASSERT_VALID_EXT_RETURN(pUVM, 0);
1417 return pUVM->vm.s.cActiveEmts;
1418}
1419
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