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
29 #include <sys/types.h>
32 #include <libkern/OSAtomic.h>
33 #include <sys/sysctl.h>
35 #include <mach/clock.h>
36 #include <mach/clock_types.h>
37 #include <mach/mach_host.h>
38 #include <mach/mach_port.h>
40 #include <AvailabilityMacros.h>
41 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
42 #include <objc/objc-auto.h>
45 #include "darwin_usb.h"
47 /* async event thread */
48 static pthread_mutex_t libusb_darwin_at_mutex = PTHREAD_MUTEX_INITIALIZER;
49 static pthread_cond_t libusb_darwin_at_cond = PTHREAD_COND_INITIALIZER;
51 static pthread_once_t darwin_init_once = PTHREAD_ONCE_INIT;
53 static clock_serv_t clock_realtime;
54 static clock_serv_t clock_monotonic;
56 static CFRunLoopRef libusb_darwin_acfl = NULL; /* event cf loop */
57 static CFRunLoopSourceRef libusb_darwin_acfls = NULL; /* shutdown signal for event cf loop */
58 static volatile int32_t initCount = 0;
60 static usbi_mutex_t darwin_cached_devices_lock = PTHREAD_MUTEX_INITIALIZER;
61 static struct list_head darwin_cached_devices = {&darwin_cached_devices, &darwin_cached_devices};
62 static char *darwin_device_class = kIOUSBDeviceClassName;
64 #define DARWIN_CACHED_DEVICE(a) ((struct darwin_cached_device *) (((struct darwin_device_priv *)((a)->os_priv))->dev))
66 /* async event thread */
67 static pthread_t libusb_darwin_at;
69 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
70 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
71 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
72 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
73 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
75 static int darwin_scan_devices(struct libusb_context *ctx);
76 static int process_new_device (struct libusb_context *ctx, io_service_t service);
78 #if defined(ENABLE_LOGGING)
79 static const char *darwin_error_str (int result) {
80 static char string_buffer[50];
82 case kIOReturnSuccess:
84 case kIOReturnNotOpen:
85 return "device not opened for exclusive access";
86 case kIOReturnNoDevice:
87 return "no connection to an IOService";
88 case kIOUSBNoAsyncPortErr:
89 return "no async port has been opened for interface";
90 case kIOReturnExclusiveAccess:
91 return "another process has device opened for exclusive access";
92 case kIOUSBPipeStalled:
93 return "pipe is stalled";
95 return "could not establish a connection to the Darwin kernel";
96 case kIOUSBTransactionTimeout:
97 return "transaction timed out";
98 case kIOReturnBadArgument:
99 return "invalid argument";
100 case kIOReturnAborted:
101 return "transaction aborted";
102 case kIOReturnNotResponding:
103 return "device not responding";
104 case kIOReturnOverrun:
105 return "data overrun";
106 case kIOReturnCannotWire:
107 return "physical memory can not be wired down";
108 case kIOReturnNoResources:
109 return "out of resources";
110 case kIOUSBHighSpeedSplitError:
111 return "high speed split error";
113 snprintf(string_buffer, sizeof(string_buffer), "unknown error (0x%x)", result);
114 return string_buffer;
119 static int darwin_to_libusb (int result) {
121 case kIOReturnUnderrun:
122 case kIOReturnSuccess:
123 return LIBUSB_SUCCESS;
124 case kIOReturnNotOpen:
125 case kIOReturnNoDevice:
126 return LIBUSB_ERROR_NO_DEVICE;
127 case kIOReturnExclusiveAccess:
128 return LIBUSB_ERROR_ACCESS;
129 case kIOUSBPipeStalled:
130 return LIBUSB_ERROR_PIPE;
131 case kIOReturnBadArgument:
132 return LIBUSB_ERROR_INVALID_PARAM;
133 case kIOUSBTransactionTimeout:
134 return LIBUSB_ERROR_TIMEOUT;
135 case kIOReturnNotResponding:
136 case kIOReturnAborted:
138 case kIOUSBNoAsyncPortErr:
140 return LIBUSB_ERROR_OTHER;
144 /* this function must be called with the darwin_cached_devices_lock held */
145 static void darwin_deref_cached_device(struct darwin_cached_device *cached_dev) {
146 cached_dev->refcount--;
147 /* free the device and remove it from the cache */
148 if (0 == cached_dev->refcount) {
149 list_del(&cached_dev->list);
151 (*(cached_dev->device))->Release(cached_dev->device);
156 static void darwin_ref_cached_device(struct darwin_cached_device *cached_dev) {
157 cached_dev->refcount++;
160 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) {
161 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
163 /* current interface */
164 struct darwin_interface *cInterface;
168 usbi_dbg ("converting ep address 0x%02x to pipeRef and interface", ep);
170 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
171 cInterface = &priv->interfaces[iface];
173 if (dev_handle->claimed_interfaces & (1 << iface)) {
174 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
175 if (cInterface->endpoint_addrs[i] == ep) {
182 *interface_out = cInterface;
184 usbi_dbg ("pipe %d on interface %d matches", *pipep, iface);
191 /* No pipe found with the correct endpoint address */
192 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
194 return LIBUSB_ERROR_NOT_FOUND;
197 static int usb_setup_device_iterator (io_iterator_t *deviceIterator, UInt32 location) {
198 CFMutableDictionaryRef matchingDict = IOServiceMatching(darwin_device_class);
201 return kIOReturnError;
204 CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
205 &kCFTypeDictionaryKeyCallBacks,
206 &kCFTypeDictionaryValueCallBacks);
208 if (propertyMatchDict) {
209 /* there are no unsigned CFNumber types so treat the value as signed. the os seems to do this
210 internally (CFNumberType of locationID is 3) */
211 CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberSInt32Type, &location);
213 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
214 /* release our reference to the CFNumber (CFDictionarySetValue retains it) */
215 CFRelease (locationCF);
217 CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
218 /* release out reference to the CFMutableDictionaryRef (CFDictionarySetValue retains it) */
219 CFRelease (propertyMatchDict);
221 /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
224 return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator);
227 /* Returns 1 on success, 0 on failure. */
228 static int get_ioregistry_value_number (io_service_t service, CFStringRef property, CFNumberType type, void *p) {
229 CFTypeRef cfNumber = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
233 if (CFGetTypeID(cfNumber) == CFNumberGetTypeID()) {
234 ret = CFNumberGetValue(cfNumber, type, p);
237 CFRelease (cfNumber);
243 static int get_ioregistry_value_data (io_service_t service, CFStringRef property, ssize_t size, void *p) {
244 CFTypeRef cfData = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
248 if (CFGetTypeID (cfData) == CFDataGetTypeID ()) {
249 CFIndex length = CFDataGetLength (cfData);
254 CFDataGetBytes (cfData, CFRangeMake(0, size), p);
264 static usb_device_t **darwin_device_from_service (io_service_t service)
266 io_cf_plugin_ref_t *plugInInterface = NULL;
267 usb_device_t **device;
268 kern_return_t result;
271 result = IOCreatePlugInInterfaceForService(service, kIOUSBDeviceUserClientTypeID,
272 kIOCFPlugInInterfaceID, &plugInInterface,
275 if (kIOReturnSuccess != result || !plugInInterface) {
276 usbi_dbg ("could not set up plugin for service: %s", darwin_error_str (result));
280 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
282 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
283 (*plugInInterface)->Release (plugInInterface);
288 static void darwin_devices_attached (void *ptr, io_iterator_t add_devices) {
289 struct libusb_context *ctx;
290 io_service_t service;
292 usbi_mutex_lock(&active_contexts_lock);
294 while ((service = IOIteratorNext(add_devices))) {
295 /* add this device to each active context's device list */
296 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
297 process_new_device (ctx, service);;
300 IOObjectRelease(service);
303 usbi_mutex_unlock(&active_contexts_lock);
306 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
307 struct libusb_device *dev = NULL;
308 struct libusb_context *ctx;
309 struct darwin_cached_device *old_device;
315 usbi_mutex_lock(&active_contexts_lock);
317 while ((device = IOIteratorNext (rem_devices)) != 0) {
318 /* get the location from the i/o registry */
319 ret = get_ioregistry_value_number (device, CFSTR("sessionID"), kCFNumberSInt64Type, &session);
320 IOObjectRelease (device);
324 /* we need to match darwin_ref_cached_device call made in darwin_get_cached_device function
325 otherwise no cached device will ever get freed */
326 usbi_mutex_lock(&darwin_cached_devices_lock);
327 list_for_each_entry(old_device, &darwin_cached_devices, list, struct darwin_cached_device) {
328 if (old_device->session == session) {
329 darwin_deref_cached_device (old_device);
333 usbi_mutex_unlock(&darwin_cached_devices_lock);
335 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
336 usbi_dbg ("notifying context %p of device disconnect", ctx);
338 dev = usbi_get_device_by_session_id(ctx, (unsigned long) session);
340 /* signal the core that this device has been disconnected. the core will tear down this device
341 when the reference count reaches 0 */
342 usbi_disconnect_device(dev);
343 libusb_unref_device(dev);
348 usbi_mutex_unlock(&active_contexts_lock);
351 static void darwin_hotplug_poll (void)
353 /* not sure if 5 seconds will be too long/short but it should work ok */
354 mach_timespec_t timeout = {.tv_sec = 5, .tv_nsec = 0};
356 /* since a kernel thread may nodify the IOInterators used for
357 * hotplug notidication we can't just clear the iterators.
358 * instead just wait until all IOService providers are quiet */
359 (void) IOKitWaitQuiet (kIOMasterPortDefault, &timeout);
362 static void darwin_clear_iterator (io_iterator_t iter) {
365 while ((device = IOIteratorNext (iter)) != 0)
366 IOObjectRelease (device);
369 static void *darwin_event_thread_main (void *arg0) {
371 struct libusb_context *ctx = (struct libusb_context *)arg0;
372 CFRunLoopRef runloop;
374 /* Set this thread's name, so it can be seen in the debugger
375 and crash reports. */
376 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
377 pthread_setname_np ("org.libusb.device-hotplug");
379 /* Tell the Objective-C garbage collector about this thread.
380 This is required because, unlike NSThreads, pthreads are
381 not automatically registered. Although we don't use
382 Objective-C, we use CoreFoundation, which does. */
383 objc_registerThreadWithCollector();
386 /* hotplug (device arrival/removal) sources */
387 CFRunLoopSourceContext libusb_shutdown_cfsourcectx;
388 CFRunLoopSourceRef libusb_notification_cfsource;
389 io_notification_port_t libusb_notification_port;
390 io_iterator_t libusb_rem_device_iterator;
391 io_iterator_t libusb_add_device_iterator;
393 usbi_dbg ("creating hotplug event source");
395 runloop = CFRunLoopGetCurrent ();
398 /* add the shutdown cfsource to the run loop */
399 memset(&libusb_shutdown_cfsourcectx, 0, sizeof(libusb_shutdown_cfsourcectx));
400 libusb_shutdown_cfsourcectx.info = runloop;
401 libusb_shutdown_cfsourcectx.perform = (void (*)(void *))CFRunLoopStop;
402 libusb_darwin_acfls = CFRunLoopSourceCreate(NULL, 0, &libusb_shutdown_cfsourcectx);
403 CFRunLoopAddSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
405 /* add the notification port to the run loop */
406 libusb_notification_port = IONotificationPortCreate (kIOMasterPortDefault);
407 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
408 CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
410 /* create notifications for removed devices */
411 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
412 IOServiceMatching(darwin_device_class),
413 darwin_devices_detached,
414 ctx, &libusb_rem_device_iterator);
416 if (kresult != kIOReturnSuccess) {
417 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
422 /* create notifications for attached devices */
423 kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
424 IOServiceMatching(darwin_device_class),
425 darwin_devices_attached,
426 ctx, &libusb_add_device_iterator);
428 if (kresult != kIOReturnSuccess) {
429 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
435 darwin_clear_iterator (libusb_rem_device_iterator);
436 darwin_clear_iterator (libusb_add_device_iterator);
438 usbi_dbg ("darwin event thread ready to receive events");
440 /* signal the main thread that the hotplug runloop has been created. */
441 pthread_mutex_lock (&libusb_darwin_at_mutex);
442 libusb_darwin_acfl = runloop;
443 pthread_cond_signal (&libusb_darwin_at_cond);
444 pthread_mutex_unlock (&libusb_darwin_at_mutex);
446 /* run the runloop */
449 usbi_dbg ("darwin event thread exiting");
451 /* remove the notification cfsource */
452 CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
454 /* remove the shutdown cfsource */
455 CFRunLoopRemoveSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
457 /* delete notification port */
458 IONotificationPortDestroy (libusb_notification_port);
460 /* delete iterators */
461 IOObjectRelease (libusb_rem_device_iterator);
462 IOObjectRelease (libusb_add_device_iterator);
464 CFRelease (libusb_darwin_acfls);
467 libusb_darwin_acfls = NULL;
468 libusb_darwin_acfl = NULL;
473 /* cleanup function to destroy cached devices */
474 static void __attribute__((destructor)) _darwin_finalize(void) {
475 struct darwin_cached_device *dev, *next;
477 usbi_mutex_lock(&darwin_cached_devices_lock);
478 list_for_each_entry_safe(dev, next, &darwin_cached_devices, list, struct darwin_cached_device) {
479 darwin_deref_cached_device(dev);
481 usbi_mutex_unlock(&darwin_cached_devices_lock);
484 static void darwin_check_version (void) {
485 /* adjust for changes in the USB stack in xnu 15 */
486 int sysctl_args[] = {CTL_KERN, KERN_OSRELEASE};
488 char version_string[256] = {'\0',};
491 sysctl(sysctl_args, 2, version_string, &length, NULL, 0);
494 version = strtol (version_string, NULL, 10);
495 if (0 == errno && version >= 15) {
496 darwin_device_class = "IOUSBHostDevice";
500 static int darwin_init(struct libusb_context *ctx) {
501 host_name_port_t host_self;
504 rc = pthread_once (&darwin_init_once, darwin_check_version);
506 return LIBUSB_ERROR_OTHER;
509 rc = darwin_scan_devices (ctx);
510 if (LIBUSB_SUCCESS != rc) {
514 if (OSAtomicIncrement32Barrier(&initCount) == 1) {
515 /* create the clocks that will be used */
517 host_self = mach_host_self();
518 host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
519 host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
520 mach_port_deallocate(mach_task_self(), host_self);
522 pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, ctx);
524 pthread_mutex_lock (&libusb_darwin_at_mutex);
525 while (!libusb_darwin_acfl)
526 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
527 pthread_mutex_unlock (&libusb_darwin_at_mutex);
533 static void darwin_exit (void) {
534 if (OSAtomicDecrement32Barrier(&initCount) == 0) {
535 mach_port_deallocate(mach_task_self(), clock_realtime);
536 mach_port_deallocate(mach_task_self(), clock_monotonic);
538 /* stop the event runloop and wait for the thread to terminate. */
539 CFRunLoopSourceSignal(libusb_darwin_acfls);
540 CFRunLoopWakeUp (libusb_darwin_acfl);
541 pthread_join (libusb_darwin_at, NULL);
545 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
546 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
548 /* return cached copy */
549 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
556 static int get_configuration_index (struct libusb_device *dev, int config_value) {
557 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
559 IOUSBConfigurationDescriptorPtr desc;
562 /* is there a simpler way to determine the index? */
563 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
564 if (kresult != kIOReturnSuccess)
565 return darwin_to_libusb (kresult);
567 for (i = 0 ; i < numConfig ; i++) {
568 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
570 if (desc->bConfigurationValue == config_value)
574 /* configuration not found */
575 return LIBUSB_ERROR_NOT_FOUND;
578 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
579 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
582 if (0 == priv->active_config)
583 return LIBUSB_ERROR_NOT_FOUND;
585 config_index = get_configuration_index (dev, priv->active_config);
586 if (config_index < 0)
589 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
592 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
593 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
594 IOUSBConfigurationDescriptorPtr desc;
598 if (!priv || !priv->device)
599 return LIBUSB_ERROR_OTHER;
601 kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
602 if (kresult == kIOReturnSuccess) {
603 /* copy descriptor */
604 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
605 len = libusb_le16_to_cpu(desc->wTotalLength);
607 memmove (buffer, desc, len);
609 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
613 ret = darwin_to_libusb (kresult);
614 if (ret != LIBUSB_SUCCESS)
620 /* check whether the os has configured the device */
621 static int darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) {
622 usb_device_t **darwin_device = dev->device;
624 IOUSBConfigurationDescriptorPtr configDesc;
625 IOUSBFindInterfaceRequest request;
626 kern_return_t kresult;
627 io_iterator_t interface_iterator;
628 io_service_t firstInterface;
630 if (dev->dev_descriptor.bNumConfigurations < 1) {
631 usbi_err (ctx, "device has no configurations");
632 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
635 /* checking the configuration of a root hub simulation takes ~1 s in 10.11. the device is
637 if (0x05ac == dev->dev_descriptor.idVendor && 0x8005 == dev->dev_descriptor.idProduct) {
638 usbi_dbg ("ignoring configuration on root hub simulation");
639 dev->active_config = 0;
643 /* find the first configuration */
644 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
645 dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
647 /* check if the device is already configured. there is probably a better way than iterating over the
648 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
649 might lock up on the device request) */
651 /* Setup the Interface Request */
652 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
653 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
654 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
655 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
657 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
659 return darwin_to_libusb (kresult);
662 firstInterface = IOIteratorNext(interface_iterator);
664 /* done with the interface iterator */
665 IOObjectRelease(interface_iterator);
667 if (firstInterface) {
668 IOObjectRelease (firstInterface);
670 /* device is configured */
671 if (dev->dev_descriptor.bNumConfigurations == 1)
672 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
673 dev->active_config = dev->first_config;
675 /* devices with more than one configuration should work with GetConfiguration */
676 (*darwin_device)->GetConfiguration (darwin_device, &dev->active_config);
679 dev->active_config = 0;
681 usbi_dbg ("active config: %u, first config: %u", dev->active_config, dev->first_config);
686 static int darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
687 IOUSBDevRequestTO req;
689 memset (buffer, 0, buffer_size);
691 /* Set up request for descriptor/ */
692 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
693 req.bRequest = kUSBRqGetDescriptor;
694 req.wValue = desc << 8;
695 req.wIndex = desc_index;
696 req.wLength = buffer_size;
698 req.noDataTimeout = 20;
699 req.completionTimeout = 100;
701 return (*device)->DeviceRequestTO (device, &req);
704 static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct darwin_cached_device *dev) {
705 usb_device_t **device = dev->device;
706 int retries = 1, delay = 30000;
707 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
711 UInt16 idProduct, idVendor;
713 dev->can_enumerate = 0;
715 (*device)->GetDeviceClass (device, &bDeviceClass);
716 (*device)->GetDeviceProduct (device, &idProduct);
717 (*device)->GetDeviceVendor (device, &idVendor);
719 /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
720 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
721 * to follow the spec as closely as possible, try opening the device */
722 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
725 /**** retrieve device descriptor ****/
726 ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &dev->dev_descriptor, sizeof(dev->dev_descriptor));
728 if (kIOReturnOverrun == ret && kUSBDeviceDesc == dev->dev_descriptor.bDescriptorType)
729 /* received an overrun error but we still received a device descriptor */
730 ret = kIOReturnSuccess;
732 if (kIOUSBVendorIDAppleComputer == idVendor) {
733 /* NTH: don't bother retrying or unsuspending Apple devices */
737 if (kIOReturnSuccess == ret && (0 == dev->dev_descriptor.bNumConfigurations ||
738 0 == dev->dev_descriptor.bcdUSB)) {
739 /* work around for incorrectly configured devices */
740 if (try_reconfigure && is_open) {
741 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
743 /* set the first configuration */
744 (*device)->SetConfiguration(device, 1);
746 /* don't try to reconfigure again */
750 ret = kIOUSBPipeStalled;
753 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
754 /* device may be suspended. unsuspend it and try again */
755 #if DeviceVersion >= 320
758 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
759 (void)(*device)->GetUSBDeviceInformation (device, &info);
761 /* note that the device was suspended */
762 if (info & (1 << kUSBInformationDeviceIsSuspendedBit) || 0 == info)
767 /* try to unsuspend the device */
768 ret2 = (*device)->USBDeviceSuspend (device, 0);
769 if (kIOReturnSuccess != ret2) {
770 /* prevent log spew from poorly behaving devices. this indicates the
771 os actually had trouble communicating with the device */
772 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
780 if (kIOReturnSuccess != ret) {
781 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
782 /* sleep for a little while before trying again */
783 nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000UL}, NULL);
785 } while (kIOReturnSuccess != ret && retries--);
788 /* resuspend the device */
789 (void)(*device)->USBDeviceSuspend (device, 1);
792 (void) (*device)->USBDeviceClose (device);
794 if (ret != kIOReturnSuccess) {
795 /* a debug message was already printed out for this error */
796 if (LIBUSB_CLASS_HUB == bDeviceClass)
797 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
798 idVendor, idProduct, darwin_error_str (ret), ret);
800 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
801 idVendor, idProduct, darwin_error_str (ret), ret);
802 return darwin_to_libusb (ret);
805 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
806 if (libusb_le16_to_cpu (dev->dev_descriptor.idProduct) != idProduct) {
807 /* not a valid device */
808 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
809 idProduct, libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
810 return LIBUSB_ERROR_NO_DEVICE;
813 usbi_dbg ("cached device descriptor:");
814 usbi_dbg (" bDescriptorType: 0x%02x", dev->dev_descriptor.bDescriptorType);
815 usbi_dbg (" bcdUSB: 0x%04x", dev->dev_descriptor.bcdUSB);
816 usbi_dbg (" bDeviceClass: 0x%02x", dev->dev_descriptor.bDeviceClass);
817 usbi_dbg (" bDeviceSubClass: 0x%02x", dev->dev_descriptor.bDeviceSubClass);
818 usbi_dbg (" bDeviceProtocol: 0x%02x", dev->dev_descriptor.bDeviceProtocol);
819 usbi_dbg (" bMaxPacketSize0: 0x%02x", dev->dev_descriptor.bMaxPacketSize0);
820 usbi_dbg (" idVendor: 0x%04x", dev->dev_descriptor.idVendor);
821 usbi_dbg (" idProduct: 0x%04x", dev->dev_descriptor.idProduct);
822 usbi_dbg (" bcdDevice: 0x%04x", dev->dev_descriptor.bcdDevice);
823 usbi_dbg (" iManufacturer: 0x%02x", dev->dev_descriptor.iManufacturer);
824 usbi_dbg (" iProduct: 0x%02x", dev->dev_descriptor.iProduct);
825 usbi_dbg (" iSerialNumber: 0x%02x", dev->dev_descriptor.iSerialNumber);
826 usbi_dbg (" bNumConfigurations: 0x%02x", dev->dev_descriptor.bNumConfigurations);
828 dev->can_enumerate = 1;
830 return LIBUSB_SUCCESS;
833 static int get_device_port (io_service_t service, UInt8 *port) {
834 kern_return_t result;
838 if (get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, port)) {
842 result = IORegistryEntryGetParentEntry (service, kIOServicePlane, &parent);
843 if (kIOReturnSuccess == result) {
844 ret = get_ioregistry_value_data (parent, CFSTR("port"), 1, port);
845 IOObjectRelease (parent);
851 static int darwin_get_cached_device(struct libusb_context *ctx, io_service_t service,
852 struct darwin_cached_device **cached_out) {
853 struct darwin_cached_device *new_device;
854 UInt64 sessionID = 0, parent_sessionID = 0;
855 int ret = LIBUSB_SUCCESS;
856 usb_device_t **device;
858 kern_return_t result;
861 /* get some info from the io registry */
862 (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
863 if (!get_device_port (service, &port)) {
864 usbi_dbg("could not get connected port number");
867 usbi_dbg("finding cached device for sessionID 0x%" PRIx64, sessionID);
869 result = IORegistryEntryGetParentEntry (service, kIOUSBPlane, &parent);
871 if (kIOReturnSuccess == result) {
872 (void) get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, &parent_sessionID);
873 IOObjectRelease(parent);
876 usbi_mutex_lock(&darwin_cached_devices_lock);
880 list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) {
881 usbi_dbg("matching sessionID 0x%" PRIx64 " against cached device with sessionID 0x%" PRIx64, sessionID, new_device->session);
882 if (new_device->session == sessionID) {
883 usbi_dbg("using cached device for device");
884 *cached_out = new_device;
892 usbi_dbg("caching new device with sessionID 0x%" PRIx64, sessionID);
894 device = darwin_device_from_service (service);
896 ret = LIBUSB_ERROR_NO_DEVICE;
900 new_device = calloc (1, sizeof (*new_device));
902 ret = LIBUSB_ERROR_NO_MEM;
906 /* add this device to the cached device list */
907 list_add(&new_device->list, &darwin_cached_devices);
909 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
911 /* keep a reference to this device */
912 darwin_ref_cached_device(new_device);
914 new_device->device = device;
915 new_device->session = sessionID;
916 (*device)->GetLocationID (device, &new_device->location);
917 new_device->port = port;
918 new_device->parent_session = parent_sessionID;
920 /* cache the device descriptor */
921 ret = darwin_cache_device_descriptor(ctx, new_device);
925 if (new_device->can_enumerate) {
926 snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address,
927 new_device->dev_descriptor.idVendor, new_device->dev_descriptor.idProduct,
928 new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass);
932 usbi_mutex_unlock(&darwin_cached_devices_lock);
934 /* keep track of devices regardless of if we successfully enumerate them to
935 prevent them from being enumerated multiple times */
937 *cached_out = new_device;
942 static int process_new_device (struct libusb_context *ctx, io_service_t service) {
943 struct darwin_device_priv *priv;
944 struct libusb_device *dev = NULL;
945 struct darwin_cached_device *cached_device;
950 ret = darwin_get_cached_device (ctx, service, &cached_device);
952 if (ret < 0 || !cached_device->can_enumerate) {
956 /* check current active configuration (and cache the first configuration value--
957 which may be used by claim_interface) */
958 ret = darwin_check_configuration (ctx, cached_device);
962 usbi_dbg ("allocating new device in context %p for with session 0x%" PRIx64,
963 ctx, cached_device->session);
965 dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
967 return LIBUSB_ERROR_NO_MEM;
970 priv = (struct darwin_device_priv *)dev->os_priv;
972 priv->dev = cached_device;
973 darwin_ref_cached_device (priv->dev);
975 if (cached_device->parent_session > 0) {
976 dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session);
978 dev->parent_dev = NULL;
980 dev->port_number = cached_device->port;
981 dev->bus_number = cached_device->location >> 24;
982 dev->device_address = cached_device->address;
984 (*(priv->dev->device))->GetDeviceSpeed (priv->dev->device, &devSpeed);
987 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
988 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
989 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
990 #if DeviceVersion >= 500
991 case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
994 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
997 ret = usbi_sanitize_device (dev);
1001 usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
1002 dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
1006 usbi_connect_device (dev);
1008 libusb_unref_device (dev);
1014 static int darwin_scan_devices(struct libusb_context *ctx) {
1015 io_iterator_t deviceIterator;
1016 io_service_t service;
1017 kern_return_t kresult;
1019 kresult = usb_setup_device_iterator (&deviceIterator, 0);
1020 if (kresult != kIOReturnSuccess)
1021 return darwin_to_libusb (kresult);
1023 while ((service = IOIteratorNext (deviceIterator))) {
1024 (void) process_new_device (ctx, service);
1026 IOObjectRelease(service);
1029 IOObjectRelease(deviceIterator);
1034 static int darwin_open (struct libusb_device_handle *dev_handle) {
1035 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1036 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1039 if (0 == dpriv->open_count) {
1040 /* try to open the device */
1041 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
1042 if (kresult != kIOReturnSuccess) {
1043 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
1045 if (kIOReturnExclusiveAccess != kresult) {
1046 return darwin_to_libusb (kresult);
1049 /* it is possible to perform some actions on a device that is not open so do not return an error */
1055 /* create async event source */
1056 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
1057 if (kresult != kIOReturnSuccess) {
1058 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
1060 if (priv->is_open) {
1061 (*(dpriv->device))->USBDeviceClose (dpriv->device);
1066 return darwin_to_libusb (kresult);
1069 CFRetain (libusb_darwin_acfl);
1071 /* add the cfSource to the aync run loop */
1072 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
1075 /* device opened successfully */
1076 dpriv->open_count++;
1078 usbi_dbg ("device open for access");
1083 static void darwin_close (struct libusb_device_handle *dev_handle) {
1084 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1085 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1089 if (dpriv->open_count == 0) {
1090 /* something is probably very wrong if this is the case */
1091 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!");
1095 dpriv->open_count--;
1097 /* make sure all interfaces are released */
1098 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1099 if (dev_handle->claimed_interfaces & (1 << i))
1100 libusb_release_interface (dev_handle, i);
1102 if (0 == dpriv->open_count) {
1103 /* delete the device's async event source */
1104 if (priv->cfSource) {
1105 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
1106 CFRelease (priv->cfSource);
1107 priv->cfSource = NULL;
1108 CFRelease (libusb_darwin_acfl);
1111 if (priv->is_open) {
1112 /* close the device */
1113 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
1115 /* Log the fact that we had a problem closing the file, however failing a
1116 * close isn't really an error, so return success anyway */
1117 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
1123 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
1124 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1126 *config = (int) dpriv->active_config;
1131 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
1132 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1136 /* Setting configuration will invalidate the interface, so we need
1137 to reclaim it. First, dispose of existing interfaces, if any. */
1138 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1139 if (dev_handle->claimed_interfaces & (1 << i))
1140 darwin_release_interface (dev_handle, i);
1142 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
1143 if (kresult != kIOReturnSuccess)
1144 return darwin_to_libusb (kresult);
1146 /* Reclaim any interfaces. */
1147 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1148 if (dev_handle->claimed_interfaces & (1 << i))
1149 darwin_claim_interface (dev_handle, i);
1151 dpriv->active_config = config;
1156 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
1157 IOUSBFindInterfaceRequest request;
1158 kern_return_t kresult;
1159 io_iterator_t interface_iterator;
1160 UInt8 bInterfaceNumber;
1163 *usbInterfacep = IO_OBJECT_NULL;
1165 /* Setup the Interface Request */
1166 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1167 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1168 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1169 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1171 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1175 while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1176 /* find the interface number */
1177 ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
1180 if (ret && bInterfaceNumber == ifc) {
1184 (void) IOObjectRelease (*usbInterfacep);
1187 /* done with the interface iterator */
1188 IOObjectRelease(interface_iterator);
1193 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
1194 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1196 /* current interface */
1197 struct darwin_interface *cInterface = &priv->interfaces[iface];
1199 kern_return_t kresult;
1201 u_int8_t numep, direction, number;
1202 u_int8_t dont_care1, dont_care3;
1203 u_int16_t dont_care2;
1206 usbi_dbg ("building table of endpoints.");
1208 /* retrieve the total number of endpoints on this interface */
1209 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1211 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1212 return darwin_to_libusb (kresult);
1215 /* iterate through pipe references */
1216 for (i = 1 ; i <= numep ; i++) {
1217 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1218 &dont_care2, &dont_care3);
1220 if (kresult != kIOReturnSuccess) {
1221 usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
1223 return darwin_to_libusb (kresult);
1226 usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
1228 cInterface->endpoint_addrs[i - 1] = (((kUSBIn == direction) << kUSBRqDirnShift) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1231 cInterface->num_endpoints = numep;
1236 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1237 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1238 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1239 io_service_t usbInterface = IO_OBJECT_NULL;
1241 IOCFPlugInInterface **plugInInterface = NULL;
1244 /* current interface */
1245 struct darwin_interface *cInterface = &priv->interfaces[iface];
1247 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1248 if (kresult != kIOReturnSuccess)
1249 return darwin_to_libusb (kresult);
1251 /* make sure we have an interface */
1252 if (!usbInterface && dpriv->first_config != 0) {
1253 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1255 /* set the configuration */
1256 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1257 if (kresult != LIBUSB_SUCCESS) {
1258 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1262 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1264 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1265 return darwin_to_libusb (kresult);
1269 if (!usbInterface) {
1270 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1271 return LIBUSB_ERROR_NOT_FOUND;
1274 /* get an interface to the device's interface */
1275 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1276 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1278 /* ignore release error */
1279 (void)IOObjectRelease (usbInterface);
1282 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1283 return darwin_to_libusb (kresult);
1286 if (!plugInInterface) {
1287 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1288 return LIBUSB_ERROR_NOT_FOUND;
1291 /* Do the actual claim */
1292 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1293 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1294 (LPVOID)&cInterface->interface);
1295 /* We no longer need the intermediate plug-in */
1296 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1297 (*plugInInterface)->Release (plugInInterface);
1298 if (kresult || !cInterface->interface) {
1299 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1300 return darwin_to_libusb (kresult);
1303 /* claim the interface */
1304 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1306 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1307 return darwin_to_libusb (kresult);
1310 /* update list of endpoints */
1311 kresult = get_endpoints (dev_handle, iface);
1313 /* this should not happen */
1314 darwin_release_interface (dev_handle, iface);
1315 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1319 cInterface->cfSource = NULL;
1321 /* create async event source */
1322 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1323 if (kresult != kIOReturnSuccess) {
1324 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1326 /* can't continue without an async event source */
1327 (void)darwin_release_interface (dev_handle, iface);
1329 return darwin_to_libusb (kresult);
1332 /* add the cfSource to the async thread's run loop */
1333 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1335 usbi_dbg ("interface opened");
1340 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1341 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1344 /* current interface */
1345 struct darwin_interface *cInterface = &priv->interfaces[iface];
1347 /* Check to see if an interface is open */
1348 if (!cInterface->interface)
1349 return LIBUSB_SUCCESS;
1351 /* clean up endpoint data */
1352 cInterface->num_endpoints = 0;
1354 /* delete the interface's async event source */
1355 if (cInterface->cfSource) {
1356 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1357 CFRelease (cInterface->cfSource);
1360 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1362 usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1364 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1365 if (kresult != kIOReturnSuccess)
1366 usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1368 cInterface->interface = (usb_interface_t **) IO_OBJECT_NULL;
1370 return darwin_to_libusb (kresult);
1373 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1374 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1377 /* current interface */
1378 struct darwin_interface *cInterface = &priv->interfaces[iface];
1380 if (!cInterface->interface)
1381 return LIBUSB_ERROR_NO_DEVICE;
1383 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1384 if (kresult != kIOReturnSuccess)
1385 darwin_reset_device (dev_handle);
1387 /* update list of endpoints */
1388 kresult = get_endpoints (dev_handle, iface);
1390 /* this should not happen */
1391 darwin_release_interface (dev_handle, iface);
1392 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1396 return darwin_to_libusb (kresult);
1399 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1400 /* current interface */
1401 struct darwin_interface *cInterface;
1405 /* determine the interface/endpoint to use */
1406 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, NULL, &cInterface) != 0) {
1407 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1409 return LIBUSB_ERROR_NOT_FOUND;
1412 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1413 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1415 usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1417 return darwin_to_libusb (kresult);
1420 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1421 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1422 IOUSBDeviceDescriptor descriptor;
1423 IOUSBConfigurationDescriptorPtr cached_configuration;
1424 IOUSBConfigurationDescriptor configuration;
1425 bool reenumerate = false;
1429 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1431 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1432 return darwin_to_libusb (kresult);
1436 usbi_dbg ("darwin/reset_device: checking if device descriptor changed");
1438 /* ignore return code. if we can't get a descriptor it might be worthwhile re-enumerating anway */
1439 (void) darwin_request_descriptor (dpriv->device, kUSBDeviceDesc, 0, &descriptor, sizeof (descriptor));
1441 /* check if the device descriptor has changed */
1442 if (0 != memcmp (&dpriv->dev_descriptor, &descriptor, sizeof (descriptor))) {
1447 /* check if any configuration descriptor has changed */
1448 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1449 usbi_dbg ("darwin/reset_device: checking if configuration descriptor %d changed", i);
1451 (void) darwin_request_descriptor (dpriv->device, kUSBConfDesc, i, &configuration, sizeof (configuration));
1452 (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1454 if (!cached_configuration || 0 != memcmp (cached_configuration, &configuration, sizeof (configuration))) {
1462 usbi_dbg ("darwin/reset_device: device requires reenumeration");
1463 (void) (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
1464 return LIBUSB_ERROR_NOT_FOUND;
1467 usbi_dbg ("darwin/reset_device: device reset complete");
1469 return LIBUSB_SUCCESS;
1472 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1473 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1474 io_service_t usbInterface;
1478 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1480 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1482 return darwin_to_libusb (kresult);
1485 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1486 IOObjectRelease (usbInterface);
1498 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1499 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1502 return LIBUSB_ERROR_NOT_SUPPORTED;
1505 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1508 return LIBUSB_ERROR_NOT_SUPPORTED;
1511 static void darwin_destroy_device(struct libusb_device *dev) {
1512 struct darwin_device_priv *dpriv = (struct darwin_device_priv *) dev->os_priv;
1515 /* need to hold the lock in case this is the last reference to the device */
1516 usbi_mutex_lock(&darwin_cached_devices_lock);
1517 darwin_deref_cached_device (dpriv->dev);
1519 usbi_mutex_unlock(&darwin_cached_devices_lock);
1523 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1524 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1527 uint8_t transferType;
1528 /* None of the values below are used in libusbx for bulk transfers */
1529 uint8_t direction, number, interval, pipeRef;
1530 uint16_t maxPacketSize;
1532 struct darwin_interface *cInterface;
1534 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1535 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1537 return LIBUSB_ERROR_NOT_FOUND;
1540 ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1541 &transferType, &maxPacketSize, &interval);
1544 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1545 darwin_error_str(ret), ret);
1546 return darwin_to_libusb (ret);
1549 if (0 != (transfer->length % maxPacketSize)) {
1550 /* do not need a zero packet */
1551 transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1554 /* submit the request */
1555 /* timeouts are unavailable on interrupt endpoints */
1556 if (transferType == kUSBInterrupt) {
1557 if (IS_XFERIN(transfer))
1558 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1559 transfer->length, darwin_async_io_callback, itransfer);
1561 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1562 transfer->length, darwin_async_io_callback, itransfer);
1564 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1566 if (IS_XFERIN(transfer))
1567 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1568 transfer->length, transfer->timeout, transfer->timeout,
1569 darwin_async_io_callback, (void *)itransfer);
1571 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1572 transfer->length, transfer->timeout, transfer->timeout,
1573 darwin_async_io_callback, (void *)itransfer);
1577 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1578 darwin_error_str(ret), ret);
1580 return darwin_to_libusb (ret);
1583 #if InterfaceVersion >= 550
1584 static int submit_stream_transfer(struct usbi_transfer *itransfer) {
1585 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1586 struct darwin_interface *cInterface;
1590 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1591 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1593 return LIBUSB_ERROR_NOT_FOUND;
1596 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1598 if (IS_XFERIN(transfer))
1599 ret = (*(cInterface->interface))->ReadStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1600 transfer->buffer, transfer->length, transfer->timeout,
1601 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1603 ret = (*(cInterface->interface))->WriteStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1604 transfer->buffer, transfer->length, transfer->timeout,
1605 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1608 usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1609 darwin_error_str(ret), ret);
1611 return darwin_to_libusb (ret);
1615 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1616 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1617 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1620 uint8_t direction, number, interval, pipeRef, transferType;
1621 uint16_t maxPacketSize;
1623 AbsoluteTime atTime;
1626 struct darwin_interface *cInterface;
1628 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1629 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1630 free(tpriv->isoc_framelist);
1631 tpriv->isoc_framelist = NULL;
1634 if (!tpriv->isoc_framelist) {
1635 tpriv->num_iso_packets = transfer->num_iso_packets;
1636 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1637 if (!tpriv->isoc_framelist)
1638 return LIBUSB_ERROR_NO_MEM;
1641 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1642 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1643 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1645 /* determine the interface/endpoint to use */
1646 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1647 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1649 return LIBUSB_ERROR_NOT_FOUND;
1652 /* determine the properties of this endpoint and the speed of the device */
1653 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1654 &transferType, &maxPacketSize, &interval);
1656 /* Last but not least we need the bus frame number */
1657 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1659 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1660 free(tpriv->isoc_framelist);
1661 tpriv->isoc_framelist = NULL;
1663 return darwin_to_libusb (kresult);
1666 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1667 &transferType, &maxPacketSize, &interval);
1669 /* schedule for a frame a little in the future */
1672 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1673 frame = cInterface->frames[transfer->endpoint];
1675 /* submit the request */
1676 if (IS_XFERIN(transfer))
1677 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1678 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1681 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1682 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1685 if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
1687 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1));
1689 /* High/super speed */
1690 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1)) / 8;
1692 if (kresult != kIOReturnSuccess) {
1693 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1694 darwin_error_str(kresult));
1695 free (tpriv->isoc_framelist);
1696 tpriv->isoc_framelist = NULL;
1699 return darwin_to_libusb (kresult);
1702 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1703 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1704 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1705 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1706 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1710 bzero(&tpriv->req, sizeof(tpriv->req));
1712 /* IOUSBDeviceInterface expects the request in cpu endianness */
1713 tpriv->req.bmRequestType = setup->bmRequestType;
1714 tpriv->req.bRequest = setup->bRequest;
1715 /* these values should be in bus order from libusb_fill_control_setup */
1716 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1717 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1718 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1719 /* data is stored after the libusb control block */
1720 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1721 tpriv->req.completionTimeout = transfer->timeout;
1722 tpriv->req.noDataTimeout = transfer->timeout;
1724 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1726 /* all transfers in libusb-1.0 are async */
1728 if (transfer->endpoint) {
1729 struct darwin_interface *cInterface;
1732 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1733 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1735 return LIBUSB_ERROR_NOT_FOUND;
1738 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1740 /* control request on endpoint 0 */
1741 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1743 if (kresult != kIOReturnSuccess)
1744 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1746 return darwin_to_libusb (kresult);
1749 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1750 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1752 switch (transfer->type) {
1753 case LIBUSB_TRANSFER_TYPE_CONTROL:
1754 return submit_control_transfer(itransfer);
1755 case LIBUSB_TRANSFER_TYPE_BULK:
1756 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1757 return submit_bulk_transfer(itransfer);
1758 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1759 return submit_iso_transfer(itransfer);
1760 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1761 #if InterfaceVersion >= 550
1762 return submit_stream_transfer(itransfer);
1764 usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers");
1765 return LIBUSB_ERROR_NOT_SUPPORTED;
1768 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1769 return LIBUSB_ERROR_INVALID_PARAM;
1773 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1774 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1775 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1778 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
1781 return LIBUSB_ERROR_NO_DEVICE;
1783 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1785 return darwin_to_libusb (kresult);
1788 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1789 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1790 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1791 struct darwin_interface *cInterface;
1792 uint8_t pipeRef, iface;
1795 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) {
1796 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1798 return LIBUSB_ERROR_NOT_FOUND;
1802 return LIBUSB_ERROR_NO_DEVICE;
1804 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
1806 /* abort transactions */
1807 #if InterfaceVersion >= 550
1808 if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type)
1809 (*(cInterface->interface))->AbortStreamsPipe (cInterface->interface, pipeRef, itransfer->stream_id);
1812 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1814 usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
1816 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1817 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1819 return darwin_to_libusb (kresult);
1822 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1823 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1825 switch (transfer->type) {
1826 case LIBUSB_TRANSFER_TYPE_CONTROL:
1827 return cancel_control_transfer(itransfer);
1828 case LIBUSB_TRANSFER_TYPE_BULK:
1829 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1830 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1831 return darwin_abort_transfers (itransfer);
1833 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1834 return LIBUSB_ERROR_INVALID_PARAM;
1838 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1839 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1840 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1842 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1843 free (tpriv->isoc_framelist);
1844 tpriv->isoc_framelist = NULL;
1848 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1849 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1850 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1851 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1853 usbi_dbg ("an async io operation has completed");
1855 /* if requested write a zero packet */
1856 if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
1857 struct darwin_interface *cInterface;
1860 (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface);
1862 (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
1865 tpriv->result = result;
1866 tpriv->size = (UInt32) (uintptr_t) arg0;
1868 /* signal the core that this transfer is complete */
1869 usbi_signal_transfer_completion(itransfer);
1872 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1873 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT)
1874 result = kIOUSBTransactionTimeout;
1877 case kIOReturnUnderrun:
1878 case kIOReturnSuccess:
1879 return LIBUSB_TRANSFER_COMPLETED;
1880 case kIOReturnAborted:
1881 return LIBUSB_TRANSFER_CANCELLED;
1882 case kIOUSBPipeStalled:
1883 usbi_dbg ("transfer error: pipe is stalled");
1884 return LIBUSB_TRANSFER_STALL;
1885 case kIOReturnOverrun:
1886 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1887 return LIBUSB_TRANSFER_OVERFLOW;
1888 case kIOUSBTransactionTimeout:
1889 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1890 itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
1891 return LIBUSB_TRANSFER_TIMED_OUT;
1893 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1894 return LIBUSB_TRANSFER_ERROR;
1898 static int darwin_handle_transfer_completion (struct usbi_transfer *itransfer) {
1899 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1900 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1901 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1902 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1903 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1904 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1907 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1908 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1909 return LIBUSB_ERROR_INVALID_PARAM;
1912 usbi_dbg ("handling %s completion with kernel status %d",
1913 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", tpriv->result);
1915 if (kIOReturnSuccess == tpriv->result || kIOReturnUnderrun == tpriv->result) {
1916 if (isIsoc && tpriv->isoc_framelist) {
1917 /* copy isochronous results back */
1919 for (i = 0; i < transfer->num_iso_packets ; i++) {
1920 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1921 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1922 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1925 itransfer->transferred += tpriv->size;
1928 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1929 return usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, tpriv->result));
1932 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1933 mach_timespec_t sys_time;
1934 clock_serv_t clock_ref;
1937 case USBI_CLOCK_REALTIME:
1938 /* CLOCK_REALTIME represents time since the epoch */
1939 clock_ref = clock_realtime;
1941 case USBI_CLOCK_MONOTONIC:
1942 /* use system boot time as reference for the monotonic clock */
1943 clock_ref = clock_monotonic;
1946 return LIBUSB_ERROR_INVALID_PARAM;
1949 clock_get_time (clock_ref, &sys_time);
1951 tp->tv_sec = sys_time.tv_sec;
1952 tp->tv_nsec = sys_time.tv_nsec;
1957 #if InterfaceVersion >= 550
1958 static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints,
1959 int num_endpoints) {
1960 struct darwin_interface *cInterface;
1961 UInt32 supportsStreams;
1965 /* find the mimimum number of supported streams on the endpoint list */
1966 for (i = 0 ; i < num_endpoints ; ++i) {
1967 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) {
1971 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
1972 if (num_streams > supportsStreams)
1973 num_streams = supportsStreams;
1976 /* it is an error if any endpoint in endpoints does not support streams */
1977 if (0 == num_streams)
1978 return LIBUSB_ERROR_INVALID_PARAM;
1980 /* create the streams */
1981 for (i = 0 ; i < num_endpoints ; ++i) {
1982 (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
1984 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, num_streams);
1985 if (kIOReturnSuccess != rc)
1986 return darwin_to_libusb(rc);
1992 static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) {
1993 struct darwin_interface *cInterface;
1994 UInt32 supportsStreams;
1998 for (int i = 0 ; i < num_endpoints ; ++i) {
1999 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface)))
2002 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2003 if (0 == supportsStreams)
2004 return LIBUSB_ERROR_INVALID_PARAM;
2006 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, 0);
2007 if (kIOReturnSuccess != rc)
2008 return darwin_to_libusb(rc);
2011 return LIBUSB_SUCCESS;
2015 const struct usbi_os_backend darwin_backend = {
2018 .init = darwin_init,
2019 .exit = darwin_exit,
2020 .get_device_list = NULL, /* not needed */
2021 .get_device_descriptor = darwin_get_device_descriptor,
2022 .get_active_config_descriptor = darwin_get_active_config_descriptor,
2023 .get_config_descriptor = darwin_get_config_descriptor,
2024 .hotplug_poll = darwin_hotplug_poll,
2026 .open = darwin_open,
2027 .close = darwin_close,
2028 .get_configuration = darwin_get_configuration,
2029 .set_configuration = darwin_set_configuration,
2030 .claim_interface = darwin_claim_interface,
2031 .release_interface = darwin_release_interface,
2033 .set_interface_altsetting = darwin_set_interface_altsetting,
2034 .clear_halt = darwin_clear_halt,
2035 .reset_device = darwin_reset_device,
2037 #if InterfaceVersion >= 550
2038 .alloc_streams = darwin_alloc_streams,
2039 .free_streams = darwin_free_streams,
2042 .kernel_driver_active = darwin_kernel_driver_active,
2043 .detach_kernel_driver = darwin_detach_kernel_driver,
2044 .attach_kernel_driver = darwin_attach_kernel_driver,
2046 .destroy_device = darwin_destroy_device,
2048 .submit_transfer = darwin_submit_transfer,
2049 .cancel_transfer = darwin_cancel_transfer,
2050 .clear_transfer_priv = darwin_clear_transfer_priv,
2052 .handle_transfer_completion = darwin_handle_transfer_completion,
2054 .clock_gettime = darwin_clock_gettime,
2056 .device_priv_size = sizeof(struct darwin_device_priv),
2057 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
2058 .transfer_priv_size = sizeof(struct darwin_transfer_priv),