VirtualBox

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

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

BUGZ:4686 OS X guest: VBoxGuest device driver + VBoxService and VBoxControl now work.

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette