VirtualBox

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

Last change on this file since 50653 was 50596, checked in by vboxsync, 10 years ago

VMM: follow-up fix to r92440

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

© 2023 Oracle
ContactPrivacy policyTerms of Use