VirtualBox

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

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

VMM: warnings (clang)

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