VirtualBox

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

Last change on this file since 84054 was 84054, checked in by vboxsync, 5 years ago

IPRT,++: Apply bldprog-strtab.h and friends to the IPRT status message database (errmsg.cpp) to reduce size. The interface (RTErrMsg*) has been reworked as we no longer have C-strings in the database, but 'compressed' string w/o zero terminators. bugref:9726

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