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", 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;
282 struct darwin_cached_device *old_device;
288 usbi_mutex_lock(&active_contexts_lock);
290 while ((device = IOIteratorNext (rem_devices)) != 0) {
291 /* get the location from the i/o registry */
292 ret = get_ioregistry_value_number (device, CFSTR("sessionID"), kCFNumberSInt64Type, &session);
293 IOObjectRelease (device);
297 /* we need to match darwin_ref_cached_device call made in darwin_get_cached_device function
298 otherwise no cached device will ever get freed */
299 usbi_mutex_lock(&darwin_cached_devices_lock);
300 list_for_each_entry(old_device, &darwin_cached_devices, list, struct darwin_cached_device) {
301 if (old_device->session == session) {
302 darwin_deref_cached_device (old_device);
306 usbi_mutex_unlock(&darwin_cached_devices_lock);
308 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
309 usbi_dbg ("notifying context %p of device disconnect", ctx);
311 dev = usbi_get_device_by_session_id(ctx, (unsigned long) session);
313 /* signal the core that this device has been disconnected. the core will tear down this device
314 when the reference count reaches 0 */
315 usbi_disconnect_device(dev);
316 libusb_unref_device(dev);
321 usbi_mutex_unlock(&active_contexts_lock);
324 static void darwin_hotplug_poll (void)
326 /* not sure if 5 seconds will be too long/short but it should work ok */
327 mach_timespec_t timeout = {.tv_sec = 5, .tv_nsec = 0};
329 /* since a kernel thread may nodify the IOInterators used for
330 * hotplug notidication we can't just clear the iterators.
331 * instead just wait until all IOService providers are quiet */
332 (void) IOKitWaitQuiet (kIOMasterPortDefault, &timeout);
335 static void darwin_clear_iterator (io_iterator_t iter) {
338 while ((device = IOIteratorNext (iter)) != 0)
339 IOObjectRelease (device);
342 static void *darwin_event_thread_main (void *arg0) {
344 struct libusb_context *ctx = (struct libusb_context *)arg0;
345 CFRunLoopRef runloop;
347 /* Set this thread's name, so it can be seen in the debugger
348 and crash reports. */
349 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
350 pthread_setname_np ("org.libusb.device-hotplug");
352 /* Tell the Objective-C garbage collector about this thread.
353 This is required because, unlike NSThreads, pthreads are
354 not automatically registered. Although we don't use
355 Objective-C, we use CoreFoundation, which does. */
356 objc_registerThreadWithCollector();
359 /* hotplug (device arrival/removal) sources */
360 CFRunLoopSourceRef libusb_notification_cfsource;
361 io_notification_port_t libusb_notification_port;
362 io_iterator_t libusb_rem_device_iterator;
363 io_iterator_t libusb_add_device_iterator;
365 usbi_dbg ("creating hotplug event source");
367 runloop = CFRunLoopGetCurrent ();
370 /* add the notification port to the run loop */
371 libusb_notification_port = IONotificationPortCreate (kIOMasterPortDefault);
372 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
373 CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
375 /* create notifications for removed devices */
376 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
377 IOServiceMatching(kIOUSBDeviceClassName),
378 darwin_devices_detached,
379 ctx, &libusb_rem_device_iterator);
381 if (kresult != kIOReturnSuccess) {
382 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
387 /* create notifications for attached devices */
388 kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
389 IOServiceMatching(kIOUSBDeviceClassName),
390 darwin_devices_attached,
391 ctx, &libusb_add_device_iterator);
393 if (kresult != kIOReturnSuccess) {
394 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
400 darwin_clear_iterator (libusb_rem_device_iterator);
401 darwin_clear_iterator (libusb_add_device_iterator);
403 usbi_dbg ("darwin event thread ready to receive events");
405 /* signal the main thread that the hotplug runloop has been created. */
406 pthread_mutex_lock (&libusb_darwin_at_mutex);
407 libusb_darwin_acfl = runloop;
408 pthread_cond_signal (&libusb_darwin_at_cond);
409 pthread_mutex_unlock (&libusb_darwin_at_mutex);
411 /* run the runloop */
414 usbi_dbg ("darwin event thread exiting");
416 /* remove the notification cfsource */
417 CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
419 /* delete notification port */
420 IONotificationPortDestroy (libusb_notification_port);
422 /* delete iterators */
423 IOObjectRelease (libusb_rem_device_iterator);
424 IOObjectRelease (libusb_add_device_iterator);
428 libusb_darwin_acfl = NULL;
433 /* cleanup function to destroy cached devices */
434 static void __attribute__((destructor)) _darwin_finalize(void) {
435 struct darwin_cached_device *dev, *next;
437 usbi_mutex_lock(&darwin_cached_devices_lock);
438 list_for_each_entry_safe(dev, next, &darwin_cached_devices, list, struct darwin_cached_device) {
439 darwin_deref_cached_device(dev);
441 usbi_mutex_unlock(&darwin_cached_devices_lock);
444 static int darwin_init(struct libusb_context *ctx) {
445 host_name_port_t host_self;
448 rc = darwin_scan_devices (ctx);
449 if (LIBUSB_SUCCESS != rc) {
453 if (OSAtomicIncrement32Barrier(&initCount) == 1) {
454 /* create the clocks that will be used */
456 host_self = mach_host_self();
457 host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
458 host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
459 mach_port_deallocate(mach_task_self(), host_self);
461 pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, ctx);
463 pthread_mutex_lock (&libusb_darwin_at_mutex);
464 while (!libusb_darwin_acfl)
465 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
466 pthread_mutex_unlock (&libusb_darwin_at_mutex);
472 static void darwin_exit (void) {
473 if (OSAtomicDecrement32Barrier(&initCount) == 0) {
474 mach_port_deallocate(mach_task_self(), clock_realtime);
475 mach_port_deallocate(mach_task_self(), clock_monotonic);
477 /* stop the event runloop and wait for the thread to terminate. */
478 CFRunLoopStop (libusb_darwin_acfl);
479 pthread_join (libusb_darwin_at, NULL);
483 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
484 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
486 /* return cached copy */
487 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
494 static int get_configuration_index (struct libusb_device *dev, int config_value) {
495 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
497 IOUSBConfigurationDescriptorPtr desc;
500 /* is there a simpler way to determine the index? */
501 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
502 if (kresult != kIOReturnSuccess)
503 return darwin_to_libusb (kresult);
505 for (i = 0 ; i < numConfig ; i++) {
506 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
508 if (desc->bConfigurationValue == config_value)
512 /* configuration not found */
513 return LIBUSB_ERROR_NOT_FOUND;
516 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
517 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
520 if (0 == priv->active_config)
521 return LIBUSB_ERROR_NOT_FOUND;
523 config_index = get_configuration_index (dev, priv->active_config);
524 if (config_index < 0)
527 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
530 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
531 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
532 IOUSBConfigurationDescriptorPtr desc;
536 if (!priv || !priv->device)
537 return LIBUSB_ERROR_OTHER;
539 kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
540 if (kresult == kIOReturnSuccess) {
541 /* copy descriptor */
542 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
543 len = libusb_le16_to_cpu(desc->wTotalLength);
545 memmove (buffer, desc, len);
547 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
551 ret = darwin_to_libusb (kresult);
552 if (ret != LIBUSB_SUCCESS)
558 /* check whether the os has configured the device */
559 static int darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) {
560 usb_device_t **darwin_device = dev->device;
562 IOUSBConfigurationDescriptorPtr configDesc;
563 IOUSBFindInterfaceRequest request;
564 kern_return_t kresult;
565 io_iterator_t interface_iterator;
566 io_service_t firstInterface;
568 if (dev->dev_descriptor.bNumConfigurations < 1) {
569 usbi_err (ctx, "device has no configurations");
570 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
573 /* find the first configuration */
574 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
575 dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
577 /* check if the device is already configured. there is probably a better way than iterating over the
578 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
579 might lock up on the device request) */
581 /* Setup the Interface Request */
582 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
583 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
584 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
585 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
587 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
589 return darwin_to_libusb (kresult);
592 firstInterface = IOIteratorNext(interface_iterator);
594 /* done with the interface iterator */
595 IOObjectRelease(interface_iterator);
597 if (firstInterface) {
598 IOObjectRelease (firstInterface);
600 /* device is configured */
601 if (dev->dev_descriptor.bNumConfigurations == 1)
602 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
603 dev->active_config = dev->first_config;
605 /* devices with more than one configuration should work with GetConfiguration */
606 (*darwin_device)->GetConfiguration (darwin_device, &dev->active_config);
609 dev->active_config = 0;
611 usbi_dbg ("active config: %u, first config: %u", dev->active_config, dev->first_config);
616 static int darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
617 IOUSBDevRequestTO req;
619 memset (buffer, 0, buffer_size);
621 /* Set up request for descriptor/ */
622 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
623 req.bRequest = kUSBRqGetDescriptor;
624 req.wValue = desc << 8;
625 req.wIndex = desc_index;
626 req.wLength = buffer_size;
628 req.noDataTimeout = 20;
629 req.completionTimeout = 100;
631 return (*device)->DeviceRequestTO (device, &req);
634 static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct darwin_cached_device *dev) {
635 usb_device_t **device = dev->device;
636 int retries = 1, delay = 30000;
637 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
641 UInt16 idProduct, idVendor;
643 dev->can_enumerate = 0;
645 (*device)->GetDeviceClass (device, &bDeviceClass);
646 (*device)->GetDeviceProduct (device, &idProduct);
647 (*device)->GetDeviceVendor (device, &idVendor);
649 /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
650 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
651 * to follow the spec as closely as possible, try opening the device */
652 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
655 /**** retrieve device descriptor ****/
656 ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &dev->dev_descriptor, sizeof(dev->dev_descriptor));
658 if (kIOReturnOverrun == ret && kUSBDeviceDesc == dev->dev_descriptor.bDescriptorType)
659 /* received an overrun error but we still received a device descriptor */
660 ret = kIOReturnSuccess;
662 if (kIOUSBVendorIDAppleComputer == idVendor) {
663 /* NTH: don't bother retrying or unsuspending Apple devices */
667 if (kIOReturnSuccess == ret && (0 == dev->dev_descriptor.bNumConfigurations ||
668 0 == dev->dev_descriptor.bcdUSB)) {
669 /* work around for incorrectly configured devices */
670 if (try_reconfigure && is_open) {
671 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
673 /* set the first configuration */
674 (*device)->SetConfiguration(device, 1);
676 /* don't try to reconfigure again */
680 ret = kIOUSBPipeStalled;
683 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
684 /* device may be suspended. unsuspend it and try again */
685 #if DeviceVersion >= 320
688 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
689 (void)(*device)->GetUSBDeviceInformation (device, &info);
691 /* note that the device was suspended */
692 if (info & (1 << kUSBInformationDeviceIsSuspendedBit) || 0 == info)
697 /* try to unsuspend the device */
698 ret2 = (*device)->USBDeviceSuspend (device, 0);
699 if (kIOReturnSuccess != ret2) {
700 /* prevent log spew from poorly behaving devices. this indicates the
701 os actually had trouble communicating with the device */
702 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
710 if (kIOReturnSuccess != ret) {
711 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
712 /* sleep for a little while before trying again */
715 } while (kIOReturnSuccess != ret && retries--);
718 /* resuspend the device */
719 (void)(*device)->USBDeviceSuspend (device, 1);
722 (void) (*device)->USBDeviceClose (device);
724 if (ret != kIOReturnSuccess) {
725 /* a debug message was already printed out for this error */
726 if (LIBUSB_CLASS_HUB == bDeviceClass)
727 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
728 idVendor, idProduct, darwin_error_str (ret), ret);
730 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
731 idVendor, idProduct, darwin_error_str (ret), ret);
732 return darwin_to_libusb (ret);
735 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
736 if (libusb_le16_to_cpu (dev->dev_descriptor.idProduct) != idProduct) {
737 /* not a valid device */
738 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
739 idProduct, libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
740 return LIBUSB_ERROR_NO_DEVICE;
743 usbi_dbg ("cached device descriptor:");
744 usbi_dbg (" bDescriptorType: 0x%02x", dev->dev_descriptor.bDescriptorType);
745 usbi_dbg (" bcdUSB: 0x%04x", dev->dev_descriptor.bcdUSB);
746 usbi_dbg (" bDeviceClass: 0x%02x", dev->dev_descriptor.bDeviceClass);
747 usbi_dbg (" bDeviceSubClass: 0x%02x", dev->dev_descriptor.bDeviceSubClass);
748 usbi_dbg (" bDeviceProtocol: 0x%02x", dev->dev_descriptor.bDeviceProtocol);
749 usbi_dbg (" bMaxPacketSize0: 0x%02x", dev->dev_descriptor.bMaxPacketSize0);
750 usbi_dbg (" idVendor: 0x%04x", dev->dev_descriptor.idVendor);
751 usbi_dbg (" idProduct: 0x%04x", dev->dev_descriptor.idProduct);
752 usbi_dbg (" bcdDevice: 0x%04x", dev->dev_descriptor.bcdDevice);
753 usbi_dbg (" iManufacturer: 0x%02x", dev->dev_descriptor.iManufacturer);
754 usbi_dbg (" iProduct: 0x%02x", dev->dev_descriptor.iProduct);
755 usbi_dbg (" iSerialNumber: 0x%02x", dev->dev_descriptor.iSerialNumber);
756 usbi_dbg (" bNumConfigurations: 0x%02x", dev->dev_descriptor.bNumConfigurations);
758 dev->can_enumerate = 1;
760 return LIBUSB_SUCCESS;
763 static int darwin_get_cached_device(struct libusb_context *ctx, io_service_t service,
764 struct darwin_cached_device **cached_out) {
765 struct darwin_cached_device *new_device;
766 UInt64 sessionID = 0, parent_sessionID = 0;
767 int ret = LIBUSB_SUCCESS;
768 usb_device_t **device;
770 kern_return_t result;
773 /* get some info from the io registry */
774 (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
775 (void) get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, &port);
777 usbi_dbg("finding cached device for sessionID 0x%" PRIx64, sessionID);
779 result = IORegistryEntryGetParentEntry (service, kIOUSBPlane, &parent);
781 if (kIOReturnSuccess == result) {
782 (void) get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, &parent_sessionID);
783 IOObjectRelease(parent);
786 usbi_mutex_lock(&darwin_cached_devices_lock);
790 list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) {
791 usbi_dbg("matching sessionID 0x%" PRIx64 " against cached device with sessionID 0x%" PRIx64, sessionID, new_device->session);
792 if (new_device->session == sessionID) {
793 usbi_dbg("using cached device for device");
794 *cached_out = new_device;
802 usbi_dbg("caching new device with sessionID 0x%" PRIx64, sessionID);
804 device = darwin_device_from_service (service);
806 ret = LIBUSB_ERROR_NO_DEVICE;
810 new_device = calloc (1, sizeof (*new_device));
812 ret = LIBUSB_ERROR_NO_MEM;
816 /* add this device to the cached device list */
817 list_add(&new_device->list, &darwin_cached_devices);
819 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
821 /* keep a reference to this device */
822 darwin_ref_cached_device(new_device);
824 new_device->device = device;
825 new_device->session = sessionID;
826 (*device)->GetLocationID (device, &new_device->location);
827 new_device->port = port;
828 new_device->parent_session = parent_sessionID;
830 /* cache the device descriptor */
831 ret = darwin_cache_device_descriptor(ctx, new_device);
835 if (new_device->can_enumerate) {
836 snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address,
837 new_device->dev_descriptor.idVendor, new_device->dev_descriptor.idProduct,
838 new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass);
842 usbi_mutex_unlock(&darwin_cached_devices_lock);
844 /* keep track of devices regardless of if we successfully enumerate them to
845 prevent them from being enumerated multiple times */
847 *cached_out = new_device;
852 static int process_new_device (struct libusb_context *ctx, io_service_t service) {
853 struct darwin_device_priv *priv;
854 struct libusb_device *dev = NULL;
855 struct darwin_cached_device *cached_device;
860 ret = darwin_get_cached_device (ctx, service, &cached_device);
862 if (ret < 0 || !cached_device->can_enumerate) {
866 /* check current active configuration (and cache the first configuration value--
867 which may be used by claim_interface) */
868 ret = darwin_check_configuration (ctx, cached_device);
872 usbi_dbg ("allocating new device in context %p for with session 0x%" PRIx64,
873 ctx, cached_device->session);
875 dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
877 return LIBUSB_ERROR_NO_MEM;
880 priv = (struct darwin_device_priv *)dev->os_priv;
882 priv->dev = cached_device;
883 darwin_ref_cached_device (priv->dev);
885 if (cached_device->parent_session > 0) {
886 dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session);
888 dev->parent_dev = NULL;
890 dev->port_number = cached_device->port;
891 dev->bus_number = cached_device->location >> 24;
892 dev->device_address = cached_device->address;
894 (*(priv->dev->device))->GetDeviceSpeed (priv->dev->device, &devSpeed);
897 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
898 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
899 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
900 #if DeviceVersion >= 500
901 case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
904 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
907 ret = usbi_sanitize_device (dev);
911 usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
912 dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
916 usbi_connect_device (dev);
918 libusb_unref_device (dev);
924 static int darwin_scan_devices(struct libusb_context *ctx) {
925 io_iterator_t deviceIterator;
926 io_service_t service;
927 kern_return_t kresult;
929 kresult = usb_setup_device_iterator (&deviceIterator, 0);
930 if (kresult != kIOReturnSuccess)
931 return darwin_to_libusb (kresult);
933 while ((service = IOIteratorNext (deviceIterator))) {
934 (void) process_new_device (ctx, service);
936 IOObjectRelease(service);
939 IOObjectRelease(deviceIterator);
944 static int darwin_open (struct libusb_device_handle *dev_handle) {
945 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
946 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
949 if (0 == dpriv->open_count) {
950 /* try to open the device */
951 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
952 if (kresult != kIOReturnSuccess) {
953 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
955 if (kIOReturnExclusiveAccess != kresult) {
956 return darwin_to_libusb (kresult);
959 /* it is possible to perform some actions on a device that is not open so do not return an error */
965 /* create async event source */
966 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
967 if (kresult != kIOReturnSuccess) {
968 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
971 (*(dpriv->device))->USBDeviceClose (dpriv->device);
976 return darwin_to_libusb (kresult);
979 CFRetain (libusb_darwin_acfl);
981 /* add the cfSource to the aync run loop */
982 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
985 /* device opened successfully */
988 usbi_dbg ("device open for access");
993 static void darwin_close (struct libusb_device_handle *dev_handle) {
994 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
995 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
999 if (dpriv->open_count == 0) {
1000 /* something is probably very wrong if this is the case */
1001 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!");
1005 dpriv->open_count--;
1007 /* make sure all interfaces are released */
1008 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1009 if (dev_handle->claimed_interfaces & (1 << i))
1010 libusb_release_interface (dev_handle, i);
1012 if (0 == dpriv->open_count) {
1013 /* delete the device's async event source */
1014 if (priv->cfSource) {
1015 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
1016 CFRelease (priv->cfSource);
1017 priv->cfSource = NULL;
1018 CFRelease (libusb_darwin_acfl);
1021 if (priv->is_open) {
1022 /* close the device */
1023 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
1025 /* Log the fact that we had a problem closing the file, however failing a
1026 * close isn't really an error, so return success anyway */
1027 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
1033 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
1034 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1036 *config = (int) dpriv->active_config;
1041 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
1042 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1046 /* Setting configuration will invalidate the interface, so we need
1047 to reclaim it. First, dispose of existing interfaces, if any. */
1048 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1049 if (dev_handle->claimed_interfaces & (1 << i))
1050 darwin_release_interface (dev_handle, i);
1052 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
1053 if (kresult != kIOReturnSuccess)
1054 return darwin_to_libusb (kresult);
1056 /* Reclaim any interfaces. */
1057 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1058 if (dev_handle->claimed_interfaces & (1 << i))
1059 darwin_claim_interface (dev_handle, i);
1061 dpriv->active_config = config;
1066 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
1067 IOUSBFindInterfaceRequest request;
1068 kern_return_t kresult;
1069 io_iterator_t interface_iterator;
1070 UInt8 bInterfaceNumber;
1073 *usbInterfacep = IO_OBJECT_NULL;
1075 /* Setup the Interface Request */
1076 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1077 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1078 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1079 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1081 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1085 while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1086 /* find the interface number */
1087 ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
1090 if (ret && bInterfaceNumber == ifc) {
1094 (void) IOObjectRelease (*usbInterfacep);
1097 /* done with the interface iterator */
1098 IOObjectRelease(interface_iterator);
1103 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
1104 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1106 /* current interface */
1107 struct darwin_interface *cInterface = &priv->interfaces[iface];
1109 kern_return_t kresult;
1111 u_int8_t numep, direction, number;
1112 u_int8_t dont_care1, dont_care3;
1113 u_int16_t dont_care2;
1116 usbi_dbg ("building table of endpoints.");
1118 /* retrieve the total number of endpoints on this interface */
1119 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1121 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1122 return darwin_to_libusb (kresult);
1125 /* iterate through pipe references */
1126 for (i = 1 ; i <= numep ; i++) {
1127 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1128 &dont_care2, &dont_care3);
1130 if (kresult != kIOReturnSuccess) {
1131 usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
1133 return darwin_to_libusb (kresult);
1136 usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
1138 cInterface->endpoint_addrs[i - 1] = (((kUSBIn == direction) << kUSBRqDirnShift) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1141 cInterface->num_endpoints = numep;
1146 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1147 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1148 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1149 io_service_t usbInterface = IO_OBJECT_NULL;
1151 IOCFPlugInInterface **plugInInterface = NULL;
1154 /* current interface */
1155 struct darwin_interface *cInterface = &priv->interfaces[iface];
1157 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1158 if (kresult != kIOReturnSuccess)
1159 return darwin_to_libusb (kresult);
1161 /* make sure we have an interface */
1162 if (!usbInterface && dpriv->first_config != 0) {
1163 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1165 /* set the configuration */
1166 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1167 if (kresult != LIBUSB_SUCCESS) {
1168 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1172 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1174 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1175 return darwin_to_libusb (kresult);
1179 if (!usbInterface) {
1180 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1181 return LIBUSB_ERROR_NOT_FOUND;
1184 /* get an interface to the device's interface */
1185 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1186 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1188 /* ignore release error */
1189 (void)IOObjectRelease (usbInterface);
1192 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1193 return darwin_to_libusb (kresult);
1196 if (!plugInInterface) {
1197 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1198 return LIBUSB_ERROR_NOT_FOUND;
1201 /* Do the actual claim */
1202 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1203 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1204 (LPVOID)&cInterface->interface);
1205 /* We no longer need the intermediate plug-in */
1206 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1207 (*plugInInterface)->Release (plugInInterface);
1208 if (kresult || !cInterface->interface) {
1209 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1210 return darwin_to_libusb (kresult);
1213 /* claim the interface */
1214 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1216 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1217 return darwin_to_libusb (kresult);
1220 /* update list of endpoints */
1221 kresult = get_endpoints (dev_handle, iface);
1223 /* this should not happen */
1224 darwin_release_interface (dev_handle, iface);
1225 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1229 cInterface->cfSource = NULL;
1231 /* create async event source */
1232 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1233 if (kresult != kIOReturnSuccess) {
1234 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1236 /* can't continue without an async event source */
1237 (void)darwin_release_interface (dev_handle, iface);
1239 return darwin_to_libusb (kresult);
1242 /* add the cfSource to the async thread's run loop */
1243 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1245 usbi_dbg ("interface opened");
1250 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1251 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1254 /* current interface */
1255 struct darwin_interface *cInterface = &priv->interfaces[iface];
1257 /* Check to see if an interface is open */
1258 if (!cInterface->interface)
1259 return LIBUSB_SUCCESS;
1261 /* clean up endpoint data */
1262 cInterface->num_endpoints = 0;
1264 /* delete the interface's async event source */
1265 if (cInterface->cfSource) {
1266 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1267 CFRelease (cInterface->cfSource);
1270 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1272 usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1274 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1275 if (kresult != kIOReturnSuccess)
1276 usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1278 cInterface->interface = IO_OBJECT_NULL;
1280 return darwin_to_libusb (kresult);
1283 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1284 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1287 /* current interface */
1288 struct darwin_interface *cInterface = &priv->interfaces[iface];
1290 if (!cInterface->interface)
1291 return LIBUSB_ERROR_NO_DEVICE;
1293 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1294 if (kresult != kIOReturnSuccess)
1295 darwin_reset_device (dev_handle);
1297 /* update list of endpoints */
1298 kresult = get_endpoints (dev_handle, iface);
1300 /* this should not happen */
1301 darwin_release_interface (dev_handle, iface);
1302 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1306 return darwin_to_libusb (kresult);
1309 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1310 /* current interface */
1311 struct darwin_interface *cInterface;
1315 /* determine the interface/endpoint to use */
1316 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, NULL, &cInterface) != 0) {
1317 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1319 return LIBUSB_ERROR_NOT_FOUND;
1322 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1323 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1325 usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1327 return darwin_to_libusb (kresult);
1330 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1331 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1332 IOUSBDeviceDescriptor descriptor;
1333 IOUSBConfigurationDescriptorPtr cached_configuration;
1334 IOUSBConfigurationDescriptor configuration;
1335 bool reenumerate = false;
1339 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1341 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1342 return darwin_to_libusb (kresult);
1346 usbi_dbg ("darwin/reset_device: checking if device descriptor changed");
1348 /* ignore return code. if we can't get a descriptor it might be worthwhile re-enumerating anway */
1349 (void) darwin_request_descriptor (dpriv->device, kUSBDeviceDesc, 0, &descriptor, sizeof (descriptor));
1351 /* check if the device descriptor has changed */
1352 if (0 != memcmp (&dpriv->dev_descriptor, &descriptor, sizeof (descriptor))) {
1357 /* check if any configuration descriptor has changed */
1358 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1359 usbi_dbg ("darwin/reset_device: checking if configuration descriptor %d changed", i);
1361 (void) darwin_request_descriptor (dpriv->device, kUSBConfDesc, i, &configuration, sizeof (configuration));
1362 (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1364 if (!cached_configuration || 0 != memcmp (cached_configuration, &configuration, sizeof (configuration))) {
1372 usbi_dbg ("darwin/reset_device: device requires reenumeration");
1373 (void) (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
1374 return LIBUSB_ERROR_NOT_FOUND;
1377 usbi_dbg ("darwin/reset_device: device reset complete");
1379 return LIBUSB_SUCCESS;
1382 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1383 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1384 io_service_t usbInterface;
1388 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1390 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1392 return darwin_to_libusb (kresult);
1395 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1396 IOObjectRelease (usbInterface);
1408 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1409 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1412 return LIBUSB_ERROR_NOT_SUPPORTED;
1415 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1418 return LIBUSB_ERROR_NOT_SUPPORTED;
1421 static void darwin_destroy_device(struct libusb_device *dev) {
1422 struct darwin_device_priv *dpriv = (struct darwin_device_priv *) dev->os_priv;
1425 /* need to hold the lock in case this is the last reference to the device */
1426 usbi_mutex_lock(&darwin_cached_devices_lock);
1427 darwin_deref_cached_device (dpriv->dev);
1429 usbi_mutex_unlock(&darwin_cached_devices_lock);
1433 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1434 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1437 uint8_t transferType;
1438 /* None of the values below are used in libusbx for bulk transfers */
1439 uint8_t direction, number, interval, pipeRef;
1440 uint16_t maxPacketSize;
1442 struct darwin_interface *cInterface;
1444 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1445 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1447 return LIBUSB_ERROR_NOT_FOUND;
1450 ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1451 &transferType, &maxPacketSize, &interval);
1454 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1455 darwin_error_str(ret), ret);
1456 return darwin_to_libusb (ret);
1459 if (0 != (transfer->length % maxPacketSize)) {
1460 /* do not need a zero packet */
1461 transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1464 /* submit the request */
1465 /* timeouts are unavailable on interrupt endpoints */
1466 if (transferType == kUSBInterrupt) {
1467 if (IS_XFERIN(transfer))
1468 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1469 transfer->length, darwin_async_io_callback, itransfer);
1471 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1472 transfer->length, darwin_async_io_callback, itransfer);
1474 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1476 if (IS_XFERIN(transfer))
1477 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1478 transfer->length, transfer->timeout, transfer->timeout,
1479 darwin_async_io_callback, (void *)itransfer);
1481 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1482 transfer->length, transfer->timeout, transfer->timeout,
1483 darwin_async_io_callback, (void *)itransfer);
1487 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1488 darwin_error_str(ret), ret);
1490 return darwin_to_libusb (ret);
1493 #if InterfaceVersion >= 550
1494 static int submit_stream_transfer(struct usbi_transfer *itransfer) {
1495 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1496 struct darwin_interface *cInterface;
1500 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1501 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1503 return LIBUSB_ERROR_NOT_FOUND;
1506 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1508 if (IS_XFERIN(transfer))
1509 ret = (*(cInterface->interface))->ReadStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1510 transfer->buffer, transfer->length, transfer->timeout,
1511 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1513 ret = (*(cInterface->interface))->WriteStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1514 transfer->buffer, transfer->length, transfer->timeout,
1515 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1518 usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1519 darwin_error_str(ret), ret);
1521 return darwin_to_libusb (ret);
1525 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1526 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1527 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1530 uint8_t direction, number, interval, pipeRef, transferType;
1531 uint16_t maxPacketSize;
1533 AbsoluteTime atTime;
1536 struct darwin_interface *cInterface;
1538 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1539 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1540 free(tpriv->isoc_framelist);
1541 tpriv->isoc_framelist = NULL;
1544 if (!tpriv->isoc_framelist) {
1545 tpriv->num_iso_packets = transfer->num_iso_packets;
1546 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1547 if (!tpriv->isoc_framelist)
1548 return LIBUSB_ERROR_NO_MEM;
1551 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1552 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1553 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1555 /* determine the interface/endpoint to use */
1556 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1557 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1559 return LIBUSB_ERROR_NOT_FOUND;
1562 /* determine the properties of this endpoint and the speed of the device */
1563 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1564 &transferType, &maxPacketSize, &interval);
1566 /* Last but not least we need the bus frame number */
1567 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1569 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1570 free(tpriv->isoc_framelist);
1571 tpriv->isoc_framelist = NULL;
1573 return darwin_to_libusb (kresult);
1576 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1577 &transferType, &maxPacketSize, &interval);
1579 /* schedule for a frame a little in the future */
1582 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1583 frame = cInterface->frames[transfer->endpoint];
1585 /* submit the request */
1586 if (IS_XFERIN(transfer))
1587 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1588 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1591 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1592 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1595 if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
1597 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1));
1599 /* High/super speed */
1600 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1)) / 8;
1602 if (kresult != kIOReturnSuccess) {
1603 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1604 darwin_error_str(kresult));
1605 free (tpriv->isoc_framelist);
1606 tpriv->isoc_framelist = NULL;
1609 return darwin_to_libusb (kresult);
1612 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1613 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1614 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1615 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1616 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1620 bzero(&tpriv->req, sizeof(tpriv->req));
1622 /* IOUSBDeviceInterface expects the request in cpu endianess */
1623 tpriv->req.bmRequestType = setup->bmRequestType;
1624 tpriv->req.bRequest = setup->bRequest;
1625 /* these values should be in bus order from libusb_fill_control_setup */
1626 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1627 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1628 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1629 /* data is stored after the libusb control block */
1630 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1631 tpriv->req.completionTimeout = transfer->timeout;
1632 tpriv->req.noDataTimeout = transfer->timeout;
1634 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1636 /* all transfers in libusb-1.0 are async */
1638 if (transfer->endpoint) {
1639 struct darwin_interface *cInterface;
1642 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1643 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1645 return LIBUSB_ERROR_NOT_FOUND;
1648 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1650 /* control request on endpoint 0 */
1651 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1653 if (kresult != kIOReturnSuccess)
1654 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1656 return darwin_to_libusb (kresult);
1659 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1660 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1662 switch (transfer->type) {
1663 case LIBUSB_TRANSFER_TYPE_CONTROL:
1664 return submit_control_transfer(itransfer);
1665 case LIBUSB_TRANSFER_TYPE_BULK:
1666 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1667 return submit_bulk_transfer(itransfer);
1668 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1669 return submit_iso_transfer(itransfer);
1670 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1671 #if InterfaceVersion >= 550
1672 return submit_stream_transfer(itransfer);
1674 usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers");
1675 return LIBUSB_ERROR_NOT_SUPPORTED;
1678 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1679 return LIBUSB_ERROR_INVALID_PARAM;
1683 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1684 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1685 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1688 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
1691 return LIBUSB_ERROR_NO_DEVICE;
1693 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1695 return darwin_to_libusb (kresult);
1698 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1699 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1700 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1701 struct darwin_interface *cInterface;
1702 uint8_t pipeRef, iface;
1705 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) {
1706 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1708 return LIBUSB_ERROR_NOT_FOUND;
1712 return LIBUSB_ERROR_NO_DEVICE;
1714 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
1716 /* abort transactions */
1717 #if InterfaceVersion >= 550
1718 if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type)
1719 (*(cInterface->interface))->AbortStreamsPipe (cInterface->interface, pipeRef, itransfer->stream_id);
1722 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1724 usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
1726 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1727 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1729 return darwin_to_libusb (kresult);
1732 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1733 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1735 switch (transfer->type) {
1736 case LIBUSB_TRANSFER_TYPE_CONTROL:
1737 return cancel_control_transfer(itransfer);
1738 case LIBUSB_TRANSFER_TYPE_BULK:
1739 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1740 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1741 return darwin_abort_transfers (itransfer);
1743 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1744 return LIBUSB_ERROR_INVALID_PARAM;
1748 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1749 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1750 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1752 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1753 free (tpriv->isoc_framelist);
1754 tpriv->isoc_framelist = NULL;
1758 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1759 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1760 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1761 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1763 usbi_dbg ("an async io operation has completed");
1765 /* if requested write a zero packet */
1766 if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
1767 struct darwin_interface *cInterface;
1770 (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface);
1772 (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
1775 tpriv->result = result;
1776 tpriv->size = (UInt32) (uintptr_t) arg0;
1778 /* signal the core that this transfer is complete */
1779 usbi_signal_transfer_completion(itransfer);
1782 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1783 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT)
1784 result = kIOUSBTransactionTimeout;
1787 case kIOReturnUnderrun:
1788 case kIOReturnSuccess:
1789 return LIBUSB_TRANSFER_COMPLETED;
1790 case kIOReturnAborted:
1791 return LIBUSB_TRANSFER_CANCELLED;
1792 case kIOUSBPipeStalled:
1793 usbi_dbg ("transfer error: pipe is stalled");
1794 return LIBUSB_TRANSFER_STALL;
1795 case kIOReturnOverrun:
1796 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1797 return LIBUSB_TRANSFER_OVERFLOW;
1798 case kIOUSBTransactionTimeout:
1799 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1800 itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
1801 return LIBUSB_TRANSFER_TIMED_OUT;
1803 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1804 return LIBUSB_TRANSFER_ERROR;
1808 static int darwin_handle_transfer_completion (struct usbi_transfer *itransfer) {
1809 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1810 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1811 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1812 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1813 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1814 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1817 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1818 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1819 return LIBUSB_ERROR_INVALID_PARAM;
1822 usbi_dbg ("handling %s completion with kernel status %d",
1823 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", tpriv->result);
1825 if (kIOReturnSuccess == tpriv->result || kIOReturnUnderrun == tpriv->result) {
1826 if (isIsoc && tpriv->isoc_framelist) {
1827 /* copy isochronous results back */
1829 for (i = 0; i < transfer->num_iso_packets ; i++) {
1830 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1831 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1832 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1835 itransfer->transferred += tpriv->size;
1838 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1839 return usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, tpriv->result));
1842 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1843 mach_timespec_t sys_time;
1844 clock_serv_t clock_ref;
1847 case USBI_CLOCK_REALTIME:
1848 /* CLOCK_REALTIME represents time since the epoch */
1849 clock_ref = clock_realtime;
1851 case USBI_CLOCK_MONOTONIC:
1852 /* use system boot time as reference for the monotonic clock */
1853 clock_ref = clock_monotonic;
1856 return LIBUSB_ERROR_INVALID_PARAM;
1859 clock_get_time (clock_ref, &sys_time);
1861 tp->tv_sec = sys_time.tv_sec;
1862 tp->tv_nsec = sys_time.tv_nsec;
1867 #if InterfaceVersion >= 550
1868 static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints,
1869 int num_endpoints) {
1870 struct darwin_interface *cInterface;
1871 UInt32 supportsStreams;
1875 /* find the mimimum number of supported streams on the endpoint list */
1876 for (i = 0 ; i < num_endpoints ; ++i) {
1877 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) {
1881 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
1882 if (num_streams > supportsStreams)
1883 num_streams = supportsStreams;
1886 /* it is an error if any endpoint in endpoints does not support streams */
1887 if (0 == num_streams)
1888 return LIBUSB_ERROR_INVALID_PARAM;
1890 /* create the streams */
1891 for (i = 0 ; i < num_endpoints ; ++i) {
1892 (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
1894 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, num_streams);
1895 if (kIOReturnSuccess != rc)
1896 return darwin_to_libusb(rc);
1902 static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) {
1903 struct darwin_interface *cInterface;
1904 UInt32 supportsStreams;
1908 for (int i = 0 ; i < num_endpoints ; ++i) {
1909 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface)))
1912 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
1913 if (0 == supportsStreams)
1914 return LIBUSB_ERROR_INVALID_PARAM;
1916 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, 0);
1917 if (kIOReturnSuccess != rc)
1918 return darwin_to_libusb(rc);
1921 return LIBUSB_SUCCESS;
1925 const struct usbi_os_backend darwin_backend = {
1928 .init = darwin_init,
1929 .exit = darwin_exit,
1930 .get_device_list = NULL, /* not needed */
1931 .get_device_descriptor = darwin_get_device_descriptor,
1932 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1933 .get_config_descriptor = darwin_get_config_descriptor,
1934 .hotplug_poll = darwin_hotplug_poll,
1936 .open = darwin_open,
1937 .close = darwin_close,
1938 .get_configuration = darwin_get_configuration,
1939 .set_configuration = darwin_set_configuration,
1940 .claim_interface = darwin_claim_interface,
1941 .release_interface = darwin_release_interface,
1943 .set_interface_altsetting = darwin_set_interface_altsetting,
1944 .clear_halt = darwin_clear_halt,
1945 .reset_device = darwin_reset_device,
1947 #if InterfaceVersion >= 550
1948 .alloc_streams = darwin_alloc_streams,
1949 .free_streams = darwin_free_streams,
1952 .kernel_driver_active = darwin_kernel_driver_active,
1953 .detach_kernel_driver = darwin_detach_kernel_driver,
1954 .attach_kernel_driver = darwin_attach_kernel_driver,
1956 .destroy_device = darwin_destroy_device,
1958 .submit_transfer = darwin_submit_transfer,
1959 .cancel_transfer = darwin_cancel_transfer,
1960 .clear_transfer_priv = darwin_clear_transfer_priv,
1962 .handle_transfer_completion = darwin_handle_transfer_completion,
1964 .clock_gettime = darwin_clock_gettime,
1966 .device_priv_size = sizeof(struct darwin_device_priv),
1967 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1968 .transfer_priv_size = sizeof(struct darwin_transfer_priv),