1 /* -*- Mode: C; indent-tabs-mode:nil -*- */
3 * darwin backend for libusb 1.0
4 * Copyright © 2008-2017 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 #include <AvailabilityMacros.h>
40 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
41 #include <objc/objc-auto.h>
44 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 101200
45 /* Apple deprecated the darwin atomics in 10.12 in favor of C11 atomics */
46 #include <stdatomic.h>
47 #define libusb_darwin_atomic_fetch_add(x, y) atomic_fetch_add(x, y)
48 #define OSX_USE_CLOCK_GETTIME 1
50 _Atomic int32_t initCount = ATOMIC_VAR_INIT(0);
52 /* use darwin atomics if the target is older than 10.12 */
53 #include <libkern/OSAtomic.h>
55 /* OSAtomicAdd32Barrier returns the new value */
56 #define libusb_darwin_atomic_fetch_add(x, y) (OSAtomicAdd32Barrier(y, x) - y)
58 static volatile int32_t initCount = 0;
60 #define OSX_USE_CLOCK_GETTIME 0
63 #include "darwin_usb.h"
65 /* async event thread */
66 static pthread_mutex_t libusb_darwin_at_mutex = PTHREAD_MUTEX_INITIALIZER;
67 static pthread_cond_t libusb_darwin_at_cond = PTHREAD_COND_INITIALIZER;
69 static pthread_once_t darwin_init_once = PTHREAD_ONCE_INIT;
71 #if !OSX_USE_CLOCK_GETTIME
72 static clock_serv_t clock_realtime;
73 static clock_serv_t clock_monotonic;
76 static CFRunLoopRef libusb_darwin_acfl = NULL; /* event cf loop */
77 static CFRunLoopSourceRef libusb_darwin_acfls = NULL; /* shutdown signal for event cf loop */
79 static usbi_mutex_t darwin_cached_devices_lock = PTHREAD_MUTEX_INITIALIZER;
80 static struct list_head darwin_cached_devices = {&darwin_cached_devices, &darwin_cached_devices};
81 static char *darwin_device_class = kIOUSBDeviceClassName;
83 #define DARWIN_CACHED_DEVICE(a) ((struct darwin_cached_device *) (((struct darwin_device_priv *)((a)->os_priv))->dev))
85 /* async event thread */
86 static pthread_t libusb_darwin_at;
88 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
89 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
90 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
91 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
92 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
94 static int darwin_scan_devices(struct libusb_context *ctx);
95 static int process_new_device (struct libusb_context *ctx, io_service_t service);
97 #if defined(ENABLE_LOGGING)
98 static const char *darwin_error_str (int result) {
99 static char string_buffer[50];
101 case kIOReturnSuccess:
103 case kIOReturnNotOpen:
104 return "device not opened for exclusive access";
105 case kIOReturnNoDevice:
106 return "no connection to an IOService";
107 case kIOUSBNoAsyncPortErr:
108 return "no async port has been opened for interface";
109 case kIOReturnExclusiveAccess:
110 return "another process has device opened for exclusive access";
111 case kIOUSBPipeStalled:
112 return "pipe is stalled";
114 return "could not establish a connection to the Darwin kernel";
115 case kIOUSBTransactionTimeout:
116 return "transaction timed out";
117 case kIOReturnBadArgument:
118 return "invalid argument";
119 case kIOReturnAborted:
120 return "transaction aborted";
121 case kIOReturnNotResponding:
122 return "device not responding";
123 case kIOReturnOverrun:
124 return "data overrun";
125 case kIOReturnCannotWire:
126 return "physical memory can not be wired down";
127 case kIOReturnNoResources:
128 return "out of resources";
129 case kIOUSBHighSpeedSplitError:
130 return "high speed split error";
132 snprintf(string_buffer, sizeof(string_buffer), "unknown error (0x%x)", result);
133 return string_buffer;
138 static int darwin_to_libusb (int result) {
140 case kIOReturnUnderrun:
141 case kIOReturnSuccess:
142 return LIBUSB_SUCCESS;
143 case kIOReturnNotOpen:
144 case kIOReturnNoDevice:
145 return LIBUSB_ERROR_NO_DEVICE;
146 case kIOReturnExclusiveAccess:
147 return LIBUSB_ERROR_ACCESS;
148 case kIOUSBPipeStalled:
149 return LIBUSB_ERROR_PIPE;
150 case kIOReturnBadArgument:
151 return LIBUSB_ERROR_INVALID_PARAM;
152 case kIOUSBTransactionTimeout:
153 return LIBUSB_ERROR_TIMEOUT;
154 case kIOReturnNotResponding:
155 case kIOReturnAborted:
157 case kIOUSBNoAsyncPortErr:
159 return LIBUSB_ERROR_OTHER;
163 /* this function must be called with the darwin_cached_devices_lock held */
164 static void darwin_deref_cached_device(struct darwin_cached_device *cached_dev) {
165 cached_dev->refcount--;
166 /* free the device and remove it from the cache */
167 if (0 == cached_dev->refcount) {
168 list_del(&cached_dev->list);
170 (*(cached_dev->device))->Release(cached_dev->device);
175 static void darwin_ref_cached_device(struct darwin_cached_device *cached_dev) {
176 cached_dev->refcount++;
179 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) {
180 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
182 /* current interface */
183 struct darwin_interface *cInterface;
187 usbi_dbg ("converting ep address 0x%02x to pipeRef and interface", ep);
189 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
190 cInterface = &priv->interfaces[iface];
192 if (dev_handle->claimed_interfaces & (1 << iface)) {
193 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
194 if (cInterface->endpoint_addrs[i] == ep) {
201 *interface_out = cInterface;
203 usbi_dbg ("pipe %d on interface %d matches", *pipep, iface);
210 /* No pipe found with the correct endpoint address */
211 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
213 return LIBUSB_ERROR_NOT_FOUND;
216 static int usb_setup_device_iterator (io_iterator_t *deviceIterator, UInt32 location) {
217 CFMutableDictionaryRef matchingDict = IOServiceMatching(darwin_device_class);
220 return kIOReturnError;
223 CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
224 &kCFTypeDictionaryKeyCallBacks,
225 &kCFTypeDictionaryValueCallBacks);
227 if (propertyMatchDict) {
228 /* there are no unsigned CFNumber types so treat the value as signed. the os seems to do this
229 internally (CFNumberType of locationID is 3) */
230 CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberSInt32Type, &location);
232 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
233 /* release our reference to the CFNumber (CFDictionarySetValue retains it) */
234 CFRelease (locationCF);
236 CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
237 /* release out reference to the CFMutableDictionaryRef (CFDictionarySetValue retains it) */
238 CFRelease (propertyMatchDict);
240 /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
243 return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator);
246 /* Returns 1 on success, 0 on failure. */
247 static int get_ioregistry_value_number (io_service_t service, CFStringRef property, CFNumberType type, void *p) {
248 CFTypeRef cfNumber = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
252 if (CFGetTypeID(cfNumber) == CFNumberGetTypeID()) {
253 ret = CFNumberGetValue(cfNumber, type, p);
256 CFRelease (cfNumber);
262 static int get_ioregistry_value_data (io_service_t service, CFStringRef property, ssize_t size, void *p) {
263 CFTypeRef cfData = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
267 if (CFGetTypeID (cfData) == CFDataGetTypeID ()) {
268 CFIndex length = CFDataGetLength (cfData);
273 CFDataGetBytes (cfData, CFRangeMake(0, size), p);
283 static usb_device_t **darwin_device_from_service (io_service_t service)
285 io_cf_plugin_ref_t *plugInInterface = NULL;
286 usb_device_t **device;
287 kern_return_t result;
290 result = IOCreatePlugInInterfaceForService(service, kIOUSBDeviceUserClientTypeID,
291 kIOCFPlugInInterfaceID, &plugInInterface,
294 if (kIOReturnSuccess != result || !plugInInterface) {
295 usbi_dbg ("could not set up plugin for service: %s", darwin_error_str (result));
299 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
301 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
302 (*plugInInterface)->Release (plugInInterface);
307 static void darwin_devices_attached (void *ptr, io_iterator_t add_devices) {
308 struct libusb_context *ctx;
309 io_service_t service;
311 usbi_mutex_lock(&active_contexts_lock);
313 while ((service = IOIteratorNext(add_devices))) {
314 /* add this device to each active context's device list */
315 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
316 process_new_device (ctx, service);;
319 IOObjectRelease(service);
322 usbi_mutex_unlock(&active_contexts_lock);
325 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
326 struct libusb_device *dev = NULL;
327 struct libusb_context *ctx;
328 struct darwin_cached_device *old_device;
334 usbi_mutex_lock(&active_contexts_lock);
336 while ((device = IOIteratorNext (rem_devices)) != 0) {
337 /* get the location from the i/o registry */
338 ret = get_ioregistry_value_number (device, CFSTR("sessionID"), kCFNumberSInt64Type, &session);
339 IOObjectRelease (device);
343 /* we need to match darwin_ref_cached_device call made in darwin_get_cached_device function
344 otherwise no cached device will ever get freed */
345 usbi_mutex_lock(&darwin_cached_devices_lock);
346 list_for_each_entry(old_device, &darwin_cached_devices, list, struct darwin_cached_device) {
347 if (old_device->session == session) {
348 darwin_deref_cached_device (old_device);
352 usbi_mutex_unlock(&darwin_cached_devices_lock);
354 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
355 usbi_dbg ("notifying context %p of device disconnect", ctx);
357 dev = usbi_get_device_by_session_id(ctx, (unsigned long) session);
359 /* signal the core that this device has been disconnected. the core will tear down this device
360 when the reference count reaches 0 */
361 usbi_disconnect_device(dev);
362 libusb_unref_device(dev);
367 usbi_mutex_unlock(&active_contexts_lock);
370 static void darwin_hotplug_poll (void)
372 /* not sure if 5 seconds will be too long/short but it should work ok */
373 mach_timespec_t timeout = {.tv_sec = 5, .tv_nsec = 0};
375 /* since a kernel thread may nodify the IOInterators used for
376 * hotplug notidication we can't just clear the iterators.
377 * instead just wait until all IOService providers are quiet */
378 (void) IOKitWaitQuiet (kIOMasterPortDefault, &timeout);
381 static void darwin_clear_iterator (io_iterator_t iter) {
384 while ((device = IOIteratorNext (iter)) != 0)
385 IOObjectRelease (device);
388 static void *darwin_event_thread_main (void *arg0) {
390 struct libusb_context *ctx = (struct libusb_context *)arg0;
391 CFRunLoopRef runloop;
393 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
394 /* Set this thread's name, so it can be seen in the debugger
395 and crash reports. */
396 pthread_setname_np ("org.libusb.device-hotplug");
399 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
400 /* Tell the Objective-C garbage collector about this thread.
401 This is required because, unlike NSThreads, pthreads are
402 not automatically registered. Although we don't use
403 Objective-C, we use CoreFoundation, which does.
404 Garbage collection support was entirely removed in 10.12,
405 so don't bother there. */
406 objc_registerThreadWithCollector();
409 /* hotplug (device arrival/removal) sources */
410 CFRunLoopSourceContext libusb_shutdown_cfsourcectx;
411 CFRunLoopSourceRef libusb_notification_cfsource;
412 io_notification_port_t libusb_notification_port;
413 io_iterator_t libusb_rem_device_iterator;
414 io_iterator_t libusb_add_device_iterator;
416 usbi_dbg ("creating hotplug event source");
418 runloop = CFRunLoopGetCurrent ();
421 /* add the shutdown cfsource to the run loop */
422 memset(&libusb_shutdown_cfsourcectx, 0, sizeof(libusb_shutdown_cfsourcectx));
423 libusb_shutdown_cfsourcectx.info = runloop;
424 libusb_shutdown_cfsourcectx.perform = (void (*)(void *))CFRunLoopStop;
425 libusb_darwin_acfls = CFRunLoopSourceCreate(NULL, 0, &libusb_shutdown_cfsourcectx);
426 CFRunLoopAddSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
428 /* add the notification port to the run loop */
429 libusb_notification_port = IONotificationPortCreate (kIOMasterPortDefault);
430 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
431 CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
433 /* create notifications for removed devices */
434 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
435 IOServiceMatching(darwin_device_class),
436 darwin_devices_detached,
437 ctx, &libusb_rem_device_iterator);
439 if (kresult != kIOReturnSuccess) {
440 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
445 /* create notifications for attached devices */
446 kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
447 IOServiceMatching(darwin_device_class),
448 darwin_devices_attached,
449 ctx, &libusb_add_device_iterator);
451 if (kresult != kIOReturnSuccess) {
452 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
458 darwin_clear_iterator (libusb_rem_device_iterator);
459 darwin_clear_iterator (libusb_add_device_iterator);
461 usbi_dbg ("darwin event thread ready to receive events");
463 /* signal the main thread that the hotplug runloop has been created. */
464 pthread_mutex_lock (&libusb_darwin_at_mutex);
465 libusb_darwin_acfl = runloop;
466 pthread_cond_signal (&libusb_darwin_at_cond);
467 pthread_mutex_unlock (&libusb_darwin_at_mutex);
469 /* run the runloop */
472 usbi_dbg ("darwin event thread exiting");
474 /* remove the notification cfsource */
475 CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
477 /* remove the shutdown cfsource */
478 CFRunLoopRemoveSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
480 /* delete notification port */
481 IONotificationPortDestroy (libusb_notification_port);
483 /* delete iterators */
484 IOObjectRelease (libusb_rem_device_iterator);
485 IOObjectRelease (libusb_add_device_iterator);
487 CFRelease (libusb_darwin_acfls);
490 libusb_darwin_acfls = NULL;
491 libusb_darwin_acfl = NULL;
496 /* cleanup function to destroy cached devices */
497 static void __attribute__((destructor)) _darwin_finalize(void) {
498 struct darwin_cached_device *dev, *next;
500 usbi_mutex_lock(&darwin_cached_devices_lock);
501 list_for_each_entry_safe(dev, next, &darwin_cached_devices, list, struct darwin_cached_device) {
502 darwin_deref_cached_device(dev);
504 usbi_mutex_unlock(&darwin_cached_devices_lock);
507 static void darwin_check_version (void) {
508 /* adjust for changes in the USB stack in xnu 15 */
509 int sysctl_args[] = {CTL_KERN, KERN_OSRELEASE};
511 char version_string[256] = {'\0',};
514 sysctl(sysctl_args, 2, version_string, &length, NULL, 0);
517 version = strtol (version_string, NULL, 10);
518 if (0 == errno && version >= 15) {
519 darwin_device_class = "IOUSBHostDevice";
523 static int darwin_init(struct libusb_context *ctx) {
526 rc = pthread_once (&darwin_init_once, darwin_check_version);
528 return LIBUSB_ERROR_OTHER;
531 rc = darwin_scan_devices (ctx);
532 if (LIBUSB_SUCCESS != rc) {
536 if (libusb_darwin_atomic_fetch_add (&initCount, 1) == 0) {
537 #if !OSX_USE_CLOCK_GETTIME
538 /* create the clocks that will be used if clock_gettime() is not available */
539 host_name_port_t host_self;
541 host_self = mach_host_self();
542 host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
543 host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
544 mach_port_deallocate(mach_task_self(), host_self);
547 pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, ctx);
549 pthread_mutex_lock (&libusb_darwin_at_mutex);
550 while (!libusb_darwin_acfl)
551 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
552 pthread_mutex_unlock (&libusb_darwin_at_mutex);
558 static void darwin_exit (void) {
559 if (libusb_darwin_atomic_fetch_add (&initCount, -1) == 1) {
560 #if !OSX_USE_CLOCK_GETTIME
561 mach_port_deallocate(mach_task_self(), clock_realtime);
562 mach_port_deallocate(mach_task_self(), clock_monotonic);
565 /* stop the event runloop and wait for the thread to terminate. */
566 CFRunLoopSourceSignal(libusb_darwin_acfls);
567 CFRunLoopWakeUp (libusb_darwin_acfl);
568 pthread_join (libusb_darwin_at, NULL);
572 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
573 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
575 /* return cached copy */
576 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
583 static int get_configuration_index (struct libusb_device *dev, int config_value) {
584 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
586 IOUSBConfigurationDescriptorPtr desc;
589 /* is there a simpler way to determine the index? */
590 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
591 if (kresult != kIOReturnSuccess)
592 return darwin_to_libusb (kresult);
594 for (i = 0 ; i < numConfig ; i++) {
595 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
597 if (desc->bConfigurationValue == config_value)
601 /* configuration not found */
602 return LIBUSB_ERROR_NOT_FOUND;
605 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
606 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
609 if (0 == priv->active_config)
610 return LIBUSB_ERROR_NOT_FOUND;
612 config_index = get_configuration_index (dev, priv->active_config);
613 if (config_index < 0)
616 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
619 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
620 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
621 IOUSBConfigurationDescriptorPtr desc;
625 if (!priv || !priv->device)
626 return LIBUSB_ERROR_OTHER;
628 kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
629 if (kresult == kIOReturnSuccess) {
630 /* copy descriptor */
631 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
632 len = libusb_le16_to_cpu(desc->wTotalLength);
634 memmove (buffer, desc, len);
636 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
640 ret = darwin_to_libusb (kresult);
641 if (ret != LIBUSB_SUCCESS)
647 /* check whether the os has configured the device */
648 static int darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) {
649 usb_device_t **darwin_device = dev->device;
651 IOUSBConfigurationDescriptorPtr configDesc;
652 IOUSBFindInterfaceRequest request;
653 kern_return_t kresult;
654 io_iterator_t interface_iterator;
655 io_service_t firstInterface;
657 if (dev->dev_descriptor.bNumConfigurations < 1) {
658 usbi_err (ctx, "device has no configurations");
659 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
662 /* checking the configuration of a root hub simulation takes ~1 s in 10.11. the device is
664 if (0x05ac == dev->dev_descriptor.idVendor && 0x8005 == dev->dev_descriptor.idProduct) {
665 usbi_dbg ("ignoring configuration on root hub simulation");
666 dev->active_config = 0;
670 /* find the first configuration */
671 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
672 dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
674 /* check if the device is already configured. there is probably a better way than iterating over the
675 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
676 might lock up on the device request) */
678 /* Setup the Interface Request */
679 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
680 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
681 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
682 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
684 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
686 return darwin_to_libusb (kresult);
689 firstInterface = IOIteratorNext(interface_iterator);
691 /* done with the interface iterator */
692 IOObjectRelease(interface_iterator);
694 if (firstInterface) {
695 IOObjectRelease (firstInterface);
697 /* device is configured */
698 if (dev->dev_descriptor.bNumConfigurations == 1)
699 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
700 dev->active_config = dev->first_config;
702 /* devices with more than one configuration should work with GetConfiguration */
703 (*darwin_device)->GetConfiguration (darwin_device, &dev->active_config);
706 dev->active_config = 0;
708 usbi_dbg ("active config: %u, first config: %u", dev->active_config, dev->first_config);
713 static int darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
714 IOUSBDevRequestTO req;
716 memset (buffer, 0, buffer_size);
718 /* Set up request for descriptor/ */
719 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
720 req.bRequest = kUSBRqGetDescriptor;
721 req.wValue = desc << 8;
722 req.wIndex = desc_index;
723 req.wLength = buffer_size;
725 req.noDataTimeout = 20;
726 req.completionTimeout = 100;
728 return (*device)->DeviceRequestTO (device, &req);
731 static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct darwin_cached_device *dev) {
732 usb_device_t **device = dev->device;
733 int retries = 1, delay = 30000;
734 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
738 UInt16 idProduct, idVendor;
740 dev->can_enumerate = 0;
742 (*device)->GetDeviceClass (device, &bDeviceClass);
743 (*device)->GetDeviceProduct (device, &idProduct);
744 (*device)->GetDeviceVendor (device, &idVendor);
746 /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
747 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
748 * to follow the spec as closely as possible, try opening the device */
749 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
752 /**** retrieve device descriptor ****/
753 ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &dev->dev_descriptor, sizeof(dev->dev_descriptor));
755 if (kIOReturnOverrun == ret && kUSBDeviceDesc == dev->dev_descriptor.bDescriptorType)
756 /* received an overrun error but we still received a device descriptor */
757 ret = kIOReturnSuccess;
759 if (kIOUSBVendorIDAppleComputer == idVendor) {
760 /* NTH: don't bother retrying or unsuspending Apple devices */
764 if (kIOReturnSuccess == ret && (0 == dev->dev_descriptor.bNumConfigurations ||
765 0 == dev->dev_descriptor.bcdUSB)) {
766 /* work around for incorrectly configured devices */
767 if (try_reconfigure && is_open) {
768 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
770 /* set the first configuration */
771 (*device)->SetConfiguration(device, 1);
773 /* don't try to reconfigure again */
777 ret = kIOUSBPipeStalled;
780 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
781 /* device may be suspended. unsuspend it and try again */
782 #if DeviceVersion >= 320
785 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
786 (void)(*device)->GetUSBDeviceInformation (device, &info);
788 /* note that the device was suspended */
789 if (info & (1 << kUSBInformationDeviceIsSuspendedBit) || 0 == info)
794 /* try to unsuspend the device */
795 ret2 = (*device)->USBDeviceSuspend (device, 0);
796 if (kIOReturnSuccess != ret2) {
797 /* prevent log spew from poorly behaving devices. this indicates the
798 os actually had trouble communicating with the device */
799 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
807 if (kIOReturnSuccess != ret) {
808 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
809 /* sleep for a little while before trying again */
810 nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000UL}, NULL);
812 } while (kIOReturnSuccess != ret && retries--);
815 /* resuspend the device */
816 (void)(*device)->USBDeviceSuspend (device, 1);
819 (void) (*device)->USBDeviceClose (device);
821 if (ret != kIOReturnSuccess) {
822 /* a debug message was already printed out for this error */
823 if (LIBUSB_CLASS_HUB == bDeviceClass)
824 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
825 idVendor, idProduct, darwin_error_str (ret), ret);
827 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
828 idVendor, idProduct, darwin_error_str (ret), ret);
829 return darwin_to_libusb (ret);
832 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
833 if (libusb_le16_to_cpu (dev->dev_descriptor.idProduct) != idProduct) {
834 /* not a valid device */
835 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
836 idProduct, libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
837 return LIBUSB_ERROR_NO_DEVICE;
840 usbi_dbg ("cached device descriptor:");
841 usbi_dbg (" bDescriptorType: 0x%02x", dev->dev_descriptor.bDescriptorType);
842 usbi_dbg (" bcdUSB: 0x%04x", dev->dev_descriptor.bcdUSB);
843 usbi_dbg (" bDeviceClass: 0x%02x", dev->dev_descriptor.bDeviceClass);
844 usbi_dbg (" bDeviceSubClass: 0x%02x", dev->dev_descriptor.bDeviceSubClass);
845 usbi_dbg (" bDeviceProtocol: 0x%02x", dev->dev_descriptor.bDeviceProtocol);
846 usbi_dbg (" bMaxPacketSize0: 0x%02x", dev->dev_descriptor.bMaxPacketSize0);
847 usbi_dbg (" idVendor: 0x%04x", dev->dev_descriptor.idVendor);
848 usbi_dbg (" idProduct: 0x%04x", dev->dev_descriptor.idProduct);
849 usbi_dbg (" bcdDevice: 0x%04x", dev->dev_descriptor.bcdDevice);
850 usbi_dbg (" iManufacturer: 0x%02x", dev->dev_descriptor.iManufacturer);
851 usbi_dbg (" iProduct: 0x%02x", dev->dev_descriptor.iProduct);
852 usbi_dbg (" iSerialNumber: 0x%02x", dev->dev_descriptor.iSerialNumber);
853 usbi_dbg (" bNumConfigurations: 0x%02x", dev->dev_descriptor.bNumConfigurations);
855 dev->can_enumerate = 1;
857 return LIBUSB_SUCCESS;
860 static int get_device_port (io_service_t service, UInt8 *port) {
861 kern_return_t result;
865 if (get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, port)) {
869 result = IORegistryEntryGetParentEntry (service, kIOServicePlane, &parent);
870 if (kIOReturnSuccess == result) {
871 ret = get_ioregistry_value_data (parent, CFSTR("port"), 1, port);
872 IOObjectRelease (parent);
878 static int get_device_parent_sessionID(io_service_t service, UInt64 *parent_sessionID) {
879 kern_return_t result;
882 /* Walk up the tree in the IOService plane until we find a parent that has a sessionID */
884 while((result = IORegistryEntryGetParentEntry (parent, kIOServicePlane, &parent)) == kIOReturnSuccess) {
885 if (get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, parent_sessionID)) {
891 /* We ran out of parents */
895 static int darwin_get_cached_device(struct libusb_context *ctx, io_service_t service,
896 struct darwin_cached_device **cached_out) {
897 struct darwin_cached_device *new_device;
898 UInt64 sessionID = 0, parent_sessionID = 0;
899 int ret = LIBUSB_SUCCESS;
900 usb_device_t **device;
903 /* get some info from the io registry */
904 (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
905 if (!get_device_port (service, &port)) {
906 usbi_dbg("could not get connected port number");
909 usbi_dbg("finding cached device for sessionID 0x%" PRIx64, sessionID);
911 if (get_device_parent_sessionID(service, &parent_sessionID)) {
912 usbi_dbg("parent sessionID: 0x%" PRIx64, parent_sessionID);
915 usbi_mutex_lock(&darwin_cached_devices_lock);
919 list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) {
920 usbi_dbg("matching sessionID 0x%" PRIx64 " against cached device with sessionID 0x%" PRIx64, sessionID, new_device->session);
921 if (new_device->session == sessionID) {
922 usbi_dbg("using cached device for device");
923 *cached_out = new_device;
931 usbi_dbg("caching new device with sessionID 0x%" PRIx64, sessionID);
933 device = darwin_device_from_service (service);
935 ret = LIBUSB_ERROR_NO_DEVICE;
939 new_device = calloc (1, sizeof (*new_device));
941 ret = LIBUSB_ERROR_NO_MEM;
945 /* add this device to the cached device list */
946 list_add(&new_device->list, &darwin_cached_devices);
948 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
950 /* keep a reference to this device */
951 darwin_ref_cached_device(new_device);
953 new_device->device = device;
954 new_device->session = sessionID;
955 (*device)->GetLocationID (device, &new_device->location);
956 new_device->port = port;
957 new_device->parent_session = parent_sessionID;
959 /* cache the device descriptor */
960 ret = darwin_cache_device_descriptor(ctx, new_device);
964 if (new_device->can_enumerate) {
965 snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address,
966 new_device->dev_descriptor.idVendor, new_device->dev_descriptor.idProduct,
967 new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass);
971 usbi_mutex_unlock(&darwin_cached_devices_lock);
973 /* keep track of devices regardless of if we successfully enumerate them to
974 prevent them from being enumerated multiple times */
976 *cached_out = new_device;
981 static int process_new_device (struct libusb_context *ctx, io_service_t service) {
982 struct darwin_device_priv *priv;
983 struct libusb_device *dev = NULL;
984 struct darwin_cached_device *cached_device;
989 ret = darwin_get_cached_device (ctx, service, &cached_device);
991 if (ret < 0 || !cached_device->can_enumerate) {
995 /* check current active configuration (and cache the first configuration value--
996 which may be used by claim_interface) */
997 ret = darwin_check_configuration (ctx, cached_device);
1001 usbi_dbg ("allocating new device in context %p for with session 0x%" PRIx64,
1002 ctx, cached_device->session);
1004 dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
1006 return LIBUSB_ERROR_NO_MEM;
1009 priv = (struct darwin_device_priv *)dev->os_priv;
1011 priv->dev = cached_device;
1012 darwin_ref_cached_device (priv->dev);
1014 if (cached_device->parent_session > 0) {
1015 dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session);
1017 dev->parent_dev = NULL;
1019 dev->port_number = cached_device->port;
1020 dev->bus_number = cached_device->location >> 24;
1021 dev->device_address = cached_device->address;
1023 (*(priv->dev->device))->GetDeviceSpeed (priv->dev->device, &devSpeed);
1026 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
1027 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
1028 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
1029 #if DeviceVersion >= 500
1030 case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
1033 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
1036 ret = usbi_sanitize_device (dev);
1040 usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
1041 dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
1045 usbi_connect_device (dev);
1047 libusb_unref_device (dev);
1053 static int darwin_scan_devices(struct libusb_context *ctx) {
1054 io_iterator_t deviceIterator;
1055 io_service_t service;
1056 kern_return_t kresult;
1058 kresult = usb_setup_device_iterator (&deviceIterator, 0);
1059 if (kresult != kIOReturnSuccess)
1060 return darwin_to_libusb (kresult);
1062 while ((service = IOIteratorNext (deviceIterator))) {
1063 (void) process_new_device (ctx, service);
1065 IOObjectRelease(service);
1068 IOObjectRelease(deviceIterator);
1073 static int darwin_open (struct libusb_device_handle *dev_handle) {
1074 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1075 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1078 if (0 == dpriv->open_count) {
1079 /* try to open the device */
1080 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
1081 if (kresult != kIOReturnSuccess) {
1082 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
1084 if (kIOReturnExclusiveAccess != kresult) {
1085 return darwin_to_libusb (kresult);
1088 /* it is possible to perform some actions on a device that is not open so do not return an error */
1094 /* create async event source */
1095 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
1096 if (kresult != kIOReturnSuccess) {
1097 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
1099 if (priv->is_open) {
1100 (*(dpriv->device))->USBDeviceClose (dpriv->device);
1105 return darwin_to_libusb (kresult);
1108 CFRetain (libusb_darwin_acfl);
1110 /* add the cfSource to the aync run loop */
1111 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
1114 /* device opened successfully */
1115 dpriv->open_count++;
1117 usbi_dbg ("device open for access");
1122 static void darwin_close (struct libusb_device_handle *dev_handle) {
1123 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1124 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1128 if (dpriv->open_count == 0) {
1129 /* something is probably very wrong if this is the case */
1130 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!");
1134 dpriv->open_count--;
1136 /* make sure all interfaces are released */
1137 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1138 if (dev_handle->claimed_interfaces & (1 << i))
1139 libusb_release_interface (dev_handle, i);
1141 if (0 == dpriv->open_count) {
1142 /* delete the device's async event source */
1143 if (priv->cfSource) {
1144 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
1145 CFRelease (priv->cfSource);
1146 priv->cfSource = NULL;
1147 CFRelease (libusb_darwin_acfl);
1150 if (priv->is_open) {
1151 /* close the device */
1152 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
1154 /* Log the fact that we had a problem closing the file, however failing a
1155 * close isn't really an error, so return success anyway */
1156 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
1162 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
1163 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1165 *config = (int) dpriv->active_config;
1170 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
1171 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1175 /* Setting configuration will invalidate the interface, so we need
1176 to reclaim it. First, dispose of existing interfaces, if any. */
1177 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1178 if (dev_handle->claimed_interfaces & (1 << i))
1179 darwin_release_interface (dev_handle, i);
1181 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
1182 if (kresult != kIOReturnSuccess)
1183 return darwin_to_libusb (kresult);
1185 /* Reclaim any interfaces. */
1186 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1187 if (dev_handle->claimed_interfaces & (1 << i))
1188 darwin_claim_interface (dev_handle, i);
1190 dpriv->active_config = config;
1195 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
1196 IOUSBFindInterfaceRequest request;
1197 kern_return_t kresult;
1198 io_iterator_t interface_iterator;
1199 UInt8 bInterfaceNumber;
1202 *usbInterfacep = IO_OBJECT_NULL;
1204 /* Setup the Interface Request */
1205 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1206 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1207 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1208 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1210 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1214 while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1215 /* find the interface number */
1216 ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
1219 if (ret && bInterfaceNumber == ifc) {
1223 (void) IOObjectRelease (*usbInterfacep);
1226 /* done with the interface iterator */
1227 IOObjectRelease(interface_iterator);
1232 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
1233 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1235 /* current interface */
1236 struct darwin_interface *cInterface = &priv->interfaces[iface];
1238 kern_return_t kresult;
1240 u_int8_t numep, direction, number;
1241 u_int8_t dont_care1, dont_care3;
1242 u_int16_t dont_care2;
1245 usbi_dbg ("building table of endpoints.");
1247 /* retrieve the total number of endpoints on this interface */
1248 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1250 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1251 return darwin_to_libusb (kresult);
1254 /* iterate through pipe references */
1255 for (int i = 1 ; i <= numep ; i++) {
1256 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1257 &dont_care2, &dont_care3);
1259 if (kresult != kIOReturnSuccess) {
1260 /* probably a buggy device. try to get the endpoint address from the descriptors */
1261 struct libusb_config_descriptor *config;
1262 const struct libusb_endpoint_descriptor *endpoint_desc;
1265 kresult = (*(cInterface->interface))->GetAlternateSetting (cInterface->interface, &alt_setting);
1267 usbi_err (HANDLE_CTX (dev_handle), "can't get alternate setting for interface");
1268 return darwin_to_libusb (kresult);
1271 rc = libusb_get_active_config_descriptor (dev_handle->dev, &config);
1272 if (LIBUSB_SUCCESS != rc) {
1276 endpoint_desc = config->interface[iface].altsetting[alt_setting].endpoint + i - 1;
1278 cInterface->endpoint_addrs[i - 1] = endpoint_desc->bEndpointAddress;
1280 cInterface->endpoint_addrs[i - 1] = (((kUSBIn == direction) << kUSBRqDirnShift) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1283 usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, cInterface->endpoint_addrs[i - 1] >> kUSBRqDirnShift,
1284 cInterface->endpoint_addrs[i - 1] & LIBUSB_ENDPOINT_ADDRESS_MASK);
1287 cInterface->num_endpoints = numep;
1292 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1293 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1294 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1295 io_service_t usbInterface = IO_OBJECT_NULL;
1297 IOCFPlugInInterface **plugInInterface = NULL;
1300 /* current interface */
1301 struct darwin_interface *cInterface = &priv->interfaces[iface];
1303 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1304 if (kresult != kIOReturnSuccess)
1305 return darwin_to_libusb (kresult);
1307 /* make sure we have an interface */
1308 if (!usbInterface && dpriv->first_config != 0) {
1309 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1311 /* set the configuration */
1312 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1313 if (kresult != LIBUSB_SUCCESS) {
1314 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1318 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1320 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1321 return darwin_to_libusb (kresult);
1325 if (!usbInterface) {
1326 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1327 return LIBUSB_ERROR_NOT_FOUND;
1330 /* get an interface to the device's interface */
1331 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1332 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1334 /* ignore release error */
1335 (void)IOObjectRelease (usbInterface);
1338 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1339 return darwin_to_libusb (kresult);
1342 if (!plugInInterface) {
1343 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1344 return LIBUSB_ERROR_NOT_FOUND;
1347 /* Do the actual claim */
1348 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1349 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1350 (LPVOID)&cInterface->interface);
1351 /* We no longer need the intermediate plug-in */
1352 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1353 (*plugInInterface)->Release (plugInInterface);
1354 if (kresult || !cInterface->interface) {
1355 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1356 return darwin_to_libusb (kresult);
1359 /* claim the interface */
1360 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1362 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1363 return darwin_to_libusb (kresult);
1366 /* update list of endpoints */
1367 kresult = get_endpoints (dev_handle, iface);
1369 /* this should not happen */
1370 darwin_release_interface (dev_handle, iface);
1371 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1375 cInterface->cfSource = NULL;
1377 /* create async event source */
1378 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1379 if (kresult != kIOReturnSuccess) {
1380 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1382 /* can't continue without an async event source */
1383 (void)darwin_release_interface (dev_handle, iface);
1385 return darwin_to_libusb (kresult);
1388 /* add the cfSource to the async thread's run loop */
1389 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1391 usbi_dbg ("interface opened");
1396 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1397 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1400 /* current interface */
1401 struct darwin_interface *cInterface = &priv->interfaces[iface];
1403 /* Check to see if an interface is open */
1404 if (!cInterface->interface)
1405 return LIBUSB_SUCCESS;
1407 /* clean up endpoint data */
1408 cInterface->num_endpoints = 0;
1410 /* delete the interface's async event source */
1411 if (cInterface->cfSource) {
1412 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1413 CFRelease (cInterface->cfSource);
1416 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1418 usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1420 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1421 if (kresult != kIOReturnSuccess)
1422 usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1424 cInterface->interface = (usb_interface_t **) IO_OBJECT_NULL;
1426 return darwin_to_libusb (kresult);
1429 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1430 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1433 /* current interface */
1434 struct darwin_interface *cInterface = &priv->interfaces[iface];
1436 if (!cInterface->interface)
1437 return LIBUSB_ERROR_NO_DEVICE;
1439 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1440 if (kresult != kIOReturnSuccess)
1441 darwin_reset_device (dev_handle);
1443 /* update list of endpoints */
1444 kresult = get_endpoints (dev_handle, iface);
1446 /* this should not happen */
1447 darwin_release_interface (dev_handle, iface);
1448 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1452 return darwin_to_libusb (kresult);
1455 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1456 /* current interface */
1457 struct darwin_interface *cInterface;
1461 /* determine the interface/endpoint to use */
1462 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, NULL, &cInterface) != 0) {
1463 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1465 return LIBUSB_ERROR_NOT_FOUND;
1468 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1469 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1471 usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1473 return darwin_to_libusb (kresult);
1476 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1477 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1478 IOUSBDeviceDescriptor descriptor;
1479 IOUSBConfigurationDescriptorPtr cached_configuration;
1480 IOUSBConfigurationDescriptor configuration;
1481 bool reenumerate = false;
1485 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1487 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1488 return darwin_to_libusb (kresult);
1492 usbi_dbg ("darwin/reset_device: checking if device descriptor changed");
1494 /* ignore return code. if we can't get a descriptor it might be worthwhile re-enumerating anway */
1495 (void) darwin_request_descriptor (dpriv->device, kUSBDeviceDesc, 0, &descriptor, sizeof (descriptor));
1497 /* check if the device descriptor has changed */
1498 if (0 != memcmp (&dpriv->dev_descriptor, &descriptor, sizeof (descriptor))) {
1503 /* check if any configuration descriptor has changed */
1504 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1505 usbi_dbg ("darwin/reset_device: checking if configuration descriptor %d changed", i);
1507 (void) darwin_request_descriptor (dpriv->device, kUSBConfDesc, i, &configuration, sizeof (configuration));
1508 (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1510 if (!cached_configuration || 0 != memcmp (cached_configuration, &configuration, sizeof (configuration))) {
1518 usbi_dbg ("darwin/reset_device: device requires reenumeration");
1519 (void) (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
1520 return LIBUSB_ERROR_NOT_FOUND;
1523 usbi_dbg ("darwin/reset_device: device reset complete");
1525 return LIBUSB_SUCCESS;
1528 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1529 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1530 io_service_t usbInterface;
1534 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1536 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1538 return darwin_to_libusb (kresult);
1541 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1542 IOObjectRelease (usbInterface);
1554 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1555 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1558 return LIBUSB_ERROR_NOT_SUPPORTED;
1561 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1564 return LIBUSB_ERROR_NOT_SUPPORTED;
1567 static void darwin_destroy_device(struct libusb_device *dev) {
1568 struct darwin_device_priv *dpriv = (struct darwin_device_priv *) dev->os_priv;
1571 /* need to hold the lock in case this is the last reference to the device */
1572 usbi_mutex_lock(&darwin_cached_devices_lock);
1573 darwin_deref_cached_device (dpriv->dev);
1575 usbi_mutex_unlock(&darwin_cached_devices_lock);
1579 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1580 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1583 uint8_t transferType;
1584 /* None of the values below are used in libusbx for bulk transfers */
1585 uint8_t direction, number, interval, pipeRef;
1586 uint16_t maxPacketSize;
1588 struct darwin_interface *cInterface;
1590 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1591 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1593 return LIBUSB_ERROR_NOT_FOUND;
1596 ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1597 &transferType, &maxPacketSize, &interval);
1600 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1601 darwin_error_str(ret), ret);
1602 return darwin_to_libusb (ret);
1605 if (0 != (transfer->length % maxPacketSize)) {
1606 /* do not need a zero packet */
1607 transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1610 /* submit the request */
1611 /* timeouts are unavailable on interrupt endpoints */
1612 if (transferType == kUSBInterrupt) {
1613 if (IS_XFERIN(transfer))
1614 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1615 transfer->length, darwin_async_io_callback, itransfer);
1617 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1618 transfer->length, darwin_async_io_callback, itransfer);
1620 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1622 if (IS_XFERIN(transfer))
1623 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1624 transfer->length, transfer->timeout, transfer->timeout,
1625 darwin_async_io_callback, (void *)itransfer);
1627 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1628 transfer->length, transfer->timeout, transfer->timeout,
1629 darwin_async_io_callback, (void *)itransfer);
1633 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1634 darwin_error_str(ret), ret);
1636 return darwin_to_libusb (ret);
1639 #if InterfaceVersion >= 550
1640 static int submit_stream_transfer(struct usbi_transfer *itransfer) {
1641 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1642 struct darwin_interface *cInterface;
1646 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1647 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1649 return LIBUSB_ERROR_NOT_FOUND;
1652 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1654 if (IS_XFERIN(transfer))
1655 ret = (*(cInterface->interface))->ReadStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1656 transfer->buffer, transfer->length, transfer->timeout,
1657 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1659 ret = (*(cInterface->interface))->WriteStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1660 transfer->buffer, transfer->length, transfer->timeout,
1661 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1664 usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1665 darwin_error_str(ret), ret);
1667 return darwin_to_libusb (ret);
1671 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1672 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1673 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1676 uint8_t direction, number, interval, pipeRef, transferType;
1677 uint16_t maxPacketSize;
1679 AbsoluteTime atTime;
1682 struct darwin_interface *cInterface;
1684 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1685 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1686 free(tpriv->isoc_framelist);
1687 tpriv->isoc_framelist = NULL;
1690 if (!tpriv->isoc_framelist) {
1691 tpriv->num_iso_packets = transfer->num_iso_packets;
1692 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1693 if (!tpriv->isoc_framelist)
1694 return LIBUSB_ERROR_NO_MEM;
1697 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1698 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1699 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1701 /* determine the interface/endpoint to use */
1702 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1703 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1705 return LIBUSB_ERROR_NOT_FOUND;
1708 /* determine the properties of this endpoint and the speed of the device */
1709 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1710 &transferType, &maxPacketSize, &interval);
1712 /* Last but not least we need the bus frame number */
1713 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1715 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1716 free(tpriv->isoc_framelist);
1717 tpriv->isoc_framelist = NULL;
1719 return darwin_to_libusb (kresult);
1722 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1723 &transferType, &maxPacketSize, &interval);
1725 /* schedule for a frame a little in the future */
1728 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1729 frame = cInterface->frames[transfer->endpoint];
1731 /* submit the request */
1732 if (IS_XFERIN(transfer))
1733 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1734 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1737 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1738 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1741 if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
1743 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1));
1745 /* High/super speed */
1746 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1)) / 8;
1748 if (kresult != kIOReturnSuccess) {
1749 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1750 darwin_error_str(kresult));
1751 free (tpriv->isoc_framelist);
1752 tpriv->isoc_framelist = NULL;
1755 return darwin_to_libusb (kresult);
1758 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1759 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1760 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1761 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1762 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1766 memset(&tpriv->req, 0, sizeof(tpriv->req));
1768 /* IOUSBDeviceInterface expects the request in cpu endianness */
1769 tpriv->req.bmRequestType = setup->bmRequestType;
1770 tpriv->req.bRequest = setup->bRequest;
1771 /* these values should be in bus order from libusb_fill_control_setup */
1772 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1773 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1774 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1775 /* data is stored after the libusb control block */
1776 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1777 tpriv->req.completionTimeout = transfer->timeout;
1778 tpriv->req.noDataTimeout = transfer->timeout;
1780 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1782 /* all transfers in libusb-1.0 are async */
1784 if (transfer->endpoint) {
1785 struct darwin_interface *cInterface;
1788 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1789 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1791 return LIBUSB_ERROR_NOT_FOUND;
1794 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1796 /* control request on endpoint 0 */
1797 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1799 if (kresult != kIOReturnSuccess)
1800 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1802 return darwin_to_libusb (kresult);
1805 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1806 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1808 switch (transfer->type) {
1809 case LIBUSB_TRANSFER_TYPE_CONTROL:
1810 return submit_control_transfer(itransfer);
1811 case LIBUSB_TRANSFER_TYPE_BULK:
1812 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1813 return submit_bulk_transfer(itransfer);
1814 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1815 return submit_iso_transfer(itransfer);
1816 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1817 #if InterfaceVersion >= 550
1818 return submit_stream_transfer(itransfer);
1820 usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers");
1821 return LIBUSB_ERROR_NOT_SUPPORTED;
1824 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1825 return LIBUSB_ERROR_INVALID_PARAM;
1829 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1830 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1831 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1834 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
1837 return LIBUSB_ERROR_NO_DEVICE;
1839 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1841 return darwin_to_libusb (kresult);
1844 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1845 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1846 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1847 struct darwin_interface *cInterface;
1848 uint8_t pipeRef, iface;
1851 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) {
1852 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1854 return LIBUSB_ERROR_NOT_FOUND;
1858 return LIBUSB_ERROR_NO_DEVICE;
1860 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
1862 /* abort transactions */
1863 #if InterfaceVersion >= 550
1864 if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type)
1865 (*(cInterface->interface))->AbortStreamsPipe (cInterface->interface, pipeRef, itransfer->stream_id);
1868 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1870 usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
1872 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1873 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1875 return darwin_to_libusb (kresult);
1878 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1879 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1881 switch (transfer->type) {
1882 case LIBUSB_TRANSFER_TYPE_CONTROL:
1883 return cancel_control_transfer(itransfer);
1884 case LIBUSB_TRANSFER_TYPE_BULK:
1885 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1886 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1887 return darwin_abort_transfers (itransfer);
1889 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1890 return LIBUSB_ERROR_INVALID_PARAM;
1894 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1895 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1896 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1898 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1899 free (tpriv->isoc_framelist);
1900 tpriv->isoc_framelist = NULL;
1904 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1905 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1906 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1907 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1909 usbi_dbg ("an async io operation has completed");
1911 /* if requested write a zero packet */
1912 if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
1913 struct darwin_interface *cInterface;
1916 (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface);
1918 (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
1921 tpriv->result = result;
1922 tpriv->size = (UInt32) (uintptr_t) arg0;
1924 /* signal the core that this transfer is complete */
1925 usbi_signal_transfer_completion(itransfer);
1928 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1929 if (itransfer->timeout_flags & USBI_TRANSFER_TIMED_OUT)
1930 result = kIOUSBTransactionTimeout;
1933 case kIOReturnUnderrun:
1934 case kIOReturnSuccess:
1935 return LIBUSB_TRANSFER_COMPLETED;
1936 case kIOReturnAborted:
1937 return LIBUSB_TRANSFER_CANCELLED;
1938 case kIOUSBPipeStalled:
1939 usbi_dbg ("transfer error: pipe is stalled");
1940 return LIBUSB_TRANSFER_STALL;
1941 case kIOReturnOverrun:
1942 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1943 return LIBUSB_TRANSFER_OVERFLOW;
1944 case kIOUSBTransactionTimeout:
1945 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1946 itransfer->timeout_flags |= USBI_TRANSFER_TIMED_OUT;
1947 return LIBUSB_TRANSFER_TIMED_OUT;
1949 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1950 return LIBUSB_TRANSFER_ERROR;
1954 static int darwin_handle_transfer_completion (struct usbi_transfer *itransfer) {
1955 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1956 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1957 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1958 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1959 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1960 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1963 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1964 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1965 return LIBUSB_ERROR_INVALID_PARAM;
1968 usbi_dbg ("handling %s completion with kernel status %d",
1969 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", tpriv->result);
1971 if (kIOReturnSuccess == tpriv->result || kIOReturnUnderrun == tpriv->result) {
1972 if (isIsoc && tpriv->isoc_framelist) {
1973 /* copy isochronous results back */
1975 for (i = 0; i < transfer->num_iso_packets ; i++) {
1976 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1977 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1978 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1981 itransfer->transferred += tpriv->size;
1984 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1985 return usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, tpriv->result));
1988 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1989 #if !OSX_USE_CLOCK_GETTIME
1990 mach_timespec_t sys_time;
1991 clock_serv_t clock_ref;
1994 case USBI_CLOCK_REALTIME:
1995 /* CLOCK_REALTIME represents time since the epoch */
1996 clock_ref = clock_realtime;
1998 case USBI_CLOCK_MONOTONIC:
1999 /* use system boot time as reference for the monotonic clock */
2000 clock_ref = clock_monotonic;
2003 return LIBUSB_ERROR_INVALID_PARAM;
2006 clock_get_time (clock_ref, &sys_time);
2008 tp->tv_sec = sys_time.tv_sec;
2009 tp->tv_nsec = sys_time.tv_nsec;
2014 case USBI_CLOCK_MONOTONIC:
2015 return clock_gettime(CLOCK_MONOTONIC, tp);
2016 case USBI_CLOCK_REALTIME:
2017 return clock_gettime(CLOCK_REALTIME, tp);
2019 return LIBUSB_ERROR_INVALID_PARAM;
2024 #if InterfaceVersion >= 550
2025 static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints,
2026 int num_endpoints) {
2027 struct darwin_interface *cInterface;
2028 UInt32 supportsStreams;
2032 /* find the mimimum number of supported streams on the endpoint list */
2033 for (i = 0 ; i < num_endpoints ; ++i) {
2034 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) {
2038 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2039 if (num_streams > supportsStreams)
2040 num_streams = supportsStreams;
2043 /* it is an error if any endpoint in endpoints does not support streams */
2044 if (0 == num_streams)
2045 return LIBUSB_ERROR_INVALID_PARAM;
2047 /* create the streams */
2048 for (i = 0 ; i < num_endpoints ; ++i) {
2049 (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
2051 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, num_streams);
2052 if (kIOReturnSuccess != rc)
2053 return darwin_to_libusb(rc);
2059 static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) {
2060 struct darwin_interface *cInterface;
2061 UInt32 supportsStreams;
2065 for (int i = 0 ; i < num_endpoints ; ++i) {
2066 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface)))
2069 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2070 if (0 == supportsStreams)
2071 return LIBUSB_ERROR_INVALID_PARAM;
2073 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, 0);
2074 if (kIOReturnSuccess != rc)
2075 return darwin_to_libusb(rc);
2078 return LIBUSB_SUCCESS;
2082 const struct usbi_os_backend darwin_backend = {
2085 .init = darwin_init,
2086 .exit = darwin_exit,
2087 .get_device_list = NULL, /* not needed */
2088 .get_device_descriptor = darwin_get_device_descriptor,
2089 .get_active_config_descriptor = darwin_get_active_config_descriptor,
2090 .get_config_descriptor = darwin_get_config_descriptor,
2091 .hotplug_poll = darwin_hotplug_poll,
2093 .open = darwin_open,
2094 .close = darwin_close,
2095 .get_configuration = darwin_get_configuration,
2096 .set_configuration = darwin_set_configuration,
2097 .claim_interface = darwin_claim_interface,
2098 .release_interface = darwin_release_interface,
2100 .set_interface_altsetting = darwin_set_interface_altsetting,
2101 .clear_halt = darwin_clear_halt,
2102 .reset_device = darwin_reset_device,
2104 #if InterfaceVersion >= 550
2105 .alloc_streams = darwin_alloc_streams,
2106 .free_streams = darwin_free_streams,
2109 .kernel_driver_active = darwin_kernel_driver_active,
2110 .detach_kernel_driver = darwin_detach_kernel_driver,
2111 .attach_kernel_driver = darwin_attach_kernel_driver,
2113 .destroy_device = darwin_destroy_device,
2115 .submit_transfer = darwin_submit_transfer,
2116 .cancel_transfer = darwin_cancel_transfer,
2117 .clear_transfer_priv = darwin_clear_transfer_priv,
2119 .handle_transfer_completion = darwin_handle_transfer_completion,
2121 .clock_gettime = darwin_clock_gettime,
2123 .device_priv_size = sizeof(struct darwin_device_priv),
2124 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
2125 .transfer_priv_size = sizeof(struct darwin_transfer_priv),