VirtualBox

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

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

Mac OS X host: HID LEDs sync: take care about bluetooth keyboard: wake it up before setting LED in order to decrease LED-set-operation delay up to ~1-0.5 seconds.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 48.7 KB
Line 
1/* $Id: SUPDrv-darwin.cpp 49965 2013-12-17 20:20:45Z vboxsync $ */
2/** @file
3 * VirtualBox Support Driver - Darwin Specific Code.
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_SUP_DRV
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 "../SUPDrvInternal.h"
43#include <VBox/version.h>
44#include <iprt/asm.h>
45#include <iprt/asm-amd64-x86.h>
46#include <iprt/initterm.h>
47#include <iprt/assert.h>
48#include <iprt/spinlock.h>
49#include <iprt/semaphore.h>
50#include <iprt/process.h>
51#include <iprt/alloc.h>
52#include <iprt/power.h>
53#include <iprt/dbg.h>
54#include <VBox/err.h>
55#include <VBox/log.h>
56
57#include <mach/kmod.h>
58#include <miscfs/devfs/devfs.h>
59#include <sys/conf.h>
60#include <sys/errno.h>
61#include <sys/ioccom.h>
62#include <sys/malloc.h>
63#include <sys/proc.h>
64#include <sys/kauth.h>
65#include <IOKit/IOService.h>
66#include <IOKit/IOUserClient.h>
67#include <IOKit/pwr_mgt/RootDomain.h>
68#include <IOKit/IODeviceTreeSupport.h>
69#include <IOKit/usb/IOUSBHIDDriver.h>
70#include <IOKit/bluetooth/IOBluetoothHIDDriver.h>
71#include <IOKit/bluetooth/IOBluetoothHIDDriverTypes.h>
72
73#ifdef VBOX_WITH_HOST_VMX
74# include <libkern/version.h>
75RT_C_DECLS_BEGIN
76# include <i386/vmx.h>
77RT_C_DECLS_END
78#endif
79
80
81/*******************************************************************************
82* Defined Constants And Macros *
83*******************************************************************************/
84
85/** The system device node name. */
86#define DEVICE_NAME_SYS "vboxdrv"
87/** The user device node name. */
88#define DEVICE_NAME_USR "vboxdrvu"
89
90
91
92/*******************************************************************************
93* Internal Functions *
94*******************************************************************************/
95RT_C_DECLS_BEGIN
96static kern_return_t VBoxDrvDarwinStart(struct kmod_info *pKModInfo, void *pvData);
97static kern_return_t VBoxDrvDarwinStop(struct kmod_info *pKModInfo, void *pvData);
98
99static int VBoxDrvDarwinOpen(dev_t Dev, int fFlags, int fDevType, struct proc *pProcess);
100static int VBoxDrvDarwinClose(dev_t Dev, int fFlags, int fDevType, struct proc *pProcess);
101static int VBoxDrvDarwinIOCtl(dev_t Dev, u_long iCmd, caddr_t pData, int fFlags, struct proc *pProcess);
102static int VBoxDrvDarwinIOCtlSlow(PSUPDRVSESSION pSession, u_long iCmd, caddr_t pData, struct proc *pProcess);
103
104static int VBoxDrvDarwinErr2DarwinErr(int rc);
105
106static IOReturn VBoxDrvDarwinSleepHandler(void *pvTarget, void *pvRefCon, UInt32 uMessageType, IOService *pProvider, void *pvMessageArgument, vm_size_t argSize);
107RT_C_DECLS_END
108
109static void vboxdrvDarwinResolveSymbols(void);
110
111
112/*******************************************************************************
113* Structures and Typedefs *
114*******************************************************************************/
115/**
116 * The service class.
117 * This is just a formality really.
118 */
119class org_virtualbox_SupDrv : public IOService
120{
121 OSDeclareDefaultStructors(org_virtualbox_SupDrv);
122
123public:
124 virtual bool init(OSDictionary *pDictionary = 0);
125 virtual void free(void);
126 virtual bool start(IOService *pProvider);
127 virtual void stop(IOService *pProvider);
128 virtual IOService *probe(IOService *pProvider, SInt32 *pi32Score);
129 virtual bool terminate(IOOptionBits fOptions);
130};
131
132OSDefineMetaClassAndStructors(org_virtualbox_SupDrv, IOService);
133
134
135/**
136 * An attempt at getting that clientDied() notification.
137 * I don't think it'll work as I cannot figure out where/what creates the correct
138 * port right.
139 */
140class org_virtualbox_SupDrvClient : public IOUserClient
141{
142 OSDeclareDefaultStructors(org_virtualbox_SupDrvClient);
143
144private:
145 PSUPDRVSESSION m_pSession; /**< The session. */
146 task_t m_Task; /**< The client task. */
147 org_virtualbox_SupDrv *m_pProvider; /**< The service provider. */
148
149public:
150 virtual bool initWithTask(task_t OwningTask, void *pvSecurityId, UInt32 u32Type);
151 virtual bool start(IOService *pProvider);
152 static void sessionClose(RTPROCESS Process);
153 virtual IOReturn clientClose(void);
154 virtual IOReturn clientDied(void);
155 virtual bool terminate(IOOptionBits fOptions = 0);
156 virtual bool finalize(IOOptionBits fOptions);
157 virtual void stop(IOService *pProvider);
158};
159
160OSDefineMetaClassAndStructors(org_virtualbox_SupDrvClient, IOUserClient);
161
162
163
164/*******************************************************************************
165* Global Variables *
166*******************************************************************************/
167/**
168 * Declare the module stuff.
169 */
170RT_C_DECLS_BEGIN
171extern kern_return_t _start(struct kmod_info *pKModInfo, void *pvData);
172extern kern_return_t _stop(struct kmod_info *pKModInfo, void *pvData);
173
174KMOD_EXPLICIT_DECL(VBoxDrv, VBOX_VERSION_STRING, _start, _stop)
175DECLHIDDEN(kmod_start_func_t *) _realmain = VBoxDrvDarwinStart;
176DECLHIDDEN(kmod_stop_func_t *) _antimain = VBoxDrvDarwinStop;
177DECLHIDDEN(int) _kext_apple_cc = __APPLE_CC__;
178RT_C_DECLS_END
179
180
181/**
182 * Device extention & session data association structure.
183 */
184static SUPDRVDEVEXT g_DevExt;
185
186/**
187 * The character device switch table for the driver.
188 */
189static struct cdevsw g_DevCW =
190{
191 /** @todo g++ doesn't like this syntax - it worked with gcc before renaming to .cpp. */
192 /*.d_open = */VBoxDrvDarwinOpen,
193 /*.d_close = */VBoxDrvDarwinClose,
194 /*.d_read = */eno_rdwrt,
195 /*.d_write = */eno_rdwrt,
196 /*.d_ioctl = */VBoxDrvDarwinIOCtl,
197 /*.d_stop = */eno_stop,
198 /*.d_reset = */eno_reset,
199 /*.d_ttys = */NULL,
200 /*.d_select= */eno_select,
201 /*.d_mmap = */eno_mmap,
202 /*.d_strategy = */eno_strat,
203 /*.d_getc = */eno_getc,
204 /*.d_putc = */eno_putc,
205 /*.d_type = */0
206};
207
208/** Major device number. */
209static int g_iMajorDeviceNo = -1;
210/** Registered devfs device handle for the system device. */
211static void *g_hDevFsDeviceSys = NULL;
212/** Registered devfs device handle for the user device. */
213static void *g_hDevFsDeviceUsr = NULL;
214
215/** Spinlock protecting g_apSessionHashTab. */
216static RTSPINLOCK g_Spinlock = NIL_RTSPINLOCK;
217/** Hash table */
218static PSUPDRVSESSION g_apSessionHashTab[19];
219/** Calculates the index into g_apSessionHashTab.*/
220#define SESSION_HASH(pid) ((pid) % RT_ELEMENTS(g_apSessionHashTab))
221/** The number of open sessions. */
222static int32_t volatile g_cSessions = 0;
223/** The notifier handle for the sleep callback handler. */
224static IONotifier *g_pSleepNotifier = NULL;
225
226/** Pointer to vmx_suspend(). */
227static PFNRT g_pfnVmxSuspend = NULL;
228/** Pointer to vmx_resume(). */
229static PFNRT g_pfnVmxResume = NULL;
230/** Pointer to vmx_use_count. */
231static int volatile *g_pVmxUseCount = NULL;
232
233#ifdef SUPDRV_WITH_MSR_PROBER
234/** Pointer to rdmsr_carefully if found. Returns 0 on success. */
235static int (*g_pfnRdMsrCarefully)(uint32_t uMsr, uint32_t *puLow, uint32_t *puHigh) = NULL;
236/** Pointer to rdmsr64_carefully if found. Returns 0 on success. */
237static int (*g_pfnRdMsr64Carefully)(uint32_t uMsr, uint64_t *uValue) = NULL;
238/** Pointer to wrmsr[64]_carefully if found. Returns 0 on success. */
239static int (*g_pfnWrMsr64Carefully)(uint32_t uMsr, uint64_t uValue) = NULL;
240#endif
241
242
243/**
244 * Start the kernel module.
245 */
246static kern_return_t VBoxDrvDarwinStart(struct kmod_info *pKModInfo, void *pvData)
247{
248 int rc;
249#ifdef DEBUG
250 printf("VBoxDrvDarwinStart\n");
251#endif
252
253 /*
254 * Initialize IPRT.
255 */
256 rc = RTR0Init(0);
257 if (RT_SUCCESS(rc))
258 {
259 /*
260 * Initialize the device extension.
261 */
262 rc = supdrvInitDevExt(&g_DevExt, sizeof(SUPDRVSESSION));
263 if (RT_SUCCESS(rc))
264 {
265 /*
266 * Initialize the session hash table.
267 */
268 memset(g_apSessionHashTab, 0, sizeof(g_apSessionHashTab)); /* paranoia */
269 rc = RTSpinlockCreate(&g_Spinlock, RTSPINLOCK_FLAGS_INTERRUPT_SAFE, "VBoxDrvDarwin");
270 if (RT_SUCCESS(rc))
271 {
272 /*
273 * Registering ourselves as a character device.
274 */
275 g_iMajorDeviceNo = cdevsw_add(-1, &g_DevCW);
276 if (g_iMajorDeviceNo >= 0)
277 {
278#ifdef VBOX_WITH_HARDENING
279 g_hDevFsDeviceSys = devfs_make_node(makedev(g_iMajorDeviceNo, 0), DEVFS_CHAR,
280 UID_ROOT, GID_WHEEL, 0600, DEVICE_NAME_SYS);
281#else
282 g_hDevFsDeviceSys = devfs_make_node(makedev(g_iMajorDeviceNo, 0), DEVFS_CHAR,
283 UID_ROOT, GID_WHEEL, 0666, DEVICE_NAME_SYS);
284#endif
285 if (g_hDevFsDeviceSys)
286 {
287 g_hDevFsDeviceUsr = devfs_make_node(makedev(g_iMajorDeviceNo, 1), DEVFS_CHAR,
288 UID_ROOT, GID_WHEEL, 0666, DEVICE_NAME_USR);
289 if (g_hDevFsDeviceUsr)
290 {
291 LogRel(("VBoxDrv: version " VBOX_VERSION_STRING " r%d; IOCtl version %#x; IDC version %#x; dev major=%d\n",
292 VBOX_SVN_REV, SUPDRV_IOC_VERSION, SUPDRV_IDC_VERSION, g_iMajorDeviceNo));
293
294 /* Register a sleep/wakeup notification callback */
295 g_pSleepNotifier = registerPrioritySleepWakeInterest(&VBoxDrvDarwinSleepHandler, &g_DevExt, NULL);
296 if (g_pSleepNotifier == NULL)
297 LogRel(("VBoxDrv: register for sleep/wakeup events failed\n"));
298
299 /* Find kernel symbols that are kind of optional. */
300 vboxdrvDarwinResolveSymbols();
301 return KMOD_RETURN_SUCCESS;
302 }
303
304 LogRel(("VBoxDrv: devfs_make_node(makedev(%d,1),,,,%s) failed\n", g_iMajorDeviceNo, DEVICE_NAME_USR));
305 devfs_remove(g_hDevFsDeviceSys);
306 g_hDevFsDeviceSys = NULL;
307 }
308 else
309 LogRel(("VBoxDrv: devfs_make_node(makedev(%d,0),,,,%s) failed\n", g_iMajorDeviceNo, DEVICE_NAME_SYS));
310
311 cdevsw_remove(g_iMajorDeviceNo, &g_DevCW);
312 g_iMajorDeviceNo = -1;
313 }
314 else
315 LogRel(("VBoxDrv: cdevsw_add failed (%d)\n", g_iMajorDeviceNo));
316 RTSpinlockDestroy(g_Spinlock);
317 g_Spinlock = NIL_RTSPINLOCK;
318 }
319 else
320 LogRel(("VBoxDrv: RTSpinlockCreate failed (rc=%d)\n", rc));
321 supdrvDeleteDevExt(&g_DevExt);
322 }
323 else
324 printf("VBoxDrv: failed to initialize device extension (rc=%d)\n", rc);
325 RTR0TermForced();
326 }
327 else
328 printf("VBoxDrv: failed to initialize IPRT (rc=%d)\n", rc);
329
330 memset(&g_DevExt, 0, sizeof(g_DevExt));
331 return KMOD_RETURN_FAILURE;
332}
333
334
335/**
336 * Resolves kernel symbols we want (but may do without).
337 */
338static void vboxdrvDarwinResolveSymbols(void)
339{
340 RTDBGKRNLINFO hKrnlInfo;
341 int rc = RTR0DbgKrnlInfoOpen(&hKrnlInfo, 0);
342 if (RT_SUCCESS(rc))
343 {
344 /* The VMX stuff. */
345 int rc1 = RTR0DbgKrnlInfoQuerySymbol(hKrnlInfo, NULL, "vmx_resume", (void **)&g_pfnVmxResume);
346 int rc2 = RTR0DbgKrnlInfoQuerySymbol(hKrnlInfo, NULL, "vmx_suspend", (void **)&g_pfnVmxSuspend);
347 int rc3 = RTR0DbgKrnlInfoQuerySymbol(hKrnlInfo, NULL, "vmx_use_count", (void **)&g_pVmxUseCount);
348 if (RT_SUCCESS(rc1) && RT_SUCCESS(rc2) && RT_SUCCESS(rc3))
349 {
350 LogRel(("VBoxDrv: vmx_resume=%p vmx_suspend=%p vmx_use_count=%p (%d) cr4=%#x\n",
351 g_pfnVmxResume, g_pfnVmxSuspend, g_pVmxUseCount, *g_pVmxUseCount, ASMGetCR4() ));
352 }
353 else
354 {
355 LogRel(("VBoxDrv: failed to resolve vmx stuff: vmx_resume=%Rrc vmx_suspend=%Rrc vmx_use_count=%Rrc", rc1, rc2, rc3));
356 g_pfnVmxResume = NULL;
357 g_pfnVmxSuspend = NULL;
358 g_pVmxUseCount = NULL;
359 }
360
361#ifdef SUPDRV_WITH_MSR_PROBER
362 /* MSR prober stuff. */
363 int rc = RTR0DbgKrnlInfoQuerySymbol(hKrnlInfo, NULL, "rdmsr_carefully", (void **)&g_pfnRdMsrCarefully);
364 if (RT_FAILURE(rc))
365 g_pfnRdMsrCarefully = NULL;
366 rc = RTR0DbgKrnlInfoQuerySymbol(hKrnlInfo, NULL, "rdmsr64_carefully", (void **)&g_pfnRdMsr64Carefully);
367 if (RT_FAILURE(rc))
368 g_pfnRdMsr64Carefully = NULL;
369# ifdef RT_ARCH_AMD64 /* Missing 64 in name, so if implemented on 32-bit it could have different signature. */
370 rc = RTR0DbgKrnlInfoQuerySymbol(hKrnlInfo, NULL, "wrmsr_carefully", (void **)&g_pfnWrMsr64Carefully);
371 if (RT_FAILURE(rc))
372# endif
373 g_pfnWrMsr64Carefully = NULL;
374
375 LogRel(("VBoxDrv: g_pfnRdMsrCarefully=%p g_pfnRdMsr64Carefully=%p g_pfnWrMsr64Carefully=%p\n",
376 g_pfnRdMsrCarefully, g_pfnRdMsr64Carefully, g_pfnWrMsr64Carefully));
377
378#endif /* SUPDRV_WITH_MSR_PROBER */
379
380 RTR0DbgKrnlInfoRelease(hKrnlInfo);
381 }
382 else
383 LogRel(("VBoxDrv: Failed to open kernel symbols, rc=%Rrc\n", rc));
384}
385
386
387/**
388 * Stop the kernel module.
389 */
390static kern_return_t VBoxDrvDarwinStop(struct kmod_info *pKModInfo, void *pvData)
391{
392 int rc;
393 LogFlow(("VBoxDrvDarwinStop\n"));
394
395 /** @todo I've got a nagging feeling that we'll have to keep track of users and refuse
396 * unloading if we're busy. Investigate and implement this! */
397
398 /*
399 * Undo the work done during start (in reverse order).
400 */
401 if (g_pSleepNotifier)
402 {
403 g_pSleepNotifier->remove();
404 g_pSleepNotifier = NULL;
405 }
406
407 devfs_remove(g_hDevFsDeviceUsr);
408 g_hDevFsDeviceUsr = NULL;
409
410 devfs_remove(g_hDevFsDeviceSys);
411 g_hDevFsDeviceSys = NULL;
412
413 rc = cdevsw_remove(g_iMajorDeviceNo, &g_DevCW);
414 Assert(rc == g_iMajorDeviceNo);
415 g_iMajorDeviceNo = -1;
416
417 supdrvDeleteDevExt(&g_DevExt);
418
419 rc = RTSpinlockDestroy(g_Spinlock);
420 AssertRC(rc);
421 g_Spinlock = NIL_RTSPINLOCK;
422
423 RTR0TermForced();
424
425 memset(&g_DevExt, 0, sizeof(g_DevExt));
426#ifdef DEBUG
427 printf("VBoxDrvDarwinStop - done\n");
428#endif
429 return KMOD_RETURN_SUCCESS;
430}
431
432
433/**
434 * Device open. Called on open /dev/vboxdrv
435 *
436 * @param Dev The device number.
437 * @param fFlags ???.
438 * @param fDevType ???.
439 * @param pProcess The process issuing this request.
440 */
441static int VBoxDrvDarwinOpen(dev_t Dev, int fFlags, int fDevType, struct proc *pProcess)
442{
443#ifdef DEBUG_DARWIN_GIP
444 char szName[128];
445 szName[0] = '\0';
446 proc_name(proc_pid(pProcess), szName, sizeof(szName));
447 Log(("VBoxDrvDarwinOpen: pid=%d '%s'\n", proc_pid(pProcess), szName));
448#endif
449
450 /*
451 * Only two minor devices numbers are allowed.
452 */
453 if (minor(Dev) != 0 && minor(Dev) != 1)
454 return EACCES;
455
456 /*
457 * Find the session created by org_virtualbox_SupDrvClient, fail
458 * if no such session, and mark it as opened. We set the uid & gid
459 * here too, since that is more straight forward at this point.
460 */
461 const bool fUnrestricted = minor(Dev) == 0;
462 int rc = VINF_SUCCESS;
463 PSUPDRVSESSION pSession = NULL;
464 kauth_cred_t pCred = kauth_cred_proc_ref(pProcess);
465 if (pCred)
466 {
467#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
468 RTUID Uid = kauth_cred_getruid(pCred);
469 RTGID Gid = kauth_cred_getrgid(pCred);
470#else
471 RTUID Uid = pCred->cr_ruid;
472 RTGID Gid = pCred->cr_rgid;
473#endif
474 RTPROCESS Process = RTProcSelf();
475 unsigned iHash = SESSION_HASH(Process);
476 RTSpinlockAcquire(g_Spinlock);
477
478 pSession = g_apSessionHashTab[iHash];
479 while (pSession && pSession->Process != Process)
480 pSession = pSession->pNextHash;
481 if (pSession)
482 {
483 if (!pSession->fOpened)
484 {
485 pSession->fOpened = true;
486 pSession->fUnrestricted = fUnrestricted;
487 pSession->Uid = Uid;
488 pSession->Gid = Gid;
489 }
490 else
491 rc = VERR_ALREADY_LOADED;
492 }
493 else
494 rc = VERR_GENERAL_FAILURE;
495
496 RTSpinlockReleaseNoInts(g_Spinlock);
497#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1050
498 kauth_cred_unref(&pCred);
499#else /* 10.4 */
500 /* The 10.4u SDK headers and 10.4.11 kernel source have inconsistent definitions
501 of kauth_cred_unref(), so use the other (now deprecated) API for releasing it. */
502 kauth_cred_rele(pCred);
503#endif /* 10.4 */
504 }
505 else
506 rc = VERR_INVALID_PARAMETER;
507
508#ifdef DEBUG_DARWIN_GIP
509 OSDBGPRINT(("VBoxDrvDarwinOpen: pid=%d '%s' pSession=%p rc=%d\n", proc_pid(pProcess), szName, pSession, rc));
510#else
511 Log(("VBoxDrvDarwinOpen: g_DevExt=%p pSession=%p rc=%d pid=%d\n", &g_DevExt, pSession, rc, proc_pid(pProcess)));
512#endif
513 return VBoxDrvDarwinErr2DarwinErr(rc);
514}
515
516
517/**
518 * Close device.
519 */
520static int VBoxDrvDarwinClose(dev_t Dev, int fFlags, int fDevType, struct proc *pProcess)
521{
522 Log(("VBoxDrvDarwinClose: pid=%d\n", (int)RTProcSelf()));
523 Assert(proc_pid(pProcess) == (int)RTProcSelf());
524
525 /*
526 * Hand the session closing to org_virtualbox_SupDrvClient.
527 */
528 org_virtualbox_SupDrvClient::sessionClose(RTProcSelf());
529 return 0;
530}
531
532
533/**
534 * Device I/O Control entry point.
535 *
536 * @returns Darwin for slow IOCtls and VBox status code for the fast ones.
537 * @param Dev The device number (major+minor).
538 * @param iCmd The IOCtl command.
539 * @param pData Pointer to the data (if any it's a SUPDRVIOCTLDATA (kernel copy)).
540 * @param fFlags Flag saying we're a character device (like we didn't know already).
541 * @param pProcess The process issuing this request.
542 */
543static int VBoxDrvDarwinIOCtl(dev_t Dev, u_long iCmd, caddr_t pData, int fFlags, struct proc *pProcess)
544{
545 const bool fUnrestricted = minor(Dev) == 0;
546 const RTPROCESS Process = proc_pid(pProcess);
547 const unsigned iHash = SESSION_HASH(Process);
548 PSUPDRVSESSION pSession;
549
550 /*
551 * Find the session.
552 */
553 RTSpinlockAcquire(g_Spinlock);
554 pSession = g_apSessionHashTab[iHash];
555 while (pSession && pSession->Process != Process && pSession->fUnrestricted == fUnrestricted && pSession->fOpened)
556 pSession = pSession->pNextHash;
557
558 if (RT_LIKELY(pSession))
559 supdrvSessionRetain(pSession);
560 RTSpinlockReleaseNoInts(g_Spinlock);
561 if (!pSession)
562 {
563 OSDBGPRINT(("VBoxDrvDarwinIOCtl: WHAT?!? pSession == NULL! This must be a mistake... pid=%d iCmd=%#lx\n",
564 (int)Process, iCmd));
565 return EINVAL;
566 }
567
568 /*
569 * Deal with the two high-speed IOCtl that takes it's arguments from
570 * the session and iCmd, and only returns a VBox status code.
571 */
572 int rc;
573 if ( ( iCmd == SUP_IOCTL_FAST_DO_RAW_RUN
574 || iCmd == SUP_IOCTL_FAST_DO_HM_RUN
575 || iCmd == SUP_IOCTL_FAST_DO_NOP)
576 && fUnrestricted)
577 rc = supdrvIOCtlFast(iCmd, *(uint32_t *)pData, &g_DevExt, pSession);
578 else
579 rc = VBoxDrvDarwinIOCtlSlow(pSession, iCmd, pData, pProcess);
580
581 supdrvSessionRelease(pSession);
582 return rc;
583}
584
585
586/**
587 * Worker for VBoxDrvDarwinIOCtl that takes the slow IOCtl functions.
588 *
589 * @returns Darwin errno.
590 *
591 * @param pSession The session.
592 * @param iCmd The IOCtl command.
593 * @param pData Pointer to the kernel copy of the SUPDRVIOCTLDATA buffer.
594 * @param pProcess The calling process.
595 */
596static int VBoxDrvDarwinIOCtlSlow(PSUPDRVSESSION pSession, u_long iCmd, caddr_t pData, struct proc *pProcess)
597{
598 LogFlow(("VBoxDrvDarwinIOCtlSlow: pSession=%p iCmd=%p pData=%p pProcess=%p\n", pSession, iCmd, pData, pProcess));
599
600
601 /*
602 * Buffered or unbuffered?
603 */
604 PSUPREQHDR pHdr;
605 user_addr_t pUser = 0;
606 void *pvPageBuf = NULL;
607 uint32_t cbReq = IOCPARM_LEN(iCmd);
608 if ((IOC_DIRMASK & iCmd) == IOC_INOUT)
609 {
610 pHdr = (PSUPREQHDR)pData;
611 if (RT_UNLIKELY(cbReq < sizeof(*pHdr)))
612 {
613 OSDBGPRINT(("VBoxDrvDarwinIOCtlSlow: cbReq=%#x < %#x; iCmd=%#lx\n", cbReq, (int)sizeof(*pHdr), iCmd));
614 return EINVAL;
615 }
616 if (RT_UNLIKELY((pHdr->fFlags & SUPREQHDR_FLAGS_MAGIC_MASK) != SUPREQHDR_FLAGS_MAGIC))
617 {
618 OSDBGPRINT(("VBoxDrvDarwinIOCtlSlow: bad magic fFlags=%#x; iCmd=%#lx\n", pHdr->fFlags, iCmd));
619 return EINVAL;
620 }
621 if (RT_UNLIKELY( RT_MAX(pHdr->cbIn, pHdr->cbOut) != cbReq
622 || pHdr->cbIn < sizeof(*pHdr)
623 || pHdr->cbOut < sizeof(*pHdr)))
624 {
625 OSDBGPRINT(("VBoxDrvDarwinIOCtlSlow: max(%#x,%#x) != %#x; iCmd=%#lx\n", pHdr->cbIn, pHdr->cbOut, cbReq, iCmd));
626 return EINVAL;
627 }
628 }
629 else if ((IOC_DIRMASK & iCmd) == IOC_VOID && !cbReq)
630 {
631 /*
632 * Get the header and figure out how much we're gonna have to read.
633 */
634 SUPREQHDR Hdr;
635 pUser = (user_addr_t)*(void **)pData;
636 int rc = copyin(pUser, &Hdr, sizeof(Hdr));
637 if (RT_UNLIKELY(rc))
638 {
639 OSDBGPRINT(("VBoxDrvDarwinIOCtlSlow: copyin(%llx,Hdr,) -> %#x; iCmd=%#lx\n", (unsigned long long)pUser, rc, iCmd));
640 return rc;
641 }
642 if (RT_UNLIKELY((Hdr.fFlags & SUPREQHDR_FLAGS_MAGIC_MASK) != SUPREQHDR_FLAGS_MAGIC))
643 {
644 OSDBGPRINT(("VBoxDrvDarwinIOCtlSlow: bad magic fFlags=%#x; iCmd=%#lx\n", Hdr.fFlags, iCmd));
645 return EINVAL;
646 }
647 cbReq = RT_MAX(Hdr.cbIn, Hdr.cbOut);
648 if (RT_UNLIKELY( Hdr.cbIn < sizeof(Hdr)
649 || Hdr.cbOut < sizeof(Hdr)
650 || cbReq > _1M*16))
651 {
652 OSDBGPRINT(("VBoxDrvDarwinIOCtlSlow: max(%#x,%#x); iCmd=%#lx\n", Hdr.cbIn, Hdr.cbOut, iCmd));
653 return EINVAL;
654 }
655
656 /*
657 * Allocate buffer and copy in the data.
658 */
659 pHdr = (PSUPREQHDR)RTMemTmpAlloc(cbReq);
660 if (!pHdr)
661 pvPageBuf = pHdr = (PSUPREQHDR)IOMallocAligned(RT_ALIGN_Z(cbReq, PAGE_SIZE), 8);
662 if (RT_UNLIKELY(!pHdr))
663 {
664 OSDBGPRINT(("VBoxDrvDarwinIOCtlSlow: failed to allocate buffer of %d bytes; iCmd=%#lx\n", cbReq, iCmd));
665 return ENOMEM;
666 }
667 rc = copyin(pUser, pHdr, Hdr.cbIn);
668 if (RT_UNLIKELY(rc))
669 {
670 OSDBGPRINT(("VBoxDrvDarwinIOCtlSlow: copyin(%llx,%p,%#x) -> %#x; iCmd=%#lx\n",
671 (unsigned long long)pUser, pHdr, Hdr.cbIn, rc, iCmd));
672 if (pvPageBuf)
673 IOFreeAligned(pvPageBuf, RT_ALIGN_Z(cbReq, PAGE_SIZE));
674 else
675 RTMemTmpFree(pHdr);
676 return rc;
677 }
678 }
679 else
680 {
681 Log(("VBoxDrvDarwinIOCtlSlow: huh? cbReq=%#x iCmd=%#lx\n", cbReq, iCmd));
682 return EINVAL;
683 }
684
685 /*
686 * Process the IOCtl.
687 */
688 int rc = supdrvIOCtl(iCmd, &g_DevExt, pSession, pHdr);
689 if (RT_LIKELY(!rc))
690 {
691 /*
692 * If not buffered, copy back the buffer before returning.
693 */
694 if (pUser)
695 {
696 uint32_t cbOut = pHdr->cbOut;
697 if (cbOut > cbReq)
698 {
699 OSDBGPRINT(("VBoxDrvDarwinIOCtlSlow: too much output! %#x > %#x; uCmd=%#lx!\n", cbOut, cbReq, iCmd));
700 cbOut = cbReq;
701 }
702 rc = copyout(pHdr, pUser, cbOut);
703 if (RT_UNLIKELY(rc))
704 OSDBGPRINT(("VBoxDrvDarwinIOCtlSlow: copyout(%p,%llx,%#x) -> %d; uCmd=%#lx!\n",
705 pHdr, (unsigned long long)pUser, cbOut, rc, iCmd));
706
707 /* cleanup */
708 if (pvPageBuf)
709 IOFreeAligned(pvPageBuf, RT_ALIGN_Z(cbReq, PAGE_SIZE));
710 else
711 RTMemTmpFree(pHdr);
712 }
713 }
714 else
715 {
716 /*
717 * The request failed, just clean up.
718 */
719 if (pUser)
720 {
721 if (pvPageBuf)
722 IOFreeAligned(pvPageBuf, RT_ALIGN_Z(cbReq, PAGE_SIZE));
723 else
724 RTMemTmpFree(pHdr);
725 }
726
727 Log(("VBoxDrvDarwinIOCtlSlow: pid=%d iCmd=%lx pData=%p failed, rc=%d\n", proc_pid(pProcess), iCmd, (void *)pData, rc));
728 rc = EINVAL;
729 }
730
731 Log2(("VBoxDrvDarwinIOCtlSlow: returns %d\n", rc));
732 return rc;
733}
734
735
736/**
737 * The SUPDRV IDC entry point.
738 *
739 * @returns VBox status code, see supdrvIDC.
740 * @param iReq The request code.
741 * @param pReq The request.
742 */
743DECLEXPORT(int) VBOXCALL SUPDrvDarwinIDC(uint32_t uReq, PSUPDRVIDCREQHDR pReq)
744{
745 PSUPDRVSESSION pSession;
746
747 /*
748 * Some quick validations.
749 */
750 if (RT_UNLIKELY(!VALID_PTR(pReq)))
751 return VERR_INVALID_POINTER;
752
753 pSession = pReq->pSession;
754 if (pSession)
755 {
756 if (RT_UNLIKELY(!VALID_PTR(pSession)))
757 return VERR_INVALID_PARAMETER;
758 if (RT_UNLIKELY(pSession->pDevExt != &g_DevExt))
759 return VERR_INVALID_PARAMETER;
760 }
761 else if (RT_UNLIKELY(uReq != SUPDRV_IDC_REQ_CONNECT))
762 return VERR_INVALID_PARAMETER;
763
764 /*
765 * Do the job.
766 */
767 return supdrvIDC(uReq, &g_DevExt, pSession, pReq);
768}
769
770
771/**
772 * Initializes any OS specific object creator fields.
773 */
774void VBOXCALL supdrvOSObjInitCreator(PSUPDRVOBJ pObj, PSUPDRVSESSION pSession)
775{
776 NOREF(pObj);
777 NOREF(pSession);
778}
779
780
781/**
782 * Checks if the session can access the object.
783 *
784 * @returns true if a decision has been made.
785 * @returns false if the default access policy should be applied.
786 *
787 * @param pObj The object in question.
788 * @param pSession The session wanting to access the object.
789 * @param pszObjName The object name, can be NULL.
790 * @param prc Where to store the result when returning true.
791 */
792bool VBOXCALL supdrvOSObjCanAccess(PSUPDRVOBJ pObj, PSUPDRVSESSION pSession, const char *pszObjName, int *prc)
793{
794 NOREF(pObj);
795 NOREF(pSession);
796 NOREF(pszObjName);
797 NOREF(prc);
798 return false;
799}
800
801/**
802 * Callback for blah blah blah.
803 */
804IOReturn VBoxDrvDarwinSleepHandler(void * /* pvTarget */, void *pvRefCon, UInt32 uMessageType, IOService * /* pProvider */, void * /* pvMessageArgument */, vm_size_t /* argSize */)
805{
806 LogFlow(("VBoxDrv: Got sleep/wake notice. Message type was %X\n", (uint)uMessageType));
807
808 if (uMessageType == kIOMessageSystemWillSleep)
809 RTPowerSignalEvent(RTPOWEREVENT_SUSPEND);
810 else if (uMessageType == kIOMessageSystemHasPoweredOn)
811 RTPowerSignalEvent(RTPOWEREVENT_RESUME);
812
813 acknowledgeSleepWakeNotification(pvRefCon);
814
815 return 0;
816}
817
818
819/**
820 * @copydoc SUPR0EnableVTx
821 */
822int VBOXCALL supdrvOSEnableVTx(bool fEnable)
823{
824#ifdef VBOX_WITH_HOST_VMX
825 int rc;
826 if ( version_major >= 10 /* 10 = 10.6.x = Snow Leopard */
827 && g_pfnVmxSuspend
828 && g_pfnVmxResume
829 && g_pVmxUseCount)
830 {
831 if (fEnable)
832 {
833 rc = host_vmxon(false /* exclusive */);
834 if (rc == VMX_OK)
835 rc = VINF_SUCCESS;
836 else if (rc == VMX_UNSUPPORTED)
837 rc = VERR_VMX_NO_VMX;
838 else if (rc == VMX_INUSE)
839 rc = VERR_VMX_IN_VMX_ROOT_MODE;
840 else /* shouldn't happen, but just in case. */
841 {
842 LogRel(("host_vmxon returned %d\n", rc));
843 rc = VERR_UNRESOLVED_ERROR;
844 }
845 LogRel(("VBoxDrv: host_vmxon -> vmx_use_count=%d rc=%Rrc\n", *g_pVmxUseCount, rc));
846 }
847 else
848 {
849 host_vmxoff();
850 rc = VINF_SUCCESS;
851 LogRel(("VBoxDrv: host_vmxoff -> vmx_use_count=%d\n", *g_pVmxUseCount));
852 }
853 }
854 else
855 {
856 /* In 10.5.x the host_vmxon is severely broken! Don't use it, it will
857 frequnetly panic the host. */
858 rc = VERR_NOT_SUPPORTED;
859 }
860 return rc;
861#else
862 return VERR_NOT_SUPPORTED;
863#endif
864}
865
866
867/**
868 * @copydoc SUPR0SuspendVTxOnCpu
869 */
870bool VBOXCALL supdrvOSSuspendVTxOnCpu(void)
871{
872#ifdef VBOX_WITH_HOST_VMX
873 /*
874 * Consult the VMX usage counter, don't try suspend if not enabled.
875 *
876 * Note! The host_vmxon/off code is still race prone since, but this is
877 * currently the best we can do without always enable VMX when
878 * loading the driver.
879 */
880 if ( g_pVmxUseCount
881 && *g_pVmxUseCount > 0)
882 {
883 g_pfnVmxSuspend();
884 return true;
885 }
886 return false;
887#else
888 return false;
889#endif
890}
891
892
893/**
894 * @copydoc SUPR0ResumeVTxOnCpu
895 */
896void VBOXCALL supdrvOSResumeVTxOnCpu(bool fSuspended)
897{
898#ifdef VBOX_WITH_HOST_VMX
899 /*
900 * Don't consult the counter here, the state knows better.
901 * We're executing with interrupts disabled and anyone racing us with
902 * disabling VT-x will be waiting in the rendezvous code.
903 */
904 if ( fSuspended
905 && g_pfnVmxResume)
906 g_pfnVmxResume();
907 else
908 Assert(!fSuspended);
909#else
910 Assert(!fSuspended);
911#endif
912}
913
914
915bool VBOXCALL supdrvOSGetForcedAsyncTscMode(PSUPDRVDEVEXT pDevExt)
916{
917 NOREF(pDevExt);
918 return false;
919}
920
921
922void VBOXCALL supdrvOSLdrNotifyOpened(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage)
923{
924#if 1
925 NOREF(pDevExt); NOREF(pImage);
926#else
927 /*
928 * Try store the image load address in NVRAM so we can retrived it on panic.
929 * Note! This only works if you're root! - Acutally, it doesn't work at all at the moment. FIXME!
930 */
931 IORegistryEntry *pEntry = IORegistryEntry::fromPath("/options", gIODTPlane);
932 if (pEntry)
933 {
934 char szVar[80];
935 RTStrPrintf(szVar, sizeof(szVar), "vboximage"/*-%s*/, pImage->szName);
936 char szValue[48];
937 RTStrPrintf(szValue, sizeof(szValue), "%#llx,%#llx", (uint64_t)(uintptr_t)pImage->pvImage,
938 (uint64_t)(uintptr_t)pImage->pvImage + pImage->cbImageBits - 1);
939 bool fRc = pEntry->setProperty(szVar, szValue); NOREF(fRc);
940 pEntry->release();
941 SUPR0Printf("fRc=%d '%s'='%s'\n", fRc, szVar, szValue);
942 }
943 /*else
944 SUPR0Printf("failed to find /options in gIODTPlane\n");*/
945#endif
946}
947
948
949int VBOXCALL supdrvOSLdrOpen(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage, const char *pszFilename)
950{
951 NOREF(pDevExt); NOREF(pImage); NOREF(pszFilename);
952 return VERR_NOT_SUPPORTED;
953}
954
955
956int VBOXCALL supdrvOSLdrValidatePointer(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage, void *pv, const uint8_t *pbImageBits)
957{
958 NOREF(pDevExt); NOREF(pImage); NOREF(pv); NOREF(pbImageBits);
959 return VERR_NOT_SUPPORTED;
960}
961
962
963int VBOXCALL supdrvOSLdrLoad(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage, const uint8_t *pbImageBits, PSUPLDRLOAD pReq)
964{
965 NOREF(pDevExt); NOREF(pImage); NOREF(pbImageBits); NOREF(pReq);
966 return VERR_NOT_SUPPORTED;
967}
968
969
970void VBOXCALL supdrvOSLdrUnload(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage)
971{
972 NOREF(pDevExt); NOREF(pImage);
973}
974
975
976#ifdef SUPDRV_WITH_MSR_PROBER
977
978typedef struct SUPDRVDARWINMSRARGS
979{
980 RTUINT64U uValue;
981 uint32_t uMsr;
982 int rc;
983} SUPDRVDARWINMSRARGS, *PSUPDRVDARWINMSRARGS;
984
985/**
986 * On CPU worker for supdrvOSMsrProberRead.
987 *
988 * @param idCpu Ignored.
989 * @param pvUser1 Pointer to a SUPDRVDARWINMSRARGS.
990 * @param pvUser2 Ignored.
991 */
992static DECLCALLBACK(void) supdrvDarwinMsrProberReadOnCpu(RTCPUID idCpu, void *pvUser1, void *pvUser2)
993{
994 PSUPDRVDARWINMSRARGS pArgs = (PSUPDRVDARWINMSRARGS)pvUser1;
995 if (g_pfnRdMsr64Carefully)
996 pArgs->rc = g_pfnRdMsr64Carefully(pArgs->uMsr, &pArgs->uValue.u);
997 else if (g_pfnRdMsrCarefully)
998 pArgs->rc = g_pfnRdMsrCarefully(pArgs->uMsr, &pArgs->uValue.s.Lo, &pArgs->uValue.s.Hi);
999 else
1000 pArgs->rc = 2;
1001 NOREF(idCpu); NOREF(pvUser2);
1002}
1003
1004
1005int VBOXCALL supdrvOSMsrProberRead(uint32_t uMsr, RTCPUID idCpu, uint64_t *puValue)
1006{
1007 if (!g_pfnRdMsr64Carefully && !g_pfnRdMsrCarefully)
1008 return VERR_NOT_SUPPORTED;
1009
1010 SUPDRVDARWINMSRARGS Args;
1011 Args.uMsr = uMsr;
1012 Args.uValue.u = 0;
1013 Args.rc = -1;
1014
1015 if (idCpu == NIL_RTCPUID)
1016 supdrvDarwinMsrProberReadOnCpu(idCpu, &Args, NULL);
1017 else
1018 {
1019 int rc = RTMpOnSpecific(idCpu, supdrvDarwinMsrProberReadOnCpu, &Args, NULL);
1020 if (RT_FAILURE(rc))
1021 return rc;
1022 }
1023
1024 if (Args.rc)
1025 return VERR_ACCESS_DENIED;
1026 *puValue = Args.uValue.u;
1027 return VINF_SUCCESS;
1028}
1029
1030
1031/**
1032 * On CPU worker for supdrvOSMsrProberWrite.
1033 *
1034 * @param idCpu Ignored.
1035 * @param pvUser1 Pointer to a SUPDRVDARWINMSRARGS.
1036 * @param pvUser2 Ignored.
1037 */
1038static DECLCALLBACK(void) supdrvDarwinMsrProberWriteOnCpu(RTCPUID idCpu, void *pvUser1, void *pvUser2)
1039{
1040 PSUPDRVDARWINMSRARGS pArgs = (PSUPDRVDARWINMSRARGS)pvUser1;
1041 if (g_pfnWrMsr64Carefully)
1042 pArgs->rc = g_pfnWrMsr64Carefully(pArgs->uMsr, pArgs->uValue.u);
1043 else
1044 pArgs->rc = 2;
1045 NOREF(idCpu); NOREF(pvUser2);
1046}
1047
1048
1049int VBOXCALL supdrvOSMsrProberWrite(uint32_t uMsr, RTCPUID idCpu, uint64_t uValue)
1050{
1051 if (!g_pfnWrMsr64Carefully)
1052 return VERR_NOT_SUPPORTED;
1053
1054 SUPDRVDARWINMSRARGS Args;
1055 Args.uMsr = uMsr;
1056 Args.uValue.u = uValue;
1057 Args.rc = -1;
1058
1059 if (idCpu == NIL_RTCPUID)
1060 supdrvDarwinMsrProberWriteOnCpu(idCpu, &Args, NULL);
1061 else
1062 {
1063 int rc = RTMpOnSpecific(idCpu, supdrvDarwinMsrProberWriteOnCpu, &Args, NULL);
1064 if (RT_FAILURE(rc))
1065 return rc;
1066 }
1067
1068 if (Args.rc)
1069 return VERR_ACCESS_DENIED;
1070 return VINF_SUCCESS;
1071}
1072
1073
1074/**
1075 * Worker for supdrvOSMsrProberModify.
1076 */
1077static DECLCALLBACK(void) supdrvDarwinMsrProberModifyOnCpu(RTCPUID idCpu, void *pvUser1, void *pvUser2)
1078{
1079 PSUPMSRPROBER pReq = (PSUPMSRPROBER)pvUser1;
1080 register uint32_t uMsr = pReq->u.In.uMsr;
1081 bool const fFaster = pReq->u.In.enmOp == SUPMSRPROBEROP_MODIFY_FASTER;
1082 uint64_t uBefore;
1083 uint64_t uWritten;
1084 uint64_t uAfter;
1085 int rcBefore, rcWrite, rcAfter, rcRestore;
1086 RTCCUINTREG fOldFlags;
1087
1088 /* Initialize result variables. */
1089 uBefore = uWritten = uAfter = 0;
1090 rcWrite = rcAfter = rcRestore = -1;
1091
1092 /*
1093 * Do the job.
1094 */
1095 fOldFlags = ASMIntDisableFlags();
1096 ASMCompilerBarrier(); /* paranoia */
1097 if (!fFaster)
1098 ASMWriteBackAndInvalidateCaches();
1099
1100 rcBefore = g_pfnRdMsr64Carefully(uMsr, &uBefore);
1101 if (rcBefore >= 0)
1102 {
1103 register uint64_t uRestore = uBefore;
1104 uWritten = uRestore;
1105 uWritten &= pReq->u.In.uArgs.Modify.fAndMask;
1106 uWritten |= pReq->u.In.uArgs.Modify.fOrMask;
1107
1108 rcWrite = g_pfnWrMsr64Carefully(uMsr, uWritten);
1109 rcAfter = g_pfnRdMsr64Carefully(uMsr, &uAfter);
1110 rcRestore = g_pfnWrMsr64Carefully(uMsr, uRestore);
1111
1112 if (!fFaster)
1113 {
1114 ASMWriteBackAndInvalidateCaches();
1115 ASMReloadCR3();
1116 ASMNopPause();
1117 }
1118 }
1119
1120 ASMCompilerBarrier(); /* paranoia */
1121 ASMSetFlags(fOldFlags);
1122
1123 /*
1124 * Write out the results.
1125 */
1126 pReq->u.Out.uResults.Modify.uBefore = uBefore;
1127 pReq->u.Out.uResults.Modify.uWritten = uWritten;
1128 pReq->u.Out.uResults.Modify.uAfter = uAfter;
1129 pReq->u.Out.uResults.Modify.fBeforeGp = rcBefore != 0;
1130 pReq->u.Out.uResults.Modify.fModifyGp = rcWrite != 0;
1131 pReq->u.Out.uResults.Modify.fAfterGp = rcAfter != 0;
1132 pReq->u.Out.uResults.Modify.fRestoreGp = rcRestore != 0;
1133 RT_ZERO(pReq->u.Out.uResults.Modify.afReserved);
1134}
1135
1136
1137int VBOXCALL supdrvOSMsrProberModify(RTCPUID idCpu, PSUPMSRPROBER pReq)
1138{
1139 if (!g_pfnWrMsr64Carefully || !g_pfnRdMsr64Carefully)
1140 return VERR_NOT_SUPPORTED;
1141 if (idCpu == NIL_RTCPUID)
1142 {
1143 supdrvDarwinMsrProberModifyOnCpu(idCpu, pReq, NULL);
1144 return VINF_SUCCESS;
1145 }
1146 return RTMpOnSpecific(idCpu, supdrvDarwinMsrProberModifyOnCpu, pReq, NULL);
1147}
1148
1149#endif /* SUPDRV_WITH_MSR_PROBER */
1150
1151/**
1152 * Resume Bluetooth keyboard.
1153 * If there is no Bluetooth keyboard device connected to the system we just ignore this.
1154 */
1155static void supdrvDarwinResumeBluetoothKbd(void)
1156{
1157 OSDictionary *pDictionary = IOService::serviceMatching("AppleBluetoothHIDKeyboard");
1158 if (pDictionary)
1159 {
1160 OSIterator *pIter;
1161 IOBluetoothHIDDriver *pDriver;
1162
1163 pIter = IOService::getMatchingServices(pDictionary);
1164 if (pIter)
1165 {
1166 while ((pDriver = (IOBluetoothHIDDriver *)pIter->getNextObject()))
1167 if (pDriver->isKeyboard())
1168 (void)pDriver->hidControl(IOBTHID_CONTROL_EXIT_SUSPEND);
1169
1170 pIter->release();
1171 }
1172 pDictionary->release();
1173 }
1174}
1175
1176/**
1177 * Resume built-in keyboard on MacBook Air and Pro hosts.
1178 * If there is no built-in keyboard device attached to the system we just ignore this.
1179 */
1180static void supdrvDarwinResumeBuiltinKbd(void)
1181{
1182 /*
1183 * AppleUSBTCKeyboard KEXT is responsible for built-in keyboard management.
1184 * We resume keyboard by accessing to its IOService. */
1185 OSDictionary *pDictionary = IOService::serviceMatching("AppleUSBTCKeyboard");
1186 if (pDictionary)
1187 {
1188 OSIterator *pIter;
1189 IOUSBHIDDriver *pDriver;
1190
1191 pIter = IOService::getMatchingServices(pDictionary);
1192 if (pIter)
1193 {
1194 while ((pDriver = (IOUSBHIDDriver *)pIter->getNextObject()))
1195 if (pDriver->IsPortSuspended())
1196 pDriver->SuspendPort(false, 0);
1197
1198 pIter->release();
1199 }
1200 pDictionary->release();
1201 }
1202}
1203
1204
1205/**
1206 * Resume suspended keyboard devices (if any).
1207 */
1208int VBOXCALL supdrvDarwinResumeSuspendedKbds(void)
1209{
1210 supdrvDarwinResumeBuiltinKbd();
1211 supdrvDarwinResumeBluetoothKbd();
1212
1213 return 0;
1214}
1215
1216
1217/**
1218 * Converts an IPRT error code to a darwin error code.
1219 *
1220 * @returns corresponding darwin error code.
1221 * @param rc IPRT status code.
1222 */
1223static int VBoxDrvDarwinErr2DarwinErr(int rc)
1224{
1225 switch (rc)
1226 {
1227 case VINF_SUCCESS: return 0;
1228 case VERR_GENERAL_FAILURE: return EACCES;
1229 case VERR_INVALID_PARAMETER: return EINVAL;
1230 case VERR_INVALID_MAGIC: return EILSEQ;
1231 case VERR_INVALID_HANDLE: return ENXIO;
1232 case VERR_INVALID_POINTER: return EFAULT;
1233 case VERR_LOCK_FAILED: return ENOLCK;
1234 case VERR_ALREADY_LOADED: return EEXIST;
1235 case VERR_PERMISSION_DENIED: return EPERM;
1236 case VERR_VERSION_MISMATCH: return ENOSYS;
1237 }
1238
1239 return EPERM;
1240}
1241
1242
1243RTDECL(int) SUPR0Printf(const char *pszFormat, ...)
1244{
1245 va_list va;
1246 char szMsg[512];
1247
1248 va_start(va, pszFormat);
1249 RTStrPrintfV(szMsg, sizeof(szMsg) - 1, pszFormat, va);
1250 va_end(va);
1251 szMsg[sizeof(szMsg) - 1] = '\0';
1252
1253 printf("%s", szMsg);
1254 return 0;
1255}
1256
1257
1258/*
1259 *
1260 * org_virtualbox_SupDrv
1261 *
1262 */
1263
1264
1265/**
1266 * Initialize the object.
1267 */
1268bool org_virtualbox_SupDrv::init(OSDictionary *pDictionary)
1269{
1270 LogFlow(("org_virtualbox_SupDrv::init([%p], %p)\n", this, pDictionary));
1271 if (IOService::init(pDictionary))
1272 {
1273 /* init members. */
1274 return true;
1275 }
1276 return false;
1277}
1278
1279
1280/**
1281 * Free the object.
1282 */
1283void org_virtualbox_SupDrv::free(void)
1284{
1285 LogFlow(("IOService::free([%p])\n", this));
1286 IOService::free();
1287}
1288
1289
1290/**
1291 * Check if it's ok to start this service.
1292 * It's always ok by us, so it's up to IOService to decide really.
1293 */
1294IOService *org_virtualbox_SupDrv::probe(IOService *pProvider, SInt32 *pi32Score)
1295{
1296 LogFlow(("org_virtualbox_SupDrv::probe([%p])\n", this));
1297 return IOService::probe(pProvider, pi32Score);
1298}
1299
1300
1301/**
1302 * Start this service.
1303 */
1304bool org_virtualbox_SupDrv::start(IOService *pProvider)
1305{
1306 LogFlow(("org_virtualbox_SupDrv::start([%p])\n", this));
1307
1308 if (IOService::start(pProvider))
1309 {
1310 /* register the service. */
1311 registerService();
1312 return true;
1313 }
1314 return false;
1315}
1316
1317
1318/**
1319 * Stop this service.
1320 */
1321void org_virtualbox_SupDrv::stop(IOService *pProvider)
1322{
1323 LogFlow(("org_virtualbox_SupDrv::stop([%p], %p)\n", this, pProvider));
1324 IOService::stop(pProvider);
1325}
1326
1327
1328/**
1329 * Termination request.
1330 *
1331 * @return true if we're ok with shutting down now, false if we're not.
1332 * @param fOptions Flags.
1333 */
1334bool org_virtualbox_SupDrv::terminate(IOOptionBits fOptions)
1335{
1336 bool fRc;
1337 LogFlow(("org_virtualbox_SupDrv::terminate: reference_count=%d g_cSessions=%d (fOptions=%#x)\n",
1338 KMOD_INFO_NAME.reference_count, ASMAtomicUoReadS32(&g_cSessions), fOptions));
1339 if ( KMOD_INFO_NAME.reference_count != 0
1340 || ASMAtomicUoReadS32(&g_cSessions))
1341 fRc = false;
1342 else
1343 fRc = IOService::terminate(fOptions);
1344 LogFlow(("org_virtualbox_SupDrv::terminate: returns %d\n", fRc));
1345 return fRc;
1346}
1347
1348
1349/*
1350 *
1351 * org_virtualbox_SupDrvClient
1352 *
1353 */
1354
1355
1356/**
1357 * Initializer called when the client opens the service.
1358 */
1359bool org_virtualbox_SupDrvClient::initWithTask(task_t OwningTask, void *pvSecurityId, UInt32 u32Type)
1360{
1361 LogFlow(("org_virtualbox_SupDrvClient::initWithTask([%p], %#x, %p, %#x) (cur pid=%d proc=%p)\n",
1362 this, OwningTask, pvSecurityId, u32Type, RTProcSelf(), RTR0ProcHandleSelf()));
1363 AssertMsg((RTR0PROCESS)OwningTask == RTR0ProcHandleSelf(), ("%p %p\n", OwningTask, RTR0ProcHandleSelf()));
1364
1365 if (!OwningTask)
1366 return false;
1367 if (IOUserClient::initWithTask(OwningTask, pvSecurityId , u32Type))
1368 {
1369 m_Task = OwningTask;
1370 m_pSession = NULL;
1371 m_pProvider = NULL;
1372 return true;
1373 }
1374 return false;
1375}
1376
1377
1378/**
1379 * Start the client service.
1380 */
1381bool org_virtualbox_SupDrvClient::start(IOService *pProvider)
1382{
1383 LogFlow(("org_virtualbox_SupDrvClient::start([%p], %p) (cur pid=%d proc=%p)\n",
1384 this, pProvider, RTProcSelf(), RTR0ProcHandleSelf() ));
1385 AssertMsgReturn((RTR0PROCESS)m_Task == RTR0ProcHandleSelf(),
1386 ("%p %p\n", m_Task, RTR0ProcHandleSelf()),
1387 false);
1388
1389 if (IOUserClient::start(pProvider))
1390 {
1391 m_pProvider = OSDynamicCast(org_virtualbox_SupDrv, pProvider);
1392 if (m_pProvider)
1393 {
1394 Assert(!m_pSession);
1395
1396 /*
1397 * Create a new session.
1398 */
1399 int rc = supdrvCreateSession(&g_DevExt, true /* fUser */, false /*fUnrestricted*/, &m_pSession);
1400 if (RT_SUCCESS(rc))
1401 {
1402 m_pSession->fOpened = false;
1403 /* The Uid, Gid and fUnrestricted fields are set on open. */
1404
1405 /*
1406 * Insert it into the hash table, checking that there isn't
1407 * already one for this process first. (One session per proc!)
1408 */
1409 unsigned iHash = SESSION_HASH(m_pSession->Process);
1410 RTSpinlockAcquire(g_Spinlock);
1411
1412 PSUPDRVSESSION pCur = g_apSessionHashTab[iHash];
1413 if (pCur && pCur->Process != m_pSession->Process)
1414 {
1415 do pCur = pCur->pNextHash;
1416 while (pCur && pCur->Process != m_pSession->Process);
1417 }
1418 if (!pCur)
1419 {
1420 m_pSession->pNextHash = g_apSessionHashTab[iHash];
1421 g_apSessionHashTab[iHash] = m_pSession;
1422 m_pSession->pvSupDrvClient = this;
1423 ASMAtomicIncS32(&g_cSessions);
1424 rc = VINF_SUCCESS;
1425 }
1426 else
1427 rc = VERR_ALREADY_LOADED;
1428
1429 RTSpinlockReleaseNoInts(g_Spinlock);
1430 if (RT_SUCCESS(rc))
1431 {
1432 Log(("org_virtualbox_SupDrvClient::start: created session %p for pid %d\n", m_pSession, (int)RTProcSelf()));
1433 return true;
1434 }
1435
1436 LogFlow(("org_virtualbox_SupDrvClient::start: already got a session for this process (%p)\n", pCur));
1437 supdrvSessionRelease(m_pSession);
1438 }
1439
1440 m_pSession = NULL;
1441 LogFlow(("org_virtualbox_SupDrvClient::start: rc=%Rrc from supdrvCreateSession\n", rc));
1442 }
1443 else
1444 LogFlow(("org_virtualbox_SupDrvClient::start: %p isn't org_virtualbox_SupDrv\n", pProvider));
1445 }
1446 return false;
1447}
1448
1449
1450/**
1451 * Common worker for clientClose and VBoxDrvDarwinClose.
1452 */
1453/* static */ void org_virtualbox_SupDrvClient::sessionClose(RTPROCESS Process)
1454{
1455 /*
1456 * Find the session and remove it from the hash table.
1457 *
1458 * Note! Only one session per process. (Both start() and
1459 * VBoxDrvDarwinOpen makes sure this is so.)
1460 */
1461 const unsigned iHash = SESSION_HASH(Process);
1462 RTSpinlockAcquire(g_Spinlock);
1463 PSUPDRVSESSION pSession = g_apSessionHashTab[iHash];
1464 if (pSession)
1465 {
1466 if (pSession->Process == Process)
1467 {
1468 g_apSessionHashTab[iHash] = pSession->pNextHash;
1469 pSession->pNextHash = NULL;
1470 ASMAtomicDecS32(&g_cSessions);
1471 }
1472 else
1473 {
1474 PSUPDRVSESSION pPrev = pSession;
1475 pSession = pSession->pNextHash;
1476 while (pSession)
1477 {
1478 if (pSession->Process == Process)
1479 {
1480 pPrev->pNextHash = pSession->pNextHash;
1481 pSession->pNextHash = NULL;
1482 ASMAtomicDecS32(&g_cSessions);
1483 break;
1484 }
1485
1486 /* next */
1487 pPrev = pSession;
1488 pSession = pSession->pNextHash;
1489 }
1490 }
1491 }
1492 RTSpinlockReleaseNoInts(g_Spinlock);
1493 if (!pSession)
1494 {
1495 Log(("SupDrvClient::sessionClose: pSession == NULL, pid=%d; freed already?\n", (int)Process));
1496 return;
1497 }
1498
1499 /*
1500 * Remove it from the client object.
1501 */
1502 org_virtualbox_SupDrvClient *pThis = (org_virtualbox_SupDrvClient *)pSession->pvSupDrvClient;
1503 pSession->pvSupDrvClient = NULL;
1504 if (pThis)
1505 {
1506 Assert(pThis->m_pSession == pSession);
1507 pThis->m_pSession = NULL;
1508 }
1509
1510 /*
1511 * Close the session.
1512 */
1513 supdrvSessionRelease(pSession);
1514}
1515
1516
1517/**
1518 * Client exits normally.
1519 */
1520IOReturn org_virtualbox_SupDrvClient::clientClose(void)
1521{
1522 LogFlow(("org_virtualbox_SupDrvClient::clientClose([%p]) (cur pid=%d proc=%p)\n", this, RTProcSelf(), RTR0ProcHandleSelf()));
1523 AssertMsg((RTR0PROCESS)m_Task == RTR0ProcHandleSelf(), ("%p %p\n", m_Task, RTR0ProcHandleSelf()));
1524
1525 /*
1526 * Clean up the session if it's still around.
1527 *
1528 * We cannot rely 100% on close, and in the case of a dead client
1529 * we'll end up hanging inside vm_map_remove() if we postpone it.
1530 */
1531 if (m_pSession)
1532 {
1533 sessionClose(RTProcSelf());
1534 Assert(!m_pSession);
1535 }
1536
1537 m_pProvider = NULL;
1538 terminate();
1539
1540 return kIOReturnSuccess;
1541}
1542
1543
1544/**
1545 * The client exits abnormally / forgets to do cleanups. (logging)
1546 */
1547IOReturn org_virtualbox_SupDrvClient::clientDied(void)
1548{
1549 LogFlow(("org_virtualbox_SupDrvClient::clientDied([%p]) m_Task=%p R0Process=%p Process=%d\n",
1550 this, m_Task, RTR0ProcHandleSelf(), RTProcSelf()));
1551
1552 /* IOUserClient::clientDied() calls clientClose, so we'll just do the work there. */
1553 return IOUserClient::clientDied();
1554}
1555
1556
1557/**
1558 * Terminate the service (initiate the destruction). (logging)
1559 */
1560bool org_virtualbox_SupDrvClient::terminate(IOOptionBits fOptions)
1561{
1562 LogFlow(("org_virtualbox_SupDrvClient::terminate([%p], %#x)\n", this, fOptions));
1563 return IOUserClient::terminate(fOptions);
1564}
1565
1566
1567/**
1568 * The final stage of the client service destruction. (logging)
1569 */
1570bool org_virtualbox_SupDrvClient::finalize(IOOptionBits fOptions)
1571{
1572 LogFlow(("org_virtualbox_SupDrvClient::finalize([%p], %#x)\n", this, fOptions));
1573 return IOUserClient::finalize(fOptions);
1574}
1575
1576
1577/**
1578 * Stop the client service. (logging)
1579 */
1580void org_virtualbox_SupDrvClient::stop(IOService *pProvider)
1581{
1582 LogFlow(("org_virtualbox_SupDrvClient::stop([%p])\n", this));
1583 IOUserClient::stop(pProvider);
1584}
1585
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