VirtualBox

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

Last change on this file since 90439 was 90397, checked in by vboxsync, 3 years ago

VMM: Create EMTs with RTTHREADFLAGS_NO_SIGNALS set to avoid unnecessary EINTR fun. bugref:6695

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

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