VirtualBox

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

Last change on this file since 72293 was 70873, checked in by vboxsync, 7 years ago

VMMDev,VBoxGuest: Classify who is calling the host (part 1). bugref:9105

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 159.8 KB
Line 
1/* $Id: VBoxGuest.cpp 70873 2018-02-05 18:13:55Z vboxsync $ */
2/** @file
3 * VBoxGuest - Guest Additions Driver, Common Code.
4 */
5
6/*
7 * Copyright (C) 2007-2017 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/** @page pg_vbdrv VBoxGuest
28 *
29 * VBoxGuest is the device driver for VMMDev.
30 *
31 * The device driver is shipped as part of the guest additions. It has roots in
32 * the host VMM support driver (usually known as VBoxDrv), so fixes in platform
33 * specific code may apply to both drivers.
34 *
35 * The common code lives in VBoxGuest.cpp and is compiled both as C++ and C.
36 * The VBoxGuest.cpp source file shall not contain platform specific code,
37 * though it must occationally do a few \#ifdef RT_OS_XXX tests to cater for
38 * platform differences. Though, in those cases, it is common that more than
39 * one platform needs special handling.
40 *
41 * On most platforms the device driver should create two device nodes, one for
42 * full (unrestricted) access to the feature set, and one which only provides a
43 * restrict set of functions. These are generally referred to as 'vboxguest'
44 * and 'vboxuser' respectively. Currently, this two device approach is only
45 * implemented on Linux!
46 *
47 */
48
49
50/*********************************************************************************************************************************
51* Header Files *
52*********************************************************************************************************************************/
53#define LOG_GROUP LOG_GROUP_DEFAULT
54#include "VBoxGuestInternal.h"
55#include <VBox/VMMDev.h> /* for VMMDEV_RAM_SIZE */
56#include <VBox/log.h>
57#include <VBox/HostServices/GuestPropertySvc.h>
58#include <iprt/ctype.h>
59#include <iprt/mem.h>
60#include <iprt/time.h>
61#include <iprt/memobj.h>
62#include <iprt/asm.h>
63#include <iprt/asm-amd64-x86.h>
64#include <iprt/string.h>
65#include <iprt/process.h>
66#include <iprt/assert.h>
67#include <iprt/param.h>
68#include <iprt/timer.h>
69#ifdef VBOX_WITH_HGCM
70# include <iprt/thread.h>
71#endif
72#include "version-generated.h"
73#if defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)
74# include "revision-generated.h"
75#endif
76#if defined(RT_OS_SOLARIS) || defined(RT_OS_DARWIN)
77# include <iprt/rand.h>
78#endif
79
80
81/*********************************************************************************************************************************
82* Defined Constants And Macros *
83*********************************************************************************************************************************/
84#define VBOXGUEST_ACQUIRE_STYLE_EVENTS (VMMDEV_EVENT_DISPLAY_CHANGE_REQUEST | VMMDEV_EVENT_SEAMLESS_MODE_CHANGE_REQUEST)
85
86
87/*********************************************************************************************************************************
88* Internal Functions *
89*********************************************************************************************************************************/
90#ifdef VBOX_WITH_HGCM
91static DECLCALLBACK(int) vgdrvHgcmAsyncWaitCallback(VMMDevHGCMRequestHeader *pHdrNonVolatile, void *pvUser, uint32_t u32User);
92#endif
93static int vgdrvIoCtl_CancelAllWaitEvents(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession);
94static void vgdrvBitUsageTrackerClear(PVBOXGUESTBITUSAGETRACER pTracker);
95static uint32_t vgdrvGetAllowedEventMaskForSession(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession);
96static int vgdrvResetEventFilterOnHost(PVBOXGUESTDEVEXT pDevExt, uint32_t fFixedEvents);
97static int vgdrvResetMouseStatusOnHost(PVBOXGUESTDEVEXT pDevExt);
98static int vgdrvResetCapabilitiesOnHost(PVBOXGUESTDEVEXT pDevExt);
99static int vgdrvSetSessionEventFilter(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession,
100 uint32_t fOrMask, uint32_t fNotMask, bool fSessionTermination);
101static int vgdrvSetSessionMouseStatus(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession,
102 uint32_t fOrMask, uint32_t fNotMask, bool fSessionTermination);
103static int vgdrvSetSessionCapabilities(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession,
104 uint32_t fOrMask, uint32_t fNoMask,
105 uint32_t *pfSessionCaps, uint32_t *pfGlobalCaps, bool fSessionTermination);
106static int vgdrvAcquireSessionCapabilities(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession,
107 uint32_t fOrMask, uint32_t fNotMask, uint32_t fFlags, bool fSessionTermination);
108static int vgdrvDispatchEventsLocked(PVBOXGUESTDEVEXT pDevExt, uint32_t fEvents);
109
110
111/*********************************************************************************************************************************
112* Global Variables *
113*********************************************************************************************************************************/
114static const uint32_t g_cbChangeMemBalloonReq = RT_OFFSETOF(VMMDevChangeMemBalloon, aPhysPage[VMMDEV_MEMORY_BALLOON_CHUNK_PAGES]);
115
116#if defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS)
117/**
118 * Drag in the rest of IRPT since we share it with the
119 * rest of the kernel modules on Solaris.
120 */
121PFNRT g_apfnVBoxGuestIPRTDeps[] =
122{
123 /* VirtioNet */
124 (PFNRT)RTRandBytes,
125 /* RTSemMutex* */
126 (PFNRT)RTSemMutexCreate,
127 (PFNRT)RTSemMutexDestroy,
128 (PFNRT)RTSemMutexRequest,
129 (PFNRT)RTSemMutexRequestNoResume,
130 (PFNRT)RTSemMutexRequestDebug,
131 (PFNRT)RTSemMutexRequestNoResumeDebug,
132 (PFNRT)RTSemMutexRelease,
133 (PFNRT)RTSemMutexIsOwned,
134 NULL
135};
136#endif /* RT_OS_DARWIN || RT_OS_SOLARIS */
137
138
139/**
140 * Reserves memory in which the VMM can relocate any guest mappings
141 * that are floating around.
142 *
143 * This operation is a little bit tricky since the VMM might not accept
144 * just any address because of address clashes between the three contexts
145 * it operates in, so use a small stack to perform this operation.
146 *
147 * @returns VBox status code (ignored).
148 * @param pDevExt The device extension.
149 */
150static int vgdrvInitFixateGuestMappings(PVBOXGUESTDEVEXT pDevExt)
151{
152 /*
153 * Query the required space.
154 */
155 VMMDevReqHypervisorInfo *pReq;
156 int rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReq, sizeof(VMMDevReqHypervisorInfo), VMMDevReq_GetHypervisorInfo);
157 if (RT_FAILURE(rc))
158 return rc;
159 pReq->hypervisorStart = 0;
160 pReq->hypervisorSize = 0;
161 rc = VbglR0GRPerform(&pReq->header);
162 if (RT_FAILURE(rc)) /* this shouldn't happen! */
163 {
164 VbglR0GRFree(&pReq->header);
165 return rc;
166 }
167
168 /*
169 * The VMM will report back if there is nothing it wants to map, like for
170 * instance in VT-x and AMD-V mode.
171 */
172 if (pReq->hypervisorSize == 0)
173 Log(("vgdrvInitFixateGuestMappings: nothing to do\n"));
174 else
175 {
176 /*
177 * We have to try several times since the host can be picky
178 * about certain addresses.
179 */
180 RTR0MEMOBJ hFictive = NIL_RTR0MEMOBJ;
181 uint32_t cbHypervisor = pReq->hypervisorSize;
182 RTR0MEMOBJ ahTries[5];
183 uint32_t iTry;
184 bool fBitched = false;
185 Log(("vgdrvInitFixateGuestMappings: cbHypervisor=%#x\n", cbHypervisor));
186 for (iTry = 0; iTry < RT_ELEMENTS(ahTries); iTry++)
187 {
188 /*
189 * Reserve space, or if that isn't supported, create a object for
190 * some fictive physical memory and map that in to kernel space.
191 *
192 * To make the code a bit uglier, most systems cannot help with
193 * 4MB alignment, so we have to deal with that in addition to
194 * having two ways of getting the memory.
195 */
196 uint32_t uAlignment = _4M;
197 RTR0MEMOBJ hObj;
198 rc = RTR0MemObjReserveKernel(&hObj, (void *)-1, RT_ALIGN_32(cbHypervisor, _4M), uAlignment);
199 if (rc == VERR_NOT_SUPPORTED)
200 {
201 uAlignment = PAGE_SIZE;
202 rc = RTR0MemObjReserveKernel(&hObj, (void *)-1, RT_ALIGN_32(cbHypervisor, _4M) + _4M, uAlignment);
203 }
204 /*
205 * If both RTR0MemObjReserveKernel calls above failed because either not supported or
206 * not implemented at all at the current platform, try to map the memory object into the
207 * virtual kernel space.
208 */
209 if (rc == VERR_NOT_SUPPORTED)
210 {
211 if (hFictive == NIL_RTR0MEMOBJ)
212 {
213 rc = RTR0MemObjEnterPhys(&hObj, VBOXGUEST_HYPERVISOR_PHYSICAL_START, cbHypervisor + _4M, RTMEM_CACHE_POLICY_DONT_CARE);
214 if (RT_FAILURE(rc))
215 break;
216 hFictive = hObj;
217 }
218 uAlignment = _4M;
219 rc = RTR0MemObjMapKernel(&hObj, hFictive, (void *)-1, uAlignment, RTMEM_PROT_READ | RTMEM_PROT_WRITE);
220 if (rc == VERR_NOT_SUPPORTED)
221 {
222 uAlignment = PAGE_SIZE;
223 rc = RTR0MemObjMapKernel(&hObj, hFictive, (void *)-1, uAlignment, RTMEM_PROT_READ | RTMEM_PROT_WRITE);
224 }
225 }
226 if (RT_FAILURE(rc))
227 {
228 LogRel(("VBoxGuest: Failed to reserve memory for the hypervisor: rc=%Rrc (cbHypervisor=%#x uAlignment=%#x iTry=%u)\n",
229 rc, cbHypervisor, uAlignment, iTry));
230 fBitched = true;
231 break;
232 }
233
234 /*
235 * Try set it.
236 */
237 pReq->header.requestType = VMMDevReq_SetHypervisorInfo;
238 pReq->header.rc = VERR_INTERNAL_ERROR;
239 pReq->hypervisorSize = cbHypervisor;
240 pReq->hypervisorStart = (RTGCPTR32)(uintptr_t)RTR0MemObjAddress(hObj);
241 if ( uAlignment == PAGE_SIZE
242 && pReq->hypervisorStart & (_4M - 1))
243 pReq->hypervisorStart = RT_ALIGN_32(pReq->hypervisorStart, _4M);
244 AssertMsg(RT_ALIGN_32(pReq->hypervisorStart, _4M) == pReq->hypervisorStart, ("%#x\n", pReq->hypervisorStart));
245
246 rc = VbglR0GRPerform(&pReq->header);
247 if (RT_SUCCESS(rc))
248 {
249 pDevExt->hGuestMappings = hFictive != NIL_RTR0MEMOBJ ? hFictive : hObj;
250 Log(("VBoxGuest: %p LB %#x; uAlignment=%#x iTry=%u hGuestMappings=%p (%s)\n",
251 RTR0MemObjAddress(pDevExt->hGuestMappings),
252 RTR0MemObjSize(pDevExt->hGuestMappings),
253 uAlignment, iTry, pDevExt->hGuestMappings, hFictive != NIL_RTR0PTR ? "fictive" : "reservation"));
254 break;
255 }
256 ahTries[iTry] = hObj;
257 }
258
259 /*
260 * Cleanup failed attempts.
261 */
262 while (iTry-- > 0)
263 RTR0MemObjFree(ahTries[iTry], false /* fFreeMappings */);
264 if ( RT_FAILURE(rc)
265 && hFictive != NIL_RTR0PTR)
266 RTR0MemObjFree(hFictive, false /* fFreeMappings */);
267 if (RT_FAILURE(rc) && !fBitched)
268 LogRel(("VBoxGuest: Warning: failed to reserve %#d of memory for guest mappings.\n", cbHypervisor));
269 }
270 VbglR0GRFree(&pReq->header);
271
272 /*
273 * We ignore failed attempts for now.
274 */
275 return VINF_SUCCESS;
276}
277
278
279/**
280 * Undo what vgdrvInitFixateGuestMappings did.
281 *
282 * @param pDevExt The device extension.
283 */
284static void vgdrvTermUnfixGuestMappings(PVBOXGUESTDEVEXT pDevExt)
285{
286 if (pDevExt->hGuestMappings != NIL_RTR0PTR)
287 {
288 /*
289 * Tell the host that we're going to free the memory we reserved for
290 * it, the free it up. (Leak the memory if anything goes wrong here.)
291 */
292 VMMDevReqHypervisorInfo *pReq;
293 int rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReq, sizeof(VMMDevReqHypervisorInfo), VMMDevReq_SetHypervisorInfo);
294 if (RT_SUCCESS(rc))
295 {
296 pReq->hypervisorStart = 0;
297 pReq->hypervisorSize = 0;
298 rc = VbglR0GRPerform(&pReq->header);
299 VbglR0GRFree(&pReq->header);
300 }
301 if (RT_SUCCESS(rc))
302 {
303 rc = RTR0MemObjFree(pDevExt->hGuestMappings, true /* fFreeMappings */);
304 AssertRC(rc);
305 }
306 else
307 LogRel(("vgdrvTermUnfixGuestMappings: Failed to unfix the guest mappings! rc=%Rrc\n", rc));
308
309 pDevExt->hGuestMappings = NIL_RTR0MEMOBJ;
310 }
311}
312
313
314
315/**
316 * Report the guest information to the host.
317 *
318 * @returns IPRT status code.
319 * @param enmOSType The OS type to report.
320 */
321static int vgdrvReportGuestInfo(VBOXOSTYPE enmOSType)
322{
323 /*
324 * Allocate and fill in the two guest info reports.
325 */
326 VMMDevReportGuestInfo2 *pReqInfo2 = NULL;
327 VMMDevReportGuestInfo *pReqInfo1 = NULL;
328 int rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReqInfo2, sizeof (VMMDevReportGuestInfo2), VMMDevReq_ReportGuestInfo2);
329 Log(("vgdrvReportGuestInfo: VbglR0GRAlloc VMMDevReportGuestInfo2 completed with rc=%Rrc\n", rc));
330 if (RT_SUCCESS(rc))
331 {
332 pReqInfo2->guestInfo.additionsMajor = VBOX_VERSION_MAJOR;
333 pReqInfo2->guestInfo.additionsMinor = VBOX_VERSION_MINOR;
334 pReqInfo2->guestInfo.additionsBuild = VBOX_VERSION_BUILD;
335 pReqInfo2->guestInfo.additionsRevision = VBOX_SVN_REV;
336 pReqInfo2->guestInfo.additionsFeatures = VBOXGSTINFO2_F_REQUESTOR_INFO;
337 RTStrCopy(pReqInfo2->guestInfo.szName, sizeof(pReqInfo2->guestInfo.szName), VBOX_VERSION_STRING);
338
339 rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReqInfo1, sizeof (VMMDevReportGuestInfo), VMMDevReq_ReportGuestInfo);
340 Log(("vgdrvReportGuestInfo: VbglR0GRAlloc VMMDevReportGuestInfo completed with rc=%Rrc\n", rc));
341 if (RT_SUCCESS(rc))
342 {
343 pReqInfo1->guestInfo.interfaceVersion = VMMDEV_VERSION;
344 pReqInfo1->guestInfo.osType = enmOSType;
345
346 /*
347 * There are two protocols here:
348 * 1. Info2 + Info1. Supported by >=3.2.51.
349 * 2. Info1 and optionally Info2. The old protocol.
350 *
351 * We try protocol 1 first. It will fail with VERR_NOT_SUPPORTED
352 * if not supported by the VMMDev (message ordering requirement).
353 */
354 rc = VbglR0GRPerform(&pReqInfo2->header);
355 Log(("vgdrvReportGuestInfo: VbglR0GRPerform VMMDevReportGuestInfo2 completed with rc=%Rrc\n", rc));
356 if (RT_SUCCESS(rc))
357 {
358 rc = VbglR0GRPerform(&pReqInfo1->header);
359 Log(("vgdrvReportGuestInfo: VbglR0GRPerform VMMDevReportGuestInfo completed with rc=%Rrc\n", rc));
360 }
361 else if ( rc == VERR_NOT_SUPPORTED
362 || rc == VERR_NOT_IMPLEMENTED)
363 {
364 rc = VbglR0GRPerform(&pReqInfo1->header);
365 Log(("vgdrvReportGuestInfo: VbglR0GRPerform VMMDevReportGuestInfo completed with rc=%Rrc\n", rc));
366 if (RT_SUCCESS(rc))
367 {
368 rc = VbglR0GRPerform(&pReqInfo2->header);
369 Log(("vgdrvReportGuestInfo: VbglR0GRPerform VMMDevReportGuestInfo2 completed with rc=%Rrc\n", rc));
370 if (rc == VERR_NOT_IMPLEMENTED)
371 rc = VINF_SUCCESS;
372 }
373 }
374 VbglR0GRFree(&pReqInfo1->header);
375 }
376 VbglR0GRFree(&pReqInfo2->header);
377 }
378
379 return rc;
380}
381
382
383/**
384 * Report the guest driver status to the host.
385 *
386 * @returns IPRT status code.
387 * @param fActive Flag whether the driver is now active or not.
388 */
389static int vgdrvReportDriverStatus(bool fActive)
390{
391 /*
392 * Report guest status of the VBox driver to the host.
393 */
394 VMMDevReportGuestStatus *pReq2 = NULL;
395 int rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReq2, sizeof(*pReq2), VMMDevReq_ReportGuestStatus);
396 Log(("vgdrvReportDriverStatus: VbglR0GRAlloc VMMDevReportGuestStatus completed with rc=%Rrc\n", rc));
397 if (RT_SUCCESS(rc))
398 {
399 pReq2->guestStatus.facility = VBoxGuestFacilityType_VBoxGuestDriver;
400 pReq2->guestStatus.status = fActive ?
401 VBoxGuestFacilityStatus_Active
402 : VBoxGuestFacilityStatus_Inactive;
403 pReq2->guestStatus.flags = 0;
404 rc = VbglR0GRPerform(&pReq2->header);
405 Log(("vgdrvReportDriverStatus: VbglR0GRPerform VMMDevReportGuestStatus completed with fActive=%d, rc=%Rrc\n",
406 fActive ? 1 : 0, rc));
407 if (rc == VERR_NOT_IMPLEMENTED) /* Compatibility with older hosts. */
408 rc = VINF_SUCCESS;
409 VbglR0GRFree(&pReq2->header);
410 }
411
412 return rc;
413}
414
415
416/** @name Memory Ballooning
417 * @{
418 */
419
420/**
421 * Inflate the balloon by one chunk represented by an R0 memory object.
422 *
423 * The caller owns the balloon mutex.
424 *
425 * @returns IPRT status code.
426 * @param pMemObj Pointer to the R0 memory object.
427 * @param pReq The pre-allocated request for performing the VMMDev call.
428 */
429static int vgdrvBalloonInflate(PRTR0MEMOBJ pMemObj, VMMDevChangeMemBalloon *pReq)
430{
431 uint32_t iPage;
432 int rc;
433
434 for (iPage = 0; iPage < VMMDEV_MEMORY_BALLOON_CHUNK_PAGES; iPage++)
435 {
436 RTHCPHYS phys = RTR0MemObjGetPagePhysAddr(*pMemObj, iPage);
437 pReq->aPhysPage[iPage] = phys;
438 }
439
440 pReq->fInflate = true;
441 pReq->header.size = g_cbChangeMemBalloonReq;
442 pReq->cPages = VMMDEV_MEMORY_BALLOON_CHUNK_PAGES;
443
444 rc = VbglR0GRPerform(&pReq->header);
445 if (RT_FAILURE(rc))
446 LogRel(("vgdrvBalloonInflate: VbglR0GRPerform failed. rc=%Rrc\n", rc));
447 return rc;
448}
449
450
451/**
452 * Deflate the balloon by one chunk - info the host and free the memory object.
453 *
454 * The caller owns the balloon mutex.
455 *
456 * @returns IPRT status code.
457 * @param pMemObj Pointer to the R0 memory object.
458 * The memory object will be freed afterwards.
459 * @param pReq The pre-allocated request for performing the VMMDev call.
460 */
461static int vgdrvBalloonDeflate(PRTR0MEMOBJ pMemObj, VMMDevChangeMemBalloon *pReq)
462{
463 uint32_t iPage;
464 int rc;
465
466 for (iPage = 0; iPage < VMMDEV_MEMORY_BALLOON_CHUNK_PAGES; iPage++)
467 {
468 RTHCPHYS phys = RTR0MemObjGetPagePhysAddr(*pMemObj, iPage);
469 pReq->aPhysPage[iPage] = phys;
470 }
471
472 pReq->fInflate = false;
473 pReq->header.size = g_cbChangeMemBalloonReq;
474 pReq->cPages = VMMDEV_MEMORY_BALLOON_CHUNK_PAGES;
475
476 rc = VbglR0GRPerform(&pReq->header);
477 if (RT_FAILURE(rc))
478 {
479 LogRel(("vgdrvBalloonDeflate: VbglR0GRPerform failed. rc=%Rrc\n", rc));
480 return rc;
481 }
482
483 rc = RTR0MemObjFree(*pMemObj, true);
484 if (RT_FAILURE(rc))
485 {
486 LogRel(("vgdrvBalloonDeflate: RTR0MemObjFree(%p,true) -> %Rrc; this is *BAD*!\n", *pMemObj, rc));
487 return rc;
488 }
489
490 *pMemObj = NIL_RTR0MEMOBJ;
491 return VINF_SUCCESS;
492}
493
494
495/**
496 * Inflate/deflate the memory balloon and notify the host.
497 *
498 * This is a worker used by vgdrvIoCtl_CheckMemoryBalloon - it takes the mutex.
499 *
500 * @returns VBox status code.
501 * @param pDevExt The device extension.
502 * @param cBalloonChunks The new size of the balloon in chunks of 1MB.
503 * @param pfHandleInR3 Where to return the handle-in-ring3 indicator
504 * (VINF_SUCCESS if set).
505 */
506static int vgdrvSetBalloonSizeKernel(PVBOXGUESTDEVEXT pDevExt, uint32_t cBalloonChunks, bool *pfHandleInR3)
507{
508 int rc = VINF_SUCCESS;
509
510 if (pDevExt->MemBalloon.fUseKernelAPI)
511 {
512 VMMDevChangeMemBalloon *pReq;
513 uint32_t i;
514
515 if (cBalloonChunks > pDevExt->MemBalloon.cMaxChunks)
516 {
517 LogRel(("vgdrvSetBalloonSizeKernel: illegal balloon size %u (max=%u)\n",
518 cBalloonChunks, pDevExt->MemBalloon.cMaxChunks));
519 return VERR_INVALID_PARAMETER;
520 }
521
522 if (cBalloonChunks == pDevExt->MemBalloon.cMaxChunks)
523 return VINF_SUCCESS; /* nothing to do */
524
525 if ( cBalloonChunks > pDevExt->MemBalloon.cChunks
526 && !pDevExt->MemBalloon.paMemObj)
527 {
528 pDevExt->MemBalloon.paMemObj = (PRTR0MEMOBJ)RTMemAllocZ(sizeof(RTR0MEMOBJ) * pDevExt->MemBalloon.cMaxChunks);
529 if (!pDevExt->MemBalloon.paMemObj)
530 {
531 LogRel(("vgdrvSetBalloonSizeKernel: no memory for paMemObj!\n"));
532 return VERR_NO_MEMORY;
533 }
534 }
535
536 rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReq, g_cbChangeMemBalloonReq, VMMDevReq_ChangeMemBalloon);
537 if (RT_FAILURE(rc))
538 return rc;
539
540 if (cBalloonChunks > pDevExt->MemBalloon.cChunks)
541 {
542 /* inflate */
543 for (i = pDevExt->MemBalloon.cChunks; i < cBalloonChunks; i++)
544 {
545 rc = RTR0MemObjAllocPhysNC(&pDevExt->MemBalloon.paMemObj[i],
546 VMMDEV_MEMORY_BALLOON_CHUNK_SIZE, NIL_RTHCPHYS);
547 if (RT_FAILURE(rc))
548 {
549 if (rc == VERR_NOT_SUPPORTED)
550 {
551 /* not supported -- fall back to the R3-allocated memory. */
552 rc = VINF_SUCCESS;
553 pDevExt->MemBalloon.fUseKernelAPI = false;
554 Assert(pDevExt->MemBalloon.cChunks == 0);
555 Log(("VBoxGuestSetBalloonSizeKernel: PhysNC allocs not supported, falling back to R3 allocs.\n"));
556 }
557 /* else if (rc == VERR_NO_MEMORY || rc == VERR_NO_PHYS_MEMORY):
558 * cannot allocate more memory => don't try further, just stop here */
559 /* else: XXX what else can fail? VERR_MEMOBJ_INIT_FAILED for instance. just stop. */
560 break;
561 }
562
563 rc = vgdrvBalloonInflate(&pDevExt->MemBalloon.paMemObj[i], pReq);
564 if (RT_FAILURE(rc))
565 {
566 Log(("vboxGuestSetBalloonSize(inflate): failed, rc=%Rrc!\n", rc));
567 RTR0MemObjFree(pDevExt->MemBalloon.paMemObj[i], true);
568 pDevExt->MemBalloon.paMemObj[i] = NIL_RTR0MEMOBJ;
569 break;
570 }
571 pDevExt->MemBalloon.cChunks++;
572 }
573 }
574 else
575 {
576 /* deflate */
577 for (i = pDevExt->MemBalloon.cChunks; i-- > cBalloonChunks;)
578 {
579 rc = vgdrvBalloonDeflate(&pDevExt->MemBalloon.paMemObj[i], pReq);
580 if (RT_FAILURE(rc))
581 {
582 Log(("vboxGuestSetBalloonSize(deflate): failed, rc=%Rrc!\n", rc));
583 break;
584 }
585 pDevExt->MemBalloon.cChunks--;
586 }
587 }
588
589 VbglR0GRFree(&pReq->header);
590 }
591
592 /*
593 * Set the handle-in-ring3 indicator. When set Ring-3 will have to work
594 * the balloon changes via the other API.
595 */
596 *pfHandleInR3 = pDevExt->MemBalloon.fUseKernelAPI ? false : true;
597
598 return rc;
599}
600
601
602/**
603 * Inflate/deflate the balloon by one chunk.
604 *
605 * Worker for vgdrvIoCtl_ChangeMemoryBalloon - it takes the mutex.
606 *
607 * @returns VBox status code.
608 * @param pDevExt The device extension.
609 * @param pSession The session.
610 * @param pvChunk The address of the chunk to add to / remove from the
611 * balloon. (user space address)
612 * @param fInflate Inflate if true, deflate if false.
613 */
614static int vgdrvSetBalloonSizeFromUser(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, RTR3PTR pvChunk, bool fInflate)
615{
616 VMMDevChangeMemBalloon *pReq;
617 PRTR0MEMOBJ pMemObj = NULL;
618 int rc = VINF_SUCCESS;
619 uint32_t i;
620 RT_NOREF1(pSession);
621
622 if (fInflate)
623 {
624 if ( pDevExt->MemBalloon.cChunks > pDevExt->MemBalloon.cMaxChunks - 1
625 || pDevExt->MemBalloon.cMaxChunks == 0 /* If called without first querying. */)
626 {
627 LogRel(("vgdrvSetBalloonSizeFromUser: cannot inflate balloon, already have %u chunks (max=%u)\n",
628 pDevExt->MemBalloon.cChunks, pDevExt->MemBalloon.cMaxChunks));
629 return VERR_INVALID_PARAMETER;
630 }
631
632 if (!pDevExt->MemBalloon.paMemObj)
633 {
634 pDevExt->MemBalloon.paMemObj = (PRTR0MEMOBJ)RTMemAlloc(sizeof(RTR0MEMOBJ) * pDevExt->MemBalloon.cMaxChunks);
635 if (!pDevExt->MemBalloon.paMemObj)
636 {
637 LogRel(("vgdrvSetBalloonSizeFromUser: no memory for paMemObj!\n"));
638 return VERR_NO_MEMORY;
639 }
640 for (i = 0; i < pDevExt->MemBalloon.cMaxChunks; i++)
641 pDevExt->MemBalloon.paMemObj[i] = NIL_RTR0MEMOBJ;
642 }
643 }
644 else
645 {
646 if (pDevExt->MemBalloon.cChunks == 0)
647 {
648 AssertMsgFailed(("vgdrvSetBalloonSizeFromUser: cannot decrease balloon, already at size 0\n"));
649 return VERR_INVALID_PARAMETER;
650 }
651 }
652
653 /*
654 * Enumerate all memory objects and check if the object is already registered.
655 */
656 for (i = 0; i < pDevExt->MemBalloon.cMaxChunks; i++)
657 {
658 if ( fInflate
659 && !pMemObj
660 && pDevExt->MemBalloon.paMemObj[i] == NIL_RTR0MEMOBJ)
661 pMemObj = &pDevExt->MemBalloon.paMemObj[i]; /* found free object pointer */
662 if (RTR0MemObjAddressR3(pDevExt->MemBalloon.paMemObj[i]) == pvChunk)
663 {
664 if (fInflate)
665 return VERR_ALREADY_EXISTS; /* don't provide the same memory twice */
666 pMemObj = &pDevExt->MemBalloon.paMemObj[i];
667 break;
668 }
669 }
670 if (!pMemObj)
671 {
672 if (fInflate)
673 {
674 /* no free object pointer found -- should not happen */
675 return VERR_NO_MEMORY;
676 }
677
678 /* cannot free this memory as it wasn't provided before */
679 return VERR_NOT_FOUND;
680 }
681
682 /*
683 * Try inflate / default the balloon as requested.
684 */
685 rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReq, g_cbChangeMemBalloonReq, VMMDevReq_ChangeMemBalloon);
686 if (RT_FAILURE(rc))
687 return rc;
688 pReq->header.fRequestor = pSession->fRequestor;
689
690 if (fInflate)
691 {
692 rc = RTR0MemObjLockUser(pMemObj, pvChunk, VMMDEV_MEMORY_BALLOON_CHUNK_SIZE,
693 RTMEM_PROT_READ | RTMEM_PROT_WRITE, NIL_RTR0PROCESS);
694 if (RT_SUCCESS(rc))
695 {
696 rc = vgdrvBalloonInflate(pMemObj, pReq);
697 if (RT_SUCCESS(rc))
698 pDevExt->MemBalloon.cChunks++;
699 else
700 {
701 Log(("vgdrvSetBalloonSizeFromUser(inflate): failed, rc=%Rrc!\n", rc));
702 RTR0MemObjFree(*pMemObj, true);
703 *pMemObj = NIL_RTR0MEMOBJ;
704 }
705 }
706 }
707 else
708 {
709 rc = vgdrvBalloonDeflate(pMemObj, pReq);
710 if (RT_SUCCESS(rc))
711 pDevExt->MemBalloon.cChunks--;
712 else
713 Log(("vgdrvSetBalloonSizeFromUser(deflate): failed, rc=%Rrc!\n", rc));
714 }
715
716 VbglR0GRFree(&pReq->header);
717 return rc;
718}
719
720
721/**
722 * Cleanup the memory balloon of a session.
723 *
724 * Will request the balloon mutex, so it must be valid and the caller must not
725 * own it already.
726 *
727 * @param pDevExt The device extension.
728 * @param pSession The session. Can be NULL at unload.
729 */
730static void vgdrvCloseMemBalloon(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession)
731{
732 RTSemFastMutexRequest(pDevExt->MemBalloon.hMtx);
733 if ( pDevExt->MemBalloon.pOwner == pSession
734 || pSession == NULL /*unload*/)
735 {
736 if (pDevExt->MemBalloon.paMemObj)
737 {
738 VMMDevChangeMemBalloon *pReq;
739 int rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReq, g_cbChangeMemBalloonReq, VMMDevReq_ChangeMemBalloon);
740 if (RT_SUCCESS(rc))
741 {
742 /* fRequestor is kernel here, as we're cleaning up. */
743
744 uint32_t i;
745 for (i = pDevExt->MemBalloon.cChunks; i-- > 0;)
746 {
747 rc = vgdrvBalloonDeflate(&pDevExt->MemBalloon.paMemObj[i], pReq);
748 if (RT_FAILURE(rc))
749 {
750 LogRel(("vgdrvCloseMemBalloon: Deflate failed with rc=%Rrc. Will leak %u chunks.\n",
751 rc, pDevExt->MemBalloon.cChunks));
752 break;
753 }
754 pDevExt->MemBalloon.paMemObj[i] = NIL_RTR0MEMOBJ;
755 pDevExt->MemBalloon.cChunks--;
756 }
757 VbglR0GRFree(&pReq->header);
758 }
759 else
760 LogRel(("vgdrvCloseMemBalloon: Failed to allocate VMMDev request buffer (rc=%Rrc). Will leak %u chunks.\n",
761 rc, pDevExt->MemBalloon.cChunks));
762 RTMemFree(pDevExt->MemBalloon.paMemObj);
763 pDevExt->MemBalloon.paMemObj = NULL;
764 }
765
766 pDevExt->MemBalloon.pOwner = NULL;
767 }
768 RTSemFastMutexRelease(pDevExt->MemBalloon.hMtx);
769}
770
771/** @} */
772
773
774
775/** @name Heartbeat
776 * @{
777 */
778
779/**
780 * Sends heartbeat to host.
781 *
782 * @returns VBox status code.
783 */
784static int vgdrvHeartbeatSend(PVBOXGUESTDEVEXT pDevExt)
785{
786 int rc;
787 if (pDevExt->pReqGuestHeartbeat)
788 {
789 rc = VbglR0GRPerform(pDevExt->pReqGuestHeartbeat);
790 Log3(("vgdrvHeartbeatSend: VbglR0GRPerform vgdrvHeartbeatSend completed with rc=%Rrc\n", rc));
791 }
792 else
793 rc = VERR_INVALID_STATE;
794 return rc;
795}
796
797
798/**
799 * Callback for heartbeat timer.
800 */
801static DECLCALLBACK(void) vgdrvHeartbeatTimerHandler(PRTTIMER hTimer, void *pvUser, uint64_t iTick)
802{
803 PVBOXGUESTDEVEXT pDevExt = (PVBOXGUESTDEVEXT)pvUser;
804 int rc;
805 AssertReturnVoid(pDevExt);
806
807 rc = vgdrvHeartbeatSend(pDevExt);
808 if (RT_FAILURE(rc))
809 Log(("HB Timer: vgdrvHeartbeatSend failed: rc=%Rrc\n", rc));
810
811 NOREF(hTimer); NOREF(iTick);
812}
813
814
815/**
816 * Configure the host to check guest's heartbeat
817 * and get heartbeat interval from the host.
818 *
819 * @returns VBox status code.
820 * @param pDevExt The device extension.
821 * @param fEnabled Set true to enable guest heartbeat checks on host.
822 */
823static int vgdrvHeartbeatHostConfigure(PVBOXGUESTDEVEXT pDevExt, bool fEnabled)
824{
825 VMMDevReqHeartbeat *pReq;
826 int rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReq, sizeof(*pReq), VMMDevReq_HeartbeatConfigure);
827 Log(("vgdrvHeartbeatHostConfigure: VbglR0GRAlloc vgdrvHeartbeatHostConfigure completed with rc=%Rrc\n", rc));
828 if (RT_SUCCESS(rc))
829 {
830 pReq->fEnabled = fEnabled;
831 pReq->cNsInterval = 0;
832 rc = VbglR0GRPerform(&pReq->header);
833 Log(("vgdrvHeartbeatHostConfigure: VbglR0GRPerform vgdrvHeartbeatHostConfigure completed with rc=%Rrc\n", rc));
834 pDevExt->cNsHeartbeatInterval = pReq->cNsInterval;
835 VbglR0GRFree(&pReq->header);
836 }
837 return rc;
838}
839
840
841/**
842 * Initializes the heartbeat timer.
843 *
844 * This feature may be disabled by the host.
845 *
846 * @returns VBox status (ignored).
847 * @param pDevExt The device extension.
848 */
849static int vgdrvHeartbeatInit(PVBOXGUESTDEVEXT pDevExt)
850{
851 /*
852 * Make sure that heartbeat checking is disabled.
853 */
854 int rc = vgdrvHeartbeatHostConfigure(pDevExt, false);
855 if (RT_SUCCESS(rc))
856 {
857 rc = vgdrvHeartbeatHostConfigure(pDevExt, true);
858 if (RT_SUCCESS(rc))
859 {
860 /*
861 * Preallocate the request to use it from the timer callback because:
862 * 1) on Windows VbglR0GRAlloc must be called at IRQL <= APC_LEVEL
863 * and the timer callback runs at DISPATCH_LEVEL;
864 * 2) avoid repeated allocations.
865 */
866 rc = VbglR0GRAlloc(&pDevExt->pReqGuestHeartbeat, sizeof(*pDevExt->pReqGuestHeartbeat), VMMDevReq_GuestHeartbeat);
867 if (RT_SUCCESS(rc))
868 {
869 LogRel(("vgdrvHeartbeatInit: Setting up heartbeat to trigger every %RU64 milliseconds\n",
870 pDevExt->cNsHeartbeatInterval / RT_NS_1MS));
871 rc = RTTimerCreateEx(&pDevExt->pHeartbeatTimer, pDevExt->cNsHeartbeatInterval, 0 /*fFlags*/,
872 (PFNRTTIMER)vgdrvHeartbeatTimerHandler, pDevExt);
873 if (RT_SUCCESS(rc))
874 {
875 rc = RTTimerStart(pDevExt->pHeartbeatTimer, 0);
876 if (RT_SUCCESS(rc))
877 return VINF_SUCCESS;
878
879 LogRel(("vgdrvHeartbeatInit: Heartbeat timer failed to start, rc=%Rrc\n", rc));
880 }
881 else
882 LogRel(("vgdrvHeartbeatInit: Failed to create heartbeat timer: %Rrc\n", rc));
883
884 VbglR0GRFree(pDevExt->pReqGuestHeartbeat);
885 pDevExt->pReqGuestHeartbeat = NULL;
886 }
887 else
888 LogRel(("vgdrvHeartbeatInit: VbglR0GRAlloc(VMMDevReq_GuestHeartbeat): %Rrc\n", rc));
889
890 LogRel(("vgdrvHeartbeatInit: Failed to set up the timer, guest heartbeat is disabled\n"));
891 vgdrvHeartbeatHostConfigure(pDevExt, false);
892 }
893 else
894 LogRel(("vgdrvHeartbeatInit: Failed to configure host for heartbeat checking: rc=%Rrc\n", rc));
895 }
896 return rc;
897}
898
899/** @} */
900
901
902/**
903 * Helper to reinit the VMMDev communication after hibernation.
904 *
905 * @returns VBox status code.
906 * @param pDevExt The device extension.
907 * @param enmOSType The OS type.
908 *
909 * @todo Call this on all platforms, not just windows.
910 */
911int VGDrvCommonReinitDevExtAfterHibernation(PVBOXGUESTDEVEXT pDevExt, VBOXOSTYPE enmOSType)
912{
913 int rc = vgdrvReportGuestInfo(enmOSType);
914 if (RT_SUCCESS(rc))
915 {
916 rc = vgdrvReportDriverStatus(true /* Driver is active */);
917 if (RT_FAILURE(rc))
918 Log(("VGDrvCommonReinitDevExtAfterHibernation: could not report guest driver status, rc=%Rrc\n", rc));
919 }
920 else
921 Log(("VGDrvCommonReinitDevExtAfterHibernation: could not report guest information to host, rc=%Rrc\n", rc));
922 LogFlow(("VGDrvCommonReinitDevExtAfterHibernation: returned with rc=%Rrc\n", rc));
923 RT_NOREF1(pDevExt);
924 return rc;
925}
926
927
928/**
929 * Initializes the release logger (debug is implicit), if configured.
930 *
931 * @returns IPRT status code.
932 */
933int VGDrvCommonInitLoggers(void)
934{
935#ifdef VBOX_GUESTDRV_WITH_RELEASE_LOGGER
936 /*
937 * Create the release log.
938 */
939 static const char * const s_apszGroups[] = VBOX_LOGGROUP_NAMES;
940 PRTLOGGER pRelLogger;
941 int rc = RTLogCreate(&pRelLogger, 0 /*fFlags*/, "all", "VBOXGUEST_RELEASE_LOG", RT_ELEMENTS(s_apszGroups), s_apszGroups,
942 RTLOGDEST_STDOUT | RTLOGDEST_DEBUGGER, NULL);
943 if (RT_SUCCESS(rc))
944 RTLogRelSetDefaultInstance(pRelLogger);
945 /** @todo Add native hook for getting logger config parameters and setting
946 * them. On linux we should use the module parameter stuff... */
947 return rc;
948#else
949 return VINF_SUCCESS;
950#endif
951}
952
953
954/**
955 * Destroys the loggers.
956 */
957void VGDrvCommonDestroyLoggers(void)
958{
959#ifdef VBOX_GUESTDRV_WITH_RELEASE_LOGGER
960 RTLogDestroy(RTLogRelSetDefaultInstance(NULL));
961 RTLogDestroy(RTLogSetDefaultInstance(NULL));
962#endif
963}
964
965
966/**
967 * Initialize the device extension fundament.
968 *
969 * There are no device resources at this point, VGDrvCommonInitDevExtResources
970 * should be called when they are available.
971 *
972 * @returns VBox status code.
973 * @param pDevExt The device extension to init.
974 */
975int VGDrvCommonInitDevExtFundament(PVBOXGUESTDEVEXT pDevExt)
976{
977 int rc;
978 AssertMsg( pDevExt->uInitState != VBOXGUESTDEVEXT_INIT_STATE_FUNDAMENT
979 && pDevExt->uInitState != VBOXGUESTDEVEXT_INIT_STATE_RESOURCES, ("uInitState=%#x\n", pDevExt->uInitState));
980
981 /*
982 * Initialize the data.
983 */
984 pDevExt->IOPortBase = UINT16_MAX;
985 pDevExt->pVMMDevMemory = NULL;
986 pDevExt->hGuestMappings = NIL_RTR0MEMOBJ;
987 pDevExt->EventSpinlock = NIL_RTSPINLOCK;
988 pDevExt->pIrqAckEvents = NULL;
989 pDevExt->PhysIrqAckEvents = NIL_RTCCPHYS;
990 RTListInit(&pDevExt->WaitList);
991#ifdef VBOX_WITH_HGCM
992 RTListInit(&pDevExt->HGCMWaitList);
993#endif
994#ifdef VBOXGUEST_USE_DEFERRED_WAKE_UP
995 RTListInit(&pDevExt->WakeUpList);
996#endif
997 RTListInit(&pDevExt->WokenUpList);
998 RTListInit(&pDevExt->FreeList);
999 RTListInit(&pDevExt->SessionList);
1000 pDevExt->cSessions = 0;
1001 pDevExt->fLoggingEnabled = false;
1002 pDevExt->f32PendingEvents = 0;
1003 pDevExt->u32MousePosChangedSeq = 0;
1004 pDevExt->SessionSpinlock = NIL_RTSPINLOCK;
1005 pDevExt->MemBalloon.hMtx = NIL_RTSEMFASTMUTEX;
1006 pDevExt->MemBalloon.cChunks = 0;
1007 pDevExt->MemBalloon.cMaxChunks = 0;
1008 pDevExt->MemBalloon.fUseKernelAPI = true;
1009 pDevExt->MemBalloon.paMemObj = NULL;
1010 pDevExt->MemBalloon.pOwner = NULL;
1011 pDevExt->pfnMouseNotifyCallback = NULL;
1012 pDevExt->pvMouseNotifyCallbackArg = NULL;
1013 pDevExt->pReqGuestHeartbeat = NULL;
1014
1015 pDevExt->fFixedEvents = 0;
1016 vgdrvBitUsageTrackerClear(&pDevExt->EventFilterTracker);
1017 pDevExt->fEventFilterHost = UINT32_MAX; /* forces a report */
1018
1019 vgdrvBitUsageTrackerClear(&pDevExt->MouseStatusTracker);
1020 pDevExt->fMouseStatusHost = UINT32_MAX; /* forces a report */
1021
1022 pDevExt->fAcquireModeGuestCaps = 0;
1023 pDevExt->fSetModeGuestCaps = 0;
1024 pDevExt->fAcquiredGuestCaps = 0;
1025 vgdrvBitUsageTrackerClear(&pDevExt->SetGuestCapsTracker);
1026 pDevExt->fGuestCapsHost = UINT32_MAX; /* forces a report */
1027
1028 /*
1029 * Create the wait and session spinlocks as well as the ballooning mutex.
1030 */
1031 rc = RTSpinlockCreate(&pDevExt->EventSpinlock, RTSPINLOCK_FLAGS_INTERRUPT_SAFE, "VBoxGuestEvent");
1032 if (RT_SUCCESS(rc))
1033 {
1034 rc = RTSpinlockCreate(&pDevExt->SessionSpinlock, RTSPINLOCK_FLAGS_INTERRUPT_SAFE, "VBoxGuestSession");
1035 if (RT_SUCCESS(rc))
1036 {
1037 rc = RTSemFastMutexCreate(&pDevExt->MemBalloon.hMtx);
1038 if (RT_SUCCESS(rc))
1039 {
1040 pDevExt->uInitState = VBOXGUESTDEVEXT_INIT_STATE_FUNDAMENT;
1041 return VINF_SUCCESS;
1042 }
1043
1044 LogRel(("VGDrvCommonInitDevExt: failed to create mutex, rc=%Rrc!\n", rc));
1045 RTSpinlockDestroy(pDevExt->SessionSpinlock);
1046 }
1047 else
1048 LogRel(("VGDrvCommonInitDevExt: failed to create spinlock, rc=%Rrc!\n", rc));
1049 RTSpinlockDestroy(pDevExt->EventSpinlock);
1050 }
1051 else
1052 LogRel(("VGDrvCommonInitDevExt: failed to create spinlock, rc=%Rrc!\n", rc));
1053
1054 pDevExt->uInitState = 0;
1055 return rc;
1056}
1057
1058
1059/**
1060 * Counter to VGDrvCommonInitDevExtFundament.
1061 *
1062 * @param pDevExt The device extension.
1063 */
1064void VGDrvCommonDeleteDevExtFundament(PVBOXGUESTDEVEXT pDevExt)
1065{
1066 int rc2;
1067 AssertMsgReturnVoid(pDevExt->uInitState == VBOXGUESTDEVEXT_INIT_STATE_FUNDAMENT, ("uInitState=%#x\n", pDevExt->uInitState));
1068 pDevExt->uInitState = VBOXGUESTDEVEXT_INIT_STATE_DELETED;
1069
1070 rc2 = RTSemFastMutexDestroy(pDevExt->MemBalloon.hMtx); AssertRC(rc2);
1071 rc2 = RTSpinlockDestroy(pDevExt->EventSpinlock); AssertRC(rc2);
1072 rc2 = RTSpinlockDestroy(pDevExt->SessionSpinlock); AssertRC(rc2);
1073}
1074
1075
1076/**
1077 * Initializes the VBoxGuest device extension resource parts.
1078 *
1079 * The native code locates the VMMDev on the PCI bus and retrieve the MMIO and
1080 * I/O port ranges, this function will take care of mapping the MMIO memory (if
1081 * present). Upon successful return the native code should set up the interrupt
1082 * handler.
1083 *
1084 * @returns VBox status code.
1085 *
1086 * @param pDevExt The device extension. Allocated by the native code.
1087 * @param IOPortBase The base of the I/O port range.
1088 * @param pvMMIOBase The base of the MMIO memory mapping.
1089 * This is optional, pass NULL if not present.
1090 * @param cbMMIO The size of the MMIO memory mapping.
1091 * This is optional, pass 0 if not present.
1092 * @param enmOSType The guest OS type to report to the VMMDev.
1093 * @param fFixedEvents Events that will be enabled upon init and no client
1094 * will ever be allowed to mask.
1095 */
1096int VGDrvCommonInitDevExtResources(PVBOXGUESTDEVEXT pDevExt, uint16_t IOPortBase,
1097 void *pvMMIOBase, uint32_t cbMMIO, VBOXOSTYPE enmOSType, uint32_t fFixedEvents)
1098{
1099 int rc;
1100 AssertMsgReturn(pDevExt->uInitState == VBOXGUESTDEVEXT_INIT_STATE_FUNDAMENT, ("uInitState=%#x\n", pDevExt->uInitState),
1101 VERR_INVALID_STATE);
1102
1103 /*
1104 * If there is an MMIO region validate the version and size.
1105 */
1106 if (pvMMIOBase)
1107 {
1108 VMMDevMemory *pVMMDev = (VMMDevMemory *)pvMMIOBase;
1109 Assert(cbMMIO);
1110 if ( pVMMDev->u32Version == VMMDEV_MEMORY_VERSION
1111 && pVMMDev->u32Size >= 32
1112 && pVMMDev->u32Size <= cbMMIO)
1113 {
1114 pDevExt->pVMMDevMemory = pVMMDev;
1115 Log(("VGDrvCommonInitDevExtResources: VMMDevMemory: mapping=%p size=%#RX32 (%#RX32) version=%#RX32\n",
1116 pVMMDev, pVMMDev->u32Size, cbMMIO, pVMMDev->u32Version));
1117 }
1118 else /* try live without it. */
1119 LogRel(("VGDrvCommonInitDevExtResources: Bogus VMMDev memory; u32Version=%RX32 (expected %RX32) u32Size=%RX32 (expected <= %RX32)\n",
1120 pVMMDev->u32Version, VMMDEV_MEMORY_VERSION, pVMMDev->u32Size, cbMMIO));
1121 }
1122
1123 /*
1124 * Initialize the guest library and report the guest info back to VMMDev,
1125 * set the interrupt control filter mask, and fixate the guest mappings
1126 * made by the VMM.
1127 */
1128 pDevExt->IOPortBase = IOPortBase;
1129 rc = VbglR0InitPrimary(pDevExt->IOPortBase, (VMMDevMemory *)pDevExt->pVMMDevMemory);
1130 if (RT_SUCCESS(rc))
1131 {
1132 rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pDevExt->pIrqAckEvents, sizeof(VMMDevEvents), VMMDevReq_AcknowledgeEvents);
1133 if (RT_SUCCESS(rc))
1134 {
1135 pDevExt->PhysIrqAckEvents = VbglR0PhysHeapGetPhysAddr(pDevExt->pIrqAckEvents);
1136 Assert(pDevExt->PhysIrqAckEvents != 0);
1137
1138 rc = vgdrvReportGuestInfo(enmOSType);
1139 if (RT_SUCCESS(rc))
1140 {
1141 /*
1142 * Set the fixed event and make sure the host doesn't have any lingering
1143 * the guest capabilities or mouse status bits set.
1144 */
1145#ifdef VBOX_WITH_HGCM
1146 fFixedEvents |= VMMDEV_EVENT_HGCM;
1147#endif
1148 pDevExt->fFixedEvents = fFixedEvents;
1149 rc = vgdrvResetEventFilterOnHost(pDevExt, fFixedEvents);
1150 if (RT_SUCCESS(rc))
1151 {
1152 rc = vgdrvResetCapabilitiesOnHost(pDevExt);
1153 if (RT_SUCCESS(rc))
1154 {
1155 rc = vgdrvResetMouseStatusOnHost(pDevExt);
1156 if (RT_SUCCESS(rc))
1157 {
1158 /*
1159 * Initialize stuff which may fail without requiring the driver init to fail.
1160 */
1161 vgdrvInitFixateGuestMappings(pDevExt);
1162 vgdrvHeartbeatInit(pDevExt);
1163
1164 /*
1165 * Done!
1166 */
1167 rc = vgdrvReportDriverStatus(true /* Driver is active */);
1168 if (RT_FAILURE(rc))
1169 LogRel(("VGDrvCommonInitDevExtResources: VBoxReportGuestDriverStatus failed, rc=%Rrc\n", rc));
1170
1171 pDevExt->uInitState = VBOXGUESTDEVEXT_INIT_STATE_RESOURCES;
1172 LogFlowFunc(("VGDrvCommonInitDevExtResources: returns success\n"));
1173 return VINF_SUCCESS;
1174 }
1175 LogRel(("VGDrvCommonInitDevExtResources: failed to clear mouse status: rc=%Rrc\n", rc));
1176 }
1177 else
1178 LogRel(("VGDrvCommonInitDevExtResources: failed to clear guest capabilities: rc=%Rrc\n", rc));
1179 }
1180 else
1181 LogRel(("VGDrvCommonInitDevExtResources: failed to set fixed event filter: rc=%Rrc\n", rc));
1182 pDevExt->fFixedEvents = 0;
1183 }
1184 else
1185 LogRel(("VGDrvCommonInitDevExtResources: vgdrvReportGuestInfo failed: rc=%Rrc\n", rc));
1186 VbglR0GRFree((VMMDevRequestHeader *)pDevExt->pIrqAckEvents);
1187 }
1188 else
1189 LogRel(("VGDrvCommonInitDevExtResources: VbglR0GRAlloc failed: rc=%Rrc\n", rc));
1190
1191 VbglR0TerminatePrimary();
1192 }
1193 else
1194 LogRel(("VGDrvCommonInitDevExtResources: VbglR0InitPrimary failed: rc=%Rrc\n", rc));
1195 pDevExt->IOPortBase = UINT16_MAX;
1196 return rc;
1197}
1198
1199
1200/**
1201 * Deletes all the items in a wait chain.
1202 * @param pList The head of the chain.
1203 */
1204static void vgdrvDeleteWaitList(PRTLISTNODE pList)
1205{
1206 while (!RTListIsEmpty(pList))
1207 {
1208 int rc2;
1209 PVBOXGUESTWAIT pWait = RTListGetFirst(pList, VBOXGUESTWAIT, ListNode);
1210 RTListNodeRemove(&pWait->ListNode);
1211
1212 rc2 = RTSemEventMultiDestroy(pWait->Event); AssertRC(rc2);
1213 pWait->Event = NIL_RTSEMEVENTMULTI;
1214 pWait->pSession = NULL;
1215 RTMemFree(pWait);
1216 }
1217}
1218
1219
1220/**
1221 * Counter to VGDrvCommonInitDevExtResources.
1222 *
1223 * @param pDevExt The device extension.
1224 */
1225void VGDrvCommonDeleteDevExtResources(PVBOXGUESTDEVEXT pDevExt)
1226{
1227 Log(("VGDrvCommonDeleteDevExtResources:\n"));
1228 AssertMsgReturnVoid(pDevExt->uInitState == VBOXGUESTDEVEXT_INIT_STATE_RESOURCES, ("uInitState=%#x\n", pDevExt->uInitState));
1229 pDevExt->uInitState = VBOXGUESTDEVEXT_INIT_STATE_FUNDAMENT;
1230
1231 /*
1232 * Stop and destroy HB timer and disable host heartbeat checking.
1233 */
1234 if (pDevExt->pHeartbeatTimer)
1235 {
1236 RTTimerDestroy(pDevExt->pHeartbeatTimer);
1237 vgdrvHeartbeatHostConfigure(pDevExt, false);
1238 }
1239
1240 VbglR0GRFree(pDevExt->pReqGuestHeartbeat);
1241 pDevExt->pReqGuestHeartbeat = NULL;
1242
1243 /*
1244 * Clean up the bits that involves the host first.
1245 */
1246 vgdrvTermUnfixGuestMappings(pDevExt);
1247 if (!RTListIsEmpty(&pDevExt->SessionList))
1248 {
1249 LogRelFunc(("session list not empty!\n"));
1250 RTListInit(&pDevExt->SessionList);
1251 }
1252
1253 /*
1254 * Update the host flags (mouse status etc) not to reflect this session.
1255 */
1256 pDevExt->fFixedEvents = 0;
1257 vgdrvResetEventFilterOnHost(pDevExt, 0 /*fFixedEvents*/);
1258 vgdrvResetCapabilitiesOnHost(pDevExt);
1259 vgdrvResetMouseStatusOnHost(pDevExt);
1260
1261 vgdrvCloseMemBalloon(pDevExt, (PVBOXGUESTSESSION)NULL);
1262
1263 /*
1264 * Cleanup all the other resources.
1265 */
1266 vgdrvDeleteWaitList(&pDevExt->WaitList);
1267#ifdef VBOX_WITH_HGCM
1268 vgdrvDeleteWaitList(&pDevExt->HGCMWaitList);
1269#endif
1270#ifdef VBOXGUEST_USE_DEFERRED_WAKE_UP
1271 vgdrvDeleteWaitList(&pDevExt->WakeUpList);
1272#endif
1273 vgdrvDeleteWaitList(&pDevExt->WokenUpList);
1274 vgdrvDeleteWaitList(&pDevExt->FreeList);
1275
1276 VbglR0TerminatePrimary();
1277
1278
1279 pDevExt->pVMMDevMemory = NULL;
1280 pDevExt->IOPortBase = 0;
1281 pDevExt->pIrqAckEvents = NULL; /* Freed by VbglR0TerminatePrimary. */
1282}
1283
1284
1285/**
1286 * Initializes the VBoxGuest device extension when the device driver is loaded.
1287 *
1288 * The native code locates the VMMDev on the PCI bus and retrieve the MMIO and
1289 * I/O port ranges, this function will take care of mapping the MMIO memory (if
1290 * present). Upon successful return the native code should set up the interrupt
1291 * handler.
1292 *
1293 * Instead of calling this method, the host specific code choose to perform a
1294 * more granular initialization using:
1295 * 1. VGDrvCommonInitLoggers
1296 * 2. VGDrvCommonInitDevExtFundament
1297 * 3. VGDrvCommonInitDevExtResources
1298 *
1299 * @returns VBox status code.
1300 *
1301 * @param pDevExt The device extension. Allocated by the native code.
1302 * @param IOPortBase The base of the I/O port range.
1303 * @param pvMMIOBase The base of the MMIO memory mapping.
1304 * This is optional, pass NULL if not present.
1305 * @param cbMMIO The size of the MMIO memory mapping.
1306 * This is optional, pass 0 if not present.
1307 * @param enmOSType The guest OS type to report to the VMMDev.
1308 * @param fFixedEvents Events that will be enabled upon init and no client
1309 * will ever be allowed to mask.
1310 */
1311int VGDrvCommonInitDevExt(PVBOXGUESTDEVEXT pDevExt, uint16_t IOPortBase,
1312 void *pvMMIOBase, uint32_t cbMMIO, VBOXOSTYPE enmOSType, uint32_t fFixedEvents)
1313{
1314 int rc;
1315 VGDrvCommonInitLoggers();
1316
1317 rc = VGDrvCommonInitDevExtFundament(pDevExt);
1318 if (RT_SUCCESS(rc))
1319 {
1320 rc = VGDrvCommonInitDevExtResources(pDevExt, IOPortBase, pvMMIOBase, cbMMIO, enmOSType, fFixedEvents);
1321 if (RT_SUCCESS(rc))
1322 return rc;
1323
1324 VGDrvCommonDeleteDevExtFundament(pDevExt);
1325 }
1326 VGDrvCommonDestroyLoggers();
1327 return rc; /* (failed) */
1328}
1329
1330
1331/**
1332 * Checks if the given option can be taken to not mean 'false'.
1333 *
1334 * @returns true or false accordingly.
1335 * @param pszValue The value to consider.
1336 */
1337bool VBDrvCommonIsOptionValueTrue(const char *pszValue)
1338{
1339 if (pszValue)
1340 {
1341 char ch;
1342 while ( (ch = *pszValue) != '\0'
1343 && RT_C_IS_SPACE(ch))
1344 pszValue++;
1345
1346 return ch != '\0'
1347 && ch != 'n' /* no */
1348 && ch != 'N' /* NO */
1349 && ch != 'd' /* disabled */
1350 && ch != 'f' /* false*/
1351 && ch != 'F' /* FALSE */
1352 && ch != 'D' /* DISABLED */
1353 && ( (ch != 'o' && ch != 'O') /* off, OFF, Off */
1354 || (pszValue[1] != 'f' && pszValue[1] != 'F') )
1355 && (ch != '0' || pszValue[1] != '\0') /* '0' */
1356 ;
1357 }
1358 return false;
1359}
1360
1361
1362/**
1363 * Processes a option.
1364 *
1365 * This will let the OS specific code have a go at it too.
1366 *
1367 * @param pDevExt The device extension.
1368 * @param pszName The option name, sans prefix.
1369 * @param pszValue The option value.
1370 */
1371void VGDrvCommonProcessOption(PVBOXGUESTDEVEXT pDevExt, const char *pszName, const char *pszValue)
1372{
1373 Log(("VGDrvCommonProcessOption: pszName='%s' pszValue='%s'\n", pszName, pszValue));
1374
1375 if ( RTStrICmpAscii(pszName, "r3_log_to_host") == 0
1376 || RTStrICmpAscii(pszName, "LoggingEnabled") == 0 /*legacy*/ )
1377 pDevExt->fLoggingEnabled = VBDrvCommonIsOptionValueTrue(pszValue);
1378 else if ( RTStrNICmpAscii(pszName, RT_STR_TUPLE("log")) == 0
1379 || RTStrNICmpAscii(pszName, RT_STR_TUPLE("dbg_log")) == 0)
1380 {
1381 bool const fLogRel = *pszName == 'd' || *pszName == 'D';
1382 const char *pszSubName = &pszName[fLogRel ? 4 + 3 : 3];
1383 if ( !*pszSubName
1384 || RTStrICmpAscii(pszSubName, "_flags") == 0
1385 || RTStrICmpAscii(pszSubName, "_dest") == 0)
1386 {
1387 PRTLOGGER pLogger = fLogRel ? RTLogRelGetDefaultInstance() : RTLogDefaultInstance();
1388 if (pLogger)
1389 {
1390 if (!*pszSubName)
1391 RTLogGroupSettings(pLogger, pszValue);
1392 else if (RTStrICmpAscii(pszSubName, "_flags"))
1393 RTLogFlags(pLogger, pszValue);
1394 else
1395 RTLogDestinations(pLogger, pszValue);
1396 }
1397 }
1398 else if (!VGDrvNativeProcessOption(pDevExt, pszName, pszValue))
1399 LogRel(("VBoxGuest: Ignoring unknown option '%s' (value '%s')\n", pszName, pszValue));
1400 }
1401 else if (!VGDrvNativeProcessOption(pDevExt, pszName, pszValue))
1402 LogRel(("VBoxGuest: Ignoring unknown option '%s' (value '%s')\n", pszName, pszValue));
1403}
1404
1405
1406/**
1407 * Read driver configuration from the host.
1408 *
1409 * This involves connecting to the guest properties service, which means that
1410 * interrupts needs to work and that the calling thread must be able to block.
1411 *
1412 * @param pDevExt The device extension.
1413 */
1414void VGDrvCommonProcessOptionsFromHost(PVBOXGUESTDEVEXT pDevExt)
1415{
1416 /*
1417 * Create a kernel session without our selves, then connect to the HGCM service.
1418 */
1419 PVBOXGUESTSESSION pSession;
1420 int rc = VGDrvCommonCreateKernelSession(pDevExt, &pSession);
1421 if (RT_SUCCESS(rc))
1422 {
1423 union
1424 {
1425 VBGLIOCHGCMCONNECT Connect;
1426 VBGLIOCHGCMDISCONNECT Disconnect;
1427 GuestPropMsgEnumProperties EnumMsg;
1428 } uBuf;
1429
1430 RT_ZERO(uBuf.Connect);
1431 VBGLREQHDR_INIT(&uBuf.Connect.Hdr, HGCM_CONNECT);
1432 uBuf.Connect.u.In.Loc.type = VMMDevHGCMLoc_LocalHost_Existing;
1433 RTStrCopy(uBuf.Connect.u.In.Loc.u.host.achName, sizeof(uBuf.Connect.u.In.Loc.u.host.achName),
1434 "VBoxGuestPropSvc"); /** @todo Add a define to the header for the name. */
1435 rc = VGDrvCommonIoCtl(VBGL_IOCTL_HGCM_CONNECT, pDevExt, pSession, &uBuf.Connect.Hdr, sizeof(uBuf.Connect));
1436 if (RT_SUCCESS(rc))
1437 {
1438 static const char g_szzPattern[] = "/VirtualBox/GuestAdd/VBoxGuest/*\0";
1439 uint32_t const idClient = uBuf.Connect.u.Out.idClient;
1440 char *pszzStrings = NULL;
1441 uint32_t cbStrings;
1442
1443 /*
1444 * Enumerate all the relevant properties. We try with a 1KB buffer, but
1445 * will double it until we get what we want or go beyond 16KB.
1446 */
1447 for (cbStrings = _1K; cbStrings <= _16K; cbStrings *= 2)
1448 {
1449 pszzStrings = (char *)RTMemAllocZ(cbStrings);
1450 if (pszzStrings)
1451 {
1452 VBGL_HGCM_HDR_INIT(&uBuf.EnumMsg.hdr, idClient, GUEST_PROP_FN_ENUM_PROPS, 3);
1453
1454 uBuf.EnumMsg.patterns.type = VMMDevHGCMParmType_LinAddr;
1455 uBuf.EnumMsg.patterns.u.Pointer.size = sizeof(g_szzPattern);
1456 uBuf.EnumMsg.patterns.u.Pointer.u.linearAddr = (uintptr_t)g_szzPattern;
1457
1458 uBuf.EnumMsg.strings.type = VMMDevHGCMParmType_LinAddr;
1459 uBuf.EnumMsg.strings.u.Pointer.size = cbStrings;
1460 uBuf.EnumMsg.strings.u.Pointer.u.linearAddr = (uintptr_t)pszzStrings;
1461
1462 uBuf.EnumMsg.size.type = VMMDevHGCMParmType_32bit;
1463 uBuf.EnumMsg.size.u.value32 = 0;
1464
1465 rc = VGDrvCommonIoCtl(VBGL_IOCTL_HGCM_CALL(sizeof(uBuf.EnumMsg)), pDevExt, pSession,
1466 &uBuf.EnumMsg.hdr.Hdr, sizeof(uBuf.EnumMsg));
1467 if (RT_SUCCESS(rc))
1468 {
1469 if ( uBuf.EnumMsg.size.type == VMMDevHGCMParmType_32bit
1470 && uBuf.EnumMsg.size.u.value32 <= cbStrings
1471 && uBuf.EnumMsg.size.u.value32 > 0)
1472 cbStrings = uBuf.EnumMsg.size.u.value32;
1473 Log(("VGDrvCommonReadConfigurationFromHost: GUEST_PROP_FN_ENUM_PROPS -> %#x bytes (cbStrings=%#x)\n",
1474 uBuf.EnumMsg.size.u.value32, cbStrings));
1475 break;
1476 }
1477
1478 RTMemFree(pszzStrings);
1479 pszzStrings = NULL;
1480 }
1481 else
1482 {
1483 LogRel(("VGDrvCommonReadConfigurationFromHost: failed to allocate %#x bytes\n", cbStrings));
1484 break;
1485 }
1486 }
1487
1488 /*
1489 * Disconnect and destroy the session.
1490 */
1491 VBGLREQHDR_INIT(&uBuf.Disconnect.Hdr, HGCM_DISCONNECT);
1492 uBuf.Disconnect.u.In.idClient = idClient;
1493 VGDrvCommonIoCtl(VBGL_IOCTL_HGCM_DISCONNECT, pDevExt, pSession, &uBuf.Disconnect.Hdr, sizeof(uBuf.Disconnect));
1494
1495 VGDrvCommonCloseSession(pDevExt, pSession);
1496
1497 /*
1498 * Process the properties if we got any.
1499 *
1500 * The string buffer contains packed strings in groups of four - name, value,
1501 * timestamp (as a decimal string) and flags. It is terminated by four empty
1502 * strings. Layout:
1503 * Name\0Value\0Timestamp\0Flags\0
1504 */
1505 if (pszzStrings)
1506 {
1507 uint32_t off;
1508 for (off = 0; off < cbStrings; off++)
1509 {
1510 /*
1511 * Parse the four fields, checking that it's all plain ASCII w/o any control characters.
1512 */
1513 const char *apszFields[4] = { NULL, NULL, NULL, NULL };
1514 bool fValidFields = true;
1515 unsigned iField;
1516 for (iField = 0; iField < RT_ELEMENTS(apszFields); iField++)
1517 {
1518 apszFields[0] = &pszzStrings[off];
1519 while (off < cbStrings)
1520 {
1521 char ch = pszzStrings[off++];
1522 if ((unsigned)ch < 0x20U || (unsigned)ch > 0x7fU)
1523 {
1524 if (!ch)
1525 break;
1526 if (fValidFields)
1527 Log(("VGDrvCommonReadConfigurationFromHost: Invalid char %#x at %#x (field %u)\n",
1528 ch, off - 1, iField));
1529 fValidFields = false;
1530 }
1531 }
1532 }
1533 if ( off <= cbStrings
1534 && fValidFields
1535 && *apszFields[0] != '\0')
1536 {
1537 /*
1538 * Validate and convert the flags to integer, then process the option.
1539 */
1540 uint32_t fFlags = 0;
1541 rc = GuestPropValidateFlags(apszFields[3], &fFlags);
1542 if (RT_SUCCESS(rc))
1543 {
1544 if (fFlags & GUEST_PROP_F_RDONLYGUEST)
1545 {
1546 apszFields[0] += sizeof(g_szzPattern) - 2;
1547 VGDrvCommonProcessOption(pDevExt, apszFields[0], apszFields[1]);
1548 }
1549 else
1550 LogRel(("VBoxGuest: Ignoring '%s' as it does not have RDONLYGUEST set\n", apszFields[0]));
1551 }
1552 else
1553 LogRel(("VBoxGuest: Invalid flags '%s' for '%s': %Rrc\n", apszFields[2], apszFields[0], rc));
1554 }
1555 else if (off < cbStrings)
1556 {
1557 LogRel(("VBoxGuest: Malformed guest properties enum result!\n"));
1558 Log(("VBoxGuest: off=%#x cbStrings=%#x\n%.*Rhxd\n", off, cbStrings, cbStrings, pszzStrings));
1559 break;
1560 }
1561 else if (!fValidFields)
1562 LogRel(("VBoxGuest: Ignoring %.*Rhxs as it has invalid characters in one or more fields\n",
1563 (int)strlen(apszFields[0]), apszFields[0]));
1564 else
1565 break;
1566 }
1567
1568 RTMemFree(pszzStrings);
1569 }
1570 else
1571 LogRel(("VGDrvCommonReadConfigurationFromHost: failed to enumerate '%s': %Rrc\n", g_szzPattern, rc));
1572
1573 }
1574 else
1575 LogRel(("VGDrvCommonReadConfigurationFromHost: failed to connect: %Rrc\n", rc));
1576 }
1577 else
1578 LogRel(("VGDrvCommonReadConfigurationFromHost: failed to connect: %Rrc\n", rc));
1579}
1580
1581
1582/**
1583 * Destroys the VBoxGuest device extension.
1584 *
1585 * The native code should call this before the driver is loaded,
1586 * but don't call this on shutdown.
1587 *
1588 * @param pDevExt The device extension.
1589 */
1590void VGDrvCommonDeleteDevExt(PVBOXGUESTDEVEXT pDevExt)
1591{
1592 Log(("VGDrvCommonDeleteDevExt:\n"));
1593 Log(("VBoxGuest: The additions driver is terminating.\n"));
1594 VGDrvCommonDeleteDevExtResources(pDevExt);
1595 VGDrvCommonDeleteDevExtFundament(pDevExt);
1596 VGDrvCommonDestroyLoggers();
1597}
1598
1599
1600/**
1601 * Creates a VBoxGuest user session.
1602 *
1603 * The native code calls this when a ring-3 client opens the device.
1604 * Use VGDrvCommonCreateKernelSession when a ring-0 client connects.
1605 *
1606 * @returns VBox status code.
1607 * @param pDevExt The device extension.
1608 * @param fRequestor VMMDEV_REQUESTOR_XXX.
1609 * @param ppSession Where to store the session on success.
1610 */
1611int VGDrvCommonCreateUserSession(PVBOXGUESTDEVEXT pDevExt, uint32_t fRequestor, PVBOXGUESTSESSION *ppSession)
1612{
1613 PVBOXGUESTSESSION pSession = (PVBOXGUESTSESSION)RTMemAllocZ(sizeof(*pSession));
1614 if (RT_UNLIKELY(!pSession))
1615 {
1616 LogRel(("VGDrvCommonCreateUserSession: no memory!\n"));
1617 return VERR_NO_MEMORY;
1618 }
1619
1620 pSession->Process = RTProcSelf();
1621 pSession->R0Process = RTR0ProcHandleSelf();
1622 pSession->pDevExt = pDevExt;
1623 pSession->fRequestor = fRequestor;
1624 pSession->fUserSession = RT_BOOL(fRequestor & VMMDEV_REQUESTOR_USER_DEVICE);
1625 RTSpinlockAcquire(pDevExt->SessionSpinlock);
1626 RTListAppend(&pDevExt->SessionList, &pSession->ListNode);
1627 pDevExt->cSessions++;
1628 RTSpinlockRelease(pDevExt->SessionSpinlock);
1629
1630 *ppSession = pSession;
1631 LogFlow(("VGDrvCommonCreateUserSession: pSession=%p proc=%RTproc (%d) r0proc=%p\n",
1632 pSession, pSession->Process, (int)pSession->Process, (uintptr_t)pSession->R0Process)); /** @todo %RTr0proc */
1633 return VINF_SUCCESS;
1634}
1635
1636
1637/**
1638 * Creates a VBoxGuest kernel session.
1639 *
1640 * The native code calls this when a ring-0 client connects to the device.
1641 * Use VGDrvCommonCreateUserSession when a ring-3 client opens the device.
1642 *
1643 * @returns VBox status code.
1644 * @param pDevExt The device extension.
1645 * @param ppSession Where to store the session on success.
1646 */
1647int VGDrvCommonCreateKernelSession(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION *ppSession)
1648{
1649 PVBOXGUESTSESSION pSession = (PVBOXGUESTSESSION)RTMemAllocZ(sizeof(*pSession));
1650 if (RT_UNLIKELY(!pSession))
1651 {
1652 LogRel(("VGDrvCommonCreateKernelSession: no memory!\n"));
1653 return VERR_NO_MEMORY;
1654 }
1655
1656 pSession->Process = NIL_RTPROCESS;
1657 pSession->R0Process = NIL_RTR0PROCESS;
1658 pSession->pDevExt = pDevExt;
1659 pSession->fRequestor = VMMDEV_REQUESTOR_KERNEL | VMMDEV_REQUESTOR_USR_DRV_OTHER
1660 | VMMDEV_REQUESTOR_CON_DONT_KNOW | VMMDEV_REQUESTOR_TRUST_NOT_GIVEN;
1661 RTSpinlockAcquire(pDevExt->SessionSpinlock);
1662 RTListAppend(&pDevExt->SessionList, &pSession->ListNode);
1663 pDevExt->cSessions++;
1664 RTSpinlockRelease(pDevExt->SessionSpinlock);
1665
1666 *ppSession = pSession;
1667 LogFlow(("VGDrvCommonCreateKernelSession: pSession=%p proc=%RTproc (%d) r0proc=%p\n",
1668 pSession, pSession->Process, (int)pSession->Process, (uintptr_t)pSession->R0Process)); /** @todo %RTr0proc */
1669 return VINF_SUCCESS;
1670}
1671
1672
1673/**
1674 * Closes a VBoxGuest session.
1675 *
1676 * @param pDevExt The device extension.
1677 * @param pSession The session to close (and free).
1678 */
1679void VGDrvCommonCloseSession(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession)
1680{
1681#ifdef VBOX_WITH_HGCM
1682 unsigned i;
1683#endif
1684 LogFlow(("VGDrvCommonCloseSession: pSession=%p proc=%RTproc (%d) r0proc=%p\n",
1685 pSession, pSession->Process, (int)pSession->Process, (uintptr_t)pSession->R0Process)); /** @todo %RTr0proc */
1686
1687 RTSpinlockAcquire(pDevExt->SessionSpinlock);
1688 RTListNodeRemove(&pSession->ListNode);
1689 pDevExt->cSessions--;
1690 RTSpinlockRelease(pDevExt->SessionSpinlock);
1691 vgdrvAcquireSessionCapabilities(pDevExt, pSession, 0, UINT32_MAX, VBGL_IOC_AGC_FLAGS_DEFAULT, true /*fSessionTermination*/);
1692 vgdrvSetSessionCapabilities(pDevExt, pSession, 0 /*fOrMask*/, UINT32_MAX /*fNotMask*/,
1693 NULL /*pfSessionCaps*/, NULL /*pfGlobalCaps*/, true /*fSessionTermination*/);
1694 vgdrvSetSessionEventFilter(pDevExt, pSession, 0 /*fOrMask*/, UINT32_MAX /*fNotMask*/, true /*fSessionTermination*/);
1695 vgdrvSetSessionMouseStatus(pDevExt, pSession, 0 /*fOrMask*/, UINT32_MAX /*fNotMask*/, true /*fSessionTermination*/);
1696
1697 vgdrvIoCtl_CancelAllWaitEvents(pDevExt, pSession);
1698
1699#ifdef VBOX_WITH_HGCM
1700 for (i = 0; i < RT_ELEMENTS(pSession->aHGCMClientIds); i++)
1701 if (pSession->aHGCMClientIds[i])
1702 {
1703 uint32_t idClient = pSession->aHGCMClientIds[i];
1704 pSession->aHGCMClientIds[i] = 0;
1705 Log(("VGDrvCommonCloseSession: disconnecting client id %#RX32\n", idClient));
1706 VbglR0HGCMInternalDisconnect(idClient, VMMDEV_REQUESTOR_KERNEL | VMMDEV_REQUESTOR_USR_DRV,
1707 vgdrvHgcmAsyncWaitCallback, pDevExt, RT_INDEFINITE_WAIT);
1708 }
1709#endif
1710
1711 pSession->pDevExt = NULL;
1712 pSession->Process = NIL_RTPROCESS;
1713 pSession->R0Process = NIL_RTR0PROCESS;
1714 vgdrvCloseMemBalloon(pDevExt, pSession);
1715 RTMemFree(pSession);
1716}
1717
1718
1719/**
1720 * Allocates a wait-for-event entry.
1721 *
1722 * @returns The wait-for-event entry.
1723 * @param pDevExt The device extension.
1724 * @param pSession The session that's allocating this. Can be NULL.
1725 */
1726static PVBOXGUESTWAIT vgdrvWaitAlloc(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession)
1727{
1728 /*
1729 * Allocate it one way or the other.
1730 */
1731 PVBOXGUESTWAIT pWait = RTListGetFirst(&pDevExt->FreeList, VBOXGUESTWAIT, ListNode);
1732 if (pWait)
1733 {
1734 RTSpinlockAcquire(pDevExt->EventSpinlock);
1735
1736 pWait = RTListGetFirst(&pDevExt->FreeList, VBOXGUESTWAIT, ListNode);
1737 if (pWait)
1738 RTListNodeRemove(&pWait->ListNode);
1739
1740 RTSpinlockRelease(pDevExt->EventSpinlock);
1741 }
1742 if (!pWait)
1743 {
1744 int rc;
1745
1746 pWait = (PVBOXGUESTWAIT)RTMemAlloc(sizeof(*pWait));
1747 if (!pWait)
1748 {
1749 LogRelMax(32, ("vgdrvWaitAlloc: out-of-memory!\n"));
1750 return NULL;
1751 }
1752
1753 rc = RTSemEventMultiCreate(&pWait->Event);
1754 if (RT_FAILURE(rc))
1755 {
1756 LogRelMax(32, ("vgdrvWaitAlloc: RTSemEventMultiCreate failed with rc=%Rrc!\n", rc));
1757 RTMemFree(pWait);
1758 return NULL;
1759 }
1760
1761 pWait->ListNode.pNext = NULL;
1762 pWait->ListNode.pPrev = NULL;
1763 }
1764
1765 /*
1766 * Zero members just as an precaution.
1767 */
1768 pWait->fReqEvents = 0;
1769 pWait->fResEvents = 0;
1770#ifdef VBOXGUEST_USE_DEFERRED_WAKE_UP
1771 pWait->fPendingWakeUp = false;
1772 pWait->fFreeMe = false;
1773#endif
1774 pWait->pSession = pSession;
1775#ifdef VBOX_WITH_HGCM
1776 pWait->pHGCMReq = NULL;
1777#endif
1778 RTSemEventMultiReset(pWait->Event);
1779 return pWait;
1780}
1781
1782
1783/**
1784 * Frees the wait-for-event entry.
1785 *
1786 * The caller must own the wait spinlock !
1787 * The entry must be in a list!
1788 *
1789 * @param pDevExt The device extension.
1790 * @param pWait The wait-for-event entry to free.
1791 */
1792static void vgdrvWaitFreeLocked(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTWAIT pWait)
1793{
1794 pWait->fReqEvents = 0;
1795 pWait->fResEvents = 0;
1796#ifdef VBOX_WITH_HGCM
1797 pWait->pHGCMReq = NULL;
1798#endif
1799#ifdef VBOXGUEST_USE_DEFERRED_WAKE_UP
1800 Assert(!pWait->fFreeMe);
1801 if (pWait->fPendingWakeUp)
1802 pWait->fFreeMe = true;
1803 else
1804#endif
1805 {
1806 RTListNodeRemove(&pWait->ListNode);
1807 RTListAppend(&pDevExt->FreeList, &pWait->ListNode);
1808 }
1809}
1810
1811
1812/**
1813 * Frees the wait-for-event entry.
1814 *
1815 * @param pDevExt The device extension.
1816 * @param pWait The wait-for-event entry to free.
1817 */
1818static void vgdrvWaitFreeUnlocked(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTWAIT pWait)
1819{
1820 RTSpinlockAcquire(pDevExt->EventSpinlock);
1821 vgdrvWaitFreeLocked(pDevExt, pWait);
1822 RTSpinlockRelease(pDevExt->EventSpinlock);
1823}
1824
1825
1826#ifdef VBOXGUEST_USE_DEFERRED_WAKE_UP
1827/**
1828 * Processes the wake-up list.
1829 *
1830 * All entries in the wake-up list gets signalled and moved to the woken-up
1831 * list.
1832 * At least on Windows this function can be invoked concurrently from
1833 * different VCPUs. So, be thread-safe.
1834 *
1835 * @param pDevExt The device extension.
1836 */
1837void VGDrvCommonWaitDoWakeUps(PVBOXGUESTDEVEXT pDevExt)
1838{
1839 if (!RTListIsEmpty(&pDevExt->WakeUpList))
1840 {
1841 RTSpinlockAcquire(pDevExt->EventSpinlock);
1842 for (;;)
1843 {
1844 int rc;
1845 PVBOXGUESTWAIT pWait = RTListGetFirst(&pDevExt->WakeUpList, VBOXGUESTWAIT, ListNode);
1846 if (!pWait)
1847 break;
1848 /* Prevent other threads from accessing pWait when spinlock is released. */
1849 RTListNodeRemove(&pWait->ListNode);
1850
1851 pWait->fPendingWakeUp = true;
1852 RTSpinlockRelease(pDevExt->EventSpinlock);
1853
1854 rc = RTSemEventMultiSignal(pWait->Event);
1855 AssertRC(rc);
1856
1857 RTSpinlockAcquire(pDevExt->EventSpinlock);
1858 Assert(pWait->ListNode.pNext == NULL && pWait->ListNode.pPrev == NULL);
1859 RTListAppend(&pDevExt->WokenUpList, &pWait->ListNode);
1860 pWait->fPendingWakeUp = false;
1861 if (RT_LIKELY(!pWait->fFreeMe))
1862 { /* likely */ }
1863 else
1864 {
1865 pWait->fFreeMe = false;
1866 vgdrvWaitFreeLocked(pDevExt, pWait);
1867 }
1868 }
1869 RTSpinlockRelease(pDevExt->EventSpinlock);
1870 }
1871}
1872#endif /* VBOXGUEST_USE_DEFERRED_WAKE_UP */
1873
1874
1875/**
1876 * Implements the fast (no input or output) type of IOCtls.
1877 *
1878 * This is currently just a placeholder stub inherited from the support driver code.
1879 *
1880 * @returns VBox status code.
1881 * @param iFunction The IOCtl function number.
1882 * @param pDevExt The device extension.
1883 * @param pSession The session.
1884 */
1885int VGDrvCommonIoCtlFast(uintptr_t iFunction, PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession)
1886{
1887 LogFlow(("VGDrvCommonIoCtlFast: iFunction=%#x pDevExt=%p pSession=%p\n", iFunction, pDevExt, pSession));
1888
1889 NOREF(iFunction);
1890 NOREF(pDevExt);
1891 NOREF(pSession);
1892 return VERR_NOT_SUPPORTED;
1893}
1894
1895
1896/**
1897 * Gets the driver I/O control interface version, maybe adjusting it for
1898 * backwards compatibility.
1899 *
1900 * The adjusting is currently not implemented as we only have one major I/O
1901 * control interface version out there to support. This is something we will
1902 * implement as needed.
1903 *
1904 * returns IPRT status code.
1905 * @param pDevExt The device extension.
1906 * @param pSession The session.
1907 * @param pReq The request info.
1908 */
1909static int vgdrvIoCtl_DriverVersionInfo(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, PVBGLIOCDRIVERVERSIONINFO pReq)
1910{
1911 int rc;
1912 LogFlow(("VBGL_IOCTL_DRIVER_VERSION_INFO: uReqVersion=%#x uMinVersion=%#x uReserved1=%#x uReserved2=%#x\n",
1913 pReq->u.In.uReqVersion, pReq->u.In.uMinVersion, pReq->u.In.uReserved1, pReq->u.In.uReserved2));
1914 RT_NOREF2(pDevExt, pSession);
1915
1916 /*
1917 * Input validation.
1918 */
1919 if ( pReq->u.In.uMinVersion <= pReq->u.In.uReqVersion
1920 && RT_HI_U16(pReq->u.In.uMinVersion) == RT_HI_U16(pReq->u.In.uReqVersion))
1921 {
1922 /*
1923 * Match the version.
1924 * The current logic is very simple, match the major interface version.
1925 */
1926 if ( pReq->u.In.uMinVersion <= VBGL_IOC_VERSION
1927 && RT_HI_U16(pReq->u.In.uMinVersion) == RT_HI_U16(VBGL_IOC_VERSION))
1928 rc = VINF_SUCCESS;
1929 else
1930 {
1931 LogRel(("VBGL_IOCTL_DRIVER_VERSION_INFO: Version mismatch. Requested: %#x Min: %#x Current: %#x\n",
1932 pReq->u.In.uReqVersion, pReq->u.In.uMinVersion, VBGL_IOC_VERSION));
1933 rc = VERR_VERSION_MISMATCH;
1934 }
1935 }
1936 else
1937 {
1938 LogRel(("VBGL_IOCTL_DRIVER_VERSION_INFO: uMinVersion=%#x uMaxVersion=%#x doesn't match!\n",
1939 pReq->u.In.uMinVersion, pReq->u.In.uReqVersion));
1940 rc = VERR_INVALID_PARAMETER;
1941 }
1942
1943 pReq->u.Out.uSessionVersion = RT_SUCCESS(rc) ? VBGL_IOC_VERSION : UINT32_MAX;
1944 pReq->u.Out.uDriverVersion = VBGL_IOC_VERSION;
1945 pReq->u.Out.uDriverRevision = VBOX_SVN_REV;
1946 pReq->u.Out.uReserved1 = 0;
1947 pReq->u.Out.uReserved2 = 0;
1948 return rc;
1949}
1950
1951
1952/**
1953 * Similar to vgdrvIoCtl_DriverVersionInfo, except its for IDC.
1954 *
1955 * returns IPRT status code.
1956 * @param pDevExt The device extension.
1957 * @param pSession The session.
1958 * @param pReq The request info.
1959 */
1960static int vgdrvIoCtl_IdcConnect(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, PVBGLIOCIDCCONNECT pReq)
1961{
1962 int rc;
1963 LogFlow(("VBGL_IOCTL_IDC_CONNECT: u32MagicCookie=%#x uReqVersion=%#x uMinVersion=%#x uReserved=%#x\n",
1964 pReq->u.In.u32MagicCookie, pReq->u.In.uReqVersion, pReq->u.In.uMinVersion, pReq->u.In.uReserved));
1965 Assert(pSession != NULL);
1966 RT_NOREF(pDevExt);
1967
1968 /*
1969 * Input validation.
1970 */
1971 if (pReq->u.In.u32MagicCookie == VBGL_IOCTL_IDC_CONNECT_MAGIC_COOKIE)
1972 {
1973 if ( pReq->u.In.uMinVersion <= pReq->u.In.uReqVersion
1974 && RT_HI_U16(pReq->u.In.uMinVersion) == RT_HI_U16(pReq->u.In.uReqVersion))
1975 {
1976 /*
1977 * Match the version.
1978 * The current logic is very simple, match the major interface version.
1979 */
1980 if ( pReq->u.In.uMinVersion <= VBGL_IOC_VERSION
1981 && RT_HI_U16(pReq->u.In.uMinVersion) == RT_HI_U16(VBGL_IOC_VERSION))
1982 {
1983 pReq->u.Out.pvSession = pSession;
1984 pReq->u.Out.uSessionVersion = VBGL_IOC_VERSION;
1985 pReq->u.Out.uDriverVersion = VBGL_IOC_VERSION;
1986 pReq->u.Out.uDriverRevision = VBOX_SVN_REV;
1987 pReq->u.Out.uReserved1 = 0;
1988 pReq->u.Out.pvReserved2 = NULL;
1989 return VINF_SUCCESS;
1990
1991 }
1992 LogRel(("VBGL_IOCTL_IDC_CONNECT: Version mismatch. Requested: %#x Min: %#x Current: %#x\n",
1993 pReq->u.In.uReqVersion, pReq->u.In.uMinVersion, VBGL_IOC_VERSION));
1994 rc = VERR_VERSION_MISMATCH;
1995 }
1996 else
1997 {
1998 LogRel(("VBGL_IOCTL_IDC_CONNECT: uMinVersion=%#x uMaxVersion=%#x doesn't match!\n",
1999 pReq->u.In.uMinVersion, pReq->u.In.uReqVersion));
2000 rc = VERR_INVALID_PARAMETER;
2001 }
2002
2003 pReq->u.Out.pvSession = NULL;
2004 pReq->u.Out.uSessionVersion = UINT32_MAX;
2005 pReq->u.Out.uDriverVersion = VBGL_IOC_VERSION;
2006 pReq->u.Out.uDriverRevision = VBOX_SVN_REV;
2007 pReq->u.Out.uReserved1 = 0;
2008 pReq->u.Out.pvReserved2 = NULL;
2009 }
2010 else
2011 {
2012 LogRel(("VBGL_IOCTL_IDC_CONNECT: u32MagicCookie=%#x expected %#x!\n",
2013 pReq->u.In.u32MagicCookie, VBGL_IOCTL_IDC_CONNECT_MAGIC_COOKIE));
2014 rc = VERR_INVALID_PARAMETER;
2015 }
2016 return rc;
2017}
2018
2019
2020/**
2021 * Counterpart to vgdrvIoCtl_IdcConnect, destroys the session.
2022 *
2023 * returns IPRT status code.
2024 * @param pDevExt The device extension.
2025 * @param pSession The session.
2026 * @param pReq The request info.
2027 */
2028static int vgdrvIoCtl_IdcDisconnect(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, PVBGLIOCIDCDISCONNECT pReq)
2029{
2030 LogFlow(("VBGL_IOCTL_IDC_DISCONNECT: pvSession=%p vs pSession=%p\n", pReq->u.In.pvSession, pSession));
2031 RT_NOREF(pDevExt);
2032 Assert(pSession != NULL);
2033
2034 if (pReq->u.In.pvSession == pSession)
2035 {
2036 VGDrvCommonCloseSession(pDevExt, pSession);
2037 return VINF_SUCCESS;
2038 }
2039 LogRel(("VBGL_IOCTL_IDC_DISCONNECT: In.pvSession=%p is not equal to pSession=%p!\n", pReq->u.In.pvSession, pSession));
2040 return VERR_INVALID_PARAMETER;
2041}
2042
2043
2044/**
2045 * Return the VMM device I/O info.
2046 *
2047 * returns IPRT status code.
2048 * @param pDevExt The device extension.
2049 * @param pInfo The request info.
2050 * @note Ring-0 only, caller checked.
2051 */
2052static int vgdrvIoCtl_GetVMMDevIoInfo(PVBOXGUESTDEVEXT pDevExt, PVBGLIOCGETVMMDEVIOINFO pInfo)
2053{
2054 LogFlow(("VBGL_IOCTL_GET_VMMDEV_IO_INFO\n"));
2055
2056 pInfo->u.Out.IoPort = pDevExt->IOPortBase;
2057 pInfo->u.Out.pvVmmDevMapping = pDevExt->pVMMDevMemory;
2058 pInfo->u.Out.auPadding[0] = 0;
2059#if HC_ARCH_BITS != 32
2060 pInfo->u.Out.auPadding[1] = 0;
2061 pInfo->u.Out.auPadding[2] = 0;
2062#endif
2063 return VINF_SUCCESS;
2064}
2065
2066
2067/**
2068 * Set the callback for the kernel mouse handler.
2069 *
2070 * returns IPRT status code.
2071 * @param pDevExt The device extension.
2072 * @param pNotify The new callback information.
2073 */
2074int vgdrvIoCtl_SetMouseNotifyCallback(PVBOXGUESTDEVEXT pDevExt, PVBGLIOCSETMOUSENOTIFYCALLBACK pNotify)
2075{
2076 LogFlow(("VBOXGUEST_IOCTL_SET_MOUSE_NOTIFY_CALLBACK: pfnNotify=%p pvUser=%p\n", pNotify->u.In.pfnNotify, pNotify->u.In.pvUser));
2077
2078#ifdef VBOXGUEST_MOUSE_NOTIFY_CAN_PREEMPT
2079 VGDrvNativeSetMouseNotifyCallback(pDevExt, pNotify);
2080#else
2081 RTSpinlockAcquire(pDevExt->EventSpinlock);
2082 pDevExt->pfnMouseNotifyCallback = pNotify->u.In.pfnNotify;
2083 pDevExt->pvMouseNotifyCallbackArg = pNotify->u.In.pvUser;
2084 RTSpinlockRelease(pDevExt->EventSpinlock);
2085#endif
2086 return VINF_SUCCESS;
2087}
2088
2089
2090/**
2091 * Worker vgdrvIoCtl_WaitEvent.
2092 *
2093 * The caller enters the spinlock, we leave it.
2094 *
2095 * @returns VINF_SUCCESS if we've left the spinlock and can return immediately.
2096 */
2097DECLINLINE(int) vbdgCheckWaitEventCondition(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession,
2098 PVBGLIOCWAITFOREVENTS pInfo, int iEvent, const uint32_t fReqEvents)
2099{
2100 uint32_t fMatches = pDevExt->f32PendingEvents & fReqEvents;
2101 if (fMatches & VBOXGUEST_ACQUIRE_STYLE_EVENTS)
2102 fMatches &= vgdrvGetAllowedEventMaskForSession(pDevExt, pSession);
2103 if (fMatches || pSession->fPendingCancelWaitEvents)
2104 {
2105 ASMAtomicAndU32(&pDevExt->f32PendingEvents, ~fMatches);
2106 RTSpinlockRelease(pDevExt->EventSpinlock);
2107
2108 pInfo->u.Out.fEvents = fMatches;
2109 if (fReqEvents & ~((uint32_t)1 << iEvent))
2110 LogFlow(("VBOXGUEST_IOCTL_WAITEVENT: returns %#x\n", pInfo->u.Out.fEvents));
2111 else
2112 LogFlow(("VBOXGUEST_IOCTL_WAITEVENT: returns %#x/%d\n", pInfo->u.Out.fEvents, iEvent));
2113 pSession->fPendingCancelWaitEvents = false;
2114 return VINF_SUCCESS;
2115 }
2116
2117 RTSpinlockRelease(pDevExt->EventSpinlock);
2118 return VERR_TIMEOUT;
2119}
2120
2121
2122static int vgdrvIoCtl_WaitForEvents(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession,
2123 PVBGLIOCWAITFOREVENTS pInfo, bool fInterruptible)
2124{
2125 uint32_t const cMsTimeout = pInfo->u.In.cMsTimeOut;
2126 const uint32_t fReqEvents = pInfo->u.In.fEvents;
2127 uint32_t fResEvents;
2128 int iEvent;
2129 PVBOXGUESTWAIT pWait;
2130 int rc;
2131
2132 pInfo->u.Out.fEvents = 0; /* Note! This overwrites pInfo->u.In.* fields! */
2133
2134 /*
2135 * Copy and verify the input mask.
2136 */
2137 iEvent = ASMBitFirstSetU32(fReqEvents) - 1;
2138 if (RT_UNLIKELY(iEvent < 0))
2139 {
2140 LogRel(("VBOXGUEST_IOCTL_WAITEVENT: Invalid input mask %#x!!\n", fReqEvents));
2141 return VERR_INVALID_PARAMETER;
2142 }
2143
2144 /*
2145 * Check the condition up front, before doing the wait-for-event allocations.
2146 */
2147 RTSpinlockAcquire(pDevExt->EventSpinlock);
2148 rc = vbdgCheckWaitEventCondition(pDevExt, pSession, pInfo, iEvent, fReqEvents);
2149 if (rc == VINF_SUCCESS)
2150 return rc;
2151
2152 if (!cMsTimeout)
2153 {
2154 LogFlow(("VBOXGUEST_IOCTL_WAITEVENT: returns VERR_TIMEOUT\n"));
2155 return VERR_TIMEOUT;
2156 }
2157
2158 pWait = vgdrvWaitAlloc(pDevExt, pSession);
2159 if (!pWait)
2160 return VERR_NO_MEMORY;
2161 pWait->fReqEvents = fReqEvents;
2162
2163 /*
2164 * We've got the wait entry now, re-enter the spinlock and check for the condition.
2165 * If the wait condition is met, return.
2166 * Otherwise enter into the list and go to sleep waiting for the ISR to signal us.
2167 */
2168 RTSpinlockAcquire(pDevExt->EventSpinlock);
2169 RTListAppend(&pDevExt->WaitList, &pWait->ListNode);
2170 rc = vbdgCheckWaitEventCondition(pDevExt, pSession, pInfo, iEvent, fReqEvents);
2171 if (rc == VINF_SUCCESS)
2172 {
2173 vgdrvWaitFreeUnlocked(pDevExt, pWait);
2174 return rc;
2175 }
2176
2177 if (fInterruptible)
2178 rc = RTSemEventMultiWaitNoResume(pWait->Event, cMsTimeout == UINT32_MAX ? RT_INDEFINITE_WAIT : cMsTimeout);
2179 else
2180 rc = RTSemEventMultiWait(pWait->Event, cMsTimeout == UINT32_MAX ? RT_INDEFINITE_WAIT : cMsTimeout);
2181
2182 /*
2183 * There is one special case here and that's when the semaphore is
2184 * destroyed upon device driver unload. This shouldn't happen of course,
2185 * but in case it does, just get out of here ASAP.
2186 */
2187 if (rc == VERR_SEM_DESTROYED)
2188 return rc;
2189
2190 /*
2191 * Unlink the wait item and dispose of it.
2192 */
2193 RTSpinlockAcquire(pDevExt->EventSpinlock);
2194 fResEvents = pWait->fResEvents;
2195 vgdrvWaitFreeLocked(pDevExt, pWait);
2196 RTSpinlockRelease(pDevExt->EventSpinlock);
2197
2198 /*
2199 * Now deal with the return code.
2200 */
2201 if ( fResEvents
2202 && fResEvents != UINT32_MAX)
2203 {
2204 pInfo->u.Out.fEvents = fResEvents;
2205 if (fReqEvents & ~((uint32_t)1 << iEvent))
2206 LogFlow(("VBOXGUEST_IOCTL_WAITEVENT: returns %#x\n", pInfo->u.Out.fEvents));
2207 else
2208 LogFlow(("VBOXGUEST_IOCTL_WAITEVENT: returns %#x/%d\n", pInfo->u.Out.fEvents, iEvent));
2209 rc = VINF_SUCCESS;
2210 }
2211 else if ( fResEvents == UINT32_MAX
2212 || rc == VERR_INTERRUPTED)
2213 {
2214 rc = VERR_INTERRUPTED;
2215 LogFlow(("VBOXGUEST_IOCTL_WAITEVENT: returns VERR_INTERRUPTED\n"));
2216 }
2217 else if (rc == VERR_TIMEOUT)
2218 LogFlow(("VBOXGUEST_IOCTL_WAITEVENT: returns VERR_TIMEOUT (2)\n"));
2219 else
2220 {
2221 if (RT_SUCCESS(rc))
2222 {
2223 LogRelMax(32, ("VBOXGUEST_IOCTL_WAITEVENT: returns %Rrc but no events!\n", rc));
2224 rc = VERR_INTERNAL_ERROR;
2225 }
2226 LogFlow(("VBOXGUEST_IOCTL_WAITEVENT: returns %Rrc\n", rc));
2227 }
2228
2229 return rc;
2230}
2231
2232
2233/** @todo the semantics of this IoCtl have been tightened, so that no calls to
2234 * VBOXGUEST_IOCTL_WAITEVENT are allowed in a session after it has been
2235 * called. Change the code to make calls to VBOXGUEST_IOCTL_WAITEVENT made
2236 * after that to return VERR_INTERRUPTED or something appropriate. */
2237static int vgdrvIoCtl_CancelAllWaitEvents(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession)
2238{
2239 PVBOXGUESTWAIT pWait;
2240 PVBOXGUESTWAIT pSafe;
2241 int rc = 0;
2242 /* Was as least one WAITEVENT in process for this session? If not we
2243 * set a flag that the next call should be interrupted immediately. This
2244 * is needed so that a user thread can reliably interrupt another one in a
2245 * WAITEVENT loop. */
2246 bool fCancelledOne = false;
2247
2248 LogFlow(("VBOXGUEST_IOCTL_CANCEL_ALL_WAITEVENTS\n"));
2249
2250 /*
2251 * Walk the event list and wake up anyone with a matching session.
2252 */
2253 RTSpinlockAcquire(pDevExt->EventSpinlock);
2254 RTListForEachSafe(&pDevExt->WaitList, pWait, pSafe, VBOXGUESTWAIT, ListNode)
2255 {
2256 if (pWait->pSession == pSession)
2257 {
2258 fCancelledOne = true;
2259 pWait->fResEvents = UINT32_MAX;
2260 RTListNodeRemove(&pWait->ListNode);
2261#ifdef VBOXGUEST_USE_DEFERRED_WAKE_UP
2262 RTListAppend(&pDevExt->WakeUpList, &pWait->ListNode);
2263#else
2264 rc |= RTSemEventMultiSignal(pWait->Event);
2265 RTListAppend(&pDevExt->WokenUpList, &pWait->ListNode);
2266#endif
2267 }
2268 }
2269 if (!fCancelledOne)
2270 pSession->fPendingCancelWaitEvents = true;
2271 RTSpinlockRelease(pDevExt->EventSpinlock);
2272 Assert(rc == 0);
2273 NOREF(rc);
2274
2275#ifdef VBOXGUEST_USE_DEFERRED_WAKE_UP
2276 VGDrvCommonWaitDoWakeUps(pDevExt);
2277#endif
2278
2279 return VINF_SUCCESS;
2280}
2281
2282
2283/**
2284 * Checks if the VMM request is allowed in the context of the given session.
2285 *
2286 * @returns VINF_SUCCESS or VERR_PERMISSION_DENIED.
2287 * @param pDevExt The device extension.
2288 * @param pSession The calling session.
2289 * @param enmType The request type.
2290 * @param pReqHdr The request.
2291 */
2292static int vgdrvCheckIfVmmReqIsAllowed(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, VMMDevRequestType enmType,
2293 VMMDevRequestHeader const *pReqHdr)
2294{
2295 /*
2296 * Categorize the request being made.
2297 */
2298 /** @todo This need quite some more work! */
2299 enum
2300 {
2301 kLevel_Invalid, kLevel_NoOne, kLevel_OnlyVBoxGuest, kLevel_OnlyKernel, kLevel_TrustedUsers, kLevel_AllUsers
2302 } enmRequired;
2303 RT_NOREF1(pDevExt);
2304
2305 switch (enmType)
2306 {
2307 /*
2308 * Deny access to anything we don't know or provide specialized I/O controls for.
2309 */
2310#ifdef VBOX_WITH_HGCM
2311 case VMMDevReq_HGCMConnect:
2312 case VMMDevReq_HGCMDisconnect:
2313# ifdef VBOX_WITH_64_BITS_GUESTS
2314 case VMMDevReq_HGCMCall32:
2315 case VMMDevReq_HGCMCall64:
2316# else
2317 case VMMDevReq_HGCMCall:
2318# endif /* VBOX_WITH_64_BITS_GUESTS */
2319 case VMMDevReq_HGCMCancel:
2320 case VMMDevReq_HGCMCancel2:
2321#endif /* VBOX_WITH_HGCM */
2322 case VMMDevReq_SetGuestCapabilities:
2323 default:
2324 enmRequired = kLevel_NoOne;
2325 break;
2326
2327 /*
2328 * There are a few things only this driver can do (and it doesn't use
2329 * the VMMRequst I/O control route anyway, but whatever).
2330 */
2331 case VMMDevReq_ReportGuestInfo:
2332 case VMMDevReq_ReportGuestInfo2:
2333 case VMMDevReq_GetHypervisorInfo:
2334 case VMMDevReq_SetHypervisorInfo:
2335 case VMMDevReq_RegisterPatchMemory:
2336 case VMMDevReq_DeregisterPatchMemory:
2337 case VMMDevReq_GetMemBalloonChangeRequest:
2338 enmRequired = kLevel_OnlyVBoxGuest;
2339 break;
2340
2341 /*
2342 * Trusted users apps only.
2343 */
2344 case VMMDevReq_QueryCredentials:
2345 case VMMDevReq_ReportCredentialsJudgement:
2346 case VMMDevReq_RegisterSharedModule:
2347 case VMMDevReq_UnregisterSharedModule:
2348 case VMMDevReq_WriteCoreDump:
2349 case VMMDevReq_GetCpuHotPlugRequest:
2350 case VMMDevReq_SetCpuHotPlugStatus:
2351 case VMMDevReq_CheckSharedModules:
2352 case VMMDevReq_GetPageSharingStatus:
2353 case VMMDevReq_DebugIsPageShared:
2354 case VMMDevReq_ReportGuestStats:
2355 case VMMDevReq_ReportGuestUserState:
2356 case VMMDevReq_GetStatisticsChangeRequest:
2357 case VMMDevReq_ChangeMemBalloon:
2358 enmRequired = kLevel_TrustedUsers;
2359 break;
2360
2361 /*
2362 * Anyone.
2363 */
2364 case VMMDevReq_GetMouseStatus:
2365 case VMMDevReq_SetMouseStatus:
2366 case VMMDevReq_SetPointerShape:
2367 case VMMDevReq_GetHostVersion:
2368 case VMMDevReq_Idle:
2369 case VMMDevReq_GetHostTime:
2370 case VMMDevReq_SetPowerStatus:
2371 case VMMDevReq_AcknowledgeEvents:
2372 case VMMDevReq_CtlGuestFilterMask:
2373 case VMMDevReq_ReportGuestStatus:
2374 case VMMDevReq_GetDisplayChangeRequest:
2375 case VMMDevReq_VideoModeSupported:
2376 case VMMDevReq_GetHeightReduction:
2377 case VMMDevReq_GetDisplayChangeRequest2:
2378 case VMMDevReq_VideoModeSupported2:
2379 case VMMDevReq_VideoAccelEnable:
2380 case VMMDevReq_VideoAccelFlush:
2381 case VMMDevReq_VideoSetVisibleRegion:
2382 case VMMDevReq_GetDisplayChangeRequestEx:
2383 case VMMDevReq_GetSeamlessChangeRequest:
2384 case VMMDevReq_GetVRDPChangeRequest:
2385 case VMMDevReq_LogString:
2386 case VMMDevReq_GetSessionId:
2387 enmRequired = kLevel_AllUsers;
2388 break;
2389
2390 /*
2391 * Depends on the request parameters...
2392 */
2393 /** @todo this have to be changed into an I/O control and the facilities
2394 * tracked in the session so they can automatically be failed when the
2395 * session terminates without reporting the new status.
2396 *
2397 * The information presented by IGuest is not reliable without this! */
2398 case VMMDevReq_ReportGuestCapabilities:
2399 switch (((VMMDevReportGuestStatus const *)pReqHdr)->guestStatus.facility)
2400 {
2401 case VBoxGuestFacilityType_All:
2402 case VBoxGuestFacilityType_VBoxGuestDriver:
2403 enmRequired = kLevel_OnlyVBoxGuest;
2404 break;
2405 case VBoxGuestFacilityType_VBoxService:
2406 enmRequired = kLevel_TrustedUsers;
2407 break;
2408 case VBoxGuestFacilityType_VBoxTrayClient:
2409 case VBoxGuestFacilityType_Seamless:
2410 case VBoxGuestFacilityType_Graphics:
2411 default:
2412 enmRequired = kLevel_AllUsers;
2413 break;
2414 }
2415 break;
2416 }
2417
2418 /*
2419 * Check against the session.
2420 */
2421 switch (enmRequired)
2422 {
2423 default:
2424 case kLevel_NoOne:
2425 break;
2426 case kLevel_OnlyVBoxGuest:
2427 case kLevel_OnlyKernel:
2428 if (pSession->R0Process == NIL_RTR0PROCESS)
2429 return VINF_SUCCESS;
2430 break;
2431 case kLevel_TrustedUsers:
2432 if (pSession->fUserSession)
2433 break;
2434 case kLevel_AllUsers:
2435 return VINF_SUCCESS;
2436 }
2437
2438 return VERR_PERMISSION_DENIED;
2439}
2440
2441static int vgdrvIoCtl_VMMDevRequest(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession,
2442 VMMDevRequestHeader *pReqHdr, size_t cbData)
2443{
2444 int rc;
2445 VMMDevRequestHeader *pReqCopy;
2446
2447 /*
2448 * Validate the header and request size.
2449 */
2450 const VMMDevRequestType enmType = pReqHdr->requestType;
2451 const uint32_t cbReq = pReqHdr->size;
2452 const uint32_t cbMinSize = (uint32_t)vmmdevGetRequestSize(enmType);
2453
2454 LogFlow(("VBOXGUEST_IOCTL_VMMREQUEST: type %d\n", pReqHdr->requestType));
2455
2456 if (cbReq < cbMinSize)
2457 {
2458 LogRel(("VBOXGUEST_IOCTL_VMMREQUEST: invalid hdr size %#x, expected >= %#x; type=%#x!!\n",
2459 cbReq, cbMinSize, enmType));
2460 return VERR_INVALID_PARAMETER;
2461 }
2462 if (cbReq > cbData)
2463 {
2464 LogRel(("VBOXGUEST_IOCTL_VMMREQUEST: invalid size %#x, expected >= %#x (hdr); type=%#x!!\n",
2465 cbData, cbReq, enmType));
2466 return VERR_INVALID_PARAMETER;
2467 }
2468 rc = VbglGR0Verify(pReqHdr, cbData);
2469 if (RT_FAILURE(rc))
2470 {
2471 Log(("VBOXGUEST_IOCTL_VMMREQUEST: invalid header: size %#x, expected >= %#x (hdr); type=%#x; rc=%Rrc!!\n",
2472 cbData, cbReq, enmType, rc));
2473 return rc;
2474 }
2475
2476 rc = vgdrvCheckIfVmmReqIsAllowed(pDevExt, pSession, enmType, pReqHdr);
2477 if (RT_FAILURE(rc))
2478 {
2479 Log(("VBOXGUEST_IOCTL_VMMREQUEST: Operation not allowed! type=%#x rc=%Rrc\n", enmType, rc));
2480 return rc;
2481 }
2482
2483 /*
2484 * Make a copy of the request in the physical memory heap so
2485 * the VBoxGuestLibrary can more easily deal with the request.
2486 * (This is really a waste of time since the OS or the OS specific
2487 * code has already buffered or locked the input/output buffer, but
2488 * it does makes things a bit simpler wrt to phys address.)
2489 */
2490 rc = VbglR0GRAlloc(&pReqCopy, cbReq, enmType);
2491 if (RT_FAILURE(rc))
2492 {
2493 Log(("VBOXGUEST_IOCTL_VMMREQUEST: failed to allocate %u (%#x) bytes to cache the request. rc=%Rrc!!\n",
2494 cbReq, cbReq, rc));
2495 return rc;
2496 }
2497 memcpy(pReqCopy, pReqHdr, cbReq);
2498 Assert(pReqCopy->reserved1 == cbReq);
2499 pReqCopy->reserved1 = 0; /* VGDrvCommonIoCtl or caller sets cbOut, so clear it. */
2500 pReqCopy->fRequestor = pSession->fRequestor;
2501
2502 if (enmType == VMMDevReq_GetMouseStatus) /* clear poll condition. */
2503 pSession->u32MousePosChangedSeq = ASMAtomicUoReadU32(&pDevExt->u32MousePosChangedSeq);
2504
2505 rc = VbglR0GRPerform(pReqCopy);
2506 if ( RT_SUCCESS(rc)
2507 && RT_SUCCESS(pReqCopy->rc))
2508 {
2509 Assert(rc != VINF_HGCM_ASYNC_EXECUTE);
2510 Assert(pReqCopy->rc != VINF_HGCM_ASYNC_EXECUTE);
2511
2512 memcpy(pReqHdr, pReqCopy, cbReq);
2513 pReqHdr->reserved1 = cbReq; /* preserve cbOut */
2514 }
2515 else if (RT_FAILURE(rc))
2516 Log(("VBOXGUEST_IOCTL_VMMREQUEST: VbglR0GRPerform - rc=%Rrc!\n", rc));
2517 else
2518 {
2519 Log(("VBOXGUEST_IOCTL_VMMREQUEST: request execution failed; VMMDev rc=%Rrc!\n", pReqCopy->rc));
2520 rc = pReqCopy->rc;
2521 }
2522
2523 VbglR0GRFree(pReqCopy);
2524 return rc;
2525}
2526
2527
2528#ifdef VBOX_WITH_HGCM
2529
2530AssertCompile(RT_INDEFINITE_WAIT == (uint32_t)RT_INDEFINITE_WAIT); /* assumed by code below */
2531
2532/** Worker for vgdrvHgcmAsyncWaitCallback*. */
2533static int vgdrvHgcmAsyncWaitCallbackWorker(VMMDevHGCMRequestHeader volatile *pHdr, PVBOXGUESTDEVEXT pDevExt,
2534 bool fInterruptible, uint32_t cMillies)
2535{
2536 int rc;
2537
2538 /*
2539 * Check to see if the condition was met by the time we got here.
2540 *
2541 * We create a simple poll loop here for dealing with out-of-memory
2542 * conditions since the caller isn't necessarily able to deal with
2543 * us returning too early.
2544 */
2545 PVBOXGUESTWAIT pWait;
2546 for (;;)
2547 {
2548 RTSpinlockAcquire(pDevExt->EventSpinlock);
2549 if ((pHdr->fu32Flags & VBOX_HGCM_REQ_DONE) != 0)
2550 {
2551 RTSpinlockRelease(pDevExt->EventSpinlock);
2552 return VINF_SUCCESS;
2553 }
2554 RTSpinlockRelease(pDevExt->EventSpinlock);
2555
2556 pWait = vgdrvWaitAlloc(pDevExt, NULL);
2557 if (pWait)
2558 break;
2559 if (fInterruptible)
2560 return VERR_INTERRUPTED;
2561 RTThreadSleep(1);
2562 }
2563 pWait->fReqEvents = VMMDEV_EVENT_HGCM;
2564 pWait->pHGCMReq = pHdr;
2565
2566 /*
2567 * Re-enter the spinlock and re-check for the condition.
2568 * If the condition is met, return.
2569 * Otherwise link us into the HGCM wait list and go to sleep.
2570 */
2571 RTSpinlockAcquire(pDevExt->EventSpinlock);
2572 RTListAppend(&pDevExt->HGCMWaitList, &pWait->ListNode);
2573 if ((pHdr->fu32Flags & VBOX_HGCM_REQ_DONE) != 0)
2574 {
2575 vgdrvWaitFreeLocked(pDevExt, pWait);
2576 RTSpinlockRelease(pDevExt->EventSpinlock);
2577 return VINF_SUCCESS;
2578 }
2579 RTSpinlockRelease(pDevExt->EventSpinlock);
2580
2581 if (fInterruptible)
2582 rc = RTSemEventMultiWaitNoResume(pWait->Event, cMillies);
2583 else
2584 rc = RTSemEventMultiWait(pWait->Event, cMillies);
2585 if (rc == VERR_SEM_DESTROYED)
2586 return rc;
2587
2588 /*
2589 * Unlink, free and return.
2590 */
2591 if ( RT_FAILURE(rc)
2592 && rc != VERR_TIMEOUT
2593 && ( !fInterruptible
2594 || rc != VERR_INTERRUPTED))
2595 LogRel(("vgdrvHgcmAsyncWaitCallback: wait failed! %Rrc\n", rc));
2596
2597 vgdrvWaitFreeUnlocked(pDevExt, pWait);
2598 return rc;
2599}
2600
2601
2602/**
2603 * This is a callback for dealing with async waits.
2604 *
2605 * It operates in a manner similar to vgdrvIoCtl_WaitEvent.
2606 */
2607static DECLCALLBACK(int) vgdrvHgcmAsyncWaitCallback(VMMDevHGCMRequestHeader *pHdr, void *pvUser, uint32_t u32User)
2608{
2609 PVBOXGUESTDEVEXT pDevExt = (PVBOXGUESTDEVEXT)pvUser;
2610 LogFlow(("vgdrvHgcmAsyncWaitCallback: requestType=%d\n", pHdr->header.requestType));
2611 return vgdrvHgcmAsyncWaitCallbackWorker((VMMDevHGCMRequestHeader volatile *)pHdr, pDevExt,
2612 false /* fInterruptible */, u32User /* cMillies */);
2613}
2614
2615
2616/**
2617 * This is a callback for dealing with async waits with a timeout.
2618 *
2619 * It operates in a manner similar to vgdrvIoCtl_WaitEvent.
2620 */
2621static DECLCALLBACK(int) vgdrvHgcmAsyncWaitCallbackInterruptible(VMMDevHGCMRequestHeader *pHdr, void *pvUser, uint32_t u32User)
2622{
2623 PVBOXGUESTDEVEXT pDevExt = (PVBOXGUESTDEVEXT)pvUser;
2624 LogFlow(("vgdrvHgcmAsyncWaitCallbackInterruptible: requestType=%d\n", pHdr->header.requestType));
2625 return vgdrvHgcmAsyncWaitCallbackWorker((VMMDevHGCMRequestHeader volatile *)pHdr, pDevExt,
2626 true /* fInterruptible */, u32User /* cMillies */);
2627}
2628
2629
2630static int vgdrvIoCtl_HGCMConnect(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, PVBGLIOCHGCMCONNECT pInfo)
2631{
2632 int rc;
2633 HGCMCLIENTID idClient = 0;
2634
2635 /*
2636 * The VbglHGCMConnect call will invoke the callback if the HGCM
2637 * call is performed in an ASYNC fashion. The function is not able
2638 * to deal with cancelled requests.
2639 */
2640 Log(("VBOXGUEST_IOCTL_HGCM_CONNECT: %.128s\n",
2641 pInfo->u.In.Loc.type == VMMDevHGCMLoc_LocalHost || pInfo->u.In.Loc.type == VMMDevHGCMLoc_LocalHost_Existing
2642 ? pInfo->u.In.Loc.u.host.achName : "<not local host>"));
2643
2644 rc = VbglR0HGCMInternalConnect(&pInfo->u.In.Loc, pSession->fRequestor, &idClient,
2645 vgdrvHgcmAsyncWaitCallback, pDevExt, RT_INDEFINITE_WAIT);
2646 Log(("VBOXGUEST_IOCTL_HGCM_CONNECT: idClient=%RX32 (rc=%Rrc)\n", idClient, rc));
2647 if (RT_SUCCESS(rc))
2648 {
2649 /*
2650 * Append the client id to the client id table.
2651 * If the table has somehow become filled up, we'll disconnect the session.
2652 */
2653 unsigned i;
2654 RTSpinlockAcquire(pDevExt->SessionSpinlock);
2655 for (i = 0; i < RT_ELEMENTS(pSession->aHGCMClientIds); i++)
2656 if (!pSession->aHGCMClientIds[i])
2657 {
2658 pSession->aHGCMClientIds[i] = idClient;
2659 break;
2660 }
2661 RTSpinlockRelease(pDevExt->SessionSpinlock);
2662 if (i >= RT_ELEMENTS(pSession->aHGCMClientIds))
2663 {
2664 LogRelMax(32, ("VBOXGUEST_IOCTL_HGCM_CONNECT: too many HGCMConnect calls for one session!\n"));
2665 VbglR0HGCMInternalDisconnect(idClient, pSession->fRequestor, vgdrvHgcmAsyncWaitCallback, pDevExt, RT_INDEFINITE_WAIT);
2666
2667 pInfo->u.Out.idClient = 0;
2668 return VERR_TOO_MANY_OPEN_FILES;
2669 }
2670 }
2671 pInfo->u.Out.idClient = idClient;
2672 return rc;
2673}
2674
2675
2676static int vgdrvIoCtl_HGCMDisconnect(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, PVBGLIOCHGCMDISCONNECT pInfo)
2677{
2678 /*
2679 * Validate the client id and invalidate its entry while we're in the call.
2680 */
2681 int rc;
2682 const uint32_t idClient = pInfo->u.In.idClient;
2683 unsigned i;
2684 RTSpinlockAcquire(pDevExt->SessionSpinlock);
2685 for (i = 0; i < RT_ELEMENTS(pSession->aHGCMClientIds); i++)
2686 if (pSession->aHGCMClientIds[i] == idClient)
2687 {
2688 pSession->aHGCMClientIds[i] = UINT32_MAX;
2689 break;
2690 }
2691 RTSpinlockRelease(pDevExt->SessionSpinlock);
2692 if (i >= RT_ELEMENTS(pSession->aHGCMClientIds))
2693 {
2694 LogRelMax(32, ("VBOXGUEST_IOCTL_HGCM_DISCONNECT: idClient=%RX32\n", idClient));
2695 return VERR_INVALID_HANDLE;
2696 }
2697
2698 /*
2699 * The VbglHGCMConnect call will invoke the callback if the HGCM
2700 * call is performed in an ASYNC fashion. The function is not able
2701 * to deal with cancelled requests.
2702 */
2703 Log(("VBOXGUEST_IOCTL_HGCM_DISCONNECT: idClient=%RX32\n", idClient));
2704 rc = VbglR0HGCMInternalDisconnect(idClient, pSession->fRequestor, vgdrvHgcmAsyncWaitCallback, pDevExt, RT_INDEFINITE_WAIT);
2705 LogFlow(("VBOXGUEST_IOCTL_HGCM_DISCONNECT: rc=%Rrc\n", rc));
2706
2707 /* Update the client id array according to the result. */
2708 RTSpinlockAcquire(pDevExt->SessionSpinlock);
2709 if (pSession->aHGCMClientIds[i] == UINT32_MAX)
2710 pSession->aHGCMClientIds[i] = RT_SUCCESS(rc) ? 0 : idClient;
2711 RTSpinlockRelease(pDevExt->SessionSpinlock);
2712
2713 return rc;
2714}
2715
2716
2717static int vgdrvIoCtl_HGCMCallInner(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, PVBGLIOCHGCMCALL pInfo,
2718 uint32_t cMillies, bool fInterruptible, bool f32bit, bool fUserData,
2719 size_t cbExtra, size_t cbData)
2720{
2721 const uint32_t u32ClientId = pInfo->u32ClientID;
2722 uint32_t fFlags;
2723 size_t cbActual;
2724 unsigned i;
2725 int rc;
2726
2727 /*
2728 * Some more validations.
2729 */
2730 if (pInfo->cParms > 4096) /* (Just make sure it doesn't overflow the next check.) */
2731 {
2732 LogRel(("VBOXGUEST_IOCTL_HGCM_CALL: cParm=%RX32 is not sane\n", pInfo->cParms));
2733 return VERR_INVALID_PARAMETER;
2734 }
2735
2736 cbActual = cbExtra + sizeof(*pInfo);
2737#ifdef RT_ARCH_AMD64
2738 if (f32bit)
2739 cbActual += pInfo->cParms * sizeof(HGCMFunctionParameter32);
2740 else
2741#endif
2742 cbActual += pInfo->cParms * sizeof(HGCMFunctionParameter);
2743 if (cbData < cbActual)
2744 {
2745 LogRel(("VBOXGUEST_IOCTL_HGCM_CALL: cbData=%#zx (%zu) required size is %#zx (%zu)\n",
2746 cbData, cbData, cbActual, cbActual));
2747 return VERR_INVALID_PARAMETER;
2748 }
2749 pInfo->Hdr.cbOut = (uint32_t)cbActual;
2750
2751 /*
2752 * Validate the client id.
2753 */
2754 RTSpinlockAcquire(pDevExt->SessionSpinlock);
2755 for (i = 0; i < RT_ELEMENTS(pSession->aHGCMClientIds); i++)
2756 if (pSession->aHGCMClientIds[i] == u32ClientId)
2757 break;
2758 RTSpinlockRelease(pDevExt->SessionSpinlock);
2759 if (RT_UNLIKELY(i >= RT_ELEMENTS(pSession->aHGCMClientIds)))
2760 {
2761 LogRelMax(32, ("VBOXGUEST_IOCTL_HGCM_CALL: Invalid handle. u32Client=%RX32\n", u32ClientId));
2762 return VERR_INVALID_HANDLE;
2763 }
2764
2765 /*
2766 * The VbglHGCMCall call will invoke the callback if the HGCM
2767 * call is performed in an ASYNC fashion. This function can
2768 * deal with cancelled requests, so we let user more requests
2769 * be interruptible (should add a flag for this later I guess).
2770 */
2771 LogFlow(("VBOXGUEST_IOCTL_HGCM_CALL: u32Client=%RX32\n", pInfo->u32ClientID));
2772 fFlags = !fUserData && pSession->R0Process == NIL_RTR0PROCESS ? VBGLR0_HGCMCALL_F_KERNEL : VBGLR0_HGCMCALL_F_USER;
2773 uint32_t cbInfo = (uint32_t)(cbData - cbExtra);
2774#ifdef RT_ARCH_AMD64
2775 if (f32bit)
2776 {
2777 if (fInterruptible)
2778 rc = VbglR0HGCMInternalCall32(pInfo, cbInfo, fFlags, pSession->fRequestor,
2779 vgdrvHgcmAsyncWaitCallbackInterruptible, pDevExt, cMillies);
2780 else
2781 rc = VbglR0HGCMInternalCall32(pInfo, cbInfo, fFlags, pSession->fRequestor,
2782 vgdrvHgcmAsyncWaitCallback, pDevExt, cMillies);
2783 }
2784 else
2785#endif
2786 {
2787 if (fInterruptible)
2788 rc = VbglR0HGCMInternalCall(pInfo, cbInfo, fFlags, pSession->fRequestor,
2789 vgdrvHgcmAsyncWaitCallbackInterruptible, pDevExt, cMillies);
2790 else
2791 rc = VbglR0HGCMInternalCall(pInfo, cbInfo, fFlags, pSession->fRequestor,
2792 vgdrvHgcmAsyncWaitCallback, pDevExt, cMillies);
2793 }
2794 if (RT_SUCCESS(rc))
2795 {
2796 rc = pInfo->Hdr.rc;
2797 LogFlow(("VBOXGUEST_IOCTL_HGCM_CALL: result=%Rrc\n", rc));
2798 }
2799 else
2800 {
2801 if ( rc != VERR_INTERRUPTED
2802 && rc != VERR_TIMEOUT)
2803 LogRelMax(32, ("VBOXGUEST_IOCTL_HGCM_CALL: %s Failed. rc=%Rrc (Hdr.rc=%Rrc).\n", f32bit ? "32" : "64", rc, pInfo->Hdr.rc));
2804 else
2805 Log(("VBOXGUEST_IOCTL_HGCM_CALL: %s Failed. rc=%Rrc (Hdr.rc=%Rrc).\n", f32bit ? "32" : "64", rc, pInfo->Hdr.rc));
2806 }
2807 return rc;
2808}
2809
2810
2811static int vgdrvIoCtl_HGCMCallWrapper(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, PVBGLIOCHGCMCALL pInfo,
2812 bool f32bit, bool fUserData, size_t cbData)
2813{
2814 return vgdrvIoCtl_HGCMCallInner(pDevExt, pSession, pInfo, pInfo->cMsTimeout,
2815 pInfo->fInterruptible || pSession->R0Process != NIL_RTR0PROCESS,
2816 f32bit, fUserData, 0 /*cbExtra*/, cbData);
2817}
2818
2819
2820#endif /* VBOX_WITH_HGCM */
2821
2822/**
2823 * Handle VBGL_IOCTL_CHECK_BALLOON from R3.
2824 *
2825 * Ask the host for the size of the balloon and try to set it accordingly. If
2826 * this approach fails because it's not supported, return with fHandleInR3 set
2827 * and let the user land supply memory we can lock via the other ioctl.
2828 *
2829 * @returns VBox status code.
2830 *
2831 * @param pDevExt The device extension.
2832 * @param pSession The session.
2833 * @param pInfo The output buffer.
2834 */
2835static int vgdrvIoCtl_CheckMemoryBalloon(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, PVBGLIOCCHECKBALLOON pInfo)
2836{
2837 VMMDevGetMemBalloonChangeRequest *pReq;
2838 int rc;
2839
2840 LogFlow(("VBGL_IOCTL_CHECK_BALLOON:\n"));
2841 rc = RTSemFastMutexRequest(pDevExt->MemBalloon.hMtx);
2842 AssertRCReturn(rc, rc);
2843
2844 /*
2845 * The first user trying to query/change the balloon becomes the
2846 * owner and owns it until the session is closed (vgdrvCloseMemBalloon).
2847 */
2848 if ( pDevExt->MemBalloon.pOwner != pSession
2849 && pDevExt->MemBalloon.pOwner == NULL)
2850 pDevExt->MemBalloon.pOwner = pSession;
2851
2852 if (pDevExt->MemBalloon.pOwner == pSession)
2853 {
2854 /*
2855 * This is a response to that event. Setting this bit means that
2856 * we request the value from the host and change the guest memory
2857 * balloon according to this value.
2858 */
2859 rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReq, sizeof(VMMDevGetMemBalloonChangeRequest), VMMDevReq_GetMemBalloonChangeRequest);
2860 if (RT_SUCCESS(rc))
2861 {
2862 pReq->header.fRequestor = pSession->fRequestor;
2863 pReq->eventAck = VMMDEV_EVENT_BALLOON_CHANGE_REQUEST;
2864 rc = VbglR0GRPerform(&pReq->header);
2865 if (RT_SUCCESS(rc))
2866 {
2867 Assert(pDevExt->MemBalloon.cMaxChunks == pReq->cPhysMemChunks || pDevExt->MemBalloon.cMaxChunks == 0);
2868 pDevExt->MemBalloon.cMaxChunks = pReq->cPhysMemChunks;
2869
2870 pInfo->u.Out.cBalloonChunks = pReq->cBalloonChunks;
2871 pInfo->u.Out.fHandleInR3 = false;
2872 pInfo->u.Out.afPadding[0] = false;
2873 pInfo->u.Out.afPadding[1] = false;
2874 pInfo->u.Out.afPadding[2] = false;
2875
2876 rc = vgdrvSetBalloonSizeKernel(pDevExt, pReq->cBalloonChunks, &pInfo->u.Out.fHandleInR3);
2877 /* Ignore various out of memory failures. */
2878 if ( rc == VERR_NO_MEMORY
2879 || rc == VERR_NO_PHYS_MEMORY
2880 || rc == VERR_NO_CONT_MEMORY)
2881 rc = VINF_SUCCESS;
2882 }
2883 else
2884 LogRel(("VBGL_IOCTL_CHECK_BALLOON: VbglR0GRPerform failed. rc=%Rrc\n", rc));
2885 VbglR0GRFree(&pReq->header);
2886 }
2887 }
2888 else
2889 rc = VERR_PERMISSION_DENIED;
2890
2891 RTSemFastMutexRelease(pDevExt->MemBalloon.hMtx);
2892 LogFlow(("VBGL_IOCTL_CHECK_BALLOON returns %Rrc\n", rc));
2893 return rc;
2894}
2895
2896
2897/**
2898 * Handle a request for changing the memory balloon.
2899 *
2900 * @returns VBox status code.
2901 *
2902 * @param pDevExt The device extention.
2903 * @param pSession The session.
2904 * @param pInfo The change request structure (input).
2905 */
2906static int vgdrvIoCtl_ChangeMemoryBalloon(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, PVBGLIOCCHANGEBALLOON pInfo)
2907{
2908 int rc;
2909 LogFlow(("VBGL_IOCTL_CHANGE_BALLOON: fInflate=%RTbool u64ChunkAddr=%p\n", pInfo->u.In.fInflate, pInfo->u.In.pvChunk));
2910 if ( pInfo->u.In.abPadding[0]
2911 || pInfo->u.In.abPadding[1]
2912 || pInfo->u.In.abPadding[2]
2913 || pInfo->u.In.abPadding[3]
2914 || pInfo->u.In.abPadding[4]
2915 || pInfo->u.In.abPadding[5]
2916 || pInfo->u.In.abPadding[6]
2917#if ARCH_BITS == 32
2918 || pInfo->u.In.abPadding[7]
2919 || pInfo->u.In.abPadding[8]
2920 || pInfo->u.In.abPadding[9]
2921#endif
2922 )
2923 {
2924 Log(("VBGL_IOCTL_CHANGE_BALLOON: Padding isn't all zero: %.*Rhxs\n", sizeof(pInfo->u.In.abPadding), pInfo->u.In.abPadding));
2925 return VERR_INVALID_PARAMETER;
2926 }
2927
2928 rc = RTSemFastMutexRequest(pDevExt->MemBalloon.hMtx);
2929 AssertRCReturn(rc, rc);
2930
2931 if (!pDevExt->MemBalloon.fUseKernelAPI)
2932 {
2933 /*
2934 * The first user trying to query/change the balloon becomes the
2935 * owner and owns it until the session is closed (vgdrvCloseMemBalloon).
2936 */
2937 if ( pDevExt->MemBalloon.pOwner != pSession
2938 && pDevExt->MemBalloon.pOwner == NULL)
2939 pDevExt->MemBalloon.pOwner = pSession;
2940
2941 if (pDevExt->MemBalloon.pOwner == pSession)
2942 rc = vgdrvSetBalloonSizeFromUser(pDevExt, pSession, pInfo->u.In.pvChunk, pInfo->u.In.fInflate != false);
2943 else
2944 rc = VERR_PERMISSION_DENIED;
2945 }
2946 else
2947 rc = VERR_PERMISSION_DENIED;
2948
2949 RTSemFastMutexRelease(pDevExt->MemBalloon.hMtx);
2950 return rc;
2951}
2952
2953
2954/**
2955 * Handle a request for writing a core dump of the guest on the host.
2956 *
2957 * @returns VBox status code.
2958 *
2959 * @param pDevExt The device extension.
2960 * @param pSession The session.
2961 * @param pInfo The output buffer.
2962 */
2963static int vgdrvIoCtl_WriteCoreDump(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, PVBGLIOCWRITECOREDUMP pInfo)
2964{
2965 VMMDevReqWriteCoreDump *pReq = NULL;
2966 int rc;
2967 LogFlow(("VBOXGUEST_IOCTL_WRITE_CORE_DUMP\n"));
2968 RT_NOREF1(pDevExt);
2969
2970 rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReq, sizeof(*pReq), VMMDevReq_WriteCoreDump);
2971 if (RT_SUCCESS(rc))
2972 {
2973 pReq->header.fRequestor = pSession->fRequestor;
2974 pReq->fFlags = pInfo->u.In.fFlags;
2975 rc = VbglR0GRPerform(&pReq->header);
2976 if (RT_FAILURE(rc))
2977 Log(("VBOXGUEST_IOCTL_WRITE_CORE_DUMP: VbglR0GRPerform failed, rc=%Rrc!\n", rc));
2978
2979 VbglR0GRFree(&pReq->header);
2980 }
2981 else
2982 Log(("VBOXGUEST_IOCTL_WRITE_CORE_DUMP: failed to allocate %u (%#x) bytes to cache the request. rc=%Rrc!!\n",
2983 sizeof(*pReq), sizeof(*pReq), rc));
2984 return rc;
2985}
2986
2987
2988/**
2989 * Guest backdoor logging.
2990 *
2991 * @returns VBox status code.
2992 *
2993 * @param pDevExt The device extension.
2994 * @param pch The log message (need not be NULL terminated).
2995 * @param cbData Size of the buffer.
2996 * @param fUserSession Copy of VBOXGUESTSESSION::fUserSession for the
2997 * call. True normal user, false root user.
2998 */
2999static int vgdrvIoCtl_Log(PVBOXGUESTDEVEXT pDevExt, const char *pch, size_t cbData, bool fUserSession)
3000{
3001 if (pDevExt->fLoggingEnabled)
3002 RTLogBackdoorPrintf("%.*s", cbData, pch);
3003 else if (!fUserSession)
3004 LogRel(("%.*s", cbData, pch));
3005 else
3006 Log(("%.*s", cbData, pch));
3007 return VINF_SUCCESS;
3008}
3009
3010
3011/** @name Guest Capabilities, Mouse Status and Event Filter
3012 * @{
3013 */
3014
3015/**
3016 * Clears a bit usage tracker (init time).
3017 *
3018 * @param pTracker The tracker to clear.
3019 */
3020static void vgdrvBitUsageTrackerClear(PVBOXGUESTBITUSAGETRACER pTracker)
3021{
3022 uint32_t iBit;
3023 AssertCompile(sizeof(pTracker->acPerBitUsage) == 32 * sizeof(uint32_t));
3024
3025 for (iBit = 0; iBit < 32; iBit++)
3026 pTracker->acPerBitUsage[iBit] = 0;
3027 pTracker->fMask = 0;
3028}
3029
3030
3031#ifdef VBOX_STRICT
3032/**
3033 * Checks that pTracker->fMask is correct and that the usage values are within
3034 * the valid range.
3035 *
3036 * @param pTracker The tracker.
3037 * @param cMax Max valid usage value.
3038 * @param pszWhat Identifies the tracker in assertions.
3039 */
3040static void vgdrvBitUsageTrackerCheckMask(PCVBOXGUESTBITUSAGETRACER pTracker, uint32_t cMax, const char *pszWhat)
3041{
3042 uint32_t fMask = 0;
3043 uint32_t iBit;
3044 AssertCompile(sizeof(pTracker->acPerBitUsage) == 32 * sizeof(uint32_t));
3045
3046 for (iBit = 0; iBit < 32; iBit++)
3047 if (pTracker->acPerBitUsage[iBit])
3048 {
3049 fMask |= RT_BIT_32(iBit);
3050 AssertMsg(pTracker->acPerBitUsage[iBit] <= cMax,
3051 ("%s: acPerBitUsage[%u]=%#x cMax=%#x\n", pszWhat, iBit, pTracker->acPerBitUsage[iBit], cMax));
3052 }
3053
3054 AssertMsg(fMask == pTracker->fMask, ("%s: %#x vs %#x\n", pszWhat, fMask, pTracker->fMask));
3055}
3056#endif
3057
3058
3059/**
3060 * Applies a change to the bit usage tracker.
3061 *
3062 *
3063 * @returns true if the mask changed, false if not.
3064 * @param pTracker The bit usage tracker.
3065 * @param fChanged The bits to change.
3066 * @param fPrevious The previous value of the bits.
3067 * @param cMax The max valid usage value for assertions.
3068 * @param pszWhat Identifies the tracker in assertions.
3069 */
3070static bool vgdrvBitUsageTrackerChange(PVBOXGUESTBITUSAGETRACER pTracker, uint32_t fChanged, uint32_t fPrevious,
3071 uint32_t cMax, const char *pszWhat)
3072{
3073 bool fGlobalChange = false;
3074 AssertCompile(sizeof(pTracker->acPerBitUsage) == 32 * sizeof(uint32_t));
3075
3076 while (fChanged)
3077 {
3078 uint32_t const iBit = ASMBitFirstSetU32(fChanged) - 1;
3079 uint32_t const fBitMask = RT_BIT_32(iBit);
3080 Assert(iBit < 32); Assert(fBitMask & fChanged);
3081
3082 if (fBitMask & fPrevious)
3083 {
3084 pTracker->acPerBitUsage[iBit] -= 1;
3085 AssertMsg(pTracker->acPerBitUsage[iBit] <= cMax,
3086 ("%s: acPerBitUsage[%u]=%#x cMax=%#x\n", pszWhat, iBit, pTracker->acPerBitUsage[iBit], cMax));
3087 if (pTracker->acPerBitUsage[iBit] == 0)
3088 {
3089 fGlobalChange = true;
3090 pTracker->fMask &= ~fBitMask;
3091 }
3092 }
3093 else
3094 {
3095 pTracker->acPerBitUsage[iBit] += 1;
3096 AssertMsg(pTracker->acPerBitUsage[iBit] > 0 && pTracker->acPerBitUsage[iBit] <= cMax,
3097 ("pTracker->acPerBitUsage[%u]=%#x cMax=%#x\n", pszWhat, iBit, pTracker->acPerBitUsage[iBit], cMax));
3098 if (pTracker->acPerBitUsage[iBit] == 1)
3099 {
3100 fGlobalChange = true;
3101 pTracker->fMask |= fBitMask;
3102 }
3103 }
3104
3105 fChanged &= ~fBitMask;
3106 }
3107
3108#ifdef VBOX_STRICT
3109 vgdrvBitUsageTrackerCheckMask(pTracker, cMax, pszWhat);
3110#endif
3111 NOREF(pszWhat); NOREF(cMax);
3112 return fGlobalChange;
3113}
3114
3115
3116/**
3117 * Init and termination worker for resetting the (host) event filter on the host
3118 *
3119 * @returns VBox status code.
3120 * @param pDevExt The device extension.
3121 * @param fFixedEvents Fixed events (init time).
3122 */
3123static int vgdrvResetEventFilterOnHost(PVBOXGUESTDEVEXT pDevExt, uint32_t fFixedEvents)
3124{
3125 VMMDevCtlGuestFilterMask *pReq;
3126 int rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReq, sizeof(*pReq), VMMDevReq_CtlGuestFilterMask);
3127 if (RT_SUCCESS(rc))
3128 {
3129 pReq->u32NotMask = UINT32_MAX & ~fFixedEvents;
3130 pReq->u32OrMask = fFixedEvents;
3131 rc = VbglR0GRPerform(&pReq->header);
3132 if (RT_FAILURE(rc))
3133 LogRelFunc(("failed with rc=%Rrc\n", rc));
3134 VbglR0GRFree(&pReq->header);
3135 }
3136 RT_NOREF1(pDevExt);
3137 return rc;
3138}
3139
3140
3141/**
3142 * Changes the event filter mask for the given session.
3143 *
3144 * This is called in response to VBGL_IOCTL_CHANGE_FILTER_MASK as well as to do
3145 * session cleanup.
3146 *
3147 * @returns VBox status code.
3148 * @param pDevExt The device extension.
3149 * @param pSession The session.
3150 * @param fOrMask The events to add.
3151 * @param fNotMask The events to remove.
3152 * @param fSessionTermination Set if we're called by the session cleanup code.
3153 * This tweaks the error handling so we perform
3154 * proper session cleanup even if the host
3155 * misbehaves.
3156 *
3157 * @remarks Takes the session spinlock.
3158 */
3159static int vgdrvSetSessionEventFilter(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession,
3160 uint32_t fOrMask, uint32_t fNotMask, bool fSessionTermination)
3161{
3162 VMMDevCtlGuestFilterMask *pReq;
3163 uint32_t fChanged;
3164 uint32_t fPrevious;
3165 int rc;
3166
3167 /*
3168 * Preallocate a request buffer so we can do all in one go without leaving the spinlock.
3169 */
3170 rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReq, sizeof(*pReq), VMMDevReq_CtlGuestFilterMask);
3171 if (RT_SUCCESS(rc))
3172 { /* nothing */ }
3173 else if (!fSessionTermination)
3174 {
3175 LogRel(("vgdrvSetSessionFilterMask: VbglR0GRAlloc failure: %Rrc\n", rc));
3176 return rc;
3177 }
3178 else
3179 pReq = NULL; /* Ignore failure, we must do session cleanup. */
3180
3181
3182 RTSpinlockAcquire(pDevExt->SessionSpinlock);
3183
3184 /*
3185 * Apply the changes to the session mask.
3186 */
3187 fPrevious = pSession->fEventFilter;
3188 pSession->fEventFilter |= fOrMask;
3189 pSession->fEventFilter &= ~fNotMask;
3190
3191 /*
3192 * If anything actually changed, update the global usage counters.
3193 */
3194 fChanged = fPrevious ^ pSession->fEventFilter;
3195 LogFlow(("vgdrvSetSessionEventFilter: Session->fEventFilter: %#x -> %#x (changed %#x)\n",
3196 fPrevious, pSession->fEventFilter, fChanged));
3197 if (fChanged)
3198 {
3199 bool fGlobalChange = vgdrvBitUsageTrackerChange(&pDevExt->EventFilterTracker, fChanged, fPrevious,
3200 pDevExt->cSessions, "EventFilterTracker");
3201
3202 /*
3203 * If there are global changes, update the event filter on the host.
3204 */
3205 if (fGlobalChange || pDevExt->fEventFilterHost == UINT32_MAX)
3206 {
3207 Assert(pReq || fSessionTermination);
3208 if (pReq)
3209 {
3210 pReq->u32OrMask = pDevExt->fFixedEvents | pDevExt->EventFilterTracker.fMask;
3211 if (pReq->u32OrMask == pDevExt->fEventFilterHost)
3212 rc = VINF_SUCCESS;
3213 else
3214 {
3215 pDevExt->fEventFilterHost = pReq->u32OrMask;
3216 pReq->u32NotMask = ~pReq->u32OrMask;
3217 rc = VbglR0GRPerform(&pReq->header);
3218 if (RT_FAILURE(rc))
3219 {
3220 /*
3221 * Failed, roll back (unless it's session termination time).
3222 */
3223 pDevExt->fEventFilterHost = UINT32_MAX;
3224 if (!fSessionTermination)
3225 {
3226 vgdrvBitUsageTrackerChange(&pDevExt->EventFilterTracker, fChanged, pSession->fEventFilter,
3227 pDevExt->cSessions, "EventFilterTracker");
3228 pSession->fEventFilter = fPrevious;
3229 }
3230 }
3231 }
3232 }
3233 else
3234 rc = VINF_SUCCESS;
3235 }
3236 }
3237
3238 RTSpinlockRelease(pDevExt->SessionSpinlock);
3239 if (pReq)
3240 VbglR0GRFree(&pReq->header);
3241 return rc;
3242}
3243
3244
3245/**
3246 * Handle VBGL_IOCTL_CHANGE_FILTER_MASK.
3247 *
3248 * @returns VBox status code.
3249 *
3250 * @param pDevExt The device extension.
3251 * @param pSession The session.
3252 * @param pInfo The request.
3253 */
3254static int vgdrvIoCtl_ChangeFilterMask(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, PVBGLIOCCHANGEFILTERMASK pInfo)
3255{
3256 LogFlow(("VBGL_IOCTL_CHANGE_FILTER_MASK: or=%#x not=%#x\n", pInfo->u.In.fOrMask, pInfo->u.In.fNotMask));
3257
3258 if ((pInfo->u.In.fOrMask | pInfo->u.In.fNotMask) & ~VMMDEV_EVENT_VALID_EVENT_MASK)
3259 {
3260 Log(("VBGL_IOCTL_CHANGE_FILTER_MASK: or=%#x not=%#x: Invalid masks!\n", pInfo->u.In.fOrMask, pInfo->u.In.fNotMask));
3261 return VERR_INVALID_PARAMETER;
3262 }
3263
3264 return vgdrvSetSessionEventFilter(pDevExt, pSession, pInfo->u.In.fOrMask, pInfo->u.In.fNotMask, false /*fSessionTermination*/);
3265}
3266
3267
3268/**
3269 * Init and termination worker for set mouse feature status to zero on the host.
3270 *
3271 * @returns VBox status code.
3272 * @param pDevExt The device extension.
3273 */
3274static int vgdrvResetMouseStatusOnHost(PVBOXGUESTDEVEXT pDevExt)
3275{
3276 VMMDevReqMouseStatus *pReq;
3277 int rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReq, sizeof(*pReq), VMMDevReq_SetMouseStatus);
3278 if (RT_SUCCESS(rc))
3279 {
3280 pReq->mouseFeatures = 0;
3281 pReq->pointerXPos = 0;
3282 pReq->pointerYPos = 0;
3283 rc = VbglR0GRPerform(&pReq->header);
3284 if (RT_FAILURE(rc))
3285 LogRelFunc(("failed with rc=%Rrc\n", rc));
3286 VbglR0GRFree(&pReq->header);
3287 }
3288 RT_NOREF1(pDevExt);
3289 return rc;
3290}
3291
3292
3293/**
3294 * Changes the mouse status mask for the given session.
3295 *
3296 * This is called in response to VBOXGUEST_IOCTL_SET_MOUSE_STATUS as well as to
3297 * do session cleanup.
3298 *
3299 * @returns VBox status code.
3300 * @param pDevExt The device extension.
3301 * @param pSession The session.
3302 * @param fOrMask The status flags to add.
3303 * @param fNotMask The status flags to remove.
3304 * @param fSessionTermination Set if we're called by the session cleanup code.
3305 * This tweaks the error handling so we perform
3306 * proper session cleanup even if the host
3307 * misbehaves.
3308 *
3309 * @remarks Takes the session spinlock.
3310 */
3311static int vgdrvSetSessionMouseStatus(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession,
3312 uint32_t fOrMask, uint32_t fNotMask, bool fSessionTermination)
3313{
3314 VMMDevReqMouseStatus *pReq;
3315 uint32_t fChanged;
3316 uint32_t fPrevious;
3317 int rc;
3318
3319 /*
3320 * Preallocate a request buffer so we can do all in one go without leaving the spinlock.
3321 */
3322 rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReq, sizeof(*pReq), VMMDevReq_SetMouseStatus);
3323 if (RT_SUCCESS(rc))
3324 {
3325 if (!fSessionTermination)
3326 pReq->header.fRequestor = pSession->fRequestor;
3327 }
3328 else if (!fSessionTermination)
3329 {
3330 LogRel(("vgdrvSetSessionMouseStatus: VbglR0GRAlloc failure: %Rrc\n", rc));
3331 return rc;
3332 }
3333 else
3334 pReq = NULL; /* Ignore failure, we must do session cleanup. */
3335
3336
3337 RTSpinlockAcquire(pDevExt->SessionSpinlock);
3338
3339 /*
3340 * Apply the changes to the session mask.
3341 */
3342 fPrevious = pSession->fMouseStatus;
3343 pSession->fMouseStatus |= fOrMask;
3344 pSession->fMouseStatus &= ~fNotMask;
3345
3346 /*
3347 * If anything actually changed, update the global usage counters.
3348 */
3349 fChanged = fPrevious ^ pSession->fMouseStatus;
3350 if (fChanged)
3351 {
3352 bool fGlobalChange = vgdrvBitUsageTrackerChange(&pDevExt->MouseStatusTracker, fChanged, fPrevious,
3353 pDevExt->cSessions, "MouseStatusTracker");
3354
3355 /*
3356 * If there are global changes, update the event filter on the host.
3357 */
3358 if (fGlobalChange || pDevExt->fMouseStatusHost == UINT32_MAX)
3359 {
3360 Assert(pReq || fSessionTermination);
3361 if (pReq)
3362 {
3363 pReq->mouseFeatures = pDevExt->MouseStatusTracker.fMask;
3364 if (pReq->mouseFeatures == pDevExt->fMouseStatusHost)
3365 rc = VINF_SUCCESS;
3366 else
3367 {
3368 pDevExt->fMouseStatusHost = pReq->mouseFeatures;
3369 pReq->pointerXPos = 0;
3370 pReq->pointerYPos = 0;
3371 rc = VbglR0GRPerform(&pReq->header);
3372 if (RT_FAILURE(rc))
3373 {
3374 /*
3375 * Failed, roll back (unless it's session termination time).
3376 */
3377 pDevExt->fMouseStatusHost = UINT32_MAX;
3378 if (!fSessionTermination)
3379 {
3380 vgdrvBitUsageTrackerChange(&pDevExt->MouseStatusTracker, fChanged, pSession->fMouseStatus,
3381 pDevExt->cSessions, "MouseStatusTracker");
3382 pSession->fMouseStatus = fPrevious;
3383 }
3384 }
3385 }
3386 }
3387 else
3388 rc = VINF_SUCCESS;
3389 }
3390 }
3391
3392 RTSpinlockRelease(pDevExt->SessionSpinlock);
3393 if (pReq)
3394 VbglR0GRFree(&pReq->header);
3395 return rc;
3396}
3397
3398
3399/**
3400 * Sets the mouse status features for this session and updates them globally.
3401 *
3402 * @returns VBox status code.
3403 *
3404 * @param pDevExt The device extention.
3405 * @param pSession The session.
3406 * @param fFeatures New bitmap of enabled features.
3407 */
3408static int vgdrvIoCtl_SetMouseStatus(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, uint32_t fFeatures)
3409{
3410 LogFlow(("VBGL_IOCTL_SET_MOUSE_STATUS: features=%#x\n", fFeatures));
3411
3412 if (fFeatures & ~VMMDEV_MOUSE_GUEST_MASK)
3413 return VERR_INVALID_PARAMETER;
3414
3415 return vgdrvSetSessionMouseStatus(pDevExt, pSession, fFeatures, ~fFeatures, false /*fSessionTermination*/);
3416}
3417
3418
3419/**
3420 * Return the mask of VMM device events that this session is allowed to see (wrt
3421 * to "acquire" mode guest capabilities).
3422 *
3423 * The events associated with guest capabilities in "acquire" mode will be
3424 * restricted to sessions which has acquired the respective capabilities.
3425 * If someone else tries to wait for acquired events, they won't be woken up
3426 * when the event becomes pending. Should some other thread in the session
3427 * acquire the capability while the corresponding event is pending, the waiting
3428 * thread will woken up.
3429 *
3430 * @returns Mask of events valid for the given session.
3431 * @param pDevExt The device extension.
3432 * @param pSession The session.
3433 *
3434 * @remarks Needs only be called when dispatching events in the
3435 * VBOXGUEST_ACQUIRE_STYLE_EVENTS mask.
3436 */
3437static uint32_t vgdrvGetAllowedEventMaskForSession(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession)
3438{
3439 uint32_t fAcquireModeGuestCaps;
3440 uint32_t fAcquiredGuestCaps;
3441 uint32_t fAllowedEvents;
3442
3443 /*
3444 * Note! Reads pSession->fAcquiredGuestCaps and pDevExt->fAcquireModeGuestCaps
3445 * WITHOUT holding VBOXGUESTDEVEXT::SessionSpinlock.
3446 */
3447 fAcquireModeGuestCaps = ASMAtomicUoReadU32(&pDevExt->fAcquireModeGuestCaps);
3448 if (fAcquireModeGuestCaps == 0)
3449 return VMMDEV_EVENT_VALID_EVENT_MASK;
3450 fAcquiredGuestCaps = ASMAtomicUoReadU32(&pSession->fAcquiredGuestCaps);
3451
3452 /*
3453 * Calculate which events to allow according to the cap config and caps
3454 * acquired by the session.
3455 */
3456 fAllowedEvents = VMMDEV_EVENT_VALID_EVENT_MASK;
3457 if ( !(fAcquiredGuestCaps & VMMDEV_GUEST_SUPPORTS_GRAPHICS)
3458 && (fAcquireModeGuestCaps & VMMDEV_GUEST_SUPPORTS_GRAPHICS))
3459 fAllowedEvents &= ~VMMDEV_EVENT_DISPLAY_CHANGE_REQUEST;
3460
3461 if ( !(fAcquiredGuestCaps & VMMDEV_GUEST_SUPPORTS_SEAMLESS)
3462 && (fAcquireModeGuestCaps & VMMDEV_GUEST_SUPPORTS_SEAMLESS))
3463 fAllowedEvents &= ~VMMDEV_EVENT_SEAMLESS_MODE_CHANGE_REQUEST;
3464
3465 return fAllowedEvents;
3466}
3467
3468
3469/**
3470 * Init and termination worker for set guest capabilities to zero on the host.
3471 *
3472 * @returns VBox status code.
3473 * @param pDevExt The device extension.
3474 */
3475static int vgdrvResetCapabilitiesOnHost(PVBOXGUESTDEVEXT pDevExt)
3476{
3477 VMMDevReqGuestCapabilities2 *pReq;
3478 int rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReq, sizeof(*pReq), VMMDevReq_SetGuestCapabilities);
3479 if (RT_SUCCESS(rc))
3480 {
3481 pReq->u32NotMask = UINT32_MAX;
3482 pReq->u32OrMask = 0;
3483 rc = VbglR0GRPerform(&pReq->header);
3484
3485 if (RT_FAILURE(rc))
3486 LogRelFunc(("failed with rc=%Rrc\n", rc));
3487 VbglR0GRFree(&pReq->header);
3488 }
3489 RT_NOREF1(pDevExt);
3490 return rc;
3491}
3492
3493
3494/**
3495 * Sets the guest capabilities to the host while holding the lock.
3496 *
3497 * This will ASSUME that we're the ones in charge of the mask, so
3498 * we'll simply clear all bits we don't set.
3499 *
3500 * @returns VBox status code.
3501 * @param pDevExt The device extension.
3502 * @param pReq The request.
3503 */
3504static int vgdrvUpdateCapabilitiesOnHostWithReqAndLock(PVBOXGUESTDEVEXT pDevExt, VMMDevReqGuestCapabilities2 *pReq)
3505{
3506 int rc;
3507
3508 pReq->u32OrMask = pDevExt->fAcquiredGuestCaps | pDevExt->SetGuestCapsTracker.fMask;
3509 if (pReq->u32OrMask == pDevExt->fGuestCapsHost)
3510 rc = VINF_SUCCESS;
3511 else
3512 {
3513 pDevExt->fGuestCapsHost = pReq->u32OrMask;
3514 pReq->u32NotMask = ~pReq->u32OrMask;
3515 rc = VbglR0GRPerform(&pReq->header);
3516 if (RT_FAILURE(rc))
3517 pDevExt->fGuestCapsHost = UINT32_MAX;
3518 }
3519
3520 return rc;
3521}
3522
3523
3524/**
3525 * Switch a set of capabilities into "acquire" mode and (maybe) acquire them for
3526 * the given session.
3527 *
3528 * This is called in response to VBOXGUEST_IOCTL_GUEST_CAPS_ACQUIRE as well as
3529 * to do session cleanup.
3530 *
3531 * @returns VBox status code.
3532 * @param pDevExt The device extension.
3533 * @param pSession The session.
3534 * @param fOrMask The capabilities to add .
3535 * @param fNotMask The capabilities to remove. Ignored in
3536 * VBOXGUESTCAPSACQUIRE_FLAGS_CONFIG_ACQUIRE_MODE.
3537 * @param fFlags Confusing operation modifier.
3538 * VBOXGUESTCAPSACQUIRE_FLAGS_NONE means to both
3539 * configure and acquire/release the capabilities.
3540 * VBOXGUESTCAPSACQUIRE_FLAGS_CONFIG_ACQUIRE_MODE
3541 * means only configure capabilities in the
3542 * @a fOrMask capabilities for "acquire" mode.
3543 * @param fSessionTermination Set if we're called by the session cleanup code.
3544 * This tweaks the error handling so we perform
3545 * proper session cleanup even if the host
3546 * misbehaves.
3547 *
3548 * @remarks Takes both the session and event spinlocks.
3549 */
3550static int vgdrvAcquireSessionCapabilities(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession,
3551 uint32_t fOrMask, uint32_t fNotMask, uint32_t fFlags,
3552 bool fSessionTermination)
3553{
3554 uint32_t fCurrentOwnedCaps;
3555 uint32_t fSessionRemovedCaps;
3556 uint32_t fSessionAddedCaps;
3557 uint32_t fOtherConflictingCaps;
3558 VMMDevReqGuestCapabilities2 *pReq = NULL;
3559 int rc;
3560
3561
3562 /*
3563 * Validate and adjust input.
3564 */
3565 if (fOrMask & ~( VMMDEV_GUEST_SUPPORTS_SEAMLESS
3566 | VMMDEV_GUEST_SUPPORTS_GUEST_HOST_WINDOW_MAPPING
3567 | VMMDEV_GUEST_SUPPORTS_GRAPHICS ) )
3568 {
3569 LogRel(("vgdrvAcquireSessionCapabilities: invalid fOrMask=%#x (pSession=%p fNotMask=%#x fFlags=%#x)\n",
3570 fOrMask, pSession, fNotMask, fFlags));
3571 return VERR_INVALID_PARAMETER;
3572 }
3573
3574 if ((fFlags & ~VBGL_IOC_AGC_FLAGS_VALID_MASK) != 0)
3575 {
3576 LogRel(("vgdrvAcquireSessionCapabilities: invalid fFlags=%#x (pSession=%p fOrMask=%#x fNotMask=%#x)\n",
3577 fFlags, pSession, fOrMask, fNotMask));
3578 return VERR_INVALID_PARAMETER;
3579 }
3580 Assert(!fOrMask || !fSessionTermination);
3581
3582 /* The fNotMask no need to have all values valid, invalid ones will simply be ignored. */
3583 fNotMask &= ~fOrMask;
3584
3585 /*
3586 * Preallocate a update request if we're about to do more than just configure
3587 * the capability mode.
3588 */
3589 if (!(fFlags & VBGL_IOC_AGC_FLAGS_CONFIG_ACQUIRE_MODE))
3590 {
3591 rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReq, sizeof(*pReq), VMMDevReq_SetGuestCapabilities);
3592 if (RT_SUCCESS(rc))
3593 {
3594 if (!fSessionTermination)
3595 pReq->header.fRequestor = pSession->fRequestor;
3596 }
3597 else if (!fSessionTermination)
3598 {
3599 LogRel(("vgdrvAcquireSessionCapabilities: pSession=%p fOrMask=%#x fNotMask=%#x fFlags=%#x: VbglR0GRAlloc failure: %Rrc\n",
3600 pSession, fOrMask, fNotMask, fFlags, rc));
3601 return rc;
3602 }
3603 else
3604 pReq = NULL; /* Ignore failure, we must do session cleanup. */
3605 }
3606
3607 /*
3608 * Try switch the capabilities in the OR mask into "acquire" mode.
3609 *
3610 * Note! We currently ignore anyone which may already have "set" the capabilities
3611 * in fOrMask. Perhaps not the best way to handle it, but it's simple...
3612 */
3613 RTSpinlockAcquire(pDevExt->EventSpinlock);
3614
3615 if (!(pDevExt->fSetModeGuestCaps & fOrMask))
3616 pDevExt->fAcquireModeGuestCaps |= fOrMask;
3617 else
3618 {
3619 RTSpinlockRelease(pDevExt->EventSpinlock);
3620
3621 if (pReq)
3622 VbglR0GRFree(&pReq->header);
3623 AssertMsgFailed(("Trying to change caps mode: %#x\n", fOrMask));
3624 LogRel(("vgdrvAcquireSessionCapabilities: pSession=%p fOrMask=%#x fNotMask=%#x fFlags=%#x: calling caps acquire for set caps\n",
3625 pSession, fOrMask, fNotMask, fFlags));
3626 return VERR_INVALID_STATE;
3627 }
3628
3629 /*
3630 * If we only wanted to switch the capabilities into "acquire" mode, we're done now.
3631 */
3632 if (fFlags & VBGL_IOC_AGC_FLAGS_CONFIG_ACQUIRE_MODE)
3633 {
3634 RTSpinlockRelease(pDevExt->EventSpinlock);
3635
3636 Assert(!pReq);
3637 Log(("vgdrvAcquireSessionCapabilities: pSession=%p fOrMask=%#x fNotMask=%#x fFlags=%#x: configured acquire caps: 0x%x\n",
3638 pSession, fOrMask, fNotMask, fFlags));
3639 return VINF_SUCCESS;
3640 }
3641 Assert(pReq || fSessionTermination);
3642
3643 /*
3644 * Caller wants to acquire/release the capabilities too.
3645 *
3646 * Note! The mode change of the capabilities above won't be reverted on
3647 * failure, this is intentional.
3648 */
3649 fCurrentOwnedCaps = pSession->fAcquiredGuestCaps;
3650 fSessionRemovedCaps = fCurrentOwnedCaps & fNotMask;
3651 fSessionAddedCaps = fOrMask & ~fCurrentOwnedCaps;
3652 fOtherConflictingCaps = pDevExt->fAcquiredGuestCaps & ~fCurrentOwnedCaps;
3653 fOtherConflictingCaps &= fSessionAddedCaps;
3654
3655 if (!fOtherConflictingCaps)
3656 {
3657 if (fSessionAddedCaps)
3658 {
3659 pSession->fAcquiredGuestCaps |= fSessionAddedCaps;
3660 pDevExt->fAcquiredGuestCaps |= fSessionAddedCaps;
3661 }
3662
3663 if (fSessionRemovedCaps)
3664 {
3665 pSession->fAcquiredGuestCaps &= ~fSessionRemovedCaps;
3666 pDevExt->fAcquiredGuestCaps &= ~fSessionRemovedCaps;
3667 }
3668
3669 /*
3670 * If something changes (which is very likely), tell the host.
3671 */
3672 if (fSessionAddedCaps || fSessionRemovedCaps || pDevExt->fGuestCapsHost == UINT32_MAX)
3673 {
3674 Assert(pReq || fSessionTermination);
3675 if (pReq)
3676 {
3677 rc = vgdrvUpdateCapabilitiesOnHostWithReqAndLock(pDevExt, pReq);
3678 if (RT_FAILURE(rc) && !fSessionTermination)
3679 {
3680 /* Failed, roll back. */
3681 if (fSessionAddedCaps)
3682 {
3683 pSession->fAcquiredGuestCaps &= ~fSessionAddedCaps;
3684 pDevExt->fAcquiredGuestCaps &= ~fSessionAddedCaps;
3685 }
3686 if (fSessionRemovedCaps)
3687 {
3688 pSession->fAcquiredGuestCaps |= fSessionRemovedCaps;
3689 pDevExt->fAcquiredGuestCaps |= fSessionRemovedCaps;
3690 }
3691
3692 RTSpinlockRelease(pDevExt->EventSpinlock);
3693 LogRel(("vgdrvAcquireSessionCapabilities: vgdrvUpdateCapabilitiesOnHostWithReqAndLock failed: rc=%Rrc\n", rc));
3694 VbglR0GRFree(&pReq->header);
3695 return rc;
3696 }
3697 }
3698 }
3699 }
3700 else
3701 {
3702 RTSpinlockRelease(pDevExt->EventSpinlock);
3703
3704 Log(("vgdrvAcquireSessionCapabilities: Caps %#x were busy\n", fOtherConflictingCaps));
3705 VbglR0GRFree(&pReq->header);
3706 return VERR_RESOURCE_BUSY;
3707 }
3708
3709 RTSpinlockRelease(pDevExt->EventSpinlock);
3710 if (pReq)
3711 VbglR0GRFree(&pReq->header);
3712
3713 /*
3714 * If we added a capability, check if that means some other thread in our
3715 * session should be unblocked because there are events pending.
3716 *
3717 * HACK ALERT! When the seamless support capability is added we generate a
3718 * seamless change event so that the ring-3 client can sync with
3719 * the seamless state. Although this introduces a spurious
3720 * wakeups of the ring-3 client, it solves the problem of client
3721 * state inconsistency in multiuser environment (on Windows).
3722 */
3723 if (fSessionAddedCaps)
3724 {
3725 uint32_t fGenFakeEvents = 0;
3726 if (fSessionAddedCaps & VMMDEV_GUEST_SUPPORTS_SEAMLESS)
3727 fGenFakeEvents |= VMMDEV_EVENT_SEAMLESS_MODE_CHANGE_REQUEST;
3728
3729 RTSpinlockAcquire(pDevExt->EventSpinlock);
3730 if (fGenFakeEvents || pDevExt->f32PendingEvents)
3731 vgdrvDispatchEventsLocked(pDevExt, fGenFakeEvents);
3732 RTSpinlockRelease(pDevExt->EventSpinlock);
3733
3734#ifdef VBOXGUEST_USE_DEFERRED_WAKE_UP
3735 VGDrvCommonWaitDoWakeUps(pDevExt);
3736#endif
3737 }
3738
3739 return VINF_SUCCESS;
3740}
3741
3742
3743/**
3744 * Handle VBGL_IOCTL_ACQUIRE_GUEST_CAPABILITIES.
3745 *
3746 * @returns VBox status code.
3747 *
3748 * @param pDevExt The device extension.
3749 * @param pSession The session.
3750 * @param pAcquire The request.
3751 */
3752static int vgdrvIoCtl_GuestCapsAcquire(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, PVBGLIOCACQUIREGUESTCAPS pAcquire)
3753{
3754 int rc;
3755 LogFlow(("VBGL_IOCTL_ACQUIRE_GUEST_CAPABILITIES: or=%#x not=%#x flags=%#x\n",
3756 pAcquire->u.In.fOrMask, pAcquire->u.In.fNotMask, pAcquire->u.In.fFlags));
3757
3758 rc = vgdrvAcquireSessionCapabilities(pDevExt, pSession, pAcquire->u.In.fOrMask, pAcquire->u.In.fNotMask,
3759 pAcquire->u.In.fFlags, false /*fSessionTermination*/);
3760 if (RT_FAILURE(rc))
3761 LogRel(("VBGL_IOCTL_ACQUIRE_GUEST_CAPABILITIES failed rc=%Rrc\n", rc));
3762 return rc;
3763}
3764
3765
3766/**
3767 * Sets the guest capabilities for a session.
3768 *
3769 * @returns VBox status code.
3770 * @param pDevExt The device extension.
3771 * @param pSession The session.
3772 * @param fOrMask The capabilities to add.
3773 * @param fNotMask The capabilities to remove.
3774 * @param pfSessionCaps Where to return the guest capabilities reported
3775 * for this session. Optional.
3776 * @param pfGlobalCaps Where to return the guest capabilities reported
3777 * for all the sessions. Optional.
3778 *
3779 * @param fSessionTermination Set if we're called by the session cleanup code.
3780 * This tweaks the error handling so we perform
3781 * proper session cleanup even if the host
3782 * misbehaves.
3783 *
3784 * @remarks Takes the session spinlock.
3785 */
3786static int vgdrvSetSessionCapabilities(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession,
3787 uint32_t fOrMask, uint32_t fNotMask, uint32_t *pfSessionCaps, uint32_t *pfGlobalCaps,
3788 bool fSessionTermination)
3789{
3790 /*
3791 * Preallocate a request buffer so we can do all in one go without leaving the spinlock.
3792 */
3793 VMMDevReqGuestCapabilities2 *pReq;
3794 int rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReq, sizeof(*pReq), VMMDevReq_SetGuestCapabilities);
3795 if (RT_SUCCESS(rc))
3796 {
3797 if (!fSessionTermination)
3798 pReq->header.fRequestor = pSession->fRequestor;
3799 }
3800 else if (!fSessionTermination)
3801 {
3802 if (pfSessionCaps)
3803 *pfSessionCaps = UINT32_MAX;
3804 if (pfGlobalCaps)
3805 *pfGlobalCaps = UINT32_MAX;
3806 LogRel(("vgdrvSetSessionCapabilities: VbglR0GRAlloc failure: %Rrc\n", rc));
3807 return rc;
3808 }
3809 else
3810 pReq = NULL; /* Ignore failure, we must do session cleanup. */
3811
3812
3813 RTSpinlockAcquire(pDevExt->SessionSpinlock);
3814
3815#ifndef VBOXGUEST_DISREGARD_ACQUIRE_MODE_GUEST_CAPS
3816 /*
3817 * Capabilities in "acquire" mode cannot be set via this API.
3818 * (Acquire mode is only used on windows at the time of writing.)
3819 */
3820 if (!(fOrMask & pDevExt->fAcquireModeGuestCaps))
3821#endif
3822 {
3823 /*
3824 * Apply the changes to the session mask.
3825 */
3826 uint32_t fChanged;
3827 uint32_t fPrevious = pSession->fCapabilities;
3828 pSession->fCapabilities |= fOrMask;
3829 pSession->fCapabilities &= ~fNotMask;
3830
3831 /*
3832 * If anything actually changed, update the global usage counters.
3833 */
3834 fChanged = fPrevious ^ pSession->fCapabilities;
3835 if (fChanged)
3836 {
3837 bool fGlobalChange = vgdrvBitUsageTrackerChange(&pDevExt->SetGuestCapsTracker, fChanged, fPrevious,
3838 pDevExt->cSessions, "SetGuestCapsTracker");
3839
3840 /*
3841 * If there are global changes, update the capabilities on the host.
3842 */
3843 if (fGlobalChange || pDevExt->fGuestCapsHost == UINT32_MAX)
3844 {
3845 Assert(pReq || fSessionTermination);
3846 if (pReq)
3847 {
3848 rc = vgdrvUpdateCapabilitiesOnHostWithReqAndLock(pDevExt, pReq);
3849
3850 /* On failure, roll back (unless it's session termination time). */
3851 if (RT_FAILURE(rc) && !fSessionTermination)
3852 {
3853 vgdrvBitUsageTrackerChange(&pDevExt->SetGuestCapsTracker, fChanged, pSession->fCapabilities,
3854 pDevExt->cSessions, "SetGuestCapsTracker");
3855 pSession->fCapabilities = fPrevious;
3856 }
3857 }
3858 }
3859 }
3860 }
3861#ifndef VBOXGUEST_DISREGARD_ACQUIRE_MODE_GUEST_CAPS
3862 else
3863 rc = VERR_RESOURCE_BUSY;
3864#endif
3865
3866 if (pfSessionCaps)
3867 *pfSessionCaps = pSession->fCapabilities;
3868 if (pfGlobalCaps)
3869 *pfGlobalCaps = pDevExt->fAcquiredGuestCaps | pDevExt->SetGuestCapsTracker.fMask;
3870
3871 RTSpinlockRelease(pDevExt->SessionSpinlock);
3872 if (pReq)
3873 VbglR0GRFree(&pReq->header);
3874 return rc;
3875}
3876
3877
3878/**
3879 * Handle VBGL_IOCTL_CHANGE_GUEST_CAPABILITIES.
3880 *
3881 * @returns VBox status code.
3882 *
3883 * @param pDevExt The device extension.
3884 * @param pSession The session.
3885 * @param pInfo The request.
3886 */
3887static int vgdrvIoCtl_SetCapabilities(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, PVBGLIOCSETGUESTCAPS pInfo)
3888{
3889 int rc;
3890 LogFlow(("VBGL_IOCTL_CHANGE_GUEST_CAPABILITIES: or=%#x not=%#x\n", pInfo->u.In.fOrMask, pInfo->u.In.fNotMask));
3891
3892 if (!((pInfo->u.In.fOrMask | pInfo->u.In.fNotMask) & ~VMMDEV_GUEST_CAPABILITIES_MASK))
3893 rc = vgdrvSetSessionCapabilities(pDevExt, pSession, pInfo->u.In.fOrMask, pInfo->u.In.fNotMask,
3894 &pInfo->u.Out.fSessionCaps, &pInfo->u.Out.fGlobalCaps, false /*fSessionTermination*/);
3895 else
3896 rc = VERR_INVALID_PARAMETER;
3897
3898 return rc;
3899}
3900
3901/** @} */
3902
3903
3904/**
3905 * Common IOCtl for user to kernel and kernel to kernel communication.
3906 *
3907 * This function only does the basic validation and then invokes
3908 * worker functions that takes care of each specific function.
3909 *
3910 * @returns VBox status code.
3911 *
3912 * @param iFunction The requested function.
3913 * @param pDevExt The device extension.
3914 * @param pSession The client session.
3915 * @param pReqHdr Pointer to the request. This always starts with
3916 * a request common header.
3917 * @param cbReq The max size of the request buffer.
3918 */
3919int VGDrvCommonIoCtl(uintptr_t iFunction, PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, PVBGLREQHDR pReqHdr, size_t cbReq)
3920{
3921 uintptr_t const iFunctionStripped = VBGL_IOCTL_CODE_STRIPPED(iFunction);
3922 int rc;
3923
3924 LogFlow(("VGDrvCommonIoCtl: iFunction=%#x pDevExt=%p pSession=%p pReqHdr=%p cbReq=%zu\n",
3925 iFunction, pDevExt, pSession, pReqHdr, cbReq));
3926
3927 /*
3928 * Define some helper macros to simplify validation.
3929 */
3930#define REQ_CHECK_SIZES_EX(Name, cbInExpect, cbOutExpect) \
3931 do { \
3932 if (RT_LIKELY( pReqHdr->cbIn == (cbInExpect) \
3933 && ( pReqHdr->cbOut == (cbOutExpect) \
3934 || ((cbInExpect) == (cbOutExpect) && pReqHdr->cbOut == 0) ) )) \
3935 { /* likely */ } \
3936 else \
3937 { \
3938 Log(( #Name ": Invalid input/output sizes. cbIn=%ld expected %ld. cbOut=%ld expected %ld.\n", \
3939 (long)pReqHdr->cbIn, (long)(cbInExpect), (long)pReqHdr->cbOut, (long)(cbOutExpect))); \
3940 return pReqHdr->rc = VERR_INVALID_PARAMETER; \
3941 } \
3942 } while (0)
3943
3944#define REQ_CHECK_SIZES(Name) REQ_CHECK_SIZES_EX(Name, Name ## _SIZE_IN, Name ## _SIZE_OUT)
3945
3946#define REQ_CHECK_SIZE_IN(Name, cbInExpect) \
3947 do { \
3948 if (RT_LIKELY(pReqHdr->cbIn == (cbInExpect))) \
3949 { /* likely */ } \
3950 else \
3951 { \
3952 Log(( #Name ": Invalid input/output sizes. cbIn=%ld expected %ld.\n", \
3953 (long)pReqHdr->cbIn, (long)(cbInExpect))); \
3954 return pReqHdr->rc = VERR_INVALID_PARAMETER; \
3955 } \
3956 } while (0)
3957
3958#define REQ_CHECK_SIZE_OUT(Name, cbOutExpect) \
3959 do { \
3960 if (RT_LIKELY( pReqHdr->cbOut == (cbOutExpect) \
3961 || (pReqHdr->cbOut == 0 && pReqHdr->cbIn == (cbOutExpect)))) \
3962 { /* likely */ } \
3963 else \
3964 { \
3965 Log(( #Name ": Invalid input/output sizes. cbOut=%ld (%ld) expected %ld.\n", \
3966 (long)pReqHdr->cbOut, (long)pReqHdr->cbIn, (long)(cbOutExpect))); \
3967 return pReqHdr->rc = VERR_INVALID_PARAMETER; \
3968 } \
3969 } while (0)
3970
3971#define REQ_CHECK_EXPR(Name, expr) \
3972 do { \
3973 if (RT_LIKELY(!!(expr))) \
3974 { /* likely */ } \
3975 else \
3976 { \
3977 Log(( #Name ": %s\n", #expr)); \
3978 return pReqHdr->rc = VERR_INVALID_PARAMETER; \
3979 } \
3980 } while (0)
3981
3982#define REQ_CHECK_EXPR_FMT(expr, fmt) \
3983 do { \
3984 if (RT_LIKELY(!!(expr))) \
3985 { /* likely */ } \
3986 else \
3987 { \
3988 Log( fmt ); \
3989 return pReqHdr->rc = VERR_INVALID_PARAMETER; \
3990 } \
3991 } while (0)
3992
3993#define REQ_CHECK_RING0(mnemonic) \
3994 do { \
3995 if (pSession->R0Process != NIL_RTR0PROCESS) \
3996 { \
3997 LogFunc((mnemonic ": Ring-0 only, caller is %RTproc/%p\n", \
3998 pSession->Process, (uintptr_t)pSession->R0Process)); \
3999 return pReqHdr->rc = VERR_PERMISSION_DENIED; \
4000 } \
4001 } while (0)
4002
4003
4004 /*
4005 * Validate the request.
4006 */
4007 if (RT_LIKELY(cbReq >= sizeof(*pReqHdr)))
4008 { /* likely */ }
4009 else
4010 {
4011 Log(("VGDrvCommonIoCtl: Bad ioctl request size; cbReq=%#lx\n", (long)cbReq));
4012 return VERR_INVALID_PARAMETER;
4013 }
4014
4015 if (pReqHdr->cbOut == 0)
4016 pReqHdr->cbOut = pReqHdr->cbIn;
4017
4018 if (RT_LIKELY( pReqHdr->uVersion == VBGLREQHDR_VERSION
4019 && pReqHdr->cbIn >= sizeof(*pReqHdr)
4020 && pReqHdr->cbIn <= cbReq
4021 && pReqHdr->cbOut >= sizeof(*pReqHdr)
4022 && pReqHdr->cbOut <= cbReq))
4023 { /* likely */ }
4024 else
4025 {
4026 Log(("VGDrvCommonIoCtl: Bad ioctl request header; cbIn=%#lx cbOut=%#lx version=%#lx\n",
4027 (long)pReqHdr->cbIn, (long)pReqHdr->cbOut, (long)pReqHdr->uVersion));
4028 return VERR_INVALID_PARAMETER;
4029 }
4030
4031 if (RT_LIKELY(RT_VALID_PTR(pSession)))
4032 { /* likely */ }
4033 else
4034 {
4035 Log(("VGDrvCommonIoCtl: Invalid pSession value %p (ioctl=%#x)\n", pSession, iFunction));
4036 return VERR_INVALID_PARAMETER;
4037 }
4038
4039
4040 /*
4041 * Deal with variably sized requests first.
4042 */
4043 rc = VINF_SUCCESS;
4044 if ( iFunctionStripped == VBGL_IOCTL_CODE_STRIPPED(VBGL_IOCTL_VMMDEV_REQUEST(0))
4045 || iFunctionStripped == VBGL_IOCTL_CODE_STRIPPED(VBGL_IOCTL_VMMDEV_REQUEST_BIG) )
4046 {
4047 REQ_CHECK_EXPR(VBGL_IOCTL_VMMDEV_REQUEST, pReqHdr->uType != VBGLREQHDR_TYPE_DEFAULT);
4048 REQ_CHECK_EXPR_FMT(pReqHdr->cbIn == pReqHdr->cbOut,
4049 ("VBGL_IOCTL_VMMDEV_REQUEST: cbIn=%ld != cbOut=%ld\n", (long)pReqHdr->cbIn, (long)pReqHdr->cbOut));
4050 pReqHdr->rc = vgdrvIoCtl_VMMDevRequest(pDevExt, pSession, (VMMDevRequestHeader *)pReqHdr, cbReq);
4051 }
4052 else if (RT_LIKELY(pReqHdr->uType == VBGLREQHDR_TYPE_DEFAULT))
4053 {
4054 if (iFunctionStripped == VBGL_IOCTL_CODE_STRIPPED(VBGL_IOCTL_LOG(0)))
4055 {
4056 REQ_CHECK_SIZE_OUT(VBGL_IOCTL_LOG, VBGL_IOCTL_LOG_SIZE_OUT);
4057 pReqHdr->rc = vgdrvIoCtl_Log(pDevExt, &((PVBGLIOCLOG)pReqHdr)->u.In.szMsg[0], pReqHdr->cbIn - sizeof(VBGLREQHDR),
4058 pSession->fUserSession);
4059 }
4060#ifdef VBOX_WITH_HGCM
4061 else if ( iFunctionStripped == VBGL_IOCTL_CODE_STRIPPED(VBGL_IOCTL_HGCM_CALL(0))
4062# if ARCH_BITS == 64
4063 || iFunctionStripped == VBGL_IOCTL_CODE_STRIPPED(VBGL_IOCTL_HGCM_CALL_32(0))
4064# endif
4065 )
4066 {
4067 REQ_CHECK_EXPR(VBGL_IOCTL_HGCM_CALL, pReqHdr->cbIn >= sizeof(VBGLIOCHGCMCALL));
4068 REQ_CHECK_EXPR(VBGL_IOCTL_HGCM_CALL, pReqHdr->cbIn == pReqHdr->cbOut);
4069 pReqHdr->rc = vgdrvIoCtl_HGCMCallWrapper(pDevExt, pSession, (PVBGLIOCHGCMCALL)pReqHdr,
4070 iFunctionStripped == VBGL_IOCTL_CODE_STRIPPED(VBGL_IOCTL_HGCM_CALL_32(0)),
4071 false /*fUserData*/, cbReq);
4072 }
4073 else if (iFunctionStripped == VBGL_IOCTL_CODE_STRIPPED(VBGL_IOCTL_HGCM_CALL_WITH_USER_DATA(0)))
4074 {
4075 REQ_CHECK_RING0("VBGL_IOCTL_HGCM_CALL_WITH_USER_DATA");
4076 REQ_CHECK_EXPR(VBGL_IOCTL_HGCM_CALL, pReqHdr->cbIn >= sizeof(VBGLIOCHGCMCALL));
4077 REQ_CHECK_EXPR(VBGL_IOCTL_HGCM_CALL, pReqHdr->cbIn == pReqHdr->cbOut);
4078 pReqHdr->rc = vgdrvIoCtl_HGCMCallWrapper(pDevExt, pSession, (PVBGLIOCHGCMCALL)pReqHdr,
4079 ARCH_BITS == 32, true /*fUserData*/, cbReq);
4080 }
4081#endif /* VBOX_WITH_HGCM */
4082 else
4083 {
4084 switch (iFunction)
4085 {
4086 /*
4087 * Ring-0 only:
4088 */
4089 case VBGL_IOCTL_IDC_CONNECT:
4090 REQ_CHECK_RING0("VBGL_IOCL_IDC_CONNECT");
4091 REQ_CHECK_SIZES(VBGL_IOCTL_IDC_CONNECT);
4092 pReqHdr->rc = vgdrvIoCtl_IdcConnect(pDevExt, pSession, (PVBGLIOCIDCCONNECT)pReqHdr);
4093 break;
4094
4095 case VBGL_IOCTL_IDC_DISCONNECT:
4096 REQ_CHECK_RING0("VBGL_IOCTL_IDC_DISCONNECT");
4097 REQ_CHECK_SIZES(VBGL_IOCTL_IDC_DISCONNECT);
4098 pReqHdr->rc = vgdrvIoCtl_IdcDisconnect(pDevExt, pSession, (PVBGLIOCIDCDISCONNECT)pReqHdr);
4099 break;
4100
4101 case VBGL_IOCTL_GET_VMMDEV_IO_INFO:
4102 REQ_CHECK_RING0("GET_VMMDEV_IO_INFO");
4103 REQ_CHECK_SIZES(VBGL_IOCTL_GET_VMMDEV_IO_INFO);
4104 pReqHdr->rc = vgdrvIoCtl_GetVMMDevIoInfo(pDevExt, (PVBGLIOCGETVMMDEVIOINFO)pReqHdr);
4105 break;
4106
4107 case VBGL_IOCTL_SET_MOUSE_NOTIFY_CALLBACK:
4108 REQ_CHECK_RING0("SET_MOUSE_NOTIFY_CALLBACK");
4109 REQ_CHECK_SIZES(VBGL_IOCTL_SET_MOUSE_NOTIFY_CALLBACK);
4110 pReqHdr->rc = vgdrvIoCtl_SetMouseNotifyCallback(pDevExt, (PVBGLIOCSETMOUSENOTIFYCALLBACK)pReqHdr);
4111 break;
4112
4113 /*
4114 * Ring-3 only:
4115 */
4116 case VBGL_IOCTL_DRIVER_VERSION_INFO:
4117 REQ_CHECK_SIZES(VBGL_IOCTL_DRIVER_VERSION_INFO);
4118 pReqHdr->rc = vgdrvIoCtl_DriverVersionInfo(pDevExt, pSession, (PVBGLIOCDRIVERVERSIONINFO)pReqHdr);
4119 break;
4120
4121 /*
4122 * Both ring-3 and ring-0:
4123 */
4124 case VBGL_IOCTL_WAIT_FOR_EVENTS:
4125 REQ_CHECK_SIZES(VBGL_IOCTL_WAIT_FOR_EVENTS);
4126 pReqHdr->rc = vgdrvIoCtl_WaitForEvents(pDevExt, pSession, (VBGLIOCWAITFOREVENTS *)pReqHdr,
4127 pSession->R0Process != NIL_RTR0PROCESS);
4128 break;
4129
4130 case VBGL_IOCTL_INTERRUPT_ALL_WAIT_FOR_EVENTS:
4131 REQ_CHECK_SIZES(VBGL_IOCTL_INTERRUPT_ALL_WAIT_FOR_EVENTS);
4132 pReqHdr->rc = vgdrvIoCtl_CancelAllWaitEvents(pDevExt, pSession);
4133 break;
4134
4135 case VBGL_IOCTL_CHANGE_FILTER_MASK:
4136 REQ_CHECK_SIZES(VBGL_IOCTL_CHANGE_FILTER_MASK);
4137 pReqHdr->rc = vgdrvIoCtl_ChangeFilterMask(pDevExt, pSession, (PVBGLIOCCHANGEFILTERMASK)pReqHdr);
4138 break;
4139
4140#ifdef VBOX_WITH_HGCM
4141 case VBGL_IOCTL_HGCM_CONNECT:
4142 REQ_CHECK_SIZES(VBGL_IOCTL_HGCM_CONNECT);
4143 pReqHdr->rc = vgdrvIoCtl_HGCMConnect(pDevExt, pSession, (PVBGLIOCHGCMCONNECT)pReqHdr);
4144 break;
4145
4146 case VBGL_IOCTL_HGCM_DISCONNECT:
4147 REQ_CHECK_SIZES(VBGL_IOCTL_HGCM_DISCONNECT);
4148 pReqHdr->rc = vgdrvIoCtl_HGCMDisconnect(pDevExt, pSession, (PVBGLIOCHGCMDISCONNECT)pReqHdr);
4149 break;
4150#endif
4151
4152 case VBGL_IOCTL_CHECK_BALLOON:
4153 REQ_CHECK_SIZES(VBGL_IOCTL_CHECK_BALLOON);
4154 pReqHdr->rc = vgdrvIoCtl_CheckMemoryBalloon(pDevExt, pSession, (PVBGLIOCCHECKBALLOON)pReqHdr);
4155 break;
4156
4157 case VBGL_IOCTL_CHANGE_BALLOON:
4158 REQ_CHECK_SIZES(VBGL_IOCTL_CHANGE_BALLOON);
4159 pReqHdr->rc = vgdrvIoCtl_ChangeMemoryBalloon(pDevExt, pSession, (PVBGLIOCCHANGEBALLOON)pReqHdr);
4160 break;
4161
4162 case VBGL_IOCTL_WRITE_CORE_DUMP:
4163 REQ_CHECK_SIZES(VBGL_IOCTL_WRITE_CORE_DUMP);
4164 pReqHdr->rc = vgdrvIoCtl_WriteCoreDump(pDevExt, pSession, (PVBGLIOCWRITECOREDUMP)pReqHdr);
4165 break;
4166
4167 case VBGL_IOCTL_SET_MOUSE_STATUS:
4168 REQ_CHECK_SIZES(VBGL_IOCTL_SET_MOUSE_STATUS);
4169 pReqHdr->rc = vgdrvIoCtl_SetMouseStatus(pDevExt, pSession, ((PVBGLIOCSETMOUSESTATUS)pReqHdr)->u.In.fStatus);
4170 break;
4171
4172 case VBGL_IOCTL_ACQUIRE_GUEST_CAPABILITIES:
4173 REQ_CHECK_SIZES(VBGL_IOCTL_ACQUIRE_GUEST_CAPABILITIES);
4174 pReqHdr->rc = vgdrvIoCtl_GuestCapsAcquire(pDevExt, pSession, (PVBGLIOCACQUIREGUESTCAPS)pReqHdr);
4175 break;
4176
4177 case VBGL_IOCTL_CHANGE_GUEST_CAPABILITIES:
4178 REQ_CHECK_SIZES(VBGL_IOCTL_CHANGE_GUEST_CAPABILITIES);
4179 pReqHdr->rc = vgdrvIoCtl_SetCapabilities(pDevExt, pSession, (PVBGLIOCSETGUESTCAPS)pReqHdr);
4180 break;
4181
4182#ifdef VBOX_WITH_DPC_LATENCY_CHECKER
4183 case VBGL_IOCTL_DPC_LATENCY_CHECKER:
4184 REQ_CHECK_SIZES(VBGL_IOCTL_DPC_LATENCY_CHECKER);
4185 pReqHdr->rc = VGDrvNtIOCtl_DpcLatencyChecker();
4186 break;
4187#endif
4188
4189 default:
4190 {
4191 LogRel(("VGDrvCommonIoCtl: Unknown request iFunction=%#x (stripped %#x) cbReq=%#x\n",
4192 iFunction, iFunctionStripped, cbReq));
4193 pReqHdr->rc = rc = VERR_NOT_SUPPORTED;
4194 break;
4195 }
4196 }
4197 }
4198 }
4199 else
4200 {
4201 Log(("VGDrvCommonIoCtl: uType=%#x, expected default (ioctl=%#x)\n", pReqHdr->uType, iFunction));
4202 return VERR_INVALID_PARAMETER;
4203 }
4204
4205 LogFlow(("VGDrvCommonIoCtl: returns %Rrc (req: rc=%Rrc cbOut=%#x)\n", rc, pReqHdr->rc, pReqHdr->cbOut));
4206 return rc;
4207}
4208
4209
4210/**
4211 * Used by VGDrvCommonISR as well as the acquire guest capability code.
4212 *
4213 * @returns VINF_SUCCESS on success. On failure, ORed together
4214 * RTSemEventMultiSignal errors (completes processing despite errors).
4215 * @param pDevExt The VBoxGuest device extension.
4216 * @param fEvents The events to dispatch.
4217 */
4218static int vgdrvDispatchEventsLocked(PVBOXGUESTDEVEXT pDevExt, uint32_t fEvents)
4219{
4220 PVBOXGUESTWAIT pWait;
4221 PVBOXGUESTWAIT pSafe;
4222 int rc = VINF_SUCCESS;
4223
4224 fEvents |= pDevExt->f32PendingEvents;
4225
4226 RTListForEachSafe(&pDevExt->WaitList, pWait, pSafe, VBOXGUESTWAIT, ListNode)
4227 {
4228 uint32_t fHandledEvents = pWait->fReqEvents & fEvents;
4229 if ( fHandledEvents != 0
4230 && !pWait->fResEvents)
4231 {
4232 /* Does this one wait on any of the events we're dispatching? We do a quick
4233 check first, then deal with VBOXGUEST_ACQUIRE_STYLE_EVENTS as applicable. */
4234 if (fHandledEvents & VBOXGUEST_ACQUIRE_STYLE_EVENTS)
4235 fHandledEvents &= vgdrvGetAllowedEventMaskForSession(pDevExt, pWait->pSession);
4236 if (fHandledEvents)
4237 {
4238 pWait->fResEvents = pWait->fReqEvents & fEvents & fHandledEvents;
4239 fEvents &= ~pWait->fResEvents;
4240 RTListNodeRemove(&pWait->ListNode);
4241#ifdef VBOXGUEST_USE_DEFERRED_WAKE_UP
4242 RTListAppend(&pDevExt->WakeUpList, &pWait->ListNode);
4243#else
4244 RTListAppend(&pDevExt->WokenUpList, &pWait->ListNode);
4245 rc |= RTSemEventMultiSignal(pWait->Event);
4246#endif
4247 if (!fEvents)
4248 break;
4249 }
4250 }
4251 }
4252
4253 ASMAtomicWriteU32(&pDevExt->f32PendingEvents, fEvents);
4254 return rc;
4255}
4256
4257
4258/**
4259 * Simply checks whether the IRQ is ours or not, does not do any interrupt
4260 * procesing.
4261 *
4262 * @returns true if it was our interrupt, false if it wasn't.
4263 * @param pDevExt The VBoxGuest device extension.
4264 */
4265bool VGDrvCommonIsOurIRQ(PVBOXGUESTDEVEXT pDevExt)
4266{
4267 VMMDevMemory volatile *pVMMDevMemory;
4268 bool fOurIrq;
4269
4270 RTSpinlockAcquire(pDevExt->EventSpinlock);
4271 pVMMDevMemory = pDevExt->pVMMDevMemory;
4272 fOurIrq = pVMMDevMemory ? pVMMDevMemory->V.V1_04.fHaveEvents : false;
4273 RTSpinlockRelease(pDevExt->EventSpinlock);
4274
4275 return fOurIrq;
4276}
4277
4278
4279/**
4280 * Common interrupt service routine.
4281 *
4282 * This deals with events and with waking up thread waiting for those events.
4283 *
4284 * @returns true if it was our interrupt, false if it wasn't.
4285 * @param pDevExt The VBoxGuest device extension.
4286 */
4287bool VGDrvCommonISR(PVBOXGUESTDEVEXT pDevExt)
4288{
4289 VMMDevEvents volatile *pReq = pDevExt->pIrqAckEvents;
4290 bool fMousePositionChanged = false;
4291 int rc = 0;
4292 VMMDevMemory volatile *pVMMDevMemory;
4293 bool fOurIrq;
4294
4295 /*
4296 * Make sure we've initialized the device extension.
4297 */
4298 if (RT_UNLIKELY(!pReq))
4299 return false;
4300
4301 /*
4302 * Enter the spinlock and check if it's our IRQ or not.
4303 */
4304 RTSpinlockAcquire(pDevExt->EventSpinlock);
4305 pVMMDevMemory = pDevExt->pVMMDevMemory;
4306 fOurIrq = pVMMDevMemory ? pVMMDevMemory->V.V1_04.fHaveEvents : false;
4307 if (fOurIrq)
4308 {
4309 /*
4310 * Acknowlegde events.
4311 * We don't use VbglR0GRPerform here as it may take another spinlocks.
4312 */
4313 pReq->header.rc = VERR_INTERNAL_ERROR;
4314 pReq->events = 0;
4315 ASMCompilerBarrier();
4316 ASMOutU32(pDevExt->IOPortBase + VMMDEV_PORT_OFF_REQUEST, (uint32_t)pDevExt->PhysIrqAckEvents);
4317 ASMCompilerBarrier(); /* paranoia */
4318 if (RT_SUCCESS(pReq->header.rc))
4319 {
4320 uint32_t fEvents = pReq->events;
4321
4322 Log3(("VGDrvCommonISR: acknowledge events succeeded %#RX32\n", fEvents));
4323
4324 /*
4325 * VMMDEV_EVENT_MOUSE_POSITION_CHANGED can only be polled for.
4326 */
4327 if (fEvents & VMMDEV_EVENT_MOUSE_POSITION_CHANGED)
4328 {
4329 fMousePositionChanged = true;
4330 fEvents &= ~VMMDEV_EVENT_MOUSE_POSITION_CHANGED;
4331#if !defined(VBOXGUEST_MOUSE_NOTIFY_CAN_PREEMPT)
4332 if (pDevExt->pfnMouseNotifyCallback)
4333 pDevExt->pfnMouseNotifyCallback(pDevExt->pvMouseNotifyCallbackArg);
4334#endif
4335 }
4336
4337#ifdef VBOX_WITH_HGCM
4338 /*
4339 * The HGCM event/list is kind of different in that we evaluate all entries.
4340 */
4341 if (fEvents & VMMDEV_EVENT_HGCM)
4342 {
4343 PVBOXGUESTWAIT pWait;
4344 PVBOXGUESTWAIT pSafe;
4345 RTListForEachSafe(&pDevExt->HGCMWaitList, pWait, pSafe, VBOXGUESTWAIT, ListNode)
4346 {
4347 if (pWait->pHGCMReq->fu32Flags & VBOX_HGCM_REQ_DONE)
4348 {
4349 pWait->fResEvents = VMMDEV_EVENT_HGCM;
4350 RTListNodeRemove(&pWait->ListNode);
4351# ifdef VBOXGUEST_USE_DEFERRED_WAKE_UP
4352 RTListAppend(&pDevExt->WakeUpList, &pWait->ListNode);
4353# else
4354 RTListAppend(&pDevExt->WokenUpList, &pWait->ListNode);
4355 rc |= RTSemEventMultiSignal(pWait->Event);
4356# endif
4357 }
4358 }
4359 fEvents &= ~VMMDEV_EVENT_HGCM;
4360 }
4361#endif
4362
4363 /*
4364 * Normal FIFO waiter evaluation.
4365 */
4366 rc |= vgdrvDispatchEventsLocked(pDevExt, fEvents);
4367 }
4368 else /* something is serious wrong... */
4369 Log(("VGDrvCommonISR: acknowledge events failed rc=%Rrc (events=%#x)!!\n",
4370 pReq->header.rc, pReq->events));
4371 }
4372 else
4373 Log3(("VGDrvCommonISR: not ours\n"));
4374
4375 RTSpinlockRelease(pDevExt->EventSpinlock);
4376
4377 /*
4378 * Execute the mouse notification callback here if it cannot be executed while
4379 * holding the interrupt safe spinlock, see @bugref{8639}.
4380 */
4381#if defined(VBOXGUEST_MOUSE_NOTIFY_CAN_PREEMPT) && !defined(RT_OS_WINDOWS) /* (Windows does this in the Dpc callback) */
4382 if ( fMousePositionChanged
4383 && pDevExt->pfnMouseNotifyCallback)
4384 pDevExt->pfnMouseNotifyCallback(pDevExt->pvMouseNotifyCallbackArg);
4385#endif
4386
4387#if defined(VBOXGUEST_USE_DEFERRED_WAKE_UP) && !defined(RT_OS_DARWIN) && !defined(RT_OS_WINDOWS)
4388 /*
4389 * Do wake-ups.
4390 * Note. On Windows this isn't possible at this IRQL, so a DPC will take
4391 * care of it. Same on darwin, doing it in the work loop callback.
4392 */
4393 VGDrvCommonWaitDoWakeUps(pDevExt);
4394#endif
4395
4396 /*
4397 * Work the poll and async notification queues on OSes that implements that.
4398 * (Do this outside the spinlock to prevent some recursive spinlocking.)
4399 */
4400 if (fMousePositionChanged)
4401 {
4402 ASMAtomicIncU32(&pDevExt->u32MousePosChangedSeq);
4403 VGDrvNativeISRMousePollEvent(pDevExt);
4404 }
4405
4406 Assert(rc == 0);
4407 NOREF(rc);
4408 return fOurIrq;
4409}
4410
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