VirtualBox

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

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

State changes for FT

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 143.6 KB
Line 
1/* $Id: VM.cpp 31695 2010-08-16 14:20:27Z 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 /* hNativeThreadR0 is initialized on EMT registration. */
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_RUNNING_FT: return "RUNNING_FT";
2766 case VMSTATE_RESETTING: return "RESETTING";
2767 case VMSTATE_RESETTING_LS: return "RESETTING_LS";
2768 case VMSTATE_SUSPENDED: return "SUSPENDED";
2769 case VMSTATE_SUSPENDED_LS: return "SUSPENDED_LS";
2770 case VMSTATE_SUSPENDED_EXT_LS: return "SUSPENDED_EXT_LS";
2771 case VMSTATE_SUSPENDING: return "SUSPENDING";
2772 case VMSTATE_SUSPENDING_LS: return "SUSPENDING_LS";
2773 case VMSTATE_SUSPENDING_EXT_LS: return "SUSPENDING_EXT_LS";
2774 case VMSTATE_SAVING: return "SAVING";
2775 case VMSTATE_DEBUGGING: return "DEBUGGING";
2776 case VMSTATE_DEBUGGING_LS: return "DEBUGGING_LS";
2777 case VMSTATE_POWERING_OFF: return "POWERING_OFF";
2778 case VMSTATE_POWERING_OFF_LS: return "POWERING_OFF_LS";
2779 case VMSTATE_FATAL_ERROR: return "FATAL_ERROR";
2780 case VMSTATE_FATAL_ERROR_LS: return "FATAL_ERROR_LS";
2781 case VMSTATE_GURU_MEDITATION: return "GURU_MEDITATION";
2782 case VMSTATE_GURU_MEDITATION_LS:return "GURU_MEDITATION_LS";
2783 case VMSTATE_LOAD_FAILURE: return "LOAD_FAILURE";
2784 case VMSTATE_OFF: return "OFF";
2785 case VMSTATE_OFF_LS: return "OFF_LS";
2786 case VMSTATE_DESTROYING: return "DESTROYING";
2787 case VMSTATE_TERMINATED: return "TERMINATED";
2788
2789 default:
2790 AssertMsgFailed(("Unknown state %d\n", enmState));
2791 return "Unknown!\n";
2792 }
2793}
2794
2795
2796/**
2797 * Validates the state transition in strict builds.
2798 *
2799 * @returns true if valid, false if not.
2800 *
2801 * @param enmStateOld The old (current) state.
2802 * @param enmStateNew The proposed new state.
2803 *
2804 * @remarks The reference for this is found in doc/vp/VMM.vpp, the VMSTATE
2805 * diagram (under State Machine Diagram).
2806 */
2807static bool vmR3ValidateStateTransition(VMSTATE enmStateOld, VMSTATE enmStateNew)
2808{
2809#ifdef VBOX_STRICT
2810 switch (enmStateOld)
2811 {
2812 case VMSTATE_CREATING:
2813 AssertMsgReturn(enmStateNew == VMSTATE_CREATED, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2814 break;
2815
2816 case VMSTATE_CREATED:
2817 AssertMsgReturn( enmStateNew == VMSTATE_LOADING
2818 || enmStateNew == VMSTATE_POWERING_ON
2819 || enmStateNew == VMSTATE_POWERING_OFF
2820 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2821 break;
2822
2823 case VMSTATE_LOADING:
2824 AssertMsgReturn( enmStateNew == VMSTATE_SUSPENDED
2825 || enmStateNew == VMSTATE_LOAD_FAILURE
2826 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2827 break;
2828
2829 case VMSTATE_POWERING_ON:
2830 AssertMsgReturn( enmStateNew == VMSTATE_RUNNING
2831 /*|| enmStateNew == VMSTATE_FATAL_ERROR ?*/
2832 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2833 break;
2834
2835 case VMSTATE_RESUMING:
2836 AssertMsgReturn( enmStateNew == VMSTATE_RUNNING
2837 /*|| enmStateNew == VMSTATE_FATAL_ERROR ?*/
2838 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2839 break;
2840
2841 case VMSTATE_RUNNING:
2842 AssertMsgReturn( enmStateNew == VMSTATE_POWERING_OFF
2843 || enmStateNew == VMSTATE_SUSPENDING
2844 || enmStateNew == VMSTATE_RESETTING
2845 || enmStateNew == VMSTATE_RUNNING_LS
2846 || enmStateNew == VMSTATE_RUNNING_FT
2847 || enmStateNew == VMSTATE_DEBUGGING
2848 || enmStateNew == VMSTATE_FATAL_ERROR
2849 || enmStateNew == VMSTATE_GURU_MEDITATION
2850 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2851 break;
2852
2853 case VMSTATE_RUNNING_LS:
2854 AssertMsgReturn( enmStateNew == VMSTATE_POWERING_OFF_LS
2855 || enmStateNew == VMSTATE_SUSPENDING_LS
2856 || enmStateNew == VMSTATE_SUSPENDING_EXT_LS
2857 || enmStateNew == VMSTATE_RESETTING_LS
2858 || enmStateNew == VMSTATE_RUNNING
2859 || enmStateNew == VMSTATE_DEBUGGING_LS
2860 || enmStateNew == VMSTATE_FATAL_ERROR_LS
2861 || enmStateNew == VMSTATE_GURU_MEDITATION_LS
2862 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2863 break;
2864
2865 case VMSTATE_RUNNING_FT:
2866 AssertMsgReturn( enmStateNew == VMSTATE_POWERING_OFF
2867 || enmStateNew == VMSTATE_FATAL_ERROR
2868 || enmStateNew == VMSTATE_GURU_MEDITATION
2869 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2870 break;
2871
2872 case VMSTATE_RESETTING:
2873 AssertMsgReturn(enmStateNew == VMSTATE_RUNNING, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2874 break;
2875
2876 case VMSTATE_RESETTING_LS:
2877 AssertMsgReturn( enmStateNew == VMSTATE_SUSPENDING_LS
2878 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2879 break;
2880
2881 case VMSTATE_SUSPENDING:
2882 AssertMsgReturn(enmStateNew == VMSTATE_SUSPENDED, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2883 break;
2884
2885 case VMSTATE_SUSPENDING_LS:
2886 AssertMsgReturn( enmStateNew == VMSTATE_SUSPENDING
2887 || enmStateNew == VMSTATE_SUSPENDED_LS
2888 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2889 break;
2890
2891 case VMSTATE_SUSPENDING_EXT_LS:
2892 AssertMsgReturn( enmStateNew == VMSTATE_SUSPENDING
2893 || enmStateNew == VMSTATE_SUSPENDED_EXT_LS
2894 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2895 break;
2896
2897 case VMSTATE_SUSPENDED:
2898 AssertMsgReturn( enmStateNew == VMSTATE_POWERING_OFF
2899 || enmStateNew == VMSTATE_SAVING
2900 || enmStateNew == VMSTATE_RESETTING
2901 || enmStateNew == VMSTATE_RESUMING
2902 || enmStateNew == VMSTATE_LOADING
2903 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2904 break;
2905
2906 case VMSTATE_SUSPENDED_LS:
2907 AssertMsgReturn( enmStateNew == VMSTATE_SUSPENDED
2908 || enmStateNew == VMSTATE_SAVING
2909 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2910 break;
2911
2912 case VMSTATE_SUSPENDED_EXT_LS:
2913 AssertMsgReturn( enmStateNew == VMSTATE_SUSPENDED
2914 || enmStateNew == VMSTATE_SAVING
2915 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2916 break;
2917
2918 case VMSTATE_SAVING:
2919 AssertMsgReturn(enmStateNew == VMSTATE_SUSPENDED, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2920 break;
2921
2922 case VMSTATE_DEBUGGING:
2923 AssertMsgReturn( enmStateNew == VMSTATE_RUNNING
2924 || enmStateNew == VMSTATE_POWERING_OFF
2925 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2926 break;
2927
2928 case VMSTATE_DEBUGGING_LS:
2929 AssertMsgReturn( enmStateNew == VMSTATE_DEBUGGING
2930 || enmStateNew == VMSTATE_RUNNING_LS
2931 || enmStateNew == VMSTATE_POWERING_OFF_LS
2932 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2933 break;
2934
2935 case VMSTATE_POWERING_OFF:
2936 AssertMsgReturn(enmStateNew == VMSTATE_OFF, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2937 break;
2938
2939 case VMSTATE_POWERING_OFF_LS:
2940 AssertMsgReturn( enmStateNew == VMSTATE_POWERING_OFF
2941 || enmStateNew == VMSTATE_OFF_LS
2942 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2943 break;
2944
2945 case VMSTATE_OFF:
2946 AssertMsgReturn(enmStateNew == VMSTATE_DESTROYING, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2947 break;
2948
2949 case VMSTATE_OFF_LS:
2950 AssertMsgReturn(enmStateNew == VMSTATE_OFF, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2951 break;
2952
2953 case VMSTATE_FATAL_ERROR:
2954 AssertMsgReturn(enmStateNew == VMSTATE_POWERING_OFF, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2955 break;
2956
2957 case VMSTATE_FATAL_ERROR_LS:
2958 AssertMsgReturn( enmStateNew == VMSTATE_FATAL_ERROR
2959 || enmStateNew == VMSTATE_POWERING_OFF_LS
2960 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2961 break;
2962
2963 case VMSTATE_GURU_MEDITATION:
2964 AssertMsgReturn( enmStateNew == VMSTATE_DEBUGGING
2965 || enmStateNew == VMSTATE_POWERING_OFF
2966 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2967 break;
2968
2969 case VMSTATE_GURU_MEDITATION_LS:
2970 AssertMsgReturn( enmStateNew == VMSTATE_GURU_MEDITATION
2971 || enmStateNew == VMSTATE_DEBUGGING_LS
2972 || enmStateNew == VMSTATE_POWERING_OFF_LS
2973 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2974 break;
2975
2976 case VMSTATE_LOAD_FAILURE:
2977 AssertMsgReturn(enmStateNew == VMSTATE_POWERING_OFF, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2978 break;
2979
2980 case VMSTATE_DESTROYING:
2981 AssertMsgReturn(enmStateNew == VMSTATE_TERMINATED, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2982 break;
2983
2984 case VMSTATE_TERMINATED:
2985 default:
2986 AssertMsgFailedReturn(("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2987 break;
2988 }
2989#endif /* VBOX_STRICT */
2990 return true;
2991}
2992
2993
2994/**
2995 * Does the state change callouts.
2996 *
2997 * The caller owns the AtStateCritSect.
2998 *
2999 * @param pVM The VM handle.
3000 * @param pUVM The UVM handle.
3001 * @param enmStateNew The New state.
3002 * @param enmStateOld The old state.
3003 */
3004static void vmR3DoAtState(PVM pVM, PUVM pUVM, VMSTATE enmStateNew, VMSTATE enmStateOld)
3005{
3006 LogRel(("Changing the VM state from '%s' to '%s'.\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)));
3007
3008 for (PVMATSTATE pCur = pUVM->vm.s.pAtState; pCur; pCur = pCur->pNext)
3009 {
3010 pCur->pfnAtState(pVM, enmStateNew, enmStateOld, pCur->pvUser);
3011 if ( enmStateNew != VMSTATE_DESTROYING
3012 && pVM->enmVMState == VMSTATE_DESTROYING)
3013 break;
3014 AssertMsg(pVM->enmVMState == enmStateNew,
3015 ("You are not allowed to change the state while in the change callback, except "
3016 "from destroying the VM. There are restrictions in the way the state changes "
3017 "are propagated up to the EM execution loop and it makes the program flow very "
3018 "difficult to follow. (%s, expected %s, old %s)\n",
3019 VMR3GetStateName(pVM->enmVMState), VMR3GetStateName(enmStateNew),
3020 VMR3GetStateName(enmStateOld)));
3021 }
3022}
3023
3024
3025/**
3026 * Sets the current VM state, with the AtStatCritSect already entered.
3027 *
3028 * @param pVM The VM handle.
3029 * @param pUVM The UVM handle.
3030 * @param enmStateNew The new state.
3031 * @param enmStateOld The old state.
3032 */
3033static void vmR3SetStateLocked(PVM pVM, PUVM pUVM, VMSTATE enmStateNew, VMSTATE enmStateOld)
3034{
3035 vmR3ValidateStateTransition(enmStateOld, enmStateNew);
3036
3037 AssertMsg(pVM->enmVMState == enmStateOld,
3038 ("%s != %s\n", VMR3GetStateName(pVM->enmVMState), VMR3GetStateName(enmStateOld)));
3039 pUVM->vm.s.enmPrevVMState = enmStateOld;
3040 pVM->enmVMState = enmStateNew;
3041 VM_FF_CLEAR(pVM, VM_FF_CHECK_VM_STATE);
3042
3043 vmR3DoAtState(pVM, pUVM, enmStateNew, enmStateOld);
3044}
3045
3046
3047/**
3048 * Sets the current VM state.
3049 *
3050 * @param pVM VM handle.
3051 * @param enmStateNew The new state.
3052 * @param enmStateOld The old state (for asserting only).
3053 */
3054static void vmR3SetState(PVM pVM, VMSTATE enmStateNew, VMSTATE enmStateOld)
3055{
3056 PUVM pUVM = pVM->pUVM;
3057 RTCritSectEnter(&pUVM->vm.s.AtStateCritSect);
3058
3059 AssertMsg(pVM->enmVMState == enmStateOld,
3060 ("%s != %s\n", VMR3GetStateName(pVM->enmVMState), VMR3GetStateName(enmStateOld)));
3061 vmR3SetStateLocked(pVM, pUVM, enmStateNew, pVM->enmVMState);
3062
3063 RTCritSectLeave(&pUVM->vm.s.AtStateCritSect);
3064}
3065
3066
3067/**
3068 * Tries to perform a state transition.
3069 *
3070 * @returns The 1-based ordinal of the succeeding transition.
3071 * VERR_VM_INVALID_VM_STATE and Assert+LogRel on failure.
3072 *
3073 * @param pVM The VM handle.
3074 * @param pszWho Who is trying to change it.
3075 * @param cTransitions The number of transitions in the ellipsis.
3076 * @param ... Transition pairs; new, old.
3077 */
3078static int vmR3TrySetState(PVM pVM, const char *pszWho, unsigned cTransitions, ...)
3079{
3080 va_list va;
3081 VMSTATE enmStateNew = VMSTATE_CREATED;
3082 VMSTATE enmStateOld = VMSTATE_CREATED;
3083
3084#ifdef VBOX_STRICT
3085 /*
3086 * Validate the input first.
3087 */
3088 va_start(va, cTransitions);
3089 for (unsigned i = 0; i < cTransitions; i++)
3090 {
3091 enmStateNew = (VMSTATE)va_arg(va, /*VMSTATE*/int);
3092 enmStateOld = (VMSTATE)va_arg(va, /*VMSTATE*/int);
3093 vmR3ValidateStateTransition(enmStateOld, enmStateNew);
3094 }
3095 va_end(va);
3096#endif
3097
3098 /*
3099 * Grab the lock and see if any of the proposed transisions works out.
3100 */
3101 va_start(va, cTransitions);
3102 int rc = VERR_VM_INVALID_VM_STATE;
3103 PUVM pUVM = pVM->pUVM;
3104 RTCritSectEnter(&pUVM->vm.s.AtStateCritSect);
3105
3106 VMSTATE enmStateCur = pVM->enmVMState;
3107
3108 for (unsigned i = 0; i < cTransitions; i++)
3109 {
3110 enmStateNew = (VMSTATE)va_arg(va, /*VMSTATE*/int);
3111 enmStateOld = (VMSTATE)va_arg(va, /*VMSTATE*/int);
3112 if (enmStateCur == enmStateOld)
3113 {
3114 vmR3SetStateLocked(pVM, pUVM, enmStateNew, enmStateOld);
3115 rc = i + 1;
3116 break;
3117 }
3118 }
3119
3120 if (RT_FAILURE(rc))
3121 {
3122 /*
3123 * Complain about it.
3124 */
3125 if (cTransitions == 1)
3126 {
3127 LogRel(("%s: %s -> %s failed, because the VM state is actually %s\n",
3128 pszWho, VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew), VMR3GetStateName(enmStateCur)));
3129 VMSetError(pVM, VERR_VM_INVALID_VM_STATE, RT_SRC_POS,
3130 N_("%s failed because the VM state is %s instead of %s"),
3131 pszWho, VMR3GetStateName(enmStateCur), VMR3GetStateName(enmStateOld));
3132 AssertMsgFailed(("%s: %s -> %s failed, because the VM state is actually %s\n",
3133 pszWho, VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew), VMR3GetStateName(enmStateCur)));
3134 }
3135 else
3136 {
3137 va_end(va);
3138 va_start(va, cTransitions);
3139 LogRel(("%s:\n", pszWho));
3140 for (unsigned i = 0; i < cTransitions; i++)
3141 {
3142 enmStateNew = (VMSTATE)va_arg(va, /*VMSTATE*/int);
3143 enmStateOld = (VMSTATE)va_arg(va, /*VMSTATE*/int);
3144 LogRel(("%s%s -> %s",
3145 i ? ", " : " ", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)));
3146 }
3147 LogRel((" failed, because the VM state is actually %s\n", VMR3GetStateName(enmStateCur)));
3148 VMSetError(pVM, VERR_VM_INVALID_VM_STATE, RT_SRC_POS,
3149 N_("%s failed because the current VM state, %s, was not found in the state transition table"),
3150 pszWho, VMR3GetStateName(enmStateCur), VMR3GetStateName(enmStateOld));
3151 AssertMsgFailed(("%s - state=%s, see release log for full details. Check the cTransitions passed us.\n",
3152 pszWho, VMR3GetStateName(enmStateCur)));
3153 }
3154 }
3155
3156 RTCritSectLeave(&pUVM->vm.s.AtStateCritSect);
3157 va_end(va);
3158 Assert(rc > 0 || rc < 0);
3159 return rc;
3160}
3161
3162
3163/**
3164 * Flag a guru meditation ... a hack.
3165 *
3166 * @param pVM The VM handle
3167 *
3168 * @todo Rewrite this part. The guru meditation should be flagged
3169 * immediately by the VMM and not by VMEmt.cpp when it's all over.
3170 */
3171void vmR3SetGuruMeditation(PVM pVM)
3172{
3173 PUVM pUVM = pVM->pUVM;
3174 RTCritSectEnter(&pUVM->vm.s.AtStateCritSect);
3175
3176 VMSTATE enmStateCur = pVM->enmVMState;
3177 if (enmStateCur == VMSTATE_RUNNING)
3178 vmR3SetStateLocked(pVM, pUVM, VMSTATE_GURU_MEDITATION, VMSTATE_RUNNING);
3179 else if (enmStateCur == VMSTATE_RUNNING_LS)
3180 {
3181 vmR3SetStateLocked(pVM, pUVM, VMSTATE_GURU_MEDITATION_LS, VMSTATE_RUNNING_LS);
3182 SSMR3Cancel(pVM);
3183 }
3184
3185 RTCritSectLeave(&pUVM->vm.s.AtStateCritSect);
3186}
3187
3188
3189/**
3190 * Called by vmR3EmulationThreadWithId just before the VM structure is freed.
3191 *
3192 * @param pVM The VM handle.
3193 */
3194void vmR3SetTerminated(PVM pVM)
3195{
3196 vmR3SetState(pVM, VMSTATE_TERMINATED, VMSTATE_DESTROYING);
3197}
3198
3199
3200/**
3201 * Checks if the VM was teleported and hasn't been fully resumed yet.
3202 *
3203 * This applies to both sides of the teleportation since we may leave a working
3204 * clone behind and the user is allowed to resume this...
3205 *
3206 * @returns true / false.
3207 * @param pVM The VM handle.
3208 * @thread Any thread.
3209 */
3210VMMR3DECL(bool) VMR3TeleportedAndNotFullyResumedYet(PVM pVM)
3211{
3212 VM_ASSERT_VALID_EXT_RETURN(pVM, false);
3213 return pVM->vm.s.fTeleportedAndNotFullyResumedYet;
3214}
3215
3216
3217/**
3218 * Registers a VM state change callback.
3219 *
3220 * You are not allowed to call any function which changes the VM state from a
3221 * state callback.
3222 *
3223 * @returns VBox status code.
3224 * @param pVM VM handle.
3225 * @param pfnAtState Pointer to callback.
3226 * @param pvUser User argument.
3227 * @thread Any.
3228 */
3229VMMR3DECL(int) VMR3AtStateRegister(PVM pVM, PFNVMATSTATE pfnAtState, void *pvUser)
3230{
3231 LogFlow(("VMR3AtStateRegister: pfnAtState=%p pvUser=%p\n", pfnAtState, pvUser));
3232
3233 /*
3234 * Validate input.
3235 */
3236 AssertPtrReturn(pfnAtState, VERR_INVALID_PARAMETER);
3237 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
3238
3239 /*
3240 * Allocate a new record.
3241 */
3242 PUVM pUVM = pVM->pUVM;
3243 PVMATSTATE pNew = (PVMATSTATE)MMR3HeapAllocU(pUVM, MM_TAG_VM, sizeof(*pNew));
3244 if (!pNew)
3245 return VERR_NO_MEMORY;
3246
3247 /* fill */
3248 pNew->pfnAtState = pfnAtState;
3249 pNew->pvUser = pvUser;
3250
3251 /* insert */
3252 RTCritSectEnter(&pUVM->vm.s.AtStateCritSect);
3253 pNew->pNext = *pUVM->vm.s.ppAtStateNext;
3254 *pUVM->vm.s.ppAtStateNext = pNew;
3255 pUVM->vm.s.ppAtStateNext = &pNew->pNext;
3256 RTCritSectLeave(&pUVM->vm.s.AtStateCritSect);
3257
3258 return VINF_SUCCESS;
3259}
3260
3261
3262/**
3263 * Deregisters a VM state change callback.
3264 *
3265 * @returns VBox status code.
3266 * @param pVM VM handle.
3267 * @param pfnAtState Pointer to callback.
3268 * @param pvUser User argument.
3269 * @thread Any.
3270 */
3271VMMR3DECL(int) VMR3AtStateDeregister(PVM pVM, PFNVMATSTATE pfnAtState, void *pvUser)
3272{
3273 LogFlow(("VMR3AtStateDeregister: pfnAtState=%p pvUser=%p\n", pfnAtState, pvUser));
3274
3275 /*
3276 * Validate input.
3277 */
3278 AssertPtrReturn(pfnAtState, VERR_INVALID_PARAMETER);
3279 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
3280
3281 PUVM pUVM = pVM->pUVM;
3282 RTCritSectEnter(&pUVM->vm.s.AtStateCritSect);
3283
3284 /*
3285 * Search the list for the entry.
3286 */
3287 PVMATSTATE pPrev = NULL;
3288 PVMATSTATE pCur = pUVM->vm.s.pAtState;
3289 while ( pCur
3290 && ( pCur->pfnAtState != pfnAtState
3291 || pCur->pvUser != pvUser))
3292 {
3293 pPrev = pCur;
3294 pCur = pCur->pNext;
3295 }
3296 if (!pCur)
3297 {
3298 AssertMsgFailed(("pfnAtState=%p was not found\n", pfnAtState));
3299 RTCritSectLeave(&pUVM->vm.s.AtStateCritSect);
3300 return VERR_FILE_NOT_FOUND;
3301 }
3302
3303 /*
3304 * Unlink it.
3305 */
3306 if (pPrev)
3307 {
3308 pPrev->pNext = pCur->pNext;
3309 if (!pCur->pNext)
3310 pUVM->vm.s.ppAtStateNext = &pPrev->pNext;
3311 }
3312 else
3313 {
3314 pUVM->vm.s.pAtState = pCur->pNext;
3315 if (!pCur->pNext)
3316 pUVM->vm.s.ppAtStateNext = &pUVM->vm.s.pAtState;
3317 }
3318
3319 RTCritSectLeave(&pUVM->vm.s.AtStateCritSect);
3320
3321 /*
3322 * Free it.
3323 */
3324 pCur->pfnAtState = NULL;
3325 pCur->pNext = NULL;
3326 MMR3HeapFree(pCur);
3327
3328 return VINF_SUCCESS;
3329}
3330
3331
3332/**
3333 * Registers a VM error callback.
3334 *
3335 * @returns VBox status code.
3336 * @param pVM The VM handle.
3337 * @param pfnAtError Pointer to callback.
3338 * @param pvUser User argument.
3339 * @thread Any.
3340 */
3341VMMR3DECL(int) VMR3AtErrorRegister(PVM pVM, PFNVMATERROR pfnAtError, void *pvUser)
3342{
3343 return VMR3AtErrorRegisterU(pVM->pUVM, pfnAtError, pvUser);
3344}
3345
3346
3347/**
3348 * Registers a VM error callback.
3349 *
3350 * @returns VBox status code.
3351 * @param pUVM The VM handle.
3352 * @param pfnAtError Pointer to callback.
3353 * @param pvUser User argument.
3354 * @thread Any.
3355 */
3356VMMR3DECL(int) VMR3AtErrorRegisterU(PUVM pUVM, PFNVMATERROR pfnAtError, void *pvUser)
3357{
3358 LogFlow(("VMR3AtErrorRegister: pfnAtError=%p pvUser=%p\n", pfnAtError, pvUser));
3359
3360 /*
3361 * Validate input.
3362 */
3363 AssertPtrReturn(pfnAtError, VERR_INVALID_PARAMETER);
3364 UVM_ASSERT_VALID_EXT_RETURN(pUVM, VERR_INVALID_VM_HANDLE);
3365
3366 /*
3367 * Allocate a new record.
3368 */
3369 PVMATERROR pNew = (PVMATERROR)MMR3HeapAllocU(pUVM, MM_TAG_VM, sizeof(*pNew));
3370 if (!pNew)
3371 return VERR_NO_MEMORY;
3372
3373 /* fill */
3374 pNew->pfnAtError = pfnAtError;
3375 pNew->pvUser = pvUser;
3376
3377 /* insert */
3378 RTCritSectEnter(&pUVM->vm.s.AtErrorCritSect);
3379 pNew->pNext = *pUVM->vm.s.ppAtErrorNext;
3380 *pUVM->vm.s.ppAtErrorNext = pNew;
3381 pUVM->vm.s.ppAtErrorNext = &pNew->pNext;
3382 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3383
3384 return VINF_SUCCESS;
3385}
3386
3387
3388/**
3389 * Deregisters a VM error callback.
3390 *
3391 * @returns VBox status code.
3392 * @param pVM The VM handle.
3393 * @param pfnAtError Pointer to callback.
3394 * @param pvUser User argument.
3395 * @thread Any.
3396 */
3397VMMR3DECL(int) VMR3AtErrorDeregister(PVM pVM, PFNVMATERROR pfnAtError, void *pvUser)
3398{
3399 LogFlow(("VMR3AtErrorDeregister: pfnAtError=%p pvUser=%p\n", pfnAtError, pvUser));
3400
3401 /*
3402 * Validate input.
3403 */
3404 AssertPtrReturn(pfnAtError, VERR_INVALID_PARAMETER);
3405 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
3406
3407 PUVM pUVM = pVM->pUVM;
3408 RTCritSectEnter(&pUVM->vm.s.AtErrorCritSect);
3409
3410 /*
3411 * Search the list for the entry.
3412 */
3413 PVMATERROR pPrev = NULL;
3414 PVMATERROR pCur = pUVM->vm.s.pAtError;
3415 while ( pCur
3416 && ( pCur->pfnAtError != pfnAtError
3417 || pCur->pvUser != pvUser))
3418 {
3419 pPrev = pCur;
3420 pCur = pCur->pNext;
3421 }
3422 if (!pCur)
3423 {
3424 AssertMsgFailed(("pfnAtError=%p was not found\n", pfnAtError));
3425 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3426 return VERR_FILE_NOT_FOUND;
3427 }
3428
3429 /*
3430 * Unlink it.
3431 */
3432 if (pPrev)
3433 {
3434 pPrev->pNext = pCur->pNext;
3435 if (!pCur->pNext)
3436 pUVM->vm.s.ppAtErrorNext = &pPrev->pNext;
3437 }
3438 else
3439 {
3440 pUVM->vm.s.pAtError = pCur->pNext;
3441 if (!pCur->pNext)
3442 pUVM->vm.s.ppAtErrorNext = &pUVM->vm.s.pAtError;
3443 }
3444
3445 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3446
3447 /*
3448 * Free it.
3449 */
3450 pCur->pfnAtError = NULL;
3451 pCur->pNext = NULL;
3452 MMR3HeapFree(pCur);
3453
3454 return VINF_SUCCESS;
3455}
3456
3457
3458/**
3459 * Ellipsis to va_list wrapper for calling pfnAtError.
3460 */
3461static void vmR3SetErrorWorkerDoCall(PVM pVM, PVMATERROR pCur, int rc, RT_SRC_POS_DECL, const char *pszFormat, ...)
3462{
3463 va_list va;
3464 va_start(va, pszFormat);
3465 pCur->pfnAtError(pVM, pCur->pvUser, rc, RT_SRC_POS_ARGS, pszFormat, va);
3466 va_end(va);
3467}
3468
3469
3470/**
3471 * This is a worker function for GC and Ring-0 calls to VMSetError and VMSetErrorV.
3472 * The message is found in VMINT.
3473 *
3474 * @param pVM The VM handle.
3475 * @thread EMT.
3476 */
3477VMMR3DECL(void) VMR3SetErrorWorker(PVM pVM)
3478{
3479 VM_ASSERT_EMT(pVM);
3480 AssertReleaseMsgFailed(("And we have a winner! You get to implement Ring-0 and GC VMSetErrorV! Contrats!\n"));
3481
3482 /*
3483 * Unpack the error (if we managed to format one).
3484 */
3485 PVMERROR pErr = pVM->vm.s.pErrorR3;
3486 const char *pszFile = NULL;
3487 const char *pszFunction = NULL;
3488 uint32_t iLine = 0;
3489 const char *pszMessage;
3490 int32_t rc = VERR_MM_HYPER_NO_MEMORY;
3491 if (pErr)
3492 {
3493 AssertCompile(sizeof(const char) == sizeof(uint8_t));
3494 if (pErr->offFile)
3495 pszFile = (const char *)pErr + pErr->offFile;
3496 iLine = pErr->iLine;
3497 if (pErr->offFunction)
3498 pszFunction = (const char *)pErr + pErr->offFunction;
3499 if (pErr->offMessage)
3500 pszMessage = (const char *)pErr + pErr->offMessage;
3501 else
3502 pszMessage = "No message!";
3503 }
3504 else
3505 pszMessage = "No message! (Failed to allocate memory to put the error message in!)";
3506
3507 /*
3508 * Call the at error callbacks.
3509 */
3510 PUVM pUVM = pVM->pUVM;
3511 RTCritSectEnter(&pUVM->vm.s.AtErrorCritSect);
3512 ASMAtomicIncU32(&pUVM->vm.s.cRuntimeErrors);
3513 for (PVMATERROR pCur = pUVM->vm.s.pAtError; pCur; pCur = pCur->pNext)
3514 vmR3SetErrorWorkerDoCall(pVM, pCur, rc, RT_SRC_POS_ARGS, "%s", pszMessage);
3515 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3516}
3517
3518
3519/**
3520 * Gets the number of errors raised via VMSetError.
3521 *
3522 * This can be used avoid double error messages.
3523 *
3524 * @returns The error count.
3525 * @param pVM The VM handle.
3526 */
3527VMMR3DECL(uint32_t) VMR3GetErrorCount(PVM pVM)
3528{
3529 return pVM->pUVM->vm.s.cErrors;
3530}
3531
3532
3533/**
3534 * Creation time wrapper for vmR3SetErrorUV.
3535 *
3536 * @returns rc.
3537 * @param pUVM Pointer to the user mode VM structure.
3538 * @param rc The VBox status code.
3539 * @param RT_SRC_POS_DECL The source position of this error.
3540 * @param pszFormat Format string.
3541 * @param ... The arguments.
3542 * @thread Any thread.
3543 */
3544static int vmR3SetErrorU(PUVM pUVM, int rc, RT_SRC_POS_DECL, const char *pszFormat, ...)
3545{
3546 va_list va;
3547 va_start(va, pszFormat);
3548 vmR3SetErrorUV(pUVM, rc, pszFile, iLine, pszFunction, pszFormat, &va);
3549 va_end(va);
3550 return rc;
3551}
3552
3553
3554/**
3555 * Worker which calls everyone listening to the VM error messages.
3556 *
3557 * @param pUVM Pointer to the user mode VM structure.
3558 * @param rc The VBox status code.
3559 * @param RT_SRC_POS_DECL The source position of this error.
3560 * @param pszFormat Format string.
3561 * @param pArgs Pointer to the format arguments.
3562 * @thread EMT
3563 */
3564DECLCALLBACK(void) vmR3SetErrorUV(PUVM pUVM, int rc, RT_SRC_POS_DECL, const char *pszFormat, va_list *pArgs)
3565{
3566 /*
3567 * Log the error.
3568 */
3569 va_list va3;
3570 va_copy(va3, *pArgs);
3571 RTLogRelPrintf("VMSetError: %s(%d) %s; rc=%Rrc\n"
3572 "VMSetError: %N\n",
3573 pszFile, iLine, pszFunction, rc,
3574 pszFormat, &va3);
3575 va_end(va3);
3576
3577#ifdef LOG_ENABLED
3578 va_copy(va3, *pArgs);
3579 RTLogPrintf("VMSetError: %s(%d) %s; rc=%Rrc\n"
3580 "%N\n",
3581 pszFile, iLine, pszFunction, rc,
3582 pszFormat, &va3);
3583 va_end(va3);
3584#endif
3585
3586 /*
3587 * Make a copy of the message.
3588 */
3589 if (pUVM->pVM)
3590 vmSetErrorCopy(pUVM->pVM, rc, RT_SRC_POS_ARGS, pszFormat, *pArgs);
3591
3592 /*
3593 * Call the at error callbacks.
3594 */
3595 bool fCalledSomeone = false;
3596 RTCritSectEnter(&pUVM->vm.s.AtErrorCritSect);
3597 ASMAtomicIncU32(&pUVM->vm.s.cErrors);
3598 for (PVMATERROR pCur = pUVM->vm.s.pAtError; pCur; pCur = pCur->pNext)
3599 {
3600 va_list va2;
3601 va_copy(va2, *pArgs);
3602 pCur->pfnAtError(pUVM->pVM, pCur->pvUser, rc, RT_SRC_POS_ARGS, pszFormat, va2);
3603 va_end(va2);
3604 fCalledSomeone = true;
3605 }
3606 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3607}
3608
3609
3610/**
3611 * Registers a VM runtime error callback.
3612 *
3613 * @returns VBox status code.
3614 * @param pVM The VM handle.
3615 * @param pfnAtRuntimeError Pointer to callback.
3616 * @param pvUser User argument.
3617 * @thread Any.
3618 */
3619VMMR3DECL(int) VMR3AtRuntimeErrorRegister(PVM pVM, PFNVMATRUNTIMEERROR pfnAtRuntimeError, void *pvUser)
3620{
3621 LogFlow(("VMR3AtRuntimeErrorRegister: pfnAtRuntimeError=%p pvUser=%p\n", pfnAtRuntimeError, pvUser));
3622
3623 /*
3624 * Validate input.
3625 */
3626 AssertPtrReturn(pfnAtRuntimeError, VERR_INVALID_PARAMETER);
3627 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
3628
3629 /*
3630 * Allocate a new record.
3631 */
3632 PUVM pUVM = pVM->pUVM;
3633 PVMATRUNTIMEERROR pNew = (PVMATRUNTIMEERROR)MMR3HeapAllocU(pUVM, MM_TAG_VM, sizeof(*pNew));
3634 if (!pNew)
3635 return VERR_NO_MEMORY;
3636
3637 /* fill */
3638 pNew->pfnAtRuntimeError = pfnAtRuntimeError;
3639 pNew->pvUser = pvUser;
3640
3641 /* insert */
3642 RTCritSectEnter(&pUVM->vm.s.AtErrorCritSect);
3643 pNew->pNext = *pUVM->vm.s.ppAtRuntimeErrorNext;
3644 *pUVM->vm.s.ppAtRuntimeErrorNext = pNew;
3645 pUVM->vm.s.ppAtRuntimeErrorNext = &pNew->pNext;
3646 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3647
3648 return VINF_SUCCESS;
3649}
3650
3651
3652/**
3653 * Deregisters a VM runtime error callback.
3654 *
3655 * @returns VBox status code.
3656 * @param pVM The VM handle.
3657 * @param pfnAtRuntimeError Pointer to callback.
3658 * @param pvUser User argument.
3659 * @thread Any.
3660 */
3661VMMR3DECL(int) VMR3AtRuntimeErrorDeregister(PVM pVM, PFNVMATRUNTIMEERROR pfnAtRuntimeError, void *pvUser)
3662{
3663 LogFlow(("VMR3AtRuntimeErrorDeregister: pfnAtRuntimeError=%p pvUser=%p\n", pfnAtRuntimeError, pvUser));
3664
3665 /*
3666 * Validate input.
3667 */
3668 AssertPtrReturn(pfnAtRuntimeError, VERR_INVALID_PARAMETER);
3669 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
3670
3671 PUVM pUVM = pVM->pUVM;
3672 RTCritSectEnter(&pUVM->vm.s.AtErrorCritSect);
3673
3674 /*
3675 * Search the list for the entry.
3676 */
3677 PVMATRUNTIMEERROR pPrev = NULL;
3678 PVMATRUNTIMEERROR pCur = pUVM->vm.s.pAtRuntimeError;
3679 while ( pCur
3680 && ( pCur->pfnAtRuntimeError != pfnAtRuntimeError
3681 || pCur->pvUser != pvUser))
3682 {
3683 pPrev = pCur;
3684 pCur = pCur->pNext;
3685 }
3686 if (!pCur)
3687 {
3688 AssertMsgFailed(("pfnAtRuntimeError=%p was not found\n", pfnAtRuntimeError));
3689 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3690 return VERR_FILE_NOT_FOUND;
3691 }
3692
3693 /*
3694 * Unlink it.
3695 */
3696 if (pPrev)
3697 {
3698 pPrev->pNext = pCur->pNext;
3699 if (!pCur->pNext)
3700 pUVM->vm.s.ppAtRuntimeErrorNext = &pPrev->pNext;
3701 }
3702 else
3703 {
3704 pUVM->vm.s.pAtRuntimeError = pCur->pNext;
3705 if (!pCur->pNext)
3706 pUVM->vm.s.ppAtRuntimeErrorNext = &pUVM->vm.s.pAtRuntimeError;
3707 }
3708
3709 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3710
3711 /*
3712 * Free it.
3713 */
3714 pCur->pfnAtRuntimeError = NULL;
3715 pCur->pNext = NULL;
3716 MMR3HeapFree(pCur);
3717
3718 return VINF_SUCCESS;
3719}
3720
3721
3722/**
3723 * EMT rendezvous worker that vmR3SetRuntimeErrorCommon uses to safely change
3724 * the state to FatalError(LS).
3725 *
3726 * @returns VERR_VM_INVALID_VM_STATE or VINF_EM_SUSPENED. (This is a strict
3727 * return code, see FNVMMEMTRENDEZVOUS.)
3728 *
3729 * @param pVM The VM handle.
3730 * @param pVCpu The VMCPU handle of the EMT.
3731 * @param pvUser Ignored.
3732 */
3733static DECLCALLBACK(VBOXSTRICTRC) vmR3SetRuntimeErrorChangeState(PVM pVM, PVMCPU pVCpu, void *pvUser)
3734{
3735 NOREF(pVCpu);
3736 Assert(!pvUser); NOREF(pvUser);
3737
3738 /*
3739 * The first EMT thru here changes the state.
3740 */
3741 if (pVCpu->idCpu == pVM->cCpus - 1)
3742 {
3743 int rc = vmR3TrySetState(pVM, "VMSetRuntimeError", 2,
3744 VMSTATE_FATAL_ERROR, VMSTATE_RUNNING,
3745 VMSTATE_FATAL_ERROR_LS, VMSTATE_RUNNING_LS);
3746 if (RT_FAILURE(rc))
3747 return rc;
3748 if (rc == 2)
3749 SSMR3Cancel(pVM);
3750
3751 VM_FF_SET(pVM, VM_FF_CHECK_VM_STATE);
3752 }
3753
3754 /* This'll make sure we get out of whereever we are (e.g. REM). */
3755 return VINF_EM_SUSPEND;
3756}
3757
3758
3759/**
3760 * Worker for VMR3SetRuntimeErrorWorker and vmR3SetRuntimeErrorV.
3761 *
3762 * This does the common parts after the error has been saved / retrieved.
3763 *
3764 * @returns VBox status code with modifications, see VMSetRuntimeErrorV.
3765 *
3766 * @param pVM The VM handle.
3767 * @param fFlags The error flags.
3768 * @param pszErrorId Error ID string.
3769 * @param pszFormat Format string.
3770 * @param pVa Pointer to the format arguments.
3771 */
3772static int vmR3SetRuntimeErrorCommon(PVM pVM, uint32_t fFlags, const char *pszErrorId, const char *pszFormat, va_list *pVa)
3773{
3774 LogRel(("VM: Raising runtime error '%s' (fFlags=%#x)\n", pszErrorId, fFlags));
3775
3776 /*
3777 * Take actions before the call.
3778 */
3779 int rc;
3780 if (fFlags & VMSETRTERR_FLAGS_FATAL)
3781 rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_DESCENDING | VMMEMTRENDEZVOUS_FLAGS_STOP_ON_ERROR,
3782 vmR3SetRuntimeErrorChangeState, NULL);
3783 else if (fFlags & VMSETRTERR_FLAGS_SUSPEND)
3784 rc = VMR3Suspend(pVM);
3785 else
3786 rc = VINF_SUCCESS;
3787
3788 /*
3789 * Do the callback round.
3790 */
3791 PUVM pUVM = pVM->pUVM;
3792 RTCritSectEnter(&pUVM->vm.s.AtErrorCritSect);
3793 ASMAtomicIncU32(&pUVM->vm.s.cRuntimeErrors);
3794 for (PVMATRUNTIMEERROR pCur = pUVM->vm.s.pAtRuntimeError; pCur; pCur = pCur->pNext)
3795 {
3796 va_list va;
3797 va_copy(va, *pVa);
3798 pCur->pfnAtRuntimeError(pVM, pCur->pvUser, fFlags, pszErrorId, pszFormat, va);
3799 va_end(va);
3800 }
3801 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3802
3803 return rc;
3804}
3805
3806
3807/**
3808 * Ellipsis to va_list wrapper for calling vmR3SetRuntimeErrorCommon.
3809 */
3810static int vmR3SetRuntimeErrorCommonF(PVM pVM, uint32_t fFlags, const char *pszErrorId, const char *pszFormat, ...)
3811{
3812 va_list va;
3813 va_start(va, pszFormat);
3814 int rc = vmR3SetRuntimeErrorCommon(pVM, fFlags, pszErrorId, pszFormat, &va);
3815 va_end(va);
3816 return rc;
3817}
3818
3819
3820/**
3821 * This is a worker function for RC and Ring-0 calls to VMSetError and
3822 * VMSetErrorV.
3823 *
3824 * The message is found in VMINT.
3825 *
3826 * @returns VBox status code, see VMSetRuntimeError.
3827 * @param pVM The VM handle.
3828 * @thread EMT.
3829 */
3830VMMR3DECL(int) VMR3SetRuntimeErrorWorker(PVM pVM)
3831{
3832 VM_ASSERT_EMT(pVM);
3833 AssertReleaseMsgFailed(("And we have a winner! You get to implement Ring-0 and GC VMSetRuntimeErrorV! Congrats!\n"));
3834
3835 /*
3836 * Unpack the error (if we managed to format one).
3837 */
3838 const char *pszErrorId = "SetRuntimeError";
3839 const char *pszMessage = "No message!";
3840 uint32_t fFlags = VMSETRTERR_FLAGS_FATAL;
3841 PVMRUNTIMEERROR pErr = pVM->vm.s.pRuntimeErrorR3;
3842 if (pErr)
3843 {
3844 AssertCompile(sizeof(const char) == sizeof(uint8_t));
3845 if (pErr->offErrorId)
3846 pszErrorId = (const char *)pErr + pErr->offErrorId;
3847 if (pErr->offMessage)
3848 pszMessage = (const char *)pErr + pErr->offMessage;
3849 fFlags = pErr->fFlags;
3850 }
3851
3852 /*
3853 * Join cause with vmR3SetRuntimeErrorV.
3854 */
3855 return vmR3SetRuntimeErrorCommonF(pVM, fFlags, pszErrorId, "%s", pszMessage);
3856}
3857
3858
3859/**
3860 * Worker for VMSetRuntimeErrorV for doing the job on EMT in ring-3.
3861 *
3862 * @returns VBox status code with modifications, see VMSetRuntimeErrorV.
3863 *
3864 * @param pVM The VM handle.
3865 * @param fFlags The error flags.
3866 * @param pszErrorId Error ID string.
3867 * @param pszMessage The error message residing the MM heap.
3868 *
3869 * @thread EMT
3870 */
3871DECLCALLBACK(int) vmR3SetRuntimeError(PVM pVM, uint32_t fFlags, const char *pszErrorId, char *pszMessage)
3872{
3873#if 0 /** @todo make copy of the error msg. */
3874 /*
3875 * Make a copy of the message.
3876 */
3877 va_list va2;
3878 va_copy(va2, *pVa);
3879 vmSetRuntimeErrorCopy(pVM, fFlags, pszErrorId, pszFormat, va2);
3880 va_end(va2);
3881#endif
3882
3883 /*
3884 * Join paths with VMR3SetRuntimeErrorWorker.
3885 */
3886 int rc = vmR3SetRuntimeErrorCommonF(pVM, fFlags, pszErrorId, "%s", pszMessage);
3887 MMR3HeapFree(pszMessage);
3888 return rc;
3889}
3890
3891
3892/**
3893 * Worker for VMSetRuntimeErrorV for doing the job on EMT in ring-3.
3894 *
3895 * @returns VBox status code with modifications, see VMSetRuntimeErrorV.
3896 *
3897 * @param pVM The VM handle.
3898 * @param fFlags The error flags.
3899 * @param pszErrorId Error ID string.
3900 * @param pszFormat Format string.
3901 * @param pVa Pointer to the format arguments.
3902 *
3903 * @thread EMT
3904 */
3905DECLCALLBACK(int) vmR3SetRuntimeErrorV(PVM pVM, uint32_t fFlags, const char *pszErrorId, const char *pszFormat, va_list *pVa)
3906{
3907 /*
3908 * Make a copy of the message.
3909 */
3910 va_list va2;
3911 va_copy(va2, *pVa);
3912 vmSetRuntimeErrorCopy(pVM, fFlags, pszErrorId, pszFormat, va2);
3913 va_end(va2);
3914
3915 /*
3916 * Join paths with VMR3SetRuntimeErrorWorker.
3917 */
3918 return vmR3SetRuntimeErrorCommon(pVM, fFlags, pszErrorId, pszFormat, pVa);
3919}
3920
3921
3922/**
3923 * Gets the number of runtime errors raised via VMR3SetRuntimeError.
3924 *
3925 * This can be used avoid double error messages.
3926 *
3927 * @returns The runtime error count.
3928 * @param pVM The VM handle.
3929 */
3930VMMR3DECL(uint32_t) VMR3GetRuntimeErrorCount(PVM pVM)
3931{
3932 return pVM->pUVM->vm.s.cRuntimeErrors;
3933}
3934
3935
3936/**
3937 * Gets the ID virtual of the virtual CPU assoicated with the calling thread.
3938 *
3939 * @returns The CPU ID. NIL_VMCPUID if the thread isn't an EMT.
3940 *
3941 * @param pVM The VM handle.
3942 */
3943VMMR3DECL(RTCPUID) VMR3GetVMCPUId(PVM pVM)
3944{
3945 PUVMCPU pUVCpu = (PUVMCPU)RTTlsGet(pVM->pUVM->vm.s.idxTLS);
3946 return pUVCpu
3947 ? pUVCpu->idCpu
3948 : NIL_VMCPUID;
3949}
3950
3951
3952/**
3953 * Returns the native handle of the current EMT VMCPU thread.
3954 *
3955 * @returns Handle if this is an EMT thread; NIL_RTNATIVETHREAD otherwise
3956 * @param pVM The VM handle.
3957 * @thread EMT
3958 */
3959VMMR3DECL(RTNATIVETHREAD) VMR3GetVMCPUNativeThread(PVM pVM)
3960{
3961 PUVMCPU pUVCpu = (PUVMCPU)RTTlsGet(pVM->pUVM->vm.s.idxTLS);
3962
3963 if (!pUVCpu)
3964 return NIL_RTNATIVETHREAD;
3965
3966 return pUVCpu->vm.s.NativeThreadEMT;
3967}
3968
3969
3970/**
3971 * Returns the native handle of the current EMT VMCPU thread.
3972 *
3973 * @returns Handle if this is an EMT thread; NIL_RTNATIVETHREAD otherwise
3974 * @param pVM The VM handle.
3975 * @thread EMT
3976 */
3977VMMR3DECL(RTNATIVETHREAD) VMR3GetVMCPUNativeThreadU(PUVM pUVM)
3978{
3979 PUVMCPU pUVCpu = (PUVMCPU)RTTlsGet(pUVM->vm.s.idxTLS);
3980
3981 if (!pUVCpu)
3982 return NIL_RTNATIVETHREAD;
3983
3984 return pUVCpu->vm.s.NativeThreadEMT;
3985}
3986
3987
3988/**
3989 * Returns the handle of the current EMT VMCPU thread.
3990 *
3991 * @returns Handle if this is an EMT thread; NIL_RTNATIVETHREAD otherwise
3992 * @param pVM The VM handle.
3993 * @thread EMT
3994 */
3995VMMR3DECL(RTTHREAD) VMR3GetVMCPUThread(PVM pVM)
3996{
3997 PUVMCPU pUVCpu = (PUVMCPU)RTTlsGet(pVM->pUVM->vm.s.idxTLS);
3998
3999 if (!pUVCpu)
4000 return NIL_RTTHREAD;
4001
4002 return pUVCpu->vm.s.ThreadEMT;
4003}
4004
4005
4006/**
4007 * Returns the handle of the current EMT VMCPU thread.
4008 *
4009 * @returns Handle if this is an EMT thread; NIL_RTNATIVETHREAD otherwise
4010 * @param pVM The VM handle.
4011 * @thread EMT
4012 */
4013VMMR3DECL(RTTHREAD) VMR3GetVMCPUThreadU(PUVM pUVM)
4014{
4015 PUVMCPU pUVCpu = (PUVMCPU)RTTlsGet(pUVM->vm.s.idxTLS);
4016
4017 if (!pUVCpu)
4018 return NIL_RTTHREAD;
4019
4020 return pUVCpu->vm.s.ThreadEMT;
4021}
4022
4023
4024/**
4025 * Return the package and core id of a CPU.
4026 *
4027 * @returns VBOX status code.
4028 * @param pVM The VM to operate on.
4029 * @param idCpu Virtual CPU to get the ID from.
4030 * @param pidCpuCore Where to store the core ID of the virtual CPU.
4031 * @param pidCpuPackage Where to store the package ID of the virtual CPU.
4032 *
4033 */
4034VMMR3DECL(int) VMR3GetCpuCoreAndPackageIdFromCpuId(PVM pVM, VMCPUID idCpu, uint32_t *pidCpuCore, uint32_t *pidCpuPackage)
4035{
4036 if (idCpu >= pVM->cCpus)
4037 return VERR_INVALID_CPU_ID;
4038
4039#ifdef VBOX_WITH_MULTI_CORE
4040 *pidCpuCore = idCpu;
4041 *pidCpuPackage = 0;
4042#else
4043 *pidCpuCore = 0;
4044 *pidCpuPackage = idCpu;
4045#endif
4046
4047 return VINF_SUCCESS;
4048}
4049
4050
4051/**
4052 * Worker for VMR3HotUnplugCpu.
4053 *
4054 * @returns VINF_EM_WAIT_SPIP (strict status code).
4055 * @param pVM The VM handle.
4056 * @param idCpu The current CPU.
4057 */
4058static DECLCALLBACK(int) vmR3HotUnplugCpu(PVM pVM, VMCPUID idCpu)
4059{
4060 PVMCPU pVCpu = VMMGetCpuById(pVM, idCpu);
4061 VMCPU_ASSERT_EMT(pVCpu);
4062
4063 /*
4064 * Reset per CPU resources.
4065 *
4066 * Actually only needed for VT-x because the CPU seems to be still in some
4067 * paged mode and startup fails after a new hot plug event. SVM works fine
4068 * even without this.
4069 */
4070 Log(("vmR3HotUnplugCpu for VCPU %u\n", idCpu));
4071 PGMR3ResetUnpluggedCpu(pVM, pVCpu);
4072 PDMR3ResetCpu(pVCpu);
4073 TRPMR3ResetCpu(pVCpu);
4074 CPUMR3ResetCpu(pVCpu);
4075 EMR3ResetCpu(pVCpu);
4076 HWACCMR3ResetCpu(pVCpu);
4077 return VINF_EM_WAIT_SIPI;
4078}
4079
4080
4081/**
4082 * Hot-unplugs a CPU from the guest.
4083 *
4084 * @returns VBox status code.
4085 * @param pVM The VM to operate on.
4086 * @param idCpu Virtual CPU to perform the hot unplugging operation on.
4087 */
4088VMMR3DECL(int) VMR3HotUnplugCpu(PVM pVM, VMCPUID idCpu)
4089{
4090 AssertReturn(idCpu < pVM->cCpus, VERR_INVALID_CPU_ID);
4091
4092 /** @todo r=bird: Don't destroy the EMT, it'll break VMMR3EmtRendezvous and
4093 * broadcast requests. Just note down somewhere that the CPU is
4094 * offline and send it to SPIP wait. Maybe modify VMCPUSTATE and push
4095 * it out of the EM loops when offline. */
4096 return VMR3ReqCallNoWaitU(pVM->pUVM, idCpu, (PFNRT)vmR3HotUnplugCpu, 2, pVM, idCpu);
4097}
4098
4099
4100/**
4101 * Hot-plugs a CPU on the guest.
4102 *
4103 * @returns VBox status code.
4104 * @param pVM The VM to operate on.
4105 * @param idCpu Virtual CPU to perform the hot plugging operation on.
4106 */
4107VMMR3DECL(int) VMR3HotPlugCpu(PVM pVM, VMCPUID idCpu)
4108{
4109 AssertReturn(idCpu < pVM->cCpus, VERR_INVALID_CPU_ID);
4110
4111 /** @todo r-bird: Just mark it online and make sure it waits on SPIP. */
4112 return VINF_SUCCESS;
4113}
4114
4115
4116/**
4117 * Changes the VCPU priority.
4118 *
4119 * @returns VBox status code.
4120 * @param pVM The VM to operate on.
4121 * @param ulCpuPriority New CPU priority
4122 */
4123VMMR3DECL(int) VMR3SetCpuPriority(PVM pVM, unsigned ulCpuPriority)
4124{
4125 AssertReturn(ulCpuPriority > 0 && ulCpuPriority <= 100, VERR_INVALID_PARAMETER);
4126
4127 Log(("VMR3SetCpuPriority: new priority = %d\n", ulCpuPriority));
4128 /* Note: not called from EMT. */
4129 pVM->uCpuPriority = ulCpuPriority;
4130 return VINF_SUCCESS;
4131}
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