VirtualBox

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

Last change on this file since 46428 was 46354, checked in by vboxsync, 12 years ago

additions/darwin: includes IOkit -> IOKit.

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