1 /* -*- Mode: C; indent-tabs-mode:nil -*- */
3 * darwin backend for libusb 1.0
4 * Copyright © 2008-2017 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 <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 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
41 #include <objc/objc-auto.h>
44 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 101200
45 /* Apple deprecated the darwin atomics in 10.12 in favor of C11 atomics */
46 #include <stdatomic.h>
47 #define libusb_darwin_atomic_fetch_add(x, y) atomic_fetch_add(x, y)
49 _Atomic int32_t initCount = ATOMIC_VAR_INIT(0);
51 /* use darwin atomics if the target is older than 10.12 */
52 #include <libkern/OSAtomic.h>
54 /* OSAtomicAdd32Barrier returns the new value */
55 #define libusb_darwin_atomic_fetch_add(x, y) (OSAtomicAdd32Barrier(y, x) - y)
57 static volatile int32_t initCount = 0;
61 /* On 10.12 and later, use newly available clock_*() functions */
62 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 101200
63 #define OSX_USE_CLOCK_GETTIME 1
65 #define OSX_USE_CLOCK_GETTIME 0
68 #include "darwin_usb.h"
70 /* async event thread */
71 static pthread_mutex_t libusb_darwin_at_mutex = PTHREAD_MUTEX_INITIALIZER;
72 static pthread_cond_t libusb_darwin_at_cond = PTHREAD_COND_INITIALIZER;
74 static pthread_once_t darwin_init_once = PTHREAD_ONCE_INIT;
76 #if !OSX_USE_CLOCK_GETTIME
77 static clock_serv_t clock_realtime;
78 static clock_serv_t clock_monotonic;
81 static CFRunLoopRef libusb_darwin_acfl = NULL; /* event cf loop */
82 static CFRunLoopSourceRef libusb_darwin_acfls = NULL; /* shutdown signal for event cf loop */
84 static usbi_mutex_t darwin_cached_devices_lock = PTHREAD_MUTEX_INITIALIZER;
85 static struct list_head darwin_cached_devices = {&darwin_cached_devices, &darwin_cached_devices};
86 static const char *darwin_device_class = kIOUSBDeviceClassName;
88 #define DARWIN_CACHED_DEVICE(a) ((struct darwin_cached_device *) (((struct darwin_device_priv *)((a)->os_priv))->dev))
90 /* async event thread */
91 static pthread_t libusb_darwin_at;
93 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
94 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
95 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
96 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
97 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
99 static int darwin_scan_devices(struct libusb_context *ctx);
100 static int process_new_device (struct libusb_context *ctx, io_service_t service);
102 #if defined(ENABLE_LOGGING)
103 static const char *darwin_error_str (int result) {
104 static char string_buffer[50];
106 case kIOReturnSuccess:
108 case kIOReturnNotOpen:
109 return "device not opened for exclusive access";
110 case kIOReturnNoDevice:
111 return "no connection to an IOService";
112 case kIOUSBNoAsyncPortErr:
113 return "no async port has been opened for interface";
114 case kIOReturnExclusiveAccess:
115 return "another process has device opened for exclusive access";
116 case kIOUSBPipeStalled:
117 return "pipe is stalled";
119 return "could not establish a connection to the Darwin kernel";
120 case kIOUSBTransactionTimeout:
121 return "transaction timed out";
122 case kIOReturnBadArgument:
123 return "invalid argument";
124 case kIOReturnAborted:
125 return "transaction aborted";
126 case kIOReturnNotResponding:
127 return "device not responding";
128 case kIOReturnOverrun:
129 return "data overrun";
130 case kIOReturnCannotWire:
131 return "physical memory can not be wired down";
132 case kIOReturnNoResources:
133 return "out of resources";
134 case kIOUSBHighSpeedSplitError:
135 return "high speed split error";
137 snprintf(string_buffer, sizeof(string_buffer), "unknown error (0x%x)", result);
138 return string_buffer;
143 static int darwin_to_libusb (int result) {
145 case kIOReturnUnderrun:
146 case kIOReturnSuccess:
147 return LIBUSB_SUCCESS;
148 case kIOReturnNotOpen:
149 case kIOReturnNoDevice:
150 return LIBUSB_ERROR_NO_DEVICE;
151 case kIOReturnExclusiveAccess:
152 return LIBUSB_ERROR_ACCESS;
153 case kIOUSBPipeStalled:
154 return LIBUSB_ERROR_PIPE;
155 case kIOReturnBadArgument:
156 return LIBUSB_ERROR_INVALID_PARAM;
157 case kIOUSBTransactionTimeout:
158 return LIBUSB_ERROR_TIMEOUT;
159 case kIOReturnNotResponding:
160 case kIOReturnAborted:
162 case kIOUSBNoAsyncPortErr:
164 return LIBUSB_ERROR_OTHER;
168 /* this function must be called with the darwin_cached_devices_lock held */
169 static void darwin_deref_cached_device(struct darwin_cached_device *cached_dev) {
170 cached_dev->refcount--;
171 /* free the device and remove it from the cache */
172 if (0 == cached_dev->refcount) {
173 list_del(&cached_dev->list);
175 (*(cached_dev->device))->Release(cached_dev->device);
180 static void darwin_ref_cached_device(struct darwin_cached_device *cached_dev) {
181 cached_dev->refcount++;
184 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) {
185 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
187 /* current interface */
188 struct darwin_interface *cInterface;
192 usbi_dbg ("converting ep address 0x%02x to pipeRef and interface", ep);
194 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
195 cInterface = &priv->interfaces[iface];
197 if (dev_handle->claimed_interfaces & (1 << iface)) {
198 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
199 if (cInterface->endpoint_addrs[i] == ep) {
206 *interface_out = cInterface;
208 usbi_dbg ("pipe %d on interface %d matches", *pipep, iface);
215 /* No pipe found with the correct endpoint address */
216 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
218 return LIBUSB_ERROR_NOT_FOUND;
221 static int usb_setup_device_iterator (io_iterator_t *deviceIterator, UInt32 location) {
222 CFMutableDictionaryRef matchingDict = IOServiceMatching(darwin_device_class);
225 return kIOReturnError;
228 CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
229 &kCFTypeDictionaryKeyCallBacks,
230 &kCFTypeDictionaryValueCallBacks);
232 if (propertyMatchDict) {
233 /* there are no unsigned CFNumber types so treat the value as signed. the os seems to do this
234 internally (CFNumberType of locationID is 3) */
235 CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberSInt32Type, &location);
237 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
238 /* release our reference to the CFNumber (CFDictionarySetValue retains it) */
239 CFRelease (locationCF);
241 CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
242 /* release out reference to the CFMutableDictionaryRef (CFDictionarySetValue retains it) */
243 CFRelease (propertyMatchDict);
245 /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
248 return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator);
251 /* Returns 1 on success, 0 on failure. */
252 static int get_ioregistry_value_number (io_service_t service, CFStringRef property, CFNumberType type, void *p) {
253 CFTypeRef cfNumber = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
257 if (CFGetTypeID(cfNumber) == CFNumberGetTypeID()) {
258 ret = CFNumberGetValue(cfNumber, type, p);
261 CFRelease (cfNumber);
267 static int get_ioregistry_value_data (io_service_t service, CFStringRef property, ssize_t size, void *p) {
268 CFTypeRef cfData = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
272 if (CFGetTypeID (cfData) == CFDataGetTypeID ()) {
273 CFIndex length = CFDataGetLength (cfData);
278 CFDataGetBytes (cfData, CFRangeMake(0, size), p);
288 static usb_device_t **darwin_device_from_service (io_service_t service)
290 io_cf_plugin_ref_t *plugInInterface = NULL;
291 usb_device_t **device;
292 kern_return_t result;
295 result = IOCreatePlugInInterfaceForService(service, kIOUSBDeviceUserClientTypeID,
296 kIOCFPlugInInterfaceID, &plugInInterface,
299 if (kIOReturnSuccess != result || !plugInInterface) {
300 usbi_dbg ("could not set up plugin for service: %s", darwin_error_str (result));
304 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
306 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
307 (*plugInInterface)->Release (plugInInterface);
312 static void darwin_devices_attached (void *ptr, io_iterator_t add_devices) {
314 struct libusb_context *ctx;
315 io_service_t service;
317 usbi_mutex_lock(&active_contexts_lock);
319 while ((service = IOIteratorNext(add_devices))) {
320 /* add this device to each active context's device list */
321 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
322 process_new_device (ctx, service);
325 IOObjectRelease(service);
328 usbi_mutex_unlock(&active_contexts_lock);
331 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
333 struct libusb_device *dev = NULL;
334 struct libusb_context *ctx;
335 struct darwin_cached_device *old_device;
341 usbi_mutex_lock(&active_contexts_lock);
343 while ((device = IOIteratorNext (rem_devices)) != 0) {
344 /* get the location from the i/o registry */
345 ret = get_ioregistry_value_number (device, CFSTR("sessionID"), kCFNumberSInt64Type, &session);
346 IOObjectRelease (device);
350 /* we need to match darwin_ref_cached_device call made in darwin_get_cached_device function
351 otherwise no cached device will ever get freed */
352 usbi_mutex_lock(&darwin_cached_devices_lock);
353 list_for_each_entry(old_device, &darwin_cached_devices, list, struct darwin_cached_device) {
354 if (old_device->session == session) {
355 darwin_deref_cached_device (old_device);
359 usbi_mutex_unlock(&darwin_cached_devices_lock);
361 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
362 usbi_dbg ("notifying context %p of device disconnect", ctx);
364 dev = usbi_get_device_by_session_id(ctx, (unsigned long) session);
366 /* signal the core that this device has been disconnected. the core will tear down this device
367 when the reference count reaches 0 */
368 usbi_disconnect_device(dev);
369 libusb_unref_device(dev);
374 usbi_mutex_unlock(&active_contexts_lock);
377 static void darwin_hotplug_poll (void)
379 /* not sure if 5 seconds will be too long/short but it should work ok */
380 mach_timespec_t timeout = {.tv_sec = 5, .tv_nsec = 0};
382 /* since a kernel thread may nodify the IOInterators used for
383 * hotplug notidication we can't just clear the iterators.
384 * instead just wait until all IOService providers are quiet */
385 (void) IOKitWaitQuiet (kIOMasterPortDefault, &timeout);
388 static void darwin_clear_iterator (io_iterator_t iter) {
391 while ((device = IOIteratorNext (iter)) != 0)
392 IOObjectRelease (device);
395 static void *darwin_event_thread_main (void *arg0) {
397 struct libusb_context *ctx = (struct libusb_context *)arg0;
398 CFRunLoopRef runloop;
400 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
401 /* Set this thread's name, so it can be seen in the debugger
402 and crash reports. */
403 pthread_setname_np ("org.libusb.device-hotplug");
406 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
407 /* Tell the Objective-C garbage collector about this thread.
408 This is required because, unlike NSThreads, pthreads are
409 not automatically registered. Although we don't use
410 Objective-C, we use CoreFoundation, which does.
411 Garbage collection support was entirely removed in 10.12,
412 so don't bother there. */
413 objc_registerThreadWithCollector();
416 /* hotplug (device arrival/removal) sources */
417 CFRunLoopSourceContext libusb_shutdown_cfsourcectx;
418 CFRunLoopSourceRef libusb_notification_cfsource;
419 io_notification_port_t libusb_notification_port;
420 io_iterator_t libusb_rem_device_iterator;
421 io_iterator_t libusb_add_device_iterator;
423 usbi_dbg ("creating hotplug event source");
425 runloop = CFRunLoopGetCurrent ();
428 /* add the shutdown cfsource to the run loop */
429 memset(&libusb_shutdown_cfsourcectx, 0, sizeof(libusb_shutdown_cfsourcectx));
430 libusb_shutdown_cfsourcectx.info = runloop;
431 libusb_shutdown_cfsourcectx.perform = (void (*)(void *))CFRunLoopStop;
432 libusb_darwin_acfls = CFRunLoopSourceCreate(NULL, 0, &libusb_shutdown_cfsourcectx);
433 CFRunLoopAddSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
435 /* add the notification port to the run loop */
436 libusb_notification_port = IONotificationPortCreate (kIOMasterPortDefault);
437 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
438 CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
440 /* create notifications for removed devices */
441 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
442 IOServiceMatching(darwin_device_class),
443 darwin_devices_detached,
444 ctx, &libusb_rem_device_iterator);
446 if (kresult != kIOReturnSuccess) {
447 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
452 /* create notifications for attached devices */
453 kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
454 IOServiceMatching(darwin_device_class),
455 darwin_devices_attached,
456 ctx, &libusb_add_device_iterator);
458 if (kresult != kIOReturnSuccess) {
459 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
465 darwin_clear_iterator (libusb_rem_device_iterator);
466 darwin_clear_iterator (libusb_add_device_iterator);
468 usbi_dbg ("darwin event thread ready to receive events");
470 /* signal the main thread that the hotplug runloop has been created. */
471 pthread_mutex_lock (&libusb_darwin_at_mutex);
472 libusb_darwin_acfl = runloop;
473 pthread_cond_signal (&libusb_darwin_at_cond);
474 pthread_mutex_unlock (&libusb_darwin_at_mutex);
476 /* run the runloop */
479 usbi_dbg ("darwin event thread exiting");
481 /* remove the notification cfsource */
482 CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
484 /* remove the shutdown cfsource */
485 CFRunLoopRemoveSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
487 /* delete notification port */
488 IONotificationPortDestroy (libusb_notification_port);
490 /* delete iterators */
491 IOObjectRelease (libusb_rem_device_iterator);
492 IOObjectRelease (libusb_add_device_iterator);
494 CFRelease (libusb_darwin_acfls);
497 libusb_darwin_acfls = NULL;
498 libusb_darwin_acfl = NULL;
503 /* cleanup function to destroy cached devices */
504 static void __attribute__((destructor)) _darwin_finalize(void) {
505 struct darwin_cached_device *dev, *next;
507 usbi_mutex_lock(&darwin_cached_devices_lock);
508 list_for_each_entry_safe(dev, next, &darwin_cached_devices, list, struct darwin_cached_device) {
509 darwin_deref_cached_device(dev);
511 usbi_mutex_unlock(&darwin_cached_devices_lock);
514 static void darwin_check_version (void) {
515 /* adjust for changes in the USB stack in xnu 15 */
516 int sysctl_args[] = {CTL_KERN, KERN_OSRELEASE};
518 char version_string[256] = {'\0',};
521 sysctl(sysctl_args, 2, version_string, &length, NULL, 0);
524 version = strtol (version_string, NULL, 10);
525 if (0 == errno && version >= 15) {
526 darwin_device_class = "IOUSBHostDevice";
530 static int darwin_init(struct libusb_context *ctx) {
533 rc = pthread_once (&darwin_init_once, darwin_check_version);
535 return LIBUSB_ERROR_OTHER;
538 rc = darwin_scan_devices (ctx);
539 if (LIBUSB_SUCCESS != rc) {
543 if (libusb_darwin_atomic_fetch_add (&initCount, 1) == 0) {
544 #if !OSX_USE_CLOCK_GETTIME
545 /* create the clocks that will be used if clock_gettime() is not available */
546 host_name_port_t host_self;
548 host_self = mach_host_self();
549 host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
550 host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
551 mach_port_deallocate(mach_task_self(), host_self);
554 pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, ctx);
556 pthread_mutex_lock (&libusb_darwin_at_mutex);
557 while (!libusb_darwin_acfl)
558 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
559 pthread_mutex_unlock (&libusb_darwin_at_mutex);
565 static void darwin_exit (struct libusb_context *ctx) {
567 if (libusb_darwin_atomic_fetch_add (&initCount, -1) == 1) {
568 #if !OSX_USE_CLOCK_GETTIME
569 mach_port_deallocate(mach_task_self(), clock_realtime);
570 mach_port_deallocate(mach_task_self(), clock_monotonic);
573 /* stop the event runloop and wait for the thread to terminate. */
574 CFRunLoopSourceSignal(libusb_darwin_acfls);
575 CFRunLoopWakeUp (libusb_darwin_acfl);
576 pthread_join (libusb_darwin_at, NULL);
580 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
581 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
583 /* return cached copy */
584 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
591 static int get_configuration_index (struct libusb_device *dev, int config_value) {
592 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
594 IOUSBConfigurationDescriptorPtr desc;
597 /* is there a simpler way to determine the index? */
598 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
599 if (kresult != kIOReturnSuccess)
600 return darwin_to_libusb (kresult);
602 for (i = 0 ; i < numConfig ; i++) {
603 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
605 if (desc->bConfigurationValue == config_value)
609 /* configuration not found */
610 return LIBUSB_ERROR_NOT_FOUND;
613 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
614 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
617 if (0 == priv->active_config)
618 return LIBUSB_ERROR_NOT_FOUND;
620 config_index = get_configuration_index (dev, priv->active_config);
621 if (config_index < 0)
624 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
627 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
628 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
629 IOUSBConfigurationDescriptorPtr desc;
633 if (!priv || !priv->device)
634 return LIBUSB_ERROR_OTHER;
636 kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
637 if (kresult == kIOReturnSuccess) {
638 /* copy descriptor */
639 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
640 len = libusb_le16_to_cpu(desc->wTotalLength);
642 memmove (buffer, desc, len);
644 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
648 ret = darwin_to_libusb (kresult);
649 if (ret != LIBUSB_SUCCESS)
655 /* check whether the os has configured the device */
656 static int darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) {
657 usb_device_t **darwin_device = dev->device;
659 IOUSBConfigurationDescriptorPtr configDesc;
660 IOUSBFindInterfaceRequest request;
661 kern_return_t kresult;
662 io_iterator_t interface_iterator;
663 io_service_t firstInterface;
665 if (dev->dev_descriptor.bNumConfigurations < 1) {
666 usbi_err (ctx, "device has no configurations");
667 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
670 /* checking the configuration of a root hub simulation takes ~1 s in 10.11. the device is
672 if (0x05ac == dev->dev_descriptor.idVendor && 0x8005 == dev->dev_descriptor.idProduct) {
673 usbi_dbg ("ignoring configuration on root hub simulation");
674 dev->active_config = 0;
678 /* find the first configuration */
679 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
680 dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
682 /* check if the device is already configured. there is probably a better way than iterating over the
683 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
684 might lock up on the device request) */
686 /* Setup the Interface Request */
687 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
688 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
689 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
690 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
692 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
694 return darwin_to_libusb (kresult);
697 firstInterface = IOIteratorNext(interface_iterator);
699 /* done with the interface iterator */
700 IOObjectRelease(interface_iterator);
702 if (firstInterface) {
703 IOObjectRelease (firstInterface);
705 /* device is configured */
706 if (dev->dev_descriptor.bNumConfigurations == 1)
707 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
708 dev->active_config = dev->first_config;
710 /* devices with more than one configuration should work with GetConfiguration */
711 (*darwin_device)->GetConfiguration (darwin_device, &dev->active_config);
714 dev->active_config = 0;
716 usbi_dbg ("active config: %u, first config: %u", dev->active_config, dev->first_config);
721 static int darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
722 IOUSBDevRequestTO req;
724 memset (buffer, 0, buffer_size);
726 /* Set up request for descriptor/ */
727 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
728 req.bRequest = kUSBRqGetDescriptor;
729 req.wValue = desc << 8;
730 req.wIndex = desc_index;
731 req.wLength = buffer_size;
733 req.noDataTimeout = 20;
734 req.completionTimeout = 100;
736 return (*device)->DeviceRequestTO (device, &req);
739 static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct darwin_cached_device *dev) {
740 usb_device_t **device = dev->device;
741 int retries = 1, delay = 30000;
742 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
746 UInt16 idProduct, idVendor;
748 dev->can_enumerate = 0;
750 (*device)->GetDeviceClass (device, &bDeviceClass);
751 (*device)->GetDeviceProduct (device, &idProduct);
752 (*device)->GetDeviceVendor (device, &idVendor);
754 /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
755 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
756 * to follow the spec as closely as possible, try opening the device */
757 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
760 /**** retrieve device descriptor ****/
761 ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &dev->dev_descriptor, sizeof(dev->dev_descriptor));
763 if (kIOReturnOverrun == ret && kUSBDeviceDesc == dev->dev_descriptor.bDescriptorType)
764 /* received an overrun error but we still received a device descriptor */
765 ret = kIOReturnSuccess;
767 if (kIOUSBVendorIDAppleComputer == idVendor) {
768 /* NTH: don't bother retrying or unsuspending Apple devices */
772 if (kIOReturnSuccess == ret && (0 == dev->dev_descriptor.bNumConfigurations ||
773 0 == dev->dev_descriptor.bcdUSB)) {
774 /* work around for incorrectly configured devices */
775 if (try_reconfigure && is_open) {
776 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
778 /* set the first configuration */
779 (*device)->SetConfiguration(device, 1);
781 /* don't try to reconfigure again */
785 ret = kIOUSBPipeStalled;
788 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
789 /* device may be suspended. unsuspend it and try again */
790 #if DeviceVersion >= 320
793 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
794 (void)(*device)->GetUSBDeviceInformation (device, &info);
796 /* note that the device was suspended */
797 if (info & (1 << kUSBInformationDeviceIsSuspendedBit) || 0 == info)
802 /* try to unsuspend the device */
803 ret2 = (*device)->USBDeviceSuspend (device, 0);
804 if (kIOReturnSuccess != ret2) {
805 /* prevent log spew from poorly behaving devices. this indicates the
806 os actually had trouble communicating with the device */
807 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
815 if (kIOReturnSuccess != ret) {
816 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
817 /* sleep for a little while before trying again */
818 nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000UL}, NULL);
820 } while (kIOReturnSuccess != ret && retries--);
823 /* resuspend the device */
824 (void)(*device)->USBDeviceSuspend (device, 1);
827 (void) (*device)->USBDeviceClose (device);
829 if (ret != kIOReturnSuccess) {
830 /* a debug message was already printed out for this error */
831 if (LIBUSB_CLASS_HUB == bDeviceClass)
832 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
833 idVendor, idProduct, darwin_error_str (ret), ret);
835 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
836 idVendor, idProduct, darwin_error_str (ret), ret);
837 return darwin_to_libusb (ret);
840 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
841 if (libusb_le16_to_cpu (dev->dev_descriptor.idProduct) != idProduct) {
842 /* not a valid device */
843 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
844 idProduct, libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
845 return LIBUSB_ERROR_NO_DEVICE;
848 usbi_dbg ("cached device descriptor:");
849 usbi_dbg (" bDescriptorType: 0x%02x", dev->dev_descriptor.bDescriptorType);
850 usbi_dbg (" bcdUSB: 0x%04x", dev->dev_descriptor.bcdUSB);
851 usbi_dbg (" bDeviceClass: 0x%02x", dev->dev_descriptor.bDeviceClass);
852 usbi_dbg (" bDeviceSubClass: 0x%02x", dev->dev_descriptor.bDeviceSubClass);
853 usbi_dbg (" bDeviceProtocol: 0x%02x", dev->dev_descriptor.bDeviceProtocol);
854 usbi_dbg (" bMaxPacketSize0: 0x%02x", dev->dev_descriptor.bMaxPacketSize0);
855 usbi_dbg (" idVendor: 0x%04x", dev->dev_descriptor.idVendor);
856 usbi_dbg (" idProduct: 0x%04x", dev->dev_descriptor.idProduct);
857 usbi_dbg (" bcdDevice: 0x%04x", dev->dev_descriptor.bcdDevice);
858 usbi_dbg (" iManufacturer: 0x%02x", dev->dev_descriptor.iManufacturer);
859 usbi_dbg (" iProduct: 0x%02x", dev->dev_descriptor.iProduct);
860 usbi_dbg (" iSerialNumber: 0x%02x", dev->dev_descriptor.iSerialNumber);
861 usbi_dbg (" bNumConfigurations: 0x%02x", dev->dev_descriptor.bNumConfigurations);
863 dev->can_enumerate = 1;
865 return LIBUSB_SUCCESS;
868 static int get_device_port (io_service_t service, UInt8 *port) {
869 kern_return_t result;
873 if (get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, port)) {
877 result = IORegistryEntryGetParentEntry (service, kIOServicePlane, &parent);
878 if (kIOReturnSuccess == result) {
879 ret = get_ioregistry_value_data (parent, CFSTR("port"), 1, port);
880 IOObjectRelease (parent);
886 static int get_device_parent_sessionID(io_service_t service, UInt64 *parent_sessionID) {
887 kern_return_t result;
890 /* Walk up the tree in the IOService plane until we find a parent that has a sessionID */
892 while((result = IORegistryEntryGetParentEntry (parent, kIOServicePlane, &parent)) == kIOReturnSuccess) {
893 if (get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, parent_sessionID)) {
899 /* We ran out of parents */
903 static int darwin_get_cached_device(struct libusb_context *ctx, io_service_t service,
904 struct darwin_cached_device **cached_out) {
905 struct darwin_cached_device *new_device;
906 UInt64 sessionID = 0, parent_sessionID = 0;
907 int ret = LIBUSB_SUCCESS;
908 usb_device_t **device;
911 /* get some info from the io registry */
912 (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
913 if (!get_device_port (service, &port)) {
914 usbi_dbg("could not get connected port number");
917 usbi_dbg("finding cached device for sessionID 0x%" PRIx64, sessionID);
919 if (get_device_parent_sessionID(service, &parent_sessionID)) {
920 usbi_dbg("parent sessionID: 0x%" PRIx64, parent_sessionID);
923 usbi_mutex_lock(&darwin_cached_devices_lock);
927 list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) {
928 usbi_dbg("matching sessionID 0x%" PRIx64 " against cached device with sessionID 0x%" PRIx64, sessionID, new_device->session);
929 if (new_device->session == sessionID) {
930 usbi_dbg("using cached device for device");
931 *cached_out = new_device;
939 usbi_dbg("caching new device with sessionID 0x%" PRIx64, sessionID);
941 device = darwin_device_from_service (service);
943 ret = LIBUSB_ERROR_NO_DEVICE;
947 new_device = calloc (1, sizeof (*new_device));
949 ret = LIBUSB_ERROR_NO_MEM;
953 /* add this device to the cached device list */
954 list_add(&new_device->list, &darwin_cached_devices);
956 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
958 /* keep a reference to this device */
959 darwin_ref_cached_device(new_device);
961 new_device->device = device;
962 new_device->session = sessionID;
963 (*device)->GetLocationID (device, &new_device->location);
964 new_device->port = port;
965 new_device->parent_session = parent_sessionID;
967 /* cache the device descriptor */
968 ret = darwin_cache_device_descriptor(ctx, new_device);
972 if (new_device->can_enumerate) {
973 snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address,
974 new_device->dev_descriptor.idVendor, new_device->dev_descriptor.idProduct,
975 new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass);
979 usbi_mutex_unlock(&darwin_cached_devices_lock);
981 /* keep track of devices regardless of if we successfully enumerate them to
982 prevent them from being enumerated multiple times */
984 *cached_out = new_device;
989 static int process_new_device (struct libusb_context *ctx, io_service_t service) {
990 struct darwin_device_priv *priv;
991 struct libusb_device *dev = NULL;
992 struct darwin_cached_device *cached_device;
997 ret = darwin_get_cached_device (ctx, service, &cached_device);
999 if (ret < 0 || !cached_device->can_enumerate) {
1003 /* check current active configuration (and cache the first configuration value--
1004 which may be used by claim_interface) */
1005 ret = darwin_check_configuration (ctx, cached_device);
1009 usbi_dbg ("allocating new device in context %p for with session 0x%" PRIx64,
1010 ctx, cached_device->session);
1012 dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
1014 return LIBUSB_ERROR_NO_MEM;
1017 priv = (struct darwin_device_priv *)dev->os_priv;
1019 priv->dev = cached_device;
1020 darwin_ref_cached_device (priv->dev);
1022 if (cached_device->parent_session > 0) {
1023 dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session);
1025 dev->parent_dev = NULL;
1027 dev->port_number = cached_device->port;
1028 dev->bus_number = cached_device->location >> 24;
1029 dev->device_address = cached_device->address;
1031 (*(priv->dev->device))->GetDeviceSpeed (priv->dev->device, &devSpeed);
1034 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
1035 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
1036 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
1037 #if DeviceVersion >= 500
1038 case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
1040 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101200
1041 case kUSBDeviceSpeedSuperPlus: dev->speed = LIBUSB_SPEED_SUPER_PLUS; break;
1044 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
1047 ret = usbi_sanitize_device (dev);
1051 usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
1052 dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
1056 usbi_connect_device (dev);
1058 libusb_unref_device (dev);
1064 static int darwin_scan_devices(struct libusb_context *ctx) {
1065 io_iterator_t deviceIterator;
1066 io_service_t service;
1067 kern_return_t kresult;
1069 kresult = usb_setup_device_iterator (&deviceIterator, 0);
1070 if (kresult != kIOReturnSuccess)
1071 return darwin_to_libusb (kresult);
1073 while ((service = IOIteratorNext (deviceIterator))) {
1074 (void) process_new_device (ctx, service);
1076 IOObjectRelease(service);
1079 IOObjectRelease(deviceIterator);
1084 static int darwin_open (struct libusb_device_handle *dev_handle) {
1085 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1086 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1089 if (0 == dpriv->open_count) {
1090 /* try to open the device */
1091 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
1092 if (kresult != kIOReturnSuccess) {
1093 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
1095 if (kIOReturnExclusiveAccess != kresult) {
1096 return darwin_to_libusb (kresult);
1099 /* it is possible to perform some actions on a device that is not open so do not return an error */
1105 /* create async event source */
1106 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
1107 if (kresult != kIOReturnSuccess) {
1108 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
1110 if (priv->is_open) {
1111 (*(dpriv->device))->USBDeviceClose (dpriv->device);
1116 return darwin_to_libusb (kresult);
1119 CFRetain (libusb_darwin_acfl);
1121 /* add the cfSource to the aync run loop */
1122 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
1125 /* device opened successfully */
1126 dpriv->open_count++;
1128 usbi_dbg ("device open for access");
1133 static void darwin_close (struct libusb_device_handle *dev_handle) {
1134 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1135 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1139 if (dpriv->open_count == 0) {
1140 /* something is probably very wrong if this is the case */
1141 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!");
1145 dpriv->open_count--;
1147 /* make sure all interfaces are released */
1148 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1149 if (dev_handle->claimed_interfaces & (1 << i))
1150 libusb_release_interface (dev_handle, i);
1152 if (0 == dpriv->open_count) {
1153 /* delete the device's async event source */
1154 if (priv->cfSource) {
1155 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
1156 CFRelease (priv->cfSource);
1157 priv->cfSource = NULL;
1158 CFRelease (libusb_darwin_acfl);
1161 if (priv->is_open) {
1162 /* close the device */
1163 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
1165 /* Log the fact that we had a problem closing the file, however failing a
1166 * close isn't really an error, so return success anyway */
1167 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
1173 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
1174 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1176 *config = (int) dpriv->active_config;
1181 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
1182 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1186 /* Setting configuration will invalidate the interface, so we need
1187 to reclaim it. First, dispose of existing interfaces, if any. */
1188 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1189 if (dev_handle->claimed_interfaces & (1 << i))
1190 darwin_release_interface (dev_handle, i);
1192 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
1193 if (kresult != kIOReturnSuccess)
1194 return darwin_to_libusb (kresult);
1196 /* Reclaim any interfaces. */
1197 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1198 if (dev_handle->claimed_interfaces & (1 << i))
1199 darwin_claim_interface (dev_handle, i);
1201 dpriv->active_config = config;
1206 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
1207 IOUSBFindInterfaceRequest request;
1208 kern_return_t kresult;
1209 io_iterator_t interface_iterator;
1210 UInt8 bInterfaceNumber;
1213 *usbInterfacep = IO_OBJECT_NULL;
1215 /* Setup the Interface Request */
1216 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1217 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1218 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1219 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1221 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1225 while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1226 /* find the interface number */
1227 ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
1230 if (ret && bInterfaceNumber == ifc) {
1234 (void) IOObjectRelease (*usbInterfacep);
1237 /* done with the interface iterator */
1238 IOObjectRelease(interface_iterator);
1243 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
1244 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1246 /* current interface */
1247 struct darwin_interface *cInterface = &priv->interfaces[iface];
1249 kern_return_t kresult;
1251 UInt8 numep, direction, number;
1252 UInt8 dont_care1, dont_care3;
1256 usbi_dbg ("building table of endpoints.");
1258 /* retrieve the total number of endpoints on this interface */
1259 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1261 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1262 return darwin_to_libusb (kresult);
1265 /* iterate through pipe references */
1266 for (int i = 1 ; i <= numep ; i++) {
1267 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1268 &dont_care2, &dont_care3);
1270 if (kresult != kIOReturnSuccess) {
1271 /* probably a buggy device. try to get the endpoint address from the descriptors */
1272 struct libusb_config_descriptor *config;
1273 const struct libusb_endpoint_descriptor *endpoint_desc;
1276 kresult = (*(cInterface->interface))->GetAlternateSetting (cInterface->interface, &alt_setting);
1278 usbi_err (HANDLE_CTX (dev_handle), "can't get alternate setting for interface");
1279 return darwin_to_libusb (kresult);
1282 rc = libusb_get_active_config_descriptor (dev_handle->dev, &config);
1283 if (LIBUSB_SUCCESS != rc) {
1287 endpoint_desc = config->interface[iface].altsetting[alt_setting].endpoint + i - 1;
1289 cInterface->endpoint_addrs[i - 1] = endpoint_desc->bEndpointAddress;
1291 cInterface->endpoint_addrs[i - 1] = (((kUSBIn == direction) << kUSBRqDirnShift) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1294 usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, cInterface->endpoint_addrs[i - 1] >> kUSBRqDirnShift,
1295 cInterface->endpoint_addrs[i - 1] & LIBUSB_ENDPOINT_ADDRESS_MASK);
1298 cInterface->num_endpoints = numep;
1303 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1304 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1305 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1306 io_service_t usbInterface = IO_OBJECT_NULL;
1308 IOCFPlugInInterface **plugInInterface = NULL;
1311 /* current interface */
1312 struct darwin_interface *cInterface = &priv->interfaces[iface];
1314 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1315 if (kresult != kIOReturnSuccess)
1316 return darwin_to_libusb (kresult);
1318 /* make sure we have an interface */
1319 if (!usbInterface && dpriv->first_config != 0) {
1320 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1322 /* set the configuration */
1323 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1324 if (kresult != LIBUSB_SUCCESS) {
1325 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1329 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1331 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1332 return darwin_to_libusb (kresult);
1336 if (!usbInterface) {
1337 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1338 return LIBUSB_ERROR_NOT_FOUND;
1341 /* get an interface to the device's interface */
1342 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1343 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1345 /* ignore release error */
1346 (void)IOObjectRelease (usbInterface);
1349 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1350 return darwin_to_libusb (kresult);
1353 if (!plugInInterface) {
1354 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1355 return LIBUSB_ERROR_NOT_FOUND;
1358 /* Do the actual claim */
1359 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1360 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1361 (LPVOID)&cInterface->interface);
1362 /* We no longer need the intermediate plug-in */
1363 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1364 (*plugInInterface)->Release (plugInInterface);
1365 if (kresult || !cInterface->interface) {
1366 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1367 return darwin_to_libusb (kresult);
1370 /* claim the interface */
1371 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1373 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1374 return darwin_to_libusb (kresult);
1377 /* update list of endpoints */
1378 kresult = get_endpoints (dev_handle, iface);
1380 /* this should not happen */
1381 darwin_release_interface (dev_handle, iface);
1382 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1386 cInterface->cfSource = NULL;
1388 /* create async event source */
1389 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1390 if (kresult != kIOReturnSuccess) {
1391 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1393 /* can't continue without an async event source */
1394 (void)darwin_release_interface (dev_handle, iface);
1396 return darwin_to_libusb (kresult);
1399 /* add the cfSource to the async thread's run loop */
1400 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1402 usbi_dbg ("interface opened");
1407 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1408 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1411 /* current interface */
1412 struct darwin_interface *cInterface = &priv->interfaces[iface];
1414 /* Check to see if an interface is open */
1415 if (!cInterface->interface)
1416 return LIBUSB_SUCCESS;
1418 /* clean up endpoint data */
1419 cInterface->num_endpoints = 0;
1421 /* delete the interface's async event source */
1422 if (cInterface->cfSource) {
1423 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1424 CFRelease (cInterface->cfSource);
1427 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1429 usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1431 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1432 if (kresult != kIOReturnSuccess)
1433 usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1435 cInterface->interface = (usb_interface_t **) IO_OBJECT_NULL;
1437 return darwin_to_libusb (kresult);
1440 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1441 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1444 /* current interface */
1445 struct darwin_interface *cInterface = &priv->interfaces[iface];
1447 if (!cInterface->interface)
1448 return LIBUSB_ERROR_NO_DEVICE;
1450 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1451 if (kresult != kIOReturnSuccess)
1452 darwin_reset_device (dev_handle);
1454 /* update list of endpoints */
1455 kresult = get_endpoints (dev_handle, iface);
1457 /* this should not happen */
1458 darwin_release_interface (dev_handle, iface);
1459 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1463 return darwin_to_libusb (kresult);
1466 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1467 /* current interface */
1468 struct darwin_interface *cInterface;
1472 /* determine the interface/endpoint to use */
1473 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, NULL, &cInterface) != 0) {
1474 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1476 return LIBUSB_ERROR_NOT_FOUND;
1479 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1480 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1482 usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1484 return darwin_to_libusb (kresult);
1487 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1488 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1489 IOUSBDeviceDescriptor descriptor;
1490 IOUSBConfigurationDescriptorPtr cached_configuration;
1491 IOUSBConfigurationDescriptor configuration;
1492 bool reenumerate = false;
1496 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1498 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1499 return darwin_to_libusb (kresult);
1503 usbi_dbg ("darwin/reset_device: checking if device descriptor changed");
1505 /* ignore return code. if we can't get a descriptor it might be worthwhile re-enumerating anway */
1506 (void) darwin_request_descriptor (dpriv->device, kUSBDeviceDesc, 0, &descriptor, sizeof (descriptor));
1508 /* check if the device descriptor has changed */
1509 if (0 != memcmp (&dpriv->dev_descriptor, &descriptor, sizeof (descriptor))) {
1514 /* check if any configuration descriptor has changed */
1515 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1516 usbi_dbg ("darwin/reset_device: checking if configuration descriptor %d changed", i);
1518 (void) darwin_request_descriptor (dpriv->device, kUSBConfDesc, i, &configuration, sizeof (configuration));
1519 (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1521 if (!cached_configuration || 0 != memcmp (cached_configuration, &configuration, sizeof (configuration))) {
1529 usbi_dbg ("darwin/reset_device: device requires reenumeration");
1530 (void) (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
1531 return LIBUSB_ERROR_NOT_FOUND;
1534 usbi_dbg ("darwin/reset_device: device reset complete");
1536 return LIBUSB_SUCCESS;
1539 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1540 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1541 io_service_t usbInterface;
1545 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1547 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1549 return darwin_to_libusb (kresult);
1552 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1553 IOObjectRelease (usbInterface);
1565 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1566 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1569 return LIBUSB_ERROR_NOT_SUPPORTED;
1572 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1575 return LIBUSB_ERROR_NOT_SUPPORTED;
1578 static void darwin_destroy_device(struct libusb_device *dev) {
1579 struct darwin_device_priv *dpriv = (struct darwin_device_priv *) dev->os_priv;
1582 /* need to hold the lock in case this is the last reference to the device */
1583 usbi_mutex_lock(&darwin_cached_devices_lock);
1584 darwin_deref_cached_device (dpriv->dev);
1586 usbi_mutex_unlock(&darwin_cached_devices_lock);
1590 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1591 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1594 uint8_t transferType;
1595 /* None of the values below are used in libusbx for bulk transfers */
1596 uint8_t direction, number, interval, pipeRef;
1597 uint16_t maxPacketSize;
1599 struct darwin_interface *cInterface;
1601 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1602 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1604 return LIBUSB_ERROR_NOT_FOUND;
1607 ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1608 &transferType, &maxPacketSize, &interval);
1611 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1612 darwin_error_str(ret), ret);
1613 return darwin_to_libusb (ret);
1616 if (0 != (transfer->length % maxPacketSize)) {
1617 /* do not need a zero packet */
1618 transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1621 /* submit the request */
1622 /* timeouts are unavailable on interrupt endpoints */
1623 if (transferType == kUSBInterrupt) {
1624 if (IS_XFERIN(transfer))
1625 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1626 transfer->length, darwin_async_io_callback, itransfer);
1628 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1629 transfer->length, darwin_async_io_callback, itransfer);
1631 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1633 if (IS_XFERIN(transfer))
1634 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1635 transfer->length, transfer->timeout, transfer->timeout,
1636 darwin_async_io_callback, (void *)itransfer);
1638 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1639 transfer->length, transfer->timeout, transfer->timeout,
1640 darwin_async_io_callback, (void *)itransfer);
1644 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1645 darwin_error_str(ret), ret);
1647 return darwin_to_libusb (ret);
1650 #if InterfaceVersion >= 550
1651 static int submit_stream_transfer(struct usbi_transfer *itransfer) {
1652 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1653 struct darwin_interface *cInterface;
1657 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1658 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1660 return LIBUSB_ERROR_NOT_FOUND;
1663 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1665 if (IS_XFERIN(transfer))
1666 ret = (*(cInterface->interface))->ReadStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1667 transfer->buffer, transfer->length, transfer->timeout,
1668 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1670 ret = (*(cInterface->interface))->WriteStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1671 transfer->buffer, transfer->length, transfer->timeout,
1672 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1675 usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1676 darwin_error_str(ret), ret);
1678 return darwin_to_libusb (ret);
1682 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1683 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1684 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1687 uint8_t direction, number, interval, pipeRef, transferType;
1688 uint16_t maxPacketSize;
1690 AbsoluteTime atTime;
1693 struct darwin_interface *cInterface;
1695 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1696 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1697 free(tpriv->isoc_framelist);
1698 tpriv->isoc_framelist = NULL;
1701 if (!tpriv->isoc_framelist) {
1702 tpriv->num_iso_packets = transfer->num_iso_packets;
1703 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1704 if (!tpriv->isoc_framelist)
1705 return LIBUSB_ERROR_NO_MEM;
1708 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1709 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1710 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1712 /* determine the interface/endpoint to use */
1713 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1714 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1716 return LIBUSB_ERROR_NOT_FOUND;
1719 /* determine the properties of this endpoint and the speed of the device */
1720 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1721 &transferType, &maxPacketSize, &interval);
1723 /* Last but not least we need the bus frame number */
1724 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1726 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1727 free(tpriv->isoc_framelist);
1728 tpriv->isoc_framelist = NULL;
1730 return darwin_to_libusb (kresult);
1733 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1734 &transferType, &maxPacketSize, &interval);
1736 /* schedule for a frame a little in the future */
1739 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1740 frame = cInterface->frames[transfer->endpoint];
1742 /* submit the request */
1743 if (IS_XFERIN(transfer))
1744 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1745 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1748 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1749 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1752 if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
1754 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1));
1756 /* High/super speed */
1757 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1)) / 8;
1759 if (kresult != kIOReturnSuccess) {
1760 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1761 darwin_error_str(kresult));
1762 free (tpriv->isoc_framelist);
1763 tpriv->isoc_framelist = NULL;
1766 return darwin_to_libusb (kresult);
1769 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1770 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1771 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1772 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1773 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1777 memset(&tpriv->req, 0, sizeof(tpriv->req));
1779 /* IOUSBDeviceInterface expects the request in cpu endianness */
1780 tpriv->req.bmRequestType = setup->bmRequestType;
1781 tpriv->req.bRequest = setup->bRequest;
1782 /* these values should be in bus order from libusb_fill_control_setup */
1783 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1784 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1785 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1786 /* data is stored after the libusb control block */
1787 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1788 tpriv->req.completionTimeout = transfer->timeout;
1789 tpriv->req.noDataTimeout = transfer->timeout;
1791 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1793 /* all transfers in libusb-1.0 are async */
1795 if (transfer->endpoint) {
1796 struct darwin_interface *cInterface;
1799 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1800 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1802 return LIBUSB_ERROR_NOT_FOUND;
1805 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1807 /* control request on endpoint 0 */
1808 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1810 if (kresult != kIOReturnSuccess)
1811 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1813 return darwin_to_libusb (kresult);
1816 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1817 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1819 switch (transfer->type) {
1820 case LIBUSB_TRANSFER_TYPE_CONTROL:
1821 return submit_control_transfer(itransfer);
1822 case LIBUSB_TRANSFER_TYPE_BULK:
1823 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1824 return submit_bulk_transfer(itransfer);
1825 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1826 return submit_iso_transfer(itransfer);
1827 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1828 #if InterfaceVersion >= 550
1829 return submit_stream_transfer(itransfer);
1831 usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers");
1832 return LIBUSB_ERROR_NOT_SUPPORTED;
1835 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1836 return LIBUSB_ERROR_INVALID_PARAM;
1840 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1841 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1842 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1845 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
1848 return LIBUSB_ERROR_NO_DEVICE;
1850 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1852 return darwin_to_libusb (kresult);
1855 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1856 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1857 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1858 struct darwin_interface *cInterface;
1859 uint8_t pipeRef, iface;
1862 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) {
1863 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1865 return LIBUSB_ERROR_NOT_FOUND;
1869 return LIBUSB_ERROR_NO_DEVICE;
1871 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
1873 /* abort transactions */
1874 #if InterfaceVersion >= 550
1875 if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type)
1876 (*(cInterface->interface))->AbortStreamsPipe (cInterface->interface, pipeRef, itransfer->stream_id);
1879 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1881 usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
1883 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1884 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1886 return darwin_to_libusb (kresult);
1889 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1890 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1892 switch (transfer->type) {
1893 case LIBUSB_TRANSFER_TYPE_CONTROL:
1894 return cancel_control_transfer(itransfer);
1895 case LIBUSB_TRANSFER_TYPE_BULK:
1896 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1897 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1898 return darwin_abort_transfers (itransfer);
1900 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1901 return LIBUSB_ERROR_INVALID_PARAM;
1905 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1906 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1907 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1909 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1910 free (tpriv->isoc_framelist);
1911 tpriv->isoc_framelist = NULL;
1915 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1916 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1917 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1918 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1920 usbi_dbg ("an async io operation has completed");
1922 /* if requested write a zero packet */
1923 if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
1924 struct darwin_interface *cInterface;
1927 (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface);
1929 (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
1932 tpriv->result = result;
1933 tpriv->size = (UInt32) (uintptr_t) arg0;
1935 /* signal the core that this transfer is complete */
1936 usbi_signal_transfer_completion(itransfer);
1939 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1940 if (itransfer->timeout_flags & USBI_TRANSFER_TIMED_OUT)
1941 result = kIOUSBTransactionTimeout;
1944 case kIOReturnUnderrun:
1945 case kIOReturnSuccess:
1946 return LIBUSB_TRANSFER_COMPLETED;
1947 case kIOReturnAborted:
1948 return LIBUSB_TRANSFER_CANCELLED;
1949 case kIOUSBPipeStalled:
1950 usbi_dbg ("transfer error: pipe is stalled");
1951 return LIBUSB_TRANSFER_STALL;
1952 case kIOReturnOverrun:
1953 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1954 return LIBUSB_TRANSFER_OVERFLOW;
1955 case kIOUSBTransactionTimeout:
1956 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1957 itransfer->timeout_flags |= USBI_TRANSFER_TIMED_OUT;
1958 return LIBUSB_TRANSFER_TIMED_OUT;
1960 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1961 return LIBUSB_TRANSFER_ERROR;
1965 static int darwin_handle_transfer_completion (struct usbi_transfer *itransfer) {
1966 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1967 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1968 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1969 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1970 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1971 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1974 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1975 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1976 return LIBUSB_ERROR_INVALID_PARAM;
1979 usbi_dbg ("handling %s completion with kernel status %d",
1980 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", tpriv->result);
1982 if (kIOReturnSuccess == tpriv->result || kIOReturnUnderrun == tpriv->result) {
1983 if (isIsoc && tpriv->isoc_framelist) {
1984 /* copy isochronous results back */
1986 for (i = 0; i < transfer->num_iso_packets ; i++) {
1987 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1988 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1989 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1992 itransfer->transferred += tpriv->size;
1995 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1996 return usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, tpriv->result));
1999 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
2000 #if !OSX_USE_CLOCK_GETTIME
2001 mach_timespec_t sys_time;
2002 clock_serv_t clock_ref;
2005 case USBI_CLOCK_REALTIME:
2006 /* CLOCK_REALTIME represents time since the epoch */
2007 clock_ref = clock_realtime;
2009 case USBI_CLOCK_MONOTONIC:
2010 /* use system boot time as reference for the monotonic clock */
2011 clock_ref = clock_monotonic;
2014 return LIBUSB_ERROR_INVALID_PARAM;
2017 clock_get_time (clock_ref, &sys_time);
2019 tp->tv_sec = sys_time.tv_sec;
2020 tp->tv_nsec = sys_time.tv_nsec;
2025 case USBI_CLOCK_MONOTONIC:
2026 return clock_gettime(CLOCK_MONOTONIC, tp);
2027 case USBI_CLOCK_REALTIME:
2028 return clock_gettime(CLOCK_REALTIME, tp);
2030 return LIBUSB_ERROR_INVALID_PARAM;
2035 #if InterfaceVersion >= 550
2036 static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints,
2037 int num_endpoints) {
2038 struct darwin_interface *cInterface;
2039 UInt32 supportsStreams;
2043 /* find the mimimum number of supported streams on the endpoint list */
2044 for (i = 0 ; i < num_endpoints ; ++i) {
2045 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) {
2049 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2050 if (num_streams > supportsStreams)
2051 num_streams = supportsStreams;
2054 /* it is an error if any endpoint in endpoints does not support streams */
2055 if (0 == num_streams)
2056 return LIBUSB_ERROR_INVALID_PARAM;
2058 /* create the streams */
2059 for (i = 0 ; i < num_endpoints ; ++i) {
2060 (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
2062 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, num_streams);
2063 if (kIOReturnSuccess != rc)
2064 return darwin_to_libusb(rc);
2070 static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) {
2071 struct darwin_interface *cInterface;
2072 UInt32 supportsStreams;
2076 for (int i = 0 ; i < num_endpoints ; ++i) {
2077 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface)))
2080 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2081 if (0 == supportsStreams)
2082 return LIBUSB_ERROR_INVALID_PARAM;
2084 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, 0);
2085 if (kIOReturnSuccess != rc)
2086 return darwin_to_libusb(rc);
2089 return LIBUSB_SUCCESS;
2093 const struct usbi_os_backend usbi_backend = {
2096 .init = darwin_init,
2097 .exit = darwin_exit,
2098 .get_device_list = NULL, /* not needed */
2099 .get_device_descriptor = darwin_get_device_descriptor,
2100 .get_active_config_descriptor = darwin_get_active_config_descriptor,
2101 .get_config_descriptor = darwin_get_config_descriptor,
2102 .hotplug_poll = darwin_hotplug_poll,
2104 .open = darwin_open,
2105 .close = darwin_close,
2106 .get_configuration = darwin_get_configuration,
2107 .set_configuration = darwin_set_configuration,
2108 .claim_interface = darwin_claim_interface,
2109 .release_interface = darwin_release_interface,
2111 .set_interface_altsetting = darwin_set_interface_altsetting,
2112 .clear_halt = darwin_clear_halt,
2113 .reset_device = darwin_reset_device,
2115 #if InterfaceVersion >= 550
2116 .alloc_streams = darwin_alloc_streams,
2117 .free_streams = darwin_free_streams,
2120 .kernel_driver_active = darwin_kernel_driver_active,
2121 .detach_kernel_driver = darwin_detach_kernel_driver,
2122 .attach_kernel_driver = darwin_attach_kernel_driver,
2124 .destroy_device = darwin_destroy_device,
2126 .submit_transfer = darwin_submit_transfer,
2127 .cancel_transfer = darwin_cancel_transfer,
2128 .clear_transfer_priv = darwin_clear_transfer_priv,
2130 .handle_transfer_completion = darwin_handle_transfer_completion,
2132 .clock_gettime = darwin_clock_gettime,
2134 .device_priv_size = sizeof(struct darwin_device_priv),
2135 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
2136 .transfer_priv_size = sizeof(struct darwin_transfer_priv),