VirtualBox

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

Last change on this file since 5605 was 5167, checked in by vboxsync, 17 years ago

New halt method.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 31.9 KB
Line 
1/* $Id: VMEmt.cpp 5167 2007-10-05 13:33:36Z vboxsync $ */
2/** @file
3 * VM - Virtual Machine, The Emulation Thread.
4 */
5
6/*
7 * Copyright (C) 2006-2007 innotek GmbH
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 as published by the Free Software Foundation,
13 * in version 2 as it comes in the "COPYING" file of the VirtualBox OSE
14 * distribution. VirtualBox OSE is distributed in the hope that it will
15 * 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/tm.h>
24#include <VBox/dbgf.h>
25#include <VBox/em.h>
26#include <VBox/pdmapi.h>
27#include <VBox/rem.h>
28#include "VMInternal.h"
29#include <VBox/vm.h>
30
31#include <VBox/err.h>
32#include <VBox/log.h>
33#include <iprt/assert.h>
34#include <iprt/asm.h>
35#include <iprt/semaphore.h>
36#include <iprt/string.h>
37#include <iprt/thread.h>
38#include <iprt/time.h>
39
40
41
42
43/**
44 * The emulation thread.
45 *
46 * @returns Thread exit code.
47 * @param ThreadSelf The handle to the executing thread.
48 * @param pvArgs Pointer to a VMEMULATIONTHREADARGS structure.
49 */
50DECLCALLBACK(int) vmR3EmulationThread(RTTHREAD ThreadSelf, void *pvArgs)
51{
52 PVMEMULATIONTHREADARGS pArgs = (PVMEMULATIONTHREADARGS)pvArgs;
53 AssertReleaseMsg(pArgs && pArgs->pVM, ("Invalid arguments to the emulation thread!\n"));
54
55 /*
56 * Init the native thread member.
57 */
58 PVM pVM = pArgs->pVM;
59 pVM->NativeThreadEMT = RTThreadGetNative(ThreadSelf);
60
61 /*
62 * The request loop.
63 */
64 VMSTATE enmBefore;
65 int rc;
66 Log(("vmR3EmulationThread: Emulation thread starting the days work... Thread=%#x pVM=%p\n", ThreadSelf, pVM));
67 for (;;)
68 {
69 /* Requested to exit the EMT thread out of sync? (currently only VMR3WaitForResume) */
70 if (setjmp(pVM->vm.s.emtJumpEnv) != 0)
71 {
72 rc = VINF_SUCCESS;
73 break;
74 }
75
76 /*
77 * Pending requests which needs servicing?
78 *
79 * We check for state changes in addition to status codes when
80 * servicing requests. (Look after the ifs.)
81 */
82 enmBefore = pVM->enmVMState;
83 if (VM_FF_ISSET(pVM, VM_FF_TERMINATE))
84 {
85 rc = VINF_EM_TERMINATE;
86 break;
87 }
88 if (pVM->vm.s.pReqs)
89 {
90 /*
91 * Service execute in EMT request.
92 */
93 rc = VMR3ReqProcess(pVM);
94 Log(("vmR3EmulationThread: Req rc=%Vrc, VM state %d -> %d\n", rc, enmBefore, pVM->enmVMState));
95 }
96 else if (VM_FF_ISSET(pVM, VM_FF_DBGF))
97 {
98 /*
99 * Service the debugger request.
100 */
101 rc = DBGFR3VMMForcedAction(pVM);
102 Log(("vmR3EmulationThread: Dbg rc=%Vrc, VM state %d -> %d\n", rc, enmBefore, pVM->enmVMState));
103 }
104 else if (VM_FF_ISSET(pVM, VM_FF_RESET))
105 {
106 /*
107 * Service a delay reset request.
108 */
109 rc = VMR3Reset(pVM);
110 VM_FF_CLEAR(pVM, VM_FF_RESET);
111 Log(("vmR3EmulationThread: Reset rc=%Vrc, VM state %d -> %d\n", rc, enmBefore, pVM->enmVMState));
112 }
113 else
114 {
115 /*
116 * Nothing important is pending, so wait for something.
117 */
118 rc = VMR3Wait(pVM);
119 if (VBOX_FAILURE(rc))
120 break;
121 }
122
123 /*
124 * Check for termination requests, these are extremely high priority.
125 */
126 if ( rc == VINF_EM_TERMINATE
127 || VM_FF_ISSET(pVM, VM_FF_TERMINATE))
128 break;
129
130 /*
131 * Some requests (both VMR3Req* and the DBGF) can potentially
132 * resume or start the VM, in that case we'll get a change in
133 * VM status indicating that we're now running.
134 */
135 if ( VBOX_SUCCESS(rc)
136 && enmBefore != pVM->enmVMState
137 && (pVM->enmVMState == VMSTATE_RUNNING))
138 {
139 rc = EMR3ExecuteVM(pVM);
140 Log(("vmR3EmulationThread: EMR3ExecuteVM() -> rc=%Vrc, enmVMState=%d\n", rc, pVM->enmVMState));
141 if (EMGetState(pVM) == EMSTATE_GURU_MEDITATION)
142 vmR3SetState(pVM, VMSTATE_GURU_MEDITATION);
143 }
144
145 } /* forever */
146
147
148 /*
149 * Exiting.
150 */
151 Log(("vmR3EmulationThread: Terminating emulation thread! Thread=%#x pVM=%p rc=%Vrc enmBefore=%d enmVMState=%d\n",
152 ThreadSelf, pVM, rc, enmBefore, pVM->enmVMState));
153 if (pVM->vm.s.fEMTDoesTheCleanup)
154 {
155 Log(("vmR3EmulationThread: executing delayed Destroy\n"));
156 vmR3Destroy(pVM);
157 vmR3DestroyFinalBit(pVM);
158 Log(("vmR3EmulationThread: EMT is terminated.\n"));
159 }
160 else
161 {
162 /* we don't reset ThreadEMT here because it's used in waiting. */
163 pVM->NativeThreadEMT = NIL_RTNATIVETHREAD;
164 }
165 return rc;
166}
167
168
169/**
170 * Wait for VM to be resumed. Handle events like vmR3EmulationThread does.
171 * In case the VM is stopped, clean up and long jump to the main EMT loop.
172 *
173 * @returns VINF_SUCCESS or doesn't return
174 * @param pVM VM handle.
175 */
176VMR3DECL(int) VMR3WaitForResume(PVM pVM)
177{
178 /*
179 * The request loop.
180 */
181 VMSTATE enmBefore;
182 int rc;
183 for (;;)
184 {
185
186 /*
187 * Pending requests which needs servicing?
188 *
189 * We check for state changes in addition to status codes when
190 * servicing requests. (Look after the ifs.)
191 */
192 enmBefore = pVM->enmVMState;
193 if (VM_FF_ISSET(pVM, VM_FF_TERMINATE))
194 {
195 rc = VINF_EM_TERMINATE;
196 break;
197 }
198 else if (pVM->vm.s.pReqs)
199 {
200 /*
201 * Service execute in EMT request.
202 */
203 rc = VMR3ReqProcess(pVM);
204 Log(("vmR3EmulationThread: Req rc=%Vrc, VM state %d -> %d\n", rc, enmBefore, pVM->enmVMState));
205 }
206 else if (VM_FF_ISSET(pVM, VM_FF_DBGF))
207 {
208 /*
209 * Service the debugger request.
210 */
211 rc = DBGFR3VMMForcedAction(pVM);
212 Log(("vmR3EmulationThread: Dbg rc=%Vrc, VM state %d -> %d\n", rc, enmBefore, pVM->enmVMState));
213 }
214 else if (VM_FF_ISSET(pVM, VM_FF_RESET))
215 {
216 /*
217 * Service a delay reset request.
218 */
219 rc = VMR3Reset(pVM);
220 VM_FF_CLEAR(pVM, VM_FF_RESET);
221 Log(("vmR3EmulationThread: Reset rc=%Vrc, VM state %d -> %d\n", rc, enmBefore, pVM->enmVMState));
222 }
223 else
224 {
225 /*
226 * Nothing important is pending, so wait for something.
227 */
228 rc = VMR3Wait(pVM);
229 if (VBOX_FAILURE(rc))
230 break;
231 }
232
233 /*
234 * Check for termination requests, these are extremely high priority.
235 */
236 if ( rc == VINF_EM_TERMINATE
237 || VM_FF_ISSET(pVM, VM_FF_TERMINATE))
238 break;
239
240 /*
241 * Some requests (both VMR3Req* and the DBGF) can potentially
242 * resume or start the VM, in that case we'll get a change in
243 * VM status indicating that we're now running.
244 */
245 if ( VBOX_SUCCESS(rc)
246 && enmBefore != pVM->enmVMState
247 && (pVM->enmVMState == VMSTATE_RUNNING))
248 {
249 /* Only valid exit reason. */
250 return VINF_SUCCESS;
251 }
252
253 } /* forever */
254
255 /* Return to the main loop in vmR3EmulationThread, which will clean up for us. */
256 longjmp(pVM->vm.s.emtJumpEnv, 1);
257}
258
259
260/**
261 * Gets the name of a halt method.
262 *
263 * @returns Pointer to a read only string.
264 * @param enmMethod The method.
265 */
266static const char *vmR3GetHaltMethodName(VMHALTMETHOD enmMethod)
267{
268 switch (enmMethod)
269 {
270 case VMHALTMETHOD_DEFAULT: return "default";
271 case VMHALTMETHOD_OLD: return "old";
272 case VMHALTMETHOD_1: return "method1";
273 //case VMHALTMETHOD_2: return "method2";
274 case VMHALTMETHOD_GLOBAL_1: return "global1";
275 default: return "unknown";
276 }
277}
278
279
280/**
281 * The old halt loop.
282 */
283static DECLCALLBACK(int) vmR3HaltOldDoHalt(PVM pVM, const uint32_t fMask, uint64_t /* u64Now*/)
284{
285 /*
286 * Halt loop.
287 */
288 int rc = VINF_SUCCESS;
289 ASMAtomicXchgU32(&pVM->vm.s.fWait, 1);
290 //unsigned cLoops = 0;
291 for (;;)
292 {
293 /*
294 * Work the timers and check if we can exit.
295 * The poll call gives us the ticks left to the next event in
296 * addition to perhaps set an FF.
297 */
298 STAM_REL_PROFILE_START(&pVM->vm.s.StatHaltPoll, a);
299 PDMR3Poll(pVM);
300 STAM_REL_PROFILE_STOP(&pVM->vm.s.StatHaltPoll, a);
301 STAM_REL_PROFILE_START(&pVM->vm.s.StatHaltTimers, b);
302 TMR3TimerQueuesDo(pVM);
303 STAM_REL_PROFILE_STOP(&pVM->vm.s.StatHaltTimers, b);
304 if (VM_FF_ISPENDING(pVM, fMask))
305 break;
306 uint64_t u64NanoTS = TMVirtualToNano(pVM, TMTimerPoll(pVM));
307 if (VM_FF_ISPENDING(pVM, fMask))
308 break;
309
310 /*
311 * Wait for a while. Someone will wake us up or interrupt the call if
312 * anything needs our attention.
313 */
314 if (u64NanoTS < 50000)
315 {
316 //RTLogPrintf("u64NanoTS=%RI64 cLoops=%d spin\n", u64NanoTS, cLoops++);
317 /* spin */;
318 }
319 else
320 {
321 VMMR3YieldStop(pVM);
322 //uint64_t u64Start = RTTimeNanoTS();
323 if (u64NanoTS < 870000) /* this is a bit speculative... works fine on linux. */
324 {
325 //RTLogPrintf("u64NanoTS=%RI64 cLoops=%d yield", u64NanoTS, cLoops++);
326 STAM_REL_PROFILE_START(&pVM->vm.s.StatHaltYield, a);
327 RTThreadYield(); /* this is the best we can do here */
328 STAM_REL_PROFILE_STOP(&pVM->vm.s.StatHaltYield, a);
329 }
330 else if (u64NanoTS < 2000000)
331 {
332 //RTLogPrintf("u64NanoTS=%RI64 cLoops=%d sleep 1ms", u64NanoTS, cLoops++);
333 STAM_REL_PROFILE_START(&pVM->vm.s.StatHaltBlock, a);
334 rc = RTSemEventWait(pVM->vm.s.EventSemWait, 1);
335 STAM_REL_PROFILE_STOP(&pVM->vm.s.StatHaltBlock, a);
336 }
337 else
338 {
339 //RTLogPrintf("u64NanoTS=%RI64 cLoops=%d sleep %dms", u64NanoTS, cLoops++, (uint32_t)RT_MIN((u64NanoTS - 500000) / 1000000, 15));
340 STAM_REL_PROFILE_START(&pVM->vm.s.StatHaltBlock, a);
341 rc = RTSemEventWait(pVM->vm.s.EventSemWait, RT_MIN((u64NanoTS - 1000000) / 1000000, 15));
342 STAM_REL_PROFILE_STOP(&pVM->vm.s.StatHaltBlock, a);
343 }
344 //uint64_t u64Slept = RTTimeNanoTS() - u64Start;
345 //RTLogPrintf(" -> rc=%Vrc in %RU64 ns / %RI64 ns delta\n", rc, u64Slept, u64NanoTS - u64Slept);
346 }
347 if (rc == VERR_TIMEOUT)
348 rc = VINF_SUCCESS;
349 else if (VBOX_FAILURE(rc))
350 {
351 AssertRC(rc != VERR_INTERRUPTED);
352 AssertMsgFailed(("RTSemEventWait->%Vrc\n", rc));
353 VM_FF_SET(pVM, VM_FF_TERMINATE);
354 rc = VERR_INTERNAL_ERROR;
355 break;
356 }
357 }
358
359 return rc;
360}
361
362
363/**
364 * Initialize the configuration of halt method 1 & 2.
365 *
366 * @return VBox status code. Failure on invalid CFGM data.
367 * @param pVM The VM handle.
368 */
369static int vmR3HaltMethod12ReadConfig(PVM pVM)
370{
371 /*
372 * The defaults.
373 */
374#if 1 /* DEBUGGING STUFF - REMOVE LATER */
375 pVM->vm.s.Halt.Method12.u32LagBlockIntervalDivisorCfg = 4;
376 pVM->vm.s.Halt.Method12.u32MinBlockIntervalCfg = 2*1000000;
377 pVM->vm.s.Halt.Method12.u32MaxBlockIntervalCfg = 75*1000000;
378 pVM->vm.s.Halt.Method12.u32StartSpinningCfg = 30*1000000;
379 pVM->vm.s.Halt.Method12.u32StopSpinningCfg = 20*1000000;
380#else
381 pVM->vm.s.Halt.Method12.u32LagBlockIntervalDivisorCfg = 4;
382 pVM->vm.s.Halt.Method12.u32MinBlockIntervalCfg = 5*1000000;
383 pVM->vm.s.Halt.Method12.u32MaxBlockIntervalCfg = 200*1000000;
384 pVM->vm.s.Halt.Method12.u32StartSpinningCfg = 20*1000000;
385 pVM->vm.s.Halt.Method12.u32StopSpinningCfg = 2*1000000;
386#endif
387
388 /*
389 * Query overrides.
390 *
391 * I don't have time to bother with niceities such as invalid value checks
392 * here right now. sorry.
393 */
394 PCFGMNODE pCfg = CFGMR3GetChild(CFGMR3GetRoot(pVM), "/VMM/HaltedMethod1");
395 if (pCfg)
396 {
397 uint32_t u32;
398 if (RT_SUCCESS(CFGMR3QueryU32(pCfg, "LagBlockIntervalDivisor", &u32)))
399 pVM->vm.s.Halt.Method12.u32LagBlockIntervalDivisorCfg = u32;
400 if (RT_SUCCESS(CFGMR3QueryU32(pCfg, "MinBlockInterval", &u32)))
401 pVM->vm.s.Halt.Method12.u32MinBlockIntervalCfg = u32;
402 if (RT_SUCCESS(CFGMR3QueryU32(pCfg, "MaxBlockInterval", &u32)))
403 pVM->vm.s.Halt.Method12.u32MaxBlockIntervalCfg = u32;
404 if (RT_SUCCESS(CFGMR3QueryU32(pCfg, "StartSpinning", &u32)))
405 pVM->vm.s.Halt.Method12.u32StartSpinningCfg = u32;
406 if (RT_SUCCESS(CFGMR3QueryU32(pCfg, "StopSpinning", &u32)))
407 pVM->vm.s.Halt.Method12.u32StopSpinningCfg = u32;
408 LogRel(("HaltedMethod1 config: %d/%d/%d/%d/%d\n",
409 pVM->vm.s.Halt.Method12.u32LagBlockIntervalDivisorCfg,
410 pVM->vm.s.Halt.Method12.u32MinBlockIntervalCfg,
411 pVM->vm.s.Halt.Method12.u32MaxBlockIntervalCfg,
412 pVM->vm.s.Halt.Method12.u32StartSpinningCfg,
413 pVM->vm.s.Halt.Method12.u32StopSpinningCfg));
414 }
415
416 return VINF_SUCCESS;
417}
418
419
420/**
421 * Initialize halt method 1.
422 *
423 * @return VBox status code.
424 * @param pVM The VM handle.
425 */
426static DECLCALLBACK(int) vmR3HaltMethod1Init(PVM pVM)
427{
428 return vmR3HaltMethod12ReadConfig(pVM);
429}
430
431
432/**
433 * Method 1 - Block whenever possible, and when lagging behind
434 * switch to spinning for 10-30ms with occational blocking until
435 * the lag has been eliminated.
436 */
437static DECLCALLBACK(int) vmR3HaltMethod1Halt(PVM pVM, const uint32_t fMask, uint64_t u64Now)
438{
439 /*
440 * To simplify things, we decide up-front whether we should switch to spinning or
441 * not. This makes some ASSUMPTIONS about the cause of the spinning (PIT/RTC/PCNet)
442 * and that it will generate interrupts or other events that will cause us to exit
443 * the halt loop.
444 */
445 bool fBlockOnce = false;
446 bool fSpinning = false;
447 uint32_t u32CatchUpPct = TMVirtualSyncGetCatchUpPct(pVM);
448 if (u32CatchUpPct /* non-zero if catching up */)
449 {
450 if (pVM->vm.s.Halt.Method12.u64StartSpinTS)
451 {
452 fSpinning = TMVirtualSyncGetLag(pVM) >= pVM->vm.s.Halt.Method12.u32StopSpinningCfg;
453 if (fSpinning)
454 {
455 uint64_t u64Lag = TMVirtualSyncGetLag(pVM);
456 fBlockOnce = u64Now - pVM->vm.s.Halt.Method12.u64LastBlockTS
457 > RT_MAX(pVM->vm.s.Halt.Method12.u32MinBlockIntervalCfg,
458 RT_MIN(u64Lag / pVM->vm.s.Halt.Method12.u32LagBlockIntervalDivisorCfg,
459 pVM->vm.s.Halt.Method12.u32MaxBlockIntervalCfg));
460 }
461 else
462 {
463 //RTLogRelPrintf("Stopped spinning (%u ms)\n", (u64Now - pVM->vm.s.Halt.Method12.u64StartSpinTS) / 1000000);
464 pVM->vm.s.Halt.Method12.u64StartSpinTS = 0;
465 }
466 }
467 else
468 {
469 fSpinning = TMVirtualSyncGetLag(pVM) >= pVM->vm.s.Halt.Method12.u32StartSpinningCfg;
470 if (fSpinning)
471 pVM->vm.s.Halt.Method12.u64StartSpinTS = u64Now;
472 }
473 }
474 else if (pVM->vm.s.Halt.Method12.u64StartSpinTS)
475 {
476 //RTLogRelPrintf("Stopped spinning (%u ms)\n", (u64Now - pVM->vm.s.Halt.Method12.u64StartSpinTS) / 1000000);
477 pVM->vm.s.Halt.Method12.u64StartSpinTS = 0;
478 }
479
480 /*
481 * Halt loop.
482 */
483 int rc = VINF_SUCCESS;
484 ASMAtomicXchgU32(&pVM->vm.s.fWait, 1);
485 unsigned cLoops = 0;
486 for (;; cLoops++)
487 {
488 /*
489 * Work the timers and check if we can exit.
490 */
491 STAM_REL_PROFILE_START(&pVM->vm.s.StatHaltPoll, a);
492 PDMR3Poll(pVM);
493 STAM_REL_PROFILE_STOP(&pVM->vm.s.StatHaltPoll, a);
494 STAM_REL_PROFILE_START(&pVM->vm.s.StatHaltTimers, b);
495 TMR3TimerQueuesDo(pVM);
496 STAM_REL_PROFILE_STOP(&pVM->vm.s.StatHaltTimers, b);
497 if (VM_FF_ISPENDING(pVM, fMask))
498 break;
499
500 /*
501 * Estimate time left to the next event.
502 */
503 uint64_t u64NanoTS = TMVirtualToNano(pVM, TMTimerPoll(pVM));
504 if (VM_FF_ISPENDING(pVM, fMask))
505 break;
506
507 /*
508 * Block if we're not spinning and the interval isn't all that small.
509 */
510 if ( ( !fSpinning
511 || fBlockOnce)
512#if 1 /* DEBUGGING STUFF - REMOVE LATER */
513 && u64NanoTS >= 100000) /* 0.100 ms */
514#else
515 && u64NanoTS >= 250000) /* 0.250 ms */
516#endif
517 {
518 const uint64_t Start = pVM->vm.s.Halt.Method12.u64LastBlockTS = RTTimeNanoTS();
519 VMMR3YieldStop(pVM);
520
521 uint32_t cMilliSecs = RT_MIN(u64NanoTS / 1000000, 15);
522 if (cMilliSecs <= pVM->vm.s.Halt.Method12.cNSBlockedTooLongAvg)
523 cMilliSecs = 1;
524 else
525 cMilliSecs -= pVM->vm.s.Halt.Method12.cNSBlockedTooLongAvg;
526 //RTLogRelPrintf("u64NanoTS=%RI64 cLoops=%3d sleep %02dms (%7RU64) ", u64NanoTS, cLoops, cMilliSecs, u64NanoTS);
527 STAM_REL_PROFILE_START(&pVM->vm.s.StatHaltBlock, a);
528 rc = RTSemEventWait(pVM->vm.s.EventSemWait, cMilliSecs);
529 STAM_REL_PROFILE_STOP(&pVM->vm.s.StatHaltBlock, a);
530 if (rc == VERR_TIMEOUT)
531 rc = VINF_SUCCESS;
532 else if (VBOX_FAILURE(rc))
533 {
534 AssertRC(rc != VERR_INTERRUPTED);
535 AssertMsgFailed(("RTSemEventWait->%Vrc\n", rc));
536 VM_FF_SET(pVM, VM_FF_TERMINATE);
537 rc = VERR_INTERNAL_ERROR;
538 break;
539 }
540
541 /*
542 * Calc the statistics.
543 * Update averages every 16th time, and flush parts of the history every 64th time.
544 */
545 const uint64_t Elapsed = RTTimeNanoTS() - Start;
546 pVM->vm.s.Halt.Method12.cNSBlocked += Elapsed;
547 if (Elapsed > u64NanoTS)
548 pVM->vm.s.Halt.Method12.cNSBlockedTooLong += Elapsed - u64NanoTS;
549 pVM->vm.s.Halt.Method12.cBlocks++;
550 if (!(pVM->vm.s.Halt.Method12.cBlocks & 0xf))
551 {
552 pVM->vm.s.Halt.Method12.cNSBlockedTooLongAvg = pVM->vm.s.Halt.Method12.cNSBlockedTooLong / pVM->vm.s.Halt.Method12.cBlocks;
553 if (!(pVM->vm.s.Halt.Method12.cBlocks & 0x3f))
554 {
555 pVM->vm.s.Halt.Method12.cNSBlockedTooLong = pVM->vm.s.Halt.Method12.cNSBlockedTooLongAvg * 0x40;
556 pVM->vm.s.Halt.Method12.cBlocks = 0x40;
557 }
558 }
559 //RTLogRelPrintf(" -> %7RU64 ns / %7RI64 ns delta%s\n", Elapsed, Elapsed - u64NanoTS, fBlockOnce ? " (block once)" : "");
560
561 /*
562 * Clear the block once flag if we actually blocked.
563 */
564 if ( fBlockOnce
565 && Elapsed > 100000 /* 0.1 ms */)
566 fBlockOnce = false;
567 }
568 }
569 //if (fSpinning) RTLogRelPrintf("spun for %RU64 ns %u loops; lag=%RU64 pct=%d\n", RTTimeNanoTS() - u64Now, cLoops, TMVirtualSyncGetLag(pVM), u32CatchUpPct);
570
571 return rc;
572}
573
574
575/**
576 * Initialize the global 1 halt method.
577 *
578 * @return VBox status code.
579 * @param pVM The VM handle.
580 */
581static DECLCALLBACK(int) vmR3HaltGlobal1Init(PVM pVM)
582{
583 return VINF_SUCCESS;
584}
585
586
587/**
588 * The global 1 halt method - Block in GMM (ring-0) and let it
589 * try take care of the global scheduling of EMT threads.
590 */
591static DECLCALLBACK(int) vmR3HaltGlobal1Halt(PVM pVM, const uint32_t fMask, uint64_t u64Now)
592{
593 /*
594 * Halt loop.
595 */
596 int rc = VINF_SUCCESS;
597 ASMAtomicXchgU32(&pVM->vm.s.fWait, 1);
598 unsigned cLoops = 0;
599 for (;; cLoops++)
600 {
601 /*
602 * Work the timers and check if we can exit.
603 */
604 STAM_REL_PROFILE_START(&pVM->vm.s.StatHaltPoll, a);
605 PDMR3Poll(pVM);
606 STAM_REL_PROFILE_STOP(&pVM->vm.s.StatHaltPoll, a);
607 STAM_REL_PROFILE_START(&pVM->vm.s.StatHaltTimers, b);
608 TMR3TimerQueuesDo(pVM);
609 STAM_REL_PROFILE_STOP(&pVM->vm.s.StatHaltTimers, b);
610 if (VM_FF_ISPENDING(pVM, fMask))
611 break;
612
613 /*
614 * Estimate time left to the next event.
615 */
616 uint64_t u64Delta;
617 uint64_t u64GipTime = TMTimerPollGIP(pVM, &u64Delta);
618 if (VM_FF_ISPENDING(pVM, fMask))
619 break;
620
621 /*
622 * Block if we're not spinning and the interval isn't all that small.
623 */
624 if (u64Delta > 50000 /* 0.050ms */)
625 {
626 VMMR3YieldStop(pVM);
627 ASMAtomicXchgU32(&pVM->vm.s.fWait, 1);
628 if (VM_FF_ISPENDING(pVM, fMask))
629 break;
630
631 //RTLogRelPrintf("u64NanoTS=%RI64 cLoops=%3d sleep %02dms (%7RU64) ", u64NanoTS, cLoops, cMilliSecs, u64NanoTS);
632 STAM_REL_PROFILE_START(&pVM->vm.s.StatHaltBlock, c);
633 rc = SUPCallVMMR0Ex(pVM->pVMR0, VMMR0_DO_GVMM_SCHED_HALT, u64GipTime, NULL);
634 STAM_REL_PROFILE_STOP(&pVM->vm.s.StatHaltBlock, c);
635 if (rc == VERR_INTERRUPTED)
636 rc = VINF_SUCCESS;
637 else if (VBOX_FAILURE(rc))
638 {
639 AssertMsgFailed(("VMMR0_DO_GVMM_SCHED_HALT->%Vrc\n", rc));
640 VM_FF_SET(pVM, VM_FF_TERMINATE);
641 rc = VERR_INTERNAL_ERROR;
642 break;
643 }
644 }
645 /*
646 * When spinning call upon the GVMM and do some wakups once
647 * in a while, it's not like we're actually busy or anything.
648 */
649 else if (!(cLoops & 0x1fff))
650 {
651 STAM_REL_PROFILE_START(&pVM->vm.s.StatHaltYield, d);
652 rc = SUPCallVMMR0Ex(pVM->pVMR0, VMMR0_DO_GVMM_SCHED_POLL, false /* don't yield */, NULL);
653 STAM_REL_PROFILE_STOP(&pVM->vm.s.StatHaltYield, d);
654 }
655 }
656 //if (fSpinning) RTLogRelPrintf("spun for %RU64 ns %u loops; lag=%RU64 pct=%d\n", RTTimeNanoTS() - u64Now, cLoops, TMVirtualSyncGetLag(pVM), u32CatchUpPct);
657
658 return rc;
659}
660
661
662/**
663 * The global 1 halt method - VMR3Wait() worker.
664 *
665 * @returns VBox status code.
666 * @param pVM The VM handle.
667 */
668static DECLCALLBACK(int) vmR3HaltGlobal1Wait(PVM pVM)
669{
670 int rc = VINF_SUCCESS;
671 ASMAtomicXchgU32(&pVM->vm.s.fWait, 1);
672 for (;;)
673 {
674 /*
675 * Check Relevant FFs.
676 */
677 if (VM_FF_ISPENDING(pVM, VM_FF_EXTERNAL_SUSPENDED_MASK))
678 break;
679
680 /*
681 * Wait for a while. Someone will wake us up or interrupt the call if
682 * anything needs our attention.
683 */
684 rc = SUPCallVMMR0Ex(pVM->pVMR0, VMMR0_DO_GVMM_SCHED_HALT, RTTimeNanoTS() + 1000000000 /* +1s */, NULL);
685 if (rc == VERR_INTERRUPTED)
686 rc = VINF_SUCCESS;
687 else if (VBOX_FAILURE(rc))
688 {
689 AssertMsgFailed(("RTSemEventWait->%Vrc\n", rc));
690 VM_FF_SET(pVM, VM_FF_TERMINATE);
691 rc = VERR_INTERNAL_ERROR;
692 break;
693 }
694
695 }
696 ASMAtomicXchgU32(&pVM->vm.s.fWait, 0);
697 return rc;
698}
699
700
701/**
702 * The global 1 halt method - VMR3NotifyFF() worker.
703 *
704 * @param pVM The VM handle.
705 * @param fNotifiedREM Se VMR3NotifyFF().
706 */
707static DECLCALLBACK(void) vmR3HaltGlobal1NotifyFF(PVM pVM, bool fNotifiedREM)
708{
709 if (pVM->vm.s.fWait)
710 {
711 int rc = SUPCallVMMR0Ex(pVM->pVMR0, VMMR0_DO_GVMM_SCHED_WAKE_UP, 0, NULL);
712 AssertRC(rc);
713 }
714 else if (!fNotifiedREM)
715 REMR3NotifyFF(pVM);
716}
717
718
719/**
720 * Default VMR3Wait() worker.
721 *
722 * @returns VBox status code.
723 * @param pVM The VM handle.
724 */
725static DECLCALLBACK(int) vmR3DefaultWait(PVM pVM)
726{
727 int rc = VINF_SUCCESS;
728 ASMAtomicXchgU32(&pVM->vm.s.fWait, 1);
729 for (;;)
730 {
731 /*
732 * Check Relevant FFs.
733 */
734 if (VM_FF_ISPENDING(pVM, VM_FF_EXTERNAL_SUSPENDED_MASK))
735 break;
736
737 /*
738 * Wait for a while. Someone will wake us up or interrupt the call if
739 * anything needs our attention.
740 */
741 rc = RTSemEventWait(pVM->vm.s.EventSemWait, 1000);
742 if (rc == VERR_TIMEOUT)
743 rc = VINF_SUCCESS;
744 else if (VBOX_FAILURE(rc))
745 {
746 AssertMsgFailed(("RTSemEventWait->%Vrc\n", rc));
747 VM_FF_SET(pVM, VM_FF_TERMINATE);
748 rc = VERR_INTERNAL_ERROR;
749 break;
750 }
751
752 }
753 ASMAtomicXchgU32(&pVM->vm.s.fWait, 0);
754 return rc;
755}
756
757
758/**
759 * Default VMR3NotifyFF() worker.
760 *
761 * @param pVM The VM handle.
762 * @param fNotifiedREM Se VMR3NotifyFF().
763 */
764static DECLCALLBACK(void) vmR3DefaultNotifyFF(PVM pVM, bool fNotifiedREM)
765{
766 if (pVM->vm.s.fWait)
767 {
768 int rc = RTSemEventSignal(pVM->vm.s.EventSemWait);
769 AssertRC(rc);
770 }
771 else if (!fNotifiedREM)
772 REMR3NotifyFF(pVM);
773}
774
775
776/**
777 * Array with halt method descriptors.
778 * VMINT::iHaltMethod contains an index into this array.
779 */
780static const struct VMHALTMETHODDESC
781{
782 /** The halt method id. */
783 VMHALTMETHOD enmHaltMethod;
784 /** The init function for loading config and initialize variables. */
785 DECLR3CALLBACKMEMBER(int, pfnInit,(PVM pVM));
786 /** The term function. */
787 DECLR3CALLBACKMEMBER(void, pfnTerm,(PVM pVM));
788 /** The halt function. */
789 DECLR3CALLBACKMEMBER(int, pfnHalt,(PVM pVM, const uint32_t fMask, uint64_t u64Now));
790 /** The wait function. */
791 DECLR3CALLBACKMEMBER(int, pfnWait,(PVM pVM));
792 /** The notifyFF function. */
793 DECLR3CALLBACKMEMBER(void, pfnNotifyFF,(PVM pVM, bool fNotifiedREM));
794} g_aHaltMethods[] =
795{
796 { VMHALTMETHOD_OLD, NULL, NULL, vmR3HaltOldDoHalt, vmR3DefaultWait, vmR3DefaultNotifyFF },
797 { VMHALTMETHOD_1, vmR3HaltMethod1Init, NULL, vmR3HaltMethod1Halt, vmR3DefaultWait, vmR3DefaultNotifyFF },
798 //{ VMHALTMETHOD_2, vmR3HaltMethod2Init, vmR3HaltMethod2Term, vmR3HaltMethod2DoHalt, vmR3HaltMethod2Wait, vmR3HaltMethod2NotifyFF },
799 { VMHALTMETHOD_GLOBAL_1,vmR3HaltGlobal1Init, NULL, vmR3HaltGlobal1Halt, vmR3HaltGlobal1Wait, vmR3HaltGlobal1NotifyFF },
800};
801
802
803/**
804 * Notify the emulation thread (EMT) about pending Forced Action (FF).
805 *
806 * This function is called by thread other than EMT to make
807 * sure EMT wakes up and promptly service an FF request.
808 *
809 * @param pVM VM handle.
810 * @param fNotifiedREM Set if REM have already been notified. If clear the
811 * generic REMR3NotifyFF() method is called.
812 */
813VMR3DECL(void) VMR3NotifyFF(PVM pVM, bool fNotifiedREM)
814{
815 LogFlow(("VMR3NotifyFF:\n"));
816 g_aHaltMethods[pVM->vm.s.iHaltMethod].pfnNotifyFF(pVM, fNotifiedREM);
817}
818
819
820/**
821 * Halted VM Wait.
822 * Any external event will unblock the thread.
823 *
824 * @returns VINF_SUCCESS unless a fatal error occured. In the latter
825 * case an appropriate status code is returned.
826 * @param pVM VM handle.
827 * @param fIgnoreInterrupts If set the VM_FF_INTERRUPT flags is ignored.
828 * @thread The emulation thread.
829 */
830VMR3DECL(int) VMR3WaitHalted(PVM pVM, bool fIgnoreInterrupts)
831{
832 LogFlow(("VMR3WaitHalted: fIgnoreInterrupts=%d\n", fIgnoreInterrupts));
833
834 /*
835 * Check Relevant FFs.
836 */
837 const uint32_t fMask = !fIgnoreInterrupts
838 ? VM_FF_EXTERNAL_HALTED_MASK
839 : VM_FF_EXTERNAL_HALTED_MASK & ~(VM_FF_INTERRUPT_APIC | VM_FF_INTERRUPT_PIC);
840 if (VM_FF_ISPENDING(pVM, fMask))
841 {
842 LogFlow(("VMR3WaitHalted: returns VINF_SUCCESS (FF %#x)\n", pVM->fForcedActions));
843 return VINF_SUCCESS;
844 }
845
846 /*
847 * The yielder is suspended while we're halting.
848 */
849 VMMR3YieldSuspend(pVM);
850
851 /*
852 * Record halt averages for the last second.
853 */
854 uint64_t u64Now = RTTimeNanoTS();
855 int64_t off = u64Now - pVM->vm.s.u64HaltsStartTS;
856 if (off > 1000000000)
857 {
858 if (off > _4G || !pVM->vm.s.cHalts)
859 {
860 pVM->vm.s.HaltInterval = 1000000000 /* 1 sec */;
861 pVM->vm.s.HaltFrequency = 1;
862 }
863 else
864 {
865 pVM->vm.s.HaltInterval = (uint32_t)off / pVM->vm.s.cHalts;
866 pVM->vm.s.HaltFrequency = ASMMultU64ByU32DivByU32(pVM->vm.s.cHalts, 1000000000, (uint32_t)off);
867 }
868 pVM->vm.s.u64HaltsStartTS = u64Now;
869 pVM->vm.s.cHalts = 0;
870 }
871 pVM->vm.s.cHalts++;
872
873 /*
874 * Do the halt.
875 */
876 int rc = g_aHaltMethods[pVM->vm.s.iHaltMethod].pfnHalt(pVM, fMask, u64Now);
877
878 /*
879 * Resume the yielder and tell the world we're not blocking.
880 */
881 ASMAtomicXchgU32(&pVM->vm.s.fWait, 0);
882 VMMR3YieldResume(pVM);
883
884 LogFlow(("VMR3WaitHalted: returns %Vrc (FF %#x)\n", rc, pVM->fForcedActions));
885 return rc;
886}
887
888
889/**
890 * Suspended VM Wait.
891 * Only a handful of forced actions will cause the function to
892 * return to the caller.
893 *
894 * @returns VINF_SUCCESS unless a fatal error occured. In the latter
895 * case an appropriate status code is returned.
896 * @param pVM VM handle.
897 * @thread The emulation thread.
898 */
899VMR3DECL(int) VMR3Wait(PVM pVM)
900{
901 LogFlow(("VMR3Wait:\n"));
902
903 /*
904 * Check Relevant FFs.
905 */
906 if (VM_FF_ISPENDING(pVM, VM_FF_EXTERNAL_SUSPENDED_MASK))
907 {
908 LogFlow(("VMR3Wait: returns VINF_SUCCESS (FF %#x)\n", pVM->fForcedActions));
909 return VINF_SUCCESS;
910 }
911
912 /*
913 * Do waiting according to the halt method (so VMR3NotifyFF
914 * doesn't have to special case anything).
915 */
916 int rc = g_aHaltMethods[pVM->vm.s.iHaltMethod].pfnWait(pVM);
917 LogFlow(("VMR3Wait: returns %Vrc (FF %#x)\n", rc, pVM->fForcedActions));
918 return rc;
919}
920
921
922/**
923 * Changes the halt method.
924 *
925 * @returns VBox status code.
926 * @param pVM The VM handle.
927 * @param enmHaltMethod The new halt method.
928 * @thread EMT.
929 */
930int vmR3SetHaltMethod(PVM pVM, VMHALTMETHOD enmHaltMethod)
931{
932 VM_ASSERT_EMT(pVM);
933 AssertReturn(enmHaltMethod > VMHALTMETHOD_INVALID && enmHaltMethod < VMHALTMETHOD_END, VERR_INVALID_PARAMETER);
934
935 /*
936 * Resolve default (can be overridden in the configuration).
937 */
938 if (enmHaltMethod == VMHALTMETHOD_DEFAULT)
939 {
940 uint32_t u32;
941 int rc = CFGMR3QueryU32(CFGMR3GetChild(CFGMR3GetRoot(pVM), "VM"), "HaltMethod", &u32);
942 if (VBOX_SUCCESS(rc))
943 {
944 enmHaltMethod = (VMHALTMETHOD)u32;
945 if (enmHaltMethod <= VMHALTMETHOD_INVALID || enmHaltMethod >= VMHALTMETHOD_END)
946 return VMSetError(pVM, VERR_INVALID_PARAMETER, RT_SRC_POS, N_("Invalid VM/HaltMethod value %d."), enmHaltMethod);
947 }
948 else if (rc == VERR_CFGM_VALUE_NOT_FOUND || rc == VERR_CFGM_CHILD_NOT_FOUND)
949 return VMSetError(pVM, rc, RT_SRC_POS, N_("Failed to Query VM/HaltMethod as uint32_t."));
950 else
951 enmHaltMethod = VMHALTMETHOD_GLOBAL_1;
952 //enmHaltMethod = VMHALTMETHOD_1;
953 //enmHaltMethod = VMHALTMETHOD_OLD;
954 }
955 LogRel(("VM: Halt method %s (%d)\n", vmR3GetHaltMethodName(enmHaltMethod), enmHaltMethod));
956
957 /*
958 * Find the descriptor.
959 */
960 unsigned i = 0;
961 while ( i < RT_ELEMENTS(g_aHaltMethods)
962 && g_aHaltMethods[i].enmHaltMethod != enmHaltMethod)
963 i++;
964 AssertReturn(i < RT_ELEMENTS(g_aHaltMethods), VERR_INVALID_PARAMETER);
965
966 /*
967 * Terminate the old one.
968 */
969 if ( pVM->vm.s.enmHaltMethod != VMHALTMETHOD_INVALID
970 && g_aHaltMethods[pVM->vm.s.iHaltMethod].pfnTerm)
971 {
972 g_aHaltMethods[pVM->vm.s.iHaltMethod].pfnTerm(pVM);
973 pVM->vm.s.enmHaltMethod = VMHALTMETHOD_INVALID;
974 }
975
976 /*
977 * Init the new one.
978 */
979 memset(&pVM->vm.s.Halt, 0, sizeof(pVM->vm.s.Halt));
980 if (g_aHaltMethods[i].pfnInit)
981 {
982 int rc = g_aHaltMethods[i].pfnInit(pVM);
983 AssertRCReturn(rc, rc);
984 }
985 pVM->vm.s.enmHaltMethod = enmHaltMethod;
986 ASMAtomicXchgU32(&pVM->vm.s.iHaltMethod, i);
987 return VINF_SUCCESS;
988}
989
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