1 /* -*- Mode: C; indent-tabs-mode:nil -*- */
3 * darwin backend for libusb 1.0
4 * Copyright © 2008-2020 Nathan Hjelm <hjelmn@cs.unm.edu>
5 * Copyright © 2019-2020 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
30 #include <sys/types.h>
33 #include <sys/sysctl.h>
35 #include <mach/clock.h>
36 #include <mach/clock_types.h>
37 #include <mach/mach_host.h>
38 #include <mach/mach_port.h>
40 /* Suppress warnings about the use of the deprecated objc_registerThreadWithCollector
41 * function. Its use is also conditionalized to only older deployment targets. */
42 #define OBJC_SILENCE_GC_DEPRECATIONS 1
44 /* Default timeout to 10s for reenumerate. This is needed because USBDeviceReEnumerate
45 * does not return error status on macOS. */
46 #define DARWIN_REENUMERATE_TIMEOUT_US 10000000
48 #include <AvailabilityMacros.h>
49 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
50 #include <objc/objc-auto.h>
53 #include "darwin_usb.h"
55 static pthread_mutex_t libusb_darwin_init_mutex = PTHREAD_MUTEX_INITIALIZER;
56 static int init_count = 0;
58 /* async event thread */
59 static pthread_mutex_t libusb_darwin_at_mutex = PTHREAD_MUTEX_INITIALIZER;
60 static pthread_cond_t libusb_darwin_at_cond = PTHREAD_COND_INITIALIZER;
62 #if !defined(HAVE_CLOCK_GETTIME)
63 static clock_serv_t clock_realtime;
64 static clock_serv_t clock_monotonic;
67 #define LIBUSB_DARWIN_STARTUP_FAILURE ((CFRunLoopRef) -1)
69 static CFRunLoopRef libusb_darwin_acfl = NULL; /* event cf loop */
70 static CFRunLoopSourceRef libusb_darwin_acfls = NULL; /* shutdown signal for event cf loop */
72 static usbi_mutex_t darwin_cached_devices_lock = PTHREAD_MUTEX_INITIALIZER;
73 static struct list_head darwin_cached_devices;
74 static const char *darwin_device_class = "IOUSBDevice";
76 #define DARWIN_CACHED_DEVICE(a) (((struct darwin_device_priv *)usbi_get_device_priv((a)))->dev)
78 /* async event thread */
79 static pthread_t libusb_darwin_at;
81 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, void *buffer, size_t len);
82 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, uint8_t iface);
83 static int darwin_release_interface(struct libusb_device_handle *dev_handle, uint8_t iface);
84 static int darwin_reenumerate_device(struct libusb_device_handle *dev_handle, bool capture);
85 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
86 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
88 static enum libusb_error darwin_scan_devices(struct libusb_context *ctx);
89 static enum libusb_error process_new_device (struct libusb_context *ctx, struct darwin_cached_device *cached_device,
90 UInt64 old_session_id);
92 static enum libusb_error darwin_get_cached_device(io_service_t service, struct darwin_cached_device **cached_out,
93 UInt64 *old_session_id);
95 #if defined(ENABLE_LOGGING)
96 static const char *darwin_error_str (IOReturn result) {
97 static char string_buffer[50];
99 case kIOReturnSuccess:
101 case kIOReturnNotOpen:
102 return "device not opened for exclusive access";
103 case kIOReturnNoDevice:
104 return "no connection to an IOService";
105 case kIOUSBNoAsyncPortErr:
106 return "no async port has been opened for interface";
107 case kIOReturnExclusiveAccess:
108 return "another process has device opened for exclusive access";
109 case kIOUSBPipeStalled:
110 return "pipe is stalled";
112 return "could not establish a connection to the Darwin kernel";
113 case kIOUSBTransactionTimeout:
114 return "transaction timed out";
115 case kIOReturnBadArgument:
116 return "invalid argument";
117 case kIOReturnAborted:
118 return "transaction aborted";
119 case kIOReturnNotResponding:
120 return "device not responding";
121 case kIOReturnOverrun:
122 return "data overrun";
123 case kIOReturnCannotWire:
124 return "physical memory can not be wired down";
125 case kIOReturnNoResources:
126 return "out of resources";
127 case kIOUSBHighSpeedSplitError:
128 return "high speed split error";
129 case kIOUSBUnknownPipeErr:
130 return "pipe ref not recognized";
132 snprintf(string_buffer, sizeof(string_buffer), "unknown error (0x%x)", result);
133 return string_buffer;
138 static enum libusb_error darwin_to_libusb (IOReturn result) {
140 case kIOReturnUnderrun:
141 case kIOReturnSuccess:
142 return LIBUSB_SUCCESS;
143 case kIOReturnNotOpen:
144 case kIOReturnNoDevice:
145 return LIBUSB_ERROR_NO_DEVICE;
146 case kIOReturnExclusiveAccess:
147 return LIBUSB_ERROR_ACCESS;
148 case kIOUSBPipeStalled:
149 return LIBUSB_ERROR_PIPE;
150 case kIOReturnBadArgument:
151 return LIBUSB_ERROR_INVALID_PARAM;
152 case kIOUSBTransactionTimeout:
153 return LIBUSB_ERROR_TIMEOUT;
154 case kIOReturnNotResponding:
155 case kIOReturnAborted:
157 case kIOUSBNoAsyncPortErr:
158 case kIOUSBUnknownPipeErr:
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;
175 IOObjectRelease (cached_dev->service);
180 static void darwin_ref_cached_device(struct darwin_cached_device *cached_dev) {
181 cached_dev->refcount++;
184 static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp, struct darwin_interface **interface_out) {
185 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
187 /* current interface */
188 struct darwin_interface *cInterface;
192 usbi_dbg ("converting ep address 0x%02x to pipeRef and interface", ep);
194 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
195 cInterface = &priv->interfaces[iface];
197 if (dev_handle->claimed_interfaces & (1U << iface)) {
198 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
199 if (cInterface->endpoint_addrs[i] == ep) {
206 *interface_out = cInterface;
208 usbi_dbg ("pipe %d on interface %d matches", *pipep, iface);
209 return LIBUSB_SUCCESS;
215 /* No pipe found with the correct endpoint address */
216 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
218 return LIBUSB_ERROR_NOT_FOUND;
221 static IOReturn usb_setup_device_iterator (io_iterator_t *deviceIterator, UInt32 location) {
222 CFMutableDictionaryRef matchingDict = IOServiceMatching(darwin_device_class);
225 return kIOReturnError;
228 CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
229 &kCFTypeDictionaryKeyCallBacks,
230 &kCFTypeDictionaryValueCallBacks);
232 /* there are no unsigned CFNumber types so treat the value as signed. the OS seems to do this
233 internally (CFNumberType of locationID is kCFNumberSInt32Type) */
234 CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberSInt32Type, &location);
236 if (propertyMatchDict && locationCF) {
237 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
238 CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
240 /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
242 /* release our references as per the Create Rule */
243 if (propertyMatchDict)
244 CFRelease (propertyMatchDict);
246 CFRelease (locationCF);
249 return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator);
252 /* Returns 1 on success, 0 on failure. */
253 static bool get_ioregistry_value_number (io_service_t service, CFStringRef property, CFNumberType type, void *p) {
254 CFTypeRef cfNumber = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
258 if (CFGetTypeID(cfNumber) == CFNumberGetTypeID()) {
259 success = CFNumberGetValue(cfNumber, type, p);
262 CFRelease (cfNumber);
265 return (success != 0);
268 /* Returns 1 on success, 0 on failure. */
269 static bool get_ioregistry_value_data (io_service_t service, CFStringRef property, ssize_t size, void *p) {
270 CFTypeRef cfData = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
271 bool success = false;
274 if (CFGetTypeID (cfData) == CFDataGetTypeID ()) {
275 CFIndex length = CFDataGetLength (cfData);
280 CFDataGetBytes (cfData, CFRangeMake(0, size), p);
290 static usb_device_t **darwin_device_from_service (io_service_t service)
292 io_cf_plugin_ref_t *plugInInterface = NULL;
293 usb_device_t **device;
296 const int max_retries = 5;
298 /* The IOCreatePlugInInterfaceForService function might consistently return
299 an "out of resources" error with certain USB devices the first time we run
300 it. The reason is still unclear, but retrying fixes the problem */
301 for (int count = 0; count < max_retries; count++) {
302 kresult = IOCreatePlugInInterfaceForService(service, kIOUSBDeviceUserClientTypeID,
303 kIOCFPlugInInterfaceID, &plugInInterface,
305 if (kIOReturnSuccess == kresult && plugInInterface) {
309 usbi_dbg ("set up plugin for service retry: %s", darwin_error_str (kresult));
311 /* sleep for a little while before trying again */
312 nanosleep(&(struct timespec){.tv_sec = 0, .tv_nsec = 1000}, NULL);
315 if (kIOReturnSuccess != kresult || !plugInInterface) {
316 usbi_dbg ("could not set up plugin for service: %s", darwin_error_str (kresult));
320 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
322 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
323 (*plugInInterface)->Release (plugInInterface);
328 static void darwin_devices_attached (void *ptr, io_iterator_t add_devices) {
330 struct darwin_cached_device *cached_device;
331 UInt64 old_session_id;
332 struct libusb_context *ctx;
333 io_service_t service;
336 usbi_mutex_lock(&active_contexts_lock);
338 while ((service = IOIteratorNext(add_devices))) {
339 ret = darwin_get_cached_device (service, &cached_device, &old_session_id);
340 if (ret < 0 || !cached_device->can_enumerate) {
344 /* add this device to each active context's device list */
345 for_each_context(ctx) {
346 process_new_device (ctx, cached_device, old_session_id);
349 if (cached_device->in_reenumerate) {
350 usbi_dbg ("cached device in reset state. reset complete...");
351 cached_device->in_reenumerate = false;
354 IOObjectRelease(service);
357 usbi_mutex_unlock(&active_contexts_lock);
360 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
362 struct libusb_device *dev = NULL;
363 struct libusb_context *ctx;
364 struct darwin_cached_device *old_device;
370 usbi_mutex_lock(&active_contexts_lock);
372 while ((device = IOIteratorNext (rem_devices)) != 0) {
373 bool is_reenumerating = false;
375 /* get the location from the i/o registry */
376 ret = get_ioregistry_value_number (device, CFSTR("sessionID"), kCFNumberSInt64Type, &session);
377 IOObjectRelease (device);
381 /* we need to match darwin_ref_cached_device call made in darwin_get_cached_device function
382 otherwise no cached device will ever get freed */
383 usbi_mutex_lock(&darwin_cached_devices_lock);
384 list_for_each_entry(old_device, &darwin_cached_devices, list, struct darwin_cached_device) {
385 if (old_device->session == session) {
386 if (old_device->in_reenumerate) {
387 /* device is re-enumerating. do not dereference the device at this time. libusb_reset_device()
388 * will deref if needed. */
389 usbi_dbg ("detected device detached due to re-enumeration");
391 /* the device object is no longer usable so go ahead and release it */
392 if (old_device->device) {
393 (*(old_device->device))->Release(old_device->device);
394 old_device->device = NULL;
397 is_reenumerating = true;
399 darwin_deref_cached_device (old_device);
406 usbi_mutex_unlock(&darwin_cached_devices_lock);
407 if (is_reenumerating) {
411 for_each_context(ctx) {
412 usbi_dbg ("notifying context %p of device disconnect", ctx);
414 dev = usbi_get_device_by_session_id(ctx, (unsigned long) session);
416 /* signal the core that this device has been disconnected. the core will tear down this device
417 when the reference count reaches 0 */
418 usbi_disconnect_device(dev);
419 libusb_unref_device(dev);
424 usbi_mutex_unlock(&active_contexts_lock);
427 static void darwin_hotplug_poll (void)
429 /* not sure if 1 ms will be too long/short but it should work ok */
430 mach_timespec_t timeout = {.tv_sec = 0, .tv_nsec = 1000000ul};
432 /* since a kernel thread may notify the IOIterators used for
433 * hotplug notification we can't just clear the iterators.
434 * instead just wait until all IOService providers are quiet */
435 (void) IOKitWaitQuiet (kIOMasterPortDefault, &timeout);
438 static void darwin_clear_iterator (io_iterator_t iter) {
441 while ((device = IOIteratorNext (iter)) != 0)
442 IOObjectRelease (device);
445 static void darwin_fail_startup(void) {
446 pthread_mutex_lock (&libusb_darwin_at_mutex);
447 libusb_darwin_acfl = LIBUSB_DARWIN_STARTUP_FAILURE;
448 pthread_cond_signal (&libusb_darwin_at_cond);
449 pthread_mutex_unlock (&libusb_darwin_at_mutex);
453 static void *darwin_event_thread_main (void *arg0) {
455 struct libusb_context *ctx = (struct libusb_context *)arg0;
456 CFRunLoopRef runloop;
457 CFRunLoopSourceRef libusb_shutdown_cfsource;
458 CFRunLoopSourceContext libusb_shutdown_cfsourcectx;
460 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
461 /* Set this thread's name, so it can be seen in the debugger
462 and crash reports. */
463 pthread_setname_np ("org.libusb.device-hotplug");
466 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
467 /* Tell the Objective-C garbage collector about this thread.
468 This is required because, unlike NSThreads, pthreads are
469 not automatically registered. Although we don't use
470 Objective-C, we use CoreFoundation, which does.
471 Garbage collection support was entirely removed in 10.12,
472 so don't bother there. */
473 objc_registerThreadWithCollector();
476 /* hotplug (device arrival/removal) sources */
477 CFRunLoopSourceRef libusb_notification_cfsource;
478 io_notification_port_t libusb_notification_port;
479 io_iterator_t libusb_rem_device_iterator;
480 io_iterator_t libusb_add_device_iterator;
482 usbi_dbg ("creating hotplug event source");
484 runloop = CFRunLoopGetCurrent ();
487 /* add the shutdown cfsource to the run loop */
488 memset(&libusb_shutdown_cfsourcectx, 0, sizeof(libusb_shutdown_cfsourcectx));
489 libusb_shutdown_cfsourcectx.info = runloop;
490 libusb_shutdown_cfsourcectx.perform = (void (*)(void *))CFRunLoopStop;
491 libusb_shutdown_cfsource = CFRunLoopSourceCreate(NULL, 0, &libusb_shutdown_cfsourcectx);
492 CFRunLoopAddSource(runloop, libusb_shutdown_cfsource, kCFRunLoopDefaultMode);
494 /* add the notification port to the run loop */
495 libusb_notification_port = IONotificationPortCreate (kIOMasterPortDefault);
496 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
497 CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
499 /* create notifications for removed devices */
500 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
501 IOServiceMatching(darwin_device_class),
502 darwin_devices_detached,
503 ctx, &libusb_rem_device_iterator);
505 if (kresult != kIOReturnSuccess) {
506 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
507 CFRelease (libusb_shutdown_cfsource);
509 darwin_fail_startup ();
512 /* create notifications for attached devices */
513 kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
514 IOServiceMatching(darwin_device_class),
515 darwin_devices_attached,
516 ctx, &libusb_add_device_iterator);
518 if (kresult != kIOReturnSuccess) {
519 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
520 CFRelease (libusb_shutdown_cfsource);
522 darwin_fail_startup ();
526 darwin_clear_iterator (libusb_rem_device_iterator);
527 darwin_clear_iterator (libusb_add_device_iterator);
529 usbi_dbg ("darwin event thread ready to receive events");
531 /* signal the main thread that the hotplug runloop has been created. */
532 pthread_mutex_lock (&libusb_darwin_at_mutex);
533 libusb_darwin_acfl = runloop;
534 libusb_darwin_acfls = libusb_shutdown_cfsource;
535 pthread_cond_signal (&libusb_darwin_at_cond);
536 pthread_mutex_unlock (&libusb_darwin_at_mutex);
538 /* run the runloop */
541 usbi_dbg ("darwin event thread exiting");
543 /* signal the main thread that the hotplug runloop has finished. */
544 pthread_mutex_lock (&libusb_darwin_at_mutex);
545 libusb_darwin_acfls = NULL;
546 libusb_darwin_acfl = NULL;
547 pthread_cond_signal (&libusb_darwin_at_cond);
548 pthread_mutex_unlock (&libusb_darwin_at_mutex);
550 /* remove the notification cfsource */
551 CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
553 /* remove the shutdown cfsource */
554 CFRunLoopRemoveSource(runloop, libusb_shutdown_cfsource, kCFRunLoopDefaultMode);
556 /* delete notification port */
557 IONotificationPortDestroy (libusb_notification_port);
559 /* delete iterators */
560 IOObjectRelease (libusb_rem_device_iterator);
561 IOObjectRelease (libusb_add_device_iterator);
563 CFRelease (libusb_shutdown_cfsource);
569 /* cleanup function to destroy cached devices */
570 static void darwin_cleanup_devices(void) {
571 struct darwin_cached_device *dev, *next;
573 list_for_each_entry_safe(dev, next, &darwin_cached_devices, list, struct darwin_cached_device) {
574 darwin_deref_cached_device(dev);
577 darwin_cached_devices.prev = darwin_cached_devices.next = NULL;
580 static int darwin_init(struct libusb_context *ctx) {
584 pthread_mutex_lock (&libusb_darwin_init_mutex);
586 first_init = (1 == ++init_count);
590 assert (NULL == darwin_cached_devices.next);
591 list_init (&darwin_cached_devices);
593 #if !defined(HAVE_CLOCK_GETTIME)
594 /* create the clocks that will be used if clock_gettime() is not available */
595 host_name_port_t host_self;
597 host_self = mach_host_self();
598 host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
599 host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
600 mach_port_deallocate(mach_task_self(), host_self);
604 rc = darwin_scan_devices (ctx);
605 if (LIBUSB_SUCCESS != rc)
609 rc = pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, ctx);
611 usbi_err (ctx, "could not create event thread, error %d", rc);
612 rc = LIBUSB_ERROR_OTHER;
616 pthread_mutex_lock (&libusb_darwin_at_mutex);
617 while (!libusb_darwin_acfl)
618 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
619 if (libusb_darwin_acfl == LIBUSB_DARWIN_STARTUP_FAILURE) {
620 libusb_darwin_acfl = NULL;
621 rc = LIBUSB_ERROR_OTHER;
623 pthread_mutex_unlock (&libusb_darwin_at_mutex);
626 pthread_join (libusb_darwin_at, NULL);
630 if (LIBUSB_SUCCESS != rc) {
632 darwin_cleanup_devices ();
633 #if !defined(HAVE_CLOCK_GETTIME)
634 mach_port_deallocate(mach_task_self(), clock_realtime);
635 mach_port_deallocate(mach_task_self(), clock_monotonic);
641 pthread_mutex_unlock (&libusb_darwin_init_mutex);
646 static void darwin_exit (struct libusb_context *ctx) {
649 pthread_mutex_lock (&libusb_darwin_init_mutex);
651 if (0 == --init_count) {
652 /* stop the event runloop and wait for the thread to terminate. */
653 pthread_mutex_lock (&libusb_darwin_at_mutex);
654 CFRunLoopSourceSignal (libusb_darwin_acfls);
655 CFRunLoopWakeUp (libusb_darwin_acfl);
656 while (libusb_darwin_acfl)
657 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
658 pthread_mutex_unlock (&libusb_darwin_at_mutex);
659 pthread_join (libusb_darwin_at, NULL);
661 darwin_cleanup_devices ();
663 #if !defined(HAVE_CLOCK_GETTIME)
664 mach_port_deallocate(mach_task_self(), clock_realtime);
665 mach_port_deallocate(mach_task_self(), clock_monotonic);
669 pthread_mutex_unlock (&libusb_darwin_init_mutex);
672 static int get_configuration_index (struct libusb_device *dev, UInt8 config_value) {
673 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
675 IOUSBConfigurationDescriptorPtr desc;
678 /* is there a simpler way to determine the index? */
679 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
680 if (kresult != kIOReturnSuccess)
681 return darwin_to_libusb (kresult);
683 for (i = 0 ; i < numConfig ; i++) {
684 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
686 if (desc->bConfigurationValue == config_value)
690 /* configuration not found */
691 return LIBUSB_ERROR_NOT_FOUND;
694 static int darwin_get_active_config_descriptor(struct libusb_device *dev, void *buffer, size_t len) {
695 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
698 if (0 == priv->active_config)
699 return LIBUSB_ERROR_NOT_FOUND;
701 config_index = get_configuration_index (dev, priv->active_config);
702 if (config_index < 0)
705 assert(config_index >= 0 && config_index <= UINT8_MAX);
706 return darwin_get_config_descriptor (dev, (UInt8)config_index, buffer, len);
709 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, void *buffer, size_t len) {
710 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
711 IOUSBConfigurationDescriptorPtr desc;
715 if (!priv || !priv->device)
716 return LIBUSB_ERROR_OTHER;
718 kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
719 if (kresult == kIOReturnSuccess) {
720 /* copy descriptor */
721 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
722 len = libusb_le16_to_cpu(desc->wTotalLength);
724 memmove (buffer, desc, len);
727 ret = darwin_to_libusb (kresult);
728 if (ret != LIBUSB_SUCCESS)
734 /* check whether the os has configured the device */
735 static enum libusb_error darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) {
736 usb_device_t **darwin_device = dev->device;
738 IOUSBConfigurationDescriptorPtr configDesc;
739 IOUSBFindInterfaceRequest request;
741 io_iterator_t interface_iterator;
742 io_service_t firstInterface;
744 if (dev->dev_descriptor.bNumConfigurations < 1) {
745 usbi_err (ctx, "device has no configurations");
746 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
749 /* checking the configuration of a root hub simulation takes ~1 s in 10.11. the device is
751 if (0x05ac == libusb_le16_to_cpu (dev->dev_descriptor.idVendor) &&
752 0x8005 == libusb_le16_to_cpu (dev->dev_descriptor.idProduct)) {
753 usbi_dbg ("ignoring configuration on root hub simulation");
754 dev->active_config = 0;
755 return LIBUSB_SUCCESS;
758 /* find the first configuration */
759 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
760 dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
762 /* check if the device is already configured. there is probably a better way than iterating over the
763 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
764 might lock up on the device request) */
766 /* Setup the Interface Request */
767 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
768 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
769 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
770 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
772 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
773 if (kresult != kIOReturnSuccess)
774 return darwin_to_libusb (kresult);
777 firstInterface = IOIteratorNext(interface_iterator);
779 /* done with the interface iterator */
780 IOObjectRelease(interface_iterator);
782 if (firstInterface) {
783 IOObjectRelease (firstInterface);
785 /* device is configured */
786 if (dev->dev_descriptor.bNumConfigurations == 1)
787 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
788 dev->active_config = dev->first_config;
790 /* devices with more than one configuration should work with GetConfiguration */
791 (*darwin_device)->GetConfiguration (darwin_device, &dev->active_config);
794 dev->active_config = 0;
796 usbi_dbg ("active config: %u, first config: %u", dev->active_config, dev->first_config);
798 return LIBUSB_SUCCESS;
801 static IOReturn darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
802 IOUSBDevRequestTO req;
804 assert(buffer_size <= UINT16_MAX);
806 memset (buffer, 0, buffer_size);
808 /* Set up request for descriptor/ */
809 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
810 req.bRequest = kUSBRqGetDescriptor;
811 req.wValue = (UInt16)(desc << 8);
812 req.wIndex = desc_index;
813 req.wLength = (UInt16)buffer_size;
815 req.noDataTimeout = 20;
816 req.completionTimeout = 100;
818 return (*device)->DeviceRequestTO (device, &req);
821 static enum libusb_error darwin_cache_device_descriptor (struct darwin_cached_device *dev) {
822 usb_device_t **device = dev->device;
824 long delay = 30000; // microseconds
825 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
827 IOReturn ret = 0, ret2;
829 UInt16 idProduct, idVendor;
831 dev->can_enumerate = 0;
833 (*device)->GetDeviceClass (device, &bDeviceClass);
834 (*device)->GetDeviceProduct (device, &idProduct);
835 (*device)->GetDeviceVendor (device, &idVendor);
837 /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
838 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
839 * to follow the spec as closely as possible, try opening the device */
840 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
843 /**** retrieve device descriptor ****/
844 ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &dev->dev_descriptor, sizeof(dev->dev_descriptor));
846 if (kIOReturnOverrun == ret && kUSBDeviceDesc == dev->dev_descriptor.bDescriptorType)
847 /* received an overrun error but we still received a device descriptor */
848 ret = kIOReturnSuccess;
850 if (kIOUSBVendorIDAppleComputer == idVendor) {
851 /* NTH: don't bother retrying or unsuspending Apple devices */
855 if (kIOReturnSuccess == ret && (0 == dev->dev_descriptor.bNumConfigurations ||
856 0 == dev->dev_descriptor.bcdUSB)) {
857 /* work around for incorrectly configured devices */
858 if (try_reconfigure && is_open) {
859 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
861 /* set the first configuration */
862 (*device)->SetConfiguration(device, 1);
864 /* don't try to reconfigure again */
868 ret = kIOUSBPipeStalled;
871 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
872 /* device may be suspended. unsuspend it and try again */
873 #if DeviceVersion >= 320
876 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
877 (void)(*device)->GetUSBDeviceInformation (device, &info);
879 /* note that the device was suspended */
880 if (info & (1U << kUSBInformationDeviceIsSuspendedBit) || 0 == info)
885 /* try to unsuspend the device */
886 ret2 = (*device)->USBDeviceSuspend (device, 0);
887 if (kIOReturnSuccess != ret2) {
888 /* prevent log spew from poorly behaving devices. this indicates the
889 os actually had trouble communicating with the device */
890 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
898 if (kIOReturnSuccess != ret) {
899 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %ld ms before trying again", ret, delay/1000);
900 /* sleep for a little while before trying again */
901 nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000}, NULL);
903 } while (kIOReturnSuccess != ret && retries--);
906 /* resuspend the device */
907 (void)(*device)->USBDeviceSuspend (device, 1);
910 (void) (*device)->USBDeviceClose (device);
912 if (ret != kIOReturnSuccess) {
913 /* a debug message was already printed out for this error */
914 if (LIBUSB_CLASS_HUB == bDeviceClass)
915 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
916 idVendor, idProduct, darwin_error_str (ret), ret);
918 usbi_warn (NULL, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
919 idVendor, idProduct, darwin_error_str (ret), ret);
920 return darwin_to_libusb (ret);
923 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
924 if (libusb_le16_to_cpu (dev->dev_descriptor.idProduct) != idProduct) {
925 /* not a valid device */
926 usbi_warn (NULL, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
927 idProduct, libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
928 return LIBUSB_ERROR_NO_DEVICE;
931 usbi_dbg ("cached device descriptor:");
932 usbi_dbg (" bDescriptorType: 0x%02x", dev->dev_descriptor.bDescriptorType);
933 usbi_dbg (" bcdUSB: 0x%04x", libusb_le16_to_cpu (dev->dev_descriptor.bcdUSB));
934 usbi_dbg (" bDeviceClass: 0x%02x", dev->dev_descriptor.bDeviceClass);
935 usbi_dbg (" bDeviceSubClass: 0x%02x", dev->dev_descriptor.bDeviceSubClass);
936 usbi_dbg (" bDeviceProtocol: 0x%02x", dev->dev_descriptor.bDeviceProtocol);
937 usbi_dbg (" bMaxPacketSize0: 0x%02x", dev->dev_descriptor.bMaxPacketSize0);
938 usbi_dbg (" idVendor: 0x%04x", libusb_le16_to_cpu (dev->dev_descriptor.idVendor));
939 usbi_dbg (" idProduct: 0x%04x", libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
940 usbi_dbg (" bcdDevice: 0x%04x", libusb_le16_to_cpu (dev->dev_descriptor.bcdDevice));
941 usbi_dbg (" iManufacturer: 0x%02x", dev->dev_descriptor.iManufacturer);
942 usbi_dbg (" iProduct: 0x%02x", dev->dev_descriptor.iProduct);
943 usbi_dbg (" iSerialNumber: 0x%02x", dev->dev_descriptor.iSerialNumber);
944 usbi_dbg (" bNumConfigurations: 0x%02x", dev->dev_descriptor.bNumConfigurations);
946 dev->can_enumerate = 1;
948 return LIBUSB_SUCCESS;
951 /* Returns 1 on success, 0 on failure. */
952 static bool get_device_port (io_service_t service, UInt8 *port) {
957 if (get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, port)) {
961 kresult = IORegistryEntryGetParentEntry (service, kIOServicePlane, &parent);
962 if (kIOReturnSuccess == kresult) {
963 ret = get_ioregistry_value_data (parent, CFSTR("port"), 1, port);
964 IOObjectRelease (parent);
970 /* Returns 1 on success, 0 on failure. */
971 static bool get_device_parent_sessionID(io_service_t service, UInt64 *parent_sessionID) {
975 /* Walk up the tree in the IOService plane until we find a parent that has a sessionID */
977 while((kresult = IORegistryEntryGetParentEntry (parent, kIOUSBPlane, &parent)) == kIOReturnSuccess) {
978 if (get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, parent_sessionID)) {
984 /* We ran out of parents */
988 static enum libusb_error darwin_get_cached_device(io_service_t service, struct darwin_cached_device **cached_out,
989 UInt64 *old_session_id) {
990 struct darwin_cached_device *new_device;
991 UInt64 sessionID = 0, parent_sessionID = 0;
992 UInt32 locationID = 0;
993 enum libusb_error ret = LIBUSB_SUCCESS;
994 usb_device_t **device;
997 /* assuming sessionID != 0 normally (never seen it be 0) */
1001 /* get some info from the io registry */
1002 (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
1003 (void) get_ioregistry_value_number (service, CFSTR("locationID"), kCFNumberSInt32Type, &locationID);
1004 if (!get_device_port (service, &port)) {
1005 usbi_dbg("could not get connected port number");
1008 usbi_dbg("finding cached device for sessionID 0x%" PRIx64, sessionID);
1010 if (get_device_parent_sessionID(service, &parent_sessionID)) {
1011 usbi_dbg("parent sessionID: 0x%" PRIx64, parent_sessionID);
1014 usbi_mutex_lock(&darwin_cached_devices_lock);
1016 list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) {
1017 usbi_dbg("matching sessionID/locationID 0x%" PRIx64 "/0x%x against cached device with sessionID/locationID 0x%" PRIx64 "/0x%x",
1018 sessionID, locationID, new_device->session, new_device->location);
1019 if (new_device->location == locationID && new_device->in_reenumerate) {
1020 usbi_dbg ("found cached device with matching location that is being re-enumerated");
1021 *old_session_id = new_device->session;
1025 if (new_device->session == sessionID) {
1026 usbi_dbg("using cached device for device");
1027 *cached_out = new_device;
1035 usbi_dbg("caching new device with sessionID 0x%" PRIx64, sessionID);
1037 device = darwin_device_from_service (service);
1039 ret = LIBUSB_ERROR_NO_DEVICE;
1043 if (!(*old_session_id)) {
1044 new_device = calloc (1, sizeof (*new_device));
1046 ret = LIBUSB_ERROR_NO_MEM;
1050 /* add this device to the cached device list */
1051 list_add(&new_device->list, &darwin_cached_devices);
1053 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
1055 /* keep a reference to this device */
1056 darwin_ref_cached_device(new_device);
1058 (*device)->GetLocationID (device, &new_device->location);
1059 new_device->port = port;
1060 new_device->parent_session = parent_sessionID;
1062 /* release the ref to old device's service */
1063 IOObjectRelease (new_device->service);
1066 /* keep track of devices regardless of if we successfully enumerate them to
1067 prevent them from being enumerated multiple times */
1068 *cached_out = new_device;
1070 new_device->session = sessionID;
1071 new_device->device = device;
1072 new_device->service = service;
1074 /* retain the service */
1075 IOObjectRetain (service);
1077 /* cache the device descriptor */
1078 ret = darwin_cache_device_descriptor(new_device);
1082 if (new_device->can_enumerate) {
1083 snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address,
1084 libusb_le16_to_cpu (new_device->dev_descriptor.idVendor),
1085 libusb_le16_to_cpu (new_device->dev_descriptor.idProduct),
1086 new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass);
1090 usbi_mutex_unlock(&darwin_cached_devices_lock);
1095 static enum libusb_error process_new_device (struct libusb_context *ctx, struct darwin_cached_device *cached_device,
1096 UInt64 old_session_id) {
1097 struct darwin_device_priv *priv;
1098 struct libusb_device *dev = NULL;
1100 enum libusb_error ret = LIBUSB_SUCCESS;
1103 /* check current active configuration (and cache the first configuration value--
1104 which may be used by claim_interface) */
1105 ret = darwin_check_configuration (ctx, cached_device);
1109 if (0 != old_session_id) {
1110 usbi_dbg ("re-using existing device from context %p for with session 0x%" PRIx64 " new session 0x%" PRIx64,
1111 ctx, old_session_id, cached_device->session);
1112 /* save the libusb device before the session id is updated */
1113 dev = usbi_get_device_by_session_id (ctx, (unsigned long) old_session_id);
1117 usbi_dbg ("allocating new device in context %p for with session 0x%" PRIx64,
1118 ctx, cached_device->session);
1120 dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
1122 return LIBUSB_ERROR_NO_MEM;
1125 priv = usbi_get_device_priv(dev);
1127 priv->dev = cached_device;
1128 darwin_ref_cached_device (priv->dev);
1129 dev->port_number = cached_device->port;
1130 dev->bus_number = cached_device->location >> 24;
1131 assert(cached_device->address <= UINT8_MAX);
1132 dev->device_address = (uint8_t)cached_device->address;
1134 priv = usbi_get_device_priv(dev);
1137 static_assert(sizeof(dev->device_descriptor) == sizeof(cached_device->dev_descriptor),
1138 "mismatch between libusb and IOKit device descriptor sizes");
1139 memcpy(&dev->device_descriptor, &cached_device->dev_descriptor, LIBUSB_DT_DEVICE_SIZE);
1140 usbi_localize_device_descriptor(&dev->device_descriptor);
1141 dev->session_data = cached_device->session;
1143 if (cached_device->parent_session > 0) {
1144 dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session);
1146 dev->parent_dev = NULL;
1149 (*(priv->dev->device))->GetDeviceSpeed (priv->dev->device, &devSpeed);
1152 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
1153 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
1154 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
1155 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
1156 case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
1158 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101200
1159 case kUSBDeviceSpeedSuperPlus: dev->speed = LIBUSB_SPEED_SUPER_PLUS; break;
1162 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
1165 ret = usbi_sanitize_device (dev);
1169 usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
1170 dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
1174 if (!cached_device->in_reenumerate && 0 == ret) {
1175 usbi_connect_device (dev);
1177 libusb_unref_device (dev);
1183 static enum libusb_error darwin_scan_devices(struct libusb_context *ctx) {
1184 struct darwin_cached_device *cached_device;
1185 UInt64 old_session_id;
1186 io_iterator_t deviceIterator;
1187 io_service_t service;
1191 kresult = usb_setup_device_iterator (&deviceIterator, 0);
1192 if (kresult != kIOReturnSuccess)
1193 return darwin_to_libusb (kresult);
1195 while ((service = IOIteratorNext (deviceIterator))) {
1196 ret = darwin_get_cached_device (service, &cached_device, &old_session_id);
1197 if (ret < 0 || !cached_device->can_enumerate) {
1201 (void) process_new_device (ctx, cached_device, old_session_id);
1203 IOObjectRelease(service);
1206 IOObjectRelease(deviceIterator);
1208 return LIBUSB_SUCCESS;
1211 static int darwin_open (struct libusb_device_handle *dev_handle) {
1212 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1213 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1216 if (0 == dpriv->open_count) {
1217 /* try to open the device */
1218 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
1219 if (kresult != kIOReturnSuccess) {
1220 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
1222 if (kIOReturnExclusiveAccess != kresult) {
1223 return darwin_to_libusb (kresult);
1226 /* it is possible to perform some actions on a device that is not open so do not return an error */
1227 priv->is_open = false;
1229 priv->is_open = true;
1232 /* create async event source */
1233 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
1234 if (kresult != kIOReturnSuccess) {
1235 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
1237 if (priv->is_open) {
1238 (*(dpriv->device))->USBDeviceClose (dpriv->device);
1241 priv->is_open = false;
1243 return darwin_to_libusb (kresult);
1246 CFRetain (libusb_darwin_acfl);
1248 /* add the cfSource to the aync run loop */
1249 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
1252 /* device opened successfully */
1253 dpriv->open_count++;
1255 usbi_dbg ("device open for access");
1260 static void darwin_close (struct libusb_device_handle *dev_handle) {
1261 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1262 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1266 if (dpriv->open_count == 0) {
1267 /* something is probably very wrong if this is the case */
1268 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!");
1272 dpriv->open_count--;
1274 /* make sure all interfaces are released */
1275 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1276 if (dev_handle->claimed_interfaces & (1U << i))
1277 libusb_release_interface (dev_handle, i);
1279 if (0 == dpriv->open_count) {
1280 /* delete the device's async event source */
1281 if (priv->cfSource) {
1282 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
1283 CFRelease (priv->cfSource);
1284 priv->cfSource = NULL;
1285 CFRelease (libusb_darwin_acfl);
1288 if (priv->is_open) {
1289 /* close the device */
1290 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
1291 if (kresult != kIOReturnSuccess) {
1292 /* Log the fact that we had a problem closing the file, however failing a
1293 * close isn't really an error, so return success anyway */
1294 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
1300 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, uint8_t *config) {
1301 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1303 *config = dpriv->active_config;
1305 return LIBUSB_SUCCESS;
1308 static enum libusb_error darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
1309 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1316 /* Setting configuration will invalidate the interface, so we need
1317 to reclaim it. First, dispose of existing interfaces, if any. */
1318 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1319 if (dev_handle->claimed_interfaces & (1U << i))
1320 darwin_release_interface (dev_handle, i);
1322 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, (UInt8)config);
1323 if (kresult != kIOReturnSuccess)
1324 return darwin_to_libusb (kresult);
1326 /* Reclaim any interfaces. */
1327 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1328 if (dev_handle->claimed_interfaces & (1U << i))
1329 darwin_claim_interface (dev_handle, i);
1331 dpriv->active_config = (UInt8)config;
1333 return LIBUSB_SUCCESS;
1336 static IOReturn darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
1337 IOUSBFindInterfaceRequest request;
1339 io_iterator_t interface_iterator;
1340 UInt8 bInterfaceNumber;
1343 *usbInterfacep = IO_OBJECT_NULL;
1345 /* Setup the Interface Request */
1346 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1347 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1348 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1349 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1351 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1352 if (kresult != kIOReturnSuccess)
1355 while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1356 /* find the interface number */
1357 ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
1360 if (ret && bInterfaceNumber == ifc) {
1364 (void) IOObjectRelease (*usbInterfacep);
1367 /* done with the interface iterator */
1368 IOObjectRelease(interface_iterator);
1370 return kIOReturnSuccess;
1373 static enum libusb_error get_endpoints (struct libusb_device_handle *dev_handle, uint8_t iface) {
1374 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1376 /* current interface */
1377 struct darwin_interface *cInterface = &priv->interfaces[iface];
1381 UInt8 numep, direction, number;
1382 UInt8 dont_care1, dont_care3;
1386 usbi_dbg ("building table of endpoints.");
1388 /* retrieve the total number of endpoints on this interface */
1389 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1390 if (kresult != kIOReturnSuccess) {
1391 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1392 return darwin_to_libusb (kresult);
1395 /* iterate through pipe references */
1396 for (UInt8 i = 1 ; i <= numep ; i++) {
1397 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1398 &dont_care2, &dont_care3);
1400 if (kresult != kIOReturnSuccess) {
1401 /* probably a buggy device. try to get the endpoint address from the descriptors */
1402 struct libusb_config_descriptor *config;
1403 const struct libusb_endpoint_descriptor *endpoint_desc;
1406 kresult = (*(cInterface->interface))->GetAlternateSetting (cInterface->interface, &alt_setting);
1407 if (kresult != kIOReturnSuccess) {
1408 usbi_err (HANDLE_CTX (dev_handle), "can't get alternate setting for interface");
1409 return darwin_to_libusb (kresult);
1412 rc = libusb_get_active_config_descriptor (dev_handle->dev, &config);
1413 if (LIBUSB_SUCCESS != rc) {
1417 endpoint_desc = config->interface[iface].altsetting[alt_setting].endpoint + i - 1;
1419 cInterface->endpoint_addrs[i - 1] = endpoint_desc->bEndpointAddress;
1421 cInterface->endpoint_addrs[i - 1] = (UInt8)(((kUSBIn == direction) << kUSBRqDirnShift) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1424 usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, cInterface->endpoint_addrs[i - 1] >> kUSBRqDirnShift,
1425 cInterface->endpoint_addrs[i - 1] & LIBUSB_ENDPOINT_ADDRESS_MASK);
1428 cInterface->num_endpoints = numep;
1430 return LIBUSB_SUCCESS;
1433 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, uint8_t iface) {
1434 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1435 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1436 io_service_t usbInterface = IO_OBJECT_NULL;
1438 enum libusb_error ret;
1439 IOCFPlugInInterface **plugInInterface = NULL;
1442 /* current interface */
1443 struct darwin_interface *cInterface = &priv->interfaces[iface];
1445 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1446 if (kresult != kIOReturnSuccess)
1447 return darwin_to_libusb (kresult);
1449 /* make sure we have an interface */
1450 if (!usbInterface && dpriv->first_config != 0) {
1451 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1453 /* set the configuration */
1454 ret = darwin_set_configuration (dev_handle, (int) dpriv->first_config);
1455 if (ret != LIBUSB_SUCCESS) {
1456 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1460 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1461 if (kresult != kIOReturnSuccess) {
1462 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1463 return darwin_to_libusb (kresult);
1467 if (!usbInterface) {
1468 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1469 return LIBUSB_ERROR_NOT_FOUND;
1472 /* get an interface to the device's interface */
1473 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1474 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1476 /* ignore release error */
1477 (void)IOObjectRelease (usbInterface);
1479 if (kresult != kIOReturnSuccess) {
1480 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1481 return darwin_to_libusb (kresult);
1484 if (!plugInInterface) {
1485 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1486 return LIBUSB_ERROR_NOT_FOUND;
1489 /* Do the actual claim */
1490 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1491 CFUUIDGetUUIDBytes(InterfaceInterfaceID),
1492 (LPVOID)&cInterface->interface);
1493 /* We no longer need the intermediate plug-in */
1494 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1495 (*plugInInterface)->Release (plugInInterface);
1496 if (kresult != kIOReturnSuccess || !cInterface->interface) {
1497 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1498 return darwin_to_libusb (kresult);
1501 /* claim the interface */
1502 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1503 if (kresult != kIOReturnSuccess) {
1504 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1505 return darwin_to_libusb (kresult);
1508 /* update list of endpoints */
1509 ret = get_endpoints (dev_handle, iface);
1511 /* this should not happen */
1512 darwin_release_interface (dev_handle, iface);
1513 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1517 cInterface->cfSource = NULL;
1519 /* create async event source */
1520 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1521 if (kresult != kIOReturnSuccess) {
1522 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1524 /* can't continue without an async event source */
1525 (void)darwin_release_interface (dev_handle, iface);
1527 return darwin_to_libusb (kresult);
1530 /* add the cfSource to the async thread's run loop */
1531 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1533 usbi_dbg ("interface opened");
1535 return LIBUSB_SUCCESS;
1538 static int darwin_release_interface(struct libusb_device_handle *dev_handle, uint8_t iface) {
1539 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1542 /* current interface */
1543 struct darwin_interface *cInterface = &priv->interfaces[iface];
1545 /* Check to see if an interface is open */
1546 if (!cInterface->interface)
1547 return LIBUSB_SUCCESS;
1549 /* clean up endpoint data */
1550 cInterface->num_endpoints = 0;
1552 /* delete the interface's async event source */
1553 if (cInterface->cfSource) {
1554 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1555 CFRelease (cInterface->cfSource);
1558 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1559 if (kresult != kIOReturnSuccess)
1560 usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1562 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1563 if (kresult != kIOReturnSuccess)
1564 usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1566 cInterface->interface = (usb_interface_t **) IO_OBJECT_NULL;
1568 return darwin_to_libusb (kresult);
1571 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, uint8_t iface, uint8_t altsetting) {
1572 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1574 enum libusb_error ret;
1576 /* current interface */
1577 struct darwin_interface *cInterface = &priv->interfaces[iface];
1579 if (!cInterface->interface)
1580 return LIBUSB_ERROR_NO_DEVICE;
1582 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1583 /* If a device only supports a default setting for the specified interface, then a STALL
1584 (kIOUSBPipeStalled) may be returned. Ref: USB 2.0 specs 9.4.10.
1585 Mimick the behaviour in e.g. the Linux kernel: in such case, reset all endpoints,
1586 and hide errors.Current implementation resets the entire device, instead of single
1587 interface, due to historic reasons. */
1588 if (kresult != kIOReturnSuccess) {
1589 usbi_warn (HANDLE_CTX (dev_handle), "SetAlternateInterface: %s", darwin_error_str(kresult));
1590 darwin_reset_device (dev_handle);
1593 /* update list of endpoints */
1594 ret = get_endpoints (dev_handle, iface);
1596 /* this should not happen */
1597 darwin_release_interface (dev_handle, iface);
1598 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1604 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1605 /* current interface */
1606 struct darwin_interface *cInterface;
1610 /* determine the interface/endpoint to use */
1611 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, NULL, &cInterface) != 0) {
1612 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1614 return LIBUSB_ERROR_NOT_FOUND;
1617 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1618 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1619 if (kresult != kIOReturnSuccess)
1620 usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1622 return darwin_to_libusb (kresult);
1625 static int darwin_restore_state (struct libusb_device_handle *dev_handle, int8_t active_config,
1626 unsigned long claimed_interfaces) {
1627 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1628 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1629 int open_count = dpriv->open_count;
1632 /* clear claimed interfaces temporarily */
1633 dev_handle->claimed_interfaces = 0;
1635 /* close and re-open the device */
1636 priv->is_open = false;
1637 dpriv->open_count = 1;
1639 /* clean up open interfaces */
1640 (void) darwin_close (dev_handle);
1642 /* re-open the device */
1643 ret = darwin_open (dev_handle);
1644 dpriv->open_count = open_count;
1645 if (LIBUSB_SUCCESS != ret) {
1646 /* could not restore configuration */
1647 return LIBUSB_ERROR_NOT_FOUND;
1650 if (dpriv->active_config != active_config) {
1651 usbi_dbg ("darwin/restore_state: restoring configuration %d...", active_config);
1653 ret = darwin_set_configuration (dev_handle, active_config);
1654 if (LIBUSB_SUCCESS != ret) {
1655 usbi_dbg ("darwin/restore_state: could not restore configuration");
1656 return LIBUSB_ERROR_NOT_FOUND;
1660 usbi_dbg ("darwin/restore_state: reclaiming interfaces");
1662 if (claimed_interfaces) {
1663 for (uint8_t iface = 0 ; iface < USB_MAXINTERFACES ; ++iface) {
1664 if (!(claimed_interfaces & (1U << iface))) {
1668 usbi_dbg ("darwin/restore_state: re-claiming interface %u", iface);
1670 ret = darwin_claim_interface (dev_handle, iface);
1671 if (LIBUSB_SUCCESS != ret) {
1672 usbi_dbg ("darwin/restore_state: could not claim interface %u", iface);
1673 return LIBUSB_ERROR_NOT_FOUND;
1676 dev_handle->claimed_interfaces |= 1U << iface;
1680 usbi_dbg ("darwin/restore_state: device state restored");
1682 return LIBUSB_SUCCESS;
1685 static int darwin_reenumerate_device (struct libusb_device_handle *dev_handle, bool capture) {
1686 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1687 unsigned long claimed_interfaces = dev_handle->claimed_interfaces;
1688 int8_t active_config = dpriv->active_config;
1690 IOUSBDeviceDescriptor descriptor;
1691 IOUSBConfigurationDescriptorPtr cached_configuration;
1692 IOUSBConfigurationDescriptor *cached_configurations;
1697 if (dpriv->in_reenumerate) {
1698 /* ack, two (or more) threads are trying to reset the device! abort! */
1699 return LIBUSB_ERROR_NOT_FOUND;
1702 dpriv->in_reenumerate = true;
1704 /* store copies of descriptors so they can be compared after the reset */
1705 memcpy (&descriptor, &dpriv->dev_descriptor, sizeof (descriptor));
1706 cached_configurations = alloca (sizeof (*cached_configurations) * descriptor.bNumConfigurations);
1708 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1709 (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1710 memcpy (cached_configurations + i, cached_configuration, sizeof (cached_configurations[i]));
1713 /* if we need to release capture */
1714 if (HAS_CAPTURE_DEVICE()) {
1716 options |= kUSBReEnumerateCaptureDeviceMask;
1722 /* from macOS 10.11 ResetDevice no longer does anything so just use USBDeviceReEnumerate */
1723 kresult = (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, options);
1724 if (kresult != kIOReturnSuccess) {
1725 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceReEnumerate: %s", darwin_error_str (kresult));
1726 dpriv->in_reenumerate = false;
1727 return darwin_to_libusb (kresult);
1730 /* capture mode does not re-enumerate but it does require re-open */
1732 usbi_dbg ("darwin/reenumerate_device: restoring state...");
1733 dpriv->in_reenumerate = false;
1734 return darwin_restore_state (dev_handle, active_config, claimed_interfaces);
1737 usbi_dbg ("darwin/reenumerate_device: waiting for re-enumeration to complete...");
1740 while (dpriv->in_reenumerate) {
1741 struct timespec delay = {.tv_sec = 0, .tv_nsec = 1000};
1742 nanosleep (&delay, NULL);
1743 if (time++ >= DARWIN_REENUMERATE_TIMEOUT_US) {
1744 usbi_err (HANDLE_CTX (dev_handle), "darwin/reenumerate_device: timeout waiting for reenumerate");
1745 dpriv->in_reenumerate = false;
1746 return LIBUSB_ERROR_TIMEOUT;
1750 /* compare descriptors */
1751 usbi_dbg ("darwin/reenumerate_device: checking whether descriptors changed");
1753 if (memcmp (&descriptor, &dpriv->dev_descriptor, sizeof (descriptor))) {
1754 /* device descriptor changed. need to return not found. */
1755 usbi_dbg ("darwin/reenumerate_device: device descriptor changed");
1756 return LIBUSB_ERROR_NOT_FOUND;
1759 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1760 (void) (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1761 if (memcmp (cached_configuration, cached_configurations + i, sizeof (cached_configurations[i]))) {
1762 usbi_dbg ("darwin/reenumerate_device: configuration descriptor %d changed", i);
1763 return LIBUSB_ERROR_NOT_FOUND;
1767 usbi_dbg ("darwin/reenumerate_device: device reset complete. restoring state...");
1769 return darwin_restore_state (dev_handle, active_config, claimed_interfaces);
1772 static int darwin_reset_device (struct libusb_device_handle *dev_handle) {
1773 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1776 if (dpriv->capture_count > 0) {
1777 /* we have to use ResetDevice as USBDeviceReEnumerate() loses the authorization for capture */
1778 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1779 return darwin_to_libusb (kresult);
1781 return darwin_reenumerate_device (dev_handle, false);
1785 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, uint8_t interface) {
1786 enum libusb_error ret = darwin_claim_interface (dev_handle, interface);
1787 if (ret == LIBUSB_SUCCESS) {
1788 darwin_release_interface (dev_handle, interface);
1790 return (ret == LIBUSB_ERROR_ACCESS);
1793 static void darwin_destroy_device(struct libusb_device *dev) {
1794 struct darwin_device_priv *dpriv = usbi_get_device_priv(dev);
1797 /* need to hold the lock in case this is the last reference to the device */
1798 usbi_mutex_lock(&darwin_cached_devices_lock);
1799 darwin_deref_cached_device (dpriv->dev);
1801 usbi_mutex_unlock(&darwin_cached_devices_lock);
1805 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1806 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1809 uint8_t transferType;
1811 uint16_t maxPacketSize;
1813 struct darwin_interface *cInterface;
1814 #if InterfaceVersion >= 550
1815 IOUSBEndpointProperties pipeProperties = {.bVersion = kUSBEndpointPropertiesVersion3};
1817 /* None of the values below are used in libusb for bulk transfers */
1818 uint8_t direction, number, interval;
1821 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1822 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1824 return LIBUSB_ERROR_NOT_FOUND;
1827 #if InterfaceVersion >= 550
1828 ret = (*(cInterface->interface))->GetPipePropertiesV3 (cInterface->interface, pipeRef, &pipeProperties);
1830 transferType = pipeProperties.bTransferType;
1831 maxPacketSize = pipeProperties.wMaxPacketSize;
1833 ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1834 &transferType, &maxPacketSize, &interval);
1838 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1839 darwin_error_str(ret), ret);
1840 return darwin_to_libusb (ret);
1843 if (0 != (transfer->length % maxPacketSize)) {
1844 /* do not need a zero packet */
1845 transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1848 /* submit the request */
1849 /* timeouts are unavailable on interrupt endpoints */
1850 if (transferType == kUSBInterrupt) {
1851 if (IS_XFERIN(transfer))
1852 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1853 (UInt32)transfer->length, darwin_async_io_callback, itransfer);
1855 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1856 (UInt32)transfer->length, darwin_async_io_callback, itransfer);
1858 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1860 if (IS_XFERIN(transfer))
1861 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1862 (UInt32)transfer->length, transfer->timeout, transfer->timeout,
1863 darwin_async_io_callback, itransfer);
1865 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1866 (UInt32)transfer->length, transfer->timeout, transfer->timeout,
1867 darwin_async_io_callback, itransfer);
1871 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1872 darwin_error_str(ret), ret);
1874 return darwin_to_libusb (ret);
1877 #if InterfaceVersion >= 550
1878 static int submit_stream_transfer(struct usbi_transfer *itransfer) {
1879 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1880 struct darwin_interface *cInterface;
1884 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1885 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1887 return LIBUSB_ERROR_NOT_FOUND;
1890 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1892 if (IS_XFERIN(transfer))
1893 ret = (*(cInterface->interface))->ReadStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1894 transfer->buffer, (UInt32)transfer->length, transfer->timeout,
1895 transfer->timeout, darwin_async_io_callback, itransfer);
1897 ret = (*(cInterface->interface))->WriteStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1898 transfer->buffer, (UInt32)transfer->length, transfer->timeout,
1899 transfer->timeout, darwin_async_io_callback, itransfer);
1902 usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1903 darwin_error_str(ret), ret);
1905 return darwin_to_libusb (ret);
1909 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1910 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1911 struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
1914 uint8_t direction, number, interval, pipeRef, transferType;
1915 uint16_t maxPacketSize;
1917 AbsoluteTime atTime;
1920 struct darwin_interface *cInterface;
1922 /* construct an array of IOUSBIsocFrames, reuse the old one if the sizes are the same */
1923 if (tpriv->num_iso_packets != transfer->num_iso_packets) {
1924 free(tpriv->isoc_framelist);
1925 tpriv->isoc_framelist = NULL;
1928 if (!tpriv->isoc_framelist) {
1929 tpriv->num_iso_packets = transfer->num_iso_packets;
1930 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc ((size_t)transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1931 if (!tpriv->isoc_framelist)
1932 return LIBUSB_ERROR_NO_MEM;
1935 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1936 for (i = 0 ; i < transfer->num_iso_packets ; i++) {
1937 unsigned int length = transfer->iso_packet_desc[i].length;
1938 assert(length <= UINT16_MAX);
1939 tpriv->isoc_framelist[i].frReqCount = (UInt16)length;
1942 /* determine the interface/endpoint to use */
1943 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1944 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1946 return LIBUSB_ERROR_NOT_FOUND;
1949 /* determine the properties of this endpoint and the speed of the device */
1950 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1951 &transferType, &maxPacketSize, &interval);
1953 /* Last but not least we need the bus frame number */
1954 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1955 if (kresult != kIOReturnSuccess) {
1956 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1957 free(tpriv->isoc_framelist);
1958 tpriv->isoc_framelist = NULL;
1960 return darwin_to_libusb (kresult);
1963 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1964 &transferType, &maxPacketSize, &interval);
1966 /* schedule for a frame a little in the future */
1969 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1970 frame = cInterface->frames[transfer->endpoint];
1972 /* submit the request */
1973 if (IS_XFERIN(transfer))
1974 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1975 (UInt32)transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1978 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1979 (UInt32)transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1982 if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
1984 cInterface->frames[transfer->endpoint] = frame + (UInt32)transfer->num_iso_packets * (1U << (interval - 1));
1986 /* High/super speed */
1987 cInterface->frames[transfer->endpoint] = frame + (UInt32)transfer->num_iso_packets * (1U << (interval - 1)) / 8;
1989 if (kresult != kIOReturnSuccess) {
1990 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1991 darwin_error_str(kresult));
1992 free (tpriv->isoc_framelist);
1993 tpriv->isoc_framelist = NULL;
1996 return darwin_to_libusb (kresult);
1999 static int submit_control_transfer(struct usbi_transfer *itransfer) {
2000 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2001 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
2002 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
2003 struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2007 memset(&tpriv->req, 0, sizeof(tpriv->req));
2009 /* IOUSBDeviceInterface expects the request in cpu endianness */
2010 tpriv->req.bmRequestType = setup->bmRequestType;
2011 tpriv->req.bRequest = setup->bRequest;
2012 /* these values should be in bus order from libusb_fill_control_setup */
2013 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
2014 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
2015 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
2016 /* data is stored after the libusb control block */
2017 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
2018 tpriv->req.completionTimeout = transfer->timeout;
2019 tpriv->req.noDataTimeout = transfer->timeout;
2021 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
2023 /* all transfers in libusb-1.0 are async */
2025 if (transfer->endpoint) {
2026 struct darwin_interface *cInterface;
2029 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
2030 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
2032 return LIBUSB_ERROR_NOT_FOUND;
2035 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
2037 /* control request on endpoint 0 */
2038 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
2040 if (kresult != kIOReturnSuccess)
2041 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
2043 return darwin_to_libusb (kresult);
2046 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
2047 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2049 switch (transfer->type) {
2050 case LIBUSB_TRANSFER_TYPE_CONTROL:
2051 return submit_control_transfer(itransfer);
2052 case LIBUSB_TRANSFER_TYPE_BULK:
2053 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2054 return submit_bulk_transfer(itransfer);
2055 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2056 return submit_iso_transfer(itransfer);
2057 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2058 #if InterfaceVersion >= 550
2059 return submit_stream_transfer(itransfer);
2061 usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers");
2062 return LIBUSB_ERROR_NOT_SUPPORTED;
2065 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
2066 return LIBUSB_ERROR_INVALID_PARAM;
2070 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
2071 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2072 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
2075 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
2078 return LIBUSB_ERROR_NO_DEVICE;
2080 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
2082 return darwin_to_libusb (kresult);
2085 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
2086 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2087 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
2088 struct darwin_interface *cInterface;
2089 uint8_t pipeRef, iface;
2092 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) {
2093 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
2095 return LIBUSB_ERROR_NOT_FOUND;
2099 return LIBUSB_ERROR_NO_DEVICE;
2101 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
2103 /* abort transactions */
2104 #if InterfaceVersion >= 550
2105 if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type)
2106 (*(cInterface->interface))->AbortStreamsPipe (cInterface->interface, pipeRef, itransfer->stream_id);
2109 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
2111 usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
2113 /* newer versions of darwin support clearing additional bits on the device's endpoint */
2114 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
2116 return darwin_to_libusb (kresult);
2119 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
2120 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2122 switch (transfer->type) {
2123 case LIBUSB_TRANSFER_TYPE_CONTROL:
2124 return cancel_control_transfer(itransfer);
2125 case LIBUSB_TRANSFER_TYPE_BULK:
2126 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2127 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2128 return darwin_abort_transfers (itransfer);
2130 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
2131 return LIBUSB_ERROR_INVALID_PARAM;
2135 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
2136 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
2137 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2138 struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2140 usbi_dbg ("an async io operation has completed");
2142 /* if requested write a zero packet */
2143 if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
2144 struct darwin_interface *cInterface;
2147 (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface);
2149 (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
2152 tpriv->result = result;
2153 tpriv->size = (UInt32) (uintptr_t) arg0;
2155 /* signal the core that this transfer is complete */
2156 usbi_signal_transfer_completion(itransfer);
2159 static enum libusb_transfer_status darwin_transfer_status (struct usbi_transfer *itransfer, IOReturn result) {
2160 if (itransfer->timeout_flags & USBI_TRANSFER_TIMED_OUT)
2161 result = kIOUSBTransactionTimeout;
2164 case kIOReturnUnderrun:
2165 case kIOReturnSuccess:
2166 return LIBUSB_TRANSFER_COMPLETED;
2167 case kIOReturnAborted:
2168 return LIBUSB_TRANSFER_CANCELLED;
2169 case kIOUSBPipeStalled:
2170 usbi_dbg ("transfer error: pipe is stalled");
2171 return LIBUSB_TRANSFER_STALL;
2172 case kIOReturnOverrun:
2173 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
2174 return LIBUSB_TRANSFER_OVERFLOW;
2175 case kIOUSBTransactionTimeout:
2176 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
2177 itransfer->timeout_flags |= USBI_TRANSFER_TIMED_OUT;
2178 return LIBUSB_TRANSFER_TIMED_OUT;
2180 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
2181 return LIBUSB_TRANSFER_ERROR;
2185 static int darwin_handle_transfer_completion (struct usbi_transfer *itransfer) {
2186 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2187 struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2188 const unsigned char max_transfer_type = LIBUSB_TRANSFER_TYPE_BULK_STREAM;
2189 const char *transfer_types[] = {"control", "isoc", "bulk", "interrupt", "bulk-stream", NULL};
2190 bool is_isoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
2192 if (transfer->type > max_transfer_type) {
2193 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
2194 return LIBUSB_ERROR_INVALID_PARAM;
2197 if (NULL == tpriv) {
2198 usbi_err (TRANSFER_CTX(transfer), "malformed request is missing transfer priv");
2199 return LIBUSB_ERROR_INVALID_PARAM;
2202 usbi_dbg ("handling transfer completion type %s with kernel status %d", transfer_types[transfer->type], tpriv->result);
2204 if (kIOReturnSuccess == tpriv->result || kIOReturnUnderrun == tpriv->result || kIOUSBTransactionTimeout == tpriv->result) {
2205 if (is_isoc && tpriv->isoc_framelist) {
2206 /* copy isochronous results back */
2208 for (int i = 0; i < transfer->num_iso_packets ; i++) {
2209 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
2210 lib_desc->status = darwin_transfer_status (itransfer, tpriv->isoc_framelist[i].frStatus);
2211 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
2213 } else if (!is_isoc) {
2214 itransfer->transferred += tpriv->size;
2218 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
2219 return usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, tpriv->result));
2222 #if !defined(HAVE_CLOCK_GETTIME)
2223 void usbi_get_monotonic_time(struct timespec *tp) {
2224 mach_timespec_t sys_time;
2226 /* use system boot time as reference for the monotonic clock */
2227 clock_get_time (clock_monotonic, &sys_time);
2229 tp->tv_sec = sys_time.tv_sec;
2230 tp->tv_nsec = sys_time.tv_nsec;
2233 void usbi_get_real_time(struct timespec *tp) {
2234 mach_timespec_t sys_time;
2236 /* CLOCK_REALTIME represents time since the epoch */
2237 clock_get_time (clock_realtime, &sys_time);
2239 tp->tv_sec = sys_time.tv_sec;
2240 tp->tv_nsec = sys_time.tv_nsec;
2244 #if InterfaceVersion >= 550
2245 static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints,
2246 int num_endpoints) {
2247 struct darwin_interface *cInterface;
2248 UInt32 supportsStreams;
2252 /* find the minimum number of supported streams on the endpoint list */
2253 for (i = 0 ; i < num_endpoints ; ++i) {
2254 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) {
2258 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2259 if (num_streams > supportsStreams)
2260 num_streams = supportsStreams;
2263 /* it is an error if any endpoint in endpoints does not support streams */
2264 if (0 == num_streams)
2265 return LIBUSB_ERROR_INVALID_PARAM;
2267 /* create the streams */
2268 for (i = 0 ; i < num_endpoints ; ++i) {
2269 (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
2271 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, num_streams);
2272 if (kIOReturnSuccess != rc)
2273 return darwin_to_libusb(rc);
2276 assert(num_streams <= INT_MAX);
2277 return (int)num_streams;
2280 static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) {
2281 struct darwin_interface *cInterface;
2282 UInt32 supportsStreams;
2286 for (int i = 0 ; i < num_endpoints ; ++i) {
2287 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface)))
2290 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2291 if (0 == supportsStreams)
2292 return LIBUSB_ERROR_INVALID_PARAM;
2294 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, 0);
2295 if (kIOReturnSuccess != rc)
2296 return darwin_to_libusb(rc);
2299 return LIBUSB_SUCCESS;
2303 #if InterfaceVersion >= 700
2305 /* macOS APIs for getting entitlement values */
2308 #include <Security/Security.h>
2310 typedef struct __SecTask *SecTaskRef;
2311 extern SecTaskRef SecTaskCreateFromSelf(CFAllocatorRef allocator);
2312 extern CFTypeRef SecTaskCopyValueForEntitlement(SecTaskRef task, CFStringRef entitlement, CFErrorRef *error);
2315 static bool darwin_has_capture_entitlements (void) {
2320 task = SecTaskCreateFromSelf (kCFAllocatorDefault);
2324 value = SecTaskCopyValueForEntitlement(task, CFSTR("com.apple.vm.device-access"), NULL);
2326 entitled = value && (CFGetTypeID (value) == CFBooleanGetTypeID ()) && CFBooleanGetValue (value);
2333 static int darwin_reload_device (struct libusb_device_handle *dev_handle) {
2334 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
2335 enum libusb_error err;
2337 usbi_mutex_lock(&darwin_cached_devices_lock);
2338 (*(dpriv->device))->Release(dpriv->device);
2339 dpriv->device = darwin_device_from_service (dpriv->service);
2340 if (!dpriv->device) {
2341 err = LIBUSB_ERROR_NO_DEVICE;
2343 err = LIBUSB_SUCCESS;
2345 usbi_mutex_unlock(&darwin_cached_devices_lock);
2350 /* On macOS, we capture an entire device at once, not individual interfaces. */
2352 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, uint8_t interface) {
2354 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
2356 enum libusb_error err;
2358 if (HAS_CAPTURE_DEVICE()) {
2360 return LIBUSB_ERROR_NOT_SUPPORTED;
2363 if (dpriv->capture_count == 0) {
2364 /* request authorization */
2365 if (darwin_has_capture_entitlements ()) {
2366 kresult = IOServiceAuthorize (dpriv->service, kIOServiceInteractionAllowed);
2367 if (kresult != kIOReturnSuccess) {
2368 usbi_err (HANDLE_CTX (dev_handle), "IOServiceAuthorize: %s", darwin_error_str(kresult));
2369 return darwin_to_libusb (kresult);
2371 /* we need start() to be called again for authorization status to refresh */
2372 err = darwin_reload_device (dev_handle);
2373 if (err != LIBUSB_SUCCESS) {
2377 /* reset device to release existing drivers */
2378 err = darwin_reenumerate_device (dev_handle, true);
2379 if (err != LIBUSB_SUCCESS) {
2383 dpriv->capture_count++;
2384 return LIBUSB_SUCCESS;
2388 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, uint8_t interface) {
2390 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
2392 if (HAS_CAPTURE_DEVICE()) {
2394 return LIBUSB_ERROR_NOT_SUPPORTED;
2397 dpriv->capture_count--;
2398 if (dpriv->capture_count > 0) {
2399 return LIBUSB_SUCCESS;
2401 dpriv->capture_count = 0;
2403 /* reset device to attach kernel drivers */
2404 return darwin_reenumerate_device (dev_handle, false);
2407 static int darwin_capture_claim_interface(struct libusb_device_handle *dev_handle, uint8_t iface) {
2408 enum libusb_error ret;
2409 if (dev_handle->auto_detach_kernel_driver) {
2410 ret = darwin_detach_kernel_driver (dev_handle, iface);
2411 if (ret != LIBUSB_SUCCESS) {
2415 return darwin_claim_interface (dev_handle, iface);
2418 static int darwin_capture_release_interface(struct libusb_device_handle *dev_handle, uint8_t iface) {
2419 enum libusb_error ret;
2421 ret = darwin_release_interface (dev_handle, iface);
2422 if (ret != LIBUSB_SUCCESS) {
2425 if (dev_handle->auto_detach_kernel_driver) {
2426 ret = darwin_attach_kernel_driver (dev_handle, iface);
2433 const struct usbi_os_backend usbi_backend = {
2435 .caps = USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2436 .init = darwin_init,
2437 .exit = darwin_exit,
2438 .get_active_config_descriptor = darwin_get_active_config_descriptor,
2439 .get_config_descriptor = darwin_get_config_descriptor,
2440 .hotplug_poll = darwin_hotplug_poll,
2442 .open = darwin_open,
2443 .close = darwin_close,
2444 .get_configuration = darwin_get_configuration,
2445 .set_configuration = darwin_set_configuration,
2447 .set_interface_altsetting = darwin_set_interface_altsetting,
2448 .clear_halt = darwin_clear_halt,
2449 .reset_device = darwin_reset_device,
2451 #if InterfaceVersion >= 550
2452 .alloc_streams = darwin_alloc_streams,
2453 .free_streams = darwin_free_streams,
2456 .kernel_driver_active = darwin_kernel_driver_active,
2458 #if InterfaceVersion >= 700
2459 .detach_kernel_driver = darwin_detach_kernel_driver,
2460 .attach_kernel_driver = darwin_attach_kernel_driver,
2461 .claim_interface = darwin_capture_claim_interface,
2462 .release_interface = darwin_capture_release_interface,
2464 .claim_interface = darwin_claim_interface,
2465 .release_interface = darwin_release_interface,
2468 .destroy_device = darwin_destroy_device,
2470 .submit_transfer = darwin_submit_transfer,
2471 .cancel_transfer = darwin_cancel_transfer,
2473 .handle_transfer_completion = darwin_handle_transfer_completion,
2475 .device_priv_size = sizeof(struct darwin_device_priv),
2476 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
2477 .transfer_priv_size = sizeof(struct darwin_transfer_priv),