VirtualBox

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

Last change on this file since 40197 was 40197, checked in by vboxsync, 13 years ago

Grml.

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