1 /* -*- Mode: C; indent-tabs-mode:nil -*- */
3 * darwin backend for libusb 1.0
4 * Copyright © 2008-2013 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 while ((device = IOIteratorNext (rem_devices)) != 0) {
288 /* get the location from the i/o registry */
289 ret = get_ioregistry_value_number (device, CFSTR("sessionID"), kCFNumberSInt64Type, &session);
290 IOObjectRelease (device);
294 usbi_mutex_lock(&active_contexts_lock);
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);
308 usbi_mutex_unlock(&active_contexts_lock);
312 static void darwin_clear_iterator (io_iterator_t iter) {
315 while ((device = IOIteratorNext (iter)) != 0)
316 IOObjectRelease (device);
319 static void *darwin_event_thread_main (void *arg0) {
321 struct libusb_context *ctx = (struct libusb_context *)arg0;
322 CFRunLoopRef runloop;
324 /* Set this thread's name, so it can be seen in the debugger
325 and crash reports. */
326 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
327 pthread_setname_np ("org.libusb.device-hotplug");
329 /* Tell the Objective-C garbage collector about this thread.
330 This is required because, unlike NSThreads, pthreads are
331 not automatically registered. Although we don't use
332 Objective-C, we use CoreFoundation, which does. */
333 objc_registerThreadWithCollector();
336 /* hotplug (device arrival/removal) sources */
337 CFRunLoopSourceRef libusb_notification_cfsource;
338 io_notification_port_t libusb_notification_port;
339 io_iterator_t libusb_rem_device_iterator;
340 io_iterator_t libusb_add_device_iterator;
342 usbi_dbg ("creating hotplug event source");
344 runloop = CFRunLoopGetCurrent ();
347 /* add the notification port to the run loop */
348 libusb_notification_port = IONotificationPortCreate (kIOMasterPortDefault);
349 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
350 CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
352 /* create notifications for removed devices */
353 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
354 IOServiceMatching(kIOUSBDeviceClassName),
355 darwin_devices_detached,
356 ctx, &libusb_rem_device_iterator);
358 if (kresult != kIOReturnSuccess) {
359 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
364 /* create notifications for attached devices */
365 kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
366 IOServiceMatching(kIOUSBDeviceClassName),
367 darwin_devices_attached,
368 ctx, &libusb_add_device_iterator);
370 if (kresult != kIOReturnSuccess) {
371 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
377 darwin_clear_iterator (libusb_rem_device_iterator);
378 darwin_clear_iterator (libusb_add_device_iterator);
380 usbi_dbg ("darwin event thread ready to receive events");
382 /* signal the main thread that the hotplug runloop has been created. */
383 pthread_mutex_lock (&libusb_darwin_at_mutex);
384 libusb_darwin_acfl = runloop;
385 pthread_cond_signal (&libusb_darwin_at_cond);
386 pthread_mutex_unlock (&libusb_darwin_at_mutex);
388 /* run the runloop */
391 usbi_dbg ("darwin event thread exiting");
393 /* remove the notification cfsource */
394 CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
396 /* delete notification port */
397 IONotificationPortDestroy (libusb_notification_port);
399 /* delete iterators */
400 IOObjectRelease (libusb_rem_device_iterator);
401 IOObjectRelease (libusb_add_device_iterator);
405 libusb_darwin_acfl = NULL;
410 /* cleanup function to destroy cached devices */
411 static void __attribute__((destructor)) _darwin_finalize(void) {
412 struct darwin_cached_device *dev, *next;
414 usbi_mutex_lock(&darwin_cached_devices_lock);
415 list_for_each_entry_safe(dev, next, &darwin_cached_devices, list, struct darwin_cached_device) {
416 darwin_deref_cached_device(dev);
418 usbi_mutex_unlock(&darwin_cached_devices_lock);
421 static int darwin_init(struct libusb_context *ctx) {
422 host_name_port_t host_self;
425 rc = darwin_scan_devices (ctx);
426 if (LIBUSB_SUCCESS != rc) {
430 if (OSAtomicIncrement32Barrier(&initCount) == 1) {
431 /* create the clocks that will be used */
433 host_self = mach_host_self();
434 host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
435 host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
436 mach_port_deallocate(mach_task_self(), host_self);
438 pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, ctx);
440 pthread_mutex_lock (&libusb_darwin_at_mutex);
441 while (!libusb_darwin_acfl)
442 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
443 pthread_mutex_unlock (&libusb_darwin_at_mutex);
449 static void darwin_exit (void) {
450 if (OSAtomicDecrement32Barrier(&initCount) == 0) {
451 mach_port_deallocate(mach_task_self(), clock_realtime);
452 mach_port_deallocate(mach_task_self(), clock_monotonic);
454 /* stop the event runloop and wait for the thread to terminate. */
455 CFRunLoopStop (libusb_darwin_acfl);
456 pthread_join (libusb_darwin_at, NULL);
460 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
461 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
463 /* return cached copy */
464 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
471 static int get_configuration_index (struct libusb_device *dev, int config_value) {
472 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
474 IOUSBConfigurationDescriptorPtr desc;
477 /* is there a simpler way to determine the index? */
478 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
479 if (kresult != kIOReturnSuccess)
480 return darwin_to_libusb (kresult);
482 for (i = 0 ; i < numConfig ; i++) {
483 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
485 if (desc->bConfigurationValue == config_value)
489 /* configuration not found */
490 return LIBUSB_ERROR_NOT_FOUND;
493 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
494 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
497 if (0 == priv->active_config)
498 return LIBUSB_ERROR_NOT_FOUND;
500 config_index = get_configuration_index (dev, priv->active_config);
501 if (config_index < 0)
504 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
507 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
508 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
509 IOUSBConfigurationDescriptorPtr desc;
513 if (!priv || !priv->device)
514 return LIBUSB_ERROR_OTHER;
516 kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
517 if (kresult == kIOReturnSuccess) {
518 /* copy descriptor */
519 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
520 len = libusb_le16_to_cpu(desc->wTotalLength);
522 memmove (buffer, desc, len);
524 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
528 ret = darwin_to_libusb (kresult);
529 if (ret != LIBUSB_SUCCESS)
535 /* check whether the os has configured the device */
536 static int darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) {
537 usb_device_t **darwin_device = dev->device;
539 IOUSBConfigurationDescriptorPtr configDesc;
540 IOUSBFindInterfaceRequest request;
541 kern_return_t kresult;
542 io_iterator_t interface_iterator;
543 io_service_t firstInterface;
545 if (dev->dev_descriptor.bNumConfigurations < 1) {
546 usbi_err (ctx, "device has no configurations");
547 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
550 /* find the first configuration */
551 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
552 dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
554 /* check if the device is already configured. there is probably a better way than iterating over the
555 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
556 might lock up on the device request) */
558 /* Setup the Interface Request */
559 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
560 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
561 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
562 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
564 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
566 return darwin_to_libusb (kresult);
569 firstInterface = IOIteratorNext(interface_iterator);
571 /* done with the interface iterator */
572 IOObjectRelease(interface_iterator);
574 if (firstInterface) {
575 IOObjectRelease (firstInterface);
577 /* device is configured */
578 if (dev->dev_descriptor.bNumConfigurations == 1)
579 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
580 dev->active_config = dev->first_config;
582 /* devices with more than one configuration should work with GetConfiguration */
583 (*darwin_device)->GetConfiguration (darwin_device, &dev->active_config);
586 dev->active_config = 0;
588 usbi_dbg ("active config: %u, first config: %u", dev->active_config, dev->first_config);
593 static int darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
594 IOUSBDevRequestTO req;
596 memset (buffer, 0, buffer_size);
598 /* Set up request for descriptor/ */
599 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
600 req.bRequest = kUSBRqGetDescriptor;
601 req.wValue = desc << 8;
602 req.wIndex = desc_index;
603 req.wLength = buffer_size;
605 req.noDataTimeout = 20;
606 req.completionTimeout = 100;
608 return (*device)->DeviceRequestTO (device, &req);
611 static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct darwin_cached_device *dev) {
612 usb_device_t **device = dev->device;
613 int retries = 1, delay = 30000;
614 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
618 UInt16 idProduct, idVendor;
620 dev->can_enumerate = 0;
622 (*device)->GetDeviceClass (device, &bDeviceClass);
623 (*device)->GetDeviceProduct (device, &idProduct);
624 (*device)->GetDeviceVendor (device, &idVendor);
626 /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
627 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
628 * to follow the spec as closely as possible, try opening the device */
629 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
632 /**** retrieve device descriptor ****/
633 ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &dev->dev_descriptor, sizeof(dev->dev_descriptor));
635 if (kIOReturnOverrun == ret && kUSBDeviceDesc == dev->dev_descriptor.bDescriptorType)
636 /* received an overrun error but we still received a device descriptor */
637 ret = kIOReturnSuccess;
639 if (kIOUSBVendorIDAppleComputer == idVendor) {
640 /* NTH: don't bother retrying or unsuspending Apple devices */
644 if (kIOReturnSuccess == ret && (0 == dev->dev_descriptor.bNumConfigurations ||
645 0 == dev->dev_descriptor.bcdUSB)) {
646 /* work around for incorrectly configured devices */
647 if (try_reconfigure && is_open) {
648 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
650 /* set the first configuration */
651 (*device)->SetConfiguration(device, 1);
653 /* don't try to reconfigure again */
657 ret = kIOUSBPipeStalled;
660 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
661 /* device may be suspended. unsuspend it and try again */
662 #if DeviceVersion >= 320
665 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
666 (void)(*device)->GetUSBDeviceInformation (device, &info);
668 /* note that the device was suspended */
669 if (info & (1 << kUSBInformationDeviceIsSuspendedBit) || 0 == info)
674 /* try to unsuspend the device */
675 ret2 = (*device)->USBDeviceSuspend (device, 0);
676 if (kIOReturnSuccess != ret2) {
677 /* prevent log spew from poorly behaving devices. this indicates the
678 os actually had trouble communicating with the device */
679 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
687 if (kIOReturnSuccess != ret) {
688 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
689 /* sleep for a little while before trying again */
692 } while (kIOReturnSuccess != ret && retries--);
695 /* resuspend the device */
696 (void)(*device)->USBDeviceSuspend (device, 1);
699 (void) (*device)->USBDeviceClose (device);
701 if (ret != kIOReturnSuccess) {
702 /* a debug message was already printed out for this error */
703 if (LIBUSB_CLASS_HUB == bDeviceClass)
704 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
705 idVendor, idProduct, darwin_error_str (ret), ret);
707 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
708 idVendor, idProduct, darwin_error_str (ret), ret);
709 return darwin_to_libusb (ret);
712 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
713 if (libusb_le16_to_cpu (dev->dev_descriptor.idProduct) != idProduct) {
714 /* not a valid device */
715 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
716 idProduct, libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
717 return LIBUSB_ERROR_NO_DEVICE;
720 usbi_dbg ("cached device descriptor:");
721 usbi_dbg (" bDescriptorType: 0x%02x", dev->dev_descriptor.bDescriptorType);
722 usbi_dbg (" bcdUSB: 0x%04x", dev->dev_descriptor.bcdUSB);
723 usbi_dbg (" bDeviceClass: 0x%02x", dev->dev_descriptor.bDeviceClass);
724 usbi_dbg (" bDeviceSubClass: 0x%02x", dev->dev_descriptor.bDeviceSubClass);
725 usbi_dbg (" bDeviceProtocol: 0x%02x", dev->dev_descriptor.bDeviceProtocol);
726 usbi_dbg (" bMaxPacketSize0: 0x%02x", dev->dev_descriptor.bMaxPacketSize0);
727 usbi_dbg (" idVendor: 0x%04x", dev->dev_descriptor.idVendor);
728 usbi_dbg (" idProduct: 0x%04x", dev->dev_descriptor.idProduct);
729 usbi_dbg (" bcdDevice: 0x%04x", dev->dev_descriptor.bcdDevice);
730 usbi_dbg (" iManufacturer: 0x%02x", dev->dev_descriptor.iManufacturer);
731 usbi_dbg (" iProduct: 0x%02x", dev->dev_descriptor.iProduct);
732 usbi_dbg (" iSerialNumber: 0x%02x", dev->dev_descriptor.iSerialNumber);
733 usbi_dbg (" bNumConfigurations: 0x%02x", dev->dev_descriptor.bNumConfigurations);
735 dev->can_enumerate = 1;
737 return LIBUSB_SUCCESS;
740 static int darwin_get_cached_device(struct libusb_context *ctx, io_service_t service,
741 struct darwin_cached_device **cached_out) {
742 struct darwin_cached_device *new_device;
743 UInt64 sessionID = 0, parent_sessionID = 0;
744 int ret = LIBUSB_SUCCESS;
745 usb_device_t **device;
747 kern_return_t result;
750 /* get some info from the io registry */
751 (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
752 (void) get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, &port);
754 usbi_dbg("finding cached device for sessionID 0x%" PRIx64, sessionID);
756 result = IORegistryEntryGetParentEntry (service, kIOUSBPlane, &parent);
758 if (kIOReturnSuccess == result) {
759 (void) get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, &parent_sessionID);
760 IOObjectRelease(parent);
763 usbi_mutex_lock(&darwin_cached_devices_lock);
767 list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) {
768 usbi_dbg("matching sessionID 0x%" PRIx64 " against cached device with sessionID 0x%" PRIx64, sessionID, new_device->session);
769 if (new_device->session == sessionID) {
770 usbi_dbg("using cached device for device");
771 *cached_out = new_device;
779 usbi_dbg("caching new device with sessionID 0x%" PRIx64, sessionID);
781 device = darwin_device_from_service (service);
783 ret = LIBUSB_ERROR_NO_DEVICE;
787 new_device = calloc (1, sizeof (*new_device));
789 ret = LIBUSB_ERROR_NO_MEM;
793 /* add this device to the cached device list */
794 list_add(&new_device->list, &darwin_cached_devices);
796 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
798 /* keep a reference to this device */
799 darwin_ref_cached_device(new_device);
801 new_device->device = device;
802 new_device->session = sessionID;
803 (*device)->GetLocationID (device, &new_device->location);
804 new_device->port = port;
805 new_device->parent_session = parent_sessionID;
807 /* cache the device descriptor */
808 ret = darwin_cache_device_descriptor(ctx, new_device);
812 if (new_device->can_enumerate) {
813 snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address,
814 new_device->dev_descriptor.idVendor, new_device->dev_descriptor.idProduct,
815 new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass);
819 usbi_mutex_unlock(&darwin_cached_devices_lock);
821 /* keep track of devices regardless of if we successfully enumerate them to
822 prevent them from being enumerated multiple times */
824 *cached_out = new_device;
829 static int process_new_device (struct libusb_context *ctx, io_service_t service) {
830 struct darwin_device_priv *priv;
831 struct libusb_device *dev = NULL;
832 struct darwin_cached_device *cached_device;
837 ret = darwin_get_cached_device (ctx, service, &cached_device);
839 if (ret < 0 || !cached_device->can_enumerate) {
843 /* check current active configuration (and cache the first configuration value--
844 which may be used by claim_interface) */
845 ret = darwin_check_configuration (ctx, cached_device);
849 usbi_dbg ("allocating new device in context %p for with session 0x%" PRIx64,
850 ctx, cached_device->session);
852 dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
854 return LIBUSB_ERROR_NO_MEM;
857 priv = (struct darwin_device_priv *)dev->os_priv;
859 priv->dev = cached_device;
860 darwin_ref_cached_device (priv->dev);
862 if (cached_device->parent_session > 0) {
863 dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session);
865 dev->parent_dev = NULL;
867 dev->port_number = cached_device->port;
868 dev->bus_number = cached_device->location >> 24;
869 dev->device_address = cached_device->address;
871 (*(priv->dev->device))->GetDeviceSpeed (priv->dev->device, &devSpeed);
874 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
875 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
876 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
877 #if DeviceVersion >= 500
878 case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
881 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
884 ret = usbi_sanitize_device (dev);
888 usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
889 dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
893 usbi_connect_device (dev);
895 libusb_unref_device (dev);
901 static int darwin_scan_devices(struct libusb_context *ctx) {
902 io_iterator_t deviceIterator;
903 io_service_t service;
904 kern_return_t kresult;
906 kresult = usb_setup_device_iterator (&deviceIterator, 0);
907 if (kresult != kIOReturnSuccess)
908 return darwin_to_libusb (kresult);
910 while ((service = IOIteratorNext (deviceIterator))) {
911 (void) process_new_device (ctx, service);
913 IOObjectRelease(service);
916 IOObjectRelease(deviceIterator);
921 static int darwin_open (struct libusb_device_handle *dev_handle) {
922 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
923 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
926 if (0 == dpriv->open_count) {
927 /* try to open the device */
928 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
929 if (kresult != kIOReturnSuccess) {
930 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
932 if (kIOReturnExclusiveAccess != kresult) {
933 return darwin_to_libusb (kresult);
936 /* it is possible to perform some actions on a device that is not open so do not return an error */
942 /* create async event source */
943 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
944 if (kresult != kIOReturnSuccess) {
945 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
948 (*(dpriv->device))->USBDeviceClose (dpriv->device);
953 return darwin_to_libusb (kresult);
956 CFRetain (libusb_darwin_acfl);
958 /* add the cfSource to the aync run loop */
959 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
962 /* device opened successfully */
965 /* create a file descriptor for notifications */
968 /* set the pipe to be non-blocking */
969 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
971 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
973 usbi_dbg ("device open for access");
978 static void darwin_close (struct libusb_device_handle *dev_handle) {
979 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
980 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
984 if (dpriv->open_count == 0) {
985 /* something is probably very wrong if this is the case */
986 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
992 /* make sure all interfaces are released */
993 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
994 if (dev_handle->claimed_interfaces & (1 << i))
995 libusb_release_interface (dev_handle, i);
997 if (0 == dpriv->open_count) {
998 /* delete the device's async event source */
999 if (priv->cfSource) {
1000 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
1001 CFRelease (priv->cfSource);
1002 priv->cfSource = NULL;
1003 CFRelease (libusb_darwin_acfl);
1006 if (priv->is_open) {
1007 /* close the device */
1008 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
1010 /* Log the fact that we had a problem closing the file, however failing a
1011 * close isn't really an error, so return success anyway */
1012 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
1017 /* file descriptors are maintained per-instance */
1018 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
1019 close (priv->fds[1]);
1020 close (priv->fds[0]);
1022 priv->fds[0] = priv->fds[1] = -1;
1025 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
1026 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1028 *config = (int) dpriv->active_config;
1033 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
1034 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1038 /* Setting configuration will invalidate the interface, so we need
1039 to reclaim it. First, dispose of existing interfaces, if any. */
1040 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1041 if (dev_handle->claimed_interfaces & (1 << i))
1042 darwin_release_interface (dev_handle, i);
1044 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
1045 if (kresult != kIOReturnSuccess)
1046 return darwin_to_libusb (kresult);
1048 /* Reclaim any interfaces. */
1049 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1050 if (dev_handle->claimed_interfaces & (1 << i))
1051 darwin_claim_interface (dev_handle, i);
1053 dpriv->active_config = config;
1058 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
1059 IOUSBFindInterfaceRequest request;
1060 kern_return_t kresult;
1061 io_iterator_t interface_iterator;
1062 UInt8 bInterfaceNumber;
1065 *usbInterfacep = IO_OBJECT_NULL;
1067 /* Setup the Interface Request */
1068 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1069 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1070 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1071 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1073 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1077 while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1078 /* find the interface number */
1079 ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
1082 if (ret && bInterfaceNumber == ifc) {
1086 (void) IOObjectRelease (*usbInterfacep);
1089 /* done with the interface iterator */
1090 IOObjectRelease(interface_iterator);
1095 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
1096 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1098 /* current interface */
1099 struct darwin_interface *cInterface = &priv->interfaces[iface];
1101 kern_return_t kresult;
1103 u_int8_t numep, direction, number;
1104 u_int8_t dont_care1, dont_care3;
1105 u_int16_t dont_care2;
1108 usbi_dbg ("building table of endpoints.");
1110 /* retrieve the total number of endpoints on this interface */
1111 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1113 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1114 return darwin_to_libusb (kresult);
1117 /* iterate through pipe references */
1118 for (i = 1 ; i <= numep ; i++) {
1119 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1120 &dont_care2, &dont_care3);
1122 if (kresult != kIOReturnSuccess) {
1123 usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
1125 return darwin_to_libusb (kresult);
1128 usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
1130 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1133 cInterface->num_endpoints = numep;
1138 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1139 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1140 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1141 io_service_t usbInterface = IO_OBJECT_NULL;
1143 IOCFPlugInInterface **plugInInterface = NULL;
1146 /* current interface */
1147 struct darwin_interface *cInterface = &priv->interfaces[iface];
1149 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1150 if (kresult != kIOReturnSuccess)
1151 return darwin_to_libusb (kresult);
1153 /* make sure we have an interface */
1154 if (!usbInterface && dpriv->first_config != 0) {
1155 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1157 /* set the configuration */
1158 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1159 if (kresult != LIBUSB_SUCCESS) {
1160 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1164 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1166 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1167 return darwin_to_libusb (kresult);
1171 if (!usbInterface) {
1172 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1173 return LIBUSB_ERROR_NOT_FOUND;
1176 /* get an interface to the device's interface */
1177 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1178 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1180 /* ignore release error */
1181 (void)IOObjectRelease (usbInterface);
1184 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1185 return darwin_to_libusb (kresult);
1188 if (!plugInInterface) {
1189 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1190 return LIBUSB_ERROR_NOT_FOUND;
1193 /* Do the actual claim */
1194 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1195 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1196 (LPVOID)&cInterface->interface);
1197 /* We no longer need the intermediate plug-in */
1198 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1199 (*plugInInterface)->Release (plugInInterface);
1200 if (kresult || !cInterface->interface) {
1201 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1202 return darwin_to_libusb (kresult);
1205 /* claim the interface */
1206 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1208 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1209 return darwin_to_libusb (kresult);
1212 /* update list of endpoints */
1213 kresult = get_endpoints (dev_handle, iface);
1215 /* this should not happen */
1216 darwin_release_interface (dev_handle, iface);
1217 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1221 cInterface->cfSource = NULL;
1223 /* create async event source */
1224 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1225 if (kresult != kIOReturnSuccess) {
1226 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1228 /* can't continue without an async event source */
1229 (void)darwin_release_interface (dev_handle, iface);
1231 return darwin_to_libusb (kresult);
1234 /* add the cfSource to the async thread's run loop */
1235 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1237 usbi_dbg ("interface opened");
1242 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1243 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1246 /* current interface */
1247 struct darwin_interface *cInterface = &priv->interfaces[iface];
1249 /* Check to see if an interface is open */
1250 if (!cInterface->interface)
1251 return LIBUSB_SUCCESS;
1253 /* clean up endpoint data */
1254 cInterface->num_endpoints = 0;
1256 /* delete the interface's async event source */
1257 if (cInterface->cfSource) {
1258 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1259 CFRelease (cInterface->cfSource);
1262 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1264 usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1266 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1267 if (kresult != kIOReturnSuccess)
1268 usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1270 cInterface->interface = IO_OBJECT_NULL;
1272 return darwin_to_libusb (kresult);
1275 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1276 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1279 /* current interface */
1280 struct darwin_interface *cInterface = &priv->interfaces[iface];
1282 if (!cInterface->interface)
1283 return LIBUSB_ERROR_NO_DEVICE;
1285 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1286 if (kresult != kIOReturnSuccess)
1287 darwin_reset_device (dev_handle);
1289 /* update list of endpoints */
1290 kresult = get_endpoints (dev_handle, iface);
1292 /* this should not happen */
1293 darwin_release_interface (dev_handle, iface);
1294 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1298 return darwin_to_libusb (kresult);
1301 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1302 /* current interface */
1303 struct darwin_interface *cInterface;
1307 /* determine the interface/endpoint to use */
1308 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, NULL, &cInterface) != 0) {
1309 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1311 return LIBUSB_ERROR_NOT_FOUND;
1314 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1315 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1317 usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1319 return darwin_to_libusb (kresult);
1322 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1323 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1324 IOUSBDeviceDescriptor descriptor;
1325 IOUSBConfigurationDescriptorPtr cached_configuration;
1326 IOUSBConfigurationDescriptor configuration;
1327 bool reenumerate = false;
1331 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1333 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1334 return darwin_to_libusb (kresult);
1338 usbi_dbg ("darwin/reset_device: checking if device descriptor changed");
1340 /* ignore return code. if we can't get a descriptor it might be worthwhile re-enumerating anway */
1341 (void) darwin_request_descriptor (dpriv->device, kUSBDeviceDesc, 0, &descriptor, sizeof (descriptor));
1343 /* check if the device descriptor has changed */
1344 if (0 != memcmp (&dpriv->dev_descriptor, &descriptor, sizeof (descriptor))) {
1349 /* check if any configuration descriptor has changed */
1350 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1351 usbi_dbg ("darwin/reset_device: checking if configuration descriptor %d changed", i);
1353 (void) darwin_request_descriptor (dpriv->device, kUSBConfDesc, i, &configuration, sizeof (configuration));
1354 (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1356 if (!cached_configuration || 0 != memcmp (cached_configuration, &configuration, sizeof (configuration))) {
1364 usbi_dbg ("darwin/reset_device: device requires reenumeration");
1365 (void) (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
1366 return LIBUSB_ERROR_NOT_FOUND;
1369 usbi_dbg ("darwin/reset_device: device reset complete");
1371 return LIBUSB_SUCCESS;
1374 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1375 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1376 io_service_t usbInterface;
1380 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1382 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1384 return darwin_to_libusb (kresult);
1387 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1388 IOObjectRelease (usbInterface);
1400 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1401 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1404 return LIBUSB_ERROR_NOT_SUPPORTED;
1407 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1410 return LIBUSB_ERROR_NOT_SUPPORTED;
1413 static void darwin_destroy_device(struct libusb_device *dev) {
1414 struct darwin_device_priv *dpriv = (struct darwin_device_priv *) dev->os_priv;
1417 /* need to hold the lock in case this is the last reference to the device */
1418 usbi_mutex_lock(&darwin_cached_devices_lock);
1419 darwin_deref_cached_device (dpriv->dev);
1421 usbi_mutex_unlock(&darwin_cached_devices_lock);
1425 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1426 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1429 uint8_t transferType;
1430 /* None of the values below are used in libusbx for bulk transfers */
1431 uint8_t direction, number, interval, pipeRef;
1432 uint16_t maxPacketSize;
1434 struct darwin_interface *cInterface;
1436 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1437 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1439 return LIBUSB_ERROR_NOT_FOUND;
1442 ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1443 &transferType, &maxPacketSize, &interval);
1446 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1447 darwin_error_str(ret), ret);
1448 return darwin_to_libusb (ret);
1451 if (0 != (transfer->length % maxPacketSize)) {
1452 /* do not need a zero packet */
1453 transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1456 /* submit the request */
1457 /* timeouts are unavailable on interrupt endpoints */
1458 if (transferType == kUSBInterrupt) {
1459 if (IS_XFERIN(transfer))
1460 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1461 transfer->length, darwin_async_io_callback, itransfer);
1463 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1464 transfer->length, darwin_async_io_callback, itransfer);
1466 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1468 if (IS_XFERIN(transfer))
1469 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1470 transfer->length, transfer->timeout, transfer->timeout,
1471 darwin_async_io_callback, (void *)itransfer);
1473 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1474 transfer->length, transfer->timeout, transfer->timeout,
1475 darwin_async_io_callback, (void *)itransfer);
1479 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1480 darwin_error_str(ret), ret);
1482 return darwin_to_libusb (ret);
1485 #if InterfaceVersion >= 550
1486 static int submit_stream_transfer(struct usbi_transfer *itransfer) {
1487 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1488 struct darwin_interface *cInterface;
1492 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1493 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1495 return LIBUSB_ERROR_NOT_FOUND;
1498 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1500 if (IS_XFERIN(transfer))
1501 ret = (*(cInterface->interface))->ReadStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1502 transfer->buffer, transfer->length, transfer->timeout,
1503 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1505 ret = (*(cInterface->interface))->WriteStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1506 transfer->buffer, transfer->length, transfer->timeout,
1507 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1510 usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1511 darwin_error_str(ret), ret);
1513 return darwin_to_libusb (ret);
1517 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1518 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1519 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1522 uint8_t direction, number, interval, pipeRef, transferType;
1523 uint16_t maxPacketSize;
1525 AbsoluteTime atTime;
1528 struct darwin_interface *cInterface;
1530 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1531 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1532 free(tpriv->isoc_framelist);
1533 tpriv->isoc_framelist = NULL;
1536 if (!tpriv->isoc_framelist) {
1537 tpriv->num_iso_packets = transfer->num_iso_packets;
1538 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1539 if (!tpriv->isoc_framelist)
1540 return LIBUSB_ERROR_NO_MEM;
1543 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1544 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1545 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1547 /* determine the interface/endpoint to use */
1548 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1549 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1551 return LIBUSB_ERROR_NOT_FOUND;
1554 /* determine the properties of this endpoint and the speed of the device */
1555 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1556 &transferType, &maxPacketSize, &interval);
1558 /* Last but not least we need the bus frame number */
1559 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1561 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1562 free(tpriv->isoc_framelist);
1563 tpriv->isoc_framelist = NULL;
1565 return darwin_to_libusb (kresult);
1568 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1569 &transferType, &maxPacketSize, &interval);
1571 /* schedule for a frame a little in the future */
1574 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1575 frame = cInterface->frames[transfer->endpoint];
1577 /* submit the request */
1578 if (IS_XFERIN(transfer))
1579 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1580 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1583 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1584 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1587 if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
1589 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1));
1591 /* High/super speed */
1592 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1)) / 8;
1594 if (kresult != kIOReturnSuccess) {
1595 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1596 darwin_error_str(kresult));
1597 free (tpriv->isoc_framelist);
1598 tpriv->isoc_framelist = NULL;
1601 return darwin_to_libusb (kresult);
1604 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1605 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1606 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1607 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1608 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1612 bzero(&tpriv->req, sizeof(tpriv->req));
1614 /* IOUSBDeviceInterface expects the request in cpu endianess */
1615 tpriv->req.bmRequestType = setup->bmRequestType;
1616 tpriv->req.bRequest = setup->bRequest;
1617 /* these values should be in bus order from libusb_fill_control_setup */
1618 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1619 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1620 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1621 /* data is stored after the libusb control block */
1622 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1623 tpriv->req.completionTimeout = transfer->timeout;
1624 tpriv->req.noDataTimeout = transfer->timeout;
1626 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1628 /* all transfers in libusb-1.0 are async */
1630 if (transfer->endpoint) {
1631 struct darwin_interface *cInterface;
1634 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1635 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1637 return LIBUSB_ERROR_NOT_FOUND;
1640 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1642 /* control request on endpoint 0 */
1643 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1645 if (kresult != kIOReturnSuccess)
1646 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1648 return darwin_to_libusb (kresult);
1651 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1652 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1654 switch (transfer->type) {
1655 case LIBUSB_TRANSFER_TYPE_CONTROL:
1656 return submit_control_transfer(itransfer);
1657 case LIBUSB_TRANSFER_TYPE_BULK:
1658 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1659 return submit_bulk_transfer(itransfer);
1660 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1661 return submit_iso_transfer(itransfer);
1662 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1663 #if InterfaceVersion >= 550
1664 return submit_stream_transfer(itransfer);
1666 usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers");
1667 return LIBUSB_ERROR_NOT_SUPPORTED;
1670 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1671 return LIBUSB_ERROR_INVALID_PARAM;
1675 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1676 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1677 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1680 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
1683 return LIBUSB_ERROR_NO_DEVICE;
1685 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1687 return darwin_to_libusb (kresult);
1690 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1691 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1692 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1693 struct darwin_interface *cInterface;
1694 uint8_t pipeRef, iface;
1697 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) {
1698 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1700 return LIBUSB_ERROR_NOT_FOUND;
1704 return LIBUSB_ERROR_NO_DEVICE;
1706 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
1708 /* abort transactions */
1709 #if InterfaceVersion >= 550
1710 if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type)
1711 (*(cInterface->interface))->AbortStreamsPipe (cInterface->interface, pipeRef, itransfer->stream_id);
1714 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1716 usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
1718 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1719 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1721 return darwin_to_libusb (kresult);
1724 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1725 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1727 switch (transfer->type) {
1728 case LIBUSB_TRANSFER_TYPE_CONTROL:
1729 return cancel_control_transfer(itransfer);
1730 case LIBUSB_TRANSFER_TYPE_BULK:
1731 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1732 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1733 return darwin_abort_transfers (itransfer);
1735 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1736 return LIBUSB_ERROR_INVALID_PARAM;
1740 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1741 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1742 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1744 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1745 free (tpriv->isoc_framelist);
1746 tpriv->isoc_framelist = NULL;
1750 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1751 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1752 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1753 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1754 struct darwin_msg_async_io_complete message = {.itransfer = itransfer, .result = result,
1755 .size = (UInt32) (uintptr_t) arg0};
1757 usbi_dbg ("an async io operation has completed");
1759 /* if requested write a zero packet */
1760 if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
1761 struct darwin_interface *cInterface;
1764 (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface);
1766 (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
1769 /* send a completion message to the device's file descriptor */
1770 write (priv->fds[1], &message, sizeof (message));
1773 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1774 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT)
1775 result = kIOUSBTransactionTimeout;
1778 case kIOReturnUnderrun:
1779 case kIOReturnSuccess:
1780 return LIBUSB_TRANSFER_COMPLETED;
1781 case kIOReturnAborted:
1782 return LIBUSB_TRANSFER_CANCELLED;
1783 case kIOUSBPipeStalled:
1784 usbi_dbg ("transfer error: pipe is stalled");
1785 return LIBUSB_TRANSFER_STALL;
1786 case kIOReturnOverrun:
1787 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1788 return LIBUSB_TRANSFER_OVERFLOW;
1789 case kIOUSBTransactionTimeout:
1790 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1791 itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
1792 return LIBUSB_TRANSFER_TIMED_OUT;
1794 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1795 return LIBUSB_TRANSFER_ERROR;
1799 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1800 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1801 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1802 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1803 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1804 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1805 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1808 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1809 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1813 usbi_dbg ("handling %s completion with kernel status %d",
1814 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
1816 if (kIOReturnSuccess == result || kIOReturnUnderrun == result) {
1817 if (isIsoc && tpriv->isoc_framelist) {
1818 /* copy isochronous results back */
1820 for (i = 0; i < transfer->num_iso_packets ; i++) {
1821 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1822 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1823 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1826 itransfer->transferred += io_size;
1829 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1830 usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
1833 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready) {
1834 struct darwin_msg_async_io_complete message;
1835 POLL_NFDS_TYPE i = 0;
1838 usbi_mutex_lock(&ctx->open_devs_lock);
1840 for (i = 0; i < nfds && num_ready > 0; i++) {
1841 struct pollfd *pollfd = &fds[i];
1843 usbi_dbg ("checking fd %i with revents = %x", pollfd->fd, pollfd->revents);
1845 if (!pollfd->revents)
1850 if (pollfd->revents & POLLERR) {
1851 /* this probably will never happen so ignore the error an move on. */
1855 /* there is only one type of message */
1856 ret = read (pollfd->fd, &message, sizeof (message));
1857 if (ret < (ssize_t) sizeof (message)) {
1858 usbi_dbg ("WARNING: short read on async io completion pipe\n");
1862 darwin_handle_callback (message.itransfer, message.result, message.size);
1865 usbi_mutex_unlock(&ctx->open_devs_lock);
1870 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1871 mach_timespec_t sys_time;
1872 clock_serv_t clock_ref;
1875 case USBI_CLOCK_REALTIME:
1876 /* CLOCK_REALTIME represents time since the epoch */
1877 clock_ref = clock_realtime;
1879 case USBI_CLOCK_MONOTONIC:
1880 /* use system boot time as reference for the monotonic clock */
1881 clock_ref = clock_monotonic;
1884 return LIBUSB_ERROR_INVALID_PARAM;
1887 clock_get_time (clock_ref, &sys_time);
1889 tp->tv_sec = sys_time.tv_sec;
1890 tp->tv_nsec = sys_time.tv_nsec;
1895 #if InterfaceVersion >= 550
1896 static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints,
1897 int num_endpoints) {
1898 struct darwin_interface *cInterface;
1899 UInt32 supportsStreams;
1903 /* find the mimimum number of supported streams on the endpoint list */
1904 for (i = 0 ; i < num_endpoints ; ++i) {
1905 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) {
1909 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
1910 if (num_streams > supportsStreams)
1911 num_streams = supportsStreams;
1914 /* it is an error if any endpoint in endpoints does not support streams */
1915 if (0 == num_streams)
1916 return LIBUSB_ERROR_INVALID_PARAM;
1918 /* create the streams */
1919 for (i = 0 ; i < num_endpoints ; ++i) {
1920 (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
1922 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, num_streams);
1923 if (kIOReturnSuccess != rc)
1924 return darwin_to_libusb(rc);
1930 static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) {
1931 struct darwin_interface *cInterface;
1932 UInt32 supportsStreams;
1936 for (int i = 0 ; i < num_endpoints ; ++i) {
1937 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface)))
1940 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
1941 if (0 == supportsStreams)
1942 return LIBUSB_ERROR_INVALID_PARAM;
1944 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, 0);
1945 if (kIOReturnSuccess != rc)
1946 return darwin_to_libusb(rc);
1949 return LIBUSB_SUCCESS;
1953 const struct usbi_os_backend darwin_backend = {
1956 .init = darwin_init,
1957 .exit = darwin_exit,
1958 .get_device_list = NULL, /* not needed */
1959 .get_device_descriptor = darwin_get_device_descriptor,
1960 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1961 .get_config_descriptor = darwin_get_config_descriptor,
1963 .open = darwin_open,
1964 .close = darwin_close,
1965 .get_configuration = darwin_get_configuration,
1966 .set_configuration = darwin_set_configuration,
1967 .claim_interface = darwin_claim_interface,
1968 .release_interface = darwin_release_interface,
1970 .set_interface_altsetting = darwin_set_interface_altsetting,
1971 .clear_halt = darwin_clear_halt,
1972 .reset_device = darwin_reset_device,
1974 #if InterfaceVersion >= 550
1975 .alloc_streams = darwin_alloc_streams,
1976 .free_streams = darwin_free_streams,
1979 .kernel_driver_active = darwin_kernel_driver_active,
1980 .detach_kernel_driver = darwin_detach_kernel_driver,
1981 .attach_kernel_driver = darwin_attach_kernel_driver,
1983 .destroy_device = darwin_destroy_device,
1985 .submit_transfer = darwin_submit_transfer,
1986 .cancel_transfer = darwin_cancel_transfer,
1987 .clear_transfer_priv = darwin_clear_transfer_priv,
1989 .handle_events = op_handle_events,
1991 .clock_gettime = darwin_clock_gettime,
1993 .device_priv_size = sizeof(struct darwin_device_priv),
1994 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1995 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1996 .add_iso_packet_size = 0,