1 /* -*- Mode: C; indent-tabs-mode:nil -*- */
3 * darwin backend for libusb 1.0
4 * Copyright © 2008-2014 Nathan Hjelm <hjelmn@users.sourceforge.net>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
28 #include <sys/types.h>
31 #include <libkern/OSAtomic.h>
32 #include <sys/sysctl.h>
34 #include <mach/clock.h>
35 #include <mach/clock_types.h>
36 #include <mach/mach_host.h>
37 #include <mach/mach_port.h>
39 #include <AvailabilityMacros.h>
40 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
41 #include <objc/objc-auto.h>
44 #include "darwin_usb.h"
46 /* async event thread */
47 static pthread_mutex_t libusb_darwin_at_mutex = PTHREAD_MUTEX_INITIALIZER;
48 static pthread_cond_t libusb_darwin_at_cond = PTHREAD_COND_INITIALIZER;
50 static pthread_once_t darwin_init_once = PTHREAD_ONCE_INIT;
52 static clock_serv_t clock_realtime;
53 static clock_serv_t clock_monotonic;
55 static CFRunLoopRef libusb_darwin_acfl = NULL; /* event cf loop */
56 static volatile int32_t initCount = 0;
58 static usbi_mutex_t darwin_cached_devices_lock = PTHREAD_MUTEX_INITIALIZER;
59 static struct list_head darwin_cached_devices = {&darwin_cached_devices, &darwin_cached_devices};
60 static char *darwin_device_class = kIOUSBDeviceClassName;
62 #define DARWIN_CACHED_DEVICE(a) ((struct darwin_cached_device *) (((struct darwin_device_priv *)((a)->os_priv))->dev))
64 /* async event thread */
65 static pthread_t libusb_darwin_at;
67 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
68 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
69 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
70 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
71 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
73 static int darwin_scan_devices(struct libusb_context *ctx);
74 static int process_new_device (struct libusb_context *ctx, io_service_t service);
76 #if defined(ENABLE_LOGGING)
77 static const char *darwin_error_str (int result) {
78 static char string_buffer[50];
80 case kIOReturnSuccess:
82 case kIOReturnNotOpen:
83 return "device not opened for exclusive access";
84 case kIOReturnNoDevice:
85 return "no connection to an IOService";
86 case kIOUSBNoAsyncPortErr:
87 return "no async port has been opened for interface";
88 case kIOReturnExclusiveAccess:
89 return "another process has device opened for exclusive access";
90 case kIOUSBPipeStalled:
91 return "pipe is stalled";
93 return "could not establish a connection to the Darwin kernel";
94 case kIOUSBTransactionTimeout:
95 return "transaction timed out";
96 case kIOReturnBadArgument:
97 return "invalid argument";
98 case kIOReturnAborted:
99 return "transaction aborted";
100 case kIOReturnNotResponding:
101 return "device not responding";
102 case kIOReturnOverrun:
103 return "data overrun";
104 case kIOReturnCannotWire:
105 return "physical memory can not be wired down";
106 case kIOReturnNoResources:
107 return "out of resources";
108 case kIOUSBHighSpeedSplitError:
109 return "high speed split error";
111 snprintf(string_buffer, sizeof(string_buffer), "unknown error (0x%x)", result);
112 return string_buffer;
117 static int darwin_to_libusb (int result) {
119 case kIOReturnUnderrun:
120 case kIOReturnSuccess:
121 return LIBUSB_SUCCESS;
122 case kIOReturnNotOpen:
123 case kIOReturnNoDevice:
124 return LIBUSB_ERROR_NO_DEVICE;
125 case kIOReturnExclusiveAccess:
126 return LIBUSB_ERROR_ACCESS;
127 case kIOUSBPipeStalled:
128 return LIBUSB_ERROR_PIPE;
129 case kIOReturnBadArgument:
130 return LIBUSB_ERROR_INVALID_PARAM;
131 case kIOUSBTransactionTimeout:
132 return LIBUSB_ERROR_TIMEOUT;
133 case kIOReturnNotResponding:
134 case kIOReturnAborted:
136 case kIOUSBNoAsyncPortErr:
138 return LIBUSB_ERROR_OTHER;
142 /* this function must be called with the darwin_cached_devices_lock held */
143 static void darwin_deref_cached_device(struct darwin_cached_device *cached_dev) {
144 cached_dev->refcount--;
145 /* free the device and remove it from the cache */
146 if (0 == cached_dev->refcount) {
147 list_del(&cached_dev->list);
149 (*(cached_dev->device))->Release(cached_dev->device);
154 static void darwin_ref_cached_device(struct darwin_cached_device *cached_dev) {
155 cached_dev->refcount++;
158 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) {
159 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
161 /* current interface */
162 struct darwin_interface *cInterface;
166 usbi_dbg ("converting ep address 0x%02x to pipeRef and interface", ep);
168 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
169 cInterface = &priv->interfaces[iface];
171 if (dev_handle->claimed_interfaces & (1 << iface)) {
172 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
173 if (cInterface->endpoint_addrs[i] == ep) {
180 *interface_out = cInterface;
182 usbi_dbg ("pipe %d on interface %d matches", *pipep, iface);
189 /* No pipe found with the correct endpoint address */
190 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
192 return LIBUSB_ERROR_NOT_FOUND;
195 static int usb_setup_device_iterator (io_iterator_t *deviceIterator, UInt32 location) {
196 CFMutableDictionaryRef matchingDict = IOServiceMatching(darwin_device_class);
199 return kIOReturnError;
202 CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
203 &kCFTypeDictionaryKeyCallBacks,
204 &kCFTypeDictionaryValueCallBacks);
206 if (propertyMatchDict) {
207 /* there are no unsigned CFNumber types so treat the value as signed. the os seems to do this
208 internally (CFNumberType of locationID is 3) */
209 CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberSInt32Type, &location);
211 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
212 /* release our reference to the CFNumber (CFDictionarySetValue retains it) */
213 CFRelease (locationCF);
215 CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
216 /* release out reference to the CFMutableDictionaryRef (CFDictionarySetValue retains it) */
217 CFRelease (propertyMatchDict);
219 /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
222 return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator);
225 /* Returns 1 on success, 0 on failure. */
226 static int get_ioregistry_value_number (io_service_t service, CFStringRef property, CFNumberType type, void *p) {
227 CFTypeRef cfNumber = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
231 if (CFGetTypeID(cfNumber) == CFNumberGetTypeID()) {
232 ret = CFNumberGetValue(cfNumber, type, p);
235 CFRelease (cfNumber);
241 static int get_ioregistry_value_data (io_service_t service, CFStringRef property, size_t size, void *p) {
242 CFTypeRef cfData = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
246 if (CFGetTypeID (cfData) == CFDataGetTypeID ()) {
247 CFIndex length = CFDataGetLength (cfData);
252 CFDataGetBytes (cfData, CFRangeMake(0, size), p);
262 static usb_device_t **darwin_device_from_service (io_service_t service)
264 io_cf_plugin_ref_t *plugInInterface = NULL;
265 usb_device_t **device;
266 kern_return_t result;
269 result = IOCreatePlugInInterfaceForService(service, kIOUSBDeviceUserClientTypeID,
270 kIOCFPlugInInterfaceID, &plugInInterface,
273 if (kIOReturnSuccess != result || !plugInInterface) {
274 usbi_dbg ("could not set up plugin for service: %s", darwin_error_str (result));
278 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
280 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
281 (*plugInInterface)->Release (plugInInterface);
286 static void darwin_devices_attached (void *ptr, io_iterator_t add_devices) {
287 struct libusb_context *ctx;
288 io_service_t service;
290 usbi_mutex_lock(&active_contexts_lock);
292 while ((service = IOIteratorNext(add_devices))) {
293 /* add this device to each active context's device list */
294 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
295 process_new_device (ctx, service);;
298 IOObjectRelease(service);
301 usbi_mutex_unlock(&active_contexts_lock);
304 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
305 struct libusb_device *dev = NULL;
306 struct libusb_context *ctx;
307 struct darwin_cached_device *old_device;
313 usbi_mutex_lock(&active_contexts_lock);
315 while ((device = IOIteratorNext (rem_devices)) != 0) {
316 /* get the location from the i/o registry */
317 ret = get_ioregistry_value_number (device, CFSTR("sessionID"), kCFNumberSInt64Type, &session);
318 IOObjectRelease (device);
322 /* we need to match darwin_ref_cached_device call made in darwin_get_cached_device function
323 otherwise no cached device will ever get freed */
324 usbi_mutex_lock(&darwin_cached_devices_lock);
325 list_for_each_entry(old_device, &darwin_cached_devices, list, struct darwin_cached_device) {
326 if (old_device->session == session) {
327 darwin_deref_cached_device (old_device);
331 usbi_mutex_unlock(&darwin_cached_devices_lock);
333 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
334 usbi_dbg ("notifying context %p of device disconnect", ctx);
336 dev = usbi_get_device_by_session_id(ctx, (unsigned long) session);
338 /* signal the core that this device has been disconnected. the core will tear down this device
339 when the reference count reaches 0 */
340 usbi_disconnect_device(dev);
341 libusb_unref_device(dev);
346 usbi_mutex_unlock(&active_contexts_lock);
349 static void darwin_hotplug_poll (void)
351 /* not sure if 5 seconds will be too long/short but it should work ok */
352 mach_timespec_t timeout = {.tv_sec = 5, .tv_nsec = 0};
354 /* since a kernel thread may nodify the IOInterators used for
355 * hotplug notidication we can't just clear the iterators.
356 * instead just wait until all IOService providers are quiet */
357 (void) IOKitWaitQuiet (kIOMasterPortDefault, &timeout);
360 static void darwin_clear_iterator (io_iterator_t iter) {
363 while ((device = IOIteratorNext (iter)) != 0)
364 IOObjectRelease (device);
367 static void *darwin_event_thread_main (void *arg0) {
369 struct libusb_context *ctx = (struct libusb_context *)arg0;
370 CFRunLoopRef runloop;
372 /* Set this thread's name, so it can be seen in the debugger
373 and crash reports. */
374 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
375 pthread_setname_np ("org.libusb.device-hotplug");
377 /* Tell the Objective-C garbage collector about this thread.
378 This is required because, unlike NSThreads, pthreads are
379 not automatically registered. Although we don't use
380 Objective-C, we use CoreFoundation, which does. */
381 objc_registerThreadWithCollector();
384 /* hotplug (device arrival/removal) sources */
385 CFRunLoopSourceRef libusb_notification_cfsource;
386 io_notification_port_t libusb_notification_port;
387 io_iterator_t libusb_rem_device_iterator;
388 io_iterator_t libusb_add_device_iterator;
390 usbi_dbg ("creating hotplug event source");
392 runloop = CFRunLoopGetCurrent ();
395 /* add the notification port to the run loop */
396 libusb_notification_port = IONotificationPortCreate (kIOMasterPortDefault);
397 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
398 CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
400 /* create notifications for removed devices */
401 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
402 IOServiceMatching(darwin_device_class),
403 darwin_devices_detached,
404 ctx, &libusb_rem_device_iterator);
406 if (kresult != kIOReturnSuccess) {
407 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
412 /* create notifications for attached devices */
413 kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
414 IOServiceMatching(darwin_device_class),
415 darwin_devices_attached,
416 ctx, &libusb_add_device_iterator);
418 if (kresult != kIOReturnSuccess) {
419 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
425 darwin_clear_iterator (libusb_rem_device_iterator);
426 darwin_clear_iterator (libusb_add_device_iterator);
428 usbi_dbg ("darwin event thread ready to receive events");
430 /* signal the main thread that the hotplug runloop has been created. */
431 pthread_mutex_lock (&libusb_darwin_at_mutex);
432 libusb_darwin_acfl = runloop;
433 pthread_cond_signal (&libusb_darwin_at_cond);
434 pthread_mutex_unlock (&libusb_darwin_at_mutex);
436 /* run the runloop */
439 usbi_dbg ("darwin event thread exiting");
441 /* remove the notification cfsource */
442 CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
444 /* delete notification port */
445 IONotificationPortDestroy (libusb_notification_port);
447 /* delete iterators */
448 IOObjectRelease (libusb_rem_device_iterator);
449 IOObjectRelease (libusb_add_device_iterator);
453 libusb_darwin_acfl = NULL;
458 /* cleanup function to destroy cached devices */
459 static void __attribute__((destructor)) _darwin_finalize(void) {
460 struct darwin_cached_device *dev, *next;
462 usbi_mutex_lock(&darwin_cached_devices_lock);
463 list_for_each_entry_safe(dev, next, &darwin_cached_devices, list, struct darwin_cached_device) {
464 darwin_deref_cached_device(dev);
466 usbi_mutex_unlock(&darwin_cached_devices_lock);
469 static void darwin_check_version (void) {
470 /* adjust for changes in the USB stack in xnu 15 */
471 int sysctl_args[] = {CTL_KERN, KERN_OSRELEASE};
473 char version_string[256] = {'\0',};
476 sysctl(sysctl_args, 2, version_string, &length, NULL, 0);
479 version = strtol (version_string, NULL, 10);
480 if (0 == errno && version >= 15) {
481 darwin_device_class = "IOUSBHostDevice";
485 static int darwin_init(struct libusb_context *ctx) {
486 host_name_port_t host_self;
489 rc = pthread_once (&darwin_init_once, darwin_check_version);
491 return LIBUSB_ERROR_OTHER;
494 rc = darwin_scan_devices (ctx);
495 if (LIBUSB_SUCCESS != rc) {
499 if (OSAtomicIncrement32Barrier(&initCount) == 1) {
500 /* create the clocks that will be used */
502 host_self = mach_host_self();
503 host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
504 host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
505 mach_port_deallocate(mach_task_self(), host_self);
507 pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, ctx);
509 pthread_mutex_lock (&libusb_darwin_at_mutex);
510 while (!libusb_darwin_acfl)
511 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
512 pthread_mutex_unlock (&libusb_darwin_at_mutex);
518 static void darwin_exit (void) {
519 if (OSAtomicDecrement32Barrier(&initCount) == 0) {
520 mach_port_deallocate(mach_task_self(), clock_realtime);
521 mach_port_deallocate(mach_task_self(), clock_monotonic);
523 /* stop the event runloop and wait for the thread to terminate. */
524 CFRunLoopStop (libusb_darwin_acfl);
525 pthread_join (libusb_darwin_at, NULL);
529 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
530 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
532 /* return cached copy */
533 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
540 static int get_configuration_index (struct libusb_device *dev, int config_value) {
541 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
543 IOUSBConfigurationDescriptorPtr desc;
546 /* is there a simpler way to determine the index? */
547 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
548 if (kresult != kIOReturnSuccess)
549 return darwin_to_libusb (kresult);
551 for (i = 0 ; i < numConfig ; i++) {
552 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
554 if (desc->bConfigurationValue == config_value)
558 /* configuration not found */
559 return LIBUSB_ERROR_NOT_FOUND;
562 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
563 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
566 if (0 == priv->active_config)
567 return LIBUSB_ERROR_NOT_FOUND;
569 config_index = get_configuration_index (dev, priv->active_config);
570 if (config_index < 0)
573 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
576 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
577 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
578 IOUSBConfigurationDescriptorPtr desc;
582 if (!priv || !priv->device)
583 return LIBUSB_ERROR_OTHER;
585 kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
586 if (kresult == kIOReturnSuccess) {
587 /* copy descriptor */
588 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
589 len = libusb_le16_to_cpu(desc->wTotalLength);
591 memmove (buffer, desc, len);
593 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
597 ret = darwin_to_libusb (kresult);
598 if (ret != LIBUSB_SUCCESS)
604 /* check whether the os has configured the device */
605 static int darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) {
606 usb_device_t **darwin_device = dev->device;
608 IOUSBConfigurationDescriptorPtr configDesc;
609 IOUSBFindInterfaceRequest request;
610 kern_return_t kresult;
611 io_iterator_t interface_iterator;
612 io_service_t firstInterface;
614 if (dev->dev_descriptor.bNumConfigurations < 1) {
615 usbi_err (ctx, "device has no configurations");
616 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
619 /* checking the configuration of a root hub simulation takes ~1 s in 10.11. the device is
621 if (0x05ac == dev->dev_descriptor.idVendor && 0x8005 == dev->dev_descriptor.idProduct) {
622 usbi_dbg ("ignoring configuration on root hub simulation");
623 dev->active_config = 0;
627 /* find the first configuration */
628 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
629 dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
631 /* check if the device is already configured. there is probably a better way than iterating over the
632 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
633 might lock up on the device request) */
635 /* Setup the Interface Request */
636 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
637 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
638 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
639 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
641 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
643 return darwin_to_libusb (kresult);
646 firstInterface = IOIteratorNext(interface_iterator);
648 /* done with the interface iterator */
649 IOObjectRelease(interface_iterator);
651 if (firstInterface) {
652 IOObjectRelease (firstInterface);
654 /* device is configured */
655 if (dev->dev_descriptor.bNumConfigurations == 1)
656 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
657 dev->active_config = dev->first_config;
659 /* devices with more than one configuration should work with GetConfiguration */
660 (*darwin_device)->GetConfiguration (darwin_device, &dev->active_config);
663 dev->active_config = 0;
665 usbi_dbg ("active config: %u, first config: %u", dev->active_config, dev->first_config);
670 static int darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
671 IOUSBDevRequestTO req;
673 memset (buffer, 0, buffer_size);
675 /* Set up request for descriptor/ */
676 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
677 req.bRequest = kUSBRqGetDescriptor;
678 req.wValue = desc << 8;
679 req.wIndex = desc_index;
680 req.wLength = buffer_size;
682 req.noDataTimeout = 20;
683 req.completionTimeout = 100;
685 return (*device)->DeviceRequestTO (device, &req);
688 static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct darwin_cached_device *dev) {
689 usb_device_t **device = dev->device;
690 int retries = 1, delay = 30000;
691 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
695 UInt16 idProduct, idVendor;
697 dev->can_enumerate = 0;
699 (*device)->GetDeviceClass (device, &bDeviceClass);
700 (*device)->GetDeviceProduct (device, &idProduct);
701 (*device)->GetDeviceVendor (device, &idVendor);
703 /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
704 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
705 * to follow the spec as closely as possible, try opening the device */
706 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
709 /**** retrieve device descriptor ****/
710 ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &dev->dev_descriptor, sizeof(dev->dev_descriptor));
712 if (kIOReturnOverrun == ret && kUSBDeviceDesc == dev->dev_descriptor.bDescriptorType)
713 /* received an overrun error but we still received a device descriptor */
714 ret = kIOReturnSuccess;
716 if (kIOUSBVendorIDAppleComputer == idVendor) {
717 /* NTH: don't bother retrying or unsuspending Apple devices */
721 if (kIOReturnSuccess == ret && (0 == dev->dev_descriptor.bNumConfigurations ||
722 0 == dev->dev_descriptor.bcdUSB)) {
723 /* work around for incorrectly configured devices */
724 if (try_reconfigure && is_open) {
725 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
727 /* set the first configuration */
728 (*device)->SetConfiguration(device, 1);
730 /* don't try to reconfigure again */
734 ret = kIOUSBPipeStalled;
737 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
738 /* device may be suspended. unsuspend it and try again */
739 #if DeviceVersion >= 320
742 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
743 (void)(*device)->GetUSBDeviceInformation (device, &info);
745 /* note that the device was suspended */
746 if (info & (1 << kUSBInformationDeviceIsSuspendedBit) || 0 == info)
751 /* try to unsuspend the device */
752 ret2 = (*device)->USBDeviceSuspend (device, 0);
753 if (kIOReturnSuccess != ret2) {
754 /* prevent log spew from poorly behaving devices. this indicates the
755 os actually had trouble communicating with the device */
756 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
764 if (kIOReturnSuccess != ret) {
765 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
766 /* sleep for a little while before trying again */
769 } while (kIOReturnSuccess != ret && retries--);
772 /* resuspend the device */
773 (void)(*device)->USBDeviceSuspend (device, 1);
776 (void) (*device)->USBDeviceClose (device);
778 if (ret != kIOReturnSuccess) {
779 /* a debug message was already printed out for this error */
780 if (LIBUSB_CLASS_HUB == bDeviceClass)
781 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
782 idVendor, idProduct, darwin_error_str (ret), ret);
784 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
785 idVendor, idProduct, darwin_error_str (ret), ret);
786 return darwin_to_libusb (ret);
789 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
790 if (libusb_le16_to_cpu (dev->dev_descriptor.idProduct) != idProduct) {
791 /* not a valid device */
792 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
793 idProduct, libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
794 return LIBUSB_ERROR_NO_DEVICE;
797 usbi_dbg ("cached device descriptor:");
798 usbi_dbg (" bDescriptorType: 0x%02x", dev->dev_descriptor.bDescriptorType);
799 usbi_dbg (" bcdUSB: 0x%04x", dev->dev_descriptor.bcdUSB);
800 usbi_dbg (" bDeviceClass: 0x%02x", dev->dev_descriptor.bDeviceClass);
801 usbi_dbg (" bDeviceSubClass: 0x%02x", dev->dev_descriptor.bDeviceSubClass);
802 usbi_dbg (" bDeviceProtocol: 0x%02x", dev->dev_descriptor.bDeviceProtocol);
803 usbi_dbg (" bMaxPacketSize0: 0x%02x", dev->dev_descriptor.bMaxPacketSize0);
804 usbi_dbg (" idVendor: 0x%04x", dev->dev_descriptor.idVendor);
805 usbi_dbg (" idProduct: 0x%04x", dev->dev_descriptor.idProduct);
806 usbi_dbg (" bcdDevice: 0x%04x", dev->dev_descriptor.bcdDevice);
807 usbi_dbg (" iManufacturer: 0x%02x", dev->dev_descriptor.iManufacturer);
808 usbi_dbg (" iProduct: 0x%02x", dev->dev_descriptor.iProduct);
809 usbi_dbg (" iSerialNumber: 0x%02x", dev->dev_descriptor.iSerialNumber);
810 usbi_dbg (" bNumConfigurations: 0x%02x", dev->dev_descriptor.bNumConfigurations);
812 dev->can_enumerate = 1;
814 return LIBUSB_SUCCESS;
817 static int get_device_port (io_service_t service, UInt8 *port) {
818 kern_return_t result;
822 if (get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, port)) {
826 result = IORegistryEntryGetParentEntry (service, kIOServicePlane, &parent);
827 if (kIOReturnSuccess == result) {
828 ret = get_ioregistry_value_data (parent, CFSTR("port"), 1, port);
829 IOObjectRelease (parent);
835 static int darwin_get_cached_device(struct libusb_context *ctx, io_service_t service,
836 struct darwin_cached_device **cached_out) {
837 struct darwin_cached_device *new_device;
838 UInt64 sessionID = 0, parent_sessionID = 0;
839 int ret = LIBUSB_SUCCESS;
840 usb_device_t **device;
842 kern_return_t result;
845 /* get some info from the io registry */
846 (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
847 if (!get_device_port (service, &port)) {
848 usbi_dbg("could not get connected port number");
851 usbi_dbg("finding cached device for sessionID 0x%" PRIx64, sessionID);
853 result = IORegistryEntryGetParentEntry (service, kIOUSBPlane, &parent);
855 if (kIOReturnSuccess == result) {
856 (void) get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, &parent_sessionID);
857 IOObjectRelease(parent);
860 usbi_mutex_lock(&darwin_cached_devices_lock);
864 list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) {
865 usbi_dbg("matching sessionID 0x%" PRIx64 " against cached device with sessionID 0x%" PRIx64, sessionID, new_device->session);
866 if (new_device->session == sessionID) {
867 usbi_dbg("using cached device for device");
868 *cached_out = new_device;
876 usbi_dbg("caching new device with sessionID 0x%" PRIx64, sessionID);
878 device = darwin_device_from_service (service);
880 ret = LIBUSB_ERROR_NO_DEVICE;
884 new_device = calloc (1, sizeof (*new_device));
886 ret = LIBUSB_ERROR_NO_MEM;
890 /* add this device to the cached device list */
891 list_add(&new_device->list, &darwin_cached_devices);
893 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
895 /* keep a reference to this device */
896 darwin_ref_cached_device(new_device);
898 new_device->device = device;
899 new_device->session = sessionID;
900 (*device)->GetLocationID (device, &new_device->location);
901 new_device->port = port;
902 new_device->parent_session = parent_sessionID;
904 /* cache the device descriptor */
905 ret = darwin_cache_device_descriptor(ctx, new_device);
909 if (new_device->can_enumerate) {
910 snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address,
911 new_device->dev_descriptor.idVendor, new_device->dev_descriptor.idProduct,
912 new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass);
916 usbi_mutex_unlock(&darwin_cached_devices_lock);
918 /* keep track of devices regardless of if we successfully enumerate them to
919 prevent them from being enumerated multiple times */
921 *cached_out = new_device;
926 static int process_new_device (struct libusb_context *ctx, io_service_t service) {
927 struct darwin_device_priv *priv;
928 struct libusb_device *dev = NULL;
929 struct darwin_cached_device *cached_device;
934 ret = darwin_get_cached_device (ctx, service, &cached_device);
936 if (ret < 0 || !cached_device->can_enumerate) {
940 /* check current active configuration (and cache the first configuration value--
941 which may be used by claim_interface) */
942 ret = darwin_check_configuration (ctx, cached_device);
946 usbi_dbg ("allocating new device in context %p for with session 0x%" PRIx64,
947 ctx, cached_device->session);
949 dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
951 return LIBUSB_ERROR_NO_MEM;
954 priv = (struct darwin_device_priv *)dev->os_priv;
956 priv->dev = cached_device;
957 darwin_ref_cached_device (priv->dev);
959 if (cached_device->parent_session > 0) {
960 dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session);
962 dev->parent_dev = NULL;
964 dev->port_number = cached_device->port;
965 dev->bus_number = cached_device->location >> 24;
966 dev->device_address = cached_device->address;
968 (*(priv->dev->device))->GetDeviceSpeed (priv->dev->device, &devSpeed);
971 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
972 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
973 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
974 #if DeviceVersion >= 500
975 case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
978 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
981 ret = usbi_sanitize_device (dev);
985 usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
986 dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
990 usbi_connect_device (dev);
992 libusb_unref_device (dev);
998 static int darwin_scan_devices(struct libusb_context *ctx) {
999 io_iterator_t deviceIterator;
1000 io_service_t service;
1001 kern_return_t kresult;
1003 kresult = usb_setup_device_iterator (&deviceIterator, 0);
1004 if (kresult != kIOReturnSuccess)
1005 return darwin_to_libusb (kresult);
1007 while ((service = IOIteratorNext (deviceIterator))) {
1008 (void) process_new_device (ctx, service);
1010 IOObjectRelease(service);
1013 IOObjectRelease(deviceIterator);
1018 static int darwin_open (struct libusb_device_handle *dev_handle) {
1019 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1020 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1023 if (0 == dpriv->open_count) {
1024 /* try to open the device */
1025 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
1026 if (kresult != kIOReturnSuccess) {
1027 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
1029 if (kIOReturnExclusiveAccess != kresult) {
1030 return darwin_to_libusb (kresult);
1033 /* it is possible to perform some actions on a device that is not open so do not return an error */
1039 /* create async event source */
1040 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
1041 if (kresult != kIOReturnSuccess) {
1042 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
1044 if (priv->is_open) {
1045 (*(dpriv->device))->USBDeviceClose (dpriv->device);
1050 return darwin_to_libusb (kresult);
1053 CFRetain (libusb_darwin_acfl);
1055 /* add the cfSource to the aync run loop */
1056 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
1059 /* device opened successfully */
1060 dpriv->open_count++;
1062 usbi_dbg ("device open for access");
1067 static void darwin_close (struct libusb_device_handle *dev_handle) {
1068 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1069 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1073 if (dpriv->open_count == 0) {
1074 /* something is probably very wrong if this is the case */
1075 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!");
1079 dpriv->open_count--;
1081 /* make sure all interfaces are released */
1082 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1083 if (dev_handle->claimed_interfaces & (1 << i))
1084 libusb_release_interface (dev_handle, i);
1086 if (0 == dpriv->open_count) {
1087 /* delete the device's async event source */
1088 if (priv->cfSource) {
1089 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
1090 CFRelease (priv->cfSource);
1091 priv->cfSource = NULL;
1092 CFRelease (libusb_darwin_acfl);
1095 if (priv->is_open) {
1096 /* close the device */
1097 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
1099 /* Log the fact that we had a problem closing the file, however failing a
1100 * close isn't really an error, so return success anyway */
1101 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
1107 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
1108 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1110 *config = (int) dpriv->active_config;
1115 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
1116 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1120 /* Setting configuration will invalidate the interface, so we need
1121 to reclaim it. First, dispose of existing interfaces, if any. */
1122 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1123 if (dev_handle->claimed_interfaces & (1 << i))
1124 darwin_release_interface (dev_handle, i);
1126 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
1127 if (kresult != kIOReturnSuccess)
1128 return darwin_to_libusb (kresult);
1130 /* Reclaim any interfaces. */
1131 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1132 if (dev_handle->claimed_interfaces & (1 << i))
1133 darwin_claim_interface (dev_handle, i);
1135 dpriv->active_config = config;
1140 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
1141 IOUSBFindInterfaceRequest request;
1142 kern_return_t kresult;
1143 io_iterator_t interface_iterator;
1144 UInt8 bInterfaceNumber;
1147 *usbInterfacep = IO_OBJECT_NULL;
1149 /* Setup the Interface Request */
1150 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1151 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1152 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1153 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1155 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1159 while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1160 /* find the interface number */
1161 ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
1164 if (ret && bInterfaceNumber == ifc) {
1168 (void) IOObjectRelease (*usbInterfacep);
1171 /* done with the interface iterator */
1172 IOObjectRelease(interface_iterator);
1177 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
1178 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1180 /* current interface */
1181 struct darwin_interface *cInterface = &priv->interfaces[iface];
1183 kern_return_t kresult;
1185 u_int8_t numep, direction, number;
1186 u_int8_t dont_care1, dont_care3;
1187 u_int16_t dont_care2;
1190 usbi_dbg ("building table of endpoints.");
1192 /* retrieve the total number of endpoints on this interface */
1193 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1195 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1196 return darwin_to_libusb (kresult);
1199 /* iterate through pipe references */
1200 for (i = 1 ; i <= numep ; i++) {
1201 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1202 &dont_care2, &dont_care3);
1204 if (kresult != kIOReturnSuccess) {
1205 usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
1207 return darwin_to_libusb (kresult);
1210 usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
1212 cInterface->endpoint_addrs[i - 1] = (((kUSBIn == direction) << kUSBRqDirnShift) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1215 cInterface->num_endpoints = numep;
1220 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1221 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1222 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1223 io_service_t usbInterface = IO_OBJECT_NULL;
1225 IOCFPlugInInterface **plugInInterface = NULL;
1228 /* current interface */
1229 struct darwin_interface *cInterface = &priv->interfaces[iface];
1231 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1232 if (kresult != kIOReturnSuccess)
1233 return darwin_to_libusb (kresult);
1235 /* make sure we have an interface */
1236 if (!usbInterface && dpriv->first_config != 0) {
1237 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1239 /* set the configuration */
1240 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1241 if (kresult != LIBUSB_SUCCESS) {
1242 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1246 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1248 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1249 return darwin_to_libusb (kresult);
1253 if (!usbInterface) {
1254 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1255 return LIBUSB_ERROR_NOT_FOUND;
1258 /* get an interface to the device's interface */
1259 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1260 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1262 /* ignore release error */
1263 (void)IOObjectRelease (usbInterface);
1266 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1267 return darwin_to_libusb (kresult);
1270 if (!plugInInterface) {
1271 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1272 return LIBUSB_ERROR_NOT_FOUND;
1275 /* Do the actual claim */
1276 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1277 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1278 (LPVOID)&cInterface->interface);
1279 /* We no longer need the intermediate plug-in */
1280 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1281 (*plugInInterface)->Release (plugInInterface);
1282 if (kresult || !cInterface->interface) {
1283 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1284 return darwin_to_libusb (kresult);
1287 /* claim the interface */
1288 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1290 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1291 return darwin_to_libusb (kresult);
1294 /* update list of endpoints */
1295 kresult = get_endpoints (dev_handle, iface);
1297 /* this should not happen */
1298 darwin_release_interface (dev_handle, iface);
1299 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1303 cInterface->cfSource = NULL;
1305 /* create async event source */
1306 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1307 if (kresult != kIOReturnSuccess) {
1308 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1310 /* can't continue without an async event source */
1311 (void)darwin_release_interface (dev_handle, iface);
1313 return darwin_to_libusb (kresult);
1316 /* add the cfSource to the async thread's run loop */
1317 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1319 usbi_dbg ("interface opened");
1324 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1325 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1328 /* current interface */
1329 struct darwin_interface *cInterface = &priv->interfaces[iface];
1331 /* Check to see if an interface is open */
1332 if (!cInterface->interface)
1333 return LIBUSB_SUCCESS;
1335 /* clean up endpoint data */
1336 cInterface->num_endpoints = 0;
1338 /* delete the interface's async event source */
1339 if (cInterface->cfSource) {
1340 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1341 CFRelease (cInterface->cfSource);
1344 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1346 usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1348 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1349 if (kresult != kIOReturnSuccess)
1350 usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1352 cInterface->interface = (usb_interface_t **) IO_OBJECT_NULL;
1354 return darwin_to_libusb (kresult);
1357 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1358 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1361 /* current interface */
1362 struct darwin_interface *cInterface = &priv->interfaces[iface];
1364 if (!cInterface->interface)
1365 return LIBUSB_ERROR_NO_DEVICE;
1367 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1368 if (kresult != kIOReturnSuccess)
1369 darwin_reset_device (dev_handle);
1371 /* update list of endpoints */
1372 kresult = get_endpoints (dev_handle, iface);
1374 /* this should not happen */
1375 darwin_release_interface (dev_handle, iface);
1376 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1380 return darwin_to_libusb (kresult);
1383 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1384 /* current interface */
1385 struct darwin_interface *cInterface;
1389 /* determine the interface/endpoint to use */
1390 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, NULL, &cInterface) != 0) {
1391 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1393 return LIBUSB_ERROR_NOT_FOUND;
1396 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1397 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1399 usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1401 return darwin_to_libusb (kresult);
1404 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1405 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1406 IOUSBDeviceDescriptor descriptor;
1407 IOUSBConfigurationDescriptorPtr cached_configuration;
1408 IOUSBConfigurationDescriptor configuration;
1409 bool reenumerate = false;
1413 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1415 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1416 return darwin_to_libusb (kresult);
1420 usbi_dbg ("darwin/reset_device: checking if device descriptor changed");
1422 /* ignore return code. if we can't get a descriptor it might be worthwhile re-enumerating anway */
1423 (void) darwin_request_descriptor (dpriv->device, kUSBDeviceDesc, 0, &descriptor, sizeof (descriptor));
1425 /* check if the device descriptor has changed */
1426 if (0 != memcmp (&dpriv->dev_descriptor, &descriptor, sizeof (descriptor))) {
1431 /* check if any configuration descriptor has changed */
1432 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1433 usbi_dbg ("darwin/reset_device: checking if configuration descriptor %d changed", i);
1435 (void) darwin_request_descriptor (dpriv->device, kUSBConfDesc, i, &configuration, sizeof (configuration));
1436 (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1438 if (!cached_configuration || 0 != memcmp (cached_configuration, &configuration, sizeof (configuration))) {
1446 usbi_dbg ("darwin/reset_device: device requires reenumeration");
1447 (void) (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
1448 return LIBUSB_ERROR_NOT_FOUND;
1451 usbi_dbg ("darwin/reset_device: device reset complete");
1453 return LIBUSB_SUCCESS;
1456 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1457 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1458 io_service_t usbInterface;
1462 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1464 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1466 return darwin_to_libusb (kresult);
1469 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1470 IOObjectRelease (usbInterface);
1482 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1483 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1486 return LIBUSB_ERROR_NOT_SUPPORTED;
1489 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1492 return LIBUSB_ERROR_NOT_SUPPORTED;
1495 static void darwin_destroy_device(struct libusb_device *dev) {
1496 struct darwin_device_priv *dpriv = (struct darwin_device_priv *) dev->os_priv;
1499 /* need to hold the lock in case this is the last reference to the device */
1500 usbi_mutex_lock(&darwin_cached_devices_lock);
1501 darwin_deref_cached_device (dpriv->dev);
1503 usbi_mutex_unlock(&darwin_cached_devices_lock);
1507 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1508 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1511 uint8_t transferType;
1512 /* None of the values below are used in libusbx for bulk transfers */
1513 uint8_t direction, number, interval, pipeRef;
1514 uint16_t maxPacketSize;
1516 struct darwin_interface *cInterface;
1518 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1519 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1521 return LIBUSB_ERROR_NOT_FOUND;
1524 ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1525 &transferType, &maxPacketSize, &interval);
1528 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1529 darwin_error_str(ret), ret);
1530 return darwin_to_libusb (ret);
1533 if (0 != (transfer->length % maxPacketSize)) {
1534 /* do not need a zero packet */
1535 transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1538 /* submit the request */
1539 /* timeouts are unavailable on interrupt endpoints */
1540 if (transferType == kUSBInterrupt) {
1541 if (IS_XFERIN(transfer))
1542 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1543 transfer->length, darwin_async_io_callback, itransfer);
1545 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1546 transfer->length, darwin_async_io_callback, itransfer);
1548 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1550 if (IS_XFERIN(transfer))
1551 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1552 transfer->length, transfer->timeout, transfer->timeout,
1553 darwin_async_io_callback, (void *)itransfer);
1555 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1556 transfer->length, transfer->timeout, transfer->timeout,
1557 darwin_async_io_callback, (void *)itransfer);
1561 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1562 darwin_error_str(ret), ret);
1564 return darwin_to_libusb (ret);
1567 #if InterfaceVersion >= 550
1568 static int submit_stream_transfer(struct usbi_transfer *itransfer) {
1569 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1570 struct darwin_interface *cInterface;
1574 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1575 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1577 return LIBUSB_ERROR_NOT_FOUND;
1580 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1582 if (IS_XFERIN(transfer))
1583 ret = (*(cInterface->interface))->ReadStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1584 transfer->buffer, transfer->length, transfer->timeout,
1585 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1587 ret = (*(cInterface->interface))->WriteStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1588 transfer->buffer, transfer->length, transfer->timeout,
1589 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1592 usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1593 darwin_error_str(ret), ret);
1595 return darwin_to_libusb (ret);
1599 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1600 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1601 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1604 uint8_t direction, number, interval, pipeRef, transferType;
1605 uint16_t maxPacketSize;
1607 AbsoluteTime atTime;
1610 struct darwin_interface *cInterface;
1612 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1613 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1614 free(tpriv->isoc_framelist);
1615 tpriv->isoc_framelist = NULL;
1618 if (!tpriv->isoc_framelist) {
1619 tpriv->num_iso_packets = transfer->num_iso_packets;
1620 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1621 if (!tpriv->isoc_framelist)
1622 return LIBUSB_ERROR_NO_MEM;
1625 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1626 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1627 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1629 /* determine the interface/endpoint to use */
1630 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1631 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1633 return LIBUSB_ERROR_NOT_FOUND;
1636 /* determine the properties of this endpoint and the speed of the device */
1637 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1638 &transferType, &maxPacketSize, &interval);
1640 /* Last but not least we need the bus frame number */
1641 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1643 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1644 free(tpriv->isoc_framelist);
1645 tpriv->isoc_framelist = NULL;
1647 return darwin_to_libusb (kresult);
1650 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1651 &transferType, &maxPacketSize, &interval);
1653 /* schedule for a frame a little in the future */
1656 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1657 frame = cInterface->frames[transfer->endpoint];
1659 /* submit the request */
1660 if (IS_XFERIN(transfer))
1661 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1662 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1665 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1666 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1669 if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
1671 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1));
1673 /* High/super speed */
1674 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1)) / 8;
1676 if (kresult != kIOReturnSuccess) {
1677 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1678 darwin_error_str(kresult));
1679 free (tpriv->isoc_framelist);
1680 tpriv->isoc_framelist = NULL;
1683 return darwin_to_libusb (kresult);
1686 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1687 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1688 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1689 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1690 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1694 bzero(&tpriv->req, sizeof(tpriv->req));
1696 /* IOUSBDeviceInterface expects the request in cpu endianness */
1697 tpriv->req.bmRequestType = setup->bmRequestType;
1698 tpriv->req.bRequest = setup->bRequest;
1699 /* these values should be in bus order from libusb_fill_control_setup */
1700 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1701 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1702 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1703 /* data is stored after the libusb control block */
1704 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1705 tpriv->req.completionTimeout = transfer->timeout;
1706 tpriv->req.noDataTimeout = transfer->timeout;
1708 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1710 /* all transfers in libusb-1.0 are async */
1712 if (transfer->endpoint) {
1713 struct darwin_interface *cInterface;
1716 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1717 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1719 return LIBUSB_ERROR_NOT_FOUND;
1722 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1724 /* control request on endpoint 0 */
1725 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1727 if (kresult != kIOReturnSuccess)
1728 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1730 return darwin_to_libusb (kresult);
1733 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1734 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1736 switch (transfer->type) {
1737 case LIBUSB_TRANSFER_TYPE_CONTROL:
1738 return submit_control_transfer(itransfer);
1739 case LIBUSB_TRANSFER_TYPE_BULK:
1740 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1741 return submit_bulk_transfer(itransfer);
1742 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1743 return submit_iso_transfer(itransfer);
1744 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1745 #if InterfaceVersion >= 550
1746 return submit_stream_transfer(itransfer);
1748 usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers");
1749 return LIBUSB_ERROR_NOT_SUPPORTED;
1752 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1753 return LIBUSB_ERROR_INVALID_PARAM;
1757 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1758 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1759 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1762 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
1765 return LIBUSB_ERROR_NO_DEVICE;
1767 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1769 return darwin_to_libusb (kresult);
1772 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1773 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1774 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1775 struct darwin_interface *cInterface;
1776 uint8_t pipeRef, iface;
1779 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) {
1780 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1782 return LIBUSB_ERROR_NOT_FOUND;
1786 return LIBUSB_ERROR_NO_DEVICE;
1788 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
1790 /* abort transactions */
1791 #if InterfaceVersion >= 550
1792 if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type)
1793 (*(cInterface->interface))->AbortStreamsPipe (cInterface->interface, pipeRef, itransfer->stream_id);
1796 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1798 usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
1800 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1801 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1803 return darwin_to_libusb (kresult);
1806 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1807 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1809 switch (transfer->type) {
1810 case LIBUSB_TRANSFER_TYPE_CONTROL:
1811 return cancel_control_transfer(itransfer);
1812 case LIBUSB_TRANSFER_TYPE_BULK:
1813 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1814 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1815 return darwin_abort_transfers (itransfer);
1817 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1818 return LIBUSB_ERROR_INVALID_PARAM;
1822 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1823 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1824 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1826 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1827 free (tpriv->isoc_framelist);
1828 tpriv->isoc_framelist = NULL;
1832 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1833 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1834 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1835 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1837 usbi_dbg ("an async io operation has completed");
1839 /* if requested write a zero packet */
1840 if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
1841 struct darwin_interface *cInterface;
1844 (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface);
1846 (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
1849 tpriv->result = result;
1850 tpriv->size = (UInt32) (uintptr_t) arg0;
1852 /* signal the core that this transfer is complete */
1853 usbi_signal_transfer_completion(itransfer);
1856 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1857 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT)
1858 result = kIOUSBTransactionTimeout;
1861 case kIOReturnUnderrun:
1862 case kIOReturnSuccess:
1863 return LIBUSB_TRANSFER_COMPLETED;
1864 case kIOReturnAborted:
1865 return LIBUSB_TRANSFER_CANCELLED;
1866 case kIOUSBPipeStalled:
1867 usbi_dbg ("transfer error: pipe is stalled");
1868 return LIBUSB_TRANSFER_STALL;
1869 case kIOReturnOverrun:
1870 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1871 return LIBUSB_TRANSFER_OVERFLOW;
1872 case kIOUSBTransactionTimeout:
1873 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1874 itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
1875 return LIBUSB_TRANSFER_TIMED_OUT;
1877 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1878 return LIBUSB_TRANSFER_ERROR;
1882 static int darwin_handle_transfer_completion (struct usbi_transfer *itransfer) {
1883 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1884 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1885 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1886 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1887 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1888 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1891 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1892 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1893 return LIBUSB_ERROR_INVALID_PARAM;
1896 usbi_dbg ("handling %s completion with kernel status %d",
1897 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", tpriv->result);
1899 if (kIOReturnSuccess == tpriv->result || kIOReturnUnderrun == tpriv->result) {
1900 if (isIsoc && tpriv->isoc_framelist) {
1901 /* copy isochronous results back */
1903 for (i = 0; i < transfer->num_iso_packets ; i++) {
1904 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1905 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1906 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1909 itransfer->transferred += tpriv->size;
1912 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1913 return usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, tpriv->result));
1916 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1917 mach_timespec_t sys_time;
1918 clock_serv_t clock_ref;
1921 case USBI_CLOCK_REALTIME:
1922 /* CLOCK_REALTIME represents time since the epoch */
1923 clock_ref = clock_realtime;
1925 case USBI_CLOCK_MONOTONIC:
1926 /* use system boot time as reference for the monotonic clock */
1927 clock_ref = clock_monotonic;
1930 return LIBUSB_ERROR_INVALID_PARAM;
1933 clock_get_time (clock_ref, &sys_time);
1935 tp->tv_sec = sys_time.tv_sec;
1936 tp->tv_nsec = sys_time.tv_nsec;
1941 #if InterfaceVersion >= 550
1942 static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints,
1943 int num_endpoints) {
1944 struct darwin_interface *cInterface;
1945 UInt32 supportsStreams;
1949 /* find the mimimum number of supported streams on the endpoint list */
1950 for (i = 0 ; i < num_endpoints ; ++i) {
1951 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) {
1955 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
1956 if (num_streams > supportsStreams)
1957 num_streams = supportsStreams;
1960 /* it is an error if any endpoint in endpoints does not support streams */
1961 if (0 == num_streams)
1962 return LIBUSB_ERROR_INVALID_PARAM;
1964 /* create the streams */
1965 for (i = 0 ; i < num_endpoints ; ++i) {
1966 (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
1968 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, num_streams);
1969 if (kIOReturnSuccess != rc)
1970 return darwin_to_libusb(rc);
1976 static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) {
1977 struct darwin_interface *cInterface;
1978 UInt32 supportsStreams;
1982 for (int i = 0 ; i < num_endpoints ; ++i) {
1983 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface)))
1986 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
1987 if (0 == supportsStreams)
1988 return LIBUSB_ERROR_INVALID_PARAM;
1990 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, 0);
1991 if (kIOReturnSuccess != rc)
1992 return darwin_to_libusb(rc);
1995 return LIBUSB_SUCCESS;
1999 const struct usbi_os_backend darwin_backend = {
2002 .init = darwin_init,
2003 .exit = darwin_exit,
2004 .get_device_list = NULL, /* not needed */
2005 .get_device_descriptor = darwin_get_device_descriptor,
2006 .get_active_config_descriptor = darwin_get_active_config_descriptor,
2007 .get_config_descriptor = darwin_get_config_descriptor,
2008 .hotplug_poll = darwin_hotplug_poll,
2010 .open = darwin_open,
2011 .close = darwin_close,
2012 .get_configuration = darwin_get_configuration,
2013 .set_configuration = darwin_set_configuration,
2014 .claim_interface = darwin_claim_interface,
2015 .release_interface = darwin_release_interface,
2017 .set_interface_altsetting = darwin_set_interface_altsetting,
2018 .clear_halt = darwin_clear_halt,
2019 .reset_device = darwin_reset_device,
2021 #if InterfaceVersion >= 550
2022 .alloc_streams = darwin_alloc_streams,
2023 .free_streams = darwin_free_streams,
2026 .kernel_driver_active = darwin_kernel_driver_active,
2027 .detach_kernel_driver = darwin_detach_kernel_driver,
2028 .attach_kernel_driver = darwin_attach_kernel_driver,
2030 .destroy_device = darwin_destroy_device,
2032 .submit_transfer = darwin_submit_transfer,
2033 .cancel_transfer = darwin_cancel_transfer,
2034 .clear_transfer_priv = darwin_clear_transfer_priv,
2036 .handle_transfer_completion = darwin_handle_transfer_completion,
2038 .clock_gettime = darwin_clock_gettime,
2040 .device_priv_size = sizeof(struct darwin_device_priv),
2041 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
2042 .transfer_priv_size = sizeof(struct darwin_transfer_priv),