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)
49 _Atomic int32_t initCount = ATOMIC_VAR_INIT(0);
51 /* use darwin atomics if the target is older than 10.12 */
52 #include <libkern/OSAtomic.h>
54 /* OSAtomicAdd32Barrier returns the new value */
55 #define libusb_darwin_atomic_fetch_add(x, y) (OSAtomicAdd32Barrier(y, x) - y)
57 static volatile int32_t initCount = 0;
61 /* On 10.12 and later, use newly available clock_*() functions */
62 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 101200
63 #define OSX_USE_CLOCK_GETTIME 1
65 #define OSX_USE_CLOCK_GETTIME 0
68 #include "darwin_usb.h"
70 /* async event thread */
71 static pthread_mutex_t libusb_darwin_at_mutex = PTHREAD_MUTEX_INITIALIZER;
72 static pthread_cond_t libusb_darwin_at_cond = PTHREAD_COND_INITIALIZER;
74 static pthread_once_t darwin_init_once = PTHREAD_ONCE_INIT;
76 #if !OSX_USE_CLOCK_GETTIME
77 static clock_serv_t clock_realtime;
78 static clock_serv_t clock_monotonic;
81 static CFRunLoopRef libusb_darwin_acfl = NULL; /* event cf loop */
82 static CFRunLoopSourceRef libusb_darwin_acfls = NULL; /* shutdown signal for event cf loop */
84 static usbi_mutex_t darwin_cached_devices_lock = PTHREAD_MUTEX_INITIALIZER;
85 static struct list_head darwin_cached_devices = {&darwin_cached_devices, &darwin_cached_devices};
86 static const char *darwin_device_class = kIOUSBDeviceClassName;
88 #define DARWIN_CACHED_DEVICE(a) ((struct darwin_cached_device *) (((struct darwin_device_priv *)((a)->os_priv))->dev))
90 /* async event thread */
91 static pthread_t libusb_darwin_at;
93 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
94 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
95 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
96 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
97 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
99 static int darwin_scan_devices(struct libusb_context *ctx);
100 static int process_new_device (struct libusb_context *ctx, io_service_t service);
102 #if defined(ENABLE_LOGGING)
103 static const char *darwin_error_str (int result) {
104 static char string_buffer[50];
106 case kIOReturnSuccess:
108 case kIOReturnNotOpen:
109 return "device not opened for exclusive access";
110 case kIOReturnNoDevice:
111 return "no connection to an IOService";
112 case kIOUSBNoAsyncPortErr:
113 return "no async port has been opened for interface";
114 case kIOReturnExclusiveAccess:
115 return "another process has device opened for exclusive access";
116 case kIOUSBPipeStalled:
117 return "pipe is stalled";
119 return "could not establish a connection to the Darwin kernel";
120 case kIOUSBTransactionTimeout:
121 return "transaction timed out";
122 case kIOReturnBadArgument:
123 return "invalid argument";
124 case kIOReturnAborted:
125 return "transaction aborted";
126 case kIOReturnNotResponding:
127 return "device not responding";
128 case kIOReturnOverrun:
129 return "data overrun";
130 case kIOReturnCannotWire:
131 return "physical memory can not be wired down";
132 case kIOReturnNoResources:
133 return "out of resources";
134 case kIOUSBHighSpeedSplitError:
135 return "high speed split error";
137 snprintf(string_buffer, sizeof(string_buffer), "unknown error (0x%x)", result);
138 return string_buffer;
143 static int darwin_to_libusb (int result) {
145 case kIOReturnUnderrun:
146 case kIOReturnSuccess:
147 return LIBUSB_SUCCESS;
148 case kIOReturnNotOpen:
149 case kIOReturnNoDevice:
150 return LIBUSB_ERROR_NO_DEVICE;
151 case kIOReturnExclusiveAccess:
152 return LIBUSB_ERROR_ACCESS;
153 case kIOUSBPipeStalled:
154 return LIBUSB_ERROR_PIPE;
155 case kIOReturnBadArgument:
156 return LIBUSB_ERROR_INVALID_PARAM;
157 case kIOUSBTransactionTimeout:
158 return LIBUSB_ERROR_TIMEOUT;
159 case kIOReturnNotResponding:
160 case kIOReturnAborted:
162 case kIOUSBNoAsyncPortErr:
164 return LIBUSB_ERROR_OTHER;
168 /* this function must be called with the darwin_cached_devices_lock held */
169 static void darwin_deref_cached_device(struct darwin_cached_device *cached_dev) {
170 cached_dev->refcount--;
171 /* free the device and remove it from the cache */
172 if (0 == cached_dev->refcount) {
173 list_del(&cached_dev->list);
175 (*(cached_dev->device))->Release(cached_dev->device);
180 static void darwin_ref_cached_device(struct darwin_cached_device *cached_dev) {
181 cached_dev->refcount++;
184 static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp, struct darwin_interface **interface_out) {
185 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
187 /* current interface */
188 struct darwin_interface *cInterface;
192 usbi_dbg ("converting ep address 0x%02x to pipeRef and interface", ep);
194 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
195 cInterface = &priv->interfaces[iface];
197 if (dev_handle->claimed_interfaces & (1 << iface)) {
198 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
199 if (cInterface->endpoint_addrs[i] == ep) {
206 *interface_out = cInterface;
208 usbi_dbg ("pipe %d on interface %d matches", *pipep, iface);
215 /* No pipe found with the correct endpoint address */
216 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
218 return LIBUSB_ERROR_NOT_FOUND;
221 static int usb_setup_device_iterator (io_iterator_t *deviceIterator, UInt32 location) {
222 CFMutableDictionaryRef matchingDict = IOServiceMatching(darwin_device_class);
225 return kIOReturnError;
228 CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
229 &kCFTypeDictionaryKeyCallBacks,
230 &kCFTypeDictionaryValueCallBacks);
232 if (propertyMatchDict) {
233 /* there are no unsigned CFNumber types so treat the value as signed. the os seems to do this
234 internally (CFNumberType of locationID is 3) */
235 CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberSInt32Type, &location);
237 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
238 /* release our reference to the CFNumber (CFDictionarySetValue retains it) */
239 CFRelease (locationCF);
241 CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
242 /* release out reference to the CFMutableDictionaryRef (CFDictionarySetValue retains it) */
243 CFRelease (propertyMatchDict);
245 /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
248 return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator);
251 /* Returns 1 on success, 0 on failure. */
252 static int get_ioregistry_value_number (io_service_t service, CFStringRef property, CFNumberType type, void *p) {
253 CFTypeRef cfNumber = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
257 if (CFGetTypeID(cfNumber) == CFNumberGetTypeID()) {
258 ret = CFNumberGetValue(cfNumber, type, p);
261 CFRelease (cfNumber);
267 static int get_ioregistry_value_data (io_service_t service, CFStringRef property, ssize_t size, void *p) {
268 CFTypeRef cfData = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
272 if (CFGetTypeID (cfData) == CFDataGetTypeID ()) {
273 CFIndex length = CFDataGetLength (cfData);
278 CFDataGetBytes (cfData, CFRangeMake(0, size), p);
288 static usb_device_t **darwin_device_from_service (io_service_t service)
290 io_cf_plugin_ref_t *plugInInterface = NULL;
291 usb_device_t **device;
292 kern_return_t result;
295 result = IOCreatePlugInInterfaceForService(service, kIOUSBDeviceUserClientTypeID,
296 kIOCFPlugInInterfaceID, &plugInInterface,
299 if (kIOReturnSuccess != result || !plugInInterface) {
300 usbi_dbg ("could not set up plugin for service: %s", darwin_error_str (result));
304 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
306 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
307 (*plugInInterface)->Release (plugInInterface);
312 static void darwin_devices_attached (void *ptr, io_iterator_t add_devices) {
314 struct libusb_context *ctx;
315 io_service_t service;
317 usbi_mutex_lock(&active_contexts_lock);
319 while ((service = IOIteratorNext(add_devices))) {
320 /* add this device to each active context's device list */
321 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
322 process_new_device (ctx, service);
325 IOObjectRelease(service);
328 usbi_mutex_unlock(&active_contexts_lock);
331 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
333 struct libusb_device *dev = NULL;
334 struct libusb_context *ctx;
335 struct darwin_cached_device *old_device;
341 usbi_mutex_lock(&active_contexts_lock);
343 while ((device = IOIteratorNext (rem_devices)) != 0) {
344 /* get the location from the i/o registry */
345 ret = get_ioregistry_value_number (device, CFSTR("sessionID"), kCFNumberSInt64Type, &session);
346 IOObjectRelease (device);
350 /* we need to match darwin_ref_cached_device call made in darwin_get_cached_device function
351 otherwise no cached device will ever get freed */
352 usbi_mutex_lock(&darwin_cached_devices_lock);
353 list_for_each_entry(old_device, &darwin_cached_devices, list, struct darwin_cached_device) {
354 if (old_device->session == session) {
355 darwin_deref_cached_device (old_device);
359 usbi_mutex_unlock(&darwin_cached_devices_lock);
361 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
362 usbi_dbg ("notifying context %p of device disconnect", ctx);
364 dev = usbi_get_device_by_session_id(ctx, (unsigned long) session);
366 /* signal the core that this device has been disconnected. the core will tear down this device
367 when the reference count reaches 0 */
368 usbi_disconnect_device(dev);
369 libusb_unref_device(dev);
374 usbi_mutex_unlock(&active_contexts_lock);
377 static void darwin_hotplug_poll (void)
379 /* not sure if 5 seconds will be too long/short but it should work ok */
380 mach_timespec_t timeout = {.tv_sec = 5, .tv_nsec = 0};
382 /* since a kernel thread may nodify the IOInterators used for
383 * hotplug notidication we can't just clear the iterators.
384 * instead just wait until all IOService providers are quiet */
385 (void) IOKitWaitQuiet (kIOMasterPortDefault, &timeout);
388 static void darwin_clear_iterator (io_iterator_t iter) {
391 while ((device = IOIteratorNext (iter)) != 0)
392 IOObjectRelease (device);
395 static void *darwin_event_thread_main (void *arg0) {
397 struct libusb_context *ctx = (struct libusb_context *)arg0;
398 CFRunLoopRef runloop;
400 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
401 /* Set this thread's name, so it can be seen in the debugger
402 and crash reports. */
403 pthread_setname_np ("org.libusb.device-hotplug");
406 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
407 /* Tell the Objective-C garbage collector about this thread.
408 This is required because, unlike NSThreads, pthreads are
409 not automatically registered. Although we don't use
410 Objective-C, we use CoreFoundation, which does.
411 Garbage collection support was entirely removed in 10.12,
412 so don't bother there. */
413 objc_registerThreadWithCollector();
416 /* hotplug (device arrival/removal) sources */
417 CFRunLoopSourceContext libusb_shutdown_cfsourcectx;
418 CFRunLoopSourceRef libusb_notification_cfsource;
419 io_notification_port_t libusb_notification_port;
420 io_iterator_t libusb_rem_device_iterator;
421 io_iterator_t libusb_add_device_iterator;
423 usbi_dbg ("creating hotplug event source");
425 runloop = CFRunLoopGetCurrent ();
428 /* add the shutdown cfsource to the run loop */
429 memset(&libusb_shutdown_cfsourcectx, 0, sizeof(libusb_shutdown_cfsourcectx));
430 libusb_shutdown_cfsourcectx.info = runloop;
431 libusb_shutdown_cfsourcectx.perform = (void (*)(void *))CFRunLoopStop;
432 libusb_darwin_acfls = CFRunLoopSourceCreate(NULL, 0, &libusb_shutdown_cfsourcectx);
433 CFRunLoopAddSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
435 /* add the notification port to the run loop */
436 libusb_notification_port = IONotificationPortCreate (kIOMasterPortDefault);
437 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
438 CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
440 /* create notifications for removed devices */
441 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
442 IOServiceMatching(darwin_device_class),
443 darwin_devices_detached,
444 ctx, &libusb_rem_device_iterator);
446 if (kresult != kIOReturnSuccess) {
447 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
452 /* create notifications for attached devices */
453 kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
454 IOServiceMatching(darwin_device_class),
455 darwin_devices_attached,
456 ctx, &libusb_add_device_iterator);
458 if (kresult != kIOReturnSuccess) {
459 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
465 darwin_clear_iterator (libusb_rem_device_iterator);
466 darwin_clear_iterator (libusb_add_device_iterator);
468 usbi_dbg ("darwin event thread ready to receive events");
470 /* signal the main thread that the hotplug runloop has been created. */
471 pthread_mutex_lock (&libusb_darwin_at_mutex);
472 libusb_darwin_acfl = runloop;
473 pthread_cond_signal (&libusb_darwin_at_cond);
474 pthread_mutex_unlock (&libusb_darwin_at_mutex);
476 /* run the runloop */
479 usbi_dbg ("darwin event thread exiting");
481 /* remove the notification cfsource */
482 CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
484 /* remove the shutdown cfsource */
485 CFRunLoopRemoveSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
487 /* delete notification port */
488 IONotificationPortDestroy (libusb_notification_port);
490 /* delete iterators */
491 IOObjectRelease (libusb_rem_device_iterator);
492 IOObjectRelease (libusb_add_device_iterator);
494 CFRelease (libusb_darwin_acfls);
497 libusb_darwin_acfls = NULL;
498 libusb_darwin_acfl = NULL;
503 /* cleanup function to destroy cached devices */
504 static void __attribute__((destructor)) _darwin_finalize(void) {
505 struct darwin_cached_device *dev, *next;
507 usbi_mutex_lock(&darwin_cached_devices_lock);
508 list_for_each_entry_safe(dev, next, &darwin_cached_devices, list, struct darwin_cached_device) {
509 darwin_deref_cached_device(dev);
511 usbi_mutex_unlock(&darwin_cached_devices_lock);
514 static void darwin_check_version (void) {
515 /* adjust for changes in the USB stack in xnu 15 */
516 int sysctl_args[] = {CTL_KERN, KERN_OSRELEASE};
518 char version_string[256] = {'\0',};
521 sysctl(sysctl_args, 2, version_string, &length, NULL, 0);
524 version = strtol (version_string, NULL, 10);
525 if (0 == errno && version >= 15) {
526 darwin_device_class = "IOUSBHostDevice";
530 static int darwin_init(struct libusb_context *ctx) {
533 rc = pthread_once (&darwin_init_once, darwin_check_version);
535 return LIBUSB_ERROR_OTHER;
538 rc = darwin_scan_devices (ctx);
539 if (LIBUSB_SUCCESS != rc) {
543 if (libusb_darwin_atomic_fetch_add (&initCount, 1) == 0) {
544 #if !OSX_USE_CLOCK_GETTIME
545 /* create the clocks that will be used if clock_gettime() is not available */
546 host_name_port_t host_self;
548 host_self = mach_host_self();
549 host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
550 host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
551 mach_port_deallocate(mach_task_self(), host_self);
554 pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, ctx);
556 pthread_mutex_lock (&libusb_darwin_at_mutex);
557 while (!libusb_darwin_acfl)
558 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
559 pthread_mutex_unlock (&libusb_darwin_at_mutex);
565 static void darwin_exit (struct libusb_context *ctx) {
567 if (libusb_darwin_atomic_fetch_add (&initCount, -1) == 1) {
568 #if !OSX_USE_CLOCK_GETTIME
569 mach_port_deallocate(mach_task_self(), clock_realtime);
570 mach_port_deallocate(mach_task_self(), clock_monotonic);
573 /* stop the event runloop and wait for the thread to terminate. */
574 CFRunLoopSourceSignal(libusb_darwin_acfls);
575 CFRunLoopWakeUp (libusb_darwin_acfl);
576 pthread_join (libusb_darwin_at, NULL);
580 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
581 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
583 /* return cached copy */
584 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
591 static int get_configuration_index (struct libusb_device *dev, int config_value) {
592 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
594 IOUSBConfigurationDescriptorPtr desc;
597 /* is there a simpler way to determine the index? */
598 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
599 if (kresult != kIOReturnSuccess)
600 return darwin_to_libusb (kresult);
602 for (i = 0 ; i < numConfig ; i++) {
603 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
605 if (desc->bConfigurationValue == config_value)
609 /* configuration not found */
610 return LIBUSB_ERROR_NOT_FOUND;
613 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
614 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
617 if (0 == priv->active_config)
618 return LIBUSB_ERROR_NOT_FOUND;
620 config_index = get_configuration_index (dev, priv->active_config);
621 if (config_index < 0)
624 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
627 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
628 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
629 IOUSBConfigurationDescriptorPtr desc;
633 if (!priv || !priv->device)
634 return LIBUSB_ERROR_OTHER;
636 kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
637 if (kresult == kIOReturnSuccess) {
638 /* copy descriptor */
639 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
640 len = libusb_le16_to_cpu(desc->wTotalLength);
642 memmove (buffer, desc, len);
644 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
648 ret = darwin_to_libusb (kresult);
649 if (ret != LIBUSB_SUCCESS)
655 /* check whether the os has configured the device */
656 static int darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) {
657 usb_device_t **darwin_device = dev->device;
659 IOUSBConfigurationDescriptorPtr configDesc;
660 IOUSBFindInterfaceRequest request;
661 kern_return_t kresult;
662 io_iterator_t interface_iterator;
663 io_service_t firstInterface;
665 if (dev->dev_descriptor.bNumConfigurations < 1) {
666 usbi_err (ctx, "device has no configurations");
667 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
670 /* checking the configuration of a root hub simulation takes ~1 s in 10.11. the device is
672 if (0x05ac == dev->dev_descriptor.idVendor && 0x8005 == dev->dev_descriptor.idProduct) {
673 usbi_dbg ("ignoring configuration on root hub simulation");
674 dev->active_config = 0;
678 /* find the first configuration */
679 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
680 dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
682 /* check if the device is already configured. there is probably a better way than iterating over the
683 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
684 might lock up on the device request) */
686 /* Setup the Interface Request */
687 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
688 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
689 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
690 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
692 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
694 return darwin_to_libusb (kresult);
697 firstInterface = IOIteratorNext(interface_iterator);
699 /* done with the interface iterator */
700 IOObjectRelease(interface_iterator);
702 if (firstInterface) {
703 IOObjectRelease (firstInterface);
705 /* device is configured */
706 if (dev->dev_descriptor.bNumConfigurations == 1)
707 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
708 dev->active_config = dev->first_config;
710 /* devices with more than one configuration should work with GetConfiguration */
711 (*darwin_device)->GetConfiguration (darwin_device, &dev->active_config);
714 dev->active_config = 0;
716 usbi_dbg ("active config: %u, first config: %u", dev->active_config, dev->first_config);
721 static int darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
722 IOUSBDevRequestTO req;
724 memset (buffer, 0, buffer_size);
726 /* Set up request for descriptor/ */
727 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
728 req.bRequest = kUSBRqGetDescriptor;
729 req.wValue = desc << 8;
730 req.wIndex = desc_index;
731 req.wLength = buffer_size;
733 req.noDataTimeout = 20;
734 req.completionTimeout = 100;
736 return (*device)->DeviceRequestTO (device, &req);
739 static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct darwin_cached_device *dev) {
740 usb_device_t **device = dev->device;
741 int retries = 1, delay = 30000;
742 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
746 UInt16 idProduct, idVendor;
748 dev->can_enumerate = 0;
750 (*device)->GetDeviceClass (device, &bDeviceClass);
751 (*device)->GetDeviceProduct (device, &idProduct);
752 (*device)->GetDeviceVendor (device, &idVendor);
754 /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
755 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
756 * to follow the spec as closely as possible, try opening the device */
757 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
760 /**** retrieve device descriptor ****/
761 ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &dev->dev_descriptor, sizeof(dev->dev_descriptor));
763 if (kIOReturnOverrun == ret && kUSBDeviceDesc == dev->dev_descriptor.bDescriptorType)
764 /* received an overrun error but we still received a device descriptor */
765 ret = kIOReturnSuccess;
767 if (kIOUSBVendorIDAppleComputer == idVendor) {
768 /* NTH: don't bother retrying or unsuspending Apple devices */
772 if (kIOReturnSuccess == ret && (0 == dev->dev_descriptor.bNumConfigurations ||
773 0 == dev->dev_descriptor.bcdUSB)) {
774 /* work around for incorrectly configured devices */
775 if (try_reconfigure && is_open) {
776 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
778 /* set the first configuration */
779 (*device)->SetConfiguration(device, 1);
781 /* don't try to reconfigure again */
785 ret = kIOUSBPipeStalled;
788 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
789 /* device may be suspended. unsuspend it and try again */
790 #if DeviceVersion >= 320
793 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
794 (void)(*device)->GetUSBDeviceInformation (device, &info);
796 /* note that the device was suspended */
797 if (info & (1 << kUSBInformationDeviceIsSuspendedBit) || 0 == info)
802 /* try to unsuspend the device */
803 ret2 = (*device)->USBDeviceSuspend (device, 0);
804 if (kIOReturnSuccess != ret2) {
805 /* prevent log spew from poorly behaving devices. this indicates the
806 os actually had trouble communicating with the device */
807 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
815 if (kIOReturnSuccess != ret) {
816 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
817 /* sleep for a little while before trying again */
818 nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000UL}, NULL);
820 } while (kIOReturnSuccess != ret && retries--);
823 /* resuspend the device */
824 (void)(*device)->USBDeviceSuspend (device, 1);
827 (void) (*device)->USBDeviceClose (device);
829 if (ret != kIOReturnSuccess) {
830 /* a debug message was already printed out for this error */
831 if (LIBUSB_CLASS_HUB == bDeviceClass)
832 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
833 idVendor, idProduct, darwin_error_str (ret), ret);
835 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
836 idVendor, idProduct, darwin_error_str (ret), ret);
837 return darwin_to_libusb (ret);
840 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
841 if (libusb_le16_to_cpu (dev->dev_descriptor.idProduct) != idProduct) {
842 /* not a valid device */
843 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
844 idProduct, libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
845 return LIBUSB_ERROR_NO_DEVICE;
848 usbi_dbg ("cached device descriptor:");
849 usbi_dbg (" bDescriptorType: 0x%02x", dev->dev_descriptor.bDescriptorType);
850 usbi_dbg (" bcdUSB: 0x%04x", dev->dev_descriptor.bcdUSB);
851 usbi_dbg (" bDeviceClass: 0x%02x", dev->dev_descriptor.bDeviceClass);
852 usbi_dbg (" bDeviceSubClass: 0x%02x", dev->dev_descriptor.bDeviceSubClass);
853 usbi_dbg (" bDeviceProtocol: 0x%02x", dev->dev_descriptor.bDeviceProtocol);
854 usbi_dbg (" bMaxPacketSize0: 0x%02x", dev->dev_descriptor.bMaxPacketSize0);
855 usbi_dbg (" idVendor: 0x%04x", dev->dev_descriptor.idVendor);
856 usbi_dbg (" idProduct: 0x%04x", dev->dev_descriptor.idProduct);
857 usbi_dbg (" bcdDevice: 0x%04x", dev->dev_descriptor.bcdDevice);
858 usbi_dbg (" iManufacturer: 0x%02x", dev->dev_descriptor.iManufacturer);
859 usbi_dbg (" iProduct: 0x%02x", dev->dev_descriptor.iProduct);
860 usbi_dbg (" iSerialNumber: 0x%02x", dev->dev_descriptor.iSerialNumber);
861 usbi_dbg (" bNumConfigurations: 0x%02x", dev->dev_descriptor.bNumConfigurations);
863 dev->can_enumerate = 1;
865 return LIBUSB_SUCCESS;
868 static int get_device_port (io_service_t service, UInt8 *port) {
869 kern_return_t result;
873 if (get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, port)) {
877 result = IORegistryEntryGetParentEntry (service, kIOServicePlane, &parent);
878 if (kIOReturnSuccess == result) {
879 ret = get_ioregistry_value_data (parent, CFSTR("port"), 1, port);
880 IOObjectRelease (parent);
886 static int get_device_parent_sessionID(io_service_t service, UInt64 *parent_sessionID) {
887 kern_return_t result;
890 /* Walk up the tree in the IOService plane until we find a parent that has a sessionID */
892 while((result = IORegistryEntryGetParentEntry (parent, kIOServicePlane, &parent)) == kIOReturnSuccess) {
893 if (get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, parent_sessionID)) {
899 /* We ran out of parents */
903 static int darwin_get_cached_device(struct libusb_context *ctx, io_service_t service,
904 struct darwin_cached_device **cached_out) {
905 struct darwin_cached_device *new_device;
906 UInt64 sessionID = 0, parent_sessionID = 0;
907 int ret = LIBUSB_SUCCESS;
908 usb_device_t **device;
911 /* get some info from the io registry */
912 (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
913 if (!get_device_port (service, &port)) {
914 usbi_dbg("could not get connected port number");
917 usbi_dbg("finding cached device for sessionID 0x%" PRIx64, sessionID);
919 if (get_device_parent_sessionID(service, &parent_sessionID)) {
920 usbi_dbg("parent sessionID: 0x%" PRIx64, parent_sessionID);
923 usbi_mutex_lock(&darwin_cached_devices_lock);
927 list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) {
928 usbi_dbg("matching sessionID 0x%" PRIx64 " against cached device with sessionID 0x%" PRIx64, sessionID, new_device->session);
929 if (new_device->session == sessionID) {
930 usbi_dbg("using cached device for device");
931 *cached_out = new_device;
939 usbi_dbg("caching new device with sessionID 0x%" PRIx64, sessionID);
941 device = darwin_device_from_service (service);
943 ret = LIBUSB_ERROR_NO_DEVICE;
947 new_device = calloc (1, sizeof (*new_device));
949 ret = LIBUSB_ERROR_NO_MEM;
953 /* add this device to the cached device list */
954 list_add(&new_device->list, &darwin_cached_devices);
956 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
958 /* keep a reference to this device */
959 darwin_ref_cached_device(new_device);
961 new_device->device = device;
962 new_device->session = sessionID;
963 (*device)->GetLocationID (device, &new_device->location);
964 new_device->port = port;
965 new_device->parent_session = parent_sessionID;
967 /* cache the device descriptor */
968 ret = darwin_cache_device_descriptor(ctx, new_device);
972 if (new_device->can_enumerate) {
973 snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address,
974 new_device->dev_descriptor.idVendor, new_device->dev_descriptor.idProduct,
975 new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass);
979 usbi_mutex_unlock(&darwin_cached_devices_lock);
981 /* keep track of devices regardless of if we successfully enumerate them to
982 prevent them from being enumerated multiple times */
984 *cached_out = new_device;
989 static int process_new_device (struct libusb_context *ctx, io_service_t service) {
990 struct darwin_device_priv *priv;
991 struct libusb_device *dev = NULL;
992 struct darwin_cached_device *cached_device;
997 ret = darwin_get_cached_device (ctx, service, &cached_device);
999 if (ret < 0 || !cached_device->can_enumerate) {
1003 /* check current active configuration (and cache the first configuration value--
1004 which may be used by claim_interface) */
1005 ret = darwin_check_configuration (ctx, cached_device);
1009 usbi_dbg ("allocating new device in context %p for with session 0x%" PRIx64,
1010 ctx, cached_device->session);
1012 dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
1014 return LIBUSB_ERROR_NO_MEM;
1017 priv = (struct darwin_device_priv *)dev->os_priv;
1019 priv->dev = cached_device;
1020 darwin_ref_cached_device (priv->dev);
1022 if (cached_device->parent_session > 0) {
1023 dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session);
1025 dev->parent_dev = NULL;
1027 dev->port_number = cached_device->port;
1028 dev->bus_number = cached_device->location >> 24;
1029 dev->device_address = cached_device->address;
1031 (*(priv->dev->device))->GetDeviceSpeed (priv->dev->device, &devSpeed);
1034 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
1035 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
1036 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
1037 #if DeviceVersion >= 500
1038 case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
1041 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
1044 ret = usbi_sanitize_device (dev);
1048 usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
1049 dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
1053 usbi_connect_device (dev);
1055 libusb_unref_device (dev);
1061 static int darwin_scan_devices(struct libusb_context *ctx) {
1062 io_iterator_t deviceIterator;
1063 io_service_t service;
1064 kern_return_t kresult;
1066 kresult = usb_setup_device_iterator (&deviceIterator, 0);
1067 if (kresult != kIOReturnSuccess)
1068 return darwin_to_libusb (kresult);
1070 while ((service = IOIteratorNext (deviceIterator))) {
1071 (void) process_new_device (ctx, service);
1073 IOObjectRelease(service);
1076 IOObjectRelease(deviceIterator);
1081 static int darwin_open (struct libusb_device_handle *dev_handle) {
1082 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1083 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1086 if (0 == dpriv->open_count) {
1087 /* try to open the device */
1088 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
1089 if (kresult != kIOReturnSuccess) {
1090 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
1092 if (kIOReturnExclusiveAccess != kresult) {
1093 return darwin_to_libusb (kresult);
1096 /* it is possible to perform some actions on a device that is not open so do not return an error */
1102 /* create async event source */
1103 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
1104 if (kresult != kIOReturnSuccess) {
1105 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
1107 if (priv->is_open) {
1108 (*(dpriv->device))->USBDeviceClose (dpriv->device);
1113 return darwin_to_libusb (kresult);
1116 CFRetain (libusb_darwin_acfl);
1118 /* add the cfSource to the aync run loop */
1119 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
1122 /* device opened successfully */
1123 dpriv->open_count++;
1125 usbi_dbg ("device open for access");
1130 static void darwin_close (struct libusb_device_handle *dev_handle) {
1131 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1132 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1136 if (dpriv->open_count == 0) {
1137 /* something is probably very wrong if this is the case */
1138 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!");
1142 dpriv->open_count--;
1144 /* make sure all interfaces are released */
1145 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1146 if (dev_handle->claimed_interfaces & (1 << i))
1147 libusb_release_interface (dev_handle, i);
1149 if (0 == dpriv->open_count) {
1150 /* delete the device's async event source */
1151 if (priv->cfSource) {
1152 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
1153 CFRelease (priv->cfSource);
1154 priv->cfSource = NULL;
1155 CFRelease (libusb_darwin_acfl);
1158 if (priv->is_open) {
1159 /* close the device */
1160 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
1162 /* Log the fact that we had a problem closing the file, however failing a
1163 * close isn't really an error, so return success anyway */
1164 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
1170 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
1171 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1173 *config = (int) dpriv->active_config;
1178 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
1179 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1183 /* Setting configuration will invalidate the interface, so we need
1184 to reclaim it. First, dispose of existing interfaces, if any. */
1185 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1186 if (dev_handle->claimed_interfaces & (1 << i))
1187 darwin_release_interface (dev_handle, i);
1189 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
1190 if (kresult != kIOReturnSuccess)
1191 return darwin_to_libusb (kresult);
1193 /* Reclaim any interfaces. */
1194 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1195 if (dev_handle->claimed_interfaces & (1 << i))
1196 darwin_claim_interface (dev_handle, i);
1198 dpriv->active_config = config;
1203 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
1204 IOUSBFindInterfaceRequest request;
1205 kern_return_t kresult;
1206 io_iterator_t interface_iterator;
1207 UInt8 bInterfaceNumber;
1210 *usbInterfacep = IO_OBJECT_NULL;
1212 /* Setup the Interface Request */
1213 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1214 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1215 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1216 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1218 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1222 while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1223 /* find the interface number */
1224 ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
1227 if (ret && bInterfaceNumber == ifc) {
1231 (void) IOObjectRelease (*usbInterfacep);
1234 /* done with the interface iterator */
1235 IOObjectRelease(interface_iterator);
1240 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
1241 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1243 /* current interface */
1244 struct darwin_interface *cInterface = &priv->interfaces[iface];
1246 kern_return_t kresult;
1248 u_int8_t numep, direction, number;
1249 u_int8_t dont_care1, dont_care3;
1250 u_int16_t dont_care2;
1253 usbi_dbg ("building table of endpoints.");
1255 /* retrieve the total number of endpoints on this interface */
1256 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1258 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1259 return darwin_to_libusb (kresult);
1262 /* iterate through pipe references */
1263 for (int i = 1 ; i <= numep ; i++) {
1264 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1265 &dont_care2, &dont_care3);
1267 if (kresult != kIOReturnSuccess) {
1268 /* probably a buggy device. try to get the endpoint address from the descriptors */
1269 struct libusb_config_descriptor *config;
1270 const struct libusb_endpoint_descriptor *endpoint_desc;
1273 kresult = (*(cInterface->interface))->GetAlternateSetting (cInterface->interface, &alt_setting);
1275 usbi_err (HANDLE_CTX (dev_handle), "can't get alternate setting for interface");
1276 return darwin_to_libusb (kresult);
1279 rc = libusb_get_active_config_descriptor (dev_handle->dev, &config);
1280 if (LIBUSB_SUCCESS != rc) {
1284 endpoint_desc = config->interface[iface].altsetting[alt_setting].endpoint + i - 1;
1286 cInterface->endpoint_addrs[i - 1] = endpoint_desc->bEndpointAddress;
1288 cInterface->endpoint_addrs[i - 1] = (((kUSBIn == direction) << kUSBRqDirnShift) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1291 usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, cInterface->endpoint_addrs[i - 1] >> kUSBRqDirnShift,
1292 cInterface->endpoint_addrs[i - 1] & LIBUSB_ENDPOINT_ADDRESS_MASK);
1295 cInterface->num_endpoints = numep;
1300 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1301 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1302 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1303 io_service_t usbInterface = IO_OBJECT_NULL;
1305 IOCFPlugInInterface **plugInInterface = NULL;
1308 /* current interface */
1309 struct darwin_interface *cInterface = &priv->interfaces[iface];
1311 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1312 if (kresult != kIOReturnSuccess)
1313 return darwin_to_libusb (kresult);
1315 /* make sure we have an interface */
1316 if (!usbInterface && dpriv->first_config != 0) {
1317 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1319 /* set the configuration */
1320 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1321 if (kresult != LIBUSB_SUCCESS) {
1322 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1326 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1328 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1329 return darwin_to_libusb (kresult);
1333 if (!usbInterface) {
1334 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1335 return LIBUSB_ERROR_NOT_FOUND;
1338 /* get an interface to the device's interface */
1339 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1340 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1342 /* ignore release error */
1343 (void)IOObjectRelease (usbInterface);
1346 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1347 return darwin_to_libusb (kresult);
1350 if (!plugInInterface) {
1351 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1352 return LIBUSB_ERROR_NOT_FOUND;
1355 /* Do the actual claim */
1356 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1357 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1358 (LPVOID)&cInterface->interface);
1359 /* We no longer need the intermediate plug-in */
1360 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1361 (*plugInInterface)->Release (plugInInterface);
1362 if (kresult || !cInterface->interface) {
1363 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1364 return darwin_to_libusb (kresult);
1367 /* claim the interface */
1368 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1370 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1371 return darwin_to_libusb (kresult);
1374 /* update list of endpoints */
1375 kresult = get_endpoints (dev_handle, iface);
1377 /* this should not happen */
1378 darwin_release_interface (dev_handle, iface);
1379 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1383 cInterface->cfSource = NULL;
1385 /* create async event source */
1386 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1387 if (kresult != kIOReturnSuccess) {
1388 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1390 /* can't continue without an async event source */
1391 (void)darwin_release_interface (dev_handle, iface);
1393 return darwin_to_libusb (kresult);
1396 /* add the cfSource to the async thread's run loop */
1397 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1399 usbi_dbg ("interface opened");
1404 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1405 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1408 /* current interface */
1409 struct darwin_interface *cInterface = &priv->interfaces[iface];
1411 /* Check to see if an interface is open */
1412 if (!cInterface->interface)
1413 return LIBUSB_SUCCESS;
1415 /* clean up endpoint data */
1416 cInterface->num_endpoints = 0;
1418 /* delete the interface's async event source */
1419 if (cInterface->cfSource) {
1420 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1421 CFRelease (cInterface->cfSource);
1424 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1426 usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1428 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1429 if (kresult != kIOReturnSuccess)
1430 usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1432 cInterface->interface = (usb_interface_t **) IO_OBJECT_NULL;
1434 return darwin_to_libusb (kresult);
1437 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1438 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1441 /* current interface */
1442 struct darwin_interface *cInterface = &priv->interfaces[iface];
1444 if (!cInterface->interface)
1445 return LIBUSB_ERROR_NO_DEVICE;
1447 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1448 if (kresult != kIOReturnSuccess)
1449 darwin_reset_device (dev_handle);
1451 /* update list of endpoints */
1452 kresult = get_endpoints (dev_handle, iface);
1454 /* this should not happen */
1455 darwin_release_interface (dev_handle, iface);
1456 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1460 return darwin_to_libusb (kresult);
1463 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1464 /* current interface */
1465 struct darwin_interface *cInterface;
1469 /* determine the interface/endpoint to use */
1470 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, NULL, &cInterface) != 0) {
1471 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1473 return LIBUSB_ERROR_NOT_FOUND;
1476 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1477 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1479 usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1481 return darwin_to_libusb (kresult);
1484 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1485 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1486 IOUSBDeviceDescriptor descriptor;
1487 IOUSBConfigurationDescriptorPtr cached_configuration;
1488 IOUSBConfigurationDescriptor configuration;
1489 bool reenumerate = false;
1493 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1495 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1496 return darwin_to_libusb (kresult);
1500 usbi_dbg ("darwin/reset_device: checking if device descriptor changed");
1502 /* ignore return code. if we can't get a descriptor it might be worthwhile re-enumerating anway */
1503 (void) darwin_request_descriptor (dpriv->device, kUSBDeviceDesc, 0, &descriptor, sizeof (descriptor));
1505 /* check if the device descriptor has changed */
1506 if (0 != memcmp (&dpriv->dev_descriptor, &descriptor, sizeof (descriptor))) {
1511 /* check if any configuration descriptor has changed */
1512 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1513 usbi_dbg ("darwin/reset_device: checking if configuration descriptor %d changed", i);
1515 (void) darwin_request_descriptor (dpriv->device, kUSBConfDesc, i, &configuration, sizeof (configuration));
1516 (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1518 if (!cached_configuration || 0 != memcmp (cached_configuration, &configuration, sizeof (configuration))) {
1526 usbi_dbg ("darwin/reset_device: device requires reenumeration");
1527 (void) (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
1528 return LIBUSB_ERROR_NOT_FOUND;
1531 usbi_dbg ("darwin/reset_device: device reset complete");
1533 return LIBUSB_SUCCESS;
1536 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1537 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1538 io_service_t usbInterface;
1542 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1544 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1546 return darwin_to_libusb (kresult);
1549 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1550 IOObjectRelease (usbInterface);
1562 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1563 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1566 return LIBUSB_ERROR_NOT_SUPPORTED;
1569 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1572 return LIBUSB_ERROR_NOT_SUPPORTED;
1575 static void darwin_destroy_device(struct libusb_device *dev) {
1576 struct darwin_device_priv *dpriv = (struct darwin_device_priv *) dev->os_priv;
1579 /* need to hold the lock in case this is the last reference to the device */
1580 usbi_mutex_lock(&darwin_cached_devices_lock);
1581 darwin_deref_cached_device (dpriv->dev);
1583 usbi_mutex_unlock(&darwin_cached_devices_lock);
1587 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1588 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1591 uint8_t transferType;
1592 /* None of the values below are used in libusbx for bulk transfers */
1593 uint8_t direction, number, interval, pipeRef;
1594 uint16_t maxPacketSize;
1596 struct darwin_interface *cInterface;
1598 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1599 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1601 return LIBUSB_ERROR_NOT_FOUND;
1604 ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1605 &transferType, &maxPacketSize, &interval);
1608 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1609 darwin_error_str(ret), ret);
1610 return darwin_to_libusb (ret);
1613 if (0 != (transfer->length % maxPacketSize)) {
1614 /* do not need a zero packet */
1615 transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1618 /* submit the request */
1619 /* timeouts are unavailable on interrupt endpoints */
1620 if (transferType == kUSBInterrupt) {
1621 if (IS_XFERIN(transfer))
1622 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1623 transfer->length, darwin_async_io_callback, itransfer);
1625 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1626 transfer->length, darwin_async_io_callback, itransfer);
1628 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1630 if (IS_XFERIN(transfer))
1631 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1632 transfer->length, transfer->timeout, transfer->timeout,
1633 darwin_async_io_callback, (void *)itransfer);
1635 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1636 transfer->length, transfer->timeout, transfer->timeout,
1637 darwin_async_io_callback, (void *)itransfer);
1641 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1642 darwin_error_str(ret), ret);
1644 return darwin_to_libusb (ret);
1647 #if InterfaceVersion >= 550
1648 static int submit_stream_transfer(struct usbi_transfer *itransfer) {
1649 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1650 struct darwin_interface *cInterface;
1654 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1655 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1657 return LIBUSB_ERROR_NOT_FOUND;
1660 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1662 if (IS_XFERIN(transfer))
1663 ret = (*(cInterface->interface))->ReadStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1664 transfer->buffer, transfer->length, transfer->timeout,
1665 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1667 ret = (*(cInterface->interface))->WriteStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1668 transfer->buffer, transfer->length, transfer->timeout,
1669 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1672 usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1673 darwin_error_str(ret), ret);
1675 return darwin_to_libusb (ret);
1679 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1680 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1681 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1684 uint8_t direction, number, interval, pipeRef, transferType;
1685 uint16_t maxPacketSize;
1687 AbsoluteTime atTime;
1690 struct darwin_interface *cInterface;
1692 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1693 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1694 free(tpriv->isoc_framelist);
1695 tpriv->isoc_framelist = NULL;
1698 if (!tpriv->isoc_framelist) {
1699 tpriv->num_iso_packets = transfer->num_iso_packets;
1700 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1701 if (!tpriv->isoc_framelist)
1702 return LIBUSB_ERROR_NO_MEM;
1705 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1706 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1707 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1709 /* determine the interface/endpoint to use */
1710 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1711 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1713 return LIBUSB_ERROR_NOT_FOUND;
1716 /* determine the properties of this endpoint and the speed of the device */
1717 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1718 &transferType, &maxPacketSize, &interval);
1720 /* Last but not least we need the bus frame number */
1721 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1723 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1724 free(tpriv->isoc_framelist);
1725 tpriv->isoc_framelist = NULL;
1727 return darwin_to_libusb (kresult);
1730 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1731 &transferType, &maxPacketSize, &interval);
1733 /* schedule for a frame a little in the future */
1736 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1737 frame = cInterface->frames[transfer->endpoint];
1739 /* submit the request */
1740 if (IS_XFERIN(transfer))
1741 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1742 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1745 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1746 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1749 if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
1751 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1));
1753 /* High/super speed */
1754 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1)) / 8;
1756 if (kresult != kIOReturnSuccess) {
1757 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1758 darwin_error_str(kresult));
1759 free (tpriv->isoc_framelist);
1760 tpriv->isoc_framelist = NULL;
1763 return darwin_to_libusb (kresult);
1766 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1767 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1768 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1769 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1770 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1774 memset(&tpriv->req, 0, sizeof(tpriv->req));
1776 /* IOUSBDeviceInterface expects the request in cpu endianness */
1777 tpriv->req.bmRequestType = setup->bmRequestType;
1778 tpriv->req.bRequest = setup->bRequest;
1779 /* these values should be in bus order from libusb_fill_control_setup */
1780 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1781 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1782 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1783 /* data is stored after the libusb control block */
1784 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1785 tpriv->req.completionTimeout = transfer->timeout;
1786 tpriv->req.noDataTimeout = transfer->timeout;
1788 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1790 /* all transfers in libusb-1.0 are async */
1792 if (transfer->endpoint) {
1793 struct darwin_interface *cInterface;
1796 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1797 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1799 return LIBUSB_ERROR_NOT_FOUND;
1802 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1804 /* control request on endpoint 0 */
1805 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1807 if (kresult != kIOReturnSuccess)
1808 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1810 return darwin_to_libusb (kresult);
1813 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1814 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1816 switch (transfer->type) {
1817 case LIBUSB_TRANSFER_TYPE_CONTROL:
1818 return submit_control_transfer(itransfer);
1819 case LIBUSB_TRANSFER_TYPE_BULK:
1820 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1821 return submit_bulk_transfer(itransfer);
1822 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1823 return submit_iso_transfer(itransfer);
1824 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1825 #if InterfaceVersion >= 550
1826 return submit_stream_transfer(itransfer);
1828 usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers");
1829 return LIBUSB_ERROR_NOT_SUPPORTED;
1832 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1833 return LIBUSB_ERROR_INVALID_PARAM;
1837 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1838 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1839 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1842 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
1845 return LIBUSB_ERROR_NO_DEVICE;
1847 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1849 return darwin_to_libusb (kresult);
1852 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1853 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1854 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1855 struct darwin_interface *cInterface;
1856 uint8_t pipeRef, iface;
1859 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) {
1860 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1862 return LIBUSB_ERROR_NOT_FOUND;
1866 return LIBUSB_ERROR_NO_DEVICE;
1868 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
1870 /* abort transactions */
1871 #if InterfaceVersion >= 550
1872 if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type)
1873 (*(cInterface->interface))->AbortStreamsPipe (cInterface->interface, pipeRef, itransfer->stream_id);
1876 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1878 usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
1880 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1881 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1883 return darwin_to_libusb (kresult);
1886 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1887 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1889 switch (transfer->type) {
1890 case LIBUSB_TRANSFER_TYPE_CONTROL:
1891 return cancel_control_transfer(itransfer);
1892 case LIBUSB_TRANSFER_TYPE_BULK:
1893 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1894 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1895 return darwin_abort_transfers (itransfer);
1897 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1898 return LIBUSB_ERROR_INVALID_PARAM;
1902 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1903 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1904 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1906 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1907 free (tpriv->isoc_framelist);
1908 tpriv->isoc_framelist = NULL;
1912 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1913 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1914 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1915 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1917 usbi_dbg ("an async io operation has completed");
1919 /* if requested write a zero packet */
1920 if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
1921 struct darwin_interface *cInterface;
1924 (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface);
1926 (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
1929 tpriv->result = result;
1930 tpriv->size = (UInt32) (uintptr_t) arg0;
1932 /* signal the core that this transfer is complete */
1933 usbi_signal_transfer_completion(itransfer);
1936 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1937 if (itransfer->timeout_flags & USBI_TRANSFER_TIMED_OUT)
1938 result = kIOUSBTransactionTimeout;
1941 case kIOReturnUnderrun:
1942 case kIOReturnSuccess:
1943 return LIBUSB_TRANSFER_COMPLETED;
1944 case kIOReturnAborted:
1945 return LIBUSB_TRANSFER_CANCELLED;
1946 case kIOUSBPipeStalled:
1947 usbi_dbg ("transfer error: pipe is stalled");
1948 return LIBUSB_TRANSFER_STALL;
1949 case kIOReturnOverrun:
1950 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1951 return LIBUSB_TRANSFER_OVERFLOW;
1952 case kIOUSBTransactionTimeout:
1953 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1954 itransfer->timeout_flags |= USBI_TRANSFER_TIMED_OUT;
1955 return LIBUSB_TRANSFER_TIMED_OUT;
1957 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1958 return LIBUSB_TRANSFER_ERROR;
1962 static int darwin_handle_transfer_completion (struct usbi_transfer *itransfer) {
1963 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1964 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1965 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1966 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1967 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1968 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1971 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1972 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1973 return LIBUSB_ERROR_INVALID_PARAM;
1976 usbi_dbg ("handling %s completion with kernel status %d",
1977 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", tpriv->result);
1979 if (kIOReturnSuccess == tpriv->result || kIOReturnUnderrun == tpriv->result) {
1980 if (isIsoc && tpriv->isoc_framelist) {
1981 /* copy isochronous results back */
1983 for (i = 0; i < transfer->num_iso_packets ; i++) {
1984 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1985 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1986 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1989 itransfer->transferred += tpriv->size;
1992 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1993 return usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, tpriv->result));
1996 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1997 #if !OSX_USE_CLOCK_GETTIME
1998 mach_timespec_t sys_time;
1999 clock_serv_t clock_ref;
2002 case USBI_CLOCK_REALTIME:
2003 /* CLOCK_REALTIME represents time since the epoch */
2004 clock_ref = clock_realtime;
2006 case USBI_CLOCK_MONOTONIC:
2007 /* use system boot time as reference for the monotonic clock */
2008 clock_ref = clock_monotonic;
2011 return LIBUSB_ERROR_INVALID_PARAM;
2014 clock_get_time (clock_ref, &sys_time);
2016 tp->tv_sec = sys_time.tv_sec;
2017 tp->tv_nsec = sys_time.tv_nsec;
2022 case USBI_CLOCK_MONOTONIC:
2023 return clock_gettime(CLOCK_MONOTONIC, tp);
2024 case USBI_CLOCK_REALTIME:
2025 return clock_gettime(CLOCK_REALTIME, tp);
2027 return LIBUSB_ERROR_INVALID_PARAM;
2032 #if InterfaceVersion >= 550
2033 static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints,
2034 int num_endpoints) {
2035 struct darwin_interface *cInterface;
2036 UInt32 supportsStreams;
2040 /* find the mimimum number of supported streams on the endpoint list */
2041 for (i = 0 ; i < num_endpoints ; ++i) {
2042 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) {
2046 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2047 if (num_streams > supportsStreams)
2048 num_streams = supportsStreams;
2051 /* it is an error if any endpoint in endpoints does not support streams */
2052 if (0 == num_streams)
2053 return LIBUSB_ERROR_INVALID_PARAM;
2055 /* create the streams */
2056 for (i = 0 ; i < num_endpoints ; ++i) {
2057 (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
2059 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, num_streams);
2060 if (kIOReturnSuccess != rc)
2061 return darwin_to_libusb(rc);
2067 static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) {
2068 struct darwin_interface *cInterface;
2069 UInt32 supportsStreams;
2073 for (int i = 0 ; i < num_endpoints ; ++i) {
2074 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface)))
2077 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2078 if (0 == supportsStreams)
2079 return LIBUSB_ERROR_INVALID_PARAM;
2081 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, 0);
2082 if (kIOReturnSuccess != rc)
2083 return darwin_to_libusb(rc);
2086 return LIBUSB_SUCCESS;
2090 const struct usbi_os_backend usbi_backend = {
2093 .init = darwin_init,
2094 .exit = darwin_exit,
2095 .get_device_list = NULL, /* not needed */
2096 .get_device_descriptor = darwin_get_device_descriptor,
2097 .get_active_config_descriptor = darwin_get_active_config_descriptor,
2098 .get_config_descriptor = darwin_get_config_descriptor,
2099 .hotplug_poll = darwin_hotplug_poll,
2101 .open = darwin_open,
2102 .close = darwin_close,
2103 .get_configuration = darwin_get_configuration,
2104 .set_configuration = darwin_set_configuration,
2105 .claim_interface = darwin_claim_interface,
2106 .release_interface = darwin_release_interface,
2108 .set_interface_altsetting = darwin_set_interface_altsetting,
2109 .clear_halt = darwin_clear_halt,
2110 .reset_device = darwin_reset_device,
2112 #if InterfaceVersion >= 550
2113 .alloc_streams = darwin_alloc_streams,
2114 .free_streams = darwin_free_streams,
2117 .kernel_driver_active = darwin_kernel_driver_active,
2118 .detach_kernel_driver = darwin_detach_kernel_driver,
2119 .attach_kernel_driver = darwin_attach_kernel_driver,
2121 .destroy_device = darwin_destroy_device,
2123 .submit_transfer = darwin_submit_transfer,
2124 .cancel_transfer = darwin_cancel_transfer,
2125 .clear_transfer_priv = darwin_clear_transfer_priv,
2127 .handle_transfer_completion = darwin_handle_transfer_completion,
2129 .clock_gettime = darwin_clock_gettime,
2131 .device_priv_size = sizeof(struct darwin_device_priv),
2132 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
2133 .transfer_priv_size = sizeof(struct darwin_transfer_priv),