VirtualBox

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

Last change on this file since 51661 was 51492, checked in by vboxsync, 11 years ago

Mac OS X host: added temporary instrumentation to see if VBox KEXTs refuse connection to IOServices from 3rd party applications.

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