1 /* -*- Mode: C; indent-tabs-mode:nil -*- */
3 * darwin backend for libusb 1.0
4 * Copyright © 2008-2019 Nathan Hjelm <hjelmn@users.sourceforge.net>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
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 #include <AvailabilityMacros.h>
45 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
46 #include <objc/objc-auto.h>
49 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 101200
50 /* Apple deprecated the darwin atomics in 10.12 in favor of C11 atomics */
51 #include <stdatomic.h>
52 #define libusb_darwin_atomic_fetch_add(x, y) atomic_fetch_add(x, y)
54 _Atomic int32_t initCount = ATOMIC_VAR_INIT(0);
56 /* use darwin atomics if the target is older than 10.12 */
57 #include <libkern/OSAtomic.h>
59 /* OSAtomicAdd32Barrier returns the new value */
60 #define libusb_darwin_atomic_fetch_add(x, y) (OSAtomicAdd32Barrier(y, x) - y)
62 static volatile int32_t initCount = 0;
66 /* On 10.12 and later, use newly available clock_*() functions */
67 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 101200
68 #define OSX_USE_CLOCK_GETTIME 1
70 #define OSX_USE_CLOCK_GETTIME 0
73 #include "darwin_usb.h"
75 /* async event thread */
76 static pthread_mutex_t libusb_darwin_at_mutex = PTHREAD_MUTEX_INITIALIZER;
77 static pthread_cond_t libusb_darwin_at_cond = PTHREAD_COND_INITIALIZER;
79 #if !OSX_USE_CLOCK_GETTIME
80 static clock_serv_t clock_realtime;
81 static clock_serv_t clock_monotonic;
84 static CFRunLoopRef libusb_darwin_acfl = NULL; /* event cf loop */
85 static CFRunLoopSourceRef libusb_darwin_acfls = NULL; /* shutdown signal for event cf loop */
87 static usbi_mutex_t darwin_cached_devices_lock = PTHREAD_MUTEX_INITIALIZER;
88 static struct list_head darwin_cached_devices = {&darwin_cached_devices, &darwin_cached_devices};
89 static const char *darwin_device_class = kIOUSBDeviceClassName;
91 #define DARWIN_CACHED_DEVICE(a) ((struct darwin_cached_device *) (((struct darwin_device_priv *)((a)->os_priv))->dev))
93 /* async event thread */
94 static pthread_t libusb_darwin_at;
96 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
97 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
98 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
99 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
100 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
102 static enum libusb_error darwin_scan_devices(struct libusb_context *ctx);
103 static enum libusb_error process_new_device (struct libusb_context *ctx, io_service_t service);
105 #if defined(ENABLE_LOGGING)
106 static const char *darwin_error_str (IOReturn result) {
107 static char string_buffer[50];
109 case kIOReturnSuccess:
111 case kIOReturnNotOpen:
112 return "device not opened for exclusive access";
113 case kIOReturnNoDevice:
114 return "no connection to an IOService";
115 case kIOUSBNoAsyncPortErr:
116 return "no async port has been opened for interface";
117 case kIOReturnExclusiveAccess:
118 return "another process has device opened for exclusive access";
119 case kIOUSBPipeStalled:
120 return "pipe is stalled";
122 return "could not establish a connection to the Darwin kernel";
123 case kIOUSBTransactionTimeout:
124 return "transaction timed out";
125 case kIOReturnBadArgument:
126 return "invalid argument";
127 case kIOReturnAborted:
128 return "transaction aborted";
129 case kIOReturnNotResponding:
130 return "device not responding";
131 case kIOReturnOverrun:
132 return "data overrun";
133 case kIOReturnCannotWire:
134 return "physical memory can not be wired down";
135 case kIOReturnNoResources:
136 return "out of resources";
137 case kIOUSBHighSpeedSplitError:
138 return "high speed split error";
140 snprintf(string_buffer, sizeof(string_buffer), "unknown error (0x%x)", result);
141 return string_buffer;
146 static enum libusb_error darwin_to_libusb (IOReturn result) {
148 case kIOReturnUnderrun:
149 case kIOReturnSuccess:
150 return LIBUSB_SUCCESS;
151 case kIOReturnNotOpen:
152 case kIOReturnNoDevice:
153 return LIBUSB_ERROR_NO_DEVICE;
154 case kIOReturnExclusiveAccess:
155 return LIBUSB_ERROR_ACCESS;
156 case kIOUSBPipeStalled:
157 return LIBUSB_ERROR_PIPE;
158 case kIOReturnBadArgument:
159 return LIBUSB_ERROR_INVALID_PARAM;
160 case kIOUSBTransactionTimeout:
161 return LIBUSB_ERROR_TIMEOUT;
162 case kIOReturnNotResponding:
163 case kIOReturnAborted:
165 case kIOUSBNoAsyncPortErr:
167 return LIBUSB_ERROR_OTHER;
171 /* this function must be called with the darwin_cached_devices_lock held */
172 static void darwin_deref_cached_device(struct darwin_cached_device *cached_dev) {
173 cached_dev->refcount--;
174 /* free the device and remove it from the cache */
175 if (0 == cached_dev->refcount) {
176 list_del(&cached_dev->list);
178 (*(cached_dev->device))->Release(cached_dev->device);
183 static void darwin_ref_cached_device(struct darwin_cached_device *cached_dev) {
184 cached_dev->refcount++;
187 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) {
188 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
190 /* current interface */
191 struct darwin_interface *cInterface;
195 usbi_dbg ("converting ep address 0x%02x to pipeRef and interface", ep);
197 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
198 cInterface = &priv->interfaces[iface];
200 if (dev_handle->claimed_interfaces & (1U << iface)) {
201 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
202 if (cInterface->endpoint_addrs[i] == ep) {
209 *interface_out = cInterface;
211 usbi_dbg ("pipe %d on interface %d matches", *pipep, iface);
212 return LIBUSB_SUCCESS;
218 /* No pipe found with the correct endpoint address */
219 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
221 return LIBUSB_ERROR_NOT_FOUND;
224 static IOReturn usb_setup_device_iterator (io_iterator_t *deviceIterator, UInt32 location) {
225 CFMutableDictionaryRef matchingDict = IOServiceMatching(darwin_device_class);
228 return kIOReturnError;
231 CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
232 &kCFTypeDictionaryKeyCallBacks,
233 &kCFTypeDictionaryValueCallBacks);
235 /* there are no unsigned CFNumber types so treat the value as signed. the OS seems to do this
236 internally (CFNumberType of locationID is kCFNumberSInt32Type) */
237 CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberSInt32Type, &location);
239 if (propertyMatchDict && locationCF) {
240 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
241 CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
243 /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
245 /* release our references as per the Create Rule */
246 if (propertyMatchDict)
247 CFRelease (propertyMatchDict);
249 CFRelease (locationCF);
252 return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator);
255 /* Returns 1 on success, 0 on failure. */
256 static bool get_ioregistry_value_number (io_service_t service, CFStringRef property, CFNumberType type, void *p) {
257 CFTypeRef cfNumber = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
261 if (CFGetTypeID(cfNumber) == CFNumberGetTypeID()) {
262 success = CFNumberGetValue(cfNumber, type, p);
265 CFRelease (cfNumber);
268 return (success != 0);
271 /* Returns 1 on success, 0 on failure. */
272 static bool get_ioregistry_value_data (io_service_t service, CFStringRef property, ssize_t size, void *p) {
273 CFTypeRef cfData = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
274 bool success = false;
277 if (CFGetTypeID (cfData) == CFDataGetTypeID ()) {
278 CFIndex length = CFDataGetLength (cfData);
283 CFDataGetBytes (cfData, CFRangeMake(0, size), p);
293 static usb_device_t **darwin_device_from_service (io_service_t service)
295 io_cf_plugin_ref_t *plugInInterface = NULL;
296 usb_device_t **device;
300 kresult = IOCreatePlugInInterfaceForService(service, kIOUSBDeviceUserClientTypeID,
301 kIOCFPlugInInterfaceID, &plugInInterface,
304 if (kIOReturnSuccess != kresult || !plugInInterface) {
305 usbi_dbg ("could not set up plugin for service: %s", darwin_error_str (kresult));
309 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
311 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
312 (*plugInInterface)->Release (plugInInterface);
317 static void darwin_devices_attached (void *ptr, io_iterator_t add_devices) {
319 struct libusb_context *ctx;
320 io_service_t service;
322 usbi_mutex_lock(&active_contexts_lock);
324 while ((service = IOIteratorNext(add_devices))) {
325 /* add this device to each active context's device list */
326 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
327 process_new_device (ctx, service);
330 IOObjectRelease(service);
333 usbi_mutex_unlock(&active_contexts_lock);
336 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
338 struct libusb_device *dev = NULL;
339 struct libusb_context *ctx;
340 struct darwin_cached_device *old_device;
346 usbi_mutex_lock(&active_contexts_lock);
348 while ((device = IOIteratorNext (rem_devices)) != 0) {
349 /* get the location from the i/o registry */
350 ret = get_ioregistry_value_number (device, CFSTR("sessionID"), kCFNumberSInt64Type, &session);
351 IOObjectRelease (device);
355 /* we need to match darwin_ref_cached_device call made in darwin_get_cached_device function
356 otherwise no cached device will ever get freed */
357 usbi_mutex_lock(&darwin_cached_devices_lock);
358 list_for_each_entry(old_device, &darwin_cached_devices, list, struct darwin_cached_device) {
359 if (old_device->session == session) {
360 darwin_deref_cached_device (old_device);
364 usbi_mutex_unlock(&darwin_cached_devices_lock);
366 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
367 usbi_dbg ("notifying context %p of device disconnect", ctx);
369 dev = usbi_get_device_by_session_id(ctx, (unsigned long) session);
371 /* signal the core that this device has been disconnected. the core will tear down this device
372 when the reference count reaches 0 */
373 usbi_disconnect_device(dev);
374 libusb_unref_device(dev);
379 usbi_mutex_unlock(&active_contexts_lock);
382 static void darwin_hotplug_poll (void)
384 /* not sure if 1 ms will be too long/short but it should work ok */
385 mach_timespec_t timeout = {.tv_sec = 0, .tv_nsec = 1000000ul};
387 /* since a kernel thread may nodify the IOInterators used for
388 * hotplug notidication we can't just clear the iterators.
389 * instead just wait until all IOService providers are quiet */
390 (void) IOKitWaitQuiet (kIOMasterPortDefault, &timeout);
393 static void darwin_clear_iterator (io_iterator_t iter) {
396 while ((device = IOIteratorNext (iter)) != 0)
397 IOObjectRelease (device);
400 static void *darwin_event_thread_main (void *arg0) {
402 struct libusb_context *ctx = (struct libusb_context *)arg0;
403 CFRunLoopRef runloop;
405 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
406 /* Set this thread's name, so it can be seen in the debugger
407 and crash reports. */
408 pthread_setname_np ("org.libusb.device-hotplug");
411 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
412 /* Tell the Objective-C garbage collector about this thread.
413 This is required because, unlike NSThreads, pthreads are
414 not automatically registered. Although we don't use
415 Objective-C, we use CoreFoundation, which does.
416 Garbage collection support was entirely removed in 10.12,
417 so don't bother there. */
418 objc_registerThreadWithCollector();
421 /* hotplug (device arrival/removal) sources */
422 CFRunLoopSourceContext libusb_shutdown_cfsourcectx;
423 CFRunLoopSourceRef libusb_notification_cfsource;
424 io_notification_port_t libusb_notification_port;
425 io_iterator_t libusb_rem_device_iterator;
426 io_iterator_t libusb_add_device_iterator;
428 usbi_dbg ("creating hotplug event source");
430 runloop = CFRunLoopGetCurrent ();
433 /* add the shutdown cfsource to the run loop */
434 memset(&libusb_shutdown_cfsourcectx, 0, sizeof(libusb_shutdown_cfsourcectx));
435 libusb_shutdown_cfsourcectx.info = runloop;
436 libusb_shutdown_cfsourcectx.perform = (void (*)(void *))CFRunLoopStop;
437 libusb_darwin_acfls = CFRunLoopSourceCreate(NULL, 0, &libusb_shutdown_cfsourcectx);
438 CFRunLoopAddSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
440 /* add the notification port to the run loop */
441 libusb_notification_port = IONotificationPortCreate (kIOMasterPortDefault);
442 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
443 CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
445 /* create notifications for removed devices */
446 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
447 IOServiceMatching(darwin_device_class),
448 darwin_devices_detached,
449 ctx, &libusb_rem_device_iterator);
451 if (kresult != kIOReturnSuccess) {
452 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
457 /* create notifications for attached devices */
458 kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
459 IOServiceMatching(darwin_device_class),
460 darwin_devices_attached,
461 ctx, &libusb_add_device_iterator);
463 if (kresult != kIOReturnSuccess) {
464 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
470 darwin_clear_iterator (libusb_rem_device_iterator);
471 darwin_clear_iterator (libusb_add_device_iterator);
473 usbi_dbg ("darwin event thread ready to receive events");
475 /* signal the main thread that the hotplug runloop has been created. */
476 pthread_mutex_lock (&libusb_darwin_at_mutex);
477 libusb_darwin_acfl = runloop;
478 pthread_cond_signal (&libusb_darwin_at_cond);
479 pthread_mutex_unlock (&libusb_darwin_at_mutex);
481 /* run the runloop */
484 usbi_dbg ("darwin event thread exiting");
486 /* remove the notification cfsource */
487 CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
489 /* remove the shutdown cfsource */
490 CFRunLoopRemoveSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
492 /* delete notification port */
493 IONotificationPortDestroy (libusb_notification_port);
495 /* delete iterators */
496 IOObjectRelease (libusb_rem_device_iterator);
497 IOObjectRelease (libusb_add_device_iterator);
499 CFRelease (libusb_darwin_acfls);
502 libusb_darwin_acfls = NULL;
503 libusb_darwin_acfl = NULL;
508 /* cleanup function to destroy cached devices */
509 static void __attribute__((destructor)) _darwin_finalize(void) {
510 struct darwin_cached_device *dev, *next;
512 usbi_mutex_lock(&darwin_cached_devices_lock);
513 list_for_each_entry_safe(dev, next, &darwin_cached_devices, list, struct darwin_cached_device) {
514 darwin_deref_cached_device(dev);
516 usbi_mutex_unlock(&darwin_cached_devices_lock);
519 static int darwin_init(struct libusb_context *ctx) {
522 rc = darwin_scan_devices (ctx);
523 if (LIBUSB_SUCCESS != rc) {
527 if (libusb_darwin_atomic_fetch_add (&initCount, 1) == 0) {
528 #if !OSX_USE_CLOCK_GETTIME
529 /* create the clocks that will be used if clock_gettime() is not available */
530 host_name_port_t host_self;
532 host_self = mach_host_self();
533 host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
534 host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
535 mach_port_deallocate(mach_task_self(), host_self);
538 pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, ctx);
540 pthread_mutex_lock (&libusb_darwin_at_mutex);
541 while (!libusb_darwin_acfl)
542 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
543 pthread_mutex_unlock (&libusb_darwin_at_mutex);
549 static void darwin_exit (struct libusb_context *ctx) {
551 if (libusb_darwin_atomic_fetch_add (&initCount, -1) == 1) {
552 #if !OSX_USE_CLOCK_GETTIME
553 mach_port_deallocate(mach_task_self(), clock_realtime);
554 mach_port_deallocate(mach_task_self(), clock_monotonic);
557 /* stop the event runloop and wait for the thread to terminate. */
558 CFRunLoopSourceSignal(libusb_darwin_acfls);
559 CFRunLoopWakeUp (libusb_darwin_acfl);
560 pthread_join (libusb_darwin_at, NULL);
564 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
565 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
567 /* return cached copy */
568 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
572 return LIBUSB_SUCCESS;
575 static int get_configuration_index (struct libusb_device *dev, int config_value) {
576 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
578 IOUSBConfigurationDescriptorPtr desc;
581 /* is there a simpler way to determine the index? */
582 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
583 if (kresult != kIOReturnSuccess)
584 return darwin_to_libusb (kresult);
586 for (i = 0 ; i < numConfig ; i++) {
587 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
589 if (desc->bConfigurationValue == config_value)
593 /* configuration not found */
594 return LIBUSB_ERROR_NOT_FOUND;
597 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
598 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
601 if (0 == priv->active_config)
602 return LIBUSB_ERROR_NOT_FOUND;
604 config_index = get_configuration_index (dev, priv->active_config);
605 if (config_index < 0)
608 assert(config_index >= 0 && config_index <= UINT8_MAX);
609 return darwin_get_config_descriptor (dev, (UInt8)config_index, buffer, len, host_endian);
612 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
613 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
614 IOUSBConfigurationDescriptorPtr desc;
618 if (!priv || !priv->device)
619 return LIBUSB_ERROR_OTHER;
621 kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
622 if (kresult == kIOReturnSuccess) {
623 /* copy descriptor */
624 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
625 len = libusb_le16_to_cpu(desc->wTotalLength);
627 memmove (buffer, desc, len);
629 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
633 ret = darwin_to_libusb (kresult);
634 if (ret != LIBUSB_SUCCESS)
640 /* check whether the os has configured the device */
641 static enum libusb_error darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) {
642 usb_device_t **darwin_device = dev->device;
644 IOUSBConfigurationDescriptorPtr configDesc;
645 IOUSBFindInterfaceRequest request;
647 io_iterator_t interface_iterator;
648 io_service_t firstInterface;
650 if (dev->dev_descriptor.bNumConfigurations < 1) {
651 usbi_err (ctx, "device has no configurations");
652 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
655 /* checking the configuration of a root hub simulation takes ~1 s in 10.11. the device is
657 if (0x05ac == dev->dev_descriptor.idVendor && 0x8005 == dev->dev_descriptor.idProduct) {
658 usbi_dbg ("ignoring configuration on root hub simulation");
659 dev->active_config = 0;
660 return LIBUSB_SUCCESS;
663 /* find the first configuration */
664 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
665 dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
667 /* check if the device is already configured. there is probably a better way than iterating over the
668 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
669 might lock up on the device request) */
671 /* Setup the Interface Request */
672 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
673 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
674 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
675 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
677 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
678 if (kresult != kIOReturnSuccess)
679 return darwin_to_libusb (kresult);
682 firstInterface = IOIteratorNext(interface_iterator);
684 /* done with the interface iterator */
685 IOObjectRelease(interface_iterator);
687 if (firstInterface) {
688 IOObjectRelease (firstInterface);
690 /* device is configured */
691 if (dev->dev_descriptor.bNumConfigurations == 1)
692 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
693 dev->active_config = dev->first_config;
695 /* devices with more than one configuration should work with GetConfiguration */
696 (*darwin_device)->GetConfiguration (darwin_device, &dev->active_config);
699 dev->active_config = 0;
701 usbi_dbg ("active config: %u, first config: %u", dev->active_config, dev->first_config);
703 return LIBUSB_SUCCESS;
706 static IOReturn darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
707 IOUSBDevRequestTO req;
709 assert(buffer_size <= UINT16_MAX);
711 memset (buffer, 0, buffer_size);
713 /* Set up request for descriptor/ */
714 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
715 req.bRequest = kUSBRqGetDescriptor;
716 req.wValue = (UInt16)(desc << 8);
717 req.wIndex = desc_index;
718 req.wLength = (UInt16)buffer_size;
720 req.noDataTimeout = 20;
721 req.completionTimeout = 100;
723 return (*device)->DeviceRequestTO (device, &req);
726 static enum libusb_error darwin_cache_device_descriptor (struct libusb_context *ctx, struct darwin_cached_device *dev) {
727 usb_device_t **device = dev->device;
729 long delay = 30000; // microseconds
730 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
732 IOReturn ret = 0, ret2;
734 UInt16 idProduct, idVendor;
736 dev->can_enumerate = 0;
738 (*device)->GetDeviceClass (device, &bDeviceClass);
739 (*device)->GetDeviceProduct (device, &idProduct);
740 (*device)->GetDeviceVendor (device, &idVendor);
742 /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
743 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
744 * to follow the spec as closely as possible, try opening the device */
745 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
748 /**** retrieve device descriptor ****/
749 ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &dev->dev_descriptor, sizeof(dev->dev_descriptor));
751 if (kIOReturnOverrun == ret && kUSBDeviceDesc == dev->dev_descriptor.bDescriptorType)
752 /* received an overrun error but we still received a device descriptor */
753 ret = kIOReturnSuccess;
755 if (kIOUSBVendorIDAppleComputer == idVendor) {
756 /* NTH: don't bother retrying or unsuspending Apple devices */
760 if (kIOReturnSuccess == ret && (0 == dev->dev_descriptor.bNumConfigurations ||
761 0 == dev->dev_descriptor.bcdUSB)) {
762 /* work around for incorrectly configured devices */
763 if (try_reconfigure && is_open) {
764 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
766 /* set the first configuration */
767 (*device)->SetConfiguration(device, 1);
769 /* don't try to reconfigure again */
773 ret = kIOUSBPipeStalled;
776 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
777 /* device may be suspended. unsuspend it and try again */
778 #if DeviceVersion >= 320
781 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
782 (void)(*device)->GetUSBDeviceInformation (device, &info);
784 /* note that the device was suspended */
785 if (info & (1U << kUSBInformationDeviceIsSuspendedBit) || 0 == info)
790 /* try to unsuspend the device */
791 ret2 = (*device)->USBDeviceSuspend (device, 0);
792 if (kIOReturnSuccess != ret2) {
793 /* prevent log spew from poorly behaving devices. this indicates the
794 os actually had trouble communicating with the device */
795 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
803 if (kIOReturnSuccess != ret) {
804 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %ld ms before trying again", ret, delay/1000);
805 /* sleep for a little while before trying again */
806 nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000}, NULL);
808 } while (kIOReturnSuccess != ret && retries--);
811 /* resuspend the device */
812 (void)(*device)->USBDeviceSuspend (device, 1);
815 (void) (*device)->USBDeviceClose (device);
817 if (ret != kIOReturnSuccess) {
818 /* a debug message was already printed out for this error */
819 if (LIBUSB_CLASS_HUB == bDeviceClass)
820 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
821 idVendor, idProduct, darwin_error_str (ret), ret);
823 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
824 idVendor, idProduct, darwin_error_str (ret), ret);
825 return darwin_to_libusb (ret);
828 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
829 if (libusb_le16_to_cpu (dev->dev_descriptor.idProduct) != idProduct) {
830 /* not a valid device */
831 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
832 idProduct, libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
833 return LIBUSB_ERROR_NO_DEVICE;
836 usbi_dbg ("cached device descriptor:");
837 usbi_dbg (" bDescriptorType: 0x%02x", dev->dev_descriptor.bDescriptorType);
838 usbi_dbg (" bcdUSB: 0x%04x", dev->dev_descriptor.bcdUSB);
839 usbi_dbg (" bDeviceClass: 0x%02x", dev->dev_descriptor.bDeviceClass);
840 usbi_dbg (" bDeviceSubClass: 0x%02x", dev->dev_descriptor.bDeviceSubClass);
841 usbi_dbg (" bDeviceProtocol: 0x%02x", dev->dev_descriptor.bDeviceProtocol);
842 usbi_dbg (" bMaxPacketSize0: 0x%02x", dev->dev_descriptor.bMaxPacketSize0);
843 usbi_dbg (" idVendor: 0x%04x", dev->dev_descriptor.idVendor);
844 usbi_dbg (" idProduct: 0x%04x", dev->dev_descriptor.idProduct);
845 usbi_dbg (" bcdDevice: 0x%04x", dev->dev_descriptor.bcdDevice);
846 usbi_dbg (" iManufacturer: 0x%02x", dev->dev_descriptor.iManufacturer);
847 usbi_dbg (" iProduct: 0x%02x", dev->dev_descriptor.iProduct);
848 usbi_dbg (" iSerialNumber: 0x%02x", dev->dev_descriptor.iSerialNumber);
849 usbi_dbg (" bNumConfigurations: 0x%02x", dev->dev_descriptor.bNumConfigurations);
851 dev->can_enumerate = 1;
853 return LIBUSB_SUCCESS;
856 /* Returns 1 on success, 0 on failure. */
857 static bool get_device_port (io_service_t service, UInt8 *port) {
862 if (get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, port)) {
866 kresult = IORegistryEntryGetParentEntry (service, kIOServicePlane, &parent);
867 if (kIOReturnSuccess == kresult) {
868 ret = get_ioregistry_value_data (parent, CFSTR("port"), 1, port);
869 IOObjectRelease (parent);
875 /* Returns 1 on success, 0 on failure. */
876 static bool get_device_parent_sessionID(io_service_t service, UInt64 *parent_sessionID) {
880 /* Walk up the tree in the IOService plane until we find a parent that has a sessionID */
882 while((kresult = IORegistryEntryGetParentEntry (parent, kIOUSBPlane, &parent)) == kIOReturnSuccess) {
883 if (get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, parent_sessionID)) {
889 /* We ran out of parents */
893 static enum libusb_error darwin_get_cached_device(struct libusb_context *ctx, io_service_t service,
894 struct darwin_cached_device **cached_out) {
895 struct darwin_cached_device *new_device;
896 UInt64 sessionID = 0, parent_sessionID = 0;
897 enum libusb_error ret = LIBUSB_SUCCESS;
898 usb_device_t **device;
901 /* get some info from the io registry */
902 (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
903 if (!get_device_port (service, &port)) {
904 usbi_dbg("could not get connected port number");
907 usbi_dbg("finding cached device for sessionID 0x%" PRIx64, sessionID);
909 if (get_device_parent_sessionID(service, &parent_sessionID)) {
910 usbi_dbg("parent sessionID: 0x%" PRIx64, parent_sessionID);
913 usbi_mutex_lock(&darwin_cached_devices_lock);
917 list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) {
918 usbi_dbg("matching sessionID 0x%" PRIx64 " against cached device with sessionID 0x%" PRIx64, sessionID, new_device->session);
919 if (new_device->session == sessionID) {
920 usbi_dbg("using cached device for device");
921 *cached_out = new_device;
929 usbi_dbg("caching new device with sessionID 0x%" PRIx64, sessionID);
931 device = darwin_device_from_service (service);
933 ret = LIBUSB_ERROR_NO_DEVICE;
937 new_device = calloc (1, sizeof (*new_device));
939 ret = LIBUSB_ERROR_NO_MEM;
943 /* add this device to the cached device list */
944 list_add(&new_device->list, &darwin_cached_devices);
946 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
948 /* keep a reference to this device */
949 darwin_ref_cached_device(new_device);
951 new_device->device = device;
952 new_device->session = sessionID;
953 (*device)->GetLocationID (device, &new_device->location);
954 new_device->port = port;
955 new_device->parent_session = parent_sessionID;
957 /* cache the device descriptor */
958 ret = darwin_cache_device_descriptor(ctx, new_device);
962 if (new_device->can_enumerate) {
963 snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address,
964 new_device->dev_descriptor.idVendor, new_device->dev_descriptor.idProduct,
965 new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass);
969 usbi_mutex_unlock(&darwin_cached_devices_lock);
971 /* keep track of devices regardless of if we successfully enumerate them to
972 prevent them from being enumerated multiple times */
974 *cached_out = new_device;
979 static enum libusb_error process_new_device (struct libusb_context *ctx, io_service_t service) {
980 struct darwin_device_priv *priv;
981 struct libusb_device *dev = NULL;
982 struct darwin_cached_device *cached_device;
984 enum libusb_error ret = LIBUSB_SUCCESS;
987 ret = darwin_get_cached_device (ctx, service, &cached_device);
989 if (ret < 0 || !cached_device->can_enumerate) {
993 /* check current active configuration (and cache the first configuration value--
994 which may be used by claim_interface) */
995 ret = darwin_check_configuration (ctx, cached_device);
999 usbi_dbg ("allocating new device in context %p for with session 0x%" PRIx64,
1000 ctx, cached_device->session);
1002 dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
1004 return LIBUSB_ERROR_NO_MEM;
1007 priv = (struct darwin_device_priv *)dev->os_priv;
1009 priv->dev = cached_device;
1010 darwin_ref_cached_device (priv->dev);
1012 if (cached_device->parent_session > 0) {
1013 dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session);
1015 dev->parent_dev = NULL;
1017 dev->port_number = cached_device->port;
1018 dev->bus_number = cached_device->location >> 24;
1019 assert(cached_device->address <= UINT8_MAX);
1020 dev->device_address = (uint8_t)cached_device->address;
1022 (*(priv->dev->device))->GetDeviceSpeed (priv->dev->device, &devSpeed);
1025 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
1026 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
1027 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
1028 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
1029 case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
1031 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101200
1032 case kUSBDeviceSpeedSuperPlus: dev->speed = LIBUSB_SPEED_SUPER_PLUS; break;
1035 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
1038 ret = usbi_sanitize_device (dev);
1042 usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
1043 dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
1047 usbi_connect_device (dev);
1049 libusb_unref_device (dev);
1055 static enum libusb_error darwin_scan_devices(struct libusb_context *ctx) {
1056 io_iterator_t deviceIterator;
1057 io_service_t service;
1060 kresult = usb_setup_device_iterator (&deviceIterator, 0);
1061 if (kresult != kIOReturnSuccess)
1062 return darwin_to_libusb (kresult);
1064 while ((service = IOIteratorNext (deviceIterator))) {
1065 (void) process_new_device (ctx, service);
1067 IOObjectRelease(service);
1070 IOObjectRelease(deviceIterator);
1072 return LIBUSB_SUCCESS;
1075 static int darwin_open (struct libusb_device_handle *dev_handle) {
1076 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1077 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1080 if (0 == dpriv->open_count) {
1081 /* try to open the device */
1082 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
1083 if (kresult != kIOReturnSuccess) {
1084 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
1086 if (kIOReturnExclusiveAccess != kresult) {
1087 return darwin_to_libusb (kresult);
1090 /* it is possible to perform some actions on a device that is not open so do not return an error */
1096 /* create async event source */
1097 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
1098 if (kresult != kIOReturnSuccess) {
1099 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
1101 if (priv->is_open) {
1102 (*(dpriv->device))->USBDeviceClose (dpriv->device);
1107 return darwin_to_libusb (kresult);
1110 CFRetain (libusb_darwin_acfl);
1112 /* add the cfSource to the aync run loop */
1113 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
1116 /* device opened successfully */
1117 dpriv->open_count++;
1119 usbi_dbg ("device open for access");
1124 static void darwin_close (struct libusb_device_handle *dev_handle) {
1125 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1126 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1130 if (dpriv->open_count == 0) {
1131 /* something is probably very wrong if this is the case */
1132 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!");
1136 dpriv->open_count--;
1138 /* make sure all interfaces are released */
1139 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1140 if (dev_handle->claimed_interfaces & (1U << i))
1141 libusb_release_interface (dev_handle, i);
1143 if (0 == dpriv->open_count) {
1144 /* delete the device's async event source */
1145 if (priv->cfSource) {
1146 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
1147 CFRelease (priv->cfSource);
1148 priv->cfSource = NULL;
1149 CFRelease (libusb_darwin_acfl);
1152 if (priv->is_open) {
1153 /* close the device */
1154 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
1155 if (kresult != kIOReturnSuccess) {
1156 /* Log the fact that we had a problem closing the file, however failing a
1157 * close isn't really an error, so return success anyway */
1158 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
1164 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
1165 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1167 *config = (int) dpriv->active_config;
1169 return LIBUSB_SUCCESS;
1172 static enum libusb_error darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
1173 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1177 assert(config >= 0 && config <= UINT8_MAX);
1179 /* Setting configuration will invalidate the interface, so we need
1180 to reclaim it. First, dispose of existing interfaces, if any. */
1181 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1182 if (dev_handle->claimed_interfaces & (1U << i))
1183 darwin_release_interface (dev_handle, i);
1185 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, (UInt8)config);
1186 if (kresult != kIOReturnSuccess)
1187 return darwin_to_libusb (kresult);
1189 /* Reclaim any interfaces. */
1190 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1191 if (dev_handle->claimed_interfaces & (1U << i))
1192 darwin_claim_interface (dev_handle, i);
1194 dpriv->active_config = (UInt8)config;
1196 return LIBUSB_SUCCESS;
1199 static IOReturn darwin_get_interface (usb_device_t **darwin_device, int ifc, io_service_t *usbInterfacep) {
1200 IOUSBFindInterfaceRequest request;
1202 io_iterator_t interface_iterator;
1203 UInt8 bInterfaceNumber;
1206 *usbInterfacep = IO_OBJECT_NULL;
1208 /* Setup the Interface Request */
1209 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1210 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1211 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1212 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1214 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1215 if (kresult != kIOReturnSuccess)
1218 while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1219 /* find the interface number */
1220 ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
1223 if (ret && bInterfaceNumber == ifc) {
1227 (void) IOObjectRelease (*usbInterfacep);
1230 /* done with the interface iterator */
1231 IOObjectRelease(interface_iterator);
1233 return kIOReturnSuccess;
1236 static enum libusb_error get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
1237 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1239 /* current interface */
1240 struct darwin_interface *cInterface = &priv->interfaces[iface];
1244 UInt8 numep, direction, number;
1245 UInt8 dont_care1, dont_care3;
1249 usbi_dbg ("building table of endpoints.");
1251 /* retrieve the total number of endpoints on this interface */
1252 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1253 if (kresult != kIOReturnSuccess) {
1254 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1255 return darwin_to_libusb (kresult);
1258 /* iterate through pipe references */
1259 for (UInt8 i = 1 ; i <= numep ; i++) {
1260 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1261 &dont_care2, &dont_care3);
1263 if (kresult != kIOReturnSuccess) {
1264 /* probably a buggy device. try to get the endpoint address from the descriptors */
1265 struct libusb_config_descriptor *config;
1266 const struct libusb_endpoint_descriptor *endpoint_desc;
1269 kresult = (*(cInterface->interface))->GetAlternateSetting (cInterface->interface, &alt_setting);
1270 if (kresult != kIOReturnSuccess) {
1271 usbi_err (HANDLE_CTX (dev_handle), "can't get alternate setting for interface");
1272 return darwin_to_libusb (kresult);
1275 rc = libusb_get_active_config_descriptor (dev_handle->dev, &config);
1276 if (LIBUSB_SUCCESS != rc) {
1280 endpoint_desc = config->interface[iface].altsetting[alt_setting].endpoint + i - 1;
1282 cInterface->endpoint_addrs[i - 1] = endpoint_desc->bEndpointAddress;
1284 cInterface->endpoint_addrs[i - 1] = (UInt8)(((kUSBIn == direction) << kUSBRqDirnShift) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1287 usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, cInterface->endpoint_addrs[i - 1] >> kUSBRqDirnShift,
1288 cInterface->endpoint_addrs[i - 1] & LIBUSB_ENDPOINT_ADDRESS_MASK);
1291 cInterface->num_endpoints = numep;
1293 return LIBUSB_SUCCESS;
1296 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1297 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1298 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1299 io_service_t usbInterface = IO_OBJECT_NULL;
1301 enum libusb_error ret;
1302 IOCFPlugInInterface **plugInInterface = NULL;
1305 assert(iface >= 0 && iface <= UINT8_MAX);
1307 /* current interface */
1308 struct darwin_interface *cInterface = &priv->interfaces[iface];
1310 kresult = darwin_get_interface (dpriv->device, (uint8_t)iface, &usbInterface);
1311 if (kresult != kIOReturnSuccess)
1312 return darwin_to_libusb (kresult);
1314 /* make sure we have an interface */
1315 if (!usbInterface && dpriv->first_config != 0) {
1316 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1318 /* set the configuration */
1319 ret = darwin_set_configuration (dev_handle, dpriv->first_config);
1320 if (ret != LIBUSB_SUCCESS) {
1321 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1325 kresult = darwin_get_interface (dpriv->device, (uint8_t)iface, &usbInterface);
1326 if (kresult != kIOReturnSuccess) {
1327 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1328 return darwin_to_libusb (kresult);
1332 if (!usbInterface) {
1333 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1334 return LIBUSB_ERROR_NOT_FOUND;
1337 /* get an interface to the device's interface */
1338 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1339 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1341 /* ignore release error */
1342 (void)IOObjectRelease (usbInterface);
1344 if (kresult != kIOReturnSuccess) {
1345 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1346 return darwin_to_libusb (kresult);
1349 if (!plugInInterface) {
1350 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1351 return LIBUSB_ERROR_NOT_FOUND;
1354 /* Do the actual claim */
1355 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1356 CFUUIDGetUUIDBytes(InterfaceInterfaceID),
1357 (LPVOID)&cInterface->interface);
1358 /* We no longer need the intermediate plug-in */
1359 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1360 (*plugInInterface)->Release (plugInInterface);
1361 if (kresult != kIOReturnSuccess || !cInterface->interface) {
1362 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1363 return darwin_to_libusb (kresult);
1366 /* claim the interface */
1367 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1368 if (kresult != kIOReturnSuccess) {
1369 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1370 return darwin_to_libusb (kresult);
1373 /* update list of endpoints */
1374 ret = get_endpoints (dev_handle, iface);
1376 /* this should not happen */
1377 darwin_release_interface (dev_handle, iface);
1378 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1382 cInterface->cfSource = NULL;
1384 /* create async event source */
1385 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1386 if (kresult != kIOReturnSuccess) {
1387 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1389 /* can't continue without an async event source */
1390 (void)darwin_release_interface (dev_handle, iface);
1392 return darwin_to_libusb (kresult);
1395 /* add the cfSource to the async thread's run loop */
1396 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1398 usbi_dbg ("interface opened");
1400 return LIBUSB_SUCCESS;
1403 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1404 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1407 /* current interface */
1408 struct darwin_interface *cInterface = &priv->interfaces[iface];
1410 /* Check to see if an interface is open */
1411 if (!cInterface->interface)
1412 return LIBUSB_SUCCESS;
1414 /* clean up endpoint data */
1415 cInterface->num_endpoints = 0;
1417 /* delete the interface's async event source */
1418 if (cInterface->cfSource) {
1419 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1420 CFRelease (cInterface->cfSource);
1423 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1424 if (kresult != kIOReturnSuccess)
1425 usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1427 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1428 if (kresult != kIOReturnSuccess)
1429 usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1431 cInterface->interface = (usb_interface_t **) IO_OBJECT_NULL;
1433 return darwin_to_libusb (kresult);
1436 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1437 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1439 enum libusb_error ret;
1441 /* current interface */
1442 struct darwin_interface *cInterface = &priv->interfaces[iface];
1444 if (!cInterface->interface)
1445 return LIBUSB_ERROR_NO_DEVICE;
1447 assert(altsetting >= 0 && altsetting <= UINT8_MAX);
1448 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, (UInt8)altsetting);
1449 if (kresult != kIOReturnSuccess)
1450 darwin_reset_device (dev_handle);
1452 /* update list of endpoints */
1453 ret = get_endpoints (dev_handle, iface);
1455 /* this should not happen */
1456 darwin_release_interface (dev_handle, iface);
1457 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1461 return darwin_to_libusb (kresult);
1464 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1465 /* current interface */
1466 struct darwin_interface *cInterface;
1470 /* determine the interface/endpoint to use */
1471 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, NULL, &cInterface) != 0) {
1472 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1474 return LIBUSB_ERROR_NOT_FOUND;
1477 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1478 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1479 if (kresult != kIOReturnSuccess)
1480 usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1482 return darwin_to_libusb (kresult);
1485 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1486 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1487 IOUSBDeviceDescriptor descriptor;
1488 IOUSBConfigurationDescriptorPtr cached_configuration;
1489 IOUSBConfigurationDescriptor configuration;
1490 bool reenumerate = false;
1494 /* from macOS 10.11 ResetDevice no longer does anything so just use USBDeviceReEnumerate */
1495 kresult = (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
1496 if (kresult != kIOReturnSuccess) {
1497 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceReEnumerate: %s", darwin_error_str (kresult));
1498 return darwin_to_libusb (kresult);
1502 usbi_dbg ("darwin/reset_device: checking if device descriptor changed");
1504 /* ignore return code. if we can't get a descriptor it might be worthwhile re-enumerating anway */
1505 (void) darwin_request_descriptor (dpriv->device, kUSBDeviceDesc, 0, &descriptor, sizeof (descriptor));
1507 /* check if the device descriptor has changed */
1508 if (0 != memcmp (&dpriv->dev_descriptor, &descriptor, sizeof (descriptor))) {
1513 /* check if any configuration descriptor has changed */
1514 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1515 usbi_dbg ("darwin/reset_device: checking if configuration descriptor %d changed", i);
1517 (void) darwin_request_descriptor (dpriv->device, kUSBConfDesc, i, &configuration, sizeof (configuration));
1518 (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1520 if (!cached_configuration || 0 != memcmp (cached_configuration, &configuration, sizeof (configuration))) {
1528 usbi_dbg ("darwin/reset_device: device requires reenumeration");
1529 (void) (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
1530 return LIBUSB_ERROR_NOT_FOUND;
1533 usbi_dbg ("darwin/reset_device: device reset complete");
1535 return LIBUSB_SUCCESS;
1538 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1539 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1540 io_service_t usbInterface;
1544 assert(interface >= 0 && interface <= UINT8_MAX);
1545 kresult = darwin_get_interface (dpriv->device, (uint8_t)interface, &usbInterface);
1546 if (kresult != kIOReturnSuccess) {
1547 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1549 return darwin_to_libusb (kresult);
1552 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1553 IOObjectRelease (usbInterface);
1565 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1566 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1569 return LIBUSB_ERROR_NOT_SUPPORTED;
1572 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1575 return LIBUSB_ERROR_NOT_SUPPORTED;
1578 static void darwin_destroy_device(struct libusb_device *dev) {
1579 struct darwin_device_priv *dpriv = (struct darwin_device_priv *) dev->os_priv;
1582 /* need to hold the lock in case this is the last reference to the device */
1583 usbi_mutex_lock(&darwin_cached_devices_lock);
1584 darwin_deref_cached_device (dpriv->dev);
1586 usbi_mutex_unlock(&darwin_cached_devices_lock);
1590 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1591 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1594 uint8_t transferType;
1595 /* None of the values below are used in libusbx for bulk transfers */
1596 uint8_t direction, number, interval, pipeRef;
1597 uint16_t maxPacketSize;
1599 struct darwin_interface *cInterface;
1601 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1602 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1604 return LIBUSB_ERROR_NOT_FOUND;
1607 ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1608 &transferType, &maxPacketSize, &interval);
1611 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1612 darwin_error_str(ret), ret);
1613 return darwin_to_libusb (ret);
1616 if (0 != (transfer->length % maxPacketSize)) {
1617 /* do not need a zero packet */
1618 transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1621 /* submit the request */
1622 /* timeouts are unavailable on interrupt endpoints */
1623 if (transferType == kUSBInterrupt) {
1624 if (IS_XFERIN(transfer))
1625 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1626 (UInt32)transfer->length, darwin_async_io_callback, itransfer);
1628 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1629 (UInt32)transfer->length, darwin_async_io_callback, itransfer);
1631 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1633 if (IS_XFERIN(transfer))
1634 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1635 (UInt32)transfer->length, transfer->timeout, transfer->timeout,
1636 darwin_async_io_callback, itransfer);
1638 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1639 (UInt32)transfer->length, transfer->timeout, transfer->timeout,
1640 darwin_async_io_callback, itransfer);
1644 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1645 darwin_error_str(ret), ret);
1647 return darwin_to_libusb (ret);
1650 #if InterfaceVersion >= 550
1651 static int submit_stream_transfer(struct usbi_transfer *itransfer) {
1652 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1653 struct darwin_interface *cInterface;
1657 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1658 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1660 return LIBUSB_ERROR_NOT_FOUND;
1663 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1665 if (IS_XFERIN(transfer))
1666 ret = (*(cInterface->interface))->ReadStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1667 transfer->buffer, (UInt32)transfer->length, transfer->timeout,
1668 transfer->timeout, darwin_async_io_callback, itransfer);
1670 ret = (*(cInterface->interface))->WriteStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1671 transfer->buffer, (UInt32)transfer->length, transfer->timeout,
1672 transfer->timeout, darwin_async_io_callback, itransfer);
1675 usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1676 darwin_error_str(ret), ret);
1678 return darwin_to_libusb (ret);
1682 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1683 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1684 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1687 uint8_t direction, number, interval, pipeRef, transferType;
1688 uint16_t maxPacketSize;
1690 AbsoluteTime atTime;
1693 struct darwin_interface *cInterface;
1695 /* construct an array of IOUSBIsocFrames, reuse the old one if the sizes are the same */
1696 if (tpriv->num_iso_packets != transfer->num_iso_packets) {
1697 free(tpriv->isoc_framelist);
1698 tpriv->isoc_framelist = NULL;
1701 if (!tpriv->isoc_framelist) {
1702 tpriv->num_iso_packets = transfer->num_iso_packets;
1703 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc ((size_t)transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1704 if (!tpriv->isoc_framelist)
1705 return LIBUSB_ERROR_NO_MEM;
1708 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1709 for (i = 0 ; i < transfer->num_iso_packets ; i++) {
1710 unsigned int length = transfer->iso_packet_desc[i].length;
1711 assert(length <= UINT16_MAX);
1712 tpriv->isoc_framelist[i].frReqCount = (UInt16)length;
1715 /* determine the interface/endpoint to use */
1716 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1717 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1719 return LIBUSB_ERROR_NOT_FOUND;
1722 /* determine the properties of this endpoint and the speed of the device */
1723 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1724 &transferType, &maxPacketSize, &interval);
1726 /* Last but not least we need the bus frame number */
1727 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1728 if (kresult != kIOReturnSuccess) {
1729 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1730 free(tpriv->isoc_framelist);
1731 tpriv->isoc_framelist = NULL;
1733 return darwin_to_libusb (kresult);
1736 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1737 &transferType, &maxPacketSize, &interval);
1739 /* schedule for a frame a little in the future */
1742 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1743 frame = cInterface->frames[transfer->endpoint];
1745 /* submit the request */
1746 if (IS_XFERIN(transfer))
1747 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1748 (UInt32)transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1751 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1752 (UInt32)transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1755 if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
1757 cInterface->frames[transfer->endpoint] = frame + (UInt32)transfer->num_iso_packets * (1U << (interval - 1));
1759 /* High/super speed */
1760 cInterface->frames[transfer->endpoint] = frame + (UInt32)transfer->num_iso_packets * (1U << (interval - 1)) / 8;
1762 if (kresult != kIOReturnSuccess) {
1763 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1764 darwin_error_str(kresult));
1765 free (tpriv->isoc_framelist);
1766 tpriv->isoc_framelist = NULL;
1769 return darwin_to_libusb (kresult);
1772 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1773 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1774 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1775 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1776 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1780 memset(&tpriv->req, 0, sizeof(tpriv->req));
1782 /* IOUSBDeviceInterface expects the request in cpu endianness */
1783 tpriv->req.bmRequestType = setup->bmRequestType;
1784 tpriv->req.bRequest = setup->bRequest;
1785 /* these values should be in bus order from libusb_fill_control_setup */
1786 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1787 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1788 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1789 /* data is stored after the libusb control block */
1790 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1791 tpriv->req.completionTimeout = transfer->timeout;
1792 tpriv->req.noDataTimeout = transfer->timeout;
1794 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1796 /* all transfers in libusb-1.0 are async */
1798 if (transfer->endpoint) {
1799 struct darwin_interface *cInterface;
1802 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1803 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1805 return LIBUSB_ERROR_NOT_FOUND;
1808 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1810 /* control request on endpoint 0 */
1811 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1813 if (kresult != kIOReturnSuccess)
1814 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1816 return darwin_to_libusb (kresult);
1819 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1820 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1822 switch (transfer->type) {
1823 case LIBUSB_TRANSFER_TYPE_CONTROL:
1824 return submit_control_transfer(itransfer);
1825 case LIBUSB_TRANSFER_TYPE_BULK:
1826 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1827 return submit_bulk_transfer(itransfer);
1828 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1829 return submit_iso_transfer(itransfer);
1830 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1831 #if InterfaceVersion >= 550
1832 return submit_stream_transfer(itransfer);
1834 usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers");
1835 return LIBUSB_ERROR_NOT_SUPPORTED;
1838 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1839 return LIBUSB_ERROR_INVALID_PARAM;
1843 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1844 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1845 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1848 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
1851 return LIBUSB_ERROR_NO_DEVICE;
1853 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1855 return darwin_to_libusb (kresult);
1858 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1859 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1860 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1861 struct darwin_interface *cInterface;
1862 uint8_t pipeRef, iface;
1865 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) {
1866 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1868 return LIBUSB_ERROR_NOT_FOUND;
1872 return LIBUSB_ERROR_NO_DEVICE;
1874 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
1876 /* abort transactions */
1877 #if InterfaceVersion >= 550
1878 if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type)
1879 (*(cInterface->interface))->AbortStreamsPipe (cInterface->interface, pipeRef, itransfer->stream_id);
1882 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1884 usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
1886 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1887 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1889 return darwin_to_libusb (kresult);
1892 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1893 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1895 switch (transfer->type) {
1896 case LIBUSB_TRANSFER_TYPE_CONTROL:
1897 return cancel_control_transfer(itransfer);
1898 case LIBUSB_TRANSFER_TYPE_BULK:
1899 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1900 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1901 return darwin_abort_transfers (itransfer);
1903 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1904 return LIBUSB_ERROR_INVALID_PARAM;
1908 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1909 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1910 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1912 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1913 free (tpriv->isoc_framelist);
1914 tpriv->isoc_framelist = NULL;
1918 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1919 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1920 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1921 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1923 usbi_dbg ("an async io operation has completed");
1925 /* if requested write a zero packet */
1926 if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
1927 struct darwin_interface *cInterface;
1930 (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface);
1932 (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
1935 tpriv->result = result;
1936 tpriv->size = (UInt32) (uintptr_t) arg0;
1938 /* signal the core that this transfer is complete */
1939 usbi_signal_transfer_completion(itransfer);
1942 static enum libusb_transfer_status darwin_transfer_status (struct usbi_transfer *itransfer, IOReturn result) {
1943 if (itransfer->timeout_flags & USBI_TRANSFER_TIMED_OUT)
1944 result = kIOUSBTransactionTimeout;
1947 case kIOReturnUnderrun:
1948 case kIOReturnSuccess:
1949 return LIBUSB_TRANSFER_COMPLETED;
1950 case kIOReturnAborted:
1951 return LIBUSB_TRANSFER_CANCELLED;
1952 case kIOUSBPipeStalled:
1953 usbi_dbg ("transfer error: pipe is stalled");
1954 return LIBUSB_TRANSFER_STALL;
1955 case kIOReturnOverrun:
1956 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1957 return LIBUSB_TRANSFER_OVERFLOW;
1958 case kIOUSBTransactionTimeout:
1959 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1960 itransfer->timeout_flags |= USBI_TRANSFER_TIMED_OUT;
1961 return LIBUSB_TRANSFER_TIMED_OUT;
1963 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1964 return LIBUSB_TRANSFER_ERROR;
1968 static int darwin_handle_transfer_completion (struct usbi_transfer *itransfer) {
1969 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1970 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1971 bool isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1972 bool isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1973 bool isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1974 bool isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1977 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1978 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1979 return LIBUSB_ERROR_INVALID_PARAM;
1982 usbi_dbg ("handling %s completion with kernel status %d",
1983 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", tpriv->result);
1985 if (kIOReturnSuccess == tpriv->result || kIOReturnUnderrun == tpriv->result) {
1986 if (isIsoc && tpriv->isoc_framelist) {
1987 /* copy isochronous results back */
1989 for (i = 0; i < transfer->num_iso_packets ; i++) {
1990 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1991 lib_desc->status = darwin_transfer_status (itransfer, tpriv->isoc_framelist[i].frStatus);
1992 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1995 itransfer->transferred += tpriv->size;
1998 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1999 return usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, tpriv->result));
2002 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
2003 #if !OSX_USE_CLOCK_GETTIME
2004 mach_timespec_t sys_time;
2005 clock_serv_t clock_ref;
2008 case USBI_CLOCK_REALTIME:
2009 /* CLOCK_REALTIME represents time since the epoch */
2010 clock_ref = clock_realtime;
2012 case USBI_CLOCK_MONOTONIC:
2013 /* use system boot time as reference for the monotonic clock */
2014 clock_ref = clock_monotonic;
2017 return LIBUSB_ERROR_INVALID_PARAM;
2020 clock_get_time (clock_ref, &sys_time);
2022 tp->tv_sec = sys_time.tv_sec;
2023 tp->tv_nsec = sys_time.tv_nsec;
2025 return LIBUSB_SUCCESS;
2028 case USBI_CLOCK_MONOTONIC:
2029 return clock_gettime(CLOCK_MONOTONIC, tp);
2030 case USBI_CLOCK_REALTIME:
2031 return clock_gettime(CLOCK_REALTIME, tp);
2033 return LIBUSB_ERROR_INVALID_PARAM;
2038 #if InterfaceVersion >= 550
2039 static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints,
2040 int num_endpoints) {
2041 struct darwin_interface *cInterface;
2042 UInt32 supportsStreams;
2046 /* find the mimimum number of supported streams on the endpoint list */
2047 for (i = 0 ; i < num_endpoints ; ++i) {
2048 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) {
2052 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2053 if (num_streams > supportsStreams)
2054 num_streams = supportsStreams;
2057 /* it is an error if any endpoint in endpoints does not support streams */
2058 if (0 == num_streams)
2059 return LIBUSB_ERROR_INVALID_PARAM;
2061 /* create the streams */
2062 for (i = 0 ; i < num_endpoints ; ++i) {
2063 (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
2065 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, num_streams);
2066 if (kIOReturnSuccess != rc)
2067 return darwin_to_libusb(rc);
2070 assert(num_streams <= INT_MAX);
2071 return (int)num_streams;
2074 static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) {
2075 struct darwin_interface *cInterface;
2076 UInt32 supportsStreams;
2080 for (int i = 0 ; i < num_endpoints ; ++i) {
2081 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface)))
2084 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2085 if (0 == supportsStreams)
2086 return LIBUSB_ERROR_INVALID_PARAM;
2088 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, 0);
2089 if (kIOReturnSuccess != rc)
2090 return darwin_to_libusb(rc);
2093 return LIBUSB_SUCCESS;
2097 const struct usbi_os_backend usbi_backend = {
2100 .init = darwin_init,
2101 .exit = darwin_exit,
2102 .get_device_list = NULL, /* not needed */
2103 .get_device_descriptor = darwin_get_device_descriptor,
2104 .get_active_config_descriptor = darwin_get_active_config_descriptor,
2105 .get_config_descriptor = darwin_get_config_descriptor,
2106 .hotplug_poll = darwin_hotplug_poll,
2108 .open = darwin_open,
2109 .close = darwin_close,
2110 .get_configuration = darwin_get_configuration,
2111 .set_configuration = darwin_set_configuration,
2112 .claim_interface = darwin_claim_interface,
2113 .release_interface = darwin_release_interface,
2115 .set_interface_altsetting = darwin_set_interface_altsetting,
2116 .clear_halt = darwin_clear_halt,
2117 .reset_device = darwin_reset_device,
2119 #if InterfaceVersion >= 550
2120 .alloc_streams = darwin_alloc_streams,
2121 .free_streams = darwin_free_streams,
2124 .kernel_driver_active = darwin_kernel_driver_active,
2125 .detach_kernel_driver = darwin_detach_kernel_driver,
2126 .attach_kernel_driver = darwin_attach_kernel_driver,
2128 .destroy_device = darwin_destroy_device,
2130 .submit_transfer = darwin_submit_transfer,
2131 .cancel_transfer = darwin_cancel_transfer,
2132 .clear_transfer_priv = darwin_clear_transfer_priv,
2134 .handle_transfer_completion = darwin_handle_transfer_completion,
2136 .clock_gettime = darwin_clock_gettime,
2138 .device_priv_size = sizeof(struct darwin_device_priv),
2139 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
2140 .transfer_priv_size = sizeof(struct darwin_transfer_priv),