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
29 #include <sys/types.h>
32 #include <sys/sysctl.h>
34 #include <mach/clock.h>
35 #include <mach/clock_types.h>
36 #include <mach/mach_host.h>
37 #include <mach/mach_port.h>
39 /* Suppress warnings about the use of the deprecated objc_registerThreadWithCollector
40 * function. Its use is also conditionalized to only older deployment targets. */
41 #define OBJC_SILENCE_GC_DEPRECATIONS 1
43 #include <AvailabilityMacros.h>
44 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
45 #include <objc/objc-auto.h>
48 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 101200
49 /* Apple deprecated the darwin atomics in 10.12 in favor of C11 atomics */
50 #include <stdatomic.h>
51 #define libusb_darwin_atomic_fetch_add(x, y) atomic_fetch_add(x, y)
53 _Atomic int32_t initCount = ATOMIC_VAR_INIT(0);
55 /* use darwin atomics if the target is older than 10.12 */
56 #include <libkern/OSAtomic.h>
58 /* OSAtomicAdd32Barrier returns the new value */
59 #define libusb_darwin_atomic_fetch_add(x, y) (OSAtomicAdd32Barrier(y, x) - y)
61 static volatile int32_t initCount = 0;
65 /* On 10.12 and later, use newly available clock_*() functions */
66 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 101200
67 #define OSX_USE_CLOCK_GETTIME 1
69 #define OSX_USE_CLOCK_GETTIME 0
72 #include "darwin_usb.h"
74 /* async event thread */
75 static pthread_mutex_t libusb_darwin_at_mutex = PTHREAD_MUTEX_INITIALIZER;
76 static pthread_cond_t libusb_darwin_at_cond = PTHREAD_COND_INITIALIZER;
78 #if !OSX_USE_CLOCK_GETTIME
79 static clock_serv_t clock_realtime;
80 static clock_serv_t clock_monotonic;
83 static CFRunLoopRef libusb_darwin_acfl = NULL; /* event cf loop */
84 static CFRunLoopSourceRef libusb_darwin_acfls = NULL; /* shutdown signal for event cf loop */
86 static usbi_mutex_t darwin_cached_devices_lock = PTHREAD_MUTEX_INITIALIZER;
87 static struct list_head darwin_cached_devices = {&darwin_cached_devices, &darwin_cached_devices};
88 static const char *darwin_device_class = kIOUSBDeviceClassName;
90 #define DARWIN_CACHED_DEVICE(a) ((struct darwin_cached_device *) (((struct darwin_device_priv *)((a)->os_priv))->dev))
92 /* async event thread */
93 static pthread_t libusb_darwin_at;
95 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
96 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
97 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
98 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
99 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
101 static enum libusb_error darwin_scan_devices(struct libusb_context *ctx);
102 static enum libusb_error process_new_device (struct libusb_context *ctx, io_service_t service);
104 #if defined(ENABLE_LOGGING)
105 static const char *darwin_error_str (IOReturn result) {
106 static char string_buffer[50];
108 case kIOReturnSuccess:
110 case kIOReturnNotOpen:
111 return "device not opened for exclusive access";
112 case kIOReturnNoDevice:
113 return "no connection to an IOService";
114 case kIOUSBNoAsyncPortErr:
115 return "no async port has been opened for interface";
116 case kIOReturnExclusiveAccess:
117 return "another process has device opened for exclusive access";
118 case kIOUSBPipeStalled:
119 return "pipe is stalled";
121 return "could not establish a connection to the Darwin kernel";
122 case kIOUSBTransactionTimeout:
123 return "transaction timed out";
124 case kIOReturnBadArgument:
125 return "invalid argument";
126 case kIOReturnAborted:
127 return "transaction aborted";
128 case kIOReturnNotResponding:
129 return "device not responding";
130 case kIOReturnOverrun:
131 return "data overrun";
132 case kIOReturnCannotWire:
133 return "physical memory can not be wired down";
134 case kIOReturnNoResources:
135 return "out of resources";
136 case kIOUSBHighSpeedSplitError:
137 return "high speed split error";
139 snprintf(string_buffer, sizeof(string_buffer), "unknown error (0x%x)", result);
140 return string_buffer;
145 static enum libusb_error darwin_to_libusb (IOReturn result) {
147 case kIOReturnUnderrun:
148 case kIOReturnSuccess:
149 return LIBUSB_SUCCESS;
150 case kIOReturnNotOpen:
151 case kIOReturnNoDevice:
152 return LIBUSB_ERROR_NO_DEVICE;
153 case kIOReturnExclusiveAccess:
154 return LIBUSB_ERROR_ACCESS;
155 case kIOUSBPipeStalled:
156 return LIBUSB_ERROR_PIPE;
157 case kIOReturnBadArgument:
158 return LIBUSB_ERROR_INVALID_PARAM;
159 case kIOUSBTransactionTimeout:
160 return LIBUSB_ERROR_TIMEOUT;
161 case kIOReturnNotResponding:
162 case kIOReturnAborted:
164 case kIOUSBNoAsyncPortErr:
166 return LIBUSB_ERROR_OTHER;
170 /* this function must be called with the darwin_cached_devices_lock held */
171 static void darwin_deref_cached_device(struct darwin_cached_device *cached_dev) {
172 cached_dev->refcount--;
173 /* free the device and remove it from the cache */
174 if (0 == cached_dev->refcount) {
175 list_del(&cached_dev->list);
177 (*(cached_dev->device))->Release(cached_dev->device);
182 static void darwin_ref_cached_device(struct darwin_cached_device *cached_dev) {
183 cached_dev->refcount++;
186 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) {
187 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
189 /* current interface */
190 struct darwin_interface *cInterface;
194 usbi_dbg ("converting ep address 0x%02x to pipeRef and interface", ep);
196 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
197 cInterface = &priv->interfaces[iface];
199 if (dev_handle->claimed_interfaces & (1 << iface)) {
200 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
201 if (cInterface->endpoint_addrs[i] == ep) {
208 *interface_out = cInterface;
210 usbi_dbg ("pipe %d on interface %d matches", *pipep, iface);
211 return LIBUSB_SUCCESS;
217 /* No pipe found with the correct endpoint address */
218 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
220 return LIBUSB_ERROR_NOT_FOUND;
223 static IOReturn usb_setup_device_iterator (io_iterator_t *deviceIterator, UInt32 location) {
224 CFMutableDictionaryRef matchingDict = IOServiceMatching(darwin_device_class);
227 return kIOReturnError;
230 CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
231 &kCFTypeDictionaryKeyCallBacks,
232 &kCFTypeDictionaryValueCallBacks);
234 /* there are no unsigned CFNumber types so treat the value as signed. the OS seems to do this
235 internally (CFNumberType of locationID is kCFNumberSInt32Type) */
236 CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberSInt32Type, &location);
238 if (propertyMatchDict && locationCF) {
239 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
240 CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
242 /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
244 /* release our references as per the Create Rule */
245 if (propertyMatchDict)
246 CFRelease (propertyMatchDict);
248 CFRelease (locationCF);
251 return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator);
254 /* Returns 1 on success, 0 on failure. */
255 static bool get_ioregistry_value_number (io_service_t service, CFStringRef property, CFNumberType type, void *p) {
256 CFTypeRef cfNumber = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
260 if (CFGetTypeID(cfNumber) == CFNumberGetTypeID()) {
261 success = CFNumberGetValue(cfNumber, type, p);
264 CFRelease (cfNumber);
267 return (success != 0);
270 /* Returns 1 on success, 0 on failure. */
271 static bool get_ioregistry_value_data (io_service_t service, CFStringRef property, ssize_t size, void *p) {
272 CFTypeRef cfData = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
273 bool success = false;
276 if (CFGetTypeID (cfData) == CFDataGetTypeID ()) {
277 CFIndex length = CFDataGetLength (cfData);
282 CFDataGetBytes (cfData, CFRangeMake(0, size), p);
292 static usb_device_t **darwin_device_from_service (io_service_t service)
294 io_cf_plugin_ref_t *plugInInterface = NULL;
295 usb_device_t **device;
299 kresult = IOCreatePlugInInterfaceForService(service, kIOUSBDeviceUserClientTypeID,
300 kIOCFPlugInInterfaceID, &plugInInterface,
303 if (kIOReturnSuccess != kresult || !plugInInterface) {
304 usbi_dbg ("could not set up plugin for service: %s", darwin_error_str (kresult));
308 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
310 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
311 (*plugInInterface)->Release (plugInInterface);
316 static void darwin_devices_attached (void *ptr, io_iterator_t add_devices) {
318 struct libusb_context *ctx;
319 io_service_t service;
321 usbi_mutex_lock(&active_contexts_lock);
323 while ((service = IOIteratorNext(add_devices))) {
324 /* add this device to each active context's device list */
325 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
326 process_new_device (ctx, service);
329 IOObjectRelease(service);
332 usbi_mutex_unlock(&active_contexts_lock);
335 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
337 struct libusb_device *dev = NULL;
338 struct libusb_context *ctx;
339 struct darwin_cached_device *old_device;
345 usbi_mutex_lock(&active_contexts_lock);
347 while ((device = IOIteratorNext (rem_devices)) != 0) {
348 /* get the location from the i/o registry */
349 ret = get_ioregistry_value_number (device, CFSTR("sessionID"), kCFNumberSInt64Type, &session);
350 IOObjectRelease (device);
354 /* we need to match darwin_ref_cached_device call made in darwin_get_cached_device function
355 otherwise no cached device will ever get freed */
356 usbi_mutex_lock(&darwin_cached_devices_lock);
357 list_for_each_entry(old_device, &darwin_cached_devices, list, struct darwin_cached_device) {
358 if (old_device->session == session) {
359 darwin_deref_cached_device (old_device);
363 usbi_mutex_unlock(&darwin_cached_devices_lock);
365 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
366 usbi_dbg ("notifying context %p of device disconnect", ctx);
368 dev = usbi_get_device_by_session_id(ctx, (unsigned long) session);
370 /* signal the core that this device has been disconnected. the core will tear down this device
371 when the reference count reaches 0 */
372 usbi_disconnect_device(dev);
373 libusb_unref_device(dev);
378 usbi_mutex_unlock(&active_contexts_lock);
381 static void darwin_hotplug_poll (void)
383 /* not sure if 1 ms will be too long/short but it should work ok */
384 mach_timespec_t timeout = {.tv_sec = 0, .tv_nsec = 1000000ul};
386 /* since a kernel thread may nodify the IOInterators used for
387 * hotplug notidication we can't just clear the iterators.
388 * instead just wait until all IOService providers are quiet */
389 (void) IOKitWaitQuiet (kIOMasterPortDefault, &timeout);
392 static void darwin_clear_iterator (io_iterator_t iter) {
395 while ((device = IOIteratorNext (iter)) != 0)
396 IOObjectRelease (device);
399 static void *darwin_event_thread_main (void *arg0) {
401 struct libusb_context *ctx = (struct libusb_context *)arg0;
402 CFRunLoopRef runloop;
404 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
405 /* Set this thread's name, so it can be seen in the debugger
406 and crash reports. */
407 pthread_setname_np ("org.libusb.device-hotplug");
410 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
411 /* Tell the Objective-C garbage collector about this thread.
412 This is required because, unlike NSThreads, pthreads are
413 not automatically registered. Although we don't use
414 Objective-C, we use CoreFoundation, which does.
415 Garbage collection support was entirely removed in 10.12,
416 so don't bother there. */
417 objc_registerThreadWithCollector();
420 /* hotplug (device arrival/removal) sources */
421 CFRunLoopSourceContext libusb_shutdown_cfsourcectx;
422 CFRunLoopSourceRef libusb_notification_cfsource;
423 io_notification_port_t libusb_notification_port;
424 io_iterator_t libusb_rem_device_iterator;
425 io_iterator_t libusb_add_device_iterator;
427 usbi_dbg ("creating hotplug event source");
429 runloop = CFRunLoopGetCurrent ();
432 /* add the shutdown cfsource to the run loop */
433 memset(&libusb_shutdown_cfsourcectx, 0, sizeof(libusb_shutdown_cfsourcectx));
434 libusb_shutdown_cfsourcectx.info = runloop;
435 libusb_shutdown_cfsourcectx.perform = (void (*)(void *))CFRunLoopStop;
436 libusb_darwin_acfls = CFRunLoopSourceCreate(NULL, 0, &libusb_shutdown_cfsourcectx);
437 CFRunLoopAddSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
439 /* add the notification port to the run loop */
440 libusb_notification_port = IONotificationPortCreate (kIOMasterPortDefault);
441 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
442 CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
444 /* create notifications for removed devices */
445 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
446 IOServiceMatching(darwin_device_class),
447 darwin_devices_detached,
448 ctx, &libusb_rem_device_iterator);
450 if (kresult != kIOReturnSuccess) {
451 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
456 /* create notifications for attached devices */
457 kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
458 IOServiceMatching(darwin_device_class),
459 darwin_devices_attached,
460 ctx, &libusb_add_device_iterator);
462 if (kresult != kIOReturnSuccess) {
463 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
469 darwin_clear_iterator (libusb_rem_device_iterator);
470 darwin_clear_iterator (libusb_add_device_iterator);
472 usbi_dbg ("darwin event thread ready to receive events");
474 /* signal the main thread that the hotplug runloop has been created. */
475 pthread_mutex_lock (&libusb_darwin_at_mutex);
476 libusb_darwin_acfl = runloop;
477 pthread_cond_signal (&libusb_darwin_at_cond);
478 pthread_mutex_unlock (&libusb_darwin_at_mutex);
480 /* run the runloop */
483 usbi_dbg ("darwin event thread exiting");
485 /* remove the notification cfsource */
486 CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
488 /* remove the shutdown cfsource */
489 CFRunLoopRemoveSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
491 /* delete notification port */
492 IONotificationPortDestroy (libusb_notification_port);
494 /* delete iterators */
495 IOObjectRelease (libusb_rem_device_iterator);
496 IOObjectRelease (libusb_add_device_iterator);
498 CFRelease (libusb_darwin_acfls);
501 libusb_darwin_acfls = NULL;
502 libusb_darwin_acfl = NULL;
507 /* cleanup function to destroy cached devices */
508 static void __attribute__((destructor)) _darwin_finalize(void) {
509 struct darwin_cached_device *dev, *next;
511 usbi_mutex_lock(&darwin_cached_devices_lock);
512 list_for_each_entry_safe(dev, next, &darwin_cached_devices, list, struct darwin_cached_device) {
513 darwin_deref_cached_device(dev);
515 usbi_mutex_unlock(&darwin_cached_devices_lock);
518 static int darwin_init(struct libusb_context *ctx) {
521 rc = darwin_scan_devices (ctx);
522 if (LIBUSB_SUCCESS != rc) {
526 if (libusb_darwin_atomic_fetch_add (&initCount, 1) == 0) {
527 #if !OSX_USE_CLOCK_GETTIME
528 /* create the clocks that will be used if clock_gettime() is not available */
529 host_name_port_t host_self;
531 host_self = mach_host_self();
532 host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
533 host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
534 mach_port_deallocate(mach_task_self(), host_self);
537 pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, ctx);
539 pthread_mutex_lock (&libusb_darwin_at_mutex);
540 while (!libusb_darwin_acfl)
541 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
542 pthread_mutex_unlock (&libusb_darwin_at_mutex);
548 static void darwin_exit (struct libusb_context *ctx) {
550 if (libusb_darwin_atomic_fetch_add (&initCount, -1) == 1) {
551 #if !OSX_USE_CLOCK_GETTIME
552 mach_port_deallocate(mach_task_self(), clock_realtime);
553 mach_port_deallocate(mach_task_self(), clock_monotonic);
556 /* stop the event runloop and wait for the thread to terminate. */
557 CFRunLoopSourceSignal(libusb_darwin_acfls);
558 CFRunLoopWakeUp (libusb_darwin_acfl);
559 pthread_join (libusb_darwin_at, NULL);
563 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
564 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
566 /* return cached copy */
567 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
571 return LIBUSB_SUCCESS;
574 static int get_configuration_index (struct libusb_device *dev, int config_value) {
575 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
577 IOUSBConfigurationDescriptorPtr desc;
580 /* is there a simpler way to determine the index? */
581 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
582 if (kresult != kIOReturnSuccess)
583 return darwin_to_libusb (kresult);
585 for (i = 0 ; i < numConfig ; i++) {
586 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
588 if (desc->bConfigurationValue == config_value)
592 /* configuration not found */
593 return LIBUSB_ERROR_NOT_FOUND;
596 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
597 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
600 if (0 == priv->active_config)
601 return LIBUSB_ERROR_NOT_FOUND;
603 config_index = get_configuration_index (dev, priv->active_config);
604 if (config_index < 0)
607 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
610 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
611 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
612 IOUSBConfigurationDescriptorPtr desc;
616 if (!priv || !priv->device)
617 return LIBUSB_ERROR_OTHER;
619 kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
620 if (kresult == kIOReturnSuccess) {
621 /* copy descriptor */
622 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
623 len = libusb_le16_to_cpu(desc->wTotalLength);
625 memmove (buffer, desc, len);
627 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
631 ret = darwin_to_libusb (kresult);
632 if (ret != LIBUSB_SUCCESS)
638 /* check whether the os has configured the device */
639 static enum libusb_error darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) {
640 usb_device_t **darwin_device = dev->device;
642 IOUSBConfigurationDescriptorPtr configDesc;
643 IOUSBFindInterfaceRequest request;
645 io_iterator_t interface_iterator;
646 io_service_t firstInterface;
648 if (dev->dev_descriptor.bNumConfigurations < 1) {
649 usbi_err (ctx, "device has no configurations");
650 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
653 /* checking the configuration of a root hub simulation takes ~1 s in 10.11. the device is
655 if (0x05ac == dev->dev_descriptor.idVendor && 0x8005 == dev->dev_descriptor.idProduct) {
656 usbi_dbg ("ignoring configuration on root hub simulation");
657 dev->active_config = 0;
658 return LIBUSB_SUCCESS;
661 /* find the first configuration */
662 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
663 dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
665 /* check if the device is already configured. there is probably a better way than iterating over the
666 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
667 might lock up on the device request) */
669 /* Setup the Interface Request */
670 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
671 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
672 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
673 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
675 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
676 if (kresult != kIOReturnSuccess)
677 return darwin_to_libusb (kresult);
680 firstInterface = IOIteratorNext(interface_iterator);
682 /* done with the interface iterator */
683 IOObjectRelease(interface_iterator);
685 if (firstInterface) {
686 IOObjectRelease (firstInterface);
688 /* device is configured */
689 if (dev->dev_descriptor.bNumConfigurations == 1)
690 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
691 dev->active_config = dev->first_config;
693 /* devices with more than one configuration should work with GetConfiguration */
694 (*darwin_device)->GetConfiguration (darwin_device, &dev->active_config);
697 dev->active_config = 0;
699 usbi_dbg ("active config: %u, first config: %u", dev->active_config, dev->first_config);
701 return LIBUSB_SUCCESS;
704 static IOReturn darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
705 IOUSBDevRequestTO req;
707 memset (buffer, 0, buffer_size);
709 /* Set up request for descriptor/ */
710 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
711 req.bRequest = kUSBRqGetDescriptor;
712 req.wValue = desc << 8;
713 req.wIndex = desc_index;
714 req.wLength = buffer_size;
716 req.noDataTimeout = 20;
717 req.completionTimeout = 100;
719 return (*device)->DeviceRequestTO (device, &req);
722 static enum libusb_error darwin_cache_device_descriptor (struct libusb_context *ctx, struct darwin_cached_device *dev) {
723 usb_device_t **device = dev->device;
724 int retries = 1, delay = 30000;
725 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
727 IOReturn ret = 0, ret2;
729 UInt16 idProduct, idVendor;
731 dev->can_enumerate = 0;
733 (*device)->GetDeviceClass (device, &bDeviceClass);
734 (*device)->GetDeviceProduct (device, &idProduct);
735 (*device)->GetDeviceVendor (device, &idVendor);
737 /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
738 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
739 * to follow the spec as closely as possible, try opening the device */
740 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
743 /**** retrieve device descriptor ****/
744 ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &dev->dev_descriptor, sizeof(dev->dev_descriptor));
746 if (kIOReturnOverrun == ret && kUSBDeviceDesc == dev->dev_descriptor.bDescriptorType)
747 /* received an overrun error but we still received a device descriptor */
748 ret = kIOReturnSuccess;
750 if (kIOUSBVendorIDAppleComputer == idVendor) {
751 /* NTH: don't bother retrying or unsuspending Apple devices */
755 if (kIOReturnSuccess == ret && (0 == dev->dev_descriptor.bNumConfigurations ||
756 0 == dev->dev_descriptor.bcdUSB)) {
757 /* work around for incorrectly configured devices */
758 if (try_reconfigure && is_open) {
759 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
761 /* set the first configuration */
762 (*device)->SetConfiguration(device, 1);
764 /* don't try to reconfigure again */
768 ret = kIOUSBPipeStalled;
771 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
772 /* device may be suspended. unsuspend it and try again */
773 #if DeviceVersion >= 320
776 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
777 (void)(*device)->GetUSBDeviceInformation (device, &info);
779 /* note that the device was suspended */
780 if (info & (1 << kUSBInformationDeviceIsSuspendedBit) || 0 == info)
785 /* try to unsuspend the device */
786 ret2 = (*device)->USBDeviceSuspend (device, 0);
787 if (kIOReturnSuccess != ret2) {
788 /* prevent log spew from poorly behaving devices. this indicates the
789 os actually had trouble communicating with the device */
790 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
798 if (kIOReturnSuccess != ret) {
799 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
800 /* sleep for a little while before trying again */
801 nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000UL}, NULL);
803 } while (kIOReturnSuccess != ret && retries--);
806 /* resuspend the device */
807 (void)(*device)->USBDeviceSuspend (device, 1);
810 (void) (*device)->USBDeviceClose (device);
812 if (ret != kIOReturnSuccess) {
813 /* a debug message was already printed out for this error */
814 if (LIBUSB_CLASS_HUB == bDeviceClass)
815 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
816 idVendor, idProduct, darwin_error_str (ret), ret);
818 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
819 idVendor, idProduct, darwin_error_str (ret), ret);
820 return darwin_to_libusb (ret);
823 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
824 if (libusb_le16_to_cpu (dev->dev_descriptor.idProduct) != idProduct) {
825 /* not a valid device */
826 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
827 idProduct, libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
828 return LIBUSB_ERROR_NO_DEVICE;
831 usbi_dbg ("cached device descriptor:");
832 usbi_dbg (" bDescriptorType: 0x%02x", dev->dev_descriptor.bDescriptorType);
833 usbi_dbg (" bcdUSB: 0x%04x", dev->dev_descriptor.bcdUSB);
834 usbi_dbg (" bDeviceClass: 0x%02x", dev->dev_descriptor.bDeviceClass);
835 usbi_dbg (" bDeviceSubClass: 0x%02x", dev->dev_descriptor.bDeviceSubClass);
836 usbi_dbg (" bDeviceProtocol: 0x%02x", dev->dev_descriptor.bDeviceProtocol);
837 usbi_dbg (" bMaxPacketSize0: 0x%02x", dev->dev_descriptor.bMaxPacketSize0);
838 usbi_dbg (" idVendor: 0x%04x", dev->dev_descriptor.idVendor);
839 usbi_dbg (" idProduct: 0x%04x", dev->dev_descriptor.idProduct);
840 usbi_dbg (" bcdDevice: 0x%04x", dev->dev_descriptor.bcdDevice);
841 usbi_dbg (" iManufacturer: 0x%02x", dev->dev_descriptor.iManufacturer);
842 usbi_dbg (" iProduct: 0x%02x", dev->dev_descriptor.iProduct);
843 usbi_dbg (" iSerialNumber: 0x%02x", dev->dev_descriptor.iSerialNumber);
844 usbi_dbg (" bNumConfigurations: 0x%02x", dev->dev_descriptor.bNumConfigurations);
846 dev->can_enumerate = 1;
848 return LIBUSB_SUCCESS;
851 /* Returns 1 on success, 0 on failure. */
852 static bool get_device_port (io_service_t service, UInt8 *port) {
857 if (get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, port)) {
861 kresult = IORegistryEntryGetParentEntry (service, kIOServicePlane, &parent);
862 if (kIOReturnSuccess == kresult) {
863 ret = get_ioregistry_value_data (parent, CFSTR("port"), 1, port);
864 IOObjectRelease (parent);
870 /* Returns 1 on success, 0 on failure. */
871 static bool get_device_parent_sessionID(io_service_t service, UInt64 *parent_sessionID) {
875 /* Walk up the tree in the IOService plane until we find a parent that has a sessionID */
877 while((kresult = IORegistryEntryGetParentEntry (parent, kIOUSBPlane, &parent)) == kIOReturnSuccess) {
878 if (get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, parent_sessionID)) {
884 /* We ran out of parents */
888 static enum libusb_error darwin_get_cached_device(struct libusb_context *ctx, io_service_t service,
889 struct darwin_cached_device **cached_out) {
890 struct darwin_cached_device *new_device;
891 UInt64 sessionID = 0, parent_sessionID = 0;
892 enum libusb_error ret = LIBUSB_SUCCESS;
893 usb_device_t **device;
896 /* get some info from the io registry */
897 (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
898 if (!get_device_port (service, &port)) {
899 usbi_dbg("could not get connected port number");
902 usbi_dbg("finding cached device for sessionID 0x%" PRIx64, sessionID);
904 if (get_device_parent_sessionID(service, &parent_sessionID)) {
905 usbi_dbg("parent sessionID: 0x%" PRIx64, parent_sessionID);
908 usbi_mutex_lock(&darwin_cached_devices_lock);
912 list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) {
913 usbi_dbg("matching sessionID 0x%" PRIx64 " against cached device with sessionID 0x%" PRIx64, sessionID, new_device->session);
914 if (new_device->session == sessionID) {
915 usbi_dbg("using cached device for device");
916 *cached_out = new_device;
924 usbi_dbg("caching new device with sessionID 0x%" PRIx64, sessionID);
926 device = darwin_device_from_service (service);
928 ret = LIBUSB_ERROR_NO_DEVICE;
932 new_device = calloc (1, sizeof (*new_device));
934 ret = LIBUSB_ERROR_NO_MEM;
938 /* add this device to the cached device list */
939 list_add(&new_device->list, &darwin_cached_devices);
941 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
943 /* keep a reference to this device */
944 darwin_ref_cached_device(new_device);
946 new_device->device = device;
947 new_device->session = sessionID;
948 (*device)->GetLocationID (device, &new_device->location);
949 new_device->port = port;
950 new_device->parent_session = parent_sessionID;
952 /* cache the device descriptor */
953 ret = darwin_cache_device_descriptor(ctx, new_device);
957 if (new_device->can_enumerate) {
958 snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address,
959 new_device->dev_descriptor.idVendor, new_device->dev_descriptor.idProduct,
960 new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass);
964 usbi_mutex_unlock(&darwin_cached_devices_lock);
966 /* keep track of devices regardless of if we successfully enumerate them to
967 prevent them from being enumerated multiple times */
969 *cached_out = new_device;
974 static enum libusb_error process_new_device (struct libusb_context *ctx, io_service_t service) {
975 struct darwin_device_priv *priv;
976 struct libusb_device *dev = NULL;
977 struct darwin_cached_device *cached_device;
979 enum libusb_error ret = LIBUSB_SUCCESS;
982 ret = darwin_get_cached_device (ctx, service, &cached_device);
984 if (ret < 0 || !cached_device->can_enumerate) {
988 /* check current active configuration (and cache the first configuration value--
989 which may be used by claim_interface) */
990 ret = darwin_check_configuration (ctx, cached_device);
994 usbi_dbg ("allocating new device in context %p for with session 0x%" PRIx64,
995 ctx, cached_device->session);
997 dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
999 return LIBUSB_ERROR_NO_MEM;
1002 priv = (struct darwin_device_priv *)dev->os_priv;
1004 priv->dev = cached_device;
1005 darwin_ref_cached_device (priv->dev);
1007 if (cached_device->parent_session > 0) {
1008 dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session);
1010 dev->parent_dev = NULL;
1012 dev->port_number = cached_device->port;
1013 dev->bus_number = cached_device->location >> 24;
1014 dev->device_address = cached_device->address;
1016 (*(priv->dev->device))->GetDeviceSpeed (priv->dev->device, &devSpeed);
1019 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
1020 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
1021 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
1022 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
1023 case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
1025 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101200
1026 case kUSBDeviceSpeedSuperPlus: dev->speed = LIBUSB_SPEED_SUPER_PLUS; break;
1029 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
1032 ret = usbi_sanitize_device (dev);
1036 usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
1037 dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
1041 usbi_connect_device (dev);
1043 libusb_unref_device (dev);
1049 static enum libusb_error darwin_scan_devices(struct libusb_context *ctx) {
1050 io_iterator_t deviceIterator;
1051 io_service_t service;
1054 kresult = usb_setup_device_iterator (&deviceIterator, 0);
1055 if (kresult != kIOReturnSuccess)
1056 return darwin_to_libusb (kresult);
1058 while ((service = IOIteratorNext (deviceIterator))) {
1059 (void) process_new_device (ctx, service);
1061 IOObjectRelease(service);
1064 IOObjectRelease(deviceIterator);
1066 return LIBUSB_SUCCESS;
1069 static int darwin_open (struct libusb_device_handle *dev_handle) {
1070 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1071 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1074 if (0 == dpriv->open_count) {
1075 /* try to open the device */
1076 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
1077 if (kresult != kIOReturnSuccess) {
1078 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
1080 if (kIOReturnExclusiveAccess != kresult) {
1081 return darwin_to_libusb (kresult);
1084 /* it is possible to perform some actions on a device that is not open so do not return an error */
1090 /* create async event source */
1091 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
1092 if (kresult != kIOReturnSuccess) {
1093 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
1095 if (priv->is_open) {
1096 (*(dpriv->device))->USBDeviceClose (dpriv->device);
1101 return darwin_to_libusb (kresult);
1104 CFRetain (libusb_darwin_acfl);
1106 /* add the cfSource to the aync run loop */
1107 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
1110 /* device opened successfully */
1111 dpriv->open_count++;
1113 usbi_dbg ("device open for access");
1118 static void darwin_close (struct libusb_device_handle *dev_handle) {
1119 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1120 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1124 if (dpriv->open_count == 0) {
1125 /* something is probably very wrong if this is the case */
1126 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!");
1130 dpriv->open_count--;
1132 /* make sure all interfaces are released */
1133 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1134 if (dev_handle->claimed_interfaces & (1 << i))
1135 libusb_release_interface (dev_handle, i);
1137 if (0 == dpriv->open_count) {
1138 /* delete the device's async event source */
1139 if (priv->cfSource) {
1140 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
1141 CFRelease (priv->cfSource);
1142 priv->cfSource = NULL;
1143 CFRelease (libusb_darwin_acfl);
1146 if (priv->is_open) {
1147 /* close the device */
1148 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
1149 if (kresult != kIOReturnSuccess) {
1150 /* Log the fact that we had a problem closing the file, however failing a
1151 * close isn't really an error, so return success anyway */
1152 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
1158 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
1159 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1161 *config = (int) dpriv->active_config;
1163 return LIBUSB_SUCCESS;
1166 static enum libusb_error darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
1167 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1171 /* Setting configuration will invalidate the interface, so we need
1172 to reclaim it. First, dispose of existing interfaces, if any. */
1173 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1174 if (dev_handle->claimed_interfaces & (1 << i))
1175 darwin_release_interface (dev_handle, i);
1177 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
1178 if (kresult != kIOReturnSuccess)
1179 return darwin_to_libusb (kresult);
1181 /* Reclaim any interfaces. */
1182 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1183 if (dev_handle->claimed_interfaces & (1 << i))
1184 darwin_claim_interface (dev_handle, i);
1186 dpriv->active_config = config;
1188 return LIBUSB_SUCCESS;
1191 static IOReturn darwin_get_interface (usb_device_t **darwin_device, int ifc, io_service_t *usbInterfacep) {
1192 IOUSBFindInterfaceRequest request;
1194 io_iterator_t interface_iterator;
1195 UInt8 bInterfaceNumber;
1198 *usbInterfacep = IO_OBJECT_NULL;
1200 /* Setup the Interface Request */
1201 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1202 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1203 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1204 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1206 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1207 if (kresult != kIOReturnSuccess)
1210 while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1211 /* find the interface number */
1212 ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
1215 if (ret && bInterfaceNumber == ifc) {
1219 (void) IOObjectRelease (*usbInterfacep);
1222 /* done with the interface iterator */
1223 IOObjectRelease(interface_iterator);
1225 return kIOReturnSuccess;
1228 static enum libusb_error get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
1229 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1231 /* current interface */
1232 struct darwin_interface *cInterface = &priv->interfaces[iface];
1236 UInt8 numep, direction, number;
1237 UInt8 dont_care1, dont_care3;
1241 usbi_dbg ("building table of endpoints.");
1243 /* retrieve the total number of endpoints on this interface */
1244 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1245 if (kresult != kIOReturnSuccess) {
1246 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1247 return darwin_to_libusb (kresult);
1250 /* iterate through pipe references */
1251 for (int i = 1 ; i <= numep ; i++) {
1252 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1253 &dont_care2, &dont_care3);
1255 if (kresult != kIOReturnSuccess) {
1256 /* probably a buggy device. try to get the endpoint address from the descriptors */
1257 struct libusb_config_descriptor *config;
1258 const struct libusb_endpoint_descriptor *endpoint_desc;
1261 kresult = (*(cInterface->interface))->GetAlternateSetting (cInterface->interface, &alt_setting);
1262 if (kresult != kIOReturnSuccess) {
1263 usbi_err (HANDLE_CTX (dev_handle), "can't get alternate setting for interface");
1264 return darwin_to_libusb (kresult);
1267 rc = libusb_get_active_config_descriptor (dev_handle->dev, &config);
1268 if (LIBUSB_SUCCESS != rc) {
1272 endpoint_desc = config->interface[iface].altsetting[alt_setting].endpoint + i - 1;
1274 cInterface->endpoint_addrs[i - 1] = endpoint_desc->bEndpointAddress;
1276 cInterface->endpoint_addrs[i - 1] = (((kUSBIn == direction) << kUSBRqDirnShift) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1279 usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, cInterface->endpoint_addrs[i - 1] >> kUSBRqDirnShift,
1280 cInterface->endpoint_addrs[i - 1] & LIBUSB_ENDPOINT_ADDRESS_MASK);
1283 cInterface->num_endpoints = numep;
1285 return LIBUSB_SUCCESS;
1288 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1289 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1290 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1291 io_service_t usbInterface = IO_OBJECT_NULL;
1293 enum libusb_error ret;
1294 IOCFPlugInInterface **plugInInterface = NULL;
1297 /* current interface */
1298 struct darwin_interface *cInterface = &priv->interfaces[iface];
1300 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1301 if (kresult != kIOReturnSuccess)
1302 return darwin_to_libusb (kresult);
1304 /* make sure we have an interface */
1305 if (!usbInterface && dpriv->first_config != 0) {
1306 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1308 /* set the configuration */
1309 ret = darwin_set_configuration (dev_handle, dpriv->first_config);
1310 if (ret != LIBUSB_SUCCESS) {
1311 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1315 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1316 if (kresult != kIOReturnSuccess) {
1317 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1318 return darwin_to_libusb (kresult);
1322 if (!usbInterface) {
1323 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1324 return LIBUSB_ERROR_NOT_FOUND;
1327 /* get an interface to the device's interface */
1328 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1329 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1331 /* ignore release error */
1332 (void)IOObjectRelease (usbInterface);
1334 if (kresult != kIOReturnSuccess) {
1335 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1336 return darwin_to_libusb (kresult);
1339 if (!plugInInterface) {
1340 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1341 return LIBUSB_ERROR_NOT_FOUND;
1344 /* Do the actual claim */
1345 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1346 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1347 (LPVOID)&cInterface->interface);
1348 /* We no longer need the intermediate plug-in */
1349 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1350 (*plugInInterface)->Release (plugInInterface);
1351 if (kresult != kIOReturnSuccess || !cInterface->interface) {
1352 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1353 return darwin_to_libusb (kresult);
1356 /* claim the interface */
1357 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1358 if (kresult != kIOReturnSuccess) {
1359 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1360 return darwin_to_libusb (kresult);
1363 /* update list of endpoints */
1364 ret = get_endpoints (dev_handle, iface);
1366 /* this should not happen */
1367 darwin_release_interface (dev_handle, iface);
1368 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1372 cInterface->cfSource = NULL;
1374 /* create async event source */
1375 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1376 if (kresult != kIOReturnSuccess) {
1377 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1379 /* can't continue without an async event source */
1380 (void)darwin_release_interface (dev_handle, iface);
1382 return darwin_to_libusb (kresult);
1385 /* add the cfSource to the async thread's run loop */
1386 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1388 usbi_dbg ("interface opened");
1390 return LIBUSB_SUCCESS;
1393 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1394 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1397 /* current interface */
1398 struct darwin_interface *cInterface = &priv->interfaces[iface];
1400 /* Check to see if an interface is open */
1401 if (!cInterface->interface)
1402 return LIBUSB_SUCCESS;
1404 /* clean up endpoint data */
1405 cInterface->num_endpoints = 0;
1407 /* delete the interface's async event source */
1408 if (cInterface->cfSource) {
1409 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1410 CFRelease (cInterface->cfSource);
1413 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1414 if (kresult != kIOReturnSuccess)
1415 usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1417 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1418 if (kresult != kIOReturnSuccess)
1419 usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1421 cInterface->interface = (usb_interface_t **) IO_OBJECT_NULL;
1423 return darwin_to_libusb (kresult);
1426 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1427 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1429 enum libusb_error ret;
1431 /* current interface */
1432 struct darwin_interface *cInterface = &priv->interfaces[iface];
1434 if (!cInterface->interface)
1435 return LIBUSB_ERROR_NO_DEVICE;
1437 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1438 if (kresult != kIOReturnSuccess)
1439 darwin_reset_device (dev_handle);
1441 /* update list of endpoints */
1442 ret = get_endpoints (dev_handle, iface);
1444 /* this should not happen */
1445 darwin_release_interface (dev_handle, iface);
1446 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1450 return darwin_to_libusb (kresult);
1453 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1454 /* current interface */
1455 struct darwin_interface *cInterface;
1459 /* determine the interface/endpoint to use */
1460 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, NULL, &cInterface) != 0) {
1461 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1463 return LIBUSB_ERROR_NOT_FOUND;
1466 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1467 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1468 if (kresult != kIOReturnSuccess)
1469 usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1471 return darwin_to_libusb (kresult);
1474 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1475 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1476 IOUSBDeviceDescriptor descriptor;
1477 IOUSBConfigurationDescriptorPtr cached_configuration;
1478 IOUSBConfigurationDescriptor configuration;
1479 bool reenumerate = false;
1483 /* from macOS 10.11 ResetDevice no longer does anything so just use USBDeviceReEnumerate */
1484 kresult = (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
1485 if (kresult != kIOReturnSuccess) {
1486 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceReEnumerate: %s", darwin_error_str (kresult));
1487 return darwin_to_libusb (kresult);
1491 usbi_dbg ("darwin/reset_device: checking if device descriptor changed");
1493 /* ignore return code. if we can't get a descriptor it might be worthwhile re-enumerating anway */
1494 (void) darwin_request_descriptor (dpriv->device, kUSBDeviceDesc, 0, &descriptor, sizeof (descriptor));
1496 /* check if the device descriptor has changed */
1497 if (0 != memcmp (&dpriv->dev_descriptor, &descriptor, sizeof (descriptor))) {
1502 /* check if any configuration descriptor has changed */
1503 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1504 usbi_dbg ("darwin/reset_device: checking if configuration descriptor %d changed", i);
1506 (void) darwin_request_descriptor (dpriv->device, kUSBConfDesc, i, &configuration, sizeof (configuration));
1507 (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1509 if (!cached_configuration || 0 != memcmp (cached_configuration, &configuration, sizeof (configuration))) {
1517 usbi_dbg ("darwin/reset_device: device requires reenumeration");
1518 (void) (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
1519 return LIBUSB_ERROR_NOT_FOUND;
1522 usbi_dbg ("darwin/reset_device: device reset complete");
1524 return LIBUSB_SUCCESS;
1527 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1528 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1529 io_service_t usbInterface;
1533 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1534 if (kresult != kIOReturnSuccess) {
1535 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1537 return darwin_to_libusb (kresult);
1540 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1541 IOObjectRelease (usbInterface);
1553 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1554 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1557 return LIBUSB_ERROR_NOT_SUPPORTED;
1560 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1563 return LIBUSB_ERROR_NOT_SUPPORTED;
1566 static void darwin_destroy_device(struct libusb_device *dev) {
1567 struct darwin_device_priv *dpriv = (struct darwin_device_priv *) dev->os_priv;
1570 /* need to hold the lock in case this is the last reference to the device */
1571 usbi_mutex_lock(&darwin_cached_devices_lock);
1572 darwin_deref_cached_device (dpriv->dev);
1574 usbi_mutex_unlock(&darwin_cached_devices_lock);
1578 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1579 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1582 uint8_t transferType;
1583 /* None of the values below are used in libusbx for bulk transfers */
1584 uint8_t direction, number, interval, pipeRef;
1585 uint16_t maxPacketSize;
1587 struct darwin_interface *cInterface;
1589 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1590 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1592 return LIBUSB_ERROR_NOT_FOUND;
1595 ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1596 &transferType, &maxPacketSize, &interval);
1599 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1600 darwin_error_str(ret), ret);
1601 return darwin_to_libusb (ret);
1604 if (0 != (transfer->length % maxPacketSize)) {
1605 /* do not need a zero packet */
1606 transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1609 /* submit the request */
1610 /* timeouts are unavailable on interrupt endpoints */
1611 if (transferType == kUSBInterrupt) {
1612 if (IS_XFERIN(transfer))
1613 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1614 transfer->length, darwin_async_io_callback, itransfer);
1616 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1617 transfer->length, darwin_async_io_callback, itransfer);
1619 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1621 if (IS_XFERIN(transfer))
1622 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1623 transfer->length, transfer->timeout, transfer->timeout,
1624 darwin_async_io_callback, (void *)itransfer);
1626 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1627 transfer->length, transfer->timeout, transfer->timeout,
1628 darwin_async_io_callback, (void *)itransfer);
1632 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1633 darwin_error_str(ret), ret);
1635 return darwin_to_libusb (ret);
1638 #if InterfaceVersion >= 550
1639 static int submit_stream_transfer(struct usbi_transfer *itransfer) {
1640 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1641 struct darwin_interface *cInterface;
1645 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1646 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1648 return LIBUSB_ERROR_NOT_FOUND;
1651 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1653 if (IS_XFERIN(transfer))
1654 ret = (*(cInterface->interface))->ReadStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1655 transfer->buffer, transfer->length, transfer->timeout,
1656 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1658 ret = (*(cInterface->interface))->WriteStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1659 transfer->buffer, transfer->length, transfer->timeout,
1660 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1663 usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1664 darwin_error_str(ret), ret);
1666 return darwin_to_libusb (ret);
1670 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1671 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1672 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1675 uint8_t direction, number, interval, pipeRef, transferType;
1676 uint16_t maxPacketSize;
1678 AbsoluteTime atTime;
1681 struct darwin_interface *cInterface;
1683 /* construct an array of IOUSBIsocFrames, reuse the old one if the sizes are the same */
1684 if (tpriv->num_iso_packets != transfer->num_iso_packets) {
1685 free(tpriv->isoc_framelist);
1686 tpriv->isoc_framelist = NULL;
1689 if (!tpriv->isoc_framelist) {
1690 tpriv->num_iso_packets = transfer->num_iso_packets;
1691 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1692 if (!tpriv->isoc_framelist)
1693 return LIBUSB_ERROR_NO_MEM;
1696 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1697 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1698 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1700 /* determine the interface/endpoint to use */
1701 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1702 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1704 return LIBUSB_ERROR_NOT_FOUND;
1707 /* determine the properties of this endpoint and the speed of the device */
1708 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1709 &transferType, &maxPacketSize, &interval);
1711 /* Last but not least we need the bus frame number */
1712 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1713 if (kresult != kIOReturnSuccess) {
1714 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1715 free(tpriv->isoc_framelist);
1716 tpriv->isoc_framelist = NULL;
1718 return darwin_to_libusb (kresult);
1721 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1722 &transferType, &maxPacketSize, &interval);
1724 /* schedule for a frame a little in the future */
1727 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1728 frame = cInterface->frames[transfer->endpoint];
1730 /* submit the request */
1731 if (IS_XFERIN(transfer))
1732 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1733 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1736 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1737 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1740 if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
1742 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1));
1744 /* High/super speed */
1745 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1)) / 8;
1747 if (kresult != kIOReturnSuccess) {
1748 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1749 darwin_error_str(kresult));
1750 free (tpriv->isoc_framelist);
1751 tpriv->isoc_framelist = NULL;
1754 return darwin_to_libusb (kresult);
1757 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1758 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1759 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1760 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1761 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1765 memset(&tpriv->req, 0, sizeof(tpriv->req));
1767 /* IOUSBDeviceInterface expects the request in cpu endianness */
1768 tpriv->req.bmRequestType = setup->bmRequestType;
1769 tpriv->req.bRequest = setup->bRequest;
1770 /* these values should be in bus order from libusb_fill_control_setup */
1771 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1772 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1773 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1774 /* data is stored after the libusb control block */
1775 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1776 tpriv->req.completionTimeout = transfer->timeout;
1777 tpriv->req.noDataTimeout = transfer->timeout;
1779 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1781 /* all transfers in libusb-1.0 are async */
1783 if (transfer->endpoint) {
1784 struct darwin_interface *cInterface;
1787 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1788 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1790 return LIBUSB_ERROR_NOT_FOUND;
1793 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1795 /* control request on endpoint 0 */
1796 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1798 if (kresult != kIOReturnSuccess)
1799 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1801 return darwin_to_libusb (kresult);
1804 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1805 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1807 switch (transfer->type) {
1808 case LIBUSB_TRANSFER_TYPE_CONTROL:
1809 return submit_control_transfer(itransfer);
1810 case LIBUSB_TRANSFER_TYPE_BULK:
1811 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1812 return submit_bulk_transfer(itransfer);
1813 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1814 return submit_iso_transfer(itransfer);
1815 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1816 #if InterfaceVersion >= 550
1817 return submit_stream_transfer(itransfer);
1819 usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers");
1820 return LIBUSB_ERROR_NOT_SUPPORTED;
1823 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1824 return LIBUSB_ERROR_INVALID_PARAM;
1828 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1829 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1830 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1833 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
1836 return LIBUSB_ERROR_NO_DEVICE;
1838 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1840 return darwin_to_libusb (kresult);
1843 static int darwin_abort_transfers (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);
1846 struct darwin_interface *cInterface;
1847 uint8_t pipeRef, iface;
1850 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) {
1851 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1853 return LIBUSB_ERROR_NOT_FOUND;
1857 return LIBUSB_ERROR_NO_DEVICE;
1859 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
1861 /* abort transactions */
1862 #if InterfaceVersion >= 550
1863 if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type)
1864 (*(cInterface->interface))->AbortStreamsPipe (cInterface->interface, pipeRef, itransfer->stream_id);
1867 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1869 usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
1871 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1872 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1874 return darwin_to_libusb (kresult);
1877 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1878 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1880 switch (transfer->type) {
1881 case LIBUSB_TRANSFER_TYPE_CONTROL:
1882 return cancel_control_transfer(itransfer);
1883 case LIBUSB_TRANSFER_TYPE_BULK:
1884 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1885 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1886 return darwin_abort_transfers (itransfer);
1888 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1889 return LIBUSB_ERROR_INVALID_PARAM;
1893 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1894 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1895 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1897 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1898 free (tpriv->isoc_framelist);
1899 tpriv->isoc_framelist = NULL;
1903 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1904 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1905 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1906 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1908 usbi_dbg ("an async io operation has completed");
1910 /* if requested write a zero packet */
1911 if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
1912 struct darwin_interface *cInterface;
1915 (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface);
1917 (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
1920 tpriv->result = result;
1921 tpriv->size = (UInt32) (uintptr_t) arg0;
1923 /* signal the core that this transfer is complete */
1924 usbi_signal_transfer_completion(itransfer);
1927 static enum libusb_transfer_status darwin_transfer_status (struct usbi_transfer *itransfer, IOReturn result) {
1928 if (itransfer->timeout_flags & USBI_TRANSFER_TIMED_OUT)
1929 result = kIOUSBTransactionTimeout;
1932 case kIOReturnUnderrun:
1933 case kIOReturnSuccess:
1934 return LIBUSB_TRANSFER_COMPLETED;
1935 case kIOReturnAborted:
1936 return LIBUSB_TRANSFER_CANCELLED;
1937 case kIOUSBPipeStalled:
1938 usbi_dbg ("transfer error: pipe is stalled");
1939 return LIBUSB_TRANSFER_STALL;
1940 case kIOReturnOverrun:
1941 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1942 return LIBUSB_TRANSFER_OVERFLOW;
1943 case kIOUSBTransactionTimeout:
1944 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1945 itransfer->timeout_flags |= USBI_TRANSFER_TIMED_OUT;
1946 return LIBUSB_TRANSFER_TIMED_OUT;
1948 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1949 return LIBUSB_TRANSFER_ERROR;
1953 static int darwin_handle_transfer_completion (struct usbi_transfer *itransfer) {
1954 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1955 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1956 bool isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1957 bool isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1958 bool isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1959 bool isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1962 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1963 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1964 return LIBUSB_ERROR_INVALID_PARAM;
1967 usbi_dbg ("handling %s completion with kernel status %d",
1968 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", tpriv->result);
1970 if (kIOReturnSuccess == tpriv->result || kIOReturnUnderrun == tpriv->result) {
1971 if (isIsoc && tpriv->isoc_framelist) {
1972 /* copy isochronous results back */
1974 for (i = 0; i < transfer->num_iso_packets ; i++) {
1975 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1976 lib_desc->status = darwin_transfer_status (itransfer, tpriv->isoc_framelist[i].frStatus);
1977 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1980 itransfer->transferred += tpriv->size;
1983 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1984 return usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, tpriv->result));
1987 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1988 #if !OSX_USE_CLOCK_GETTIME
1989 mach_timespec_t sys_time;
1990 clock_serv_t clock_ref;
1993 case USBI_CLOCK_REALTIME:
1994 /* CLOCK_REALTIME represents time since the epoch */
1995 clock_ref = clock_realtime;
1997 case USBI_CLOCK_MONOTONIC:
1998 /* use system boot time as reference for the monotonic clock */
1999 clock_ref = clock_monotonic;
2002 return LIBUSB_ERROR_INVALID_PARAM;
2005 clock_get_time (clock_ref, &sys_time);
2007 tp->tv_sec = sys_time.tv_sec;
2008 tp->tv_nsec = sys_time.tv_nsec;
2010 return LIBUSB_SUCCESS;
2013 case USBI_CLOCK_MONOTONIC:
2014 return clock_gettime(CLOCK_MONOTONIC, tp);
2015 case USBI_CLOCK_REALTIME:
2016 return clock_gettime(CLOCK_REALTIME, tp);
2018 return LIBUSB_ERROR_INVALID_PARAM;
2023 #if InterfaceVersion >= 550
2024 static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints,
2025 int num_endpoints) {
2026 struct darwin_interface *cInterface;
2027 UInt32 supportsStreams;
2031 /* find the mimimum number of supported streams on the endpoint list */
2032 for (i = 0 ; i < num_endpoints ; ++i) {
2033 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) {
2037 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2038 if (num_streams > supportsStreams)
2039 num_streams = supportsStreams;
2042 /* it is an error if any endpoint in endpoints does not support streams */
2043 if (0 == num_streams)
2044 return LIBUSB_ERROR_INVALID_PARAM;
2046 /* create the streams */
2047 for (i = 0 ; i < num_endpoints ; ++i) {
2048 (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
2050 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, num_streams);
2051 if (kIOReturnSuccess != rc)
2052 return darwin_to_libusb(rc);
2058 static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) {
2059 struct darwin_interface *cInterface;
2060 UInt32 supportsStreams;
2064 for (int i = 0 ; i < num_endpoints ; ++i) {
2065 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface)))
2068 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2069 if (0 == supportsStreams)
2070 return LIBUSB_ERROR_INVALID_PARAM;
2072 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, 0);
2073 if (kIOReturnSuccess != rc)
2074 return darwin_to_libusb(rc);
2077 return LIBUSB_SUCCESS;
2081 const struct usbi_os_backend usbi_backend = {
2084 .init = darwin_init,
2085 .exit = darwin_exit,
2086 .get_device_list = NULL, /* not needed */
2087 .get_device_descriptor = darwin_get_device_descriptor,
2088 .get_active_config_descriptor = darwin_get_active_config_descriptor,
2089 .get_config_descriptor = darwin_get_config_descriptor,
2090 .hotplug_poll = darwin_hotplug_poll,
2092 .open = darwin_open,
2093 .close = darwin_close,
2094 .get_configuration = darwin_get_configuration,
2095 .set_configuration = darwin_set_configuration,
2096 .claim_interface = darwin_claim_interface,
2097 .release_interface = darwin_release_interface,
2099 .set_interface_altsetting = darwin_set_interface_altsetting,
2100 .clear_halt = darwin_clear_halt,
2101 .reset_device = darwin_reset_device,
2103 #if InterfaceVersion >= 550
2104 .alloc_streams = darwin_alloc_streams,
2105 .free_streams = darwin_free_streams,
2108 .kernel_driver_active = darwin_kernel_driver_active,
2109 .detach_kernel_driver = darwin_detach_kernel_driver,
2110 .attach_kernel_driver = darwin_attach_kernel_driver,
2112 .destroy_device = darwin_destroy_device,
2114 .submit_transfer = darwin_submit_transfer,
2115 .cancel_transfer = darwin_cancel_transfer,
2116 .clear_transfer_priv = darwin_clear_transfer_priv,
2118 .handle_transfer_completion = darwin_handle_transfer_completion,
2120 .clock_gettime = darwin_clock_gettime,
2122 .device_priv_size = sizeof(struct darwin_device_priv),
2123 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
2124 .transfer_priv_size = sizeof(struct darwin_transfer_priv),