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 /* On 10.12 and later, use newly available clock_*() functions */
51 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 101200
52 #define OSX_USE_CLOCK_GETTIME 1
54 #define OSX_USE_CLOCK_GETTIME 0
57 #include "darwin_usb.h"
59 static pthread_mutex_t libusb_darwin_init_mutex = PTHREAD_MUTEX_INITIALIZER;
60 static int init_count = 0;
62 /* async event thread */
63 static pthread_mutex_t libusb_darwin_at_mutex = PTHREAD_MUTEX_INITIALIZER;
64 static pthread_cond_t libusb_darwin_at_cond = PTHREAD_COND_INITIALIZER;
66 #if !OSX_USE_CLOCK_GETTIME
67 static clock_serv_t clock_realtime;
68 static clock_serv_t clock_monotonic;
71 #define LIBUSB_DARWIN_STARTUP_FAILURE ((CFRunLoopRef) -1)
73 static CFRunLoopRef libusb_darwin_acfl = NULL; /* event cf loop */
74 static CFRunLoopSourceRef libusb_darwin_acfls = NULL; /* shutdown signal for event cf loop */
76 static usbi_mutex_t darwin_cached_devices_lock = PTHREAD_MUTEX_INITIALIZER;
77 static struct list_head darwin_cached_devices = {&darwin_cached_devices, &darwin_cached_devices};
78 static const char *darwin_device_class = kIOUSBDeviceClassName;
80 #define DARWIN_CACHED_DEVICE(a) (((struct darwin_device_priv *)usbi_get_device_priv((a)))->dev)
82 /* async event thread */
83 static pthread_t libusb_darwin_at;
85 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
86 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
87 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
88 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
89 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
91 static enum libusb_error darwin_scan_devices(struct libusb_context *ctx);
92 static enum libusb_error process_new_device (struct libusb_context *ctx, struct darwin_cached_device *cached_device,
93 UInt64 old_session_id);
95 static enum libusb_error darwin_get_cached_device(io_service_t service, struct darwin_cached_device **cached_out,
96 UInt64 *old_session_id);
98 #if defined(ENABLE_LOGGING)
99 static const char *darwin_error_str (IOReturn result) {
100 static char string_buffer[50];
102 case kIOReturnSuccess:
104 case kIOReturnNotOpen:
105 return "device not opened for exclusive access";
106 case kIOReturnNoDevice:
107 return "no connection to an IOService";
108 case kIOUSBNoAsyncPortErr:
109 return "no async port has been opened for interface";
110 case kIOReturnExclusiveAccess:
111 return "another process has device opened for exclusive access";
112 case kIOUSBPipeStalled:
113 return "pipe is stalled";
115 return "could not establish a connection to the Darwin kernel";
116 case kIOUSBTransactionTimeout:
117 return "transaction timed out";
118 case kIOReturnBadArgument:
119 return "invalid argument";
120 case kIOReturnAborted:
121 return "transaction aborted";
122 case kIOReturnNotResponding:
123 return "device not responding";
124 case kIOReturnOverrun:
125 return "data overrun";
126 case kIOReturnCannotWire:
127 return "physical memory can not be wired down";
128 case kIOReturnNoResources:
129 return "out of resources";
130 case kIOUSBHighSpeedSplitError:
131 return "high speed split error";
133 snprintf(string_buffer, sizeof(string_buffer), "unknown error (0x%x)", result);
134 return string_buffer;
139 static enum libusb_error darwin_to_libusb (IOReturn result) {
141 case kIOReturnUnderrun:
142 case kIOReturnSuccess:
143 return LIBUSB_SUCCESS;
144 case kIOReturnNotOpen:
145 case kIOReturnNoDevice:
146 return LIBUSB_ERROR_NO_DEVICE;
147 case kIOReturnExclusiveAccess:
148 return LIBUSB_ERROR_ACCESS;
149 case kIOUSBPipeStalled:
150 return LIBUSB_ERROR_PIPE;
151 case kIOReturnBadArgument:
152 return LIBUSB_ERROR_INVALID_PARAM;
153 case kIOUSBTransactionTimeout:
154 return LIBUSB_ERROR_TIMEOUT;
155 case kIOReturnNotResponding:
156 case kIOReturnAborted:
158 case kIOUSBNoAsyncPortErr:
160 return LIBUSB_ERROR_OTHER;
164 /* this function must be called with the darwin_cached_devices_lock held */
165 static void darwin_deref_cached_device(struct darwin_cached_device *cached_dev) {
166 cached_dev->refcount--;
167 /* free the device and remove it from the cache */
168 if (0 == cached_dev->refcount) {
169 list_del(&cached_dev->list);
171 if (cached_dev->device) {
172 (*(cached_dev->device))->Release(cached_dev->device);
173 cached_dev->device = NULL;
179 static void darwin_ref_cached_device(struct darwin_cached_device *cached_dev) {
180 cached_dev->refcount++;
183 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) {
184 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
186 /* current interface */
187 struct darwin_interface *cInterface;
191 usbi_dbg ("converting ep address 0x%02x to pipeRef and interface", ep);
193 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
194 cInterface = &priv->interfaces[iface];
196 if (dev_handle->claimed_interfaces & (1U << iface)) {
197 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
198 if (cInterface->endpoint_addrs[i] == ep) {
205 *interface_out = cInterface;
207 usbi_dbg ("pipe %d on interface %d matches", *pipep, iface);
208 return LIBUSB_SUCCESS;
214 /* No pipe found with the correct endpoint address */
215 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
217 return LIBUSB_ERROR_NOT_FOUND;
220 static IOReturn usb_setup_device_iterator (io_iterator_t *deviceIterator, UInt32 location) {
221 CFMutableDictionaryRef matchingDict = IOServiceMatching(darwin_device_class);
224 return kIOReturnError;
227 CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
228 &kCFTypeDictionaryKeyCallBacks,
229 &kCFTypeDictionaryValueCallBacks);
231 /* there are no unsigned CFNumber types so treat the value as signed. the OS seems to do this
232 internally (CFNumberType of locationID is kCFNumberSInt32Type) */
233 CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberSInt32Type, &location);
235 if (propertyMatchDict && locationCF) {
236 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
237 CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
239 /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
241 /* release our references as per the Create Rule */
242 if (propertyMatchDict)
243 CFRelease (propertyMatchDict);
245 CFRelease (locationCF);
248 return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator);
251 /* Returns 1 on success, 0 on failure. */
252 static bool 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 success = CFNumberGetValue(cfNumber, type, p);
261 CFRelease (cfNumber);
264 return (success != 0);
267 /* Returns 1 on success, 0 on failure. */
268 static bool get_ioregistry_value_data (io_service_t service, CFStringRef property, ssize_t size, void *p) {
269 CFTypeRef cfData = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
270 bool success = false;
273 if (CFGetTypeID (cfData) == CFDataGetTypeID ()) {
274 CFIndex length = CFDataGetLength (cfData);
279 CFDataGetBytes (cfData, CFRangeMake(0, size), p);
289 static usb_device_t **darwin_device_from_service (io_service_t service)
291 io_cf_plugin_ref_t *plugInInterface = NULL;
292 usb_device_t **device;
295 const int max_retries = 5;
297 /* The IOCreatePlugInInterfaceForService function might consistently return
298 an "out of resources" error with certain USB devices the first time we run
299 it. The reason is still unclear, but retrying fixes the problem */
300 for (int count = 0; count < max_retries; count++) {
301 kresult = IOCreatePlugInInterfaceForService(service, kIOUSBDeviceUserClientTypeID,
302 kIOCFPlugInInterfaceID, &plugInInterface,
304 if (kIOReturnSuccess == kresult && plugInInterface) {
308 usbi_dbg ("set up plugin for service retry: %s", darwin_error_str (kresult));
310 /* sleep for a little while before trying again */
311 nanosleep(&(struct timespec){.tv_sec = 0, .tv_nsec = 1000}, NULL);
314 if (kIOReturnSuccess != kresult || !plugInInterface) {
315 usbi_dbg ("could not set up plugin for service: %s", darwin_error_str (kresult));
319 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
321 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
322 (*plugInInterface)->Release (plugInInterface);
327 static void darwin_devices_attached (void *ptr, io_iterator_t add_devices) {
329 struct darwin_cached_device *cached_device;
330 UInt64 old_session_id;
331 struct libusb_context *ctx;
332 io_service_t service;
335 usbi_mutex_lock(&active_contexts_lock);
337 while ((service = IOIteratorNext(add_devices))) {
338 ret = darwin_get_cached_device (service, &cached_device, &old_session_id);
339 if (ret < 0 || !cached_device->can_enumerate) {
343 /* add this device to each active context's device list */
344 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
345 process_new_device (ctx, cached_device, old_session_id);
348 if (cached_device->in_reenumerate) {
349 usbi_dbg ("cached device in reset state. reset complete...");
350 cached_device->in_reenumerate = false;
353 IOObjectRelease(service);
356 usbi_mutex_unlock(&active_contexts_lock);
359 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
361 struct libusb_device *dev = NULL;
362 struct libusb_context *ctx;
363 struct darwin_cached_device *old_device;
369 usbi_mutex_lock(&active_contexts_lock);
371 while ((device = IOIteratorNext (rem_devices)) != 0) {
372 bool is_reenumerating = false;
374 /* get the location from the i/o registry */
375 ret = get_ioregistry_value_number (device, CFSTR("sessionID"), kCFNumberSInt64Type, &session);
376 IOObjectRelease (device);
380 /* we need to match darwin_ref_cached_device call made in darwin_get_cached_device function
381 otherwise no cached device will ever get freed */
382 usbi_mutex_lock(&darwin_cached_devices_lock);
383 list_for_each_entry(old_device, &darwin_cached_devices, list, struct darwin_cached_device) {
384 if (old_device->session == session) {
385 if (old_device->in_reenumerate) {
386 /* device is re-enumerating. do not dereference the device at this time. libusb_reset_device()
387 * will deref if needed. */
388 usbi_dbg ("detected device detatched due to re-enumeration");
390 /* the device object is no longer usable so go ahead and release it */
391 if (old_device->device) {
392 (*(old_device->device))->Release(old_device->device);
393 old_device->device = NULL;
396 is_reenumerating = true;
398 darwin_deref_cached_device (old_device);
405 usbi_mutex_unlock(&darwin_cached_devices_lock);
406 if (is_reenumerating) {
410 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
411 usbi_dbg ("notifying context %p of device disconnect", ctx);
413 dev = usbi_get_device_by_session_id(ctx, (unsigned long) session);
415 /* signal the core that this device has been disconnected. the core will tear down this device
416 when the reference count reaches 0 */
417 usbi_disconnect_device(dev);
418 libusb_unref_device(dev);
423 usbi_mutex_unlock(&active_contexts_lock);
426 static void darwin_hotplug_poll (void)
428 /* not sure if 1 ms will be too long/short but it should work ok */
429 mach_timespec_t timeout = {.tv_sec = 0, .tv_nsec = 1000000ul};
431 /* since a kernel thread may notify the IOIterators used for
432 * hotplug notification we can't just clear the iterators.
433 * instead just wait until all IOService providers are quiet */
434 (void) IOKitWaitQuiet (kIOMasterPortDefault, &timeout);
437 static void darwin_clear_iterator (io_iterator_t iter) {
440 while ((device = IOIteratorNext (iter)) != 0)
441 IOObjectRelease (device);
444 static void darwin_fail_startup(void) {
445 pthread_mutex_lock (&libusb_darwin_at_mutex);
446 libusb_darwin_acfl = LIBUSB_DARWIN_STARTUP_FAILURE;
447 pthread_cond_signal (&libusb_darwin_at_cond);
448 pthread_mutex_unlock (&libusb_darwin_at_mutex);
452 static void *darwin_event_thread_main (void *arg0) {
454 struct libusb_context *ctx = (struct libusb_context *)arg0;
455 CFRunLoopRef runloop;
456 CFRunLoopSourceRef libusb_shutdown_cfsource;
457 CFRunLoopSourceContext libusb_shutdown_cfsourcectx;
459 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
460 /* Set this thread's name, so it can be seen in the debugger
461 and crash reports. */
462 pthread_setname_np ("org.libusb.device-hotplug");
465 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
466 /* Tell the Objective-C garbage collector about this thread.
467 This is required because, unlike NSThreads, pthreads are
468 not automatically registered. Although we don't use
469 Objective-C, we use CoreFoundation, which does.
470 Garbage collection support was entirely removed in 10.12,
471 so don't bother there. */
472 objc_registerThreadWithCollector();
475 /* hotplug (device arrival/removal) sources */
476 CFRunLoopSourceRef libusb_notification_cfsource;
477 io_notification_port_t libusb_notification_port;
478 io_iterator_t libusb_rem_device_iterator;
479 io_iterator_t libusb_add_device_iterator;
481 usbi_dbg ("creating hotplug event source");
483 runloop = CFRunLoopGetCurrent ();
486 /* add the shutdown cfsource to the run loop */
487 memset(&libusb_shutdown_cfsourcectx, 0, sizeof(libusb_shutdown_cfsourcectx));
488 libusb_shutdown_cfsourcectx.info = runloop;
489 libusb_shutdown_cfsourcectx.perform = (void (*)(void *))CFRunLoopStop;
490 libusb_shutdown_cfsource = CFRunLoopSourceCreate(NULL, 0, &libusb_shutdown_cfsourcectx);
491 CFRunLoopAddSource(runloop, libusb_shutdown_cfsource, kCFRunLoopDefaultMode);
493 /* add the notification port to the run loop */
494 libusb_notification_port = IONotificationPortCreate (kIOMasterPortDefault);
495 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
496 CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
498 /* create notifications for removed devices */
499 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
500 IOServiceMatching(darwin_device_class),
501 darwin_devices_detached,
502 ctx, &libusb_rem_device_iterator);
504 if (kresult != kIOReturnSuccess) {
505 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
506 CFRelease (libusb_shutdown_cfsource);
508 darwin_fail_startup ();
511 /* create notifications for attached devices */
512 kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
513 IOServiceMatching(darwin_device_class),
514 darwin_devices_attached,
515 ctx, &libusb_add_device_iterator);
517 if (kresult != kIOReturnSuccess) {
518 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
519 CFRelease (libusb_shutdown_cfsource);
521 darwin_fail_startup ();
525 darwin_clear_iterator (libusb_rem_device_iterator);
526 darwin_clear_iterator (libusb_add_device_iterator);
528 usbi_dbg ("darwin event thread ready to receive events");
530 /* signal the main thread that the hotplug runloop has been created. */
531 pthread_mutex_lock (&libusb_darwin_at_mutex);
532 libusb_darwin_acfl = runloop;
533 libusb_darwin_acfls = libusb_shutdown_cfsource;
534 pthread_cond_signal (&libusb_darwin_at_cond);
535 pthread_mutex_unlock (&libusb_darwin_at_mutex);
537 /* run the runloop */
540 usbi_dbg ("darwin event thread exiting");
542 /* signal the main thread that the hotplug runloop has finished. */
543 pthread_mutex_lock (&libusb_darwin_at_mutex);
544 libusb_darwin_acfls = NULL;
545 libusb_darwin_acfl = NULL;
546 pthread_cond_signal (&libusb_darwin_at_cond);
547 pthread_mutex_unlock (&libusb_darwin_at_mutex);
549 /* remove the notification cfsource */
550 CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
552 /* remove the shutdown cfsource */
553 CFRunLoopRemoveSource(runloop, libusb_shutdown_cfsource, kCFRunLoopDefaultMode);
555 /* delete notification port */
556 IONotificationPortDestroy (libusb_notification_port);
558 /* delete iterators */
559 IOObjectRelease (libusb_rem_device_iterator);
560 IOObjectRelease (libusb_add_device_iterator);
562 CFRelease (libusb_shutdown_cfsource);
568 /* cleanup function to destroy cached devices */
569 static void __attribute__((destructor)) _darwin_finalize(void) {
570 struct darwin_cached_device *dev, *next;
572 usbi_mutex_lock(&darwin_cached_devices_lock);
573 list_for_each_entry_safe(dev, next, &darwin_cached_devices, list, struct darwin_cached_device) {
574 darwin_deref_cached_device(dev);
576 usbi_mutex_unlock(&darwin_cached_devices_lock);
579 static int darwin_init(struct libusb_context *ctx) {
583 pthread_mutex_lock (&libusb_darwin_init_mutex);
585 first_init = (1 == ++init_count);
588 #if !OSX_USE_CLOCK_GETTIME
590 /* create the clocks that will be used if clock_gettime() is not available */
591 host_name_port_t host_self;
593 host_self = mach_host_self();
594 host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
595 host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
596 mach_port_deallocate(mach_task_self(), host_self);
600 rc = darwin_scan_devices (ctx);
601 if (LIBUSB_SUCCESS != rc)
605 rc = pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, ctx);
607 usbi_err (ctx, "could not create event thread, error %d", rc);
608 rc = LIBUSB_ERROR_OTHER;
612 pthread_mutex_lock (&libusb_darwin_at_mutex);
613 while (!libusb_darwin_acfl)
614 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
615 if (libusb_darwin_acfl == LIBUSB_DARWIN_STARTUP_FAILURE) {
616 libusb_darwin_acfl = NULL;
617 rc = LIBUSB_ERROR_OTHER;
619 pthread_mutex_unlock (&libusb_darwin_at_mutex);
622 pthread_join (libusb_darwin_at, NULL);
626 if (LIBUSB_SUCCESS != rc) {
627 #if !OSX_USE_CLOCK_GETTIME
629 mach_port_deallocate(mach_task_self(), clock_realtime);
630 mach_port_deallocate(mach_task_self(), clock_monotonic);
636 pthread_mutex_unlock (&libusb_darwin_init_mutex);
641 static void darwin_exit (struct libusb_context *ctx) {
644 pthread_mutex_lock (&libusb_darwin_init_mutex);
646 if (0 == --init_count) {
647 /* stop the event runloop and wait for the thread to terminate. */
648 pthread_mutex_lock (&libusb_darwin_at_mutex);
649 CFRunLoopSourceSignal (libusb_darwin_acfls);
650 CFRunLoopWakeUp (libusb_darwin_acfl);
651 while (libusb_darwin_acfl)
652 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
653 pthread_mutex_unlock (&libusb_darwin_at_mutex);
654 pthread_join (libusb_darwin_at, NULL);
656 #if !OSX_USE_CLOCK_GETTIME
657 mach_port_deallocate(mach_task_self(), clock_realtime);
658 mach_port_deallocate(mach_task_self(), clock_monotonic);
662 pthread_mutex_unlock (&libusb_darwin_init_mutex);
665 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
666 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
668 /* return cached copy */
669 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
673 return LIBUSB_SUCCESS;
676 static int get_configuration_index (struct libusb_device *dev, int config_value) {
677 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
679 IOUSBConfigurationDescriptorPtr desc;
682 /* is there a simpler way to determine the index? */
683 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
684 if (kresult != kIOReturnSuccess)
685 return darwin_to_libusb (kresult);
687 for (i = 0 ; i < numConfig ; i++) {
688 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
690 if (desc->bConfigurationValue == config_value)
694 /* configuration not found */
695 return LIBUSB_ERROR_NOT_FOUND;
698 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
699 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
702 if (0 == priv->active_config)
703 return LIBUSB_ERROR_NOT_FOUND;
705 config_index = get_configuration_index (dev, priv->active_config);
706 if (config_index < 0)
709 assert(config_index >= 0 && config_index <= UINT8_MAX);
710 return darwin_get_config_descriptor (dev, (UInt8)config_index, buffer, len, host_endian);
713 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
714 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
715 IOUSBConfigurationDescriptorPtr desc;
719 if (!priv || !priv->device)
720 return LIBUSB_ERROR_OTHER;
722 kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
723 if (kresult == kIOReturnSuccess) {
724 /* copy descriptor */
725 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
726 len = libusb_le16_to_cpu(desc->wTotalLength);
728 memmove (buffer, desc, len);
730 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
734 ret = darwin_to_libusb (kresult);
735 if (ret != LIBUSB_SUCCESS)
741 /* check whether the os has configured the device */
742 static enum libusb_error darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) {
743 usb_device_t **darwin_device = dev->device;
745 IOUSBConfigurationDescriptorPtr configDesc;
746 IOUSBFindInterfaceRequest request;
748 io_iterator_t interface_iterator;
749 io_service_t firstInterface;
751 if (dev->dev_descriptor.bNumConfigurations < 1) {
752 usbi_err (ctx, "device has no configurations");
753 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
756 /* checking the configuration of a root hub simulation takes ~1 s in 10.11. the device is
758 if (0x05ac == dev->dev_descriptor.idVendor && 0x8005 == dev->dev_descriptor.idProduct) {
759 usbi_dbg ("ignoring configuration on root hub simulation");
760 dev->active_config = 0;
761 return LIBUSB_SUCCESS;
764 /* find the first configuration */
765 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
766 dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
768 /* check if the device is already configured. there is probably a better way than iterating over the
769 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
770 might lock up on the device request) */
772 /* Setup the Interface Request */
773 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
774 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
775 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
776 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
778 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
779 if (kresult != kIOReturnSuccess)
780 return darwin_to_libusb (kresult);
783 firstInterface = IOIteratorNext(interface_iterator);
785 /* done with the interface iterator */
786 IOObjectRelease(interface_iterator);
788 if (firstInterface) {
789 IOObjectRelease (firstInterface);
791 /* device is configured */
792 if (dev->dev_descriptor.bNumConfigurations == 1)
793 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
794 dev->active_config = dev->first_config;
796 /* devices with more than one configuration should work with GetConfiguration */
797 (*darwin_device)->GetConfiguration (darwin_device, &dev->active_config);
800 dev->active_config = 0;
802 usbi_dbg ("active config: %u, first config: %u", dev->active_config, dev->first_config);
804 return LIBUSB_SUCCESS;
807 static IOReturn darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
808 IOUSBDevRequestTO req;
810 assert(buffer_size <= UINT16_MAX);
812 memset (buffer, 0, buffer_size);
814 /* Set up request for descriptor/ */
815 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
816 req.bRequest = kUSBRqGetDescriptor;
817 req.wValue = (UInt16)(desc << 8);
818 req.wIndex = desc_index;
819 req.wLength = (UInt16)buffer_size;
821 req.noDataTimeout = 20;
822 req.completionTimeout = 100;
824 return (*device)->DeviceRequestTO (device, &req);
827 static enum libusb_error darwin_cache_device_descriptor (struct darwin_cached_device *dev) {
828 usb_device_t **device = dev->device;
830 long delay = 30000; // microseconds
831 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
833 IOReturn ret = 0, ret2;
835 UInt16 idProduct, idVendor;
837 dev->can_enumerate = 0;
839 (*device)->GetDeviceClass (device, &bDeviceClass);
840 (*device)->GetDeviceProduct (device, &idProduct);
841 (*device)->GetDeviceVendor (device, &idVendor);
843 /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
844 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
845 * to follow the spec as closely as possible, try opening the device */
846 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
849 /**** retrieve device descriptor ****/
850 ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &dev->dev_descriptor, sizeof(dev->dev_descriptor));
852 if (kIOReturnOverrun == ret && kUSBDeviceDesc == dev->dev_descriptor.bDescriptorType)
853 /* received an overrun error but we still received a device descriptor */
854 ret = kIOReturnSuccess;
856 if (kIOUSBVendorIDAppleComputer == idVendor) {
857 /* NTH: don't bother retrying or unsuspending Apple devices */
861 if (kIOReturnSuccess == ret && (0 == dev->dev_descriptor.bNumConfigurations ||
862 0 == dev->dev_descriptor.bcdUSB)) {
863 /* work around for incorrectly configured devices */
864 if (try_reconfigure && is_open) {
865 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
867 /* set the first configuration */
868 (*device)->SetConfiguration(device, 1);
870 /* don't try to reconfigure again */
874 ret = kIOUSBPipeStalled;
877 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
878 /* device may be suspended. unsuspend it and try again */
879 #if DeviceVersion >= 320
882 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
883 (void)(*device)->GetUSBDeviceInformation (device, &info);
885 /* note that the device was suspended */
886 if (info & (1U << kUSBInformationDeviceIsSuspendedBit) || 0 == info)
891 /* try to unsuspend the device */
892 ret2 = (*device)->USBDeviceSuspend (device, 0);
893 if (kIOReturnSuccess != ret2) {
894 /* prevent log spew from poorly behaving devices. this indicates the
895 os actually had trouble communicating with the device */
896 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
904 if (kIOReturnSuccess != ret) {
905 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %ld ms before trying again", ret, delay/1000);
906 /* sleep for a little while before trying again */
907 nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000}, NULL);
909 } while (kIOReturnSuccess != ret && retries--);
912 /* resuspend the device */
913 (void)(*device)->USBDeviceSuspend (device, 1);
916 (void) (*device)->USBDeviceClose (device);
918 if (ret != kIOReturnSuccess) {
919 /* a debug message was already printed out for this error */
920 if (LIBUSB_CLASS_HUB == bDeviceClass)
921 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
922 idVendor, idProduct, darwin_error_str (ret), ret);
924 usbi_warn (NULL, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
925 idVendor, idProduct, darwin_error_str (ret), ret);
926 return darwin_to_libusb (ret);
929 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
930 if (libusb_le16_to_cpu (dev->dev_descriptor.idProduct) != idProduct) {
931 /* not a valid device */
932 usbi_warn (NULL, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
933 idProduct, libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
934 return LIBUSB_ERROR_NO_DEVICE;
937 usbi_dbg ("cached device descriptor:");
938 usbi_dbg (" bDescriptorType: 0x%02x", dev->dev_descriptor.bDescriptorType);
939 usbi_dbg (" bcdUSB: 0x%04x", dev->dev_descriptor.bcdUSB);
940 usbi_dbg (" bDeviceClass: 0x%02x", dev->dev_descriptor.bDeviceClass);
941 usbi_dbg (" bDeviceSubClass: 0x%02x", dev->dev_descriptor.bDeviceSubClass);
942 usbi_dbg (" bDeviceProtocol: 0x%02x", dev->dev_descriptor.bDeviceProtocol);
943 usbi_dbg (" bMaxPacketSize0: 0x%02x", dev->dev_descriptor.bMaxPacketSize0);
944 usbi_dbg (" idVendor: 0x%04x", dev->dev_descriptor.idVendor);
945 usbi_dbg (" idProduct: 0x%04x", dev->dev_descriptor.idProduct);
946 usbi_dbg (" bcdDevice: 0x%04x", dev->dev_descriptor.bcdDevice);
947 usbi_dbg (" iManufacturer: 0x%02x", dev->dev_descriptor.iManufacturer);
948 usbi_dbg (" iProduct: 0x%02x", dev->dev_descriptor.iProduct);
949 usbi_dbg (" iSerialNumber: 0x%02x", dev->dev_descriptor.iSerialNumber);
950 usbi_dbg (" bNumConfigurations: 0x%02x", dev->dev_descriptor.bNumConfigurations);
952 dev->can_enumerate = 1;
954 return LIBUSB_SUCCESS;
957 /* Returns 1 on success, 0 on failure. */
958 static bool get_device_port (io_service_t service, UInt8 *port) {
963 if (get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, port)) {
967 kresult = IORegistryEntryGetParentEntry (service, kIOServicePlane, &parent);
968 if (kIOReturnSuccess == kresult) {
969 ret = get_ioregistry_value_data (parent, CFSTR("port"), 1, port);
970 IOObjectRelease (parent);
976 /* Returns 1 on success, 0 on failure. */
977 static bool get_device_parent_sessionID(io_service_t service, UInt64 *parent_sessionID) {
981 /* Walk up the tree in the IOService plane until we find a parent that has a sessionID */
983 while((kresult = IORegistryEntryGetParentEntry (parent, kIOUSBPlane, &parent)) == kIOReturnSuccess) {
984 if (get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, parent_sessionID)) {
990 /* We ran out of parents */
994 static enum libusb_error darwin_get_cached_device(io_service_t service, struct darwin_cached_device **cached_out,
995 UInt64 *old_session_id) {
996 struct darwin_cached_device *new_device;
997 UInt64 sessionID = 0, parent_sessionID = 0;
998 UInt32 locationID = 0;
999 enum libusb_error ret = LIBUSB_SUCCESS;
1000 usb_device_t **device;
1003 /* assuming sessionID != 0 normally (never seen it be 0) */
1004 *old_session_id = 0;
1007 /* get some info from the io registry */
1008 (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
1009 (void) get_ioregistry_value_number (service, CFSTR("locationID"), kCFNumberSInt32Type, &locationID);
1010 if (!get_device_port (service, &port)) {
1011 usbi_dbg("could not get connected port number");
1014 usbi_dbg("finding cached device for sessionID 0x%" PRIx64, sessionID);
1016 if (get_device_parent_sessionID(service, &parent_sessionID)) {
1017 usbi_dbg("parent sessionID: 0x%" PRIx64, parent_sessionID);
1020 usbi_mutex_lock(&darwin_cached_devices_lock);
1022 list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) {
1023 usbi_dbg("matching sessionID/locationID 0x%" PRIx64 "/0x%x against cached device with sessionID/locationID 0x%" PRIx64 "/0x%x",
1024 sessionID, locationID, new_device->session, new_device->location);
1025 if (new_device->location == locationID && new_device->in_reenumerate) {
1026 usbi_dbg ("found cached device with matching location that is being re-enumerated");
1027 *old_session_id = new_device->session;
1031 if (new_device->session == sessionID) {
1032 usbi_dbg("using cached device for device");
1033 *cached_out = new_device;
1041 usbi_dbg("caching new device with sessionID 0x%" PRIx64, sessionID);
1043 device = darwin_device_from_service (service);
1045 ret = LIBUSB_ERROR_NO_DEVICE;
1049 if (!(*old_session_id)) {
1050 new_device = calloc (1, sizeof (*new_device));
1052 ret = LIBUSB_ERROR_NO_MEM;
1056 /* add this device to the cached device list */
1057 list_add(&new_device->list, &darwin_cached_devices);
1059 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
1061 /* keep a reference to this device */
1062 darwin_ref_cached_device(new_device);
1064 (*device)->GetLocationID (device, &new_device->location);
1065 new_device->port = port;
1066 new_device->parent_session = parent_sessionID;
1069 /* keep track of devices regardless of if we successfully enumerate them to
1070 prevent them from being enumerated multiple times */
1071 *cached_out = new_device;
1073 new_device->session = sessionID;
1074 new_device->device = device;
1076 /* cache the device descriptor */
1077 ret = darwin_cache_device_descriptor(new_device);
1081 if (new_device->can_enumerate) {
1082 snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address,
1083 new_device->dev_descriptor.idVendor, new_device->dev_descriptor.idProduct,
1084 new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass);
1088 usbi_mutex_unlock(&darwin_cached_devices_lock);
1093 static enum libusb_error process_new_device (struct libusb_context *ctx, struct darwin_cached_device *cached_device,
1094 UInt64 old_session_id) {
1095 struct darwin_device_priv *priv;
1096 struct libusb_device *dev = NULL;
1098 enum libusb_error ret = LIBUSB_SUCCESS;
1101 /* check current active configuration (and cache the first configuration value--
1102 which may be used by claim_interface) */
1103 ret = darwin_check_configuration (ctx, cached_device);
1107 if (0 != old_session_id) {
1108 usbi_dbg ("re-using existing device from context %p for with session 0x%" PRIx64 " new session 0x%" PRIx64,
1109 ctx, old_session_id, cached_device->session);
1110 /* save the libusb device before the session id is updated */
1111 dev = usbi_get_device_by_session_id (ctx, (unsigned long) old_session_id);
1115 usbi_dbg ("allocating new device in context %p for with session 0x%" PRIx64,
1116 ctx, cached_device->session);
1118 dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
1120 return LIBUSB_ERROR_NO_MEM;
1123 priv = usbi_get_device_priv(dev);
1125 priv->dev = cached_device;
1126 darwin_ref_cached_device (priv->dev);
1127 dev->port_number = cached_device->port;
1128 dev->bus_number = cached_device->location >> 24;
1129 assert(cached_device->address <= UINT8_MAX);
1130 dev->device_address = (uint8_t)cached_device->address;
1132 priv = usbi_get_device_priv(dev);
1135 if (cached_device->parent_session > 0) {
1136 dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session);
1138 dev->parent_dev = NULL;
1141 (*(priv->dev->device))->GetDeviceSpeed (priv->dev->device, &devSpeed);
1144 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
1145 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
1146 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
1147 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
1148 case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
1150 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101200
1151 case kUSBDeviceSpeedSuperPlus: dev->speed = LIBUSB_SPEED_SUPER_PLUS; break;
1154 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
1157 ret = usbi_sanitize_device (dev);
1161 usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
1162 dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
1166 if (!cached_device->in_reenumerate && 0 == ret) {
1167 usbi_connect_device (dev);
1169 libusb_unref_device (dev);
1175 static enum libusb_error darwin_scan_devices(struct libusb_context *ctx) {
1176 struct darwin_cached_device *cached_device;
1177 UInt64 old_session_id;
1178 io_iterator_t deviceIterator;
1179 io_service_t service;
1183 kresult = usb_setup_device_iterator (&deviceIterator, 0);
1184 if (kresult != kIOReturnSuccess)
1185 return darwin_to_libusb (kresult);
1187 while ((service = IOIteratorNext (deviceIterator))) {
1188 ret = darwin_get_cached_device (service, &cached_device, &old_session_id);
1189 if (ret < 0 || !cached_device->can_enumerate) {
1193 (void) process_new_device (ctx, cached_device, old_session_id);
1195 IOObjectRelease(service);
1198 IOObjectRelease(deviceIterator);
1200 return LIBUSB_SUCCESS;
1203 static int darwin_open (struct libusb_device_handle *dev_handle) {
1204 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1205 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1208 if (0 == dpriv->open_count) {
1209 /* try to open the device */
1210 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
1211 if (kresult != kIOReturnSuccess) {
1212 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
1214 if (kIOReturnExclusiveAccess != kresult) {
1215 return darwin_to_libusb (kresult);
1218 /* it is possible to perform some actions on a device that is not open so do not return an error */
1219 priv->is_open = false;
1221 priv->is_open = true;
1224 /* create async event source */
1225 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
1226 if (kresult != kIOReturnSuccess) {
1227 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
1229 if (priv->is_open) {
1230 (*(dpriv->device))->USBDeviceClose (dpriv->device);
1233 priv->is_open = false;
1235 return darwin_to_libusb (kresult);
1238 CFRetain (libusb_darwin_acfl);
1240 /* add the cfSource to the aync run loop */
1241 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
1244 /* device opened successfully */
1245 dpriv->open_count++;
1247 usbi_dbg ("device open for access");
1252 static void darwin_close (struct libusb_device_handle *dev_handle) {
1253 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1254 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1258 if (dpriv->open_count == 0) {
1259 /* something is probably very wrong if this is the case */
1260 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!");
1264 dpriv->open_count--;
1266 /* make sure all interfaces are released */
1267 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1268 if (dev_handle->claimed_interfaces & (1U << i))
1269 libusb_release_interface (dev_handle, i);
1271 if (0 == dpriv->open_count) {
1272 /* delete the device's async event source */
1273 if (priv->cfSource) {
1274 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
1275 CFRelease (priv->cfSource);
1276 priv->cfSource = NULL;
1277 CFRelease (libusb_darwin_acfl);
1280 if (priv->is_open) {
1281 /* close the device */
1282 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
1283 if (kresult != kIOReturnSuccess) {
1284 /* Log the fact that we had a problem closing the file, however failing a
1285 * close isn't really an error, so return success anyway */
1286 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
1292 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
1293 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1295 *config = (int) dpriv->active_config;
1297 return LIBUSB_SUCCESS;
1300 static enum libusb_error darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
1301 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1305 assert(config >= 0 && config <= UINT8_MAX);
1307 /* Setting configuration will invalidate the interface, so we need
1308 to reclaim it. First, dispose of existing interfaces, if any. */
1309 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1310 if (dev_handle->claimed_interfaces & (1U << i))
1311 darwin_release_interface (dev_handle, i);
1313 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, (UInt8)config);
1314 if (kresult != kIOReturnSuccess)
1315 return darwin_to_libusb (kresult);
1317 /* Reclaim any interfaces. */
1318 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1319 if (dev_handle->claimed_interfaces & (1U << i))
1320 darwin_claim_interface (dev_handle, i);
1322 dpriv->active_config = (UInt8)config;
1324 return LIBUSB_SUCCESS;
1327 static IOReturn darwin_get_interface (usb_device_t **darwin_device, int ifc, io_service_t *usbInterfacep) {
1328 IOUSBFindInterfaceRequest request;
1330 io_iterator_t interface_iterator;
1331 UInt8 bInterfaceNumber;
1334 *usbInterfacep = IO_OBJECT_NULL;
1336 /* Setup the Interface Request */
1337 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1338 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1339 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1340 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1342 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1343 if (kresult != kIOReturnSuccess)
1346 while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1347 /* find the interface number */
1348 ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
1351 if (ret && bInterfaceNumber == ifc) {
1355 (void) IOObjectRelease (*usbInterfacep);
1358 /* done with the interface iterator */
1359 IOObjectRelease(interface_iterator);
1361 return kIOReturnSuccess;
1364 static enum libusb_error get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
1365 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1367 /* current interface */
1368 struct darwin_interface *cInterface = &priv->interfaces[iface];
1372 UInt8 numep, direction, number;
1373 UInt8 dont_care1, dont_care3;
1377 usbi_dbg ("building table of endpoints.");
1379 /* retrieve the total number of endpoints on this interface */
1380 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1381 if (kresult != kIOReturnSuccess) {
1382 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1383 return darwin_to_libusb (kresult);
1386 /* iterate through pipe references */
1387 for (UInt8 i = 1 ; i <= numep ; i++) {
1388 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1389 &dont_care2, &dont_care3);
1391 if (kresult != kIOReturnSuccess) {
1392 /* probably a buggy device. try to get the endpoint address from the descriptors */
1393 struct libusb_config_descriptor *config;
1394 const struct libusb_endpoint_descriptor *endpoint_desc;
1397 kresult = (*(cInterface->interface))->GetAlternateSetting (cInterface->interface, &alt_setting);
1398 if (kresult != kIOReturnSuccess) {
1399 usbi_err (HANDLE_CTX (dev_handle), "can't get alternate setting for interface");
1400 return darwin_to_libusb (kresult);
1403 rc = libusb_get_active_config_descriptor (dev_handle->dev, &config);
1404 if (LIBUSB_SUCCESS != rc) {
1408 endpoint_desc = config->interface[iface].altsetting[alt_setting].endpoint + i - 1;
1410 cInterface->endpoint_addrs[i - 1] = endpoint_desc->bEndpointAddress;
1412 cInterface->endpoint_addrs[i - 1] = (UInt8)(((kUSBIn == direction) << kUSBRqDirnShift) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1415 usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, cInterface->endpoint_addrs[i - 1] >> kUSBRqDirnShift,
1416 cInterface->endpoint_addrs[i - 1] & LIBUSB_ENDPOINT_ADDRESS_MASK);
1419 cInterface->num_endpoints = numep;
1421 return LIBUSB_SUCCESS;
1424 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1425 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1426 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1427 io_service_t usbInterface = IO_OBJECT_NULL;
1429 enum libusb_error ret;
1430 IOCFPlugInInterface **plugInInterface = NULL;
1433 assert(iface >= 0 && iface <= UINT8_MAX);
1435 /* current interface */
1436 struct darwin_interface *cInterface = &priv->interfaces[iface];
1438 kresult = darwin_get_interface (dpriv->device, (uint8_t)iface, &usbInterface);
1439 if (kresult != kIOReturnSuccess)
1440 return darwin_to_libusb (kresult);
1442 /* make sure we have an interface */
1443 if (!usbInterface && dpriv->first_config != 0) {
1444 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1446 /* set the configuration */
1447 ret = darwin_set_configuration (dev_handle, dpriv->first_config);
1448 if (ret != LIBUSB_SUCCESS) {
1449 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1453 kresult = darwin_get_interface (dpriv->device, (uint8_t)iface, &usbInterface);
1454 if (kresult != kIOReturnSuccess) {
1455 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1456 return darwin_to_libusb (kresult);
1460 if (!usbInterface) {
1461 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1462 return LIBUSB_ERROR_NOT_FOUND;
1465 /* get an interface to the device's interface */
1466 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1467 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1469 /* ignore release error */
1470 (void)IOObjectRelease (usbInterface);
1472 if (kresult != kIOReturnSuccess) {
1473 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1474 return darwin_to_libusb (kresult);
1477 if (!plugInInterface) {
1478 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1479 return LIBUSB_ERROR_NOT_FOUND;
1482 /* Do the actual claim */
1483 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1484 CFUUIDGetUUIDBytes(InterfaceInterfaceID),
1485 (LPVOID)&cInterface->interface);
1486 /* We no longer need the intermediate plug-in */
1487 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1488 (*plugInInterface)->Release (plugInInterface);
1489 if (kresult != kIOReturnSuccess || !cInterface->interface) {
1490 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1491 return darwin_to_libusb (kresult);
1494 /* claim the interface */
1495 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1496 if (kresult != kIOReturnSuccess) {
1497 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1498 return darwin_to_libusb (kresult);
1501 /* update list of endpoints */
1502 ret = get_endpoints (dev_handle, iface);
1504 /* this should not happen */
1505 darwin_release_interface (dev_handle, iface);
1506 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1510 cInterface->cfSource = NULL;
1512 /* create async event source */
1513 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1514 if (kresult != kIOReturnSuccess) {
1515 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1517 /* can't continue without an async event source */
1518 (void)darwin_release_interface (dev_handle, iface);
1520 return darwin_to_libusb (kresult);
1523 /* add the cfSource to the async thread's run loop */
1524 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1526 usbi_dbg ("interface opened");
1528 return LIBUSB_SUCCESS;
1531 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1532 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1535 /* current interface */
1536 struct darwin_interface *cInterface = &priv->interfaces[iface];
1538 /* Check to see if an interface is open */
1539 if (!cInterface->interface)
1540 return LIBUSB_SUCCESS;
1542 /* clean up endpoint data */
1543 cInterface->num_endpoints = 0;
1545 /* delete the interface's async event source */
1546 if (cInterface->cfSource) {
1547 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1548 CFRelease (cInterface->cfSource);
1551 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1552 if (kresult != kIOReturnSuccess)
1553 usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1555 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1556 if (kresult != kIOReturnSuccess)
1557 usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1559 cInterface->interface = (usb_interface_t **) IO_OBJECT_NULL;
1561 return darwin_to_libusb (kresult);
1564 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1565 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1567 enum libusb_error ret;
1569 /* current interface */
1570 struct darwin_interface *cInterface = &priv->interfaces[iface];
1572 if (!cInterface->interface)
1573 return LIBUSB_ERROR_NO_DEVICE;
1575 assert(altsetting >= 0 && altsetting <= UINT8_MAX);
1576 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, (UInt8)altsetting);
1577 if (kresult != kIOReturnSuccess)
1578 darwin_reset_device (dev_handle);
1580 /* update list of endpoints */
1581 ret = get_endpoints (dev_handle, iface);
1583 /* this should not happen */
1584 darwin_release_interface (dev_handle, iface);
1585 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1589 return darwin_to_libusb (kresult);
1592 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1593 /* current interface */
1594 struct darwin_interface *cInterface;
1598 /* determine the interface/endpoint to use */
1599 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, NULL, &cInterface) != 0) {
1600 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1602 return LIBUSB_ERROR_NOT_FOUND;
1605 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1606 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1607 if (kresult != kIOReturnSuccess)
1608 usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1610 return darwin_to_libusb (kresult);
1613 static int darwin_restore_state (struct libusb_device_handle *dev_handle, int8_t active_config,
1614 unsigned long claimed_interfaces) {
1615 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1616 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1617 int open_count = dpriv->open_count;
1620 /* clear claimed interfaces temporarily */
1621 dev_handle->claimed_interfaces = 0;
1623 /* close and re-open the device */
1624 priv->is_open = false;
1625 dpriv->open_count = 1;
1627 /* clean up open interfaces */
1628 (void) darwin_close (dev_handle);
1630 /* re-open the device */
1631 ret = darwin_open (dev_handle);
1632 dpriv->open_count = open_count;
1633 if (LIBUSB_SUCCESS != ret) {
1634 /* could not restore configuration */
1635 return LIBUSB_ERROR_NOT_FOUND;
1638 if (dpriv->active_config != active_config) {
1639 usbi_dbg ("darwin/restore_state: restoring configuration %d...", active_config);
1641 ret = darwin_set_configuration (dev_handle, active_config);
1642 if (LIBUSB_SUCCESS != ret) {
1643 usbi_dbg ("darwin/restore_state: could not restore configuration");
1644 return LIBUSB_ERROR_NOT_FOUND;
1648 usbi_dbg ("darwin/restore_state: reclaiming interfaces");
1650 if (claimed_interfaces) {
1651 for (int iface = 0 ; iface < USB_MAXINTERFACES ; ++iface) {
1652 if (!(claimed_interfaces & (1U << iface))) {
1656 usbi_dbg ("darwin/restore_state: re-claiming interface %d", iface);
1658 ret = darwin_claim_interface (dev_handle, iface);
1659 if (LIBUSB_SUCCESS != ret) {
1660 usbi_dbg ("darwin/restore_state: could not claim interface %d", iface);
1661 return LIBUSB_ERROR_NOT_FOUND;
1664 dev_handle->claimed_interfaces |= 1U << iface;
1668 usbi_dbg ("darwin/restore_state: device state restored");
1670 return LIBUSB_SUCCESS;
1673 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1674 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1675 unsigned long claimed_interfaces = dev_handle->claimed_interfaces;
1676 int8_t active_config = dpriv->active_config;
1677 IOUSBDeviceDescriptor descriptor;
1678 IOUSBConfigurationDescriptorPtr cached_configuration;
1679 IOUSBConfigurationDescriptor *cached_configurations;
1683 if (dpriv->in_reenumerate) {
1684 /* ack, two (or more) threads are trying to reset the device! abort! */
1685 return LIBUSB_ERROR_NOT_FOUND;
1688 dpriv->in_reenumerate = true;
1690 /* store copies of descriptors so they can be compared after the reset */
1691 memcpy (&descriptor, &dpriv->dev_descriptor, sizeof (descriptor));
1692 cached_configurations = alloca (sizeof (*cached_configurations) * descriptor.bNumConfigurations);
1694 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1695 (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1696 memcpy (cached_configurations + i, cached_configuration, sizeof (cached_configurations[i]));
1699 /* from macOS 10.11 ResetDevice no longer does anything so just use USBDeviceReEnumerate */
1700 kresult = (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
1701 if (kresult != kIOReturnSuccess) {
1702 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceReEnumerate: %s", darwin_error_str (kresult));
1703 dpriv->in_reenumerate = false;
1704 return darwin_to_libusb (kresult);
1707 usbi_dbg ("darwin/reset_device: waiting for re-enumeration to complete...");
1709 while (dpriv->in_reenumerate) {
1710 struct timespec delay = {.tv_sec = 0, .tv_nsec = 1000};
1711 nanosleep (&delay, NULL);
1714 /* compare descriptors */
1715 usbi_dbg ("darwin/reset_device: checking whether descriptors changed");
1717 if (memcmp (&descriptor, &dpriv->dev_descriptor, sizeof (descriptor))) {
1718 /* device descriptor changed. need to return not found. */
1719 usbi_dbg ("darwin/reset_device: device descriptor changed");
1720 return LIBUSB_ERROR_NOT_FOUND;
1723 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1724 (void) (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1725 if (memcmp (cached_configuration, cached_configurations + i, sizeof (cached_configurations[i]))) {
1726 usbi_dbg ("darwin/reset_device: configuration descriptor %d changed", i);
1727 return LIBUSB_ERROR_NOT_FOUND;
1731 usbi_dbg ("darwin/reset_device: device reset complete. restoring state...");
1733 return darwin_restore_state (dev_handle, active_config, claimed_interfaces);
1736 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1737 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1738 io_service_t usbInterface;
1742 assert(interface >= 0 && interface <= UINT8_MAX);
1743 kresult = darwin_get_interface (dpriv->device, (uint8_t)interface, &usbInterface);
1744 if (kresult != kIOReturnSuccess) {
1745 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1747 return darwin_to_libusb (kresult);
1750 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1751 IOObjectRelease (usbInterface);
1763 static void darwin_destroy_device(struct libusb_device *dev) {
1764 struct darwin_device_priv *dpriv = usbi_get_device_priv(dev);
1767 /* need to hold the lock in case this is the last reference to the device */
1768 usbi_mutex_lock(&darwin_cached_devices_lock);
1769 darwin_deref_cached_device (dpriv->dev);
1771 usbi_mutex_unlock(&darwin_cached_devices_lock);
1775 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1776 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1779 uint8_t transferType;
1780 /* None of the values below are used in libusbx for bulk transfers */
1781 uint8_t direction, number, interval, pipeRef;
1782 uint16_t maxPacketSize;
1784 struct darwin_interface *cInterface;
1786 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1787 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1789 return LIBUSB_ERROR_NOT_FOUND;
1792 ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1793 &transferType, &maxPacketSize, &interval);
1796 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1797 darwin_error_str(ret), ret);
1798 return darwin_to_libusb (ret);
1801 if (0 != (transfer->length % maxPacketSize)) {
1802 /* do not need a zero packet */
1803 transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1806 /* submit the request */
1807 /* timeouts are unavailable on interrupt endpoints */
1808 if (transferType == kUSBInterrupt) {
1809 if (IS_XFERIN(transfer))
1810 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1811 (UInt32)transfer->length, darwin_async_io_callback, itransfer);
1813 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1814 (UInt32)transfer->length, darwin_async_io_callback, itransfer);
1816 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1818 if (IS_XFERIN(transfer))
1819 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1820 (UInt32)transfer->length, transfer->timeout, transfer->timeout,
1821 darwin_async_io_callback, itransfer);
1823 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1824 (UInt32)transfer->length, transfer->timeout, transfer->timeout,
1825 darwin_async_io_callback, itransfer);
1829 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1830 darwin_error_str(ret), ret);
1832 return darwin_to_libusb (ret);
1835 #if InterfaceVersion >= 550
1836 static int submit_stream_transfer(struct usbi_transfer *itransfer) {
1837 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1838 struct darwin_interface *cInterface;
1842 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1843 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1845 return LIBUSB_ERROR_NOT_FOUND;
1848 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1850 if (IS_XFERIN(transfer))
1851 ret = (*(cInterface->interface))->ReadStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1852 transfer->buffer, (UInt32)transfer->length, transfer->timeout,
1853 transfer->timeout, darwin_async_io_callback, itransfer);
1855 ret = (*(cInterface->interface))->WriteStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1856 transfer->buffer, (UInt32)transfer->length, transfer->timeout,
1857 transfer->timeout, darwin_async_io_callback, itransfer);
1860 usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1861 darwin_error_str(ret), ret);
1863 return darwin_to_libusb (ret);
1867 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1868 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1869 struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
1872 uint8_t direction, number, interval, pipeRef, transferType;
1873 uint16_t maxPacketSize;
1875 AbsoluteTime atTime;
1878 struct darwin_interface *cInterface;
1880 /* construct an array of IOUSBIsocFrames, reuse the old one if the sizes are the same */
1881 if (tpriv->num_iso_packets != transfer->num_iso_packets) {
1882 free(tpriv->isoc_framelist);
1883 tpriv->isoc_framelist = NULL;
1886 if (!tpriv->isoc_framelist) {
1887 tpriv->num_iso_packets = transfer->num_iso_packets;
1888 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc ((size_t)transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1889 if (!tpriv->isoc_framelist)
1890 return LIBUSB_ERROR_NO_MEM;
1893 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1894 for (i = 0 ; i < transfer->num_iso_packets ; i++) {
1895 unsigned int length = transfer->iso_packet_desc[i].length;
1896 assert(length <= UINT16_MAX);
1897 tpriv->isoc_framelist[i].frReqCount = (UInt16)length;
1900 /* determine the interface/endpoint to use */
1901 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1902 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1904 return LIBUSB_ERROR_NOT_FOUND;
1907 /* determine the properties of this endpoint and the speed of the device */
1908 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1909 &transferType, &maxPacketSize, &interval);
1911 /* Last but not least we need the bus frame number */
1912 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1913 if (kresult != kIOReturnSuccess) {
1914 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1915 free(tpriv->isoc_framelist);
1916 tpriv->isoc_framelist = NULL;
1918 return darwin_to_libusb (kresult);
1921 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1922 &transferType, &maxPacketSize, &interval);
1924 /* schedule for a frame a little in the future */
1927 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1928 frame = cInterface->frames[transfer->endpoint];
1930 /* submit the request */
1931 if (IS_XFERIN(transfer))
1932 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1933 (UInt32)transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1936 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1937 (UInt32)transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1940 if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
1942 cInterface->frames[transfer->endpoint] = frame + (UInt32)transfer->num_iso_packets * (1U << (interval - 1));
1944 /* High/super speed */
1945 cInterface->frames[transfer->endpoint] = frame + (UInt32)transfer->num_iso_packets * (1U << (interval - 1)) / 8;
1947 if (kresult != kIOReturnSuccess) {
1948 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1949 darwin_error_str(kresult));
1950 free (tpriv->isoc_framelist);
1951 tpriv->isoc_framelist = NULL;
1954 return darwin_to_libusb (kresult);
1957 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1958 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1959 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1960 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1961 struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
1965 memset(&tpriv->req, 0, sizeof(tpriv->req));
1967 /* IOUSBDeviceInterface expects the request in cpu endianness */
1968 tpriv->req.bmRequestType = setup->bmRequestType;
1969 tpriv->req.bRequest = setup->bRequest;
1970 /* these values should be in bus order from libusb_fill_control_setup */
1971 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1972 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1973 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1974 /* data is stored after the libusb control block */
1975 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1976 tpriv->req.completionTimeout = transfer->timeout;
1977 tpriv->req.noDataTimeout = transfer->timeout;
1979 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1981 /* all transfers in libusb-1.0 are async */
1983 if (transfer->endpoint) {
1984 struct darwin_interface *cInterface;
1987 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1988 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1990 return LIBUSB_ERROR_NOT_FOUND;
1993 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1995 /* control request on endpoint 0 */
1996 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1998 if (kresult != kIOReturnSuccess)
1999 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
2001 return darwin_to_libusb (kresult);
2004 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
2005 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2007 switch (transfer->type) {
2008 case LIBUSB_TRANSFER_TYPE_CONTROL:
2009 return submit_control_transfer(itransfer);
2010 case LIBUSB_TRANSFER_TYPE_BULK:
2011 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2012 return submit_bulk_transfer(itransfer);
2013 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2014 return submit_iso_transfer(itransfer);
2015 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2016 #if InterfaceVersion >= 550
2017 return submit_stream_transfer(itransfer);
2019 usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers");
2020 return LIBUSB_ERROR_NOT_SUPPORTED;
2023 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
2024 return LIBUSB_ERROR_INVALID_PARAM;
2028 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
2029 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2030 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
2033 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
2036 return LIBUSB_ERROR_NO_DEVICE;
2038 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
2040 return darwin_to_libusb (kresult);
2043 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
2044 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2045 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
2046 struct darwin_interface *cInterface;
2047 uint8_t pipeRef, iface;
2050 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) {
2051 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
2053 return LIBUSB_ERROR_NOT_FOUND;
2057 return LIBUSB_ERROR_NO_DEVICE;
2059 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
2061 /* abort transactions */
2062 #if InterfaceVersion >= 550
2063 if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type)
2064 (*(cInterface->interface))->AbortStreamsPipe (cInterface->interface, pipeRef, itransfer->stream_id);
2067 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
2069 usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
2071 /* newer versions of darwin support clearing additional bits on the device's endpoint */
2072 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
2074 return darwin_to_libusb (kresult);
2077 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
2078 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2080 switch (transfer->type) {
2081 case LIBUSB_TRANSFER_TYPE_CONTROL:
2082 return cancel_control_transfer(itransfer);
2083 case LIBUSB_TRANSFER_TYPE_BULK:
2084 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2085 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2086 return darwin_abort_transfers (itransfer);
2088 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
2089 return LIBUSB_ERROR_INVALID_PARAM;
2093 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
2094 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
2095 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2096 struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2098 usbi_dbg ("an async io operation has completed");
2100 /* if requested write a zero packet */
2101 if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
2102 struct darwin_interface *cInterface;
2105 (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface);
2107 (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
2110 tpriv->result = result;
2111 tpriv->size = (UInt32) (uintptr_t) arg0;
2113 /* signal the core that this transfer is complete */
2114 usbi_signal_transfer_completion(itransfer);
2117 static enum libusb_transfer_status darwin_transfer_status (struct usbi_transfer *itransfer, IOReturn result) {
2118 if (itransfer->timeout_flags & USBI_TRANSFER_TIMED_OUT)
2119 result = kIOUSBTransactionTimeout;
2122 case kIOReturnUnderrun:
2123 case kIOReturnSuccess:
2124 return LIBUSB_TRANSFER_COMPLETED;
2125 case kIOReturnAborted:
2126 return LIBUSB_TRANSFER_CANCELLED;
2127 case kIOUSBPipeStalled:
2128 usbi_dbg ("transfer error: pipe is stalled");
2129 return LIBUSB_TRANSFER_STALL;
2130 case kIOReturnOverrun:
2131 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
2132 return LIBUSB_TRANSFER_OVERFLOW;
2133 case kIOUSBTransactionTimeout:
2134 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
2135 itransfer->timeout_flags |= USBI_TRANSFER_TIMED_OUT;
2136 return LIBUSB_TRANSFER_TIMED_OUT;
2138 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
2139 return LIBUSB_TRANSFER_ERROR;
2143 static int darwin_handle_transfer_completion (struct usbi_transfer *itransfer) {
2144 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2145 struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2146 bool isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
2147 bool isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
2148 bool isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
2149 bool isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
2152 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
2153 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
2154 return LIBUSB_ERROR_INVALID_PARAM;
2157 usbi_dbg ("handling %s completion with kernel status %d",
2158 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", tpriv->result);
2160 if (kIOReturnSuccess == tpriv->result || kIOReturnUnderrun == tpriv->result) {
2161 if (isIsoc && tpriv->isoc_framelist) {
2162 /* copy isochronous results back */
2164 for (i = 0; i < transfer->num_iso_packets ; i++) {
2165 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
2166 lib_desc->status = darwin_transfer_status (itransfer, tpriv->isoc_framelist[i].frStatus);
2167 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
2170 itransfer->transferred += tpriv->size;
2173 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
2174 return usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, tpriv->result));
2177 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
2178 #if !OSX_USE_CLOCK_GETTIME
2179 mach_timespec_t sys_time;
2180 clock_serv_t clock_ref;
2183 case USBI_CLOCK_REALTIME:
2184 /* CLOCK_REALTIME represents time since the epoch */
2185 clock_ref = clock_realtime;
2187 case USBI_CLOCK_MONOTONIC:
2188 /* use system boot time as reference for the monotonic clock */
2189 clock_ref = clock_monotonic;
2192 return LIBUSB_ERROR_INVALID_PARAM;
2195 clock_get_time (clock_ref, &sys_time);
2197 tp->tv_sec = sys_time.tv_sec;
2198 tp->tv_nsec = sys_time.tv_nsec;
2200 return LIBUSB_SUCCESS;
2203 case USBI_CLOCK_MONOTONIC:
2204 return clock_gettime(CLOCK_MONOTONIC, tp);
2205 case USBI_CLOCK_REALTIME:
2206 return clock_gettime(CLOCK_REALTIME, tp);
2208 return LIBUSB_ERROR_INVALID_PARAM;
2213 #if InterfaceVersion >= 550
2214 static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints,
2215 int num_endpoints) {
2216 struct darwin_interface *cInterface;
2217 UInt32 supportsStreams;
2221 /* find the mimimum number of supported streams on the endpoint list */
2222 for (i = 0 ; i < num_endpoints ; ++i) {
2223 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) {
2227 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2228 if (num_streams > supportsStreams)
2229 num_streams = supportsStreams;
2232 /* it is an error if any endpoint in endpoints does not support streams */
2233 if (0 == num_streams)
2234 return LIBUSB_ERROR_INVALID_PARAM;
2236 /* create the streams */
2237 for (i = 0 ; i < num_endpoints ; ++i) {
2238 (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
2240 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, num_streams);
2241 if (kIOReturnSuccess != rc)
2242 return darwin_to_libusb(rc);
2245 assert(num_streams <= INT_MAX);
2246 return (int)num_streams;
2249 static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) {
2250 struct darwin_interface *cInterface;
2251 UInt32 supportsStreams;
2255 for (int i = 0 ; i < num_endpoints ; ++i) {
2256 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface)))
2259 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2260 if (0 == supportsStreams)
2261 return LIBUSB_ERROR_INVALID_PARAM;
2263 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, 0);
2264 if (kIOReturnSuccess != rc)
2265 return darwin_to_libusb(rc);
2268 return LIBUSB_SUCCESS;
2272 const struct usbi_os_backend usbi_backend = {
2275 .init = darwin_init,
2276 .exit = darwin_exit,
2277 .get_device_descriptor = darwin_get_device_descriptor,
2278 .get_active_config_descriptor = darwin_get_active_config_descriptor,
2279 .get_config_descriptor = darwin_get_config_descriptor,
2280 .hotplug_poll = darwin_hotplug_poll,
2282 .open = darwin_open,
2283 .close = darwin_close,
2284 .get_configuration = darwin_get_configuration,
2285 .set_configuration = darwin_set_configuration,
2286 .claim_interface = darwin_claim_interface,
2287 .release_interface = darwin_release_interface,
2289 .set_interface_altsetting = darwin_set_interface_altsetting,
2290 .clear_halt = darwin_clear_halt,
2291 .reset_device = darwin_reset_device,
2293 #if InterfaceVersion >= 550
2294 .alloc_streams = darwin_alloc_streams,
2295 .free_streams = darwin_free_streams,
2298 .kernel_driver_active = darwin_kernel_driver_active,
2300 .destroy_device = darwin_destroy_device,
2302 .submit_transfer = darwin_submit_transfer,
2303 .cancel_transfer = darwin_cancel_transfer,
2305 .handle_transfer_completion = darwin_handle_transfer_completion,
2307 .clock_gettime = darwin_clock_gettime,
2309 .device_priv_size = sizeof(struct darwin_device_priv),
2310 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
2311 .transfer_priv_size = sizeof(struct darwin_transfer_priv),