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, *ifcp);
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 /* create a file descriptor for notifications */
979 /* set the pipe to be non-blocking */
980 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
982 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
984 usbi_dbg ("device open for access");
989 static void darwin_close (struct libusb_device_handle *dev_handle) {
990 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
991 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
995 if (dpriv->open_count == 0) {
996 /* something is probably very wrong if this is the case */
997 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
1001 dpriv->open_count--;
1003 /* make sure all interfaces are released */
1004 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1005 if (dev_handle->claimed_interfaces & (1 << i))
1006 libusb_release_interface (dev_handle, i);
1008 if (0 == dpriv->open_count) {
1009 /* delete the device's async event source */
1010 if (priv->cfSource) {
1011 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
1012 CFRelease (priv->cfSource);
1013 priv->cfSource = NULL;
1014 CFRelease (libusb_darwin_acfl);
1017 if (priv->is_open) {
1018 /* close the device */
1019 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
1021 /* Log the fact that we had a problem closing the file, however failing a
1022 * close isn't really an error, so return success anyway */
1023 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
1028 /* file descriptors are maintained per-instance */
1029 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
1030 close (priv->fds[1]);
1031 close (priv->fds[0]);
1033 priv->fds[0] = priv->fds[1] = -1;
1036 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
1037 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1039 *config = (int) dpriv->active_config;
1044 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
1045 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1049 /* Setting configuration will invalidate the interface, so we need
1050 to reclaim it. First, dispose of existing interfaces, if any. */
1051 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1052 if (dev_handle->claimed_interfaces & (1 << i))
1053 darwin_release_interface (dev_handle, i);
1055 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
1056 if (kresult != kIOReturnSuccess)
1057 return darwin_to_libusb (kresult);
1059 /* Reclaim any interfaces. */
1060 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1061 if (dev_handle->claimed_interfaces & (1 << i))
1062 darwin_claim_interface (dev_handle, i);
1064 dpriv->active_config = config;
1069 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
1070 IOUSBFindInterfaceRequest request;
1071 kern_return_t kresult;
1072 io_iterator_t interface_iterator;
1073 UInt8 bInterfaceNumber;
1076 *usbInterfacep = IO_OBJECT_NULL;
1078 /* Setup the Interface Request */
1079 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1080 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1081 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1082 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1084 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1088 while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1089 /* find the interface number */
1090 ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
1093 if (ret && bInterfaceNumber == ifc) {
1097 (void) IOObjectRelease (*usbInterfacep);
1100 /* done with the interface iterator */
1101 IOObjectRelease(interface_iterator);
1106 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
1107 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1109 /* current interface */
1110 struct darwin_interface *cInterface = &priv->interfaces[iface];
1112 kern_return_t kresult;
1114 u_int8_t numep, direction, number;
1115 u_int8_t dont_care1, dont_care3;
1116 u_int16_t dont_care2;
1119 usbi_dbg ("building table of endpoints.");
1121 /* retrieve the total number of endpoints on this interface */
1122 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1124 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1125 return darwin_to_libusb (kresult);
1128 /* iterate through pipe references */
1129 for (i = 1 ; i <= numep ; i++) {
1130 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1131 &dont_care2, &dont_care3);
1133 if (kresult != kIOReturnSuccess) {
1134 usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
1136 return darwin_to_libusb (kresult);
1139 usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
1141 cInterface->endpoint_addrs[i - 1] = (((kUSBIn == direction) << kUSBRqDirnShift) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1144 cInterface->num_endpoints = numep;
1149 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1150 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1151 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1152 io_service_t usbInterface = IO_OBJECT_NULL;
1154 IOCFPlugInInterface **plugInInterface = NULL;
1157 /* current interface */
1158 struct darwin_interface *cInterface = &priv->interfaces[iface];
1160 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1161 if (kresult != kIOReturnSuccess)
1162 return darwin_to_libusb (kresult);
1164 /* make sure we have an interface */
1165 if (!usbInterface && dpriv->first_config != 0) {
1166 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1168 /* set the configuration */
1169 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1170 if (kresult != LIBUSB_SUCCESS) {
1171 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1175 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1177 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1178 return darwin_to_libusb (kresult);
1182 if (!usbInterface) {
1183 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1184 return LIBUSB_ERROR_NOT_FOUND;
1187 /* get an interface to the device's interface */
1188 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1189 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1191 /* ignore release error */
1192 (void)IOObjectRelease (usbInterface);
1195 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1196 return darwin_to_libusb (kresult);
1199 if (!plugInInterface) {
1200 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1201 return LIBUSB_ERROR_NOT_FOUND;
1204 /* Do the actual claim */
1205 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1206 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1207 (LPVOID)&cInterface->interface);
1208 /* We no longer need the intermediate plug-in */
1209 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1210 (*plugInInterface)->Release (plugInInterface);
1211 if (kresult || !cInterface->interface) {
1212 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1213 return darwin_to_libusb (kresult);
1216 /* claim the interface */
1217 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1219 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1220 return darwin_to_libusb (kresult);
1223 /* update list of endpoints */
1224 kresult = get_endpoints (dev_handle, iface);
1226 /* this should not happen */
1227 darwin_release_interface (dev_handle, iface);
1228 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1232 cInterface->cfSource = NULL;
1234 /* create async event source */
1235 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1236 if (kresult != kIOReturnSuccess) {
1237 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1239 /* can't continue without an async event source */
1240 (void)darwin_release_interface (dev_handle, iface);
1242 return darwin_to_libusb (kresult);
1245 /* add the cfSource to the async thread's run loop */
1246 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1248 usbi_dbg ("interface opened");
1253 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1254 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1257 /* current interface */
1258 struct darwin_interface *cInterface = &priv->interfaces[iface];
1260 /* Check to see if an interface is open */
1261 if (!cInterface->interface)
1262 return LIBUSB_SUCCESS;
1264 /* clean up endpoint data */
1265 cInterface->num_endpoints = 0;
1267 /* delete the interface's async event source */
1268 if (cInterface->cfSource) {
1269 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1270 CFRelease (cInterface->cfSource);
1273 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1275 usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1277 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1278 if (kresult != kIOReturnSuccess)
1279 usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1281 cInterface->interface = IO_OBJECT_NULL;
1283 return darwin_to_libusb (kresult);
1286 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1287 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1290 /* current interface */
1291 struct darwin_interface *cInterface = &priv->interfaces[iface];
1293 if (!cInterface->interface)
1294 return LIBUSB_ERROR_NO_DEVICE;
1296 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1297 if (kresult != kIOReturnSuccess)
1298 darwin_reset_device (dev_handle);
1300 /* update list of endpoints */
1301 kresult = get_endpoints (dev_handle, iface);
1303 /* this should not happen */
1304 darwin_release_interface (dev_handle, iface);
1305 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1309 return darwin_to_libusb (kresult);
1312 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1313 /* current interface */
1314 struct darwin_interface *cInterface;
1318 /* determine the interface/endpoint to use */
1319 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, NULL, &cInterface) != 0) {
1320 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1322 return LIBUSB_ERROR_NOT_FOUND;
1325 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1326 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1328 usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1330 return darwin_to_libusb (kresult);
1333 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1334 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1335 IOUSBDeviceDescriptor descriptor;
1336 IOUSBConfigurationDescriptorPtr cached_configuration;
1337 IOUSBConfigurationDescriptor configuration;
1338 bool reenumerate = false;
1342 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1344 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1345 return darwin_to_libusb (kresult);
1349 usbi_dbg ("darwin/reset_device: checking if device descriptor changed");
1351 /* ignore return code. if we can't get a descriptor it might be worthwhile re-enumerating anway */
1352 (void) darwin_request_descriptor (dpriv->device, kUSBDeviceDesc, 0, &descriptor, sizeof (descriptor));
1354 /* check if the device descriptor has changed */
1355 if (0 != memcmp (&dpriv->dev_descriptor, &descriptor, sizeof (descriptor))) {
1360 /* check if any configuration descriptor has changed */
1361 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1362 usbi_dbg ("darwin/reset_device: checking if configuration descriptor %d changed", i);
1364 (void) darwin_request_descriptor (dpriv->device, kUSBConfDesc, i, &configuration, sizeof (configuration));
1365 (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1367 if (!cached_configuration || 0 != memcmp (cached_configuration, &configuration, sizeof (configuration))) {
1375 usbi_dbg ("darwin/reset_device: device requires reenumeration");
1376 (void) (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
1377 return LIBUSB_ERROR_NOT_FOUND;
1380 usbi_dbg ("darwin/reset_device: device reset complete");
1382 return LIBUSB_SUCCESS;
1385 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1386 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1387 io_service_t usbInterface;
1391 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1393 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1395 return darwin_to_libusb (kresult);
1398 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1399 IOObjectRelease (usbInterface);
1411 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1412 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1415 return LIBUSB_ERROR_NOT_SUPPORTED;
1418 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1421 return LIBUSB_ERROR_NOT_SUPPORTED;
1424 static void darwin_destroy_device(struct libusb_device *dev) {
1425 struct darwin_device_priv *dpriv = (struct darwin_device_priv *) dev->os_priv;
1428 /* need to hold the lock in case this is the last reference to the device */
1429 usbi_mutex_lock(&darwin_cached_devices_lock);
1430 darwin_deref_cached_device (dpriv->dev);
1432 usbi_mutex_unlock(&darwin_cached_devices_lock);
1436 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1437 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1440 uint8_t transferType;
1441 /* None of the values below are used in libusbx for bulk transfers */
1442 uint8_t direction, number, interval, pipeRef;
1443 uint16_t maxPacketSize;
1445 struct darwin_interface *cInterface;
1447 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1448 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1450 return LIBUSB_ERROR_NOT_FOUND;
1453 ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1454 &transferType, &maxPacketSize, &interval);
1457 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1458 darwin_error_str(ret), ret);
1459 return darwin_to_libusb (ret);
1462 if (0 != (transfer->length % maxPacketSize)) {
1463 /* do not need a zero packet */
1464 transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1467 /* submit the request */
1468 /* timeouts are unavailable on interrupt endpoints */
1469 if (transferType == kUSBInterrupt) {
1470 if (IS_XFERIN(transfer))
1471 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1472 transfer->length, darwin_async_io_callback, itransfer);
1474 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1475 transfer->length, darwin_async_io_callback, itransfer);
1477 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1479 if (IS_XFERIN(transfer))
1480 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1481 transfer->length, transfer->timeout, transfer->timeout,
1482 darwin_async_io_callback, (void *)itransfer);
1484 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1485 transfer->length, transfer->timeout, transfer->timeout,
1486 darwin_async_io_callback, (void *)itransfer);
1490 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1491 darwin_error_str(ret), ret);
1493 return darwin_to_libusb (ret);
1496 #if InterfaceVersion >= 550
1497 static int submit_stream_transfer(struct usbi_transfer *itransfer) {
1498 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1499 struct darwin_interface *cInterface;
1503 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1504 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1506 return LIBUSB_ERROR_NOT_FOUND;
1509 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1511 if (IS_XFERIN(transfer))
1512 ret = (*(cInterface->interface))->ReadStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1513 transfer->buffer, transfer->length, transfer->timeout,
1514 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1516 ret = (*(cInterface->interface))->WriteStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1517 transfer->buffer, transfer->length, transfer->timeout,
1518 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1521 usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1522 darwin_error_str(ret), ret);
1524 return darwin_to_libusb (ret);
1528 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1529 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1530 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1533 uint8_t direction, number, interval, pipeRef, transferType;
1534 uint16_t maxPacketSize;
1536 AbsoluteTime atTime;
1539 struct darwin_interface *cInterface;
1541 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1542 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1543 free(tpriv->isoc_framelist);
1544 tpriv->isoc_framelist = NULL;
1547 if (!tpriv->isoc_framelist) {
1548 tpriv->num_iso_packets = transfer->num_iso_packets;
1549 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1550 if (!tpriv->isoc_framelist)
1551 return LIBUSB_ERROR_NO_MEM;
1554 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1555 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1556 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1558 /* determine the interface/endpoint to use */
1559 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1560 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1562 return LIBUSB_ERROR_NOT_FOUND;
1565 /* determine the properties of this endpoint and the speed of the device */
1566 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1567 &transferType, &maxPacketSize, &interval);
1569 /* Last but not least we need the bus frame number */
1570 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1572 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1573 free(tpriv->isoc_framelist);
1574 tpriv->isoc_framelist = NULL;
1576 return darwin_to_libusb (kresult);
1579 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1580 &transferType, &maxPacketSize, &interval);
1582 /* schedule for a frame a little in the future */
1585 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1586 frame = cInterface->frames[transfer->endpoint];
1588 /* submit the request */
1589 if (IS_XFERIN(transfer))
1590 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1591 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1594 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1595 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1598 if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
1600 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1));
1602 /* High/super speed */
1603 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1)) / 8;
1605 if (kresult != kIOReturnSuccess) {
1606 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1607 darwin_error_str(kresult));
1608 free (tpriv->isoc_framelist);
1609 tpriv->isoc_framelist = NULL;
1612 return darwin_to_libusb (kresult);
1615 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1616 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1617 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1618 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1619 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1623 bzero(&tpriv->req, sizeof(tpriv->req));
1625 /* IOUSBDeviceInterface expects the request in cpu endianess */
1626 tpriv->req.bmRequestType = setup->bmRequestType;
1627 tpriv->req.bRequest = setup->bRequest;
1628 /* these values should be in bus order from libusb_fill_control_setup */
1629 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1630 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1631 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1632 /* data is stored after the libusb control block */
1633 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1634 tpriv->req.completionTimeout = transfer->timeout;
1635 tpriv->req.noDataTimeout = transfer->timeout;
1637 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1639 /* all transfers in libusb-1.0 are async */
1641 if (transfer->endpoint) {
1642 struct darwin_interface *cInterface;
1645 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1646 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1648 return LIBUSB_ERROR_NOT_FOUND;
1651 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1653 /* control request on endpoint 0 */
1654 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1656 if (kresult != kIOReturnSuccess)
1657 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1659 return darwin_to_libusb (kresult);
1662 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1663 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1665 switch (transfer->type) {
1666 case LIBUSB_TRANSFER_TYPE_CONTROL:
1667 return submit_control_transfer(itransfer);
1668 case LIBUSB_TRANSFER_TYPE_BULK:
1669 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1670 return submit_bulk_transfer(itransfer);
1671 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1672 return submit_iso_transfer(itransfer);
1673 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1674 #if InterfaceVersion >= 550
1675 return submit_stream_transfer(itransfer);
1677 usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers");
1678 return LIBUSB_ERROR_NOT_SUPPORTED;
1681 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1682 return LIBUSB_ERROR_INVALID_PARAM;
1686 static int cancel_control_transfer(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);
1691 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
1694 return LIBUSB_ERROR_NO_DEVICE;
1696 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1698 return darwin_to_libusb (kresult);
1701 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1702 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1703 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1704 struct darwin_interface *cInterface;
1705 uint8_t pipeRef, iface;
1708 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) {
1709 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1711 return LIBUSB_ERROR_NOT_FOUND;
1715 return LIBUSB_ERROR_NO_DEVICE;
1717 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
1719 /* abort transactions */
1720 #if InterfaceVersion >= 550
1721 if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type)
1722 (*(cInterface->interface))->AbortStreamsPipe (cInterface->interface, pipeRef, itransfer->stream_id);
1725 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1727 usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
1729 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1730 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1732 return darwin_to_libusb (kresult);
1735 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1736 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1738 switch (transfer->type) {
1739 case LIBUSB_TRANSFER_TYPE_CONTROL:
1740 return cancel_control_transfer(itransfer);
1741 case LIBUSB_TRANSFER_TYPE_BULK:
1742 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1743 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1744 return darwin_abort_transfers (itransfer);
1746 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1747 return LIBUSB_ERROR_INVALID_PARAM;
1751 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1752 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1753 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1755 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1756 free (tpriv->isoc_framelist);
1757 tpriv->isoc_framelist = NULL;
1761 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1762 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1763 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1764 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1765 struct darwin_msg_async_io_complete message = {.itransfer = itransfer, .result = result,
1766 .size = (UInt32) (uintptr_t) arg0};
1768 usbi_dbg ("an async io operation has completed");
1770 /* if requested write a zero packet */
1771 if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
1772 struct darwin_interface *cInterface;
1775 (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface);
1777 (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
1780 /* send a completion message to the device's file descriptor */
1781 write (priv->fds[1], &message, sizeof (message));
1784 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1785 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT)
1786 result = kIOUSBTransactionTimeout;
1789 case kIOReturnUnderrun:
1790 case kIOReturnSuccess:
1791 return LIBUSB_TRANSFER_COMPLETED;
1792 case kIOReturnAborted:
1793 return LIBUSB_TRANSFER_CANCELLED;
1794 case kIOUSBPipeStalled:
1795 usbi_dbg ("transfer error: pipe is stalled");
1796 return LIBUSB_TRANSFER_STALL;
1797 case kIOReturnOverrun:
1798 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1799 return LIBUSB_TRANSFER_OVERFLOW;
1800 case kIOUSBTransactionTimeout:
1801 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1802 itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
1803 return LIBUSB_TRANSFER_TIMED_OUT;
1805 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1806 return LIBUSB_TRANSFER_ERROR;
1810 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1811 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1812 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1813 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1814 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1815 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1816 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1819 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1820 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1824 usbi_dbg ("handling %s completion with kernel status %d",
1825 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
1827 if (kIOReturnSuccess == result || kIOReturnUnderrun == result) {
1828 if (isIsoc && tpriv->isoc_framelist) {
1829 /* copy isochronous results back */
1831 for (i = 0; i < transfer->num_iso_packets ; i++) {
1832 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1833 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1834 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1837 itransfer->transferred += io_size;
1840 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1841 usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
1844 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready) {
1845 struct darwin_msg_async_io_complete message;
1846 POLL_NFDS_TYPE i = 0;
1849 usbi_mutex_lock(&ctx->open_devs_lock);
1851 for (i = 0; i < nfds && num_ready > 0; i++) {
1852 struct pollfd *pollfd = &fds[i];
1854 usbi_dbg ("checking fd %i with revents = %x", pollfd->fd, pollfd->revents);
1856 if (!pollfd->revents)
1861 if (pollfd->revents & POLLERR) {
1862 /* this probably will never happen so ignore the error an move on. */
1866 /* there is only one type of message */
1867 ret = read (pollfd->fd, &message, sizeof (message));
1868 if (ret < (ssize_t) sizeof (message)) {
1869 usbi_dbg ("WARNING: short read on async io completion pipe\n");
1873 darwin_handle_callback (message.itransfer, message.result, message.size);
1876 usbi_mutex_unlock(&ctx->open_devs_lock);
1881 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1882 mach_timespec_t sys_time;
1883 clock_serv_t clock_ref;
1886 case USBI_CLOCK_REALTIME:
1887 /* CLOCK_REALTIME represents time since the epoch */
1888 clock_ref = clock_realtime;
1890 case USBI_CLOCK_MONOTONIC:
1891 /* use system boot time as reference for the monotonic clock */
1892 clock_ref = clock_monotonic;
1895 return LIBUSB_ERROR_INVALID_PARAM;
1898 clock_get_time (clock_ref, &sys_time);
1900 tp->tv_sec = sys_time.tv_sec;
1901 tp->tv_nsec = sys_time.tv_nsec;
1906 #if InterfaceVersion >= 550
1907 static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints,
1908 int num_endpoints) {
1909 struct darwin_interface *cInterface;
1910 UInt32 supportsStreams;
1914 /* find the mimimum number of supported streams on the endpoint list */
1915 for (i = 0 ; i < num_endpoints ; ++i) {
1916 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) {
1920 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
1921 if (num_streams > supportsStreams)
1922 num_streams = supportsStreams;
1925 /* it is an error if any endpoint in endpoints does not support streams */
1926 if (0 == num_streams)
1927 return LIBUSB_ERROR_INVALID_PARAM;
1929 /* create the streams */
1930 for (i = 0 ; i < num_endpoints ; ++i) {
1931 (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
1933 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, num_streams);
1934 if (kIOReturnSuccess != rc)
1935 return darwin_to_libusb(rc);
1941 static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) {
1942 struct darwin_interface *cInterface;
1943 UInt32 supportsStreams;
1947 for (int i = 0 ; i < num_endpoints ; ++i) {
1948 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface)))
1951 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
1952 if (0 == supportsStreams)
1953 return LIBUSB_ERROR_INVALID_PARAM;
1955 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, 0);
1956 if (kIOReturnSuccess != rc)
1957 return darwin_to_libusb(rc);
1960 return LIBUSB_SUCCESS;
1964 const struct usbi_os_backend darwin_backend = {
1967 .init = darwin_init,
1968 .exit = darwin_exit,
1969 .get_device_list = NULL, /* not needed */
1970 .get_device_descriptor = darwin_get_device_descriptor,
1971 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1972 .get_config_descriptor = darwin_get_config_descriptor,
1973 .hotplug_poll = darwin_hotplug_poll,
1975 .open = darwin_open,
1976 .close = darwin_close,
1977 .get_configuration = darwin_get_configuration,
1978 .set_configuration = darwin_set_configuration,
1979 .claim_interface = darwin_claim_interface,
1980 .release_interface = darwin_release_interface,
1982 .set_interface_altsetting = darwin_set_interface_altsetting,
1983 .clear_halt = darwin_clear_halt,
1984 .reset_device = darwin_reset_device,
1986 #if InterfaceVersion >= 550
1987 .alloc_streams = darwin_alloc_streams,
1988 .free_streams = darwin_free_streams,
1991 .kernel_driver_active = darwin_kernel_driver_active,
1992 .detach_kernel_driver = darwin_detach_kernel_driver,
1993 .attach_kernel_driver = darwin_attach_kernel_driver,
1995 .destroy_device = darwin_destroy_device,
1997 .submit_transfer = darwin_submit_transfer,
1998 .cancel_transfer = darwin_cancel_transfer,
1999 .clear_transfer_priv = darwin_clear_transfer_priv,
2001 .handle_events = op_handle_events,
2003 .clock_gettime = darwin_clock_gettime,
2005 .device_priv_size = sizeof(struct darwin_device_priv),
2006 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
2007 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
2008 .add_iso_packet_size = 0,