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 int init_count = 0;
57 /* async event thread */
58 static pthread_mutex_t libusb_darwin_at_mutex = PTHREAD_MUTEX_INITIALIZER;
59 static pthread_cond_t libusb_darwin_at_cond = PTHREAD_COND_INITIALIZER;
61 #if !defined(HAVE_CLOCK_GETTIME)
62 static clock_serv_t clock_realtime;
63 static clock_serv_t clock_monotonic;
66 #define LIBUSB_DARWIN_STARTUP_FAILURE ((CFRunLoopRef) -1)
68 static CFRunLoopRef libusb_darwin_acfl = NULL; /* event cf loop */
69 static CFRunLoopSourceRef libusb_darwin_acfls = NULL; /* shutdown signal for event cf loop */
71 static usbi_mutex_t darwin_cached_devices_lock = PTHREAD_MUTEX_INITIALIZER;
72 static struct list_head darwin_cached_devices;
73 static const char *darwin_device_class = "IOUSBDevice";
75 #define DARWIN_CACHED_DEVICE(a) (((struct darwin_device_priv *)usbi_get_device_priv((a)))->dev)
77 /* async event thread */
78 static pthread_t libusb_darwin_at;
80 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, void *buffer, size_t len);
81 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, uint8_t iface);
82 static int darwin_release_interface(struct libusb_device_handle *dev_handle, uint8_t iface);
83 static int darwin_reenumerate_device(struct libusb_device_handle *dev_handle, bool capture);
84 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint);
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;
367 UInt64 session, locationID;
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 (void) get_ioregistry_value_number (device, CFSTR("locationID"), kCFNumberSInt32Type, &locationID);
378 IOObjectRelease (device);
382 /* we need to match darwin_ref_cached_device call made in darwin_get_cached_device function
383 otherwise no cached device will ever get freed */
384 usbi_mutex_lock(&darwin_cached_devices_lock);
385 list_for_each_entry(old_device, &darwin_cached_devices, list, struct darwin_cached_device) {
386 if (old_device->session == session) {
387 if (old_device->in_reenumerate) {
388 /* device is re-enumerating. do not dereference the device at this time. libusb_reset_device()
389 * will deref if needed. */
390 usbi_dbg ("detected device detached due to re-enumeration. sessionID: 0x%" PRIx64 ", locationID: 0x%" PRIx64,
391 session, locationID);
393 /* the device object is no longer usable so go ahead and release it */
394 if (old_device->device) {
395 (*(old_device->device))->Release(old_device->device);
396 old_device->device = NULL;
399 is_reenumerating = true;
401 darwin_deref_cached_device (old_device);
408 usbi_mutex_unlock(&darwin_cached_devices_lock);
409 if (is_reenumerating) {
413 for_each_context(ctx) {
414 usbi_dbg ("notifying context %p of device disconnect", ctx);
416 dev = usbi_get_device_by_session_id(ctx, (unsigned long) session);
418 /* signal the core that this device has been disconnected. the core will tear down this device
419 when the reference count reaches 0 */
420 usbi_disconnect_device(dev);
421 libusb_unref_device(dev);
426 usbi_mutex_unlock(&active_contexts_lock);
429 static void darwin_hotplug_poll (void)
431 /* not sure if 1 ms will be too long/short but it should work ok */
432 mach_timespec_t timeout = {.tv_sec = 0, .tv_nsec = 1000000ul};
434 /* since a kernel thread may notify the IOIterators used for
435 * hotplug notification we can't just clear the iterators.
436 * instead just wait until all IOService providers are quiet */
437 (void) IOKitWaitQuiet (kIOMasterPortDefault, &timeout);
440 static void darwin_clear_iterator (io_iterator_t iter) {
443 while ((device = IOIteratorNext (iter)) != 0)
444 IOObjectRelease (device);
447 static void darwin_fail_startup(void) {
448 pthread_mutex_lock (&libusb_darwin_at_mutex);
449 libusb_darwin_acfl = LIBUSB_DARWIN_STARTUP_FAILURE;
450 pthread_cond_signal (&libusb_darwin_at_cond);
451 pthread_mutex_unlock (&libusb_darwin_at_mutex);
455 static void *darwin_event_thread_main (void *arg0) {
457 struct libusb_context *ctx = (struct libusb_context *)arg0;
458 CFRunLoopRef runloop;
459 CFRunLoopSourceRef libusb_shutdown_cfsource;
460 CFRunLoopSourceContext libusb_shutdown_cfsourcectx;
462 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
463 /* Set this thread's name, so it can be seen in the debugger
464 and crash reports. */
465 pthread_setname_np ("org.libusb.device-hotplug");
468 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
469 /* Tell the Objective-C garbage collector about this thread.
470 This is required because, unlike NSThreads, pthreads are
471 not automatically registered. Although we don't use
472 Objective-C, we use CoreFoundation, which does.
473 Garbage collection support was entirely removed in 10.12,
474 so don't bother there. */
475 objc_registerThreadWithCollector();
478 /* hotplug (device arrival/removal) sources */
479 CFRunLoopSourceRef libusb_notification_cfsource;
480 io_notification_port_t libusb_notification_port;
481 io_iterator_t libusb_rem_device_iterator;
482 io_iterator_t libusb_add_device_iterator;
484 usbi_dbg ("creating hotplug event source");
486 runloop = CFRunLoopGetCurrent ();
489 /* add the shutdown cfsource to the run loop */
490 memset(&libusb_shutdown_cfsourcectx, 0, sizeof(libusb_shutdown_cfsourcectx));
491 libusb_shutdown_cfsourcectx.info = runloop;
492 libusb_shutdown_cfsourcectx.perform = (void (*)(void *))CFRunLoopStop;
493 libusb_shutdown_cfsource = CFRunLoopSourceCreate(NULL, 0, &libusb_shutdown_cfsourcectx);
494 CFRunLoopAddSource(runloop, libusb_shutdown_cfsource, kCFRunLoopDefaultMode);
496 /* add the notification port to the run loop */
497 libusb_notification_port = IONotificationPortCreate (kIOMasterPortDefault);
498 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
499 CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
501 /* create notifications for removed devices */
502 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
503 IOServiceMatching(darwin_device_class),
504 darwin_devices_detached,
505 ctx, &libusb_rem_device_iterator);
507 if (kresult != kIOReturnSuccess) {
508 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
509 CFRelease (libusb_shutdown_cfsource);
511 darwin_fail_startup ();
514 /* create notifications for attached devices */
515 kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
516 IOServiceMatching(darwin_device_class),
517 darwin_devices_attached,
518 ctx, &libusb_add_device_iterator);
520 if (kresult != kIOReturnSuccess) {
521 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
522 CFRelease (libusb_shutdown_cfsource);
524 darwin_fail_startup ();
528 darwin_clear_iterator (libusb_rem_device_iterator);
529 darwin_clear_iterator (libusb_add_device_iterator);
531 usbi_dbg ("darwin event thread ready to receive events");
533 /* signal the main thread that the hotplug runloop has been created. */
534 pthread_mutex_lock (&libusb_darwin_at_mutex);
535 libusb_darwin_acfl = runloop;
536 libusb_darwin_acfls = libusb_shutdown_cfsource;
537 pthread_cond_signal (&libusb_darwin_at_cond);
538 pthread_mutex_unlock (&libusb_darwin_at_mutex);
540 /* run the runloop */
543 usbi_dbg ("darwin event thread exiting");
545 /* signal the main thread that the hotplug runloop has finished. */
546 pthread_mutex_lock (&libusb_darwin_at_mutex);
547 libusb_darwin_acfls = NULL;
548 libusb_darwin_acfl = NULL;
549 pthread_cond_signal (&libusb_darwin_at_cond);
550 pthread_mutex_unlock (&libusb_darwin_at_mutex);
552 /* remove the notification cfsource */
553 CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
555 /* remove the shutdown cfsource */
556 CFRunLoopRemoveSource(runloop, libusb_shutdown_cfsource, kCFRunLoopDefaultMode);
558 /* delete notification port */
559 IONotificationPortDestroy (libusb_notification_port);
561 /* delete iterators */
562 IOObjectRelease (libusb_rem_device_iterator);
563 IOObjectRelease (libusb_add_device_iterator);
565 CFRelease (libusb_shutdown_cfsource);
571 /* cleanup function to destroy cached devices */
572 static void darwin_cleanup_devices(void) {
573 struct darwin_cached_device *dev, *next;
575 list_for_each_entry_safe(dev, next, &darwin_cached_devices, list, struct darwin_cached_device) {
576 darwin_deref_cached_device(dev);
580 static int darwin_init(struct libusb_context *ctx) {
584 first_init = (1 == ++init_count);
588 if (NULL == darwin_cached_devices.next) {
589 list_init (&darwin_cached_devices);
591 assert(list_empty(&darwin_cached_devices));
592 #if !defined(HAVE_CLOCK_GETTIME)
593 /* create the clocks that will be used if clock_gettime() is not available */
594 host_name_port_t host_self;
596 host_self = mach_host_self();
597 host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
598 host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
599 mach_port_deallocate(mach_task_self(), host_self);
603 rc = darwin_scan_devices (ctx);
604 if (LIBUSB_SUCCESS != rc)
608 rc = pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, ctx);
610 usbi_err (ctx, "could not create event thread, error %d", rc);
611 rc = LIBUSB_ERROR_OTHER;
615 pthread_mutex_lock (&libusb_darwin_at_mutex);
616 while (!libusb_darwin_acfl)
617 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
618 if (libusb_darwin_acfl == LIBUSB_DARWIN_STARTUP_FAILURE) {
619 libusb_darwin_acfl = NULL;
620 rc = LIBUSB_ERROR_OTHER;
622 pthread_mutex_unlock (&libusb_darwin_at_mutex);
625 pthread_join (libusb_darwin_at, NULL);
629 if (LIBUSB_SUCCESS != rc) {
631 darwin_cleanup_devices ();
632 #if !defined(HAVE_CLOCK_GETTIME)
633 mach_port_deallocate(mach_task_self(), clock_realtime);
634 mach_port_deallocate(mach_task_self(), clock_monotonic);
643 static void darwin_exit (struct libusb_context *ctx) {
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 darwin_cleanup_devices ();
658 #if !defined(HAVE_CLOCK_GETTIME)
659 mach_port_deallocate(mach_task_self(), clock_realtime);
660 mach_port_deallocate(mach_task_self(), clock_monotonic);
665 static int get_configuration_index (struct libusb_device *dev, UInt8 config_value) {
666 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
668 IOUSBConfigurationDescriptorPtr desc;
671 /* is there a simpler way to determine the index? */
672 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
673 if (kresult != kIOReturnSuccess)
674 return darwin_to_libusb (kresult);
676 for (i = 0 ; i < numConfig ; i++) {
677 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
679 if (desc->bConfigurationValue == config_value)
683 /* configuration not found */
684 return LIBUSB_ERROR_NOT_FOUND;
687 static int darwin_get_active_config_descriptor(struct libusb_device *dev, void *buffer, size_t len) {
688 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
691 if (0 == priv->active_config)
692 return LIBUSB_ERROR_NOT_FOUND;
694 config_index = get_configuration_index (dev, priv->active_config);
695 if (config_index < 0)
698 assert(config_index >= 0 && config_index <= UINT8_MAX);
699 return darwin_get_config_descriptor (dev, (UInt8)config_index, buffer, len);
702 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, void *buffer, size_t len) {
703 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
704 IOUSBConfigurationDescriptorPtr desc;
708 if (!priv || !priv->device)
709 return LIBUSB_ERROR_OTHER;
711 kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
712 if (kresult == kIOReturnSuccess) {
713 /* copy descriptor */
714 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
715 len = libusb_le16_to_cpu(desc->wTotalLength);
717 memmove (buffer, desc, len);
720 ret = darwin_to_libusb (kresult);
721 if (ret != LIBUSB_SUCCESS)
727 /* check whether the os has configured the device */
728 static enum libusb_error darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) {
729 usb_device_t **darwin_device = dev->device;
731 IOUSBConfigurationDescriptorPtr configDesc;
732 IOUSBFindInterfaceRequest request;
734 io_iterator_t interface_iterator;
735 io_service_t firstInterface;
737 if (dev->dev_descriptor.bNumConfigurations < 1) {
738 usbi_err (ctx, "device has no configurations");
739 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
742 /* checking the configuration of a root hub simulation takes ~1 s in 10.11. the device is
744 if (0x05ac == libusb_le16_to_cpu (dev->dev_descriptor.idVendor) &&
745 0x8005 == libusb_le16_to_cpu (dev->dev_descriptor.idProduct)) {
746 usbi_dbg ("ignoring configuration on root hub simulation");
747 dev->active_config = 0;
748 return LIBUSB_SUCCESS;
751 /* find the first configuration */
752 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
753 dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
755 /* check if the device is already configured. there is probably a better way than iterating over the
756 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
757 might lock up on the device request) */
759 /* Setup the Interface Request */
760 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
761 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
762 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
763 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
765 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
766 if (kresult != kIOReturnSuccess)
767 return darwin_to_libusb (kresult);
770 firstInterface = IOIteratorNext(interface_iterator);
772 /* done with the interface iterator */
773 IOObjectRelease(interface_iterator);
775 if (firstInterface) {
776 IOObjectRelease (firstInterface);
778 /* device is configured */
779 if (dev->dev_descriptor.bNumConfigurations == 1)
780 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
781 dev->active_config = dev->first_config;
783 /* devices with more than one configuration should work with GetConfiguration */
784 (*darwin_device)->GetConfiguration (darwin_device, &dev->active_config);
787 dev->active_config = 0;
789 usbi_dbg ("active config: %u, first config: %u", dev->active_config, dev->first_config);
791 return LIBUSB_SUCCESS;
794 static IOReturn darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
795 IOUSBDevRequestTO req;
797 assert(buffer_size <= UINT16_MAX);
799 memset (buffer, 0, buffer_size);
801 /* Set up request for descriptor/ */
802 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
803 req.bRequest = kUSBRqGetDescriptor;
804 req.wValue = (UInt16)(desc << 8);
805 req.wIndex = desc_index;
806 req.wLength = (UInt16)buffer_size;
808 req.noDataTimeout = 20;
809 req.completionTimeout = 100;
811 return (*device)->DeviceRequestTO (device, &req);
814 static enum libusb_error darwin_cache_device_descriptor (struct darwin_cached_device *dev) {
815 usb_device_t **device = dev->device;
817 long delay = 30000; // microseconds
818 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
820 IOReturn ret = 0, ret2;
822 UInt16 idProduct, idVendor;
824 dev->can_enumerate = 0;
826 (*device)->GetDeviceClass (device, &bDeviceClass);
827 (*device)->GetDeviceProduct (device, &idProduct);
828 (*device)->GetDeviceVendor (device, &idVendor);
830 /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
831 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
832 * to follow the spec as closely as possible, try opening the device */
833 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
836 /**** retrieve device descriptor ****/
837 ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &dev->dev_descriptor, sizeof(dev->dev_descriptor));
839 if (kIOReturnOverrun == ret && kUSBDeviceDesc == dev->dev_descriptor.bDescriptorType)
840 /* received an overrun error but we still received a device descriptor */
841 ret = kIOReturnSuccess;
843 if (kIOUSBVendorIDAppleComputer == idVendor) {
844 /* NTH: don't bother retrying or unsuspending Apple devices */
848 if (kIOReturnSuccess == ret && (0 == dev->dev_descriptor.bNumConfigurations ||
849 0 == dev->dev_descriptor.bcdUSB)) {
850 /* work around for incorrectly configured devices */
851 if (try_reconfigure && is_open) {
852 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
854 /* set the first configuration */
855 (*device)->SetConfiguration(device, 1);
857 /* don't try to reconfigure again */
861 ret = kIOUSBPipeStalled;
864 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
865 /* device may be suspended. unsuspend it and try again */
866 #if DeviceVersion >= 320
869 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
870 (void)(*device)->GetUSBDeviceInformation (device, &info);
872 /* note that the device was suspended */
873 if (info & (1U << kUSBInformationDeviceIsSuspendedBit) || 0 == info)
878 /* try to unsuspend the device */
879 ret2 = (*device)->USBDeviceSuspend (device, 0);
880 if (kIOReturnSuccess != ret2) {
881 /* prevent log spew from poorly behaving devices. this indicates the
882 os actually had trouble communicating with the device */
883 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
891 if (kIOReturnSuccess != ret) {
892 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %ld ms before trying again", ret, delay/1000);
893 /* sleep for a little while before trying again */
894 nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000}, NULL);
896 } while (kIOReturnSuccess != ret && retries--);
899 /* resuspend the device */
900 (void)(*device)->USBDeviceSuspend (device, 1);
903 (void) (*device)->USBDeviceClose (device);
905 if (ret != kIOReturnSuccess) {
906 /* a debug message was already printed out for this error */
907 if (LIBUSB_CLASS_HUB == bDeviceClass)
908 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
909 idVendor, idProduct, darwin_error_str (ret), ret);
911 usbi_warn (NULL, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
912 idVendor, idProduct, darwin_error_str (ret), ret);
913 return darwin_to_libusb (ret);
916 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
917 if (libusb_le16_to_cpu (dev->dev_descriptor.idProduct) != idProduct) {
918 /* not a valid device */
919 usbi_warn (NULL, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
920 idProduct, libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
921 return LIBUSB_ERROR_NO_DEVICE;
924 usbi_dbg ("cached device descriptor:");
925 usbi_dbg (" bDescriptorType: 0x%02x", dev->dev_descriptor.bDescriptorType);
926 usbi_dbg (" bcdUSB: 0x%04x", libusb_le16_to_cpu (dev->dev_descriptor.bcdUSB));
927 usbi_dbg (" bDeviceClass: 0x%02x", dev->dev_descriptor.bDeviceClass);
928 usbi_dbg (" bDeviceSubClass: 0x%02x", dev->dev_descriptor.bDeviceSubClass);
929 usbi_dbg (" bDeviceProtocol: 0x%02x", dev->dev_descriptor.bDeviceProtocol);
930 usbi_dbg (" bMaxPacketSize0: 0x%02x", dev->dev_descriptor.bMaxPacketSize0);
931 usbi_dbg (" idVendor: 0x%04x", libusb_le16_to_cpu (dev->dev_descriptor.idVendor));
932 usbi_dbg (" idProduct: 0x%04x", libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
933 usbi_dbg (" bcdDevice: 0x%04x", libusb_le16_to_cpu (dev->dev_descriptor.bcdDevice));
934 usbi_dbg (" iManufacturer: 0x%02x", dev->dev_descriptor.iManufacturer);
935 usbi_dbg (" iProduct: 0x%02x", dev->dev_descriptor.iProduct);
936 usbi_dbg (" iSerialNumber: 0x%02x", dev->dev_descriptor.iSerialNumber);
937 usbi_dbg (" bNumConfigurations: 0x%02x", dev->dev_descriptor.bNumConfigurations);
939 dev->can_enumerate = 1;
941 return LIBUSB_SUCCESS;
944 /* Returns 1 on success, 0 on failure. */
945 static bool get_device_port (io_service_t service, UInt8 *port) {
950 if (get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, port)) {
954 kresult = IORegistryEntryGetParentEntry (service, kIOServicePlane, &parent);
955 if (kIOReturnSuccess == kresult) {
956 ret = get_ioregistry_value_data (parent, CFSTR("port"), 1, port);
957 IOObjectRelease (parent);
963 /* Returns 1 on success, 0 on failure. */
964 static bool get_device_parent_sessionID(io_service_t service, UInt64 *parent_sessionID) {
968 /* Walk up the tree in the IOService plane until we find a parent that has a sessionID */
970 while((kresult = IORegistryEntryGetParentEntry (parent, kIOUSBPlane, &parent)) == kIOReturnSuccess) {
971 if (get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, parent_sessionID)) {
977 /* We ran out of parents */
981 static enum libusb_error darwin_get_cached_device(io_service_t service, struct darwin_cached_device **cached_out,
982 UInt64 *old_session_id) {
983 struct darwin_cached_device *new_device;
984 UInt64 sessionID = 0, parent_sessionID = 0;
985 UInt32 locationID = 0;
986 enum libusb_error ret = LIBUSB_SUCCESS;
987 usb_device_t **device;
990 /* assuming sessionID != 0 normally (never seen it be 0) */
994 /* get some info from the io registry */
995 (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
996 (void) get_ioregistry_value_number (service, CFSTR("locationID"), kCFNumberSInt32Type, &locationID);
997 if (!get_device_port (service, &port)) {
998 usbi_dbg("could not get connected port number");
1001 usbi_dbg("finding cached device for sessionID 0x%" PRIx64, sessionID);
1003 if (get_device_parent_sessionID(service, &parent_sessionID)) {
1004 usbi_dbg("parent sessionID: 0x%" PRIx64, parent_sessionID);
1007 usbi_mutex_lock(&darwin_cached_devices_lock);
1009 list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) {
1010 usbi_dbg("matching sessionID/locationID 0x%" PRIx64 "/0x%x against cached device with sessionID/locationID 0x%" PRIx64 "/0x%x",
1011 sessionID, locationID, new_device->session, new_device->location);
1012 if (new_device->location == locationID && new_device->in_reenumerate) {
1013 usbi_dbg ("found cached device with matching location that is being re-enumerated");
1014 *old_session_id = new_device->session;
1018 if (new_device->session == sessionID) {
1019 usbi_dbg("using cached device for device");
1020 *cached_out = new_device;
1028 usbi_dbg("caching new device with sessionID 0x%" PRIx64, sessionID);
1030 device = darwin_device_from_service (service);
1032 ret = LIBUSB_ERROR_NO_DEVICE;
1036 if (!(*old_session_id)) {
1037 new_device = calloc (1, sizeof (*new_device));
1039 ret = LIBUSB_ERROR_NO_MEM;
1043 /* add this device to the cached device list */
1044 list_add(&new_device->list, &darwin_cached_devices);
1046 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
1048 /* keep a reference to this device */
1049 darwin_ref_cached_device(new_device);
1051 (*device)->GetLocationID (device, &new_device->location);
1052 new_device->port = port;
1053 new_device->parent_session = parent_sessionID;
1055 /* release the ref to old device's service */
1056 IOObjectRelease (new_device->service);
1059 /* keep track of devices regardless of if we successfully enumerate them to
1060 prevent them from being enumerated multiple times */
1061 *cached_out = new_device;
1063 new_device->session = sessionID;
1064 new_device->device = device;
1065 new_device->service = service;
1067 /* retain the service */
1068 IOObjectRetain (service);
1070 /* cache the device descriptor */
1071 ret = darwin_cache_device_descriptor(new_device);
1075 if (new_device->can_enumerate) {
1076 snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address,
1077 libusb_le16_to_cpu (new_device->dev_descriptor.idVendor),
1078 libusb_le16_to_cpu (new_device->dev_descriptor.idProduct),
1079 new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass);
1083 usbi_mutex_unlock(&darwin_cached_devices_lock);
1088 static enum libusb_error process_new_device (struct libusb_context *ctx, struct darwin_cached_device *cached_device,
1089 UInt64 old_session_id) {
1090 struct darwin_device_priv *priv;
1091 struct libusb_device *dev = NULL;
1093 enum libusb_error ret = LIBUSB_SUCCESS;
1096 /* check current active configuration (and cache the first configuration value--
1097 which may be used by claim_interface) */
1098 ret = darwin_check_configuration (ctx, cached_device);
1102 if (0 != old_session_id) {
1103 usbi_dbg ("re-using existing device from context %p for with session 0x%" PRIx64 " new session 0x%" PRIx64,
1104 ctx, old_session_id, cached_device->session);
1105 /* save the libusb device before the session id is updated */
1106 dev = usbi_get_device_by_session_id (ctx, (unsigned long) old_session_id);
1110 usbi_dbg ("allocating new device in context %p for with session 0x%" PRIx64,
1111 ctx, cached_device->session);
1113 dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
1115 return LIBUSB_ERROR_NO_MEM;
1118 priv = usbi_get_device_priv(dev);
1120 priv->dev = cached_device;
1121 darwin_ref_cached_device (priv->dev);
1122 dev->port_number = cached_device->port;
1123 /* the location ID encodes the path to the device. the top byte of the location ID contains the bus number
1124 (numbered from 0). the remaining bytes can be used to construct the device tree for that bus. */
1125 dev->bus_number = cached_device->location >> 24;
1126 assert(cached_device->address <= UINT8_MAX);
1127 dev->device_address = (uint8_t)cached_device->address;
1129 priv = usbi_get_device_priv(dev);
1132 static_assert(sizeof(dev->device_descriptor) == sizeof(cached_device->dev_descriptor),
1133 "mismatch between libusb and IOKit device descriptor sizes");
1134 memcpy(&dev->device_descriptor, &cached_device->dev_descriptor, LIBUSB_DT_DEVICE_SIZE);
1135 usbi_localize_device_descriptor(&dev->device_descriptor);
1136 dev->session_data = cached_device->session;
1138 if (NULL != dev->parent_dev) {
1139 libusb_unref_device(dev->parent_dev);
1140 dev->parent_dev = NULL;
1143 if (cached_device->parent_session > 0) {
1144 dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session);
1147 (*(priv->dev->device))->GetDeviceSpeed (priv->dev->device, &devSpeed);
1150 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
1151 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
1152 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
1153 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1080
1154 case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
1156 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101200
1157 case kUSBDeviceSpeedSuperPlus: dev->speed = LIBUSB_SPEED_SUPER_PLUS; break;
1160 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
1163 ret = usbi_sanitize_device (dev);
1167 usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
1168 dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
1172 if (!cached_device->in_reenumerate && 0 == ret) {
1173 usbi_connect_device (dev);
1175 libusb_unref_device (dev);
1181 static enum libusb_error darwin_scan_devices(struct libusb_context *ctx) {
1182 struct darwin_cached_device *cached_device;
1183 UInt64 old_session_id;
1184 io_iterator_t deviceIterator;
1185 io_service_t service;
1189 kresult = usb_setup_device_iterator (&deviceIterator, 0);
1190 if (kresult != kIOReturnSuccess)
1191 return darwin_to_libusb (kresult);
1193 while ((service = IOIteratorNext (deviceIterator))) {
1194 ret = darwin_get_cached_device (service, &cached_device, &old_session_id);
1195 if (ret < 0 || !cached_device->can_enumerate) {
1199 (void) process_new_device (ctx, cached_device, old_session_id);
1201 IOObjectRelease(service);
1204 IOObjectRelease(deviceIterator);
1206 return LIBUSB_SUCCESS;
1209 static int darwin_open (struct libusb_device_handle *dev_handle) {
1210 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1211 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1214 if (0 == dpriv->open_count) {
1215 /* try to open the device */
1216 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
1217 if (kresult != kIOReturnSuccess) {
1218 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
1220 if (kIOReturnExclusiveAccess != kresult) {
1221 return darwin_to_libusb (kresult);
1224 /* it is possible to perform some actions on a device that is not open so do not return an error */
1225 priv->is_open = false;
1227 priv->is_open = true;
1230 /* create async event source */
1231 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
1232 if (kresult != kIOReturnSuccess) {
1233 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
1235 if (priv->is_open) {
1236 (*(dpriv->device))->USBDeviceClose (dpriv->device);
1239 priv->is_open = false;
1241 return darwin_to_libusb (kresult);
1244 CFRetain (libusb_darwin_acfl);
1246 /* add the cfSource to the aync run loop */
1247 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
1250 /* device opened successfully */
1251 dpriv->open_count++;
1253 usbi_dbg ("device open for access");
1258 static void darwin_close (struct libusb_device_handle *dev_handle) {
1259 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1260 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1264 if (dpriv->open_count == 0) {
1265 /* something is probably very wrong if this is the case */
1266 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!");
1270 dpriv->open_count--;
1271 if (NULL == dpriv->device) {
1272 usbi_warn (HANDLE_CTX (dev_handle), "darwin_close device missing IOService");
1276 /* make sure all interfaces are released */
1277 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1278 if (dev_handle->claimed_interfaces & (1U << i))
1279 libusb_release_interface (dev_handle, i);
1281 if (0 == dpriv->open_count) {
1282 /* delete the device's async event source */
1283 if (priv->cfSource) {
1284 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
1285 CFRelease (priv->cfSource);
1286 priv->cfSource = NULL;
1287 CFRelease (libusb_darwin_acfl);
1290 if (priv->is_open) {
1291 /* close the device */
1292 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
1293 if (kresult != kIOReturnSuccess) {
1294 /* Log the fact that we had a problem closing the file, however failing a
1295 * close isn't really an error, so return success anyway */
1296 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
1302 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, uint8_t *config) {
1303 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1305 *config = dpriv->active_config;
1307 return LIBUSB_SUCCESS;
1310 static enum libusb_error darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
1311 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1318 /* Setting configuration will invalidate the interface, so we need
1319 to reclaim it. First, dispose of existing interfaces, if any. */
1320 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1321 if (dev_handle->claimed_interfaces & (1U << i))
1322 darwin_release_interface (dev_handle, i);
1324 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, (UInt8)config);
1325 if (kresult != kIOReturnSuccess)
1326 return darwin_to_libusb (kresult);
1328 /* Reclaim any interfaces. */
1329 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1330 if (dev_handle->claimed_interfaces & (1U << i))
1331 darwin_claim_interface (dev_handle, i);
1333 dpriv->active_config = (UInt8)config;
1335 return LIBUSB_SUCCESS;
1338 static IOReturn darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
1339 IOUSBFindInterfaceRequest request;
1341 io_iterator_t interface_iterator;
1342 UInt8 bInterfaceNumber;
1345 *usbInterfacep = IO_OBJECT_NULL;
1347 /* Setup the Interface Request */
1348 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1349 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1350 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1351 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1353 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1354 if (kresult != kIOReturnSuccess)
1357 while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1358 /* find the interface number */
1359 ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
1362 if (ret && bInterfaceNumber == ifc) {
1366 (void) IOObjectRelease (*usbInterfacep);
1369 /* done with the interface iterator */
1370 IOObjectRelease(interface_iterator);
1372 return kIOReturnSuccess;
1375 static enum libusb_error get_endpoints (struct libusb_device_handle *dev_handle, uint8_t iface) {
1376 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1378 /* current interface */
1379 struct darwin_interface *cInterface = &priv->interfaces[iface];
1383 UInt8 numep, direction, number;
1384 UInt8 dont_care1, dont_care3;
1388 usbi_dbg ("building table of endpoints.");
1390 /* retrieve the total number of endpoints on this interface */
1391 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1392 if (kresult != kIOReturnSuccess) {
1393 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1394 return darwin_to_libusb (kresult);
1397 /* iterate through pipe references */
1398 for (UInt8 i = 1 ; i <= numep ; i++) {
1399 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1400 &dont_care2, &dont_care3);
1402 if (kresult != kIOReturnSuccess) {
1403 /* probably a buggy device. try to get the endpoint address from the descriptors */
1404 struct libusb_config_descriptor *config;
1405 const struct libusb_endpoint_descriptor *endpoint_desc;
1408 kresult = (*(cInterface->interface))->GetAlternateSetting (cInterface->interface, &alt_setting);
1409 if (kresult != kIOReturnSuccess) {
1410 usbi_err (HANDLE_CTX (dev_handle), "can't get alternate setting for interface");
1411 return darwin_to_libusb (kresult);
1414 rc = libusb_get_active_config_descriptor (dev_handle->dev, &config);
1415 if (LIBUSB_SUCCESS != rc) {
1419 endpoint_desc = config->interface[iface].altsetting[alt_setting].endpoint + i - 1;
1421 cInterface->endpoint_addrs[i - 1] = endpoint_desc->bEndpointAddress;
1423 cInterface->endpoint_addrs[i - 1] = (UInt8)(((kUSBIn == direction) << kUSBRqDirnShift) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1426 usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, cInterface->endpoint_addrs[i - 1] >> kUSBRqDirnShift,
1427 cInterface->endpoint_addrs[i - 1] & LIBUSB_ENDPOINT_ADDRESS_MASK);
1430 cInterface->num_endpoints = numep;
1432 return LIBUSB_SUCCESS;
1435 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, uint8_t iface) {
1436 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1437 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1438 io_service_t usbInterface = IO_OBJECT_NULL;
1440 enum libusb_error ret;
1441 IOCFPlugInInterface **plugInInterface = NULL;
1444 /* current interface */
1445 struct darwin_interface *cInterface = &priv->interfaces[iface];
1447 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1448 if (kresult != kIOReturnSuccess)
1449 return darwin_to_libusb (kresult);
1451 /* make sure we have an interface */
1452 if (!usbInterface && dpriv->first_config != 0) {
1453 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1455 /* set the configuration */
1456 ret = darwin_set_configuration (dev_handle, (int) dpriv->first_config);
1457 if (ret != LIBUSB_SUCCESS) {
1458 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1462 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1463 if (kresult != kIOReturnSuccess) {
1464 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1465 return darwin_to_libusb (kresult);
1469 if (!usbInterface) {
1470 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1471 return LIBUSB_ERROR_NOT_FOUND;
1474 /* get an interface to the device's interface */
1475 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1476 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1478 /* ignore release error */
1479 (void)IOObjectRelease (usbInterface);
1481 if (kresult != kIOReturnSuccess) {
1482 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1483 return darwin_to_libusb (kresult);
1486 if (!plugInInterface) {
1487 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1488 return LIBUSB_ERROR_NOT_FOUND;
1491 /* Do the actual claim */
1492 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1493 CFUUIDGetUUIDBytes(InterfaceInterfaceID),
1494 (LPVOID)&cInterface->interface);
1495 /* We no longer need the intermediate plug-in */
1496 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1497 (*plugInInterface)->Release (plugInInterface);
1498 if (kresult != kIOReturnSuccess || !cInterface->interface) {
1499 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1500 return darwin_to_libusb (kresult);
1503 /* claim the interface */
1504 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1505 if (kresult != kIOReturnSuccess) {
1506 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1507 return darwin_to_libusb (kresult);
1510 /* update list of endpoints */
1511 ret = get_endpoints (dev_handle, iface);
1513 /* this should not happen */
1514 darwin_release_interface (dev_handle, iface);
1515 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1519 cInterface->cfSource = NULL;
1521 /* create async event source */
1522 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1523 if (kresult != kIOReturnSuccess) {
1524 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1526 /* can't continue without an async event source */
1527 (void)darwin_release_interface (dev_handle, iface);
1529 return darwin_to_libusb (kresult);
1532 /* add the cfSource to the async thread's run loop */
1533 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1535 usbi_dbg ("interface opened");
1537 return LIBUSB_SUCCESS;
1540 static int darwin_release_interface(struct libusb_device_handle *dev_handle, uint8_t iface) {
1541 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1544 /* current interface */
1545 struct darwin_interface *cInterface = &priv->interfaces[iface];
1547 /* Check to see if an interface is open */
1548 if (!cInterface->interface)
1549 return LIBUSB_SUCCESS;
1551 /* clean up endpoint data */
1552 cInterface->num_endpoints = 0;
1554 /* delete the interface's async event source */
1555 if (cInterface->cfSource) {
1556 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1557 CFRelease (cInterface->cfSource);
1560 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1561 if (kresult != kIOReturnSuccess)
1562 usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1564 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1565 if (kresult != kIOReturnSuccess)
1566 usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1568 cInterface->interface = (usb_interface_t **) IO_OBJECT_NULL;
1570 return darwin_to_libusb (kresult);
1573 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, uint8_t iface, uint8_t altsetting) {
1574 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1576 enum libusb_error ret;
1578 uint8_t old_alt_setting;
1580 /* current interface */
1581 struct darwin_interface *cInterface = &priv->interfaces[iface];
1583 if (!cInterface->interface)
1584 return LIBUSB_ERROR_NO_DEVICE;
1586 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1587 if (kresult == kIOReturnSuccess) {
1588 /* update the list of endpoints */
1589 ret = get_endpoints (dev_handle, iface);
1591 /* this should not happen */
1592 darwin_release_interface (dev_handle, iface);
1593 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1598 usbi_warn (HANDLE_CTX (dev_handle), "SetAlternateInterface: %s", darwin_error_str(kresult));
1600 if (kresult != kIOUSBPipeStalled)
1601 return darwin_to_libusb (kresult);
1603 /* If a device only supports a default setting for the specified interface, then a STALL
1604 (kIOUSBPipeStalled) may be returned. Ref: USB 2.0 specs 9.4.10.
1605 Mimick the behaviour in e.g. the Linux kernel: in such case, reset all endpoints
1606 of the interface (as would have been done per 9.1.1.5) and return success. */
1608 /* For some reason we need to reclaim the interface after the pipe error */
1609 ret = darwin_claim_interface (dev_handle, iface);
1612 darwin_release_interface (dev_handle, iface);
1613 usbi_err (HANDLE_CTX (dev_handle), "could not reclaim interface");
1616 /* Return error if a change to another value was attempted */
1617 kresult = (*(cInterface->interface))->GetAlternateSetting (cInterface->interface, &old_alt_setting);
1618 if (kresult == kIOReturnSuccess && altsetting != old_alt_setting)
1619 return LIBUSB_ERROR_PIPE;
1621 for (i = 0 ; i < cInterface->num_endpoints ; i++)
1622 darwin_clear_halt(dev_handle, cInterface->endpoint_addrs[i]);
1624 return LIBUSB_SUCCESS;
1627 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1628 /* current interface */
1629 struct darwin_interface *cInterface;
1633 /* determine the interface/endpoint to use */
1634 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, NULL, &cInterface) != 0) {
1635 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1637 return LIBUSB_ERROR_NOT_FOUND;
1640 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1641 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1642 if (kresult != kIOReturnSuccess)
1643 usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1645 return darwin_to_libusb (kresult);
1648 static int darwin_restore_state (struct libusb_device_handle *dev_handle, int8_t active_config,
1649 unsigned long claimed_interfaces) {
1650 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1651 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1652 int open_count = dpriv->open_count;
1655 /* clear claimed interfaces temporarily */
1656 dev_handle->claimed_interfaces = 0;
1658 /* close and re-open the device */
1659 priv->is_open = false;
1660 dpriv->open_count = 1;
1662 /* clean up open interfaces */
1663 (void) darwin_close (dev_handle);
1665 /* re-open the device */
1666 ret = darwin_open (dev_handle);
1667 dpriv->open_count = open_count;
1668 if (LIBUSB_SUCCESS != ret) {
1669 /* could not restore configuration */
1670 return LIBUSB_ERROR_NOT_FOUND;
1673 if (dpriv->active_config != active_config) {
1674 usbi_dbg ("darwin/restore_state: restoring configuration %d...", active_config);
1676 ret = darwin_set_configuration (dev_handle, active_config);
1677 if (LIBUSB_SUCCESS != ret) {
1678 usbi_dbg ("darwin/restore_state: could not restore configuration");
1679 return LIBUSB_ERROR_NOT_FOUND;
1683 usbi_dbg ("darwin/restore_state: reclaiming interfaces");
1685 if (claimed_interfaces) {
1686 for (uint8_t iface = 0 ; iface < USB_MAXINTERFACES ; ++iface) {
1687 if (!(claimed_interfaces & (1U << iface))) {
1691 usbi_dbg ("darwin/restore_state: re-claiming interface %u", iface);
1693 ret = darwin_claim_interface (dev_handle, iface);
1694 if (LIBUSB_SUCCESS != ret) {
1695 usbi_dbg ("darwin/restore_state: could not claim interface %u", iface);
1696 return LIBUSB_ERROR_NOT_FOUND;
1699 dev_handle->claimed_interfaces |= 1U << iface;
1703 usbi_dbg ("darwin/restore_state: device state restored");
1705 return LIBUSB_SUCCESS;
1708 static int darwin_reenumerate_device (struct libusb_device_handle *dev_handle, bool capture) {
1709 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1710 unsigned long claimed_interfaces = dev_handle->claimed_interfaces;
1711 int8_t active_config = dpriv->active_config;
1713 IOUSBDeviceDescriptor descriptor;
1714 IOUSBConfigurationDescriptorPtr cached_configuration;
1715 IOUSBConfigurationDescriptor *cached_configurations;
1720 if (dpriv->in_reenumerate) {
1721 /* ack, two (or more) threads are trying to reset the device! abort! */
1722 return LIBUSB_ERROR_NOT_FOUND;
1725 dpriv->in_reenumerate = true;
1727 /* store copies of descriptors so they can be compared after the reset */
1728 memcpy (&descriptor, &dpriv->dev_descriptor, sizeof (descriptor));
1729 cached_configurations = alloca (sizeof (*cached_configurations) * descriptor.bNumConfigurations);
1731 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1732 (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1733 memcpy (cached_configurations + i, cached_configuration, sizeof (cached_configurations[i]));
1736 /* if we need to release capture */
1737 if (HAS_CAPTURE_DEVICE()) {
1739 options |= kUSBReEnumerateCaptureDeviceMask;
1745 /* from macOS 10.11 ResetDevice no longer does anything so just use USBDeviceReEnumerate */
1746 kresult = (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, options);
1747 if (kresult != kIOReturnSuccess) {
1748 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceReEnumerate: %s", darwin_error_str (kresult));
1749 dpriv->in_reenumerate = false;
1750 return darwin_to_libusb (kresult);
1753 /* capture mode does not re-enumerate but it does require re-open */
1755 usbi_dbg ("darwin/reenumerate_device: restoring state...");
1756 dpriv->in_reenumerate = false;
1757 return darwin_restore_state (dev_handle, active_config, claimed_interfaces);
1760 usbi_dbg ("darwin/reenumerate_device: waiting for re-enumeration to complete...");
1763 while (dpriv->in_reenumerate) {
1764 struct timespec delay = {.tv_sec = 0, .tv_nsec = 1000};
1765 nanosleep (&delay, NULL);
1766 if (time++ >= DARWIN_REENUMERATE_TIMEOUT_US) {
1767 usbi_err (HANDLE_CTX (dev_handle), "darwin/reenumerate_device: timeout waiting for reenumerate");
1768 dpriv->in_reenumerate = false;
1769 return LIBUSB_ERROR_TIMEOUT;
1773 /* compare descriptors */
1774 usbi_dbg ("darwin/reenumerate_device: checking whether descriptors changed");
1776 if (memcmp (&descriptor, &dpriv->dev_descriptor, sizeof (descriptor))) {
1777 /* device descriptor changed. need to return not found. */
1778 usbi_dbg ("darwin/reenumerate_device: device descriptor changed");
1779 return LIBUSB_ERROR_NOT_FOUND;
1782 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1783 (void) (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1784 if (memcmp (cached_configuration, cached_configurations + i, sizeof (cached_configurations[i]))) {
1785 usbi_dbg ("darwin/reenumerate_device: configuration descriptor %d changed", i);
1786 return LIBUSB_ERROR_NOT_FOUND;
1790 usbi_dbg ("darwin/reenumerate_device: device reset complete. restoring state...");
1792 return darwin_restore_state (dev_handle, active_config, claimed_interfaces);
1795 static int darwin_reset_device (struct libusb_device_handle *dev_handle) {
1796 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1799 if (dpriv->capture_count > 0) {
1800 /* we have to use ResetDevice as USBDeviceReEnumerate() loses the authorization for capture */
1801 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1802 return darwin_to_libusb (kresult);
1804 return darwin_reenumerate_device (dev_handle, false);
1808 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, uint8_t interface) {
1809 enum libusb_error ret = darwin_claim_interface (dev_handle, interface);
1810 if (ret == LIBUSB_SUCCESS) {
1811 darwin_release_interface (dev_handle, interface);
1813 return (ret == LIBUSB_ERROR_ACCESS);
1816 static void darwin_destroy_device(struct libusb_device *dev) {
1817 struct darwin_device_priv *dpriv = usbi_get_device_priv(dev);
1820 /* need to hold the lock in case this is the last reference to the device */
1821 usbi_mutex_lock(&darwin_cached_devices_lock);
1822 darwin_deref_cached_device (dpriv->dev);
1824 usbi_mutex_unlock(&darwin_cached_devices_lock);
1828 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1829 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1832 uint8_t transferType;
1834 uint16_t maxPacketSize;
1836 struct darwin_interface *cInterface;
1837 #if InterfaceVersion >= 550
1838 IOUSBEndpointProperties pipeProperties = {.bVersion = kUSBEndpointPropertiesVersion3};
1840 /* None of the values below are used in libusb for bulk transfers */
1841 uint8_t direction, number, interval;
1844 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1845 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1847 return LIBUSB_ERROR_NOT_FOUND;
1850 #if InterfaceVersion >= 550
1851 ret = (*(cInterface->interface))->GetPipePropertiesV3 (cInterface->interface, pipeRef, &pipeProperties);
1853 transferType = pipeProperties.bTransferType;
1854 maxPacketSize = pipeProperties.wMaxPacketSize;
1856 ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1857 &transferType, &maxPacketSize, &interval);
1861 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1862 darwin_error_str(ret), ret);
1863 return darwin_to_libusb (ret);
1866 if (0 != (transfer->length % maxPacketSize)) {
1867 /* do not need a zero packet */
1868 transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1871 /* submit the request */
1872 /* timeouts are unavailable on interrupt endpoints */
1873 if (transferType == kUSBInterrupt) {
1874 if (IS_XFERIN(transfer))
1875 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1876 (UInt32)transfer->length, darwin_async_io_callback, itransfer);
1878 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1879 (UInt32)transfer->length, darwin_async_io_callback, itransfer);
1881 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1883 if (IS_XFERIN(transfer))
1884 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1885 (UInt32)transfer->length, transfer->timeout, transfer->timeout,
1886 darwin_async_io_callback, itransfer);
1888 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1889 (UInt32)transfer->length, transfer->timeout, transfer->timeout,
1890 darwin_async_io_callback, itransfer);
1894 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1895 darwin_error_str(ret), ret);
1897 return darwin_to_libusb (ret);
1900 #if InterfaceVersion >= 550
1901 static int submit_stream_transfer(struct usbi_transfer *itransfer) {
1902 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1903 struct darwin_interface *cInterface;
1907 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1908 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1910 return LIBUSB_ERROR_NOT_FOUND;
1913 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1915 if (IS_XFERIN(transfer))
1916 ret = (*(cInterface->interface))->ReadStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1917 transfer->buffer, (UInt32)transfer->length, transfer->timeout,
1918 transfer->timeout, darwin_async_io_callback, itransfer);
1920 ret = (*(cInterface->interface))->WriteStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1921 transfer->buffer, (UInt32)transfer->length, transfer->timeout,
1922 transfer->timeout, darwin_async_io_callback, itransfer);
1925 usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1926 darwin_error_str(ret), ret);
1928 return darwin_to_libusb (ret);
1932 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1933 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1934 struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
1937 uint8_t direction, number, interval, pipeRef, transferType;
1938 uint16_t maxPacketSize;
1940 AbsoluteTime atTime;
1943 struct darwin_interface *cInterface;
1945 /* construct an array of IOUSBIsocFrames, reuse the old one if the sizes are the same */
1946 if (tpriv->num_iso_packets != transfer->num_iso_packets) {
1947 free(tpriv->isoc_framelist);
1948 tpriv->isoc_framelist = NULL;
1951 if (!tpriv->isoc_framelist) {
1952 tpriv->num_iso_packets = transfer->num_iso_packets;
1953 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc ((size_t)transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1954 if (!tpriv->isoc_framelist)
1955 return LIBUSB_ERROR_NO_MEM;
1958 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1959 for (i = 0 ; i < transfer->num_iso_packets ; i++) {
1960 unsigned int length = transfer->iso_packet_desc[i].length;
1961 assert(length <= UINT16_MAX);
1962 tpriv->isoc_framelist[i].frReqCount = (UInt16)length;
1965 /* determine the interface/endpoint to use */
1966 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1967 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1969 return LIBUSB_ERROR_NOT_FOUND;
1972 /* determine the properties of this endpoint and the speed of the device */
1973 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1974 &transferType, &maxPacketSize, &interval);
1976 /* Last but not least we need the bus frame number */
1977 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1978 if (kresult != kIOReturnSuccess) {
1979 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1980 free(tpriv->isoc_framelist);
1981 tpriv->isoc_framelist = NULL;
1983 return darwin_to_libusb (kresult);
1986 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1987 &transferType, &maxPacketSize, &interval);
1989 /* schedule for a frame a little in the future */
1992 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1993 frame = cInterface->frames[transfer->endpoint];
1995 /* submit the request */
1996 if (IS_XFERIN(transfer))
1997 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1998 (UInt32)transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
2001 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
2002 (UInt32)transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
2005 if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
2007 cInterface->frames[transfer->endpoint] = frame + (UInt32)transfer->num_iso_packets * (1U << (interval - 1));
2009 /* High/super speed */
2010 cInterface->frames[transfer->endpoint] = frame + (UInt32)transfer->num_iso_packets * (1U << (interval - 1)) / 8;
2012 if (kresult != kIOReturnSuccess) {
2013 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
2014 darwin_error_str(kresult));
2015 free (tpriv->isoc_framelist);
2016 tpriv->isoc_framelist = NULL;
2019 return darwin_to_libusb (kresult);
2022 static int submit_control_transfer(struct usbi_transfer *itransfer) {
2023 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2024 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
2025 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
2026 struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2030 memset(&tpriv->req, 0, sizeof(tpriv->req));
2032 /* IOUSBDeviceInterface expects the request in cpu endianness */
2033 tpriv->req.bmRequestType = setup->bmRequestType;
2034 tpriv->req.bRequest = setup->bRequest;
2035 /* these values should be in bus order from libusb_fill_control_setup */
2036 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
2037 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
2038 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
2039 /* data is stored after the libusb control block */
2040 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
2041 tpriv->req.completionTimeout = transfer->timeout;
2042 tpriv->req.noDataTimeout = transfer->timeout;
2044 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
2046 /* all transfers in libusb-1.0 are async */
2048 if (transfer->endpoint) {
2049 struct darwin_interface *cInterface;
2052 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
2053 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
2055 return LIBUSB_ERROR_NOT_FOUND;
2058 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
2060 /* control request on endpoint 0 */
2061 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
2063 if (kresult != kIOReturnSuccess)
2064 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
2066 return darwin_to_libusb (kresult);
2069 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
2070 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2072 switch (transfer->type) {
2073 case LIBUSB_TRANSFER_TYPE_CONTROL:
2074 return submit_control_transfer(itransfer);
2075 case LIBUSB_TRANSFER_TYPE_BULK:
2076 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2077 return submit_bulk_transfer(itransfer);
2078 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2079 return submit_iso_transfer(itransfer);
2080 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2081 #if InterfaceVersion >= 550
2082 return submit_stream_transfer(itransfer);
2084 usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers");
2085 return LIBUSB_ERROR_NOT_SUPPORTED;
2088 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
2089 return LIBUSB_ERROR_INVALID_PARAM;
2093 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
2094 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2095 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
2098 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
2101 return LIBUSB_ERROR_NO_DEVICE;
2103 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
2105 return darwin_to_libusb (kresult);
2108 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
2109 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2110 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
2111 struct darwin_interface *cInterface;
2112 uint8_t pipeRef, iface;
2115 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) {
2116 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
2118 return LIBUSB_ERROR_NOT_FOUND;
2122 return LIBUSB_ERROR_NO_DEVICE;
2124 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
2126 /* abort transactions */
2127 #if InterfaceVersion >= 550
2128 if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type)
2129 (*(cInterface->interface))->AbortStreamsPipe (cInterface->interface, pipeRef, itransfer->stream_id);
2132 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
2134 usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
2136 /* newer versions of darwin support clearing additional bits on the device's endpoint */
2137 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
2139 return darwin_to_libusb (kresult);
2142 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
2143 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2145 switch (transfer->type) {
2146 case LIBUSB_TRANSFER_TYPE_CONTROL:
2147 return cancel_control_transfer(itransfer);
2148 case LIBUSB_TRANSFER_TYPE_BULK:
2149 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2150 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2151 return darwin_abort_transfers (itransfer);
2153 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
2154 return LIBUSB_ERROR_INVALID_PARAM;
2158 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
2159 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
2160 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2161 struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2163 usbi_dbg ("an async io operation has completed");
2165 /* if requested write a zero packet */
2166 if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
2167 struct darwin_interface *cInterface;
2170 (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface);
2172 (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
2175 tpriv->result = result;
2176 tpriv->size = (UInt32) (uintptr_t) arg0;
2178 /* signal the core that this transfer is complete */
2179 usbi_signal_transfer_completion(itransfer);
2182 static enum libusb_transfer_status darwin_transfer_status (struct usbi_transfer *itransfer, IOReturn result) {
2183 if (itransfer->timeout_flags & USBI_TRANSFER_TIMED_OUT)
2184 result = kIOUSBTransactionTimeout;
2187 case kIOReturnUnderrun:
2188 case kIOReturnSuccess:
2189 return LIBUSB_TRANSFER_COMPLETED;
2190 case kIOReturnAborted:
2191 return LIBUSB_TRANSFER_CANCELLED;
2192 case kIOUSBPipeStalled:
2193 usbi_dbg ("transfer error: pipe is stalled");
2194 return LIBUSB_TRANSFER_STALL;
2195 case kIOReturnOverrun:
2196 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
2197 return LIBUSB_TRANSFER_OVERFLOW;
2198 case kIOUSBTransactionTimeout:
2199 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
2200 itransfer->timeout_flags |= USBI_TRANSFER_TIMED_OUT;
2201 return LIBUSB_TRANSFER_TIMED_OUT;
2203 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
2204 return LIBUSB_TRANSFER_ERROR;
2208 static int darwin_handle_transfer_completion (struct usbi_transfer *itransfer) {
2209 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2210 struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2211 const unsigned char max_transfer_type = LIBUSB_TRANSFER_TYPE_BULK_STREAM;
2212 const char *transfer_types[] = {"control", "isoc", "bulk", "interrupt", "bulk-stream", NULL};
2213 bool is_isoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
2215 if (transfer->type > max_transfer_type) {
2216 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
2217 return LIBUSB_ERROR_INVALID_PARAM;
2220 if (NULL == tpriv) {
2221 usbi_err (TRANSFER_CTX(transfer), "malformed request is missing transfer priv");
2222 return LIBUSB_ERROR_INVALID_PARAM;
2225 usbi_dbg ("handling transfer completion type %s with kernel status %d", transfer_types[transfer->type], tpriv->result);
2227 if (kIOReturnSuccess == tpriv->result || kIOReturnUnderrun == tpriv->result || kIOUSBTransactionTimeout == tpriv->result) {
2228 if (is_isoc && tpriv->isoc_framelist) {
2229 /* copy isochronous results back */
2231 for (int i = 0; i < transfer->num_iso_packets ; i++) {
2232 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
2233 lib_desc->status = darwin_transfer_status (itransfer, tpriv->isoc_framelist[i].frStatus);
2234 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
2236 } else if (!is_isoc) {
2237 itransfer->transferred += tpriv->size;
2241 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
2242 return usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, tpriv->result));
2245 #if !defined(HAVE_CLOCK_GETTIME)
2246 void usbi_get_monotonic_time(struct timespec *tp) {
2247 mach_timespec_t sys_time;
2249 /* use system boot time as reference for the monotonic clock */
2250 clock_get_time (clock_monotonic, &sys_time);
2252 tp->tv_sec = sys_time.tv_sec;
2253 tp->tv_nsec = sys_time.tv_nsec;
2256 void usbi_get_real_time(struct timespec *tp) {
2257 mach_timespec_t sys_time;
2259 /* CLOCK_REALTIME represents time since the epoch */
2260 clock_get_time (clock_realtime, &sys_time);
2262 tp->tv_sec = sys_time.tv_sec;
2263 tp->tv_nsec = sys_time.tv_nsec;
2267 #if InterfaceVersion >= 550
2268 static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints,
2269 int num_endpoints) {
2270 struct darwin_interface *cInterface;
2271 UInt32 supportsStreams;
2275 /* find the minimum number of supported streams on the endpoint list */
2276 for (i = 0 ; i < num_endpoints ; ++i) {
2277 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) {
2281 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2282 if (num_streams > supportsStreams)
2283 num_streams = supportsStreams;
2286 /* it is an error if any endpoint in endpoints does not support streams */
2287 if (0 == num_streams)
2288 return LIBUSB_ERROR_INVALID_PARAM;
2290 /* create the streams */
2291 for (i = 0 ; i < num_endpoints ; ++i) {
2292 (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
2294 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, num_streams);
2295 if (kIOReturnSuccess != rc)
2296 return darwin_to_libusb(rc);
2299 assert(num_streams <= INT_MAX);
2300 return (int)num_streams;
2303 static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) {
2304 struct darwin_interface *cInterface;
2305 UInt32 supportsStreams;
2309 for (int i = 0 ; i < num_endpoints ; ++i) {
2310 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface)))
2313 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2314 if (0 == supportsStreams)
2315 return LIBUSB_ERROR_INVALID_PARAM;
2317 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, 0);
2318 if (kIOReturnSuccess != rc)
2319 return darwin_to_libusb(rc);
2322 return LIBUSB_SUCCESS;
2326 #if InterfaceVersion >= 700
2328 /* macOS APIs for getting entitlement values */
2331 #include <Security/Security.h>
2333 typedef struct __SecTask *SecTaskRef;
2334 extern SecTaskRef SecTaskCreateFromSelf(CFAllocatorRef allocator);
2335 extern CFTypeRef SecTaskCopyValueForEntitlement(SecTaskRef task, CFStringRef entitlement, CFErrorRef *error);
2338 static bool darwin_has_capture_entitlements (void) {
2343 task = SecTaskCreateFromSelf (kCFAllocatorDefault);
2347 value = SecTaskCopyValueForEntitlement(task, CFSTR("com.apple.vm.device-access"), NULL);
2349 entitled = value && (CFGetTypeID (value) == CFBooleanGetTypeID ()) && CFBooleanGetValue (value);
2356 static int darwin_reload_device (struct libusb_device_handle *dev_handle) {
2357 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
2358 enum libusb_error err;
2360 usbi_mutex_lock(&darwin_cached_devices_lock);
2361 (*(dpriv->device))->Release(dpriv->device);
2362 dpriv->device = darwin_device_from_service (dpriv->service);
2363 if (!dpriv->device) {
2364 err = LIBUSB_ERROR_NO_DEVICE;
2366 err = LIBUSB_SUCCESS;
2368 usbi_mutex_unlock(&darwin_cached_devices_lock);
2373 /* On macOS, we capture an entire device at once, not individual interfaces. */
2375 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, uint8_t interface) {
2377 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
2379 enum libusb_error err;
2381 if (HAS_CAPTURE_DEVICE()) {
2383 return LIBUSB_ERROR_NOT_SUPPORTED;
2386 if (dpriv->capture_count == 0) {
2387 usbi_dbg ("attempting to detach kernel driver from device");
2389 if (!darwin_has_capture_entitlements ()) {
2390 usbi_warn (HANDLE_CTX (dev_handle), "no capture entitlements. can not detach the kernel driver for this device");
2391 return LIBUSB_ERROR_NOT_SUPPORTED;
2394 /* request authorization */
2395 kresult = IOServiceAuthorize (dpriv->service, kIOServiceInteractionAllowed);
2396 if (kresult != kIOReturnSuccess) {
2397 usbi_err (HANDLE_CTX (dev_handle), "IOServiceAuthorize: %s", darwin_error_str(kresult));
2398 return darwin_to_libusb (kresult);
2401 /* we need start() to be called again for authorization status to refresh */
2402 err = darwin_reload_device (dev_handle);
2403 if (err != LIBUSB_SUCCESS) {
2407 /* reset device to release existing drivers */
2408 err = darwin_reenumerate_device (dev_handle, true);
2409 if (err != LIBUSB_SUCCESS) {
2413 dpriv->capture_count++;
2414 return LIBUSB_SUCCESS;
2418 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, uint8_t interface) {
2420 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
2422 if (HAS_CAPTURE_DEVICE()) {
2424 return LIBUSB_ERROR_NOT_SUPPORTED;
2427 dpriv->capture_count--;
2428 if (dpriv->capture_count > 0) {
2429 return LIBUSB_SUCCESS;
2432 usbi_dbg ("reenumerating device for kernel driver attach");
2434 /* reset device to attach kernel drivers */
2435 return darwin_reenumerate_device (dev_handle, false);
2438 static int darwin_capture_claim_interface(struct libusb_device_handle *dev_handle, uint8_t iface) {
2439 enum libusb_error ret;
2440 if (dev_handle->auto_detach_kernel_driver) {
2441 ret = darwin_detach_kernel_driver (dev_handle, iface);
2442 if (ret != LIBUSB_SUCCESS) {
2443 usbi_warn (HANDLE_CTX (dev_handle), "failed to auto-detach the kernel driver for this device, ret=%d", ret);
2447 return darwin_claim_interface (dev_handle, iface);
2450 static int darwin_capture_release_interface(struct libusb_device_handle *dev_handle, uint8_t iface) {
2451 enum libusb_error ret;
2452 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
2454 ret = darwin_release_interface (dev_handle, iface);
2455 if (ret != LIBUSB_SUCCESS) {
2459 if (dev_handle->auto_detach_kernel_driver && dpriv->capture_count > 0) {
2460 ret = darwin_attach_kernel_driver (dev_handle, iface);
2461 if (LIBUSB_SUCCESS != ret) {
2462 usbi_warn (HANDLE_CTX (dev_handle), "on attempt to reattach the kernel driver got ret=%d", ret);
2464 /* ignore the error as the interface was successfully released */
2467 return LIBUSB_SUCCESS;
2472 const struct usbi_os_backend usbi_backend = {
2474 .caps = USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2475 .init = darwin_init,
2476 .exit = darwin_exit,
2477 .get_active_config_descriptor = darwin_get_active_config_descriptor,
2478 .get_config_descriptor = darwin_get_config_descriptor,
2479 .hotplug_poll = darwin_hotplug_poll,
2481 .open = darwin_open,
2482 .close = darwin_close,
2483 .get_configuration = darwin_get_configuration,
2484 .set_configuration = darwin_set_configuration,
2486 .set_interface_altsetting = darwin_set_interface_altsetting,
2487 .clear_halt = darwin_clear_halt,
2488 .reset_device = darwin_reset_device,
2490 #if InterfaceVersion >= 550
2491 .alloc_streams = darwin_alloc_streams,
2492 .free_streams = darwin_free_streams,
2495 .kernel_driver_active = darwin_kernel_driver_active,
2497 #if InterfaceVersion >= 700
2498 .detach_kernel_driver = darwin_detach_kernel_driver,
2499 .attach_kernel_driver = darwin_attach_kernel_driver,
2500 .claim_interface = darwin_capture_claim_interface,
2501 .release_interface = darwin_capture_release_interface,
2503 .claim_interface = darwin_claim_interface,
2504 .release_interface = darwin_release_interface,
2507 .destroy_device = darwin_destroy_device,
2509 .submit_transfer = darwin_submit_transfer,
2510 .cancel_transfer = darwin_cancel_transfer,
2512 .handle_transfer_completion = darwin_handle_transfer_completion,
2514 .device_priv_size = sizeof(struct darwin_device_priv),
2515 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
2516 .transfer_priv_size = sizeof(struct darwin_transfer_priv),