VirtualBox

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

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

vboxdrvDarwinResolveSymbols: Fail if we cannot get the vmx_* symbols we need for raw-mode.

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