VirtualBox

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

Last change on this file since 70918 was 70918, checked in by vboxsync, 7 years ago

VMM: NEM kick off.

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette