VirtualBox

source: vbox/trunk/src/VBox/HostDrivers/Support/darwin/SUPDrv-darwin.cpp@ 12000

Last change on this file since 12000 was 11725, checked in by vboxsync, 16 years ago

#3076: Merged in the branch with the alternate driver authentication method. (34468:HEAD)

File size: 31.9 KB
Line 
1/* $Id: $ */
2/** @file
3 *
4 * VBox host drivers - Ring-0 support drivers - Darwin host:
5 * Darwin driver C code
6 */
7
8/*
9 * Copyright (C) 2006-2007 Sun Microsystems, Inc.
10 *
11 * This file is part of VirtualBox Open Source Edition (OSE), as
12 * available from http://www.virtualbox.org. This file is free software;
13 * you can redistribute it and/or modify it under the terms of the GNU
14 * General Public License (GPL) as published by the Free Software
15 * Foundation, in version 2 as it comes in the "COPYING" file of the
16 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
17 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
18 *
19 * The contents of this file may alternatively be used under the terms
20 * of the Common Development and Distribution License Version 1.0
21 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
22 * VirtualBox OSE distribution, in which case the provisions of the
23 * CDDL are applicable instead of those of the GPL.
24 *
25 * You may elect to license modified versions of this file under the
26 * terms and conditions of either the GPL or the CDDL or both.
27 *
28 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
29 * Clara, CA 95054 USA or visit http://www.sun.com if you need
30 * additional information or have any questions.
31 */
32
33/*******************************************************************************
34* Header Files *
35*******************************************************************************/
36#define LOG_GROUP LOG_GROUP_SUP_DRV
37/*
38 * Deal with conflicts first.
39 * PVM - BSD mess, that FreeBSD has correct a long time ago.
40 * iprt/types.h before sys/param.h - prevents UINT32_C and friends.
41 */
42#include <iprt/types.h>
43#include <sys/param.h>
44#undef PVM
45
46#include <IOKit/IOLib.h> /* Assert as function */
47
48#include "../SUPDrvInternal.h"
49#include <VBox/version.h>
50#include <iprt/initterm.h>
51#include <iprt/assert.h>
52#include <iprt/spinlock.h>
53#include <iprt/semaphore.h>
54#include <iprt/process.h>
55#include <iprt/alloc.h>
56#include <iprt/uuid.h>
57#include <iprt/err.h>
58#include <VBox/log.h>
59
60#include <mach/kmod.h>
61#include <miscfs/devfs/devfs.h>
62#include <sys/conf.h>
63#include <sys/errno.h>
64#include <sys/ioccom.h>
65#include <sys/malloc.h>
66#include <sys/proc.h>
67#include <IOKit/IOService.h>
68#include <IOKit/IOUserclient.h>
69
70
71/*******************************************************************************
72* Defined Constants And Macros *
73*******************************************************************************/
74
75/** The module name. */
76#define DEVICE_NAME "vboxdrv"
77
78
79
80/*******************************************************************************
81* Internal Functions *
82*******************************************************************************/
83__BEGIN_DECLS
84static kern_return_t VBoxDrvDarwinStart(struct kmod_info *pKModInfo, void *pvData);
85static kern_return_t VBoxDrvDarwinStop(struct kmod_info *pKModInfo, void *pvData);
86
87static int VBoxDrvDarwinOpen(dev_t Dev, int fFlags, int fDevType, struct proc *pProcess);
88static int VBoxDrvDarwinClose(dev_t Dev, int fFlags, int fDevType, struct proc *pProcess);
89static int VBoxDrvDarwinIOCtl(dev_t Dev, u_long iCmd, caddr_t pData, int fFlags, struct proc *pProcess);
90static int VBoxDrvDarwinIOCtlSlow(PSUPDRVSESSION pSession, u_long iCmd, caddr_t pData, struct proc *pProcess);
91
92static int VBoxDrvDarwinErr2DarwinErr(int rc);
93__END_DECLS
94
95
96/*******************************************************************************
97* Structures and Typedefs *
98*******************************************************************************/
99/**
100 * The service class.
101 * This is just a formality really.
102 */
103class org_virtualbox_SupDrv : public IOService
104{
105 OSDeclareDefaultStructors(org_virtualbox_SupDrv)
106
107public:
108 virtual bool init(OSDictionary *pDictionary = 0);
109 virtual void free(void);
110 virtual bool start(IOService *pProvider);
111 virtual void stop(IOService *pProvider);
112 virtual IOService *probe(IOService *pProvider, SInt32 *pi32Score);
113 virtual bool terminate(IOOptionBits fOptions);
114};
115
116OSDefineMetaClassAndStructors(org_virtualbox_SupDrv, IOService)
117
118
119/**
120 * An attempt at getting that clientDied() notification.
121 * I don't think it'll work as I cannot figure out where/what creates the correct
122 * port right.
123 */
124class org_virtualbox_SupDrvClient : public IOUserClient
125{
126 OSDeclareDefaultStructors(org_virtualbox_SupDrvClient)
127
128private:
129 PSUPDRVSESSION m_pSession; /**< The session. */
130 task_t m_Task; /**< The client task. */
131 org_virtualbox_SupDrv *m_pProvider; /**< The service provider. */
132
133public:
134 virtual bool initWithTask(task_t OwningTask, void *pvSecurityId, UInt32 u32Type);
135 virtual bool start(IOService *pProvider);
136 static void sessionClose(RTPROCESS Process);
137 virtual IOReturn clientClose(void);
138 virtual IOReturn clientDied(void);
139 virtual bool terminate(IOOptionBits fOptions = 0);
140 virtual bool finalize(IOOptionBits fOptions);
141 virtual void stop(IOService *pProvider);
142};
143
144OSDefineMetaClassAndStructors(org_virtualbox_SupDrvClient, IOUserClient)
145
146
147
148/*******************************************************************************
149* Global Variables *
150*******************************************************************************/
151/**
152 * Declare the module stuff.
153 */
154__BEGIN_DECLS
155extern kern_return_t _start(struct kmod_info *pKModInfo, void *pvData);
156extern kern_return_t _stop(struct kmod_info *pKModInfo, void *pvData);
157
158KMOD_EXPLICIT_DECL(VBoxDrv, VBOX_VERSION_STRING, _start, _stop)
159DECLHIDDEN(kmod_start_func_t *) _realmain = VBoxDrvDarwinStart;
160DECLHIDDEN(kmod_stop_func_t *) _antimain = VBoxDrvDarwinStop;
161DECLHIDDEN(int) _kext_apple_cc = __APPLE_CC__;
162__END_DECLS
163
164
165/**
166 * Device extention & session data association structure.
167 */
168static SUPDRVDEVEXT g_DevExt;
169
170/**
171 * The character device switch table for the driver.
172 */
173static struct cdevsw g_DevCW =
174{
175 /** @todo g++ doesn't like this syntax - it worked with gcc before renaming to .cpp. */
176 /*.d_open = */VBoxDrvDarwinOpen,
177 /*.d_close = */VBoxDrvDarwinClose,
178 /*.d_read = */eno_rdwrt,
179 /*.d_write = */eno_rdwrt,
180 /*.d_ioctl = */VBoxDrvDarwinIOCtl,
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_hDevFsDevice = NULL;
196
197/** Spinlock protecting g_apSessionHashTab. */
198static RTSPINLOCK g_Spinlock = NIL_RTSPINLOCK;
199/** Hash table */
200static PSUPDRVSESSION g_apSessionHashTab[19];
201/** Calculates the index into g_apSessionHashTab.*/
202#define SESSION_HASH(pid) ((pid) % RT_ELEMENTS(g_apSessionHashTab))
203/** The number of open sessions. */
204static int32_t volatile g_cSessions = 0;
205
206
207/*
208 * Drag in the rest of IRPT since we share it with the
209 * rest of the kernel modules on darwin.
210 */
211PFNRT g_apfnVBoxDrvIPRTDeps[] =
212{
213 (PFNRT)RTUuidCompare,
214 (PFNRT)RTErrConvertFromErrno,
215 NULL
216};
217
218
219/**
220 * Start the kernel module.
221 */
222static kern_return_t VBoxDrvDarwinStart(struct kmod_info *pKModInfo, void *pvData)
223{
224 int rc;
225#ifdef DEBUG
226 printf("VBoxDrvDarwinStart\n");
227#endif
228
229 /*
230 * Initialize IPRT.
231 */
232 rc = RTR0Init(0);
233 if (RT_SUCCESS(rc))
234 {
235 /*
236 * Initialize the device extension.
237 */
238 rc = supdrvInitDevExt(&g_DevExt);
239 if (RT_SUCCESS(rc))
240 {
241 /*
242 * Initialize the session hash table.
243 */
244 memset(g_apSessionHashTab, 0, sizeof(g_apSessionHashTab)); /* paranoia */
245 rc = RTSpinlockCreate(&g_Spinlock);
246 if (RT_SUCCESS(rc))
247 {
248 /*
249 * Registering ourselves as a character device.
250 */
251 g_iMajorDeviceNo = cdevsw_add(-1, &g_DevCW);
252 if (g_iMajorDeviceNo >= 0)
253 {
254 /** @todo the UID, GID and mode mask should be configurable! This isn't very secure... */
255#ifdef VBOX_WITH_HARDENING
256 g_hDevFsDevice = devfs_make_node(makedev(g_iMajorDeviceNo, 0), DEVFS_CHAR,
257 UID_ROOT, GID_WHEEL, 0600, DEVICE_NAME);
258#else
259 g_hDevFsDevice = devfs_make_node(makedev(g_iMajorDeviceNo, 0), DEVFS_CHAR,
260 UID_ROOT, GID_WHEEL, 0666, DEVICE_NAME);
261#endif
262 if (g_hDevFsDevice)
263 {
264 LogRel(("VBoxDrv: version " VBOX_VERSION_STRING " r%d; IOCtl version %#x; IDC version %#x; dev major=%d\n",
265 VBOX_SVN_REV, SUPDRV_IOC_VERSION, SUPDRV_IDC_VERSION, g_iMajorDeviceNo));
266 return KMOD_RETURN_SUCCESS;
267 }
268
269 LogRel(("VBoxDrv: devfs_make_node(makedev(%d,0),,,,%s) failed\n", g_iMajorDeviceNo, DEVICE_NAME));
270 cdevsw_remove(g_iMajorDeviceNo, &g_DevCW);
271 g_iMajorDeviceNo = -1;
272 }
273 else
274 LogRel(("VBoxDrv: cdevsw_add failed (%d)\n", g_iMajorDeviceNo));
275 RTSpinlockDestroy(g_Spinlock);
276 g_Spinlock = NIL_RTSPINLOCK;
277 }
278 else
279 LogRel(("VBoxDrv: RTSpinlockCreate failed (rc=%d)\n", rc));
280 supdrvDeleteDevExt(&g_DevExt);
281 }
282 else
283 printf("VBoxDrv: failed to initialize device extension (rc=%d)\n", rc);
284 RTR0Term();
285 }
286 else
287 printf("VBoxDrv: failed to initialize IPRT (rc=%d)\n", rc);
288
289 memset(&g_DevExt, 0, sizeof(g_DevExt));
290 return KMOD_RETURN_FAILURE;
291}
292
293
294/**
295 * Stop the kernel module.
296 */
297static kern_return_t VBoxDrvDarwinStop(struct kmod_info *pKModInfo, void *pvData)
298{
299 int rc;
300 LogFlow(("VBoxDrvDarwinStop\n"));
301
302 /** @todo I've got a nagging feeling that we'll have to keep track of users and refuse
303 * unloading if we're busy. Investigate and implement this! */
304
305 /*
306 * Undo the work done during start (in reverse order).
307 */
308 devfs_remove(g_hDevFsDevice);
309 g_hDevFsDevice = NULL;
310
311 rc = cdevsw_remove(g_iMajorDeviceNo, &g_DevCW);
312 Assert(rc == g_iMajorDeviceNo);
313 g_iMajorDeviceNo = -1;
314
315 supdrvDeleteDevExt(&g_DevExt);
316
317 rc = RTSpinlockDestroy(g_Spinlock);
318 AssertRC(rc);
319 g_Spinlock = NIL_RTSPINLOCK;
320
321 RTR0Term();
322
323 memset(&g_DevExt, 0, sizeof(g_DevExt));
324#ifdef DEBUG
325 printf("VBoxDrvDarwinStop - done\n");
326#endif
327 return KMOD_RETURN_SUCCESS;
328}
329
330
331/**
332 * Device open. Called on open /dev/vboxdrv
333 *
334 * @param pInode Pointer to inode info structure.
335 * @param pFilp Associated file pointer.
336 */
337static int VBoxDrvDarwinOpen(dev_t Dev, int fFlags, int fDevType, struct proc *pProcess)
338{
339#ifdef DEBUG_DARWIN_GIP
340 char szName[128];
341 szName[0] = '\0';
342 proc_name(proc_pid(pProcess), szName, sizeof(szName));
343 Log(("VBoxDrvDarwinOpen: pid=%d '%s'\n", proc_pid(pProcess), szName));
344#endif
345
346 /*
347 * Find the session created by org_virtualbox_SupDrvClient, 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 int rc = VINF_SUCCESS;
352 PSUPDRVSESSION pSession = NULL;
353 struct ucred *pCred = proc_ucred(pProcess);
354 if (pCred)
355 {
356 RTUID Uid = pCred->cr_ruid;
357 RTGID Gid = pCred->cr_rgid;
358 RTPROCESS Process = RTProcSelf();
359 unsigned iHash = SESSION_HASH(Process);
360 RTSPINLOCKTMP Tmp = RTSPINLOCKTMP_INITIALIZER;
361 RTSpinlockAcquireNoInts(g_Spinlock, &Tmp);
362
363 pSession = g_apSessionHashTab[iHash];
364 if (pSession && pSession->Process != Process)
365 {
366 do pSession = pSession->pNextHash;
367 while (pSession && pSession->Process != Process);
368 }
369 if (pSession)
370 {
371 if (!pSession->fOpened)
372 {
373 pSession->fOpened = true;
374 pSession->Uid = Uid;
375 pSession->Gid = Gid;
376 }
377 else
378 rc = VERR_ALREADY_LOADED;
379 }
380 else
381 rc = VERR_GENERAL_FAILURE;
382
383 RTSpinlockReleaseNoInts(g_Spinlock, &Tmp);
384 }
385 else
386 rc = SUPDRV_ERR_INVALID_PARAM;
387
388#ifdef DEBUG_DARWIN_GIP
389 OSDBGPRINT(("VBoxDrvDarwinOpen: pid=%d '%s' pSession=%p rc=%d\n", proc_pid(pProcess), szName, pSession, rc));
390#else
391 Log(("VBoxDrvDarwinOpen: g_DevExt=%p pSession=%p rc=%d pid=%d\n", &g_DevExt, pSession, rc, proc_pid(pProcess)));
392#endif
393 return VBoxDrvDarwinErr2DarwinErr(rc);
394}
395
396
397/**
398 * Close device.
399 */
400static int VBoxDrvDarwinClose(dev_t Dev, int fFlags, int fDevType, struct proc *pProcess)
401{
402 Log(("VBoxDrvDarwinClose: pid=%d\n", (int)RTProcSelf()));
403 Assert(proc_pid(pProcess) == (int)RTProcSelf());
404
405 /*
406 * Hand the session closing to org_virtualbox_SupDrvClient.
407 */
408 org_virtualbox_SupDrvClient::sessionClose(RTProcSelf());
409 return 0;
410}
411
412
413/**
414 * Device I/O Control entry point.
415 *
416 * @returns Darwin for slow IOCtls and VBox status code for the fast ones.
417 * @param Dev The device number (major+minor).
418 * @param iCmd The IOCtl command.
419 * @param pData Pointer to the data (if any it's a SUPDRVIOCTLDATA (kernel copy)).
420 * @param fFlags Flag saying we're a character device (like we didn't know already).
421 * @param pProcess The process issuing this request.
422 */
423static int VBoxDrvDarwinIOCtl(dev_t Dev, u_long iCmd, caddr_t pData, int fFlags, struct proc *pProcess)
424{
425 RTSPINLOCKTMP Tmp = RTSPINLOCKTMP_INITIALIZER;
426 const RTPROCESS Process = proc_pid(pProcess);
427 const unsigned iHash = SESSION_HASH(Process);
428 PSUPDRVSESSION pSession;
429
430 /*
431 * Find the session.
432 */
433 RTSpinlockAcquireNoInts(g_Spinlock, &Tmp);
434 pSession = g_apSessionHashTab[iHash];
435 if (pSession && pSession->Process != Process)
436 {
437 do pSession = pSession->pNextHash;
438 while (pSession && pSession->Process != Process);
439 }
440 RTSpinlockReleaseNoInts(g_Spinlock, &Tmp);
441 if (!pSession)
442 {
443 OSDBGPRINT(("VBoxDrvDarwinIOCtl: WHAT?!? pSession == NULL! This must be a mistake... pid=%d iCmd=%#x\n",
444 (int)Process, iCmd));
445 return EINVAL;
446 }
447
448 /*
449 * Deal with the two high-speed IOCtl that takes it's arguments from
450 * the session and iCmd, and only returns a VBox status code.
451 */
452 if ( iCmd == SUP_IOCTL_FAST_DO_RAW_RUN
453 || iCmd == SUP_IOCTL_FAST_DO_HWACC_RUN
454 || iCmd == SUP_IOCTL_FAST_DO_NOP)
455 return supdrvIOCtlFast(iCmd, &g_DevExt, pSession);
456 return VBoxDrvDarwinIOCtlSlow(pSession, iCmd, pData, pProcess);
457}
458
459
460/**
461 * Worker for VBoxDrvDarwinIOCtl that takes the slow IOCtl functions.
462 *
463 * @returns Darwin errno.
464 *
465 * @param pSession The session.
466 * @param iCmd The IOCtl command.
467 * @param pData Pointer to the kernel copy of the SUPDRVIOCTLDATA buffer.
468 * @param pProcess The calling process.
469 */
470static int VBoxDrvDarwinIOCtlSlow(PSUPDRVSESSION pSession, u_long iCmd, caddr_t pData, struct proc *pProcess)
471{
472 LogFlow(("VBoxDrvDarwinIOCtlSlow: pSession=%p iCmd=%p pData=%p pProcess=%p\n", pSession, iCmd, pData, pProcess));
473
474
475 /*
476 * Buffered or unbuffered?
477 */
478 PSUPREQHDR pHdr;
479 user_addr_t pUser = 0;
480 void *pvPageBuf = NULL;
481 uint32_t cbReq = IOCPARM_LEN(iCmd);
482 if ((IOC_DIRMASK & iCmd) == IOC_INOUT)
483 {
484 pHdr = (PSUPREQHDR)pData;
485 if (RT_UNLIKELY(cbReq < sizeof(*pHdr)))
486 {
487 OSDBGPRINT(("VBoxDrvDarwinIOCtlSlow: cbReq=%#x < %#x; iCmd=%#lx\n", cbReq, (int)sizeof(*pHdr), iCmd));
488 return EINVAL;
489 }
490 if (RT_UNLIKELY((pHdr->fFlags & SUPREQHDR_FLAGS_MAGIC_MASK) != SUPREQHDR_FLAGS_MAGIC))
491 {
492 OSDBGPRINT(("VBoxDrvDarwinIOCtlSlow: bad magic fFlags=%#x; iCmd=%#lx\n", pHdr->fFlags, iCmd));
493 return EINVAL;
494 }
495 if (RT_UNLIKELY( RT_MAX(pHdr->cbIn, pHdr->cbOut) != cbReq
496 || pHdr->cbIn < sizeof(*pHdr)
497 || pHdr->cbOut < sizeof(*pHdr)))
498 {
499 OSDBGPRINT(("VBoxDrvDarwinIOCtlSlow: max(%#x,%#x) != %#x; iCmd=%#lx\n", pHdr->cbIn, pHdr->cbOut, cbReq, iCmd));
500 return EINVAL;
501 }
502 }
503 else if ((IOC_DIRMASK & iCmd) == IOC_VOID && !cbReq)
504 {
505 /*
506 * Get the header and figure out how much we're gonna have to read.
507 */
508 SUPREQHDR Hdr;
509 pUser = (user_addr_t)*(void **)pData;
510 int rc = copyin(pUser, &Hdr, sizeof(Hdr));
511 if (RT_UNLIKELY(rc))
512 {
513 OSDBGPRINT(("VBoxDrvDarwinIOCtlSlow: copyin(%llx,Hdr,) -> %#x; iCmd=%#lx\n", (unsigned long long)pUser, rc, iCmd));
514 return rc;
515 }
516 if (RT_UNLIKELY((Hdr.fFlags & SUPREQHDR_FLAGS_MAGIC_MASK) != SUPREQHDR_FLAGS_MAGIC))
517 {
518 OSDBGPRINT(("VBoxDrvDarwinIOCtlSlow: bad magic fFlags=%#x; iCmd=%#lx\n", Hdr.fFlags, iCmd));
519 return EINVAL;
520 }
521 cbReq = RT_MAX(Hdr.cbIn, Hdr.cbOut);
522 if (RT_UNLIKELY( Hdr.cbIn < sizeof(Hdr)
523 || Hdr.cbOut < sizeof(Hdr)
524 || cbReq > _1M*16))
525 {
526 OSDBGPRINT(("VBoxDrvDarwinIOCtlSlow: max(%#x,%#x); iCmd=%#lx\n", Hdr.cbIn, Hdr.cbOut, iCmd));
527 return EINVAL;
528 }
529
530 /*
531 * Allocate buffer and copy in the data.
532 */
533 pHdr = (PSUPREQHDR)RTMemTmpAlloc(cbReq);
534 if (!pHdr)
535 pvPageBuf = pHdr = (PSUPREQHDR)IOMallocAligned(RT_ALIGN_Z(cbReq, PAGE_SIZE), 8);
536 if (RT_UNLIKELY(!pHdr))
537 {
538 OSDBGPRINT(("VBoxDrvDarwinIOCtlSlow: failed to allocate buffer of %d bytes; iCmd=%#lx\n", cbReq, iCmd));
539 return ENOMEM;
540 }
541 rc = copyin(pUser, pHdr, Hdr.cbIn);
542 if (RT_UNLIKELY(rc))
543 {
544 OSDBGPRINT(("VBoxDrvDarwinIOCtlSlow: copyin(%llx,%p,%#x) -> %#x; iCmd=%#lx\n",
545 (unsigned long long)pUser, pHdr, Hdr.cbIn, rc, iCmd));
546 if (pvPageBuf)
547 IOFreeAligned(pvPageBuf, RT_ALIGN_Z(cbReq, PAGE_SIZE));
548 else
549 RTMemTmpFree(pHdr);
550 return rc;
551 }
552 }
553 else
554 {
555 Log(("VBoxDrvDarwinIOCtlSlow: huh? cbReq=%#x iCmd=%#lx\n", cbReq, iCmd));
556 return EINVAL;
557 }
558
559 /*
560 * Process the IOCtl.
561 */
562 int rc = supdrvIOCtl(iCmd, &g_DevExt, pSession, pHdr);
563 if (RT_LIKELY(!rc))
564 {
565 /*
566 * If not buffered, copy back the buffer before returning.
567 */
568 if (pUser)
569 {
570 uint32_t cbOut = pHdr->cbOut;
571 if (cbOut > cbReq)
572 {
573 OSDBGPRINT(("VBoxDrvDarwinIOCtlSlow: too much output! %#x > %#x; uCmd=%#lx!\n", cbOut, cbReq, iCmd));
574 cbOut = cbReq;
575 }
576 rc = copyout(pHdr, pUser, cbOut);
577 if (RT_UNLIKELY(rc))
578 OSDBGPRINT(("VBoxDrvDarwinIOCtlSlow: copyout(%p,%llx,%#x) -> %d; uCmd=%#lx!\n",
579 pHdr, (unsigned long long)pUser, cbOut, rc, iCmd));
580
581 /* cleanup */
582 if (pvPageBuf)
583 IOFreeAligned(pvPageBuf, RT_ALIGN_Z(cbReq, PAGE_SIZE));
584 else
585 RTMemTmpFree(pHdr);
586 }
587 }
588 else
589 {
590 /*
591 * The request failed, just clean up.
592 */
593 if (pUser)
594 {
595 if (pvPageBuf)
596 IOFreeAligned(pvPageBuf, RT_ALIGN_Z(cbReq, PAGE_SIZE));
597 else
598 RTMemTmpFree(pHdr);
599 }
600
601 Log(("VBoxDrvDarwinIOCtlSlow: pid=%d iCmd=%lx pData=%p failed, rc=%d\n", proc_pid(pProcess), iCmd, (void *)pData, rc));
602 rc = EINVAL;
603 }
604
605 Log2(("VBoxDrvDarwinIOCtlSlow: returns %d\n", rc));
606 return rc;
607}
608
609
610/**
611 * The SUPDRV IDC entry point.
612 *
613 * @returns VBox status code, see supdrvIDC.
614 * @param iReq The request code.
615 * @param pReq The request.
616 */
617int VBOXCALL SUPDrvDarwinIDC(uint32_t uReq, PSUPDRVIDCREQHDR pReq)
618{
619 PSUPDRVSESSION pSession;
620
621 /*
622 * Some quick validations.
623 */
624 if (RT_UNLIKELY(!VALID_PTR(pReq)))
625 return VERR_INVALID_POINTER;
626
627 pSession = pReq->pSession;
628 if (pSession)
629 {
630 if (RT_UNLIKELY(!VALID_PTR(pSession)))
631 return VERR_INVALID_PARAMETER;
632 if (RT_UNLIKELY(pSession->pDevExt != &g_DevExt))
633 return VERR_INVALID_PARAMETER;
634 }
635 else if (RT_UNLIKELY(uReq != SUPDRV_IDC_REQ_CONNECT))
636 return VERR_INVALID_PARAMETER;
637
638 /*
639 * Do the job.
640 */
641 return supdrvIDC(uReq, &g_DevExt, pSession, pReq);
642}
643
644
645/**
646 * Initializes any OS specific object creator fields.
647 */
648void VBOXCALL supdrvOSObjInitCreator(PSUPDRVOBJ pObj, PSUPDRVSESSION pSession)
649{
650 NOREF(pObj);
651 NOREF(pSession);
652}
653
654
655/**
656 * Checks if the session can access the object.
657 *
658 * @returns true if a decision has been made.
659 * @returns false if the default access policy should be applied.
660 *
661 * @param pObj The object in question.
662 * @param pSession The session wanting to access the object.
663 * @param pszObjName The object name, can be NULL.
664 * @param prc Where to store the result when returning true.
665 */
666bool VBOXCALL supdrvOSObjCanAccess(PSUPDRVOBJ pObj, PSUPDRVSESSION pSession, const char *pszObjName, int *prc)
667{
668 NOREF(pObj);
669 NOREF(pSession);
670 NOREF(pszObjName);
671 NOREF(prc);
672 return false;
673}
674
675
676bool VBOXCALL supdrvOSGetForcedAsyncTscMode(PSUPDRVDEVEXT pDevExt)
677{
678 NOREF(pDevExt);
679 return false;
680}
681
682
683/**
684 * Converts a supdrv error code to a darwin error code.
685 *
686 * @returns corresponding darwin error code.
687 * @param rc supdrv error code (SUPDRV_ERR_* defines).
688 */
689static int VBoxDrvDarwinErr2DarwinErr(int rc)
690{
691 switch (rc)
692 {
693 case 0: return 0;
694 case SUPDRV_ERR_GENERAL_FAILURE: return EACCES;
695 case SUPDRV_ERR_INVALID_PARAM: return EINVAL;
696 case SUPDRV_ERR_INVALID_MAGIC: return EILSEQ;
697 case SUPDRV_ERR_INVALID_HANDLE: return ENXIO;
698 case SUPDRV_ERR_INVALID_POINTER: return EFAULT;
699 case SUPDRV_ERR_LOCK_FAILED: return ENOLCK;
700 case SUPDRV_ERR_ALREADY_LOADED: return EEXIST;
701 case SUPDRV_ERR_PERMISSION_DENIED: return EPERM;
702 case SUPDRV_ERR_VERSION_MISMATCH: return ENOSYS;
703 }
704
705 return EPERM;
706}
707
708
709/** @todo move this to assembly where a simple "jmp printf" will to the trick. */
710RTDECL(int) SUPR0Printf(const char *pszFormat, ...)
711{
712 va_list args;
713 char szMsg[512];
714
715 va_start(args, pszFormat);
716 vsnprintf(szMsg, sizeof(szMsg) - 1, pszFormat, args);
717 va_end(args);
718
719 szMsg[sizeof(szMsg) - 1] = '\0';
720 printf("%s", szMsg);
721 return 0;
722}
723
724
725/*
726 *
727 * org_virtualbox_SupDrv
728 *
729 */
730
731
732/**
733 * Initialize the object.
734 */
735bool org_virtualbox_SupDrv::init(OSDictionary *pDictionary)
736{
737 LogFlow(("org_virtualbox_SupDrv::init([%p], %p)\n", this, pDictionary));
738 if (IOService::init(pDictionary))
739 {
740 /* init members. */
741 return true;
742 }
743 return false;
744}
745
746
747/**
748 * Free the object.
749 */
750void org_virtualbox_SupDrv::free(void)
751{
752 LogFlow(("IOService::free([%p])\n", this));
753 IOService::free();
754}
755
756
757/**
758 * Check if it's ok to start this service.
759 * It's always ok by us, so it's up to IOService to decide really.
760 */
761IOService *org_virtualbox_SupDrv::probe(IOService *pProvider, SInt32 *pi32Score)
762{
763 LogFlow(("org_virtualbox_SupDrv::probe([%p])\n", this));
764 return IOService::probe(pProvider, pi32Score);
765}
766
767
768/**
769 * Start this service.
770 */
771bool org_virtualbox_SupDrv::start(IOService *pProvider)
772{
773 LogFlow(("org_virtualbox_SupDrv::start([%p])\n", this));
774
775 if (IOService::start(pProvider))
776 {
777 /* register the service. */
778 registerService();
779 return true;
780 }
781 return false;
782}
783
784
785/**
786 * Stop this service.
787 */
788void org_virtualbox_SupDrv::stop(IOService *pProvider)
789{
790 LogFlow(("org_virtualbox_SupDrv::stop([%p], %p)\n", this, pProvider));
791 IOService::stop(pProvider);
792}
793
794
795/**
796 * Termination request.
797 *
798 * @return true if we're ok with shutting down now, false if we're not.
799 * @param fOptions Flags.
800 */
801bool org_virtualbox_SupDrv::terminate(IOOptionBits fOptions)
802{
803 bool fRc;
804 LogFlow(("org_virtualbox_SupDrv::terminate: reference_count=%d g_cSessions=%d (fOptions=%#x)\n",
805 KMOD_INFO_NAME.reference_count, ASMAtomicUoReadS32(&g_cSessions), fOptions));
806 if ( KMOD_INFO_NAME.reference_count != 0
807 || ASMAtomicUoReadS32(&g_cSessions))
808 fRc = false;
809 else
810 fRc = IOService::terminate(fOptions);
811 LogFlow(("org_virtualbox_SupDrv::terminate: returns %d\n", fRc));
812 return fRc;
813}
814
815
816/*
817 *
818 * org_virtualbox_SupDrvClient
819 *
820 */
821
822
823/**
824 * Initializer called when the client opens the service.
825 */
826bool org_virtualbox_SupDrvClient::initWithTask(task_t OwningTask, void *pvSecurityId, UInt32 u32Type)
827{
828 LogFlow(("org_virtualbox_SupDrvClient::initWithTask([%p], %#x, %p, %#x) (cur pid=%d proc=%p)\n",
829 this, OwningTask, pvSecurityId, u32Type, RTProcSelf(), RTR0ProcHandleSelf()));
830 AssertMsg((RTR0PROCESS)OwningTask == RTR0ProcHandleSelf(), ("%p %p\n", OwningTask, RTR0ProcHandleSelf()));
831
832 if (!OwningTask)
833 return false;
834 if (IOUserClient::initWithTask(OwningTask, pvSecurityId , u32Type))
835 {
836 m_Task = OwningTask;
837 m_pSession = NULL;
838 m_pProvider = NULL;
839 return true;
840 }
841 return false;
842}
843
844
845/**
846 * Start the client service.
847 */
848bool org_virtualbox_SupDrvClient::start(IOService *pProvider)
849{
850 LogFlow(("org_virtualbox_SupDrvClient::start([%p], %p) (cur pid=%d proc=%p)\n",
851 this, pProvider, RTProcSelf(), RTR0ProcHandleSelf() ));
852 AssertMsgReturn((RTR0PROCESS)m_Task == RTR0ProcHandleSelf(),
853 ("%p %p\n", m_Task, RTR0ProcHandleSelf()),
854 false);
855
856 if (IOUserClient::start(pProvider))
857 {
858 m_pProvider = OSDynamicCast(org_virtualbox_SupDrv, pProvider);
859 if (m_pProvider)
860 {
861 Assert(!m_pSession);
862
863 /*
864 * Create a new session.
865 */
866 int rc = supdrvCreateSession(&g_DevExt, true /* fUser */, &m_pSession);
867 if (RT_SUCCESS(rc))
868 {
869 m_pSession->fOpened = false;
870 /* The Uid and Gid fields are set on open. */
871
872 /*
873 * Insert it into the hash table, checking that there isn't
874 * already one for this process first.
875 */
876 unsigned iHash = SESSION_HASH(m_pSession->Process);
877 RTSPINLOCKTMP Tmp = RTSPINLOCKTMP_INITIALIZER;
878 RTSpinlockAcquireNoInts(g_Spinlock, &Tmp);
879
880 PSUPDRVSESSION pCur = g_apSessionHashTab[iHash];
881 if (pCur && pCur->Process != m_pSession->Process)
882 {
883 do pCur = pCur->pNextHash;
884 while (pCur && pCur->Process != m_pSession->Process);
885 }
886 if (!pCur)
887 {
888 m_pSession->pNextHash = g_apSessionHashTab[iHash];
889 g_apSessionHashTab[iHash] = m_pSession;
890 m_pSession->pvSupDrvClient = this;
891 ASMAtomicIncS32(&g_cSessions);
892 rc = VINF_SUCCESS;
893 }
894 else
895 rc = VERR_ALREADY_LOADED;
896
897 RTSpinlockReleaseNoInts(g_Spinlock, &Tmp);
898 if (RT_SUCCESS(rc))
899 {
900 Log(("org_virtualbox_SupDrvClient::start: created session %p for pid %d\n", m_pSession, (int)RTProcSelf()));
901 return true;
902 }
903
904 LogFlow(("org_virtualbox_SupDrvClient::start: already got a session for this process (%p)\n", pCur));
905 supdrvCloseSession(&g_DevExt, m_pSession);
906 }
907
908 m_pSession = NULL;
909 LogFlow(("org_virtualbox_SupDrvClient::start: rc=%Rrc from supdrvCreateSession\n", rc));
910 }
911 else
912 LogFlow(("org_virtualbox_SupDrvClient::start: %p isn't org_virtualbox_SupDrv\n", pProvider));
913 }
914 return false;
915}
916
917
918/**
919 * Common worker for clientClose and VBoxDrvDarwinClose.
920 *
921 * It will
922 */
923/* static */ void org_virtualbox_SupDrvClient::sessionClose(RTPROCESS Process)
924{
925 /*
926 * Look for the session.
927 */
928 const unsigned iHash = SESSION_HASH(Process);
929 RTSPINLOCKTMP Tmp = RTSPINLOCKTMP_INITIALIZER;
930 RTSpinlockAcquireNoInts(g_Spinlock, &Tmp);
931 PSUPDRVSESSION pSession = g_apSessionHashTab[iHash];
932 if (pSession)
933 {
934 if (pSession->Process == Process)
935 {
936 g_apSessionHashTab[iHash] = pSession->pNextHash;
937 pSession->pNextHash = NULL;
938 ASMAtomicDecS32(&g_cSessions);
939 }
940 else
941 {
942 PSUPDRVSESSION pPrev = pSession;
943 pSession = pSession->pNextHash;
944 while (pSession)
945 {
946 if (pSession->Process == Process)
947 {
948 pPrev->pNextHash = pSession->pNextHash;
949 pSession->pNextHash = NULL;
950 ASMAtomicDecS32(&g_cSessions);
951 break;
952 }
953
954 /* next */
955 pPrev = pSession;
956 pSession = pSession->pNextHash;
957 }
958 }
959 }
960 RTSpinlockReleaseNoInts(g_Spinlock, &Tmp);
961 if (!pSession)
962 {
963 Log(("SupDrvClient::sessionClose: pSession == NULL, pid=%d; freed already?\n", (int)Process));
964 return;
965 }
966
967 /*
968 * Remove it from the client object.
969 */
970 org_virtualbox_SupDrvClient *pThis = (org_virtualbox_SupDrvClient *)pSession->pvSupDrvClient;
971 pSession->pvSupDrvClient = NULL;
972 if (pThis)
973 {
974 Assert(pThis->m_pSession == pSession);
975 pThis->m_pSession = NULL;
976 }
977
978 /*
979 * Close the session.
980 */
981 supdrvCloseSession(&g_DevExt, pSession);
982}
983
984
985/**
986 * Client exits normally.
987 */
988IOReturn org_virtualbox_SupDrvClient::clientClose(void)
989{
990 LogFlow(("org_virtualbox_SupDrvClient::clientClose([%p]) (cur pid=%d proc=%p)\n", this, RTProcSelf(), RTR0ProcHandleSelf()));
991 AssertMsg((RTR0PROCESS)m_Task == RTR0ProcHandleSelf(), ("%p %p\n", m_Task, RTR0ProcHandleSelf()));
992
993 /*
994 * Clean up the session if it's still around.
995 *
996 * We cannot rely 100% on close, and in the case of a dead client
997 * we'll end up hanging inside vm_map_remove() if we postpone it.
998 */
999 if (m_pSession)
1000 {
1001 sessionClose(RTProcSelf());
1002 Assert(!m_pSession);
1003 }
1004
1005 m_pProvider = NULL;
1006 terminate();
1007
1008 return kIOReturnSuccess;
1009}
1010
1011
1012/**
1013 * The client exits abnormally / forgets to do cleanups. (logging)
1014 */
1015IOReturn org_virtualbox_SupDrvClient::clientDied(void)
1016{
1017 LogFlow(("org_virtualbox_SupDrvClient::clientDied([%p]) m_Task=%p R0Process=%p Process=%d\n",
1018 this, m_Task, RTR0ProcHandleSelf(), RTProcSelf()));
1019
1020 /* IOUserClient::clientDied() calls clientClose, so we'll just do the work there. */
1021 return IOUserClient::clientDied();
1022}
1023
1024
1025/**
1026 * Terminate the service (initiate the destruction). (logging)
1027 */
1028bool org_virtualbox_SupDrvClient::terminate(IOOptionBits fOptions)
1029{
1030 LogFlow(("org_virtualbox_SupDrvClient::terminate([%p], %#x)\n", this, fOptions));
1031 return IOUserClient::terminate(fOptions);
1032}
1033
1034
1035/**
1036 * The final stage of the client service destruction. (logging)
1037 */
1038bool org_virtualbox_SupDrvClient::finalize(IOOptionBits fOptions)
1039{
1040 LogFlow(("org_virtualbox_SupDrvClient::finalize([%p], %#x)\n", this, fOptions));
1041 return IOUserClient::finalize(fOptions);
1042}
1043
1044
1045/**
1046 * Stop the client service. (logging)
1047 */
1048void org_virtualbox_SupDrvClient::stop(IOService *pProvider)
1049{
1050 LogFlow(("org_virtualbox_SupDrvClient::stop([%p])\n", this));
1051 IOUserClient::stop(pProvider);
1052}
1053
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