VirtualBox

source: vbox/trunk/src/VBox/Additions/common/VBoxGuest/VBoxGuest.cpp@ 45779

Last change on this file since 45779 was 45779, checked in by vboxsync, 12 years ago

VBoxGuest: better caps filtering; cleanup

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 108.5 KB
Line 
1/* $Id: VBoxGuest.cpp 45779 2013-04-26 15:18:59Z vboxsync $ */
2/** @file
3 * VBoxGuest - Guest Additions Driver, Common Code.
4 */
5
6/*
7 * Copyright (C) 2007-2012 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 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28/*******************************************************************************
29* Header Files *
30*******************************************************************************/
31#define LOG_GROUP LOG_GROUP_DEFAULT
32#include "VBoxGuestInternal.h"
33#include "VBoxGuest2.h"
34#include <VBox/VMMDev.h> /* for VMMDEV_RAM_SIZE */
35#include <VBox/log.h>
36#include <iprt/mem.h>
37#include <iprt/time.h>
38#include <iprt/memobj.h>
39#include <iprt/asm.h>
40#include <iprt/asm-amd64-x86.h>
41#include <iprt/string.h>
42#include <iprt/process.h>
43#include <iprt/assert.h>
44#include <iprt/param.h>
45#ifdef VBOX_WITH_HGCM
46# include <iprt/thread.h>
47#endif
48#include "version-generated.h"
49#if defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)
50# include "revision-generated.h"
51#endif
52#ifdef RT_OS_WINDOWS
53# ifndef CTL_CODE
54# include <Windows.h>
55# endif
56#endif
57#if defined(RT_OS_SOLARIS) || defined(RT_OS_DARWIN)
58# include <iprt/rand.h>
59#endif
60
61
62/*******************************************************************************
63* Internal Functions *
64*******************************************************************************/
65#ifdef VBOX_WITH_HGCM
66static DECLCALLBACK(int) VBoxGuestHGCMAsyncWaitCallback(VMMDevHGCMRequestHeader *pHdrNonVolatile, void *pvUser, uint32_t u32User);
67#endif
68#ifdef DEBUG
69static void testSetMouseStatus(void);
70#endif
71static int VBoxGuestCommonIOCtl_SetMouseStatus(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, uint32_t fFeatures);
72
73static int VBoxGuestCommonGuestCapsAcquire(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, uint32_t fOrMask, uint32_t fNotMask);
74
75#define VBOXGUEST_ACQUIRE_STYLE_EVENTS (VMMDEV_EVENT_DISPLAY_CHANGE_REQUEST | VMMDEV_EVENT_SEAMLESS_MODE_CHANGE_REQUEST)
76
77DECLINLINE(uint32_t) VBoxGuestCommonGetHandledEventsLocked(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession)
78{
79 if(!pDevExt->u32AcquireModeGuestCaps)
80 return VMMDEV_EVENT_VALID_EVENT_MASK;
81
82 uint32_t u32AllowedGuestCaps = pSession->u32AquiredGuestCaps | (VMMDEV_EVENT_VALID_EVENT_MASK & ~pDevExt->u32AcquireModeGuestCaps);
83 uint32_t u32CleanupEvents = VBOXGUEST_ACQUIRE_STYLE_EVENTS;
84 if (u32AllowedGuestCaps & VMMDEV_GUEST_SUPPORTS_GRAPHICS)
85 u32CleanupEvents &= ~VMMDEV_EVENT_DISPLAY_CHANGE_REQUEST;
86 if (u32AllowedGuestCaps & VMMDEV_GUEST_SUPPORTS_SEAMLESS)
87 u32CleanupEvents &= ~VMMDEV_EVENT_SEAMLESS_MODE_CHANGE_REQUEST;
88
89 return VMMDEV_EVENT_VALID_EVENT_MASK & ~u32CleanupEvents;
90}
91
92DECLINLINE(uint32_t) VBoxGuestCommonGetAndCleanPendingEventsLocked(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, uint32_t fReqEvents)
93{
94 uint32_t fMatches = pDevExt->f32PendingEvents & fReqEvents & VBoxGuestCommonGetHandledEventsLocked(pDevExt, pSession);
95 if (fMatches)
96 ASMAtomicAndU32(&pDevExt->f32PendingEvents, ~fMatches);
97 return fMatches;
98}
99
100DECLINLINE(bool) VBoxGuestCommonGuestCapsModeSet(PVBOXGUESTDEVEXT pDevExt, uint32_t fCaps, bool fAcquire, uint32_t *pu32OtherVal)
101{
102 uint32_t *pVal = fAcquire ? &pDevExt->u32AcquireModeGuestCaps : &pDevExt->u32SetModeGuestCaps;
103 const uint32_t fNotVal = !fAcquire ? pDevExt->u32AcquireModeGuestCaps : pDevExt->u32SetModeGuestCaps;
104 bool fResult = true;
105 RTSpinlockAcquire(pDevExt->EventSpinlock);
106
107 if (!(fNotVal & fCaps))
108 *pVal |= fCaps;
109 else
110 {
111 AssertMsgFailed(("trying to change caps mode\n"));
112 fResult = false;
113 }
114
115 RTSpinlockReleaseNoInts(pDevExt->EventSpinlock);
116
117 if (pu32OtherVal)
118 *pu32OtherVal = fNotVal;
119 return fResult;
120}
121
122/*******************************************************************************
123* Global Variables *
124*******************************************************************************/
125static const size_t cbChangeMemBalloonReq = RT_OFFSETOF(VMMDevChangeMemBalloon, aPhysPage[VMMDEV_MEMORY_BALLOON_CHUNK_PAGES]);
126
127#if defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS)
128/**
129 * Drag in the rest of IRPT since we share it with the
130 * rest of the kernel modules on Solaris.
131 */
132PFNRT g_apfnVBoxGuestIPRTDeps[] =
133{
134 /* VirtioNet */
135 (PFNRT)RTRandBytes,
136 /* RTSemMutex* */
137 (PFNRT)RTSemMutexCreate,
138 (PFNRT)RTSemMutexDestroy,
139 (PFNRT)RTSemMutexRequest,
140 (PFNRT)RTSemMutexRequestNoResume,
141 (PFNRT)RTSemMutexRequestDebug,
142 (PFNRT)RTSemMutexRequestNoResumeDebug,
143 (PFNRT)RTSemMutexRelease,
144 (PFNRT)RTSemMutexIsOwned,
145 NULL
146};
147#endif /* RT_OS_DARWIN || RT_OS_SOLARIS */
148
149
150/**
151 * Reserves memory in which the VMM can relocate any guest mappings
152 * that are floating around.
153 *
154 * This operation is a little bit tricky since the VMM might not accept
155 * just any address because of address clashes between the three contexts
156 * it operates in, so use a small stack to perform this operation.
157 *
158 * @returns VBox status code (ignored).
159 * @param pDevExt The device extension.
160 */
161static int vboxGuestInitFixateGuestMappings(PVBOXGUESTDEVEXT pDevExt)
162{
163 /*
164 * Query the required space.
165 */
166 VMMDevReqHypervisorInfo *pReq;
167 int rc = VbglGRAlloc((VMMDevRequestHeader **)&pReq, sizeof(VMMDevReqHypervisorInfo), VMMDevReq_GetHypervisorInfo);
168 if (RT_FAILURE(rc))
169 return rc;
170 pReq->hypervisorStart = 0;
171 pReq->hypervisorSize = 0;
172 rc = VbglGRPerform(&pReq->header);
173 if (RT_FAILURE(rc)) /* this shouldn't happen! */
174 {
175 VbglGRFree(&pReq->header);
176 return rc;
177 }
178
179 /*
180 * The VMM will report back if there is nothing it wants to map, like for
181 * instance in VT-x and AMD-V mode.
182 */
183 if (pReq->hypervisorSize == 0)
184 Log(("vboxGuestInitFixateGuestMappings: nothing to do\n"));
185 else
186 {
187 /*
188 * We have to try several times since the host can be picky
189 * about certain addresses.
190 */
191 RTR0MEMOBJ hFictive = NIL_RTR0MEMOBJ;
192 uint32_t cbHypervisor = pReq->hypervisorSize;
193 RTR0MEMOBJ ahTries[5];
194 uint32_t iTry;
195 bool fBitched = false;
196 Log(("vboxGuestInitFixateGuestMappings: cbHypervisor=%#x\n", cbHypervisor));
197 for (iTry = 0; iTry < RT_ELEMENTS(ahTries); iTry++)
198 {
199 /*
200 * Reserve space, or if that isn't supported, create a object for
201 * some fictive physical memory and map that in to kernel space.
202 *
203 * To make the code a bit uglier, most systems cannot help with
204 * 4MB alignment, so we have to deal with that in addition to
205 * having two ways of getting the memory.
206 */
207 uint32_t uAlignment = _4M;
208 RTR0MEMOBJ hObj;
209 rc = RTR0MemObjReserveKernel(&hObj, (void *)-1, RT_ALIGN_32(cbHypervisor, _4M), uAlignment);
210 if (rc == VERR_NOT_SUPPORTED)
211 {
212 uAlignment = PAGE_SIZE;
213 rc = RTR0MemObjReserveKernel(&hObj, (void *)-1, RT_ALIGN_32(cbHypervisor, _4M) + _4M, uAlignment);
214 }
215 /*
216 * If both RTR0MemObjReserveKernel calls above failed because either not supported or
217 * not implemented at all at the current platform, try to map the memory object into the
218 * virtual kernel space.
219 */
220 if (rc == VERR_NOT_SUPPORTED)
221 {
222 if (hFictive == NIL_RTR0MEMOBJ)
223 {
224 rc = RTR0MemObjEnterPhys(&hObj, VBOXGUEST_HYPERVISOR_PHYSICAL_START, cbHypervisor + _4M, RTMEM_CACHE_POLICY_DONT_CARE);
225 if (RT_FAILURE(rc))
226 break;
227 hFictive = hObj;
228 }
229 uAlignment = _4M;
230 rc = RTR0MemObjMapKernel(&hObj, hFictive, (void *)-1, uAlignment, RTMEM_PROT_READ | RTMEM_PROT_WRITE);
231 if (rc == VERR_NOT_SUPPORTED)
232 {
233 uAlignment = PAGE_SIZE;
234 rc = RTR0MemObjMapKernel(&hObj, hFictive, (void *)-1, uAlignment, RTMEM_PROT_READ | RTMEM_PROT_WRITE);
235 }
236 }
237 if (RT_FAILURE(rc))
238 {
239 LogRel(("VBoxGuest: Failed to reserve memory for the hypervisor: rc=%Rrc (cbHypervisor=%#x uAlignment=%#x iTry=%u)\n",
240 rc, cbHypervisor, uAlignment, iTry));
241 fBitched = true;
242 break;
243 }
244
245 /*
246 * Try set it.
247 */
248 pReq->header.requestType = VMMDevReq_SetHypervisorInfo;
249 pReq->header.rc = VERR_INTERNAL_ERROR;
250 pReq->hypervisorSize = cbHypervisor;
251 pReq->hypervisorStart = (uintptr_t)RTR0MemObjAddress(hObj);
252 if ( uAlignment == PAGE_SIZE
253 && pReq->hypervisorStart & (_4M - 1))
254 pReq->hypervisorStart = RT_ALIGN_32(pReq->hypervisorStart, _4M);
255 AssertMsg(RT_ALIGN_32(pReq->hypervisorStart, _4M) == pReq->hypervisorStart, ("%#x\n", pReq->hypervisorStart));
256
257 rc = VbglGRPerform(&pReq->header);
258 if (RT_SUCCESS(rc))
259 {
260 pDevExt->hGuestMappings = hFictive != NIL_RTR0MEMOBJ ? hFictive : hObj;
261 Log(("VBoxGuest: %p LB %#x; uAlignment=%#x iTry=%u hGuestMappings=%p (%s)\n",
262 RTR0MemObjAddress(pDevExt->hGuestMappings),
263 RTR0MemObjSize(pDevExt->hGuestMappings),
264 uAlignment, iTry, pDevExt->hGuestMappings, hFictive != NIL_RTR0PTR ? "fictive" : "reservation"));
265 break;
266 }
267 ahTries[iTry] = hObj;
268 }
269
270 /*
271 * Cleanup failed attempts.
272 */
273 while (iTry-- > 0)
274 RTR0MemObjFree(ahTries[iTry], false /* fFreeMappings */);
275 if ( RT_FAILURE(rc)
276 && hFictive != NIL_RTR0PTR)
277 RTR0MemObjFree(hFictive, false /* fFreeMappings */);
278 if (RT_FAILURE(rc) && !fBitched)
279 LogRel(("VBoxGuest: Warning: failed to reserve %#d of memory for guest mappings.\n", cbHypervisor));
280 }
281 VbglGRFree(&pReq->header);
282
283 /*
284 * We ignore failed attempts for now.
285 */
286 return VINF_SUCCESS;
287}
288
289
290/**
291 * Undo what vboxGuestInitFixateGuestMappings did.
292 *
293 * @param pDevExt The device extension.
294 */
295static void vboxGuestTermUnfixGuestMappings(PVBOXGUESTDEVEXT pDevExt)
296{
297 if (pDevExt->hGuestMappings != NIL_RTR0PTR)
298 {
299 /*
300 * Tell the host that we're going to free the memory we reserved for
301 * it, the free it up. (Leak the memory if anything goes wrong here.)
302 */
303 VMMDevReqHypervisorInfo *pReq;
304 int rc = VbglGRAlloc((VMMDevRequestHeader **)&pReq, sizeof(VMMDevReqHypervisorInfo), VMMDevReq_SetHypervisorInfo);
305 if (RT_SUCCESS(rc))
306 {
307 pReq->hypervisorStart = 0;
308 pReq->hypervisorSize = 0;
309 rc = VbglGRPerform(&pReq->header);
310 VbglGRFree(&pReq->header);
311 }
312 if (RT_SUCCESS(rc))
313 {
314 rc = RTR0MemObjFree(pDevExt->hGuestMappings, true /* fFreeMappings */);
315 AssertRC(rc);
316 }
317 else
318 LogRel(("vboxGuestTermUnfixGuestMappings: Failed to unfix the guest mappings! rc=%Rrc\n", rc));
319
320 pDevExt->hGuestMappings = NIL_RTR0MEMOBJ;
321 }
322}
323
324
325/**
326 * Sets the interrupt filter mask during initialization and termination.
327 *
328 * This will ASSUME that we're the ones in carge over the mask, so
329 * we'll simply clear all bits we don't set.
330 *
331 * @returns VBox status code (ignored).
332 * @param pDevExt The device extension.
333 * @param fMask The new mask.
334 */
335static int vboxGuestSetFilterMask(PVBOXGUESTDEVEXT pDevExt, uint32_t fMask)
336{
337 VMMDevCtlGuestFilterMask *pReq;
338 int rc = VbglGRAlloc((VMMDevRequestHeader **)&pReq, sizeof(*pReq), VMMDevReq_CtlGuestFilterMask);
339 if (RT_SUCCESS(rc))
340 {
341 pReq->u32OrMask = fMask;
342 pReq->u32NotMask = ~fMask;
343 rc = VbglGRPerform(&pReq->header);
344 if (RT_FAILURE(rc))
345 LogRel(("vboxGuestSetFilterMask: failed with rc=%Rrc\n", rc));
346 VbglGRFree(&pReq->header);
347 }
348 return rc;
349}
350
351
352/**
353 * Inflate the balloon by one chunk represented by an R0 memory object.
354 *
355 * The caller owns the balloon mutex.
356 *
357 * @returns IPRT status code.
358 * @param pMemObj Pointer to the R0 memory object.
359 * @param pReq The pre-allocated request for performing the VMMDev call.
360 */
361static int vboxGuestBalloonInflate(PRTR0MEMOBJ pMemObj, VMMDevChangeMemBalloon *pReq)
362{
363 uint32_t iPage;
364 int rc;
365
366 for (iPage = 0; iPage < VMMDEV_MEMORY_BALLOON_CHUNK_PAGES; iPage++)
367 {
368 RTHCPHYS phys = RTR0MemObjGetPagePhysAddr(*pMemObj, iPage);
369 pReq->aPhysPage[iPage] = phys;
370 }
371
372 pReq->fInflate = true;
373 pReq->header.size = cbChangeMemBalloonReq;
374 pReq->cPages = VMMDEV_MEMORY_BALLOON_CHUNK_PAGES;
375
376 rc = VbglGRPerform(&pReq->header);
377 if (RT_FAILURE(rc))
378 LogRel(("vboxGuestBalloonInflate: VbglGRPerform failed. rc=%Rrc\n", rc));
379 return rc;
380}
381
382
383/**
384 * Deflate the balloon by one chunk - info the host and free the memory object.
385 *
386 * The caller owns the balloon mutex.
387 *
388 * @returns IPRT status code.
389 * @param pMemObj Pointer to the R0 memory object.
390 * The memory object will be freed afterwards.
391 * @param pReq The pre-allocated request for performing the VMMDev call.
392 */
393static int vboxGuestBalloonDeflate(PRTR0MEMOBJ pMemObj, VMMDevChangeMemBalloon *pReq)
394{
395 uint32_t iPage;
396 int rc;
397
398 for (iPage = 0; iPage < VMMDEV_MEMORY_BALLOON_CHUNK_PAGES; iPage++)
399 {
400 RTHCPHYS phys = RTR0MemObjGetPagePhysAddr(*pMemObj, iPage);
401 pReq->aPhysPage[iPage] = phys;
402 }
403
404 pReq->fInflate = false;
405 pReq->header.size = cbChangeMemBalloonReq;
406 pReq->cPages = VMMDEV_MEMORY_BALLOON_CHUNK_PAGES;
407
408 rc = VbglGRPerform(&pReq->header);
409 if (RT_FAILURE(rc))
410 {
411 LogRel(("vboxGuestBalloonDeflate: VbglGRPerform failed. rc=%Rrc\n", rc));
412 return rc;
413 }
414
415 rc = RTR0MemObjFree(*pMemObj, true);
416 if (RT_FAILURE(rc))
417 {
418 LogRel(("vboxGuestBalloonDeflate: RTR0MemObjFree(%p,true) -> %Rrc; this is *BAD*!\n", *pMemObj, rc));
419 return rc;
420 }
421
422 *pMemObj = NIL_RTR0MEMOBJ;
423 return VINF_SUCCESS;
424}
425
426
427/**
428 * Inflate/deflate the memory balloon and notify the host.
429 *
430 * This is a worker used by VBoxGuestCommonIOCtl_CheckMemoryBalloon - it takes
431 * the mutex.
432 *
433 * @returns VBox status code.
434 * @param pDevExt The device extension.
435 * @param pSession The session.
436 * @param cBalloonChunks The new size of the balloon in chunks of 1MB.
437 * @param pfHandleInR3 Where to return the handle-in-ring3 indicator
438 * (VINF_SUCCESS if set).
439 */
440static int vboxGuestSetBalloonSizeKernel(PVBOXGUESTDEVEXT pDevExt, uint32_t cBalloonChunks, uint32_t *pfHandleInR3)
441{
442 int rc = VINF_SUCCESS;
443
444 if (pDevExt->MemBalloon.fUseKernelAPI)
445 {
446 VMMDevChangeMemBalloon *pReq;
447 uint32_t i;
448
449 if (cBalloonChunks > pDevExt->MemBalloon.cMaxChunks)
450 {
451 LogRel(("vboxGuestSetBalloonSizeKernel: illegal balloon size %u (max=%u)\n",
452 cBalloonChunks, pDevExt->MemBalloon.cMaxChunks));
453 return VERR_INVALID_PARAMETER;
454 }
455
456 if (cBalloonChunks == pDevExt->MemBalloon.cMaxChunks)
457 return VINF_SUCCESS; /* nothing to do */
458
459 if ( cBalloonChunks > pDevExt->MemBalloon.cChunks
460 && !pDevExt->MemBalloon.paMemObj)
461 {
462 pDevExt->MemBalloon.paMemObj = (PRTR0MEMOBJ)RTMemAllocZ(sizeof(RTR0MEMOBJ) * pDevExt->MemBalloon.cMaxChunks);
463 if (!pDevExt->MemBalloon.paMemObj)
464 {
465 LogRel(("VBoxGuestSetBalloonSizeKernel: no memory for paMemObj!\n"));
466 return VERR_NO_MEMORY;
467 }
468 }
469
470 rc = VbglGRAlloc((VMMDevRequestHeader **)&pReq, cbChangeMemBalloonReq, VMMDevReq_ChangeMemBalloon);
471 if (RT_FAILURE(rc))
472 return rc;
473
474 if (cBalloonChunks > pDevExt->MemBalloon.cChunks)
475 {
476 /* inflate */
477 for (i = pDevExt->MemBalloon.cChunks; i < cBalloonChunks; i++)
478 {
479 rc = RTR0MemObjAllocPhysNC(&pDevExt->MemBalloon.paMemObj[i],
480 VMMDEV_MEMORY_BALLOON_CHUNK_SIZE, NIL_RTHCPHYS);
481 if (RT_FAILURE(rc))
482 {
483 if (rc == VERR_NOT_SUPPORTED)
484 {
485 /* not supported -- fall back to the R3-allocated memory. */
486 rc = VINF_SUCCESS;
487 pDevExt->MemBalloon.fUseKernelAPI = false;
488 Assert(pDevExt->MemBalloon.cChunks == 0);
489 Log(("VBoxGuestSetBalloonSizeKernel: PhysNC allocs not supported, falling back to R3 allocs.\n"));
490 }
491 /* else if (rc == VERR_NO_MEMORY || rc == VERR_NO_PHYS_MEMORY):
492 * cannot allocate more memory => don't try further, just stop here */
493 /* else: XXX what else can fail? VERR_MEMOBJ_INIT_FAILED for instance. just stop. */
494 break;
495 }
496
497 rc = vboxGuestBalloonInflate(&pDevExt->MemBalloon.paMemObj[i], pReq);
498 if (RT_FAILURE(rc))
499 {
500 Log(("vboxGuestSetBalloonSize(inflate): failed, rc=%Rrc!\n", rc));
501 RTR0MemObjFree(pDevExt->MemBalloon.paMemObj[i], true);
502 pDevExt->MemBalloon.paMemObj[i] = NIL_RTR0MEMOBJ;
503 break;
504 }
505 pDevExt->MemBalloon.cChunks++;
506 }
507 }
508 else
509 {
510 /* deflate */
511 for (i = pDevExt->MemBalloon.cChunks; i-- > cBalloonChunks;)
512 {
513 rc = vboxGuestBalloonDeflate(&pDevExt->MemBalloon.paMemObj[i], pReq);
514 if (RT_FAILURE(rc))
515 {
516 Log(("vboxGuestSetBalloonSize(deflate): failed, rc=%Rrc!\n", rc));
517 break;
518 }
519 pDevExt->MemBalloon.cChunks--;
520 }
521 }
522
523 VbglGRFree(&pReq->header);
524 }
525
526 /*
527 * Set the handle-in-ring3 indicator. When set Ring-3 will have to work
528 * the balloon changes via the other API.
529 */
530 *pfHandleInR3 = pDevExt->MemBalloon.fUseKernelAPI ? false : true;
531
532 return rc;
533}
534
535
536/**
537 * Helper to reinit the VBoxVMM communication after hibernation.
538 *
539 * @returns VBox status code.
540 * @param pDevExt The device extension.
541 * @param enmOSType The OS type.
542 */
543int VBoxGuestReinitDevExtAfterHibernation(PVBOXGUESTDEVEXT pDevExt, VBOXOSTYPE enmOSType)
544{
545 int rc = VBoxGuestReportGuestInfo(enmOSType);
546 if (RT_SUCCESS(rc))
547 {
548 rc = VBoxGuestReportDriverStatus(true /* Driver is active */);
549 if (RT_FAILURE(rc))
550 Log(("VBoxGuest::VBoxGuestReinitDevExtAfterHibernation: could not report guest driver status, rc=%Rrc\n", rc));
551 }
552 else
553 Log(("VBoxGuest::VBoxGuestReinitDevExtAfterHibernation: could not report guest information to host, rc=%Rrc\n", rc));
554 Log(("VBoxGuest::VBoxGuestReinitDevExtAfterHibernation: returned with rc=%Rrc\n", rc));
555 return rc;
556}
557
558
559/**
560 * Inflate/deflate the balloon by one chunk.
561 *
562 * Worker for VBoxGuestCommonIOCtl_ChangeMemoryBalloon - it takes the mutex.
563 *
564 * @returns VBox status code.
565 * @param pDevExt The device extension.
566 * @param pSession The session.
567 * @param u64ChunkAddr The address of the chunk to add to / remove from the
568 * balloon.
569 * @param fInflate Inflate if true, deflate if false.
570 */
571static int vboxGuestSetBalloonSizeFromUser(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession,
572 uint64_t u64ChunkAddr, bool fInflate)
573{
574 VMMDevChangeMemBalloon *pReq;
575 int rc = VINF_SUCCESS;
576 uint32_t i;
577 PRTR0MEMOBJ pMemObj = NULL;
578
579 if (fInflate)
580 {
581 if ( pDevExt->MemBalloon.cChunks > pDevExt->MemBalloon.cMaxChunks - 1
582 || pDevExt->MemBalloon.cMaxChunks == 0 /* If called without first querying. */)
583 {
584 LogRel(("vboxGuestSetBalloonSize: cannot inflate balloon, already have %u chunks (max=%u)\n",
585 pDevExt->MemBalloon.cChunks, pDevExt->MemBalloon.cMaxChunks));
586 return VERR_INVALID_PARAMETER;
587 }
588
589 if (!pDevExt->MemBalloon.paMemObj)
590 {
591 pDevExt->MemBalloon.paMemObj = (PRTR0MEMOBJ)RTMemAlloc(sizeof(RTR0MEMOBJ) * pDevExt->MemBalloon.cMaxChunks);
592 if (!pDevExt->MemBalloon.paMemObj)
593 {
594 LogRel(("VBoxGuestSetBalloonSizeFromUser: no memory for paMemObj!\n"));
595 return VERR_NO_MEMORY;
596 }
597 for (i = 0; i < pDevExt->MemBalloon.cMaxChunks; i++)
598 pDevExt->MemBalloon.paMemObj[i] = NIL_RTR0MEMOBJ;
599 }
600 }
601 else
602 {
603 if (pDevExt->MemBalloon.cChunks == 0)
604 {
605 AssertMsgFailed(("vboxGuestSetBalloonSize: cannot decrease balloon, already at size 0\n"));
606 return VERR_INVALID_PARAMETER;
607 }
608 }
609
610 /*
611 * Enumerate all memory objects and check if the object is already registered.
612 */
613 for (i = 0; i < pDevExt->MemBalloon.cMaxChunks; i++)
614 {
615 if ( fInflate
616 && !pMemObj
617 && pDevExt->MemBalloon.paMemObj[i] == NIL_RTR0MEMOBJ)
618 pMemObj = &pDevExt->MemBalloon.paMemObj[i]; /* found free object pointer */
619 if (RTR0MemObjAddressR3(pDevExt->MemBalloon.paMemObj[i]) == u64ChunkAddr)
620 {
621 if (fInflate)
622 return VERR_ALREADY_EXISTS; /* don't provide the same memory twice */
623 pMemObj = &pDevExt->MemBalloon.paMemObj[i];
624 break;
625 }
626 }
627 if (!pMemObj)
628 {
629 if (fInflate)
630 {
631 /* no free object pointer found -- should not happen */
632 return VERR_NO_MEMORY;
633 }
634
635 /* cannot free this memory as it wasn't provided before */
636 return VERR_NOT_FOUND;
637 }
638
639 /*
640 * Try inflate / default the balloon as requested.
641 */
642 rc = VbglGRAlloc((VMMDevRequestHeader **)&pReq, cbChangeMemBalloonReq, VMMDevReq_ChangeMemBalloon);
643 if (RT_FAILURE(rc))
644 return rc;
645
646 if (fInflate)
647 {
648 rc = RTR0MemObjLockUser(pMemObj, (RTR3PTR)u64ChunkAddr, VMMDEV_MEMORY_BALLOON_CHUNK_SIZE,
649 RTMEM_PROT_READ | RTMEM_PROT_WRITE, NIL_RTR0PROCESS);
650 if (RT_SUCCESS(rc))
651 {
652 rc = vboxGuestBalloonInflate(pMemObj, pReq);
653 if (RT_SUCCESS(rc))
654 pDevExt->MemBalloon.cChunks++;
655 else
656 {
657 Log(("vboxGuestSetBalloonSize(inflate): failed, rc=%Rrc!\n", rc));
658 RTR0MemObjFree(*pMemObj, true);
659 *pMemObj = NIL_RTR0MEMOBJ;
660 }
661 }
662 }
663 else
664 {
665 rc = vboxGuestBalloonDeflate(pMemObj, pReq);
666 if (RT_SUCCESS(rc))
667 pDevExt->MemBalloon.cChunks--;
668 else
669 Log(("vboxGuestSetBalloonSize(deflate): failed, rc=%Rrc!\n", rc));
670 }
671
672 VbglGRFree(&pReq->header);
673 return rc;
674}
675
676
677/**
678 * Cleanup the memory balloon of a session.
679 *
680 * Will request the balloon mutex, so it must be valid and the caller must not
681 * own it already.
682 *
683 * @param pDevExt The device extension.
684 * @param pDevExt The session. Can be NULL at unload.
685 */
686static void vboxGuestCloseMemBalloon(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession)
687{
688 RTSemFastMutexRequest(pDevExt->MemBalloon.hMtx);
689 if ( pDevExt->MemBalloon.pOwner == pSession
690 || pSession == NULL /*unload*/)
691 {
692 if (pDevExt->MemBalloon.paMemObj)
693 {
694 VMMDevChangeMemBalloon *pReq;
695 int rc = VbglGRAlloc((VMMDevRequestHeader **)&pReq, cbChangeMemBalloonReq, VMMDevReq_ChangeMemBalloon);
696 if (RT_SUCCESS(rc))
697 {
698 uint32_t i;
699 for (i = pDevExt->MemBalloon.cChunks; i-- > 0;)
700 {
701 rc = vboxGuestBalloonDeflate(&pDevExt->MemBalloon.paMemObj[i], pReq);
702 if (RT_FAILURE(rc))
703 {
704 LogRel(("vboxGuestCloseMemBalloon: Deflate failed with rc=%Rrc. Will leak %u chunks.\n",
705 rc, pDevExt->MemBalloon.cChunks));
706 break;
707 }
708 pDevExt->MemBalloon.paMemObj[i] = NIL_RTR0MEMOBJ;
709 pDevExt->MemBalloon.cChunks--;
710 }
711 VbglGRFree(&pReq->header);
712 }
713 else
714 LogRel(("vboxGuestCloseMemBalloon: Failed to allocate VMMDev request buffer (rc=%Rrc). Will leak %u chunks.\n",
715 rc, pDevExt->MemBalloon.cChunks));
716 RTMemFree(pDevExt->MemBalloon.paMemObj);
717 pDevExt->MemBalloon.paMemObj = NULL;
718 }
719
720 pDevExt->MemBalloon.pOwner = NULL;
721 }
722 RTSemFastMutexRelease(pDevExt->MemBalloon.hMtx);
723}
724
725
726/**
727 * Initializes the VBoxGuest device extension when the
728 * device driver is loaded.
729 *
730 * The native code locates the VMMDev on the PCI bus and retrieve
731 * the MMIO and I/O port ranges, this function will take care of
732 * mapping the MMIO memory (if present). Upon successful return
733 * the native code should set up the interrupt handler.
734 *
735 * @returns VBox status code.
736 *
737 * @param pDevExt The device extension. Allocated by the native code.
738 * @param IOPortBase The base of the I/O port range.
739 * @param pvMMIOBase The base of the MMIO memory mapping.
740 * This is optional, pass NULL if not present.
741 * @param cbMMIO The size of the MMIO memory mapping.
742 * This is optional, pass 0 if not present.
743 * @param enmOSType The guest OS type to report to the VMMDev.
744 * @param fFixedEvents Events that will be enabled upon init and no client
745 * will ever be allowed to mask.
746 */
747int VBoxGuestInitDevExt(PVBOXGUESTDEVEXT pDevExt, uint16_t IOPortBase,
748 void *pvMMIOBase, uint32_t cbMMIO, VBOXOSTYPE enmOSType, uint32_t fFixedEvents)
749{
750 int rc, rc2;
751 unsigned i;
752
753 /*
754 * Adjust fFixedEvents.
755 */
756#ifdef VBOX_WITH_HGCM
757 fFixedEvents |= VMMDEV_EVENT_HGCM;
758#endif
759
760 /*
761 * Initialize the data.
762 */
763 pDevExt->IOPortBase = IOPortBase;
764 pDevExt->pVMMDevMemory = NULL;
765 pDevExt->fFixedEvents = fFixedEvents;
766 pDevExt->hGuestMappings = NIL_RTR0MEMOBJ;
767 pDevExt->EventSpinlock = NIL_RTSPINLOCK;
768 pDevExt->pIrqAckEvents = NULL;
769 pDevExt->PhysIrqAckEvents = NIL_RTCCPHYS;
770 RTListInit(&pDevExt->WaitList);
771#ifdef VBOX_WITH_HGCM
772 RTListInit(&pDevExt->HGCMWaitList);
773#endif
774#ifdef VBOXGUEST_USE_DEFERRED_WAKE_UP
775 RTListInit(&pDevExt->WakeUpList);
776#endif
777 RTListInit(&pDevExt->WokenUpList);
778 RTListInit(&pDevExt->FreeList);
779#ifdef VBOX_WITH_VRDP_SESSION_HANDLING
780 pDevExt->fVRDPEnabled = false;
781#endif
782 pDevExt->fLoggingEnabled = false;
783 pDevExt->f32PendingEvents = 0;
784 pDevExt->u32MousePosChangedSeq = 0;
785 pDevExt->SessionSpinlock = NIL_RTSPINLOCK;
786 pDevExt->MemBalloon.hMtx = NIL_RTSEMFASTMUTEX;
787 pDevExt->MemBalloon.cChunks = 0;
788 pDevExt->MemBalloon.cMaxChunks = 0;
789 pDevExt->MemBalloon.fUseKernelAPI = true;
790 pDevExt->MemBalloon.paMemObj = NULL;
791 pDevExt->MemBalloon.pOwner = NULL;
792 for (i = 0; i < RT_ELEMENTS(pDevExt->acMouseFeatureUsage); ++i)
793 pDevExt->acMouseFeatureUsage[i] = 0;
794 pDevExt->fMouseStatus = 0;
795 pDevExt->MouseNotifyCallback.pfnNotify = NULL;
796 pDevExt->MouseNotifyCallback.pvUser = NULL;
797 pDevExt->cISR = 0;
798
799 /*
800 * If there is an MMIO region validate the version and size.
801 */
802 if (pvMMIOBase)
803 {
804 VMMDevMemory *pVMMDev = (VMMDevMemory *)pvMMIOBase;
805 Assert(cbMMIO);
806 if ( pVMMDev->u32Version == VMMDEV_MEMORY_VERSION
807 && pVMMDev->u32Size >= 32
808 && pVMMDev->u32Size <= cbMMIO)
809 {
810 pDevExt->pVMMDevMemory = pVMMDev;
811 Log(("VBoxGuestInitDevExt: VMMDevMemory: mapping=%p size=%#RX32 (%#RX32) version=%#RX32\n",
812 pVMMDev, pVMMDev->u32Size, cbMMIO, pVMMDev->u32Version));
813 }
814 else /* try live without it. */
815 LogRel(("VBoxGuestInitDevExt: Bogus VMMDev memory; u32Version=%RX32 (expected %RX32) u32Size=%RX32 (expected <= %RX32)\n",
816 pVMMDev->u32Version, VMMDEV_MEMORY_VERSION, pVMMDev->u32Size, cbMMIO));
817 }
818
819 pDevExt->u32AcquireModeGuestCaps = 0;
820 pDevExt->u32SetModeGuestCaps = 0;
821 pDevExt->u32GuestCaps = 0;
822
823 /*
824 * Create the wait and session spinlocks as well as the ballooning mutex.
825 */
826 rc = RTSpinlockCreate(&pDevExt->EventSpinlock, RTSPINLOCK_FLAGS_INTERRUPT_SAFE, "VBoxGuestEvent");
827 if (RT_SUCCESS(rc))
828 rc = RTSpinlockCreate(&pDevExt->SessionSpinlock, RTSPINLOCK_FLAGS_INTERRUPT_SAFE, "VBoxGuestSession");
829 if (RT_FAILURE(rc))
830 {
831 LogRel(("VBoxGuestInitDevExt: failed to create spinlock, rc=%Rrc!\n", rc));
832 if (pDevExt->EventSpinlock != NIL_RTSPINLOCK)
833 RTSpinlockDestroy(pDevExt->EventSpinlock);
834 return rc;
835 }
836
837 rc = RTSemFastMutexCreate(&pDevExt->MemBalloon.hMtx);
838 if (RT_FAILURE(rc))
839 {
840 LogRel(("VBoxGuestInitDevExt: failed to create mutex, rc=%Rrc!\n", rc));
841 RTSpinlockDestroy(pDevExt->SessionSpinlock);
842 RTSpinlockDestroy(pDevExt->EventSpinlock);
843 return rc;
844 }
845
846 /*
847 * Initialize the guest library and report the guest info back to VMMDev,
848 * set the interrupt control filter mask, and fixate the guest mappings
849 * made by the VMM.
850 */
851 rc = VbglInit(pDevExt->IOPortBase, (VMMDevMemory *)pDevExt->pVMMDevMemory);
852 if (RT_SUCCESS(rc))
853 {
854 rc = VbglGRAlloc((VMMDevRequestHeader **)&pDevExt->pIrqAckEvents, sizeof(VMMDevEvents), VMMDevReq_AcknowledgeEvents);
855 if (RT_SUCCESS(rc))
856 {
857 pDevExt->PhysIrqAckEvents = VbglPhysHeapGetPhysAddr(pDevExt->pIrqAckEvents);
858 Assert(pDevExt->PhysIrqAckEvents != 0);
859
860 rc = VBoxGuestReportGuestInfo(enmOSType);
861 if (RT_SUCCESS(rc))
862 {
863 rc = vboxGuestSetFilterMask(pDevExt, fFixedEvents);
864 if (RT_SUCCESS(rc))
865 {
866 /*
867 * Disable guest graphics capability by default. The guest specific
868 * graphics driver will re-enable this when it is necessary.
869 */
870 rc = VBoxGuestSetGuestCapabilities(0, VMMDEV_GUEST_SUPPORTS_GRAPHICS);
871 if (RT_SUCCESS(rc))
872 {
873 vboxGuestInitFixateGuestMappings(pDevExt);
874
875#ifdef DEBUG
876 testSetMouseStatus(); /* Other tests? */
877#endif
878
879 rc = VBoxGuestReportDriverStatus(true /* Driver is active */);
880 if (RT_FAILURE(rc))
881 LogRel(("VBoxGuestInitDevExt: VBoxReportGuestDriverStatus failed, rc=%Rrc\n", rc));
882
883 Log(("VBoxGuestInitDevExt: returns success\n"));
884 return VINF_SUCCESS;
885 }
886
887 LogRel(("VBoxGuestInitDevExt: VBoxGuestSetGuestCapabilities failed, rc=%Rrc\n", rc));
888 }
889 else
890 LogRel(("VBoxGuestInitDevExt: vboxGuestSetFilterMask failed, rc=%Rrc\n", rc));
891 }
892 else
893 LogRel(("VBoxGuestInitDevExt: VBoxReportGuestInfo failed, rc=%Rrc\n", rc));
894 VbglGRFree((VMMDevRequestHeader *)pDevExt->pIrqAckEvents);
895 }
896 else
897 LogRel(("VBoxGuestInitDevExt: VBoxGRAlloc failed, rc=%Rrc\n", rc));
898
899 VbglTerminate();
900 }
901 else
902 LogRel(("VBoxGuestInitDevExt: VbglInit failed, rc=%Rrc\n", rc));
903
904 rc2 = RTSemFastMutexDestroy(pDevExt->MemBalloon.hMtx); AssertRC(rc2);
905 rc2 = RTSpinlockDestroy(pDevExt->EventSpinlock); AssertRC(rc2);
906 rc2 = RTSpinlockDestroy(pDevExt->SessionSpinlock); AssertRC(rc2);
907 return rc; /* (failed) */
908}
909
910
911/**
912 * Deletes all the items in a wait chain.
913 * @param pList The head of the chain.
914 */
915static void VBoxGuestDeleteWaitList(PRTLISTNODE pList)
916{
917 while (!RTListIsEmpty(pList))
918 {
919 int rc2;
920 PVBOXGUESTWAIT pWait = RTListGetFirst(pList, VBOXGUESTWAIT, ListNode);
921 RTListNodeRemove(&pWait->ListNode);
922
923 rc2 = RTSemEventMultiDestroy(pWait->Event); AssertRC(rc2);
924 pWait->Event = NIL_RTSEMEVENTMULTI;
925 pWait->pSession = NULL;
926 RTMemFree(pWait);
927 }
928}
929
930
931/**
932 * Destroys the VBoxGuest device extension.
933 *
934 * The native code should call this before the driver is loaded,
935 * but don't call this on shutdown.
936 *
937 * @param pDevExt The device extension.
938 */
939void VBoxGuestDeleteDevExt(PVBOXGUESTDEVEXT pDevExt)
940{
941 int rc2;
942 Log(("VBoxGuestDeleteDevExt:\n"));
943 Log(("VBoxGuest: The additions driver is terminating.\n"));
944
945 /*
946 * Clean up the bits that involves the host first.
947 */
948 vboxGuestTermUnfixGuestMappings(pDevExt);
949 VBoxGuestSetGuestCapabilities(0, UINT32_MAX); /* clears all capabilities */
950 vboxGuestSetFilterMask(pDevExt, 0); /* filter all events */
951 vboxGuestCloseMemBalloon(pDevExt, (PVBOXGUESTSESSION)NULL);
952
953 /*
954 * Cleanup all the other resources.
955 */
956 rc2 = RTSpinlockDestroy(pDevExt->EventSpinlock); AssertRC(rc2);
957 rc2 = RTSpinlockDestroy(pDevExt->SessionSpinlock); AssertRC(rc2);
958 rc2 = RTSemFastMutexDestroy(pDevExt->MemBalloon.hMtx); AssertRC(rc2);
959
960 VBoxGuestDeleteWaitList(&pDevExt->WaitList);
961#ifdef VBOX_WITH_HGCM
962 VBoxGuestDeleteWaitList(&pDevExt->HGCMWaitList);
963#endif
964#ifdef VBOXGUEST_USE_DEFERRED_WAKE_UP
965 VBoxGuestDeleteWaitList(&pDevExt->WakeUpList);
966#endif
967 VBoxGuestDeleteWaitList(&pDevExt->WokenUpList);
968 VBoxGuestDeleteWaitList(&pDevExt->FreeList);
969
970 VbglTerminate();
971
972 pDevExt->pVMMDevMemory = NULL;
973
974 pDevExt->IOPortBase = 0;
975 pDevExt->pIrqAckEvents = NULL;
976}
977
978
979/**
980 * Creates a VBoxGuest user session.
981 *
982 * The native code calls this when a ring-3 client opens the device.
983 * Use VBoxGuestCreateKernelSession when a ring-0 client connects.
984 *
985 * @returns VBox status code.
986 * @param pDevExt The device extension.
987 * @param ppSession Where to store the session on success.
988 */
989int VBoxGuestCreateUserSession(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION *ppSession)
990{
991 PVBOXGUESTSESSION pSession = (PVBOXGUESTSESSION)RTMemAllocZ(sizeof(*pSession));
992 if (RT_UNLIKELY(!pSession))
993 {
994 LogRel(("VBoxGuestCreateUserSession: no memory!\n"));
995 return VERR_NO_MEMORY;
996 }
997
998 pSession->Process = RTProcSelf();
999 pSession->R0Process = RTR0ProcHandleSelf();
1000 pSession->pDevExt = pDevExt;
1001
1002 *ppSession = pSession;
1003 LogFlow(("VBoxGuestCreateUserSession: pSession=%p proc=%RTproc (%d) r0proc=%p\n",
1004 pSession, pSession->Process, (int)pSession->Process, (uintptr_t)pSession->R0Process)); /** @todo %RTr0proc */
1005 return VINF_SUCCESS;
1006}
1007
1008
1009/**
1010 * Creates a VBoxGuest kernel session.
1011 *
1012 * The native code calls this when a ring-0 client connects to the device.
1013 * Use VBoxGuestCreateUserSession when a ring-3 client opens the device.
1014 *
1015 * @returns VBox status code.
1016 * @param pDevExt The device extension.
1017 * @param ppSession Where to store the session on success.
1018 */
1019int VBoxGuestCreateKernelSession(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION *ppSession)
1020{
1021 PVBOXGUESTSESSION pSession = (PVBOXGUESTSESSION)RTMemAllocZ(sizeof(*pSession));
1022 if (RT_UNLIKELY(!pSession))
1023 {
1024 LogRel(("VBoxGuestCreateKernelSession: no memory!\n"));
1025 return VERR_NO_MEMORY;
1026 }
1027
1028 pSession->Process = NIL_RTPROCESS;
1029 pSession->R0Process = NIL_RTR0PROCESS;
1030 pSession->pDevExt = pDevExt;
1031
1032 *ppSession = pSession;
1033 LogFlow(("VBoxGuestCreateKernelSession: pSession=%p proc=%RTproc (%d) r0proc=%p\n",
1034 pSession, pSession->Process, (int)pSession->Process, (uintptr_t)pSession->R0Process)); /** @todo %RTr0proc */
1035 return VINF_SUCCESS;
1036}
1037
1038
1039
1040/**
1041 * Closes a VBoxGuest session.
1042 *
1043 * @param pDevExt The device extension.
1044 * @param pSession The session to close (and free).
1045 */
1046void VBoxGuestCloseSession(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession)
1047{
1048 unsigned i; NOREF(i);
1049 Log(("VBoxGuestCloseSession: pSession=%p proc=%RTproc (%d) r0proc=%p\n",
1050 pSession, pSession->Process, (int)pSession->Process, (uintptr_t)pSession->R0Process)); /** @todo %RTr0proc */
1051
1052 VBoxGuestCommonGuestCapsAcquire(pDevExt, pSession, 0, UINT32_MAX);
1053
1054#ifdef VBOX_WITH_HGCM
1055 for (i = 0; i < RT_ELEMENTS(pSession->aHGCMClientIds); i++)
1056 if (pSession->aHGCMClientIds[i])
1057 {
1058 VBoxGuestHGCMDisconnectInfo Info;
1059 Info.result = 0;
1060 Info.u32ClientID = pSession->aHGCMClientIds[i];
1061 pSession->aHGCMClientIds[i] = 0;
1062 Log(("VBoxGuestCloseSession: disconnecting client id %#RX32\n", Info.u32ClientID));
1063 VbglR0HGCMInternalDisconnect(&Info, VBoxGuestHGCMAsyncWaitCallback, pDevExt, RT_INDEFINITE_WAIT);
1064 }
1065#endif
1066
1067 pSession->pDevExt = NULL;
1068 pSession->Process = NIL_RTPROCESS;
1069 pSession->R0Process = NIL_RTR0PROCESS;
1070 vboxGuestCloseMemBalloon(pDevExt, pSession);
1071 /* Reset any mouse status flags which the session may have set. */
1072 VBoxGuestCommonIOCtl_SetMouseStatus(pDevExt, pSession, 0);
1073 RTMemFree(pSession);
1074}
1075
1076
1077/**
1078 * Allocates a wait-for-event entry.
1079 *
1080 * @returns The wait-for-event entry.
1081 * @param pDevExt The device extension.
1082 * @param pSession The session that's allocating this. Can be NULL.
1083 */
1084static PVBOXGUESTWAIT VBoxGuestWaitAlloc(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession)
1085{
1086 /*
1087 * Allocate it one way or the other.
1088 */
1089 PVBOXGUESTWAIT pWait = RTListGetFirst(&pDevExt->FreeList, VBOXGUESTWAIT, ListNode);
1090 if (pWait)
1091 {
1092 RTSpinlockAcquire(pDevExt->EventSpinlock);
1093
1094 pWait = RTListGetFirst(&pDevExt->FreeList, VBOXGUESTWAIT, ListNode);
1095 if (pWait)
1096 RTListNodeRemove(&pWait->ListNode);
1097
1098 RTSpinlockReleaseNoInts(pDevExt->EventSpinlock);
1099 }
1100 if (!pWait)
1101 {
1102 static unsigned s_cErrors = 0;
1103 int rc;
1104
1105 pWait = (PVBOXGUESTWAIT)RTMemAlloc(sizeof(*pWait));
1106 if (!pWait)
1107 {
1108 if (s_cErrors++ < 32)
1109 LogRel(("VBoxGuestWaitAlloc: out-of-memory!\n"));
1110 return NULL;
1111 }
1112
1113 rc = RTSemEventMultiCreate(&pWait->Event);
1114 if (RT_FAILURE(rc))
1115 {
1116 if (s_cErrors++ < 32)
1117 LogRel(("VBoxGuestCommonIOCtl: RTSemEventMultiCreate failed with rc=%Rrc!\n", rc));
1118 RTMemFree(pWait);
1119 return NULL;
1120 }
1121
1122 pWait->ListNode.pNext = NULL;
1123 pWait->ListNode.pPrev = NULL;
1124 }
1125
1126 /*
1127 * Zero members just as an precaution.
1128 */
1129 pWait->fReqEvents = 0;
1130 pWait->fResEvents = 0;
1131#ifdef VBOXGUEST_USE_DEFERRED_WAKE_UP
1132 pWait->fPendingWakeUp = false;
1133 pWait->fFreeMe = false;
1134#endif
1135 pWait->pSession = pSession;
1136#ifdef VBOX_WITH_HGCM
1137 pWait->pHGCMReq = NULL;
1138#endif
1139 RTSemEventMultiReset(pWait->Event);
1140 return pWait;
1141}
1142
1143
1144/**
1145 * Frees the wait-for-event entry.
1146 *
1147 * The caller must own the wait spinlock !
1148 * The entry must be in a list!
1149 *
1150 * @param pDevExt The device extension.
1151 * @param pWait The wait-for-event entry to free.
1152 */
1153static void VBoxGuestWaitFreeLocked(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTWAIT pWait)
1154{
1155 pWait->fReqEvents = 0;
1156 pWait->fResEvents = 0;
1157#ifdef VBOX_WITH_HGCM
1158 pWait->pHGCMReq = NULL;
1159#endif
1160#ifdef VBOXGUEST_USE_DEFERRED_WAKE_UP
1161 Assert(!pWait->fFreeMe);
1162 if (pWait->fPendingWakeUp)
1163 pWait->fFreeMe = true;
1164 else
1165#endif
1166 {
1167 RTListNodeRemove(&pWait->ListNode);
1168 RTListAppend(&pDevExt->FreeList, &pWait->ListNode);
1169 }
1170}
1171
1172
1173/**
1174 * Frees the wait-for-event entry.
1175 *
1176 * @param pDevExt The device extension.
1177 * @param pWait The wait-for-event entry to free.
1178 */
1179static void VBoxGuestWaitFreeUnlocked(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTWAIT pWait)
1180{
1181 RTSpinlockAcquire(pDevExt->EventSpinlock);
1182 VBoxGuestWaitFreeLocked(pDevExt, pWait);
1183 RTSpinlockReleaseNoInts(pDevExt->EventSpinlock);
1184}
1185
1186
1187#ifdef VBOXGUEST_USE_DEFERRED_WAKE_UP
1188/**
1189 * Processes the wake-up list.
1190 *
1191 * All entries in the wake-up list gets signalled and moved to the woken-up
1192 * list.
1193 *
1194 * @param pDevExt The device extension.
1195 */
1196void VBoxGuestWaitDoWakeUps(PVBOXGUESTDEVEXT pDevExt)
1197{
1198 if (!RTListIsEmpty(&pDevExt->WakeUpList))
1199 {
1200 RTSpinlockAcquire(pDevExt->EventSpinlock);
1201 for (;;)
1202 {
1203 int rc;
1204 PVBOXGUESTWAIT pWait = RTListGetFirst(&pDevExt->WakeUpList, VBOXGUESTWAIT, ListNode);
1205 if (!pWait)
1206 break;
1207 pWait->fPendingWakeUp = true;
1208 RTSpinlockReleaseNoInts(pDevExt->EventSpinlock);
1209
1210 rc = RTSemEventMultiSignal(pWait->Event);
1211 AssertRC(rc);
1212
1213 RTSpinlockAcquire(pDevExt->EventSpinlock);
1214 pWait->fPendingWakeUp = false;
1215 if (!pWait->fFreeMe)
1216 {
1217 RTListNodeRemove(&pWait->ListNode);
1218 RTListAppend(&pDevExt->WokenUpList, &pWait->ListNode);
1219 }
1220 else
1221 {
1222 pWait->fFreeMe = false;
1223 VBoxGuestWaitFreeLocked(pDevExt, pWait);
1224 }
1225 }
1226 RTSpinlockReleaseNoInts(pDevExt->EventSpinlock);
1227 }
1228}
1229#endif /* VBOXGUEST_USE_DEFERRED_WAKE_UP */
1230
1231
1232/**
1233 * Modifies the guest capabilities.
1234 *
1235 * Should be called during driver init and termination.
1236 *
1237 * @returns VBox status code.
1238 * @param fOr The Or mask (what to enable).
1239 * @param fNot The Not mask (what to disable).
1240 */
1241int VBoxGuestSetGuestCapabilities(uint32_t fOr, uint32_t fNot)
1242{
1243 VMMDevReqGuestCapabilities2 *pReq;
1244 int rc = VbglGRAlloc((VMMDevRequestHeader **)&pReq, sizeof(*pReq), VMMDevReq_SetGuestCapabilities);
1245 if (RT_FAILURE(rc))
1246 {
1247 Log(("VBoxGuestSetGuestCapabilities: failed to allocate %u (%#x) bytes to cache the request. rc=%Rrc!!\n",
1248 sizeof(*pReq), sizeof(*pReq), rc));
1249 return rc;
1250 }
1251
1252 pReq->u32OrMask = fOr;
1253 pReq->u32NotMask = fNot;
1254
1255 rc = VbglGRPerform(&pReq->header);
1256 if (RT_FAILURE(rc))
1257 Log(("VBoxGuestSetGuestCapabilities: VbglGRPerform failed, rc=%Rrc!\n", rc));
1258
1259 VbglGRFree(&pReq->header);
1260 return rc;
1261}
1262
1263
1264/**
1265 * Implements the fast (no input or output) type of IOCtls.
1266 *
1267 * This is currently just a placeholder stub inherited from the support driver code.
1268 *
1269 * @returns VBox status code.
1270 * @param iFunction The IOCtl function number.
1271 * @param pDevExt The device extension.
1272 * @param pSession The session.
1273 */
1274int VBoxGuestCommonIOCtlFast(unsigned iFunction, PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession)
1275{
1276 Log(("VBoxGuestCommonIOCtlFast: iFunction=%#x pDevExt=%p pSession=%p\n", iFunction, pDevExt, pSession));
1277
1278 NOREF(iFunction);
1279 NOREF(pDevExt);
1280 NOREF(pSession);
1281 return VERR_NOT_SUPPORTED;
1282}
1283
1284
1285/**
1286 * Return the VMM device port.
1287 *
1288 * returns IPRT status code.
1289 * @param pDevExt The device extension.
1290 * @param pInfo The request info.
1291 * @param pcbDataReturned (out) contains the number of bytes to return.
1292 */
1293static int VBoxGuestCommonIOCtl_GetVMMDevPort(PVBOXGUESTDEVEXT pDevExt, VBoxGuestPortInfo *pInfo, size_t *pcbDataReturned)
1294{
1295 Log(("VBoxGuestCommonIOCtl: GETVMMDEVPORT\n"));
1296 pInfo->portAddress = pDevExt->IOPortBase;
1297 pInfo->pVMMDevMemory = (VMMDevMemory *)pDevExt->pVMMDevMemory;
1298 if (pcbDataReturned)
1299 *pcbDataReturned = sizeof(*pInfo);
1300 return VINF_SUCCESS;
1301}
1302
1303
1304#ifndef RT_OS_WINDOWS
1305/**
1306 * Set the callback for the kernel mouse handler.
1307 *
1308 * returns IPRT status code.
1309 * @param pDevExt The device extension.
1310 * @param pNotify The new callback information.
1311 * @note This function takes the session spinlock to update the callback
1312 * information, but the interrupt handler will not do this. To make
1313 * sure that the interrupt handler sees a consistent structure, we
1314 * set the function pointer to NULL before updating the data and only
1315 * set it to the correct value once the data is updated. Since the
1316 * interrupt handler executes atomically this ensures that the data is
1317 * valid if the function pointer is non-NULL.
1318 */
1319int VBoxGuestCommonIOCtl_SetMouseNotifyCallback(PVBOXGUESTDEVEXT pDevExt, VBoxGuestMouseSetNotifyCallback *pNotify)
1320{
1321 Log(("VBoxGuestCommonIOCtl: SET_MOUSE_NOTIFY_CALLBACK\n"));
1322
1323 RTSpinlockAcquire(pDevExt->EventSpinlock);
1324 pDevExt->MouseNotifyCallback = *pNotify;
1325 RTSpinlockReleaseNoInts(pDevExt->EventSpinlock);
1326
1327 /* Make sure no active ISR is referencing the old data - hacky but should be
1328 * effective. */
1329 while (pDevExt->cISR > 0)
1330 ASMNopPause();
1331
1332 return VINF_SUCCESS;
1333}
1334#endif
1335
1336
1337/**
1338 * Worker VBoxGuestCommonIOCtl_WaitEvent.
1339 *
1340 * The caller enters the spinlock, we leave it.
1341 *
1342 * @returns VINF_SUCCESS if we've left the spinlock and can return immediately.
1343 */
1344DECLINLINE(int) WaitEventCheckCondition(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, VBoxGuestWaitEventInfo *pInfo,
1345 int iEvent, const uint32_t fReqEvents)
1346{
1347 uint32_t fMatches = VBoxGuestCommonGetAndCleanPendingEventsLocked(pDevExt, pSession, fReqEvents);
1348 if (fMatches)
1349 {
1350 RTSpinlockReleaseNoInts(pDevExt->EventSpinlock);
1351
1352 pInfo->u32EventFlagsOut = fMatches;
1353 pInfo->u32Result = VBOXGUEST_WAITEVENT_OK;
1354 if (fReqEvents & ~((uint32_t)1 << iEvent))
1355 Log(("VBoxGuestCommonIOCtl: WAITEVENT: returns %#x\n", pInfo->u32EventFlagsOut));
1356 else
1357 Log(("VBoxGuestCommonIOCtl: WAITEVENT: returns %#x/%d\n", pInfo->u32EventFlagsOut, iEvent));
1358 return VINF_SUCCESS;
1359 }
1360 RTSpinlockReleaseNoInts(pDevExt->EventSpinlock);
1361 return VERR_TIMEOUT;
1362}
1363
1364
1365static int VBoxGuestCommonIOCtl_WaitEvent(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession,
1366 VBoxGuestWaitEventInfo *pInfo, size_t *pcbDataReturned, bool fInterruptible)
1367{
1368 const uint32_t fReqEvents = pInfo->u32EventMaskIn;
1369 uint32_t fResEvents;
1370 int iEvent;
1371 PVBOXGUESTWAIT pWait;
1372 int rc;
1373
1374 pInfo->u32EventFlagsOut = 0;
1375 pInfo->u32Result = VBOXGUEST_WAITEVENT_ERROR;
1376 if (pcbDataReturned)
1377 *pcbDataReturned = sizeof(*pInfo);
1378
1379 /*
1380 * Copy and verify the input mask.
1381 */
1382 iEvent = ASMBitFirstSetU32(fReqEvents) - 1;
1383 if (RT_UNLIKELY(iEvent < 0))
1384 {
1385 Log(("VBoxGuestCommonIOCtl: WAITEVENT: Invalid input mask %#x!!\n", fReqEvents));
1386 return VERR_INVALID_PARAMETER;
1387 }
1388
1389 /*
1390 * Check the condition up front, before doing the wait-for-event allocations.
1391 */
1392 RTSpinlockAcquire(pDevExt->EventSpinlock);
1393 rc = WaitEventCheckCondition(pDevExt, pSession, pInfo, iEvent, fReqEvents);
1394 if (rc == VINF_SUCCESS)
1395 return rc;
1396
1397 if (!pInfo->u32TimeoutIn)
1398 {
1399 pInfo->u32Result = VBOXGUEST_WAITEVENT_TIMEOUT;
1400 Log(("VBoxGuestCommonIOCtl: WAITEVENT: returns VERR_TIMEOUT\n"));
1401 return VERR_TIMEOUT;
1402 }
1403
1404 pWait = VBoxGuestWaitAlloc(pDevExt, pSession);
1405 if (!pWait)
1406 return VERR_NO_MEMORY;
1407 pWait->fReqEvents = fReqEvents;
1408
1409 /*
1410 * We've got the wait entry now, re-enter the spinlock and check for the condition.
1411 * If the wait condition is met, return.
1412 * Otherwise enter into the list and go to sleep waiting for the ISR to signal us.
1413 */
1414 RTSpinlockAcquire(pDevExt->EventSpinlock);
1415 RTListAppend(&pDevExt->WaitList, &pWait->ListNode);
1416 rc = WaitEventCheckCondition(pDevExt, pSession, pInfo, iEvent, fReqEvents);
1417 if (rc == VINF_SUCCESS)
1418 {
1419 VBoxGuestWaitFreeUnlocked(pDevExt, pWait);
1420 return rc;
1421 }
1422
1423 if (fInterruptible)
1424 rc = RTSemEventMultiWaitNoResume(pWait->Event,
1425 pInfo->u32TimeoutIn == UINT32_MAX ? RT_INDEFINITE_WAIT : pInfo->u32TimeoutIn);
1426 else
1427 rc = RTSemEventMultiWait(pWait->Event,
1428 pInfo->u32TimeoutIn == UINT32_MAX ? RT_INDEFINITE_WAIT : pInfo->u32TimeoutIn);
1429
1430 /*
1431 * There is one special case here and that's when the semaphore is
1432 * destroyed upon device driver unload. This shouldn't happen of course,
1433 * but in case it does, just get out of here ASAP.
1434 */
1435 if (rc == VERR_SEM_DESTROYED)
1436 return rc;
1437
1438 /*
1439 * Unlink the wait item and dispose of it.
1440 */
1441 RTSpinlockAcquire(pDevExt->EventSpinlock);
1442 fResEvents = pWait->fResEvents;
1443 VBoxGuestWaitFreeLocked(pDevExt, pWait);
1444 RTSpinlockReleaseNoInts(pDevExt->EventSpinlock);
1445
1446 /*
1447 * Now deal with the return code.
1448 */
1449 if ( fResEvents
1450 && fResEvents != UINT32_MAX)
1451 {
1452 pInfo->u32EventFlagsOut = fResEvents;
1453 pInfo->u32Result = VBOXGUEST_WAITEVENT_OK;
1454 if (fReqEvents & ~((uint32_t)1 << iEvent))
1455 Log(("VBoxGuestCommonIOCtl: WAITEVENT: returns %#x\n", pInfo->u32EventFlagsOut));
1456 else
1457 Log(("VBoxGuestCommonIOCtl: WAITEVENT: returns %#x/%d\n", pInfo->u32EventFlagsOut, iEvent));
1458 rc = VINF_SUCCESS;
1459 }
1460 else if ( fResEvents == UINT32_MAX
1461 || rc == VERR_INTERRUPTED)
1462 {
1463 pInfo->u32Result = VBOXGUEST_WAITEVENT_INTERRUPTED;
1464 rc = VERR_INTERRUPTED;
1465 Log(("VBoxGuestCommonIOCtl: WAITEVENT: returns VERR_INTERRUPTED\n"));
1466 }
1467 else if (rc == VERR_TIMEOUT)
1468 {
1469 pInfo->u32Result = VBOXGUEST_WAITEVENT_TIMEOUT;
1470 Log(("VBoxGuestCommonIOCtl: WAITEVENT: returns VERR_TIMEOUT (2)\n"));
1471 }
1472 else
1473 {
1474 if (RT_SUCCESS(rc))
1475 {
1476 static unsigned s_cErrors = 0;
1477 if (s_cErrors++ < 32)
1478 LogRel(("VBoxGuestCommonIOCtl: WAITEVENT: returns %Rrc but no events!\n", rc));
1479 rc = VERR_INTERNAL_ERROR;
1480 }
1481 pInfo->u32Result = VBOXGUEST_WAITEVENT_ERROR;
1482 Log(("VBoxGuestCommonIOCtl: WAITEVENT: returns %Rrc\n", rc));
1483 }
1484
1485 return rc;
1486}
1487
1488
1489static int VBoxGuestCommonIOCtl_CancelAllWaitEvents(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession)
1490{
1491 PVBOXGUESTWAIT pWait;
1492 PVBOXGUESTWAIT pSafe;
1493 int rc = 0;
1494
1495 Log(("VBoxGuestCommonIOCtl: CANCEL_ALL_WAITEVENTS\n"));
1496
1497 /*
1498 * Walk the event list and wake up anyone with a matching session.
1499 */
1500 RTSpinlockAcquire(pDevExt->EventSpinlock);
1501 RTListForEachSafe(&pDevExt->WaitList, pWait, pSafe, VBOXGUESTWAIT, ListNode)
1502 {
1503 if (pWait->pSession == pSession)
1504 {
1505 pWait->fResEvents = UINT32_MAX;
1506 RTListNodeRemove(&pWait->ListNode);
1507#ifdef VBOXGUEST_USE_DEFERRED_WAKE_UP
1508 RTListAppend(&pDevExt->WakeUpList, &pWait->ListNode);
1509#else
1510 rc |= RTSemEventMultiSignal(pWait->Event);
1511 RTListAppend(&pDevExt->WokenUpList, &pWait->ListNode);
1512#endif
1513 }
1514 }
1515 RTSpinlockReleaseNoInts(pDevExt->EventSpinlock);
1516 Assert(rc == 0);
1517
1518#ifdef VBOXGUEST_USE_DEFERRED_WAKE_UP
1519 VBoxGuestWaitDoWakeUps(pDevExt);
1520#endif
1521
1522 return VINF_SUCCESS;
1523}
1524
1525/**
1526 * Checks if the VMM request is allowed in the context of the given session.
1527 *
1528 * @returns VINF_SUCCESS or VERR_PERMISSION_DENIED.
1529 * @param pSession The calling session.
1530 * @param enmType The request type.
1531 * @param pReqHdr The request.
1532 */
1533static int VBoxGuestCheckIfVMMReqAllowed(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, VMMDevRequestType enmType,
1534 VMMDevRequestHeader const *pReqHdr)
1535{
1536 /*
1537 * Categorize the request being made.
1538 */
1539 /** @todo This need quite some more work! */
1540 enum
1541 {
1542 kLevel_Invalid, kLevel_NoOne, kLevel_OnlyVBoxGuest, kLevel_OnlyKernel, kLevel_TrustedUsers, kLevel_AllUsers
1543 } enmRequired;
1544 switch (enmType)
1545 {
1546 /*
1547 * Deny access to anything we don't know or provide specialized I/O controls for.
1548 */
1549#ifdef VBOX_WITH_HGCM
1550 case VMMDevReq_HGCMConnect:
1551 case VMMDevReq_HGCMDisconnect:
1552# ifdef VBOX_WITH_64_BITS_GUESTS
1553 case VMMDevReq_HGCMCall32:
1554 case VMMDevReq_HGCMCall64:
1555# else
1556 case VMMDevReq_HGCMCall:
1557# endif /* VBOX_WITH_64_BITS_GUESTS */
1558 case VMMDevReq_HGCMCancel:
1559 case VMMDevReq_HGCMCancel2:
1560#endif /* VBOX_WITH_HGCM */
1561 default:
1562 enmRequired = kLevel_NoOne;
1563 break;
1564
1565 /*
1566 * There are a few things only this driver can do (and it doesn't use
1567 * the VMMRequst I/O control route anyway, but whatever).
1568 */
1569 case VMMDevReq_ReportGuestInfo:
1570 case VMMDevReq_ReportGuestInfo2:
1571 case VMMDevReq_GetHypervisorInfo:
1572 case VMMDevReq_SetHypervisorInfo:
1573 case VMMDevReq_RegisterPatchMemory:
1574 case VMMDevReq_DeregisterPatchMemory:
1575 case VMMDevReq_GetMemBalloonChangeRequest:
1576 enmRequired = kLevel_OnlyVBoxGuest;
1577 break;
1578
1579 /*
1580 * Trusted users apps only.
1581 */
1582 case VMMDevReq_QueryCredentials:
1583 case VMMDevReq_ReportCredentialsJudgement:
1584 case VMMDevReq_RegisterSharedModule:
1585 case VMMDevReq_UnregisterSharedModule:
1586 case VMMDevReq_WriteCoreDump:
1587 case VMMDevReq_GetCpuHotPlugRequest:
1588 case VMMDevReq_SetCpuHotPlugStatus:
1589 case VMMDevReq_CheckSharedModules:
1590 case VMMDevReq_GetPageSharingStatus:
1591 case VMMDevReq_DebugIsPageShared:
1592 case VMMDevReq_ReportGuestStats:
1593 case VMMDevReq_GetStatisticsChangeRequest:
1594 case VMMDevReq_ChangeMemBalloon:
1595 enmRequired = kLevel_TrustedUsers;
1596 break;
1597
1598 /*
1599 * Anyone. But not for CapsAcquire mode
1600 */
1601 case VMMDevReq_SetGuestCapabilities:
1602 {
1603 VMMDevReqGuestCapabilities2 *pCaps = (VMMDevReqGuestCapabilities2*)pReqHdr;
1604 uint32_t fAcquireCaps = 0;
1605 if (!VBoxGuestCommonGuestCapsModeSet(pDevExt, pCaps->u32OrMask, false, &fAcquireCaps))
1606 {
1607 AssertFailed();
1608 LogRel(("calling caps set for acquired caps %d\n", pCaps->u32OrMask));
1609 enmRequired = kLevel_NoOne;
1610 break;
1611 }
1612 /* hack to adjust the notcaps.
1613 * @todo: move to a better place
1614 * user-mode apps are allowed to pass any mask to the notmask,
1615 * the driver cleans up them accordingly */
1616 pCaps->u32NotMask &= ~fAcquireCaps;
1617 /* do not break, make it fall through to the below enmRequired setting */
1618 }
1619 /*
1620 * Anyone.
1621 */
1622 case VMMDevReq_GetMouseStatus:
1623 case VMMDevReq_SetMouseStatus:
1624 case VMMDevReq_SetPointerShape:
1625 case VMMDevReq_GetHostVersion:
1626 case VMMDevReq_Idle:
1627 case VMMDevReq_GetHostTime:
1628 case VMMDevReq_SetPowerStatus:
1629 case VMMDevReq_AcknowledgeEvents:
1630 case VMMDevReq_CtlGuestFilterMask:
1631 case VMMDevReq_ReportGuestStatus:
1632 case VMMDevReq_GetDisplayChangeRequest:
1633 case VMMDevReq_VideoModeSupported:
1634 case VMMDevReq_GetHeightReduction:
1635 case VMMDevReq_GetDisplayChangeRequest2:
1636 case VMMDevReq_VideoModeSupported2:
1637 case VMMDevReq_VideoAccelEnable:
1638 case VMMDevReq_VideoAccelFlush:
1639 case VMMDevReq_VideoSetVisibleRegion:
1640 case VMMDevReq_GetDisplayChangeRequestEx:
1641 case VMMDevReq_GetSeamlessChangeRequest:
1642 case VMMDevReq_GetVRDPChangeRequest:
1643 case VMMDevReq_LogString:
1644 case VMMDevReq_GetSessionId:
1645 enmRequired = kLevel_AllUsers;
1646 break;
1647
1648 /*
1649 * Depends on the request parameters...
1650 */
1651 /** @todo this have to be changed into an I/O control and the facilities
1652 * tracked in the session so they can automatically be failed when the
1653 * session terminates without reporting the new status.
1654 *
1655 * The information presented by IGuest is not reliable without this! */
1656 case VMMDevReq_ReportGuestCapabilities:
1657 switch (((VMMDevReportGuestStatus const *)pReqHdr)->guestStatus.facility)
1658 {
1659 case VBoxGuestFacilityType_All:
1660 case VBoxGuestFacilityType_VBoxGuestDriver:
1661 enmRequired = kLevel_OnlyVBoxGuest;
1662 break;
1663 case VBoxGuestFacilityType_VBoxService:
1664 enmRequired = kLevel_TrustedUsers;
1665 break;
1666 case VBoxGuestFacilityType_VBoxTrayClient:
1667 case VBoxGuestFacilityType_Seamless:
1668 case VBoxGuestFacilityType_Graphics:
1669 default:
1670 enmRequired = kLevel_AllUsers;
1671 break;
1672 }
1673 break;
1674 }
1675
1676 /*
1677 * Check against the session.
1678 */
1679 switch (enmRequired)
1680 {
1681 default:
1682 case kLevel_NoOne:
1683 break;
1684 case kLevel_OnlyVBoxGuest:
1685 case kLevel_OnlyKernel:
1686 if (pSession->R0Process == NIL_RTR0PROCESS)
1687 return VINF_SUCCESS;
1688 break;
1689 case kLevel_TrustedUsers:
1690 case kLevel_AllUsers:
1691 return VINF_SUCCESS;
1692 }
1693
1694 return VERR_PERMISSION_DENIED;
1695}
1696
1697static int VBoxGuestCommonIOCtl_VMMRequest(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession,
1698 VMMDevRequestHeader *pReqHdr, size_t cbData, size_t *pcbDataReturned)
1699{
1700 int rc;
1701 VMMDevRequestHeader *pReqCopy;
1702
1703 /*
1704 * Validate the header and request size.
1705 */
1706 const VMMDevRequestType enmType = pReqHdr->requestType;
1707 const uint32_t cbReq = pReqHdr->size;
1708 const uint32_t cbMinSize = vmmdevGetRequestSize(enmType);
1709
1710 Log(("VBoxGuestCommonIOCtl: VMMREQUEST type %d\n", pReqHdr->requestType));
1711
1712 if (cbReq < cbMinSize)
1713 {
1714 Log(("VBoxGuestCommonIOCtl: VMMREQUEST: invalid hdr size %#x, expected >= %#x; type=%#x!!\n",
1715 cbReq, cbMinSize, enmType));
1716 return VERR_INVALID_PARAMETER;
1717 }
1718 if (cbReq > cbData)
1719 {
1720 Log(("VBoxGuestCommonIOCtl: VMMREQUEST: invalid size %#x, expected >= %#x (hdr); type=%#x!!\n",
1721 cbData, cbReq, enmType));
1722 return VERR_INVALID_PARAMETER;
1723 }
1724 rc = VbglGRVerify(pReqHdr, cbData);
1725 if (RT_FAILURE(rc))
1726 {
1727 Log(("VBoxGuestCommonIOCtl: VMMREQUEST: invalid header: size %#x, expected >= %#x (hdr); type=%#x; rc=%Rrc!!\n",
1728 cbData, cbReq, enmType, rc));
1729 return rc;
1730 }
1731
1732 rc = VBoxGuestCheckIfVMMReqAllowed(pDevExt, pSession, enmType, pReqHdr);
1733 if (RT_FAILURE(rc))
1734 {
1735 Log(("VBoxGuestCommonIOCtl: VMMREQUEST: Operation not allowed! type=%#x rc=%Rrc\n", enmType, rc));
1736 return rc;
1737 }
1738
1739 /*
1740 * Make a copy of the request in the physical memory heap so
1741 * the VBoxGuestLibrary can more easily deal with the request.
1742 * (This is really a waste of time since the OS or the OS specific
1743 * code has already buffered or locked the input/output buffer, but
1744 * it does makes things a bit simpler wrt to phys address.)
1745 */
1746 rc = VbglGRAlloc(&pReqCopy, cbReq, enmType);
1747 if (RT_FAILURE(rc))
1748 {
1749 Log(("VBoxGuestCommonIOCtl: VMMREQUEST: failed to allocate %u (%#x) bytes to cache the request. rc=%Rrc!!\n",
1750 cbReq, cbReq, rc));
1751 return rc;
1752 }
1753 memcpy(pReqCopy, pReqHdr, cbReq);
1754
1755 if (enmType == VMMDevReq_GetMouseStatus) /* clear poll condition. */
1756 pSession->u32MousePosChangedSeq = ASMAtomicUoReadU32(&pDevExt->u32MousePosChangedSeq);
1757
1758 rc = VbglGRPerform(pReqCopy);
1759 if ( RT_SUCCESS(rc)
1760 && RT_SUCCESS(pReqCopy->rc))
1761 {
1762 Assert(rc != VINF_HGCM_ASYNC_EXECUTE);
1763 Assert(pReqCopy->rc != VINF_HGCM_ASYNC_EXECUTE);
1764
1765 memcpy(pReqHdr, pReqCopy, cbReq);
1766 if (pcbDataReturned)
1767 *pcbDataReturned = cbReq;
1768 }
1769 else if (RT_FAILURE(rc))
1770 Log(("VBoxGuestCommonIOCtl: VMMREQUEST: VbglGRPerform - rc=%Rrc!\n", rc));
1771 else
1772 {
1773 Log(("VBoxGuestCommonIOCtl: VMMREQUEST: request execution failed; VMMDev rc=%Rrc!\n", pReqCopy->rc));
1774 rc = pReqCopy->rc;
1775 }
1776
1777 VbglGRFree(pReqCopy);
1778 return rc;
1779}
1780
1781
1782static int VBoxGuestCommonIOCtl_CtlFilterMask(PVBOXGUESTDEVEXT pDevExt, VBoxGuestFilterMaskInfo *pInfo)
1783{
1784 VMMDevCtlGuestFilterMask *pReq;
1785 int rc = VbglGRAlloc((VMMDevRequestHeader **)&pReq, sizeof(*pReq), VMMDevReq_CtlGuestFilterMask);
1786 if (RT_FAILURE(rc))
1787 {
1788 Log(("VBoxGuestCommonIOCtl: CTL_FILTER_MASK: failed to allocate %u (%#x) bytes to cache the request. rc=%Rrc!!\n",
1789 sizeof(*pReq), sizeof(*pReq), rc));
1790 return rc;
1791 }
1792
1793 pReq->u32OrMask = pInfo->u32OrMask;
1794 pReq->u32NotMask = pInfo->u32NotMask;
1795 pReq->u32NotMask &= ~pDevExt->fFixedEvents; /* don't permit these to be cleared! */
1796 rc = VbglGRPerform(&pReq->header);
1797 if (RT_FAILURE(rc))
1798 Log(("VBoxGuestCommonIOCtl: CTL_FILTER_MASK: VbglGRPerform failed, rc=%Rrc!\n", rc));
1799
1800 VbglGRFree(&pReq->header);
1801 return rc;
1802}
1803
1804#ifdef VBOX_WITH_HGCM
1805
1806AssertCompile(RT_INDEFINITE_WAIT == (uint32_t)RT_INDEFINITE_WAIT); /* assumed by code below */
1807
1808/** Worker for VBoxGuestHGCMAsyncWaitCallback*. */
1809static int VBoxGuestHGCMAsyncWaitCallbackWorker(VMMDevHGCMRequestHeader volatile *pHdr, PVBOXGUESTDEVEXT pDevExt,
1810 bool fInterruptible, uint32_t cMillies)
1811{
1812 int rc;
1813
1814 /*
1815 * Check to see if the condition was met by the time we got here.
1816 *
1817 * We create a simple poll loop here for dealing with out-of-memory
1818 * conditions since the caller isn't necessarily able to deal with
1819 * us returning too early.
1820 */
1821 PVBOXGUESTWAIT pWait;
1822 for (;;)
1823 {
1824 RTSpinlockAcquire(pDevExt->EventSpinlock);
1825 if ((pHdr->fu32Flags & VBOX_HGCM_REQ_DONE) != 0)
1826 {
1827 RTSpinlockReleaseNoInts(pDevExt->EventSpinlock);
1828 return VINF_SUCCESS;
1829 }
1830 RTSpinlockReleaseNoInts(pDevExt->EventSpinlock);
1831
1832 pWait = VBoxGuestWaitAlloc(pDevExt, NULL);
1833 if (pWait)
1834 break;
1835 if (fInterruptible)
1836 return VERR_INTERRUPTED;
1837 RTThreadSleep(1);
1838 }
1839 pWait->fReqEvents = VMMDEV_EVENT_HGCM;
1840 pWait->pHGCMReq = pHdr;
1841
1842 /*
1843 * Re-enter the spinlock and re-check for the condition.
1844 * If the condition is met, return.
1845 * Otherwise link us into the HGCM wait list and go to sleep.
1846 */
1847 RTSpinlockAcquire(pDevExt->EventSpinlock);
1848 RTListAppend(&pDevExt->HGCMWaitList, &pWait->ListNode);
1849 if ((pHdr->fu32Flags & VBOX_HGCM_REQ_DONE) != 0)
1850 {
1851 VBoxGuestWaitFreeLocked(pDevExt, pWait);
1852 RTSpinlockReleaseNoInts(pDevExt->EventSpinlock);
1853 return VINF_SUCCESS;
1854 }
1855 RTSpinlockReleaseNoInts(pDevExt->EventSpinlock);
1856
1857 if (fInterruptible)
1858 rc = RTSemEventMultiWaitNoResume(pWait->Event, cMillies);
1859 else
1860 rc = RTSemEventMultiWait(pWait->Event, cMillies);
1861 if (rc == VERR_SEM_DESTROYED)
1862 return rc;
1863
1864 /*
1865 * Unlink, free and return.
1866 */
1867 if ( RT_FAILURE(rc)
1868 && rc != VERR_TIMEOUT
1869 && ( !fInterruptible
1870 || rc != VERR_INTERRUPTED))
1871 LogRel(("VBoxGuestHGCMAsyncWaitCallback: wait failed! %Rrc\n", rc));
1872
1873 VBoxGuestWaitFreeUnlocked(pDevExt, pWait);
1874 return rc;
1875}
1876
1877
1878/**
1879 * This is a callback for dealing with async waits.
1880 *
1881 * It operates in a manner similar to VBoxGuestCommonIOCtl_WaitEvent.
1882 */
1883static DECLCALLBACK(int) VBoxGuestHGCMAsyncWaitCallback(VMMDevHGCMRequestHeader *pHdr, void *pvUser, uint32_t u32User)
1884{
1885 PVBOXGUESTDEVEXT pDevExt = (PVBOXGUESTDEVEXT)pvUser;
1886 Log(("VBoxGuestHGCMAsyncWaitCallback: requestType=%d\n", pHdr->header.requestType));
1887 return VBoxGuestHGCMAsyncWaitCallbackWorker((VMMDevHGCMRequestHeader volatile *)pHdr,
1888 pDevExt,
1889 false /* fInterruptible */,
1890 u32User /* cMillies */);
1891}
1892
1893
1894/**
1895 * This is a callback for dealing with async waits with a timeout.
1896 *
1897 * It operates in a manner similar to VBoxGuestCommonIOCtl_WaitEvent.
1898 */
1899static DECLCALLBACK(int) VBoxGuestHGCMAsyncWaitCallbackInterruptible(VMMDevHGCMRequestHeader *pHdr,
1900 void *pvUser, uint32_t u32User)
1901{
1902 PVBOXGUESTDEVEXT pDevExt = (PVBOXGUESTDEVEXT)pvUser;
1903 Log(("VBoxGuestHGCMAsyncWaitCallbackInterruptible: requestType=%d\n", pHdr->header.requestType));
1904 return VBoxGuestHGCMAsyncWaitCallbackWorker((VMMDevHGCMRequestHeader volatile *)pHdr,
1905 pDevExt,
1906 true /* fInterruptible */,
1907 u32User /* cMillies */ );
1908
1909}
1910
1911
1912static int VBoxGuestCommonIOCtl_HGCMConnect(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession,
1913 VBoxGuestHGCMConnectInfo *pInfo, size_t *pcbDataReturned)
1914{
1915 int rc;
1916
1917 /*
1918 * The VbglHGCMConnect call will invoke the callback if the HGCM
1919 * call is performed in an ASYNC fashion. The function is not able
1920 * to deal with cancelled requests.
1921 */
1922 Log(("VBoxGuestCommonIOCtl: HGCM_CONNECT: %.128s\n",
1923 pInfo->Loc.type == VMMDevHGCMLoc_LocalHost || pInfo->Loc.type == VMMDevHGCMLoc_LocalHost_Existing
1924 ? pInfo->Loc.u.host.achName : "<not local host>"));
1925
1926 rc = VbglR0HGCMInternalConnect(pInfo, VBoxGuestHGCMAsyncWaitCallback, pDevExt, RT_INDEFINITE_WAIT);
1927 if (RT_SUCCESS(rc))
1928 {
1929 Log(("VBoxGuestCommonIOCtl: HGCM_CONNECT: u32Client=%RX32 result=%Rrc (rc=%Rrc)\n",
1930 pInfo->u32ClientID, pInfo->result, rc));
1931 if (RT_SUCCESS(pInfo->result))
1932 {
1933 /*
1934 * Append the client id to the client id table.
1935 * If the table has somehow become filled up, we'll disconnect the session.
1936 */
1937 unsigned i;
1938 RTSpinlockAcquire(pDevExt->SessionSpinlock);
1939 for (i = 0; i < RT_ELEMENTS(pSession->aHGCMClientIds); i++)
1940 if (!pSession->aHGCMClientIds[i])
1941 {
1942 pSession->aHGCMClientIds[i] = pInfo->u32ClientID;
1943 break;
1944 }
1945 RTSpinlockReleaseNoInts(pDevExt->SessionSpinlock);
1946 if (i >= RT_ELEMENTS(pSession->aHGCMClientIds))
1947 {
1948 static unsigned s_cErrors = 0;
1949 VBoxGuestHGCMDisconnectInfo Info;
1950
1951 if (s_cErrors++ < 32)
1952 LogRel(("VBoxGuestCommonIOCtl: HGCM_CONNECT: too many HGCMConnect calls for one session!\n"));
1953
1954 Info.result = 0;
1955 Info.u32ClientID = pInfo->u32ClientID;
1956 VbglR0HGCMInternalDisconnect(&Info, VBoxGuestHGCMAsyncWaitCallback, pDevExt, RT_INDEFINITE_WAIT);
1957 return VERR_TOO_MANY_OPEN_FILES;
1958 }
1959 }
1960 if (pcbDataReturned)
1961 *pcbDataReturned = sizeof(*pInfo);
1962 }
1963 return rc;
1964}
1965
1966
1967static int VBoxGuestCommonIOCtl_HGCMDisconnect(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, VBoxGuestHGCMDisconnectInfo *pInfo,
1968 size_t *pcbDataReturned)
1969{
1970 /*
1971 * Validate the client id and invalidate its entry while we're in the call.
1972 */
1973 int rc;
1974 const uint32_t u32ClientId = pInfo->u32ClientID;
1975 unsigned i;
1976 RTSpinlockAcquire(pDevExt->SessionSpinlock);
1977 for (i = 0; i < RT_ELEMENTS(pSession->aHGCMClientIds); i++)
1978 if (pSession->aHGCMClientIds[i] == u32ClientId)
1979 {
1980 pSession->aHGCMClientIds[i] = UINT32_MAX;
1981 break;
1982 }
1983 RTSpinlockReleaseNoInts(pDevExt->SessionSpinlock);
1984 if (i >= RT_ELEMENTS(pSession->aHGCMClientIds))
1985 {
1986 static unsigned s_cErrors = 0;
1987 if (s_cErrors++ > 32)
1988 LogRel(("VBoxGuestCommonIOCtl: HGCM_DISCONNECT: u32Client=%RX32\n", u32ClientId));
1989 return VERR_INVALID_HANDLE;
1990 }
1991
1992 /*
1993 * The VbglHGCMConnect call will invoke the callback if the HGCM
1994 * call is performed in an ASYNC fashion. The function is not able
1995 * to deal with cancelled requests.
1996 */
1997 Log(("VBoxGuestCommonIOCtl: HGCM_DISCONNECT: u32Client=%RX32\n", pInfo->u32ClientID));
1998 rc = VbglR0HGCMInternalDisconnect(pInfo, VBoxGuestHGCMAsyncWaitCallback, pDevExt, RT_INDEFINITE_WAIT);
1999 if (RT_SUCCESS(rc))
2000 {
2001 Log(("VBoxGuestCommonIOCtl: HGCM_DISCONNECT: result=%Rrc\n", pInfo->result));
2002 if (pcbDataReturned)
2003 *pcbDataReturned = sizeof(*pInfo);
2004 }
2005
2006 /* Update the client id array according to the result. */
2007 RTSpinlockAcquire(pDevExt->SessionSpinlock);
2008 if (pSession->aHGCMClientIds[i] == UINT32_MAX)
2009 pSession->aHGCMClientIds[i] = RT_SUCCESS(rc) && RT_SUCCESS(pInfo->result) ? 0 : u32ClientId;
2010 RTSpinlockReleaseNoInts(pDevExt->SessionSpinlock);
2011
2012 return rc;
2013}
2014
2015
2016static int VBoxGuestCommonIOCtl_HGCMCall(PVBOXGUESTDEVEXT pDevExt,
2017 PVBOXGUESTSESSION pSession,
2018 VBoxGuestHGCMCallInfo *pInfo,
2019 uint32_t cMillies, bool fInterruptible, bool f32bit, bool fUserData,
2020 size_t cbExtra, size_t cbData, size_t *pcbDataReturned)
2021{
2022 const uint32_t u32ClientId = pInfo->u32ClientID;
2023 uint32_t fFlags;
2024 size_t cbActual;
2025 unsigned i;
2026 int rc;
2027
2028 /*
2029 * Some more validations.
2030 */
2031 if (pInfo->cParms > 4096) /* (Just make sure it doesn't overflow the next check.) */
2032 {
2033 LogRel(("VBoxGuestCommonIOCtl: HGCM_CALL: cParm=%RX32 is not sane\n", pInfo->cParms));
2034 return VERR_INVALID_PARAMETER;
2035 }
2036
2037 cbActual = cbExtra + sizeof(*pInfo);
2038#ifdef RT_ARCH_AMD64
2039 if (f32bit)
2040 cbActual += pInfo->cParms * sizeof(HGCMFunctionParameter32);
2041 else
2042#endif
2043 cbActual += pInfo->cParms * sizeof(HGCMFunctionParameter);
2044 if (cbData < cbActual)
2045 {
2046 LogRel(("VBoxGuestCommonIOCtl: HGCM_CALL: cbData=%#zx (%zu) required size is %#zx (%zu)\n",
2047 cbData, cbActual));
2048 return VERR_INVALID_PARAMETER;
2049 }
2050
2051 /*
2052 * Validate the client id.
2053 */
2054 RTSpinlockAcquire(pDevExt->SessionSpinlock);
2055 for (i = 0; i < RT_ELEMENTS(pSession->aHGCMClientIds); i++)
2056 if (pSession->aHGCMClientIds[i] == u32ClientId)
2057 break;
2058 RTSpinlockReleaseNoInts(pDevExt->SessionSpinlock);
2059 if (RT_UNLIKELY(i >= RT_ELEMENTS(pSession->aHGCMClientIds)))
2060 {
2061 static unsigned s_cErrors = 0;
2062 if (s_cErrors++ > 32)
2063 LogRel(("VBoxGuestCommonIOCtl: HGCM_CALL: Invalid handle. u32Client=%RX32\n", u32ClientId));
2064 return VERR_INVALID_HANDLE;
2065 }
2066
2067 /*
2068 * The VbglHGCMCall call will invoke the callback if the HGCM
2069 * call is performed in an ASYNC fashion. This function can
2070 * deal with cancelled requests, so we let user more requests
2071 * be interruptible (should add a flag for this later I guess).
2072 */
2073 Log(("VBoxGuestCommonIOCtl: HGCM_CALL: u32Client=%RX32\n", pInfo->u32ClientID));
2074 fFlags = !fUserData && pSession->R0Process == NIL_RTR0PROCESS ? VBGLR0_HGCMCALL_F_KERNEL : VBGLR0_HGCMCALL_F_USER;
2075#ifdef RT_ARCH_AMD64
2076 if (f32bit)
2077 {
2078 if (fInterruptible)
2079 rc = VbglR0HGCMInternalCall32(pInfo, cbData - cbExtra, fFlags, VBoxGuestHGCMAsyncWaitCallbackInterruptible, pDevExt, cMillies);
2080 else
2081 rc = VbglR0HGCMInternalCall32(pInfo, cbData - cbExtra, fFlags, VBoxGuestHGCMAsyncWaitCallback, pDevExt, cMillies);
2082 }
2083 else
2084#endif
2085 {
2086 if (fInterruptible)
2087 rc = VbglR0HGCMInternalCall(pInfo, cbData - cbExtra, fFlags, VBoxGuestHGCMAsyncWaitCallbackInterruptible, pDevExt, cMillies);
2088 else
2089 rc = VbglR0HGCMInternalCall(pInfo, cbData - cbExtra, fFlags, VBoxGuestHGCMAsyncWaitCallback, pDevExt, cMillies);
2090 }
2091 if (RT_SUCCESS(rc))
2092 {
2093 Log(("VBoxGuestCommonIOCtl: HGCM_CALL: result=%Rrc\n", pInfo->result));
2094 if (pcbDataReturned)
2095 *pcbDataReturned = cbActual;
2096 }
2097 else
2098 {
2099 if ( rc != VERR_INTERRUPTED
2100 && rc != VERR_TIMEOUT)
2101 {
2102 static unsigned s_cErrors = 0;
2103 if (s_cErrors++ < 32)
2104 LogRel(("VBoxGuestCommonIOCtl: HGCM_CALL: %s Failed. rc=%Rrc.\n", f32bit ? "32" : "64", rc));
2105 }
2106 else
2107 Log(("VBoxGuestCommonIOCtl: HGCM_CALL: %s Failed. rc=%Rrc.\n", f32bit ? "32" : "64", rc));
2108 }
2109 return rc;
2110}
2111
2112
2113#endif /* VBOX_WITH_HGCM */
2114
2115/**
2116 * Handle VBOXGUEST_IOCTL_CHECK_BALLOON from R3.
2117 *
2118 * Ask the host for the size of the balloon and try to set it accordingly. If
2119 * this approach fails because it's not supported, return with fHandleInR3 set
2120 * and let the user land supply memory we can lock via the other ioctl.
2121 *
2122 * @returns VBox status code.
2123 *
2124 * @param pDevExt The device extension.
2125 * @param pSession The session.
2126 * @param pInfo The output buffer.
2127 * @param pcbDataReturned Where to store the amount of returned data. Can
2128 * be NULL.
2129 */
2130static int VBoxGuestCommonIOCtl_CheckMemoryBalloon(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession,
2131 VBoxGuestCheckBalloonInfo *pInfo, size_t *pcbDataReturned)
2132{
2133 VMMDevGetMemBalloonChangeRequest *pReq;
2134 int rc;
2135
2136 Log(("VBoxGuestCommonIOCtl: CHECK_MEMORY_BALLOON\n"));
2137 rc = RTSemFastMutexRequest(pDevExt->MemBalloon.hMtx);
2138 AssertRCReturn(rc, rc);
2139
2140 /*
2141 * The first user trying to query/change the balloon becomes the
2142 * owner and owns it until the session is closed (vboxGuestCloseMemBalloon).
2143 */
2144 if ( pDevExt->MemBalloon.pOwner != pSession
2145 && pDevExt->MemBalloon.pOwner == NULL)
2146 pDevExt->MemBalloon.pOwner = pSession;
2147
2148 if (pDevExt->MemBalloon.pOwner == pSession)
2149 {
2150 rc = VbglGRAlloc((VMMDevRequestHeader **)&pReq, sizeof(VMMDevGetMemBalloonChangeRequest), VMMDevReq_GetMemBalloonChangeRequest);
2151 if (RT_SUCCESS(rc))
2152 {
2153 /*
2154 * This is a response to that event. Setting this bit means that
2155 * we request the value from the host and change the guest memory
2156 * balloon according to this value.
2157 */
2158 pReq->eventAck = VMMDEV_EVENT_BALLOON_CHANGE_REQUEST;
2159 rc = VbglGRPerform(&pReq->header);
2160 if (RT_SUCCESS(rc))
2161 {
2162 Assert(pDevExt->MemBalloon.cMaxChunks == pReq->cPhysMemChunks || pDevExt->MemBalloon.cMaxChunks == 0);
2163 pDevExt->MemBalloon.cMaxChunks = pReq->cPhysMemChunks;
2164
2165 pInfo->cBalloonChunks = pReq->cBalloonChunks;
2166 pInfo->fHandleInR3 = false;
2167
2168 rc = vboxGuestSetBalloonSizeKernel(pDevExt, pReq->cBalloonChunks, &pInfo->fHandleInR3);
2169 /* Ignore various out of memory failures. */
2170 if ( rc == VERR_NO_MEMORY
2171 || rc == VERR_NO_PHYS_MEMORY
2172 || rc == VERR_NO_CONT_MEMORY)
2173 rc = VINF_SUCCESS;
2174
2175 if (pcbDataReturned)
2176 *pcbDataReturned = sizeof(VBoxGuestCheckBalloonInfo);
2177 }
2178 else
2179 LogRel(("VBoxGuestCommonIOCtl: CHECK_MEMORY_BALLOON: VbglGRPerform failed. rc=%Rrc\n", rc));
2180 VbglGRFree(&pReq->header);
2181 }
2182 }
2183 else
2184 rc = VERR_PERMISSION_DENIED;
2185
2186 RTSemFastMutexRelease(pDevExt->MemBalloon.hMtx);
2187 Log(("VBoxGuestCommonIOCtl: CHECK_MEMORY_BALLOON returns %Rrc\n", rc));
2188 return rc;
2189}
2190
2191
2192/**
2193 * Handle a request for changing the memory balloon.
2194 *
2195 * @returns VBox status code.
2196 *
2197 * @param pDevExt The device extention.
2198 * @param pSession The session.
2199 * @param pInfo The change request structure (input).
2200 * @param pcbDataReturned Where to store the amount of returned data. Can
2201 * be NULL.
2202 */
2203static int VBoxGuestCommonIOCtl_ChangeMemoryBalloon(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession,
2204 VBoxGuestChangeBalloonInfo *pInfo, size_t *pcbDataReturned)
2205{
2206 int rc = RTSemFastMutexRequest(pDevExt->MemBalloon.hMtx);
2207 AssertRCReturn(rc, rc);
2208
2209 if (!pDevExt->MemBalloon.fUseKernelAPI)
2210 {
2211 /*
2212 * The first user trying to query/change the balloon becomes the
2213 * owner and owns it until the session is closed (vboxGuestCloseMemBalloon).
2214 */
2215 if ( pDevExt->MemBalloon.pOwner != pSession
2216 && pDevExt->MemBalloon.pOwner == NULL)
2217 pDevExt->MemBalloon.pOwner = pSession;
2218
2219 if (pDevExt->MemBalloon.pOwner == pSession)
2220 {
2221 rc = vboxGuestSetBalloonSizeFromUser(pDevExt, pSession, pInfo->u64ChunkAddr, !!pInfo->fInflate);
2222 if (pcbDataReturned)
2223 *pcbDataReturned = 0;
2224 }
2225 else
2226 rc = VERR_PERMISSION_DENIED;
2227 }
2228 else
2229 rc = VERR_PERMISSION_DENIED;
2230
2231 RTSemFastMutexRelease(pDevExt->MemBalloon.hMtx);
2232 return rc;
2233}
2234
2235
2236/**
2237 * Handle a request for writing a core dump of the guest on the host.
2238 *
2239 * @returns VBox status code.
2240 *
2241 * @param pDevExt The device extension.
2242 * @param pInfo The output buffer.
2243 */
2244static int VBoxGuestCommonIOCtl_WriteCoreDump(PVBOXGUESTDEVEXT pDevExt, VBoxGuestWriteCoreDump *pInfo)
2245{
2246 VMMDevReqWriteCoreDump *pReq = NULL;
2247 int rc = VbglGRAlloc((VMMDevRequestHeader **)&pReq, sizeof(*pReq), VMMDevReq_WriteCoreDump);
2248 if (RT_FAILURE(rc))
2249 {
2250 Log(("VBoxGuestCommonIOCtl: WRITE_CORE_DUMP: failed to allocate %u (%#x) bytes to cache the request. rc=%Rrc!!\n",
2251 sizeof(*pReq), sizeof(*pReq), rc));
2252 return rc;
2253 }
2254
2255 pReq->fFlags = pInfo->fFlags;
2256 rc = VbglGRPerform(&pReq->header);
2257 if (RT_FAILURE(rc))
2258 Log(("VBoxGuestCommonIOCtl: WRITE_CORE_DUMP: VbglGRPerform failed, rc=%Rrc!\n", rc));
2259
2260 VbglGRFree(&pReq->header);
2261 return rc;
2262}
2263
2264
2265#ifdef VBOX_WITH_VRDP_SESSION_HANDLING
2266/**
2267 * Enables the VRDP session and saves its session ID.
2268 *
2269 * @returns VBox status code.
2270 *
2271 * @param pDevExt The device extention.
2272 * @param pSession The session.
2273 */
2274static int VBoxGuestCommonIOCtl_EnableVRDPSession(VBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession)
2275{
2276 /* Nothing to do here right now, since this only is supported on Windows at the moment. */
2277 return VERR_NOT_IMPLEMENTED;
2278}
2279
2280
2281/**
2282 * Disables the VRDP session.
2283 *
2284 * @returns VBox status code.
2285 *
2286 * @param pDevExt The device extention.
2287 * @param pSession The session.
2288 */
2289static int VBoxGuestCommonIOCtl_DisableVRDPSession(VBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession)
2290{
2291 /* Nothing to do here right now, since this only is supported on Windows at the moment. */
2292 return VERR_NOT_IMPLEMENTED;
2293}
2294#endif /* VBOX_WITH_VRDP_SESSION_HANDLING */
2295
2296#ifdef DEBUG
2297/** Unit test SetMouseStatus instead of really executing the request. */
2298static bool g_test_fSetMouseStatus = false;
2299/** When unit testing SetMouseStatus, the fake RC for the GR to return. */
2300static int g_test_SetMouseStatusGRRC;
2301/** When unit testing SetMouseStatus this will be set to the status passed to
2302 * the GR. */
2303static uint32_t g_test_statusSetMouseStatus;
2304#endif
2305
2306static int vboxguestcommonSetMouseStatus(uint32_t fFeatures)
2307{
2308 VMMDevReqMouseStatus *pReq;
2309 int rc;
2310
2311 LogRelFlowFunc(("fFeatures=%u\n", (int) fFeatures));
2312 rc = VbglGRAlloc((VMMDevRequestHeader **)&pReq, sizeof(*pReq), VMMDevReq_SetMouseStatus);
2313 if (RT_SUCCESS(rc))
2314 {
2315 pReq->mouseFeatures = fFeatures;
2316 pReq->pointerXPos = 0;
2317 pReq->pointerYPos = 0;
2318#ifdef DEBUG
2319 if (g_test_fSetMouseStatus)
2320 {
2321 g_test_statusSetMouseStatus = pReq->mouseFeatures;
2322 rc = g_test_SetMouseStatusGRRC;
2323 }
2324 else
2325#endif
2326 rc = VbglGRPerform(&pReq->header);
2327 VbglGRFree(&pReq->header);
2328 }
2329 LogRelFlowFunc(("rc=%Rrc\n", rc));
2330 return rc;
2331}
2332
2333
2334/**
2335 * Sets the mouse status features for this session and updates them
2336 * globally. We aim to ensure that if several threads call this in
2337 * parallel the most recent status will always end up being set.
2338 *
2339 * @returns VBox status code.
2340 *
2341 * @param pDevExt The device extention.
2342 * @param pSession The session.
2343 * @param fFeatures New bitmap of enabled features.
2344 */
2345static int VBoxGuestCommonIOCtl_SetMouseStatus(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, uint32_t fFeatures)
2346{
2347 uint32_t fNewDevExtStatus = 0;
2348 unsigned i;
2349 int rc;
2350 /* Exit early if nothing has changed - hack to work around the
2351 * Windows Additions not using the common code. */
2352 bool fNoAction;
2353
2354 RTSpinlockAcquire(pDevExt->SessionSpinlock);
2355
2356 /* For all the bits which the guest is allowed to set, check whether the
2357 * requested value is different to the current one and adjust the global
2358 * usage counter and if appropriate the global state if so. */
2359 for (i = 0; i < sizeof(fFeatures) * 8; i++)
2360 {
2361 if (RT_BIT_32(i) & VMMDEV_MOUSE_GUEST_MASK)
2362 {
2363 if ( (RT_BIT_32(i) & fFeatures)
2364 && !(RT_BIT_32(i) & pSession->fMouseStatus))
2365 pDevExt->acMouseFeatureUsage[i]++;
2366 else if ( !(RT_BIT_32(i) & fFeatures)
2367 && (RT_BIT_32(i) & pSession->fMouseStatus))
2368 pDevExt->acMouseFeatureUsage[i]--;
2369 }
2370 if (pDevExt->acMouseFeatureUsage[i] > 0)
2371 fNewDevExtStatus |= RT_BIT_32(i);
2372 }
2373
2374 pSession->fMouseStatus = fFeatures & VMMDEV_MOUSE_GUEST_MASK;
2375 fNoAction = (pDevExt->fMouseStatus == fNewDevExtStatus);
2376 pDevExt->fMouseStatus = fNewDevExtStatus;
2377
2378 RTSpinlockReleaseNoInts(pDevExt->SessionSpinlock);
2379 if (fNoAction)
2380 return VINF_SUCCESS;
2381
2382 do
2383 {
2384 fNewDevExtStatus = pDevExt->fMouseStatus;
2385 rc = vboxguestcommonSetMouseStatus(fNewDevExtStatus);
2386 } while ( RT_SUCCESS(rc)
2387 && fNewDevExtStatus != pDevExt->fMouseStatus);
2388
2389 return rc;
2390}
2391
2392
2393#ifdef DEBUG
2394/** Unit test for the SET_MOUSE_STATUS IoCtl. Since this is closely tied to
2395 * the code in question it probably makes most sense to keep it next to the
2396 * code. */
2397static void testSetMouseStatus(void)
2398{
2399 uint32_t u32Data;
2400 int rc;
2401 RTSPINLOCK Spinlock;
2402
2403 g_test_fSetMouseStatus = true;
2404 rc = RTSpinlockCreate(&Spinlock, RTSPINLOCK_FLAGS_INTERRUPT_SAFE, "VBoxGuestTest");
2405 AssertRCReturnVoid(rc);
2406 {
2407 VBOXGUESTDEVEXT DevExt = { 0 };
2408 VBOXGUESTSESSION Session = { 0 };
2409
2410 g_test_statusSetMouseStatus = ~0;
2411 g_test_SetMouseStatusGRRC = VINF_SUCCESS;
2412 DevExt.SessionSpinlock = Spinlock;
2413 u32Data = VMMDEV_MOUSE_GUEST_CAN_ABSOLUTE;
2414 rc = VBoxGuestCommonIOCtl(VBOXGUEST_IOCTL_SET_MOUSE_STATUS, &DevExt,
2415 &Session, &u32Data, sizeof(u32Data), NULL);
2416 AssertRCSuccess(rc);
2417 AssertMsg( g_test_statusSetMouseStatus
2418 == VMMDEV_MOUSE_GUEST_CAN_ABSOLUTE,
2419 ("Actual status: 0x%x\n", g_test_statusSetMouseStatus));
2420 DevExt.acMouseFeatureUsage[ASMBitFirstSetU32(VMMDEV_MOUSE_GUEST_NEEDS_HOST_CURSOR) - 1] = 1;
2421 rc = VBoxGuestCommonIOCtl(VBOXGUEST_IOCTL_SET_MOUSE_STATUS, &DevExt,
2422 &Session, &u32Data, sizeof(u32Data), NULL);
2423 AssertRCSuccess(rc);
2424 AssertMsg( g_test_statusSetMouseStatus
2425 == ( VMMDEV_MOUSE_GUEST_CAN_ABSOLUTE
2426 | VMMDEV_MOUSE_GUEST_NEEDS_HOST_CURSOR),
2427 ("Actual status: 0x%x\n", g_test_statusSetMouseStatus));
2428 u32Data = VMMDEV_MOUSE_HOST_WANTS_ABSOLUTE; /* Can't change this */
2429 rc = VBoxGuestCommonIOCtl(VBOXGUEST_IOCTL_SET_MOUSE_STATUS, &DevExt,
2430 &Session, &u32Data, sizeof(u32Data), NULL);
2431 AssertRCSuccess(rc);
2432 AssertMsg( g_test_statusSetMouseStatus
2433 == VMMDEV_MOUSE_GUEST_NEEDS_HOST_CURSOR,
2434 ("Actual status: 0x%x\n", g_test_statusSetMouseStatus));
2435 u32Data = VMMDEV_MOUSE_GUEST_NEEDS_HOST_CURSOR;
2436 rc = VBoxGuestCommonIOCtl(VBOXGUEST_IOCTL_SET_MOUSE_STATUS, &DevExt,
2437 &Session, &u32Data, sizeof(u32Data), NULL);
2438 AssertRCSuccess(rc);
2439 AssertMsg( g_test_statusSetMouseStatus
2440 == VMMDEV_MOUSE_GUEST_NEEDS_HOST_CURSOR,
2441 ("Actual status: 0x%x\n", g_test_statusSetMouseStatus));
2442 u32Data = 0;
2443 rc = VBoxGuestCommonIOCtl(VBOXGUEST_IOCTL_SET_MOUSE_STATUS, &DevExt,
2444 &Session, &u32Data, sizeof(u32Data), NULL);
2445 AssertRCSuccess(rc);
2446 AssertMsg( g_test_statusSetMouseStatus
2447 == VMMDEV_MOUSE_GUEST_NEEDS_HOST_CURSOR,
2448 ("Actual status: 0x%x\n", g_test_statusSetMouseStatus));
2449 AssertMsg(DevExt.acMouseFeatureUsage[ASMBitFirstSetU32(VMMDEV_MOUSE_GUEST_NEEDS_HOST_CURSOR) - 1] == 1,
2450 ("Actual value: %d\n", DevExt.acMouseFeatureUsage[ASMBitFirstSetU32(VMMDEV_MOUSE_GUEST_NEEDS_HOST_CURSOR)]));
2451 g_test_SetMouseStatusGRRC = VERR_UNRESOLVED_ERROR;
2452 /* This should succeed as the host request should not be made
2453 * since nothing has changed. */
2454 rc = VBoxGuestCommonIOCtl(VBOXGUEST_IOCTL_SET_MOUSE_STATUS, &DevExt,
2455 &Session, &u32Data, sizeof(u32Data), NULL);
2456 AssertRCSuccess(rc);
2457 /* This should fail with VERR_UNRESOLVED_ERROR as set above. */
2458 u32Data = VMMDEV_MOUSE_GUEST_CAN_ABSOLUTE;
2459 rc = VBoxGuestCommonIOCtl(VBOXGUEST_IOCTL_SET_MOUSE_STATUS, &DevExt,
2460 &Session, &u32Data, sizeof(u32Data), NULL);
2461 AssertMsg(rc == VERR_UNRESOLVED_ERROR, ("rc == %Rrc\n", rc));
2462 /* Untested paths: out of memory; race setting status to host */
2463 }
2464 RTSpinlockDestroy(Spinlock);
2465 g_test_fSetMouseStatus = false;
2466}
2467#endif
2468
2469
2470/**
2471 * Guest backdoor logging.
2472 *
2473 * @returns VBox status code.
2474 *
2475 * @param pDevExt The device extension.
2476 * @param pch The log message (need not be NULL terminated).
2477 * @param cbData Size of the buffer.
2478 * @param pcbDataReturned Where to store the amount of returned data. Can be NULL.
2479 */
2480static int VBoxGuestCommonIOCtl_Log(PVBOXGUESTDEVEXT pDevExt, const char *pch, size_t cbData, size_t *pcbDataReturned)
2481{
2482 NOREF(pch);
2483 NOREF(cbData);
2484 if (pDevExt->fLoggingEnabled)
2485 RTLogBackdoorPrintf("%.*s", cbData, pch);
2486 else
2487 Log(("%.*s", cbData, pch));
2488 if (pcbDataReturned)
2489 *pcbDataReturned = 0;
2490 return VINF_SUCCESS;
2491}
2492
2493static bool VBoxGuestCommonGuestCapsValidateValues(uint32_t fCaps)
2494{
2495 if (fCaps & (~(VMMDEV_GUEST_SUPPORTS_SEAMLESS | VMMDEV_GUEST_SUPPORTS_GUEST_HOST_WINDOW_MAPPING | VMMDEV_GUEST_SUPPORTS_GRAPHICS)))
2496 {
2497 LogRel(("VBoxGuestCommonGuestCapsValidateValues: invalid guest caps 0x%x\n", fCaps));
2498 return false;
2499 }
2500 return true;
2501}
2502
2503static void VBoxGuestCommonCheckEvents(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, uint32_t fGenFakeEvents)
2504{
2505 RTSpinlockAcquire(pDevExt->EventSpinlock);
2506 uint32_t fEvents = fGenFakeEvents | pDevExt->f32PendingEvents;
2507 PVBOXGUESTWAIT pWait;
2508 PVBOXGUESTWAIT pSafe;
2509
2510 RTListForEachSafe(&pDevExt->WaitList, pWait, pSafe, VBOXGUESTWAIT, ListNode)
2511 {
2512 uint32_t fHandledEvents = VBoxGuestCommonGetHandledEventsLocked(pDevExt, pWait->pSession);
2513 if ( (pWait->fReqEvents & fEvents & fHandledEvents)
2514 && !pWait->fResEvents)
2515 {
2516 pWait->fResEvents = pWait->fReqEvents & fEvents & fHandledEvents;
2517 Assert(!(fGenFakeEvents & pWait->fResEvents) || pSession == pWait->pSession);
2518 fEvents &= ~pWait->fResEvents;
2519 RTListNodeRemove(&pWait->ListNode);
2520#ifdef VBOXGUEST_USE_DEFERRED_WAKE_UP
2521 RTListAppend(&pDevExt->WakeUpList, &pWait->ListNode);
2522#else
2523 RTListAppend(&pDevExt->WokenUpList, &pWait->ListNode);
2524 rc |= RTSemEventMultiSignal(pWait->Event);
2525#endif
2526 if (!fEvents)
2527 break;
2528 }
2529 }
2530 ASMAtomicWriteU32(&pDevExt->f32PendingEvents, fEvents);
2531
2532 RTSpinlockReleaseNoInts(pDevExt->EventSpinlock);
2533
2534#ifdef VBOXGUEST_USE_DEFERRED_WAKE_UP
2535 VBoxGuestWaitDoWakeUps(pDevExt);
2536#endif
2537}
2538
2539static int VBoxGuestCommonGuestCapsAcquire(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, uint32_t fOrMask, uint32_t fNotMask)
2540{
2541 uint32_t fSetCaps = 0;
2542 if (!VBoxGuestCommonGuestCapsModeSet(pDevExt, fOrMask, true, &fSetCaps))
2543 {
2544 Assert(0);
2545 LogRel(("calling caps acquire for set caps %d\n", fOrMask));
2546 return VERR_INVALID_STATE;
2547 }
2548
2549 /* user-mode apps are allowed to pass any mask to the notmask,
2550 * the driver cleans up them accordingly */
2551 fNotMask &= ~fSetCaps;
2552
2553 if (!VBoxGuestCommonGuestCapsValidateValues(fOrMask))
2554 return VERR_INVALID_PARAMETER;
2555
2556 /* the fNotMask no need to have all values valid,
2557 * invalid ones will simply be ignored */
2558 uint32_t fCurrentOwnedCaps;
2559 uint32_t fSessionNotCaps;
2560 uint32_t fSessionOrCaps;
2561 uint32_t fOtherConflictingCaps;
2562
2563 fNotMask &= ~fOrMask;
2564
2565 RTSpinlockAcquire(pDevExt->EventSpinlock);
2566
2567 fCurrentOwnedCaps = pSession->u32AquiredGuestCaps;
2568 fSessionNotCaps = fCurrentOwnedCaps & fNotMask;
2569 fSessionOrCaps = fOrMask & ~fCurrentOwnedCaps;
2570 fOtherConflictingCaps = pDevExt->u32GuestCaps & ~fCurrentOwnedCaps;
2571 fOtherConflictingCaps &= fSessionOrCaps;
2572
2573 if (!fOtherConflictingCaps)
2574 {
2575 if (fSessionOrCaps)
2576 {
2577 pSession->u32AquiredGuestCaps |= fSessionOrCaps;
2578 pDevExt->u32GuestCaps |= fSessionOrCaps;
2579 }
2580
2581 if (fSessionNotCaps)
2582 {
2583 pSession->u32AquiredGuestCaps &= ~fSessionNotCaps;
2584 pDevExt->u32GuestCaps &= ~fSessionNotCaps;
2585 }
2586 }
2587
2588 RTSpinlockReleaseNoInts(pDevExt->EventSpinlock);
2589
2590 if (fOtherConflictingCaps)
2591 {
2592 Log(("VBoxGuest: Caps 0x%x were busy\n", fOtherConflictingCaps));
2593 return VERR_RESOURCE_BUSY;
2594 }
2595
2596 /* now do host notification outside the lock */
2597 if (!fSessionOrCaps && !fSessionNotCaps)
2598 {
2599 /* no changes, return */
2600 return VINF_SUCCESS;
2601 }
2602
2603 int rc = VBoxGuestSetGuestCapabilities(fSessionOrCaps, fSessionNotCaps);
2604 if (!RT_SUCCESS(rc))
2605 {
2606 /* Failure branch
2607 * this is generally bad since e.g. failure to release the caps may result in other sessions not being able to use it
2608 * so we are not trying to restore the caps back to their values before the VBoxGuestCommonGuestCapsAcquire call,
2609 * but just pretend everithing is OK.
2610 * @todo: better failure handling mechanism? */
2611 }
2612
2613 /* success! */
2614 uint32_t fGenFakeEvents = 0;
2615
2616 if (fSessionOrCaps & VMMDEV_GUEST_SUPPORTS_SEAMLESS)
2617 {
2618 /* generate the seamless change event so that the r3 app could synch with the seamless state
2619 * although this introduces a false alarming of r3 client, it still solve the problem of
2620 * client state inconsistency in multiuser environment */
2621 fGenFakeEvents |= VMMDEV_EVENT_SEAMLESS_MODE_CHANGE_REQUEST;
2622 }
2623
2624 /* since the acquire filter mask has changed, we need to process events in any way to ensure they go from pending events field
2625 * to the proper (un-filtered) entries */
2626 VBoxGuestCommonCheckEvents(pDevExt, pSession, fGenFakeEvents);
2627
2628 return VINF_SUCCESS;
2629}
2630
2631static int VBoxGuestCommonIOCTL_GuestCapsAcquire(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, VBoxGuestCapsAquire *pAcquire)
2632{
2633 int rc = VBoxGuestCommonGuestCapsAcquire(pDevExt, pSession, pAcquire->u32OrMask, pAcquire->u32NotMask);
2634 if (!RT_SUCCESS(rc))
2635 LogRel(("VBoxGuestCommonGuestCapsAcquire: failed rc %d\n", rc));
2636 pAcquire->rc = rc;
2637 return VINF_SUCCESS;
2638}
2639
2640
2641/**
2642 * Common IOCtl for user to kernel and kernel to kernel communication.
2643 *
2644 * This function only does the basic validation and then invokes
2645 * worker functions that takes care of each specific function.
2646 *
2647 * @returns VBox status code.
2648 *
2649 * @param iFunction The requested function.
2650 * @param pDevExt The device extension.
2651 * @param pSession The client session.
2652 * @param pvData The input/output data buffer. Can be NULL depending on the function.
2653 * @param cbData The max size of the data buffer.
2654 * @param pcbDataReturned Where to store the amount of returned data. Can be NULL.
2655 */
2656int VBoxGuestCommonIOCtl(unsigned iFunction, PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession,
2657 void *pvData, size_t cbData, size_t *pcbDataReturned)
2658{
2659 int rc;
2660 Log(("VBoxGuestCommonIOCtl: iFunction=%#x pDevExt=%p pSession=%p pvData=%p cbData=%zu\n",
2661 iFunction, pDevExt, pSession, pvData, cbData));
2662
2663 /*
2664 * Make sure the returned data size is set to zero.
2665 */
2666 if (pcbDataReturned)
2667 *pcbDataReturned = 0;
2668
2669 /*
2670 * Define some helper macros to simplify validation.
2671 */
2672#define CHECKRET_RING0(mnemonic) \
2673 do { \
2674 if (pSession->R0Process != NIL_RTR0PROCESS) \
2675 { \
2676 LogFunc((mnemonic ": Ring-0 only, caller is %RTproc/%p\n", \
2677 pSession->Process, (uintptr_t)pSession->R0Process)); \
2678 return VERR_PERMISSION_DENIED; \
2679 } \
2680 } while (0)
2681#define CHECKRET_MIN_SIZE(mnemonic, cbMin) \
2682 do { \
2683 if (cbData < (cbMin)) \
2684 { \
2685 LogFunc((mnemonic ": cbData=%#zx (%zu) min is %#zx (%zu)\n", \
2686 cbData, cbData, (size_t)(cbMin), (size_t)(cbMin))); \
2687 return VERR_BUFFER_OVERFLOW; \
2688 } \
2689 if ((cbMin) != 0 && !VALID_PTR(pvData)) \
2690 { \
2691 LogFunc((mnemonic ": Invalid pointer %p\n", pvData)); \
2692 return VERR_INVALID_POINTER; \
2693 } \
2694 } while (0)
2695#define CHECKRET_SIZE(mnemonic, cb) \
2696 do { \
2697 if (cbData != (cb)) \
2698 { \
2699 LogFunc((mnemonic ": cbData=%#zx (%zu) expected is %#zx (%zu)\n", \
2700 cbData, cbData, (size_t)(cb), (size_t)(cb))); \
2701 return VERR_BUFFER_OVERFLOW; \
2702 } \
2703 if ((cb) != 0 && !VALID_PTR(pvData)) \
2704 { \
2705 LogFunc((mnemonic ": Invalid pointer %p\n", pvData)); \
2706 return VERR_INVALID_POINTER; \
2707 } \
2708 } while (0)
2709
2710
2711 /*
2712 * Deal with variably sized requests first.
2713 */
2714 rc = VINF_SUCCESS;
2715 if (VBOXGUEST_IOCTL_STRIP_SIZE(iFunction) == VBOXGUEST_IOCTL_STRIP_SIZE(VBOXGUEST_IOCTL_VMMREQUEST(0)))
2716 {
2717 CHECKRET_MIN_SIZE("VMMREQUEST", sizeof(VMMDevRequestHeader));
2718 rc = VBoxGuestCommonIOCtl_VMMRequest(pDevExt, pSession, (VMMDevRequestHeader *)pvData, cbData, pcbDataReturned);
2719 }
2720#ifdef VBOX_WITH_HGCM
2721 /*
2722 * These ones are a bit tricky.
2723 */
2724 else if (VBOXGUEST_IOCTL_STRIP_SIZE(iFunction) == VBOXGUEST_IOCTL_STRIP_SIZE(VBOXGUEST_IOCTL_HGCM_CALL(0)))
2725 {
2726 bool fInterruptible = pSession->R0Process != NIL_RTR0PROCESS;
2727 CHECKRET_MIN_SIZE("HGCM_CALL", sizeof(VBoxGuestHGCMCallInfo));
2728 rc = VBoxGuestCommonIOCtl_HGCMCall(pDevExt, pSession, (VBoxGuestHGCMCallInfo *)pvData, RT_INDEFINITE_WAIT,
2729 fInterruptible, false /*f32bit*/, false /* fUserData */,
2730 0, cbData, pcbDataReturned);
2731 }
2732 else if (VBOXGUEST_IOCTL_STRIP_SIZE(iFunction) == VBOXGUEST_IOCTL_STRIP_SIZE(VBOXGUEST_IOCTL_HGCM_CALL_TIMED(0)))
2733 {
2734 VBoxGuestHGCMCallInfoTimed *pInfo = (VBoxGuestHGCMCallInfoTimed *)pvData;
2735 CHECKRET_MIN_SIZE("HGCM_CALL_TIMED", sizeof(VBoxGuestHGCMCallInfoTimed));
2736 rc = VBoxGuestCommonIOCtl_HGCMCall(pDevExt, pSession, &pInfo->info, pInfo->u32Timeout,
2737 !!pInfo->fInterruptible || pSession->R0Process != NIL_RTR0PROCESS,
2738 false /*f32bit*/, false /* fUserData */,
2739 RT_OFFSETOF(VBoxGuestHGCMCallInfoTimed, info), cbData, pcbDataReturned);
2740 }
2741 else if (VBOXGUEST_IOCTL_STRIP_SIZE(iFunction) == VBOXGUEST_IOCTL_STRIP_SIZE(VBOXGUEST_IOCTL_HGCM_CALL_USERDATA(0)))
2742 {
2743 bool fInterruptible = true;
2744 CHECKRET_MIN_SIZE("HGCM_CALL", sizeof(VBoxGuestHGCMCallInfo));
2745 rc = VBoxGuestCommonIOCtl_HGCMCall(pDevExt, pSession, (VBoxGuestHGCMCallInfo *)pvData, RT_INDEFINITE_WAIT,
2746 fInterruptible, false /*f32bit*/, true /* fUserData */,
2747 0, cbData, pcbDataReturned);
2748 }
2749# ifdef RT_ARCH_AMD64
2750 else if (VBOXGUEST_IOCTL_STRIP_SIZE(iFunction) == VBOXGUEST_IOCTL_STRIP_SIZE(VBOXGUEST_IOCTL_HGCM_CALL_32(0)))
2751 {
2752 bool fInterruptible = pSession->R0Process != NIL_RTR0PROCESS;
2753 CHECKRET_MIN_SIZE("HGCM_CALL", sizeof(VBoxGuestHGCMCallInfo));
2754 rc = VBoxGuestCommonIOCtl_HGCMCall(pDevExt, pSession, (VBoxGuestHGCMCallInfo *)pvData, RT_INDEFINITE_WAIT,
2755 fInterruptible, true /*f32bit*/, false /* fUserData */,
2756 0, cbData, pcbDataReturned);
2757 }
2758 else if (VBOXGUEST_IOCTL_STRIP_SIZE(iFunction) == VBOXGUEST_IOCTL_STRIP_SIZE(VBOXGUEST_IOCTL_HGCM_CALL_TIMED_32(0)))
2759 {
2760 CHECKRET_MIN_SIZE("HGCM_CALL_TIMED", sizeof(VBoxGuestHGCMCallInfoTimed));
2761 VBoxGuestHGCMCallInfoTimed *pInfo = (VBoxGuestHGCMCallInfoTimed *)pvData;
2762 rc = VBoxGuestCommonIOCtl_HGCMCall(pDevExt, pSession, &pInfo->info, pInfo->u32Timeout,
2763 !!pInfo->fInterruptible || pSession->R0Process != NIL_RTR0PROCESS,
2764 true /*f32bit*/, false /* fUserData */,
2765 RT_OFFSETOF(VBoxGuestHGCMCallInfoTimed, info), cbData, pcbDataReturned);
2766 }
2767# endif
2768#endif /* VBOX_WITH_HGCM */
2769 else if (VBOXGUEST_IOCTL_STRIP_SIZE(iFunction) == VBOXGUEST_IOCTL_STRIP_SIZE(VBOXGUEST_IOCTL_LOG(0)))
2770 {
2771 CHECKRET_MIN_SIZE("LOG", 1);
2772 rc = VBoxGuestCommonIOCtl_Log(pDevExt, (char *)pvData, cbData, pcbDataReturned);
2773 }
2774 else
2775 {
2776 switch (iFunction)
2777 {
2778 case VBOXGUEST_IOCTL_GETVMMDEVPORT:
2779 CHECKRET_RING0("GETVMMDEVPORT");
2780 CHECKRET_MIN_SIZE("GETVMMDEVPORT", sizeof(VBoxGuestPortInfo));
2781 rc = VBoxGuestCommonIOCtl_GetVMMDevPort(pDevExt, (VBoxGuestPortInfo *)pvData, pcbDataReturned);
2782 break;
2783
2784#ifndef RT_OS_WINDOWS /* Windows has its own implementation of this. */
2785 case VBOXGUEST_IOCTL_SET_MOUSE_NOTIFY_CALLBACK:
2786 CHECKRET_RING0("SET_MOUSE_NOTIFY_CALLBACK");
2787 CHECKRET_SIZE("SET_MOUSE_NOTIFY_CALLBACK", sizeof(VBoxGuestMouseSetNotifyCallback));
2788 rc = VBoxGuestCommonIOCtl_SetMouseNotifyCallback(pDevExt, (VBoxGuestMouseSetNotifyCallback *)pvData);
2789 break;
2790#endif
2791
2792 case VBOXGUEST_IOCTL_WAITEVENT:
2793 CHECKRET_MIN_SIZE("WAITEVENT", sizeof(VBoxGuestWaitEventInfo));
2794 rc = VBoxGuestCommonIOCtl_WaitEvent(pDevExt, pSession, (VBoxGuestWaitEventInfo *)pvData,
2795 pcbDataReturned, pSession->R0Process != NIL_RTR0PROCESS);
2796 break;
2797
2798 case VBOXGUEST_IOCTL_CANCEL_ALL_WAITEVENTS:
2799 if (cbData != 0)
2800 rc = VERR_INVALID_PARAMETER;
2801 rc = VBoxGuestCommonIOCtl_CancelAllWaitEvents(pDevExt, pSession);
2802 break;
2803
2804 case VBOXGUEST_IOCTL_CTL_FILTER_MASK:
2805 CHECKRET_MIN_SIZE("CTL_FILTER_MASK", sizeof(VBoxGuestFilterMaskInfo));
2806 rc = VBoxGuestCommonIOCtl_CtlFilterMask(pDevExt, (VBoxGuestFilterMaskInfo *)pvData);
2807 break;
2808
2809#ifdef VBOX_WITH_HGCM
2810 case VBOXGUEST_IOCTL_HGCM_CONNECT:
2811# ifdef RT_ARCH_AMD64
2812 case VBOXGUEST_IOCTL_HGCM_CONNECT_32:
2813# endif
2814 CHECKRET_MIN_SIZE("HGCM_CONNECT", sizeof(VBoxGuestHGCMConnectInfo));
2815 rc = VBoxGuestCommonIOCtl_HGCMConnect(pDevExt, pSession, (VBoxGuestHGCMConnectInfo *)pvData, pcbDataReturned);
2816 break;
2817
2818 case VBOXGUEST_IOCTL_HGCM_DISCONNECT:
2819# ifdef RT_ARCH_AMD64
2820 case VBOXGUEST_IOCTL_HGCM_DISCONNECT_32:
2821# endif
2822 CHECKRET_MIN_SIZE("HGCM_DISCONNECT", sizeof(VBoxGuestHGCMDisconnectInfo));
2823 rc = VBoxGuestCommonIOCtl_HGCMDisconnect(pDevExt, pSession, (VBoxGuestHGCMDisconnectInfo *)pvData, pcbDataReturned);
2824 break;
2825#endif /* VBOX_WITH_HGCM */
2826
2827 case VBOXGUEST_IOCTL_CHECK_BALLOON:
2828 CHECKRET_MIN_SIZE("CHECK_MEMORY_BALLOON", sizeof(VBoxGuestCheckBalloonInfo));
2829 rc = VBoxGuestCommonIOCtl_CheckMemoryBalloon(pDevExt, pSession, (VBoxGuestCheckBalloonInfo *)pvData, pcbDataReturned);
2830 break;
2831
2832 case VBOXGUEST_IOCTL_CHANGE_BALLOON:
2833 CHECKRET_MIN_SIZE("CHANGE_MEMORY_BALLOON", sizeof(VBoxGuestChangeBalloonInfo));
2834 rc = VBoxGuestCommonIOCtl_ChangeMemoryBalloon(pDevExt, pSession, (VBoxGuestChangeBalloonInfo *)pvData, pcbDataReturned);
2835 break;
2836
2837 case VBOXGUEST_IOCTL_WRITE_CORE_DUMP:
2838 CHECKRET_MIN_SIZE("WRITE_CORE_DUMP", sizeof(VBoxGuestWriteCoreDump));
2839 rc = VBoxGuestCommonIOCtl_WriteCoreDump(pDevExt, (VBoxGuestWriteCoreDump *)pvData);
2840 break;
2841
2842#ifdef VBOX_WITH_VRDP_SESSION_HANDLING
2843 case VBOXGUEST_IOCTL_ENABLE_VRDP_SESSION:
2844 rc = VBoxGuestCommonIOCtl_EnableVRDPSession(pDevExt, pSession);
2845 break;
2846
2847 case VBOXGUEST_IOCTL_DISABLE_VRDP_SESSION:
2848 rc = VBoxGuestCommonIOCtl_DisableVRDPSession(pDevExt, pSession);
2849 break;
2850#endif /* VBOX_WITH_VRDP_SESSION_HANDLING */
2851 case VBOXGUEST_IOCTL_SET_MOUSE_STATUS:
2852 CHECKRET_SIZE("SET_MOUSE_STATUS", sizeof(uint32_t));
2853 rc = VBoxGuestCommonIOCtl_SetMouseStatus(pDevExt, pSession,
2854 *(uint32_t *)pvData);
2855 break;
2856
2857#ifdef VBOX_WITH_DPC_LATENCY_CHECKER
2858 case VBOXGUEST_IOCTL_DPC_LATENCY_CHECKER:
2859 CHECKRET_SIZE("DPC_LATENCY_CHECKER", 0);
2860 rc = VbgdNtIOCtl_DpcLatencyChecker();
2861 break;
2862#endif
2863
2864 case VBOXGUEST_IOCTL_GUEST_CAPS_ACQUIRE:
2865 CHECKRET_SIZE("GUEST_CAPS_ACQUIRE", sizeof(VBoxGuestCapsAquire));
2866 rc = VBoxGuestCommonIOCTL_GuestCapsAcquire(pDevExt, pSession, (VBoxGuestCapsAquire*)pvData);
2867 *pcbDataReturned = sizeof(VBoxGuestCapsAquire);
2868 break;
2869
2870 default:
2871 {
2872 LogRel(("VBoxGuestCommonIOCtl: Unknown request iFunction=%#x Stripped size=%#x\n", iFunction,
2873 VBOXGUEST_IOCTL_STRIP_SIZE(iFunction)));
2874 rc = VERR_NOT_SUPPORTED;
2875 break;
2876 }
2877 }
2878 }
2879
2880 Log(("VBoxGuestCommonIOCtl: returns %Rrc *pcbDataReturned=%zu\n", rc, pcbDataReturned ? *pcbDataReturned : 0));
2881 return rc;
2882}
2883
2884
2885
2886/**
2887 * Common interrupt service routine.
2888 *
2889 * This deals with events and with waking up thread waiting for those events.
2890 *
2891 * @returns true if it was our interrupt, false if it wasn't.
2892 * @param pDevExt The VBoxGuest device extension.
2893 */
2894bool VBoxGuestCommonISR(PVBOXGUESTDEVEXT pDevExt)
2895{
2896#ifndef RT_OS_WINDOWS
2897 VBoxGuestMouseSetNotifyCallback MouseNotifyCallback = { NULL, NULL };
2898#endif
2899 bool fMousePositionChanged = false;
2900 VMMDevEvents volatile *pReq = pDevExt->pIrqAckEvents;
2901 int rc = 0;
2902 bool fOurIrq;
2903
2904 /*
2905 * Make sure we've initialized the device extension.
2906 */
2907 if (RT_UNLIKELY(!pReq))
2908 return false;
2909
2910 /*
2911 * Enter the spinlock, increase the ISR count and check if it's our IRQ or
2912 * not.
2913 */
2914 RTSpinlockAcquire(pDevExt->EventSpinlock);
2915 ASMAtomicIncU32(&pDevExt->cISR);
2916 fOurIrq = pDevExt->pVMMDevMemory->V.V1_04.fHaveEvents;
2917 if (fOurIrq)
2918 {
2919 /*
2920 * Acknowlegde events.
2921 * We don't use VbglGRPerform here as it may take another spinlocks.
2922 */
2923 pReq->header.rc = VERR_INTERNAL_ERROR;
2924 pReq->events = 0;
2925 ASMCompilerBarrier();
2926 ASMOutU32(pDevExt->IOPortBase + VMMDEV_PORT_OFF_REQUEST, (uint32_t)pDevExt->PhysIrqAckEvents);
2927 ASMCompilerBarrier(); /* paranoia */
2928 if (RT_SUCCESS(pReq->header.rc))
2929 {
2930 uint32_t fEvents = pReq->events;
2931 PVBOXGUESTWAIT pWait;
2932 PVBOXGUESTWAIT pSafe;
2933
2934 Log(("VBoxGuestCommonISR: acknowledge events succeeded %#RX32\n", fEvents));
2935
2936 /*
2937 * VMMDEV_EVENT_MOUSE_POSITION_CHANGED can only be polled for.
2938 */
2939 if (fEvents & VMMDEV_EVENT_MOUSE_POSITION_CHANGED)
2940 {
2941#ifndef RT_OS_WINDOWS
2942 MouseNotifyCallback = pDevExt->MouseNotifyCallback;
2943#endif
2944 fMousePositionChanged = true;
2945 fEvents &= ~VMMDEV_EVENT_MOUSE_POSITION_CHANGED;
2946 }
2947
2948#ifdef VBOX_WITH_HGCM
2949 /*
2950 * The HGCM event/list is kind of different in that we evaluate all entries.
2951 */
2952 if (fEvents & VMMDEV_EVENT_HGCM)
2953 {
2954 RTListForEachSafe(&pDevExt->HGCMWaitList, pWait, pSafe, VBOXGUESTWAIT, ListNode)
2955 {
2956 if (pWait->pHGCMReq->fu32Flags & VBOX_HGCM_REQ_DONE)
2957 {
2958 pWait->fResEvents = VMMDEV_EVENT_HGCM;
2959 RTListNodeRemove(&pWait->ListNode);
2960# ifdef VBOXGUEST_USE_DEFERRED_WAKE_UP
2961 RTListAppend(&pDevExt->WakeUpList, &pWait->ListNode);
2962# else
2963 RTListAppend(&pDevExt->WokenUpList, &pWait->ListNode);
2964 rc |= RTSemEventMultiSignal(pWait->Event);
2965# endif
2966 }
2967 }
2968 fEvents &= ~VMMDEV_EVENT_HGCM;
2969 }
2970#endif
2971
2972 /*
2973 * Normal FIFO waiter evaluation.
2974 */
2975 fEvents |= pDevExt->f32PendingEvents;
2976 RTListForEachSafe(&pDevExt->WaitList, pWait, pSafe, VBOXGUESTWAIT, ListNode)
2977 {
2978 uint32_t fHandledEvents = VBoxGuestCommonGetHandledEventsLocked(pDevExt, pWait->pSession);
2979 if ( (pWait->fReqEvents & fEvents & fHandledEvents)
2980 && !pWait->fResEvents)
2981 {
2982 pWait->fResEvents = pWait->fReqEvents & fEvents & fHandledEvents;
2983 fEvents &= ~pWait->fResEvents;
2984 RTListNodeRemove(&pWait->ListNode);
2985#ifdef VBOXGUEST_USE_DEFERRED_WAKE_UP
2986 RTListAppend(&pDevExt->WakeUpList, &pWait->ListNode);
2987#else
2988 RTListAppend(&pDevExt->WokenUpList, &pWait->ListNode);
2989 rc |= RTSemEventMultiSignal(pWait->Event);
2990#endif
2991 if (!fEvents)
2992 break;
2993 }
2994 }
2995 ASMAtomicWriteU32(&pDevExt->f32PendingEvents, fEvents);
2996 }
2997 else /* something is serious wrong... */
2998 Log(("VBoxGuestCommonISR: acknowledge events failed rc=%Rrc (events=%#x)!!\n",
2999 pReq->header.rc, pReq->events));
3000 }
3001 else
3002 LogFlow(("VBoxGuestCommonISR: not ours\n"));
3003
3004 RTSpinlockReleaseNoInts(pDevExt->EventSpinlock);
3005
3006#if defined(VBOXGUEST_USE_DEFERRED_WAKE_UP) && !defined(RT_OS_WINDOWS)
3007 /*
3008 * Do wake-ups.
3009 * Note. On Windows this isn't possible at this IRQL, so a DPC will take
3010 * care of it.
3011 */
3012 VBoxGuestWaitDoWakeUps(pDevExt);
3013#endif
3014
3015 /*
3016 * Work the poll and async notification queues on OSes that implements that.
3017 * (Do this outside the spinlock to prevent some recursive spinlocking.)
3018 */
3019 if (fMousePositionChanged)
3020 {
3021 ASMAtomicIncU32(&pDevExt->u32MousePosChangedSeq);
3022 VBoxGuestNativeISRMousePollEvent(pDevExt);
3023#ifndef RT_OS_WINDOWS
3024 if (MouseNotifyCallback.pfnNotify)
3025 MouseNotifyCallback.pfnNotify(MouseNotifyCallback.pvUser);
3026#endif
3027 }
3028
3029 ASMAtomicDecU32(&pDevExt->cISR);
3030 Assert(rc == 0);
3031 return fOurIrq;
3032}
3033
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