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 const 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) {
309 struct libusb_context *ctx;
310 io_service_t service;
312 usbi_mutex_lock(&active_contexts_lock);
314 while ((service = IOIteratorNext(add_devices))) {
315 /* add this device to each active context's device list */
316 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
317 process_new_device (ctx, service);
320 IOObjectRelease(service);
323 usbi_mutex_unlock(&active_contexts_lock);
326 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
328 struct libusb_device *dev = NULL;
329 struct libusb_context *ctx;
330 struct darwin_cached_device *old_device;
336 usbi_mutex_lock(&active_contexts_lock);
338 while ((device = IOIteratorNext (rem_devices)) != 0) {
339 /* get the location from the i/o registry */
340 ret = get_ioregistry_value_number (device, CFSTR("sessionID"), kCFNumberSInt64Type, &session);
341 IOObjectRelease (device);
345 /* we need to match darwin_ref_cached_device call made in darwin_get_cached_device function
346 otherwise no cached device will ever get freed */
347 usbi_mutex_lock(&darwin_cached_devices_lock);
348 list_for_each_entry(old_device, &darwin_cached_devices, list, struct darwin_cached_device) {
349 if (old_device->session == session) {
350 darwin_deref_cached_device (old_device);
354 usbi_mutex_unlock(&darwin_cached_devices_lock);
356 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
357 usbi_dbg ("notifying context %p of device disconnect", ctx);
359 dev = usbi_get_device_by_session_id(ctx, (unsigned long) session);
361 /* signal the core that this device has been disconnected. the core will tear down this device
362 when the reference count reaches 0 */
363 usbi_disconnect_device(dev);
364 libusb_unref_device(dev);
369 usbi_mutex_unlock(&active_contexts_lock);
372 static void darwin_hotplug_poll (void)
374 /* not sure if 5 seconds will be too long/short but it should work ok */
375 mach_timespec_t timeout = {.tv_sec = 5, .tv_nsec = 0};
377 /* since a kernel thread may nodify the IOInterators used for
378 * hotplug notidication we can't just clear the iterators.
379 * instead just wait until all IOService providers are quiet */
380 (void) IOKitWaitQuiet (kIOMasterPortDefault, &timeout);
383 static void darwin_clear_iterator (io_iterator_t iter) {
386 while ((device = IOIteratorNext (iter)) != 0)
387 IOObjectRelease (device);
390 static void *darwin_event_thread_main (void *arg0) {
392 struct libusb_context *ctx = (struct libusb_context *)arg0;
393 CFRunLoopRef runloop;
395 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
396 /* Set this thread's name, so it can be seen in the debugger
397 and crash reports. */
398 pthread_setname_np ("org.libusb.device-hotplug");
401 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
402 /* Tell the Objective-C garbage collector about this thread.
403 This is required because, unlike NSThreads, pthreads are
404 not automatically registered. Although we don't use
405 Objective-C, we use CoreFoundation, which does.
406 Garbage collection support was entirely removed in 10.12,
407 so don't bother there. */
408 objc_registerThreadWithCollector();
411 /* hotplug (device arrival/removal) sources */
412 CFRunLoopSourceContext libusb_shutdown_cfsourcectx;
413 CFRunLoopSourceRef libusb_notification_cfsource;
414 io_notification_port_t libusb_notification_port;
415 io_iterator_t libusb_rem_device_iterator;
416 io_iterator_t libusb_add_device_iterator;
418 usbi_dbg ("creating hotplug event source");
420 runloop = CFRunLoopGetCurrent ();
423 /* add the shutdown cfsource to the run loop */
424 memset(&libusb_shutdown_cfsourcectx, 0, sizeof(libusb_shutdown_cfsourcectx));
425 libusb_shutdown_cfsourcectx.info = runloop;
426 libusb_shutdown_cfsourcectx.perform = (void (*)(void *))CFRunLoopStop;
427 libusb_darwin_acfls = CFRunLoopSourceCreate(NULL, 0, &libusb_shutdown_cfsourcectx);
428 CFRunLoopAddSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
430 /* add the notification port to the run loop */
431 libusb_notification_port = IONotificationPortCreate (kIOMasterPortDefault);
432 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
433 CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
435 /* create notifications for removed devices */
436 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
437 IOServiceMatching(darwin_device_class),
438 darwin_devices_detached,
439 ctx, &libusb_rem_device_iterator);
441 if (kresult != kIOReturnSuccess) {
442 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
447 /* create notifications for attached devices */
448 kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
449 IOServiceMatching(darwin_device_class),
450 darwin_devices_attached,
451 ctx, &libusb_add_device_iterator);
453 if (kresult != kIOReturnSuccess) {
454 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
460 darwin_clear_iterator (libusb_rem_device_iterator);
461 darwin_clear_iterator (libusb_add_device_iterator);
463 usbi_dbg ("darwin event thread ready to receive events");
465 /* signal the main thread that the hotplug runloop has been created. */
466 pthread_mutex_lock (&libusb_darwin_at_mutex);
467 libusb_darwin_acfl = runloop;
468 pthread_cond_signal (&libusb_darwin_at_cond);
469 pthread_mutex_unlock (&libusb_darwin_at_mutex);
471 /* run the runloop */
474 usbi_dbg ("darwin event thread exiting");
476 /* remove the notification cfsource */
477 CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
479 /* remove the shutdown cfsource */
480 CFRunLoopRemoveSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
482 /* delete notification port */
483 IONotificationPortDestroy (libusb_notification_port);
485 /* delete iterators */
486 IOObjectRelease (libusb_rem_device_iterator);
487 IOObjectRelease (libusb_add_device_iterator);
489 CFRelease (libusb_darwin_acfls);
492 libusb_darwin_acfls = NULL;
493 libusb_darwin_acfl = NULL;
498 /* cleanup function to destroy cached devices */
499 static void __attribute__((destructor)) _darwin_finalize(void) {
500 struct darwin_cached_device *dev, *next;
502 usbi_mutex_lock(&darwin_cached_devices_lock);
503 list_for_each_entry_safe(dev, next, &darwin_cached_devices, list, struct darwin_cached_device) {
504 darwin_deref_cached_device(dev);
506 usbi_mutex_unlock(&darwin_cached_devices_lock);
509 static void darwin_check_version (void) {
510 /* adjust for changes in the USB stack in xnu 15 */
511 int sysctl_args[] = {CTL_KERN, KERN_OSRELEASE};
513 char version_string[256] = {'\0',};
516 sysctl(sysctl_args, 2, version_string, &length, NULL, 0);
519 version = strtol (version_string, NULL, 10);
520 if (0 == errno && version >= 15) {
521 darwin_device_class = "IOUSBHostDevice";
525 static int darwin_init(struct libusb_context *ctx) {
528 rc = pthread_once (&darwin_init_once, darwin_check_version);
530 return LIBUSB_ERROR_OTHER;
533 rc = darwin_scan_devices (ctx);
534 if (LIBUSB_SUCCESS != rc) {
538 if (libusb_darwin_atomic_fetch_add (&initCount, 1) == 0) {
539 #if !OSX_USE_CLOCK_GETTIME
540 /* create the clocks that will be used if clock_gettime() is not available */
541 host_name_port_t host_self;
543 host_self = mach_host_self();
544 host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
545 host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
546 mach_port_deallocate(mach_task_self(), host_self);
549 pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, ctx);
551 pthread_mutex_lock (&libusb_darwin_at_mutex);
552 while (!libusb_darwin_acfl)
553 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
554 pthread_mutex_unlock (&libusb_darwin_at_mutex);
560 static void darwin_exit (struct libusb_context *ctx) {
562 if (libusb_darwin_atomic_fetch_add (&initCount, -1) == 1) {
563 #if !OSX_USE_CLOCK_GETTIME
564 mach_port_deallocate(mach_task_self(), clock_realtime);
565 mach_port_deallocate(mach_task_self(), clock_monotonic);
568 /* stop the event runloop and wait for the thread to terminate. */
569 CFRunLoopSourceSignal(libusb_darwin_acfls);
570 CFRunLoopWakeUp (libusb_darwin_acfl);
571 pthread_join (libusb_darwin_at, NULL);
575 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
576 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
578 /* return cached copy */
579 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
586 static int get_configuration_index (struct libusb_device *dev, int config_value) {
587 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
589 IOUSBConfigurationDescriptorPtr desc;
592 /* is there a simpler way to determine the index? */
593 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
594 if (kresult != kIOReturnSuccess)
595 return darwin_to_libusb (kresult);
597 for (i = 0 ; i < numConfig ; i++) {
598 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
600 if (desc->bConfigurationValue == config_value)
604 /* configuration not found */
605 return LIBUSB_ERROR_NOT_FOUND;
608 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
609 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
612 if (0 == priv->active_config)
613 return LIBUSB_ERROR_NOT_FOUND;
615 config_index = get_configuration_index (dev, priv->active_config);
616 if (config_index < 0)
619 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
622 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
623 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
624 IOUSBConfigurationDescriptorPtr desc;
628 if (!priv || !priv->device)
629 return LIBUSB_ERROR_OTHER;
631 kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
632 if (kresult == kIOReturnSuccess) {
633 /* copy descriptor */
634 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
635 len = libusb_le16_to_cpu(desc->wTotalLength);
637 memmove (buffer, desc, len);
639 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
643 ret = darwin_to_libusb (kresult);
644 if (ret != LIBUSB_SUCCESS)
650 /* check whether the os has configured the device */
651 static int darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) {
652 usb_device_t **darwin_device = dev->device;
654 IOUSBConfigurationDescriptorPtr configDesc;
655 IOUSBFindInterfaceRequest request;
656 kern_return_t kresult;
657 io_iterator_t interface_iterator;
658 io_service_t firstInterface;
660 if (dev->dev_descriptor.bNumConfigurations < 1) {
661 usbi_err (ctx, "device has no configurations");
662 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
665 /* checking the configuration of a root hub simulation takes ~1 s in 10.11. the device is
667 if (0x05ac == dev->dev_descriptor.idVendor && 0x8005 == dev->dev_descriptor.idProduct) {
668 usbi_dbg ("ignoring configuration on root hub simulation");
669 dev->active_config = 0;
673 /* find the first configuration */
674 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
675 dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
677 /* check if the device is already configured. there is probably a better way than iterating over the
678 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
679 might lock up on the device request) */
681 /* Setup the Interface Request */
682 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
683 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
684 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
685 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
687 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
689 return darwin_to_libusb (kresult);
692 firstInterface = IOIteratorNext(interface_iterator);
694 /* done with the interface iterator */
695 IOObjectRelease(interface_iterator);
697 if (firstInterface) {
698 IOObjectRelease (firstInterface);
700 /* device is configured */
701 if (dev->dev_descriptor.bNumConfigurations == 1)
702 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
703 dev->active_config = dev->first_config;
705 /* devices with more than one configuration should work with GetConfiguration */
706 (*darwin_device)->GetConfiguration (darwin_device, &dev->active_config);
709 dev->active_config = 0;
711 usbi_dbg ("active config: %u, first config: %u", dev->active_config, dev->first_config);
716 static int darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
717 IOUSBDevRequestTO req;
719 memset (buffer, 0, buffer_size);
721 /* Set up request for descriptor/ */
722 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
723 req.bRequest = kUSBRqGetDescriptor;
724 req.wValue = desc << 8;
725 req.wIndex = desc_index;
726 req.wLength = buffer_size;
728 req.noDataTimeout = 20;
729 req.completionTimeout = 100;
731 return (*device)->DeviceRequestTO (device, &req);
734 static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct darwin_cached_device *dev) {
735 usb_device_t **device = dev->device;
736 int retries = 1, delay = 30000;
737 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
741 UInt16 idProduct, idVendor;
743 dev->can_enumerate = 0;
745 (*device)->GetDeviceClass (device, &bDeviceClass);
746 (*device)->GetDeviceProduct (device, &idProduct);
747 (*device)->GetDeviceVendor (device, &idVendor);
749 /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
750 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
751 * to follow the spec as closely as possible, try opening the device */
752 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
755 /**** retrieve device descriptor ****/
756 ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &dev->dev_descriptor, sizeof(dev->dev_descriptor));
758 if (kIOReturnOverrun == ret && kUSBDeviceDesc == dev->dev_descriptor.bDescriptorType)
759 /* received an overrun error but we still received a device descriptor */
760 ret = kIOReturnSuccess;
762 if (kIOUSBVendorIDAppleComputer == idVendor) {
763 /* NTH: don't bother retrying or unsuspending Apple devices */
767 if (kIOReturnSuccess == ret && (0 == dev->dev_descriptor.bNumConfigurations ||
768 0 == dev->dev_descriptor.bcdUSB)) {
769 /* work around for incorrectly configured devices */
770 if (try_reconfigure && is_open) {
771 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
773 /* set the first configuration */
774 (*device)->SetConfiguration(device, 1);
776 /* don't try to reconfigure again */
780 ret = kIOUSBPipeStalled;
783 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
784 /* device may be suspended. unsuspend it and try again */
785 #if DeviceVersion >= 320
788 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
789 (void)(*device)->GetUSBDeviceInformation (device, &info);
791 /* note that the device was suspended */
792 if (info & (1 << kUSBInformationDeviceIsSuspendedBit) || 0 == info)
797 /* try to unsuspend the device */
798 ret2 = (*device)->USBDeviceSuspend (device, 0);
799 if (kIOReturnSuccess != ret2) {
800 /* prevent log spew from poorly behaving devices. this indicates the
801 os actually had trouble communicating with the device */
802 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
810 if (kIOReturnSuccess != ret) {
811 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
812 /* sleep for a little while before trying again */
813 nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000UL}, NULL);
815 } while (kIOReturnSuccess != ret && retries--);
818 /* resuspend the device */
819 (void)(*device)->USBDeviceSuspend (device, 1);
822 (void) (*device)->USBDeviceClose (device);
824 if (ret != kIOReturnSuccess) {
825 /* a debug message was already printed out for this error */
826 if (LIBUSB_CLASS_HUB == bDeviceClass)
827 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
828 idVendor, idProduct, darwin_error_str (ret), ret);
830 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
831 idVendor, idProduct, darwin_error_str (ret), ret);
832 return darwin_to_libusb (ret);
835 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
836 if (libusb_le16_to_cpu (dev->dev_descriptor.idProduct) != idProduct) {
837 /* not a valid device */
838 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
839 idProduct, libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
840 return LIBUSB_ERROR_NO_DEVICE;
843 usbi_dbg ("cached device descriptor:");
844 usbi_dbg (" bDescriptorType: 0x%02x", dev->dev_descriptor.bDescriptorType);
845 usbi_dbg (" bcdUSB: 0x%04x", dev->dev_descriptor.bcdUSB);
846 usbi_dbg (" bDeviceClass: 0x%02x", dev->dev_descriptor.bDeviceClass);
847 usbi_dbg (" bDeviceSubClass: 0x%02x", dev->dev_descriptor.bDeviceSubClass);
848 usbi_dbg (" bDeviceProtocol: 0x%02x", dev->dev_descriptor.bDeviceProtocol);
849 usbi_dbg (" bMaxPacketSize0: 0x%02x", dev->dev_descriptor.bMaxPacketSize0);
850 usbi_dbg (" idVendor: 0x%04x", dev->dev_descriptor.idVendor);
851 usbi_dbg (" idProduct: 0x%04x", dev->dev_descriptor.idProduct);
852 usbi_dbg (" bcdDevice: 0x%04x", dev->dev_descriptor.bcdDevice);
853 usbi_dbg (" iManufacturer: 0x%02x", dev->dev_descriptor.iManufacturer);
854 usbi_dbg (" iProduct: 0x%02x", dev->dev_descriptor.iProduct);
855 usbi_dbg (" iSerialNumber: 0x%02x", dev->dev_descriptor.iSerialNumber);
856 usbi_dbg (" bNumConfigurations: 0x%02x", dev->dev_descriptor.bNumConfigurations);
858 dev->can_enumerate = 1;
860 return LIBUSB_SUCCESS;
863 static int get_device_port (io_service_t service, UInt8 *port) {
864 kern_return_t result;
868 if (get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, port)) {
872 result = IORegistryEntryGetParentEntry (service, kIOServicePlane, &parent);
873 if (kIOReturnSuccess == result) {
874 ret = get_ioregistry_value_data (parent, CFSTR("port"), 1, port);
875 IOObjectRelease (parent);
881 static int get_device_parent_sessionID(io_service_t service, UInt64 *parent_sessionID) {
882 kern_return_t result;
885 /* Walk up the tree in the IOService plane until we find a parent that has a sessionID */
887 while((result = IORegistryEntryGetParentEntry (parent, kIOServicePlane, &parent)) == kIOReturnSuccess) {
888 if (get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, parent_sessionID)) {
894 /* We ran out of parents */
898 static int darwin_get_cached_device(struct libusb_context *ctx, io_service_t service,
899 struct darwin_cached_device **cached_out) {
900 struct darwin_cached_device *new_device;
901 UInt64 sessionID = 0, parent_sessionID = 0;
902 int ret = LIBUSB_SUCCESS;
903 usb_device_t **device;
906 /* get some info from the io registry */
907 (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
908 if (!get_device_port (service, &port)) {
909 usbi_dbg("could not get connected port number");
912 usbi_dbg("finding cached device for sessionID 0x%" PRIx64, sessionID);
914 if (get_device_parent_sessionID(service, &parent_sessionID)) {
915 usbi_dbg("parent sessionID: 0x%" PRIx64, parent_sessionID);
918 usbi_mutex_lock(&darwin_cached_devices_lock);
922 list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) {
923 usbi_dbg("matching sessionID 0x%" PRIx64 " against cached device with sessionID 0x%" PRIx64, sessionID, new_device->session);
924 if (new_device->session == sessionID) {
925 usbi_dbg("using cached device for device");
926 *cached_out = new_device;
934 usbi_dbg("caching new device with sessionID 0x%" PRIx64, sessionID);
936 device = darwin_device_from_service (service);
938 ret = LIBUSB_ERROR_NO_DEVICE;
942 new_device = calloc (1, sizeof (*new_device));
944 ret = LIBUSB_ERROR_NO_MEM;
948 /* add this device to the cached device list */
949 list_add(&new_device->list, &darwin_cached_devices);
951 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
953 /* keep a reference to this device */
954 darwin_ref_cached_device(new_device);
956 new_device->device = device;
957 new_device->session = sessionID;
958 (*device)->GetLocationID (device, &new_device->location);
959 new_device->port = port;
960 new_device->parent_session = parent_sessionID;
962 /* cache the device descriptor */
963 ret = darwin_cache_device_descriptor(ctx, new_device);
967 if (new_device->can_enumerate) {
968 snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address,
969 new_device->dev_descriptor.idVendor, new_device->dev_descriptor.idProduct,
970 new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass);
974 usbi_mutex_unlock(&darwin_cached_devices_lock);
976 /* keep track of devices regardless of if we successfully enumerate them to
977 prevent them from being enumerated multiple times */
979 *cached_out = new_device;
984 static int process_new_device (struct libusb_context *ctx, io_service_t service) {
985 struct darwin_device_priv *priv;
986 struct libusb_device *dev = NULL;
987 struct darwin_cached_device *cached_device;
992 ret = darwin_get_cached_device (ctx, service, &cached_device);
994 if (ret < 0 || !cached_device->can_enumerate) {
998 /* check current active configuration (and cache the first configuration value--
999 which may be used by claim_interface) */
1000 ret = darwin_check_configuration (ctx, cached_device);
1004 usbi_dbg ("allocating new device in context %p for with session 0x%" PRIx64,
1005 ctx, cached_device->session);
1007 dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
1009 return LIBUSB_ERROR_NO_MEM;
1012 priv = (struct darwin_device_priv *)dev->os_priv;
1014 priv->dev = cached_device;
1015 darwin_ref_cached_device (priv->dev);
1017 if (cached_device->parent_session > 0) {
1018 dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session);
1020 dev->parent_dev = NULL;
1022 dev->port_number = cached_device->port;
1023 dev->bus_number = cached_device->location >> 24;
1024 dev->device_address = cached_device->address;
1026 (*(priv->dev->device))->GetDeviceSpeed (priv->dev->device, &devSpeed);
1029 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
1030 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
1031 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
1032 #if DeviceVersion >= 500
1033 case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
1036 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
1039 ret = usbi_sanitize_device (dev);
1043 usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
1044 dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
1048 usbi_connect_device (dev);
1050 libusb_unref_device (dev);
1056 static int darwin_scan_devices(struct libusb_context *ctx) {
1057 io_iterator_t deviceIterator;
1058 io_service_t service;
1059 kern_return_t kresult;
1061 kresult = usb_setup_device_iterator (&deviceIterator, 0);
1062 if (kresult != kIOReturnSuccess)
1063 return darwin_to_libusb (kresult);
1065 while ((service = IOIteratorNext (deviceIterator))) {
1066 (void) process_new_device (ctx, service);
1068 IOObjectRelease(service);
1071 IOObjectRelease(deviceIterator);
1076 static int darwin_open (struct libusb_device_handle *dev_handle) {
1077 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1078 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1081 if (0 == dpriv->open_count) {
1082 /* try to open the device */
1083 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
1084 if (kresult != kIOReturnSuccess) {
1085 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
1087 if (kIOReturnExclusiveAccess != kresult) {
1088 return darwin_to_libusb (kresult);
1091 /* it is possible to perform some actions on a device that is not open so do not return an error */
1097 /* create async event source */
1098 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
1099 if (kresult != kIOReturnSuccess) {
1100 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
1102 if (priv->is_open) {
1103 (*(dpriv->device))->USBDeviceClose (dpriv->device);
1108 return darwin_to_libusb (kresult);
1111 CFRetain (libusb_darwin_acfl);
1113 /* add the cfSource to the aync run loop */
1114 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
1117 /* device opened successfully */
1118 dpriv->open_count++;
1120 usbi_dbg ("device open for access");
1125 static void darwin_close (struct libusb_device_handle *dev_handle) {
1126 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1127 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1131 if (dpriv->open_count == 0) {
1132 /* something is probably very wrong if this is the case */
1133 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!");
1137 dpriv->open_count--;
1139 /* make sure all interfaces are released */
1140 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1141 if (dev_handle->claimed_interfaces & (1 << i))
1142 libusb_release_interface (dev_handle, i);
1144 if (0 == dpriv->open_count) {
1145 /* delete the device's async event source */
1146 if (priv->cfSource) {
1147 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
1148 CFRelease (priv->cfSource);
1149 priv->cfSource = NULL;
1150 CFRelease (libusb_darwin_acfl);
1153 if (priv->is_open) {
1154 /* close the device */
1155 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
1157 /* Log the fact that we had a problem closing the file, however failing a
1158 * close isn't really an error, so return success anyway */
1159 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
1165 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
1166 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1168 *config = (int) dpriv->active_config;
1173 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
1174 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1178 /* Setting configuration will invalidate the interface, so we need
1179 to reclaim it. First, dispose of existing interfaces, if any. */
1180 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1181 if (dev_handle->claimed_interfaces & (1 << i))
1182 darwin_release_interface (dev_handle, i);
1184 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
1185 if (kresult != kIOReturnSuccess)
1186 return darwin_to_libusb (kresult);
1188 /* Reclaim any interfaces. */
1189 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1190 if (dev_handle->claimed_interfaces & (1 << i))
1191 darwin_claim_interface (dev_handle, i);
1193 dpriv->active_config = config;
1198 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
1199 IOUSBFindInterfaceRequest request;
1200 kern_return_t kresult;
1201 io_iterator_t interface_iterator;
1202 UInt8 bInterfaceNumber;
1205 *usbInterfacep = IO_OBJECT_NULL;
1207 /* Setup the Interface Request */
1208 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1209 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1210 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1211 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1213 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1217 while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1218 /* find the interface number */
1219 ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
1222 if (ret && bInterfaceNumber == ifc) {
1226 (void) IOObjectRelease (*usbInterfacep);
1229 /* done with the interface iterator */
1230 IOObjectRelease(interface_iterator);
1235 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
1236 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1238 /* current interface */
1239 struct darwin_interface *cInterface = &priv->interfaces[iface];
1241 kern_return_t kresult;
1243 u_int8_t numep, direction, number;
1244 u_int8_t dont_care1, dont_care3;
1245 u_int16_t dont_care2;
1248 usbi_dbg ("building table of endpoints.");
1250 /* retrieve the total number of endpoints on this interface */
1251 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1253 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1254 return darwin_to_libusb (kresult);
1257 /* iterate through pipe references */
1258 for (int i = 1 ; i <= numep ; i++) {
1259 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1260 &dont_care2, &dont_care3);
1262 if (kresult != kIOReturnSuccess) {
1263 /* probably a buggy device. try to get the endpoint address from the descriptors */
1264 struct libusb_config_descriptor *config;
1265 const struct libusb_endpoint_descriptor *endpoint_desc;
1268 kresult = (*(cInterface->interface))->GetAlternateSetting (cInterface->interface, &alt_setting);
1270 usbi_err (HANDLE_CTX (dev_handle), "can't get alternate setting for interface");
1271 return darwin_to_libusb (kresult);
1274 rc = libusb_get_active_config_descriptor (dev_handle->dev, &config);
1275 if (LIBUSB_SUCCESS != rc) {
1279 endpoint_desc = config->interface[iface].altsetting[alt_setting].endpoint + i - 1;
1281 cInterface->endpoint_addrs[i - 1] = endpoint_desc->bEndpointAddress;
1283 cInterface->endpoint_addrs[i - 1] = (((kUSBIn == direction) << kUSBRqDirnShift) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1286 usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, cInterface->endpoint_addrs[i - 1] >> kUSBRqDirnShift,
1287 cInterface->endpoint_addrs[i - 1] & LIBUSB_ENDPOINT_ADDRESS_MASK);
1290 cInterface->num_endpoints = numep;
1295 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1296 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1297 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1298 io_service_t usbInterface = IO_OBJECT_NULL;
1300 IOCFPlugInInterface **plugInInterface = NULL;
1303 /* current interface */
1304 struct darwin_interface *cInterface = &priv->interfaces[iface];
1306 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1307 if (kresult != kIOReturnSuccess)
1308 return darwin_to_libusb (kresult);
1310 /* make sure we have an interface */
1311 if (!usbInterface && dpriv->first_config != 0) {
1312 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1314 /* set the configuration */
1315 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1316 if (kresult != LIBUSB_SUCCESS) {
1317 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1321 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1323 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1324 return darwin_to_libusb (kresult);
1328 if (!usbInterface) {
1329 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1330 return LIBUSB_ERROR_NOT_FOUND;
1333 /* get an interface to the device's interface */
1334 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1335 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1337 /* ignore release error */
1338 (void)IOObjectRelease (usbInterface);
1341 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1342 return darwin_to_libusb (kresult);
1345 if (!plugInInterface) {
1346 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1347 return LIBUSB_ERROR_NOT_FOUND;
1350 /* Do the actual claim */
1351 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1352 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1353 (LPVOID)&cInterface->interface);
1354 /* We no longer need the intermediate plug-in */
1355 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1356 (*plugInInterface)->Release (plugInInterface);
1357 if (kresult || !cInterface->interface) {
1358 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1359 return darwin_to_libusb (kresult);
1362 /* claim the interface */
1363 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1365 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1366 return darwin_to_libusb (kresult);
1369 /* update list of endpoints */
1370 kresult = get_endpoints (dev_handle, iface);
1372 /* this should not happen */
1373 darwin_release_interface (dev_handle, iface);
1374 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1378 cInterface->cfSource = NULL;
1380 /* create async event source */
1381 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1382 if (kresult != kIOReturnSuccess) {
1383 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1385 /* can't continue without an async event source */
1386 (void)darwin_release_interface (dev_handle, iface);
1388 return darwin_to_libusb (kresult);
1391 /* add the cfSource to the async thread's run loop */
1392 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1394 usbi_dbg ("interface opened");
1399 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1400 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1403 /* current interface */
1404 struct darwin_interface *cInterface = &priv->interfaces[iface];
1406 /* Check to see if an interface is open */
1407 if (!cInterface->interface)
1408 return LIBUSB_SUCCESS;
1410 /* clean up endpoint data */
1411 cInterface->num_endpoints = 0;
1413 /* delete the interface's async event source */
1414 if (cInterface->cfSource) {
1415 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1416 CFRelease (cInterface->cfSource);
1419 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1421 usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1423 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1424 if (kresult != kIOReturnSuccess)
1425 usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1427 cInterface->interface = (usb_interface_t **) IO_OBJECT_NULL;
1429 return darwin_to_libusb (kresult);
1432 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1433 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1436 /* current interface */
1437 struct darwin_interface *cInterface = &priv->interfaces[iface];
1439 if (!cInterface->interface)
1440 return LIBUSB_ERROR_NO_DEVICE;
1442 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1443 if (kresult != kIOReturnSuccess)
1444 darwin_reset_device (dev_handle);
1446 /* update list of endpoints */
1447 kresult = get_endpoints (dev_handle, iface);
1449 /* this should not happen */
1450 darwin_release_interface (dev_handle, iface);
1451 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1455 return darwin_to_libusb (kresult);
1458 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1459 /* current interface */
1460 struct darwin_interface *cInterface;
1464 /* determine the interface/endpoint to use */
1465 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, NULL, &cInterface) != 0) {
1466 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1468 return LIBUSB_ERROR_NOT_FOUND;
1471 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1472 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1474 usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1476 return darwin_to_libusb (kresult);
1479 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1480 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1481 IOUSBDeviceDescriptor descriptor;
1482 IOUSBConfigurationDescriptorPtr cached_configuration;
1483 IOUSBConfigurationDescriptor configuration;
1484 bool reenumerate = false;
1488 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1490 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1491 return darwin_to_libusb (kresult);
1495 usbi_dbg ("darwin/reset_device: checking if device descriptor changed");
1497 /* ignore return code. if we can't get a descriptor it might be worthwhile re-enumerating anway */
1498 (void) darwin_request_descriptor (dpriv->device, kUSBDeviceDesc, 0, &descriptor, sizeof (descriptor));
1500 /* check if the device descriptor has changed */
1501 if (0 != memcmp (&dpriv->dev_descriptor, &descriptor, sizeof (descriptor))) {
1506 /* check if any configuration descriptor has changed */
1507 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1508 usbi_dbg ("darwin/reset_device: checking if configuration descriptor %d changed", i);
1510 (void) darwin_request_descriptor (dpriv->device, kUSBConfDesc, i, &configuration, sizeof (configuration));
1511 (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1513 if (!cached_configuration || 0 != memcmp (cached_configuration, &configuration, sizeof (configuration))) {
1521 usbi_dbg ("darwin/reset_device: device requires reenumeration");
1522 (void) (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
1523 return LIBUSB_ERROR_NOT_FOUND;
1526 usbi_dbg ("darwin/reset_device: device reset complete");
1528 return LIBUSB_SUCCESS;
1531 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1532 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1533 io_service_t usbInterface;
1537 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1539 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1541 return darwin_to_libusb (kresult);
1544 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1545 IOObjectRelease (usbInterface);
1557 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1558 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1561 return LIBUSB_ERROR_NOT_SUPPORTED;
1564 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1567 return LIBUSB_ERROR_NOT_SUPPORTED;
1570 static void darwin_destroy_device(struct libusb_device *dev) {
1571 struct darwin_device_priv *dpriv = (struct darwin_device_priv *) dev->os_priv;
1574 /* need to hold the lock in case this is the last reference to the device */
1575 usbi_mutex_lock(&darwin_cached_devices_lock);
1576 darwin_deref_cached_device (dpriv->dev);
1578 usbi_mutex_unlock(&darwin_cached_devices_lock);
1582 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1583 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1586 uint8_t transferType;
1587 /* None of the values below are used in libusbx for bulk transfers */
1588 uint8_t direction, number, interval, pipeRef;
1589 uint16_t maxPacketSize;
1591 struct darwin_interface *cInterface;
1593 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1594 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1596 return LIBUSB_ERROR_NOT_FOUND;
1599 ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1600 &transferType, &maxPacketSize, &interval);
1603 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1604 darwin_error_str(ret), ret);
1605 return darwin_to_libusb (ret);
1608 if (0 != (transfer->length % maxPacketSize)) {
1609 /* do not need a zero packet */
1610 transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1613 /* submit the request */
1614 /* timeouts are unavailable on interrupt endpoints */
1615 if (transferType == kUSBInterrupt) {
1616 if (IS_XFERIN(transfer))
1617 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1618 transfer->length, darwin_async_io_callback, itransfer);
1620 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1621 transfer->length, darwin_async_io_callback, itransfer);
1623 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1625 if (IS_XFERIN(transfer))
1626 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1627 transfer->length, transfer->timeout, transfer->timeout,
1628 darwin_async_io_callback, (void *)itransfer);
1630 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1631 transfer->length, transfer->timeout, transfer->timeout,
1632 darwin_async_io_callback, (void *)itransfer);
1636 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1637 darwin_error_str(ret), ret);
1639 return darwin_to_libusb (ret);
1642 #if InterfaceVersion >= 550
1643 static int submit_stream_transfer(struct usbi_transfer *itransfer) {
1644 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1645 struct darwin_interface *cInterface;
1649 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1650 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1652 return LIBUSB_ERROR_NOT_FOUND;
1655 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1657 if (IS_XFERIN(transfer))
1658 ret = (*(cInterface->interface))->ReadStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1659 transfer->buffer, transfer->length, transfer->timeout,
1660 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1662 ret = (*(cInterface->interface))->WriteStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1663 transfer->buffer, transfer->length, transfer->timeout,
1664 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1667 usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1668 darwin_error_str(ret), ret);
1670 return darwin_to_libusb (ret);
1674 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1675 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1676 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1679 uint8_t direction, number, interval, pipeRef, transferType;
1680 uint16_t maxPacketSize;
1682 AbsoluteTime atTime;
1685 struct darwin_interface *cInterface;
1687 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1688 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1689 free(tpriv->isoc_framelist);
1690 tpriv->isoc_framelist = NULL;
1693 if (!tpriv->isoc_framelist) {
1694 tpriv->num_iso_packets = transfer->num_iso_packets;
1695 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1696 if (!tpriv->isoc_framelist)
1697 return LIBUSB_ERROR_NO_MEM;
1700 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1701 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1702 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1704 /* determine the interface/endpoint to use */
1705 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1706 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1708 return LIBUSB_ERROR_NOT_FOUND;
1711 /* determine the properties of this endpoint and the speed of the device */
1712 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1713 &transferType, &maxPacketSize, &interval);
1715 /* Last but not least we need the bus frame number */
1716 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1718 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1719 free(tpriv->isoc_framelist);
1720 tpriv->isoc_framelist = NULL;
1722 return darwin_to_libusb (kresult);
1725 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1726 &transferType, &maxPacketSize, &interval);
1728 /* schedule for a frame a little in the future */
1731 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1732 frame = cInterface->frames[transfer->endpoint];
1734 /* submit the request */
1735 if (IS_XFERIN(transfer))
1736 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1737 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1740 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1741 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1744 if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
1746 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1));
1748 /* High/super speed */
1749 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1)) / 8;
1751 if (kresult != kIOReturnSuccess) {
1752 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1753 darwin_error_str(kresult));
1754 free (tpriv->isoc_framelist);
1755 tpriv->isoc_framelist = NULL;
1758 return darwin_to_libusb (kresult);
1761 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1762 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1763 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1764 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1765 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1769 memset(&tpriv->req, 0, sizeof(tpriv->req));
1771 /* IOUSBDeviceInterface expects the request in cpu endianness */
1772 tpriv->req.bmRequestType = setup->bmRequestType;
1773 tpriv->req.bRequest = setup->bRequest;
1774 /* these values should be in bus order from libusb_fill_control_setup */
1775 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1776 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1777 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1778 /* data is stored after the libusb control block */
1779 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1780 tpriv->req.completionTimeout = transfer->timeout;
1781 tpriv->req.noDataTimeout = transfer->timeout;
1783 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1785 /* all transfers in libusb-1.0 are async */
1787 if (transfer->endpoint) {
1788 struct darwin_interface *cInterface;
1791 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1792 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1794 return LIBUSB_ERROR_NOT_FOUND;
1797 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1799 /* control request on endpoint 0 */
1800 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1802 if (kresult != kIOReturnSuccess)
1803 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1805 return darwin_to_libusb (kresult);
1808 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1809 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1811 switch (transfer->type) {
1812 case LIBUSB_TRANSFER_TYPE_CONTROL:
1813 return submit_control_transfer(itransfer);
1814 case LIBUSB_TRANSFER_TYPE_BULK:
1815 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1816 return submit_bulk_transfer(itransfer);
1817 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1818 return submit_iso_transfer(itransfer);
1819 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1820 #if InterfaceVersion >= 550
1821 return submit_stream_transfer(itransfer);
1823 usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers");
1824 return LIBUSB_ERROR_NOT_SUPPORTED;
1827 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1828 return LIBUSB_ERROR_INVALID_PARAM;
1832 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1833 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1834 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1837 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
1840 return LIBUSB_ERROR_NO_DEVICE;
1842 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1844 return darwin_to_libusb (kresult);
1847 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1848 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1849 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1850 struct darwin_interface *cInterface;
1851 uint8_t pipeRef, iface;
1854 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) {
1855 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1857 return LIBUSB_ERROR_NOT_FOUND;
1861 return LIBUSB_ERROR_NO_DEVICE;
1863 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
1865 /* abort transactions */
1866 #if InterfaceVersion >= 550
1867 if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type)
1868 (*(cInterface->interface))->AbortStreamsPipe (cInterface->interface, pipeRef, itransfer->stream_id);
1871 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1873 usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
1875 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1876 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1878 return darwin_to_libusb (kresult);
1881 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1882 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1884 switch (transfer->type) {
1885 case LIBUSB_TRANSFER_TYPE_CONTROL:
1886 return cancel_control_transfer(itransfer);
1887 case LIBUSB_TRANSFER_TYPE_BULK:
1888 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1889 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1890 return darwin_abort_transfers (itransfer);
1892 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1893 return LIBUSB_ERROR_INVALID_PARAM;
1897 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1898 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1899 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1901 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1902 free (tpriv->isoc_framelist);
1903 tpriv->isoc_framelist = NULL;
1907 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1908 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1909 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1910 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1912 usbi_dbg ("an async io operation has completed");
1914 /* if requested write a zero packet */
1915 if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
1916 struct darwin_interface *cInterface;
1919 (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface);
1921 (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
1924 tpriv->result = result;
1925 tpriv->size = (UInt32) (uintptr_t) arg0;
1927 /* signal the core that this transfer is complete */
1928 usbi_signal_transfer_completion(itransfer);
1931 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1932 if (itransfer->timeout_flags & USBI_TRANSFER_TIMED_OUT)
1933 result = kIOUSBTransactionTimeout;
1936 case kIOReturnUnderrun:
1937 case kIOReturnSuccess:
1938 return LIBUSB_TRANSFER_COMPLETED;
1939 case kIOReturnAborted:
1940 return LIBUSB_TRANSFER_CANCELLED;
1941 case kIOUSBPipeStalled:
1942 usbi_dbg ("transfer error: pipe is stalled");
1943 return LIBUSB_TRANSFER_STALL;
1944 case kIOReturnOverrun:
1945 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1946 return LIBUSB_TRANSFER_OVERFLOW;
1947 case kIOUSBTransactionTimeout:
1948 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1949 itransfer->timeout_flags |= USBI_TRANSFER_TIMED_OUT;
1950 return LIBUSB_TRANSFER_TIMED_OUT;
1952 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1953 return LIBUSB_TRANSFER_ERROR;
1957 static int darwin_handle_transfer_completion (struct usbi_transfer *itransfer) {
1958 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1959 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1960 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1961 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1962 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1963 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1966 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1967 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1968 return LIBUSB_ERROR_INVALID_PARAM;
1971 usbi_dbg ("handling %s completion with kernel status %d",
1972 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", tpriv->result);
1974 if (kIOReturnSuccess == tpriv->result || kIOReturnUnderrun == tpriv->result) {
1975 if (isIsoc && tpriv->isoc_framelist) {
1976 /* copy isochronous results back */
1978 for (i = 0; i < transfer->num_iso_packets ; i++) {
1979 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1980 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1981 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1984 itransfer->transferred += tpriv->size;
1987 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1988 return usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, tpriv->result));
1991 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1992 #if !OSX_USE_CLOCK_GETTIME
1993 mach_timespec_t sys_time;
1994 clock_serv_t clock_ref;
1997 case USBI_CLOCK_REALTIME:
1998 /* CLOCK_REALTIME represents time since the epoch */
1999 clock_ref = clock_realtime;
2001 case USBI_CLOCK_MONOTONIC:
2002 /* use system boot time as reference for the monotonic clock */
2003 clock_ref = clock_monotonic;
2006 return LIBUSB_ERROR_INVALID_PARAM;
2009 clock_get_time (clock_ref, &sys_time);
2011 tp->tv_sec = sys_time.tv_sec;
2012 tp->tv_nsec = sys_time.tv_nsec;
2017 case USBI_CLOCK_MONOTONIC:
2018 return clock_gettime(CLOCK_MONOTONIC, tp);
2019 case USBI_CLOCK_REALTIME:
2020 return clock_gettime(CLOCK_REALTIME, tp);
2022 return LIBUSB_ERROR_INVALID_PARAM;
2027 #if InterfaceVersion >= 550
2028 static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints,
2029 int num_endpoints) {
2030 struct darwin_interface *cInterface;
2031 UInt32 supportsStreams;
2035 /* find the mimimum number of supported streams on the endpoint list */
2036 for (i = 0 ; i < num_endpoints ; ++i) {
2037 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) {
2041 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2042 if (num_streams > supportsStreams)
2043 num_streams = supportsStreams;
2046 /* it is an error if any endpoint in endpoints does not support streams */
2047 if (0 == num_streams)
2048 return LIBUSB_ERROR_INVALID_PARAM;
2050 /* create the streams */
2051 for (i = 0 ; i < num_endpoints ; ++i) {
2052 (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
2054 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, num_streams);
2055 if (kIOReturnSuccess != rc)
2056 return darwin_to_libusb(rc);
2062 static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) {
2063 struct darwin_interface *cInterface;
2064 UInt32 supportsStreams;
2068 for (int i = 0 ; i < num_endpoints ; ++i) {
2069 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface)))
2072 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2073 if (0 == supportsStreams)
2074 return LIBUSB_ERROR_INVALID_PARAM;
2076 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, 0);
2077 if (kIOReturnSuccess != rc)
2078 return darwin_to_libusb(rc);
2081 return LIBUSB_SUCCESS;
2085 const struct usbi_os_backend usbi_backend = {
2088 .init = darwin_init,
2089 .exit = darwin_exit,
2090 .get_device_list = NULL, /* not needed */
2091 .get_device_descriptor = darwin_get_device_descriptor,
2092 .get_active_config_descriptor = darwin_get_active_config_descriptor,
2093 .get_config_descriptor = darwin_get_config_descriptor,
2094 .hotplug_poll = darwin_hotplug_poll,
2096 .open = darwin_open,
2097 .close = darwin_close,
2098 .get_configuration = darwin_get_configuration,
2099 .set_configuration = darwin_set_configuration,
2100 .claim_interface = darwin_claim_interface,
2101 .release_interface = darwin_release_interface,
2103 .set_interface_altsetting = darwin_set_interface_altsetting,
2104 .clear_halt = darwin_clear_halt,
2105 .reset_device = darwin_reset_device,
2107 #if InterfaceVersion >= 550
2108 .alloc_streams = darwin_alloc_streams,
2109 .free_streams = darwin_free_streams,
2112 .kernel_driver_active = darwin_kernel_driver_active,
2113 .detach_kernel_driver = darwin_detach_kernel_driver,
2114 .attach_kernel_driver = darwin_attach_kernel_driver,
2116 .destroy_device = darwin_destroy_device,
2118 .submit_transfer = darwin_submit_transfer,
2119 .cancel_transfer = darwin_cancel_transfer,
2120 .clear_transfer_priv = darwin_clear_transfer_priv,
2122 .handle_transfer_completion = darwin_handle_transfer_completion,
2124 .clock_gettime = darwin_clock_gettime,
2126 .device_priv_size = sizeof(struct darwin_device_priv),
2127 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
2128 .transfer_priv_size = sizeof(struct darwin_transfer_priv),