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 volatile int32_t initCount = 0;
59 static usbi_mutex_t darwin_cached_devices_lock = PTHREAD_MUTEX_INITIALIZER;
60 static struct list_head darwin_cached_devices = {&darwin_cached_devices, &darwin_cached_devices};
61 static char *darwin_device_class = kIOUSBDeviceClassName;
63 #define DARWIN_CACHED_DEVICE(a) ((struct darwin_cached_device *) (((struct darwin_device_priv *)((a)->os_priv))->dev))
65 /* async event thread */
66 static pthread_t libusb_darwin_at;
68 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
69 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
70 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
71 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
72 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
74 static int darwin_scan_devices(struct libusb_context *ctx);
75 static int process_new_device (struct libusb_context *ctx, io_service_t service);
77 #if defined(ENABLE_LOGGING)
78 static const char *darwin_error_str (int result) {
79 static char string_buffer[50];
81 case kIOReturnSuccess:
83 case kIOReturnNotOpen:
84 return "device not opened for exclusive access";
85 case kIOReturnNoDevice:
86 return "no connection to an IOService";
87 case kIOUSBNoAsyncPortErr:
88 return "no async port has been opened for interface";
89 case kIOReturnExclusiveAccess:
90 return "another process has device opened for exclusive access";
91 case kIOUSBPipeStalled:
92 return "pipe is stalled";
94 return "could not establish a connection to the Darwin kernel";
95 case kIOUSBTransactionTimeout:
96 return "transaction timed out";
97 case kIOReturnBadArgument:
98 return "invalid argument";
99 case kIOReturnAborted:
100 return "transaction aborted";
101 case kIOReturnNotResponding:
102 return "device not responding";
103 case kIOReturnOverrun:
104 return "data overrun";
105 case kIOReturnCannotWire:
106 return "physical memory can not be wired down";
107 case kIOReturnNoResources:
108 return "out of resources";
109 case kIOUSBHighSpeedSplitError:
110 return "high speed split error";
112 snprintf(string_buffer, sizeof(string_buffer), "unknown error (0x%x)", result);
113 return string_buffer;
118 static int darwin_to_libusb (int result) {
120 case kIOReturnUnderrun:
121 case kIOReturnSuccess:
122 return LIBUSB_SUCCESS;
123 case kIOReturnNotOpen:
124 case kIOReturnNoDevice:
125 return LIBUSB_ERROR_NO_DEVICE;
126 case kIOReturnExclusiveAccess:
127 return LIBUSB_ERROR_ACCESS;
128 case kIOUSBPipeStalled:
129 return LIBUSB_ERROR_PIPE;
130 case kIOReturnBadArgument:
131 return LIBUSB_ERROR_INVALID_PARAM;
132 case kIOUSBTransactionTimeout:
133 return LIBUSB_ERROR_TIMEOUT;
134 case kIOReturnNotResponding:
135 case kIOReturnAborted:
137 case kIOUSBNoAsyncPortErr:
139 return LIBUSB_ERROR_OTHER;
143 /* this function must be called with the darwin_cached_devices_lock held */
144 static void darwin_deref_cached_device(struct darwin_cached_device *cached_dev) {
145 cached_dev->refcount--;
146 /* free the device and remove it from the cache */
147 if (0 == cached_dev->refcount) {
148 list_del(&cached_dev->list);
150 (*(cached_dev->device))->Release(cached_dev->device);
155 static void darwin_ref_cached_device(struct darwin_cached_device *cached_dev) {
156 cached_dev->refcount++;
159 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) {
160 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
162 /* current interface */
163 struct darwin_interface *cInterface;
167 usbi_dbg ("converting ep address 0x%02x to pipeRef and interface", ep);
169 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
170 cInterface = &priv->interfaces[iface];
172 if (dev_handle->claimed_interfaces & (1 << iface)) {
173 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
174 if (cInterface->endpoint_addrs[i] == ep) {
181 *interface_out = cInterface;
183 usbi_dbg ("pipe %d on interface %d matches", *pipep, iface);
190 /* No pipe found with the correct endpoint address */
191 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
193 return LIBUSB_ERROR_NOT_FOUND;
196 static int usb_setup_device_iterator (io_iterator_t *deviceIterator, UInt32 location) {
197 CFMutableDictionaryRef matchingDict = IOServiceMatching(darwin_device_class);
200 return kIOReturnError;
203 CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
204 &kCFTypeDictionaryKeyCallBacks,
205 &kCFTypeDictionaryValueCallBacks);
207 if (propertyMatchDict) {
208 /* there are no unsigned CFNumber types so treat the value as signed. the os seems to do this
209 internally (CFNumberType of locationID is 3) */
210 CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberSInt32Type, &location);
212 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
213 /* release our reference to the CFNumber (CFDictionarySetValue retains it) */
214 CFRelease (locationCF);
216 CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
217 /* release out reference to the CFMutableDictionaryRef (CFDictionarySetValue retains it) */
218 CFRelease (propertyMatchDict);
220 /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
223 return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator);
226 /* Returns 1 on success, 0 on failure. */
227 static int get_ioregistry_value_number (io_service_t service, CFStringRef property, CFNumberType type, void *p) {
228 CFTypeRef cfNumber = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
232 if (CFGetTypeID(cfNumber) == CFNumberGetTypeID()) {
233 ret = CFNumberGetValue(cfNumber, type, p);
236 CFRelease (cfNumber);
242 static int get_ioregistry_value_data (io_service_t service, CFStringRef property, ssize_t size, void *p) {
243 CFTypeRef cfData = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
247 if (CFGetTypeID (cfData) == CFDataGetTypeID ()) {
248 CFIndex length = CFDataGetLength (cfData);
253 CFDataGetBytes (cfData, CFRangeMake(0, size), p);
263 static usb_device_t **darwin_device_from_service (io_service_t service)
265 io_cf_plugin_ref_t *plugInInterface = NULL;
266 usb_device_t **device;
267 kern_return_t result;
270 result = IOCreatePlugInInterfaceForService(service, kIOUSBDeviceUserClientTypeID,
271 kIOCFPlugInInterfaceID, &plugInInterface,
274 if (kIOReturnSuccess != result || !plugInInterface) {
275 usbi_dbg ("could not set up plugin for service: %s", darwin_error_str (result));
279 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
281 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
282 (*plugInInterface)->Release (plugInInterface);
287 static void darwin_devices_attached (void *ptr, io_iterator_t add_devices) {
288 struct libusb_context *ctx;
289 io_service_t service;
291 usbi_mutex_lock(&active_contexts_lock);
293 while ((service = IOIteratorNext(add_devices))) {
294 /* add this device to each active context's device list */
295 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
296 process_new_device (ctx, service);;
299 IOObjectRelease(service);
302 usbi_mutex_unlock(&active_contexts_lock);
305 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
306 struct libusb_device *dev = NULL;
307 struct libusb_context *ctx;
308 struct darwin_cached_device *old_device;
314 usbi_mutex_lock(&active_contexts_lock);
316 while ((device = IOIteratorNext (rem_devices)) != 0) {
317 /* get the location from the i/o registry */
318 ret = get_ioregistry_value_number (device, CFSTR("sessionID"), kCFNumberSInt64Type, &session);
319 IOObjectRelease (device);
323 /* we need to match darwin_ref_cached_device call made in darwin_get_cached_device function
324 otherwise no cached device will ever get freed */
325 usbi_mutex_lock(&darwin_cached_devices_lock);
326 list_for_each_entry(old_device, &darwin_cached_devices, list, struct darwin_cached_device) {
327 if (old_device->session == session) {
328 darwin_deref_cached_device (old_device);
332 usbi_mutex_unlock(&darwin_cached_devices_lock);
334 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
335 usbi_dbg ("notifying context %p of device disconnect", ctx);
337 dev = usbi_get_device_by_session_id(ctx, (unsigned long) session);
339 /* signal the core that this device has been disconnected. the core will tear down this device
340 when the reference count reaches 0 */
341 usbi_disconnect_device(dev);
342 libusb_unref_device(dev);
347 usbi_mutex_unlock(&active_contexts_lock);
350 static void darwin_hotplug_poll (void)
352 /* not sure if 5 seconds will be too long/short but it should work ok */
353 mach_timespec_t timeout = {.tv_sec = 5, .tv_nsec = 0};
355 /* since a kernel thread may nodify the IOInterators used for
356 * hotplug notidication we can't just clear the iterators.
357 * instead just wait until all IOService providers are quiet */
358 (void) IOKitWaitQuiet (kIOMasterPortDefault, &timeout);
361 static void darwin_clear_iterator (io_iterator_t iter) {
364 while ((device = IOIteratorNext (iter)) != 0)
365 IOObjectRelease (device);
368 static void *darwin_event_thread_main (void *arg0) {
370 struct libusb_context *ctx = (struct libusb_context *)arg0;
371 CFRunLoopRef runloop;
373 /* Set this thread's name, so it can be seen in the debugger
374 and crash reports. */
375 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
376 pthread_setname_np ("org.libusb.device-hotplug");
378 /* Tell the Objective-C garbage collector about this thread.
379 This is required because, unlike NSThreads, pthreads are
380 not automatically registered. Although we don't use
381 Objective-C, we use CoreFoundation, which does. */
382 objc_registerThreadWithCollector();
385 /* hotplug (device arrival/removal) sources */
386 CFRunLoopSourceRef libusb_notification_cfsource;
387 io_notification_port_t libusb_notification_port;
388 io_iterator_t libusb_rem_device_iterator;
389 io_iterator_t libusb_add_device_iterator;
391 usbi_dbg ("creating hotplug event source");
393 runloop = CFRunLoopGetCurrent ();
396 /* add the notification port to the run loop */
397 libusb_notification_port = IONotificationPortCreate (kIOMasterPortDefault);
398 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
399 CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
401 /* create notifications for removed devices */
402 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
403 IOServiceMatching(darwin_device_class),
404 darwin_devices_detached,
405 ctx, &libusb_rem_device_iterator);
407 if (kresult != kIOReturnSuccess) {
408 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
413 /* create notifications for attached devices */
414 kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
415 IOServiceMatching(darwin_device_class),
416 darwin_devices_attached,
417 ctx, &libusb_add_device_iterator);
419 if (kresult != kIOReturnSuccess) {
420 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
426 darwin_clear_iterator (libusb_rem_device_iterator);
427 darwin_clear_iterator (libusb_add_device_iterator);
429 usbi_dbg ("darwin event thread ready to receive events");
431 /* signal the main thread that the hotplug runloop has been created. */
432 pthread_mutex_lock (&libusb_darwin_at_mutex);
433 libusb_darwin_acfl = runloop;
434 pthread_cond_signal (&libusb_darwin_at_cond);
435 pthread_mutex_unlock (&libusb_darwin_at_mutex);
437 /* run the runloop */
440 usbi_dbg ("darwin event thread exiting");
442 /* remove the notification cfsource */
443 CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
445 /* delete notification port */
446 IONotificationPortDestroy (libusb_notification_port);
448 /* delete iterators */
449 IOObjectRelease (libusb_rem_device_iterator);
450 IOObjectRelease (libusb_add_device_iterator);
454 libusb_darwin_acfl = NULL;
459 /* cleanup function to destroy cached devices */
460 static void __attribute__((destructor)) _darwin_finalize(void) {
461 struct darwin_cached_device *dev, *next;
463 usbi_mutex_lock(&darwin_cached_devices_lock);
464 list_for_each_entry_safe(dev, next, &darwin_cached_devices, list, struct darwin_cached_device) {
465 darwin_deref_cached_device(dev);
467 usbi_mutex_unlock(&darwin_cached_devices_lock);
470 static void darwin_check_version (void) {
471 /* adjust for changes in the USB stack in xnu 15 */
472 int sysctl_args[] = {CTL_KERN, KERN_OSRELEASE};
474 char version_string[256] = {'\0',};
477 sysctl(sysctl_args, 2, version_string, &length, NULL, 0);
480 version = strtol (version_string, NULL, 10);
481 if (0 == errno && version >= 15) {
482 darwin_device_class = "IOUSBHostDevice";
486 static int darwin_init(struct libusb_context *ctx) {
487 host_name_port_t host_self;
490 rc = pthread_once (&darwin_init_once, darwin_check_version);
492 return LIBUSB_ERROR_OTHER;
495 rc = darwin_scan_devices (ctx);
496 if (LIBUSB_SUCCESS != rc) {
500 if (OSAtomicIncrement32Barrier(&initCount) == 1) {
501 /* create the clocks that will be used */
503 host_self = mach_host_self();
504 host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
505 host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
506 mach_port_deallocate(mach_task_self(), host_self);
508 pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, ctx);
510 pthread_mutex_lock (&libusb_darwin_at_mutex);
511 while (!libusb_darwin_acfl)
512 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
513 pthread_mutex_unlock (&libusb_darwin_at_mutex);
519 static void darwin_exit (void) {
520 if (OSAtomicDecrement32Barrier(&initCount) == 0) {
521 mach_port_deallocate(mach_task_self(), clock_realtime);
522 mach_port_deallocate(mach_task_self(), clock_monotonic);
524 /* stop the event runloop and wait for the thread to terminate. */
525 CFRunLoopStop (libusb_darwin_acfl);
526 pthread_join (libusb_darwin_at, NULL);
530 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
531 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
533 /* return cached copy */
534 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
541 static int get_configuration_index (struct libusb_device *dev, int config_value) {
542 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
544 IOUSBConfigurationDescriptorPtr desc;
547 /* is there a simpler way to determine the index? */
548 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
549 if (kresult != kIOReturnSuccess)
550 return darwin_to_libusb (kresult);
552 for (i = 0 ; i < numConfig ; i++) {
553 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
555 if (desc->bConfigurationValue == config_value)
559 /* configuration not found */
560 return LIBUSB_ERROR_NOT_FOUND;
563 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
564 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
567 if (0 == priv->active_config)
568 return LIBUSB_ERROR_NOT_FOUND;
570 config_index = get_configuration_index (dev, priv->active_config);
571 if (config_index < 0)
574 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
577 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
578 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
579 IOUSBConfigurationDescriptorPtr desc;
583 if (!priv || !priv->device)
584 return LIBUSB_ERROR_OTHER;
586 kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
587 if (kresult == kIOReturnSuccess) {
588 /* copy descriptor */
589 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
590 len = libusb_le16_to_cpu(desc->wTotalLength);
592 memmove (buffer, desc, len);
594 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
598 ret = darwin_to_libusb (kresult);
599 if (ret != LIBUSB_SUCCESS)
605 /* check whether the os has configured the device */
606 static int darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) {
607 usb_device_t **darwin_device = dev->device;
609 IOUSBConfigurationDescriptorPtr configDesc;
610 IOUSBFindInterfaceRequest request;
611 kern_return_t kresult;
612 io_iterator_t interface_iterator;
613 io_service_t firstInterface;
615 if (dev->dev_descriptor.bNumConfigurations < 1) {
616 usbi_err (ctx, "device has no configurations");
617 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
620 /* checking the configuration of a root hub simulation takes ~1 s in 10.11. the device is
622 if (0x05ac == dev->dev_descriptor.idVendor && 0x8005 == dev->dev_descriptor.idProduct) {
623 usbi_dbg ("ignoring configuration on root hub simulation");
624 dev->active_config = 0;
628 /* find the first configuration */
629 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
630 dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
632 /* check if the device is already configured. there is probably a better way than iterating over the
633 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
634 might lock up on the device request) */
636 /* Setup the Interface Request */
637 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
638 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
639 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
640 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
642 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
644 return darwin_to_libusb (kresult);
647 firstInterface = IOIteratorNext(interface_iterator);
649 /* done with the interface iterator */
650 IOObjectRelease(interface_iterator);
652 if (firstInterface) {
653 IOObjectRelease (firstInterface);
655 /* device is configured */
656 if (dev->dev_descriptor.bNumConfigurations == 1)
657 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
658 dev->active_config = dev->first_config;
660 /* devices with more than one configuration should work with GetConfiguration */
661 (*darwin_device)->GetConfiguration (darwin_device, &dev->active_config);
664 dev->active_config = 0;
666 usbi_dbg ("active config: %u, first config: %u", dev->active_config, dev->first_config);
671 static int darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
672 IOUSBDevRequestTO req;
674 memset (buffer, 0, buffer_size);
676 /* Set up request for descriptor/ */
677 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
678 req.bRequest = kUSBRqGetDescriptor;
679 req.wValue = desc << 8;
680 req.wIndex = desc_index;
681 req.wLength = buffer_size;
683 req.noDataTimeout = 20;
684 req.completionTimeout = 100;
686 return (*device)->DeviceRequestTO (device, &req);
689 static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct darwin_cached_device *dev) {
690 usb_device_t **device = dev->device;
691 int retries = 1, delay = 30000;
692 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
696 UInt16 idProduct, idVendor;
698 dev->can_enumerate = 0;
700 (*device)->GetDeviceClass (device, &bDeviceClass);
701 (*device)->GetDeviceProduct (device, &idProduct);
702 (*device)->GetDeviceVendor (device, &idVendor);
704 /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
705 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
706 * to follow the spec as closely as possible, try opening the device */
707 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
710 /**** retrieve device descriptor ****/
711 ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &dev->dev_descriptor, sizeof(dev->dev_descriptor));
713 if (kIOReturnOverrun == ret && kUSBDeviceDesc == dev->dev_descriptor.bDescriptorType)
714 /* received an overrun error but we still received a device descriptor */
715 ret = kIOReturnSuccess;
717 if (kIOUSBVendorIDAppleComputer == idVendor) {
718 /* NTH: don't bother retrying or unsuspending Apple devices */
722 if (kIOReturnSuccess == ret && (0 == dev->dev_descriptor.bNumConfigurations ||
723 0 == dev->dev_descriptor.bcdUSB)) {
724 /* work around for incorrectly configured devices */
725 if (try_reconfigure && is_open) {
726 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
728 /* set the first configuration */
729 (*device)->SetConfiguration(device, 1);
731 /* don't try to reconfigure again */
735 ret = kIOUSBPipeStalled;
738 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
739 /* device may be suspended. unsuspend it and try again */
740 #if DeviceVersion >= 320
743 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
744 (void)(*device)->GetUSBDeviceInformation (device, &info);
746 /* note that the device was suspended */
747 if (info & (1 << kUSBInformationDeviceIsSuspendedBit) || 0 == info)
752 /* try to unsuspend the device */
753 ret2 = (*device)->USBDeviceSuspend (device, 0);
754 if (kIOReturnSuccess != ret2) {
755 /* prevent log spew from poorly behaving devices. this indicates the
756 os actually had trouble communicating with the device */
757 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
765 if (kIOReturnSuccess != ret) {
766 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
767 /* sleep for a little while before trying again */
768 nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000UL}, NULL);
770 } while (kIOReturnSuccess != ret && retries--);
773 /* resuspend the device */
774 (void)(*device)->USBDeviceSuspend (device, 1);
777 (void) (*device)->USBDeviceClose (device);
779 if (ret != kIOReturnSuccess) {
780 /* a debug message was already printed out for this error */
781 if (LIBUSB_CLASS_HUB == bDeviceClass)
782 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
783 idVendor, idProduct, darwin_error_str (ret), ret);
785 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
786 idVendor, idProduct, darwin_error_str (ret), ret);
787 return darwin_to_libusb (ret);
790 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
791 if (libusb_le16_to_cpu (dev->dev_descriptor.idProduct) != idProduct) {
792 /* not a valid device */
793 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
794 idProduct, libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
795 return LIBUSB_ERROR_NO_DEVICE;
798 usbi_dbg ("cached device descriptor:");
799 usbi_dbg (" bDescriptorType: 0x%02x", dev->dev_descriptor.bDescriptorType);
800 usbi_dbg (" bcdUSB: 0x%04x", dev->dev_descriptor.bcdUSB);
801 usbi_dbg (" bDeviceClass: 0x%02x", dev->dev_descriptor.bDeviceClass);
802 usbi_dbg (" bDeviceSubClass: 0x%02x", dev->dev_descriptor.bDeviceSubClass);
803 usbi_dbg (" bDeviceProtocol: 0x%02x", dev->dev_descriptor.bDeviceProtocol);
804 usbi_dbg (" bMaxPacketSize0: 0x%02x", dev->dev_descriptor.bMaxPacketSize0);
805 usbi_dbg (" idVendor: 0x%04x", dev->dev_descriptor.idVendor);
806 usbi_dbg (" idProduct: 0x%04x", dev->dev_descriptor.idProduct);
807 usbi_dbg (" bcdDevice: 0x%04x", dev->dev_descriptor.bcdDevice);
808 usbi_dbg (" iManufacturer: 0x%02x", dev->dev_descriptor.iManufacturer);
809 usbi_dbg (" iProduct: 0x%02x", dev->dev_descriptor.iProduct);
810 usbi_dbg (" iSerialNumber: 0x%02x", dev->dev_descriptor.iSerialNumber);
811 usbi_dbg (" bNumConfigurations: 0x%02x", dev->dev_descriptor.bNumConfigurations);
813 dev->can_enumerate = 1;
815 return LIBUSB_SUCCESS;
818 static int get_device_port (io_service_t service, UInt8 *port) {
819 kern_return_t result;
823 if (get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, port)) {
827 result = IORegistryEntryGetParentEntry (service, kIOServicePlane, &parent);
828 if (kIOReturnSuccess == result) {
829 ret = get_ioregistry_value_data (parent, CFSTR("port"), 1, port);
830 IOObjectRelease (parent);
836 static int darwin_get_cached_device(struct libusb_context *ctx, io_service_t service,
837 struct darwin_cached_device **cached_out) {
838 struct darwin_cached_device *new_device;
839 UInt64 sessionID = 0, parent_sessionID = 0;
840 int ret = LIBUSB_SUCCESS;
841 usb_device_t **device;
843 kern_return_t result;
846 /* get some info from the io registry */
847 (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
848 if (!get_device_port (service, &port)) {
849 usbi_dbg("could not get connected port number");
852 usbi_dbg("finding cached device for sessionID 0x%" PRIx64, sessionID);
854 result = IORegistryEntryGetParentEntry (service, kIOUSBPlane, &parent);
856 if (kIOReturnSuccess == result) {
857 (void) get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, &parent_sessionID);
858 IOObjectRelease(parent);
861 usbi_mutex_lock(&darwin_cached_devices_lock);
865 list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) {
866 usbi_dbg("matching sessionID 0x%" PRIx64 " against cached device with sessionID 0x%" PRIx64, sessionID, new_device->session);
867 if (new_device->session == sessionID) {
868 usbi_dbg("using cached device for device");
869 *cached_out = new_device;
877 usbi_dbg("caching new device with sessionID 0x%" PRIx64, sessionID);
879 device = darwin_device_from_service (service);
881 ret = LIBUSB_ERROR_NO_DEVICE;
885 new_device = calloc (1, sizeof (*new_device));
887 ret = LIBUSB_ERROR_NO_MEM;
891 /* add this device to the cached device list */
892 list_add(&new_device->list, &darwin_cached_devices);
894 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
896 /* keep a reference to this device */
897 darwin_ref_cached_device(new_device);
899 new_device->device = device;
900 new_device->session = sessionID;
901 (*device)->GetLocationID (device, &new_device->location);
902 new_device->port = port;
903 new_device->parent_session = parent_sessionID;
905 /* cache the device descriptor */
906 ret = darwin_cache_device_descriptor(ctx, new_device);
910 if (new_device->can_enumerate) {
911 snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address,
912 new_device->dev_descriptor.idVendor, new_device->dev_descriptor.idProduct,
913 new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass);
917 usbi_mutex_unlock(&darwin_cached_devices_lock);
919 /* keep track of devices regardless of if we successfully enumerate them to
920 prevent them from being enumerated multiple times */
922 *cached_out = new_device;
927 static int process_new_device (struct libusb_context *ctx, io_service_t service) {
928 struct darwin_device_priv *priv;
929 struct libusb_device *dev = NULL;
930 struct darwin_cached_device *cached_device;
935 ret = darwin_get_cached_device (ctx, service, &cached_device);
937 if (ret < 0 || !cached_device->can_enumerate) {
941 /* check current active configuration (and cache the first configuration value--
942 which may be used by claim_interface) */
943 ret = darwin_check_configuration (ctx, cached_device);
947 usbi_dbg ("allocating new device in context %p for with session 0x%" PRIx64,
948 ctx, cached_device->session);
950 dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
952 return LIBUSB_ERROR_NO_MEM;
955 priv = (struct darwin_device_priv *)dev->os_priv;
957 priv->dev = cached_device;
958 darwin_ref_cached_device (priv->dev);
960 if (cached_device->parent_session > 0) {
961 dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session);
963 dev->parent_dev = NULL;
965 dev->port_number = cached_device->port;
966 dev->bus_number = cached_device->location >> 24;
967 dev->device_address = cached_device->address;
969 (*(priv->dev->device))->GetDeviceSpeed (priv->dev->device, &devSpeed);
972 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
973 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
974 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
975 #if DeviceVersion >= 500
976 case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
979 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
982 ret = usbi_sanitize_device (dev);
986 usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
987 dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
991 usbi_connect_device (dev);
993 libusb_unref_device (dev);
999 static int darwin_scan_devices(struct libusb_context *ctx) {
1000 io_iterator_t deviceIterator;
1001 io_service_t service;
1002 kern_return_t kresult;
1004 kresult = usb_setup_device_iterator (&deviceIterator, 0);
1005 if (kresult != kIOReturnSuccess)
1006 return darwin_to_libusb (kresult);
1008 while ((service = IOIteratorNext (deviceIterator))) {
1009 (void) process_new_device (ctx, service);
1011 IOObjectRelease(service);
1014 IOObjectRelease(deviceIterator);
1019 static int darwin_open (struct libusb_device_handle *dev_handle) {
1020 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1021 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1024 if (0 == dpriv->open_count) {
1025 /* try to open the device */
1026 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
1027 if (kresult != kIOReturnSuccess) {
1028 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
1030 if (kIOReturnExclusiveAccess != kresult) {
1031 return darwin_to_libusb (kresult);
1034 /* it is possible to perform some actions on a device that is not open so do not return an error */
1040 /* create async event source */
1041 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
1042 if (kresult != kIOReturnSuccess) {
1043 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
1045 if (priv->is_open) {
1046 (*(dpriv->device))->USBDeviceClose (dpriv->device);
1051 return darwin_to_libusb (kresult);
1054 CFRetain (libusb_darwin_acfl);
1056 /* add the cfSource to the aync run loop */
1057 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
1060 /* device opened successfully */
1061 dpriv->open_count++;
1063 usbi_dbg ("device open for access");
1068 static void darwin_close (struct libusb_device_handle *dev_handle) {
1069 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1070 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1074 if (dpriv->open_count == 0) {
1075 /* something is probably very wrong if this is the case */
1076 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!");
1080 dpriv->open_count--;
1082 /* make sure all interfaces are released */
1083 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1084 if (dev_handle->claimed_interfaces & (1 << i))
1085 libusb_release_interface (dev_handle, i);
1087 if (0 == dpriv->open_count) {
1088 /* delete the device's async event source */
1089 if (priv->cfSource) {
1090 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
1091 CFRelease (priv->cfSource);
1092 priv->cfSource = NULL;
1093 CFRelease (libusb_darwin_acfl);
1096 if (priv->is_open) {
1097 /* close the device */
1098 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
1100 /* Log the fact that we had a problem closing the file, however failing a
1101 * close isn't really an error, so return success anyway */
1102 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
1108 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
1109 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1111 *config = (int) dpriv->active_config;
1116 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
1117 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1121 /* Setting configuration will invalidate the interface, so we need
1122 to reclaim it. First, dispose of existing interfaces, if any. */
1123 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1124 if (dev_handle->claimed_interfaces & (1 << i))
1125 darwin_release_interface (dev_handle, i);
1127 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
1128 if (kresult != kIOReturnSuccess)
1129 return darwin_to_libusb (kresult);
1131 /* Reclaim any interfaces. */
1132 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1133 if (dev_handle->claimed_interfaces & (1 << i))
1134 darwin_claim_interface (dev_handle, i);
1136 dpriv->active_config = config;
1141 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
1142 IOUSBFindInterfaceRequest request;
1143 kern_return_t kresult;
1144 io_iterator_t interface_iterator;
1145 UInt8 bInterfaceNumber;
1148 *usbInterfacep = IO_OBJECT_NULL;
1150 /* Setup the Interface Request */
1151 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1152 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1153 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1154 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1156 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1160 while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1161 /* find the interface number */
1162 ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
1165 if (ret && bInterfaceNumber == ifc) {
1169 (void) IOObjectRelease (*usbInterfacep);
1172 /* done with the interface iterator */
1173 IOObjectRelease(interface_iterator);
1178 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
1179 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1181 /* current interface */
1182 struct darwin_interface *cInterface = &priv->interfaces[iface];
1184 kern_return_t kresult;
1186 u_int8_t numep, direction, number;
1187 u_int8_t dont_care1, dont_care3;
1188 u_int16_t dont_care2;
1191 usbi_dbg ("building table of endpoints.");
1193 /* retrieve the total number of endpoints on this interface */
1194 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1196 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1197 return darwin_to_libusb (kresult);
1200 /* iterate through pipe references */
1201 for (i = 1 ; i <= numep ; i++) {
1202 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1203 &dont_care2, &dont_care3);
1205 if (kresult != kIOReturnSuccess) {
1206 usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
1208 return darwin_to_libusb (kresult);
1211 usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
1213 cInterface->endpoint_addrs[i - 1] = (((kUSBIn == direction) << kUSBRqDirnShift) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1216 cInterface->num_endpoints = numep;
1221 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1222 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1223 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1224 io_service_t usbInterface = IO_OBJECT_NULL;
1226 IOCFPlugInInterface **plugInInterface = NULL;
1229 /* current interface */
1230 struct darwin_interface *cInterface = &priv->interfaces[iface];
1232 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1233 if (kresult != kIOReturnSuccess)
1234 return darwin_to_libusb (kresult);
1236 /* make sure we have an interface */
1237 if (!usbInterface && dpriv->first_config != 0) {
1238 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1240 /* set the configuration */
1241 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1242 if (kresult != LIBUSB_SUCCESS) {
1243 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1247 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1249 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1250 return darwin_to_libusb (kresult);
1254 if (!usbInterface) {
1255 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1256 return LIBUSB_ERROR_NOT_FOUND;
1259 /* get an interface to the device's interface */
1260 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1261 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1263 /* ignore release error */
1264 (void)IOObjectRelease (usbInterface);
1267 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1268 return darwin_to_libusb (kresult);
1271 if (!plugInInterface) {
1272 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1273 return LIBUSB_ERROR_NOT_FOUND;
1276 /* Do the actual claim */
1277 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1278 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1279 (LPVOID)&cInterface->interface);
1280 /* We no longer need the intermediate plug-in */
1281 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1282 (*plugInInterface)->Release (plugInInterface);
1283 if (kresult || !cInterface->interface) {
1284 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1285 return darwin_to_libusb (kresult);
1288 /* claim the interface */
1289 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1291 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1292 return darwin_to_libusb (kresult);
1295 /* update list of endpoints */
1296 kresult = get_endpoints (dev_handle, iface);
1298 /* this should not happen */
1299 darwin_release_interface (dev_handle, iface);
1300 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1304 cInterface->cfSource = NULL;
1306 /* create async event source */
1307 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1308 if (kresult != kIOReturnSuccess) {
1309 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1311 /* can't continue without an async event source */
1312 (void)darwin_release_interface (dev_handle, iface);
1314 return darwin_to_libusb (kresult);
1317 /* add the cfSource to the async thread's run loop */
1318 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1320 usbi_dbg ("interface opened");
1325 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1326 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1329 /* current interface */
1330 struct darwin_interface *cInterface = &priv->interfaces[iface];
1332 /* Check to see if an interface is open */
1333 if (!cInterface->interface)
1334 return LIBUSB_SUCCESS;
1336 /* clean up endpoint data */
1337 cInterface->num_endpoints = 0;
1339 /* delete the interface's async event source */
1340 if (cInterface->cfSource) {
1341 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1342 CFRelease (cInterface->cfSource);
1345 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1347 usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1349 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1350 if (kresult != kIOReturnSuccess)
1351 usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1353 cInterface->interface = (usb_interface_t **) IO_OBJECT_NULL;
1355 return darwin_to_libusb (kresult);
1358 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1359 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1362 /* current interface */
1363 struct darwin_interface *cInterface = &priv->interfaces[iface];
1365 if (!cInterface->interface)
1366 return LIBUSB_ERROR_NO_DEVICE;
1368 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1369 if (kresult != kIOReturnSuccess)
1370 darwin_reset_device (dev_handle);
1372 /* update list of endpoints */
1373 kresult = get_endpoints (dev_handle, iface);
1375 /* this should not happen */
1376 darwin_release_interface (dev_handle, iface);
1377 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1381 return darwin_to_libusb (kresult);
1384 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1385 /* current interface */
1386 struct darwin_interface *cInterface;
1390 /* determine the interface/endpoint to use */
1391 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, NULL, &cInterface) != 0) {
1392 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1394 return LIBUSB_ERROR_NOT_FOUND;
1397 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1398 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1400 usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1402 return darwin_to_libusb (kresult);
1405 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1406 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1407 IOUSBDeviceDescriptor descriptor;
1408 IOUSBConfigurationDescriptorPtr cached_configuration;
1409 IOUSBConfigurationDescriptor configuration;
1410 bool reenumerate = false;
1414 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1416 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1417 return darwin_to_libusb (kresult);
1421 usbi_dbg ("darwin/reset_device: checking if device descriptor changed");
1423 /* ignore return code. if we can't get a descriptor it might be worthwhile re-enumerating anway */
1424 (void) darwin_request_descriptor (dpriv->device, kUSBDeviceDesc, 0, &descriptor, sizeof (descriptor));
1426 /* check if the device descriptor has changed */
1427 if (0 != memcmp (&dpriv->dev_descriptor, &descriptor, sizeof (descriptor))) {
1432 /* check if any configuration descriptor has changed */
1433 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1434 usbi_dbg ("darwin/reset_device: checking if configuration descriptor %d changed", i);
1436 (void) darwin_request_descriptor (dpriv->device, kUSBConfDesc, i, &configuration, sizeof (configuration));
1437 (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1439 if (!cached_configuration || 0 != memcmp (cached_configuration, &configuration, sizeof (configuration))) {
1447 usbi_dbg ("darwin/reset_device: device requires reenumeration");
1448 (void) (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
1449 return LIBUSB_ERROR_NOT_FOUND;
1452 usbi_dbg ("darwin/reset_device: device reset complete");
1454 return LIBUSB_SUCCESS;
1457 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1458 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1459 io_service_t usbInterface;
1463 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1465 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1467 return darwin_to_libusb (kresult);
1470 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1471 IOObjectRelease (usbInterface);
1483 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1484 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1487 return LIBUSB_ERROR_NOT_SUPPORTED;
1490 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1493 return LIBUSB_ERROR_NOT_SUPPORTED;
1496 static void darwin_destroy_device(struct libusb_device *dev) {
1497 struct darwin_device_priv *dpriv = (struct darwin_device_priv *) dev->os_priv;
1500 /* need to hold the lock in case this is the last reference to the device */
1501 usbi_mutex_lock(&darwin_cached_devices_lock);
1502 darwin_deref_cached_device (dpriv->dev);
1504 usbi_mutex_unlock(&darwin_cached_devices_lock);
1508 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1509 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1512 uint8_t transferType;
1513 /* None of the values below are used in libusbx for bulk transfers */
1514 uint8_t direction, number, interval, pipeRef;
1515 uint16_t maxPacketSize;
1517 struct darwin_interface *cInterface;
1519 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1520 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1522 return LIBUSB_ERROR_NOT_FOUND;
1525 ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1526 &transferType, &maxPacketSize, &interval);
1529 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1530 darwin_error_str(ret), ret);
1531 return darwin_to_libusb (ret);
1534 if (0 != (transfer->length % maxPacketSize)) {
1535 /* do not need a zero packet */
1536 transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1539 /* submit the request */
1540 /* timeouts are unavailable on interrupt endpoints */
1541 if (transferType == kUSBInterrupt) {
1542 if (IS_XFERIN(transfer))
1543 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1544 transfer->length, darwin_async_io_callback, itransfer);
1546 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1547 transfer->length, darwin_async_io_callback, itransfer);
1549 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1551 if (IS_XFERIN(transfer))
1552 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1553 transfer->length, transfer->timeout, transfer->timeout,
1554 darwin_async_io_callback, (void *)itransfer);
1556 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1557 transfer->length, transfer->timeout, transfer->timeout,
1558 darwin_async_io_callback, (void *)itransfer);
1562 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1563 darwin_error_str(ret), ret);
1565 return darwin_to_libusb (ret);
1568 #if InterfaceVersion >= 550
1569 static int submit_stream_transfer(struct usbi_transfer *itransfer) {
1570 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1571 struct darwin_interface *cInterface;
1575 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1576 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1578 return LIBUSB_ERROR_NOT_FOUND;
1581 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1583 if (IS_XFERIN(transfer))
1584 ret = (*(cInterface->interface))->ReadStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1585 transfer->buffer, transfer->length, transfer->timeout,
1586 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1588 ret = (*(cInterface->interface))->WriteStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1589 transfer->buffer, transfer->length, transfer->timeout,
1590 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1593 usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1594 darwin_error_str(ret), ret);
1596 return darwin_to_libusb (ret);
1600 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1601 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1602 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1605 uint8_t direction, number, interval, pipeRef, transferType;
1606 uint16_t maxPacketSize;
1608 AbsoluteTime atTime;
1611 struct darwin_interface *cInterface;
1613 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1614 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1615 free(tpriv->isoc_framelist);
1616 tpriv->isoc_framelist = NULL;
1619 if (!tpriv->isoc_framelist) {
1620 tpriv->num_iso_packets = transfer->num_iso_packets;
1621 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1622 if (!tpriv->isoc_framelist)
1623 return LIBUSB_ERROR_NO_MEM;
1626 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1627 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1628 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1630 /* determine the interface/endpoint to use */
1631 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1632 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1634 return LIBUSB_ERROR_NOT_FOUND;
1637 /* determine the properties of this endpoint and the speed of the device */
1638 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1639 &transferType, &maxPacketSize, &interval);
1641 /* Last but not least we need the bus frame number */
1642 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1644 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1645 free(tpriv->isoc_framelist);
1646 tpriv->isoc_framelist = NULL;
1648 return darwin_to_libusb (kresult);
1651 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1652 &transferType, &maxPacketSize, &interval);
1654 /* schedule for a frame a little in the future */
1657 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1658 frame = cInterface->frames[transfer->endpoint];
1660 /* submit the request */
1661 if (IS_XFERIN(transfer))
1662 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1663 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1666 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1667 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1670 if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
1672 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1));
1674 /* High/super speed */
1675 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1)) / 8;
1677 if (kresult != kIOReturnSuccess) {
1678 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1679 darwin_error_str(kresult));
1680 free (tpriv->isoc_framelist);
1681 tpriv->isoc_framelist = NULL;
1684 return darwin_to_libusb (kresult);
1687 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1688 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1689 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1690 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1691 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1695 bzero(&tpriv->req, sizeof(tpriv->req));
1697 /* IOUSBDeviceInterface expects the request in cpu endianness */
1698 tpriv->req.bmRequestType = setup->bmRequestType;
1699 tpriv->req.bRequest = setup->bRequest;
1700 /* these values should be in bus order from libusb_fill_control_setup */
1701 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1702 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1703 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1704 /* data is stored after the libusb control block */
1705 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1706 tpriv->req.completionTimeout = transfer->timeout;
1707 tpriv->req.noDataTimeout = transfer->timeout;
1709 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1711 /* all transfers in libusb-1.0 are async */
1713 if (transfer->endpoint) {
1714 struct darwin_interface *cInterface;
1717 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1718 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1720 return LIBUSB_ERROR_NOT_FOUND;
1723 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1725 /* control request on endpoint 0 */
1726 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1728 if (kresult != kIOReturnSuccess)
1729 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1731 return darwin_to_libusb (kresult);
1734 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1735 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1737 switch (transfer->type) {
1738 case LIBUSB_TRANSFER_TYPE_CONTROL:
1739 return submit_control_transfer(itransfer);
1740 case LIBUSB_TRANSFER_TYPE_BULK:
1741 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1742 return submit_bulk_transfer(itransfer);
1743 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1744 return submit_iso_transfer(itransfer);
1745 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1746 #if InterfaceVersion >= 550
1747 return submit_stream_transfer(itransfer);
1749 usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers");
1750 return LIBUSB_ERROR_NOT_SUPPORTED;
1753 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1754 return LIBUSB_ERROR_INVALID_PARAM;
1758 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1759 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1760 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1763 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
1766 return LIBUSB_ERROR_NO_DEVICE;
1768 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1770 return darwin_to_libusb (kresult);
1773 static int darwin_abort_transfers (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);
1776 struct darwin_interface *cInterface;
1777 uint8_t pipeRef, iface;
1780 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) {
1781 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1783 return LIBUSB_ERROR_NOT_FOUND;
1787 return LIBUSB_ERROR_NO_DEVICE;
1789 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
1791 /* abort transactions */
1792 #if InterfaceVersion >= 550
1793 if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type)
1794 (*(cInterface->interface))->AbortStreamsPipe (cInterface->interface, pipeRef, itransfer->stream_id);
1797 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1799 usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
1801 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1802 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1804 return darwin_to_libusb (kresult);
1807 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1808 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1810 switch (transfer->type) {
1811 case LIBUSB_TRANSFER_TYPE_CONTROL:
1812 return cancel_control_transfer(itransfer);
1813 case LIBUSB_TRANSFER_TYPE_BULK:
1814 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1815 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1816 return darwin_abort_transfers (itransfer);
1818 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1819 return LIBUSB_ERROR_INVALID_PARAM;
1823 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1824 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1825 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1827 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1828 free (tpriv->isoc_framelist);
1829 tpriv->isoc_framelist = NULL;
1833 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1834 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1835 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1836 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1838 usbi_dbg ("an async io operation has completed");
1840 /* if requested write a zero packet */
1841 if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
1842 struct darwin_interface *cInterface;
1845 (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface);
1847 (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
1850 tpriv->result = result;
1851 tpriv->size = (UInt32) (uintptr_t) arg0;
1853 /* signal the core that this transfer is complete */
1854 usbi_signal_transfer_completion(itransfer);
1857 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1858 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT)
1859 result = kIOUSBTransactionTimeout;
1862 case kIOReturnUnderrun:
1863 case kIOReturnSuccess:
1864 return LIBUSB_TRANSFER_COMPLETED;
1865 case kIOReturnAborted:
1866 return LIBUSB_TRANSFER_CANCELLED;
1867 case kIOUSBPipeStalled:
1868 usbi_dbg ("transfer error: pipe is stalled");
1869 return LIBUSB_TRANSFER_STALL;
1870 case kIOReturnOverrun:
1871 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1872 return LIBUSB_TRANSFER_OVERFLOW;
1873 case kIOUSBTransactionTimeout:
1874 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1875 itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
1876 return LIBUSB_TRANSFER_TIMED_OUT;
1878 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1879 return LIBUSB_TRANSFER_ERROR;
1883 static int darwin_handle_transfer_completion (struct usbi_transfer *itransfer) {
1884 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1885 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1886 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1887 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1888 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1889 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1892 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1893 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1894 return LIBUSB_ERROR_INVALID_PARAM;
1897 usbi_dbg ("handling %s completion with kernel status %d",
1898 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", tpriv->result);
1900 if (kIOReturnSuccess == tpriv->result || kIOReturnUnderrun == tpriv->result) {
1901 if (isIsoc && tpriv->isoc_framelist) {
1902 /* copy isochronous results back */
1904 for (i = 0; i < transfer->num_iso_packets ; i++) {
1905 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1906 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1907 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1910 itransfer->transferred += tpriv->size;
1913 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1914 return usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, tpriv->result));
1917 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1918 mach_timespec_t sys_time;
1919 clock_serv_t clock_ref;
1922 case USBI_CLOCK_REALTIME:
1923 /* CLOCK_REALTIME represents time since the epoch */
1924 clock_ref = clock_realtime;
1926 case USBI_CLOCK_MONOTONIC:
1927 /* use system boot time as reference for the monotonic clock */
1928 clock_ref = clock_monotonic;
1931 return LIBUSB_ERROR_INVALID_PARAM;
1934 clock_get_time (clock_ref, &sys_time);
1936 tp->tv_sec = sys_time.tv_sec;
1937 tp->tv_nsec = sys_time.tv_nsec;
1942 #if InterfaceVersion >= 550
1943 static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints,
1944 int num_endpoints) {
1945 struct darwin_interface *cInterface;
1946 UInt32 supportsStreams;
1950 /* find the mimimum number of supported streams on the endpoint list */
1951 for (i = 0 ; i < num_endpoints ; ++i) {
1952 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) {
1956 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
1957 if (num_streams > supportsStreams)
1958 num_streams = supportsStreams;
1961 /* it is an error if any endpoint in endpoints does not support streams */
1962 if (0 == num_streams)
1963 return LIBUSB_ERROR_INVALID_PARAM;
1965 /* create the streams */
1966 for (i = 0 ; i < num_endpoints ; ++i) {
1967 (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
1969 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, num_streams);
1970 if (kIOReturnSuccess != rc)
1971 return darwin_to_libusb(rc);
1977 static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) {
1978 struct darwin_interface *cInterface;
1979 UInt32 supportsStreams;
1983 for (int i = 0 ; i < num_endpoints ; ++i) {
1984 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface)))
1987 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
1988 if (0 == supportsStreams)
1989 return LIBUSB_ERROR_INVALID_PARAM;
1991 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, 0);
1992 if (kIOReturnSuccess != rc)
1993 return darwin_to_libusb(rc);
1996 return LIBUSB_SUCCESS;
2000 const struct usbi_os_backend darwin_backend = {
2003 .init = darwin_init,
2004 .exit = darwin_exit,
2005 .get_device_list = NULL, /* not needed */
2006 .get_device_descriptor = darwin_get_device_descriptor,
2007 .get_active_config_descriptor = darwin_get_active_config_descriptor,
2008 .get_config_descriptor = darwin_get_config_descriptor,
2009 .hotplug_poll = darwin_hotplug_poll,
2011 .open = darwin_open,
2012 .close = darwin_close,
2013 .get_configuration = darwin_get_configuration,
2014 .set_configuration = darwin_set_configuration,
2015 .claim_interface = darwin_claim_interface,
2016 .release_interface = darwin_release_interface,
2018 .set_interface_altsetting = darwin_set_interface_altsetting,
2019 .clear_halt = darwin_clear_halt,
2020 .reset_device = darwin_reset_device,
2022 #if InterfaceVersion >= 550
2023 .alloc_streams = darwin_alloc_streams,
2024 .free_streams = darwin_free_streams,
2027 .kernel_driver_active = darwin_kernel_driver_active,
2028 .detach_kernel_driver = darwin_detach_kernel_driver,
2029 .attach_kernel_driver = darwin_attach_kernel_driver,
2031 .destroy_device = darwin_destroy_device,
2033 .submit_transfer = darwin_submit_transfer,
2034 .cancel_transfer = darwin_cancel_transfer,
2035 .clear_transfer_priv = darwin_clear_transfer_priv,
2037 .handle_transfer_completion = darwin_handle_transfer_completion,
2039 .clock_gettime = darwin_clock_gettime,
2041 .device_priv_size = sizeof(struct darwin_device_priv),
2042 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
2043 .transfer_priv_size = sizeof(struct darwin_transfer_priv),