1 /* -*- Mode: C; indent-tabs-mode:nil -*- */
3 * darwin backend for libusb 1.0
4 * Copyright © 2008-2019 Nathan Hjelm <hjelmn@users.sourceforge.net>
5 * Copyright © 2019 Google LLC. All rights reserved.
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
31 #include <sys/types.h>
34 #include <sys/sysctl.h>
36 #include <mach/clock.h>
37 #include <mach/clock_types.h>
38 #include <mach/mach_host.h>
39 #include <mach/mach_port.h>
41 /* Suppress warnings about the use of the deprecated objc_registerThreadWithCollector
42 * function. Its use is also conditionalized to only older deployment targets. */
43 #define OBJC_SILENCE_GC_DEPRECATIONS 1
45 #include <AvailabilityMacros.h>
46 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
47 #include <objc/objc-auto.h>
50 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 101200
51 /* Apple deprecated the darwin atomics in 10.12 in favor of C11 atomics */
52 #include <stdatomic.h>
53 #define libusb_darwin_atomic_fetch_add(x, y) atomic_fetch_add(x, y)
55 _Atomic int32_t initCount = ATOMIC_VAR_INIT(0);
57 /* use darwin atomics if the target is older than 10.12 */
58 #include <libkern/OSAtomic.h>
60 /* OSAtomicAdd32Barrier returns the new value */
61 #define libusb_darwin_atomic_fetch_add(x, y) (OSAtomicAdd32Barrier(y, x) - y)
63 static volatile int32_t initCount = 0;
67 /* On 10.12 and later, use newly available clock_*() functions */
68 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 101200
69 #define OSX_USE_CLOCK_GETTIME 1
71 #define OSX_USE_CLOCK_GETTIME 0
74 #include "darwin_usb.h"
76 /* async event thread */
77 static pthread_mutex_t libusb_darwin_at_mutex = PTHREAD_MUTEX_INITIALIZER;
78 static pthread_cond_t libusb_darwin_at_cond = PTHREAD_COND_INITIALIZER;
80 #if !OSX_USE_CLOCK_GETTIME
81 static clock_serv_t clock_realtime;
82 static clock_serv_t clock_monotonic;
85 static CFRunLoopRef libusb_darwin_acfl = NULL; /* event cf loop */
86 static CFRunLoopSourceRef libusb_darwin_acfls = NULL; /* shutdown signal for event cf loop */
88 static usbi_mutex_t darwin_cached_devices_lock = PTHREAD_MUTEX_INITIALIZER;
89 static struct list_head darwin_cached_devices = {&darwin_cached_devices, &darwin_cached_devices};
90 static const char *darwin_device_class = kIOUSBDeviceClassName;
92 #define DARWIN_CACHED_DEVICE(a) ((struct darwin_cached_device *) (((struct darwin_device_priv *)((a)->os_priv))->dev))
94 /* async event thread */
95 static pthread_t libusb_darwin_at;
97 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
98 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
99 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
100 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
101 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
103 static enum libusb_error darwin_scan_devices(struct libusb_context *ctx);
104 static enum libusb_error process_new_device (struct libusb_context *ctx, io_service_t service);
106 #if defined(ENABLE_LOGGING)
107 static const char *darwin_error_str (IOReturn result) {
108 static char string_buffer[50];
110 case kIOReturnSuccess:
112 case kIOReturnNotOpen:
113 return "device not opened for exclusive access";
114 case kIOReturnNoDevice:
115 return "no connection to an IOService";
116 case kIOUSBNoAsyncPortErr:
117 return "no async port has been opened for interface";
118 case kIOReturnExclusiveAccess:
119 return "another process has device opened for exclusive access";
120 case kIOUSBPipeStalled:
121 return "pipe is stalled";
123 return "could not establish a connection to the Darwin kernel";
124 case kIOUSBTransactionTimeout:
125 return "transaction timed out";
126 case kIOReturnBadArgument:
127 return "invalid argument";
128 case kIOReturnAborted:
129 return "transaction aborted";
130 case kIOReturnNotResponding:
131 return "device not responding";
132 case kIOReturnOverrun:
133 return "data overrun";
134 case kIOReturnCannotWire:
135 return "physical memory can not be wired down";
136 case kIOReturnNoResources:
137 return "out of resources";
138 case kIOUSBHighSpeedSplitError:
139 return "high speed split error";
141 snprintf(string_buffer, sizeof(string_buffer), "unknown error (0x%x)", result);
142 return string_buffer;
147 static enum libusb_error darwin_to_libusb (IOReturn result) {
149 case kIOReturnUnderrun:
150 case kIOReturnSuccess:
151 return LIBUSB_SUCCESS;
152 case kIOReturnNotOpen:
153 case kIOReturnNoDevice:
154 return LIBUSB_ERROR_NO_DEVICE;
155 case kIOReturnExclusiveAccess:
156 return LIBUSB_ERROR_ACCESS;
157 case kIOUSBPipeStalled:
158 return LIBUSB_ERROR_PIPE;
159 case kIOReturnBadArgument:
160 return LIBUSB_ERROR_INVALID_PARAM;
161 case kIOUSBTransactionTimeout:
162 return LIBUSB_ERROR_TIMEOUT;
163 case kIOReturnNotResponding:
164 case kIOReturnAborted:
166 case kIOUSBNoAsyncPortErr:
168 return LIBUSB_ERROR_OTHER;
172 /* this function must be called with the darwin_cached_devices_lock held */
173 static void darwin_deref_cached_device(struct darwin_cached_device *cached_dev) {
174 cached_dev->refcount--;
175 /* free the device and remove it from the cache */
176 if (0 == cached_dev->refcount) {
177 list_del(&cached_dev->list);
179 (*(cached_dev->device))->Release(cached_dev->device);
184 static void darwin_ref_cached_device(struct darwin_cached_device *cached_dev) {
185 cached_dev->refcount++;
188 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) {
189 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
191 /* current interface */
192 struct darwin_interface *cInterface;
196 usbi_dbg ("converting ep address 0x%02x to pipeRef and interface", ep);
198 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
199 cInterface = &priv->interfaces[iface];
201 if (dev_handle->claimed_interfaces & (1U << iface)) {
202 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
203 if (cInterface->endpoint_addrs[i] == ep) {
210 *interface_out = cInterface;
212 usbi_dbg ("pipe %d on interface %d matches", *pipep, iface);
213 return LIBUSB_SUCCESS;
219 /* No pipe found with the correct endpoint address */
220 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
222 return LIBUSB_ERROR_NOT_FOUND;
225 static IOReturn usb_setup_device_iterator (io_iterator_t *deviceIterator, UInt32 location) {
226 CFMutableDictionaryRef matchingDict = IOServiceMatching(darwin_device_class);
229 return kIOReturnError;
232 CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
233 &kCFTypeDictionaryKeyCallBacks,
234 &kCFTypeDictionaryValueCallBacks);
236 /* there are no unsigned CFNumber types so treat the value as signed. the OS seems to do this
237 internally (CFNumberType of locationID is kCFNumberSInt32Type) */
238 CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberSInt32Type, &location);
240 if (propertyMatchDict && locationCF) {
241 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
242 CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
244 /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
246 /* release our references as per the Create Rule */
247 if (propertyMatchDict)
248 CFRelease (propertyMatchDict);
250 CFRelease (locationCF);
253 return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator);
256 /* Returns 1 on success, 0 on failure. */
257 static bool get_ioregistry_value_number (io_service_t service, CFStringRef property, CFNumberType type, void *p) {
258 CFTypeRef cfNumber = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
262 if (CFGetTypeID(cfNumber) == CFNumberGetTypeID()) {
263 success = CFNumberGetValue(cfNumber, type, p);
266 CFRelease (cfNumber);
269 return (success != 0);
272 /* Returns 1 on success, 0 on failure. */
273 static bool get_ioregistry_value_data (io_service_t service, CFStringRef property, ssize_t size, void *p) {
274 CFTypeRef cfData = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
275 bool success = false;
278 if (CFGetTypeID (cfData) == CFDataGetTypeID ()) {
279 CFIndex length = CFDataGetLength (cfData);
284 CFDataGetBytes (cfData, CFRangeMake(0, size), p);
294 static usb_device_t **darwin_device_from_service (io_service_t service)
296 io_cf_plugin_ref_t *plugInInterface = NULL;
297 usb_device_t **device;
301 kresult = IOCreatePlugInInterfaceForService(service, kIOUSBDeviceUserClientTypeID,
302 kIOCFPlugInInterfaceID, &plugInInterface,
305 if (kIOReturnSuccess != kresult || !plugInInterface) {
306 usbi_dbg ("could not set up plugin for service: %s", darwin_error_str (kresult));
310 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
312 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
313 (*plugInInterface)->Release (plugInInterface);
318 static void darwin_devices_attached (void *ptr, io_iterator_t add_devices) {
320 struct libusb_context *ctx;
321 io_service_t service;
323 usbi_mutex_lock(&active_contexts_lock);
325 while ((service = IOIteratorNext(add_devices))) {
326 /* add this device to each active context's device list */
327 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
328 process_new_device (ctx, service);
331 IOObjectRelease(service);
334 usbi_mutex_unlock(&active_contexts_lock);
337 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
339 struct libusb_device *dev = NULL;
340 struct libusb_context *ctx;
341 struct darwin_cached_device *old_device;
347 usbi_mutex_lock(&active_contexts_lock);
349 while ((device = IOIteratorNext (rem_devices)) != 0) {
350 /* get the location from the i/o registry */
351 ret = get_ioregistry_value_number (device, CFSTR("sessionID"), kCFNumberSInt64Type, &session);
352 IOObjectRelease (device);
356 /* we need to match darwin_ref_cached_device call made in darwin_get_cached_device function
357 otherwise no cached device will ever get freed */
358 usbi_mutex_lock(&darwin_cached_devices_lock);
359 list_for_each_entry(old_device, &darwin_cached_devices, list, struct darwin_cached_device) {
360 if (old_device->session == session) {
361 if (old_device->in_reenumerate) {
362 /* device is re-enumerating. do not dereference the device at this time. libusb_reset_device()
363 * will deref if needed. */
364 usbi_dbg ("detected device detatched due to re-enumeration");
366 darwin_deref_cached_device (old_device);
371 usbi_mutex_unlock(&darwin_cached_devices_lock);
372 if (old_device->in_reenumerate) {
376 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
377 usbi_dbg ("notifying context %p of device disconnect", ctx);
379 dev = usbi_get_device_by_session_id(ctx, (unsigned long) session);
381 /* signal the core that this device has been disconnected. the core will tear down this device
382 when the reference count reaches 0 */
383 usbi_disconnect_device(dev);
384 libusb_unref_device(dev);
389 usbi_mutex_unlock(&active_contexts_lock);
392 static void darwin_hotplug_poll (void)
394 /* not sure if 1 ms will be too long/short but it should work ok */
395 mach_timespec_t timeout = {.tv_sec = 0, .tv_nsec = 1000000ul};
397 /* since a kernel thread may nodify the IOInterators used for
398 * hotplug notidication we can't just clear the iterators.
399 * instead just wait until all IOService providers are quiet */
400 (void) IOKitWaitQuiet (kIOMasterPortDefault, &timeout);
403 static void darwin_clear_iterator (io_iterator_t iter) {
406 while ((device = IOIteratorNext (iter)) != 0)
407 IOObjectRelease (device);
410 static void *darwin_event_thread_main (void *arg0) {
412 struct libusb_context *ctx = (struct libusb_context *)arg0;
413 CFRunLoopRef runloop;
415 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
416 /* Set this thread's name, so it can be seen in the debugger
417 and crash reports. */
418 pthread_setname_np ("org.libusb.device-hotplug");
421 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
422 /* Tell the Objective-C garbage collector about this thread.
423 This is required because, unlike NSThreads, pthreads are
424 not automatically registered. Although we don't use
425 Objective-C, we use CoreFoundation, which does.
426 Garbage collection support was entirely removed in 10.12,
427 so don't bother there. */
428 objc_registerThreadWithCollector();
431 /* hotplug (device arrival/removal) sources */
432 CFRunLoopSourceContext libusb_shutdown_cfsourcectx;
433 CFRunLoopSourceRef libusb_notification_cfsource;
434 io_notification_port_t libusb_notification_port;
435 io_iterator_t libusb_rem_device_iterator;
436 io_iterator_t libusb_add_device_iterator;
438 usbi_dbg ("creating hotplug event source");
440 runloop = CFRunLoopGetCurrent ();
443 /* add the shutdown cfsource to the run loop */
444 memset(&libusb_shutdown_cfsourcectx, 0, sizeof(libusb_shutdown_cfsourcectx));
445 libusb_shutdown_cfsourcectx.info = runloop;
446 libusb_shutdown_cfsourcectx.perform = (void (*)(void *))CFRunLoopStop;
447 libusb_darwin_acfls = CFRunLoopSourceCreate(NULL, 0, &libusb_shutdown_cfsourcectx);
448 CFRunLoopAddSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
450 /* add the notification port to the run loop */
451 libusb_notification_port = IONotificationPortCreate (kIOMasterPortDefault);
452 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
453 CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
455 /* create notifications for removed devices */
456 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
457 IOServiceMatching(darwin_device_class),
458 darwin_devices_detached,
459 ctx, &libusb_rem_device_iterator);
461 if (kresult != kIOReturnSuccess) {
462 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
467 /* create notifications for attached devices */
468 kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
469 IOServiceMatching(darwin_device_class),
470 darwin_devices_attached,
471 ctx, &libusb_add_device_iterator);
473 if (kresult != kIOReturnSuccess) {
474 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
480 darwin_clear_iterator (libusb_rem_device_iterator);
481 darwin_clear_iterator (libusb_add_device_iterator);
483 usbi_dbg ("darwin event thread ready to receive events");
485 /* signal the main thread that the hotplug runloop has been created. */
486 pthread_mutex_lock (&libusb_darwin_at_mutex);
487 libusb_darwin_acfl = runloop;
488 pthread_cond_signal (&libusb_darwin_at_cond);
489 pthread_mutex_unlock (&libusb_darwin_at_mutex);
491 /* run the runloop */
494 usbi_dbg ("darwin event thread exiting");
496 /* remove the notification cfsource */
497 CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
499 /* remove the shutdown cfsource */
500 CFRunLoopRemoveSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
502 /* delete notification port */
503 IONotificationPortDestroy (libusb_notification_port);
505 /* delete iterators */
506 IOObjectRelease (libusb_rem_device_iterator);
507 IOObjectRelease (libusb_add_device_iterator);
509 CFRelease (libusb_darwin_acfls);
512 libusb_darwin_acfls = NULL;
513 libusb_darwin_acfl = NULL;
518 /* cleanup function to destroy cached devices */
519 static void __attribute__((destructor)) _darwin_finalize(void) {
520 struct darwin_cached_device *dev, *next;
522 usbi_mutex_lock(&darwin_cached_devices_lock);
523 list_for_each_entry_safe(dev, next, &darwin_cached_devices, list, struct darwin_cached_device) {
524 darwin_deref_cached_device(dev);
526 usbi_mutex_unlock(&darwin_cached_devices_lock);
529 static int darwin_init(struct libusb_context *ctx) {
532 rc = darwin_scan_devices (ctx);
533 if (LIBUSB_SUCCESS != rc) {
537 if (libusb_darwin_atomic_fetch_add (&initCount, 1) == 0) {
538 #if !OSX_USE_CLOCK_GETTIME
539 /* create the clocks that will be used if clock_gettime() is not available */
540 host_name_port_t host_self;
542 host_self = mach_host_self();
543 host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
544 host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
545 mach_port_deallocate(mach_task_self(), host_self);
548 pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, ctx);
550 pthread_mutex_lock (&libusb_darwin_at_mutex);
551 while (!libusb_darwin_acfl)
552 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
553 pthread_mutex_unlock (&libusb_darwin_at_mutex);
559 static void darwin_exit (struct libusb_context *ctx) {
561 if (libusb_darwin_atomic_fetch_add (&initCount, -1) == 1) {
562 #if !OSX_USE_CLOCK_GETTIME
563 mach_port_deallocate(mach_task_self(), clock_realtime);
564 mach_port_deallocate(mach_task_self(), clock_monotonic);
567 /* stop the event runloop and wait for the thread to terminate. */
568 CFRunLoopSourceSignal(libusb_darwin_acfls);
569 CFRunLoopWakeUp (libusb_darwin_acfl);
570 pthread_join (libusb_darwin_at, NULL);
574 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
575 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
577 /* return cached copy */
578 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
582 return LIBUSB_SUCCESS;
585 static int get_configuration_index (struct libusb_device *dev, int config_value) {
586 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
588 IOUSBConfigurationDescriptorPtr desc;
591 /* is there a simpler way to determine the index? */
592 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
593 if (kresult != kIOReturnSuccess)
594 return darwin_to_libusb (kresult);
596 for (i = 0 ; i < numConfig ; i++) {
597 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
599 if (desc->bConfigurationValue == config_value)
603 /* configuration not found */
604 return LIBUSB_ERROR_NOT_FOUND;
607 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
608 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
611 if (0 == priv->active_config)
612 return LIBUSB_ERROR_NOT_FOUND;
614 config_index = get_configuration_index (dev, priv->active_config);
615 if (config_index < 0)
618 assert(config_index >= 0 && config_index <= UINT8_MAX);
619 return darwin_get_config_descriptor (dev, (UInt8)config_index, buffer, len, host_endian);
622 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
623 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
624 IOUSBConfigurationDescriptorPtr desc;
628 if (!priv || !priv->device)
629 return LIBUSB_ERROR_OTHER;
631 kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
632 if (kresult == kIOReturnSuccess) {
633 /* copy descriptor */
634 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
635 len = libusb_le16_to_cpu(desc->wTotalLength);
637 memmove (buffer, desc, len);
639 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
643 ret = darwin_to_libusb (kresult);
644 if (ret != LIBUSB_SUCCESS)
650 /* check whether the os has configured the device */
651 static enum libusb_error darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) {
652 usb_device_t **darwin_device = dev->device;
654 IOUSBConfigurationDescriptorPtr configDesc;
655 IOUSBFindInterfaceRequest request;
657 io_iterator_t interface_iterator;
658 io_service_t firstInterface;
660 if (dev->dev_descriptor.bNumConfigurations < 1) {
661 usbi_err (ctx, "device has no configurations");
662 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
665 /* checking the configuration of a root hub simulation takes ~1 s in 10.11. the device is
667 if (0x05ac == dev->dev_descriptor.idVendor && 0x8005 == dev->dev_descriptor.idProduct) {
668 usbi_dbg ("ignoring configuration on root hub simulation");
669 dev->active_config = 0;
670 return LIBUSB_SUCCESS;
673 /* find the first configuration */
674 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
675 dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
677 /* check if the device is already configured. there is probably a better way than iterating over the
678 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
679 might lock up on the device request) */
681 /* Setup the Interface Request */
682 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
683 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
684 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
685 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
687 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
688 if (kresult != kIOReturnSuccess)
689 return darwin_to_libusb (kresult);
692 firstInterface = IOIteratorNext(interface_iterator);
694 /* done with the interface iterator */
695 IOObjectRelease(interface_iterator);
697 if (firstInterface) {
698 IOObjectRelease (firstInterface);
700 /* device is configured */
701 if (dev->dev_descriptor.bNumConfigurations == 1)
702 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
703 dev->active_config = dev->first_config;
705 /* devices with more than one configuration should work with GetConfiguration */
706 (*darwin_device)->GetConfiguration (darwin_device, &dev->active_config);
709 dev->active_config = 0;
711 usbi_dbg ("active config: %u, first config: %u", dev->active_config, dev->first_config);
713 return LIBUSB_SUCCESS;
716 static IOReturn darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
717 IOUSBDevRequestTO req;
719 assert(buffer_size <= UINT16_MAX);
721 memset (buffer, 0, buffer_size);
723 /* Set up request for descriptor/ */
724 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
725 req.bRequest = kUSBRqGetDescriptor;
726 req.wValue = (UInt16)(desc << 8);
727 req.wIndex = desc_index;
728 req.wLength = (UInt16)buffer_size;
730 req.noDataTimeout = 20;
731 req.completionTimeout = 100;
733 return (*device)->DeviceRequestTO (device, &req);
736 static enum libusb_error darwin_cache_device_descriptor (struct libusb_context *ctx, struct darwin_cached_device *dev) {
737 usb_device_t **device = dev->device;
739 long delay = 30000; // microseconds
740 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
742 IOReturn ret = 0, ret2;
744 UInt16 idProduct, idVendor;
746 dev->can_enumerate = 0;
748 (*device)->GetDeviceClass (device, &bDeviceClass);
749 (*device)->GetDeviceProduct (device, &idProduct);
750 (*device)->GetDeviceVendor (device, &idVendor);
752 /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
753 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
754 * to follow the spec as closely as possible, try opening the device */
755 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
758 /**** retrieve device descriptor ****/
759 ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &dev->dev_descriptor, sizeof(dev->dev_descriptor));
761 if (kIOReturnOverrun == ret && kUSBDeviceDesc == dev->dev_descriptor.bDescriptorType)
762 /* received an overrun error but we still received a device descriptor */
763 ret = kIOReturnSuccess;
765 if (kIOUSBVendorIDAppleComputer == idVendor) {
766 /* NTH: don't bother retrying or unsuspending Apple devices */
770 if (kIOReturnSuccess == ret && (0 == dev->dev_descriptor.bNumConfigurations ||
771 0 == dev->dev_descriptor.bcdUSB)) {
772 /* work around for incorrectly configured devices */
773 if (try_reconfigure && is_open) {
774 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
776 /* set the first configuration */
777 (*device)->SetConfiguration(device, 1);
779 /* don't try to reconfigure again */
783 ret = kIOUSBPipeStalled;
786 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
787 /* device may be suspended. unsuspend it and try again */
788 #if DeviceVersion >= 320
791 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
792 (void)(*device)->GetUSBDeviceInformation (device, &info);
794 /* note that the device was suspended */
795 if (info & (1U << kUSBInformationDeviceIsSuspendedBit) || 0 == info)
800 /* try to unsuspend the device */
801 ret2 = (*device)->USBDeviceSuspend (device, 0);
802 if (kIOReturnSuccess != ret2) {
803 /* prevent log spew from poorly behaving devices. this indicates the
804 os actually had trouble communicating with the device */
805 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
813 if (kIOReturnSuccess != ret) {
814 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %ld ms before trying again", ret, delay/1000);
815 /* sleep for a little while before trying again */
816 nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000}, NULL);
818 } while (kIOReturnSuccess != ret && retries--);
821 /* resuspend the device */
822 (void)(*device)->USBDeviceSuspend (device, 1);
825 (void) (*device)->USBDeviceClose (device);
827 if (ret != kIOReturnSuccess) {
828 /* a debug message was already printed out for this error */
829 if (LIBUSB_CLASS_HUB == bDeviceClass)
830 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
831 idVendor, idProduct, darwin_error_str (ret), ret);
833 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
834 idVendor, idProduct, darwin_error_str (ret), ret);
835 return darwin_to_libusb (ret);
838 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
839 if (libusb_le16_to_cpu (dev->dev_descriptor.idProduct) != idProduct) {
840 /* not a valid device */
841 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
842 idProduct, libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
843 return LIBUSB_ERROR_NO_DEVICE;
846 usbi_dbg ("cached device descriptor:");
847 usbi_dbg (" bDescriptorType: 0x%02x", dev->dev_descriptor.bDescriptorType);
848 usbi_dbg (" bcdUSB: 0x%04x", dev->dev_descriptor.bcdUSB);
849 usbi_dbg (" bDeviceClass: 0x%02x", dev->dev_descriptor.bDeviceClass);
850 usbi_dbg (" bDeviceSubClass: 0x%02x", dev->dev_descriptor.bDeviceSubClass);
851 usbi_dbg (" bDeviceProtocol: 0x%02x", dev->dev_descriptor.bDeviceProtocol);
852 usbi_dbg (" bMaxPacketSize0: 0x%02x", dev->dev_descriptor.bMaxPacketSize0);
853 usbi_dbg (" idVendor: 0x%04x", dev->dev_descriptor.idVendor);
854 usbi_dbg (" idProduct: 0x%04x", dev->dev_descriptor.idProduct);
855 usbi_dbg (" bcdDevice: 0x%04x", dev->dev_descriptor.bcdDevice);
856 usbi_dbg (" iManufacturer: 0x%02x", dev->dev_descriptor.iManufacturer);
857 usbi_dbg (" iProduct: 0x%02x", dev->dev_descriptor.iProduct);
858 usbi_dbg (" iSerialNumber: 0x%02x", dev->dev_descriptor.iSerialNumber);
859 usbi_dbg (" bNumConfigurations: 0x%02x", dev->dev_descriptor.bNumConfigurations);
861 dev->can_enumerate = 1;
863 return LIBUSB_SUCCESS;
866 /* Returns 1 on success, 0 on failure. */
867 static bool get_device_port (io_service_t service, UInt8 *port) {
872 if (get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, port)) {
876 kresult = IORegistryEntryGetParentEntry (service, kIOServicePlane, &parent);
877 if (kIOReturnSuccess == kresult) {
878 ret = get_ioregistry_value_data (parent, CFSTR("port"), 1, port);
879 IOObjectRelease (parent);
885 /* Returns 1 on success, 0 on failure. */
886 static bool get_device_parent_sessionID(io_service_t service, UInt64 *parent_sessionID) {
890 /* Walk up the tree in the IOService plane until we find a parent that has a sessionID */
892 while((kresult = IORegistryEntryGetParentEntry (parent, kIOUSBPlane, &parent)) == kIOReturnSuccess) {
893 if (get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, parent_sessionID)) {
899 /* We ran out of parents */
903 static enum libusb_error 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 UInt32 locationID = 0;
908 enum libusb_error ret = LIBUSB_SUCCESS;
909 usb_device_t **device;
911 bool reuse_device = false;
913 /* get some info from the io registry */
914 (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
915 (void) get_ioregistry_value_number (service, CFSTR("locationID"), kCFNumberSInt32Type, &locationID);
916 if (!get_device_port (service, &port)) {
917 usbi_dbg("could not get connected port number");
920 usbi_dbg("finding cached device for sessionID 0x%" PRIx64, sessionID);
922 if (get_device_parent_sessionID(service, &parent_sessionID)) {
923 usbi_dbg("parent sessionID: 0x%" PRIx64, parent_sessionID);
926 usbi_mutex_lock(&darwin_cached_devices_lock);
930 list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) {
931 usbi_dbg("matching sessionID/locationID 0x%" PRIx64 "/0x%x against cached device with sessionID/locationID 0x%" PRIx64 "/0x%x",
932 sessionID, locationID, new_device->session, new_device->location);
933 if (new_device->location == locationID && new_device->in_reenumerate) {
934 usbi_dbg ("found cached device with matching location that is being re-enumerated");
935 new_device->session = sessionID;
940 if (new_device->session == sessionID) {
941 usbi_dbg("using cached device for device");
942 *cached_out = new_device;
950 usbi_dbg("caching new device with sessionID 0x%" PRIx64, sessionID);
952 device = darwin_device_from_service (service);
954 ret = LIBUSB_ERROR_NO_DEVICE;
959 new_device = calloc (1, sizeof (*new_device));
961 ret = LIBUSB_ERROR_NO_MEM;
965 /* add this device to the cached device list */
966 list_add(&new_device->list, &darwin_cached_devices);
968 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
970 /* keep a reference to this device */
971 darwin_ref_cached_device(new_device);
973 new_device->session = sessionID;
974 (*device)->GetLocationID (device, &new_device->location);
975 new_device->port = port;
976 new_device->parent_session = parent_sessionID;
979 new_device->device = device;
981 /* cache the device descriptor */
982 ret = darwin_cache_device_descriptor(ctx, new_device);
986 if (new_device->can_enumerate) {
987 snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address,
988 new_device->dev_descriptor.idVendor, new_device->dev_descriptor.idProduct,
989 new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass);
993 usbi_mutex_unlock(&darwin_cached_devices_lock);
995 /* keep track of devices regardless of if we successfully enumerate them to
996 prevent them from being enumerated multiple times */
998 *cached_out = new_device;
1003 static enum libusb_error process_new_device (struct libusb_context *ctx, io_service_t service) {
1004 struct darwin_device_priv *priv;
1005 struct libusb_device *dev = NULL;
1006 struct darwin_cached_device *cached_device;
1008 enum libusb_error ret = LIBUSB_SUCCESS;
1011 ret = darwin_get_cached_device (ctx, service, &cached_device);
1012 if (ret < 0 || !cached_device->can_enumerate) {
1016 /* check current active configuration (and cache the first configuration value--
1017 which may be used by claim_interface) */
1018 ret = darwin_check_configuration (ctx, cached_device);
1022 usbi_dbg ("allocating new device in context %p for with session 0x%" PRIx64,
1023 ctx, cached_device->session);
1025 dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
1027 return LIBUSB_ERROR_NO_MEM;
1030 priv = (struct darwin_device_priv *)dev->os_priv;
1032 priv->dev = cached_device;
1033 darwin_ref_cached_device (priv->dev);
1035 if (cached_device->parent_session > 0) {
1036 dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session);
1038 dev->parent_dev = NULL;
1040 dev->port_number = cached_device->port;
1041 dev->bus_number = cached_device->location >> 24;
1042 assert(cached_device->address <= UINT8_MAX);
1043 dev->device_address = (uint8_t)cached_device->address;
1045 (*(priv->dev->device))->GetDeviceSpeed (priv->dev->device, &devSpeed);
1048 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
1049 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
1050 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
1051 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
1052 case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
1054 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101200
1055 case kUSBDeviceSpeedSuperPlus: dev->speed = LIBUSB_SPEED_SUPER_PLUS; break;
1058 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
1061 ret = usbi_sanitize_device (dev);
1065 usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
1066 dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
1070 if (cached_device->in_reenumerate) {
1071 usbi_dbg ("cached device in reset state. reset complete...");
1072 cached_device->in_reenumerate = false;
1073 } else if (0 == ret) {
1074 usbi_connect_device (dev);
1076 libusb_unref_device (dev);
1082 static enum libusb_error darwin_scan_devices(struct libusb_context *ctx) {
1083 io_iterator_t deviceIterator;
1084 io_service_t service;
1087 kresult = usb_setup_device_iterator (&deviceIterator, 0);
1088 if (kresult != kIOReturnSuccess)
1089 return darwin_to_libusb (kresult);
1091 while ((service = IOIteratorNext (deviceIterator))) {
1092 (void) process_new_device (ctx, service);
1094 IOObjectRelease(service);
1097 IOObjectRelease(deviceIterator);
1099 return LIBUSB_SUCCESS;
1102 static int darwin_open (struct libusb_device_handle *dev_handle) {
1103 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1104 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1107 if (0 == dpriv->open_count) {
1108 /* try to open the device */
1109 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
1110 if (kresult != kIOReturnSuccess) {
1111 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
1113 if (kIOReturnExclusiveAccess != kresult) {
1114 return darwin_to_libusb (kresult);
1117 /* it is possible to perform some actions on a device that is not open so do not return an error */
1118 priv->is_open = false;
1120 priv->is_open = true;
1123 /* create async event source */
1124 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
1125 if (kresult != kIOReturnSuccess) {
1126 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
1128 if (priv->is_open) {
1129 (*(dpriv->device))->USBDeviceClose (dpriv->device);
1132 priv->is_open = false;
1134 return darwin_to_libusb (kresult);
1137 CFRetain (libusb_darwin_acfl);
1139 /* add the cfSource to the aync run loop */
1140 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
1143 /* device opened successfully */
1144 dpriv->open_count++;
1146 usbi_dbg ("device open for access");
1151 static void darwin_close (struct libusb_device_handle *dev_handle) {
1152 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1153 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1157 if (dpriv->open_count == 0) {
1158 /* something is probably very wrong if this is the case */
1159 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!");
1163 dpriv->open_count--;
1165 /* make sure all interfaces are released */
1166 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1167 if (dev_handle->claimed_interfaces & (1U << i))
1168 libusb_release_interface (dev_handle, i);
1170 if (0 == dpriv->open_count) {
1171 /* delete the device's async event source */
1172 if (priv->cfSource) {
1173 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
1174 CFRelease (priv->cfSource);
1175 priv->cfSource = NULL;
1176 CFRelease (libusb_darwin_acfl);
1179 if (priv->is_open) {
1180 /* close the device */
1181 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
1182 if (kresult != kIOReturnSuccess) {
1183 /* Log the fact that we had a problem closing the file, however failing a
1184 * close isn't really an error, so return success anyway */
1185 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
1191 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
1192 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1194 *config = (int) dpriv->active_config;
1196 return LIBUSB_SUCCESS;
1199 static enum libusb_error darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
1200 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1204 assert(config >= 0 && config <= UINT8_MAX);
1206 /* Setting configuration will invalidate the interface, so we need
1207 to reclaim it. First, dispose of existing interfaces, if any. */
1208 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1209 if (dev_handle->claimed_interfaces & (1U << i))
1210 darwin_release_interface (dev_handle, i);
1212 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, (UInt8)config);
1213 if (kresult != kIOReturnSuccess)
1214 return darwin_to_libusb (kresult);
1216 /* Reclaim any interfaces. */
1217 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1218 if (dev_handle->claimed_interfaces & (1U << i))
1219 darwin_claim_interface (dev_handle, i);
1221 dpriv->active_config = (UInt8)config;
1223 return LIBUSB_SUCCESS;
1226 static IOReturn darwin_get_interface (usb_device_t **darwin_device, int ifc, io_service_t *usbInterfacep) {
1227 IOUSBFindInterfaceRequest request;
1229 io_iterator_t interface_iterator;
1230 UInt8 bInterfaceNumber;
1233 *usbInterfacep = IO_OBJECT_NULL;
1235 /* Setup the Interface Request */
1236 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1237 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1238 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1239 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1241 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1242 if (kresult != kIOReturnSuccess)
1245 while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1246 /* find the interface number */
1247 ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
1250 if (ret && bInterfaceNumber == ifc) {
1254 (void) IOObjectRelease (*usbInterfacep);
1257 /* done with the interface iterator */
1258 IOObjectRelease(interface_iterator);
1260 return kIOReturnSuccess;
1263 static enum libusb_error get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
1264 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1266 /* current interface */
1267 struct darwin_interface *cInterface = &priv->interfaces[iface];
1271 UInt8 numep, direction, number;
1272 UInt8 dont_care1, dont_care3;
1276 usbi_dbg ("building table of endpoints.");
1278 /* retrieve the total number of endpoints on this interface */
1279 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1280 if (kresult != kIOReturnSuccess) {
1281 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1282 return darwin_to_libusb (kresult);
1285 /* iterate through pipe references */
1286 for (UInt8 i = 1 ; i <= numep ; i++) {
1287 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1288 &dont_care2, &dont_care3);
1290 if (kresult != kIOReturnSuccess) {
1291 /* probably a buggy device. try to get the endpoint address from the descriptors */
1292 struct libusb_config_descriptor *config;
1293 const struct libusb_endpoint_descriptor *endpoint_desc;
1296 kresult = (*(cInterface->interface))->GetAlternateSetting (cInterface->interface, &alt_setting);
1297 if (kresult != kIOReturnSuccess) {
1298 usbi_err (HANDLE_CTX (dev_handle), "can't get alternate setting for interface");
1299 return darwin_to_libusb (kresult);
1302 rc = libusb_get_active_config_descriptor (dev_handle->dev, &config);
1303 if (LIBUSB_SUCCESS != rc) {
1307 endpoint_desc = config->interface[iface].altsetting[alt_setting].endpoint + i - 1;
1309 cInterface->endpoint_addrs[i - 1] = endpoint_desc->bEndpointAddress;
1311 cInterface->endpoint_addrs[i - 1] = (UInt8)(((kUSBIn == direction) << kUSBRqDirnShift) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1314 usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, cInterface->endpoint_addrs[i - 1] >> kUSBRqDirnShift,
1315 cInterface->endpoint_addrs[i - 1] & LIBUSB_ENDPOINT_ADDRESS_MASK);
1318 cInterface->num_endpoints = numep;
1320 return LIBUSB_SUCCESS;
1323 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1324 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1325 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1326 io_service_t usbInterface = IO_OBJECT_NULL;
1328 enum libusb_error ret;
1329 IOCFPlugInInterface **plugInInterface = NULL;
1332 assert(iface >= 0 && iface <= UINT8_MAX);
1334 /* current interface */
1335 struct darwin_interface *cInterface = &priv->interfaces[iface];
1337 kresult = darwin_get_interface (dpriv->device, (uint8_t)iface, &usbInterface);
1338 if (kresult != kIOReturnSuccess)
1339 return darwin_to_libusb (kresult);
1341 /* make sure we have an interface */
1342 if (!usbInterface && dpriv->first_config != 0) {
1343 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1345 /* set the configuration */
1346 ret = darwin_set_configuration (dev_handle, dpriv->first_config);
1347 if (ret != LIBUSB_SUCCESS) {
1348 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1352 kresult = darwin_get_interface (dpriv->device, (uint8_t)iface, &usbInterface);
1353 if (kresult != kIOReturnSuccess) {
1354 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1355 return darwin_to_libusb (kresult);
1359 if (!usbInterface) {
1360 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1361 return LIBUSB_ERROR_NOT_FOUND;
1364 /* get an interface to the device's interface */
1365 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1366 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1368 /* ignore release error */
1369 (void)IOObjectRelease (usbInterface);
1371 if (kresult != kIOReturnSuccess) {
1372 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1373 return darwin_to_libusb (kresult);
1376 if (!plugInInterface) {
1377 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1378 return LIBUSB_ERROR_NOT_FOUND;
1381 /* Do the actual claim */
1382 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1383 CFUUIDGetUUIDBytes(InterfaceInterfaceID),
1384 (LPVOID)&cInterface->interface);
1385 /* We no longer need the intermediate plug-in */
1386 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1387 (*plugInInterface)->Release (plugInInterface);
1388 if (kresult != kIOReturnSuccess || !cInterface->interface) {
1389 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1390 return darwin_to_libusb (kresult);
1393 /* claim the interface */
1394 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1395 if (kresult != kIOReturnSuccess) {
1396 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1397 return darwin_to_libusb (kresult);
1400 /* update list of endpoints */
1401 ret = get_endpoints (dev_handle, iface);
1403 /* this should not happen */
1404 darwin_release_interface (dev_handle, iface);
1405 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1409 cInterface->cfSource = NULL;
1411 /* create async event source */
1412 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1413 if (kresult != kIOReturnSuccess) {
1414 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1416 /* can't continue without an async event source */
1417 (void)darwin_release_interface (dev_handle, iface);
1419 return darwin_to_libusb (kresult);
1422 /* add the cfSource to the async thread's run loop */
1423 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1425 usbi_dbg ("interface opened");
1427 return LIBUSB_SUCCESS;
1430 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1431 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1434 /* current interface */
1435 struct darwin_interface *cInterface = &priv->interfaces[iface];
1437 /* Check to see if an interface is open */
1438 if (!cInterface->interface)
1439 return LIBUSB_SUCCESS;
1441 /* clean up endpoint data */
1442 cInterface->num_endpoints = 0;
1444 /* delete the interface's async event source */
1445 if (cInterface->cfSource) {
1446 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1447 CFRelease (cInterface->cfSource);
1450 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1451 if (kresult != kIOReturnSuccess)
1452 usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1454 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1455 if (kresult != kIOReturnSuccess)
1456 usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1458 cInterface->interface = (usb_interface_t **) IO_OBJECT_NULL;
1460 return darwin_to_libusb (kresult);
1463 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1464 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1466 enum libusb_error ret;
1468 /* current interface */
1469 struct darwin_interface *cInterface = &priv->interfaces[iface];
1471 if (!cInterface->interface)
1472 return LIBUSB_ERROR_NO_DEVICE;
1474 assert(altsetting >= 0 && altsetting <= UINT8_MAX);
1475 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, (UInt8)altsetting);
1476 if (kresult != kIOReturnSuccess)
1477 darwin_reset_device (dev_handle);
1479 /* update list of endpoints */
1480 ret = get_endpoints (dev_handle, iface);
1482 /* this should not happen */
1483 darwin_release_interface (dev_handle, iface);
1484 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1488 return darwin_to_libusb (kresult);
1491 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1492 /* current interface */
1493 struct darwin_interface *cInterface;
1497 /* determine the interface/endpoint to use */
1498 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, NULL, &cInterface) != 0) {
1499 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1501 return LIBUSB_ERROR_NOT_FOUND;
1504 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1505 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1506 if (kresult != kIOReturnSuccess)
1507 usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1509 return darwin_to_libusb (kresult);
1512 static int darwin_restore_state (struct libusb_device_handle *dev_handle, int8_t active_config,
1513 unsigned long claimed_interfaces) {
1514 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1515 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1516 int open_count = dpriv->open_count;
1519 /* clear claimed interfaces temporarily */
1520 dev_handle->claimed_interfaces = 0;
1522 /* close and re-open the device */
1523 priv->is_open = false;
1524 dpriv->open_count = 1;
1526 /* clean up open interfaces */
1527 (void) darwin_close (dev_handle);
1529 /* re-open the device */
1530 ret = darwin_open (dev_handle);
1531 dpriv->open_count = open_count;
1532 if (LIBUSB_SUCCESS != ret) {
1533 /* could not restore configuration */
1534 return LIBUSB_ERROR_NOT_FOUND;
1537 if (dpriv->active_config != active_config) {
1538 usbi_dbg ("darwin/restore_state: restoring configuration %d...", active_config);
1540 ret = darwin_set_configuration (dev_handle, active_config);
1541 if (LIBUSB_SUCCESS != ret) {
1542 usbi_dbg ("darwin/restore_state: could not restore configuration");
1543 return LIBUSB_ERROR_NOT_FOUND;
1547 usbi_dbg ("darwin/restore_state: reclaiming interfaces");
1549 if (claimed_interfaces) {
1550 for (int iface = 0 ; iface < USB_MAXINTERFACES ; ++iface) {
1551 if (!(claimed_interfaces & (1U << iface))) {
1555 usbi_dbg ("darwin/restore_state: re-claiming interface %d", iface);
1557 ret = darwin_claim_interface (dev_handle, iface);
1558 if (LIBUSB_SUCCESS != ret) {
1559 usbi_dbg ("darwin/restore_state: could not claim interface %d", iface);
1560 return LIBUSB_ERROR_NOT_FOUND;
1563 dev_handle->claimed_interfaces |= 1U << iface;
1567 usbi_dbg ("darwin/restore_state: device state restored");
1569 return LIBUSB_SUCCESS;
1572 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1573 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1574 unsigned long claimed_interfaces = dev_handle->claimed_interfaces;
1575 int8_t active_config = dpriv->active_config;
1576 IOUSBDeviceDescriptor descriptor;
1577 IOUSBConfigurationDescriptorPtr cached_configuration;
1578 IOUSBConfigurationDescriptor *cached_configurations;
1582 if (dpriv->in_reenumerate) {
1583 /* ack, two (or more) threads are trying to reset the device! abort! */
1584 return LIBUSB_ERROR_NOT_FOUND;
1587 dpriv->in_reenumerate = true;
1589 /* store copies of descriptors so they can be compared after the reset */
1590 memcpy (&descriptor, &dpriv->dev_descriptor, sizeof (descriptor));
1591 cached_configurations = alloca (sizeof (*cached_configurations) * descriptor.bNumConfigurations);
1593 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1594 (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1595 memcpy (cached_configurations + i, cached_configuration, sizeof (cached_configurations[i]));
1598 /* from macOS 10.11 ResetDevice no longer does anything so just use USBDeviceReEnumerate */
1599 kresult = (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
1600 if (kresult != kIOReturnSuccess) {
1601 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceReEnumerate: %s", darwin_error_str (kresult));
1602 dpriv->in_reenumerate = false;
1603 return darwin_to_libusb (kresult);
1606 usbi_dbg ("darwin/reset_device: waiting for re-enumeration to complete...");
1608 while (dpriv->in_reenumerate) {
1609 struct timespec delay = {.tv_sec = 0, .tv_nsec = 1000};
1610 nanosleep (&delay, NULL);
1613 /* compare descriptors */
1614 usbi_dbg ("darwin/reset_device: checking whether descriptors changed");
1616 if (memcmp (&descriptor, &dpriv->dev_descriptor, sizeof (descriptor))) {
1617 /* device descriptor changed. need to return not found. */
1618 usbi_dbg ("darwin/reset_device: device descriptor changed");
1619 return LIBUSB_ERROR_NOT_FOUND;
1622 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1623 (void) (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1624 if (memcmp (cached_configuration, cached_configurations + i, sizeof (cached_configurations[i]))) {
1625 usbi_dbg ("darwin/reset_device: configuration descriptor %d changed", i);
1626 return LIBUSB_ERROR_NOT_FOUND;
1630 usbi_dbg ("darwin/reset_device: device reset complete. restoring state...");
1632 return darwin_restore_state (dev_handle, active_config, claimed_interfaces);
1635 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1636 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1637 io_service_t usbInterface;
1641 assert(interface >= 0 && interface <= UINT8_MAX);
1642 kresult = darwin_get_interface (dpriv->device, (uint8_t)interface, &usbInterface);
1643 if (kresult != kIOReturnSuccess) {
1644 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1646 return darwin_to_libusb (kresult);
1649 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1650 IOObjectRelease (usbInterface);
1662 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1663 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1666 return LIBUSB_ERROR_NOT_SUPPORTED;
1669 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1672 return LIBUSB_ERROR_NOT_SUPPORTED;
1675 static void darwin_destroy_device(struct libusb_device *dev) {
1676 struct darwin_device_priv *dpriv = (struct darwin_device_priv *) dev->os_priv;
1679 /* need to hold the lock in case this is the last reference to the device */
1680 usbi_mutex_lock(&darwin_cached_devices_lock);
1681 darwin_deref_cached_device (dpriv->dev);
1683 usbi_mutex_unlock(&darwin_cached_devices_lock);
1687 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1688 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1691 uint8_t transferType;
1692 /* None of the values below are used in libusbx for bulk transfers */
1693 uint8_t direction, number, interval, pipeRef;
1694 uint16_t maxPacketSize;
1696 struct darwin_interface *cInterface;
1698 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1699 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1701 return LIBUSB_ERROR_NOT_FOUND;
1704 ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1705 &transferType, &maxPacketSize, &interval);
1708 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1709 darwin_error_str(ret), ret);
1710 return darwin_to_libusb (ret);
1713 if (0 != (transfer->length % maxPacketSize)) {
1714 /* do not need a zero packet */
1715 transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1718 /* submit the request */
1719 /* timeouts are unavailable on interrupt endpoints */
1720 if (transferType == kUSBInterrupt) {
1721 if (IS_XFERIN(transfer))
1722 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1723 (UInt32)transfer->length, darwin_async_io_callback, itransfer);
1725 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1726 (UInt32)transfer->length, darwin_async_io_callback, itransfer);
1728 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1730 if (IS_XFERIN(transfer))
1731 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1732 (UInt32)transfer->length, transfer->timeout, transfer->timeout,
1733 darwin_async_io_callback, itransfer);
1735 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1736 (UInt32)transfer->length, transfer->timeout, transfer->timeout,
1737 darwin_async_io_callback, itransfer);
1741 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1742 darwin_error_str(ret), ret);
1744 return darwin_to_libusb (ret);
1747 #if InterfaceVersion >= 550
1748 static int submit_stream_transfer(struct usbi_transfer *itransfer) {
1749 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1750 struct darwin_interface *cInterface;
1754 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1755 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1757 return LIBUSB_ERROR_NOT_FOUND;
1760 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1762 if (IS_XFERIN(transfer))
1763 ret = (*(cInterface->interface))->ReadStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1764 transfer->buffer, (UInt32)transfer->length, transfer->timeout,
1765 transfer->timeout, darwin_async_io_callback, itransfer);
1767 ret = (*(cInterface->interface))->WriteStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1768 transfer->buffer, (UInt32)transfer->length, transfer->timeout,
1769 transfer->timeout, darwin_async_io_callback, itransfer);
1772 usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1773 darwin_error_str(ret), ret);
1775 return darwin_to_libusb (ret);
1779 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1780 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1781 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1784 uint8_t direction, number, interval, pipeRef, transferType;
1785 uint16_t maxPacketSize;
1787 AbsoluteTime atTime;
1790 struct darwin_interface *cInterface;
1792 /* construct an array of IOUSBIsocFrames, reuse the old one if the sizes are the same */
1793 if (tpriv->num_iso_packets != transfer->num_iso_packets) {
1794 free(tpriv->isoc_framelist);
1795 tpriv->isoc_framelist = NULL;
1798 if (!tpriv->isoc_framelist) {
1799 tpriv->num_iso_packets = transfer->num_iso_packets;
1800 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc ((size_t)transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1801 if (!tpriv->isoc_framelist)
1802 return LIBUSB_ERROR_NO_MEM;
1805 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1806 for (i = 0 ; i < transfer->num_iso_packets ; i++) {
1807 unsigned int length = transfer->iso_packet_desc[i].length;
1808 assert(length <= UINT16_MAX);
1809 tpriv->isoc_framelist[i].frReqCount = (UInt16)length;
1812 /* determine the interface/endpoint to use */
1813 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1814 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1816 return LIBUSB_ERROR_NOT_FOUND;
1819 /* determine the properties of this endpoint and the speed of the device */
1820 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1821 &transferType, &maxPacketSize, &interval);
1823 /* Last but not least we need the bus frame number */
1824 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1825 if (kresult != kIOReturnSuccess) {
1826 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1827 free(tpriv->isoc_framelist);
1828 tpriv->isoc_framelist = NULL;
1830 return darwin_to_libusb (kresult);
1833 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1834 &transferType, &maxPacketSize, &interval);
1836 /* schedule for a frame a little in the future */
1839 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1840 frame = cInterface->frames[transfer->endpoint];
1842 /* submit the request */
1843 if (IS_XFERIN(transfer))
1844 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1845 (UInt32)transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1848 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1849 (UInt32)transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1852 if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
1854 cInterface->frames[transfer->endpoint] = frame + (UInt32)transfer->num_iso_packets * (1U << (interval - 1));
1856 /* High/super speed */
1857 cInterface->frames[transfer->endpoint] = frame + (UInt32)transfer->num_iso_packets * (1U << (interval - 1)) / 8;
1859 if (kresult != kIOReturnSuccess) {
1860 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1861 darwin_error_str(kresult));
1862 free (tpriv->isoc_framelist);
1863 tpriv->isoc_framelist = NULL;
1866 return darwin_to_libusb (kresult);
1869 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1870 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1871 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1872 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1873 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1877 memset(&tpriv->req, 0, sizeof(tpriv->req));
1879 /* IOUSBDeviceInterface expects the request in cpu endianness */
1880 tpriv->req.bmRequestType = setup->bmRequestType;
1881 tpriv->req.bRequest = setup->bRequest;
1882 /* these values should be in bus order from libusb_fill_control_setup */
1883 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1884 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1885 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1886 /* data is stored after the libusb control block */
1887 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1888 tpriv->req.completionTimeout = transfer->timeout;
1889 tpriv->req.noDataTimeout = transfer->timeout;
1891 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1893 /* all transfers in libusb-1.0 are async */
1895 if (transfer->endpoint) {
1896 struct darwin_interface *cInterface;
1899 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1900 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1902 return LIBUSB_ERROR_NOT_FOUND;
1905 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1907 /* control request on endpoint 0 */
1908 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1910 if (kresult != kIOReturnSuccess)
1911 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1913 return darwin_to_libusb (kresult);
1916 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1917 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1919 switch (transfer->type) {
1920 case LIBUSB_TRANSFER_TYPE_CONTROL:
1921 return submit_control_transfer(itransfer);
1922 case LIBUSB_TRANSFER_TYPE_BULK:
1923 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1924 return submit_bulk_transfer(itransfer);
1925 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1926 return submit_iso_transfer(itransfer);
1927 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1928 #if InterfaceVersion >= 550
1929 return submit_stream_transfer(itransfer);
1931 usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers");
1932 return LIBUSB_ERROR_NOT_SUPPORTED;
1935 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1936 return LIBUSB_ERROR_INVALID_PARAM;
1940 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1941 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1942 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1945 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
1948 return LIBUSB_ERROR_NO_DEVICE;
1950 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1952 return darwin_to_libusb (kresult);
1955 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1956 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1957 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1958 struct darwin_interface *cInterface;
1959 uint8_t pipeRef, iface;
1962 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) {
1963 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1965 return LIBUSB_ERROR_NOT_FOUND;
1969 return LIBUSB_ERROR_NO_DEVICE;
1971 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
1973 /* abort transactions */
1974 #if InterfaceVersion >= 550
1975 if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type)
1976 (*(cInterface->interface))->AbortStreamsPipe (cInterface->interface, pipeRef, itransfer->stream_id);
1979 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1981 usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
1983 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1984 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1986 return darwin_to_libusb (kresult);
1989 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1990 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1992 switch (transfer->type) {
1993 case LIBUSB_TRANSFER_TYPE_CONTROL:
1994 return cancel_control_transfer(itransfer);
1995 case LIBUSB_TRANSFER_TYPE_BULK:
1996 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1997 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1998 return darwin_abort_transfers (itransfer);
2000 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
2001 return LIBUSB_ERROR_INVALID_PARAM;
2005 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
2006 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2007 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2009 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
2010 free (tpriv->isoc_framelist);
2011 tpriv->isoc_framelist = NULL;
2015 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
2016 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
2017 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2018 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2020 usbi_dbg ("an async io operation has completed");
2022 /* if requested write a zero packet */
2023 if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
2024 struct darwin_interface *cInterface;
2027 (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface);
2029 (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
2032 tpriv->result = result;
2033 tpriv->size = (UInt32) (uintptr_t) arg0;
2035 /* signal the core that this transfer is complete */
2036 usbi_signal_transfer_completion(itransfer);
2039 static enum libusb_transfer_status darwin_transfer_status (struct usbi_transfer *itransfer, IOReturn result) {
2040 if (itransfer->timeout_flags & USBI_TRANSFER_TIMED_OUT)
2041 result = kIOUSBTransactionTimeout;
2044 case kIOReturnUnderrun:
2045 case kIOReturnSuccess:
2046 return LIBUSB_TRANSFER_COMPLETED;
2047 case kIOReturnAborted:
2048 return LIBUSB_TRANSFER_CANCELLED;
2049 case kIOUSBPipeStalled:
2050 usbi_dbg ("transfer error: pipe is stalled");
2051 return LIBUSB_TRANSFER_STALL;
2052 case kIOReturnOverrun:
2053 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
2054 return LIBUSB_TRANSFER_OVERFLOW;
2055 case kIOUSBTransactionTimeout:
2056 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
2057 itransfer->timeout_flags |= USBI_TRANSFER_TIMED_OUT;
2058 return LIBUSB_TRANSFER_TIMED_OUT;
2060 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
2061 return LIBUSB_TRANSFER_ERROR;
2065 static int darwin_handle_transfer_completion (struct usbi_transfer *itransfer) {
2066 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2067 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2068 bool isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
2069 bool isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
2070 bool isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
2071 bool isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
2074 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
2075 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
2076 return LIBUSB_ERROR_INVALID_PARAM;
2079 usbi_dbg ("handling %s completion with kernel status %d",
2080 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", tpriv->result);
2082 if (kIOReturnSuccess == tpriv->result || kIOReturnUnderrun == tpriv->result) {
2083 if (isIsoc && tpriv->isoc_framelist) {
2084 /* copy isochronous results back */
2086 for (i = 0; i < transfer->num_iso_packets ; i++) {
2087 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
2088 lib_desc->status = darwin_transfer_status (itransfer, tpriv->isoc_framelist[i].frStatus);
2089 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
2092 itransfer->transferred += tpriv->size;
2095 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
2096 return usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, tpriv->result));
2099 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
2100 #if !OSX_USE_CLOCK_GETTIME
2101 mach_timespec_t sys_time;
2102 clock_serv_t clock_ref;
2105 case USBI_CLOCK_REALTIME:
2106 /* CLOCK_REALTIME represents time since the epoch */
2107 clock_ref = clock_realtime;
2109 case USBI_CLOCK_MONOTONIC:
2110 /* use system boot time as reference for the monotonic clock */
2111 clock_ref = clock_monotonic;
2114 return LIBUSB_ERROR_INVALID_PARAM;
2117 clock_get_time (clock_ref, &sys_time);
2119 tp->tv_sec = sys_time.tv_sec;
2120 tp->tv_nsec = sys_time.tv_nsec;
2122 return LIBUSB_SUCCESS;
2125 case USBI_CLOCK_MONOTONIC:
2126 return clock_gettime(CLOCK_MONOTONIC, tp);
2127 case USBI_CLOCK_REALTIME:
2128 return clock_gettime(CLOCK_REALTIME, tp);
2130 return LIBUSB_ERROR_INVALID_PARAM;
2135 #if InterfaceVersion >= 550
2136 static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints,
2137 int num_endpoints) {
2138 struct darwin_interface *cInterface;
2139 UInt32 supportsStreams;
2143 /* find the mimimum number of supported streams on the endpoint list */
2144 for (i = 0 ; i < num_endpoints ; ++i) {
2145 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) {
2149 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2150 if (num_streams > supportsStreams)
2151 num_streams = supportsStreams;
2154 /* it is an error if any endpoint in endpoints does not support streams */
2155 if (0 == num_streams)
2156 return LIBUSB_ERROR_INVALID_PARAM;
2158 /* create the streams */
2159 for (i = 0 ; i < num_endpoints ; ++i) {
2160 (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
2162 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, num_streams);
2163 if (kIOReturnSuccess != rc)
2164 return darwin_to_libusb(rc);
2167 assert(num_streams <= INT_MAX);
2168 return (int)num_streams;
2171 static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) {
2172 struct darwin_interface *cInterface;
2173 UInt32 supportsStreams;
2177 for (int i = 0 ; i < num_endpoints ; ++i) {
2178 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface)))
2181 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2182 if (0 == supportsStreams)
2183 return LIBUSB_ERROR_INVALID_PARAM;
2185 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, 0);
2186 if (kIOReturnSuccess != rc)
2187 return darwin_to_libusb(rc);
2190 return LIBUSB_SUCCESS;
2194 const struct usbi_os_backend usbi_backend = {
2197 .init = darwin_init,
2198 .exit = darwin_exit,
2199 .get_device_list = NULL, /* not needed */
2200 .get_device_descriptor = darwin_get_device_descriptor,
2201 .get_active_config_descriptor = darwin_get_active_config_descriptor,
2202 .get_config_descriptor = darwin_get_config_descriptor,
2203 .hotplug_poll = darwin_hotplug_poll,
2205 .open = darwin_open,
2206 .close = darwin_close,
2207 .get_configuration = darwin_get_configuration,
2208 .set_configuration = darwin_set_configuration,
2209 .claim_interface = darwin_claim_interface,
2210 .release_interface = darwin_release_interface,
2212 .set_interface_altsetting = darwin_set_interface_altsetting,
2213 .clear_halt = darwin_clear_halt,
2214 .reset_device = darwin_reset_device,
2216 #if InterfaceVersion >= 550
2217 .alloc_streams = darwin_alloc_streams,
2218 .free_streams = darwin_free_streams,
2221 .kernel_driver_active = darwin_kernel_driver_active,
2222 .detach_kernel_driver = darwin_detach_kernel_driver,
2223 .attach_kernel_driver = darwin_attach_kernel_driver,
2225 .destroy_device = darwin_destroy_device,
2227 .submit_transfer = darwin_submit_transfer,
2228 .cancel_transfer = darwin_cancel_transfer,
2229 .clear_transfer_priv = darwin_clear_transfer_priv,
2231 .handle_transfer_completion = darwin_handle_transfer_completion,
2233 .clock_gettime = darwin_clock_gettime,
2235 .device_priv_size = sizeof(struct darwin_device_priv),
2236 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
2237 .transfer_priv_size = sizeof(struct darwin_transfer_priv),