VirtualBox

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

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

(C) year

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