VirtualBox

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

Last change on this file since 61628 was 61628, checked in by vboxsync, 8 years ago

DBGF: Added bsod_msr event, stubbed bsod_efi event. Since we cannot return VINF_EM_DBG_EVENT from an MSR handler, VMCPU_FF_DBGF was introduced as an alternative.

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