VirtualBox

source: vbox/trunk/src/VBox/VMM/VM.cpp@ 31331

Last change on this file since 31331 was 31331, checked in by vboxsync, 14 years ago

Added VMR3SetCpuPriority

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 142.9 KB
Line 
1/* $Id: VM.cpp 31331 2010-08-03 12:22:53Z vboxsync $ */
2/** @file
3 * VM - Virtual Machine
4 */
5
6/*
7 * Copyright (C) 2006-2010 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/** @page pg_vm VM API
19 *
20 * This is the encapsulating bit. It provides the APIs that Main and VBoxBFE
21 * use to create a VMM instance for running a guest in. It also provides
22 * facilities for queuing request for execution in EMT (serialization purposes
23 * mostly) and for reporting error back to the VMM user (Main/VBoxBFE).
24 *
25 *
26 * @section sec_vm_design Design Critique / Things To Do
27 *
28 * In hindsight this component is a big design mistake, all this stuff really
29 * belongs in the VMM component. It just seemed like a kind of ok idea at a
30 * time when the VMM bit was a kind of vague. 'VM' also happend to be the name
31 * of the per-VM instance structure (see vm.h), so it kind of made sense.
32 * However as it turned out, VMM(.cpp) is almost empty all it provides in ring-3
33 * is some minor functionally and some "routing" services.
34 *
35 * Fixing this is just a matter of some more or less straight forward
36 * refactoring, the question is just when someone will get to it. Moving the EMT
37 * would be a good start.
38 *
39 */
40
41/*******************************************************************************
42* Header Files *
43*******************************************************************************/
44#define LOG_GROUP LOG_GROUP_VM
45#include <VBox/cfgm.h>
46#include <VBox/vmm.h>
47#include <VBox/gvmm.h>
48#include <VBox/mm.h>
49#include <VBox/cpum.h>
50#include <VBox/selm.h>
51#include <VBox/trpm.h>
52#include <VBox/dbgf.h>
53#include <VBox/pgm.h>
54#include <VBox/pdmapi.h>
55#include <VBox/pdmcritsect.h>
56#include <VBox/em.h>
57#include <VBox/rem.h>
58#include <VBox/tm.h>
59#include <VBox/stam.h>
60#include <VBox/patm.h>
61#include <VBox/csam.h>
62#include <VBox/iom.h>
63#include <VBox/ssm.h>
64#include <VBox/hwaccm.h>
65#include "VMInternal.h"
66#include <VBox/vm.h>
67#include <VBox/uvm.h>
68
69#include <VBox/sup.h>
70#include <VBox/dbg.h>
71#include <VBox/err.h>
72#include <VBox/param.h>
73#include <VBox/log.h>
74#include <iprt/assert.h>
75#include <iprt/alloc.h>
76#include <iprt/asm.h>
77#include <iprt/env.h>
78#include <iprt/string.h>
79#include <iprt/time.h>
80#include <iprt/semaphore.h>
81#include <iprt/thread.h>
82
83
84/*******************************************************************************
85* Structures and Typedefs *
86*******************************************************************************/
87/**
88 * VM destruction callback registration record.
89 */
90typedef struct VMATDTOR
91{
92 /** Pointer to the next record in the list. */
93 struct VMATDTOR *pNext;
94 /** Pointer to the callback function. */
95 PFNVMATDTOR pfnAtDtor;
96 /** The user argument. */
97 void *pvUser;
98} VMATDTOR;
99/** Pointer to a VM destruction callback registration record. */
100typedef VMATDTOR *PVMATDTOR;
101
102
103/*******************************************************************************
104* Global Variables *
105*******************************************************************************/
106/** Pointer to the list of VMs. */
107static PUVM g_pUVMsHead = NULL;
108
109/** Pointer to the list of at VM destruction callbacks. */
110static PVMATDTOR g_pVMAtDtorHead = NULL;
111/** Lock the g_pVMAtDtorHead list. */
112#define VM_ATDTOR_LOCK() do { } while (0)
113/** Unlock the g_pVMAtDtorHead list. */
114#define VM_ATDTOR_UNLOCK() do { } while (0)
115
116
117/*******************************************************************************
118* Internal Functions *
119*******************************************************************************/
120static int vmR3CreateUVM(uint32_t cCpus, PUVM *ppUVM);
121static int vmR3CreateU(PUVM pUVM, uint32_t cCpus, PFNCFGMCONSTRUCTOR pfnCFGMConstructor, void *pvUserCFGM);
122static int vmR3InitRing3(PVM pVM, PUVM pUVM);
123static int vmR3InitVMCpu(PVM pVM);
124static int vmR3InitRing0(PVM pVM);
125static int vmR3InitGC(PVM pVM);
126static int vmR3InitDoCompleted(PVM pVM, VMINITCOMPLETED enmWhat);
127static DECLCALLBACK(size_t) vmR3LogPrefixCallback(PRTLOGGER pLogger, char *pchBuf, size_t cchBuf, void *pvUser);
128static void vmR3DestroyUVM(PUVM pUVM, uint32_t cMilliesEMTWait);
129static void vmR3AtDtor(PVM pVM);
130static bool vmR3ValidateStateTransition(VMSTATE enmStateOld, VMSTATE enmStateNew);
131static void vmR3DoAtState(PVM pVM, PUVM pUVM, VMSTATE enmStateNew, VMSTATE enmStateOld);
132static int vmR3TrySetState(PVM pVM, const char *pszWho, unsigned cTransitions, ...);
133static void vmR3SetStateLocked(PVM pVM, PUVM pUVM, VMSTATE enmStateNew, VMSTATE enmStateOld);
134static void vmR3SetState(PVM pVM, VMSTATE enmStateNew, VMSTATE enmStateOld);
135static int vmR3SetErrorU(PUVM pUVM, int rc, RT_SRC_POS_DECL, const char *pszFormat, ...);
136
137
138/**
139 * Do global VMM init.
140 *
141 * @returns VBox status code.
142 */
143VMMR3DECL(int) VMR3GlobalInit(void)
144{
145 /*
146 * Only once.
147 */
148 static bool volatile s_fDone = false;
149 if (s_fDone)
150 return VINF_SUCCESS;
151
152 /*
153 * We're done.
154 */
155 s_fDone = true;
156 return VINF_SUCCESS;
157}
158
159
160
161/**
162 * Creates a virtual machine by calling the supplied configuration constructor.
163 *
164 * On successful returned the VM is powered, i.e. VMR3PowerOn() should be
165 * called to start the execution.
166 *
167 * @returns 0 on success.
168 * @returns VBox error code on failure.
169 * @param cCpus Number of virtual CPUs for the new VM.
170 * @param pfnVMAtError Pointer to callback function for setting VM
171 * errors. This was added as an implicit call to
172 * VMR3AtErrorRegister() since there is no way the
173 * caller can get to the VM handle early enough to
174 * do this on its own.
175 * This is called in the context of an EMT.
176 * @param pvUserVM The user argument passed to pfnVMAtError.
177 * @param pfnCFGMConstructor Pointer to callback function for constructing the VM configuration tree.
178 * This is called in the context of an EMT0.
179 * @param pvUserCFGM The user argument passed to pfnCFGMConstructor.
180 * @param ppVM Where to store the 'handle' of the created VM.
181 */
182VMMR3DECL(int) VMR3Create(uint32_t cCpus, PFNVMATERROR pfnVMAtError, void *pvUserVM, PFNCFGMCONSTRUCTOR pfnCFGMConstructor, void *pvUserCFGM, PVM *ppVM)
183{
184 LogFlow(("VMR3Create: cCpus=%RU32 pfnVMAtError=%p pvUserVM=%p pfnCFGMConstructor=%p pvUserCFGM=%p ppVM=%p\n",
185 cCpus, pfnVMAtError, pvUserVM, pfnCFGMConstructor, pvUserCFGM, ppVM));
186
187 /*
188 * Because of the current hackiness of the applications
189 * we'll have to initialize global stuff from here.
190 * Later the applications will take care of this in a proper way.
191 */
192 static bool fGlobalInitDone = false;
193 if (!fGlobalInitDone)
194 {
195 int rc = VMR3GlobalInit();
196 if (RT_FAILURE(rc))
197 return rc;
198 fGlobalInitDone = true;
199 }
200
201 /*
202 * Validate input.
203 */
204 AssertLogRelMsgReturn(cCpus > 0 && cCpus <= VMM_MAX_CPU_COUNT, ("%RU32\n", cCpus), VERR_TOO_MANY_CPUS);
205
206 /*
207 * Create the UVM so we can register the at-error callback
208 * and consoliate a bit of cleanup code.
209 */
210 PUVM pUVM = NULL; /* shuts up gcc */
211 int rc = vmR3CreateUVM(cCpus, &pUVM);
212 if (RT_FAILURE(rc))
213 return rc;
214 if (pfnVMAtError)
215 rc = VMR3AtErrorRegisterU(pUVM, pfnVMAtError, pvUserVM);
216 if (RT_SUCCESS(rc))
217 {
218 /*
219 * Initialize the support library creating the session for this VM.
220 */
221 rc = SUPR3Init(&pUVM->vm.s.pSession);
222 if (RT_SUCCESS(rc))
223 {
224 /*
225 * Call vmR3CreateU in the EMT thread and wait for it to finish.
226 *
227 * Note! VMCPUID_ANY is used here because VMR3ReqQueueU would have trouble
228 * submitting a request to a specific VCPU without a pVM. So, to make
229 * sure init is running on EMT(0), vmR3EmulationThreadWithId makes sure
230 * that only EMT(0) is servicing VMCPUID_ANY requests when pVM is NULL.
231 */
232 PVMREQ pReq;
233 rc = VMR3ReqCallU(pUVM, VMCPUID_ANY, &pReq, RT_INDEFINITE_WAIT, VMREQFLAGS_VBOX_STATUS,
234 (PFNRT)vmR3CreateU, 4, pUVM, cCpus, pfnCFGMConstructor, pvUserCFGM);
235 if (RT_SUCCESS(rc))
236 {
237 rc = pReq->iStatus;
238 VMR3ReqFree(pReq);
239 if (RT_SUCCESS(rc))
240 {
241 /*
242 * Success!
243 */
244 *ppVM = pUVM->pVM;
245 LogFlow(("VMR3Create: returns VINF_SUCCESS *ppVM=%p\n", *ppVM));
246 return VINF_SUCCESS;
247 }
248 }
249 else
250 AssertMsgFailed(("VMR3ReqCallU failed rc=%Rrc\n", rc));
251
252 /*
253 * An error occurred during VM creation. Set the error message directly
254 * using the initial callback, as the callback list doesn't exist yet.
255 */
256 const char *pszError = NULL;
257 switch (rc)
258 {
259 case VERR_VMX_IN_VMX_ROOT_MODE:
260#ifdef RT_OS_LINUX
261 pszError = N_("VirtualBox can't operate in VMX root mode. "
262 "Please disable the KVM kernel extension, recompile your kernel and reboot");
263#else
264 pszError = N_("VirtualBox can't operate in VMX root mode. Please close all other virtualization programs.");
265#endif
266 break;
267
268 case VERR_SVM_IN_USE:
269#ifdef RT_OS_LINUX
270 pszError = N_("VirtualBox can't enable the AMD-V extension. "
271 "Please disable the KVM kernel extension, recompile your kernel and reboot");
272#else
273 pszError = N_("VirtualBox can't enable the AMD-V extension. Please close all other virtualization programs.");
274#endif
275 break;
276
277 case VERR_VERSION_MISMATCH:
278 pszError = N_("VMMR0 driver version mismatch. Please terminate all VMs, make sure that "
279 "VBoxNetDHCP is not running and try again. If you still get this error, "
280 "re-install VirtualBox");
281 break;
282
283#ifdef RT_OS_LINUX
284 case VERR_SUPDRV_COMPONENT_NOT_FOUND:
285 pszError = N_("One of the kernel modules was not successfully loaded. Make sure "
286 "that no kernel modules from an older version of VirtualBox exist. "
287 "Then try to recompile and reload the kernel modules by executing "
288 "'/etc/init.d/vboxdrv setup' as root");
289 break;
290#endif
291
292 case VERR_RAW_MODE_INVALID_SMP:
293 pszError = N_("VT-x/AMD-V is either not available on your host or disabled. "
294 "VirtualBox requires this hardware extension to emulate more than one "
295 "guest CPU");
296 break;
297
298 case VERR_SUPDRV_KERNEL_TOO_OLD_FOR_VTX:
299#ifdef RT_OS_LINUX
300 pszError = N_("Because the host kernel is too old, VirtualBox cannot enable the VT-x "
301 "extension. Either upgrade your kernel to Linux 2.6.13 or later or disable "
302 "the VT-x extension in the VM settings. Note that without VT-x you have "
303 "to reduce the number of guest CPUs to one");
304#else
305 pszError = N_("Because the host kernel is too old, VirtualBox cannot enable the VT-x "
306 "extension. Either upgrade your kernel or disable the VT-x extension in the "
307 "VM settings. Note that without VT-x you have to reduce the number of guest "
308 "CPUs to one");
309#endif
310 break;
311
312 default:
313 pszError = N_("Unknown error creating VM");
314 break;
315 }
316 vmR3SetErrorU(pUVM, rc, RT_SRC_POS, pszError, rc);
317 }
318 else
319 {
320 /*
321 * An error occurred at support library initialization time (before the
322 * VM could be created). Set the error message directly using the
323 * initial callback, as the callback list doesn't exist yet.
324 */
325 const char *pszError;
326 switch (rc)
327 {
328 case VERR_VM_DRIVER_LOAD_ERROR:
329#ifdef RT_OS_LINUX
330 pszError = N_("VirtualBox kernel driver not loaded. The vboxdrv kernel module "
331 "was either not loaded or /dev/vboxdrv is not set up properly. "
332 "Re-setup the kernel module by executing "
333 "'/etc/init.d/vboxdrv setup' as root");
334#else
335 pszError = N_("VirtualBox kernel driver not loaded");
336#endif
337 break;
338 case VERR_VM_DRIVER_OPEN_ERROR:
339 pszError = N_("VirtualBox kernel driver cannot be opened");
340 break;
341 case VERR_VM_DRIVER_NOT_ACCESSIBLE:
342#ifdef VBOX_WITH_HARDENING
343 /* This should only happen if the executable wasn't hardened - bad code/build. */
344 pszError = N_("VirtualBox kernel driver not accessible, permission problem. "
345 "Re-install VirtualBox. If you are building it yourself, you "
346 "should make sure it installed correctly and that the setuid "
347 "bit is set on the executables calling VMR3Create.");
348#else
349 /* This should only happen when mixing builds or with the usual /dev/vboxdrv access issues. */
350# if defined(RT_OS_DARWIN)
351 pszError = N_("VirtualBox KEXT is not accessible, permission problem. "
352 "If you have built VirtualBox yourself, make sure that you do not "
353 "have the vboxdrv KEXT from a different build or installation loaded.");
354# elif defined(RT_OS_LINUX)
355 pszError = N_("VirtualBox kernel driver is not accessible, permission problem. "
356 "If you have built VirtualBox yourself, make sure that you do "
357 "not have the vboxdrv kernel module from a different build or "
358 "installation loaded. Also, make sure the vboxdrv udev rule gives "
359 "you the permission you need to access the device.");
360# elif defined(RT_OS_WINDOWS)
361 pszError = N_("VirtualBox kernel driver is not accessible, permission problem.");
362# else /* solaris, freebsd, ++. */
363 pszError = N_("VirtualBox kernel module is not accessible, permission problem. "
364 "If you have built VirtualBox yourself, make sure that you do "
365 "not have the vboxdrv kernel module from a different install loaded.");
366# endif
367#endif
368 break;
369 case VERR_INVALID_HANDLE: /** @todo track down and fix this error. */
370 case VERR_VM_DRIVER_NOT_INSTALLED:
371#ifdef RT_OS_LINUX
372 pszError = N_("VirtualBox kernel driver not installed. The vboxdrv kernel module "
373 "was either not loaded or /dev/vboxdrv was not created for some "
374 "reason. Re-setup the kernel module by executing "
375 "'/etc/init.d/vboxdrv setup' as root");
376#else
377 pszError = N_("VirtualBox kernel driver not installed");
378#endif
379 break;
380 case VERR_NO_MEMORY:
381 pszError = N_("VirtualBox support library out of memory");
382 break;
383 case VERR_VERSION_MISMATCH:
384 case VERR_VM_DRIVER_VERSION_MISMATCH:
385 pszError = N_("The VirtualBox support driver which is running is from a different "
386 "version of VirtualBox. You can correct this by stopping all "
387 "running instances of VirtualBox and reinstalling the software.");
388 break;
389 default:
390 pszError = N_("Unknown error initializing kernel driver");
391 AssertMsgFailed(("Add error message for rc=%d (%Rrc)\n", rc, rc));
392 }
393 vmR3SetErrorU(pUVM, rc, RT_SRC_POS, pszError, rc);
394 }
395 }
396
397 /* cleanup */
398 vmR3DestroyUVM(pUVM, 2000);
399 LogFlow(("VMR3Create: returns %Rrc\n", rc));
400 return rc;
401}
402
403
404/**
405 * Creates the UVM.
406 *
407 * This will not initialize the support library even if vmR3DestroyUVM
408 * will terminate that.
409 *
410 * @returns VBox status code.
411 * @param cCpus Number of virtual CPUs
412 * @param ppUVM Where to store the UVM pointer.
413 */
414static int vmR3CreateUVM(uint32_t cCpus, PUVM *ppUVM)
415{
416 uint32_t i;
417
418 /*
419 * Create and initialize the UVM.
420 */
421 PUVM pUVM = (PUVM)RTMemPageAllocZ(RT_OFFSETOF(UVM, aCpus[cCpus]));
422 AssertReturn(pUVM, VERR_NO_MEMORY);
423 pUVM->u32Magic = UVM_MAGIC;
424 pUVM->cCpus = cCpus;
425
426 AssertCompile(sizeof(pUVM->vm.s) <= sizeof(pUVM->vm.padding));
427
428 pUVM->vm.s.ppAtStateNext = &pUVM->vm.s.pAtState;
429 pUVM->vm.s.ppAtErrorNext = &pUVM->vm.s.pAtError;
430 pUVM->vm.s.ppAtRuntimeErrorNext = &pUVM->vm.s.pAtRuntimeError;
431
432 pUVM->vm.s.enmHaltMethod = VMHALTMETHOD_BOOTSTRAP;
433
434 /* Initialize the VMCPU array in the UVM. */
435 for (i = 0; i < cCpus; i++)
436 {
437 pUVM->aCpus[i].pUVM = pUVM;
438 pUVM->aCpus[i].idCpu = i;
439 }
440
441 /* Allocate a TLS entry to store the VMINTUSERPERVMCPU pointer. */
442 int rc = RTTlsAllocEx(&pUVM->vm.s.idxTLS, NULL);
443 AssertRC(rc);
444 if (RT_SUCCESS(rc))
445 {
446 /* Allocate a halt method event semaphore for each VCPU. */
447 for (i = 0; i < cCpus; i++)
448 pUVM->aCpus[i].vm.s.EventSemWait = NIL_RTSEMEVENT;
449 for (i = 0; i < cCpus; i++)
450 {
451 rc = RTSemEventCreate(&pUVM->aCpus[i].vm.s.EventSemWait);
452 if (RT_FAILURE(rc))
453 break;
454 }
455 if (RT_SUCCESS(rc))
456 {
457 rc = RTCritSectInit(&pUVM->vm.s.AtStateCritSect);
458 if (RT_SUCCESS(rc))
459 {
460 rc = RTCritSectInit(&pUVM->vm.s.AtErrorCritSect);
461 if (RT_SUCCESS(rc))
462 {
463 /*
464 * Init fundamental (sub-)components - STAM, MMR3Heap and PDMLdr.
465 */
466 rc = STAMR3InitUVM(pUVM);
467 if (RT_SUCCESS(rc))
468 {
469 rc = MMR3InitUVM(pUVM);
470 if (RT_SUCCESS(rc))
471 {
472 rc = PDMR3InitUVM(pUVM);
473 if (RT_SUCCESS(rc))
474 {
475 /*
476 * Start the emulation threads for all VMCPUs.
477 */
478 for (i = 0; i < cCpus; i++)
479 {
480 rc = RTThreadCreateF(&pUVM->aCpus[i].vm.s.ThreadEMT, vmR3EmulationThread, &pUVM->aCpus[i], _1M,
481 RTTHREADTYPE_EMULATION, RTTHREADFLAGS_WAITABLE,
482 cCpus > 1 ? "EMT-%u" : "EMT", i);
483 if (RT_FAILURE(rc))
484 break;
485
486 pUVM->aCpus[i].vm.s.NativeThreadEMT = RTThreadGetNative(pUVM->aCpus[i].vm.s.ThreadEMT);
487 }
488
489 if (RT_SUCCESS(rc))
490 {
491 *ppUVM = pUVM;
492 return VINF_SUCCESS;
493 }
494
495 /* bail out. */
496 while (i-- > 0)
497 {
498 /** @todo rainy day: terminate the EMTs. */
499 }
500 PDMR3TermUVM(pUVM);
501 }
502 MMR3TermUVM(pUVM);
503 }
504 STAMR3TermUVM(pUVM);
505 }
506 RTCritSectDelete(&pUVM->vm.s.AtErrorCritSect);
507 }
508 RTCritSectDelete(&pUVM->vm.s.AtStateCritSect);
509 }
510 }
511 for (i = 0; i < cCpus; i++)
512 {
513 RTSemEventDestroy(pUVM->aCpus[i].vm.s.EventSemWait);
514 pUVM->aCpus[i].vm.s.EventSemWait = NIL_RTSEMEVENT;
515 }
516 RTTlsFree(pUVM->vm.s.idxTLS);
517 }
518 RTMemPageFree(pUVM, sizeof(*pUVM));
519 return rc;
520}
521
522
523/**
524 * Creates and initializes the VM.
525 *
526 * @thread EMT
527 */
528static int vmR3CreateU(PUVM pUVM, uint32_t cCpus, PFNCFGMCONSTRUCTOR pfnCFGMConstructor, void *pvUserCFGM)
529{
530 int rc = VINF_SUCCESS;
531
532 /*
533 * Load the VMMR0.r0 module so that we can call GVMMR0CreateVM.
534 */
535 rc = PDMR3LdrLoadVMMR0U(pUVM);
536 if (RT_FAILURE(rc))
537 {
538 /** @todo we need a cleaner solution for this (VERR_VMX_IN_VMX_ROOT_MODE).
539 * bird: what about moving the message down here? Main picks the first message, right? */
540 if (rc == VERR_VMX_IN_VMX_ROOT_MODE)
541 return rc; /* proper error message set later on */
542 return vmR3SetErrorU(pUVM, rc, RT_SRC_POS, N_("Failed to load VMMR0.r0"));
543 }
544
545 /*
546 * Request GVMM to create a new VM for us.
547 */
548 GVMMCREATEVMREQ CreateVMReq;
549 CreateVMReq.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
550 CreateVMReq.Hdr.cbReq = sizeof(CreateVMReq);
551 CreateVMReq.pSession = pUVM->vm.s.pSession;
552 CreateVMReq.pVMR0 = NIL_RTR0PTR;
553 CreateVMReq.pVMR3 = NULL;
554 CreateVMReq.cCpus = cCpus;
555 rc = SUPR3CallVMMR0Ex(NIL_RTR0PTR, NIL_VMCPUID, VMMR0_DO_GVMM_CREATE_VM, 0, &CreateVMReq.Hdr);
556 if (RT_SUCCESS(rc))
557 {
558 PVM pVM = pUVM->pVM = CreateVMReq.pVMR3;
559 AssertRelease(VALID_PTR(pVM));
560 AssertRelease(pVM->pVMR0 == CreateVMReq.pVMR0);
561 AssertRelease(pVM->pSession == pUVM->vm.s.pSession);
562 AssertRelease(pVM->cCpus == cCpus);
563 AssertRelease(pVM->uCpuPriority == 100);
564 AssertRelease(pVM->offVMCPU == RT_UOFFSETOF(VM, aCpus));
565
566 Log(("VMR3Create: Created pUVM=%p pVM=%p pVMR0=%p hSelf=%#x cCpus=%RU32\n",
567 pUVM, pVM, pVM->pVMR0, pVM->hSelf, pVM->cCpus));
568
569 /*
570 * Initialize the VM structure and our internal data (VMINT).
571 */
572 pVM->pUVM = pUVM;
573
574 for (VMCPUID i = 0; i < pVM->cCpus; i++)
575 {
576 pVM->aCpus[i].pUVCpu = &pUVM->aCpus[i];
577 pVM->aCpus[i].idCpu = i;
578 pVM->aCpus[i].hNativeThread = pUVM->aCpus[i].vm.s.NativeThreadEMT;
579 Assert(pVM->aCpus[i].hNativeThread != NIL_RTNATIVETHREAD);
580
581 pUVM->aCpus[i].pVCpu = &pVM->aCpus[i];
582 pUVM->aCpus[i].pVM = pVM;
583 }
584
585
586 /*
587 * Init the configuration.
588 */
589 rc = CFGMR3Init(pVM, pfnCFGMConstructor, pvUserCFGM);
590 if (RT_SUCCESS(rc))
591 {
592 PCFGMNODE pRoot = CFGMR3GetRoot(pVM);
593 rc = CFGMR3QueryBoolDef(pRoot, "HwVirtExtForced", &pVM->fHwVirtExtForced, false);
594 if (RT_SUCCESS(rc) && pVM->fHwVirtExtForced)
595 pVM->fHWACCMEnabled = true;
596
597 /*
598 * If executing in fake suplib mode disable RR3 and RR0 in the config.
599 */
600 const char *psz = RTEnvGet("VBOX_SUPLIB_FAKE");
601 if (psz && !strcmp(psz, "fake"))
602 {
603 CFGMR3RemoveValue(pRoot, "RawR3Enabled");
604 CFGMR3InsertInteger(pRoot, "RawR3Enabled", 0);
605 CFGMR3RemoveValue(pRoot, "RawR0Enabled");
606 CFGMR3InsertInteger(pRoot, "RawR0Enabled", 0);
607 }
608
609 /*
610 * Make sure the CPU count in the config data matches.
611 */
612 if (RT_SUCCESS(rc))
613 {
614 uint32_t cCPUsCfg;
615 rc = CFGMR3QueryU32Def(pRoot, "NumCPUs", &cCPUsCfg, 1);
616 AssertLogRelMsgRC(rc, ("Configuration error: Querying \"NumCPUs\" as integer failed, rc=%Rrc\n", rc));
617 if (RT_SUCCESS(rc) && cCPUsCfg != cCpus)
618 {
619 AssertLogRelMsgFailed(("Configuration error: \"NumCPUs\"=%RU32 and VMR3CreateVM::cCpus=%RU32 does not match!\n",
620 cCPUsCfg, cCpus));
621 rc = VERR_INVALID_PARAMETER;
622 }
623 }
624 if (RT_SUCCESS(rc))
625 {
626 rc = CFGMR3QueryU32Def(pRoot, "CpuPriority", &pVM->uCpuPriority, 100);
627 AssertLogRelMsgRC(rc, ("Configuration error: Querying \"CpuPriority\" as integer failed, rc=%Rrc\n", rc));
628
629 /*
630 * Init the ring-3 components and ring-3 per cpu data, finishing it off
631 * by a relocation round (intermediate context finalization will do this).
632 */
633 rc = vmR3InitRing3(pVM, pUVM);
634 if (RT_SUCCESS(rc))
635 {
636 rc = vmR3InitVMCpu(pVM);
637 if (RT_SUCCESS(rc))
638 rc = PGMR3FinalizeMappings(pVM);
639 if (RT_SUCCESS(rc))
640 {
641
642 LogFlow(("Ring-3 init succeeded\n"));
643
644 /*
645 * Init the Ring-0 components.
646 */
647 rc = vmR3InitRing0(pVM);
648 if (RT_SUCCESS(rc))
649 {
650 /* Relocate again, because some switcher fixups depends on R0 init results. */
651 VMR3Relocate(pVM, 0);
652
653#ifdef VBOX_WITH_DEBUGGER
654 /*
655 * Init the tcp debugger console if we're building
656 * with debugger support.
657 */
658 void *pvUser = NULL;
659 rc = DBGCTcpCreate(pVM, &pvUser);
660 if ( RT_SUCCESS(rc)
661 || rc == VERR_NET_ADDRESS_IN_USE)
662 {
663 pUVM->vm.s.pvDBGC = pvUser;
664#endif
665 /*
666 * Init the Guest Context components.
667 */
668 rc = vmR3InitGC(pVM);
669 if (RT_SUCCESS(rc))
670 {
671 /*
672 * Now we can safely set the VM halt method to default.
673 */
674 rc = vmR3SetHaltMethodU(pUVM, VMHALTMETHOD_DEFAULT);
675 if (RT_SUCCESS(rc))
676 {
677 /*
678 * Set the state and link into the global list.
679 */
680 vmR3SetState(pVM, VMSTATE_CREATED, VMSTATE_CREATING);
681 pUVM->pNext = g_pUVMsHead;
682 g_pUVMsHead = pUVM;
683
684#ifdef LOG_ENABLED
685 RTLogSetCustomPrefixCallback(NULL, vmR3LogPrefixCallback, pUVM);
686#endif
687 return VINF_SUCCESS;
688 }
689 }
690#ifdef VBOX_WITH_DEBUGGER
691 DBGCTcpTerminate(pVM, pUVM->vm.s.pvDBGC);
692 pUVM->vm.s.pvDBGC = NULL;
693 }
694#endif
695 //..
696 }
697 }
698 vmR3Destroy(pVM);
699 }
700 }
701 //..
702
703 /* Clean CFGM. */
704 int rc2 = CFGMR3Term(pVM);
705 AssertRC(rc2);
706 }
707
708 /*
709 * Do automatic cleanups while the VM structure is still alive and all
710 * references to it are still working.
711 */
712 PDMR3CritSectTerm(pVM);
713
714 /*
715 * Drop all references to VM and the VMCPU structures, then
716 * tell GVMM to destroy the VM.
717 */
718 pUVM->pVM = NULL;
719 for (VMCPUID i = 0; i < pUVM->cCpus; i++)
720 {
721 pUVM->aCpus[i].pVM = NULL;
722 pUVM->aCpus[i].pVCpu = NULL;
723 }
724 Assert(pUVM->vm.s.enmHaltMethod == VMHALTMETHOD_BOOTSTRAP);
725
726 if (pUVM->cCpus > 1)
727 {
728 /* Poke the other EMTs since they may have stale pVM and pVCpu references
729 on the stack (see VMR3WaitU for instance) if they've been awakened after
730 VM creation. */
731 for (VMCPUID i = 1; i < pUVM->cCpus; i++)
732 VMR3NotifyCpuFFU(&pUVM->aCpus[i], 0);
733 RTThreadSleep(RT_MIN(100 + 25 *(pUVM->cCpus - 1), 500)); /* very sophisticated */
734 }
735
736 int rc2 = SUPR3CallVMMR0Ex(CreateVMReq.pVMR0, 0 /*idCpu*/, VMMR0_DO_GVMM_DESTROY_VM, 0, NULL);
737 AssertRC(rc2);
738 }
739 else
740 vmR3SetErrorU(pUVM, rc, RT_SRC_POS, N_("VM creation failed (GVMM)"));
741
742 LogFlow(("vmR3CreateU: returns %Rrc\n", rc));
743 return rc;
744}
745
746
747/**
748 * Register the calling EMT with GVM.
749 *
750 * @returns VBox status code.
751 * @param pVM The VM handle.
752 * @param idCpu The Virtual CPU ID.
753 */
754static DECLCALLBACK(int) vmR3RegisterEMT(PVM pVM, VMCPUID idCpu)
755{
756 Assert(VMMGetCpuId(pVM) == idCpu);
757 int rc = SUPR3CallVMMR0Ex(pVM->pVMR0, idCpu, VMMR0_DO_GVMM_REGISTER_VMCPU, 0, NULL);
758 if (RT_FAILURE(rc))
759 LogRel(("idCpu=%u rc=%Rrc\n", idCpu, rc));
760 return rc;
761}
762
763
764/**
765 * Initializes all R3 components of the VM
766 */
767static int vmR3InitRing3(PVM pVM, PUVM pUVM)
768{
769 int rc;
770
771 /*
772 * Register the other EMTs with GVM.
773 */
774 for (VMCPUID idCpu = 1; idCpu < pVM->cCpus; idCpu++)
775 {
776 rc = VMR3ReqCallWaitU(pUVM, idCpu, (PFNRT)vmR3RegisterEMT, 2, pVM, idCpu);
777 if (RT_FAILURE(rc))
778 return rc;
779 }
780
781 /*
782 * Init all R3 components, the order here might be important.
783 */
784 rc = MMR3Init(pVM);
785 if (RT_SUCCESS(rc))
786 {
787 STAM_REG(pVM, &pVM->StatTotalInGC, STAMTYPE_PROFILE_ADV, "/PROF/VM/InGC", STAMUNIT_TICKS_PER_CALL, "Profiling the total time spent in GC.");
788 STAM_REG(pVM, &pVM->StatSwitcherToGC, STAMTYPE_PROFILE_ADV, "/PROF/VM/SwitchToGC", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
789 STAM_REG(pVM, &pVM->StatSwitcherToHC, STAMTYPE_PROFILE_ADV, "/PROF/VM/SwitchToHC", STAMUNIT_TICKS_PER_CALL, "Profiling switching to HC.");
790 STAM_REG(pVM, &pVM->StatSwitcherSaveRegs, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/SaveRegs", STAMUNIT_TICKS_PER_CALL,"Profiling switching to GC.");
791 STAM_REG(pVM, &pVM->StatSwitcherSysEnter, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/SysEnter", STAMUNIT_TICKS_PER_CALL,"Profiling switching to GC.");
792 STAM_REG(pVM, &pVM->StatSwitcherDebug, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/Debug", STAMUNIT_TICKS_PER_CALL,"Profiling switching to GC.");
793 STAM_REG(pVM, &pVM->StatSwitcherCR0, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/CR0", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
794 STAM_REG(pVM, &pVM->StatSwitcherCR4, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/CR4", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
795 STAM_REG(pVM, &pVM->StatSwitcherLgdt, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/Lgdt", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
796 STAM_REG(pVM, &pVM->StatSwitcherLidt, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/Lidt", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
797 STAM_REG(pVM, &pVM->StatSwitcherLldt, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/Lldt", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
798 STAM_REG(pVM, &pVM->StatSwitcherTSS, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/TSS", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
799 STAM_REG(pVM, &pVM->StatSwitcherJmpCR3, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/JmpCR3", STAMUNIT_TICKS_PER_CALL,"Profiling switching to GC.");
800 STAM_REG(pVM, &pVM->StatSwitcherRstrRegs, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/RstrRegs", STAMUNIT_TICKS_PER_CALL,"Profiling switching to GC.");
801
802 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
803 {
804 rc = STAMR3RegisterF(pVM, &pUVM->aCpus[idCpu].vm.s.StatHaltYield, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL, "Profiling halted state yielding.", "/PROF/VM/CPU%d/Halt/Yield", idCpu);
805 AssertRC(rc);
806 rc = STAMR3RegisterF(pVM, &pUVM->aCpus[idCpu].vm.s.StatHaltBlock, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL, "Profiling halted state blocking.", "/PROF/VM/CPU%d/Halt/Block", idCpu);
807 AssertRC(rc);
808 rc = STAMR3RegisterF(pVM, &pUVM->aCpus[idCpu].vm.s.StatHaltTimers, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL, "Profiling halted state timer tasks.", "/PROF/VM/CPU%d/Halt/Timers", idCpu);
809 AssertRC(rc);
810 }
811
812 STAM_REG(pVM, &pUVM->vm.s.StatReqAllocNew, STAMTYPE_COUNTER, "/VM/Req/AllocNew", STAMUNIT_OCCURENCES, "Number of VMR3ReqAlloc returning a new packet.");
813 STAM_REG(pVM, &pUVM->vm.s.StatReqAllocRaces, STAMTYPE_COUNTER, "/VM/Req/AllocRaces", STAMUNIT_OCCURENCES, "Number of VMR3ReqAlloc causing races.");
814 STAM_REG(pVM, &pUVM->vm.s.StatReqAllocRecycled, STAMTYPE_COUNTER, "/VM/Req/AllocRecycled", STAMUNIT_OCCURENCES, "Number of VMR3ReqAlloc returning a recycled packet.");
815 STAM_REG(pVM, &pUVM->vm.s.StatReqFree, STAMTYPE_COUNTER, "/VM/Req/Free", STAMUNIT_OCCURENCES, "Number of VMR3ReqFree calls.");
816 STAM_REG(pVM, &pUVM->vm.s.StatReqFreeOverflow, STAMTYPE_COUNTER, "/VM/Req/FreeOverflow", STAMUNIT_OCCURENCES, "Number of times the request was actually freed.");
817 STAM_REG(pVM, &pUVM->vm.s.StatReqProcessed, STAMTYPE_COUNTER, "/VM/Req/Processed", STAMUNIT_OCCURENCES, "Number of processed requests (any queue).");
818 STAM_REG(pVM, &pUVM->vm.s.StatReqMoreThan1, STAMTYPE_COUNTER, "/VM/Req/MoreThan1", STAMUNIT_OCCURENCES, "Number of times there are more than one request on the queue when processing it.");
819 STAM_REG(pVM, &pUVM->vm.s.StatReqPushBackRaces, STAMTYPE_COUNTER, "/VM/Req/PushBackRaces", STAMUNIT_OCCURENCES, "Number of push back races.");
820
821 rc = CPUMR3Init(pVM);
822 if (RT_SUCCESS(rc))
823 {
824 rc = HWACCMR3Init(pVM);
825 if (RT_SUCCESS(rc))
826 {
827 rc = PGMR3Init(pVM);
828 if (RT_SUCCESS(rc))
829 {
830 rc = REMR3Init(pVM);
831 if (RT_SUCCESS(rc))
832 {
833 rc = MMR3InitPaging(pVM);
834 if (RT_SUCCESS(rc))
835 rc = TMR3Init(pVM);
836 if (RT_SUCCESS(rc))
837 {
838 rc = VMMR3Init(pVM);
839 if (RT_SUCCESS(rc))
840 {
841 rc = SELMR3Init(pVM);
842 if (RT_SUCCESS(rc))
843 {
844 rc = TRPMR3Init(pVM);
845 if (RT_SUCCESS(rc))
846 {
847 rc = CSAMR3Init(pVM);
848 if (RT_SUCCESS(rc))
849 {
850 rc = PATMR3Init(pVM);
851 if (RT_SUCCESS(rc))
852 {
853 rc = IOMR3Init(pVM);
854 if (RT_SUCCESS(rc))
855 {
856 rc = EMR3Init(pVM);
857 if (RT_SUCCESS(rc))
858 {
859 rc = DBGFR3Init(pVM);
860 if (RT_SUCCESS(rc))
861 {
862 rc = PDMR3Init(pVM);
863 if (RT_SUCCESS(rc))
864 {
865 rc = PGMR3InitDynMap(pVM);
866 if (RT_SUCCESS(rc))
867 rc = MMR3HyperInitFinalize(pVM);
868 if (RT_SUCCESS(rc))
869 rc = PATMR3InitFinalize(pVM);
870 if (RT_SUCCESS(rc))
871 rc = PGMR3InitFinalize(pVM);
872 if (RT_SUCCESS(rc))
873 rc = SELMR3InitFinalize(pVM);
874 if (RT_SUCCESS(rc))
875 rc = TMR3InitFinalize(pVM);
876 if (RT_SUCCESS(rc))
877 rc = VMMR3InitFinalize(pVM);
878 if (RT_SUCCESS(rc))
879 rc = REMR3InitFinalize(pVM);
880 if (RT_SUCCESS(rc))
881 rc = vmR3InitDoCompleted(pVM, VMINITCOMPLETED_RING3);
882 if (RT_SUCCESS(rc))
883 {
884 LogFlow(("vmR3InitRing3: returns %Rrc\n", VINF_SUCCESS));
885 return VINF_SUCCESS;
886 }
887 int rc2 = PDMR3Term(pVM);
888 AssertRC(rc2);
889 }
890 int rc2 = DBGFR3Term(pVM);
891 AssertRC(rc2);
892 }
893 int rc2 = EMR3Term(pVM);
894 AssertRC(rc2);
895 }
896 int rc2 = IOMR3Term(pVM);
897 AssertRC(rc2);
898 }
899 int rc2 = PATMR3Term(pVM);
900 AssertRC(rc2);
901 }
902 int rc2 = CSAMR3Term(pVM);
903 AssertRC(rc2);
904 }
905 int rc2 = TRPMR3Term(pVM);
906 AssertRC(rc2);
907 }
908 int rc2 = SELMR3Term(pVM);
909 AssertRC(rc2);
910 }
911 int rc2 = VMMR3Term(pVM);
912 AssertRC(rc2);
913 }
914 int rc2 = TMR3Term(pVM);
915 AssertRC(rc2);
916 }
917 int rc2 = REMR3Term(pVM);
918 AssertRC(rc2);
919 }
920 int rc2 = PGMR3Term(pVM);
921 AssertRC(rc2);
922 }
923 int rc2 = HWACCMR3Term(pVM);
924 AssertRC(rc2);
925 }
926 //int rc2 = CPUMR3Term(pVM);
927 //AssertRC(rc2);
928 }
929 /* MMR3Term is not called here because it'll kill the heap. */
930 }
931
932 LogFlow(("vmR3InitRing3: returns %Rrc\n", rc));
933 return rc;
934}
935
936
937/**
938 * Initializes all VM CPU components of the VM
939 */
940static int vmR3InitVMCpu(PVM pVM)
941{
942 int rc = VINF_SUCCESS;
943 int rc2;
944
945 rc = CPUMR3InitCPU(pVM);
946 if (RT_SUCCESS(rc))
947 {
948 rc = HWACCMR3InitCPU(pVM);
949 if (RT_SUCCESS(rc))
950 {
951 rc = PGMR3InitCPU(pVM);
952 if (RT_SUCCESS(rc))
953 {
954 rc = TMR3InitCPU(pVM);
955 if (RT_SUCCESS(rc))
956 {
957 rc = VMMR3InitCPU(pVM);
958 if (RT_SUCCESS(rc))
959 {
960 rc = EMR3InitCPU(pVM);
961 if (RT_SUCCESS(rc))
962 {
963 LogFlow(("vmR3InitVMCpu: returns %Rrc\n", VINF_SUCCESS));
964 return VINF_SUCCESS;
965 }
966
967 rc2 = VMMR3TermCPU(pVM);
968 AssertRC(rc2);
969 }
970 rc2 = TMR3TermCPU(pVM);
971 AssertRC(rc2);
972 }
973 rc2 = PGMR3TermCPU(pVM);
974 AssertRC(rc2);
975 }
976 rc2 = HWACCMR3TermCPU(pVM);
977 AssertRC(rc2);
978 }
979 rc2 = CPUMR3TermCPU(pVM);
980 AssertRC(rc2);
981 }
982 LogFlow(("vmR3InitVMCpu: returns %Rrc\n", rc));
983 return rc;
984}
985
986
987/**
988 * Initializes all R0 components of the VM
989 */
990static int vmR3InitRing0(PVM pVM)
991{
992 LogFlow(("vmR3InitRing0:\n"));
993
994 /*
995 * Check for FAKE suplib mode.
996 */
997 int rc = VINF_SUCCESS;
998 const char *psz = RTEnvGet("VBOX_SUPLIB_FAKE");
999 if (!psz || strcmp(psz, "fake"))
1000 {
1001 /*
1002 * Call the VMMR0 component and let it do the init.
1003 */
1004 rc = VMMR3InitR0(pVM);
1005 }
1006 else
1007 Log(("vmR3InitRing0: skipping because of VBOX_SUPLIB_FAKE=fake\n"));
1008
1009 /*
1010 * Do notifications and return.
1011 */
1012 if (RT_SUCCESS(rc))
1013 rc = vmR3InitDoCompleted(pVM, VMINITCOMPLETED_RING0);
1014
1015 /** @todo Move this to the VMINITCOMPLETED_RING0 notification handler. */
1016 if (RT_SUCCESS(rc))
1017 {
1018 rc = HWACCMR3InitFinalizeR0(pVM);
1019 CPUMR3SetHWVirtEx(pVM, HWACCMIsEnabled(pVM));
1020 }
1021
1022 LogFlow(("vmR3InitRing0: returns %Rrc\n", rc));
1023 return rc;
1024}
1025
1026
1027/**
1028 * Initializes all GC components of the VM
1029 */
1030static int vmR3InitGC(PVM pVM)
1031{
1032 LogFlow(("vmR3InitGC:\n"));
1033
1034 /*
1035 * Check for FAKE suplib mode.
1036 */
1037 int rc = VINF_SUCCESS;
1038 const char *psz = RTEnvGet("VBOX_SUPLIB_FAKE");
1039 if (!psz || strcmp(psz, "fake"))
1040 {
1041 /*
1042 * Call the VMMR0 component and let it do the init.
1043 */
1044 rc = VMMR3InitRC(pVM);
1045 }
1046 else
1047 Log(("vmR3InitGC: skipping because of VBOX_SUPLIB_FAKE=fake\n"));
1048
1049 /*
1050 * Do notifications and return.
1051 */
1052 if (RT_SUCCESS(rc))
1053 rc = vmR3InitDoCompleted(pVM, VMINITCOMPLETED_GC);
1054 LogFlow(("vmR3InitGC: returns %Rrc\n", rc));
1055 return rc;
1056}
1057
1058
1059/**
1060 * Do init completed notifications.
1061 * This notifications can fail.
1062 *
1063 * @param pVM The VM handle.
1064 * @param enmWhat What's completed.
1065 */
1066static int vmR3InitDoCompleted(PVM pVM, VMINITCOMPLETED enmWhat)
1067{
1068 return VINF_SUCCESS;
1069}
1070
1071
1072/**
1073 * Logger callback for inserting a custom prefix.
1074 *
1075 * @returns Number of chars written.
1076 * @param pLogger The logger.
1077 * @param pchBuf The output buffer.
1078 * @param cchBuf The output buffer size.
1079 * @param pvUser Pointer to the UVM structure.
1080 */
1081static DECLCALLBACK(size_t) vmR3LogPrefixCallback(PRTLOGGER pLogger, char *pchBuf, size_t cchBuf, void *pvUser)
1082{
1083 AssertReturn(cchBuf >= 2, 0);
1084 PUVM pUVM = (PUVM)pvUser;
1085 PUVMCPU pUVCpu = (PUVMCPU)RTTlsGet(pUVM->vm.s.idxTLS);
1086 if (pUVCpu)
1087 {
1088 static const char s_szHex[17] = "0123456789abcdef";
1089 VMCPUID const idCpu = pUVCpu->idCpu;
1090 pchBuf[1] = s_szHex[ idCpu & 15];
1091 pchBuf[0] = s_szHex[(idCpu >> 4) & 15];
1092 }
1093 else
1094 {
1095 pchBuf[0] = 'x';
1096 pchBuf[1] = 'y';
1097 }
1098
1099 return 2;
1100}
1101
1102
1103/**
1104 * Calls the relocation functions for all VMM components so they can update
1105 * any GC pointers. When this function is called all the basic VM members
1106 * have been updated and the actual memory relocation have been done
1107 * by the PGM/MM.
1108 *
1109 * This is used both on init and on runtime relocations.
1110 *
1111 * @param pVM VM handle.
1112 * @param offDelta Relocation delta relative to old location.
1113 */
1114VMMR3DECL(void) VMR3Relocate(PVM pVM, RTGCINTPTR offDelta)
1115{
1116 LogFlow(("VMR3Relocate: offDelta=%RGv\n", offDelta));
1117
1118 /*
1119 * The order here is very important!
1120 */
1121 PGMR3Relocate(pVM, offDelta);
1122 PDMR3LdrRelocateU(pVM->pUVM, offDelta);
1123 PGMR3Relocate(pVM, 0); /* Repeat after PDM relocation. */
1124 CPUMR3Relocate(pVM);
1125 HWACCMR3Relocate(pVM);
1126 SELMR3Relocate(pVM);
1127 VMMR3Relocate(pVM, offDelta);
1128 SELMR3Relocate(pVM); /* !hack! fix stack! */
1129 TRPMR3Relocate(pVM, offDelta);
1130 PATMR3Relocate(pVM);
1131 CSAMR3Relocate(pVM, offDelta);
1132 IOMR3Relocate(pVM, offDelta);
1133 EMR3Relocate(pVM);
1134 TMR3Relocate(pVM, offDelta);
1135 DBGFR3Relocate(pVM, offDelta);
1136 PDMR3Relocate(pVM, offDelta);
1137}
1138
1139
1140/**
1141 * EMT rendezvous worker for VMR3PowerOn.
1142 *
1143 * @returns VERR_VM_INVALID_VM_STATE or VINF_SUCCESS. (This is a strict return
1144 * code, see FNVMMEMTRENDEZVOUS.)
1145 *
1146 * @param pVM The VM handle.
1147 * @param pVCpu The VMCPU handle of the EMT.
1148 * @param pvUser Ignored.
1149 */
1150static DECLCALLBACK(VBOXSTRICTRC) vmR3PowerOn(PVM pVM, PVMCPU pVCpu, void *pvUser)
1151{
1152 LogFlow(("vmR3PowerOn: pVM=%p pVCpu=%p/#%u\n", pVM, pVCpu, pVCpu->idCpu));
1153 Assert(!pvUser); NOREF(pvUser);
1154
1155 /*
1156 * The first thread thru here tries to change the state. We shouldn't be
1157 * called again if this fails.
1158 */
1159 if (pVCpu->idCpu == pVM->cCpus - 1)
1160 {
1161 int rc = vmR3TrySetState(pVM, "VMR3PowerOn", 1, VMSTATE_POWERING_ON, VMSTATE_CREATED);
1162 if (RT_FAILURE(rc))
1163 return rc;
1164 }
1165
1166 VMSTATE enmVMState = VMR3GetState(pVM);
1167 AssertMsgReturn(enmVMState == VMSTATE_POWERING_ON,
1168 ("%s\n", VMR3GetStateName(enmVMState)),
1169 VERR_INTERNAL_ERROR_4);
1170
1171 /*
1172 * All EMTs changes their state to started.
1173 */
1174 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED);
1175
1176 /*
1177 * EMT(0) is last thru here and it will make the notification calls
1178 * and advance the state.
1179 */
1180 if (pVCpu->idCpu == 0)
1181 {
1182 PDMR3PowerOn(pVM);
1183 vmR3SetState(pVM, VMSTATE_RUNNING, VMSTATE_POWERING_ON);
1184 }
1185
1186 return VINF_SUCCESS;
1187}
1188
1189
1190/**
1191 * Powers on the virtual machine.
1192 *
1193 * @returns VBox status code.
1194 *
1195 * @param pVM The VM to power on.
1196 *
1197 * @thread Any thread.
1198 * @vmstate Created
1199 * @vmstateto PoweringOn+Running
1200 */
1201VMMR3DECL(int) VMR3PowerOn(PVM pVM)
1202{
1203 LogFlow(("VMR3PowerOn: pVM=%p\n", pVM));
1204 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
1205
1206 /*
1207 * Gather all the EMTs to reduce the init TSC drift and keep
1208 * the state changing APIs a bit uniform.
1209 */
1210 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_DESCENDING | VMMEMTRENDEZVOUS_FLAGS_STOP_ON_ERROR,
1211 vmR3PowerOn, NULL);
1212 LogFlow(("VMR3PowerOn: returns %Rrc\n", rc));
1213 return rc;
1214}
1215
1216
1217/**
1218 * Does the suspend notifications.
1219 *
1220 * @param pVM The VM handle.
1221 * @thread EMT(0)
1222 */
1223static void vmR3SuspendDoWork(PVM pVM)
1224{
1225 PDMR3Suspend(pVM);
1226}
1227
1228
1229/**
1230 * EMT rendezvous worker for VMR3Suspend.
1231 *
1232 * @returns VERR_VM_INVALID_VM_STATE or VINF_EM_SUSPEND. (This is a strict
1233 * return code, see FNVMMEMTRENDEZVOUS.)
1234 *
1235 * @param pVM The VM handle.
1236 * @param pVCpu The VMCPU handle of the EMT.
1237 * @param pvUser Ignored.
1238 */
1239static DECLCALLBACK(VBOXSTRICTRC) vmR3Suspend(PVM pVM, PVMCPU pVCpu, void *pvUser)
1240{
1241 LogFlow(("vmR3Suspend: pVM=%p pVCpu=%p/#%u\n", pVM, pVCpu, pVCpu->idCpu));
1242 Assert(!pvUser); NOREF(pvUser);
1243
1244 /*
1245 * The first EMT switches the state to suspending. If this fails because
1246 * something was racing us in one way or the other, there will be no more
1247 * calls and thus the state assertion below is not going to annoy anyone.
1248 */
1249 if (pVCpu->idCpu == pVM->cCpus - 1)
1250 {
1251 int rc = vmR3TrySetState(pVM, "VMR3Suspend", 2,
1252 VMSTATE_SUSPENDING, VMSTATE_RUNNING,
1253 VMSTATE_SUSPENDING_EXT_LS, VMSTATE_RUNNING_LS);
1254 if (RT_FAILURE(rc))
1255 return rc;
1256 }
1257
1258 VMSTATE enmVMState = VMR3GetState(pVM);
1259 AssertMsgReturn( enmVMState == VMSTATE_SUSPENDING
1260 || enmVMState == VMSTATE_SUSPENDING_EXT_LS,
1261 ("%s\n", VMR3GetStateName(enmVMState)),
1262 VERR_INTERNAL_ERROR_4);
1263
1264 /*
1265 * EMT(0) does the actually suspending *after* all the other CPUs have
1266 * been thru here.
1267 */
1268 if (pVCpu->idCpu == 0)
1269 {
1270 vmR3SuspendDoWork(pVM);
1271
1272 int rc = vmR3TrySetState(pVM, "VMR3Suspend", 2,
1273 VMSTATE_SUSPENDED, VMSTATE_SUSPENDING,
1274 VMSTATE_SUSPENDED_EXT_LS, VMSTATE_SUSPENDING_EXT_LS);
1275 if (RT_FAILURE(rc))
1276 return VERR_INTERNAL_ERROR_3;
1277 }
1278
1279 return VINF_EM_SUSPEND;
1280}
1281
1282
1283/**
1284 * Suspends a running VM.
1285 *
1286 * @returns VBox status code. When called on EMT, this will be a strict status
1287 * code that has to be propagated up the call stack.
1288 *
1289 * @param pVM The VM to suspend.
1290 *
1291 * @thread Any thread.
1292 * @vmstate Running or RunningLS
1293 * @vmstateto Suspending + Suspended or SuspendingExtLS + SuspendedExtLS
1294 */
1295VMMR3DECL(int) VMR3Suspend(PVM pVM)
1296{
1297 LogFlow(("VMR3Suspend: pVM=%p\n", pVM));
1298 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
1299
1300 /*
1301 * Gather all the EMTs to make sure there are no races before
1302 * changing the VM state.
1303 */
1304 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_DESCENDING | VMMEMTRENDEZVOUS_FLAGS_STOP_ON_ERROR,
1305 vmR3Suspend, NULL);
1306 LogFlow(("VMR3Suspend: returns %Rrc\n", rc));
1307 return rc;
1308}
1309
1310
1311/**
1312 * EMT rendezvous worker for VMR3Resume.
1313 *
1314 * @returns VERR_VM_INVALID_VM_STATE or VINF_EM_RESUME. (This is a strict
1315 * return code, see FNVMMEMTRENDEZVOUS.)
1316 *
1317 * @param pVM The VM handle.
1318 * @param pVCpu The VMCPU handle of the EMT.
1319 * @param pvUser Ignored.
1320 */
1321static DECLCALLBACK(VBOXSTRICTRC) vmR3Resume(PVM pVM, PVMCPU pVCpu, void *pvUser)
1322{
1323 LogFlow(("vmR3Resume: pVM=%p pVCpu=%p/#%u\n", pVM, pVCpu, pVCpu->idCpu));
1324 Assert(!pvUser); NOREF(pvUser);
1325
1326 /*
1327 * The first thread thru here tries to change the state. We shouldn't be
1328 * called again if this fails.
1329 */
1330 if (pVCpu->idCpu == pVM->cCpus - 1)
1331 {
1332 int rc = vmR3TrySetState(pVM, "VMR3Resume", 1, VMSTATE_RESUMING, VMSTATE_SUSPENDED);
1333 if (RT_FAILURE(rc))
1334 return rc;
1335 }
1336
1337 VMSTATE enmVMState = VMR3GetState(pVM);
1338 AssertMsgReturn(enmVMState == VMSTATE_RESUMING,
1339 ("%s\n", VMR3GetStateName(enmVMState)),
1340 VERR_INTERNAL_ERROR_4);
1341
1342#if 0
1343 /*
1344 * All EMTs changes their state to started.
1345 */
1346 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED);
1347#endif
1348
1349 /*
1350 * EMT(0) is last thru here and it will make the notification calls
1351 * and advance the state.
1352 */
1353 if (pVCpu->idCpu == 0)
1354 {
1355 PDMR3Resume(pVM);
1356 vmR3SetState(pVM, VMSTATE_RUNNING, VMSTATE_RESUMING);
1357 pVM->vm.s.fTeleportedAndNotFullyResumedYet = false;
1358 }
1359
1360 return VINF_EM_RESUME;
1361}
1362
1363
1364/**
1365 * Resume VM execution.
1366 *
1367 * @returns VBox status code. When called on EMT, this will be a strict status
1368 * code that has to be propagated up the call stack.
1369 *
1370 * @param pVM The VM to resume.
1371 *
1372 * @thread Any thread.
1373 * @vmstate Suspended
1374 * @vmstateto Running
1375 */
1376VMMR3DECL(int) VMR3Resume(PVM pVM)
1377{
1378 LogFlow(("VMR3Resume: pVM=%p\n", pVM));
1379 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
1380
1381 /*
1382 * Gather all the EMTs to make sure there are no races before
1383 * changing the VM state.
1384 */
1385 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_DESCENDING | VMMEMTRENDEZVOUS_FLAGS_STOP_ON_ERROR,
1386 vmR3Resume, NULL);
1387 LogFlow(("VMR3Resume: returns %Rrc\n", rc));
1388 return rc;
1389}
1390
1391
1392/**
1393 * EMT rendezvous worker for VMR3Save and VMR3Teleport that suspends the VM
1394 * after the live step has been completed.
1395 *
1396 * @returns VERR_VM_INVALID_VM_STATE or VINF_EM_RESUME. (This is a strict
1397 * return code, see FNVMMEMTRENDEZVOUS.)
1398 *
1399 * @param pVM The VM handle.
1400 * @param pVCpu The VMCPU handle of the EMT.
1401 * @param pvUser The pfSuspended argument of vmR3SaveTeleport.
1402 */
1403static DECLCALLBACK(VBOXSTRICTRC) vmR3LiveDoSuspend(PVM pVM, PVMCPU pVCpu, void *pvUser)
1404{
1405 LogFlow(("vmR3LiveDoSuspend: pVM=%p pVCpu=%p/#%u\n", pVM, pVCpu, pVCpu->idCpu));
1406 bool *pfSuspended = (bool *)pvUser;
1407
1408 /*
1409 * The first thread thru here tries to change the state. We shouldn't be
1410 * called again if this fails.
1411 */
1412 if (pVCpu->idCpu == pVM->cCpus - 1U)
1413 {
1414 PUVM pUVM = pVM->pUVM;
1415 int rc;
1416
1417 RTCritSectEnter(&pUVM->vm.s.AtStateCritSect);
1418 VMSTATE enmVMState = pVM->enmVMState;
1419 switch (enmVMState)
1420 {
1421 case VMSTATE_RUNNING_LS:
1422 vmR3SetStateLocked(pVM, pUVM, VMSTATE_SUSPENDING_LS, VMSTATE_RUNNING_LS);
1423 rc = VINF_SUCCESS;
1424 break;
1425
1426 case VMSTATE_SUSPENDED_EXT_LS:
1427 case VMSTATE_SUSPENDED_LS: /* (via reset) */
1428 rc = VINF_SUCCESS;
1429 break;
1430
1431 case VMSTATE_DEBUGGING_LS:
1432 rc = VERR_TRY_AGAIN;
1433 break;
1434
1435 case VMSTATE_OFF_LS:
1436 vmR3SetStateLocked(pVM, pUVM, VMSTATE_OFF, VMSTATE_OFF_LS);
1437 rc = VERR_SSM_LIVE_POWERED_OFF;
1438 break;
1439
1440 case VMSTATE_FATAL_ERROR_LS:
1441 vmR3SetStateLocked(pVM, pUVM, VMSTATE_FATAL_ERROR, VMSTATE_FATAL_ERROR_LS);
1442 rc = VERR_SSM_LIVE_FATAL_ERROR;
1443 break;
1444
1445 case VMSTATE_GURU_MEDITATION_LS:
1446 vmR3SetStateLocked(pVM, pUVM, VMSTATE_GURU_MEDITATION, VMSTATE_GURU_MEDITATION_LS);
1447 rc = VERR_SSM_LIVE_GURU_MEDITATION;
1448 break;
1449
1450 case VMSTATE_POWERING_OFF_LS:
1451 case VMSTATE_SUSPENDING_EXT_LS:
1452 case VMSTATE_RESETTING_LS:
1453 default:
1454 AssertMsgFailed(("%s\n", VMR3GetStateName(enmVMState)));
1455 rc = VERR_INTERNAL_ERROR_3;
1456 break;
1457 }
1458 RTCritSectLeave(&pUVM->vm.s.AtStateCritSect);
1459 if (RT_FAILURE(rc))
1460 {
1461 LogFlow(("vmR3LiveDoSuspend: returns %Rrc (state was %s)\n", rc, VMR3GetStateName(enmVMState)));
1462 return rc;
1463 }
1464 }
1465
1466 VMSTATE enmVMState = VMR3GetState(pVM);
1467 AssertMsgReturn(enmVMState == VMSTATE_SUSPENDING_LS,
1468 ("%s\n", VMR3GetStateName(enmVMState)),
1469 VERR_INTERNAL_ERROR_4);
1470
1471 /*
1472 * Only EMT(0) have work to do since it's last thru here.
1473 */
1474 if (pVCpu->idCpu == 0)
1475 {
1476 vmR3SuspendDoWork(pVM);
1477 int rc = vmR3TrySetState(pVM, "VMR3Suspend", 1,
1478 VMSTATE_SUSPENDED_LS, VMSTATE_SUSPENDING_LS);
1479 if (RT_FAILURE(rc))
1480 return VERR_INTERNAL_ERROR_3;
1481
1482 *pfSuspended = true;
1483 }
1484
1485 return VINF_EM_SUSPEND;
1486}
1487
1488
1489/**
1490 * EMT rendezvous worker that VMR3Save and VMR3Teleport uses to clean up a
1491 * SSMR3LiveDoStep1 failure.
1492 *
1493 * Doing this as a rendezvous operation avoids all annoying transition
1494 * states.
1495 *
1496 * @returns VERR_VM_INVALID_VM_STATE, VINF_SUCCESS or some specific VERR_SSM_*
1497 * status code. (This is a strict return code, see FNVMMEMTRENDEZVOUS.)
1498 *
1499 * @param pVM The VM handle.
1500 * @param pVCpu The VMCPU handle of the EMT.
1501 * @param pvUser The pfSuspended argument of vmR3SaveTeleport.
1502 */
1503static DECLCALLBACK(VBOXSTRICTRC) vmR3LiveDoStep1Cleanup(PVM pVM, PVMCPU pVCpu, void *pvUser)
1504{
1505 LogFlow(("vmR3LiveDoStep1Cleanup: pVM=%p pVCpu=%p/#%u\n", pVM, pVCpu, pVCpu->idCpu));
1506 bool *pfSuspended = (bool *)pvUser;
1507 NOREF(pVCpu);
1508
1509 int rc = vmR3TrySetState(pVM, "vmR3LiveDoStep1Cleanup", 8,
1510 VMSTATE_OFF, VMSTATE_OFF_LS, /* 1 */
1511 VMSTATE_FATAL_ERROR, VMSTATE_FATAL_ERROR_LS, /* 2 */
1512 VMSTATE_GURU_MEDITATION, VMSTATE_GURU_MEDITATION_LS, /* 3 */
1513 VMSTATE_SUSPENDED, VMSTATE_SUSPENDED_LS, /* 4 */
1514 VMSTATE_SUSPENDED, VMSTATE_SAVING,
1515 VMSTATE_SUSPENDED, VMSTATE_SUSPENDED_EXT_LS,
1516 VMSTATE_RUNNING, VMSTATE_RUNNING_LS,
1517 VMSTATE_DEBUGGING, VMSTATE_DEBUGGING_LS);
1518 if (rc == 1)
1519 rc = VERR_SSM_LIVE_POWERED_OFF;
1520 else if (rc == 2)
1521 rc = VERR_SSM_LIVE_FATAL_ERROR;
1522 else if (rc == 3)
1523 rc = VERR_SSM_LIVE_GURU_MEDITATION;
1524 else if (rc == 4)
1525 {
1526 *pfSuspended = true;
1527 rc = VINF_SUCCESS;
1528 }
1529 else if (rc > 0)
1530 rc = VINF_SUCCESS;
1531 return rc;
1532}
1533
1534
1535/**
1536 * EMT(0) worker for VMR3Save and VMR3Teleport that completes the live save.
1537 *
1538 * @returns VBox status code.
1539 * @retval VINF_SSM_LIVE_SUSPENDED if VMR3Suspend was called.
1540 *
1541 * @param pVM The VM handle.
1542 * @param pSSM The handle of saved state operation.
1543 *
1544 * @thread EMT(0)
1545 */
1546static DECLCALLBACK(int) vmR3LiveDoStep2(PVM pVM, PSSMHANDLE pSSM)
1547{
1548 LogFlow(("vmR3LiveDoStep2: pVM=%p pSSM=%p\n", pVM, pSSM));
1549 VM_ASSERT_EMT0(pVM);
1550
1551 /*
1552 * Advance the state and mark if VMR3Suspend was called.
1553 */
1554 int rc = VINF_SUCCESS;
1555 VMSTATE enmVMState = VMR3GetState(pVM);
1556 if (enmVMState == VMSTATE_SUSPENDED_LS)
1557 vmR3SetState(pVM, VMSTATE_SAVING, VMSTATE_SUSPENDED_LS);
1558 else
1559 {
1560 if (enmVMState != VMSTATE_SAVING)
1561 vmR3SetState(pVM, VMSTATE_SAVING, VMSTATE_SUSPENDED_EXT_LS);
1562 rc = VINF_SSM_LIVE_SUSPENDED;
1563 }
1564
1565 /*
1566 * Finish up and release the handle. Careful with the status codes.
1567 */
1568 int rc2 = SSMR3LiveDoStep2(pSSM);
1569 if (rc == VINF_SUCCESS || (RT_FAILURE(rc2) && RT_SUCCESS(rc)))
1570 rc = rc2;
1571
1572 rc2 = SSMR3LiveDone(pSSM);
1573 if (rc == VINF_SUCCESS || (RT_FAILURE(rc2) && RT_SUCCESS(rc)))
1574 rc = rc2;
1575
1576 /*
1577 * Advance to the final state and return.
1578 */
1579 vmR3SetState(pVM, VMSTATE_SUSPENDED, VMSTATE_SAVING);
1580 Assert(rc > VINF_EM_LAST || rc < VINF_EM_FIRST);
1581 return rc;
1582}
1583
1584
1585/**
1586 * Worker for vmR3SaveTeleport that validates the state and calls SSMR3Save or
1587 * SSMR3LiveSave.
1588 *
1589 * @returns VBox status code.
1590 *
1591 * @param pVM The VM handle.
1592 * @param cMsMaxDowntime The maximum downtime given as milliseconds.
1593 * @param pszFilename The name of the file. NULL if pStreamOps is used.
1594 * @param pStreamOps The stream methods. NULL if pszFilename is used.
1595 * @param pvStreamOpsUser The user argument to the stream methods.
1596 * @param enmAfter What to do afterwards.
1597 * @param pfnProgress Progress callback. Optional.
1598 * @param pvProgressUser User argument for the progress callback.
1599 * @param ppSSM Where to return the saved state handle in case of a
1600 * live snapshot scenario.
1601 * @thread EMT
1602 */
1603static DECLCALLBACK(int) vmR3Save(PVM pVM, uint32_t cMsMaxDowntime, const char *pszFilename, PCSSMSTRMOPS pStreamOps, void *pvStreamOpsUser,
1604 SSMAFTER enmAfter, PFNVMPROGRESS pfnProgress, void *pvProgressUser, PSSMHANDLE *ppSSM)
1605{
1606 LogFlow(("vmR3Save: pVM=%p cMsMaxDowntime=%u pszFilename=%p:{%s} pStreamOps=%p pvStreamOpsUser=%p enmAfter=%d pfnProgress=%p pvProgressUser=%p ppSSM=%p\n",
1607 pVM, cMsMaxDowntime, pszFilename, pszFilename, pStreamOps, pvStreamOpsUser, enmAfter, pfnProgress, pvProgressUser, ppSSM));
1608
1609 /*
1610 * Validate input.
1611 */
1612 AssertPtrNull(pszFilename);
1613 AssertPtrNull(pStreamOps);
1614 AssertPtr(pVM);
1615 Assert( enmAfter == SSMAFTER_DESTROY
1616 || enmAfter == SSMAFTER_CONTINUE
1617 || enmAfter == SSMAFTER_TELEPORT);
1618 AssertPtr(ppSSM);
1619 *ppSSM = NULL;
1620
1621 /*
1622 * Change the state and perform/start the saving.
1623 */
1624 int rc = vmR3TrySetState(pVM, "VMR3Save", 2,
1625 VMSTATE_SAVING, VMSTATE_SUSPENDED,
1626 VMSTATE_RUNNING_LS, VMSTATE_RUNNING);
1627 if (rc == 1 && enmAfter != SSMAFTER_TELEPORT)
1628 {
1629 Assert(!pStreamOps);
1630 rc = SSMR3Save(pVM, pszFilename, enmAfter, pfnProgress, pvProgressUser);
1631 vmR3SetState(pVM, VMSTATE_SUSPENDED, VMSTATE_SAVING);
1632 }
1633 else if (rc == 2 || enmAfter == SSMAFTER_TELEPORT)
1634 {
1635 if (enmAfter == SSMAFTER_TELEPORT)
1636 pVM->vm.s.fTeleportedAndNotFullyResumedYet = true;
1637 rc = SSMR3LiveSave(pVM, cMsMaxDowntime, pszFilename, pStreamOps, pvStreamOpsUser,
1638 enmAfter, pfnProgress, pvProgressUser, ppSSM);
1639 /* (We're not subject to cancellation just yet.) */
1640 }
1641 else
1642 Assert(RT_FAILURE(rc));
1643 return rc;
1644}
1645
1646
1647/**
1648 * Commmon worker for VMR3Save and VMR3Teleport.
1649 *
1650 * @returns VBox status code.
1651 *
1652 * @param pVM The VM handle.
1653 * @param cMsMaxDowntime The maximum downtime given as milliseconds.
1654 * @param pszFilename The name of the file. NULL if pStreamOps is used.
1655 * @param pStreamOps The stream methods. NULL if pszFilename is used.
1656 * @param pvStreamOpsUser The user argument to the stream methods.
1657 * @param enmAfter What to do afterwards.
1658 * @param pfnProgress Progress callback. Optional.
1659 * @param pvProgressUser User argument for the progress callback.
1660 * @param pfSuspended Set if we suspended the VM.
1661 *
1662 * @thread Non-EMT
1663 */
1664static int vmR3SaveTeleport(PVM pVM, uint32_t cMsMaxDowntime,
1665 const char *pszFilename, PCSSMSTRMOPS pStreamOps, void *pvStreamOpsUser,
1666 SSMAFTER enmAfter, PFNVMPROGRESS pfnProgress, void *pvProgressUser, bool *pfSuspended)
1667{
1668 /*
1669 * Request the operation in EMT(0).
1670 */
1671 PSSMHANDLE pSSM;
1672 int rc = VMR3ReqCallWaitU(pVM->pUVM, 0 /*idDstCpu*/,
1673 (PFNRT)vmR3Save, 9, pVM, cMsMaxDowntime, pszFilename, pStreamOps, pvStreamOpsUser,
1674 enmAfter, pfnProgress, pvProgressUser, &pSSM);
1675 if ( RT_SUCCESS(rc)
1676 && pSSM)
1677 {
1678 /*
1679 * Live snapshot.
1680 *
1681 * The state handling here is kind of tricky, doing it on EMT(0) helps
1682 * a bit. See the VMSTATE diagram for details.
1683 */
1684 rc = SSMR3LiveDoStep1(pSSM);
1685 if (RT_SUCCESS(rc))
1686 {
1687 if (VMR3GetState(pVM) != VMSTATE_SAVING)
1688 for (;;)
1689 {
1690 /* Try suspend the VM. */
1691 rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_DESCENDING | VMMEMTRENDEZVOUS_FLAGS_STOP_ON_ERROR,
1692 vmR3LiveDoSuspend, pfSuspended);
1693 if (rc != VERR_TRY_AGAIN)
1694 break;
1695
1696 /* Wait for the state to change. */
1697 RTThreadSleep(250); /** @todo Live Migration: fix this polling wait by some smart use of multiple release event semaphores.. */
1698 }
1699 if (RT_SUCCESS(rc))
1700 rc = VMR3ReqCallWaitU(pVM->pUVM, 0 /*idDstCpu*/, (PFNRT)vmR3LiveDoStep2, 2, pVM, pSSM);
1701 else
1702 {
1703 int rc2 = VMR3ReqCallWaitU(pVM->pUVM, 0 /*idDstCpu*/, (PFNRT)SSMR3LiveDone, 1, pSSM);
1704 AssertMsg(rc2 == rc, ("%Rrc != %Rrc\n", rc2, rc));
1705 }
1706 }
1707 else
1708 {
1709 int rc2 = VMR3ReqCallWaitU(pVM->pUVM, 0 /*idDstCpu*/, (PFNRT)SSMR3LiveDone, 1, pSSM);
1710 AssertMsg(rc2 == rc, ("%Rrc != %Rrc\n", rc2, rc));
1711
1712 rc2 = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, vmR3LiveDoStep1Cleanup, pfSuspended);
1713 if (RT_FAILURE(rc2) && rc == VERR_SSM_CANCELLED)
1714 rc = rc2;
1715 }
1716 }
1717
1718 return rc;
1719}
1720
1721
1722/**
1723 * Save current VM state.
1724 *
1725 * Can be used for both saving the state and creating snapshots.
1726 *
1727 * When called for a VM in the Running state, the saved state is created live
1728 * and the VM is only suspended when the final part of the saving is preformed.
1729 * The VM state will not be restored to Running in this case and it's up to the
1730 * caller to call VMR3Resume if this is desirable. (The rational is that the
1731 * caller probably wish to reconfigure the disks before resuming the VM.)
1732 *
1733 * @returns VBox status code.
1734 *
1735 * @param pVM The VM which state should be saved.
1736 * @param pszFilename The name of the save state file.
1737 * @param fContinueAfterwards Whether continue execution afterwards or not.
1738 * When in doubt, set this to true.
1739 * @param pfnProgress Progress callback. Optional.
1740 * @param pvUser User argument for the progress callback.
1741 * @param pfSuspended Set if we suspended the VM.
1742 *
1743 * @thread Non-EMT.
1744 * @vmstate Suspended or Running
1745 * @vmstateto Saving+Suspended or
1746 * RunningLS+SuspeningLS+SuspendedLS+Saving+Suspended.
1747 */
1748VMMR3DECL(int) VMR3Save(PVM pVM, const char *pszFilename, bool fContinueAfterwards,
1749 PFNVMPROGRESS pfnProgress, void *pvUser, bool *pfSuspended)
1750{
1751 LogFlow(("VMR3Save: pVM=%p pszFilename=%p:{%s} fContinueAfterwards=%RTbool pfnProgress=%p pvUser=%p pfSuspended=%p\n",
1752 pVM, pszFilename, pszFilename, fContinueAfterwards, pfnProgress, pvUser, pfSuspended));
1753
1754 /*
1755 * Validate input.
1756 */
1757 AssertPtr(pfSuspended);
1758 *pfSuspended = false;
1759 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
1760 VM_ASSERT_OTHER_THREAD(pVM);
1761 AssertPtrReturn(pszFilename, VERR_INVALID_POINTER);
1762 AssertReturn(*pszFilename, VERR_INVALID_PARAMETER);
1763 AssertPtrNullReturn(pfnProgress, VERR_INVALID_POINTER);
1764
1765 /*
1766 * Join paths with VMR3Teleport.
1767 */
1768 SSMAFTER enmAfter = fContinueAfterwards ? SSMAFTER_CONTINUE : SSMAFTER_DESTROY;
1769 int rc = vmR3SaveTeleport(pVM, 250 /*cMsMaxDowntime*/,
1770 pszFilename, NULL /*pStreamOps*/, NULL /*pvStreamOpsUser*/,
1771 enmAfter, pfnProgress, pvUser, pfSuspended);
1772 LogFlow(("VMR3Save: returns %Rrc (*pfSuspended=%RTbool)\n", rc, *pfSuspended));
1773 return rc;
1774}
1775
1776
1777/**
1778 * Teleport the VM (aka live migration).
1779 *
1780 * @returns VBox status code.
1781 *
1782 * @param pVM The VM which state should be saved.
1783 * @param cMsMaxDowntime The maximum downtime given as milliseconds.
1784 * @param pStreamOps The stream methods.
1785 * @param pvStreamOpsUser The user argument to the stream methods.
1786 * @param pfnProgress Progress callback. Optional.
1787 * @param pvProgressUser User argument for the progress callback.
1788 * @param pfSuspended Set if we suspended the VM.
1789 *
1790 * @thread Non-EMT.
1791 * @vmstate Suspended or Running
1792 * @vmstateto Saving+Suspended or
1793 * RunningLS+SuspeningLS+SuspendedLS+Saving+Suspended.
1794 */
1795VMMR3DECL(int) VMR3Teleport(PVM pVM, uint32_t cMsMaxDowntime, PCSSMSTRMOPS pStreamOps, void *pvStreamOpsUser,
1796 PFNVMPROGRESS pfnProgress, void *pvProgressUser, bool *pfSuspended)
1797{
1798 LogFlow(("VMR3Teleport: pVM=%p cMsMaxDowntime=%u pStreamOps=%p pvStreamOps=%p pfnProgress=%p pvProgressUser=%p\n",
1799 pVM, cMsMaxDowntime, pStreamOps, pvStreamOpsUser, pfnProgress, pvProgressUser));
1800
1801 /*
1802 * Validate input.
1803 */
1804 AssertPtr(pfSuspended);
1805 *pfSuspended = false;
1806 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
1807 VM_ASSERT_OTHER_THREAD(pVM);
1808 AssertPtrReturn(pStreamOps, VERR_INVALID_POINTER);
1809 AssertPtrNullReturn(pfnProgress, VERR_INVALID_POINTER);
1810
1811 /*
1812 * Join paths with VMR3Save.
1813 */
1814 int rc = vmR3SaveTeleport(pVM, cMsMaxDowntime,
1815 NULL /*pszFilename*/, pStreamOps, pvStreamOpsUser,
1816 SSMAFTER_TELEPORT, pfnProgress, pvProgressUser, pfSuspended);
1817 LogFlow(("VMR3Teleport: returns %Rrc (*pfSuspended=%RTbool)\n", rc, *pfSuspended));
1818 return rc;
1819}
1820
1821
1822
1823/**
1824 * EMT(0) worker for VMR3LoadFromFile and VMR3LoadFromStream.
1825 *
1826 * @returns VBox status code.
1827 *
1828 * @param pVM The VM handle.
1829 * @param pszFilename The name of the file. NULL if pStreamOps is used.
1830 * @param pStreamOps The stream methods. NULL if pszFilename is used.
1831 * @param pvStreamOpsUser The user argument to the stream methods.
1832 * @param pfnProgress Progress callback. Optional.
1833 * @param pvUser User argument for the progress callback.
1834 * @param fTeleporting Indicates whether we're teleporting or not.
1835 *
1836 * @thread EMT.
1837 */
1838static DECLCALLBACK(int) vmR3Load(PVM pVM, const char *pszFilename, PCSSMSTRMOPS pStreamOps, void *pvStreamOpsUser,
1839 PFNVMPROGRESS pfnProgress, void *pvProgressUser, bool fTeleporting)
1840{
1841 LogFlow(("vmR3Load: pVM=%p pszFilename=%p:{%s} pStreamOps=%p pvStreamOpsUser=%p pfnProgress=%p pvProgressUser=%p fTeleporting=%RTbool\n",
1842 pVM, pszFilename, pszFilename, pStreamOps, pvStreamOpsUser, pfnProgress, pvProgressUser, fTeleporting));
1843
1844 /*
1845 * Validate input (paranoia).
1846 */
1847 AssertPtr(pVM);
1848 AssertPtrNull(pszFilename);
1849 AssertPtrNull(pStreamOps);
1850 AssertPtrNull(pfnProgress);
1851
1852 /*
1853 * Change the state and perform the load.
1854 *
1855 * Always perform a relocation round afterwards to make sure hypervisor
1856 * selectors and such are correct.
1857 */
1858 int rc = vmR3TrySetState(pVM, "VMR3Load", 2,
1859 VMSTATE_LOADING, VMSTATE_CREATED,
1860 VMSTATE_LOADING, VMSTATE_SUSPENDED);
1861 if (RT_FAILURE(rc))
1862 return rc;
1863 pVM->vm.s.fTeleportedAndNotFullyResumedYet = fTeleporting;
1864
1865 uint32_t cErrorsPriorToSave = VMR3GetErrorCount(pVM);
1866 rc = SSMR3Load(pVM, pszFilename, pStreamOps, pvStreamOpsUser, SSMAFTER_RESUME, pfnProgress, pvProgressUser);
1867 if (RT_SUCCESS(rc))
1868 {
1869 VMR3Relocate(pVM, 0 /*offDelta*/);
1870 vmR3SetState(pVM, VMSTATE_SUSPENDED, VMSTATE_LOADING);
1871 }
1872 else
1873 {
1874 pVM->vm.s.fTeleportedAndNotFullyResumedYet = false;
1875 vmR3SetState(pVM, VMSTATE_LOAD_FAILURE, VMSTATE_LOADING);
1876 if (cErrorsPriorToSave == VMR3GetErrorCount(pVM))
1877 rc = VMSetError(pVM, rc, RT_SRC_POS,
1878 N_("Unable to restore the virtual machine's saved state from '%s'. "
1879 "It may be damaged or from an older version of VirtualBox. "
1880 "Please discard the saved state before starting the virtual machine"),
1881 pszFilename);
1882 }
1883
1884 return rc;
1885}
1886
1887
1888/**
1889 * Loads a VM state into a newly created VM or a one that is suspended.
1890 *
1891 * To restore a saved state on VM startup, call this function and then resume
1892 * the VM instead of powering it on.
1893 *
1894 * @returns VBox status code.
1895 *
1896 * @param pVM The VM handle.
1897 * @param pszFilename The name of the save state file.
1898 * @param pfnProgress Progress callback. Optional.
1899 * @param pvUser User argument for the progress callback.
1900 *
1901 * @thread Any thread.
1902 * @vmstate Created, Suspended
1903 * @vmstateto Loading+Suspended
1904 */
1905VMMR3DECL(int) VMR3LoadFromFile(PVM pVM, const char *pszFilename, PFNVMPROGRESS pfnProgress, void *pvUser)
1906{
1907 LogFlow(("VMR3LoadFromFile: pVM=%p pszFilename=%p:{%s} pfnProgress=%p pvUser=%p\n",
1908 pVM, pszFilename, pszFilename, pfnProgress, pvUser));
1909
1910 /*
1911 * Validate input.
1912 */
1913 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
1914 AssertPtrReturn(pszFilename, VERR_INVALID_POINTER);
1915
1916 /*
1917 * Forward the request to EMT(0). No need to setup a rendezvous here
1918 * since there is no execution taking place when this call is allowed.
1919 */
1920 int rc = VMR3ReqCallWaitU(pVM->pUVM, 0 /*idDstCpu*/, (PFNRT)vmR3Load, 7,
1921 pVM, pszFilename, (uintptr_t)NULL /*pStreamOps*/, (uintptr_t)NULL /*pvStreamOpsUser*/, pfnProgress, pvUser,
1922 false /*fTeleporting*/);
1923 LogFlow(("VMR3LoadFromFile: returns %Rrc\n", rc));
1924 return rc;
1925}
1926
1927
1928/**
1929 * VMR3LoadFromFile for arbritrary file streams.
1930 *
1931 * @returns VBox status code.
1932 *
1933 * @param pVM The VM handle.
1934 * @param pStreamOps The stream methods.
1935 * @param pvStreamOpsUser The user argument to the stream methods.
1936 * @param pfnProgress Progress callback. Optional.
1937 * @param pvProgressUser User argument for the progress callback.
1938 *
1939 * @thread Any thread.
1940 * @vmstate Created, Suspended
1941 * @vmstateto Loading+Suspended
1942 */
1943VMMR3DECL(int) VMR3LoadFromStream(PVM pVM, PCSSMSTRMOPS pStreamOps, void *pvStreamOpsUser,
1944 PFNVMPROGRESS pfnProgress, void *pvProgressUser)
1945{
1946 LogFlow(("VMR3LoadFromStream: pVM=%p pStreamOps=%p pvStreamOpsUser=%p pfnProgress=%p pvProgressUser=%p\n",
1947 pVM, pStreamOps, pvStreamOpsUser, pfnProgress, pvProgressUser));
1948
1949 /*
1950 * Validate input.
1951 */
1952 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
1953 AssertPtrReturn(pStreamOps, VERR_INVALID_POINTER);
1954
1955 /*
1956 * Forward the request to EMT(0). No need to setup a rendezvous here
1957 * since there is no execution taking place when this call is allowed.
1958 */
1959 int rc = VMR3ReqCallWaitU(pVM->pUVM, 0 /*idDstCpu*/, (PFNRT)vmR3Load, 7,
1960 pVM, (uintptr_t)NULL /*pszFilename*/, pStreamOps, pvStreamOpsUser, pfnProgress, pvProgressUser,
1961 true /*fTeleporting*/);
1962 LogFlow(("VMR3LoadFromStream: returns %Rrc\n", rc));
1963 return rc;
1964}
1965
1966
1967/**
1968 * EMT rendezvous worker for VMR3PowerOff.
1969 *
1970 * @returns VERR_VM_INVALID_VM_STATE or VINF_EM_OFF. (This is a strict
1971 * return code, see FNVMMEMTRENDEZVOUS.)
1972 *
1973 * @param pVM The VM handle.
1974 * @param pVCpu The VMCPU handle of the EMT.
1975 * @param pvUser Ignored.
1976 */
1977static DECLCALLBACK(VBOXSTRICTRC) vmR3PowerOff(PVM pVM, PVMCPU pVCpu, void *pvUser)
1978{
1979 LogFlow(("vmR3PowerOff: pVM=%p pVCpu=%p/#%u\n", pVM, pVCpu, pVCpu->idCpu));
1980 Assert(!pvUser); NOREF(pvUser);
1981
1982 /*
1983 * The first EMT thru here will change the state to PoweringOff.
1984 */
1985 if (pVCpu->idCpu == pVM->cCpus - 1)
1986 {
1987 int rc = vmR3TrySetState(pVM, "VMR3PowerOff", 11,
1988 VMSTATE_POWERING_OFF, VMSTATE_RUNNING, /* 1 */
1989 VMSTATE_POWERING_OFF, VMSTATE_SUSPENDED, /* 2 */
1990 VMSTATE_POWERING_OFF, VMSTATE_DEBUGGING, /* 3 */
1991 VMSTATE_POWERING_OFF, VMSTATE_LOAD_FAILURE, /* 4 */
1992 VMSTATE_POWERING_OFF, VMSTATE_GURU_MEDITATION, /* 5 */
1993 VMSTATE_POWERING_OFF, VMSTATE_FATAL_ERROR, /* 6 */
1994 VMSTATE_POWERING_OFF, VMSTATE_CREATED, /* 7 */ /** @todo update the diagram! */
1995 VMSTATE_POWERING_OFF_LS, VMSTATE_RUNNING_LS, /* 8 */
1996 VMSTATE_POWERING_OFF_LS, VMSTATE_DEBUGGING_LS, /* 9 */
1997 VMSTATE_POWERING_OFF_LS, VMSTATE_GURU_MEDITATION_LS,/* 10 */
1998 VMSTATE_POWERING_OFF_LS, VMSTATE_FATAL_ERROR_LS); /* 11 */
1999 if (RT_FAILURE(rc))
2000 return rc;
2001 if (rc >= 7)
2002 SSMR3Cancel(pVM);
2003 }
2004
2005 /*
2006 * Check the state.
2007 */
2008 VMSTATE enmVMState = VMR3GetState(pVM);
2009 AssertMsgReturn( enmVMState == VMSTATE_POWERING_OFF
2010 || enmVMState == VMSTATE_POWERING_OFF_LS,
2011 ("%s\n", VMR3GetStateName(enmVMState)),
2012 VERR_VM_INVALID_VM_STATE);
2013
2014 /*
2015 * EMT(0) does the actual power off work here *after* all the other EMTs
2016 * have been thru and entered the STOPPED state.
2017 */
2018 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STOPPED);
2019 if (pVCpu->idCpu == 0)
2020 {
2021 /*
2022 * For debugging purposes, we will log a summary of the guest state at this point.
2023 */
2024 if (enmVMState != VMSTATE_GURU_MEDITATION)
2025 {
2026 /** @todo SMP support? */
2027 /** @todo make the state dumping at VMR3PowerOff optional. */
2028 RTLogRelPrintf("****************** Guest state at power off ******************\n");
2029 DBGFR3Info(pVM, "cpumguest", "verbose", DBGFR3InfoLogRelHlp());
2030 RTLogRelPrintf("***\n");
2031 DBGFR3Info(pVM, "mode", NULL, DBGFR3InfoLogRelHlp());
2032 RTLogRelPrintf("***\n");
2033 DBGFR3Info(pVM, "activetimers", NULL, DBGFR3InfoLogRelHlp());
2034 RTLogRelPrintf("***\n");
2035 DBGFR3Info(pVM, "gdt", NULL, DBGFR3InfoLogRelHlp());
2036 /** @todo dump guest call stack. */
2037#if 1 // "temporary" while debugging #1589
2038 RTLogRelPrintf("***\n");
2039 uint32_t esp = CPUMGetGuestESP(pVCpu);
2040 if ( CPUMGetGuestSS(pVCpu) == 0
2041 && esp < _64K)
2042 {
2043 uint8_t abBuf[PAGE_SIZE];
2044 RTLogRelPrintf("***\n"
2045 "ss:sp=0000:%04x ", esp);
2046 uint32_t Start = esp & ~(uint32_t)63;
2047 int rc = PGMPhysSimpleReadGCPhys(pVM, abBuf, Start, 0x100);
2048 if (RT_SUCCESS(rc))
2049 RTLogRelPrintf("0000:%04x TO 0000:%04x:\n"
2050 "%.*Rhxd\n",
2051 Start, Start + 0x100 - 1,
2052 0x100, abBuf);
2053 else
2054 RTLogRelPrintf("rc=%Rrc\n", rc);
2055
2056 /* grub ... */
2057 if (esp < 0x2000 && esp > 0x1fc0)
2058 {
2059 rc = PGMPhysSimpleReadGCPhys(pVM, abBuf, 0x8000, 0x800);
2060 if (RT_SUCCESS(rc))
2061 RTLogRelPrintf("0000:8000 TO 0000:87ff:\n"
2062 "%.*Rhxd\n",
2063 0x800, abBuf);
2064 }
2065 /* microsoft cdrom hang ... */
2066 if (true)
2067 {
2068 rc = PGMPhysSimpleReadGCPhys(pVM, abBuf, 0x8000, 0x200);
2069 if (RT_SUCCESS(rc))
2070 RTLogRelPrintf("2000:0000 TO 2000:01ff:\n"
2071 "%.*Rhxd\n",
2072 0x200, abBuf);
2073 }
2074 }
2075#endif
2076 RTLogRelPrintf("************** End of Guest state at power off ***************\n");
2077 }
2078
2079 /*
2080 * Perform the power off notifications and advance the state to
2081 * Off or OffLS.
2082 */
2083 PDMR3PowerOff(pVM);
2084
2085 PUVM pUVM = pVM->pUVM;
2086 RTCritSectEnter(&pUVM->vm.s.AtStateCritSect);
2087 enmVMState = pVM->enmVMState;
2088 if (enmVMState == VMSTATE_POWERING_OFF_LS)
2089 vmR3SetStateLocked(pVM, pUVM, VMSTATE_OFF_LS, VMSTATE_POWERING_OFF_LS);
2090 else
2091 vmR3SetStateLocked(pVM, pUVM, VMSTATE_OFF, VMSTATE_POWERING_OFF);
2092 RTCritSectLeave(&pUVM->vm.s.AtStateCritSect);
2093 }
2094 return VINF_EM_OFF;
2095}
2096
2097
2098/**
2099 * Power off the VM.
2100 *
2101 * @returns VBox status code. When called on EMT, this will be a strict status
2102 * code that has to be propagated up the call stack.
2103 *
2104 * @param pVM The handle of the VM to be powered off.
2105 *
2106 * @thread Any thread.
2107 * @vmstate Suspended, Running, Guru Meditation, Load Failure
2108 * @vmstateto Off or OffLS
2109 */
2110VMMR3DECL(int) VMR3PowerOff(PVM pVM)
2111{
2112 LogFlow(("VMR3PowerOff: pVM=%p\n", pVM));
2113 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
2114
2115 /*
2116 * Gather all the EMTs to make sure there are no races before
2117 * changing the VM state.
2118 */
2119 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_DESCENDING | VMMEMTRENDEZVOUS_FLAGS_STOP_ON_ERROR,
2120 vmR3PowerOff, NULL);
2121 LogFlow(("VMR3PowerOff: returns %Rrc\n", rc));
2122 return rc;
2123}
2124
2125
2126/**
2127 * Destroys the VM.
2128 *
2129 * The VM must be powered off (or never really powered on) to call this
2130 * function. The VM handle is destroyed and can no longer be used up successful
2131 * return.
2132 *
2133 * @returns VBox status code.
2134 *
2135 * @param pVM The handle of the VM which should be destroyed.
2136 *
2137 * @thread Any none emulation thread.
2138 * @vmstate Off, Created
2139 * @vmstateto N/A
2140 */
2141VMMR3DECL(int) VMR3Destroy(PVM pVM)
2142{
2143 LogFlow(("VMR3Destroy: pVM=%p\n", pVM));
2144
2145 /*
2146 * Validate input.
2147 */
2148 if (!pVM)
2149 return VERR_INVALID_PARAMETER;
2150 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
2151 AssertLogRelReturn(!VM_IS_EMT(pVM), VERR_VM_THREAD_IS_EMT);
2152
2153 /*
2154 * Change VM state to destroying and unlink the VM.
2155 */
2156 int rc = vmR3TrySetState(pVM, "VMR3Destroy", 1, VMSTATE_DESTROYING, VMSTATE_OFF);
2157 if (RT_FAILURE(rc))
2158 return rc;
2159
2160 /** @todo lock this when we start having multiple machines in a process... */
2161 PUVM pUVM = pVM->pUVM; AssertPtr(pUVM);
2162 if (g_pUVMsHead == pUVM)
2163 g_pUVMsHead = pUVM->pNext;
2164 else
2165 {
2166 PUVM pPrev = g_pUVMsHead;
2167 while (pPrev && pPrev->pNext != pUVM)
2168 pPrev = pPrev->pNext;
2169 AssertMsgReturn(pPrev, ("pUVM=%p / pVM=%p is INVALID!\n", pUVM, pVM), VERR_INVALID_PARAMETER);
2170
2171 pPrev->pNext = pUVM->pNext;
2172 }
2173 pUVM->pNext = NULL;
2174
2175 /*
2176 * Notify registered at destruction listeners.
2177 */
2178 vmR3AtDtor(pVM);
2179
2180 /*
2181 * Call vmR3Destroy on each of the EMTs ending with EMT(0) doing the bulk
2182 * of the cleanup.
2183 */
2184 /* vmR3Destroy on all EMTs, ending with EMT(0). */
2185 rc = VMR3ReqCallWaitU(pUVM, VMCPUID_ALL_REVERSE, (PFNRT)vmR3Destroy, 1, pVM);
2186 AssertLogRelRC(rc);
2187
2188 /* Wait for EMTs and destroy the UVM. */
2189 vmR3DestroyUVM(pUVM, 30000);
2190
2191 LogFlow(("VMR3Destroy: returns VINF_SUCCESS\n"));
2192 return VINF_SUCCESS;
2193}
2194
2195
2196/**
2197 * Internal destruction worker.
2198 *
2199 * This is either called from VMR3Destroy via VMR3ReqCallU or from
2200 * vmR3EmulationThreadWithId when EMT(0) terminates after having called
2201 * VMR3Destroy().
2202 *
2203 * When called on EMT(0), it will performed the great bulk of the destruction.
2204 * When called on the other EMTs, they will do nothing and the whole purpose is
2205 * to return VINF_EM_TERMINATE so they break out of their run loops.
2206 *
2207 * @returns VINF_EM_TERMINATE.
2208 * @param pVM The VM handle.
2209 */
2210DECLCALLBACK(int) vmR3Destroy(PVM pVM)
2211{
2212 PUVM pUVM = pVM->pUVM;
2213 PVMCPU pVCpu = VMMGetCpu(pVM);
2214 Assert(pVCpu);
2215 LogFlow(("vmR3Destroy: pVM=%p pUVM=%p pVCpu=%p idCpu=%u\n", pVM, pUVM, pVCpu, pVCpu->idCpu));
2216
2217 /*
2218 * Only VCPU 0 does the full cleanup (last).
2219 */
2220 if (pVCpu->idCpu == 0)
2221 {
2222 /*
2223 * Dump statistics to the log.
2224 */
2225#if defined(VBOX_WITH_STATISTICS) || defined(LOG_ENABLED)
2226 RTLogFlags(NULL, "nodisabled nobuffered");
2227#endif
2228#ifdef VBOX_WITH_STATISTICS
2229 STAMR3Dump(pVM, "*");
2230#else
2231 LogRel(("************************* Statistics *************************\n"));
2232 STAMR3DumpToReleaseLog(pVM, "*");
2233 LogRel(("********************* End of statistics **********************\n"));
2234#endif
2235
2236 /*
2237 * Destroy the VM components.
2238 */
2239 int rc = TMR3Term(pVM);
2240 AssertRC(rc);
2241#ifdef VBOX_WITH_DEBUGGER
2242 rc = DBGCTcpTerminate(pVM, pUVM->vm.s.pvDBGC);
2243 pUVM->vm.s.pvDBGC = NULL;
2244#endif
2245 AssertRC(rc);
2246 rc = DBGFR3Term(pVM);
2247 AssertRC(rc);
2248 rc = PDMR3Term(pVM);
2249 AssertRC(rc);
2250 rc = EMR3Term(pVM);
2251 AssertRC(rc);
2252 rc = IOMR3Term(pVM);
2253 AssertRC(rc);
2254 rc = CSAMR3Term(pVM);
2255 AssertRC(rc);
2256 rc = PATMR3Term(pVM);
2257 AssertRC(rc);
2258 rc = TRPMR3Term(pVM);
2259 AssertRC(rc);
2260 rc = SELMR3Term(pVM);
2261 AssertRC(rc);
2262 rc = REMR3Term(pVM);
2263 AssertRC(rc);
2264 rc = HWACCMR3Term(pVM);
2265 AssertRC(rc);
2266 rc = PGMR3Term(pVM);
2267 AssertRC(rc);
2268 rc = VMMR3Term(pVM); /* Terminates the ring-0 code! */
2269 AssertRC(rc);
2270 rc = CPUMR3Term(pVM);
2271 AssertRC(rc);
2272 SSMR3Term(pVM);
2273 rc = PDMR3CritSectTerm(pVM);
2274 AssertRC(rc);
2275 rc = MMR3Term(pVM);
2276 AssertRC(rc);
2277
2278 /*
2279 * We're done, tell the other EMTs to quit.
2280 */
2281 ASMAtomicUoWriteBool(&pUVM->vm.s.fTerminateEMT, true);
2282 ASMAtomicWriteU32(&pVM->fGlobalForcedActions, VM_FF_CHECK_VM_STATE); /* Can't hurt... */
2283 LogFlow(("vmR3Destroy: returning %Rrc\n", VINF_EM_TERMINATE));
2284 }
2285 return VINF_EM_TERMINATE;
2286}
2287
2288
2289/**
2290 * Destroys the UVM portion.
2291 *
2292 * This is called as the final step in the VM destruction or as the cleanup
2293 * in case of a creation failure.
2294 *
2295 * @param pVM VM Handle.
2296 * @param cMilliesEMTWait The number of milliseconds to wait for the emulation
2297 * threads.
2298 */
2299static void vmR3DestroyUVM(PUVM pUVM, uint32_t cMilliesEMTWait)
2300{
2301 /*
2302 * Signal termination of each the emulation threads and
2303 * wait for them to complete.
2304 */
2305 /* Signal them. */
2306 ASMAtomicUoWriteBool(&pUVM->vm.s.fTerminateEMT, true);
2307 if (pUVM->pVM)
2308 VM_FF_SET(pUVM->pVM, VM_FF_CHECK_VM_STATE); /* Can't hurt... */
2309 for (VMCPUID i = 0; i < pUVM->cCpus; i++)
2310 {
2311 VMR3NotifyGlobalFFU(pUVM, VMNOTIFYFF_FLAGS_DONE_REM);
2312 RTSemEventSignal(pUVM->aCpus[i].vm.s.EventSemWait);
2313 }
2314
2315 /* Wait for them. */
2316 uint64_t NanoTS = RTTimeNanoTS();
2317 RTTHREAD hSelf = RTThreadSelf();
2318 ASMAtomicUoWriteBool(&pUVM->vm.s.fTerminateEMT, true);
2319 for (VMCPUID i = 0; i < pUVM->cCpus; i++)
2320 {
2321 RTTHREAD hThread = pUVM->aCpus[i].vm.s.ThreadEMT;
2322 if ( hThread != NIL_RTTHREAD
2323 && hThread != hSelf)
2324 {
2325 uint64_t cMilliesElapsed = (RTTimeNanoTS() - NanoTS) / 1000000;
2326 int rc2 = RTThreadWait(hThread,
2327 cMilliesElapsed < cMilliesEMTWait
2328 ? RT_MAX(cMilliesEMTWait - cMilliesElapsed, 2000)
2329 : 2000,
2330 NULL);
2331 if (rc2 == VERR_TIMEOUT) /* avoid the assertion when debugging. */
2332 rc2 = RTThreadWait(hThread, 1000, NULL);
2333 AssertLogRelMsgRC(rc2, ("i=%u rc=%Rrc\n", i, rc2));
2334 if (RT_SUCCESS(rc2))
2335 pUVM->aCpus[0].vm.s.ThreadEMT = NIL_RTTHREAD;
2336 }
2337 }
2338
2339 /* Cleanup the semaphores. */
2340 for (VMCPUID i = 0; i < pUVM->cCpus; i++)
2341 {
2342 RTSemEventDestroy(pUVM->aCpus[i].vm.s.EventSemWait);
2343 pUVM->aCpus[i].vm.s.EventSemWait = NIL_RTSEMEVENT;
2344 }
2345
2346 /*
2347 * Free the event semaphores associated with the request packets.
2348 */
2349 unsigned cReqs = 0;
2350 for (unsigned i = 0; i < RT_ELEMENTS(pUVM->vm.s.apReqFree); i++)
2351 {
2352 PVMREQ pReq = pUVM->vm.s.apReqFree[i];
2353 pUVM->vm.s.apReqFree[i] = NULL;
2354 for (; pReq; pReq = pReq->pNext, cReqs++)
2355 {
2356 pReq->enmState = VMREQSTATE_INVALID;
2357 RTSemEventDestroy(pReq->EventSem);
2358 }
2359 }
2360 Assert(cReqs == pUVM->vm.s.cReqFree); NOREF(cReqs);
2361
2362 /*
2363 * Kill all queued requests. (There really shouldn't be any!)
2364 */
2365 for (unsigned i = 0; i < 10; i++)
2366 {
2367 PVMREQ pReqHead = ASMAtomicXchgPtrT(&pUVM->vm.s.pReqs, NULL, PVMREQ);
2368 AssertMsg(!pReqHead, ("This isn't supposed to happen! VMR3Destroy caller has to serialize this.\n"));
2369 if (!pReqHead)
2370 break;
2371 for (PVMREQ pReq = pReqHead; pReq; pReq = pReq->pNext)
2372 {
2373 ASMAtomicUoWriteSize(&pReq->iStatus, VERR_INTERNAL_ERROR);
2374 ASMAtomicWriteSize(&pReq->enmState, VMREQSTATE_INVALID);
2375 RTSemEventSignal(pReq->EventSem);
2376 RTThreadSleep(2);
2377 RTSemEventDestroy(pReq->EventSem);
2378 }
2379 /* give them a chance to respond before we free the request memory. */
2380 RTThreadSleep(32);
2381 }
2382
2383 /*
2384 * Now all queued VCPU requests (again, there shouldn't be any).
2385 */
2386 for (VMCPUID idCpu = 0; idCpu < pUVM->cCpus; idCpu++)
2387 {
2388 PUVMCPU pUVCpu = &pUVM->aCpus[idCpu];
2389
2390 for (unsigned i = 0; i < 10; i++)
2391 {
2392 PVMREQ pReqHead = ASMAtomicXchgPtrT(&pUVCpu->vm.s.pReqs, NULL, PVMREQ);
2393 AssertMsg(!pReqHead, ("This isn't supposed to happen! VMR3Destroy caller has to serialize this.\n"));
2394 if (!pReqHead)
2395 break;
2396 for (PVMREQ pReq = pReqHead; pReq; pReq = pReq->pNext)
2397 {
2398 ASMAtomicUoWriteSize(&pReq->iStatus, VERR_INTERNAL_ERROR);
2399 ASMAtomicWriteSize(&pReq->enmState, VMREQSTATE_INVALID);
2400 RTSemEventSignal(pReq->EventSem);
2401 RTThreadSleep(2);
2402 RTSemEventDestroy(pReq->EventSem);
2403 }
2404 /* give them a chance to respond before we free the request memory. */
2405 RTThreadSleep(32);
2406 }
2407 }
2408
2409 /*
2410 * Make sure the VMMR0.r0 module and whatever else is unloaded.
2411 */
2412 PDMR3TermUVM(pUVM);
2413
2414 /*
2415 * Terminate the support library if initialized.
2416 */
2417 if (pUVM->vm.s.pSession)
2418 {
2419 int rc = SUPR3Term(false /*fForced*/);
2420 AssertRC(rc);
2421 pUVM->vm.s.pSession = NIL_RTR0PTR;
2422 }
2423
2424 /*
2425 * Destroy the MM heap and free the UVM structure.
2426 */
2427 MMR3TermUVM(pUVM);
2428 STAMR3TermUVM(pUVM);
2429
2430#ifdef LOG_ENABLED
2431 RTLogSetCustomPrefixCallback(NULL, NULL, NULL);
2432#endif
2433 RTTlsFree(pUVM->vm.s.idxTLS);
2434
2435 ASMAtomicUoWriteU32(&pUVM->u32Magic, UINT32_MAX);
2436 RTMemPageFree(pUVM, sizeof(*pUVM));
2437
2438 RTLogFlush(NULL);
2439}
2440
2441
2442/**
2443 * Enumerates the VMs in this process.
2444 *
2445 * @returns Pointer to the next VM.
2446 * @returns NULL when no more VMs.
2447 * @param pVMPrev The previous VM
2448 * Use NULL to start the enumeration.
2449 */
2450VMMR3DECL(PVM) VMR3EnumVMs(PVM pVMPrev)
2451{
2452 /*
2453 * This is quick and dirty. It has issues with VM being
2454 * destroyed during the enumeration.
2455 */
2456 PUVM pNext;
2457 if (pVMPrev)
2458 pNext = pVMPrev->pUVM->pNext;
2459 else
2460 pNext = g_pUVMsHead;
2461 return pNext ? pNext->pVM : NULL;
2462}
2463
2464
2465/**
2466 * Registers an at VM destruction callback.
2467 *
2468 * @returns VBox status code.
2469 * @param pfnAtDtor Pointer to callback.
2470 * @param pvUser User argument.
2471 */
2472VMMR3DECL(int) VMR3AtDtorRegister(PFNVMATDTOR pfnAtDtor, void *pvUser)
2473{
2474 /*
2475 * Check if already registered.
2476 */
2477 VM_ATDTOR_LOCK();
2478 PVMATDTOR pCur = g_pVMAtDtorHead;
2479 while (pCur)
2480 {
2481 if (pfnAtDtor == pCur->pfnAtDtor)
2482 {
2483 VM_ATDTOR_UNLOCK();
2484 AssertMsgFailed(("Already registered at destruction callback %p!\n", pfnAtDtor));
2485 return VERR_INVALID_PARAMETER;
2486 }
2487
2488 /* next */
2489 pCur = pCur->pNext;
2490 }
2491 VM_ATDTOR_UNLOCK();
2492
2493 /*
2494 * Allocate new entry.
2495 */
2496 PVMATDTOR pVMAtDtor = (PVMATDTOR)RTMemAlloc(sizeof(*pVMAtDtor));
2497 if (!pVMAtDtor)
2498 return VERR_NO_MEMORY;
2499
2500 VM_ATDTOR_LOCK();
2501 pVMAtDtor->pfnAtDtor = pfnAtDtor;
2502 pVMAtDtor->pvUser = pvUser;
2503 pVMAtDtor->pNext = g_pVMAtDtorHead;
2504 g_pVMAtDtorHead = pVMAtDtor;
2505 VM_ATDTOR_UNLOCK();
2506
2507 return VINF_SUCCESS;
2508}
2509
2510
2511/**
2512 * Deregisters an at VM destruction callback.
2513 *
2514 * @returns VBox status code.
2515 * @param pfnAtDtor Pointer to callback.
2516 */
2517VMMR3DECL(int) VMR3AtDtorDeregister(PFNVMATDTOR pfnAtDtor)
2518{
2519 /*
2520 * Find it, unlink it and free it.
2521 */
2522 VM_ATDTOR_LOCK();
2523 PVMATDTOR pPrev = NULL;
2524 PVMATDTOR pCur = g_pVMAtDtorHead;
2525 while (pCur)
2526 {
2527 if (pfnAtDtor == pCur->pfnAtDtor)
2528 {
2529 if (pPrev)
2530 pPrev->pNext = pCur->pNext;
2531 else
2532 g_pVMAtDtorHead = pCur->pNext;
2533 pCur->pNext = NULL;
2534 VM_ATDTOR_UNLOCK();
2535
2536 RTMemFree(pCur);
2537 return VINF_SUCCESS;
2538 }
2539
2540 /* next */
2541 pPrev = pCur;
2542 pCur = pCur->pNext;
2543 }
2544 VM_ATDTOR_UNLOCK();
2545
2546 return VERR_INVALID_PARAMETER;
2547}
2548
2549
2550/**
2551 * Walks the list of at VM destructor callbacks.
2552 * @param pVM The VM which is about to be destroyed.
2553 */
2554static void vmR3AtDtor(PVM pVM)
2555{
2556 /*
2557 * Find it, unlink it and free it.
2558 */
2559 VM_ATDTOR_LOCK();
2560 for (PVMATDTOR pCur = g_pVMAtDtorHead; pCur; pCur = pCur->pNext)
2561 pCur->pfnAtDtor(pVM, pCur->pvUser);
2562 VM_ATDTOR_UNLOCK();
2563}
2564
2565
2566/**
2567 * Worker which checks integrity of some internal structures.
2568 * This is yet another attempt to track down that AVL tree crash.
2569 */
2570static void vmR3CheckIntegrity(PVM pVM)
2571{
2572#ifdef VBOX_STRICT
2573 int rc = PGMR3CheckIntegrity(pVM);
2574 AssertReleaseRC(rc);
2575#endif
2576}
2577
2578
2579/**
2580 * EMT rendezvous worker for VMR3Reset.
2581 *
2582 * This is called by the emulation threads as a response to the reset request
2583 * issued by VMR3Reset().
2584 *
2585 * @returns VERR_VM_INVALID_VM_STATE, VINF_EM_RESET or VINF_EM_SUSPEND. (This
2586 * is a strict return code, see FNVMMEMTRENDEZVOUS.)
2587 *
2588 * @param pVM The VM handle.
2589 * @param pVCpu The VMCPU handle of the EMT.
2590 * @param pvUser Ignored.
2591 */
2592static DECLCALLBACK(VBOXSTRICTRC) vmR3Reset(PVM pVM, PVMCPU pVCpu, void *pvUser)
2593{
2594 Assert(!pvUser); NOREF(pvUser);
2595
2596 /*
2597 * The first EMT will try change the state to resetting. If this fails,
2598 * we won't get called for the other EMTs.
2599 */
2600 if (pVCpu->idCpu == pVM->cCpus - 1)
2601 {
2602 int rc = vmR3TrySetState(pVM, "VMR3Reset", 3,
2603 VMSTATE_RESETTING, VMSTATE_RUNNING,
2604 VMSTATE_RESETTING, VMSTATE_SUSPENDED,
2605 VMSTATE_RESETTING_LS, VMSTATE_RUNNING_LS);
2606 if (RT_FAILURE(rc))
2607 return rc;
2608 }
2609
2610 /*
2611 * Check the state.
2612 */
2613 VMSTATE enmVMState = VMR3GetState(pVM);
2614 AssertLogRelMsgReturn( enmVMState == VMSTATE_RESETTING
2615 || enmVMState == VMSTATE_RESETTING_LS,
2616 ("%s\n", VMR3GetStateName(enmVMState)),
2617 VERR_INTERNAL_ERROR_4);
2618
2619 /*
2620 * EMT(0) does the full cleanup *after* all the other EMTs has been
2621 * thru here and been told to enter the EMSTATE_WAIT_SIPI state.
2622 *
2623 * Because there are per-cpu reset routines and order may/is important,
2624 * the following sequence looks a bit ugly...
2625 */
2626 if (pVCpu->idCpu == 0)
2627 vmR3CheckIntegrity(pVM);
2628
2629 /* Reset the VCpu state. */
2630 VMCPU_ASSERT_STATE(pVCpu, VMCPUSTATE_STARTED);
2631
2632 /* Clear all pending forced actions. */
2633 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_ALL_MASK & ~VMCPU_FF_REQUEST);
2634
2635 /*
2636 * Reset the VM components.
2637 */
2638 if (pVCpu->idCpu == 0)
2639 {
2640 PATMR3Reset(pVM);
2641 CSAMR3Reset(pVM);
2642 PGMR3Reset(pVM); /* We clear VM RAM in PGMR3Reset. It's vital PDMR3Reset is executed
2643 * _afterwards_. E.g. ACPI sets up RAM tables during init/reset. */
2644/** @todo PGMR3Reset should be called after PDMR3Reset really, because we'll trash OS <-> hardware
2645 * communication structures residing in RAM when done in the other order. I.e. the device must be
2646 * quiesced first, then we clear the memory and plan tables. Probably have to make these things
2647 * explicit in some way, some memory setup pass or something.
2648 * (Example: DevAHCI may assert if memory is zeroed before it've read the FIS.)
2649 *
2650 * @bugref{4467}
2651 */
2652 MMR3Reset(pVM);
2653 PDMR3Reset(pVM);
2654 SELMR3Reset(pVM);
2655 TRPMR3Reset(pVM);
2656 REMR3Reset(pVM);
2657 IOMR3Reset(pVM);
2658 CPUMR3Reset(pVM);
2659 }
2660 CPUMR3ResetCpu(pVCpu);
2661 if (pVCpu->idCpu == 0)
2662 {
2663 TMR3Reset(pVM);
2664 EMR3Reset(pVM);
2665 HWACCMR3Reset(pVM); /* This must come *after* PATM, CSAM, CPUM, SELM and TRPM. */
2666
2667#ifdef LOG_ENABLED
2668 /*
2669 * Debug logging.
2670 */
2671 RTLogPrintf("\n\nThe VM was reset:\n");
2672 DBGFR3Info(pVM, "cpum", "verbose", NULL);
2673#endif
2674
2675 /*
2676 * Since EMT(0) is the last to go thru here, it will advance the state.
2677 * When a live save is active, we will move on to SuspendingLS but
2678 * leave it for VMR3Reset to do the actual suspending due to deadlock risks.
2679 */
2680 PUVM pUVM = pVM->pUVM;
2681 RTCritSectEnter(&pUVM->vm.s.AtStateCritSect);
2682 enmVMState = pVM->enmVMState;
2683 if (enmVMState == VMSTATE_RESETTING)
2684 {
2685 if (pUVM->vm.s.enmPrevVMState == VMSTATE_SUSPENDED)
2686 vmR3SetStateLocked(pVM, pUVM, VMSTATE_SUSPENDED, VMSTATE_RESETTING);
2687 else
2688 vmR3SetStateLocked(pVM, pUVM, VMSTATE_RUNNING, VMSTATE_RESETTING);
2689 }
2690 else
2691 vmR3SetStateLocked(pVM, pUVM, VMSTATE_SUSPENDING_LS, VMSTATE_RESETTING_LS);
2692 RTCritSectLeave(&pUVM->vm.s.AtStateCritSect);
2693
2694 vmR3CheckIntegrity(pVM);
2695
2696 /*
2697 * Do the suspend bit as well.
2698 * It only requires some EMT(0) work at present.
2699 */
2700 if (enmVMState != VMSTATE_RESETTING)
2701 {
2702 vmR3SuspendDoWork(pVM);
2703 vmR3SetState(pVM, VMSTATE_SUSPENDED_LS, VMSTATE_SUSPENDING_LS);
2704 }
2705 }
2706
2707 return enmVMState == VMSTATE_RESETTING
2708 ? VINF_EM_RESET
2709 : VINF_EM_SUSPEND; /** @todo VINF_EM_SUSPEND has lower priority than VINF_EM_RESET, so fix races. Perhaps add a new code for this combined case. */
2710}
2711
2712
2713/**
2714 * Reset the current VM.
2715 *
2716 * @returns VBox status code.
2717 * @param pVM VM to reset.
2718 */
2719VMMR3DECL(int) VMR3Reset(PVM pVM)
2720{
2721 LogFlow(("VMR3Reset:\n"));
2722 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
2723
2724 /*
2725 * Gather all the EMTs to make sure there are no races before
2726 * changing the VM state.
2727 */
2728 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_DESCENDING | VMMEMTRENDEZVOUS_FLAGS_STOP_ON_ERROR,
2729 vmR3Reset, NULL);
2730 LogFlow(("VMR3Reset: returns %Rrc\n", rc));
2731 return rc;
2732}
2733
2734
2735/**
2736 * Gets the current VM state.
2737 *
2738 * @returns The current VM state.
2739 * @param pVM VM handle.
2740 * @thread Any
2741 */
2742VMMR3DECL(VMSTATE) VMR3GetState(PVM pVM)
2743{
2744 return pVM->enmVMState;
2745}
2746
2747
2748/**
2749 * Gets the state name string for a VM state.
2750 *
2751 * @returns Pointer to the state name. (readonly)
2752 * @param enmState The state.
2753 */
2754VMMR3DECL(const char *) VMR3GetStateName(VMSTATE enmState)
2755{
2756 switch (enmState)
2757 {
2758 case VMSTATE_CREATING: return "CREATING";
2759 case VMSTATE_CREATED: return "CREATED";
2760 case VMSTATE_LOADING: return "LOADING";
2761 case VMSTATE_POWERING_ON: return "POWERING_ON";
2762 case VMSTATE_RESUMING: return "RESUMING";
2763 case VMSTATE_RUNNING: return "RUNNING";
2764 case VMSTATE_RUNNING_LS: return "RUNNING_LS";
2765 case VMSTATE_RESETTING: return "RESETTING";
2766 case VMSTATE_RESETTING_LS: return "RESETTING_LS";
2767 case VMSTATE_SUSPENDED: return "SUSPENDED";
2768 case VMSTATE_SUSPENDED_LS: return "SUSPENDED_LS";
2769 case VMSTATE_SUSPENDED_EXT_LS: return "SUSPENDED_EXT_LS";
2770 case VMSTATE_SUSPENDING: return "SUSPENDING";
2771 case VMSTATE_SUSPENDING_LS: return "SUSPENDING_LS";
2772 case VMSTATE_SUSPENDING_EXT_LS: return "SUSPENDING_EXT_LS";
2773 case VMSTATE_SAVING: return "SAVING";
2774 case VMSTATE_DEBUGGING: return "DEBUGGING";
2775 case VMSTATE_DEBUGGING_LS: return "DEBUGGING_LS";
2776 case VMSTATE_POWERING_OFF: return "POWERING_OFF";
2777 case VMSTATE_POWERING_OFF_LS: return "POWERING_OFF_LS";
2778 case VMSTATE_FATAL_ERROR: return "FATAL_ERROR";
2779 case VMSTATE_FATAL_ERROR_LS: return "FATAL_ERROR_LS";
2780 case VMSTATE_GURU_MEDITATION: return "GURU_MEDITATION";
2781 case VMSTATE_GURU_MEDITATION_LS:return "GURU_MEDITATION_LS";
2782 case VMSTATE_LOAD_FAILURE: return "LOAD_FAILURE";
2783 case VMSTATE_OFF: return "OFF";
2784 case VMSTATE_OFF_LS: return "OFF_LS";
2785 case VMSTATE_DESTROYING: return "DESTROYING";
2786 case VMSTATE_TERMINATED: return "TERMINATED";
2787
2788 default:
2789 AssertMsgFailed(("Unknown state %d\n", enmState));
2790 return "Unknown!\n";
2791 }
2792}
2793
2794
2795/**
2796 * Validates the state transition in strict builds.
2797 *
2798 * @returns true if valid, false if not.
2799 *
2800 * @param enmStateOld The old (current) state.
2801 * @param enmStateNew The proposed new state.
2802 *
2803 * @remarks The reference for this is found in doc/vp/VMM.vpp, the VMSTATE
2804 * diagram (under State Machine Diagram).
2805 */
2806static bool vmR3ValidateStateTransition(VMSTATE enmStateOld, VMSTATE enmStateNew)
2807{
2808#ifdef VBOX_STRICT
2809 switch (enmStateOld)
2810 {
2811 case VMSTATE_CREATING:
2812 AssertMsgReturn(enmStateNew == VMSTATE_CREATED, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2813 break;
2814
2815 case VMSTATE_CREATED:
2816 AssertMsgReturn( enmStateNew == VMSTATE_LOADING
2817 || enmStateNew == VMSTATE_POWERING_ON
2818 || enmStateNew == VMSTATE_POWERING_OFF
2819 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2820 break;
2821
2822 case VMSTATE_LOADING:
2823 AssertMsgReturn( enmStateNew == VMSTATE_SUSPENDED
2824 || enmStateNew == VMSTATE_LOAD_FAILURE
2825 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2826 break;
2827
2828 case VMSTATE_POWERING_ON:
2829 AssertMsgReturn( enmStateNew == VMSTATE_RUNNING
2830 /*|| enmStateNew == VMSTATE_FATAL_ERROR ?*/
2831 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2832 break;
2833
2834 case VMSTATE_RESUMING:
2835 AssertMsgReturn( enmStateNew == VMSTATE_RUNNING
2836 /*|| enmStateNew == VMSTATE_FATAL_ERROR ?*/
2837 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2838 break;
2839
2840 case VMSTATE_RUNNING:
2841 AssertMsgReturn( enmStateNew == VMSTATE_POWERING_OFF
2842 || enmStateNew == VMSTATE_SUSPENDING
2843 || enmStateNew == VMSTATE_RESETTING
2844 || enmStateNew == VMSTATE_RUNNING_LS
2845 || enmStateNew == VMSTATE_DEBUGGING
2846 || enmStateNew == VMSTATE_FATAL_ERROR
2847 || enmStateNew == VMSTATE_GURU_MEDITATION
2848 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2849 break;
2850
2851 case VMSTATE_RUNNING_LS:
2852 AssertMsgReturn( enmStateNew == VMSTATE_POWERING_OFF_LS
2853 || enmStateNew == VMSTATE_SUSPENDING_LS
2854 || enmStateNew == VMSTATE_SUSPENDING_EXT_LS
2855 || enmStateNew == VMSTATE_RESETTING_LS
2856 || enmStateNew == VMSTATE_RUNNING
2857 || enmStateNew == VMSTATE_DEBUGGING_LS
2858 || enmStateNew == VMSTATE_FATAL_ERROR_LS
2859 || enmStateNew == VMSTATE_GURU_MEDITATION_LS
2860 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2861 break;
2862
2863 case VMSTATE_RESETTING:
2864 AssertMsgReturn(enmStateNew == VMSTATE_RUNNING, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2865 break;
2866
2867 case VMSTATE_RESETTING_LS:
2868 AssertMsgReturn( enmStateNew == VMSTATE_SUSPENDING_LS
2869 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2870 break;
2871
2872 case VMSTATE_SUSPENDING:
2873 AssertMsgReturn(enmStateNew == VMSTATE_SUSPENDED, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2874 break;
2875
2876 case VMSTATE_SUSPENDING_LS:
2877 AssertMsgReturn( enmStateNew == VMSTATE_SUSPENDING
2878 || enmStateNew == VMSTATE_SUSPENDED_LS
2879 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2880 break;
2881
2882 case VMSTATE_SUSPENDING_EXT_LS:
2883 AssertMsgReturn( enmStateNew == VMSTATE_SUSPENDING
2884 || enmStateNew == VMSTATE_SUSPENDED_EXT_LS
2885 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2886 break;
2887
2888 case VMSTATE_SUSPENDED:
2889 AssertMsgReturn( enmStateNew == VMSTATE_POWERING_OFF
2890 || enmStateNew == VMSTATE_SAVING
2891 || enmStateNew == VMSTATE_RESETTING
2892 || enmStateNew == VMSTATE_RESUMING
2893 || enmStateNew == VMSTATE_LOADING
2894 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2895 break;
2896
2897 case VMSTATE_SUSPENDED_LS:
2898 AssertMsgReturn( enmStateNew == VMSTATE_SUSPENDED
2899 || enmStateNew == VMSTATE_SAVING
2900 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2901 break;
2902
2903 case VMSTATE_SUSPENDED_EXT_LS:
2904 AssertMsgReturn( enmStateNew == VMSTATE_SUSPENDED
2905 || enmStateNew == VMSTATE_SAVING
2906 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2907 break;
2908
2909 case VMSTATE_SAVING:
2910 AssertMsgReturn(enmStateNew == VMSTATE_SUSPENDED, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2911 break;
2912
2913 case VMSTATE_DEBUGGING:
2914 AssertMsgReturn( enmStateNew == VMSTATE_RUNNING
2915 || enmStateNew == VMSTATE_POWERING_OFF
2916 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2917 break;
2918
2919 case VMSTATE_DEBUGGING_LS:
2920 AssertMsgReturn( enmStateNew == VMSTATE_DEBUGGING
2921 || enmStateNew == VMSTATE_RUNNING_LS
2922 || enmStateNew == VMSTATE_POWERING_OFF_LS
2923 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2924 break;
2925
2926 case VMSTATE_POWERING_OFF:
2927 AssertMsgReturn(enmStateNew == VMSTATE_OFF, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2928 break;
2929
2930 case VMSTATE_POWERING_OFF_LS:
2931 AssertMsgReturn( enmStateNew == VMSTATE_POWERING_OFF
2932 || enmStateNew == VMSTATE_OFF_LS
2933 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2934 break;
2935
2936 case VMSTATE_OFF:
2937 AssertMsgReturn(enmStateNew == VMSTATE_DESTROYING, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2938 break;
2939
2940 case VMSTATE_OFF_LS:
2941 AssertMsgReturn(enmStateNew == VMSTATE_OFF, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2942 break;
2943
2944 case VMSTATE_FATAL_ERROR:
2945 AssertMsgReturn(enmStateNew == VMSTATE_POWERING_OFF, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2946 break;
2947
2948 case VMSTATE_FATAL_ERROR_LS:
2949 AssertMsgReturn( enmStateNew == VMSTATE_FATAL_ERROR
2950 || enmStateNew == VMSTATE_POWERING_OFF_LS
2951 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2952 break;
2953
2954 case VMSTATE_GURU_MEDITATION:
2955 AssertMsgReturn( enmStateNew == VMSTATE_DEBUGGING
2956 || enmStateNew == VMSTATE_POWERING_OFF
2957 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2958 break;
2959
2960 case VMSTATE_GURU_MEDITATION_LS:
2961 AssertMsgReturn( enmStateNew == VMSTATE_GURU_MEDITATION
2962 || enmStateNew == VMSTATE_DEBUGGING_LS
2963 || enmStateNew == VMSTATE_POWERING_OFF_LS
2964 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2965 break;
2966
2967 case VMSTATE_LOAD_FAILURE:
2968 AssertMsgReturn(enmStateNew == VMSTATE_POWERING_OFF, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2969 break;
2970
2971 case VMSTATE_DESTROYING:
2972 AssertMsgReturn(enmStateNew == VMSTATE_TERMINATED, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2973 break;
2974
2975 case VMSTATE_TERMINATED:
2976 default:
2977 AssertMsgFailedReturn(("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2978 break;
2979 }
2980#endif /* VBOX_STRICT */
2981 return true;
2982}
2983
2984
2985/**
2986 * Does the state change callouts.
2987 *
2988 * The caller owns the AtStateCritSect.
2989 *
2990 * @param pVM The VM handle.
2991 * @param pUVM The UVM handle.
2992 * @param enmStateNew The New state.
2993 * @param enmStateOld The old state.
2994 */
2995static void vmR3DoAtState(PVM pVM, PUVM pUVM, VMSTATE enmStateNew, VMSTATE enmStateOld)
2996{
2997 LogRel(("Changing the VM state from '%s' to '%s'.\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)));
2998
2999 for (PVMATSTATE pCur = pUVM->vm.s.pAtState; pCur; pCur = pCur->pNext)
3000 {
3001 pCur->pfnAtState(pVM, enmStateNew, enmStateOld, pCur->pvUser);
3002 if ( enmStateNew != VMSTATE_DESTROYING
3003 && pVM->enmVMState == VMSTATE_DESTROYING)
3004 break;
3005 AssertMsg(pVM->enmVMState == enmStateNew,
3006 ("You are not allowed to change the state while in the change callback, except "
3007 "from destroying the VM. There are restrictions in the way the state changes "
3008 "are propagated up to the EM execution loop and it makes the program flow very "
3009 "difficult to follow. (%s, expected %s, old %s)\n",
3010 VMR3GetStateName(pVM->enmVMState), VMR3GetStateName(enmStateNew),
3011 VMR3GetStateName(enmStateOld)));
3012 }
3013}
3014
3015
3016/**
3017 * Sets the current VM state, with the AtStatCritSect already entered.
3018 *
3019 * @param pVM The VM handle.
3020 * @param pUVM The UVM handle.
3021 * @param enmStateNew The new state.
3022 * @param enmStateOld The old state.
3023 */
3024static void vmR3SetStateLocked(PVM pVM, PUVM pUVM, VMSTATE enmStateNew, VMSTATE enmStateOld)
3025{
3026 vmR3ValidateStateTransition(enmStateOld, enmStateNew);
3027
3028 AssertMsg(pVM->enmVMState == enmStateOld,
3029 ("%s != %s\n", VMR3GetStateName(pVM->enmVMState), VMR3GetStateName(enmStateOld)));
3030 pUVM->vm.s.enmPrevVMState = enmStateOld;
3031 pVM->enmVMState = enmStateNew;
3032 VM_FF_CLEAR(pVM, VM_FF_CHECK_VM_STATE);
3033
3034 vmR3DoAtState(pVM, pUVM, enmStateNew, enmStateOld);
3035}
3036
3037
3038/**
3039 * Sets the current VM state.
3040 *
3041 * @param pVM VM handle.
3042 * @param enmStateNew The new state.
3043 * @param enmStateOld The old state (for asserting only).
3044 */
3045static void vmR3SetState(PVM pVM, VMSTATE enmStateNew, VMSTATE enmStateOld)
3046{
3047 PUVM pUVM = pVM->pUVM;
3048 RTCritSectEnter(&pUVM->vm.s.AtStateCritSect);
3049
3050 AssertMsg(pVM->enmVMState == enmStateOld,
3051 ("%s != %s\n", VMR3GetStateName(pVM->enmVMState), VMR3GetStateName(enmStateOld)));
3052 vmR3SetStateLocked(pVM, pUVM, enmStateNew, pVM->enmVMState);
3053
3054 RTCritSectLeave(&pUVM->vm.s.AtStateCritSect);
3055}
3056
3057
3058/**
3059 * Tries to perform a state transition.
3060 *
3061 * @returns The 1-based ordinal of the succeeding transition.
3062 * VERR_VM_INVALID_VM_STATE and Assert+LogRel on failure.
3063 *
3064 * @param pVM The VM handle.
3065 * @param pszWho Who is trying to change it.
3066 * @param cTransitions The number of transitions in the ellipsis.
3067 * @param ... Transition pairs; new, old.
3068 */
3069static int vmR3TrySetState(PVM pVM, const char *pszWho, unsigned cTransitions, ...)
3070{
3071 va_list va;
3072 VMSTATE enmStateNew = VMSTATE_CREATED;
3073 VMSTATE enmStateOld = VMSTATE_CREATED;
3074
3075#ifdef VBOX_STRICT
3076 /*
3077 * Validate the input first.
3078 */
3079 va_start(va, cTransitions);
3080 for (unsigned i = 0; i < cTransitions; i++)
3081 {
3082 enmStateNew = (VMSTATE)va_arg(va, /*VMSTATE*/int);
3083 enmStateOld = (VMSTATE)va_arg(va, /*VMSTATE*/int);
3084 vmR3ValidateStateTransition(enmStateOld, enmStateNew);
3085 }
3086 va_end(va);
3087#endif
3088
3089 /*
3090 * Grab the lock and see if any of the proposed transisions works out.
3091 */
3092 va_start(va, cTransitions);
3093 int rc = VERR_VM_INVALID_VM_STATE;
3094 PUVM pUVM = pVM->pUVM;
3095 RTCritSectEnter(&pUVM->vm.s.AtStateCritSect);
3096
3097 VMSTATE enmStateCur = pVM->enmVMState;
3098
3099 for (unsigned i = 0; i < cTransitions; i++)
3100 {
3101 enmStateNew = (VMSTATE)va_arg(va, /*VMSTATE*/int);
3102 enmStateOld = (VMSTATE)va_arg(va, /*VMSTATE*/int);
3103 if (enmStateCur == enmStateOld)
3104 {
3105 vmR3SetStateLocked(pVM, pUVM, enmStateNew, enmStateOld);
3106 rc = i + 1;
3107 break;
3108 }
3109 }
3110
3111 if (RT_FAILURE(rc))
3112 {
3113 /*
3114 * Complain about it.
3115 */
3116 if (cTransitions == 1)
3117 {
3118 LogRel(("%s: %s -> %s failed, because the VM state is actually %s\n",
3119 pszWho, VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew), VMR3GetStateName(enmStateCur)));
3120 VMSetError(pVM, VERR_VM_INVALID_VM_STATE, RT_SRC_POS,
3121 N_("%s failed because the VM state is %s instead of %s"),
3122 pszWho, VMR3GetStateName(enmStateCur), VMR3GetStateName(enmStateOld));
3123 AssertMsgFailed(("%s: %s -> %s failed, because the VM state is actually %s\n",
3124 pszWho, VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew), VMR3GetStateName(enmStateCur)));
3125 }
3126 else
3127 {
3128 va_end(va);
3129 va_start(va, cTransitions);
3130 LogRel(("%s:\n", pszWho));
3131 for (unsigned i = 0; i < cTransitions; i++)
3132 {
3133 enmStateNew = (VMSTATE)va_arg(va, /*VMSTATE*/int);
3134 enmStateOld = (VMSTATE)va_arg(va, /*VMSTATE*/int);
3135 LogRel(("%s%s -> %s",
3136 i ? ", " : " ", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)));
3137 }
3138 LogRel((" failed, because the VM state is actually %s\n", VMR3GetStateName(enmStateCur)));
3139 VMSetError(pVM, VERR_VM_INVALID_VM_STATE, RT_SRC_POS,
3140 N_("%s failed because the current VM state, %s, was not found in the state transition table"),
3141 pszWho, VMR3GetStateName(enmStateCur), VMR3GetStateName(enmStateOld));
3142 AssertMsgFailed(("%s - state=%s, see release log for full details. Check the cTransitions passed us.\n",
3143 pszWho, VMR3GetStateName(enmStateCur)));
3144 }
3145 }
3146
3147 RTCritSectLeave(&pUVM->vm.s.AtStateCritSect);
3148 va_end(va);
3149 Assert(rc > 0 || rc < 0);
3150 return rc;
3151}
3152
3153
3154/**
3155 * Flag a guru meditation ... a hack.
3156 *
3157 * @param pVM The VM handle
3158 *
3159 * @todo Rewrite this part. The guru meditation should be flagged
3160 * immediately by the VMM and not by VMEmt.cpp when it's all over.
3161 */
3162void vmR3SetGuruMeditation(PVM pVM)
3163{
3164 PUVM pUVM = pVM->pUVM;
3165 RTCritSectEnter(&pUVM->vm.s.AtStateCritSect);
3166
3167 VMSTATE enmStateCur = pVM->enmVMState;
3168 if (enmStateCur == VMSTATE_RUNNING)
3169 vmR3SetStateLocked(pVM, pUVM, VMSTATE_GURU_MEDITATION, VMSTATE_RUNNING);
3170 else if (enmStateCur == VMSTATE_RUNNING_LS)
3171 {
3172 vmR3SetStateLocked(pVM, pUVM, VMSTATE_GURU_MEDITATION_LS, VMSTATE_RUNNING_LS);
3173 SSMR3Cancel(pVM);
3174 }
3175
3176 RTCritSectLeave(&pUVM->vm.s.AtStateCritSect);
3177}
3178
3179
3180/**
3181 * Called by vmR3EmulationThreadWithId just before the VM structure is freed.
3182 *
3183 * @param pVM The VM handle.
3184 */
3185void vmR3SetTerminated(PVM pVM)
3186{
3187 vmR3SetState(pVM, VMSTATE_TERMINATED, VMSTATE_DESTROYING);
3188}
3189
3190
3191/**
3192 * Checks if the VM was teleported and hasn't been fully resumed yet.
3193 *
3194 * This applies to both sides of the teleportation since we may leave a working
3195 * clone behind and the user is allowed to resume this...
3196 *
3197 * @returns true / false.
3198 * @param pVM The VM handle.
3199 * @thread Any thread.
3200 */
3201VMMR3DECL(bool) VMR3TeleportedAndNotFullyResumedYet(PVM pVM)
3202{
3203 VM_ASSERT_VALID_EXT_RETURN(pVM, false);
3204 return pVM->vm.s.fTeleportedAndNotFullyResumedYet;
3205}
3206
3207
3208/**
3209 * Registers a VM state change callback.
3210 *
3211 * You are not allowed to call any function which changes the VM state from a
3212 * state callback.
3213 *
3214 * @returns VBox status code.
3215 * @param pVM VM handle.
3216 * @param pfnAtState Pointer to callback.
3217 * @param pvUser User argument.
3218 * @thread Any.
3219 */
3220VMMR3DECL(int) VMR3AtStateRegister(PVM pVM, PFNVMATSTATE pfnAtState, void *pvUser)
3221{
3222 LogFlow(("VMR3AtStateRegister: pfnAtState=%p pvUser=%p\n", pfnAtState, pvUser));
3223
3224 /*
3225 * Validate input.
3226 */
3227 AssertPtrReturn(pfnAtState, VERR_INVALID_PARAMETER);
3228 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
3229
3230 /*
3231 * Allocate a new record.
3232 */
3233 PUVM pUVM = pVM->pUVM;
3234 PVMATSTATE pNew = (PVMATSTATE)MMR3HeapAllocU(pUVM, MM_TAG_VM, sizeof(*pNew));
3235 if (!pNew)
3236 return VERR_NO_MEMORY;
3237
3238 /* fill */
3239 pNew->pfnAtState = pfnAtState;
3240 pNew->pvUser = pvUser;
3241
3242 /* insert */
3243 RTCritSectEnter(&pUVM->vm.s.AtStateCritSect);
3244 pNew->pNext = *pUVM->vm.s.ppAtStateNext;
3245 *pUVM->vm.s.ppAtStateNext = pNew;
3246 pUVM->vm.s.ppAtStateNext = &pNew->pNext;
3247 RTCritSectLeave(&pUVM->vm.s.AtStateCritSect);
3248
3249 return VINF_SUCCESS;
3250}
3251
3252
3253/**
3254 * Deregisters a VM state change callback.
3255 *
3256 * @returns VBox status code.
3257 * @param pVM VM handle.
3258 * @param pfnAtState Pointer to callback.
3259 * @param pvUser User argument.
3260 * @thread Any.
3261 */
3262VMMR3DECL(int) VMR3AtStateDeregister(PVM pVM, PFNVMATSTATE pfnAtState, void *pvUser)
3263{
3264 LogFlow(("VMR3AtStateDeregister: pfnAtState=%p pvUser=%p\n", pfnAtState, pvUser));
3265
3266 /*
3267 * Validate input.
3268 */
3269 AssertPtrReturn(pfnAtState, VERR_INVALID_PARAMETER);
3270 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
3271
3272 PUVM pUVM = pVM->pUVM;
3273 RTCritSectEnter(&pUVM->vm.s.AtStateCritSect);
3274
3275 /*
3276 * Search the list for the entry.
3277 */
3278 PVMATSTATE pPrev = NULL;
3279 PVMATSTATE pCur = pUVM->vm.s.pAtState;
3280 while ( pCur
3281 && ( pCur->pfnAtState != pfnAtState
3282 || pCur->pvUser != pvUser))
3283 {
3284 pPrev = pCur;
3285 pCur = pCur->pNext;
3286 }
3287 if (!pCur)
3288 {
3289 AssertMsgFailed(("pfnAtState=%p was not found\n", pfnAtState));
3290 RTCritSectLeave(&pUVM->vm.s.AtStateCritSect);
3291 return VERR_FILE_NOT_FOUND;
3292 }
3293
3294 /*
3295 * Unlink it.
3296 */
3297 if (pPrev)
3298 {
3299 pPrev->pNext = pCur->pNext;
3300 if (!pCur->pNext)
3301 pUVM->vm.s.ppAtStateNext = &pPrev->pNext;
3302 }
3303 else
3304 {
3305 pUVM->vm.s.pAtState = pCur->pNext;
3306 if (!pCur->pNext)
3307 pUVM->vm.s.ppAtStateNext = &pUVM->vm.s.pAtState;
3308 }
3309
3310 RTCritSectLeave(&pUVM->vm.s.AtStateCritSect);
3311
3312 /*
3313 * Free it.
3314 */
3315 pCur->pfnAtState = NULL;
3316 pCur->pNext = NULL;
3317 MMR3HeapFree(pCur);
3318
3319 return VINF_SUCCESS;
3320}
3321
3322
3323/**
3324 * Registers a VM error callback.
3325 *
3326 * @returns VBox status code.
3327 * @param pVM The VM handle.
3328 * @param pfnAtError Pointer to callback.
3329 * @param pvUser User argument.
3330 * @thread Any.
3331 */
3332VMMR3DECL(int) VMR3AtErrorRegister(PVM pVM, PFNVMATERROR pfnAtError, void *pvUser)
3333{
3334 return VMR3AtErrorRegisterU(pVM->pUVM, pfnAtError, pvUser);
3335}
3336
3337
3338/**
3339 * Registers a VM error callback.
3340 *
3341 * @returns VBox status code.
3342 * @param pUVM The VM handle.
3343 * @param pfnAtError Pointer to callback.
3344 * @param pvUser User argument.
3345 * @thread Any.
3346 */
3347VMMR3DECL(int) VMR3AtErrorRegisterU(PUVM pUVM, PFNVMATERROR pfnAtError, void *pvUser)
3348{
3349 LogFlow(("VMR3AtErrorRegister: pfnAtError=%p pvUser=%p\n", pfnAtError, pvUser));
3350
3351 /*
3352 * Validate input.
3353 */
3354 AssertPtrReturn(pfnAtError, VERR_INVALID_PARAMETER);
3355 UVM_ASSERT_VALID_EXT_RETURN(pUVM, VERR_INVALID_VM_HANDLE);
3356
3357 /*
3358 * Allocate a new record.
3359 */
3360 PVMATERROR pNew = (PVMATERROR)MMR3HeapAllocU(pUVM, MM_TAG_VM, sizeof(*pNew));
3361 if (!pNew)
3362 return VERR_NO_MEMORY;
3363
3364 /* fill */
3365 pNew->pfnAtError = pfnAtError;
3366 pNew->pvUser = pvUser;
3367
3368 /* insert */
3369 RTCritSectEnter(&pUVM->vm.s.AtErrorCritSect);
3370 pNew->pNext = *pUVM->vm.s.ppAtErrorNext;
3371 *pUVM->vm.s.ppAtErrorNext = pNew;
3372 pUVM->vm.s.ppAtErrorNext = &pNew->pNext;
3373 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3374
3375 return VINF_SUCCESS;
3376}
3377
3378
3379/**
3380 * Deregisters a VM error callback.
3381 *
3382 * @returns VBox status code.
3383 * @param pVM The VM handle.
3384 * @param pfnAtError Pointer to callback.
3385 * @param pvUser User argument.
3386 * @thread Any.
3387 */
3388VMMR3DECL(int) VMR3AtErrorDeregister(PVM pVM, PFNVMATERROR pfnAtError, void *pvUser)
3389{
3390 LogFlow(("VMR3AtErrorDeregister: pfnAtError=%p pvUser=%p\n", pfnAtError, pvUser));
3391
3392 /*
3393 * Validate input.
3394 */
3395 AssertPtrReturn(pfnAtError, VERR_INVALID_PARAMETER);
3396 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
3397
3398 PUVM pUVM = pVM->pUVM;
3399 RTCritSectEnter(&pUVM->vm.s.AtErrorCritSect);
3400
3401 /*
3402 * Search the list for the entry.
3403 */
3404 PVMATERROR pPrev = NULL;
3405 PVMATERROR pCur = pUVM->vm.s.pAtError;
3406 while ( pCur
3407 && ( pCur->pfnAtError != pfnAtError
3408 || pCur->pvUser != pvUser))
3409 {
3410 pPrev = pCur;
3411 pCur = pCur->pNext;
3412 }
3413 if (!pCur)
3414 {
3415 AssertMsgFailed(("pfnAtError=%p was not found\n", pfnAtError));
3416 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3417 return VERR_FILE_NOT_FOUND;
3418 }
3419
3420 /*
3421 * Unlink it.
3422 */
3423 if (pPrev)
3424 {
3425 pPrev->pNext = pCur->pNext;
3426 if (!pCur->pNext)
3427 pUVM->vm.s.ppAtErrorNext = &pPrev->pNext;
3428 }
3429 else
3430 {
3431 pUVM->vm.s.pAtError = pCur->pNext;
3432 if (!pCur->pNext)
3433 pUVM->vm.s.ppAtErrorNext = &pUVM->vm.s.pAtError;
3434 }
3435
3436 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3437
3438 /*
3439 * Free it.
3440 */
3441 pCur->pfnAtError = NULL;
3442 pCur->pNext = NULL;
3443 MMR3HeapFree(pCur);
3444
3445 return VINF_SUCCESS;
3446}
3447
3448
3449/**
3450 * Ellipsis to va_list wrapper for calling pfnAtError.
3451 */
3452static void vmR3SetErrorWorkerDoCall(PVM pVM, PVMATERROR pCur, int rc, RT_SRC_POS_DECL, const char *pszFormat, ...)
3453{
3454 va_list va;
3455 va_start(va, pszFormat);
3456 pCur->pfnAtError(pVM, pCur->pvUser, rc, RT_SRC_POS_ARGS, pszFormat, va);
3457 va_end(va);
3458}
3459
3460
3461/**
3462 * This is a worker function for GC and Ring-0 calls to VMSetError and VMSetErrorV.
3463 * The message is found in VMINT.
3464 *
3465 * @param pVM The VM handle.
3466 * @thread EMT.
3467 */
3468VMMR3DECL(void) VMR3SetErrorWorker(PVM pVM)
3469{
3470 VM_ASSERT_EMT(pVM);
3471 AssertReleaseMsgFailed(("And we have a winner! You get to implement Ring-0 and GC VMSetErrorV! Contrats!\n"));
3472
3473 /*
3474 * Unpack the error (if we managed to format one).
3475 */
3476 PVMERROR pErr = pVM->vm.s.pErrorR3;
3477 const char *pszFile = NULL;
3478 const char *pszFunction = NULL;
3479 uint32_t iLine = 0;
3480 const char *pszMessage;
3481 int32_t rc = VERR_MM_HYPER_NO_MEMORY;
3482 if (pErr)
3483 {
3484 AssertCompile(sizeof(const char) == sizeof(uint8_t));
3485 if (pErr->offFile)
3486 pszFile = (const char *)pErr + pErr->offFile;
3487 iLine = pErr->iLine;
3488 if (pErr->offFunction)
3489 pszFunction = (const char *)pErr + pErr->offFunction;
3490 if (pErr->offMessage)
3491 pszMessage = (const char *)pErr + pErr->offMessage;
3492 else
3493 pszMessage = "No message!";
3494 }
3495 else
3496 pszMessage = "No message! (Failed to allocate memory to put the error message in!)";
3497
3498 /*
3499 * Call the at error callbacks.
3500 */
3501 PUVM pUVM = pVM->pUVM;
3502 RTCritSectEnter(&pUVM->vm.s.AtErrorCritSect);
3503 ASMAtomicIncU32(&pUVM->vm.s.cRuntimeErrors);
3504 for (PVMATERROR pCur = pUVM->vm.s.pAtError; pCur; pCur = pCur->pNext)
3505 vmR3SetErrorWorkerDoCall(pVM, pCur, rc, RT_SRC_POS_ARGS, "%s", pszMessage);
3506 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3507}
3508
3509
3510/**
3511 * Gets the number of errors raised via VMSetError.
3512 *
3513 * This can be used avoid double error messages.
3514 *
3515 * @returns The error count.
3516 * @param pVM The VM handle.
3517 */
3518VMMR3DECL(uint32_t) VMR3GetErrorCount(PVM pVM)
3519{
3520 return pVM->pUVM->vm.s.cErrors;
3521}
3522
3523
3524/**
3525 * Creation time wrapper for vmR3SetErrorUV.
3526 *
3527 * @returns rc.
3528 * @param pUVM Pointer to the user mode VM structure.
3529 * @param rc The VBox status code.
3530 * @param RT_SRC_POS_DECL The source position of this error.
3531 * @param pszFormat Format string.
3532 * @param ... The arguments.
3533 * @thread Any thread.
3534 */
3535static int vmR3SetErrorU(PUVM pUVM, int rc, RT_SRC_POS_DECL, const char *pszFormat, ...)
3536{
3537 va_list va;
3538 va_start(va, pszFormat);
3539 vmR3SetErrorUV(pUVM, rc, pszFile, iLine, pszFunction, pszFormat, &va);
3540 va_end(va);
3541 return rc;
3542}
3543
3544
3545/**
3546 * Worker which calls everyone listening to the VM error messages.
3547 *
3548 * @param pUVM Pointer to the user mode VM structure.
3549 * @param rc The VBox status code.
3550 * @param RT_SRC_POS_DECL The source position of this error.
3551 * @param pszFormat Format string.
3552 * @param pArgs Pointer to the format arguments.
3553 * @thread EMT
3554 */
3555DECLCALLBACK(void) vmR3SetErrorUV(PUVM pUVM, int rc, RT_SRC_POS_DECL, const char *pszFormat, va_list *pArgs)
3556{
3557 /*
3558 * Log the error.
3559 */
3560 va_list va3;
3561 va_copy(va3, *pArgs);
3562 RTLogRelPrintf("VMSetError: %s(%d) %s; rc=%Rrc\n"
3563 "VMSetError: %N\n",
3564 pszFile, iLine, pszFunction, rc,
3565 pszFormat, &va3);
3566 va_end(va3);
3567
3568#ifdef LOG_ENABLED
3569 va_copy(va3, *pArgs);
3570 RTLogPrintf("VMSetError: %s(%d) %s; rc=%Rrc\n"
3571 "%N\n",
3572 pszFile, iLine, pszFunction, rc,
3573 pszFormat, &va3);
3574 va_end(va3);
3575#endif
3576
3577 /*
3578 * Make a copy of the message.
3579 */
3580 if (pUVM->pVM)
3581 vmSetErrorCopy(pUVM->pVM, rc, RT_SRC_POS_ARGS, pszFormat, *pArgs);
3582
3583 /*
3584 * Call the at error callbacks.
3585 */
3586 bool fCalledSomeone = false;
3587 RTCritSectEnter(&pUVM->vm.s.AtErrorCritSect);
3588 ASMAtomicIncU32(&pUVM->vm.s.cErrors);
3589 for (PVMATERROR pCur = pUVM->vm.s.pAtError; pCur; pCur = pCur->pNext)
3590 {
3591 va_list va2;
3592 va_copy(va2, *pArgs);
3593 pCur->pfnAtError(pUVM->pVM, pCur->pvUser, rc, RT_SRC_POS_ARGS, pszFormat, va2);
3594 va_end(va2);
3595 fCalledSomeone = true;
3596 }
3597 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3598}
3599
3600
3601/**
3602 * Registers a VM runtime error callback.
3603 *
3604 * @returns VBox status code.
3605 * @param pVM The VM handle.
3606 * @param pfnAtRuntimeError Pointer to callback.
3607 * @param pvUser User argument.
3608 * @thread Any.
3609 */
3610VMMR3DECL(int) VMR3AtRuntimeErrorRegister(PVM pVM, PFNVMATRUNTIMEERROR pfnAtRuntimeError, void *pvUser)
3611{
3612 LogFlow(("VMR3AtRuntimeErrorRegister: pfnAtRuntimeError=%p pvUser=%p\n", pfnAtRuntimeError, pvUser));
3613
3614 /*
3615 * Validate input.
3616 */
3617 AssertPtrReturn(pfnAtRuntimeError, VERR_INVALID_PARAMETER);
3618 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
3619
3620 /*
3621 * Allocate a new record.
3622 */
3623 PUVM pUVM = pVM->pUVM;
3624 PVMATRUNTIMEERROR pNew = (PVMATRUNTIMEERROR)MMR3HeapAllocU(pUVM, MM_TAG_VM, sizeof(*pNew));
3625 if (!pNew)
3626 return VERR_NO_MEMORY;
3627
3628 /* fill */
3629 pNew->pfnAtRuntimeError = pfnAtRuntimeError;
3630 pNew->pvUser = pvUser;
3631
3632 /* insert */
3633 RTCritSectEnter(&pUVM->vm.s.AtErrorCritSect);
3634 pNew->pNext = *pUVM->vm.s.ppAtRuntimeErrorNext;
3635 *pUVM->vm.s.ppAtRuntimeErrorNext = pNew;
3636 pUVM->vm.s.ppAtRuntimeErrorNext = &pNew->pNext;
3637 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3638
3639 return VINF_SUCCESS;
3640}
3641
3642
3643/**
3644 * Deregisters a VM runtime error callback.
3645 *
3646 * @returns VBox status code.
3647 * @param pVM The VM handle.
3648 * @param pfnAtRuntimeError Pointer to callback.
3649 * @param pvUser User argument.
3650 * @thread Any.
3651 */
3652VMMR3DECL(int) VMR3AtRuntimeErrorDeregister(PVM pVM, PFNVMATRUNTIMEERROR pfnAtRuntimeError, void *pvUser)
3653{
3654 LogFlow(("VMR3AtRuntimeErrorDeregister: pfnAtRuntimeError=%p pvUser=%p\n", pfnAtRuntimeError, pvUser));
3655
3656 /*
3657 * Validate input.
3658 */
3659 AssertPtrReturn(pfnAtRuntimeError, VERR_INVALID_PARAMETER);
3660 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
3661
3662 PUVM pUVM = pVM->pUVM;
3663 RTCritSectEnter(&pUVM->vm.s.AtErrorCritSect);
3664
3665 /*
3666 * Search the list for the entry.
3667 */
3668 PVMATRUNTIMEERROR pPrev = NULL;
3669 PVMATRUNTIMEERROR pCur = pUVM->vm.s.pAtRuntimeError;
3670 while ( pCur
3671 && ( pCur->pfnAtRuntimeError != pfnAtRuntimeError
3672 || pCur->pvUser != pvUser))
3673 {
3674 pPrev = pCur;
3675 pCur = pCur->pNext;
3676 }
3677 if (!pCur)
3678 {
3679 AssertMsgFailed(("pfnAtRuntimeError=%p was not found\n", pfnAtRuntimeError));
3680 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3681 return VERR_FILE_NOT_FOUND;
3682 }
3683
3684 /*
3685 * Unlink it.
3686 */
3687 if (pPrev)
3688 {
3689 pPrev->pNext = pCur->pNext;
3690 if (!pCur->pNext)
3691 pUVM->vm.s.ppAtRuntimeErrorNext = &pPrev->pNext;
3692 }
3693 else
3694 {
3695 pUVM->vm.s.pAtRuntimeError = pCur->pNext;
3696 if (!pCur->pNext)
3697 pUVM->vm.s.ppAtRuntimeErrorNext = &pUVM->vm.s.pAtRuntimeError;
3698 }
3699
3700 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3701
3702 /*
3703 * Free it.
3704 */
3705 pCur->pfnAtRuntimeError = NULL;
3706 pCur->pNext = NULL;
3707 MMR3HeapFree(pCur);
3708
3709 return VINF_SUCCESS;
3710}
3711
3712
3713/**
3714 * EMT rendezvous worker that vmR3SetRuntimeErrorCommon uses to safely change
3715 * the state to FatalError(LS).
3716 *
3717 * @returns VERR_VM_INVALID_VM_STATE or VINF_EM_SUSPENED. (This is a strict
3718 * return code, see FNVMMEMTRENDEZVOUS.)
3719 *
3720 * @param pVM The VM handle.
3721 * @param pVCpu The VMCPU handle of the EMT.
3722 * @param pvUser Ignored.
3723 */
3724static DECLCALLBACK(VBOXSTRICTRC) vmR3SetRuntimeErrorChangeState(PVM pVM, PVMCPU pVCpu, void *pvUser)
3725{
3726 NOREF(pVCpu);
3727 Assert(!pvUser); NOREF(pvUser);
3728
3729 /*
3730 * The first EMT thru here changes the state.
3731 */
3732 if (pVCpu->idCpu == pVM->cCpus - 1)
3733 {
3734 int rc = vmR3TrySetState(pVM, "VMSetRuntimeError", 2,
3735 VMSTATE_FATAL_ERROR, VMSTATE_RUNNING,
3736 VMSTATE_FATAL_ERROR_LS, VMSTATE_RUNNING_LS);
3737 if (RT_FAILURE(rc))
3738 return rc;
3739 if (rc == 2)
3740 SSMR3Cancel(pVM);
3741
3742 VM_FF_SET(pVM, VM_FF_CHECK_VM_STATE);
3743 }
3744
3745 /* This'll make sure we get out of whereever we are (e.g. REM). */
3746 return VINF_EM_SUSPEND;
3747}
3748
3749
3750/**
3751 * Worker for VMR3SetRuntimeErrorWorker and vmR3SetRuntimeErrorV.
3752 *
3753 * This does the common parts after the error has been saved / retrieved.
3754 *
3755 * @returns VBox status code with modifications, see VMSetRuntimeErrorV.
3756 *
3757 * @param pVM The VM handle.
3758 * @param fFlags The error flags.
3759 * @param pszErrorId Error ID string.
3760 * @param pszFormat Format string.
3761 * @param pVa Pointer to the format arguments.
3762 */
3763static int vmR3SetRuntimeErrorCommon(PVM pVM, uint32_t fFlags, const char *pszErrorId, const char *pszFormat, va_list *pVa)
3764{
3765 LogRel(("VM: Raising runtime error '%s' (fFlags=%#x)\n", pszErrorId, fFlags));
3766
3767 /*
3768 * Take actions before the call.
3769 */
3770 int rc;
3771 if (fFlags & VMSETRTERR_FLAGS_FATAL)
3772 rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_DESCENDING | VMMEMTRENDEZVOUS_FLAGS_STOP_ON_ERROR,
3773 vmR3SetRuntimeErrorChangeState, NULL);
3774 else if (fFlags & VMSETRTERR_FLAGS_SUSPEND)
3775 rc = VMR3Suspend(pVM);
3776 else
3777 rc = VINF_SUCCESS;
3778
3779 /*
3780 * Do the callback round.
3781 */
3782 PUVM pUVM = pVM->pUVM;
3783 RTCritSectEnter(&pUVM->vm.s.AtErrorCritSect);
3784 ASMAtomicIncU32(&pUVM->vm.s.cRuntimeErrors);
3785 for (PVMATRUNTIMEERROR pCur = pUVM->vm.s.pAtRuntimeError; pCur; pCur = pCur->pNext)
3786 {
3787 va_list va;
3788 va_copy(va, *pVa);
3789 pCur->pfnAtRuntimeError(pVM, pCur->pvUser, fFlags, pszErrorId, pszFormat, va);
3790 va_end(va);
3791 }
3792 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3793
3794 return rc;
3795}
3796
3797
3798/**
3799 * Ellipsis to va_list wrapper for calling vmR3SetRuntimeErrorCommon.
3800 */
3801static int vmR3SetRuntimeErrorCommonF(PVM pVM, uint32_t fFlags, const char *pszErrorId, const char *pszFormat, ...)
3802{
3803 va_list va;
3804 va_start(va, pszFormat);
3805 int rc = vmR3SetRuntimeErrorCommon(pVM, fFlags, pszErrorId, pszFormat, &va);
3806 va_end(va);
3807 return rc;
3808}
3809
3810
3811/**
3812 * This is a worker function for RC and Ring-0 calls to VMSetError and
3813 * VMSetErrorV.
3814 *
3815 * The message is found in VMINT.
3816 *
3817 * @returns VBox status code, see VMSetRuntimeError.
3818 * @param pVM The VM handle.
3819 * @thread EMT.
3820 */
3821VMMR3DECL(int) VMR3SetRuntimeErrorWorker(PVM pVM)
3822{
3823 VM_ASSERT_EMT(pVM);
3824 AssertReleaseMsgFailed(("And we have a winner! You get to implement Ring-0 and GC VMSetRuntimeErrorV! Congrats!\n"));
3825
3826 /*
3827 * Unpack the error (if we managed to format one).
3828 */
3829 const char *pszErrorId = "SetRuntimeError";
3830 const char *pszMessage = "No message!";
3831 uint32_t fFlags = VMSETRTERR_FLAGS_FATAL;
3832 PVMRUNTIMEERROR pErr = pVM->vm.s.pRuntimeErrorR3;
3833 if (pErr)
3834 {
3835 AssertCompile(sizeof(const char) == sizeof(uint8_t));
3836 if (pErr->offErrorId)
3837 pszErrorId = (const char *)pErr + pErr->offErrorId;
3838 if (pErr->offMessage)
3839 pszMessage = (const char *)pErr + pErr->offMessage;
3840 fFlags = pErr->fFlags;
3841 }
3842
3843 /*
3844 * Join cause with vmR3SetRuntimeErrorV.
3845 */
3846 return vmR3SetRuntimeErrorCommonF(pVM, fFlags, pszErrorId, "%s", pszMessage);
3847}
3848
3849
3850/**
3851 * Worker for VMSetRuntimeErrorV for doing the job on EMT in ring-3.
3852 *
3853 * @returns VBox status code with modifications, see VMSetRuntimeErrorV.
3854 *
3855 * @param pVM The VM handle.
3856 * @param fFlags The error flags.
3857 * @param pszErrorId Error ID string.
3858 * @param pszMessage The error message residing the MM heap.
3859 *
3860 * @thread EMT
3861 */
3862DECLCALLBACK(int) vmR3SetRuntimeError(PVM pVM, uint32_t fFlags, const char *pszErrorId, char *pszMessage)
3863{
3864#if 0 /** @todo make copy of the error msg. */
3865 /*
3866 * Make a copy of the message.
3867 */
3868 va_list va2;
3869 va_copy(va2, *pVa);
3870 vmSetRuntimeErrorCopy(pVM, fFlags, pszErrorId, pszFormat, va2);
3871 va_end(va2);
3872#endif
3873
3874 /*
3875 * Join paths with VMR3SetRuntimeErrorWorker.
3876 */
3877 int rc = vmR3SetRuntimeErrorCommonF(pVM, fFlags, pszErrorId, "%s", pszMessage);
3878 MMR3HeapFree(pszMessage);
3879 return rc;
3880}
3881
3882
3883/**
3884 * Worker for VMSetRuntimeErrorV for doing the job on EMT in ring-3.
3885 *
3886 * @returns VBox status code with modifications, see VMSetRuntimeErrorV.
3887 *
3888 * @param pVM The VM handle.
3889 * @param fFlags The error flags.
3890 * @param pszErrorId Error ID string.
3891 * @param pszFormat Format string.
3892 * @param pVa Pointer to the format arguments.
3893 *
3894 * @thread EMT
3895 */
3896DECLCALLBACK(int) vmR3SetRuntimeErrorV(PVM pVM, uint32_t fFlags, const char *pszErrorId, const char *pszFormat, va_list *pVa)
3897{
3898 /*
3899 * Make a copy of the message.
3900 */
3901 va_list va2;
3902 va_copy(va2, *pVa);
3903 vmSetRuntimeErrorCopy(pVM, fFlags, pszErrorId, pszFormat, va2);
3904 va_end(va2);
3905
3906 /*
3907 * Join paths with VMR3SetRuntimeErrorWorker.
3908 */
3909 return vmR3SetRuntimeErrorCommon(pVM, fFlags, pszErrorId, pszFormat, pVa);
3910}
3911
3912
3913/**
3914 * Gets the number of runtime errors raised via VMR3SetRuntimeError.
3915 *
3916 * This can be used avoid double error messages.
3917 *
3918 * @returns The runtime error count.
3919 * @param pVM The VM handle.
3920 */
3921VMMR3DECL(uint32_t) VMR3GetRuntimeErrorCount(PVM pVM)
3922{
3923 return pVM->pUVM->vm.s.cRuntimeErrors;
3924}
3925
3926
3927/**
3928 * Gets the ID virtual of the virtual CPU assoicated with the calling thread.
3929 *
3930 * @returns The CPU ID. NIL_VMCPUID if the thread isn't an EMT.
3931 *
3932 * @param pVM The VM handle.
3933 */
3934VMMR3DECL(RTCPUID) VMR3GetVMCPUId(PVM pVM)
3935{
3936 PUVMCPU pUVCpu = (PUVMCPU)RTTlsGet(pVM->pUVM->vm.s.idxTLS);
3937 return pUVCpu
3938 ? pUVCpu->idCpu
3939 : NIL_VMCPUID;
3940}
3941
3942
3943/**
3944 * Returns the native handle of the current EMT VMCPU thread.
3945 *
3946 * @returns Handle if this is an EMT thread; NIL_RTNATIVETHREAD otherwise
3947 * @param pVM The VM handle.
3948 * @thread EMT
3949 */
3950VMMR3DECL(RTNATIVETHREAD) VMR3GetVMCPUNativeThread(PVM pVM)
3951{
3952 PUVMCPU pUVCpu = (PUVMCPU)RTTlsGet(pVM->pUVM->vm.s.idxTLS);
3953
3954 if (!pUVCpu)
3955 return NIL_RTNATIVETHREAD;
3956
3957 return pUVCpu->vm.s.NativeThreadEMT;
3958}
3959
3960
3961/**
3962 * Returns the native handle of the current EMT VMCPU thread.
3963 *
3964 * @returns Handle if this is an EMT thread; NIL_RTNATIVETHREAD otherwise
3965 * @param pVM The VM handle.
3966 * @thread EMT
3967 */
3968VMMR3DECL(RTNATIVETHREAD) VMR3GetVMCPUNativeThreadU(PUVM pUVM)
3969{
3970 PUVMCPU pUVCpu = (PUVMCPU)RTTlsGet(pUVM->vm.s.idxTLS);
3971
3972 if (!pUVCpu)
3973 return NIL_RTNATIVETHREAD;
3974
3975 return pUVCpu->vm.s.NativeThreadEMT;
3976}
3977
3978
3979/**
3980 * Returns the handle of the current EMT VMCPU thread.
3981 *
3982 * @returns Handle if this is an EMT thread; NIL_RTNATIVETHREAD otherwise
3983 * @param pVM The VM handle.
3984 * @thread EMT
3985 */
3986VMMR3DECL(RTTHREAD) VMR3GetVMCPUThread(PVM pVM)
3987{
3988 PUVMCPU pUVCpu = (PUVMCPU)RTTlsGet(pVM->pUVM->vm.s.idxTLS);
3989
3990 if (!pUVCpu)
3991 return NIL_RTTHREAD;
3992
3993 return pUVCpu->vm.s.ThreadEMT;
3994}
3995
3996
3997/**
3998 * Returns the handle of the current EMT VMCPU thread.
3999 *
4000 * @returns Handle if this is an EMT thread; NIL_RTNATIVETHREAD otherwise
4001 * @param pVM The VM handle.
4002 * @thread EMT
4003 */
4004VMMR3DECL(RTTHREAD) VMR3GetVMCPUThreadU(PUVM pUVM)
4005{
4006 PUVMCPU pUVCpu = (PUVMCPU)RTTlsGet(pUVM->vm.s.idxTLS);
4007
4008 if (!pUVCpu)
4009 return NIL_RTTHREAD;
4010
4011 return pUVCpu->vm.s.ThreadEMT;
4012}
4013
4014
4015/**
4016 * Return the package and core id of a CPU.
4017 *
4018 * @returns VBOX status code.
4019 * @param pVM The VM to operate on.
4020 * @param idCpu Virtual CPU to get the ID from.
4021 * @param pidCpuCore Where to store the core ID of the virtual CPU.
4022 * @param pidCpuPackage Where to store the package ID of the virtual CPU.
4023 *
4024 */
4025VMMR3DECL(int) VMR3GetCpuCoreAndPackageIdFromCpuId(PVM pVM, VMCPUID idCpu, uint32_t *pidCpuCore, uint32_t *pidCpuPackage)
4026{
4027 if (idCpu >= pVM->cCpus)
4028 return VERR_INVALID_CPU_ID;
4029
4030#ifdef VBOX_WITH_MULTI_CORE
4031 *pidCpuCore = idCpu;
4032 *pidCpuPackage = 0;
4033#else
4034 *pidCpuCore = 0;
4035 *pidCpuPackage = idCpu;
4036#endif
4037
4038 return VINF_SUCCESS;
4039}
4040
4041
4042/**
4043 * Worker for VMR3HotUnplugCpu.
4044 *
4045 * @returns VINF_EM_WAIT_SPIP (strict status code).
4046 * @param pVM The VM handle.
4047 * @param idCpu The current CPU.
4048 */
4049static DECLCALLBACK(int) vmR3HotUnplugCpu(PVM pVM, VMCPUID idCpu)
4050{
4051 PVMCPU pVCpu = VMMGetCpuById(pVM, idCpu);
4052 VMCPU_ASSERT_EMT(pVCpu);
4053
4054 /*
4055 * Reset per CPU resources.
4056 *
4057 * Actually only needed for VT-x because the CPU seems to be still in some
4058 * paged mode and startup fails after a new hot plug event. SVM works fine
4059 * even without this.
4060 */
4061 Log(("vmR3HotUnplugCpu for VCPU %u\n", idCpu));
4062 PGMR3ResetUnpluggedCpu(pVM, pVCpu);
4063 PDMR3ResetCpu(pVCpu);
4064 TRPMR3ResetCpu(pVCpu);
4065 CPUMR3ResetCpu(pVCpu);
4066 EMR3ResetCpu(pVCpu);
4067 HWACCMR3ResetCpu(pVCpu);
4068 return VINF_EM_WAIT_SIPI;
4069}
4070
4071
4072/**
4073 * Hot-unplugs a CPU from the guest.
4074 *
4075 * @returns VBox status code.
4076 * @param pVM The VM to operate on.
4077 * @param idCpu Virtual CPU to perform the hot unplugging operation on.
4078 */
4079VMMR3DECL(int) VMR3HotUnplugCpu(PVM pVM, VMCPUID idCpu)
4080{
4081 AssertReturn(idCpu < pVM->cCpus, VERR_INVALID_CPU_ID);
4082
4083 /** @todo r=bird: Don't destroy the EMT, it'll break VMMR3EmtRendezvous and
4084 * broadcast requests. Just note down somewhere that the CPU is
4085 * offline and send it to SPIP wait. Maybe modify VMCPUSTATE and push
4086 * it out of the EM loops when offline. */
4087 return VMR3ReqCallNoWaitU(pVM->pUVM, idCpu, (PFNRT)vmR3HotUnplugCpu, 2, pVM, idCpu);
4088}
4089
4090
4091/**
4092 * Hot-plugs a CPU on the guest.
4093 *
4094 * @returns VBox status code.
4095 * @param pVM The VM to operate on.
4096 * @param idCpu Virtual CPU to perform the hot plugging operation on.
4097 */
4098VMMR3DECL(int) VMR3HotPlugCpu(PVM pVM, VMCPUID idCpu)
4099{
4100 AssertReturn(idCpu < pVM->cCpus, VERR_INVALID_CPU_ID);
4101
4102 /** @todo r-bird: Just mark it online and make sure it waits on SPIP. */
4103 return VINF_SUCCESS;
4104}
4105
4106
4107/**
4108 * Changes the VCPU priority.
4109 *
4110 * @returns VBox status code.
4111 * @param pVM The VM to operate on.
4112 * @param ulCpuPriority New CPU priority
4113 */
4114VMMR3DECL(int) VMR3SetCpuPriority(PVM pVM, unsigned ulCpuPriority)
4115{
4116 AssertReturn(ulCpuPriority > 0 && ulCpuPriority <= 100, VERR_INVALID_PARAMETER);
4117 /* Note: not called from EMT. */
4118 pVM->uCpuPriority = ulCpuPriority;
4119 return VINF_SUCCESS;
4120}
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