VirtualBox

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

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

Devices: Must not use PAGE_SIZE, PAGE_SHIFT, PAGE_OFFSET_MASK, PAGE_ADDRESS or PHYS_PAGE_ADDRESS here either. bugref:9898

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 74.1 KB
Line 
1/* $Id: USBProxyDevice-darwin.cpp 93944 2022-02-24 21:15:14Z 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 * @param pvBackend Backend specific pointer, unused for the Darwin backend.
1104 */
1105static DECLCALLBACK(int) usbProxyDarwinOpen(PUSBPROXYDEV pProxyDev, const char *pszAddress, void *pvBackend)
1106{
1107 RT_NOREF(pvBackend);
1108 LogFlow(("usbProxyDarwinOpen: pProxyDev=%p pszAddress=%s\n", pProxyDev, pszAddress));
1109
1110 /*
1111 * Init globals once.
1112 */
1113 int vrc = RTOnce(&g_usbProxyDarwinOnce, usbProxyDarwinInitOnce, NULL);
1114 AssertRCReturn(vrc, vrc);
1115
1116 PUSBPROXYDEVOSX pDevOsX = USBPROXYDEV_2_DATA(pProxyDev, PUSBPROXYDEVOSX);
1117
1118 /*
1119 * The idea here was to create a matching directory with the sessionID
1120 * and locationID included, however this doesn't seem to work. So, we'll
1121 * use the product id and vendor id to limit the set of matching device
1122 * and manually match these two properties. sigh.
1123 * (Btw. vendor and product id must be used *together* apparently.)
1124 *
1125 * Wonder if we could use the entry path? Docs indicates says we must
1126 * use IOServiceGetMatchingServices and I'm not in a mood to explore
1127 * this subject further right now. Maybe check this later.
1128 */
1129 CFMutableDictionaryRef RefMatchingDict = IOServiceMatching(kIOUSBDeviceClassName);
1130 AssertReturn(RefMatchingDict != NULL, VERR_OPEN_FAILED);
1131
1132 uint64_t u64SessionId = 0;
1133 uint32_t u32LocationId = 0;
1134 const char *psz = pszAddress;
1135 do
1136 {
1137 const char chValue = *psz;
1138 AssertReleaseReturn(psz[1] == '=', VERR_INTERNAL_ERROR);
1139 uint64_t u64Value;
1140 int rc = RTStrToUInt64Ex(psz + 2, (char **)&psz, 0, &u64Value);
1141 AssertReleaseRCReturn(rc, rc);
1142 AssertReleaseReturn(!*psz || *psz == ';', rc);
1143 switch (chValue)
1144 {
1145 case 'l':
1146 u32LocationId = (uint32_t)u64Value;
1147 break;
1148 case 's':
1149 u64SessionId = u64Value;
1150 break;
1151 case 'p':
1152 case 'v':
1153 {
1154#if 0 /* Guess what, this doesn't 'ing work either! */
1155 SInt32 i32 = (int16_t)u64Value;
1156 CFNumberRef Num = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &i32);
1157 AssertBreak(Num);
1158 CFDictionarySetValue(RefMatchingDict, chValue == 'p' ? CFSTR(kUSBProductID) : CFSTR(kUSBVendorID), Num);
1159 CFRelease(Num);
1160#endif
1161 break;
1162 }
1163 default:
1164 AssertReleaseMsgFailedReturn(("chValue=%#x\n", chValue), VERR_INTERNAL_ERROR);
1165 }
1166 if (*psz == ';')
1167 psz++;
1168 } while (*psz);
1169
1170 io_iterator_t USBDevices = IO_OBJECT_NULL;
1171 IOReturn irc = IOServiceGetMatchingServices(g_MasterPort, RefMatchingDict, &USBDevices);
1172 AssertMsgReturn(irc == kIOReturnSuccess, ("irc=%#x\n", irc), RTErrConvertFromDarwinIO(irc));
1173 RefMatchingDict = NULL; /* the reference is consumed by IOServiceGetMatchingServices. */
1174
1175 unsigned cMatches = 0;
1176 io_object_t USBDevice;
1177 while ((USBDevice = IOIteratorNext(USBDevices)))
1178 {
1179 cMatches++;
1180 CFMutableDictionaryRef PropsRef = 0;
1181 kern_return_t krc = IORegistryEntryCreateCFProperties(USBDevice, &PropsRef, kCFAllocatorDefault, kNilOptions);
1182 if (krc == KERN_SUCCESS)
1183 {
1184 uint64_t u64CurSessionId;
1185 uint32_t u32CurLocationId;
1186 if ( ( !u64SessionId
1187 || ( usbProxyDarwinDictGetU64(PropsRef, CFSTR("sessionID"), &u64CurSessionId)
1188 && u64CurSessionId == u64SessionId))
1189 && ( !u32LocationId
1190 || ( usbProxyDarwinDictGetU32(PropsRef, CFSTR(kUSBDevicePropertyLocationID), &u32CurLocationId)
1191 && u32CurLocationId == u32LocationId))
1192 )
1193 {
1194 CFRelease(PropsRef);
1195 break;
1196 }
1197 CFRelease(PropsRef);
1198 }
1199 IOObjectRelease(USBDevice);
1200 }
1201 IOObjectRelease(USBDevices);
1202 USBDevices = IO_OBJECT_NULL;
1203 if (!USBDevice)
1204 {
1205 LogRel(("USB: Device '%s' not found (%d pid+vid matches)\n", pszAddress, cMatches));
1206 IOObjectRelease(USBDevices);
1207 return VERR_VUSB_DEVICE_NAME_NOT_FOUND;
1208 }
1209
1210 /*
1211 * Create a plugin interface for the device and query its IOUSBDeviceInterface.
1212 */
1213 SInt32 Score = 0;
1214 IOCFPlugInInterface **ppPlugInInterface = NULL;
1215 irc = IOCreatePlugInInterfaceForService(USBDevice, kIOUSBDeviceUserClientTypeID,
1216 kIOCFPlugInInterfaceID, &ppPlugInInterface, &Score);
1217 if (irc == kIOReturnSuccess)
1218 {
1219 IOUSBDeviceInterface245 **ppDevI = NULL;
1220 HRESULT hrc = (*ppPlugInInterface)->QueryInterface(ppPlugInInterface,
1221 CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID245),
1222 (LPVOID *)&ppDevI);
1223 irc = IODestroyPlugInInterface(ppPlugInInterface); Assert(irc == kIOReturnSuccess);
1224 ppPlugInInterface = NULL;
1225 if (hrc == S_OK)
1226 {
1227 /*
1228 * Try open the device for exclusive access.
1229 * If we fail, we'll try figure out who is using the device and
1230 * convince them to let go of it...
1231 */
1232 irc = (*ppDevI)->USBDeviceReEnumerate(ppDevI, kUSBReEnumerateCaptureDeviceMask);
1233 Log(("USBDeviceReEnumerate (capture) returned irc=%#x\n", irc));
1234
1235 irc = (*ppDevI)->USBDeviceOpenSeize(ppDevI);
1236 if (irc == kIOReturnExclusiveAccess)
1237 {
1238 RTThreadSleep(20);
1239 irc = (*ppDevI)->USBDeviceOpenSeize(ppDevI);
1240 }
1241 if (irc == kIOReturnSuccess)
1242 {
1243 /*
1244 * Init a proxy device instance.
1245 */
1246 RTListInit((PRTLISTNODE)&pDevOsX->HeadOfRunLoopLst);
1247 vrc = RTCritSectInit(&pDevOsX->CritSect);
1248 if (RT_SUCCESS(vrc))
1249 {
1250 pDevOsX->USBDevice = USBDevice;
1251 pDevOsX->ppDevI = ppDevI;
1252 pDevOsX->pProxyDev = pProxyDev;
1253 pDevOsX->pTaxingHead = NULL;
1254 pDevOsX->pTaxingTail = NULL;
1255 pDevOsX->hRunLoopReapingLast = NULL;
1256
1257 /*
1258 * Try seize all the interface.
1259 */
1260 char *pszDummyName = pProxyDev->pUsbIns->pszName;
1261 pProxyDev->pUsbIns->pszName = (char *)pszAddress;
1262 vrc = usbProxyDarwinSeizeAllInterfaces(pDevOsX, false /* give up on failure */);
1263 pProxyDev->pUsbIns->pszName = pszDummyName;
1264 if (RT_SUCCESS(vrc))
1265 {
1266 /*
1267 * Create the async event source and add it to the run loop.
1268 */
1269 irc = (*ppDevI)->CreateDeviceAsyncEventSource(ppDevI, &pDevOsX->RunLoopSrcRef);
1270 if (irc == kIOReturnSuccess)
1271 {
1272 /*
1273 * Determine the active configuration.
1274 * Can cause hangs, so drop it for now.
1275 */
1276 /** @todo test Palm. */
1277 //uint8_t u8Cfg;
1278 //irc = (*ppDevI)->GetConfiguration(ppDevI, &u8Cfg);
1279 if (irc != kIOReturnNoDevice)
1280 {
1281 CFRunLoopSourceContext CtxRunLoopSource;
1282 CtxRunLoopSource.version = 0;
1283 CtxRunLoopSource.info = NULL;
1284 CtxRunLoopSource.retain = NULL;
1285 CtxRunLoopSource.release = NULL;
1286 CtxRunLoopSource.copyDescription = NULL;
1287 CtxRunLoopSource.equal = NULL;
1288 CtxRunLoopSource.hash = NULL;
1289 CtxRunLoopSource.schedule = NULL;
1290 CtxRunLoopSource.cancel = NULL;
1291 CtxRunLoopSource.perform = usbProxyDarwinPerformWakeup;
1292 pDevOsX->hRunLoopSrcWakeRef = CFRunLoopSourceCreate(NULL, 0, &CtxRunLoopSource);
1293 if (CFRunLoopSourceIsValid(pDevOsX->hRunLoopSrcWakeRef))
1294 {
1295 //pProxyDev->iActiveCfg = irc == kIOReturnSuccess ? u8Cfg : -1;
1296 RTListInit(&pDevOsX->HeadOfRunLoopWakeLst);
1297 pProxyDev->iActiveCfg = -1;
1298 pProxyDev->cIgnoreSetConfigs = 1;
1299
1300 usbProxyDarwinAddRunLoopRef(&pDevOsX->HeadOfRunLoopLst, pDevOsX->RunLoopSrcRef);
1301 return VINF_SUCCESS; /* return */
1302 }
1303 else
1304 {
1305 LogRel(("USB: Device '%s' out of memory allocating runloop source\n", pszAddress));
1306 vrc = VERR_NO_MEMORY;
1307 }
1308 }
1309 vrc = VERR_VUSB_DEVICE_NOT_ATTACHED;
1310 }
1311 else
1312 vrc = RTErrConvertFromDarwin(irc);
1313
1314 usbProxyDarwinReleaseAllInterfaces(pDevOsX);
1315 }
1316 /* else: already bitched */
1317
1318 RTCritSectDelete(&pDevOsX->CritSect);
1319 }
1320
1321 irc = (*ppDevI)->USBDeviceClose(ppDevI);
1322 AssertMsg(irc == kIOReturnSuccess, ("%#x\n", irc));
1323 }
1324 else if (irc == kIOReturnExclusiveAccess)
1325 {
1326 LogRel(("USB: Device '%s' is being used by another process\n", pszAddress));
1327 vrc = VERR_SHARING_VIOLATION;
1328 }
1329 else
1330 {
1331 LogRel(("USB: Failed to open device '%s', irc=%#x.\n", pszAddress, irc));
1332 vrc = VERR_OPEN_FAILED;
1333 }
1334 }
1335 else
1336 {
1337 LogRel(("USB: Failed to create plugin interface for device '%s', hrc=%#x.\n", pszAddress, hrc));
1338 vrc = VERR_OPEN_FAILED;
1339 }
1340
1341 (*ppDevI)->Release(ppDevI);
1342 }
1343 else
1344 {
1345 LogRel(("USB: Failed to open device '%s', plug-in creation failed with irc=%#x.\n", pszAddress, irc));
1346 vrc = RTErrConvertFromDarwin(irc);
1347 }
1348
1349 return vrc;
1350}
1351
1352
1353/**
1354 * Closes the proxy device.
1355 */
1356static DECLCALLBACK(void) usbProxyDarwinClose(PUSBPROXYDEV pProxyDev)
1357{
1358 LogFlow(("usbProxyDarwinClose: pProxyDev=%s\n", pProxyDev->pUsbIns->pszName));
1359 PUSBPROXYDEVOSX pDevOsX = USBPROXYDEV_2_DATA(pProxyDev, PUSBPROXYDEVOSX);
1360 AssertPtrReturnVoid(pDevOsX);
1361
1362 /*
1363 * Release interfaces we've laid claim to, then reset the device
1364 * and finally close it.
1365 */
1366 RTCritSectEnter(&pDevOsX->CritSect);
1367 /* ?? */
1368 RTCritSectLeave(&pDevOsX->CritSect);
1369
1370 usbProxyDarwinReleaseAllInterfaces(pDevOsX);
1371
1372 if (pDevOsX->RunLoopSrcRef)
1373 {
1374 int rc = usbProxyDarwinRemoveSourceRefFromAllRunLoops(&pDevOsX->HeadOfRunLoopLst, pDevOsX->RunLoopSrcRef);
1375 AssertRC(rc);
1376
1377 RTListInit((PRTLISTNODE)&pDevOsX->HeadOfRunLoopLst);
1378
1379 CFRelease(pDevOsX->RunLoopSrcRef);
1380 pDevOsX->RunLoopSrcRef = NULL;
1381 }
1382
1383 if (pDevOsX->hRunLoopSrcWakeRef)
1384 {
1385 int rc = usbProxyDarwinRemoveSourceRefFromAllRunLoops(&pDevOsX->HeadOfRunLoopWakeLst, pDevOsX->hRunLoopSrcWakeRef);
1386 AssertRC(rc);
1387
1388 RTListInit((PRTLISTNODE)&pDevOsX->HeadOfRunLoopWakeLst);
1389
1390 CFRelease(pDevOsX->hRunLoopSrcWakeRef);
1391 pDevOsX->hRunLoopSrcWakeRef = NULL;
1392 }
1393
1394 IOReturn irc = (*pDevOsX->ppDevI)->ResetDevice(pDevOsX->ppDevI);
1395
1396 irc = (*pDevOsX->ppDevI)->USBDeviceClose(pDevOsX->ppDevI);
1397 if (irc != kIOReturnSuccess && irc != kIOReturnNoDevice)
1398 {
1399 LogRel(("USB: USBDeviceClose -> %#x\n", irc));
1400 AssertMsgFailed(("irc=%#x\n", irc));
1401 }
1402
1403 irc = (*pDevOsX->ppDevI)->USBDeviceReEnumerate(pDevOsX->ppDevI, kUSBReEnumerateReleaseDeviceMask);
1404 Log(("USBDeviceReEnumerate (release) returned irc=%#x\n", irc));
1405
1406 (*pDevOsX->ppDevI)->Release(pDevOsX->ppDevI);
1407 pDevOsX->ppDevI = NULL;
1408 kern_return_t krc = IOObjectRelease(pDevOsX->USBDevice); Assert(krc == KERN_SUCCESS); NOREF(krc);
1409 pDevOsX->USBDevice = IO_OBJECT_NULL;
1410 pDevOsX->pProxyDev = NULL;
1411
1412 /*
1413 * Free all the resources.
1414 */
1415 RTCritSectDelete(&pDevOsX->CritSect);
1416
1417 PUSBPROXYURBOSX pUrbOsX;
1418 while ((pUrbOsX = pDevOsX->pFreeHead) != NULL)
1419 {
1420 pDevOsX->pFreeHead = pUrbOsX->pNext;
1421 RTMemFree(pUrbOsX);
1422 }
1423
1424 LogFlow(("usbProxyDarwinClose: returns\n"));
1425}
1426
1427
1428/** @interface_method_impl{USBPROXYBACK,pfnReset}*/
1429static DECLCALLBACK(int) usbProxyDarwinReset(PUSBPROXYDEV pProxyDev, bool fResetOnLinux)
1430{
1431 RT_NOREF(fResetOnLinux);
1432 PUSBPROXYDEVOSX pDevOsX = USBPROXYDEV_2_DATA(pProxyDev, PUSBPROXYDEVOSX);
1433 LogFlow(("usbProxyDarwinReset: pProxyDev=%s\n", pProxyDev->pUsbIns->pszName));
1434
1435 IOReturn irc = (*pDevOsX->ppDevI)->ResetDevice(pDevOsX->ppDevI);
1436 int rc;
1437 if (irc == kIOReturnSuccess)
1438 {
1439 /** @todo Some docs say that some drivers will do a default config, check this out ... */
1440 pProxyDev->cIgnoreSetConfigs = 0;
1441 pProxyDev->iActiveCfg = -1;
1442
1443 rc = VINF_SUCCESS;
1444 }
1445 else if (irc == kIOReturnNoDevice)
1446 rc = VERR_VUSB_DEVICE_NOT_ATTACHED;
1447 else
1448 {
1449 AssertMsgFailed(("irc=%#x\n", irc));
1450 rc = VERR_GENERAL_FAILURE;
1451 }
1452
1453 LogFlow(("usbProxyDarwinReset: returns success %Rrc\n", rc));
1454 return rc;
1455}
1456
1457
1458/**
1459 * SET_CONFIGURATION.
1460 *
1461 * The caller makes sure that it's not called first time after open or reset
1462 * with the active interface.
1463 *
1464 * @returns success indicator.
1465 * @param pProxyDev The device instance data.
1466 * @param iCfg The configuration to set.
1467 */
1468static DECLCALLBACK(int) usbProxyDarwinSetConfig(PUSBPROXYDEV pProxyDev, int iCfg)
1469{
1470 PUSBPROXYDEVOSX pDevOsX = USBPROXYDEV_2_DATA(pProxyDev, PUSBPROXYDEVOSX);
1471 LogFlow(("usbProxyDarwinSetConfig: pProxyDev=%s cfg=%#x\n",
1472 pProxyDev->pUsbIns->pszName, iCfg));
1473
1474 IOReturn irc = (*pDevOsX->ppDevI)->SetConfiguration(pDevOsX->ppDevI, (uint8_t)iCfg);
1475 if (irc != kIOReturnSuccess)
1476 {
1477 Log(("usbProxyDarwinSetConfig: Set configuration -> %#x\n", irc));
1478 return RTErrConvertFromDarwin(irc);
1479 }
1480
1481 usbProxyDarwinReleaseAllInterfaces(pDevOsX);
1482 usbProxyDarwinSeizeAllInterfaces(pDevOsX, true /* make the best out of it */);
1483 return VINF_SUCCESS;
1484}
1485
1486
1487/**
1488 * Claims an interface.
1489 *
1490 * This is a stub on Darwin since we release/claim all interfaces at
1491 * open/reset/setconfig time.
1492 *
1493 * @returns success indicator (always VINF_SUCCESS).
1494 */
1495static DECLCALLBACK(int) usbProxyDarwinClaimInterface(PUSBPROXYDEV pProxyDev, int iIf)
1496{
1497 RT_NOREF(pProxyDev, iIf);
1498 return VINF_SUCCESS;
1499}
1500
1501
1502/**
1503 * Releases an interface.
1504 *
1505 * This is a stub on Darwin since we release/claim all interfaces at
1506 * open/reset/setconfig time.
1507 *
1508 * @returns success indicator.
1509 */
1510static DECLCALLBACK(int) usbProxyDarwinReleaseInterface(PUSBPROXYDEV pProxyDev, int iIf)
1511{
1512 RT_NOREF(pProxyDev, iIf);
1513 return VINF_SUCCESS;
1514}
1515
1516
1517/**
1518 * SET_INTERFACE.
1519 *
1520 * @returns success indicator.
1521 */
1522static DECLCALLBACK(int) usbProxyDarwinSetInterface(PUSBPROXYDEV pProxyDev, int iIf, int iAlt)
1523{
1524 PUSBPROXYDEVOSX pDevOsX = USBPROXYDEV_2_DATA(pProxyDev, PUSBPROXYDEVOSX);
1525 IOReturn irc = kIOReturnSuccess;
1526 PUSBPROXYIFOSX pIf = usbProxyDarwinGetInterface(pDevOsX, iIf);
1527 LogFlow(("usbProxyDarwinSetInterface: pProxyDev=%s iIf=%#x iAlt=%#x iCurAlt=%#x\n",
1528 pProxyDev->pUsbIns->pszName, iIf, iAlt, pIf ? pIf->u8AltSetting : 0xbeef));
1529 if (pIf)
1530 {
1531 /* Avoid SetAlternateInterface when possible as it will recreate the pipes. */
1532 if (iAlt != pIf->u8AltSetting)
1533 {
1534 irc = (*pIf->ppIfI)->SetAlternateInterface(pIf->ppIfI, iAlt);
1535 if (irc == kIOReturnSuccess)
1536 {
1537 usbProxyDarwinGetPipeProperties(pDevOsX, pIf);
1538 return VINF_SUCCESS;
1539 }
1540 }
1541 else
1542 {
1543 /*
1544 * Just send the request anyway?
1545 */
1546 IOUSBDevRequest Req;
1547 Req.bmRequestType = 0x01;
1548 Req.bRequest = 0x0b; /* SET_INTERFACE */
1549 Req.wIndex = iIf;
1550 Req.wValue = iAlt;
1551 Req.wLength = 0;
1552 Req.wLenDone = 0;
1553 Req.pData = NULL;
1554 irc = (*pDevOsX->ppDevI)->DeviceRequest(pDevOsX->ppDevI, &Req);
1555 Log(("usbProxyDarwinSetInterface: SET_INTERFACE(%d,%d) -> irc=%#x\n", iIf, iAlt, irc));
1556 return VINF_SUCCESS;
1557 }
1558 }
1559
1560 LogFlow(("usbProxyDarwinSetInterface: pProxyDev=%s eiIf=%#x iAlt=%#x - failure - pIf=%p irc=%#x\n",
1561 pProxyDev->pUsbIns->pszName, iIf, iAlt, pIf, irc));
1562 return RTErrConvertFromDarwin(irc);
1563}
1564
1565
1566/**
1567 * Clears the halted endpoint 'EndPt'.
1568 */
1569static DECLCALLBACK(int) usbProxyDarwinClearHaltedEp(PUSBPROXYDEV pProxyDev, unsigned int EndPt)
1570{
1571 PUSBPROXYDEVOSX pDevOsX = USBPROXYDEV_2_DATA(pProxyDev, PUSBPROXYDEVOSX);
1572 LogFlow(("usbProxyDarwinClearHaltedEp: pProxyDev=%s EndPt=%#x\n", pProxyDev->pUsbIns->pszName, EndPt));
1573
1574 /*
1575 * Clearing the zero control pipe doesn't make sense and isn't
1576 * supported by the API. Just ignore it.
1577 */
1578 if (EndPt == 0)
1579 return VINF_SUCCESS;
1580
1581 /*
1582 * Find the interface/pipe combination and invoke the ClearPipeStallBothEnds
1583 * method. (The ResetPipe and ClearPipeStall methods will not send the
1584 * CLEAR_FEATURE(ENDPOINT_HALT) request that this method implements.)
1585 */
1586 IOReturn irc = kIOReturnSuccess;
1587 uint8_t u8PipeRef;
1588 PUSBPROXYIFOSX pIf = usbProxyDarwinGetInterfaceForEndpoint(pDevOsX, EndPt, &u8PipeRef, NULL);
1589 if (pIf)
1590 {
1591 irc = (*pIf->ppIfI)->ClearPipeStallBothEnds(pIf->ppIfI, u8PipeRef);
1592 if (irc == kIOReturnSuccess)
1593 return VINF_SUCCESS;
1594 AssertMsg(irc == kIOReturnNoDevice || irc == kIOReturnNotResponding, ("irc=#x (control pipe?)\n", irc));
1595 }
1596
1597 LogFlow(("usbProxyDarwinClearHaltedEp: pProxyDev=%s EndPt=%#x - failure - pIf=%p irc=%#x\n",
1598 pProxyDev->pUsbIns->pszName, EndPt, pIf, irc));
1599 return RTErrConvertFromDarwin(irc);
1600}
1601
1602
1603/**
1604 * @interface_method_impl{USBPROXYBACK,pfnUrbQueue}
1605 */
1606static DECLCALLBACK(int) usbProxyDarwinUrbQueue(PUSBPROXYDEV pProxyDev, PVUSBURB pUrb)
1607{
1608 PUSBPROXYDEVOSX pDevOsX = USBPROXYDEV_2_DATA(pProxyDev, PUSBPROXYDEVOSX);
1609 LogFlow(("%s: usbProxyDarwinUrbQueue: pProxyDev=%s pUrb=%p EndPt=%d cbData=%d\n",
1610 pUrb->pszDesc, pProxyDev->pUsbIns->pszName, pUrb, pUrb->EndPt, pUrb->cbData));
1611
1612 /*
1613 * Find the target interface / pipe.
1614 */
1615 uint8_t u8PipeRef = 0xff;
1616 PUSBPROXYIFOSX pIf = NULL;
1617 PUSBPROXYPIPEOSX pPipe = NULL;
1618 if (pUrb->EndPt)
1619 {
1620 /* Make sure the interface is there. */
1621 const uint8_t EndPt = pUrb->EndPt | (pUrb->enmDir == VUSBDIRECTION_IN ? 0x80 : 0);
1622 pIf = usbProxyDarwinGetInterfaceForEndpoint(pDevOsX, EndPt, &u8PipeRef, &pPipe);
1623 if (!pIf)
1624 {
1625 LogFlow(("%s: usbProxyDarwinUrbQueue: pProxyDev=%s EndPt=%d cbData=%d - can't find interface / pipe!!!\n",
1626 pUrb->pszDesc, pProxyDev->pUsbIns->pszName, pUrb->EndPt, pUrb->cbData));
1627 return VERR_NOT_FOUND;
1628 }
1629 }
1630 /* else: pIf == NULL -> default control pipe.*/
1631
1632 /*
1633 * Allocate a Darwin urb.
1634 */
1635 PUSBPROXYURBOSX pUrbOsX = usbProxyDarwinUrbAlloc(pDevOsX);
1636 if (!pUrbOsX)
1637 return VERR_NO_MEMORY;
1638
1639 pUrbOsX->u64SubmitTS = RTTimeMilliTS();
1640 pUrbOsX->pVUsbUrb = pUrb;
1641 pUrbOsX->pDevOsX = pDevOsX;
1642 pUrbOsX->enmType = pUrb->enmType;
1643
1644 /*
1645 * Submit the request.
1646 */
1647 IOReturn irc = kIOReturnError;
1648 switch (pUrb->enmType)
1649 {
1650 case VUSBXFERTYPE_MSG:
1651 {
1652 AssertMsgBreak(pUrb->cbData >= sizeof(VUSBSETUP), ("cbData=%d\n", pUrb->cbData));
1653 PVUSBSETUP pSetup = (PVUSBSETUP)&pUrb->abData[0];
1654 pUrbOsX->u.ControlMsg.bmRequestType = pSetup->bmRequestType;
1655 pUrbOsX->u.ControlMsg.bRequest = pSetup->bRequest;
1656 pUrbOsX->u.ControlMsg.wValue = pSetup->wValue;
1657 pUrbOsX->u.ControlMsg.wIndex = pSetup->wIndex;
1658 pUrbOsX->u.ControlMsg.wLength = pSetup->wLength;
1659 pUrbOsX->u.ControlMsg.pData = pSetup + 1;
1660 pUrbOsX->u.ControlMsg.wLenDone = pSetup->wLength;
1661
1662 if (pIf)
1663 irc = (*pIf->ppIfI)->ControlRequestAsync(pIf->ppIfI, u8PipeRef, &pUrbOsX->u.ControlMsg,
1664 usbProxyDarwinUrbAsyncComplete, pUrbOsX);
1665 else
1666 irc = (*pDevOsX->ppDevI)->DeviceRequestAsync(pDevOsX->ppDevI, &pUrbOsX->u.ControlMsg,
1667 usbProxyDarwinUrbAsyncComplete, pUrbOsX);
1668 break;
1669 }
1670
1671 case VUSBXFERTYPE_BULK:
1672 case VUSBXFERTYPE_INTR:
1673 {
1674 AssertBreak(pIf);
1675 Assert(pUrb->enmDir == VUSBDIRECTION_IN || pUrb->enmDir == VUSBDIRECTION_OUT);
1676 if (pUrb->enmDir == VUSBDIRECTION_OUT)
1677 irc = (*pIf->ppIfI)->WritePipeAsync(pIf->ppIfI, u8PipeRef, pUrb->abData, pUrb->cbData,
1678 usbProxyDarwinUrbAsyncComplete, pUrbOsX);
1679 else
1680 irc = (*pIf->ppIfI)->ReadPipeAsync(pIf->ppIfI, u8PipeRef, pUrb->abData, pUrb->cbData,
1681 usbProxyDarwinUrbAsyncComplete, pUrbOsX);
1682
1683 break;
1684 }
1685
1686 case VUSBXFERTYPE_ISOC:
1687 {
1688 AssertBreak(pIf);
1689 Assert(pUrb->enmDir == VUSBDIRECTION_IN || pUrb->enmDir == VUSBDIRECTION_OUT);
1690
1691#ifdef USE_LOW_LATENCY_API
1692 /* Allocate an isochronous buffer and copy over the data. */
1693 AssertBreak(pUrb->cbData <= 8192);
1694 int rc = usbProxyDarwinUrbAllocIsocBuf(pUrbOsX, pIf);
1695 AssertRCBreak(rc);
1696 if (pUrb->enmDir == VUSBDIRECTION_OUT)
1697 memcpy(pUrbOsX->u.Isoc.pBuf->pvBuf, pUrb->abData, pUrb->cbData);
1698 else
1699 memset(pUrbOsX->u.Isoc.pBuf->pvBuf, 0xfe, pUrb->cbData);
1700#endif
1701
1702 /* Get the current frame number (+2) and make sure it doesn't
1703 overlap with the previous request. See WARNING in
1704 ApplUSBUHCI::CreateIsochTransfer for details on the +2. */
1705 UInt64 FrameNo;
1706 AbsoluteTime FrameTime;
1707 irc = (*pIf->ppIfI)->GetBusFrameNumber(pIf->ppIfI, &FrameNo, &FrameTime);
1708 AssertMsg(irc == kIOReturnSuccess, ("GetBusFrameNumber -> %#x\n", irc));
1709 FrameNo += 2;
1710 if (FrameNo <= pPipe->u64NextFrameNo)
1711 FrameNo = pPipe->u64NextFrameNo;
1712
1713 for (unsigned j = 0; ; j++)
1714 {
1715 unsigned i;
1716 for (i = 0; i < pUrb->cIsocPkts; i++)
1717 {
1718 pUrbOsX->u.Isoc.aFrames[i].frReqCount = pUrb->aIsocPkts[i].cb;
1719 pUrbOsX->u.Isoc.aFrames[i].frActCount = 0;
1720 pUrbOsX->u.Isoc.aFrames[i].frStatus = kIOUSBNotSent1Err;
1721#ifdef USE_LOW_LATENCY_API
1722 pUrbOsX->u.Isoc.aFrames[i].frTimeStamp.hi = 0;
1723 pUrbOsX->u.Isoc.aFrames[i].frTimeStamp.lo = 0;
1724#endif
1725 }
1726 for (; i < RT_ELEMENTS(pUrbOsX->u.Isoc.aFrames); i++)
1727 {
1728 pUrbOsX->u.Isoc.aFrames[i].frReqCount = 0;
1729 pUrbOsX->u.Isoc.aFrames[i].frActCount = 0;
1730 pUrbOsX->u.Isoc.aFrames[i].frStatus = kIOReturnError;
1731#ifdef USE_LOW_LATENCY_API
1732 pUrbOsX->u.Isoc.aFrames[i].frTimeStamp.hi = 0;
1733 pUrbOsX->u.Isoc.aFrames[i].frTimeStamp.lo = 0;
1734#endif
1735 }
1736
1737#ifdef USE_LOW_LATENCY_API
1738 if (pUrb->enmDir == VUSBDIRECTION_OUT)
1739 irc = (*pIf->ppIfI)->LowLatencyWriteIsochPipeAsync(pIf->ppIfI, u8PipeRef,
1740 pUrbOsX->u.Isoc.pBuf->pvBuf, FrameNo, pUrb->cIsocPkts, 0, pUrbOsX->u.Isoc.aFrames,
1741 usbProxyDarwinUrbAsyncComplete, pUrbOsX);
1742 else
1743 irc = (*pIf->ppIfI)->LowLatencyReadIsochPipeAsync(pIf->ppIfI, u8PipeRef,
1744 pUrbOsX->u.Isoc.pBuf->pvBuf, FrameNo, pUrb->cIsocPkts, 0, pUrbOsX->u.Isoc.aFrames,
1745 usbProxyDarwinUrbAsyncComplete, pUrbOsX);
1746#else
1747 if (pUrb->enmDir == VUSBDIRECTION_OUT)
1748 irc = (*pIf->ppIfI)->WriteIsochPipeAsync(pIf->ppIfI, u8PipeRef,
1749 pUrb->abData, FrameNo, pUrb->cIsocPkts, &pUrbOsX->u.Isoc.aFrames[0],
1750 usbProxyDarwinUrbAsyncComplete, pUrbOsX);
1751 else
1752 irc = (*pIf->ppIfI)->ReadIsochPipeAsync(pIf->ppIfI, u8PipeRef,
1753 pUrb->abData, FrameNo, pUrb->cIsocPkts, &pUrbOsX->u.Isoc.aFrames[0],
1754 usbProxyDarwinUrbAsyncComplete, pUrbOsX);
1755#endif
1756 if ( irc != kIOReturnIsoTooOld
1757 || j >= 5)
1758 {
1759 Log(("%s: usbProxyDarwinUrbQueue: isoc: u64NextFrameNo=%RX64 FrameNo=%RX64 #Frames=%d j=%d (pipe=%d)\n",
1760 pUrb->pszDesc, pPipe->u64NextFrameNo, FrameNo, pUrb->cIsocPkts, j, u8PipeRef));
1761 if (irc == kIOReturnSuccess)
1762 {
1763 if (pPipe->fIsFullSpeed)
1764 pPipe->u64NextFrameNo = FrameNo + pUrb->cIsocPkts;
1765 else
1766 pPipe->u64NextFrameNo = FrameNo + 1;
1767 }
1768 break;
1769 }
1770
1771 /* try again... */
1772 irc = (*pIf->ppIfI)->GetBusFrameNumber(pIf->ppIfI, &FrameNo, &FrameTime);
1773 if (FrameNo <= pPipe->u64NextFrameNo)
1774 FrameNo = pPipe->u64NextFrameNo;
1775 FrameNo += j;
1776 }
1777 break;
1778 }
1779
1780 default:
1781 AssertMsgFailed(("%s: enmType=%#x\n", pUrb->pszDesc, pUrb->enmType));
1782 break;
1783 }
1784
1785 /*
1786 * Success?
1787 */
1788 if (RT_LIKELY(irc == kIOReturnSuccess))
1789 {
1790 Log(("%s: usbProxyDarwinUrbQueue: success\n", pUrb->pszDesc));
1791 return VINF_SUCCESS;
1792 }
1793 switch (irc)
1794 {
1795 case kIOUSBPipeStalled:
1796 {
1797 /* Increment in flight counter because the completion handler will decrease it always. */
1798 usbProxyDarwinUrbAsyncComplete(pUrbOsX, kIOUSBPipeStalled, 0);
1799 Log(("%s: usbProxyDarwinUrbQueue: pProxyDev=%s EndPt=%d cbData=%d - failed irc=%#x! (stall)\n",
1800 pUrb->pszDesc, pProxyDev->pUsbIns->pszName, pUrb->EndPt, pUrb->cbData, irc));
1801 return VINF_SUCCESS;
1802 }
1803 }
1804
1805 usbProxyDarwinUrbFree(pDevOsX, pUrbOsX);
1806 Log(("%s: usbProxyDarwinUrbQueue: pProxyDev=%s EndPt=%d cbData=%d - failed irc=%#x!\n",
1807 pUrb->pszDesc, pProxyDev->pUsbIns->pszName, pUrb->EndPt, pUrb->cbData, irc));
1808 return RTErrConvertFromDarwin(irc);
1809}
1810
1811
1812/**
1813 * Reap URBs in-flight on a device.
1814 *
1815 * @returns Pointer to a completed URB.
1816 * @returns NULL if no URB was completed.
1817 * @param pProxyDev The device.
1818 * @param cMillies Number of milliseconds to wait. Use 0 to not wait at all.
1819 */
1820static DECLCALLBACK(PVUSBURB) usbProxyDarwinUrbReap(PUSBPROXYDEV pProxyDev, RTMSINTERVAL cMillies)
1821{
1822 PVUSBURB pUrb = NULL;
1823 PUSBPROXYDEVOSX pDevOsX = USBPROXYDEV_2_DATA(pProxyDev, PUSBPROXYDEVOSX);
1824 CFRunLoopRef hRunLoopRef = CFRunLoopGetCurrent();
1825
1826 Assert(!pDevOsX->hRunLoopReaping);
1827
1828 /*
1829 * If the last seen runloop for reaping differs we have to check whether the
1830 * the runloop sources are in the new runloop.
1831 */
1832 if (pDevOsX->hRunLoopReapingLast != hRunLoopRef)
1833 {
1834 RTCritSectEnter(&pDevOsX->CritSect);
1835
1836 /* Every pipe. */
1837 if (!pDevOsX->pIfHead)
1838 usbProxyDarwinSeizeAllInterfaces(pDevOsX, true /* make the best out of it */);
1839
1840 PUSBPROXYIFOSX pIf;
1841 for (pIf = pDevOsX->pIfHead; pIf; pIf = pIf->pNext)
1842 {
1843 if (!CFRunLoopContainsSource(hRunLoopRef, pIf->RunLoopSrcRef, g_pRunLoopMode))
1844 usbProxyDarwinAddRunLoopRef(&pIf->HeadOfRunLoopLst, pIf->RunLoopSrcRef);
1845 }
1846
1847 /* Default control pipe. */
1848 if (!CFRunLoopContainsSource(hRunLoopRef, pDevOsX->RunLoopSrcRef, g_pRunLoopMode))
1849 usbProxyDarwinAddRunLoopRef(&pDevOsX->HeadOfRunLoopLst, pDevOsX->RunLoopSrcRef);
1850
1851 /* Runloop wakeup source. */
1852 if (!CFRunLoopContainsSource(hRunLoopRef, pDevOsX->hRunLoopSrcWakeRef, g_pRunLoopMode))
1853 usbProxyDarwinAddRunLoopRef(&pDevOsX->HeadOfRunLoopWakeLst, pDevOsX->hRunLoopSrcWakeRef);
1854 RTCritSectLeave(&pDevOsX->CritSect);
1855
1856 pDevOsX->hRunLoopReapingLast = hRunLoopRef;
1857 }
1858
1859 ASMAtomicXchgPtr((void * volatile *)&pDevOsX->hRunLoopReaping, hRunLoopRef);
1860
1861 if (ASMAtomicXchgBool(&pDevOsX->fReapingThreadWake, false))
1862 {
1863 /* Return immediately. */
1864 ASMAtomicXchgPtr((void * volatile *)&pDevOsX->hRunLoopReaping, NULL);
1865 return NULL;
1866 }
1867
1868 /*
1869 * Excercise the runloop until we get an URB or we time out.
1870 */
1871 if ( !pDevOsX->pTaxingHead
1872 && cMillies)
1873 CFRunLoopRunInMode(g_pRunLoopMode, cMillies / 1000.0, true);
1874
1875 ASMAtomicXchgPtr((void * volatile *)&pDevOsX->hRunLoopReaping, NULL);
1876 ASMAtomicXchgBool(&pDevOsX->fReapingThreadWake, false);
1877
1878 /*
1879 * Any URBs pending delivery?
1880 */
1881 while ( pDevOsX->pTaxingHead
1882 && !pUrb)
1883 {
1884 RTCritSectEnter(&pDevOsX->CritSect);
1885
1886 PUSBPROXYURBOSX pUrbOsX = pDevOsX->pTaxingHead;
1887 if (pUrbOsX)
1888 {
1889 /*
1890 * Remove from the taxing list.
1891 */
1892 if (pUrbOsX->pNext)
1893 pUrbOsX->pNext->pPrev = pUrbOsX->pPrev;
1894 else if (pDevOsX->pTaxingTail == pUrbOsX)
1895 pDevOsX->pTaxingTail = pUrbOsX->pPrev;
1896
1897 if (pUrbOsX->pPrev)
1898 pUrbOsX->pPrev->pNext = pUrbOsX->pNext;
1899 else if (pDevOsX->pTaxingHead == pUrbOsX)
1900 pDevOsX->pTaxingHead = pUrbOsX->pNext;
1901 else
1902 AssertFailed();
1903
1904 pUrb = pUrbOsX->pVUsbUrb;
1905 if (pUrb)
1906 {
1907 pUrb->Dev.pvPrivate = NULL;
1908 usbProxyDarwinUrbFree(pDevOsX, pUrbOsX);
1909 }
1910 }
1911 RTCritSectLeave(&pDevOsX->CritSect);
1912 }
1913
1914 if (pUrb)
1915 LogFlowFunc(("LEAVE: %s: pProxyDev=%s returns %p\n", pUrb->pszDesc, pProxyDev->pUsbIns->pszName, pUrb));
1916 else
1917 LogFlowFunc(("LEAVE: NULL pProxyDev=%s returns NULL\n", pProxyDev->pUsbIns->pszName));
1918
1919 return pUrb;
1920}
1921
1922
1923/**
1924 * Cancels a URB.
1925 *
1926 * The URB requires reaping, so we don't change its state.
1927 *
1928 * @remark There isn't any way to cancel a specific async request
1929 * on darwin. The interface only supports the aborting of
1930 * all URBs pending on an interface / pipe pair. Provided
1931 * the card does the URB cancelling before submitting new
1932 * requests, we should probably be fine...
1933 */
1934static DECLCALLBACK(int) usbProxyDarwinUrbCancel(PUSBPROXYDEV pProxyDev, PVUSBURB pUrb)
1935{
1936 PUSBPROXYDEVOSX pDevOsX = USBPROXYDEV_2_DATA(pProxyDev, PUSBPROXYDEVOSX);
1937 LogFlow(("%s: usbProxyDarwinUrbCancel: pProxyDev=%s EndPt=%d\n",
1938 pUrb->pszDesc, pProxyDev->pUsbIns->pszName, pUrb->EndPt));
1939
1940 /*
1941 * Determine the interface / endpoint ref and invoke AbortPipe.
1942 */
1943 IOReturn irc = kIOReturnSuccess;
1944 if (!pUrb->EndPt)
1945 irc = (*pDevOsX->ppDevI)->USBDeviceAbortPipeZero(pDevOsX->ppDevI);
1946 else
1947 {
1948 uint8_t u8PipeRef;
1949 const uint8_t EndPt = pUrb->EndPt | (pUrb->enmDir == VUSBDIRECTION_IN ? 0x80 : 0);
1950 PUSBPROXYIFOSX pIf = usbProxyDarwinGetInterfaceForEndpoint(pDevOsX, EndPt, &u8PipeRef, NULL);
1951 if (pIf)
1952 irc = (*pIf->ppIfI)->AbortPipe(pIf->ppIfI, u8PipeRef);
1953 else /* this may happen if a device reset, set configuration or set interface has been performed. */
1954 Log(("usbProxyDarwinUrbCancel: pProxyDev=%s pUrb=%p EndPt=%d - cannot find the interface / pipe!\n",
1955 pProxyDev->pUsbIns->pszName, pUrb, pUrb->EndPt));
1956 }
1957
1958 int rc = VINF_SUCCESS;
1959 if (irc != kIOReturnSuccess)
1960 {
1961 Log(("usbProxyDarwinUrbCancel: pProxyDev=%s pUrb=%p EndPt=%d -> %#x!\n",
1962 pProxyDev->pUsbIns->pszName, pUrb, pUrb->EndPt, irc));
1963 rc = RTErrConvertFromDarwin(irc);
1964 }
1965
1966 return rc;
1967}
1968
1969
1970static DECLCALLBACK(int) usbProxyDarwinWakeup(PUSBPROXYDEV pProxyDev)
1971{
1972 PUSBPROXYDEVOSX pDevOsX = USBPROXYDEV_2_DATA(pProxyDev, PUSBPROXYDEVOSX);
1973
1974 LogFlow(("usbProxyDarwinWakeup: pProxyDev=%p\n", pProxyDev));
1975
1976 ASMAtomicXchgBool(&pDevOsX->fReapingThreadWake, true);
1977 usbProxyDarwinReaperKick(pDevOsX);
1978 return VINF_SUCCESS;
1979}
1980
1981
1982/**
1983 * The Darwin USB Proxy Backend.
1984 */
1985extern const USBPROXYBACK g_USBProxyDeviceHost =
1986{
1987 /* pszName */
1988 "host",
1989 /* cbBackend */
1990 sizeof(USBPROXYDEVOSX),
1991 usbProxyDarwinOpen,
1992 NULL,
1993 usbProxyDarwinClose,
1994 usbProxyDarwinReset,
1995 usbProxyDarwinSetConfig,
1996 usbProxyDarwinClaimInterface,
1997 usbProxyDarwinReleaseInterface,
1998 usbProxyDarwinSetInterface,
1999 usbProxyDarwinClearHaltedEp,
2000 usbProxyDarwinUrbQueue,
2001 usbProxyDarwinUrbCancel,
2002 usbProxyDarwinUrbReap,
2003 usbProxyDarwinWakeup,
2004 0
2005};
2006
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