VirtualBox

source: vbox/trunk/src/VBox/Devices/USB/darwin/USBProxyDevice-darwin.cpp@ 94342

Last change on this file since 94342 was 94342, checked in by vboxsync, 3 years ago

Main,VMM/PDMUsb,Devices/USB,VRDP: Drop passing pointers through CFGM in favor of using VMM2USERMETHODS::pfnQueryGenericObject, bugref:10053

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 73.9 KB
Line 
1/* $Id: USBProxyDevice-darwin.cpp 94342 2022-03-23 19:53:21Z vboxsync $ */
2/** @file
3 * USB device proxy - the Darwin backend.
4 */
5
6/*
7 * Copyright (C) 2006-2022 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
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_DRV_USBPROXY
23#define __STDC_LIMIT_MACROS
24#define __STDC_CONSTANT_MACROS
25
26#include <mach/mach.h>
27#include <Carbon/Carbon.h>
28#include <IOKit/IOKitLib.h>
29#include <mach/mach_error.h>
30#include <IOKit/usb/IOUSBLib.h>
31#include <IOKit/IOCFPlugIn.h>
32#ifndef __MAC_10_10 /* Quick hack: The following two masks appeared in 10.10. */
33# define kUSBReEnumerateReleaseDeviceMask RT_BIT_32(29)
34# define kUSBReEnumerateCaptureDeviceMask RT_BIT_32(30)
35#endif
36
37#include <VBox/log.h>
38#include <VBox/err.h>
39#include <VBox/vmm/pdm.h>
40
41#include <iprt/assert.h>
42#include <iprt/critsect.h>
43#include <iprt/list.h>
44#include <iprt/mem.h>
45#include <iprt/once.h>
46#include <iprt/string.h>
47#include <iprt/time.h>
48
49#include "../USBProxyDevice.h"
50#include <VBox/usblib.h>
51
52
53/*********************************************************************************************************************************
54* Defined Constants And Macros *
55*********************************************************************************************************************************/
56/** An experiment... */
57//#define USE_LOW_LATENCY_API 1
58
59
60/*********************************************************************************************************************************
61* Structures and Typedefs *
62*********************************************************************************************************************************/
63/** Forward declaration of the Darwin interface structure. */
64typedef struct USBPROXYIFOSX *PUSBPROXYIFOSX;
65
66
67/**
68 * A low latency isochronous buffer.
69 *
70 * These are allocated in chunks on an interface level, see USBPROXYISOCBUFCOL.
71 */
72typedef struct USBPROXYISOCBUF
73{
74 /** Whether this buffer is in use or not. */
75 bool volatile fUsed;
76 /** Pointer to the buffer. */
77 void *pvBuf;
78 /** Pointer to an array of 8 frames. */
79 IOUSBLowLatencyIsocFrame *paFrames;
80} USBPROXYISOCBUF, *PUSBPROXYISOCBUF;
81
82
83/**
84 * Isochronous buffer collection (associated with an interface).
85 *
86 * These are allocated in decent sized chunks and there isn't supposed
87 * to be too many of these per interface.
88 */
89typedef struct USBPROXYISOCBUFCOL
90{
91 /** Write or Read buffers? */
92 USBLowLatencyBufferType enmType;
93 /** The next buffer collection on this interface. */
94 struct USBPROXYISOCBUFCOL *pNext;
95 /** The buffer. */
96 void *pvBuffer;
97 /** The frame. */
98 void *pvFrames;
99 /** The buffers.
100 * The number of buffers here is decided by pvFrame begin allocated in
101 * GUEST_PAGE_SIZE chunks. The size of IOUSBLowLatencyIsocFrame is 16 bytes
102 * and we require 8 of those per buffer. GUEST_PAGE_SIZE / (16 * 8) = 32.
103 * @remarks Don't allocate too many as it may temporarily halt the system if
104 * some pool is low / exhausted. (Contiguous memory woes on mach.)
105 */
106 USBPROXYISOCBUF aBuffers[/*32*/ 4];
107} USBPROXYISOCBUFCOL, *PUSBPROXYISOCBUFCOL;
108
109AssertCompileSize(IOUSBLowLatencyIsocFrame, 16);
110
111/**
112 * Per-urb data for the Darwin usb proxy backend.
113 *
114 * This is required to track in-flight and landed URBs
115 * since we take down the URBs in a different thread (perhaps).
116 */
117typedef struct USBPROXYURBOSX
118{
119 /** Pointer to the next Darwin URB. */
120 struct USBPROXYURBOSX *pNext;
121 /** Pointer to the previous Darwin URB. */
122 struct USBPROXYURBOSX *pPrev;
123 /** The millisecond timestamp when this URB was submitted. */
124 uint64_t u64SubmitTS;
125 /** Pointer to the VUSB URB.
126 * This is set to NULL if canceled. */
127 PVUSBURB pVUsbUrb;
128 /** Pointer to the Darwin device. */
129 struct USBPROXYDEVOSX *pDevOsX;
130 /** The transfer type. */
131 VUSBXFERTYPE enmType;
132 /** Union with data depending on transfer type. */
133 union
134 {
135 /** The control message. */
136 IOUSBDevRequest ControlMsg;
137 /** The Isochronous Data. */
138 struct
139 {
140#ifdef USE_LOW_LATENCY_API
141 /** The low latency isochronous buffer. */
142 PUSBPROXYISOCBUF pBuf;
143 /** Array of frames parallel to the one in VUSBURB. (Same as pBuf->paFrames.) */
144 IOUSBLowLatencyIsocFrame *aFrames;
145#else
146 /** Array of frames parallel to the one in VUSBURB. */
147 IOUSBIsocFrame aFrames[8];
148#endif
149 } Isoc;
150 } u;
151} USBPROXYURBOSX, *PUSBPROXYURBOSX;
152
153/**
154 * Per-pipe data for the Darwin usb proxy backend.
155 */
156typedef struct USBPROXYPIPEOSX
157{
158 /** The endpoint number. */
159 uint8_t u8Endpoint;
160 /** The IOKit pipe reference. */
161 uint8_t u8PipeRef;
162 /** The pipe Transfer type type. */
163 uint8_t u8TransferType;
164 /** The pipe direction. */
165 uint8_t u8Direction;
166 /** The endpoint interval. (interrupt) */
167 uint8_t u8Interval;
168 /** Full-speed device indicator (isochronous pipes only). */
169 bool fIsFullSpeed;
170 /** The max packet size. */
171 uint16_t u16MaxPacketSize;
172 /** The next frame number (isochronous pipes only). */
173 uint64_t u64NextFrameNo;
174} USBPROXYPIPEOSX, *PUSBPROXYPIPEOSX, **PPUSBPROXYPIPEOSX;
175
176typedef struct RUNLOOPREFLIST
177{
178 RTLISTNODE List;
179 CFRunLoopRef RunLoopRef;
180} RUNLOOPREFLIST, *PRUNLOOPREFLIST;
181typedef RUNLOOPREFLIST **PPRUNLOOPREFLIST;
182
183/**
184 * Per-interface data for the Darwin usb proxy backend.
185 */
186typedef struct USBPROXYIFOSX
187{
188 /** Pointer to the next interface. */
189 struct USBPROXYIFOSX *pNext;
190 /** The interface number. */
191 uint8_t u8Interface;
192 /** The current alternative interface setting.
193 * This is used to skip unnecessary SetAltInterface calls. */
194 uint8_t u8AltSetting;
195 /** The interface class. (not really used) */
196 uint8_t u8Class;
197 /** The interface protocol. (not really used) */
198 uint8_t u8Protocol;
199 /** The number of pipes. */
200 uint8_t cPipes;
201 /** Array containing all the pipes. (Currently unsorted.) */
202 USBPROXYPIPEOSX aPipes[kUSBMaxPipes];
203 /** The IOUSBDeviceInterface. */
204 IOUSBInterfaceInterface245 **ppIfI;
205 /** The run loop source for the async operations on the interface level. */
206 CFRunLoopSourceRef RunLoopSrcRef;
207 /** List of isochronous buffer collections.
208 * These are allocated on demand by the URB queuing routine and then recycled until the interface is destroyed. */
209 RTLISTANCHOR HeadOfRunLoopLst;
210 PUSBPROXYISOCBUFCOL pIsocBufCols;
211} USBPROXYIFOSX, *PUSBPROXYIFOSX, **PPUSBPROXYIFOSX;
212/** Pointer to a pointer to an darwin interface. */
213typedef USBPROXYIFOSX **PPUSBPROXYIFOSX;
214
215/**
216 * Per-device Data for the Darwin usb proxy backend.
217 */
218typedef struct USBPROXYDEVOSX
219{
220 /** The USB Device IOService object. */
221 io_object_t USBDevice;
222 /** The IOUSBDeviceInterface. */
223 IOUSBDeviceInterface245 **ppDevI;
224 /** The run loop source for the async operations on the device level
225 * (i.e. the default control pipe stuff). */
226 CFRunLoopSourceRef RunLoopSrcRef;
227 /** we want to add and remove RunLoopSourceRefs to run loop's of
228 * every EMT thread participated in USB processing. */
229 RTLISTANCHOR HeadOfRunLoopLst;
230 /** Pointer to the proxy device instance. */
231 PUSBPROXYDEV pProxyDev;
232
233 /** Pointer to the first interface. */
234 PUSBPROXYIFOSX pIfHead;
235 /** Pointer to the last interface. */
236 PUSBPROXYIFOSX pIfTail;
237
238 /** Critical section protecting the lists. */
239 RTCRITSECT CritSect;
240 /** The list of free Darwin URBs. Singly linked. */
241 PUSBPROXYURBOSX pFreeHead;
242 /** The list of landed Darwin URBs. Doubly linked.
243 * Only the split head will appear in this list. */
244 PUSBPROXYURBOSX pTaxingHead;
245 /** The tail of the landed Darwin URBs. */
246 PUSBPROXYURBOSX pTaxingTail;
247 /** Last reaper runloop reference, there can be only one runloop at a time. */
248 CFRunLoopRef hRunLoopReapingLast;
249 /** Runloop source for waking up the reaper thread. */
250 CFRunLoopSourceRef hRunLoopSrcWakeRef;
251 /** List of threads used for reaping which can be woken up. */
252 RTLISTANCHOR HeadOfRunLoopWakeLst;
253 /** Runloop reference of the thread reaping. */
254 volatile CFRunLoopRef hRunLoopReaping;
255 /** Flag whether the reaping thread is about the be waked. */
256 volatile bool fReapingThreadWake;
257} USBPROXYDEVOSX, *PUSBPROXYDEVOSX;
258
259
260/*********************************************************************************************************************************
261* Global Variables *
262*********************************************************************************************************************************/
263static RTONCE g_usbProxyDarwinOnce = RTONCE_INITIALIZER;
264/** The runloop mode we use.
265 * Since it's difficult to remove this, we leak it to prevent crashes.
266 * @bugref{4407} */
267static CFStringRef g_pRunLoopMode = NULL;
268/** The IO Master Port.
269 * Not worth cleaning up. */
270static mach_port_t g_MasterPort = MACH_PORT_NULL;
271
272
273/**
274 * Init once callback that sets up g_MasterPort and g_pRunLoopMode.
275 *
276 * @returns IPRT status code.
277 *
278 * @param pvUser1 NULL, ignored.
279 */
280static DECLCALLBACK(int32_t) usbProxyDarwinInitOnce(void *pvUser1)
281{
282 RT_NOREF(pvUser1);
283
284 int rc;
285 kern_return_t krc = IOMasterPort(MACH_PORT_NULL, &g_MasterPort);
286 if (krc == KERN_SUCCESS)
287 {
288 g_pRunLoopMode = CFStringCreateWithCString(kCFAllocatorDefault, "VBoxUsbProxyMode", kCFStringEncodingUTF8);
289 if (g_pRunLoopMode)
290 return VINF_SUCCESS;
291 rc = VERR_INTERNAL_ERROR_5;
292 }
293 else
294 rc = RTErrConvertFromDarwin(krc);
295 return rc;
296}
297
298/**
299 * Kicks the reaper thread if it sleeps currently to respond to state changes
300 * or to pick up completed URBs.
301 *
302 * @returns nothing.
303 * @param pDevOsX The darwin device instance data.
304 */
305static void usbProxyDarwinReaperKick(PUSBPROXYDEVOSX pDevOsX)
306{
307 CFRunLoopRef hRunLoopWake = (CFRunLoopRef)ASMAtomicReadPtr((void * volatile *)&pDevOsX->hRunLoopReaping);
308 if (hRunLoopWake)
309 {
310 LogFlowFunc(("Waking runloop %p\n", hRunLoopWake));
311 CFRunLoopSourceSignal(pDevOsX->hRunLoopSrcWakeRef);
312 CFRunLoopWakeUp(hRunLoopWake);
313 }
314}
315
316/**
317 * Adds Source ref to current run loop and adds it the list of runloops.
318 */
319static int usbProxyDarwinAddRunLoopRef(PRTLISTANCHOR pListHead,
320 CFRunLoopSourceRef SourceRef)
321{
322 AssertPtrReturn(pListHead, VERR_INVALID_PARAMETER);
323 AssertReturn(CFRunLoopSourceIsValid(SourceRef), VERR_INVALID_PARAMETER);
324
325 if (CFRunLoopContainsSource(CFRunLoopGetCurrent(), SourceRef, g_pRunLoopMode))
326 return VINF_SUCCESS;
327
328 /* Add to the list */
329 PRUNLOOPREFLIST pListNode = (PRUNLOOPREFLIST)RTMemAllocZ(sizeof(RUNLOOPREFLIST));
330 if (!pListNode)
331 return VERR_NO_MEMORY;
332
333 pListNode->RunLoopRef = CFRunLoopGetCurrent();
334
335 CFRetain(pListNode->RunLoopRef);
336 CFRetain(SourceRef); /* We want to be aware of releasing */
337
338 CFRunLoopAddSource(pListNode->RunLoopRef, SourceRef, g_pRunLoopMode);
339
340 RTListInit(&pListNode->List);
341
342 RTListAppend((PRTLISTNODE)pListHead, &pListNode->List);
343
344 return VINF_SUCCESS;
345}
346
347
348/*
349 * Removes all source reference from mode of run loop's we've registered them.
350 *
351 */
352static int usbProxyDarwinRemoveSourceRefFromAllRunLoops(PRTLISTANCHOR pHead,
353 CFRunLoopSourceRef SourceRef)
354{
355 AssertPtrReturn(pHead, VERR_INVALID_PARAMETER);
356
357 while (!RTListIsEmpty(pHead))
358 {
359 PRUNLOOPREFLIST pNode = RTListGetFirst(pHead, RUNLOOPREFLIST, List);
360 /* XXX: Should Release Reference? */
361 Assert(CFGetRetainCount(pNode->RunLoopRef));
362
363 CFRunLoopRemoveSource(pNode->RunLoopRef, SourceRef, g_pRunLoopMode);
364 CFRelease(SourceRef);
365 CFRelease(pNode->RunLoopRef);
366
367 RTListNodeRemove(&pNode->List);
368
369 RTMemFree(pNode);
370 }
371
372 return VINF_SUCCESS;
373}
374
375
376/**
377 * Allocates a Darwin URB request structure.
378 *
379 * @returns Pointer to an active URB request.
380 * @returns NULL on failure.
381 *
382 * @param pDevOsX The darwin proxy device.
383 */
384static PUSBPROXYURBOSX usbProxyDarwinUrbAlloc(PUSBPROXYDEVOSX pDevOsX)
385{
386 PUSBPROXYURBOSX pUrbOsX;
387
388 RTCritSectEnter(&pDevOsX->CritSect);
389
390 /*
391 * Try remove a Darwin URB from the free list, if none there allocate a new one.
392 */
393 pUrbOsX = pDevOsX->pFreeHead;
394 if (pUrbOsX)
395 {
396 pDevOsX->pFreeHead = pUrbOsX->pNext;
397 RTCritSectLeave(&pDevOsX->CritSect);
398 }
399 else
400 {
401 RTCritSectLeave(&pDevOsX->CritSect);
402 pUrbOsX = (PUSBPROXYURBOSX)RTMemAlloc(sizeof(*pUrbOsX));
403 if (!pUrbOsX)
404 return NULL;
405 }
406 pUrbOsX->pVUsbUrb = NULL;
407 pUrbOsX->pDevOsX = pDevOsX;
408 pUrbOsX->enmType = VUSBXFERTYPE_INVALID;
409
410 return pUrbOsX;
411}
412
413
414#ifdef USE_LOW_LATENCY_API
415/**
416 * Allocates an low latency isochronous buffer.
417 *
418 * @returns VBox status code.
419 * @param pUrbOsX The OsX URB to allocate it for.
420 * @param pIf The interface to allocated it from.
421 */
422static int usbProxyDarwinUrbAllocIsocBuf(PUSBPROXYURBOSX pUrbOsX, PUSBPROXYIFOSX pIf)
423{
424 USBLowLatencyBufferType enmLLType = pUrbOsX->pVUsbUrb->enmDir == VUSBDIRECTION_IN
425 ? kUSBLowLatencyWriteBuffer : kUSBLowLatencyReadBuffer;
426
427 /*
428 * Walk the buffer collection list and look for an unused one.
429 */
430 pUrbOsX->u.Isoc.pBuf = NULL;
431 for (PUSBPROXYISOCBUFCOL pCur = pIf->pIsocBufCols; pCur; pCur = pCur->pNext)
432 if (pCur->enmType == enmLLType)
433 for (unsigned i = 0; i < RT_ELEMENTS(pCur->aBuffers); i++)
434 if (!pCur->aBuffers[i].fUsed)
435 {
436 pCur->aBuffers[i].fUsed = true;
437 pUrbOsX->u.Isoc.pBuf = &pCur->aBuffers[i];
438 AssertPtr(pUrbOsX->u.Isoc.pBuf);
439 AssertPtr(pUrbOsX->u.Isoc.pBuf->pvBuf);
440 pUrbOsX->u.Isoc.aFrames = pCur->aBuffers[i].paFrames;
441 AssertPtr(pUrbOsX->u.Isoc.aFrames);
442 return VINF_SUCCESS;
443 }
444
445 /*
446 * Didn't find an empty one, create a new buffer collection and take the first buffer.
447 */
448 PUSBPROXYISOCBUFCOL pNew = (PUSBPROXYISOCBUFCOL)RTMemAllocZ(sizeof(*pNew));
449 AssertReturn(pNew, VERR_NO_MEMORY);
450
451 IOReturn irc = (*pIf->ppIfI)->LowLatencyCreateBuffer(pIf->ppIfI, &pNew->pvBuffer, 8192 * RT_ELEMENTS(pNew->aBuffers), enmLLType);
452 if ((irc == kIOReturnSuccess) != RT_VALID_PTR(pNew->pvBuffer))
453 {
454 AssertPtr(pNew->pvBuffer);
455 irc = kIOReturnNoMemory;
456 }
457 if (irc == kIOReturnSuccess)
458 {
459 /** @todo GUEST_PAGE_SIZE or HOST_PAGE_SIZE or just 4K? */
460 irc = (*pIf->ppIfI)->LowLatencyCreateBuffer(pIf->ppIfI, &pNew->pvFrames, GUEST_PAGE_SIZE, kUSBLowLatencyFrameListBuffer);
461 if ((irc == kIOReturnSuccess) != RT_VALID_PTR(pNew->pvFrames))
462 {
463 AssertPtr(pNew->pvFrames);
464 irc = kIOReturnNoMemory;
465 }
466 if (irc == kIOReturnSuccess)
467 {
468 for (unsigned i = 0; i < RT_ELEMENTS(pNew->aBuffers); i++)
469 {
470 //pNew->aBuffers[i].fUsed = false;
471 pNew->aBuffers[i].paFrames = &((IOUSBLowLatencyIsocFrame *)pNew->pvFrames)[i * 8];
472 pNew->aBuffers[i].pvBuf = (uint8_t *)pNew->pvBuffer + i * 8192;
473 }
474
475 pNew->aBuffers[0].fUsed = true;
476 pUrbOsX->u.Isoc.aFrames = pNew->aBuffers[0].paFrames;
477 pUrbOsX->u.Isoc.pBuf = &pNew->aBuffers[0];
478
479 pNew->enmType = enmLLType;
480 pNew->pNext = pIf->pIsocBufCols;
481 pIf->pIsocBufCols = pNew;
482
483#if 0 /* doesn't help :-/ */
484 /*
485 * If this is the first time we're here, try mess with the policy?
486 */
487 if (!pNew->pNext)
488 for (unsigned iPipe = 0; iPipe < pIf->cPipes; iPipe++)
489 if (pIf->aPipes[iPipe].u8TransferType == kUSBIsoc)
490 {
491 irc = (*pIf->ppIfI)->SetPipePolicy(pIf->ppIfI, pIf->aPipes[iPipe].u8PipeRef,
492 pIf->aPipes[iPipe].u16MaxPacketSize, pIf->aPipes[iPipe].u8Interval);
493 AssertMsg(irc == kIOReturnSuccess, ("%#x\n", irc));
494 }
495#endif
496
497 return VINF_SUCCESS;
498 }
499
500 /* bail out */
501 (*pIf->ppIfI)->LowLatencyDestroyBuffer(pIf->ppIfI, pNew->pvBuffer);
502 }
503 AssertMsgFailed(("%#x\n", irc));
504 RTMemFree(pNew);
505
506 return RTErrConvertFromDarwin(irc);
507}
508#endif /* USE_LOW_LATENCY_API */
509
510
511/**
512 * Frees a Darwin URB request structure.
513 *
514 * @param pDevOsX The darwin proxy device.
515 * @param pUrbOsX The Darwin URB to free.
516 */
517static void usbProxyDarwinUrbFree(PUSBPROXYDEVOSX pDevOsX, PUSBPROXYURBOSX pUrbOsX)
518{
519 RTCritSectEnter(&pDevOsX->CritSect);
520
521#ifdef USE_LOW_LATENCY_API
522 /*
523 * Free low latency stuff.
524 */
525 if ( pUrbOsX->enmType == VUSBXFERTYPE_ISOC
526 && pUrbOsX->u.Isoc.pBuf)
527 {
528 pUrbOsX->u.Isoc.pBuf->fUsed = false;
529 pUrbOsX->u.Isoc.pBuf = NULL;
530 }
531#endif
532
533 /*
534 * Link it into the free list.
535 */
536 pUrbOsX->pPrev = NULL;
537 pUrbOsX->pNext = pDevOsX->pFreeHead;
538 pDevOsX->pFreeHead = pUrbOsX;
539
540 pUrbOsX->pVUsbUrb = NULL;
541 pUrbOsX->pDevOsX = NULL;
542 pUrbOsX->enmType = VUSBXFERTYPE_INVALID;
543
544 RTCritSectLeave(&pDevOsX->CritSect);
545}
546
547/**
548 * Translate the IOKit status code to a VUSB status.
549 *
550 * @returns VUSB URB status code.
551 * @param irc IOKit status code.
552 */
553static VUSBSTATUS vusbProxyDarwinStatusToVUsbStatus(IOReturn irc)
554{
555 switch (irc)
556 {
557 /* IOKit OHCI VUSB */
558 case kIOReturnSuccess: /* 0 */ return VUSBSTATUS_OK;
559 case kIOUSBCRCErr: /* 1 */ return VUSBSTATUS_CRC;
560 //case kIOUSBBitstufErr: /* 2 */ return VUSBSTATUS_;
561 //case kIOUSBDataToggleErr: /* 3 */ return VUSBSTATUS_;
562 case kIOUSBPipeStalled: /* 4 */ return VUSBSTATUS_STALL;
563 case kIOReturnNotResponding: /* 5 */ return VUSBSTATUS_DNR;
564 //case kIOUSBPIDCheckErr: /* 6 */ return VUSBSTATUS_;
565 //case kIOUSBWrongPIDErr: /* 7 */ return VUSBSTATUS_;
566 case kIOReturnOverrun: /* 8 */ return VUSBSTATUS_DATA_OVERRUN;
567 case kIOReturnUnderrun: /* 9 */ return VUSBSTATUS_DATA_UNDERRUN;
568 //case kIOUSBReserved1Err: /* 10 */ return VUSBSTATUS_;
569 //case kIOUSBReserved2Err: /* 11 */ return VUSBSTATUS_;
570 //case kIOUSBBufferOverrunErr: /* 12 */ return VUSBSTATUS_;
571 //case kIOUSBBufferUnderrunErr: /* 13 */ return VUSBSTATUS_;
572 case kIOUSBNotSent1Err: /* 14 */ return VUSBSTATUS_NOT_ACCESSED/*VUSBSTATUS_OK*/;
573 case kIOUSBNotSent2Err: /* 15 */ return VUSBSTATUS_NOT_ACCESSED/*VUSBSTATUS_OK*/;
574
575 /* Other errors */
576 case kIOUSBTransactionTimeout: return VUSBSTATUS_DNR;
577 //case kIOReturnAborted: return VUSBSTATUS_CRC; - see on SET_INTERFACE...
578
579 default:
580 Log(("vusbProxyDarwinStatusToVUsbStatus: irc=%#x!!\n", irc));
581 return VUSBSTATUS_STALL;
582 }
583}
584
585
586/**
587 * Completion callback for an async URB transfer.
588 *
589 * @param pvUrbOsX The Darwin URB.
590 * @param irc The status of the operation.
591 * @param Size Possible the transfer size.
592 */
593static void usbProxyDarwinUrbAsyncComplete(void *pvUrbOsX, IOReturn irc, void *Size)
594{
595 PUSBPROXYURBOSX pUrbOsX = (PUSBPROXYURBOSX)pvUrbOsX;
596 PUSBPROXYDEVOSX pDevOsX = pUrbOsX->pDevOsX;
597 const uint32_t cb = (uintptr_t)Size;
598
599 /*
600 * Do status updates.
601 */
602 PVUSBURB pUrb = pUrbOsX->pVUsbUrb;
603 if (pUrb)
604 {
605 Assert(pUrb->u32Magic == VUSBURB_MAGIC);
606 if (pUrb->enmType == VUSBXFERTYPE_ISOC)
607 {
608#ifdef USE_LOW_LATENCY_API
609 /* copy the data. */
610 //if (pUrb->enmDir == VUSBDIRECTION_IN)
611 memcpy(pUrb->abData, pUrbOsX->u.Isoc.pBuf->pvBuf, pUrb->cbData);
612#endif
613 Log3(("AsyncComplete isoc - raw data (%d bytes):\n"
614 "%16.*Rhxd\n", pUrb->cbData, pUrb->cbData, pUrb->abData));
615 uint32_t off = 0;
616 for (unsigned i = 0; i < pUrb->cIsocPkts; i++)
617 {
618#ifdef USE_LOW_LATENCY_API
619 Log2((" %d{%d/%d-%x-%RX64}", i, pUrbOsX->u.Isoc.aFrames[i].frActCount, pUrb->aIsocPkts[i].cb, pUrbOsX->u.Isoc.aFrames[i].frStatus,
620 RT_MAKE_U64(pUrbOsX->u.Isoc.aFrames[i].frTimeStamp.lo, pUrbOsX->u.Isoc.aFrames[i].frTimeStamp.hi) ));
621#else
622 Log2((" %d{%d/%d-%x}", i, pUrbOsX->u.Isoc.aFrames[i].frActCount, pUrb->aIsocPkts[i].cb, pUrbOsX->u.Isoc.aFrames[i].frStatus));
623#endif
624 pUrb->aIsocPkts[i].enmStatus = vusbProxyDarwinStatusToVUsbStatus(pUrbOsX->u.Isoc.aFrames[i].frStatus);
625 pUrb->aIsocPkts[i].cb = pUrbOsX->u.Isoc.aFrames[i].frActCount;
626 off += pUrbOsX->u.Isoc.aFrames[i].frActCount;
627 }
628 Log2(("\n"));
629#if 0 /** @todo revisit this, wasn't working previously. */
630 for (int i = (int)pUrb->cIsocPkts - 1; i >= 0; i--)
631 Assert( !pUrbOsX->u.Isoc.aFrames[i].frActCount
632 && !pUrbOsX->u.Isoc.aFrames[i].frReqCount
633 && !pUrbOsX->u.Isoc.aFrames[i].frStatus);
634#endif
635 pUrb->cbData = off; /* 'Size' seems to be pointing at an error code or something... */
636 pUrb->enmStatus = VUSBSTATUS_OK; /* Don't use 'irc'. OHCI expects OK unless it's a really bad error. */
637 }
638 else
639 {
640 pUrb->cbData = cb;
641 pUrb->enmStatus = vusbProxyDarwinStatusToVUsbStatus(irc);
642 if (pUrb->enmType == VUSBXFERTYPE_MSG)
643 pUrb->cbData += sizeof(VUSBSETUP);
644 }
645 }
646
647 RTCritSectEnter(&pDevOsX->CritSect);
648
649 /*
650 * Link it into the taxing list.
651 */
652 pUrbOsX->pNext = NULL;
653 pUrbOsX->pPrev = pDevOsX->pTaxingTail;
654 if (pDevOsX->pTaxingTail)
655 pDevOsX->pTaxingTail->pNext = pUrbOsX;
656 else
657 pDevOsX->pTaxingHead = pUrbOsX;
658 pDevOsX->pTaxingTail = pUrbOsX;
659
660 RTCritSectLeave(&pDevOsX->CritSect);
661
662 LogFlow(("%s: usbProxyDarwinUrbAsyncComplete: cb=%d EndPt=%#x irc=%#x (%d)\n",
663 pUrb->pszDesc, cb, pUrb ? pUrb->EndPt : 0xff, irc, pUrb ? pUrb->enmStatus : 0xff));
664}
665
666/**
667 * Release all interfaces (current config).
668 *
669 * @param pDevOsX The darwin proxy device.
670 */
671static void usbProxyDarwinReleaseAllInterfaces(PUSBPROXYDEVOSX pDevOsX)
672{
673 RTCritSectEnter(&pDevOsX->CritSect);
674
675 /* Kick the reaper thread out of sleep. */
676 usbProxyDarwinReaperKick(pDevOsX);
677
678 PUSBPROXYIFOSX pIf = pDevOsX->pIfHead;
679 pDevOsX->pIfHead = pDevOsX->pIfTail = NULL;
680
681 while (pIf)
682 {
683 PUSBPROXYIFOSX pNext = pIf->pNext;
684 IOReturn irc;
685
686 if (pIf->RunLoopSrcRef)
687 {
688 int rc = usbProxyDarwinRemoveSourceRefFromAllRunLoops((PRTLISTANCHOR)&pIf->HeadOfRunLoopLst, pIf->RunLoopSrcRef);
689 AssertRC(rc);
690
691 CFRelease(pIf->RunLoopSrcRef);
692 pIf->RunLoopSrcRef = NULL;
693 RTListInit((PRTLISTNODE)&pIf->HeadOfRunLoopLst);
694 }
695
696 while (pIf->pIsocBufCols)
697 {
698 PUSBPROXYISOCBUFCOL pCur = pIf->pIsocBufCols;
699 pIf->pIsocBufCols = pCur->pNext;
700 pCur->pNext = NULL;
701
702 irc = (*pIf->ppIfI)->LowLatencyDestroyBuffer(pIf->ppIfI, pCur->pvBuffer);
703 AssertMsg(irc == kIOReturnSuccess || irc == MACH_SEND_INVALID_DEST, ("%#x\n", irc));
704 pCur->pvBuffer = NULL;
705
706 irc = (*pIf->ppIfI)->LowLatencyDestroyBuffer(pIf->ppIfI, pCur->pvFrames);
707 AssertMsg(irc == kIOReturnSuccess || irc == MACH_SEND_INVALID_DEST, ("%#x\n", irc));
708 pCur->pvFrames = NULL;
709
710 RTMemFree(pCur);
711 }
712
713 irc = (*pIf->ppIfI)->USBInterfaceClose(pIf->ppIfI);
714 AssertMsg(irc == kIOReturnSuccess || irc == kIOReturnNoDevice, ("%#x\n", irc));
715
716 (*pIf->ppIfI)->Release(pIf->ppIfI);
717 pIf->ppIfI = NULL;
718
719 RTMemFree(pIf);
720
721 pIf = pNext;
722 }
723 RTCritSectLeave(&pDevOsX->CritSect);
724}
725
726
727/**
728 * Get the properties all the pipes associated with an interface.
729 *
730 * This is used when we seize all the interface and after SET_INTERFACE.
731 *
732 * @returns VBox status code.
733 * @param pDevOsX The darwin proxy device.
734 * @param pIf The interface to get pipe props for.
735 */
736static int usbProxyDarwinGetPipeProperties(PUSBPROXYDEVOSX pDevOsX, PUSBPROXYIFOSX pIf)
737{
738 /*
739 * Get the pipe (endpoint) count (it might have changed - even on open).
740 */
741 int rc = VINF_SUCCESS;
742 bool fFullSpeed;
743 UInt32 u32UsecInFrame;
744 UInt8 cPipes;
745 IOReturn irc = (*pIf->ppIfI)->GetNumEndpoints(pIf->ppIfI, &cPipes);
746 if (irc != kIOReturnSuccess)
747 {
748 pIf->cPipes = 0;
749 if (irc == kIOReturnNoDevice)
750 rc = VERR_VUSB_DEVICE_NOT_ATTACHED;
751 else
752 rc = RTErrConvertFromDarwin(irc);
753 return rc;
754 }
755 AssertRelease(cPipes < RT_ELEMENTS(pIf->aPipes));
756 pIf->cPipes = cPipes + 1;
757
758 /* Find out if this is a full-speed interface (needed for isochronous support). */
759 irc = (*pIf->ppIfI)->GetFrameListTime(pIf->ppIfI, &u32UsecInFrame);
760 if (irc != kIOReturnSuccess)
761 {
762 pIf->cPipes = 0;
763 if (irc == kIOReturnNoDevice)
764 rc = VERR_VUSB_DEVICE_NOT_ATTACHED;
765 else
766 rc = RTErrConvertFromDarwin(irc);
767 return rc;
768 }
769 fFullSpeed = u32UsecInFrame == kUSBFullSpeedMicrosecondsInFrame;
770
771 /*
772 * Get the properties of each pipe.
773 */
774 for (unsigned i = 0; i < pIf->cPipes; i++)
775 {
776 pIf->aPipes[i].u8PipeRef = i;
777 pIf->aPipes[i].fIsFullSpeed = fFullSpeed;
778 pIf->aPipes[i].u64NextFrameNo = 0;
779 irc = (*pIf->ppIfI)->GetPipeProperties(pIf->ppIfI, i,
780 &pIf->aPipes[i].u8Direction,
781 &pIf->aPipes[i].u8Endpoint,
782 &pIf->aPipes[i].u8TransferType,
783 &pIf->aPipes[i].u16MaxPacketSize,
784 &pIf->aPipes[i].u8Interval);
785 if (irc != kIOReturnSuccess)
786 {
787 LogRel(("USB: Failed to query properties for pipe %#d / interface %#x on device '%s'. (prot=%#x class=%#x)\n",
788 i, pIf->u8Interface, pDevOsX->pProxyDev->pUsbIns->pszName, pIf->u8Protocol, pIf->u8Class));
789 if (irc == kIOReturnNoDevice)
790 rc = VERR_VUSB_DEVICE_NOT_ATTACHED;
791 else
792 rc = RTErrConvertFromDarwin(irc);
793 pIf->cPipes = i;
794 break;
795 }
796 /* reconstruct bEndpoint */
797 if (pIf->aPipes[i].u8Direction == kUSBIn)
798 pIf->aPipes[i].u8Endpoint |= 0x80;
799 Log2(("usbProxyDarwinGetPipeProperties: #If=%d EndPt=%#x Dir=%d Type=%d PipeRef=%#x MaxPktSize=%#x Interval=%#x\n",
800 pIf->u8Interface, pIf->aPipes[i].u8Endpoint, pIf->aPipes[i].u8Direction, pIf->aPipes[i].u8TransferType,
801 pIf->aPipes[i].u8PipeRef, pIf->aPipes[i].u16MaxPacketSize, pIf->aPipes[i].u8Interval));
802 }
803
804 /** @todo sort or hash these for speedy lookup... */
805 return VINF_SUCCESS;
806}
807
808
809/**
810 * Seize all interfaces (current config).
811 *
812 * @returns VBox status code.
813 * @param pDevOsX The darwin proxy device.
814 * @param fMakeTheBestOfIt If set we will not give up on error. This is for
815 * use during SET_CONFIGURATION and similar.
816 */
817static int usbProxyDarwinSeizeAllInterfaces(PUSBPROXYDEVOSX pDevOsX, bool fMakeTheBestOfIt)
818{
819 PUSBPROXYDEV pProxyDev = pDevOsX->pProxyDev;
820
821 RTCritSectEnter(&pDevOsX->CritSect);
822
823 /*
824 * Create a interface enumerator for all the interface (current config).
825 */
826 io_iterator_t Interfaces = IO_OBJECT_NULL;
827 IOUSBFindInterfaceRequest Req;
828 Req.bInterfaceClass = kIOUSBFindInterfaceDontCare;
829 Req.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
830 Req.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
831 Req.bAlternateSetting = kIOUSBFindInterfaceDontCare;
832 IOReturn irc = (*pDevOsX->ppDevI)->CreateInterfaceIterator(pDevOsX->ppDevI, &Req, &Interfaces);
833 int rc;
834 if (irc == kIOReturnSuccess)
835 {
836 /*
837 * Iterate the interfaces.
838 */
839 io_object_t Interface;
840 rc = VINF_SUCCESS;
841 while ((Interface = IOIteratorNext(Interfaces)))
842 {
843 /*
844 * Create a plug-in and query the IOUSBInterfaceInterface (cute name).
845 */
846 IOCFPlugInInterface **ppPlugInInterface = NULL;
847 kern_return_t krc;
848 SInt32 Score = 0;
849 krc = IOCreatePlugInInterfaceForService(Interface, kIOUSBInterfaceUserClientTypeID,
850 kIOCFPlugInInterfaceID, &ppPlugInInterface, &Score);
851 IOObjectRelease(Interface);
852 Interface = IO_OBJECT_NULL;
853 if (krc == KERN_SUCCESS)
854 {
855 IOUSBInterfaceInterface245 **ppIfI;
856 HRESULT hrc = (*ppPlugInInterface)->QueryInterface(ppPlugInInterface,
857 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID245),
858 (LPVOID *)&ppIfI);
859 krc = IODestroyPlugInInterface(ppPlugInInterface); Assert(krc == KERN_SUCCESS);
860 ppPlugInInterface = NULL;
861 if (hrc == S_OK)
862 {
863 /*
864 * Query some basic properties first.
865 * (This means we can print more informative messages on failure
866 * to seize the interface.)
867 */
868 UInt8 u8Interface = 0xff;
869 irc = (*ppIfI)->GetInterfaceNumber(ppIfI, &u8Interface);
870 UInt8 u8AltSetting = 0xff;
871 if (irc == kIOReturnSuccess)
872 irc = (*ppIfI)->GetAlternateSetting(ppIfI, &u8AltSetting);
873 UInt8 u8Class = 0xff;
874 if (irc == kIOReturnSuccess)
875 irc = (*ppIfI)->GetInterfaceClass(ppIfI, &u8Class);
876 UInt8 u8Protocol = 0xff;
877 if (irc == kIOReturnSuccess)
878 irc = (*ppIfI)->GetInterfaceProtocol(ppIfI, &u8Protocol);
879 UInt8 cEndpoints = 0;
880 if (irc == kIOReturnSuccess)
881 irc = (*ppIfI)->GetNumEndpoints(ppIfI, &cEndpoints);
882 if (irc == kIOReturnSuccess)
883 {
884 /*
885 * Try seize the interface.
886 */
887 irc = (*ppIfI)->USBInterfaceOpenSeize(ppIfI);
888 if (irc == kIOReturnSuccess)
889 {
890 PUSBPROXYIFOSX pIf = (PUSBPROXYIFOSX)RTMemAllocZ(sizeof(*pIf));
891 if (pIf)
892 {
893 /*
894 * Create the per-interface entry and query the
895 * endpoint data.
896 */
897 /* initialize the entry */
898 pIf->u8Interface = u8Interface;
899 pIf->u8AltSetting = u8AltSetting;
900 pIf->u8Class = u8Class;
901 pIf->u8Protocol = u8Protocol;
902 pIf->cPipes = cEndpoints;
903 pIf->ppIfI = ppIfI;
904
905 /* query pipe/endpoint properties. */
906 rc = usbProxyDarwinGetPipeProperties(pDevOsX, pIf);
907 if (RT_SUCCESS(rc))
908 {
909 /*
910 * Create the async event source and add it to the
911 * default current run loop.
912 * (Later: Add to the worker thread run loop instead.)
913 */
914 irc = (*ppIfI)->CreateInterfaceAsyncEventSource(ppIfI, &pIf->RunLoopSrcRef);
915 if (irc == kIOReturnSuccess)
916 {
917 RTListInit((PRTLISTNODE)&pIf->HeadOfRunLoopLst);
918 usbProxyDarwinAddRunLoopRef(&pIf->HeadOfRunLoopLst,
919 pIf->RunLoopSrcRef);
920
921 /*
922 * Just link the interface into the list and we're good.
923 */
924 pIf->pNext = NULL;
925 Log(("USB: Seized interface %#x (alt=%d prot=%#x class=%#x)\n",
926 u8Interface, u8AltSetting, u8Protocol, u8Class));
927 if (pDevOsX->pIfTail)
928 pDevOsX->pIfTail = pDevOsX->pIfTail->pNext = pIf;
929 else
930 pDevOsX->pIfTail = pDevOsX->pIfHead = pIf;
931 continue;
932 }
933 rc = RTErrConvertFromDarwin(irc);
934 }
935
936 /* failure cleanup. */
937 RTMemFree(pIf);
938 }
939 }
940 else if (irc == kIOReturnExclusiveAccess)
941 {
942 LogRel(("USB: Interface %#x on device '%s' is being used by another process. (prot=%#x class=%#x)\n",
943 u8Interface, pProxyDev->pUsbIns->pszName, u8Protocol, u8Class));
944 rc = VERR_SHARING_VIOLATION;
945 }
946 else
947 {
948 LogRel(("USB: Failed to open interface %#x on device '%s'. (prot=%#x class=%#x) krc=%#x\n",
949 u8Interface, pProxyDev->pUsbIns->pszName, u8Protocol, u8Class, irc));
950 rc = VERR_OPEN_FAILED;
951 }
952 }
953 else
954 {
955 rc = RTErrConvertFromDarwin(irc);
956 LogRel(("USB: Failed to query interface properties on device '%s', irc=%#x.\n",
957 pProxyDev->pUsbIns->pszName, irc));
958 }
959 (*ppIfI)->Release(ppIfI);
960 ppIfI = NULL;
961 }
962 else if (RT_SUCCESS(rc))
963 rc = RTErrConvertFromDarwinCOM(hrc);
964 }
965 else if (RT_SUCCESS(rc))
966 rc = RTErrConvertFromDarwin(krc);
967 if (!fMakeTheBestOfIt)
968 {
969 usbProxyDarwinReleaseAllInterfaces(pDevOsX);
970 break;
971 }
972 } /* iterate */
973 IOObjectRelease(Interfaces);
974 }
975 else if (irc == kIOReturnNoDevice)
976 rc = VERR_VUSB_DEVICE_NOT_ATTACHED;
977 else
978 {
979 AssertMsgFailed(("%#x\n", irc));
980 rc = VERR_GENERAL_FAILURE;
981 }
982
983 RTCritSectLeave(&pDevOsX->CritSect);
984 return rc;
985}
986
987
988/**
989 * Find a particular interface.
990 *
991 * @returns The requested interface or NULL if not found.
992 * @param pDevOsX The darwin proxy device.
993 * @param u8Interface The interface number.
994 */
995static PUSBPROXYIFOSX usbProxyDarwinGetInterface(PUSBPROXYDEVOSX pDevOsX, uint8_t u8Interface)
996{
997 if (!pDevOsX->pIfHead)
998 usbProxyDarwinSeizeAllInterfaces(pDevOsX, true /* make the best out of it */);
999
1000 PUSBPROXYIFOSX pIf;
1001 for (pIf = pDevOsX->pIfHead; pIf; pIf = pIf->pNext)
1002 if (pIf->u8Interface == u8Interface)
1003 return pIf;
1004
1005/* AssertMsgFailed(("Cannot find If#=%d\n", u8Interface)); - the 3rd quickcam interface is capture by the ****ing audio crap. */
1006 return NULL;
1007}
1008
1009
1010/**
1011 * Find a particular endpoint.
1012 *
1013 * @returns The requested interface or NULL if not found.
1014 * @param pDevOsX The darwin proxy device.
1015 * @param u8Endpoint The endpoint.
1016 * @param pu8PipeRef Where to store the darwin pipe ref.
1017 * @param ppPipe Where to store the darwin pipe pointer. (optional)
1018 */
1019static PUSBPROXYIFOSX usbProxyDarwinGetInterfaceForEndpoint(PUSBPROXYDEVOSX pDevOsX, uint8_t u8Endpoint,
1020 uint8_t *pu8PipeRef, PPUSBPROXYPIPEOSX ppPipe)
1021{
1022 if (!pDevOsX->pIfHead)
1023 usbProxyDarwinSeizeAllInterfaces(pDevOsX, true /* make the best out of it */);
1024
1025 PUSBPROXYIFOSX pIf;
1026 for (pIf = pDevOsX->pIfHead; pIf; pIf = pIf->pNext)
1027 {
1028 unsigned i = pIf->cPipes;
1029 while (i-- > 0)
1030 if (pIf->aPipes[i].u8Endpoint == u8Endpoint)
1031 {
1032 *pu8PipeRef = pIf->aPipes[i].u8PipeRef;
1033 if (ppPipe)
1034 *ppPipe = &pIf->aPipes[i];
1035 return pIf;
1036 }
1037 }
1038
1039 AssertMsgFailed(("Cannot find EndPt=%#x\n", u8Endpoint));
1040 return NULL;
1041}
1042
1043
1044/**
1045 * Gets an unsigned 32-bit integer value.
1046 *
1047 * @returns Success indicator (true/false).
1048 * @param DictRef The dictionary.
1049 * @param KeyStrRef The key name.
1050 * @param pu32 Where to store the key value.
1051 */
1052static bool usbProxyDarwinDictGetU32(CFMutableDictionaryRef DictRef, CFStringRef KeyStrRef, uint32_t *pu32)
1053{
1054 CFTypeRef ValRef = CFDictionaryGetValue(DictRef, KeyStrRef);
1055 if (ValRef)
1056 {
1057 if (CFNumberGetValue((CFNumberRef)ValRef, kCFNumberSInt32Type, pu32))
1058 return true;
1059 }
1060 *pu32 = 0;
1061 return false;
1062}
1063
1064
1065/**
1066 * Gets an unsigned 64-bit integer value.
1067 *
1068 * @returns Success indicator (true/false).
1069 * @param DictRef The dictionary.
1070 * @param KeyStrRef The key name.
1071 * @param pu64 Where to store the key value.
1072 */
1073static bool usbProxyDarwinDictGetU64(CFMutableDictionaryRef DictRef, CFStringRef KeyStrRef, uint64_t *pu64)
1074{
1075 CFTypeRef ValRef = CFDictionaryGetValue(DictRef, KeyStrRef);
1076 if (ValRef)
1077 {
1078 if (CFNumberGetValue((CFNumberRef)ValRef, kCFNumberSInt64Type, pu64))
1079 return true;
1080 }
1081 *pu64 = 0;
1082 return false;
1083}
1084
1085
1086static DECLCALLBACK(void) usbProxyDarwinPerformWakeup(void *pInfo)
1087{
1088 RT_NOREF(pInfo);
1089 return;
1090}
1091
1092
1093/* -=-=-=-=-=- The exported methods -=-=-=-=-=- */
1094
1095/**
1096 * Opens the USB Device.
1097 *
1098 * @returns VBox status code.
1099 * @param pProxyDev The device instance.
1100 * @param pszAddress The session id and/or location id of the device to open.
1101 * The format of this string is something iokit.c in Main defines, currently
1102 * it's sequences of "[l|s]=<value>" separated by ";".
1103 */
1104static DECLCALLBACK(int) usbProxyDarwinOpen(PUSBPROXYDEV pProxyDev, const char *pszAddress)
1105{
1106 LogFlow(("usbProxyDarwinOpen: pProxyDev=%p pszAddress=%s\n", pProxyDev, pszAddress));
1107
1108 /*
1109 * Init globals once.
1110 */
1111 int vrc = RTOnce(&g_usbProxyDarwinOnce, usbProxyDarwinInitOnce, NULL);
1112 AssertRCReturn(vrc, vrc);
1113
1114 PUSBPROXYDEVOSX pDevOsX = USBPROXYDEV_2_DATA(pProxyDev, PUSBPROXYDEVOSX);
1115
1116 /*
1117 * The idea here was to create a matching directory with the sessionID
1118 * and locationID included, however this doesn't seem to work. So, we'll
1119 * use the product id and vendor id to limit the set of matching device
1120 * and manually match these two properties. sigh.
1121 * (Btw. vendor and product id must be used *together* apparently.)
1122 *
1123 * Wonder if we could use the entry path? Docs indicates says we must
1124 * use IOServiceGetMatchingServices and I'm not in a mood to explore
1125 * this subject further right now. Maybe check this later.
1126 */
1127 CFMutableDictionaryRef RefMatchingDict = IOServiceMatching(kIOUSBDeviceClassName);
1128 AssertReturn(RefMatchingDict != NULL, VERR_OPEN_FAILED);
1129
1130 uint64_t u64SessionId = 0;
1131 uint32_t u32LocationId = 0;
1132 const char *psz = pszAddress;
1133 do
1134 {
1135 const char chValue = *psz;
1136 AssertReleaseReturn(psz[1] == '=', VERR_INTERNAL_ERROR);
1137 uint64_t u64Value;
1138 int rc = RTStrToUInt64Ex(psz + 2, (char **)&psz, 0, &u64Value);
1139 AssertReleaseRCReturn(rc, rc);
1140 AssertReleaseReturn(!*psz || *psz == ';', rc);
1141 switch (chValue)
1142 {
1143 case 'l':
1144 u32LocationId = (uint32_t)u64Value;
1145 break;
1146 case 's':
1147 u64SessionId = u64Value;
1148 break;
1149 case 'p':
1150 case 'v':
1151 {
1152#if 0 /* Guess what, this doesn't 'ing work either! */
1153 SInt32 i32 = (int16_t)u64Value;
1154 CFNumberRef Num = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &i32);
1155 AssertBreak(Num);
1156 CFDictionarySetValue(RefMatchingDict, chValue == 'p' ? CFSTR(kUSBProductID) : CFSTR(kUSBVendorID), Num);
1157 CFRelease(Num);
1158#endif
1159 break;
1160 }
1161 default:
1162 AssertReleaseMsgFailedReturn(("chValue=%#x\n", chValue), VERR_INTERNAL_ERROR);
1163 }
1164 if (*psz == ';')
1165 psz++;
1166 } while (*psz);
1167
1168 io_iterator_t USBDevices = IO_OBJECT_NULL;
1169 IOReturn irc = IOServiceGetMatchingServices(g_MasterPort, RefMatchingDict, &USBDevices);
1170 AssertMsgReturn(irc == kIOReturnSuccess, ("irc=%#x\n", irc), RTErrConvertFromDarwinIO(irc));
1171 RefMatchingDict = NULL; /* the reference is consumed by IOServiceGetMatchingServices. */
1172
1173 unsigned cMatches = 0;
1174 io_object_t USBDevice;
1175 while ((USBDevice = IOIteratorNext(USBDevices)))
1176 {
1177 cMatches++;
1178 CFMutableDictionaryRef PropsRef = 0;
1179 kern_return_t krc = IORegistryEntryCreateCFProperties(USBDevice, &PropsRef, kCFAllocatorDefault, kNilOptions);
1180 if (krc == KERN_SUCCESS)
1181 {
1182 uint64_t u64CurSessionId;
1183 uint32_t u32CurLocationId;
1184 if ( ( !u64SessionId
1185 || ( usbProxyDarwinDictGetU64(PropsRef, CFSTR("sessionID"), &u64CurSessionId)
1186 && u64CurSessionId == u64SessionId))
1187 && ( !u32LocationId
1188 || ( usbProxyDarwinDictGetU32(PropsRef, CFSTR(kUSBDevicePropertyLocationID), &u32CurLocationId)
1189 && u32CurLocationId == u32LocationId))
1190 )
1191 {
1192 CFRelease(PropsRef);
1193 break;
1194 }
1195 CFRelease(PropsRef);
1196 }
1197 IOObjectRelease(USBDevice);
1198 }
1199 IOObjectRelease(USBDevices);
1200 USBDevices = IO_OBJECT_NULL;
1201 if (!USBDevice)
1202 {
1203 LogRel(("USB: Device '%s' not found (%d pid+vid matches)\n", pszAddress, cMatches));
1204 IOObjectRelease(USBDevices);
1205 return VERR_VUSB_DEVICE_NAME_NOT_FOUND;
1206 }
1207
1208 /*
1209 * Create a plugin interface for the device and query its IOUSBDeviceInterface.
1210 */
1211 SInt32 Score = 0;
1212 IOCFPlugInInterface **ppPlugInInterface = NULL;
1213 irc = IOCreatePlugInInterfaceForService(USBDevice, kIOUSBDeviceUserClientTypeID,
1214 kIOCFPlugInInterfaceID, &ppPlugInInterface, &Score);
1215 if (irc == kIOReturnSuccess)
1216 {
1217 IOUSBDeviceInterface245 **ppDevI = NULL;
1218 HRESULT hrc = (*ppPlugInInterface)->QueryInterface(ppPlugInInterface,
1219 CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID245),
1220 (LPVOID *)&ppDevI);
1221 irc = IODestroyPlugInInterface(ppPlugInInterface); Assert(irc == kIOReturnSuccess);
1222 ppPlugInInterface = NULL;
1223 if (hrc == S_OK)
1224 {
1225 /*
1226 * Try open the device for exclusive access.
1227 * If we fail, we'll try figure out who is using the device and
1228 * convince them to let go of it...
1229 */
1230 irc = (*ppDevI)->USBDeviceReEnumerate(ppDevI, kUSBReEnumerateCaptureDeviceMask);
1231 Log(("USBDeviceReEnumerate (capture) returned irc=%#x\n", irc));
1232
1233 irc = (*ppDevI)->USBDeviceOpenSeize(ppDevI);
1234 if (irc == kIOReturnExclusiveAccess)
1235 {
1236 RTThreadSleep(20);
1237 irc = (*ppDevI)->USBDeviceOpenSeize(ppDevI);
1238 }
1239 if (irc == kIOReturnSuccess)
1240 {
1241 /*
1242 * Init a proxy device instance.
1243 */
1244 RTListInit((PRTLISTNODE)&pDevOsX->HeadOfRunLoopLst);
1245 vrc = RTCritSectInit(&pDevOsX->CritSect);
1246 if (RT_SUCCESS(vrc))
1247 {
1248 pDevOsX->USBDevice = USBDevice;
1249 pDevOsX->ppDevI = ppDevI;
1250 pDevOsX->pProxyDev = pProxyDev;
1251 pDevOsX->pTaxingHead = NULL;
1252 pDevOsX->pTaxingTail = NULL;
1253 pDevOsX->hRunLoopReapingLast = NULL;
1254
1255 /*
1256 * Try seize all the interface.
1257 */
1258 char *pszDummyName = pProxyDev->pUsbIns->pszName;
1259 pProxyDev->pUsbIns->pszName = (char *)pszAddress;
1260 vrc = usbProxyDarwinSeizeAllInterfaces(pDevOsX, false /* give up on failure */);
1261 pProxyDev->pUsbIns->pszName = pszDummyName;
1262 if (RT_SUCCESS(vrc))
1263 {
1264 /*
1265 * Create the async event source and add it to the run loop.
1266 */
1267 irc = (*ppDevI)->CreateDeviceAsyncEventSource(ppDevI, &pDevOsX->RunLoopSrcRef);
1268 if (irc == kIOReturnSuccess)
1269 {
1270 /*
1271 * Determine the active configuration.
1272 * Can cause hangs, so drop it for now.
1273 */
1274 /** @todo test Palm. */
1275 //uint8_t u8Cfg;
1276 //irc = (*ppDevI)->GetConfiguration(ppDevI, &u8Cfg);
1277 if (irc != kIOReturnNoDevice)
1278 {
1279 CFRunLoopSourceContext CtxRunLoopSource;
1280 CtxRunLoopSource.version = 0;
1281 CtxRunLoopSource.info = NULL;
1282 CtxRunLoopSource.retain = NULL;
1283 CtxRunLoopSource.release = NULL;
1284 CtxRunLoopSource.copyDescription = NULL;
1285 CtxRunLoopSource.equal = NULL;
1286 CtxRunLoopSource.hash = NULL;
1287 CtxRunLoopSource.schedule = NULL;
1288 CtxRunLoopSource.cancel = NULL;
1289 CtxRunLoopSource.perform = usbProxyDarwinPerformWakeup;
1290 pDevOsX->hRunLoopSrcWakeRef = CFRunLoopSourceCreate(NULL, 0, &CtxRunLoopSource);
1291 if (CFRunLoopSourceIsValid(pDevOsX->hRunLoopSrcWakeRef))
1292 {
1293 //pProxyDev->iActiveCfg = irc == kIOReturnSuccess ? u8Cfg : -1;
1294 RTListInit(&pDevOsX->HeadOfRunLoopWakeLst);
1295 pProxyDev->iActiveCfg = -1;
1296 pProxyDev->cIgnoreSetConfigs = 1;
1297
1298 usbProxyDarwinAddRunLoopRef(&pDevOsX->HeadOfRunLoopLst, pDevOsX->RunLoopSrcRef);
1299 return VINF_SUCCESS; /* return */
1300 }
1301 else
1302 {
1303 LogRel(("USB: Device '%s' out of memory allocating runloop source\n", pszAddress));
1304 vrc = VERR_NO_MEMORY;
1305 }
1306 }
1307 vrc = VERR_VUSB_DEVICE_NOT_ATTACHED;
1308 }
1309 else
1310 vrc = RTErrConvertFromDarwin(irc);
1311
1312 usbProxyDarwinReleaseAllInterfaces(pDevOsX);
1313 }
1314 /* else: already bitched */
1315
1316 RTCritSectDelete(&pDevOsX->CritSect);
1317 }
1318
1319 irc = (*ppDevI)->USBDeviceClose(ppDevI);
1320 AssertMsg(irc == kIOReturnSuccess, ("%#x\n", irc));
1321 }
1322 else if (irc == kIOReturnExclusiveAccess)
1323 {
1324 LogRel(("USB: Device '%s' is being used by another process\n", pszAddress));
1325 vrc = VERR_SHARING_VIOLATION;
1326 }
1327 else
1328 {
1329 LogRel(("USB: Failed to open device '%s', irc=%#x.\n", pszAddress, irc));
1330 vrc = VERR_OPEN_FAILED;
1331 }
1332 }
1333 else
1334 {
1335 LogRel(("USB: Failed to create plugin interface for device '%s', hrc=%#x.\n", pszAddress, hrc));
1336 vrc = VERR_OPEN_FAILED;
1337 }
1338
1339 (*ppDevI)->Release(ppDevI);
1340 }
1341 else
1342 {
1343 LogRel(("USB: Failed to open device '%s', plug-in creation failed with irc=%#x.\n", pszAddress, irc));
1344 vrc = RTErrConvertFromDarwin(irc);
1345 }
1346
1347 return vrc;
1348}
1349
1350
1351/**
1352 * Closes the proxy device.
1353 */
1354static DECLCALLBACK(void) usbProxyDarwinClose(PUSBPROXYDEV pProxyDev)
1355{
1356 LogFlow(("usbProxyDarwinClose: pProxyDev=%s\n", pProxyDev->pUsbIns->pszName));
1357 PUSBPROXYDEVOSX pDevOsX = USBPROXYDEV_2_DATA(pProxyDev, PUSBPROXYDEVOSX);
1358 AssertPtrReturnVoid(pDevOsX);
1359
1360 /*
1361 * Release interfaces we've laid claim to, then reset the device
1362 * and finally close it.
1363 */
1364 RTCritSectEnter(&pDevOsX->CritSect);
1365 /* ?? */
1366 RTCritSectLeave(&pDevOsX->CritSect);
1367
1368 usbProxyDarwinReleaseAllInterfaces(pDevOsX);
1369
1370 if (pDevOsX->RunLoopSrcRef)
1371 {
1372 int rc = usbProxyDarwinRemoveSourceRefFromAllRunLoops(&pDevOsX->HeadOfRunLoopLst, pDevOsX->RunLoopSrcRef);
1373 AssertRC(rc);
1374
1375 RTListInit((PRTLISTNODE)&pDevOsX->HeadOfRunLoopLst);
1376
1377 CFRelease(pDevOsX->RunLoopSrcRef);
1378 pDevOsX->RunLoopSrcRef = NULL;
1379 }
1380
1381 if (pDevOsX->hRunLoopSrcWakeRef)
1382 {
1383 int rc = usbProxyDarwinRemoveSourceRefFromAllRunLoops(&pDevOsX->HeadOfRunLoopWakeLst, pDevOsX->hRunLoopSrcWakeRef);
1384 AssertRC(rc);
1385
1386 RTListInit((PRTLISTNODE)&pDevOsX->HeadOfRunLoopWakeLst);
1387
1388 CFRelease(pDevOsX->hRunLoopSrcWakeRef);
1389 pDevOsX->hRunLoopSrcWakeRef = NULL;
1390 }
1391
1392 IOReturn irc = (*pDevOsX->ppDevI)->ResetDevice(pDevOsX->ppDevI);
1393
1394 irc = (*pDevOsX->ppDevI)->USBDeviceClose(pDevOsX->ppDevI);
1395 if (irc != kIOReturnSuccess && irc != kIOReturnNoDevice)
1396 {
1397 LogRel(("USB: USBDeviceClose -> %#x\n", irc));
1398 AssertMsgFailed(("irc=%#x\n", irc));
1399 }
1400
1401 irc = (*pDevOsX->ppDevI)->USBDeviceReEnumerate(pDevOsX->ppDevI, kUSBReEnumerateReleaseDeviceMask);
1402 Log(("USBDeviceReEnumerate (release) returned irc=%#x\n", irc));
1403
1404 (*pDevOsX->ppDevI)->Release(pDevOsX->ppDevI);
1405 pDevOsX->ppDevI = NULL;
1406 kern_return_t krc = IOObjectRelease(pDevOsX->USBDevice); Assert(krc == KERN_SUCCESS); NOREF(krc);
1407 pDevOsX->USBDevice = IO_OBJECT_NULL;
1408 pDevOsX->pProxyDev = NULL;
1409
1410 /*
1411 * Free all the resources.
1412 */
1413 RTCritSectDelete(&pDevOsX->CritSect);
1414
1415 PUSBPROXYURBOSX pUrbOsX;
1416 while ((pUrbOsX = pDevOsX->pFreeHead) != NULL)
1417 {
1418 pDevOsX->pFreeHead = pUrbOsX->pNext;
1419 RTMemFree(pUrbOsX);
1420 }
1421
1422 LogFlow(("usbProxyDarwinClose: returns\n"));
1423}
1424
1425
1426/** @interface_method_impl{USBPROXYBACK,pfnReset}*/
1427static DECLCALLBACK(int) usbProxyDarwinReset(PUSBPROXYDEV pProxyDev, bool fResetOnLinux)
1428{
1429 RT_NOREF(fResetOnLinux);
1430 PUSBPROXYDEVOSX pDevOsX = USBPROXYDEV_2_DATA(pProxyDev, PUSBPROXYDEVOSX);
1431 LogFlow(("usbProxyDarwinReset: pProxyDev=%s\n", pProxyDev->pUsbIns->pszName));
1432
1433 IOReturn irc = (*pDevOsX->ppDevI)->ResetDevice(pDevOsX->ppDevI);
1434 int rc;
1435 if (irc == kIOReturnSuccess)
1436 {
1437 /** @todo Some docs say that some drivers will do a default config, check this out ... */
1438 pProxyDev->cIgnoreSetConfigs = 0;
1439 pProxyDev->iActiveCfg = -1;
1440
1441 rc = VINF_SUCCESS;
1442 }
1443 else if (irc == kIOReturnNoDevice)
1444 rc = VERR_VUSB_DEVICE_NOT_ATTACHED;
1445 else
1446 {
1447 AssertMsgFailed(("irc=%#x\n", irc));
1448 rc = VERR_GENERAL_FAILURE;
1449 }
1450
1451 LogFlow(("usbProxyDarwinReset: returns success %Rrc\n", rc));
1452 return rc;
1453}
1454
1455
1456/**
1457 * SET_CONFIGURATION.
1458 *
1459 * The caller makes sure that it's not called first time after open or reset
1460 * with the active interface.
1461 *
1462 * @returns success indicator.
1463 * @param pProxyDev The device instance data.
1464 * @param iCfg The configuration to set.
1465 */
1466static DECLCALLBACK(int) usbProxyDarwinSetConfig(PUSBPROXYDEV pProxyDev, int iCfg)
1467{
1468 PUSBPROXYDEVOSX pDevOsX = USBPROXYDEV_2_DATA(pProxyDev, PUSBPROXYDEVOSX);
1469 LogFlow(("usbProxyDarwinSetConfig: pProxyDev=%s cfg=%#x\n",
1470 pProxyDev->pUsbIns->pszName, iCfg));
1471
1472 IOReturn irc = (*pDevOsX->ppDevI)->SetConfiguration(pDevOsX->ppDevI, (uint8_t)iCfg);
1473 if (irc != kIOReturnSuccess)
1474 {
1475 Log(("usbProxyDarwinSetConfig: Set configuration -> %#x\n", irc));
1476 return RTErrConvertFromDarwin(irc);
1477 }
1478
1479 usbProxyDarwinReleaseAllInterfaces(pDevOsX);
1480 usbProxyDarwinSeizeAllInterfaces(pDevOsX, true /* make the best out of it */);
1481 return VINF_SUCCESS;
1482}
1483
1484
1485/**
1486 * Claims an interface.
1487 *
1488 * This is a stub on Darwin since we release/claim all interfaces at
1489 * open/reset/setconfig time.
1490 *
1491 * @returns success indicator (always VINF_SUCCESS).
1492 */
1493static DECLCALLBACK(int) usbProxyDarwinClaimInterface(PUSBPROXYDEV pProxyDev, int iIf)
1494{
1495 RT_NOREF(pProxyDev, iIf);
1496 return VINF_SUCCESS;
1497}
1498
1499
1500/**
1501 * Releases an interface.
1502 *
1503 * This is a stub on Darwin since we release/claim all interfaces at
1504 * open/reset/setconfig time.
1505 *
1506 * @returns success indicator.
1507 */
1508static DECLCALLBACK(int) usbProxyDarwinReleaseInterface(PUSBPROXYDEV pProxyDev, int iIf)
1509{
1510 RT_NOREF(pProxyDev, iIf);
1511 return VINF_SUCCESS;
1512}
1513
1514
1515/**
1516 * SET_INTERFACE.
1517 *
1518 * @returns success indicator.
1519 */
1520static DECLCALLBACK(int) usbProxyDarwinSetInterface(PUSBPROXYDEV pProxyDev, int iIf, int iAlt)
1521{
1522 PUSBPROXYDEVOSX pDevOsX = USBPROXYDEV_2_DATA(pProxyDev, PUSBPROXYDEVOSX);
1523 IOReturn irc = kIOReturnSuccess;
1524 PUSBPROXYIFOSX pIf = usbProxyDarwinGetInterface(pDevOsX, iIf);
1525 LogFlow(("usbProxyDarwinSetInterface: pProxyDev=%s iIf=%#x iAlt=%#x iCurAlt=%#x\n",
1526 pProxyDev->pUsbIns->pszName, iIf, iAlt, pIf ? pIf->u8AltSetting : 0xbeef));
1527 if (pIf)
1528 {
1529 /* Avoid SetAlternateInterface when possible as it will recreate the pipes. */
1530 if (iAlt != pIf->u8AltSetting)
1531 {
1532 irc = (*pIf->ppIfI)->SetAlternateInterface(pIf->ppIfI, iAlt);
1533 if (irc == kIOReturnSuccess)
1534 {
1535 usbProxyDarwinGetPipeProperties(pDevOsX, pIf);
1536 return VINF_SUCCESS;
1537 }
1538 }
1539 else
1540 {
1541 /*
1542 * Just send the request anyway?
1543 */
1544 IOUSBDevRequest Req;
1545 Req.bmRequestType = 0x01;
1546 Req.bRequest = 0x0b; /* SET_INTERFACE */
1547 Req.wIndex = iIf;
1548 Req.wValue = iAlt;
1549 Req.wLength = 0;
1550 Req.wLenDone = 0;
1551 Req.pData = NULL;
1552 irc = (*pDevOsX->ppDevI)->DeviceRequest(pDevOsX->ppDevI, &Req);
1553 Log(("usbProxyDarwinSetInterface: SET_INTERFACE(%d,%d) -> irc=%#x\n", iIf, iAlt, irc));
1554 return VINF_SUCCESS;
1555 }
1556 }
1557
1558 LogFlow(("usbProxyDarwinSetInterface: pProxyDev=%s eiIf=%#x iAlt=%#x - failure - pIf=%p irc=%#x\n",
1559 pProxyDev->pUsbIns->pszName, iIf, iAlt, pIf, irc));
1560 return RTErrConvertFromDarwin(irc);
1561}
1562
1563
1564/**
1565 * Clears the halted endpoint 'EndPt'.
1566 */
1567static DECLCALLBACK(int) usbProxyDarwinClearHaltedEp(PUSBPROXYDEV pProxyDev, unsigned int EndPt)
1568{
1569 PUSBPROXYDEVOSX pDevOsX = USBPROXYDEV_2_DATA(pProxyDev, PUSBPROXYDEVOSX);
1570 LogFlow(("usbProxyDarwinClearHaltedEp: pProxyDev=%s EndPt=%#x\n", pProxyDev->pUsbIns->pszName, EndPt));
1571
1572 /*
1573 * Clearing the zero control pipe doesn't make sense and isn't
1574 * supported by the API. Just ignore it.
1575 */
1576 if (EndPt == 0)
1577 return VINF_SUCCESS;
1578
1579 /*
1580 * Find the interface/pipe combination and invoke the ClearPipeStallBothEnds
1581 * method. (The ResetPipe and ClearPipeStall methods will not send the
1582 * CLEAR_FEATURE(ENDPOINT_HALT) request that this method implements.)
1583 */
1584 IOReturn irc = kIOReturnSuccess;
1585 uint8_t u8PipeRef;
1586 PUSBPROXYIFOSX pIf = usbProxyDarwinGetInterfaceForEndpoint(pDevOsX, EndPt, &u8PipeRef, NULL);
1587 if (pIf)
1588 {
1589 irc = (*pIf->ppIfI)->ClearPipeStallBothEnds(pIf->ppIfI, u8PipeRef);
1590 if (irc == kIOReturnSuccess)
1591 return VINF_SUCCESS;
1592 AssertMsg(irc == kIOReturnNoDevice || irc == kIOReturnNotResponding, ("irc=#x (control pipe?)\n", irc));
1593 }
1594
1595 LogFlow(("usbProxyDarwinClearHaltedEp: pProxyDev=%s EndPt=%#x - failure - pIf=%p irc=%#x\n",
1596 pProxyDev->pUsbIns->pszName, EndPt, pIf, irc));
1597 return RTErrConvertFromDarwin(irc);
1598}
1599
1600
1601/**
1602 * @interface_method_impl{USBPROXYBACK,pfnUrbQueue}
1603 */
1604static DECLCALLBACK(int) usbProxyDarwinUrbQueue(PUSBPROXYDEV pProxyDev, PVUSBURB pUrb)
1605{
1606 PUSBPROXYDEVOSX pDevOsX = USBPROXYDEV_2_DATA(pProxyDev, PUSBPROXYDEVOSX);
1607 LogFlow(("%s: usbProxyDarwinUrbQueue: pProxyDev=%s pUrb=%p EndPt=%d cbData=%d\n",
1608 pUrb->pszDesc, pProxyDev->pUsbIns->pszName, pUrb, pUrb->EndPt, pUrb->cbData));
1609
1610 /*
1611 * Find the target interface / pipe.
1612 */
1613 uint8_t u8PipeRef = 0xff;
1614 PUSBPROXYIFOSX pIf = NULL;
1615 PUSBPROXYPIPEOSX pPipe = NULL;
1616 if (pUrb->EndPt)
1617 {
1618 /* Make sure the interface is there. */
1619 const uint8_t EndPt = pUrb->EndPt | (pUrb->enmDir == VUSBDIRECTION_IN ? 0x80 : 0);
1620 pIf = usbProxyDarwinGetInterfaceForEndpoint(pDevOsX, EndPt, &u8PipeRef, &pPipe);
1621 if (!pIf)
1622 {
1623 LogFlow(("%s: usbProxyDarwinUrbQueue: pProxyDev=%s EndPt=%d cbData=%d - can't find interface / pipe!!!\n",
1624 pUrb->pszDesc, pProxyDev->pUsbIns->pszName, pUrb->EndPt, pUrb->cbData));
1625 return VERR_NOT_FOUND;
1626 }
1627 }
1628 /* else: pIf == NULL -> default control pipe.*/
1629
1630 /*
1631 * Allocate a Darwin urb.
1632 */
1633 PUSBPROXYURBOSX pUrbOsX = usbProxyDarwinUrbAlloc(pDevOsX);
1634 if (!pUrbOsX)
1635 return VERR_NO_MEMORY;
1636
1637 pUrbOsX->u64SubmitTS = RTTimeMilliTS();
1638 pUrbOsX->pVUsbUrb = pUrb;
1639 pUrbOsX->pDevOsX = pDevOsX;
1640 pUrbOsX->enmType = pUrb->enmType;
1641
1642 /*
1643 * Submit the request.
1644 */
1645 IOReturn irc = kIOReturnError;
1646 switch (pUrb->enmType)
1647 {
1648 case VUSBXFERTYPE_MSG:
1649 {
1650 AssertMsgBreak(pUrb->cbData >= sizeof(VUSBSETUP), ("cbData=%d\n", pUrb->cbData));
1651 PVUSBSETUP pSetup = (PVUSBSETUP)&pUrb->abData[0];
1652 pUrbOsX->u.ControlMsg.bmRequestType = pSetup->bmRequestType;
1653 pUrbOsX->u.ControlMsg.bRequest = pSetup->bRequest;
1654 pUrbOsX->u.ControlMsg.wValue = pSetup->wValue;
1655 pUrbOsX->u.ControlMsg.wIndex = pSetup->wIndex;
1656 pUrbOsX->u.ControlMsg.wLength = pSetup->wLength;
1657 pUrbOsX->u.ControlMsg.pData = pSetup + 1;
1658 pUrbOsX->u.ControlMsg.wLenDone = pSetup->wLength;
1659
1660 if (pIf)
1661 irc = (*pIf->ppIfI)->ControlRequestAsync(pIf->ppIfI, u8PipeRef, &pUrbOsX->u.ControlMsg,
1662 usbProxyDarwinUrbAsyncComplete, pUrbOsX);
1663 else
1664 irc = (*pDevOsX->ppDevI)->DeviceRequestAsync(pDevOsX->ppDevI, &pUrbOsX->u.ControlMsg,
1665 usbProxyDarwinUrbAsyncComplete, pUrbOsX);
1666 break;
1667 }
1668
1669 case VUSBXFERTYPE_BULK:
1670 case VUSBXFERTYPE_INTR:
1671 {
1672 AssertBreak(pIf);
1673 Assert(pUrb->enmDir == VUSBDIRECTION_IN || pUrb->enmDir == VUSBDIRECTION_OUT);
1674 if (pUrb->enmDir == VUSBDIRECTION_OUT)
1675 irc = (*pIf->ppIfI)->WritePipeAsync(pIf->ppIfI, u8PipeRef, pUrb->abData, pUrb->cbData,
1676 usbProxyDarwinUrbAsyncComplete, pUrbOsX);
1677 else
1678 irc = (*pIf->ppIfI)->ReadPipeAsync(pIf->ppIfI, u8PipeRef, pUrb->abData, pUrb->cbData,
1679 usbProxyDarwinUrbAsyncComplete, pUrbOsX);
1680
1681 break;
1682 }
1683
1684 case VUSBXFERTYPE_ISOC:
1685 {
1686 AssertBreak(pIf);
1687 Assert(pUrb->enmDir == VUSBDIRECTION_IN || pUrb->enmDir == VUSBDIRECTION_OUT);
1688
1689#ifdef USE_LOW_LATENCY_API
1690 /* Allocate an isochronous buffer and copy over the data. */
1691 AssertBreak(pUrb->cbData <= 8192);
1692 int rc = usbProxyDarwinUrbAllocIsocBuf(pUrbOsX, pIf);
1693 AssertRCBreak(rc);
1694 if (pUrb->enmDir == VUSBDIRECTION_OUT)
1695 memcpy(pUrbOsX->u.Isoc.pBuf->pvBuf, pUrb->abData, pUrb->cbData);
1696 else
1697 memset(pUrbOsX->u.Isoc.pBuf->pvBuf, 0xfe, pUrb->cbData);
1698#endif
1699
1700 /* Get the current frame number (+2) and make sure it doesn't
1701 overlap with the previous request. See WARNING in
1702 ApplUSBUHCI::CreateIsochTransfer for details on the +2. */
1703 UInt64 FrameNo;
1704 AbsoluteTime FrameTime;
1705 irc = (*pIf->ppIfI)->GetBusFrameNumber(pIf->ppIfI, &FrameNo, &FrameTime);
1706 AssertMsg(irc == kIOReturnSuccess, ("GetBusFrameNumber -> %#x\n", irc));
1707 FrameNo += 2;
1708 if (FrameNo <= pPipe->u64NextFrameNo)
1709 FrameNo = pPipe->u64NextFrameNo;
1710
1711 for (unsigned j = 0; ; j++)
1712 {
1713 unsigned i;
1714 for (i = 0; i < pUrb->cIsocPkts; i++)
1715 {
1716 pUrbOsX->u.Isoc.aFrames[i].frReqCount = pUrb->aIsocPkts[i].cb;
1717 pUrbOsX->u.Isoc.aFrames[i].frActCount = 0;
1718 pUrbOsX->u.Isoc.aFrames[i].frStatus = kIOUSBNotSent1Err;
1719#ifdef USE_LOW_LATENCY_API
1720 pUrbOsX->u.Isoc.aFrames[i].frTimeStamp.hi = 0;
1721 pUrbOsX->u.Isoc.aFrames[i].frTimeStamp.lo = 0;
1722#endif
1723 }
1724 for (; i < RT_ELEMENTS(pUrbOsX->u.Isoc.aFrames); i++)
1725 {
1726 pUrbOsX->u.Isoc.aFrames[i].frReqCount = 0;
1727 pUrbOsX->u.Isoc.aFrames[i].frActCount = 0;
1728 pUrbOsX->u.Isoc.aFrames[i].frStatus = kIOReturnError;
1729#ifdef USE_LOW_LATENCY_API
1730 pUrbOsX->u.Isoc.aFrames[i].frTimeStamp.hi = 0;
1731 pUrbOsX->u.Isoc.aFrames[i].frTimeStamp.lo = 0;
1732#endif
1733 }
1734
1735#ifdef USE_LOW_LATENCY_API
1736 if (pUrb->enmDir == VUSBDIRECTION_OUT)
1737 irc = (*pIf->ppIfI)->LowLatencyWriteIsochPipeAsync(pIf->ppIfI, u8PipeRef,
1738 pUrbOsX->u.Isoc.pBuf->pvBuf, FrameNo, pUrb->cIsocPkts, 0, pUrbOsX->u.Isoc.aFrames,
1739 usbProxyDarwinUrbAsyncComplete, pUrbOsX);
1740 else
1741 irc = (*pIf->ppIfI)->LowLatencyReadIsochPipeAsync(pIf->ppIfI, u8PipeRef,
1742 pUrbOsX->u.Isoc.pBuf->pvBuf, FrameNo, pUrb->cIsocPkts, 0, pUrbOsX->u.Isoc.aFrames,
1743 usbProxyDarwinUrbAsyncComplete, pUrbOsX);
1744#else
1745 if (pUrb->enmDir == VUSBDIRECTION_OUT)
1746 irc = (*pIf->ppIfI)->WriteIsochPipeAsync(pIf->ppIfI, u8PipeRef,
1747 pUrb->abData, FrameNo, pUrb->cIsocPkts, &pUrbOsX->u.Isoc.aFrames[0],
1748 usbProxyDarwinUrbAsyncComplete, pUrbOsX);
1749 else
1750 irc = (*pIf->ppIfI)->ReadIsochPipeAsync(pIf->ppIfI, u8PipeRef,
1751 pUrb->abData, FrameNo, pUrb->cIsocPkts, &pUrbOsX->u.Isoc.aFrames[0],
1752 usbProxyDarwinUrbAsyncComplete, pUrbOsX);
1753#endif
1754 if ( irc != kIOReturnIsoTooOld
1755 || j >= 5)
1756 {
1757 Log(("%s: usbProxyDarwinUrbQueue: isoc: u64NextFrameNo=%RX64 FrameNo=%RX64 #Frames=%d j=%d (pipe=%d)\n",
1758 pUrb->pszDesc, pPipe->u64NextFrameNo, FrameNo, pUrb->cIsocPkts, j, u8PipeRef));
1759 if (irc == kIOReturnSuccess)
1760 {
1761 if (pPipe->fIsFullSpeed)
1762 pPipe->u64NextFrameNo = FrameNo + pUrb->cIsocPkts;
1763 else
1764 pPipe->u64NextFrameNo = FrameNo + 1;
1765 }
1766 break;
1767 }
1768
1769 /* try again... */
1770 irc = (*pIf->ppIfI)->GetBusFrameNumber(pIf->ppIfI, &FrameNo, &FrameTime);
1771 if (FrameNo <= pPipe->u64NextFrameNo)
1772 FrameNo = pPipe->u64NextFrameNo;
1773 FrameNo += j;
1774 }
1775 break;
1776 }
1777
1778 default:
1779 AssertMsgFailed(("%s: enmType=%#x\n", pUrb->pszDesc, pUrb->enmType));
1780 break;
1781 }
1782
1783 /*
1784 * Success?
1785 */
1786 if (RT_LIKELY(irc == kIOReturnSuccess))
1787 {
1788 Log(("%s: usbProxyDarwinUrbQueue: success\n", pUrb->pszDesc));
1789 return VINF_SUCCESS;
1790 }
1791 switch (irc)
1792 {
1793 case kIOUSBPipeStalled:
1794 {
1795 /* Increment in flight counter because the completion handler will decrease it always. */
1796 usbProxyDarwinUrbAsyncComplete(pUrbOsX, kIOUSBPipeStalled, 0);
1797 Log(("%s: usbProxyDarwinUrbQueue: pProxyDev=%s EndPt=%d cbData=%d - failed irc=%#x! (stall)\n",
1798 pUrb->pszDesc, pProxyDev->pUsbIns->pszName, pUrb->EndPt, pUrb->cbData, irc));
1799 return VINF_SUCCESS;
1800 }
1801 }
1802
1803 usbProxyDarwinUrbFree(pDevOsX, pUrbOsX);
1804 Log(("%s: usbProxyDarwinUrbQueue: pProxyDev=%s EndPt=%d cbData=%d - failed irc=%#x!\n",
1805 pUrb->pszDesc, pProxyDev->pUsbIns->pszName, pUrb->EndPt, pUrb->cbData, irc));
1806 return RTErrConvertFromDarwin(irc);
1807}
1808
1809
1810/**
1811 * Reap URBs in-flight on a device.
1812 *
1813 * @returns Pointer to a completed URB.
1814 * @returns NULL if no URB was completed.
1815 * @param pProxyDev The device.
1816 * @param cMillies Number of milliseconds to wait. Use 0 to not wait at all.
1817 */
1818static DECLCALLBACK(PVUSBURB) usbProxyDarwinUrbReap(PUSBPROXYDEV pProxyDev, RTMSINTERVAL cMillies)
1819{
1820 PVUSBURB pUrb = NULL;
1821 PUSBPROXYDEVOSX pDevOsX = USBPROXYDEV_2_DATA(pProxyDev, PUSBPROXYDEVOSX);
1822 CFRunLoopRef hRunLoopRef = CFRunLoopGetCurrent();
1823
1824 Assert(!pDevOsX->hRunLoopReaping);
1825
1826 /*
1827 * If the last seen runloop for reaping differs we have to check whether the
1828 * the runloop sources are in the new runloop.
1829 */
1830 if (pDevOsX->hRunLoopReapingLast != hRunLoopRef)
1831 {
1832 RTCritSectEnter(&pDevOsX->CritSect);
1833
1834 /* Every pipe. */
1835 if (!pDevOsX->pIfHead)
1836 usbProxyDarwinSeizeAllInterfaces(pDevOsX, true /* make the best out of it */);
1837
1838 PUSBPROXYIFOSX pIf;
1839 for (pIf = pDevOsX->pIfHead; pIf; pIf = pIf->pNext)
1840 {
1841 if (!CFRunLoopContainsSource(hRunLoopRef, pIf->RunLoopSrcRef, g_pRunLoopMode))
1842 usbProxyDarwinAddRunLoopRef(&pIf->HeadOfRunLoopLst, pIf->RunLoopSrcRef);
1843 }
1844
1845 /* Default control pipe. */
1846 if (!CFRunLoopContainsSource(hRunLoopRef, pDevOsX->RunLoopSrcRef, g_pRunLoopMode))
1847 usbProxyDarwinAddRunLoopRef(&pDevOsX->HeadOfRunLoopLst, pDevOsX->RunLoopSrcRef);
1848
1849 /* Runloop wakeup source. */
1850 if (!CFRunLoopContainsSource(hRunLoopRef, pDevOsX->hRunLoopSrcWakeRef, g_pRunLoopMode))
1851 usbProxyDarwinAddRunLoopRef(&pDevOsX->HeadOfRunLoopWakeLst, pDevOsX->hRunLoopSrcWakeRef);
1852 RTCritSectLeave(&pDevOsX->CritSect);
1853
1854 pDevOsX->hRunLoopReapingLast = hRunLoopRef;
1855 }
1856
1857 ASMAtomicXchgPtr((void * volatile *)&pDevOsX->hRunLoopReaping, hRunLoopRef);
1858
1859 if (ASMAtomicXchgBool(&pDevOsX->fReapingThreadWake, false))
1860 {
1861 /* Return immediately. */
1862 ASMAtomicXchgPtr((void * volatile *)&pDevOsX->hRunLoopReaping, NULL);
1863 return NULL;
1864 }
1865
1866 /*
1867 * Excercise the runloop until we get an URB or we time out.
1868 */
1869 if ( !pDevOsX->pTaxingHead
1870 && cMillies)
1871 CFRunLoopRunInMode(g_pRunLoopMode, cMillies / 1000.0, true);
1872
1873 ASMAtomicXchgPtr((void * volatile *)&pDevOsX->hRunLoopReaping, NULL);
1874 ASMAtomicXchgBool(&pDevOsX->fReapingThreadWake, false);
1875
1876 /*
1877 * Any URBs pending delivery?
1878 */
1879 while ( pDevOsX->pTaxingHead
1880 && !pUrb)
1881 {
1882 RTCritSectEnter(&pDevOsX->CritSect);
1883
1884 PUSBPROXYURBOSX pUrbOsX = pDevOsX->pTaxingHead;
1885 if (pUrbOsX)
1886 {
1887 /*
1888 * Remove from the taxing list.
1889 */
1890 if (pUrbOsX->pNext)
1891 pUrbOsX->pNext->pPrev = pUrbOsX->pPrev;
1892 else if (pDevOsX->pTaxingTail == pUrbOsX)
1893 pDevOsX->pTaxingTail = pUrbOsX->pPrev;
1894
1895 if (pUrbOsX->pPrev)
1896 pUrbOsX->pPrev->pNext = pUrbOsX->pNext;
1897 else if (pDevOsX->pTaxingHead == pUrbOsX)
1898 pDevOsX->pTaxingHead = pUrbOsX->pNext;
1899 else
1900 AssertFailed();
1901
1902 pUrb = pUrbOsX->pVUsbUrb;
1903 if (pUrb)
1904 {
1905 pUrb->Dev.pvPrivate = NULL;
1906 usbProxyDarwinUrbFree(pDevOsX, pUrbOsX);
1907 }
1908 }
1909 RTCritSectLeave(&pDevOsX->CritSect);
1910 }
1911
1912 if (pUrb)
1913 LogFlowFunc(("LEAVE: %s: pProxyDev=%s returns %p\n", pUrb->pszDesc, pProxyDev->pUsbIns->pszName, pUrb));
1914 else
1915 LogFlowFunc(("LEAVE: NULL pProxyDev=%s returns NULL\n", pProxyDev->pUsbIns->pszName));
1916
1917 return pUrb;
1918}
1919
1920
1921/**
1922 * Cancels a URB.
1923 *
1924 * The URB requires reaping, so we don't change its state.
1925 *
1926 * @remark There isn't any way to cancel a specific async request
1927 * on darwin. The interface only supports the aborting of
1928 * all URBs pending on an interface / pipe pair. Provided
1929 * the card does the URB cancelling before submitting new
1930 * requests, we should probably be fine...
1931 */
1932static DECLCALLBACK(int) usbProxyDarwinUrbCancel(PUSBPROXYDEV pProxyDev, PVUSBURB pUrb)
1933{
1934 PUSBPROXYDEVOSX pDevOsX = USBPROXYDEV_2_DATA(pProxyDev, PUSBPROXYDEVOSX);
1935 LogFlow(("%s: usbProxyDarwinUrbCancel: pProxyDev=%s EndPt=%d\n",
1936 pUrb->pszDesc, pProxyDev->pUsbIns->pszName, pUrb->EndPt));
1937
1938 /*
1939 * Determine the interface / endpoint ref and invoke AbortPipe.
1940 */
1941 IOReturn irc = kIOReturnSuccess;
1942 if (!pUrb->EndPt)
1943 irc = (*pDevOsX->ppDevI)->USBDeviceAbortPipeZero(pDevOsX->ppDevI);
1944 else
1945 {
1946 uint8_t u8PipeRef;
1947 const uint8_t EndPt = pUrb->EndPt | (pUrb->enmDir == VUSBDIRECTION_IN ? 0x80 : 0);
1948 PUSBPROXYIFOSX pIf = usbProxyDarwinGetInterfaceForEndpoint(pDevOsX, EndPt, &u8PipeRef, NULL);
1949 if (pIf)
1950 irc = (*pIf->ppIfI)->AbortPipe(pIf->ppIfI, u8PipeRef);
1951 else /* this may happen if a device reset, set configuration or set interface has been performed. */
1952 Log(("usbProxyDarwinUrbCancel: pProxyDev=%s pUrb=%p EndPt=%d - cannot find the interface / pipe!\n",
1953 pProxyDev->pUsbIns->pszName, pUrb, pUrb->EndPt));
1954 }
1955
1956 int rc = VINF_SUCCESS;
1957 if (irc != kIOReturnSuccess)
1958 {
1959 Log(("usbProxyDarwinUrbCancel: pProxyDev=%s pUrb=%p EndPt=%d -> %#x!\n",
1960 pProxyDev->pUsbIns->pszName, pUrb, pUrb->EndPt, irc));
1961 rc = RTErrConvertFromDarwin(irc);
1962 }
1963
1964 return rc;
1965}
1966
1967
1968static DECLCALLBACK(int) usbProxyDarwinWakeup(PUSBPROXYDEV pProxyDev)
1969{
1970 PUSBPROXYDEVOSX pDevOsX = USBPROXYDEV_2_DATA(pProxyDev, PUSBPROXYDEVOSX);
1971
1972 LogFlow(("usbProxyDarwinWakeup: pProxyDev=%p\n", pProxyDev));
1973
1974 ASMAtomicXchgBool(&pDevOsX->fReapingThreadWake, true);
1975 usbProxyDarwinReaperKick(pDevOsX);
1976 return VINF_SUCCESS;
1977}
1978
1979
1980/**
1981 * The Darwin USB Proxy Backend.
1982 */
1983extern const USBPROXYBACK g_USBProxyDeviceHost =
1984{
1985 /* pszName */
1986 "host",
1987 /* cbBackend */
1988 sizeof(USBPROXYDEVOSX),
1989 usbProxyDarwinOpen,
1990 NULL,
1991 usbProxyDarwinClose,
1992 usbProxyDarwinReset,
1993 usbProxyDarwinSetConfig,
1994 usbProxyDarwinClaimInterface,
1995 usbProxyDarwinReleaseInterface,
1996 usbProxyDarwinSetInterface,
1997 usbProxyDarwinClearHaltedEp,
1998 usbProxyDarwinUrbQueue,
1999 usbProxyDarwinUrbCancel,
2000 usbProxyDarwinUrbReap,
2001 usbProxyDarwinWakeup,
2002 0
2003};
2004
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