VirtualBox

source: vbox/trunk/src/VBox/Additions/common/VBoxGuest/VBoxGuest-darwin.cpp@ 72352

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

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

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 39.7 KB
Line 
1/* $Id: VBoxGuest-darwin.cpp 70873 2018-02-05 18:13:55Z vboxsync $ */
2/** @file
3 * VBoxGuest - Darwin Specifics.
4 */
5
6/*
7 * Copyright (C) 2006-2017 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28/*********************************************************************************************************************************
29* Header Files *
30*********************************************************************************************************************************/
31#define LOG_GROUP LOG_GROUP_VGDRV
32/*
33 * Deal with conflicts first.
34 * PVM - BSD mess, that FreeBSD has correct a long time ago.
35 * iprt/types.h before sys/param.h - prevents UINT32_C and friends.
36 */
37#include <iprt/types.h>
38#include <sys/param.h>
39#undef PVM
40
41#include <IOKit/IOLib.h> /* Assert as function */
42
43#include <VBox/version.h>
44#include <iprt/asm.h>
45#include <iprt/assert.h>
46#include <iprt/initterm.h>
47#include <iprt/mem.h>
48#include <iprt/process.h>
49#include <iprt/power.h>
50#include <iprt/semaphore.h>
51#include <iprt/spinlock.h>
52#include <iprt/string.h>
53#include <VBox/err.h>
54#include <VBox/log.h>
55
56#include <mach/kmod.h>
57#include <miscfs/devfs/devfs.h>
58#include <sys/conf.h>
59#include <sys/errno.h>
60#include <sys/ioccom.h>
61#include <sys/malloc.h>
62#include <sys/proc.h>
63#include <sys/kauth.h>
64#include <IOKit/IOService.h>
65#include <IOKit/IOUserClient.h>
66#include <IOKit/pwr_mgt/RootDomain.h>
67#include <IOKit/pci/IOPCIDevice.h>
68#include <IOKit/IOBufferMemoryDescriptor.h>
69#include <IOKit/IOFilterInterruptEventSource.h>
70#include "VBoxGuestInternal.h"
71
72
73/*********************************************************************************************************************************
74* Defined Constants And Macros *
75*********************************************************************************************************************************/
76
77/** The system device node name. */
78#define DEVICE_NAME_SYS "vboxguest"
79/** The user device node name. */
80#define DEVICE_NAME_USR "vboxguestu"
81
82
83/*********************************************************************************************************************************
84* Internal Functions *
85*********************************************************************************************************************************/
86RT_C_DECLS_BEGIN
87static kern_return_t vgdrvDarwinStart(struct kmod_info *pKModInfo, void *pvData);
88static kern_return_t vgdrvDarwinStop(struct kmod_info *pKModInfo, void *pvData);
89static int vgdrvDarwinCharDevRemove(void);
90
91static int vgdrvDarwinOpen(dev_t Dev, int fFlags, int fDevType, struct proc *pProcess);
92static int vgdrvDarwinClose(dev_t Dev, int fFlags, int fDevType, struct proc *pProcess);
93static int vgdrvDarwinIOCtlSlow(PVBOXGUESTSESSION pSession, u_long iCmd, caddr_t pData, struct proc *pProcess);
94static int vgdrvDarwinIOCtl(dev_t Dev, u_long iCmd, caddr_t pData, int fFlags, struct proc *pProcess);
95
96static int vgdrvDarwinErr2DarwinErr(int rc);
97
98static IOReturn vgdrvDarwinSleepHandler(void *pvTarget, void *pvRefCon, UInt32 uMessageType, IOService *pProvider, void *pvMessageArgument, vm_size_t argSize);
99RT_C_DECLS_END
100
101
102/*********************************************************************************************************************************
103* Structures and Typedefs *
104*********************************************************************************************************************************/
105/**
106 * The service class for handling the VMMDev PCI device.
107 *
108 * Instantiated when the module is loaded (and on PCI hotplugging?).
109 */
110class org_virtualbox_VBoxGuest : public IOService
111{
112 OSDeclareDefaultStructors(org_virtualbox_VBoxGuest);
113
114private:
115 IOPCIDevice *m_pIOPCIDevice;
116 IOMemoryMap *m_pMap;
117 IOFilterInterruptEventSource *m_pInterruptSrc;
118
119 bool setupVmmDevInterrupts(IOService *pProvider);
120 bool disableVmmDevInterrupts(void);
121 bool isVmmDev(IOPCIDevice *pIOPCIDevice);
122
123protected:
124 IOWorkLoop *m_pWorkLoop;
125
126public:
127 virtual bool start(IOService *pProvider);
128 virtual void stop(IOService *pProvider);
129 virtual bool terminate(IOOptionBits fOptions);
130 IOWorkLoop * getWorkLoop();
131};
132
133OSDefineMetaClassAndStructors(org_virtualbox_VBoxGuest, IOService);
134
135
136/**
137 * An attempt at getting that clientDied() notification.
138 * I don't think it'll work as I cannot figure out where/what creates the correct
139 * port right.
140 *
141 * Instantiated when userland does IOServiceOpen().
142 */
143class org_virtualbox_VBoxGuestClient : public IOUserClient
144{
145 OSDeclareDefaultStructors(org_virtualbox_VBoxGuestClient);
146
147private:
148 PVBOXGUESTSESSION m_pSession; /**< The session. */
149 task_t m_Task; /**< The client task. */
150 org_virtualbox_VBoxGuest *m_pProvider; /**< The service provider. */
151
152public:
153 virtual bool initWithTask(task_t OwningTask, void *pvSecurityId, UInt32 u32Type);
154 virtual bool start(IOService *pProvider);
155 static void sessionClose(RTPROCESS Process);
156 virtual IOReturn clientClose(void);
157};
158
159OSDefineMetaClassAndStructors(org_virtualbox_VBoxGuestClient, IOUserClient);
160
161
162
163/*********************************************************************************************************************************
164* Global Variables *
165*********************************************************************************************************************************/
166/**
167 * Declare the module stuff.
168 */
169RT_C_DECLS_BEGIN
170extern kern_return_t _start(struct kmod_info *pKModInfo, void *pvData);
171extern kern_return_t _stop(struct kmod_info *pKModInfo, void *pvData);
172
173KMOD_EXPLICIT_DECL(VBoxGuest, VBOX_VERSION_STRING, _start, _stop)
174DECLHIDDEN(kmod_start_func_t *) _realmain = vgdrvDarwinStart;
175DECLHIDDEN(kmod_stop_func_t *) _antimain = vgdrvDarwinStop;
176DECLHIDDEN(int) _kext_apple_cc = __APPLE_CC__;
177RT_C_DECLS_END
178
179
180/**
181 * Device extention & session data association structure.
182 */
183static VBOXGUESTDEVEXT g_DevExt;
184
185/**
186 * The character device switch table for the driver.
187 */
188static struct cdevsw g_DevCW =
189{
190 /*.d_open = */ vgdrvDarwinOpen,
191 /*.d_close = */ vgdrvDarwinClose,
192 /*.d_read = */ eno_rdwrt,
193 /*.d_write = */ eno_rdwrt,
194 /*.d_ioctl = */ vgdrvDarwinIOCtl,
195 /*.d_stop = */ eno_stop,
196 /*.d_reset = */ eno_reset,
197 /*.d_ttys = */ NULL,
198 /*.d_select = */ eno_select,
199 /*.d_mmap = */ eno_mmap,
200 /*.d_strategy = */ eno_strat,
201 /*.d_getc = */ (void *)(uintptr_t)&enodev, //eno_getc,
202 /*.d_putc = */ (void *)(uintptr_t)&enodev, //eno_putc,
203 /*.d_type = */ 0
204};
205
206/** Major device number. */
207static int g_iMajorDeviceNo = -1;
208/** Registered devfs device handle. */
209static void *g_hDevFsDeviceSys = NULL;
210/** Registered devfs device handle for the user device. */
211static void *g_hDevFsDeviceUsr = NULL; /**< @todo 4 later */
212
213/** Spinlock protecting g_apSessionHashTab. */
214static RTSPINLOCK g_Spinlock = NIL_RTSPINLOCK;
215/** Hash table */
216static PVBOXGUESTSESSION g_apSessionHashTab[19];
217/** Calculates the index into g_apSessionHashTab.*/
218#define SESSION_HASH(pid) ((pid) % RT_ELEMENTS(g_apSessionHashTab))
219/** The number of open sessions. */
220static int32_t volatile g_cSessions = 0;
221/** The number of IOService class instances. */
222static bool volatile g_fInstantiated = 0;
223/** The notifier handle for the sleep callback handler. */
224static IONotifier *g_pSleepNotifier = NULL;
225
226/* States of atimic variable aimed to protect dynamic object allocation in SMP environment. */
227#define VBOXGUEST_OBJECT_UNINITIALIZED (0)
228#define VBOXGUEST_OBJECT_INITIALIZING (1)
229#define VBOXGUEST_OBJECT_INITIALIZED (2)
230#define VBOXGUEST_OBJECT_INVALID (3)
231/** Atomic variable used to protect work loop allocation when multiple threads attempt to obtain it. */
232static uint8_t volatile g_fWorkLoopCreated = VBOXGUEST_OBJECT_UNINITIALIZED;
233
234
235/**
236 * Start the kernel module.
237 */
238static kern_return_t vgdrvDarwinStart(struct kmod_info *pKModInfo, void *pvData)
239{
240 RT_NOREF(pKModInfo, pvData);
241
242 /*
243 * Initialize IPRT.
244 */
245 int rc = RTR0Init(0);
246 if (RT_SUCCESS(rc))
247 {
248 Log(("VBoxGuest: driver loaded\n"));
249 return KMOD_RETURN_SUCCESS;
250 }
251
252 printf("VBoxGuest: RTR0Init failed with rc=%d\n", rc);
253 return KMOD_RETURN_FAILURE;
254}
255
256
257/**
258 * Register VBoxGuest char device
259 */
260static int vgdrvDarwinCharDevInit(void)
261{
262 int rc = RTSpinlockCreate(&g_Spinlock, RTSPINLOCK_FLAGS_INTERRUPT_SAFE, "VBoxGuestDarwin");
263 if (RT_SUCCESS(rc))
264 {
265 /*
266 * Registering ourselves as a character device.
267 */
268 g_iMajorDeviceNo = cdevsw_add(-1, &g_DevCW);
269 if (g_iMajorDeviceNo >= 0)
270 {
271 g_hDevFsDeviceSys = devfs_make_node(makedev(g_iMajorDeviceNo, 0), DEVFS_CHAR,
272 UID_ROOT, GID_WHEEL, 0666, DEVICE_NAME_SYS);
273 if (g_hDevFsDeviceSys != NULL)
274 {
275 /*
276 * Register a sleep/wakeup notification callback.
277 */
278 g_pSleepNotifier = registerPrioritySleepWakeInterest(&vgdrvDarwinSleepHandler, &g_DevExt, NULL);
279 if (g_pSleepNotifier != NULL)
280 {
281 return KMOD_RETURN_SUCCESS;
282 }
283 }
284 }
285 vgdrvDarwinCharDevRemove();
286 }
287 return KMOD_RETURN_FAILURE;
288}
289
290
291/**
292 * Stop the kernel module.
293 */
294static kern_return_t vgdrvDarwinStop(struct kmod_info *pKModInfo, void *pvData)
295{
296 RT_NOREF(pKModInfo, pvData);
297 RTR0TermForced();
298
299 printf("VBoxGuest: driver unloaded\n");
300 return KMOD_RETURN_SUCCESS;
301}
302
303
304/* Unregister VBoxGuest char device */
305static int vgdrvDarwinCharDevRemove(void)
306{
307 int rc = KMOD_RETURN_SUCCESS;
308
309 if (g_pSleepNotifier)
310 {
311 g_pSleepNotifier->remove();
312 g_pSleepNotifier = NULL;
313 }
314
315 if (g_hDevFsDeviceSys)
316 {
317 devfs_remove(g_hDevFsDeviceSys);
318 g_hDevFsDeviceSys = NULL;
319 }
320
321 if (g_hDevFsDeviceUsr)
322 {
323 devfs_remove(g_hDevFsDeviceUsr);
324 g_hDevFsDeviceUsr = NULL;
325 }
326
327 if (g_iMajorDeviceNo != -1)
328 {
329 int rc2 = cdevsw_remove(g_iMajorDeviceNo, &g_DevCW);
330 Assert(rc2 == g_iMajorDeviceNo); NOREF(rc2);
331 g_iMajorDeviceNo = -1;
332 }
333
334 if (g_Spinlock != NIL_RTSPINLOCK)
335 {
336 int rc2 = RTSpinlockDestroy(g_Spinlock); AssertRC(rc2);
337 g_Spinlock = NIL_RTSPINLOCK;
338 }
339
340 return rc;
341}
342
343
344/**
345 * Device open. Called on open /dev/vboxguest and (later) /dev/vboxguestu.
346 *
347 * @param Dev The device number.
348 * @param fFlags ???.
349 * @param fDevType ???.
350 * @param pProcess The process issuing this request.
351 */
352static int vgdrvDarwinOpen(dev_t Dev, int fFlags, int fDevType, struct proc *pProcess)
353{
354 RT_NOREF(fFlags, fDevType);
355
356 /*
357 * Only two minor devices numbers are allowed.
358 */
359 if (minor(Dev) != 0 && minor(Dev) != 1)
360 return EACCES;
361
362 /*
363 * Find the session created by org_virtualbox_VBoxGuestClient, fail
364 * if no such session, and mark it as opened. We set the uid & gid
365 * here too, since that is more straight forward at this point.
366 */
367 //const bool fUnrestricted = minor(Dev) == 0;
368 int rc = VINF_SUCCESS;
369 PVBOXGUESTSESSION pSession = NULL;
370 kauth_cred_t pCred = kauth_cred_proc_ref(pProcess);
371 if (pCred)
372 {
373 RTPROCESS Process = RTProcSelf();
374 unsigned iHash = SESSION_HASH(Process);
375 RTSpinlockAcquire(g_Spinlock);
376
377 pSession = g_apSessionHashTab[iHash];
378 while (pSession && pSession->Process != Process)
379 pSession = pSession->pNextHash;
380 if (pSession)
381 {
382 if (!pSession->fOpened)
383 {
384 pSession->fOpened = true;
385 /*pSession->fUnrestricted = fUnrestricted; - later */
386 }
387 else
388 rc = VERR_ALREADY_LOADED;
389 }
390 else
391 rc = VERR_GENERAL_FAILURE;
392
393 RTSpinlockRelease(g_Spinlock);
394#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1050
395 kauth_cred_unref(&pCred);
396#else /* 10.4 */
397 /* The 10.4u SDK headers and 10.4.11 kernel source have inconsistent definitions
398 of kauth_cred_unref(), so use the other (now deprecated) API for releasing it. */
399 kauth_cred_rele(pCred);
400#endif /* 10.4 */
401 }
402 else
403 rc = VERR_INVALID_PARAMETER;
404
405 Log(("vgdrvDarwinOpen: g_DevExt=%p pSession=%p rc=%d pid=%d\n", &g_DevExt, pSession, rc, proc_pid(pProcess)));
406 return vgdrvDarwinErr2DarwinErr(rc);
407}
408
409
410/**
411 * Close device.
412 */
413static int vgdrvDarwinClose(dev_t Dev, int fFlags, int fDevType, struct proc *pProcess)
414{
415 RT_NOREF(Dev, fFlags, fDevType, pProcess);
416 Log(("vgdrvDarwinClose: pid=%d\n", (int)RTProcSelf()));
417 Assert(proc_pid(pProcess) == (int)RTProcSelf());
418
419 /*
420 * Hand the session closing to org_virtualbox_VBoxGuestClient.
421 */
422 org_virtualbox_VBoxGuestClient::sessionClose(RTProcSelf());
423 return 0;
424}
425
426
427/**
428 * Device I/O Control entry point.
429 *
430 * @returns Darwin for slow IOCtls and VBox status code for the fast ones.
431 * @param Dev The device number (major+minor).
432 * @param iCmd The IOCtl command.
433 * @param pData Pointer to the request data.
434 * @param fFlags Flag saying we're a character device (like we didn't know already).
435 * @param pProcess The process issuing this request.
436 */
437static int vgdrvDarwinIOCtl(dev_t Dev, u_long iCmd, caddr_t pData, int fFlags, struct proc *pProcess)
438{
439 RT_NOREF(Dev, fFlags);
440 //const bool fUnrestricted = minor(Dev) == 0;
441 const RTPROCESS Process = proc_pid(pProcess);
442 const unsigned iHash = SESSION_HASH(Process);
443 PVBOXGUESTSESSION pSession;
444
445 /*
446 * Find the session.
447 */
448 RTSpinlockAcquire(g_Spinlock);
449 pSession = g_apSessionHashTab[iHash];
450 while (pSession && pSession->Process != Process && (/*later: pSession->fUnrestricted != fUnrestricted ||*/ !pSession->fOpened))
451 pSession = pSession->pNextHash;
452 RTSpinlockRelease(g_Spinlock);
453 if (!pSession)
454 {
455 Log(("VBoxDrvDarwinIOCtl: WHAT?!? pSession == NULL! This must be a mistake... pid=%d iCmd=%#lx\n", (int)Process, iCmd));
456 return EINVAL;
457 }
458
459 /*
460 * Deal with the high-speed IOCtl.
461 */
462 if (VBGL_IOCTL_IS_FAST(iCmd))
463 return VGDrvCommonIoCtlFast(iCmd, &g_DevExt, pSession);
464
465 return vgdrvDarwinIOCtlSlow(pSession, iCmd, pData, pProcess);
466}
467
468
469/**
470 * Worker for VBoxDrvDarwinIOCtl that takes the slow IOCtl functions.
471 *
472 * @returns Darwin errno.
473 *
474 * @param pSession The session.
475 * @param iCmd The IOCtl command.
476 * @param pData Pointer to the request data.
477 * @param pProcess The calling process.
478 */
479static int vgdrvDarwinIOCtlSlow(PVBOXGUESTSESSION pSession, u_long iCmd, caddr_t pData, struct proc *pProcess)
480{
481 RT_NOREF(pProcess);
482 LogFlow(("vgdrvDarwinIOCtlSlow: pSession=%p iCmd=%p pData=%p pProcess=%p\n", pSession, iCmd, pData, pProcess));
483
484
485 /*
486 * Buffered or unbuffered?
487 */
488 PVBGLREQHDR pHdr;
489 user_addr_t pUser = 0;
490 void *pvPageBuf = NULL;
491 uint32_t cbReq = IOCPARM_LEN(iCmd);
492 if ((IOC_DIRMASK & iCmd) == IOC_INOUT)
493 {
494 pHdr = (PVBGLREQHDR)pData;
495 if (RT_UNLIKELY(cbReq < sizeof(*pHdr)))
496 {
497 LogRel(("vgdrvDarwinIOCtlSlow: cbReq=%#x < %#x; iCmd=%#lx\n", cbReq, (int)sizeof(*pHdr), iCmd));
498 return EINVAL;
499 }
500 if (RT_UNLIKELY(pHdr->uVersion != VBGLREQHDR_VERSION))
501 {
502 LogRel(("vgdrvDarwinIOCtlSlow: bad uVersion=%#x; iCmd=%#lx\n", pHdr->uVersion, iCmd));
503 return EINVAL;
504 }
505 if (RT_UNLIKELY( RT_MAX(pHdr->cbIn, pHdr->cbOut) != cbReq
506 || pHdr->cbIn < sizeof(*pHdr)
507 || (pHdr->cbOut < sizeof(*pHdr) && pHdr->cbOut != 0)))
508 {
509 LogRel(("vgdrvDarwinIOCtlSlow: max(%#x,%#x) != %#x; iCmd=%#lx\n", pHdr->cbIn, pHdr->cbOut, cbReq, iCmd));
510 return EINVAL;
511 }
512 }
513 else if ((IOC_DIRMASK & iCmd) == IOC_VOID && !cbReq)
514 {
515 /*
516 * Get the header and figure out how much we're gonna have to read.
517 */
518 VBGLREQHDR Hdr;
519 pUser = (user_addr_t)*(void **)pData;
520 int rc = copyin(pUser, &Hdr, sizeof(Hdr));
521 if (RT_UNLIKELY(rc))
522 {
523 LogRel(("vgdrvDarwinIOCtlSlow: copyin(%llx,Hdr,) -> %#x; iCmd=%#lx\n", (unsigned long long)pUser, rc, iCmd));
524 return rc;
525 }
526 if (RT_UNLIKELY(Hdr.uVersion != VBGLREQHDR_VERSION))
527 {
528 LogRel(("vgdrvDarwinIOCtlSlow: bad uVersion=%#x; iCmd=%#lx\n", Hdr.uVersion, iCmd));
529 return EINVAL;
530 }
531 cbReq = RT_MAX(Hdr.cbIn, Hdr.cbOut);
532 if (RT_UNLIKELY( Hdr.cbIn < sizeof(Hdr)
533 || (Hdr.cbOut < sizeof(Hdr) && Hdr.cbOut != 0)
534 || cbReq > _1M*16))
535 {
536 LogRel(("vgdrvDarwinIOCtlSlow: max(%#x,%#x); iCmd=%#lx\n", Hdr.cbIn, Hdr.cbOut, iCmd));
537 return EINVAL;
538 }
539
540 /*
541 * Allocate buffer and copy in the data.
542 */
543 pHdr = (PVBGLREQHDR)RTMemTmpAlloc(cbReq);
544 if (!pHdr)
545 pvPageBuf = pHdr = (PVBGLREQHDR)IOMallocAligned(RT_ALIGN_Z(cbReq, PAGE_SIZE), 8);
546 if (RT_UNLIKELY(!pHdr))
547 {
548 LogRel(("vgdrvDarwinIOCtlSlow: failed to allocate buffer of %d bytes; iCmd=%#lx\n", cbReq, iCmd));
549 return ENOMEM;
550 }
551 rc = copyin(pUser, pHdr, Hdr.cbIn);
552 if (RT_UNLIKELY(rc))
553 {
554 LogRel(("vgdrvDarwinIOCtlSlow: copyin(%llx,%p,%#x) -> %#x; iCmd=%#lx\n",
555 (unsigned long long)pUser, pHdr, Hdr.cbIn, rc, iCmd));
556 if (pvPageBuf)
557 IOFreeAligned(pvPageBuf, RT_ALIGN_Z(cbReq, PAGE_SIZE));
558 else
559 RTMemTmpFree(pHdr);
560 return rc;
561 }
562 if (Hdr.cbIn < cbReq)
563 RT_BZERO((uint8_t *)pHdr + Hdr.cbIn, cbReq - Hdr.cbIn);
564 }
565 else
566 {
567 Log(("vgdrvDarwinIOCtlSlow: huh? cbReq=%#x iCmd=%#lx\n", cbReq, iCmd));
568 return EINVAL;
569 }
570
571 /*
572 * Process the IOCtl.
573 */
574 int rc = VGDrvCommonIoCtl(iCmd, &g_DevExt, pSession, pHdr, cbReq);
575 if (RT_LIKELY(!rc))
576 {
577 /*
578 * If not buffered, copy back the buffer before returning.
579 */
580 if (pUser)
581 {
582 uint32_t cbOut = pHdr->cbOut;
583 if (cbOut > cbReq)
584 {
585 LogRel(("vgdrvDarwinIOCtlSlow: too much output! %#x > %#x; uCmd=%#lx!\n", cbOut, cbReq, iCmd));
586 cbOut = cbReq;
587 }
588 rc = copyout(pHdr, pUser, cbOut);
589 if (RT_UNLIKELY(rc))
590 LogRel(("vgdrvDarwinIOCtlSlow: copyout(%p,%llx,%#x) -> %d; uCmd=%#lx!\n",
591 pHdr, (unsigned long long)pUser, cbOut, rc, iCmd));
592
593 /* cleanup */
594 if (pvPageBuf)
595 IOFreeAligned(pvPageBuf, RT_ALIGN_Z(cbReq, PAGE_SIZE));
596 else
597 RTMemTmpFree(pHdr);
598 }
599 }
600 else
601 {
602 /*
603 * The request failed, just clean up.
604 */
605 if (pUser)
606 {
607 if (pvPageBuf)
608 IOFreeAligned(pvPageBuf, RT_ALIGN_Z(cbReq, PAGE_SIZE));
609 else
610 RTMemTmpFree(pHdr);
611 }
612
613 Log(("vgdrvDarwinIOCtlSlow: pid=%d iCmd=%lx pData=%p failed, rc=%d\n", proc_pid(pProcess), iCmd, (void *)pData, rc));
614 rc = EINVAL;
615 }
616
617 Log2(("vgdrvDarwinIOCtlSlow: returns %d\n", rc));
618 return rc;
619}
620
621
622/**
623 * @note This code is duplicated on other platforms with variations, so please
624 * keep them all up to date when making changes!
625 */
626int VBOXCALL VBoxGuestIDC(void *pvSession, uintptr_t uReq, PVBGLREQHDR pReqHdr, size_t cbReq)
627{
628 /*
629 * Simple request validation (common code does the rest).
630 */
631 int rc;
632 if ( RT_VALID_PTR(pReqHdr)
633 && cbReq >= sizeof(*pReqHdr))
634 {
635 /*
636 * All requests except the connect one requires a valid session.
637 */
638 PVBOXGUESTSESSION pSession = (PVBOXGUESTSESSION)pvSession;
639 if (pSession)
640 {
641 if ( RT_VALID_PTR(pSession)
642 && pSession->pDevExt == &g_DevExt)
643 rc = VGDrvCommonIoCtl(uReq, &g_DevExt, pSession, pReqHdr, cbReq);
644 else
645 rc = VERR_INVALID_HANDLE;
646 }
647 else if (uReq == VBGL_IOCTL_IDC_CONNECT)
648 {
649 rc = VGDrvCommonCreateKernelSession(&g_DevExt, &pSession);
650 if (RT_SUCCESS(rc))
651 {
652 rc = VGDrvCommonIoCtl(uReq, &g_DevExt, pSession, pReqHdr, cbReq);
653 if (RT_FAILURE(rc))
654 VGDrvCommonCloseSession(&g_DevExt, pSession);
655 }
656 }
657 else
658 rc = VERR_INVALID_HANDLE;
659 }
660 else
661 rc = VERR_INVALID_POINTER;
662 return rc;
663}
664
665
666void VGDrvNativeISRMousePollEvent(PVBOXGUESTDEVEXT pDevExt)
667{
668 NOREF(pDevExt);
669}
670
671
672bool VGDrvNativeProcessOption(PVBOXGUESTDEVEXT pDevExt, const char *pszName, const char *pszValue)
673{
674 RT_NOREF(pDevExt); RT_NOREF(pszName); RT_NOREF(pszValue);
675 return false;
676}
677
678
679/**
680 * Callback for blah blah blah.
681 */
682static IOReturn vgdrvDarwinSleepHandler(void *pvTarget, void *pvRefCon, UInt32 uMessageType,
683 IOService *pProvider, void *pvMsgArg, vm_size_t cbMsgArg)
684{
685 RT_NOREF(pvTarget, pProvider, pvMsgArg, cbMsgArg);
686 LogFlow(("VBoxGuest: Got sleep/wake notice. Message type was %x\n", uMessageType));
687
688 if (uMessageType == kIOMessageSystemWillSleep)
689 RTPowerSignalEvent(RTPOWEREVENT_SUSPEND);
690 else if (uMessageType == kIOMessageSystemHasPoweredOn)
691 RTPowerSignalEvent(RTPOWEREVENT_RESUME);
692
693 acknowledgeSleepWakeNotification(pvRefCon);
694
695 return 0;
696}
697
698
699/**
700 * Converts an IPRT error code to a darwin error code.
701 *
702 * @returns corresponding darwin error code.
703 * @param rc IPRT status code.
704 */
705static int vgdrvDarwinErr2DarwinErr(int rc)
706{
707 switch (rc)
708 {
709 case VINF_SUCCESS: return 0;
710 case VERR_GENERAL_FAILURE: return EACCES;
711 case VERR_INVALID_PARAMETER: return EINVAL;
712 case VERR_INVALID_MAGIC: return EILSEQ;
713 case VERR_INVALID_HANDLE: return ENXIO;
714 case VERR_INVALID_POINTER: return EFAULT;
715 case VERR_LOCK_FAILED: return ENOLCK;
716 case VERR_ALREADY_LOADED: return EEXIST;
717 case VERR_PERMISSION_DENIED: return EPERM;
718 case VERR_VERSION_MISMATCH: return ENOSYS;
719 }
720
721 return EPERM;
722}
723
724
725/*
726 *
727 * org_virtualbox_VBoxGuest
728 *
729 */
730
731
732/**
733 * Lazy initialization of the m_pWorkLoop member.
734 *
735 * @returns m_pWorkLoop.
736 */
737IOWorkLoop *org_virtualbox_VBoxGuest::getWorkLoop()
738{
739/** @todo r=bird: This is actually a classic RTOnce scenario, except it's
740 * tied to a org_virtualbox_VBoxGuest instance. */
741 /*
742 * Handle the case when work loop was not created yet.
743 */
744 if (ASMAtomicCmpXchgU8(&g_fWorkLoopCreated, VBOXGUEST_OBJECT_INITIALIZING, VBOXGUEST_OBJECT_UNINITIALIZED))
745 {
746 m_pWorkLoop = IOWorkLoop::workLoop();
747 if (m_pWorkLoop)
748 {
749 /* Notify the rest of threads about the fact that work
750 * loop was successully allocated and can be safely used */
751 Log(("VBoxGuest: created new work loop\n"));
752 ASMAtomicWriteU8(&g_fWorkLoopCreated, VBOXGUEST_OBJECT_INITIALIZED);
753 }
754 else
755 {
756 /* Notify the rest of threads about the fact that there was
757 * an error during allocation of a work loop */
758 Log(("VBoxGuest: failed to create new work loop!\n"));
759 ASMAtomicWriteU8(&g_fWorkLoopCreated, VBOXGUEST_OBJECT_UNINITIALIZED);
760 }
761 }
762 /*
763 * Handle the case when work loop is already create or
764 * in the process of being.
765 */
766 else
767 {
768 uint8_t fWorkLoopCreated = ASMAtomicReadU8(&g_fWorkLoopCreated);
769 while (fWorkLoopCreated == VBOXGUEST_OBJECT_INITIALIZING)
770 {
771 thread_block(0);
772 fWorkLoopCreated = ASMAtomicReadU8(&g_fWorkLoopCreated);
773 }
774 if (fWorkLoopCreated != VBOXGUEST_OBJECT_INITIALIZED)
775 Log(("VBoxGuest: No work loop!\n"));
776 }
777
778 return m_pWorkLoop;
779}
780
781
782/**
783 * Perform pending wake ups in work loop context.
784 */
785static void vgdrvDarwinDeferredIrqHandler(OSObject *pOwner, IOInterruptEventSource *pSrc, int cInts)
786{
787 NOREF(pOwner); NOREF(pSrc); NOREF(cInts);
788
789 VGDrvCommonWaitDoWakeUps(&g_DevExt);
790}
791
792
793/**
794 * Callback triggered when interrupt occurs.
795 */
796static bool vgdrvDarwinDirectIrqHandler(OSObject *pOwner, IOFilterInterruptEventSource *pSrc)
797{
798 RT_NOREF(pOwner);
799 if (!pSrc)
800 return false;
801
802 bool fTaken = VGDrvCommonISR(&g_DevExt);
803 if (!fTaken) /** @todo r=bird: This looks bogus as we might actually be sharing interrupts with someone. */
804 Log(("VGDrvCommonISR error\n"));
805
806 return fTaken;
807}
808
809
810bool org_virtualbox_VBoxGuest::setupVmmDevInterrupts(IOService *pProvider)
811{
812 IOWorkLoop *pWorkLoop = getWorkLoop();
813 if (!pWorkLoop)
814 return false;
815
816 m_pInterruptSrc = IOFilterInterruptEventSource::filterInterruptEventSource(this,
817 &vgdrvDarwinDeferredIrqHandler,
818 &vgdrvDarwinDirectIrqHandler,
819 pProvider);
820 IOReturn rc = pWorkLoop->addEventSource(m_pInterruptSrc);
821 if (rc == kIOReturnSuccess)
822 {
823 m_pInterruptSrc->enable();
824 return true;
825 }
826
827 m_pInterruptSrc->disable();
828 m_pInterruptSrc->release();
829 m_pInterruptSrc = NULL;
830 return false;
831}
832
833
834bool org_virtualbox_VBoxGuest::disableVmmDevInterrupts(void)
835{
836 IOWorkLoop *pWorkLoop = (IOWorkLoop *)getWorkLoop();
837
838 if (!pWorkLoop)
839 return false;
840
841 if (!m_pInterruptSrc)
842 return false;
843
844 m_pInterruptSrc->disable();
845 pWorkLoop->removeEventSource(m_pInterruptSrc);
846 m_pInterruptSrc->release();
847 m_pInterruptSrc = NULL;
848
849 return true;
850}
851
852
853bool org_virtualbox_VBoxGuest::isVmmDev(IOPCIDevice *pIOPCIDevice)
854{
855 UInt16 uVendorId, uDeviceId;
856
857 if (!pIOPCIDevice)
858 return false;
859
860 uVendorId = m_pIOPCIDevice->configRead16(kIOPCIConfigVendorID);
861 uDeviceId = m_pIOPCIDevice->configRead16(kIOPCIConfigDeviceID);
862
863 if (uVendorId == VMMDEV_VENDORID && uDeviceId == VMMDEV_DEVICEID)
864 return true;
865
866 return true;
867}
868
869
870/**
871 * Start this service.
872 */
873bool org_virtualbox_VBoxGuest::start(IOService *pProvider)
874{
875 /*
876 * Low level initialization / device initialization should be performed only once.
877 */
878 if (!ASMAtomicCmpXchgBool(&g_fInstantiated, true, false))
879 return false;
880
881 if (!IOService::start(pProvider))
882 return false;
883
884 m_pIOPCIDevice = OSDynamicCast(IOPCIDevice, pProvider);
885 if (m_pIOPCIDevice)
886 {
887 if (isVmmDev(m_pIOPCIDevice))
888 {
889 /* Enable memory response from VMM device */
890 m_pIOPCIDevice->setMemoryEnable(true);
891 m_pIOPCIDevice->setIOEnable(true);
892
893 IOMemoryDescriptor *pMem = m_pIOPCIDevice->getDeviceMemoryWithIndex(0);
894 if (pMem)
895 {
896 IOPhysicalAddress IOPortBasePhys = pMem->getPhysicalAddress();
897 /* Check that returned value is from I/O port range (at least it is 16-bit lenght) */
898 if((IOPortBasePhys >> 16) == 0)
899 {
900
901 RTIOPORT IOPortBase = (RTIOPORT)IOPortBasePhys;
902 void *pvMMIOBase = NULL;
903 uint32_t cbMMIO = 0;
904 m_pMap = m_pIOPCIDevice->mapDeviceMemoryWithIndex(1);
905 if (m_pMap)
906 {
907 pvMMIOBase = (void *)m_pMap->getVirtualAddress();
908 cbMMIO = m_pMap->getLength();
909 }
910
911 int rc = VGDrvCommonInitDevExt(&g_DevExt,
912 IOPortBase,
913 pvMMIOBase,
914 cbMMIO,
915#if ARCH_BITS == 64
916 VBOXOSTYPE_MacOS_x64,
917#else
918 VBOXOSTYPE_MacOS,
919#endif
920 0);
921 if (RT_SUCCESS(rc))
922 {
923 rc = vgdrvDarwinCharDevInit();
924 if (rc == KMOD_RETURN_SUCCESS)
925 {
926 if (setupVmmDevInterrupts(pProvider))
927 {
928 /*
929 * Read host configuration.
930 */
931 VGDrvCommonProcessOptionsFromHost(&g_DevExt);
932
933 /*
934 * Register the service.
935 */
936 registerService();
937 LogRel(("VBoxGuest: IOService started\n"));
938 return true;
939 }
940
941 LogRel(("VBoxGuest: Failed to set up interrupts\n"));
942 vgdrvDarwinCharDevRemove();
943 }
944 else
945 LogRel(("VBoxGuest: Failed to initialize character device (rc=%d).\n", rc));
946
947 VGDrvCommonDeleteDevExt(&g_DevExt);
948 }
949 else
950 LogRel(("VBoxGuest: Failed to initialize common code (rc=%d).\n", rc));
951
952 if (m_pMap)
953 {
954 m_pMap->release();
955 m_pMap = NULL;
956 }
957 }
958 }
959 else
960 LogRel(("VBoxGuest: The device missing is the I/O port range (#0).\n"));
961 }
962 else
963 LogRel(("VBoxGuest: Not the VMMDev (%#x:%#x).\n",
964 m_pIOPCIDevice->configRead16(kIOPCIConfigVendorID), m_pIOPCIDevice->configRead16(kIOPCIConfigDeviceID)));
965 }
966 else
967 LogRel(("VBoxGuest: Provider is not an instance of IOPCIDevice.\n"));
968
969 ASMAtomicXchgBool(&g_fInstantiated, false);
970 IOService::stop(pProvider);
971 return false;
972}
973
974
975/**
976 * Stop this service.
977 */
978void org_virtualbox_VBoxGuest::stop(IOService *pProvider)
979{
980 /* Do not use Log*() here (in IOService instance) because its instance
981 * already terminated in BSD's module unload callback! */
982 Log(("org_virtualbox_VBoxGuest::stop([%p], %p)\n", this, pProvider));
983
984 AssertReturnVoid(ASMAtomicReadBool(&g_fInstantiated));
985
986 /* Low level termination should be performed only once */
987 if (!disableVmmDevInterrupts())
988 printf("VBoxGuest: unable to unregister interrupt handler\n");
989
990 vgdrvDarwinCharDevRemove();
991 VGDrvCommonDeleteDevExt(&g_DevExt);
992
993 if (m_pMap)
994 {
995 m_pMap->release();
996 m_pMap = NULL;
997 }
998
999 IOService::stop(pProvider);
1000
1001 ASMAtomicWriteBool(&g_fInstantiated, false);
1002
1003 printf("VBoxGuest: IOService stopped\n");
1004}
1005
1006
1007/**
1008 * Termination request.
1009 *
1010 * @return true if we're ok with shutting down now, false if we're not.
1011 * @param fOptions Flags.
1012 */
1013bool org_virtualbox_VBoxGuest::terminate(IOOptionBits fOptions)
1014{
1015 /* Do not use Log*() here (in IOService instance) because its instance
1016 * already terminated in BSD's module unload callback! */
1017#ifdef LOG_ENABLED
1018 printf("org_virtualbox_VBoxGuest::terminate: reference_count=%d g_cSessions=%d (fOptions=%#x)\n",
1019 KMOD_INFO_NAME.reference_count, ASMAtomicUoReadS32(&g_cSessions), fOptions);
1020#endif
1021
1022 bool fRc;
1023 if ( KMOD_INFO_NAME.reference_count != 0
1024 || ASMAtomicUoReadS32(&g_cSessions))
1025 fRc = false;
1026 else
1027 fRc = IOService::terminate(fOptions);
1028
1029#ifdef LOG_ENABLED
1030 printf("org_virtualbox_SupDrv::terminate: returns %d\n", fRc);
1031#endif
1032 return fRc;
1033}
1034
1035
1036/*
1037 *
1038 * org_virtualbox_VBoxGuestClient
1039 *
1040 */
1041
1042
1043/**
1044 * Initializer called when the client opens the service.
1045 */
1046bool org_virtualbox_VBoxGuestClient::initWithTask(task_t OwningTask, void *pvSecurityId, UInt32 u32Type)
1047{
1048 LogFlow(("org_virtualbox_VBoxGuestClient::initWithTask([%p], %#x, %p, %#x) (cur pid=%d proc=%p)\n",
1049 this, OwningTask, pvSecurityId, u32Type, RTProcSelf(), RTR0ProcHandleSelf()));
1050 AssertMsg((RTR0PROCESS)OwningTask == RTR0ProcHandleSelf(), ("%p %p\n", OwningTask, RTR0ProcHandleSelf()));
1051
1052 if (!OwningTask)
1053 return false;
1054
1055 if (u32Type != VBOXGUEST_DARWIN_IOSERVICE_COOKIE)
1056 {
1057 Log(("org_virtualbox_VBoxGuestClient::initWithTask: Bad cookie %#x\n", u32Type));
1058 return false;
1059 }
1060
1061 if (IOUserClient::initWithTask(OwningTask, pvSecurityId , u32Type))
1062 {
1063 /*
1064 * In theory we have to call task_reference() to make sure that the task is
1065 * valid during the lifetime of this object. The pointer is only used to check
1066 * for the context this object is called in though and never dereferenced
1067 * or passed to anything which might, so we just skip this step.
1068 */
1069 m_Task = OwningTask;
1070 m_pSession = NULL;
1071 m_pProvider = NULL;
1072 return true;
1073 }
1074 return false;
1075}
1076
1077
1078/**
1079 * Start the client service.
1080 */
1081bool org_virtualbox_VBoxGuestClient::start(IOService *pProvider)
1082{
1083 LogFlow(("org_virtualbox_VBoxGuestClient::start([%p], %p) (cur pid=%d proc=%p)\n",
1084 this, pProvider, RTProcSelf(), RTR0ProcHandleSelf() ));
1085 AssertMsgReturn((RTR0PROCESS)m_Task == RTR0ProcHandleSelf(),
1086 ("%p %p\n", m_Task, RTR0ProcHandleSelf()),
1087 false);
1088
1089 if (IOUserClient::start(pProvider))
1090 {
1091 m_pProvider = OSDynamicCast(org_virtualbox_VBoxGuest, pProvider);
1092 if (m_pProvider)
1093 {
1094 Assert(!m_pSession);
1095
1096 /*
1097 * Create a new session.
1098 */
1099 int rc = VGDrvCommonCreateUserSession(&g_DevExt, VMMDEV_REQUESTOR_USERMODE, &m_pSession);
1100 if (RT_SUCCESS(rc))
1101 {
1102 m_pSession->fOpened = false;
1103 /* The fUnrestricted field is set on open. */
1104
1105 /*
1106 * Insert it into the hash table, checking that there isn't
1107 * already one for this process first. (One session per proc!)
1108 */
1109 unsigned iHash = SESSION_HASH(m_pSession->Process);
1110 RTSpinlockAcquire(g_Spinlock);
1111
1112 PVBOXGUESTSESSION pCur = g_apSessionHashTab[iHash];
1113 if (pCur && pCur->Process != m_pSession->Process)
1114 {
1115 do pCur = pCur->pNextHash;
1116 while (pCur && pCur->Process != m_pSession->Process);
1117 }
1118 if (!pCur)
1119 {
1120 m_pSession->pNextHash = g_apSessionHashTab[iHash];
1121 g_apSessionHashTab[iHash] = m_pSession;
1122 m_pSession->pvVBoxGuestClient = this;
1123 ASMAtomicIncS32(&g_cSessions);
1124 rc = VINF_SUCCESS;
1125 }
1126 else
1127 rc = VERR_ALREADY_LOADED;
1128
1129 RTSpinlockRelease(g_Spinlock);
1130 if (RT_SUCCESS(rc))
1131 {
1132 Log(("org_virtualbox_VBoxGuestClient::start: created session %p for pid %d\n", m_pSession, (int)RTProcSelf()));
1133 return true;
1134 }
1135
1136 LogFlow(("org_virtualbox_VBoxGuestClient::start: already got a session for this process (%p)\n", pCur));
1137 VGDrvCommonCloseSession(&g_DevExt, m_pSession);
1138 }
1139
1140 m_pSession = NULL;
1141 LogFlow(("org_virtualbox_VBoxGuestClient::start: rc=%Rrc from supdrvCreateSession\n", rc));
1142 }
1143 else
1144 LogFlow(("org_virtualbox_VBoxGuestClient::start: %p isn't org_virtualbox_VBoxGuest\n", pProvider));
1145 }
1146 return false;
1147}
1148
1149
1150/**
1151 * Common worker for clientClose and VBoxDrvDarwinClose.
1152 */
1153/* static */ void org_virtualbox_VBoxGuestClient::sessionClose(RTPROCESS Process)
1154{
1155 /*
1156 * Find the session and remove it from the hash table.
1157 *
1158 * Note! Only one session per process. (Both start() and
1159 * vgdrvDarwinOpen makes sure this is so.)
1160 */
1161 const unsigned iHash = SESSION_HASH(Process);
1162 RTSpinlockAcquire(g_Spinlock);
1163 PVBOXGUESTSESSION pSession = g_apSessionHashTab[iHash];
1164 if (pSession)
1165 {
1166 if (pSession->Process == Process)
1167 {
1168 g_apSessionHashTab[iHash] = pSession->pNextHash;
1169 pSession->pNextHash = NULL;
1170 ASMAtomicDecS32(&g_cSessions);
1171 }
1172 else
1173 {
1174 PVBOXGUESTSESSION pPrev = pSession;
1175 pSession = pSession->pNextHash;
1176 while (pSession)
1177 {
1178 if (pSession->Process == Process)
1179 {
1180 pPrev->pNextHash = pSession->pNextHash;
1181 pSession->pNextHash = NULL;
1182 ASMAtomicDecS32(&g_cSessions);
1183 break;
1184 }
1185
1186 /* next */
1187 pPrev = pSession;
1188 pSession = pSession->pNextHash;
1189 }
1190 }
1191 }
1192 RTSpinlockRelease(g_Spinlock);
1193 if (!pSession)
1194 {
1195 Log(("VBoxGuestClient::sessionClose: pSession == NULL, pid=%d; freed already?\n", (int)Process));
1196 return;
1197 }
1198
1199 /*
1200 * Remove it from the client object.
1201 */
1202 org_virtualbox_VBoxGuestClient *pThis = (org_virtualbox_VBoxGuestClient *)pSession->pvVBoxGuestClient;
1203 pSession->pvVBoxGuestClient = NULL;
1204 if (pThis)
1205 {
1206 Assert(pThis->m_pSession == pSession);
1207 pThis->m_pSession = NULL;
1208 }
1209
1210 /*
1211 * Close the session.
1212 */
1213 VGDrvCommonCloseSession(&g_DevExt, pSession);
1214}
1215
1216
1217/**
1218 * Client exits normally.
1219 */
1220IOReturn org_virtualbox_VBoxGuestClient::clientClose(void)
1221{
1222 LogFlow(("org_virtualbox_VBoxGuestClient::clientClose([%p]) (cur pid=%d proc=%p)\n", this, RTProcSelf(), RTR0ProcHandleSelf()));
1223 AssertMsg((RTR0PROCESS)m_Task == RTR0ProcHandleSelf(), ("%p %p\n", m_Task, RTR0ProcHandleSelf()));
1224
1225 /*
1226 * Clean up the session if it's still around.
1227 *
1228 * We cannot rely 100% on close, and in the case of a dead client
1229 * we'll end up hanging inside vm_map_remove() if we postpone it.
1230 */
1231 if (m_pSession)
1232 {
1233 sessionClose(RTProcSelf());
1234 Assert(!m_pSession);
1235 }
1236
1237 m_pProvider = NULL;
1238 terminate();
1239
1240 return kIOReturnSuccess;
1241}
1242
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