VirtualBox

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

Last change on this file since 12310 was 12310, checked in by vboxsync, 16 years ago

GVMM: Fixed a semaphore leak.

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