VirtualBox

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

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

VMM/MM: Removed the hyper heap. bugref:10093 bugref:9517

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