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 /* Suppress warnings about the use of the deprecated objc_registerThreadWithCollector
40 * function. Its use is also conditionalized to only older deployment targets. */
41 #define OBJC_SILENCE_GC_DEPRECATIONS 1
43 #include <AvailabilityMacros.h>
44 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
45 #include <objc/objc-auto.h>
48 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 101200
49 /* Apple deprecated the darwin atomics in 10.12 in favor of C11 atomics */
50 #include <stdatomic.h>
51 #define libusb_darwin_atomic_fetch_add(x, y) atomic_fetch_add(x, y)
53 _Atomic int32_t initCount = ATOMIC_VAR_INIT(0);
55 /* use darwin atomics if the target is older than 10.12 */
56 #include <libkern/OSAtomic.h>
58 /* OSAtomicAdd32Barrier returns the new value */
59 #define libusb_darwin_atomic_fetch_add(x, y) (OSAtomicAdd32Barrier(y, x) - y)
61 static volatile int32_t initCount = 0;
65 /* On 10.12 and later, use newly available clock_*() functions */
66 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 101200
67 #define OSX_USE_CLOCK_GETTIME 1
69 #define OSX_USE_CLOCK_GETTIME 0
72 #include "darwin_usb.h"
74 /* async event thread */
75 static pthread_mutex_t libusb_darwin_at_mutex = PTHREAD_MUTEX_INITIALIZER;
76 static pthread_cond_t libusb_darwin_at_cond = PTHREAD_COND_INITIALIZER;
78 static pthread_once_t darwin_init_once = PTHREAD_ONCE_INIT;
80 #if !OSX_USE_CLOCK_GETTIME
81 static clock_serv_t clock_realtime;
82 static clock_serv_t clock_monotonic;
85 static CFRunLoopRef libusb_darwin_acfl = NULL; /* event cf loop */
86 static CFRunLoopSourceRef libusb_darwin_acfls = NULL; /* shutdown signal for event cf loop */
88 static usbi_mutex_t darwin_cached_devices_lock = PTHREAD_MUTEX_INITIALIZER;
89 static struct list_head darwin_cached_devices = {&darwin_cached_devices, &darwin_cached_devices};
90 static const char *darwin_device_class = kIOUSBDeviceClassName;
92 #define DARWIN_CACHED_DEVICE(a) ((struct darwin_cached_device *) (((struct darwin_device_priv *)((a)->os_priv))->dev))
94 /* async event thread */
95 static pthread_t libusb_darwin_at;
97 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
98 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
99 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
100 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
101 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
103 static int darwin_scan_devices(struct libusb_context *ctx);
104 static int process_new_device (struct libusb_context *ctx, io_service_t service);
106 #if defined(ENABLE_LOGGING)
107 static const char *darwin_error_str (int result) {
108 static char string_buffer[50];
110 case kIOReturnSuccess:
112 case kIOReturnNotOpen:
113 return "device not opened for exclusive access";
114 case kIOReturnNoDevice:
115 return "no connection to an IOService";
116 case kIOUSBNoAsyncPortErr:
117 return "no async port has been opened for interface";
118 case kIOReturnExclusiveAccess:
119 return "another process has device opened for exclusive access";
120 case kIOUSBPipeStalled:
121 return "pipe is stalled";
123 return "could not establish a connection to the Darwin kernel";
124 case kIOUSBTransactionTimeout:
125 return "transaction timed out";
126 case kIOReturnBadArgument:
127 return "invalid argument";
128 case kIOReturnAborted:
129 return "transaction aborted";
130 case kIOReturnNotResponding:
131 return "device not responding";
132 case kIOReturnOverrun:
133 return "data overrun";
134 case kIOReturnCannotWire:
135 return "physical memory can not be wired down";
136 case kIOReturnNoResources:
137 return "out of resources";
138 case kIOUSBHighSpeedSplitError:
139 return "high speed split error";
141 snprintf(string_buffer, sizeof(string_buffer), "unknown error (0x%x)", result);
142 return string_buffer;
147 static int darwin_to_libusb (int result) {
149 case kIOReturnUnderrun:
150 case kIOReturnSuccess:
151 return LIBUSB_SUCCESS;
152 case kIOReturnNotOpen:
153 case kIOReturnNoDevice:
154 return LIBUSB_ERROR_NO_DEVICE;
155 case kIOReturnExclusiveAccess:
156 return LIBUSB_ERROR_ACCESS;
157 case kIOUSBPipeStalled:
158 return LIBUSB_ERROR_PIPE;
159 case kIOReturnBadArgument:
160 return LIBUSB_ERROR_INVALID_PARAM;
161 case kIOUSBTransactionTimeout:
162 return LIBUSB_ERROR_TIMEOUT;
163 case kIOReturnNotResponding:
164 case kIOReturnAborted:
166 case kIOUSBNoAsyncPortErr:
168 return LIBUSB_ERROR_OTHER;
172 /* this function must be called with the darwin_cached_devices_lock held */
173 static void darwin_deref_cached_device(struct darwin_cached_device *cached_dev) {
174 cached_dev->refcount--;
175 /* free the device and remove it from the cache */
176 if (0 == cached_dev->refcount) {
177 list_del(&cached_dev->list);
179 (*(cached_dev->device))->Release(cached_dev->device);
184 static void darwin_ref_cached_device(struct darwin_cached_device *cached_dev) {
185 cached_dev->refcount++;
188 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) {
189 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
191 /* current interface */
192 struct darwin_interface *cInterface;
196 usbi_dbg ("converting ep address 0x%02x to pipeRef and interface", ep);
198 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
199 cInterface = &priv->interfaces[iface];
201 if (dev_handle->claimed_interfaces & (1 << iface)) {
202 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
203 if (cInterface->endpoint_addrs[i] == ep) {
210 *interface_out = cInterface;
212 usbi_dbg ("pipe %d on interface %d matches", *pipep, iface);
219 /* No pipe found with the correct endpoint address */
220 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
222 return LIBUSB_ERROR_NOT_FOUND;
225 static int usb_setup_device_iterator (io_iterator_t *deviceIterator, UInt32 location) {
226 CFMutableDictionaryRef matchingDict = IOServiceMatching(darwin_device_class);
229 return kIOReturnError;
232 CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
233 &kCFTypeDictionaryKeyCallBacks,
234 &kCFTypeDictionaryValueCallBacks);
236 if (propertyMatchDict) {
237 /* there are no unsigned CFNumber types so treat the value as signed. the os seems to do this
238 internally (CFNumberType of locationID is 3) */
239 CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberSInt32Type, &location);
241 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
242 /* release our reference to the CFNumber (CFDictionarySetValue retains it) */
243 CFRelease (locationCF);
245 CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
246 /* release out reference to the CFMutableDictionaryRef (CFDictionarySetValue retains it) */
247 CFRelease (propertyMatchDict);
249 /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
252 return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator);
255 /* Returns 1 on success, 0 on failure. */
256 static int get_ioregistry_value_number (io_service_t service, CFStringRef property, CFNumberType type, void *p) {
257 CFTypeRef cfNumber = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
261 if (CFGetTypeID(cfNumber) == CFNumberGetTypeID()) {
262 ret = CFNumberGetValue(cfNumber, type, p);
265 CFRelease (cfNumber);
271 static int get_ioregistry_value_data (io_service_t service, CFStringRef property, ssize_t size, void *p) {
272 CFTypeRef cfData = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
276 if (CFGetTypeID (cfData) == CFDataGetTypeID ()) {
277 CFIndex length = CFDataGetLength (cfData);
282 CFDataGetBytes (cfData, CFRangeMake(0, size), p);
292 static usb_device_t **darwin_device_from_service (io_service_t service)
294 io_cf_plugin_ref_t *plugInInterface = NULL;
295 usb_device_t **device;
296 kern_return_t result;
299 result = IOCreatePlugInInterfaceForService(service, kIOUSBDeviceUserClientTypeID,
300 kIOCFPlugInInterfaceID, &plugInInterface,
303 if (kIOReturnSuccess != result || !plugInInterface) {
304 usbi_dbg ("could not set up plugin for service: %s", darwin_error_str (result));
308 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
310 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
311 (*plugInInterface)->Release (plugInInterface);
316 static void darwin_devices_attached (void *ptr, io_iterator_t add_devices) {
318 struct libusb_context *ctx;
319 io_service_t service;
321 usbi_mutex_lock(&active_contexts_lock);
323 while ((service = IOIteratorNext(add_devices))) {
324 /* add this device to each active context's device list */
325 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
326 process_new_device (ctx, service);
329 IOObjectRelease(service);
332 usbi_mutex_unlock(&active_contexts_lock);
335 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
337 struct libusb_device *dev = NULL;
338 struct libusb_context *ctx;
339 struct darwin_cached_device *old_device;
345 usbi_mutex_lock(&active_contexts_lock);
347 while ((device = IOIteratorNext (rem_devices)) != 0) {
348 /* get the location from the i/o registry */
349 ret = get_ioregistry_value_number (device, CFSTR("sessionID"), kCFNumberSInt64Type, &session);
350 IOObjectRelease (device);
354 /* we need to match darwin_ref_cached_device call made in darwin_get_cached_device function
355 otherwise no cached device will ever get freed */
356 usbi_mutex_lock(&darwin_cached_devices_lock);
357 list_for_each_entry(old_device, &darwin_cached_devices, list, struct darwin_cached_device) {
358 if (old_device->session == session) {
359 darwin_deref_cached_device (old_device);
363 usbi_mutex_unlock(&darwin_cached_devices_lock);
365 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
366 usbi_dbg ("notifying context %p of device disconnect", ctx);
368 dev = usbi_get_device_by_session_id(ctx, (unsigned long) session);
370 /* signal the core that this device has been disconnected. the core will tear down this device
371 when the reference count reaches 0 */
372 usbi_disconnect_device(dev);
373 libusb_unref_device(dev);
378 usbi_mutex_unlock(&active_contexts_lock);
381 static void darwin_hotplug_poll (void)
383 /* not sure if 5 seconds will be too long/short but it should work ok */
384 mach_timespec_t timeout = {.tv_sec = 5, .tv_nsec = 0};
386 /* since a kernel thread may nodify the IOInterators used for
387 * hotplug notidication we can't just clear the iterators.
388 * instead just wait until all IOService providers are quiet */
389 (void) IOKitWaitQuiet (kIOMasterPortDefault, &timeout);
392 static void darwin_clear_iterator (io_iterator_t iter) {
395 while ((device = IOIteratorNext (iter)) != 0)
396 IOObjectRelease (device);
399 static void *darwin_event_thread_main (void *arg0) {
401 struct libusb_context *ctx = (struct libusb_context *)arg0;
402 CFRunLoopRef runloop;
404 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
405 /* Set this thread's name, so it can be seen in the debugger
406 and crash reports. */
407 pthread_setname_np ("org.libusb.device-hotplug");
410 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
411 /* Tell the Objective-C garbage collector about this thread.
412 This is required because, unlike NSThreads, pthreads are
413 not automatically registered. Although we don't use
414 Objective-C, we use CoreFoundation, which does.
415 Garbage collection support was entirely removed in 10.12,
416 so don't bother there. */
417 objc_registerThreadWithCollector();
420 /* hotplug (device arrival/removal) sources */
421 CFRunLoopSourceContext libusb_shutdown_cfsourcectx;
422 CFRunLoopSourceRef libusb_notification_cfsource;
423 io_notification_port_t libusb_notification_port;
424 io_iterator_t libusb_rem_device_iterator;
425 io_iterator_t libusb_add_device_iterator;
427 usbi_dbg ("creating hotplug event source");
429 runloop = CFRunLoopGetCurrent ();
432 /* add the shutdown cfsource to the run loop */
433 memset(&libusb_shutdown_cfsourcectx, 0, sizeof(libusb_shutdown_cfsourcectx));
434 libusb_shutdown_cfsourcectx.info = runloop;
435 libusb_shutdown_cfsourcectx.perform = (void (*)(void *))CFRunLoopStop;
436 libusb_darwin_acfls = CFRunLoopSourceCreate(NULL, 0, &libusb_shutdown_cfsourcectx);
437 CFRunLoopAddSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
439 /* add the notification port to the run loop */
440 libusb_notification_port = IONotificationPortCreate (kIOMasterPortDefault);
441 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
442 CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
444 /* create notifications for removed devices */
445 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
446 IOServiceMatching(darwin_device_class),
447 darwin_devices_detached,
448 ctx, &libusb_rem_device_iterator);
450 if (kresult != kIOReturnSuccess) {
451 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
456 /* create notifications for attached devices */
457 kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
458 IOServiceMatching(darwin_device_class),
459 darwin_devices_attached,
460 ctx, &libusb_add_device_iterator);
462 if (kresult != kIOReturnSuccess) {
463 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
469 darwin_clear_iterator (libusb_rem_device_iterator);
470 darwin_clear_iterator (libusb_add_device_iterator);
472 usbi_dbg ("darwin event thread ready to receive events");
474 /* signal the main thread that the hotplug runloop has been created. */
475 pthread_mutex_lock (&libusb_darwin_at_mutex);
476 libusb_darwin_acfl = runloop;
477 pthread_cond_signal (&libusb_darwin_at_cond);
478 pthread_mutex_unlock (&libusb_darwin_at_mutex);
480 /* run the runloop */
483 usbi_dbg ("darwin event thread exiting");
485 /* remove the notification cfsource */
486 CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
488 /* remove the shutdown cfsource */
489 CFRunLoopRemoveSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
491 /* delete notification port */
492 IONotificationPortDestroy (libusb_notification_port);
494 /* delete iterators */
495 IOObjectRelease (libusb_rem_device_iterator);
496 IOObjectRelease (libusb_add_device_iterator);
498 CFRelease (libusb_darwin_acfls);
501 libusb_darwin_acfls = NULL;
502 libusb_darwin_acfl = NULL;
507 /* cleanup function to destroy cached devices */
508 static void __attribute__((destructor)) _darwin_finalize(void) {
509 struct darwin_cached_device *dev, *next;
511 usbi_mutex_lock(&darwin_cached_devices_lock);
512 list_for_each_entry_safe(dev, next, &darwin_cached_devices, list, struct darwin_cached_device) {
513 darwin_deref_cached_device(dev);
515 usbi_mutex_unlock(&darwin_cached_devices_lock);
518 static void darwin_check_version (void) {
519 /* adjust for changes in the USB stack in xnu 15 */
520 int sysctl_args[] = {CTL_KERN, KERN_OSRELEASE};
522 char version_string[256] = {'\0',};
525 sysctl(sysctl_args, 2, version_string, &length, NULL, 0);
528 version = strtol (version_string, NULL, 10);
529 if (0 == errno && version >= 15) {
530 darwin_device_class = "IOUSBHostDevice";
534 static int darwin_init(struct libusb_context *ctx) {
537 rc = pthread_once (&darwin_init_once, darwin_check_version);
539 return LIBUSB_ERROR_OTHER;
542 rc = darwin_scan_devices (ctx);
543 if (LIBUSB_SUCCESS != rc) {
547 if (libusb_darwin_atomic_fetch_add (&initCount, 1) == 0) {
548 #if !OSX_USE_CLOCK_GETTIME
549 /* create the clocks that will be used if clock_gettime() is not available */
550 host_name_port_t host_self;
552 host_self = mach_host_self();
553 host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
554 host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
555 mach_port_deallocate(mach_task_self(), host_self);
558 pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, ctx);
560 pthread_mutex_lock (&libusb_darwin_at_mutex);
561 while (!libusb_darwin_acfl)
562 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
563 pthread_mutex_unlock (&libusb_darwin_at_mutex);
569 static void darwin_exit (struct libusb_context *ctx) {
571 if (libusb_darwin_atomic_fetch_add (&initCount, -1) == 1) {
572 #if !OSX_USE_CLOCK_GETTIME
573 mach_port_deallocate(mach_task_self(), clock_realtime);
574 mach_port_deallocate(mach_task_self(), clock_monotonic);
577 /* stop the event runloop and wait for the thread to terminate. */
578 CFRunLoopSourceSignal(libusb_darwin_acfls);
579 CFRunLoopWakeUp (libusb_darwin_acfl);
580 pthread_join (libusb_darwin_at, NULL);
584 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
585 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
587 /* return cached copy */
588 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
595 static int get_configuration_index (struct libusb_device *dev, int config_value) {
596 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
598 IOUSBConfigurationDescriptorPtr desc;
601 /* is there a simpler way to determine the index? */
602 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
603 if (kresult != kIOReturnSuccess)
604 return darwin_to_libusb (kresult);
606 for (i = 0 ; i < numConfig ; i++) {
607 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
609 if (desc->bConfigurationValue == config_value)
613 /* configuration not found */
614 return LIBUSB_ERROR_NOT_FOUND;
617 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
618 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
621 if (0 == priv->active_config)
622 return LIBUSB_ERROR_NOT_FOUND;
624 config_index = get_configuration_index (dev, priv->active_config);
625 if (config_index < 0)
628 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
631 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
632 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
633 IOUSBConfigurationDescriptorPtr desc;
637 if (!priv || !priv->device)
638 return LIBUSB_ERROR_OTHER;
640 kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
641 if (kresult == kIOReturnSuccess) {
642 /* copy descriptor */
643 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
644 len = libusb_le16_to_cpu(desc->wTotalLength);
646 memmove (buffer, desc, len);
648 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
652 ret = darwin_to_libusb (kresult);
653 if (ret != LIBUSB_SUCCESS)
659 /* check whether the os has configured the device */
660 static int darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) {
661 usb_device_t **darwin_device = dev->device;
663 IOUSBConfigurationDescriptorPtr configDesc;
664 IOUSBFindInterfaceRequest request;
665 kern_return_t kresult;
666 io_iterator_t interface_iterator;
667 io_service_t firstInterface;
669 if (dev->dev_descriptor.bNumConfigurations < 1) {
670 usbi_err (ctx, "device has no configurations");
671 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
674 /* checking the configuration of a root hub simulation takes ~1 s in 10.11. the device is
676 if (0x05ac == dev->dev_descriptor.idVendor && 0x8005 == dev->dev_descriptor.idProduct) {
677 usbi_dbg ("ignoring configuration on root hub simulation");
678 dev->active_config = 0;
682 /* find the first configuration */
683 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
684 dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
686 /* check if the device is already configured. there is probably a better way than iterating over the
687 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
688 might lock up on the device request) */
690 /* Setup the Interface Request */
691 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
692 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
693 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
694 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
696 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
698 return darwin_to_libusb (kresult);
701 firstInterface = IOIteratorNext(interface_iterator);
703 /* done with the interface iterator */
704 IOObjectRelease(interface_iterator);
706 if (firstInterface) {
707 IOObjectRelease (firstInterface);
709 /* device is configured */
710 if (dev->dev_descriptor.bNumConfigurations == 1)
711 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
712 dev->active_config = dev->first_config;
714 /* devices with more than one configuration should work with GetConfiguration */
715 (*darwin_device)->GetConfiguration (darwin_device, &dev->active_config);
718 dev->active_config = 0;
720 usbi_dbg ("active config: %u, first config: %u", dev->active_config, dev->first_config);
725 static int darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
726 IOUSBDevRequestTO req;
728 memset (buffer, 0, buffer_size);
730 /* Set up request for descriptor/ */
731 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
732 req.bRequest = kUSBRqGetDescriptor;
733 req.wValue = desc << 8;
734 req.wIndex = desc_index;
735 req.wLength = buffer_size;
737 req.noDataTimeout = 20;
738 req.completionTimeout = 100;
740 return (*device)->DeviceRequestTO (device, &req);
743 static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct darwin_cached_device *dev) {
744 usb_device_t **device = dev->device;
745 int retries = 1, delay = 30000;
746 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
750 UInt16 idProduct, idVendor;
752 dev->can_enumerate = 0;
754 (*device)->GetDeviceClass (device, &bDeviceClass);
755 (*device)->GetDeviceProduct (device, &idProduct);
756 (*device)->GetDeviceVendor (device, &idVendor);
758 /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
759 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
760 * to follow the spec as closely as possible, try opening the device */
761 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
764 /**** retrieve device descriptor ****/
765 ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &dev->dev_descriptor, sizeof(dev->dev_descriptor));
767 if (kIOReturnOverrun == ret && kUSBDeviceDesc == dev->dev_descriptor.bDescriptorType)
768 /* received an overrun error but we still received a device descriptor */
769 ret = kIOReturnSuccess;
771 if (kIOUSBVendorIDAppleComputer == idVendor) {
772 /* NTH: don't bother retrying or unsuspending Apple devices */
776 if (kIOReturnSuccess == ret && (0 == dev->dev_descriptor.bNumConfigurations ||
777 0 == dev->dev_descriptor.bcdUSB)) {
778 /* work around for incorrectly configured devices */
779 if (try_reconfigure && is_open) {
780 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
782 /* set the first configuration */
783 (*device)->SetConfiguration(device, 1);
785 /* don't try to reconfigure again */
789 ret = kIOUSBPipeStalled;
792 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
793 /* device may be suspended. unsuspend it and try again */
794 #if DeviceVersion >= 320
797 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
798 (void)(*device)->GetUSBDeviceInformation (device, &info);
800 /* note that the device was suspended */
801 if (info & (1 << kUSBInformationDeviceIsSuspendedBit) || 0 == info)
806 /* try to unsuspend the device */
807 ret2 = (*device)->USBDeviceSuspend (device, 0);
808 if (kIOReturnSuccess != ret2) {
809 /* prevent log spew from poorly behaving devices. this indicates the
810 os actually had trouble communicating with the device */
811 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
819 if (kIOReturnSuccess != ret) {
820 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
821 /* sleep for a little while before trying again */
822 nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000UL}, NULL);
824 } while (kIOReturnSuccess != ret && retries--);
827 /* resuspend the device */
828 (void)(*device)->USBDeviceSuspend (device, 1);
831 (void) (*device)->USBDeviceClose (device);
833 if (ret != kIOReturnSuccess) {
834 /* a debug message was already printed out for this error */
835 if (LIBUSB_CLASS_HUB == bDeviceClass)
836 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
837 idVendor, idProduct, darwin_error_str (ret), ret);
839 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
840 idVendor, idProduct, darwin_error_str (ret), ret);
841 return darwin_to_libusb (ret);
844 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
845 if (libusb_le16_to_cpu (dev->dev_descriptor.idProduct) != idProduct) {
846 /* not a valid device */
847 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
848 idProduct, libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
849 return LIBUSB_ERROR_NO_DEVICE;
852 usbi_dbg ("cached device descriptor:");
853 usbi_dbg (" bDescriptorType: 0x%02x", dev->dev_descriptor.bDescriptorType);
854 usbi_dbg (" bcdUSB: 0x%04x", dev->dev_descriptor.bcdUSB);
855 usbi_dbg (" bDeviceClass: 0x%02x", dev->dev_descriptor.bDeviceClass);
856 usbi_dbg (" bDeviceSubClass: 0x%02x", dev->dev_descriptor.bDeviceSubClass);
857 usbi_dbg (" bDeviceProtocol: 0x%02x", dev->dev_descriptor.bDeviceProtocol);
858 usbi_dbg (" bMaxPacketSize0: 0x%02x", dev->dev_descriptor.bMaxPacketSize0);
859 usbi_dbg (" idVendor: 0x%04x", dev->dev_descriptor.idVendor);
860 usbi_dbg (" idProduct: 0x%04x", dev->dev_descriptor.idProduct);
861 usbi_dbg (" bcdDevice: 0x%04x", dev->dev_descriptor.bcdDevice);
862 usbi_dbg (" iManufacturer: 0x%02x", dev->dev_descriptor.iManufacturer);
863 usbi_dbg (" iProduct: 0x%02x", dev->dev_descriptor.iProduct);
864 usbi_dbg (" iSerialNumber: 0x%02x", dev->dev_descriptor.iSerialNumber);
865 usbi_dbg (" bNumConfigurations: 0x%02x", dev->dev_descriptor.bNumConfigurations);
867 dev->can_enumerate = 1;
869 return LIBUSB_SUCCESS;
872 static int get_device_port (io_service_t service, UInt8 *port) {
873 kern_return_t result;
877 if (get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, port)) {
881 result = IORegistryEntryGetParentEntry (service, kIOServicePlane, &parent);
882 if (kIOReturnSuccess == result) {
883 ret = get_ioregistry_value_data (parent, CFSTR("port"), 1, port);
884 IOObjectRelease (parent);
890 static int get_device_parent_sessionID(io_service_t service, UInt64 *parent_sessionID) {
891 kern_return_t result;
894 /* Walk up the tree in the IOService plane until we find a parent that has a sessionID */
896 while((result = IORegistryEntryGetParentEntry (parent, kIOServicePlane, &parent)) == kIOReturnSuccess) {
897 if (get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, parent_sessionID)) {
903 /* We ran out of parents */
907 static int darwin_get_cached_device(struct libusb_context *ctx, io_service_t service,
908 struct darwin_cached_device **cached_out) {
909 struct darwin_cached_device *new_device;
910 UInt64 sessionID = 0, parent_sessionID = 0;
911 int ret = LIBUSB_SUCCESS;
912 usb_device_t **device;
915 /* get some info from the io registry */
916 (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
917 if (!get_device_port (service, &port)) {
918 usbi_dbg("could not get connected port number");
921 usbi_dbg("finding cached device for sessionID 0x%" PRIx64, sessionID);
923 if (get_device_parent_sessionID(service, &parent_sessionID)) {
924 usbi_dbg("parent sessionID: 0x%" PRIx64, parent_sessionID);
927 usbi_mutex_lock(&darwin_cached_devices_lock);
931 list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) {
932 usbi_dbg("matching sessionID 0x%" PRIx64 " against cached device with sessionID 0x%" PRIx64, sessionID, new_device->session);
933 if (new_device->session == sessionID) {
934 usbi_dbg("using cached device for device");
935 *cached_out = new_device;
943 usbi_dbg("caching new device with sessionID 0x%" PRIx64, sessionID);
945 device = darwin_device_from_service (service);
947 ret = LIBUSB_ERROR_NO_DEVICE;
951 new_device = calloc (1, sizeof (*new_device));
953 ret = LIBUSB_ERROR_NO_MEM;
957 /* add this device to the cached device list */
958 list_add(&new_device->list, &darwin_cached_devices);
960 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
962 /* keep a reference to this device */
963 darwin_ref_cached_device(new_device);
965 new_device->device = device;
966 new_device->session = sessionID;
967 (*device)->GetLocationID (device, &new_device->location);
968 new_device->port = port;
969 new_device->parent_session = parent_sessionID;
971 /* cache the device descriptor */
972 ret = darwin_cache_device_descriptor(ctx, new_device);
976 if (new_device->can_enumerate) {
977 snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address,
978 new_device->dev_descriptor.idVendor, new_device->dev_descriptor.idProduct,
979 new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass);
983 usbi_mutex_unlock(&darwin_cached_devices_lock);
985 /* keep track of devices regardless of if we successfully enumerate them to
986 prevent them from being enumerated multiple times */
988 *cached_out = new_device;
993 static int process_new_device (struct libusb_context *ctx, io_service_t service) {
994 struct darwin_device_priv *priv;
995 struct libusb_device *dev = NULL;
996 struct darwin_cached_device *cached_device;
1001 ret = darwin_get_cached_device (ctx, service, &cached_device);
1003 if (ret < 0 || !cached_device->can_enumerate) {
1007 /* check current active configuration (and cache the first configuration value--
1008 which may be used by claim_interface) */
1009 ret = darwin_check_configuration (ctx, cached_device);
1013 usbi_dbg ("allocating new device in context %p for with session 0x%" PRIx64,
1014 ctx, cached_device->session);
1016 dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
1018 return LIBUSB_ERROR_NO_MEM;
1021 priv = (struct darwin_device_priv *)dev->os_priv;
1023 priv->dev = cached_device;
1024 darwin_ref_cached_device (priv->dev);
1026 if (cached_device->parent_session > 0) {
1027 dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session);
1029 dev->parent_dev = NULL;
1031 dev->port_number = cached_device->port;
1032 dev->bus_number = cached_device->location >> 24;
1033 dev->device_address = cached_device->address;
1035 (*(priv->dev->device))->GetDeviceSpeed (priv->dev->device, &devSpeed);
1038 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
1039 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
1040 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
1041 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
1042 case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
1044 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101200
1045 case kUSBDeviceSpeedSuperPlus: dev->speed = LIBUSB_SPEED_SUPER_PLUS; break;
1048 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
1051 ret = usbi_sanitize_device (dev);
1055 usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
1056 dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
1060 usbi_connect_device (dev);
1062 libusb_unref_device (dev);
1068 static int darwin_scan_devices(struct libusb_context *ctx) {
1069 io_iterator_t deviceIterator;
1070 io_service_t service;
1071 kern_return_t kresult;
1073 kresult = usb_setup_device_iterator (&deviceIterator, 0);
1074 if (kresult != kIOReturnSuccess)
1075 return darwin_to_libusb (kresult);
1077 while ((service = IOIteratorNext (deviceIterator))) {
1078 (void) process_new_device (ctx, service);
1080 IOObjectRelease(service);
1083 IOObjectRelease(deviceIterator);
1088 static int darwin_open (struct libusb_device_handle *dev_handle) {
1089 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1090 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1093 if (0 == dpriv->open_count) {
1094 /* try to open the device */
1095 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
1096 if (kresult != kIOReturnSuccess) {
1097 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
1099 if (kIOReturnExclusiveAccess != kresult) {
1100 return darwin_to_libusb (kresult);
1103 /* it is possible to perform some actions on a device that is not open so do not return an error */
1109 /* create async event source */
1110 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
1111 if (kresult != kIOReturnSuccess) {
1112 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
1114 if (priv->is_open) {
1115 (*(dpriv->device))->USBDeviceClose (dpriv->device);
1120 return darwin_to_libusb (kresult);
1123 CFRetain (libusb_darwin_acfl);
1125 /* add the cfSource to the aync run loop */
1126 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
1129 /* device opened successfully */
1130 dpriv->open_count++;
1132 usbi_dbg ("device open for access");
1137 static void darwin_close (struct libusb_device_handle *dev_handle) {
1138 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1139 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1143 if (dpriv->open_count == 0) {
1144 /* something is probably very wrong if this is the case */
1145 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!");
1149 dpriv->open_count--;
1151 /* make sure all interfaces are released */
1152 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1153 if (dev_handle->claimed_interfaces & (1 << i))
1154 libusb_release_interface (dev_handle, i);
1156 if (0 == dpriv->open_count) {
1157 /* delete the device's async event source */
1158 if (priv->cfSource) {
1159 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
1160 CFRelease (priv->cfSource);
1161 priv->cfSource = NULL;
1162 CFRelease (libusb_darwin_acfl);
1165 if (priv->is_open) {
1166 /* close the device */
1167 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
1169 /* Log the fact that we had a problem closing the file, however failing a
1170 * close isn't really an error, so return success anyway */
1171 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
1177 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
1178 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1180 *config = (int) dpriv->active_config;
1185 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
1186 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1190 /* Setting configuration will invalidate the interface, so we need
1191 to reclaim it. First, dispose of existing interfaces, if any. */
1192 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1193 if (dev_handle->claimed_interfaces & (1 << i))
1194 darwin_release_interface (dev_handle, i);
1196 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
1197 if (kresult != kIOReturnSuccess)
1198 return darwin_to_libusb (kresult);
1200 /* Reclaim any interfaces. */
1201 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1202 if (dev_handle->claimed_interfaces & (1 << i))
1203 darwin_claim_interface (dev_handle, i);
1205 dpriv->active_config = config;
1210 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
1211 IOUSBFindInterfaceRequest request;
1212 kern_return_t kresult;
1213 io_iterator_t interface_iterator;
1214 UInt8 bInterfaceNumber;
1217 *usbInterfacep = IO_OBJECT_NULL;
1219 /* Setup the Interface Request */
1220 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1221 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1222 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1223 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1225 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1229 while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1230 /* find the interface number */
1231 ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
1234 if (ret && bInterfaceNumber == ifc) {
1238 (void) IOObjectRelease (*usbInterfacep);
1241 /* done with the interface iterator */
1242 IOObjectRelease(interface_iterator);
1247 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
1248 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1250 /* current interface */
1251 struct darwin_interface *cInterface = &priv->interfaces[iface];
1253 kern_return_t kresult;
1255 UInt8 numep, direction, number;
1256 UInt8 dont_care1, dont_care3;
1260 usbi_dbg ("building table of endpoints.");
1262 /* retrieve the total number of endpoints on this interface */
1263 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1265 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1266 return darwin_to_libusb (kresult);
1269 /* iterate through pipe references */
1270 for (int i = 1 ; i <= numep ; i++) {
1271 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1272 &dont_care2, &dont_care3);
1274 if (kresult != kIOReturnSuccess) {
1275 /* probably a buggy device. try to get the endpoint address from the descriptors */
1276 struct libusb_config_descriptor *config;
1277 const struct libusb_endpoint_descriptor *endpoint_desc;
1280 kresult = (*(cInterface->interface))->GetAlternateSetting (cInterface->interface, &alt_setting);
1282 usbi_err (HANDLE_CTX (dev_handle), "can't get alternate setting for interface");
1283 return darwin_to_libusb (kresult);
1286 rc = libusb_get_active_config_descriptor (dev_handle->dev, &config);
1287 if (LIBUSB_SUCCESS != rc) {
1291 endpoint_desc = config->interface[iface].altsetting[alt_setting].endpoint + i - 1;
1293 cInterface->endpoint_addrs[i - 1] = endpoint_desc->bEndpointAddress;
1295 cInterface->endpoint_addrs[i - 1] = (((kUSBIn == direction) << kUSBRqDirnShift) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1298 usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, cInterface->endpoint_addrs[i - 1] >> kUSBRqDirnShift,
1299 cInterface->endpoint_addrs[i - 1] & LIBUSB_ENDPOINT_ADDRESS_MASK);
1302 cInterface->num_endpoints = numep;
1307 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1308 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1309 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1310 io_service_t usbInterface = IO_OBJECT_NULL;
1312 IOCFPlugInInterface **plugInInterface = NULL;
1315 /* current interface */
1316 struct darwin_interface *cInterface = &priv->interfaces[iface];
1318 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1319 if (kresult != kIOReturnSuccess)
1320 return darwin_to_libusb (kresult);
1322 /* make sure we have an interface */
1323 if (!usbInterface && dpriv->first_config != 0) {
1324 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1326 /* set the configuration */
1327 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1328 if (kresult != LIBUSB_SUCCESS) {
1329 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1333 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1335 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1336 return darwin_to_libusb (kresult);
1340 if (!usbInterface) {
1341 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1342 return LIBUSB_ERROR_NOT_FOUND;
1345 /* get an interface to the device's interface */
1346 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1347 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1349 /* ignore release error */
1350 (void)IOObjectRelease (usbInterface);
1353 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1354 return darwin_to_libusb (kresult);
1357 if (!plugInInterface) {
1358 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1359 return LIBUSB_ERROR_NOT_FOUND;
1362 /* Do the actual claim */
1363 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1364 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1365 (LPVOID)&cInterface->interface);
1366 /* We no longer need the intermediate plug-in */
1367 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1368 (*plugInInterface)->Release (plugInInterface);
1369 if (kresult || !cInterface->interface) {
1370 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1371 return darwin_to_libusb (kresult);
1374 /* claim the interface */
1375 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1377 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1378 return darwin_to_libusb (kresult);
1381 /* update list of endpoints */
1382 kresult = get_endpoints (dev_handle, iface);
1384 /* this should not happen */
1385 darwin_release_interface (dev_handle, iface);
1386 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1390 cInterface->cfSource = NULL;
1392 /* create async event source */
1393 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1394 if (kresult != kIOReturnSuccess) {
1395 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1397 /* can't continue without an async event source */
1398 (void)darwin_release_interface (dev_handle, iface);
1400 return darwin_to_libusb (kresult);
1403 /* add the cfSource to the async thread's run loop */
1404 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1406 usbi_dbg ("interface opened");
1411 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1412 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1415 /* current interface */
1416 struct darwin_interface *cInterface = &priv->interfaces[iface];
1418 /* Check to see if an interface is open */
1419 if (!cInterface->interface)
1420 return LIBUSB_SUCCESS;
1422 /* clean up endpoint data */
1423 cInterface->num_endpoints = 0;
1425 /* delete the interface's async event source */
1426 if (cInterface->cfSource) {
1427 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1428 CFRelease (cInterface->cfSource);
1431 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1433 usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1435 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1436 if (kresult != kIOReturnSuccess)
1437 usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1439 cInterface->interface = (usb_interface_t **) IO_OBJECT_NULL;
1441 return darwin_to_libusb (kresult);
1444 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1445 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1448 /* current interface */
1449 struct darwin_interface *cInterface = &priv->interfaces[iface];
1451 if (!cInterface->interface)
1452 return LIBUSB_ERROR_NO_DEVICE;
1454 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1455 if (kresult != kIOReturnSuccess)
1456 darwin_reset_device (dev_handle);
1458 /* update list of endpoints */
1459 kresult = get_endpoints (dev_handle, iface);
1461 /* this should not happen */
1462 darwin_release_interface (dev_handle, iface);
1463 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1467 return darwin_to_libusb (kresult);
1470 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1471 /* current interface */
1472 struct darwin_interface *cInterface;
1476 /* determine the interface/endpoint to use */
1477 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, NULL, &cInterface) != 0) {
1478 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1480 return LIBUSB_ERROR_NOT_FOUND;
1483 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1484 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1486 usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1488 return darwin_to_libusb (kresult);
1491 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1492 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1493 IOUSBDeviceDescriptor descriptor;
1494 IOUSBConfigurationDescriptorPtr cached_configuration;
1495 IOUSBConfigurationDescriptor configuration;
1496 bool reenumerate = false;
1500 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1502 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1503 return darwin_to_libusb (kresult);
1507 usbi_dbg ("darwin/reset_device: checking if device descriptor changed");
1509 /* ignore return code. if we can't get a descriptor it might be worthwhile re-enumerating anway */
1510 (void) darwin_request_descriptor (dpriv->device, kUSBDeviceDesc, 0, &descriptor, sizeof (descriptor));
1512 /* check if the device descriptor has changed */
1513 if (0 != memcmp (&dpriv->dev_descriptor, &descriptor, sizeof (descriptor))) {
1518 /* check if any configuration descriptor has changed */
1519 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1520 usbi_dbg ("darwin/reset_device: checking if configuration descriptor %d changed", i);
1522 (void) darwin_request_descriptor (dpriv->device, kUSBConfDesc, i, &configuration, sizeof (configuration));
1523 (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1525 if (!cached_configuration || 0 != memcmp (cached_configuration, &configuration, sizeof (configuration))) {
1533 usbi_dbg ("darwin/reset_device: device requires reenumeration");
1534 (void) (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
1535 return LIBUSB_ERROR_NOT_FOUND;
1538 usbi_dbg ("darwin/reset_device: device reset complete");
1540 return LIBUSB_SUCCESS;
1543 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1544 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1545 io_service_t usbInterface;
1549 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1551 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1553 return darwin_to_libusb (kresult);
1556 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1557 IOObjectRelease (usbInterface);
1569 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1570 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1573 return LIBUSB_ERROR_NOT_SUPPORTED;
1576 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1579 return LIBUSB_ERROR_NOT_SUPPORTED;
1582 static void darwin_destroy_device(struct libusb_device *dev) {
1583 struct darwin_device_priv *dpriv = (struct darwin_device_priv *) dev->os_priv;
1586 /* need to hold the lock in case this is the last reference to the device */
1587 usbi_mutex_lock(&darwin_cached_devices_lock);
1588 darwin_deref_cached_device (dpriv->dev);
1590 usbi_mutex_unlock(&darwin_cached_devices_lock);
1594 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1595 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1598 uint8_t transferType;
1599 /* None of the values below are used in libusbx for bulk transfers */
1600 uint8_t direction, number, interval, pipeRef;
1601 uint16_t maxPacketSize;
1603 struct darwin_interface *cInterface;
1605 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1606 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1608 return LIBUSB_ERROR_NOT_FOUND;
1611 ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1612 &transferType, &maxPacketSize, &interval);
1615 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1616 darwin_error_str(ret), ret);
1617 return darwin_to_libusb (ret);
1620 if (0 != (transfer->length % maxPacketSize)) {
1621 /* do not need a zero packet */
1622 transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1625 /* submit the request */
1626 /* timeouts are unavailable on interrupt endpoints */
1627 if (transferType == kUSBInterrupt) {
1628 if (IS_XFERIN(transfer))
1629 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1630 transfer->length, darwin_async_io_callback, itransfer);
1632 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1633 transfer->length, darwin_async_io_callback, itransfer);
1635 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1637 if (IS_XFERIN(transfer))
1638 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1639 transfer->length, transfer->timeout, transfer->timeout,
1640 darwin_async_io_callback, (void *)itransfer);
1642 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1643 transfer->length, transfer->timeout, transfer->timeout,
1644 darwin_async_io_callback, (void *)itransfer);
1648 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1649 darwin_error_str(ret), ret);
1651 return darwin_to_libusb (ret);
1654 #if InterfaceVersion >= 550
1655 static int submit_stream_transfer(struct usbi_transfer *itransfer) {
1656 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1657 struct darwin_interface *cInterface;
1661 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1662 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1664 return LIBUSB_ERROR_NOT_FOUND;
1667 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1669 if (IS_XFERIN(transfer))
1670 ret = (*(cInterface->interface))->ReadStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1671 transfer->buffer, transfer->length, transfer->timeout,
1672 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1674 ret = (*(cInterface->interface))->WriteStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1675 transfer->buffer, transfer->length, transfer->timeout,
1676 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1679 usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1680 darwin_error_str(ret), ret);
1682 return darwin_to_libusb (ret);
1686 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1687 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1688 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1691 uint8_t direction, number, interval, pipeRef, transferType;
1692 uint16_t maxPacketSize;
1694 AbsoluteTime atTime;
1697 struct darwin_interface *cInterface;
1699 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1700 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1701 free(tpriv->isoc_framelist);
1702 tpriv->isoc_framelist = NULL;
1705 if (!tpriv->isoc_framelist) {
1706 tpriv->num_iso_packets = transfer->num_iso_packets;
1707 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1708 if (!tpriv->isoc_framelist)
1709 return LIBUSB_ERROR_NO_MEM;
1712 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1713 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1714 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1716 /* determine the interface/endpoint to use */
1717 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1718 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1720 return LIBUSB_ERROR_NOT_FOUND;
1723 /* determine the properties of this endpoint and the speed of the device */
1724 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1725 &transferType, &maxPacketSize, &interval);
1727 /* Last but not least we need the bus frame number */
1728 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1730 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1731 free(tpriv->isoc_framelist);
1732 tpriv->isoc_framelist = NULL;
1734 return darwin_to_libusb (kresult);
1737 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1738 &transferType, &maxPacketSize, &interval);
1740 /* schedule for a frame a little in the future */
1743 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1744 frame = cInterface->frames[transfer->endpoint];
1746 /* submit the request */
1747 if (IS_XFERIN(transfer))
1748 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1749 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1752 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1753 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1756 if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
1758 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1));
1760 /* High/super speed */
1761 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1)) / 8;
1763 if (kresult != kIOReturnSuccess) {
1764 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1765 darwin_error_str(kresult));
1766 free (tpriv->isoc_framelist);
1767 tpriv->isoc_framelist = NULL;
1770 return darwin_to_libusb (kresult);
1773 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1774 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1775 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1776 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1777 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1781 memset(&tpriv->req, 0, sizeof(tpriv->req));
1783 /* IOUSBDeviceInterface expects the request in cpu endianness */
1784 tpriv->req.bmRequestType = setup->bmRequestType;
1785 tpriv->req.bRequest = setup->bRequest;
1786 /* these values should be in bus order from libusb_fill_control_setup */
1787 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1788 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1789 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1790 /* data is stored after the libusb control block */
1791 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1792 tpriv->req.completionTimeout = transfer->timeout;
1793 tpriv->req.noDataTimeout = transfer->timeout;
1795 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1797 /* all transfers in libusb-1.0 are async */
1799 if (transfer->endpoint) {
1800 struct darwin_interface *cInterface;
1803 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1804 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1806 return LIBUSB_ERROR_NOT_FOUND;
1809 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1811 /* control request on endpoint 0 */
1812 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1814 if (kresult != kIOReturnSuccess)
1815 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1817 return darwin_to_libusb (kresult);
1820 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1821 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1823 switch (transfer->type) {
1824 case LIBUSB_TRANSFER_TYPE_CONTROL:
1825 return submit_control_transfer(itransfer);
1826 case LIBUSB_TRANSFER_TYPE_BULK:
1827 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1828 return submit_bulk_transfer(itransfer);
1829 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1830 return submit_iso_transfer(itransfer);
1831 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1832 #if InterfaceVersion >= 550
1833 return submit_stream_transfer(itransfer);
1835 usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers");
1836 return LIBUSB_ERROR_NOT_SUPPORTED;
1839 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1840 return LIBUSB_ERROR_INVALID_PARAM;
1844 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1845 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1846 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1849 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
1852 return LIBUSB_ERROR_NO_DEVICE;
1854 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1856 return darwin_to_libusb (kresult);
1859 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1860 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1861 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1862 struct darwin_interface *cInterface;
1863 uint8_t pipeRef, iface;
1866 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) {
1867 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1869 return LIBUSB_ERROR_NOT_FOUND;
1873 return LIBUSB_ERROR_NO_DEVICE;
1875 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
1877 /* abort transactions */
1878 #if InterfaceVersion >= 550
1879 if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type)
1880 (*(cInterface->interface))->AbortStreamsPipe (cInterface->interface, pipeRef, itransfer->stream_id);
1883 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1885 usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
1887 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1888 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1890 return darwin_to_libusb (kresult);
1893 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1894 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1896 switch (transfer->type) {
1897 case LIBUSB_TRANSFER_TYPE_CONTROL:
1898 return cancel_control_transfer(itransfer);
1899 case LIBUSB_TRANSFER_TYPE_BULK:
1900 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1901 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1902 return darwin_abort_transfers (itransfer);
1904 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1905 return LIBUSB_ERROR_INVALID_PARAM;
1909 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1910 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1911 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1913 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1914 free (tpriv->isoc_framelist);
1915 tpriv->isoc_framelist = NULL;
1919 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1920 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1921 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1922 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1924 usbi_dbg ("an async io operation has completed");
1926 /* if requested write a zero packet */
1927 if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
1928 struct darwin_interface *cInterface;
1931 (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface);
1933 (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
1936 tpriv->result = result;
1937 tpriv->size = (UInt32) (uintptr_t) arg0;
1939 /* signal the core that this transfer is complete */
1940 usbi_signal_transfer_completion(itransfer);
1943 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1944 if (itransfer->timeout_flags & USBI_TRANSFER_TIMED_OUT)
1945 result = kIOUSBTransactionTimeout;
1948 case kIOReturnUnderrun:
1949 case kIOReturnSuccess:
1950 return LIBUSB_TRANSFER_COMPLETED;
1951 case kIOReturnAborted:
1952 return LIBUSB_TRANSFER_CANCELLED;
1953 case kIOUSBPipeStalled:
1954 usbi_dbg ("transfer error: pipe is stalled");
1955 return LIBUSB_TRANSFER_STALL;
1956 case kIOReturnOverrun:
1957 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1958 return LIBUSB_TRANSFER_OVERFLOW;
1959 case kIOUSBTransactionTimeout:
1960 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1961 itransfer->timeout_flags |= USBI_TRANSFER_TIMED_OUT;
1962 return LIBUSB_TRANSFER_TIMED_OUT;
1964 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1965 return LIBUSB_TRANSFER_ERROR;
1969 static int darwin_handle_transfer_completion (struct usbi_transfer *itransfer) {
1970 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1971 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1972 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1973 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1974 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1975 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1978 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1979 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1980 return LIBUSB_ERROR_INVALID_PARAM;
1983 usbi_dbg ("handling %s completion with kernel status %d",
1984 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", tpriv->result);
1986 if (kIOReturnSuccess == tpriv->result || kIOReturnUnderrun == tpriv->result) {
1987 if (isIsoc && tpriv->isoc_framelist) {
1988 /* copy isochronous results back */
1990 for (i = 0; i < transfer->num_iso_packets ; i++) {
1991 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1992 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1993 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1996 itransfer->transferred += tpriv->size;
1999 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
2000 return usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, tpriv->result));
2003 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
2004 #if !OSX_USE_CLOCK_GETTIME
2005 mach_timespec_t sys_time;
2006 clock_serv_t clock_ref;
2009 case USBI_CLOCK_REALTIME:
2010 /* CLOCK_REALTIME represents time since the epoch */
2011 clock_ref = clock_realtime;
2013 case USBI_CLOCK_MONOTONIC:
2014 /* use system boot time as reference for the monotonic clock */
2015 clock_ref = clock_monotonic;
2018 return LIBUSB_ERROR_INVALID_PARAM;
2021 clock_get_time (clock_ref, &sys_time);
2023 tp->tv_sec = sys_time.tv_sec;
2024 tp->tv_nsec = sys_time.tv_nsec;
2029 case USBI_CLOCK_MONOTONIC:
2030 return clock_gettime(CLOCK_MONOTONIC, tp);
2031 case USBI_CLOCK_REALTIME:
2032 return clock_gettime(CLOCK_REALTIME, tp);
2034 return LIBUSB_ERROR_INVALID_PARAM;
2039 #if InterfaceVersion >= 550
2040 static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints,
2041 int num_endpoints) {
2042 struct darwin_interface *cInterface;
2043 UInt32 supportsStreams;
2047 /* find the mimimum number of supported streams on the endpoint list */
2048 for (i = 0 ; i < num_endpoints ; ++i) {
2049 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) {
2053 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2054 if (num_streams > supportsStreams)
2055 num_streams = supportsStreams;
2058 /* it is an error if any endpoint in endpoints does not support streams */
2059 if (0 == num_streams)
2060 return LIBUSB_ERROR_INVALID_PARAM;
2062 /* create the streams */
2063 for (i = 0 ; i < num_endpoints ; ++i) {
2064 (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
2066 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, num_streams);
2067 if (kIOReturnSuccess != rc)
2068 return darwin_to_libusb(rc);
2074 static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) {
2075 struct darwin_interface *cInterface;
2076 UInt32 supportsStreams;
2080 for (int i = 0 ; i < num_endpoints ; ++i) {
2081 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface)))
2084 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2085 if (0 == supportsStreams)
2086 return LIBUSB_ERROR_INVALID_PARAM;
2088 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, 0);
2089 if (kIOReturnSuccess != rc)
2090 return darwin_to_libusb(rc);
2093 return LIBUSB_SUCCESS;
2097 const struct usbi_os_backend usbi_backend = {
2100 .init = darwin_init,
2101 .exit = darwin_exit,
2102 .get_device_list = NULL, /* not needed */
2103 .get_device_descriptor = darwin_get_device_descriptor,
2104 .get_active_config_descriptor = darwin_get_active_config_descriptor,
2105 .get_config_descriptor = darwin_get_config_descriptor,
2106 .hotplug_poll = darwin_hotplug_poll,
2108 .open = darwin_open,
2109 .close = darwin_close,
2110 .get_configuration = darwin_get_configuration,
2111 .set_configuration = darwin_set_configuration,
2112 .claim_interface = darwin_claim_interface,
2113 .release_interface = darwin_release_interface,
2115 .set_interface_altsetting = darwin_set_interface_altsetting,
2116 .clear_halt = darwin_clear_halt,
2117 .reset_device = darwin_reset_device,
2119 #if InterfaceVersion >= 550
2120 .alloc_streams = darwin_alloc_streams,
2121 .free_streams = darwin_free_streams,
2124 .kernel_driver_active = darwin_kernel_driver_active,
2125 .detach_kernel_driver = darwin_detach_kernel_driver,
2126 .attach_kernel_driver = darwin_attach_kernel_driver,
2128 .destroy_device = darwin_destroy_device,
2130 .submit_transfer = darwin_submit_transfer,
2131 .cancel_transfer = darwin_cancel_transfer,
2132 .clear_transfer_priv = darwin_clear_transfer_priv,
2134 .handle_transfer_completion = darwin_handle_transfer_completion,
2136 .clock_gettime = darwin_clock_gettime,
2138 .device_priv_size = sizeof(struct darwin_device_priv),
2139 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
2140 .transfer_priv_size = sizeof(struct darwin_transfer_priv),