VirtualBox

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

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

SUPDrv,asm-amd64-x86.h: More EFLAGS.AC checks.

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