VirtualBox

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

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

Additions/common/VBoxGuest: export RTSemMutex symbols from the Solaris version of the driver too.

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