1 /* -*- Mode: C; indent-tabs-mode:nil -*- */
3 * darwin backend for libusb 1.0
4 * Copyright © 2008-2014 Nathan Hjelm <hjelmn@users.sourceforge.net>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
28 #include <sys/types.h>
31 #include <libkern/OSAtomic.h>
33 #include <mach/clock.h>
34 #include <mach/clock_types.h>
35 #include <mach/mach_host.h>
36 #include <mach/mach_port.h>
38 #include <AvailabilityMacros.h>
39 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
40 #include <objc/objc-auto.h>
43 #include "darwin_usb.h"
45 /* async event thread */
46 static pthread_mutex_t libusb_darwin_at_mutex = PTHREAD_MUTEX_INITIALIZER;
47 static pthread_cond_t libusb_darwin_at_cond = PTHREAD_COND_INITIALIZER;
49 static clock_serv_t clock_realtime;
50 static clock_serv_t clock_monotonic;
52 static CFRunLoopRef libusb_darwin_acfl = NULL; /* event cf loop */
53 static volatile int32_t initCount = 0;
55 static usbi_mutex_t darwin_cached_devices_lock = PTHREAD_MUTEX_INITIALIZER;
56 static struct list_head darwin_cached_devices = {&darwin_cached_devices, &darwin_cached_devices};
58 #define DARWIN_CACHED_DEVICE(a) ((struct darwin_cached_device *) (((struct darwin_device_priv *)((a)->os_priv))->dev))
60 /* async event thread */
61 static pthread_t libusb_darwin_at;
63 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
64 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
65 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
66 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
67 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
69 static int darwin_scan_devices(struct libusb_context *ctx);
70 static int process_new_device (struct libusb_context *ctx, io_service_t service);
72 #if defined(ENABLE_LOGGING)
73 static const char *darwin_error_str (int result) {
74 static char string_buffer[50];
76 case kIOReturnSuccess:
78 case kIOReturnNotOpen:
79 return "device not opened for exclusive access";
80 case kIOReturnNoDevice:
81 return "no connection to an IOService";
82 case kIOUSBNoAsyncPortErr:
83 return "no async port has been opened for interface";
84 case kIOReturnExclusiveAccess:
85 return "another process has device opened for exclusive access";
86 case kIOUSBPipeStalled:
87 return "pipe is stalled";
89 return "could not establish a connection to the Darwin kernel";
90 case kIOUSBTransactionTimeout:
91 return "transaction timed out";
92 case kIOReturnBadArgument:
93 return "invalid argument";
94 case kIOReturnAborted:
95 return "transaction aborted";
96 case kIOReturnNotResponding:
97 return "device not responding";
98 case kIOReturnOverrun:
99 return "data overrun";
100 case kIOReturnCannotWire:
101 return "physical memory can not be wired down";
102 case kIOReturnNoResources:
103 return "out of resources";
104 case kIOUSBHighSpeedSplitError:
105 return "high speed split error";
107 snprintf(string_buffer, sizeof(string_buffer), "unknown error (0x%x)", result);
108 return string_buffer;
113 static int darwin_to_libusb (int result) {
115 case kIOReturnUnderrun:
116 case kIOReturnSuccess:
117 return LIBUSB_SUCCESS;
118 case kIOReturnNotOpen:
119 case kIOReturnNoDevice:
120 return LIBUSB_ERROR_NO_DEVICE;
121 case kIOReturnExclusiveAccess:
122 return LIBUSB_ERROR_ACCESS;
123 case kIOUSBPipeStalled:
124 return LIBUSB_ERROR_PIPE;
125 case kIOReturnBadArgument:
126 return LIBUSB_ERROR_INVALID_PARAM;
127 case kIOUSBTransactionTimeout:
128 return LIBUSB_ERROR_TIMEOUT;
129 case kIOReturnNotResponding:
130 case kIOReturnAborted:
132 case kIOUSBNoAsyncPortErr:
134 return LIBUSB_ERROR_OTHER;
138 /* this function must be called with the darwin_cached_devices_lock held */
139 static void darwin_deref_cached_device(struct darwin_cached_device *cached_dev) {
140 cached_dev->refcount--;
141 /* free the device and remove it from the cache */
142 if (0 == cached_dev->refcount) {
143 list_del(&cached_dev->list);
145 (*(cached_dev->device))->Release(cached_dev->device);
150 static void darwin_ref_cached_device(struct darwin_cached_device *cached_dev) {
151 cached_dev->refcount++;
154 static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp, struct darwin_interface **interface_out) {
155 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
157 /* current interface */
158 struct darwin_interface *cInterface;
162 usbi_dbg ("converting ep address 0x%02x to pipeRef and interface", ep);
164 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
165 cInterface = &priv->interfaces[iface];
167 if (dev_handle->claimed_interfaces & (1 << iface)) {
168 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
169 if (cInterface->endpoint_addrs[i] == ep) {
176 *interface_out = cInterface;
178 usbi_dbg ("pipe %d on interface %d matches", *pipep, iface);
185 /* No pipe found with the correct endpoint address */
186 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
188 return LIBUSB_ERROR_NOT_FOUND;
191 static int usb_setup_device_iterator (io_iterator_t *deviceIterator, UInt32 location) {
192 CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBDeviceClassName);
195 return kIOReturnError;
198 CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
199 &kCFTypeDictionaryKeyCallBacks,
200 &kCFTypeDictionaryValueCallBacks);
202 if (propertyMatchDict) {
203 /* there are no unsigned CFNumber types so treat the value as signed. the os seems to do this
204 internally (CFNumberType of locationID is 3) */
205 CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberSInt32Type, &location);
207 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
208 /* release our reference to the CFNumber (CFDictionarySetValue retains it) */
209 CFRelease (locationCF);
211 CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
212 /* release out reference to the CFMutableDictionaryRef (CFDictionarySetValue retains it) */
213 CFRelease (propertyMatchDict);
215 /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
218 return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator);
221 /* Returns 1 on success, 0 on failure. */
222 static int get_ioregistry_value_number (io_service_t service, CFStringRef property, CFNumberType type, void *p) {
223 CFTypeRef cfNumber = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
227 if (CFGetTypeID(cfNumber) == CFNumberGetTypeID()) {
228 ret = CFNumberGetValue(cfNumber, type, p);
231 CFRelease (cfNumber);
237 static usb_device_t **darwin_device_from_service (io_service_t service)
239 io_cf_plugin_ref_t *plugInInterface = NULL;
240 usb_device_t **device;
241 kern_return_t result;
244 result = IOCreatePlugInInterfaceForService(service, kIOUSBDeviceUserClientTypeID,
245 kIOCFPlugInInterfaceID, &plugInInterface,
248 if (kIOReturnSuccess != result || !plugInInterface) {
249 usbi_dbg ("could not set up plugin for service: %s\n", darwin_error_str (result));
253 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
255 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
256 (*plugInInterface)->Release (plugInInterface);
261 static void darwin_devices_attached (void *ptr, io_iterator_t add_devices) {
262 struct libusb_context *ctx;
263 io_service_t service;
265 usbi_mutex_lock(&active_contexts_lock);
267 while ((service = IOIteratorNext(add_devices))) {
268 /* add this device to each active context's device list */
269 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
270 process_new_device (ctx, service);;
273 IOObjectRelease(service);
276 usbi_mutex_unlock(&active_contexts_lock);
279 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
280 struct libusb_device *dev = NULL;
281 struct libusb_context *ctx;
287 usbi_mutex_lock(&active_contexts_lock);
289 while ((device = IOIteratorNext (rem_devices)) != 0) {
290 /* get the location from the i/o registry */
291 ret = get_ioregistry_value_number (device, CFSTR("sessionID"), kCFNumberSInt64Type, &session);
292 IOObjectRelease (device);
296 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
297 usbi_dbg ("notifying context %p of device disconnect", ctx);
299 dev = usbi_get_device_by_session_id(ctx, (unsigned long) session);
301 /* signal the core that this device has been disconnected. the core will tear down this device
302 when the reference count reaches 0 */
303 usbi_disconnect_device(dev);
304 libusb_unref_device(dev);
309 usbi_mutex_unlock(&active_contexts_lock);
312 static void darwin_hotplug_poll (void)
314 /* not sure if 5 seconds will be too long/short but it should work ok */
315 mach_timespec_t timeout = {.tv_sec = 5, .tv_nsec = 0};
317 /* since a kernel thread may nodify the IOInterators used for
318 * hotplug notidication we can't just clear the iterators.
319 * instead just wait until all IOService providers are quiet */
320 (void) IOKitWaitQuiet (kIOMasterPortDefault, &timeout);
323 static void darwin_clear_iterator (io_iterator_t iter) {
326 while ((device = IOIteratorNext (iter)) != 0)
327 IOObjectRelease (device);
330 static void *darwin_event_thread_main (void *arg0) {
332 struct libusb_context *ctx = (struct libusb_context *)arg0;
333 CFRunLoopRef runloop;
335 /* Set this thread's name, so it can be seen in the debugger
336 and crash reports. */
337 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
338 pthread_setname_np ("org.libusb.device-hotplug");
340 /* Tell the Objective-C garbage collector about this thread.
341 This is required because, unlike NSThreads, pthreads are
342 not automatically registered. Although we don't use
343 Objective-C, we use CoreFoundation, which does. */
344 objc_registerThreadWithCollector();
347 /* hotplug (device arrival/removal) sources */
348 CFRunLoopSourceRef libusb_notification_cfsource;
349 io_notification_port_t libusb_notification_port;
350 io_iterator_t libusb_rem_device_iterator;
351 io_iterator_t libusb_add_device_iterator;
353 usbi_dbg ("creating hotplug event source");
355 runloop = CFRunLoopGetCurrent ();
358 /* add the notification port to the run loop */
359 libusb_notification_port = IONotificationPortCreate (kIOMasterPortDefault);
360 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
361 CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
363 /* create notifications for removed devices */
364 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
365 IOServiceMatching(kIOUSBDeviceClassName),
366 darwin_devices_detached,
367 ctx, &libusb_rem_device_iterator);
369 if (kresult != kIOReturnSuccess) {
370 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
375 /* create notifications for attached devices */
376 kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
377 IOServiceMatching(kIOUSBDeviceClassName),
378 darwin_devices_attached,
379 ctx, &libusb_add_device_iterator);
381 if (kresult != kIOReturnSuccess) {
382 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
388 darwin_clear_iterator (libusb_rem_device_iterator);
389 darwin_clear_iterator (libusb_add_device_iterator);
391 usbi_dbg ("darwin event thread ready to receive events");
393 /* signal the main thread that the hotplug runloop has been created. */
394 pthread_mutex_lock (&libusb_darwin_at_mutex);
395 libusb_darwin_acfl = runloop;
396 pthread_cond_signal (&libusb_darwin_at_cond);
397 pthread_mutex_unlock (&libusb_darwin_at_mutex);
399 /* run the runloop */
402 usbi_dbg ("darwin event thread exiting");
404 /* remove the notification cfsource */
405 CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
407 /* delete notification port */
408 IONotificationPortDestroy (libusb_notification_port);
410 /* delete iterators */
411 IOObjectRelease (libusb_rem_device_iterator);
412 IOObjectRelease (libusb_add_device_iterator);
416 libusb_darwin_acfl = NULL;
421 /* cleanup function to destroy cached devices */
422 static void __attribute__((destructor)) _darwin_finalize(void) {
423 struct darwin_cached_device *dev, *next;
425 usbi_mutex_lock(&darwin_cached_devices_lock);
426 list_for_each_entry_safe(dev, next, &darwin_cached_devices, list, struct darwin_cached_device) {
427 darwin_deref_cached_device(dev);
429 usbi_mutex_unlock(&darwin_cached_devices_lock);
432 static int darwin_init(struct libusb_context *ctx) {
433 host_name_port_t host_self;
436 rc = darwin_scan_devices (ctx);
437 if (LIBUSB_SUCCESS != rc) {
441 if (OSAtomicIncrement32Barrier(&initCount) == 1) {
442 /* create the clocks that will be used */
444 host_self = mach_host_self();
445 host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
446 host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
447 mach_port_deallocate(mach_task_self(), host_self);
449 pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, ctx);
451 pthread_mutex_lock (&libusb_darwin_at_mutex);
452 while (!libusb_darwin_acfl)
453 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
454 pthread_mutex_unlock (&libusb_darwin_at_mutex);
460 static void darwin_exit (void) {
461 if (OSAtomicDecrement32Barrier(&initCount) == 0) {
462 mach_port_deallocate(mach_task_self(), clock_realtime);
463 mach_port_deallocate(mach_task_self(), clock_monotonic);
465 /* stop the event runloop and wait for the thread to terminate. */
466 CFRunLoopStop (libusb_darwin_acfl);
467 pthread_join (libusb_darwin_at, NULL);
471 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
472 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
474 /* return cached copy */
475 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
482 static int get_configuration_index (struct libusb_device *dev, int config_value) {
483 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
485 IOUSBConfigurationDescriptorPtr desc;
488 /* is there a simpler way to determine the index? */
489 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
490 if (kresult != kIOReturnSuccess)
491 return darwin_to_libusb (kresult);
493 for (i = 0 ; i < numConfig ; i++) {
494 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
496 if (desc->bConfigurationValue == config_value)
500 /* configuration not found */
501 return LIBUSB_ERROR_NOT_FOUND;
504 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
505 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
508 if (0 == priv->active_config)
509 return LIBUSB_ERROR_NOT_FOUND;
511 config_index = get_configuration_index (dev, priv->active_config);
512 if (config_index < 0)
515 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
518 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
519 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
520 IOUSBConfigurationDescriptorPtr desc;
524 if (!priv || !priv->device)
525 return LIBUSB_ERROR_OTHER;
527 kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
528 if (kresult == kIOReturnSuccess) {
529 /* copy descriptor */
530 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
531 len = libusb_le16_to_cpu(desc->wTotalLength);
533 memmove (buffer, desc, len);
535 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
539 ret = darwin_to_libusb (kresult);
540 if (ret != LIBUSB_SUCCESS)
546 /* check whether the os has configured the device */
547 static int darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) {
548 usb_device_t **darwin_device = dev->device;
550 IOUSBConfigurationDescriptorPtr configDesc;
551 IOUSBFindInterfaceRequest request;
552 kern_return_t kresult;
553 io_iterator_t interface_iterator;
554 io_service_t firstInterface;
556 if (dev->dev_descriptor.bNumConfigurations < 1) {
557 usbi_err (ctx, "device has no configurations");
558 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
561 /* find the first configuration */
562 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
563 dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
565 /* check if the device is already configured. there is probably a better way than iterating over the
566 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
567 might lock up on the device request) */
569 /* Setup the Interface Request */
570 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
571 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
572 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
573 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
575 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
577 return darwin_to_libusb (kresult);
580 firstInterface = IOIteratorNext(interface_iterator);
582 /* done with the interface iterator */
583 IOObjectRelease(interface_iterator);
585 if (firstInterface) {
586 IOObjectRelease (firstInterface);
588 /* device is configured */
589 if (dev->dev_descriptor.bNumConfigurations == 1)
590 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
591 dev->active_config = dev->first_config;
593 /* devices with more than one configuration should work with GetConfiguration */
594 (*darwin_device)->GetConfiguration (darwin_device, &dev->active_config);
597 dev->active_config = 0;
599 usbi_dbg ("active config: %u, first config: %u", dev->active_config, dev->first_config);
604 static int darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
605 IOUSBDevRequestTO req;
607 memset (buffer, 0, buffer_size);
609 /* Set up request for descriptor/ */
610 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
611 req.bRequest = kUSBRqGetDescriptor;
612 req.wValue = desc << 8;
613 req.wIndex = desc_index;
614 req.wLength = buffer_size;
616 req.noDataTimeout = 20;
617 req.completionTimeout = 100;
619 return (*device)->DeviceRequestTO (device, &req);
622 static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct darwin_cached_device *dev) {
623 usb_device_t **device = dev->device;
624 int retries = 1, delay = 30000;
625 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
629 UInt16 idProduct, idVendor;
631 dev->can_enumerate = 0;
633 (*device)->GetDeviceClass (device, &bDeviceClass);
634 (*device)->GetDeviceProduct (device, &idProduct);
635 (*device)->GetDeviceVendor (device, &idVendor);
637 /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
638 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
639 * to follow the spec as closely as possible, try opening the device */
640 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
643 /**** retrieve device descriptor ****/
644 ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &dev->dev_descriptor, sizeof(dev->dev_descriptor));
646 if (kIOReturnOverrun == ret && kUSBDeviceDesc == dev->dev_descriptor.bDescriptorType)
647 /* received an overrun error but we still received a device descriptor */
648 ret = kIOReturnSuccess;
650 if (kIOUSBVendorIDAppleComputer == idVendor) {
651 /* NTH: don't bother retrying or unsuspending Apple devices */
655 if (kIOReturnSuccess == ret && (0 == dev->dev_descriptor.bNumConfigurations ||
656 0 == dev->dev_descriptor.bcdUSB)) {
657 /* work around for incorrectly configured devices */
658 if (try_reconfigure && is_open) {
659 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
661 /* set the first configuration */
662 (*device)->SetConfiguration(device, 1);
664 /* don't try to reconfigure again */
668 ret = kIOUSBPipeStalled;
671 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
672 /* device may be suspended. unsuspend it and try again */
673 #if DeviceVersion >= 320
676 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
677 (void)(*device)->GetUSBDeviceInformation (device, &info);
679 /* note that the device was suspended */
680 if (info & (1 << kUSBInformationDeviceIsSuspendedBit) || 0 == info)
685 /* try to unsuspend the device */
686 ret2 = (*device)->USBDeviceSuspend (device, 0);
687 if (kIOReturnSuccess != ret2) {
688 /* prevent log spew from poorly behaving devices. this indicates the
689 os actually had trouble communicating with the device */
690 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
698 if (kIOReturnSuccess != ret) {
699 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
700 /* sleep for a little while before trying again */
703 } while (kIOReturnSuccess != ret && retries--);
706 /* resuspend the device */
707 (void)(*device)->USBDeviceSuspend (device, 1);
710 (void) (*device)->USBDeviceClose (device);
712 if (ret != kIOReturnSuccess) {
713 /* a debug message was already printed out for this error */
714 if (LIBUSB_CLASS_HUB == bDeviceClass)
715 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
716 idVendor, idProduct, darwin_error_str (ret), ret);
718 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
719 idVendor, idProduct, darwin_error_str (ret), ret);
720 return darwin_to_libusb (ret);
723 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
724 if (libusb_le16_to_cpu (dev->dev_descriptor.idProduct) != idProduct) {
725 /* not a valid device */
726 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
727 idProduct, libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
728 return LIBUSB_ERROR_NO_DEVICE;
731 usbi_dbg ("cached device descriptor:");
732 usbi_dbg (" bDescriptorType: 0x%02x", dev->dev_descriptor.bDescriptorType);
733 usbi_dbg (" bcdUSB: 0x%04x", dev->dev_descriptor.bcdUSB);
734 usbi_dbg (" bDeviceClass: 0x%02x", dev->dev_descriptor.bDeviceClass);
735 usbi_dbg (" bDeviceSubClass: 0x%02x", dev->dev_descriptor.bDeviceSubClass);
736 usbi_dbg (" bDeviceProtocol: 0x%02x", dev->dev_descriptor.bDeviceProtocol);
737 usbi_dbg (" bMaxPacketSize0: 0x%02x", dev->dev_descriptor.bMaxPacketSize0);
738 usbi_dbg (" idVendor: 0x%04x", dev->dev_descriptor.idVendor);
739 usbi_dbg (" idProduct: 0x%04x", dev->dev_descriptor.idProduct);
740 usbi_dbg (" bcdDevice: 0x%04x", dev->dev_descriptor.bcdDevice);
741 usbi_dbg (" iManufacturer: 0x%02x", dev->dev_descriptor.iManufacturer);
742 usbi_dbg (" iProduct: 0x%02x", dev->dev_descriptor.iProduct);
743 usbi_dbg (" iSerialNumber: 0x%02x", dev->dev_descriptor.iSerialNumber);
744 usbi_dbg (" bNumConfigurations: 0x%02x", dev->dev_descriptor.bNumConfigurations);
746 dev->can_enumerate = 1;
748 return LIBUSB_SUCCESS;
751 static int darwin_get_cached_device(struct libusb_context *ctx, io_service_t service,
752 struct darwin_cached_device **cached_out) {
753 struct darwin_cached_device *new_device;
754 UInt64 sessionID = 0, parent_sessionID = 0;
755 int ret = LIBUSB_SUCCESS;
756 usb_device_t **device;
758 kern_return_t result;
761 /* get some info from the io registry */
762 (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
763 (void) get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, &port);
765 usbi_dbg("finding cached device for sessionID 0x%" PRIx64, sessionID);
767 result = IORegistryEntryGetParentEntry (service, kIOUSBPlane, &parent);
769 if (kIOReturnSuccess == result) {
770 (void) get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, &parent_sessionID);
771 IOObjectRelease(parent);
774 usbi_mutex_lock(&darwin_cached_devices_lock);
778 list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) {
779 usbi_dbg("matching sessionID 0x%" PRIx64 " against cached device with sessionID 0x%" PRIx64, sessionID, new_device->session);
780 if (new_device->session == sessionID) {
781 usbi_dbg("using cached device for device");
782 *cached_out = new_device;
790 usbi_dbg("caching new device with sessionID 0x%" PRIx64, sessionID);
792 device = darwin_device_from_service (service);
794 ret = LIBUSB_ERROR_NO_DEVICE;
798 new_device = calloc (1, sizeof (*new_device));
800 ret = LIBUSB_ERROR_NO_MEM;
804 /* add this device to the cached device list */
805 list_add(&new_device->list, &darwin_cached_devices);
807 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
809 /* keep a reference to this device */
810 darwin_ref_cached_device(new_device);
812 new_device->device = device;
813 new_device->session = sessionID;
814 (*device)->GetLocationID (device, &new_device->location);
815 new_device->port = port;
816 new_device->parent_session = parent_sessionID;
818 /* cache the device descriptor */
819 ret = darwin_cache_device_descriptor(ctx, new_device);
823 if (new_device->can_enumerate) {
824 snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address,
825 new_device->dev_descriptor.idVendor, new_device->dev_descriptor.idProduct,
826 new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass);
830 usbi_mutex_unlock(&darwin_cached_devices_lock);
832 /* keep track of devices regardless of if we successfully enumerate them to
833 prevent them from being enumerated multiple times */
835 *cached_out = new_device;
840 static int process_new_device (struct libusb_context *ctx, io_service_t service) {
841 struct darwin_device_priv *priv;
842 struct libusb_device *dev = NULL;
843 struct darwin_cached_device *cached_device;
848 ret = darwin_get_cached_device (ctx, service, &cached_device);
850 if (ret < 0 || !cached_device->can_enumerate) {
854 /* check current active configuration (and cache the first configuration value--
855 which may be used by claim_interface) */
856 ret = darwin_check_configuration (ctx, cached_device);
860 usbi_dbg ("allocating new device in context %p for with session 0x%" PRIx64,
861 ctx, cached_device->session);
863 dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
865 return LIBUSB_ERROR_NO_MEM;
868 priv = (struct darwin_device_priv *)dev->os_priv;
870 priv->dev = cached_device;
871 darwin_ref_cached_device (priv->dev);
873 if (cached_device->parent_session > 0) {
874 dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session);
876 dev->parent_dev = NULL;
878 dev->port_number = cached_device->port;
879 dev->bus_number = cached_device->location >> 24;
880 dev->device_address = cached_device->address;
882 (*(priv->dev->device))->GetDeviceSpeed (priv->dev->device, &devSpeed);
885 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
886 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
887 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
888 #if DeviceVersion >= 500
889 case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
892 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
895 ret = usbi_sanitize_device (dev);
899 usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
900 dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
904 usbi_connect_device (dev);
906 libusb_unref_device (dev);
912 static int darwin_scan_devices(struct libusb_context *ctx) {
913 io_iterator_t deviceIterator;
914 io_service_t service;
915 kern_return_t kresult;
917 kresult = usb_setup_device_iterator (&deviceIterator, 0);
918 if (kresult != kIOReturnSuccess)
919 return darwin_to_libusb (kresult);
921 while ((service = IOIteratorNext (deviceIterator))) {
922 (void) process_new_device (ctx, service);
924 IOObjectRelease(service);
927 IOObjectRelease(deviceIterator);
932 static int darwin_open (struct libusb_device_handle *dev_handle) {
933 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
934 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
937 if (0 == dpriv->open_count) {
938 /* try to open the device */
939 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
940 if (kresult != kIOReturnSuccess) {
941 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
943 if (kIOReturnExclusiveAccess != kresult) {
944 return darwin_to_libusb (kresult);
947 /* it is possible to perform some actions on a device that is not open so do not return an error */
953 /* create async event source */
954 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
955 if (kresult != kIOReturnSuccess) {
956 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
959 (*(dpriv->device))->USBDeviceClose (dpriv->device);
964 return darwin_to_libusb (kresult);
967 CFRetain (libusb_darwin_acfl);
969 /* add the cfSource to the aync run loop */
970 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
973 /* device opened successfully */
976 usbi_dbg ("device open for access");
981 static void darwin_close (struct libusb_device_handle *dev_handle) {
982 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
983 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
987 if (dpriv->open_count == 0) {
988 /* something is probably very wrong if this is the case */
989 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
995 /* make sure all interfaces are released */
996 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
997 if (dev_handle->claimed_interfaces & (1 << i))
998 libusb_release_interface (dev_handle, i);
1000 if (0 == dpriv->open_count) {
1001 /* delete the device's async event source */
1002 if (priv->cfSource) {
1003 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
1004 CFRelease (priv->cfSource);
1005 priv->cfSource = NULL;
1006 CFRelease (libusb_darwin_acfl);
1009 if (priv->is_open) {
1010 /* close the device */
1011 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
1013 /* Log the fact that we had a problem closing the file, however failing a
1014 * close isn't really an error, so return success anyway */
1015 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
1021 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
1022 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1024 *config = (int) dpriv->active_config;
1029 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
1030 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1034 /* Setting configuration will invalidate the interface, so we need
1035 to reclaim it. First, dispose of existing interfaces, if any. */
1036 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1037 if (dev_handle->claimed_interfaces & (1 << i))
1038 darwin_release_interface (dev_handle, i);
1040 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
1041 if (kresult != kIOReturnSuccess)
1042 return darwin_to_libusb (kresult);
1044 /* Reclaim any interfaces. */
1045 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1046 if (dev_handle->claimed_interfaces & (1 << i))
1047 darwin_claim_interface (dev_handle, i);
1049 dpriv->active_config = config;
1054 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
1055 IOUSBFindInterfaceRequest request;
1056 kern_return_t kresult;
1057 io_iterator_t interface_iterator;
1058 UInt8 bInterfaceNumber;
1061 *usbInterfacep = IO_OBJECT_NULL;
1063 /* Setup the Interface Request */
1064 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1065 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1066 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1067 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1069 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1073 while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1074 /* find the interface number */
1075 ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
1078 if (ret && bInterfaceNumber == ifc) {
1082 (void) IOObjectRelease (*usbInterfacep);
1085 /* done with the interface iterator */
1086 IOObjectRelease(interface_iterator);
1091 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
1092 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1094 /* current interface */
1095 struct darwin_interface *cInterface = &priv->interfaces[iface];
1097 kern_return_t kresult;
1099 u_int8_t numep, direction, number;
1100 u_int8_t dont_care1, dont_care3;
1101 u_int16_t dont_care2;
1104 usbi_dbg ("building table of endpoints.");
1106 /* retrieve the total number of endpoints on this interface */
1107 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1109 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1110 return darwin_to_libusb (kresult);
1113 /* iterate through pipe references */
1114 for (i = 1 ; i <= numep ; i++) {
1115 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1116 &dont_care2, &dont_care3);
1118 if (kresult != kIOReturnSuccess) {
1119 usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
1121 return darwin_to_libusb (kresult);
1124 usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
1126 cInterface->endpoint_addrs[i - 1] = (((kUSBIn == direction) << kUSBRqDirnShift) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1129 cInterface->num_endpoints = numep;
1134 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1135 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1136 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1137 io_service_t usbInterface = IO_OBJECT_NULL;
1139 IOCFPlugInInterface **plugInInterface = NULL;
1142 /* current interface */
1143 struct darwin_interface *cInterface = &priv->interfaces[iface];
1145 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1146 if (kresult != kIOReturnSuccess)
1147 return darwin_to_libusb (kresult);
1149 /* make sure we have an interface */
1150 if (!usbInterface && dpriv->first_config != 0) {
1151 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1153 /* set the configuration */
1154 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1155 if (kresult != LIBUSB_SUCCESS) {
1156 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1160 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1162 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1163 return darwin_to_libusb (kresult);
1167 if (!usbInterface) {
1168 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1169 return LIBUSB_ERROR_NOT_FOUND;
1172 /* get an interface to the device's interface */
1173 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1174 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1176 /* ignore release error */
1177 (void)IOObjectRelease (usbInterface);
1180 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1181 return darwin_to_libusb (kresult);
1184 if (!plugInInterface) {
1185 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1186 return LIBUSB_ERROR_NOT_FOUND;
1189 /* Do the actual claim */
1190 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1191 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1192 (LPVOID)&cInterface->interface);
1193 /* We no longer need the intermediate plug-in */
1194 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1195 (*plugInInterface)->Release (plugInInterface);
1196 if (kresult || !cInterface->interface) {
1197 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1198 return darwin_to_libusb (kresult);
1201 /* claim the interface */
1202 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1204 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1205 return darwin_to_libusb (kresult);
1208 /* update list of endpoints */
1209 kresult = get_endpoints (dev_handle, iface);
1211 /* this should not happen */
1212 darwin_release_interface (dev_handle, iface);
1213 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1217 cInterface->cfSource = NULL;
1219 /* create async event source */
1220 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1221 if (kresult != kIOReturnSuccess) {
1222 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1224 /* can't continue without an async event source */
1225 (void)darwin_release_interface (dev_handle, iface);
1227 return darwin_to_libusb (kresult);
1230 /* add the cfSource to the async thread's run loop */
1231 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1233 usbi_dbg ("interface opened");
1238 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1239 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1242 /* current interface */
1243 struct darwin_interface *cInterface = &priv->interfaces[iface];
1245 /* Check to see if an interface is open */
1246 if (!cInterface->interface)
1247 return LIBUSB_SUCCESS;
1249 /* clean up endpoint data */
1250 cInterface->num_endpoints = 0;
1252 /* delete the interface's async event source */
1253 if (cInterface->cfSource) {
1254 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1255 CFRelease (cInterface->cfSource);
1258 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1260 usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1262 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1263 if (kresult != kIOReturnSuccess)
1264 usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1266 cInterface->interface = IO_OBJECT_NULL;
1268 return darwin_to_libusb (kresult);
1271 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1272 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1275 /* current interface */
1276 struct darwin_interface *cInterface = &priv->interfaces[iface];
1278 if (!cInterface->interface)
1279 return LIBUSB_ERROR_NO_DEVICE;
1281 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1282 if (kresult != kIOReturnSuccess)
1283 darwin_reset_device (dev_handle);
1285 /* update list of endpoints */
1286 kresult = get_endpoints (dev_handle, iface);
1288 /* this should not happen */
1289 darwin_release_interface (dev_handle, iface);
1290 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1294 return darwin_to_libusb (kresult);
1297 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1298 /* current interface */
1299 struct darwin_interface *cInterface;
1303 /* determine the interface/endpoint to use */
1304 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, NULL, &cInterface) != 0) {
1305 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1307 return LIBUSB_ERROR_NOT_FOUND;
1310 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1311 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1313 usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1315 return darwin_to_libusb (kresult);
1318 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1319 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1320 IOUSBDeviceDescriptor descriptor;
1321 IOUSBConfigurationDescriptorPtr cached_configuration;
1322 IOUSBConfigurationDescriptor configuration;
1323 bool reenumerate = false;
1327 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1329 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1330 return darwin_to_libusb (kresult);
1334 usbi_dbg ("darwin/reset_device: checking if device descriptor changed");
1336 /* ignore return code. if we can't get a descriptor it might be worthwhile re-enumerating anway */
1337 (void) darwin_request_descriptor (dpriv->device, kUSBDeviceDesc, 0, &descriptor, sizeof (descriptor));
1339 /* check if the device descriptor has changed */
1340 if (0 != memcmp (&dpriv->dev_descriptor, &descriptor, sizeof (descriptor))) {
1345 /* check if any configuration descriptor has changed */
1346 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1347 usbi_dbg ("darwin/reset_device: checking if configuration descriptor %d changed", i);
1349 (void) darwin_request_descriptor (dpriv->device, kUSBConfDesc, i, &configuration, sizeof (configuration));
1350 (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1352 if (!cached_configuration || 0 != memcmp (cached_configuration, &configuration, sizeof (configuration))) {
1360 usbi_dbg ("darwin/reset_device: device requires reenumeration");
1361 (void) (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
1362 return LIBUSB_ERROR_NOT_FOUND;
1365 usbi_dbg ("darwin/reset_device: device reset complete");
1367 return LIBUSB_SUCCESS;
1370 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1371 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1372 io_service_t usbInterface;
1376 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1378 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1380 return darwin_to_libusb (kresult);
1383 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1384 IOObjectRelease (usbInterface);
1396 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1397 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1400 return LIBUSB_ERROR_NOT_SUPPORTED;
1403 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1406 return LIBUSB_ERROR_NOT_SUPPORTED;
1409 static void darwin_destroy_device(struct libusb_device *dev) {
1410 struct darwin_device_priv *dpriv = (struct darwin_device_priv *) dev->os_priv;
1413 /* need to hold the lock in case this is the last reference to the device */
1414 usbi_mutex_lock(&darwin_cached_devices_lock);
1415 darwin_deref_cached_device (dpriv->dev);
1417 usbi_mutex_unlock(&darwin_cached_devices_lock);
1421 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1422 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1425 uint8_t transferType;
1426 /* None of the values below are used in libusbx for bulk transfers */
1427 uint8_t direction, number, interval, pipeRef;
1428 uint16_t maxPacketSize;
1430 struct darwin_interface *cInterface;
1432 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1433 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1435 return LIBUSB_ERROR_NOT_FOUND;
1438 ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1439 &transferType, &maxPacketSize, &interval);
1442 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1443 darwin_error_str(ret), ret);
1444 return darwin_to_libusb (ret);
1447 if (0 != (transfer->length % maxPacketSize)) {
1448 /* do not need a zero packet */
1449 transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1452 /* submit the request */
1453 /* timeouts are unavailable on interrupt endpoints */
1454 if (transferType == kUSBInterrupt) {
1455 if (IS_XFERIN(transfer))
1456 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1457 transfer->length, darwin_async_io_callback, itransfer);
1459 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1460 transfer->length, darwin_async_io_callback, itransfer);
1462 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1464 if (IS_XFERIN(transfer))
1465 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1466 transfer->length, transfer->timeout, transfer->timeout,
1467 darwin_async_io_callback, (void *)itransfer);
1469 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1470 transfer->length, transfer->timeout, transfer->timeout,
1471 darwin_async_io_callback, (void *)itransfer);
1475 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1476 darwin_error_str(ret), ret);
1478 return darwin_to_libusb (ret);
1481 #if InterfaceVersion >= 550
1482 static int submit_stream_transfer(struct usbi_transfer *itransfer) {
1483 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1484 struct darwin_interface *cInterface;
1488 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1489 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1491 return LIBUSB_ERROR_NOT_FOUND;
1494 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1496 if (IS_XFERIN(transfer))
1497 ret = (*(cInterface->interface))->ReadStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1498 transfer->buffer, transfer->length, transfer->timeout,
1499 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1501 ret = (*(cInterface->interface))->WriteStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1502 transfer->buffer, transfer->length, transfer->timeout,
1503 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1506 usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1507 darwin_error_str(ret), ret);
1509 return darwin_to_libusb (ret);
1513 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1514 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1515 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1518 uint8_t direction, number, interval, pipeRef, transferType;
1519 uint16_t maxPacketSize;
1521 AbsoluteTime atTime;
1524 struct darwin_interface *cInterface;
1526 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1527 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1528 free(tpriv->isoc_framelist);
1529 tpriv->isoc_framelist = NULL;
1532 if (!tpriv->isoc_framelist) {
1533 tpriv->num_iso_packets = transfer->num_iso_packets;
1534 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1535 if (!tpriv->isoc_framelist)
1536 return LIBUSB_ERROR_NO_MEM;
1539 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1540 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1541 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1543 /* determine the interface/endpoint to use */
1544 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1545 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1547 return LIBUSB_ERROR_NOT_FOUND;
1550 /* determine the properties of this endpoint and the speed of the device */
1551 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1552 &transferType, &maxPacketSize, &interval);
1554 /* Last but not least we need the bus frame number */
1555 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1557 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1558 free(tpriv->isoc_framelist);
1559 tpriv->isoc_framelist = NULL;
1561 return darwin_to_libusb (kresult);
1564 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1565 &transferType, &maxPacketSize, &interval);
1567 /* schedule for a frame a little in the future */
1570 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1571 frame = cInterface->frames[transfer->endpoint];
1573 /* submit the request */
1574 if (IS_XFERIN(transfer))
1575 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1576 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1579 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1580 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1583 if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
1585 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1));
1587 /* High/super speed */
1588 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1)) / 8;
1590 if (kresult != kIOReturnSuccess) {
1591 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1592 darwin_error_str(kresult));
1593 free (tpriv->isoc_framelist);
1594 tpriv->isoc_framelist = NULL;
1597 return darwin_to_libusb (kresult);
1600 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1601 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1602 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1603 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1604 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1608 bzero(&tpriv->req, sizeof(tpriv->req));
1610 /* IOUSBDeviceInterface expects the request in cpu endianess */
1611 tpriv->req.bmRequestType = setup->bmRequestType;
1612 tpriv->req.bRequest = setup->bRequest;
1613 /* these values should be in bus order from libusb_fill_control_setup */
1614 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1615 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1616 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1617 /* data is stored after the libusb control block */
1618 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1619 tpriv->req.completionTimeout = transfer->timeout;
1620 tpriv->req.noDataTimeout = transfer->timeout;
1622 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1624 /* all transfers in libusb-1.0 are async */
1626 if (transfer->endpoint) {
1627 struct darwin_interface *cInterface;
1630 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1631 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1633 return LIBUSB_ERROR_NOT_FOUND;
1636 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1638 /* control request on endpoint 0 */
1639 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1641 if (kresult != kIOReturnSuccess)
1642 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1644 return darwin_to_libusb (kresult);
1647 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1648 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1650 switch (transfer->type) {
1651 case LIBUSB_TRANSFER_TYPE_CONTROL:
1652 return submit_control_transfer(itransfer);
1653 case LIBUSB_TRANSFER_TYPE_BULK:
1654 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1655 return submit_bulk_transfer(itransfer);
1656 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1657 return submit_iso_transfer(itransfer);
1658 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1659 #if InterfaceVersion >= 550
1660 return submit_stream_transfer(itransfer);
1662 usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers");
1663 return LIBUSB_ERROR_NOT_SUPPORTED;
1666 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1667 return LIBUSB_ERROR_INVALID_PARAM;
1671 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1672 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1673 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1676 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
1679 return LIBUSB_ERROR_NO_DEVICE;
1681 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1683 return darwin_to_libusb (kresult);
1686 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1687 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1688 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1689 struct darwin_interface *cInterface;
1690 uint8_t pipeRef, iface;
1693 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) {
1694 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1696 return LIBUSB_ERROR_NOT_FOUND;
1700 return LIBUSB_ERROR_NO_DEVICE;
1702 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
1704 /* abort transactions */
1705 #if InterfaceVersion >= 550
1706 if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type)
1707 (*(cInterface->interface))->AbortStreamsPipe (cInterface->interface, pipeRef, itransfer->stream_id);
1710 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1712 usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
1714 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1715 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1717 return darwin_to_libusb (kresult);
1720 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1721 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1723 switch (transfer->type) {
1724 case LIBUSB_TRANSFER_TYPE_CONTROL:
1725 return cancel_control_transfer(itransfer);
1726 case LIBUSB_TRANSFER_TYPE_BULK:
1727 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1728 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1729 return darwin_abort_transfers (itransfer);
1731 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1732 return LIBUSB_ERROR_INVALID_PARAM;
1736 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1737 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1738 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1740 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1741 free (tpriv->isoc_framelist);
1742 tpriv->isoc_framelist = NULL;
1746 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1747 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1748 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1749 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1751 usbi_dbg ("an async io operation has completed");
1753 /* if requested write a zero packet */
1754 if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
1755 struct darwin_interface *cInterface;
1758 (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface);
1760 (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
1763 tpriv->result = result;
1764 tpriv->size = (UInt32) (uintptr_t) arg0;
1766 /* signal the core that this transfer is complete */
1767 usbi_signal_transfer_completion(itransfer);
1770 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1771 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT)
1772 result = kIOUSBTransactionTimeout;
1775 case kIOReturnUnderrun:
1776 case kIOReturnSuccess:
1777 return LIBUSB_TRANSFER_COMPLETED;
1778 case kIOReturnAborted:
1779 return LIBUSB_TRANSFER_CANCELLED;
1780 case kIOUSBPipeStalled:
1781 usbi_dbg ("transfer error: pipe is stalled");
1782 return LIBUSB_TRANSFER_STALL;
1783 case kIOReturnOverrun:
1784 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1785 return LIBUSB_TRANSFER_OVERFLOW;
1786 case kIOUSBTransactionTimeout:
1787 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1788 itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
1789 return LIBUSB_TRANSFER_TIMED_OUT;
1791 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1792 return LIBUSB_TRANSFER_ERROR;
1796 static int darwin_handle_transfer_completion (struct usbi_transfer *itransfer) {
1797 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1798 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1799 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1800 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1801 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1802 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1805 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1806 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1807 return LIBUSB_ERROR_INVALID_PARAM;
1810 usbi_dbg ("handling %s completion with kernel status %d",
1811 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", tpriv->result);
1813 if (kIOReturnSuccess == tpriv->result || kIOReturnUnderrun == tpriv->result) {
1814 if (isIsoc && tpriv->isoc_framelist) {
1815 /* copy isochronous results back */
1817 for (i = 0; i < transfer->num_iso_packets ; i++) {
1818 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1819 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1820 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1823 itransfer->transferred += tpriv->size;
1826 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1827 return usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, tpriv->result));
1830 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1831 mach_timespec_t sys_time;
1832 clock_serv_t clock_ref;
1835 case USBI_CLOCK_REALTIME:
1836 /* CLOCK_REALTIME represents time since the epoch */
1837 clock_ref = clock_realtime;
1839 case USBI_CLOCK_MONOTONIC:
1840 /* use system boot time as reference for the monotonic clock */
1841 clock_ref = clock_monotonic;
1844 return LIBUSB_ERROR_INVALID_PARAM;
1847 clock_get_time (clock_ref, &sys_time);
1849 tp->tv_sec = sys_time.tv_sec;
1850 tp->tv_nsec = sys_time.tv_nsec;
1855 #if InterfaceVersion >= 550
1856 static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints,
1857 int num_endpoints) {
1858 struct darwin_interface *cInterface;
1859 UInt32 supportsStreams;
1863 /* find the mimimum number of supported streams on the endpoint list */
1864 for (i = 0 ; i < num_endpoints ; ++i) {
1865 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) {
1869 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
1870 if (num_streams > supportsStreams)
1871 num_streams = supportsStreams;
1874 /* it is an error if any endpoint in endpoints does not support streams */
1875 if (0 == num_streams)
1876 return LIBUSB_ERROR_INVALID_PARAM;
1878 /* create the streams */
1879 for (i = 0 ; i < num_endpoints ; ++i) {
1880 (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
1882 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, num_streams);
1883 if (kIOReturnSuccess != rc)
1884 return darwin_to_libusb(rc);
1890 static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) {
1891 struct darwin_interface *cInterface;
1892 UInt32 supportsStreams;
1896 for (int i = 0 ; i < num_endpoints ; ++i) {
1897 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface)))
1900 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
1901 if (0 == supportsStreams)
1902 return LIBUSB_ERROR_INVALID_PARAM;
1904 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, 0);
1905 if (kIOReturnSuccess != rc)
1906 return darwin_to_libusb(rc);
1909 return LIBUSB_SUCCESS;
1913 const struct usbi_os_backend darwin_backend = {
1916 .init = darwin_init,
1917 .exit = darwin_exit,
1918 .get_device_list = NULL, /* not needed */
1919 .get_device_descriptor = darwin_get_device_descriptor,
1920 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1921 .get_config_descriptor = darwin_get_config_descriptor,
1922 .hotplug_poll = darwin_hotplug_poll,
1924 .open = darwin_open,
1925 .close = darwin_close,
1926 .get_configuration = darwin_get_configuration,
1927 .set_configuration = darwin_set_configuration,
1928 .claim_interface = darwin_claim_interface,
1929 .release_interface = darwin_release_interface,
1931 .set_interface_altsetting = darwin_set_interface_altsetting,
1932 .clear_halt = darwin_clear_halt,
1933 .reset_device = darwin_reset_device,
1935 #if InterfaceVersion >= 550
1936 .alloc_streams = darwin_alloc_streams,
1937 .free_streams = darwin_free_streams,
1940 .kernel_driver_active = darwin_kernel_driver_active,
1941 .detach_kernel_driver = darwin_detach_kernel_driver,
1942 .attach_kernel_driver = darwin_attach_kernel_driver,
1944 .destroy_device = darwin_destroy_device,
1946 .submit_transfer = darwin_submit_transfer,
1947 .cancel_transfer = darwin_cancel_transfer,
1948 .clear_transfer_priv = darwin_clear_transfer_priv,
1950 .handle_transfer_completion = darwin_handle_transfer_completion,
1952 .clock_gettime = darwin_clock_gettime,
1954 .device_priv_size = sizeof(struct darwin_device_priv),
1955 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1956 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1957 .add_iso_packet_size = 0,