VirtualBox

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

Last change on this file since 48034 was 48034, checked in by vboxsync, 11 years ago

Guest Additions: add release logger to VBoxGuest driver (enabled for darwin only); make VBoxGuest.kext workable on 64 bit system.

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