VirtualBox

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

Last change on this file since 55782 was 55319, checked in by vboxsync, 10 years ago

forward-ported r98914, r98916 from 4.3 to trunk (LogRel and build fix)

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