VirtualBox

source: vbox/trunk/src/VBox/VMM/VMMR0/GVMMR0.cpp@ 29698

Last change on this file since 29698 was 29250, checked in by vboxsync, 15 years ago

iprt/asm*.h: split out asm-math.h, don't include asm-*.h from asm.h, don't include asm.h from sup.h. Fixed a couple file headers.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 68.2 KB
Line 
1/* $Id: GVMMR0.cpp 29250 2010-05-09 17:53:58Z vboxsync $ */
2/** @file
3 * GVMM - Global VM Manager.
4 */
5
6/*
7 * Copyright (C) 2007 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
19/** @page pg_gvmm GVMM - The Global VM Manager
20 *
21 * The Global VM Manager lives in ring-0. It's main function at the moment
22 * is to manage a list of all running VMs, keep a ring-0 only structure (GVM)
23 * for each of them, and assign them unique identifiers (so GMM can track
24 * page owners). The idea for the future is to add an idle priority kernel
25 * thread that can take care of tasks like page sharing.
26 *
27 * The GVMM will create a ring-0 object for each VM when it's registered,
28 * this is both for session cleanup purposes and for having a point where
29 * it's possible to implement usage polices later (in SUPR0ObjRegister).
30 */
31
32
33/*******************************************************************************
34* Header Files *
35*******************************************************************************/
36#define LOG_GROUP LOG_GROUP_GVMM
37#include <VBox/gvmm.h>
38#include <VBox/gmm.h>
39#include "GVMMR0Internal.h"
40#include <VBox/gvm.h>
41#include <VBox/vm.h>
42#include <VBox/vmm.h>
43#include <VBox/param.h>
44#include <VBox/err.h>
45#include <iprt/asm.h>
46#include <iprt/asm-amd64-x86.h>
47#include <iprt/mem.h>
48#include <iprt/semaphore.h>
49#include <iprt/time.h>
50#include <VBox/log.h>
51#include <iprt/thread.h>
52#include <iprt/process.h>
53#include <iprt/param.h>
54#include <iprt/string.h>
55#include <iprt/assert.h>
56#include <iprt/mem.h>
57#include <iprt/memobj.h>
58#include <iprt/mp.h>
59
60
61/*******************************************************************************
62* Structures and Typedefs *
63*******************************************************************************/
64
65/**
66 * Global VM handle.
67 */
68typedef struct GVMHANDLE
69{
70 /** The index of the next handle in the list (free or used). (0 is nil.) */
71 uint16_t volatile iNext;
72 /** Our own index / handle value. */
73 uint16_t iSelf;
74 /** The pointer to the ring-0 only (aka global) VM structure. */
75 PGVM pGVM;
76 /** The ring-0 mapping of the shared VM instance data. */
77 PVM pVM;
78 /** The virtual machine object. */
79 void *pvObj;
80 /** The session this VM is associated with. */
81 PSUPDRVSESSION pSession;
82 /** The ring-0 handle of the EMT0 thread.
83 * This is used for ownership checks as well as looking up a VM handle by thread
84 * at times like assertions. */
85 RTNATIVETHREAD hEMT0;
86 /** The process ID of the handle owner.
87 * This is used for access checks. */
88 RTPROCESS ProcId;
89} GVMHANDLE;
90/** Pointer to a global VM handle. */
91typedef GVMHANDLE *PGVMHANDLE;
92
93/** Number of GVM handles (including the NIL handle). */
94#if HC_ARCH_BITS == 64
95# define GVMM_MAX_HANDLES 1024
96#else
97# define GVMM_MAX_HANDLES 128
98#endif
99
100/**
101 * The GVMM instance data.
102 */
103typedef struct GVMM
104{
105 /** Eyecatcher / magic. */
106 uint32_t u32Magic;
107 /** The index of the head of the free handle chain. (0 is nil.) */
108 uint16_t volatile iFreeHead;
109 /** The index of the head of the active handle chain. (0 is nil.) */
110 uint16_t volatile iUsedHead;
111 /** The number of VMs. */
112 uint16_t volatile cVMs;
113// /** The number of halted EMT threads. */
114// uint16_t volatile cHaltedEMTs;
115 /** The number of EMTs. */
116 uint32_t volatile cEMTs;
117 /** The lock used to serialize VM creation, destruction and associated events that
118 * isn't performance critical. Owners may acquire the list lock. */
119 RTSEMFASTMUTEX CreateDestroyLock;
120 /** The lock used to serialize used list updates and accesses.
121 * This indirectly includes scheduling since the scheduler will have to walk the
122 * used list to examin running VMs. Owners may not acquire any other locks. */
123 RTSEMFASTMUTEX UsedLock;
124 /** The handle array.
125 * The size of this array defines the maximum number of currently running VMs.
126 * The first entry is unused as it represents the NIL handle. */
127 GVMHANDLE aHandles[GVMM_MAX_HANDLES];
128
129 /** @gcfgm{/GVMM/cEMTsMeansCompany, 32-bit, 0, UINT32_MAX, 1}
130 * The number of EMTs that means we no longer consider ourselves alone on a
131 * CPU/Core.
132 */
133 uint32_t cEMTsMeansCompany;
134 /** @gcfgm{/GVMM/MinSleepAlone,32-bit, 0, 100000000, 750000, ns}
135 * The minimum sleep time for when we're alone, in nano seconds.
136 */
137 uint32_t nsMinSleepAlone;
138 /** @gcfgm{/GVMM/MinSleepCompany,32-bit,0, 100000000, 15000, ns}
139 * The minimum sleep time for when we've got company, in nano seconds.
140 */
141 uint32_t nsMinSleepCompany;
142 /** @gcfgm{/GVMM/EarlyWakeUp1, 32-bit, 0, 100000000, 25000, ns}
143 * The limit for the first round of early wakeups, given in nano seconds.
144 */
145 uint32_t nsEarlyWakeUp1;
146 /** @gcfgm{/GVMM/EarlyWakeUp2, 32-bit, 0, 100000000, 50000, ns}
147 * The limit for the second round of early wakeups, given in nano seconds.
148 */
149 uint32_t nsEarlyWakeUp2;
150} GVMM;
151/** Pointer to the GVMM instance data. */
152typedef GVMM *PGVMM;
153
154/** The GVMM::u32Magic value (Charlie Haden). */
155#define GVMM_MAGIC 0x19370806
156
157
158
159/*******************************************************************************
160* Global Variables *
161*******************************************************************************/
162/** Pointer to the GVMM instance data.
163 * (Just my general dislike for global variables.) */
164static PGVMM g_pGVMM = NULL;
165
166/** Macro for obtaining and validating the g_pGVMM pointer.
167 * On failure it will return from the invoking function with the specified return value.
168 *
169 * @param pGVMM The name of the pGVMM variable.
170 * @param rc The return value on failure. Use VERR_INTERNAL_ERROR for
171 * VBox status codes.
172 */
173#define GVMM_GET_VALID_INSTANCE(pGVMM, rc) \
174 do { \
175 (pGVMM) = g_pGVMM;\
176 AssertPtrReturn((pGVMM), (rc)); \
177 AssertMsgReturn((pGVMM)->u32Magic == GVMM_MAGIC, ("%p - %#x\n", (pGVMM), (pGVMM)->u32Magic), (rc)); \
178 } while (0)
179
180/** Macro for obtaining and validating the g_pGVMM pointer, void function variant.
181 * On failure it will return from the invoking function.
182 *
183 * @param pGVMM The name of the pGVMM variable.
184 */
185#define GVMM_GET_VALID_INSTANCE_VOID(pGVMM) \
186 do { \
187 (pGVMM) = g_pGVMM;\
188 AssertPtrReturnVoid((pGVMM)); \
189 AssertMsgReturnVoid((pGVMM)->u32Magic == GVMM_MAGIC, ("%p - %#x\n", (pGVMM), (pGVMM)->u32Magic)); \
190 } while (0)
191
192
193/*******************************************************************************
194* Internal Functions *
195*******************************************************************************/
196static void gvmmR0InitPerVMData(PGVM pGVM);
197static DECLCALLBACK(void) gvmmR0HandleObjDestructor(void *pvObj, void *pvGVMM, void *pvHandle);
198static int gvmmR0ByVM(PVM pVM, PGVM *ppGVM, PGVMM *ppGVMM, bool fTakeUsedLock);
199static int gvmmR0ByVMAndEMT(PVM pVM, VMCPUID idCpu, PGVM *ppGVM, PGVMM *ppGVMM);
200
201
202/**
203 * Initializes the GVMM.
204 *
205 * This is called while owninng the loader sempahore (see supdrvIOCtl_LdrLoad()).
206 *
207 * @returns VBox status code.
208 */
209GVMMR0DECL(int) GVMMR0Init(void)
210{
211 LogFlow(("GVMMR0Init:\n"));
212
213 /*
214 * Allocate and initialize the instance data.
215 */
216 PGVMM pGVMM = (PGVMM)RTMemAllocZ(sizeof(*pGVMM));
217 if (!pGVMM)
218 return VERR_NO_MEMORY;
219 int rc = RTSemFastMutexCreate(&pGVMM->CreateDestroyLock);
220 if (RT_SUCCESS(rc))
221 {
222 rc = RTSemFastMutexCreate(&pGVMM->UsedLock);
223 if (RT_SUCCESS(rc))
224 {
225 pGVMM->u32Magic = GVMM_MAGIC;
226 pGVMM->iUsedHead = 0;
227 pGVMM->iFreeHead = 1;
228
229 /* the nil handle */
230 pGVMM->aHandles[0].iSelf = 0;
231 pGVMM->aHandles[0].iNext = 0;
232
233 /* the tail */
234 unsigned i = RT_ELEMENTS(pGVMM->aHandles) - 1;
235 pGVMM->aHandles[i].iSelf = i;
236 pGVMM->aHandles[i].iNext = 0; /* nil */
237
238 /* the rest */
239 while (i-- > 1)
240 {
241 pGVMM->aHandles[i].iSelf = i;
242 pGVMM->aHandles[i].iNext = i + 1;
243 }
244
245 /* The default configuration values. */
246 pGVMM->cEMTsMeansCompany = 1; /** @todo should be adjusted to relative to the cpu count or something... */
247 pGVMM->nsMinSleepAlone = 750000 /* ns (0.750 ms) */; /** @todo this should be adjusted to be 75% (or something) of the scheduler granularity... */
248 pGVMM->nsMinSleepCompany = 15000 /* ns (0.015 ms) */;
249 pGVMM->nsEarlyWakeUp1 = 25000 /* ns (0.025 ms) */;
250 pGVMM->nsEarlyWakeUp2 = 50000 /* ns (0.050 ms) */;
251
252 g_pGVMM = pGVMM;
253 LogFlow(("GVMMR0Init: pGVMM=%p\n", pGVMM));
254 return VINF_SUCCESS;
255 }
256
257 RTSemFastMutexDestroy(pGVMM->CreateDestroyLock);
258 }
259
260 RTMemFree(pGVMM);
261 return rc;
262}
263
264
265/**
266 * Terminates the GVM.
267 *
268 * This is called while owning the loader semaphore (see supdrvLdrFree()).
269 * And unless something is wrong, there should be absolutely no VMs
270 * registered at this point.
271 */
272GVMMR0DECL(void) GVMMR0Term(void)
273{
274 LogFlow(("GVMMR0Term:\n"));
275
276 PGVMM pGVMM = g_pGVMM;
277 g_pGVMM = NULL;
278 if (RT_UNLIKELY(!VALID_PTR(pGVMM)))
279 {
280 SUPR0Printf("GVMMR0Term: pGVMM=%p\n", pGVMM);
281 return;
282 }
283
284 pGVMM->u32Magic++;
285
286 RTSemFastMutexDestroy(pGVMM->UsedLock);
287 pGVMM->UsedLock = NIL_RTSEMFASTMUTEX;
288 RTSemFastMutexDestroy(pGVMM->CreateDestroyLock);
289 pGVMM->CreateDestroyLock = NIL_RTSEMFASTMUTEX;
290
291 pGVMM->iFreeHead = 0;
292 if (pGVMM->iUsedHead)
293 {
294 SUPR0Printf("GVMMR0Term: iUsedHead=%#x! (cVMs=%#x cEMTs=%#x)\n", pGVMM->iUsedHead, pGVMM->cVMs, pGVMM->cEMTs);
295 pGVMM->iUsedHead = 0;
296 }
297
298 RTMemFree(pGVMM);
299}
300
301
302/**
303 * A quick hack for setting global config values.
304 *
305 * @returns VBox status code.
306 *
307 * @param pSession The session handle. Used for authentication.
308 * @param pszName The variable name.
309 * @param u64Value The new value.
310 */
311GVMMR0DECL(int) GVMMR0SetConfig(PSUPDRVSESSION pSession, const char *pszName, uint64_t u64Value)
312{
313 /*
314 * Validate input.
315 */
316 PGVMM pGVMM;
317 GVMM_GET_VALID_INSTANCE(pGVMM, VERR_INTERNAL_ERROR);
318 AssertPtrReturn(pSession, VERR_INVALID_HANDLE);
319 AssertPtrReturn(pszName, VERR_INVALID_POINTER);
320
321 /*
322 * String switch time!
323 */
324 if (strncmp(pszName, "/GVMM/", sizeof("/GVMM/") - 1))
325 return VERR_CFGM_VALUE_NOT_FOUND; /* borrow status codes from CFGM... */
326 int rc = VINF_SUCCESS;
327 pszName += sizeof("/GVMM/") - 1;
328 if (!strcmp(pszName, "cEMTsMeansCompany"))
329 {
330 if (u64Value <= UINT32_MAX)
331 pGVMM->cEMTsMeansCompany = u64Value;
332 else
333 rc = VERR_OUT_OF_RANGE;
334 }
335 else if (!strcmp(pszName, "MinSleepAlone"))
336 {
337 if (u64Value <= 100000000)
338 pGVMM->nsMinSleepAlone = u64Value;
339 else
340 rc = VERR_OUT_OF_RANGE;
341 }
342 else if (!strcmp(pszName, "MinSleepCompany"))
343 {
344 if (u64Value <= 100000000)
345 pGVMM->nsMinSleepCompany = u64Value;
346 else
347 rc = VERR_OUT_OF_RANGE;
348 }
349 else if (!strcmp(pszName, "EarlyWakeUp1"))
350 {
351 if (u64Value <= 100000000)
352 pGVMM->nsEarlyWakeUp1 = u64Value;
353 else
354 rc = VERR_OUT_OF_RANGE;
355 }
356 else if (!strcmp(pszName, "EarlyWakeUp2"))
357 {
358 if (u64Value <= 100000000)
359 pGVMM->nsEarlyWakeUp2 = u64Value;
360 else
361 rc = VERR_OUT_OF_RANGE;
362 }
363 else
364 rc = VERR_CFGM_VALUE_NOT_FOUND;
365 return rc;
366}
367
368
369/**
370 * A quick hack for getting global config values.
371 *
372 * @returns VBox status code.
373 *
374 * @param pSession The session handle. Used for authentication.
375 * @param pszName The variable name.
376 * @param u64Value The new value.
377 */
378GVMMR0DECL(int) GVMMR0QueryConfig(PSUPDRVSESSION pSession, const char *pszName, uint64_t *pu64Value)
379{
380 /*
381 * Validate input.
382 */
383 PGVMM pGVMM;
384 GVMM_GET_VALID_INSTANCE(pGVMM, VERR_INTERNAL_ERROR);
385 AssertPtrReturn(pSession, VERR_INVALID_HANDLE);
386 AssertPtrReturn(pszName, VERR_INVALID_POINTER);
387 AssertPtrReturn(pu64Value, VERR_INVALID_POINTER);
388
389 /*
390 * String switch time!
391 */
392 if (strncmp(pszName, "/GVMM/", sizeof("/GVMM/") - 1))
393 return VERR_CFGM_VALUE_NOT_FOUND; /* borrow status codes from CFGM... */
394 int rc = VINF_SUCCESS;
395 pszName += sizeof("/GVMM/") - 1;
396 if (!strcmp(pszName, "cEMTsMeansCompany"))
397 *pu64Value = pGVMM->cEMTsMeansCompany;
398 else if (!strcmp(pszName, "MinSleepAlone"))
399 *pu64Value = pGVMM->nsMinSleepAlone;
400 else if (!strcmp(pszName, "MinSleepCompany"))
401 *pu64Value = pGVMM->nsMinSleepCompany;
402 else if (!strcmp(pszName, "EarlyWakeUp1"))
403 *pu64Value = pGVMM->nsEarlyWakeUp1;
404 else if (!strcmp(pszName, "EarlyWakeUp2"))
405 *pu64Value = pGVMM->nsEarlyWakeUp2;
406 else
407 rc = VERR_CFGM_VALUE_NOT_FOUND;
408 return rc;
409}
410
411
412/**
413 * Try acquire the 'used' lock.
414 *
415 * @returns IPRT status code, see RTSemFastMutexRequest.
416 * @param pGVMM The GVMM instance data.
417 */
418DECLINLINE(int) gvmmR0UsedLock(PGVMM pGVMM)
419{
420 LogFlow(("++gvmmR0UsedLock(%p)\n", pGVMM));
421 int rc = RTSemFastMutexRequest(pGVMM->UsedLock);
422 LogFlow(("gvmmR0UsedLock(%p)->%Rrc\n", pGVMM, rc));
423 return rc;
424}
425
426
427/**
428 * Release the 'used' lock.
429 *
430 * @returns IPRT status code, see RTSemFastMutexRelease.
431 * @param pGVMM The GVMM instance data.
432 */
433DECLINLINE(int) gvmmR0UsedUnlock(PGVMM pGVMM)
434{
435 LogFlow(("--gvmmR0UsedUnlock(%p)\n", pGVMM));
436 int rc = RTSemFastMutexRelease(pGVMM->UsedLock);
437 AssertRC(rc);
438 return rc;
439}
440
441
442/**
443 * Try acquire the 'create & destroy' lock.
444 *
445 * @returns IPRT status code, see RTSemFastMutexRequest.
446 * @param pGVMM The GVMM instance data.
447 */
448DECLINLINE(int) gvmmR0CreateDestroyLock(PGVMM pGVMM)
449{
450 LogFlow(("++gvmmR0CreateDestroyLock(%p)\n", pGVMM));
451 int rc = RTSemFastMutexRequest(pGVMM->CreateDestroyLock);
452 LogFlow(("gvmmR0CreateDestroyLock(%p)->%Rrc\n", pGVMM, rc));
453 return rc;
454}
455
456
457/**
458 * Release the 'create & destroy' lock.
459 *
460 * @returns IPRT status code, see RTSemFastMutexRequest.
461 * @param pGVMM The GVMM instance data.
462 */
463DECLINLINE(int) gvmmR0CreateDestroyUnlock(PGVMM pGVMM)
464{
465 LogFlow(("--gvmmR0CreateDestroyUnlock(%p)\n", pGVMM));
466 int rc = RTSemFastMutexRelease(pGVMM->CreateDestroyLock);
467 AssertRC(rc);
468 return rc;
469}
470
471
472/**
473 * Request wrapper for the GVMMR0CreateVM API.
474 *
475 * @returns VBox status code.
476 * @param pReq The request buffer.
477 */
478GVMMR0DECL(int) GVMMR0CreateVMReq(PGVMMCREATEVMREQ pReq)
479{
480 /*
481 * Validate the request.
482 */
483 if (!VALID_PTR(pReq))
484 return VERR_INVALID_POINTER;
485 if (pReq->Hdr.cbReq != sizeof(*pReq))
486 return VERR_INVALID_PARAMETER;
487 if (!VALID_PTR(pReq->pSession))
488 return VERR_INVALID_POINTER;
489
490 /*
491 * Execute it.
492 */
493 PVM pVM;
494 pReq->pVMR0 = NULL;
495 pReq->pVMR3 = NIL_RTR3PTR;
496 int rc = GVMMR0CreateVM(pReq->pSession, pReq->cCpus, &pVM);
497 if (RT_SUCCESS(rc))
498 {
499 pReq->pVMR0 = pVM;
500 pReq->pVMR3 = pVM->pVMR3;
501 }
502 return rc;
503}
504
505
506/**
507 * Allocates the VM structure and registers it with GVM.
508 *
509 * The caller will become the VM owner and there by the EMT.
510 *
511 * @returns VBox status code.
512 * @param pSession The support driver session.
513 * @param cCpus Number of virtual CPUs for the new VM.
514 * @param ppVM Where to store the pointer to the VM structure.
515 *
516 * @thread EMT.
517 */
518GVMMR0DECL(int) GVMMR0CreateVM(PSUPDRVSESSION pSession, uint32_t cCpus, PVM *ppVM)
519{
520 LogFlow(("GVMMR0CreateVM: pSession=%p\n", pSession));
521 PGVMM pGVMM;
522 GVMM_GET_VALID_INSTANCE(pGVMM, VERR_INTERNAL_ERROR);
523
524 AssertPtrReturn(ppVM, VERR_INVALID_POINTER);
525 *ppVM = NULL;
526
527 if ( cCpus == 0
528 || cCpus > VMM_MAX_CPU_COUNT)
529 return VERR_INVALID_PARAMETER;
530
531 RTNATIVETHREAD hEMT0 = RTThreadNativeSelf();
532 AssertReturn(hEMT0 != NIL_RTNATIVETHREAD, VERR_INTERNAL_ERROR);
533 RTNATIVETHREAD ProcId = RTProcSelf();
534 AssertReturn(ProcId != NIL_RTPROCESS, VERR_INTERNAL_ERROR);
535
536 /*
537 * The whole allocation process is protected by the lock.
538 */
539 int rc = gvmmR0CreateDestroyLock(pGVMM);
540 AssertRCReturn(rc, rc);
541
542 /*
543 * Allocate a handle first so we don't waste resources unnecessarily.
544 */
545 uint16_t iHandle = pGVMM->iFreeHead;
546 if (iHandle)
547 {
548 PGVMHANDLE pHandle = &pGVMM->aHandles[iHandle];
549
550 /* consistency checks, a bit paranoid as always. */
551 if ( !pHandle->pVM
552 && !pHandle->pGVM
553 && !pHandle->pvObj
554 && pHandle->iSelf == iHandle)
555 {
556 pHandle->pvObj = SUPR0ObjRegister(pSession, SUPDRVOBJTYPE_VM, gvmmR0HandleObjDestructor, pGVMM, pHandle);
557 if (pHandle->pvObj)
558 {
559 /*
560 * Move the handle from the free to used list and perform permission checks.
561 */
562 rc = gvmmR0UsedLock(pGVMM);
563 AssertRC(rc);
564
565 pGVMM->iFreeHead = pHandle->iNext;
566 pHandle->iNext = pGVMM->iUsedHead;
567 pGVMM->iUsedHead = iHandle;
568 pGVMM->cVMs++;
569
570 pHandle->pVM = NULL;
571 pHandle->pGVM = NULL;
572 pHandle->pSession = pSession;
573 pHandle->hEMT0 = NIL_RTNATIVETHREAD;
574 pHandle->ProcId = NIL_RTPROCESS;
575
576 gvmmR0UsedUnlock(pGVMM);
577
578 rc = SUPR0ObjVerifyAccess(pHandle->pvObj, pSession, NULL);
579 if (RT_SUCCESS(rc))
580 {
581 /*
582 * Allocate the global VM structure (GVM) and initialize it.
583 */
584 PGVM pGVM = (PGVM)RTMemAllocZ(RT_UOFFSETOF(GVM, aCpus[cCpus]));
585 if (pGVM)
586 {
587 pGVM->u32Magic = GVM_MAGIC;
588 pGVM->hSelf = iHandle;
589 pGVM->pVM = NULL;
590 pGVM->cCpus = cCpus;
591
592 gvmmR0InitPerVMData(pGVM);
593 GMMR0InitPerVMData(pGVM);
594
595 /*
596 * Allocate the shared VM structure and associated page array.
597 */
598 const uint32_t cbVM = RT_UOFFSETOF(VM, aCpus[cCpus]);
599 const uint32_t cPages = RT_ALIGN_32(cbVM, PAGE_SIZE) >> PAGE_SHIFT;
600#ifdef RT_OS_DARWIN /** @todo Figure out why this is broken. Is it only on snow leopard? */
601 rc = RTR0MemObjAllocLow(&pGVM->gvmm.s.VMMemObj, (cPages + 1) << PAGE_SHIFT, false /* fExecutable */);
602#else
603 rc = RTR0MemObjAllocLow(&pGVM->gvmm.s.VMMemObj, cPages << PAGE_SHIFT, false /* fExecutable */);
604#endif
605 if (RT_SUCCESS(rc))
606 {
607 PVM pVM = (PVM)RTR0MemObjAddress(pGVM->gvmm.s.VMMemObj); AssertPtr(pVM);
608 memset(pVM, 0, cPages << PAGE_SHIFT);
609 pVM->enmVMState = VMSTATE_CREATING;
610 pVM->pVMR0 = pVM;
611 pVM->pSession = pSession;
612 pVM->hSelf = iHandle;
613 pVM->cbSelf = cbVM;
614 pVM->cCpus = cCpus;
615 pVM->offVMCPU = RT_UOFFSETOF(VM, aCpus);
616
617 rc = RTR0MemObjAllocPage(&pGVM->gvmm.s.VMPagesMemObj, cPages * sizeof(SUPPAGE), false /* fExecutable */);
618 if (RT_SUCCESS(rc))
619 {
620 PSUPPAGE paPages = (PSUPPAGE)RTR0MemObjAddress(pGVM->gvmm.s.VMPagesMemObj); AssertPtr(paPages);
621 for (uint32_t iPage = 0; iPage < cPages; iPage++)
622 {
623 paPages[iPage].uReserved = 0;
624 paPages[iPage].Phys = RTR0MemObjGetPagePhysAddr(pGVM->gvmm.s.VMMemObj, iPage);
625 Assert(paPages[iPage].Phys != NIL_RTHCPHYS);
626 }
627
628 /*
629 * Map them into ring-3.
630 */
631 rc = RTR0MemObjMapUser(&pGVM->gvmm.s.VMMapObj, pGVM->gvmm.s.VMMemObj, (RTR3PTR)-1, 0,
632 RTMEM_PROT_READ | RTMEM_PROT_WRITE, NIL_RTR0PROCESS);
633 if (RT_SUCCESS(rc))
634 {
635 pVM->pVMR3 = RTR0MemObjAddressR3(pGVM->gvmm.s.VMMapObj);
636 AssertPtr((void *)pVM->pVMR3);
637
638 /* Initialize all the VM pointers. */
639 for (uint32_t i = 0; i < cCpus; i++)
640 {
641 pVM->aCpus[i].pVMR0 = pVM;
642 pVM->aCpus[i].pVMR3 = pVM->pVMR3;
643 }
644
645 rc = RTR0MemObjMapUser(&pGVM->gvmm.s.VMPagesMapObj, pGVM->gvmm.s.VMPagesMemObj, (RTR3PTR)-1, 0,
646 RTMEM_PROT_READ | RTMEM_PROT_WRITE, NIL_RTR0PROCESS);
647 if (RT_SUCCESS(rc))
648 {
649 pVM->paVMPagesR3 = RTR0MemObjAddressR3(pGVM->gvmm.s.VMPagesMapObj);
650 AssertPtr((void *)pVM->paVMPagesR3);
651
652 /* complete the handle - take the UsedLock sem just to be careful. */
653 rc = gvmmR0UsedLock(pGVMM);
654 AssertRC(rc);
655
656 pHandle->pVM = pVM;
657 pHandle->pGVM = pGVM;
658 pHandle->hEMT0 = hEMT0;
659 pHandle->ProcId = ProcId;
660 pGVM->pVM = pVM;
661 pGVM->aCpus[0].hEMT = hEMT0;
662 pGVMM->cEMTs += cCpus;
663
664 gvmmR0UsedUnlock(pGVMM);
665 gvmmR0CreateDestroyUnlock(pGVMM);
666
667 *ppVM = pVM;
668 Log(("GVMMR0CreateVM: pVM=%p pVMR3=%p pGVM=%p hGVM=%d\n", pVM, pVM->pVMR3, pGVM, iHandle));
669 return VINF_SUCCESS;
670 }
671
672 RTR0MemObjFree(pGVM->gvmm.s.VMMapObj, false /* fFreeMappings */);
673 pGVM->gvmm.s.VMMapObj = NIL_RTR0MEMOBJ;
674 }
675 RTR0MemObjFree(pGVM->gvmm.s.VMPagesMemObj, false /* fFreeMappings */);
676 pGVM->gvmm.s.VMPagesMemObj = NIL_RTR0MEMOBJ;
677 }
678 RTR0MemObjFree(pGVM->gvmm.s.VMMemObj, false /* fFreeMappings */);
679 pGVM->gvmm.s.VMMemObj = NIL_RTR0MEMOBJ;
680 }
681 }
682 }
683 /* else: The user wasn't permitted to create this VM. */
684
685 /*
686 * The handle will be freed by gvmmR0HandleObjDestructor as we release the
687 * object reference here. A little extra mess because of non-recursive lock.
688 */
689 void *pvObj = pHandle->pvObj;
690 pHandle->pvObj = NULL;
691 gvmmR0CreateDestroyUnlock(pGVMM);
692
693 SUPR0ObjRelease(pvObj, pSession);
694
695 SUPR0Printf("GVMMR0CreateVM: failed, rc=%d\n", rc);
696 return rc;
697 }
698
699 rc = VERR_NO_MEMORY;
700 }
701 else
702 rc = VERR_INTERNAL_ERROR;
703 }
704 else
705 rc = VERR_GVM_TOO_MANY_VMS;
706
707 gvmmR0CreateDestroyUnlock(pGVMM);
708 return rc;
709}
710
711
712/**
713 * Initializes the per VM data belonging to GVMM.
714 *
715 * @param pGVM Pointer to the global VM structure.
716 */
717static void gvmmR0InitPerVMData(PGVM pGVM)
718{
719 AssertCompile(RT_SIZEOFMEMB(GVM,gvmm.s) <= RT_SIZEOFMEMB(GVM,gvmm.padding));
720 AssertCompile(RT_SIZEOFMEMB(GVMCPU,gvmm.s) <= RT_SIZEOFMEMB(GVMCPU,gvmm.padding));
721 pGVM->gvmm.s.VMMemObj = NIL_RTR0MEMOBJ;
722 pGVM->gvmm.s.VMMapObj = NIL_RTR0MEMOBJ;
723 pGVM->gvmm.s.VMPagesMemObj = NIL_RTR0MEMOBJ;
724 pGVM->gvmm.s.VMPagesMapObj = NIL_RTR0MEMOBJ;
725 pGVM->gvmm.s.fDoneVMMR0Init = false;
726 pGVM->gvmm.s.fDoneVMMR0Term = false;
727
728 for (VMCPUID i = 0; i < pGVM->cCpus; i++)
729 {
730 pGVM->aCpus[i].gvmm.s.HaltEventMulti = NIL_RTSEMEVENTMULTI;
731 pGVM->aCpus[i].hEMT = NIL_RTNATIVETHREAD;
732 }
733}
734
735
736/**
737 * Does the VM initialization.
738 *
739 * @returns VBox status code.
740 * @param pVM Pointer to the shared VM structure.
741 */
742GVMMR0DECL(int) GVMMR0InitVM(PVM pVM)
743{
744 LogFlow(("GVMMR0InitVM: pVM=%p\n", pVM));
745
746 /*
747 * Validate the VM structure, state and handle.
748 */
749 PGVM pGVM;
750 PGVMM pGVMM;
751 int rc = gvmmR0ByVMAndEMT(pVM, 0 /* idCpu */, &pGVM, &pGVMM);
752 if (RT_SUCCESS(rc))
753 {
754 if ( !pGVM->gvmm.s.fDoneVMMR0Init
755 && pGVM->aCpus[0].gvmm.s.HaltEventMulti == NIL_RTSEMEVENTMULTI)
756 {
757 for (VMCPUID i = 0; i < pGVM->cCpus; i++)
758 {
759 rc = RTSemEventMultiCreate(&pGVM->aCpus[i].gvmm.s.HaltEventMulti);
760 if (RT_FAILURE(rc))
761 {
762 pGVM->aCpus[i].gvmm.s.HaltEventMulti = NIL_RTSEMEVENTMULTI;
763 break;
764 }
765 }
766 }
767 else
768 rc = VERR_WRONG_ORDER;
769 }
770
771 LogFlow(("GVMMR0InitVM: returns %Rrc\n", rc));
772 return rc;
773}
774
775
776/**
777 * Indicates that we're done with the ring-0 initialization
778 * of the VM.
779 *
780 * @param pVM Pointer to the shared VM structure.
781 * @thread EMT(0)
782 */
783GVMMR0DECL(void) GVMMR0DoneInitVM(PVM pVM)
784{
785 /* Validate the VM structure, state and handle. */
786 PGVM pGVM;
787 PGVMM pGVMM;
788 int rc = gvmmR0ByVMAndEMT(pVM, 0 /* idCpu */, &pGVM, &pGVMM);
789 AssertRCReturnVoid(rc);
790
791 /* Set the indicator. */
792 pGVM->gvmm.s.fDoneVMMR0Init = true;
793}
794
795
796/**
797 * Indicates that we're doing the ring-0 termination of the VM.
798 *
799 * @returns true if termination hasn't been done already, false if it has.
800 * @param pVM Pointer to the shared VM structure.
801 * @param pGVM Pointer to the global VM structure. Optional.
802 * @thread EMT(0)
803 */
804GVMMR0DECL(bool) GVMMR0DoingTermVM(PVM pVM, PGVM pGVM)
805{
806 /* Validate the VM structure, state and handle. */
807 AssertPtrNullReturn(pGVM, false);
808 AssertReturn(!pGVM || pGVM->u32Magic == GVM_MAGIC, false);
809 if (!pGVM)
810 {
811 PGVMM pGVMM;
812 int rc = gvmmR0ByVMAndEMT(pVM, 0 /* idCpu */, &pGVM, &pGVMM);
813 AssertRCReturn(rc, false);
814 }
815
816 /* Set the indicator. */
817 if (pGVM->gvmm.s.fDoneVMMR0Term)
818 return false;
819 pGVM->gvmm.s.fDoneVMMR0Term = true;
820 return true;
821}
822
823
824/**
825 * Destroys the VM, freeing all associated resources (the ring-0 ones anyway).
826 *
827 * This is call from the vmR3DestroyFinalBit and from a error path in VMR3Create,
828 * and the caller is not the EMT thread, unfortunately. For security reasons, it
829 * would've been nice if the caller was actually the EMT thread or that we somehow
830 * could've associated the calling thread with the VM up front.
831 *
832 * @returns VBox status code.
833 * @param pVM Where to store the pointer to the VM structure.
834 *
835 * @thread EMT(0) if it's associated with the VM, otherwise any thread.
836 */
837GVMMR0DECL(int) GVMMR0DestroyVM(PVM pVM)
838{
839 LogFlow(("GVMMR0DestroyVM: pVM=%p\n", pVM));
840 PGVMM pGVMM;
841 GVMM_GET_VALID_INSTANCE(pGVMM, VERR_INTERNAL_ERROR);
842
843
844 /*
845 * Validate the VM structure, state and caller.
846 */
847 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
848 AssertReturn(!((uintptr_t)pVM & PAGE_OFFSET_MASK), VERR_INVALID_POINTER);
849 AssertMsgReturn(pVM->enmVMState >= VMSTATE_CREATING && pVM->enmVMState <= VMSTATE_TERMINATED, ("%d\n", pVM->enmVMState), VERR_WRONG_ORDER);
850
851 uint32_t hGVM = pVM->hSelf;
852 AssertReturn(hGVM != NIL_GVM_HANDLE, VERR_INVALID_HANDLE);
853 AssertReturn(hGVM < RT_ELEMENTS(pGVMM->aHandles), VERR_INVALID_HANDLE);
854
855 PGVMHANDLE pHandle = &pGVMM->aHandles[hGVM];
856 AssertReturn(pHandle->pVM == pVM, VERR_NOT_OWNER);
857
858 RTPROCESS ProcId = RTProcSelf();
859 RTNATIVETHREAD hSelf = RTThreadNativeSelf();
860 AssertReturn( ( pHandle->hEMT0 == hSelf
861 && pHandle->ProcId == ProcId)
862 || pHandle->hEMT0 == NIL_RTNATIVETHREAD, VERR_NOT_OWNER);
863
864 /*
865 * Lookup the handle and destroy the object.
866 * Since the lock isn't recursive and we'll have to leave it before dereferencing the
867 * object, we take some precautions against racing callers just in case...
868 */
869 int rc = gvmmR0CreateDestroyLock(pGVMM);
870 AssertRC(rc);
871
872 /* be careful here because we might theoretically be racing someone else cleaning up. */
873 if ( pHandle->pVM == pVM
874 && ( ( pHandle->hEMT0 == hSelf
875 && pHandle->ProcId == ProcId)
876 || pHandle->hEMT0 == NIL_RTNATIVETHREAD)
877 && VALID_PTR(pHandle->pvObj)
878 && VALID_PTR(pHandle->pSession)
879 && VALID_PTR(pHandle->pGVM)
880 && pHandle->pGVM->u32Magic == GVM_MAGIC)
881 {
882 void *pvObj = pHandle->pvObj;
883 pHandle->pvObj = NULL;
884 gvmmR0CreateDestroyUnlock(pGVMM);
885
886 SUPR0ObjRelease(pvObj, pHandle->pSession);
887 }
888 else
889 {
890 SUPR0Printf("GVMMR0DestroyVM: pHandle=%p:{.pVM=%p, .hEMT0=%p, .ProcId=%u, .pvObj=%p} pVM=%p hSelf=%p\n",
891 pHandle, pHandle->pVM, pHandle->hEMT0, pHandle->ProcId, pHandle->pvObj, pVM, hSelf);
892 gvmmR0CreateDestroyUnlock(pGVMM);
893 rc = VERR_INTERNAL_ERROR;
894 }
895
896 return rc;
897}
898
899
900/**
901 * Performs VM cleanup task as part of object destruction.
902 *
903 * @param pGVM The GVM pointer.
904 */
905static void gvmmR0CleanupVM(PGVM pGVM)
906{
907 if ( pGVM->gvmm.s.fDoneVMMR0Init
908 && !pGVM->gvmm.s.fDoneVMMR0Term)
909 {
910 if ( pGVM->gvmm.s.VMMemObj != NIL_RTR0MEMOBJ
911 && RTR0MemObjAddress(pGVM->gvmm.s.VMMemObj) == pGVM->pVM)
912 {
913 LogFlow(("gvmmR0CleanupVM: Calling VMMR0TermVM\n"));
914 VMMR0TermVM(pGVM->pVM, pGVM);
915 }
916 else
917 AssertMsgFailed(("gvmmR0CleanupVM: VMMemObj=%p pVM=%p\n", pGVM->gvmm.s.VMMemObj, pGVM->pVM));
918 }
919
920 GMMR0CleanupVM(pGVM);
921}
922
923
924/**
925 * Handle destructor.
926 *
927 * @param pvGVMM The GVM instance pointer.
928 * @param pvHandle The handle pointer.
929 */
930static DECLCALLBACK(void) gvmmR0HandleObjDestructor(void *pvObj, void *pvGVMM, void *pvHandle)
931{
932 LogFlow(("gvmmR0HandleObjDestructor: %p %p %p\n", pvObj, pvGVMM, pvHandle));
933
934 /*
935 * Some quick, paranoid, input validation.
936 */
937 PGVMHANDLE pHandle = (PGVMHANDLE)pvHandle;
938 AssertPtr(pHandle);
939 PGVMM pGVMM = (PGVMM)pvGVMM;
940 Assert(pGVMM == g_pGVMM);
941 const uint16_t iHandle = pHandle - &pGVMM->aHandles[0];
942 if ( !iHandle
943 || iHandle >= RT_ELEMENTS(pGVMM->aHandles)
944 || iHandle != pHandle->iSelf)
945 {
946 SUPR0Printf("GVM: handle %d is out of range or corrupt (iSelf=%d)!\n", iHandle, pHandle->iSelf);
947 return;
948 }
949
950 int rc = gvmmR0CreateDestroyLock(pGVMM);
951 AssertRC(rc);
952 rc = gvmmR0UsedLock(pGVMM);
953 AssertRC(rc);
954
955 /*
956 * This is a tad slow but a doubly linked list is too much hazzle.
957 */
958 if (RT_UNLIKELY(pHandle->iNext >= RT_ELEMENTS(pGVMM->aHandles)))
959 {
960 SUPR0Printf("GVM: used list index %d is out of range!\n", pHandle->iNext);
961 gvmmR0UsedUnlock(pGVMM);
962 gvmmR0CreateDestroyUnlock(pGVMM);
963 return;
964 }
965
966 if (pGVMM->iUsedHead == iHandle)
967 pGVMM->iUsedHead = pHandle->iNext;
968 else
969 {
970 uint16_t iPrev = pGVMM->iUsedHead;
971 int c = RT_ELEMENTS(pGVMM->aHandles) + 2;
972 while (iPrev)
973 {
974 if (RT_UNLIKELY(iPrev >= RT_ELEMENTS(pGVMM->aHandles)))
975 {
976 SUPR0Printf("GVM: used list index %d is out of range!\n", iPrev);
977 gvmmR0UsedUnlock(pGVMM);
978 gvmmR0CreateDestroyUnlock(pGVMM);
979 return;
980 }
981 if (RT_UNLIKELY(c-- <= 0))
982 {
983 iPrev = 0;
984 break;
985 }
986
987 if (pGVMM->aHandles[iPrev].iNext == iHandle)
988 break;
989 iPrev = pGVMM->aHandles[iPrev].iNext;
990 }
991 if (!iPrev)
992 {
993 SUPR0Printf("GVM: can't find the handle previous previous of %d!\n", pHandle->iSelf);
994 gvmmR0UsedUnlock(pGVMM);
995 gvmmR0CreateDestroyUnlock(pGVMM);
996 return;
997 }
998
999 Assert(pGVMM->aHandles[iPrev].iNext == iHandle);
1000 pGVMM->aHandles[iPrev].iNext = pHandle->iNext;
1001 }
1002 pHandle->iNext = 0;
1003 pGVMM->cVMs--;
1004
1005 /*
1006 * Do the global cleanup round.
1007 */
1008 PGVM pGVM = pHandle->pGVM;
1009 if ( VALID_PTR(pGVM)
1010 && pGVM->u32Magic == GVM_MAGIC)
1011 {
1012 pGVMM->cEMTs -= pGVM->cCpus;
1013 gvmmR0UsedUnlock(pGVMM);
1014
1015 gvmmR0CleanupVM(pGVM);
1016
1017 /*
1018 * Do the GVMM cleanup - must be done last.
1019 */
1020 /* The VM and VM pages mappings/allocations. */
1021 if (pGVM->gvmm.s.VMPagesMapObj != NIL_RTR0MEMOBJ)
1022 {
1023 rc = RTR0MemObjFree(pGVM->gvmm.s.VMPagesMapObj, false /* fFreeMappings */); AssertRC(rc);
1024 pGVM->gvmm.s.VMPagesMapObj = NIL_RTR0MEMOBJ;
1025 }
1026
1027 if (pGVM->gvmm.s.VMMapObj != NIL_RTR0MEMOBJ)
1028 {
1029 rc = RTR0MemObjFree(pGVM->gvmm.s.VMMapObj, false /* fFreeMappings */); AssertRC(rc);
1030 pGVM->gvmm.s.VMMapObj = NIL_RTR0MEMOBJ;
1031 }
1032
1033 if (pGVM->gvmm.s.VMPagesMemObj != NIL_RTR0MEMOBJ)
1034 {
1035 rc = RTR0MemObjFree(pGVM->gvmm.s.VMPagesMemObj, false /* fFreeMappings */); AssertRC(rc);
1036 pGVM->gvmm.s.VMPagesMemObj = NIL_RTR0MEMOBJ;
1037 }
1038
1039 if (pGVM->gvmm.s.VMMemObj != NIL_RTR0MEMOBJ)
1040 {
1041 rc = RTR0MemObjFree(pGVM->gvmm.s.VMMemObj, false /* fFreeMappings */); AssertRC(rc);
1042 pGVM->gvmm.s.VMMemObj = NIL_RTR0MEMOBJ;
1043 }
1044
1045 for (VMCPUID i = 0; i < pGVM->cCpus; i++)
1046 {
1047 if (pGVM->aCpus[i].gvmm.s.HaltEventMulti != NIL_RTSEMEVENTMULTI)
1048 {
1049 rc = RTSemEventMultiDestroy(pGVM->aCpus[i].gvmm.s.HaltEventMulti); AssertRC(rc);
1050 pGVM->aCpus[i].gvmm.s.HaltEventMulti = NIL_RTSEMEVENTMULTI;
1051 }
1052 }
1053
1054 /* the GVM structure itself. */
1055 pGVM->u32Magic |= UINT32_C(0x80000000);
1056 RTMemFree(pGVM);
1057
1058 /* Re-acquire the UsedLock before freeing the handle since we're updating handle fields. */
1059 rc = gvmmR0UsedLock(pGVMM);
1060 AssertRC(rc);
1061 }
1062 /* else: GVMMR0CreateVM cleanup. */
1063
1064 /*
1065 * Free the handle.
1066 */
1067 pHandle->iNext = pGVMM->iFreeHead;
1068 pGVMM->iFreeHead = iHandle;
1069 ASMAtomicXchgPtr((void * volatile *)&pHandle->pGVM, NULL);
1070 ASMAtomicXchgPtr((void * volatile *)&pHandle->pVM, NULL);
1071 ASMAtomicXchgPtr((void * volatile *)&pHandle->pvObj, NULL);
1072 ASMAtomicXchgPtr((void * volatile *)&pHandle->pSession, NULL);
1073 ASMAtomicXchgSize(&pHandle->hEMT0, NIL_RTNATIVETHREAD);
1074 ASMAtomicXchgSize(&pHandle->ProcId, NIL_RTPROCESS);
1075
1076 gvmmR0UsedUnlock(pGVMM);
1077 gvmmR0CreateDestroyUnlock(pGVMM);
1078 LogFlow(("gvmmR0HandleObjDestructor: returns\n"));
1079}
1080
1081
1082/**
1083 * Registers the calling thread as the EMT of a Virtual CPU.
1084 *
1085 * Note that VCPU 0 is automatically registered during VM creation.
1086 *
1087 * @returns VBox status code
1088 * @param pVM The shared VM structure (the ring-0 mapping).
1089 * @param idCpu VCPU id.
1090 */
1091GVMMR0DECL(int) GVMMR0RegisterVCpu(PVM pVM, VMCPUID idCpu)
1092{
1093 AssertReturn(idCpu != 0, VERR_NOT_OWNER);
1094
1095 /*
1096 * Validate the VM structure, state and handle.
1097 */
1098 PGVM pGVM;
1099 PGVMM pGVMM;
1100 int rc = gvmmR0ByVM(pVM, &pGVM, &pGVMM, false /* fTakeUsedLock */);
1101 if (RT_FAILURE(rc))
1102 return rc;
1103
1104 AssertReturn(idCpu < pVM->cCpus, VERR_INVALID_CPU_ID);
1105 AssertReturn(pGVM->aCpus[idCpu].hEMT == NIL_RTNATIVETHREAD, VERR_ACCESS_DENIED);
1106
1107 pGVM->aCpus[idCpu].hEMT = RTThreadNativeSelf();
1108 return VINF_SUCCESS;
1109}
1110
1111
1112/**
1113 * Lookup a GVM structure by its handle.
1114 *
1115 * @returns The GVM pointer on success, NULL on failure.
1116 * @param hGVM The global VM handle. Asserts on bad handle.
1117 */
1118GVMMR0DECL(PGVM) GVMMR0ByHandle(uint32_t hGVM)
1119{
1120 PGVMM pGVMM;
1121 GVMM_GET_VALID_INSTANCE(pGVMM, NULL);
1122
1123 /*
1124 * Validate.
1125 */
1126 AssertReturn(hGVM != NIL_GVM_HANDLE, NULL);
1127 AssertReturn(hGVM < RT_ELEMENTS(pGVMM->aHandles), NULL);
1128
1129 /*
1130 * Look it up.
1131 */
1132 PGVMHANDLE pHandle = &pGVMM->aHandles[hGVM];
1133 AssertPtrReturn(pHandle->pVM, NULL);
1134 AssertPtrReturn(pHandle->pvObj, NULL);
1135 PGVM pGVM = pHandle->pGVM;
1136 AssertPtrReturn(pGVM, NULL);
1137 AssertReturn(pGVM->pVM == pHandle->pVM, NULL);
1138
1139 return pHandle->pGVM;
1140}
1141
1142
1143/**
1144 * Lookup a GVM structure by the shared VM structure.
1145 *
1146 * The calling thread must be in the same process as the VM. All current lookups
1147 * are by threads inside the same process, so this will not be an issue.
1148 *
1149 * @returns VBox status code.
1150 * @param pVM The shared VM structure (the ring-0 mapping).
1151 * @param ppGVM Where to store the GVM pointer.
1152 * @param ppGVMM Where to store the pointer to the GVMM instance data.
1153 * @param fTakeUsedLock Whether to take the used lock or not.
1154 * Be very careful if not taking the lock as it's possible that
1155 * the VM will disappear then.
1156 *
1157 * @remark This will not assert on an invalid pVM but try return sliently.
1158 */
1159static int gvmmR0ByVM(PVM pVM, PGVM *ppGVM, PGVMM *ppGVMM, bool fTakeUsedLock)
1160{
1161 RTPROCESS ProcId = RTProcSelf();
1162 PGVMM pGVMM;
1163 GVMM_GET_VALID_INSTANCE(pGVMM, VERR_INTERNAL_ERROR);
1164
1165 /*
1166 * Validate.
1167 */
1168 if (RT_UNLIKELY( !VALID_PTR(pVM)
1169 || ((uintptr_t)pVM & PAGE_OFFSET_MASK)))
1170 return VERR_INVALID_POINTER;
1171 if (RT_UNLIKELY( pVM->enmVMState < VMSTATE_CREATING
1172 || pVM->enmVMState >= VMSTATE_TERMINATED))
1173 return VERR_INVALID_POINTER;
1174
1175 uint16_t hGVM = pVM->hSelf;
1176 if (RT_UNLIKELY( hGVM == NIL_GVM_HANDLE
1177 || hGVM >= RT_ELEMENTS(pGVMM->aHandles)))
1178 return VERR_INVALID_HANDLE;
1179
1180 /*
1181 * Look it up.
1182 */
1183 PGVMHANDLE pHandle = &pGVMM->aHandles[hGVM];
1184 PGVM pGVM;
1185 if (fTakeUsedLock)
1186 {
1187 int rc = gvmmR0UsedLock(pGVMM);
1188 AssertRCReturn(rc, rc);
1189
1190 pGVM = pHandle->pGVM;
1191 if (RT_UNLIKELY( pHandle->pVM != pVM
1192 || pHandle->ProcId != ProcId
1193 || !VALID_PTR(pHandle->pvObj)
1194 || !VALID_PTR(pGVM)
1195 || pGVM->pVM != pVM))
1196 {
1197 gvmmR0UsedUnlock(pGVMM);
1198 return VERR_INVALID_HANDLE;
1199 }
1200 }
1201 else
1202 {
1203 if (RT_UNLIKELY(pHandle->pVM != pVM))
1204 return VERR_INVALID_HANDLE;
1205 if (RT_UNLIKELY(pHandle->ProcId != ProcId))
1206 return VERR_INVALID_HANDLE;
1207 if (RT_UNLIKELY(!VALID_PTR(pHandle->pvObj)))
1208 return VERR_INVALID_HANDLE;
1209
1210 pGVM = pHandle->pGVM;
1211 if (RT_UNLIKELY(!VALID_PTR(pGVM)))
1212 return VERR_INVALID_HANDLE;
1213 if (RT_UNLIKELY(pGVM->pVM != pVM))
1214 return VERR_INVALID_HANDLE;
1215 }
1216
1217 *ppGVM = pGVM;
1218 *ppGVMM = pGVMM;
1219 return VINF_SUCCESS;
1220}
1221
1222
1223/**
1224 * Lookup a GVM structure by the shared VM structure.
1225 *
1226 * @returns The GVM pointer on success, NULL on failure.
1227 * @param pVM The shared VM structure (the ring-0 mapping).
1228 *
1229 * @remark This will not take the 'used'-lock because it doesn't do
1230 * nesting and this function will be used from under the lock.
1231 */
1232GVMMR0DECL(PGVM) GVMMR0ByVM(PVM pVM)
1233{
1234 PGVM pGVM;
1235 PGVMM pGVMM;
1236 int rc = gvmmR0ByVM(pVM, &pGVM, &pGVMM, false /* fTakeUsedLock */);
1237 if (RT_SUCCESS(rc))
1238 return pGVM;
1239 AssertRC(rc);
1240 return NULL;
1241}
1242
1243
1244/**
1245 * Lookup a GVM structure by the shared VM structure and ensuring that the
1246 * caller is an EMT thread.
1247 *
1248 * @returns VBox status code.
1249 * @param pVM The shared VM structure (the ring-0 mapping).
1250 * @param idCpu The Virtual CPU ID of the calling EMT.
1251 * @param ppGVM Where to store the GVM pointer.
1252 * @param ppGVMM Where to store the pointer to the GVMM instance data.
1253 * @thread EMT
1254 *
1255 * @remark This will assert in all failure paths.
1256 */
1257static int gvmmR0ByVMAndEMT(PVM pVM, VMCPUID idCpu, PGVM *ppGVM, PGVMM *ppGVMM)
1258{
1259 PGVMM pGVMM;
1260 GVMM_GET_VALID_INSTANCE(pGVMM, VERR_INTERNAL_ERROR);
1261
1262 /*
1263 * Validate.
1264 */
1265 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
1266 AssertReturn(!((uintptr_t)pVM & PAGE_OFFSET_MASK), VERR_INVALID_POINTER);
1267
1268 uint16_t hGVM = pVM->hSelf;
1269 AssertReturn(hGVM != NIL_GVM_HANDLE, VERR_INVALID_HANDLE);
1270 AssertReturn(hGVM < RT_ELEMENTS(pGVMM->aHandles), VERR_INVALID_HANDLE);
1271
1272 /*
1273 * Look it up.
1274 */
1275 PGVMHANDLE pHandle = &pGVMM->aHandles[hGVM];
1276 AssertReturn(pHandle->pVM == pVM, VERR_NOT_OWNER);
1277 RTPROCESS ProcId = RTProcSelf();
1278 AssertReturn(pHandle->ProcId == ProcId, VERR_NOT_OWNER);
1279 AssertPtrReturn(pHandle->pvObj, VERR_INTERNAL_ERROR);
1280
1281 PGVM pGVM = pHandle->pGVM;
1282 AssertPtrReturn(pGVM, VERR_INTERNAL_ERROR);
1283 AssertReturn(pGVM->pVM == pVM, VERR_INTERNAL_ERROR);
1284 RTNATIVETHREAD hAllegedEMT = RTThreadNativeSelf();
1285 AssertReturn(idCpu < pGVM->cCpus, VERR_INVALID_CPU_ID);
1286 AssertReturn(pGVM->aCpus[idCpu].hEMT == hAllegedEMT, VERR_INTERNAL_ERROR);
1287
1288 *ppGVM = pGVM;
1289 *ppGVMM = pGVMM;
1290 return VINF_SUCCESS;
1291}
1292
1293
1294/**
1295 * Lookup a GVM structure by the shared VM structure
1296 * and ensuring that the caller is the EMT thread.
1297 *
1298 * @returns VBox status code.
1299 * @param pVM The shared VM structure (the ring-0 mapping).
1300 * @param idCpu The Virtual CPU ID of the calling EMT.
1301 * @param ppGVM Where to store the GVM pointer.
1302 * @thread EMT
1303 */
1304GVMMR0DECL(int) GVMMR0ByVMAndEMT(PVM pVM, VMCPUID idCpu, PGVM *ppGVM)
1305{
1306 AssertPtrReturn(ppGVM, VERR_INVALID_POINTER);
1307 PGVMM pGVMM;
1308 return gvmmR0ByVMAndEMT(pVM, idCpu, ppGVM, &pGVMM);
1309}
1310
1311
1312/**
1313 * Lookup a VM by its global handle.
1314 *
1315 * @returns The VM handle on success, NULL on failure.
1316 * @param hGVM The global VM handle. Asserts on bad handle.
1317 */
1318GVMMR0DECL(PVM) GVMMR0GetVMByHandle(uint32_t hGVM)
1319{
1320 PGVM pGVM = GVMMR0ByHandle(hGVM);
1321 return pGVM ? pGVM->pVM : NULL;
1322}
1323
1324
1325/**
1326 * Looks up the VM belonging to the specified EMT thread.
1327 *
1328 * This is used by the assertion machinery in VMMR0.cpp to avoid causing
1329 * unnecessary kernel panics when the EMT thread hits an assertion. The
1330 * call may or not be an EMT thread.
1331 *
1332 * @returns The VM handle on success, NULL on failure.
1333 * @param hEMT The native thread handle of the EMT.
1334 * NIL_RTNATIVETHREAD means the current thread
1335 */
1336GVMMR0DECL(PVM) GVMMR0GetVMByEMT(RTNATIVETHREAD hEMT)
1337{
1338 /*
1339 * No Assertions here as we're usually called in a AssertMsgN or
1340 * RTAssert* context.
1341 */
1342 PGVMM pGVMM = g_pGVMM;
1343 if ( !VALID_PTR(pGVMM)
1344 || pGVMM->u32Magic != GVMM_MAGIC)
1345 return NULL;
1346
1347 if (hEMT == NIL_RTNATIVETHREAD)
1348 hEMT = RTThreadNativeSelf();
1349 RTPROCESS ProcId = RTProcSelf();
1350
1351 /*
1352 * Search the handles in a linear fashion as we don't dare to take the lock (assert).
1353 */
1354 for (unsigned i = 1; i < RT_ELEMENTS(pGVMM->aHandles); i++)
1355 {
1356 if ( pGVMM->aHandles[i].iSelf == i
1357 && pGVMM->aHandles[i].ProcId == ProcId
1358 && VALID_PTR(pGVMM->aHandles[i].pvObj)
1359 && VALID_PTR(pGVMM->aHandles[i].pVM)
1360 && VALID_PTR(pGVMM->aHandles[i].pGVM))
1361 {
1362 if (pGVMM->aHandles[i].hEMT0 == hEMT)
1363 return pGVMM->aHandles[i].pVM;
1364
1365 /* This is fearly safe with the current process per VM approach. */
1366 PGVM pGVM = pGVMM->aHandles[i].pGVM;
1367 VMCPUID const cCpus = pGVM->cCpus;
1368 if ( cCpus < 1
1369 || cCpus > VMM_MAX_CPU_COUNT)
1370 continue;
1371 for (VMCPUID idCpu = 1; idCpu < cCpus; idCpu++)
1372 if (pGVM->aCpus[idCpu].hEMT == hEMT)
1373 return pGVMM->aHandles[i].pVM;
1374 }
1375 }
1376 return NULL;
1377}
1378
1379
1380/**
1381 * This is will wake up expired and soon-to-be expired VMs.
1382 *
1383 * @returns Number of VMs that has been woken up.
1384 * @param pGVMM Pointer to the GVMM instance data.
1385 * @param u64Now The current time.
1386 */
1387static unsigned gvmmR0SchedDoWakeUps(PGVMM pGVMM, uint64_t u64Now)
1388{
1389/** @todo Rewrite this algorithm. See performance defect XYZ. */
1390
1391 /*
1392 * The first pass will wake up VMs which have actually expired
1393 * and look for VMs that should be woken up in the 2nd and 3rd passes.
1394 */
1395 unsigned cWoken = 0;
1396 unsigned cHalted = 0;
1397 unsigned cTodo2nd = 0;
1398 unsigned cTodo3rd = 0;
1399 for (unsigned i = pGVMM->iUsedHead, cGuard = 0;
1400 i != NIL_GVM_HANDLE && i < RT_ELEMENTS(pGVMM->aHandles);
1401 i = pGVMM->aHandles[i].iNext)
1402 {
1403 PGVM pCurGVM = pGVMM->aHandles[i].pGVM;
1404 if ( VALID_PTR(pCurGVM)
1405 && pCurGVM->u32Magic == GVM_MAGIC)
1406 {
1407 for (VMCPUID idCpu = 0; idCpu < pCurGVM->cCpus; idCpu++)
1408 {
1409 PGVMCPU pCurGVCpu = &pCurGVM->aCpus[idCpu];
1410
1411 uint64_t u64 = pCurGVCpu->gvmm.s.u64HaltExpire;
1412 if (u64)
1413 {
1414 if (u64 <= u64Now)
1415 {
1416 if (ASMAtomicXchgU64(&pCurGVCpu->gvmm.s.u64HaltExpire, 0))
1417 {
1418 int rc = RTSemEventMultiSignal(pCurGVCpu->gvmm.s.HaltEventMulti);
1419 AssertRC(rc);
1420 cWoken++;
1421 }
1422 }
1423 else
1424 {
1425 cHalted++;
1426 if (u64 <= u64Now + pGVMM->nsEarlyWakeUp1)
1427 cTodo2nd++;
1428 else if (u64 <= u64Now + pGVMM->nsEarlyWakeUp2)
1429 cTodo3rd++;
1430 }
1431 }
1432 }
1433 }
1434 AssertLogRelBreak(cGuard++ < RT_ELEMENTS(pGVMM->aHandles));
1435 }
1436
1437 if (cTodo2nd)
1438 {
1439 for (unsigned i = pGVMM->iUsedHead, cGuard = 0;
1440 i != NIL_GVM_HANDLE && i < RT_ELEMENTS(pGVMM->aHandles);
1441 i = pGVMM->aHandles[i].iNext)
1442 {
1443 PGVM pCurGVM = pGVMM->aHandles[i].pGVM;
1444 if ( VALID_PTR(pCurGVM)
1445 && pCurGVM->u32Magic == GVM_MAGIC)
1446 {
1447 for (VMCPUID idCpu = 0; idCpu < pCurGVM->cCpus; idCpu++)
1448 {
1449 PGVMCPU pCurGVCpu = &pCurGVM->aCpus[idCpu];
1450
1451 if ( pCurGVCpu->gvmm.s.u64HaltExpire
1452 && pCurGVCpu->gvmm.s.u64HaltExpire <= u64Now + pGVMM->nsEarlyWakeUp1)
1453 {
1454 if (ASMAtomicXchgU64(&pCurGVCpu->gvmm.s.u64HaltExpire, 0))
1455 {
1456 int rc = RTSemEventMultiSignal(pCurGVCpu->gvmm.s.HaltEventMulti);
1457 AssertRC(rc);
1458 cWoken++;
1459 }
1460 }
1461 }
1462 }
1463 AssertLogRelBreak(cGuard++ < RT_ELEMENTS(pGVMM->aHandles));
1464 }
1465 }
1466
1467 if (cTodo3rd)
1468 {
1469 for (unsigned i = pGVMM->iUsedHead, cGuard = 0;
1470 i != NIL_GVM_HANDLE && i < RT_ELEMENTS(pGVMM->aHandles);
1471 i = pGVMM->aHandles[i].iNext)
1472 {
1473 PGVM pCurGVM = pGVMM->aHandles[i].pGVM;
1474 if ( VALID_PTR(pCurGVM)
1475 && pCurGVM->u32Magic == GVM_MAGIC)
1476 {
1477 for (VMCPUID idCpu = 0; idCpu < pCurGVM->cCpus; idCpu++)
1478 {
1479 PGVMCPU pCurGVCpu = &pCurGVM->aCpus[idCpu];
1480
1481 if ( pCurGVCpu->gvmm.s.u64HaltExpire
1482 && pCurGVCpu->gvmm.s.u64HaltExpire <= u64Now + pGVMM->nsEarlyWakeUp2)
1483 {
1484 if (ASMAtomicXchgU64(&pCurGVCpu->gvmm.s.u64HaltExpire, 0))
1485 {
1486 int rc = RTSemEventMultiSignal(pCurGVCpu->gvmm.s.HaltEventMulti);
1487 AssertRC(rc);
1488 cWoken++;
1489 }
1490 }
1491 }
1492 }
1493 AssertLogRelBreak(cGuard++ < RT_ELEMENTS(pGVMM->aHandles));
1494 }
1495 }
1496
1497 return cWoken;
1498}
1499
1500
1501/**
1502 * Halt the EMT thread.
1503 *
1504 * @returns VINF_SUCCESS normal wakeup (timeout or kicked by other thread).
1505 * VERR_INTERRUPTED if a signal was scheduled for the thread.
1506 * @param pVM Pointer to the shared VM structure.
1507 * @param idCpu The Virtual CPU ID of the calling EMT.
1508 * @param u64ExpireGipTime The time for the sleep to expire expressed as GIP time.
1509 * @thread EMT(idCpu).
1510 */
1511GVMMR0DECL(int) GVMMR0SchedHalt(PVM pVM, VMCPUID idCpu, uint64_t u64ExpireGipTime)
1512{
1513 LogFlow(("GVMMR0SchedHalt: pVM=%p\n", pVM));
1514
1515 /*
1516 * Validate the VM structure, state and handle.
1517 */
1518 PGVM pGVM;
1519 PGVMM pGVMM;
1520 int rc = gvmmR0ByVMAndEMT(pVM, idCpu, &pGVM, &pGVMM);
1521 if (RT_FAILURE(rc))
1522 return rc;
1523 pGVM->gvmm.s.StatsSched.cHaltCalls++;
1524
1525 PGVMCPU pCurGVCpu = &pGVM->aCpus[idCpu];
1526 Assert(!pCurGVCpu->gvmm.s.u64HaltExpire);
1527
1528 /*
1529 * Take the UsedList semaphore, get the current time
1530 * and check if anyone needs waking up.
1531 * Interrupts must NOT be disabled at this point because we ask for GIP time!
1532 */
1533 rc = gvmmR0UsedLock(pGVMM);
1534 AssertRC(rc);
1535
1536 pCurGVCpu->gvmm.s.iCpuEmt = ASMGetApicId();
1537
1538 Assert(ASMGetFlags() & X86_EFL_IF);
1539 const uint64_t u64Now = RTTimeNanoTS(); /* (GIP time) */
1540 pGVM->gvmm.s.StatsSched.cHaltWakeUps += gvmmR0SchedDoWakeUps(pGVMM, u64Now);
1541
1542 /*
1543 * Go to sleep if we must...
1544 */
1545 if ( u64Now < u64ExpireGipTime
1546 && u64ExpireGipTime - u64Now > (pGVMM->cEMTs > pGVMM->cEMTsMeansCompany
1547 ? pGVMM->nsMinSleepCompany
1548 : pGVMM->nsMinSleepAlone))
1549 {
1550 pGVM->gvmm.s.StatsSched.cHaltBlocking++;
1551 ASMAtomicXchgU64(&pCurGVCpu->gvmm.s.u64HaltExpire, u64ExpireGipTime);
1552 gvmmR0UsedUnlock(pGVMM);
1553
1554 uint32_t cMillies = (u64ExpireGipTime - u64Now) / 1000000;
1555 rc = RTSemEventMultiWaitNoResume(pCurGVCpu->gvmm.s.HaltEventMulti, cMillies ? cMillies : 1);
1556 ASMAtomicXchgU64(&pCurGVCpu->gvmm.s.u64HaltExpire, 0);
1557 if (rc == VERR_TIMEOUT)
1558 {
1559 pGVM->gvmm.s.StatsSched.cHaltTimeouts++;
1560 rc = VINF_SUCCESS;
1561 }
1562 }
1563 else
1564 {
1565 pGVM->gvmm.s.StatsSched.cHaltNotBlocking++;
1566 gvmmR0UsedUnlock(pGVMM);
1567 }
1568
1569 /* Make sure false wake up calls (gvmmR0SchedDoWakeUps) cause us to spin. */
1570 RTSemEventMultiReset(pCurGVCpu->gvmm.s.HaltEventMulti);
1571
1572 return rc;
1573}
1574
1575
1576/**
1577 * Worker for GVMMR0SchedWakeUp and GVMMR0SchedWakeUpAndPokeCpus that wakes up
1578 * the a sleeping EMT.
1579 *
1580 * @retval VINF_SUCCESS if successfully woken up.
1581 * @retval VINF_GVM_NOT_BLOCKED if the EMT wasn't blocked.
1582 *
1583 * @param pGVM The global (ring-0) VM structure.
1584 * @param pGVCpu The global (ring-0) VCPU structure.
1585 */
1586DECLINLINE(int) gvmmR0SchedWakeUpOne(PGVM pGVM, PGVMCPU pGVCpu)
1587{
1588 pGVM->gvmm.s.StatsSched.cWakeUpCalls++;
1589
1590 /*
1591 * Signal the semaphore regardless of whether it's current blocked on it.
1592 *
1593 * The reason for this is that there is absolutely no way we can be 100%
1594 * certain that it isn't *about* go to go to sleep on it and just got
1595 * delayed a bit en route. So, we will always signal the semaphore when
1596 * the it is flagged as halted in the VMM.
1597 */
1598/** @todo we can optimize some of that by means of the pVCpu->enmState now. */
1599 int rc;
1600 if (pGVCpu->gvmm.s.u64HaltExpire)
1601 {
1602 rc = VINF_SUCCESS;
1603 ASMAtomicXchgU64(&pGVCpu->gvmm.s.u64HaltExpire, 0);
1604 }
1605 else
1606 {
1607 rc = VINF_GVM_NOT_BLOCKED;
1608 pGVM->gvmm.s.StatsSched.cWakeUpNotHalted++;
1609 }
1610
1611 int rc2 = RTSemEventMultiSignal(pGVCpu->gvmm.s.HaltEventMulti);
1612 AssertRC(rc2);
1613
1614 return rc;
1615}
1616
1617
1618/**
1619 * Wakes up the halted EMT thread so it can service a pending request.
1620 *
1621 * @returns VBox status code.
1622 * @retval VINF_SUCCESS if successfully woken up.
1623 * @retval VINF_GVM_NOT_BLOCKED if the EMT wasn't blocked.
1624 *
1625 * @param pVM Pointer to the shared VM structure.
1626 * @param idCpu The Virtual CPU ID of the EMT to wake up.
1627 * @param fTakeUsedLock Take the used lock or not
1628 * @thread Any but EMT.
1629 */
1630GVMMR0DECL(int) GVMMR0SchedWakeUpEx(PVM pVM, VMCPUID idCpu, bool fTakeUsedLock)
1631{
1632 /*
1633 * Validate input and take the UsedLock.
1634 */
1635 PGVM pGVM;
1636 PGVMM pGVMM;
1637 int rc = gvmmR0ByVM(pVM, &pGVM, &pGVMM, fTakeUsedLock);
1638 if (RT_SUCCESS(rc))
1639 {
1640 if (idCpu < pGVM->cCpus)
1641 {
1642 /*
1643 * Do the actual job.
1644 */
1645 rc = gvmmR0SchedWakeUpOne(pGVM, &pGVM->aCpus[idCpu]);
1646
1647 if (fTakeUsedLock)
1648 {
1649 /*
1650 * While we're here, do a round of scheduling.
1651 */
1652 Assert(ASMGetFlags() & X86_EFL_IF);
1653 const uint64_t u64Now = RTTimeNanoTS(); /* (GIP time) */
1654 pGVM->gvmm.s.StatsSched.cWakeUpWakeUps += gvmmR0SchedDoWakeUps(pGVMM, u64Now);
1655 }
1656 }
1657 else
1658 rc = VERR_INVALID_CPU_ID;
1659
1660 if (fTakeUsedLock)
1661 {
1662 int rc2 = gvmmR0UsedUnlock(pGVMM);
1663 AssertRC(rc2);
1664 }
1665 }
1666
1667 LogFlow(("GVMMR0SchedWakeUp: returns %Rrc\n", rc));
1668 return rc;
1669}
1670
1671
1672/**
1673 * Wakes up the halted EMT thread so it can service a pending request.
1674 *
1675 * @returns VBox status code.
1676 * @retval VINF_SUCCESS if successfully woken up.
1677 * @retval VINF_GVM_NOT_BLOCKED if the EMT wasn't blocked.
1678 *
1679 * @param pVM Pointer to the shared VM structure.
1680 * @param idCpu The Virtual CPU ID of the EMT to wake up.
1681 * @thread Any but EMT.
1682 */
1683GVMMR0DECL(int) GVMMR0SchedWakeUp(PVM pVM, VMCPUID idCpu)
1684{
1685 return GVMMR0SchedWakeUpEx(pVM, idCpu, true /* fTakeUsedLock */);
1686}
1687
1688/**
1689 * Worker common to GVMMR0SchedPoke and GVMMR0SchedWakeUpAndPokeCpus that pokes
1690 * the Virtual CPU if it's still busy executing guest code.
1691 *
1692 * @returns VBox status code.
1693 * @retval VINF_SUCCESS if poked successfully.
1694 * @retval VINF_GVM_NOT_BUSY_IN_GC if the EMT wasn't busy in GC.
1695 *
1696 * @param pGVM The global (ring-0) VM structure.
1697 * @param pVCpu The Virtual CPU handle.
1698 */
1699DECLINLINE(int) gvmmR0SchedPokeOne(PGVM pGVM, PVMCPU pVCpu)
1700{
1701 pGVM->gvmm.s.StatsSched.cPokeCalls++;
1702
1703 RTCPUID idHostCpu = pVCpu->idHostCpu;
1704 if ( idHostCpu == NIL_RTCPUID
1705 || VMCPU_GET_STATE(pVCpu) != VMCPUSTATE_STARTED_EXEC)
1706 {
1707 pGVM->gvmm.s.StatsSched.cPokeNotBusy++;
1708 return VINF_GVM_NOT_BUSY_IN_GC;
1709 }
1710
1711 /* Note: this function is not implemented on Darwin and Linux (kernel < 2.6.19) */
1712 RTMpPokeCpu(idHostCpu);
1713 return VINF_SUCCESS;
1714}
1715
1716/**
1717 * Pokes an EMT if it's still busy running guest code.
1718 *
1719 * @returns VBox status code.
1720 * @retval VINF_SUCCESS if poked successfully.
1721 * @retval VINF_GVM_NOT_BUSY_IN_GC if the EMT wasn't busy in GC.
1722 *
1723 * @param pVM Pointer to the shared VM structure.
1724 * @param idCpu The ID of the virtual CPU to poke.
1725 * @param fTakeUsedLock Take the used lock or not
1726 */
1727GVMMR0DECL(int) GVMMR0SchedPokeEx(PVM pVM, VMCPUID idCpu, bool fTakeUsedLock)
1728{
1729 /*
1730 * Validate input and take the UsedLock.
1731 */
1732 PGVM pGVM;
1733 PGVMM pGVMM;
1734 int rc = gvmmR0ByVM(pVM, &pGVM, &pGVMM, fTakeUsedLock);
1735 if (RT_SUCCESS(rc))
1736 {
1737 if (idCpu < pGVM->cCpus)
1738 rc = gvmmR0SchedPokeOne(pGVM, &pVM->aCpus[idCpu]);
1739 else
1740 rc = VERR_INVALID_CPU_ID;
1741
1742 if (fTakeUsedLock)
1743 {
1744 int rc2 = gvmmR0UsedUnlock(pGVMM);
1745 AssertRC(rc2);
1746 }
1747 }
1748
1749 LogFlow(("GVMMR0SchedWakeUpAndPokeCpus: returns %Rrc\n", rc));
1750 return rc;
1751}
1752
1753
1754/**
1755 * Pokes an EMT if it's still busy running guest code.
1756 *
1757 * @returns VBox status code.
1758 * @retval VINF_SUCCESS if poked successfully.
1759 * @retval VINF_GVM_NOT_BUSY_IN_GC if the EMT wasn't busy in GC.
1760 *
1761 * @param pVM Pointer to the shared VM structure.
1762 * @param idCpu The ID of the virtual CPU to poke.
1763 */
1764GVMMR0DECL(int) GVMMR0SchedPoke(PVM pVM, VMCPUID idCpu)
1765{
1766 return GVMMR0SchedPokeEx(pVM, idCpu, true /* fTakeUsedLock */);
1767}
1768
1769
1770/**
1771 * Wakes up a set of halted EMT threads so they can service pending request.
1772 *
1773 * @returns VBox status code, no informational stuff.
1774 *
1775 * @param pVM Pointer to the shared VM structure.
1776 * @param pSleepSet The set of sleepers to wake up.
1777 * @param pPokeSet The set of CPUs to poke.
1778 */
1779GVMMR0DECL(int) GVMMR0SchedWakeUpAndPokeCpus(PVM pVM, PCVMCPUSET pSleepSet, PCVMCPUSET pPokeSet)
1780{
1781 AssertPtrReturn(pSleepSet, VERR_INVALID_POINTER);
1782 AssertPtrReturn(pPokeSet, VERR_INVALID_POINTER);
1783 RTNATIVETHREAD hSelf = RTThreadNativeSelf();
1784
1785 /*
1786 * Validate input and take the UsedLock.
1787 */
1788 PGVM pGVM;
1789 PGVMM pGVMM;
1790 int rc = gvmmR0ByVM(pVM, &pGVM, &pGVMM, true /* fTakeUsedLock */);
1791 if (RT_SUCCESS(rc))
1792 {
1793 rc = VINF_SUCCESS;
1794 VMCPUID idCpu = pGVM->cCpus;
1795 while (idCpu-- > 0)
1796 {
1797 /* Don't try poke or wake up ourselves. */
1798 if (pGVM->aCpus[idCpu].hEMT == hSelf)
1799 continue;
1800
1801 /* just ignore errors for now. */
1802 if (VMCPUSET_IS_PRESENT(pSleepSet, idCpu))
1803 gvmmR0SchedWakeUpOne(pGVM, &pGVM->aCpus[idCpu]);
1804 else if (VMCPUSET_IS_PRESENT(pPokeSet, idCpu))
1805 gvmmR0SchedPokeOne(pGVM, &pVM->aCpus[idCpu]);
1806 }
1807
1808 int rc2 = gvmmR0UsedUnlock(pGVMM);
1809 AssertRC(rc2);
1810 }
1811
1812 LogFlow(("GVMMR0SchedWakeUpAndPokeCpus: returns %Rrc\n", rc));
1813 return rc;
1814}
1815
1816
1817/**
1818 * VMMR0 request wrapper for GVMMR0SchedWakeUpAndPokeCpus.
1819 *
1820 * @returns see GVMMR0SchedWakeUpAndPokeCpus.
1821 * @param pVM Pointer to the shared VM structure.
1822 * @param pReq The request packet.
1823 */
1824GVMMR0DECL(int) GVMMR0SchedWakeUpAndPokeCpusReq(PVM pVM, PGVMMSCHEDWAKEUPANDPOKECPUSREQ pReq)
1825{
1826 /*
1827 * Validate input and pass it on.
1828 */
1829 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
1830 AssertMsgReturn(pReq->Hdr.cbReq == sizeof(*pReq), ("%#x != %#x\n", pReq->Hdr.cbReq, sizeof(*pReq)), VERR_INVALID_PARAMETER);
1831
1832 return GVMMR0SchedWakeUpAndPokeCpus(pVM, &pReq->SleepSet, &pReq->PokeSet);
1833}
1834
1835
1836
1837/**
1838 * Poll the schedule to see if someone else should get a chance to run.
1839 *
1840 * This is a bit hackish and will not work too well if the machine is
1841 * under heavy load from non-VM processes.
1842 *
1843 * @returns VINF_SUCCESS if not yielded.
1844 * VINF_GVM_YIELDED if an attempt to switch to a different VM task was made.
1845 * @param pVM Pointer to the shared VM structure.
1846 * @param idCpu The Virtual CPU ID of the calling EMT.
1847 * @param u64ExpireGipTime The time for the sleep to expire expressed as GIP time.
1848 * @param fYield Whether to yield or not.
1849 * This is for when we're spinning in the halt loop.
1850 * @thread EMT(idCpu).
1851 */
1852GVMMR0DECL(int) GVMMR0SchedPoll(PVM pVM, VMCPUID idCpu, bool fYield)
1853{
1854 /*
1855 * Validate input.
1856 */
1857 PGVM pGVM;
1858 PGVMM pGVMM;
1859 int rc = gvmmR0ByVMAndEMT(pVM, idCpu, &pGVM, &pGVMM);
1860 if (RT_SUCCESS(rc))
1861 {
1862 rc = gvmmR0UsedLock(pGVMM);
1863 AssertRC(rc);
1864 pGVM->gvmm.s.StatsSched.cPollCalls++;
1865
1866 Assert(ASMGetFlags() & X86_EFL_IF);
1867 const uint64_t u64Now = RTTimeNanoTS(); /* (GIP time) */
1868
1869 if (!fYield)
1870 pGVM->gvmm.s.StatsSched.cPollWakeUps += gvmmR0SchedDoWakeUps(pGVMM, u64Now);
1871 else
1872 {
1873 /** @todo implement this... */
1874 rc = VERR_NOT_IMPLEMENTED;
1875 }
1876
1877 gvmmR0UsedUnlock(pGVMM);
1878 }
1879
1880 LogFlow(("GVMMR0SchedWakeUp: returns %Rrc\n", rc));
1881 return rc;
1882}
1883
1884
1885
1886/**
1887 * Retrieves the GVMM statistics visible to the caller.
1888 *
1889 * @returns VBox status code.
1890 *
1891 * @param pStats Where to put the statistics.
1892 * @param pSession The current session.
1893 * @param pVM The VM to obtain statistics for. Optional.
1894 */
1895GVMMR0DECL(int) GVMMR0QueryStatistics(PGVMMSTATS pStats, PSUPDRVSESSION pSession, PVM pVM)
1896{
1897 LogFlow(("GVMMR0QueryStatistics: pStats=%p pSession=%p pVM=%p\n", pStats, pSession, pVM));
1898
1899 /*
1900 * Validate input.
1901 */
1902 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1903 AssertPtrReturn(pStats, VERR_INVALID_POINTER);
1904 pStats->cVMs = 0; /* (crash before taking the sem...) */
1905
1906 /*
1907 * Take the lock and get the VM statistics.
1908 */
1909 PGVMM pGVMM;
1910 if (pVM)
1911 {
1912 PGVM pGVM;
1913 int rc = gvmmR0ByVM(pVM, &pGVM, &pGVMM, true /*fTakeUsedLock*/);
1914 if (RT_FAILURE(rc))
1915 return rc;
1916 pStats->SchedVM = pGVM->gvmm.s.StatsSched;
1917 }
1918 else
1919 {
1920 GVMM_GET_VALID_INSTANCE(pGVMM, VERR_INTERNAL_ERROR);
1921 memset(&pStats->SchedVM, 0, sizeof(pStats->SchedVM));
1922
1923 int rc = gvmmR0UsedLock(pGVMM);
1924 AssertRCReturn(rc, rc);
1925 }
1926
1927 /*
1928 * Enumerate the VMs and add the ones visibile to the statistics.
1929 */
1930 pStats->cVMs = 0;
1931 pStats->cEMTs = 0;
1932 memset(&pStats->SchedSum, 0, sizeof(pStats->SchedSum));
1933
1934 for (unsigned i = pGVMM->iUsedHead;
1935 i != NIL_GVM_HANDLE && i < RT_ELEMENTS(pGVMM->aHandles);
1936 i = pGVMM->aHandles[i].iNext)
1937 {
1938 PGVM pGVM = pGVMM->aHandles[i].pGVM;
1939 void *pvObj = pGVMM->aHandles[i].pvObj;
1940 if ( VALID_PTR(pvObj)
1941 && VALID_PTR(pGVM)
1942 && pGVM->u32Magic == GVM_MAGIC
1943 && RT_SUCCESS(SUPR0ObjVerifyAccess(pvObj, pSession, NULL)))
1944 {
1945 pStats->cVMs++;
1946 pStats->cEMTs += pGVM->cCpus;
1947
1948 pStats->SchedSum.cHaltCalls += pGVM->gvmm.s.StatsSched.cHaltCalls;
1949 pStats->SchedSum.cHaltBlocking += pGVM->gvmm.s.StatsSched.cHaltBlocking;
1950 pStats->SchedSum.cHaltTimeouts += pGVM->gvmm.s.StatsSched.cHaltTimeouts;
1951 pStats->SchedSum.cHaltNotBlocking += pGVM->gvmm.s.StatsSched.cHaltNotBlocking;
1952 pStats->SchedSum.cHaltWakeUps += pGVM->gvmm.s.StatsSched.cHaltWakeUps;
1953
1954 pStats->SchedSum.cWakeUpCalls += pGVM->gvmm.s.StatsSched.cWakeUpCalls;
1955 pStats->SchedSum.cWakeUpNotHalted += pGVM->gvmm.s.StatsSched.cWakeUpNotHalted;
1956 pStats->SchedSum.cWakeUpWakeUps += pGVM->gvmm.s.StatsSched.cWakeUpWakeUps;
1957
1958 pStats->SchedSum.cPokeCalls += pGVM->gvmm.s.StatsSched.cPokeCalls;
1959 pStats->SchedSum.cPokeNotBusy += pGVM->gvmm.s.StatsSched.cPokeNotBusy;
1960
1961 pStats->SchedSum.cPollCalls += pGVM->gvmm.s.StatsSched.cPollCalls;
1962 pStats->SchedSum.cPollHalts += pGVM->gvmm.s.StatsSched.cPollHalts;
1963 pStats->SchedSum.cPollWakeUps += pGVM->gvmm.s.StatsSched.cPollWakeUps;
1964 }
1965 }
1966
1967 gvmmR0UsedUnlock(pGVMM);
1968
1969 return VINF_SUCCESS;
1970}
1971
1972
1973/**
1974 * VMMR0 request wrapper for GVMMR0QueryStatistics.
1975 *
1976 * @returns see GVMMR0QueryStatistics.
1977 * @param pVM Pointer to the shared VM structure. Optional.
1978 * @param pReq The request packet.
1979 */
1980GVMMR0DECL(int) GVMMR0QueryStatisticsReq(PVM pVM, PGVMMQUERYSTATISTICSSREQ pReq)
1981{
1982 /*
1983 * Validate input and pass it on.
1984 */
1985 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
1986 AssertMsgReturn(pReq->Hdr.cbReq == sizeof(*pReq), ("%#x != %#x\n", pReq->Hdr.cbReq, sizeof(*pReq)), VERR_INVALID_PARAMETER);
1987
1988 return GVMMR0QueryStatistics(&pReq->Stats, pReq->pSession, pVM);
1989}
1990
1991
1992/**
1993 * Resets the specified GVMM statistics.
1994 *
1995 * @returns VBox status code.
1996 *
1997 * @param pStats Which statistics to reset, that is, non-zero fields indicates which to reset.
1998 * @param pSession The current session.
1999 * @param pVM The VM to reset statistics for. Optional.
2000 */
2001GVMMR0DECL(int) GVMMR0ResetStatistics(PCGVMMSTATS pStats, PSUPDRVSESSION pSession, PVM pVM)
2002{
2003 LogFlow(("GVMMR0ResetStatistics: pStats=%p pSession=%p pVM=%p\n", pStats, pSession, pVM));
2004
2005 /*
2006 * Validate input.
2007 */
2008 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
2009 AssertPtrReturn(pStats, VERR_INVALID_POINTER);
2010
2011 /*
2012 * Take the lock and get the VM statistics.
2013 */
2014 PGVMM pGVMM;
2015 if (pVM)
2016 {
2017 PGVM pGVM;
2018 int rc = gvmmR0ByVM(pVM, &pGVM, &pGVMM, true /*fTakeUsedLock*/);
2019 if (RT_FAILURE(rc))
2020 return rc;
2021# define MAYBE_RESET_FIELD(field) \
2022 do { if (pStats->SchedVM. field ) { pGVM->gvmm.s.StatsSched. field = 0; } } while (0)
2023 MAYBE_RESET_FIELD(cHaltCalls);
2024 MAYBE_RESET_FIELD(cHaltBlocking);
2025 MAYBE_RESET_FIELD(cHaltTimeouts);
2026 MAYBE_RESET_FIELD(cHaltNotBlocking);
2027 MAYBE_RESET_FIELD(cHaltWakeUps);
2028 MAYBE_RESET_FIELD(cWakeUpCalls);
2029 MAYBE_RESET_FIELD(cWakeUpNotHalted);
2030 MAYBE_RESET_FIELD(cWakeUpWakeUps);
2031 MAYBE_RESET_FIELD(cPokeCalls);
2032 MAYBE_RESET_FIELD(cPokeNotBusy);
2033 MAYBE_RESET_FIELD(cPollCalls);
2034 MAYBE_RESET_FIELD(cPollHalts);
2035 MAYBE_RESET_FIELD(cPollWakeUps);
2036# undef MAYBE_RESET_FIELD
2037 }
2038 else
2039 {
2040 GVMM_GET_VALID_INSTANCE(pGVMM, VERR_INTERNAL_ERROR);
2041
2042 int rc = gvmmR0UsedLock(pGVMM);
2043 AssertRCReturn(rc, rc);
2044 }
2045
2046 /*
2047 * Enumerate the VMs and add the ones visibile to the statistics.
2048 */
2049 if (ASMMemIsAll8(&pStats->SchedSum, sizeof(pStats->SchedSum), 0))
2050 {
2051 for (unsigned i = pGVMM->iUsedHead;
2052 i != NIL_GVM_HANDLE && i < RT_ELEMENTS(pGVMM->aHandles);
2053 i = pGVMM->aHandles[i].iNext)
2054 {
2055 PGVM pGVM = pGVMM->aHandles[i].pGVM;
2056 void *pvObj = pGVMM->aHandles[i].pvObj;
2057 if ( VALID_PTR(pvObj)
2058 && VALID_PTR(pGVM)
2059 && pGVM->u32Magic == GVM_MAGIC
2060 && RT_SUCCESS(SUPR0ObjVerifyAccess(pvObj, pSession, NULL)))
2061 {
2062# define MAYBE_RESET_FIELD(field) \
2063 do { if (pStats->SchedSum. field ) { pGVM->gvmm.s.StatsSched. field = 0; } } while (0)
2064 MAYBE_RESET_FIELD(cHaltCalls);
2065 MAYBE_RESET_FIELD(cHaltBlocking);
2066 MAYBE_RESET_FIELD(cHaltTimeouts);
2067 MAYBE_RESET_FIELD(cHaltNotBlocking);
2068 MAYBE_RESET_FIELD(cHaltWakeUps);
2069 MAYBE_RESET_FIELD(cWakeUpCalls);
2070 MAYBE_RESET_FIELD(cWakeUpNotHalted);
2071 MAYBE_RESET_FIELD(cWakeUpWakeUps);
2072 MAYBE_RESET_FIELD(cPokeCalls);
2073 MAYBE_RESET_FIELD(cPokeNotBusy);
2074 MAYBE_RESET_FIELD(cPollCalls);
2075 MAYBE_RESET_FIELD(cPollHalts);
2076 MAYBE_RESET_FIELD(cPollWakeUps);
2077# undef MAYBE_RESET_FIELD
2078 }
2079 }
2080 }
2081
2082 gvmmR0UsedUnlock(pGVMM);
2083
2084 return VINF_SUCCESS;
2085}
2086
2087
2088/**
2089 * VMMR0 request wrapper for GVMMR0ResetStatistics.
2090 *
2091 * @returns see GVMMR0ResetStatistics.
2092 * @param pVM Pointer to the shared VM structure. Optional.
2093 * @param pReq The request packet.
2094 */
2095GVMMR0DECL(int) GVMMR0ResetStatisticsReq(PVM pVM, PGVMMRESETSTATISTICSSREQ pReq)
2096{
2097 /*
2098 * Validate input and pass it on.
2099 */
2100 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
2101 AssertMsgReturn(pReq->Hdr.cbReq == sizeof(*pReq), ("%#x != %#x\n", pReq->Hdr.cbReq, sizeof(*pReq)), VERR_INVALID_PARAMETER);
2102
2103 return GVMMR0ResetStatistics(&pReq->Stats, pReq->pSession, pVM);
2104}
2105
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