VirtualBox

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

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

forward-ported r98913 from 4.3 to trunk (Support/Darwin: on recent CPUs set EFLAGS.AC before executing the IOCtl to disable SMAP)

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

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette