VirtualBox

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

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

VMM: Refuse to run on macOS 12. bugref:10124

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