VirtualBox

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

Last change on this file since 56296 was 55881, checked in by vboxsync, 9 years ago

DBGF,DBGC: Moved the plug-ins from DBGC to DBGF so we can make use of them via IMachineDebugger.

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