1 /* -*- Mode: C; indent-tabs-mode:nil -*- */
3 * darwin backend for libusb 1.0
4 * Copyright © 2008-2016 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
41 #include <objc/objc-auto.h>
44 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 101300
45 /* Apple deprecated the darwin atomics in 10.12 in favor of C11 atomics */
46 #include <stdatomic.h>
47 #define libusb_darwin_atomic_fetch_add(x, y) atomic_fetch_add(x, y)
49 _Atomic int32_t initCount = ATOMIC_VAR_INIT(0);
51 /* use darwin atomics if the target is older than 10.12 */
52 #include <libkern/OSAtomic.h>
54 /* OSAtomicAdd32Barrier returns the new value */
55 #define libusb_darwin_atomic_fetch_add(x, y) (OSAtomicAdd32Barrier(x, y) - y)
57 static volatile int32_t initCount = 0;
60 #include "darwin_usb.h"
62 /* async event thread */
63 static pthread_mutex_t libusb_darwin_at_mutex = PTHREAD_MUTEX_INITIALIZER;
64 static pthread_cond_t libusb_darwin_at_cond = PTHREAD_COND_INITIALIZER;
66 static pthread_once_t darwin_init_once = PTHREAD_ONCE_INIT;
68 static clock_serv_t clock_realtime;
69 static clock_serv_t clock_monotonic;
71 static CFRunLoopRef libusb_darwin_acfl = NULL; /* event cf loop */
72 static CFRunLoopSourceRef libusb_darwin_acfls = NULL; /* shutdown signal for event cf loop */
74 static usbi_mutex_t darwin_cached_devices_lock = PTHREAD_MUTEX_INITIALIZER;
75 static struct list_head darwin_cached_devices = {&darwin_cached_devices, &darwin_cached_devices};
76 static char *darwin_device_class = kIOUSBDeviceClassName;
78 #define DARWIN_CACHED_DEVICE(a) ((struct darwin_cached_device *) (((struct darwin_device_priv *)((a)->os_priv))->dev))
80 /* async event thread */
81 static pthread_t libusb_darwin_at;
83 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
84 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
85 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
86 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
87 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
89 static int darwin_scan_devices(struct libusb_context *ctx);
90 static int process_new_device (struct libusb_context *ctx, io_service_t service);
92 #if defined(ENABLE_LOGGING)
93 static const char *darwin_error_str (int result) {
94 static char string_buffer[50];
96 case kIOReturnSuccess:
98 case kIOReturnNotOpen:
99 return "device not opened for exclusive access";
100 case kIOReturnNoDevice:
101 return "no connection to an IOService";
102 case kIOUSBNoAsyncPortErr:
103 return "no async port has been opened for interface";
104 case kIOReturnExclusiveAccess:
105 return "another process has device opened for exclusive access";
106 case kIOUSBPipeStalled:
107 return "pipe is stalled";
109 return "could not establish a connection to the Darwin kernel";
110 case kIOUSBTransactionTimeout:
111 return "transaction timed out";
112 case kIOReturnBadArgument:
113 return "invalid argument";
114 case kIOReturnAborted:
115 return "transaction aborted";
116 case kIOReturnNotResponding:
117 return "device not responding";
118 case kIOReturnOverrun:
119 return "data overrun";
120 case kIOReturnCannotWire:
121 return "physical memory can not be wired down";
122 case kIOReturnNoResources:
123 return "out of resources";
124 case kIOUSBHighSpeedSplitError:
125 return "high speed split error";
127 snprintf(string_buffer, sizeof(string_buffer), "unknown error (0x%x)", result);
128 return string_buffer;
133 static int darwin_to_libusb (int result) {
135 case kIOReturnUnderrun:
136 case kIOReturnSuccess:
137 return LIBUSB_SUCCESS;
138 case kIOReturnNotOpen:
139 case kIOReturnNoDevice:
140 return LIBUSB_ERROR_NO_DEVICE;
141 case kIOReturnExclusiveAccess:
142 return LIBUSB_ERROR_ACCESS;
143 case kIOUSBPipeStalled:
144 return LIBUSB_ERROR_PIPE;
145 case kIOReturnBadArgument:
146 return LIBUSB_ERROR_INVALID_PARAM;
147 case kIOUSBTransactionTimeout:
148 return LIBUSB_ERROR_TIMEOUT;
149 case kIOReturnNotResponding:
150 case kIOReturnAborted:
152 case kIOUSBNoAsyncPortErr:
154 return LIBUSB_ERROR_OTHER;
158 /* this function must be called with the darwin_cached_devices_lock held */
159 static void darwin_deref_cached_device(struct darwin_cached_device *cached_dev) {
160 cached_dev->refcount--;
161 /* free the device and remove it from the cache */
162 if (0 == cached_dev->refcount) {
163 list_del(&cached_dev->list);
165 (*(cached_dev->device))->Release(cached_dev->device);
170 static void darwin_ref_cached_device(struct darwin_cached_device *cached_dev) {
171 cached_dev->refcount++;
174 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) {
175 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
177 /* current interface */
178 struct darwin_interface *cInterface;
182 usbi_dbg ("converting ep address 0x%02x to pipeRef and interface", ep);
184 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
185 cInterface = &priv->interfaces[iface];
187 if (dev_handle->claimed_interfaces & (1 << iface)) {
188 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
189 if (cInterface->endpoint_addrs[i] == ep) {
196 *interface_out = cInterface;
198 usbi_dbg ("pipe %d on interface %d matches", *pipep, iface);
205 /* No pipe found with the correct endpoint address */
206 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
208 return LIBUSB_ERROR_NOT_FOUND;
211 static int usb_setup_device_iterator (io_iterator_t *deviceIterator, UInt32 location) {
212 CFMutableDictionaryRef matchingDict = IOServiceMatching(darwin_device_class);
215 return kIOReturnError;
218 CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
219 &kCFTypeDictionaryKeyCallBacks,
220 &kCFTypeDictionaryValueCallBacks);
222 if (propertyMatchDict) {
223 /* there are no unsigned CFNumber types so treat the value as signed. the os seems to do this
224 internally (CFNumberType of locationID is 3) */
225 CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberSInt32Type, &location);
227 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
228 /* release our reference to the CFNumber (CFDictionarySetValue retains it) */
229 CFRelease (locationCF);
231 CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
232 /* release out reference to the CFMutableDictionaryRef (CFDictionarySetValue retains it) */
233 CFRelease (propertyMatchDict);
235 /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
238 return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator);
241 /* Returns 1 on success, 0 on failure. */
242 static int get_ioregistry_value_number (io_service_t service, CFStringRef property, CFNumberType type, void *p) {
243 CFTypeRef cfNumber = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
247 if (CFGetTypeID(cfNumber) == CFNumberGetTypeID()) {
248 ret = CFNumberGetValue(cfNumber, type, p);
251 CFRelease (cfNumber);
257 static int get_ioregistry_value_data (io_service_t service, CFStringRef property, ssize_t size, void *p) {
258 CFTypeRef cfData = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
262 if (CFGetTypeID (cfData) == CFDataGetTypeID ()) {
263 CFIndex length = CFDataGetLength (cfData);
268 CFDataGetBytes (cfData, CFRangeMake(0, size), p);
278 static usb_device_t **darwin_device_from_service (io_service_t service)
280 io_cf_plugin_ref_t *plugInInterface = NULL;
281 usb_device_t **device;
282 kern_return_t result;
285 result = IOCreatePlugInInterfaceForService(service, kIOUSBDeviceUserClientTypeID,
286 kIOCFPlugInInterfaceID, &plugInInterface,
289 if (kIOReturnSuccess != result || !plugInInterface) {
290 usbi_dbg ("could not set up plugin for service: %s", darwin_error_str (result));
294 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
296 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
297 (*plugInInterface)->Release (plugInInterface);
302 static void darwin_devices_attached (void *ptr, io_iterator_t add_devices) {
303 struct libusb_context *ctx;
304 io_service_t service;
306 usbi_mutex_lock(&active_contexts_lock);
308 while ((service = IOIteratorNext(add_devices))) {
309 /* add this device to each active context's device list */
310 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
311 process_new_device (ctx, service);;
314 IOObjectRelease(service);
317 usbi_mutex_unlock(&active_contexts_lock);
320 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
321 struct libusb_device *dev = NULL;
322 struct libusb_context *ctx;
323 struct darwin_cached_device *old_device;
329 usbi_mutex_lock(&active_contexts_lock);
331 while ((device = IOIteratorNext (rem_devices)) != 0) {
332 /* get the location from the i/o registry */
333 ret = get_ioregistry_value_number (device, CFSTR("sessionID"), kCFNumberSInt64Type, &session);
334 IOObjectRelease (device);
338 /* we need to match darwin_ref_cached_device call made in darwin_get_cached_device function
339 otherwise no cached device will ever get freed */
340 usbi_mutex_lock(&darwin_cached_devices_lock);
341 list_for_each_entry(old_device, &darwin_cached_devices, list, struct darwin_cached_device) {
342 if (old_device->session == session) {
343 darwin_deref_cached_device (old_device);
347 usbi_mutex_unlock(&darwin_cached_devices_lock);
349 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
350 usbi_dbg ("notifying context %p of device disconnect", ctx);
352 dev = usbi_get_device_by_session_id(ctx, (unsigned long) session);
354 /* signal the core that this device has been disconnected. the core will tear down this device
355 when the reference count reaches 0 */
356 usbi_disconnect_device(dev);
357 libusb_unref_device(dev);
362 usbi_mutex_unlock(&active_contexts_lock);
365 static void darwin_hotplug_poll (void)
367 /* not sure if 5 seconds will be too long/short but it should work ok */
368 mach_timespec_t timeout = {.tv_sec = 5, .tv_nsec = 0};
370 /* since a kernel thread may nodify the IOInterators used for
371 * hotplug notidication we can't just clear the iterators.
372 * instead just wait until all IOService providers are quiet */
373 (void) IOKitWaitQuiet (kIOMasterPortDefault, &timeout);
376 static void darwin_clear_iterator (io_iterator_t iter) {
379 while ((device = IOIteratorNext (iter)) != 0)
380 IOObjectRelease (device);
383 static void *darwin_event_thread_main (void *arg0) {
385 struct libusb_context *ctx = (struct libusb_context *)arg0;
386 CFRunLoopRef runloop;
388 /* Set this thread's name, so it can be seen in the debugger
389 and crash reports. */
390 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED <= 1080
391 pthread_setname_np ("org.libusb.device-hotplug");
393 /* Tell the Objective-C garbage collector about this thread.
394 This is required because, unlike NSThreads, pthreads are
395 not automatically registered. Although we don't use
396 Objective-C, we use CoreFoundation, which does. */
397 objc_registerThreadWithCollector();
400 /* hotplug (device arrival/removal) sources */
401 CFRunLoopSourceContext libusb_shutdown_cfsourcectx;
402 CFRunLoopSourceRef libusb_notification_cfsource;
403 io_notification_port_t libusb_notification_port;
404 io_iterator_t libusb_rem_device_iterator;
405 io_iterator_t libusb_add_device_iterator;
407 usbi_dbg ("creating hotplug event source");
409 runloop = CFRunLoopGetCurrent ();
412 /* add the shutdown cfsource to the run loop */
413 memset(&libusb_shutdown_cfsourcectx, 0, sizeof(libusb_shutdown_cfsourcectx));
414 libusb_shutdown_cfsourcectx.info = runloop;
415 libusb_shutdown_cfsourcectx.perform = (void (*)(void *))CFRunLoopStop;
416 libusb_darwin_acfls = CFRunLoopSourceCreate(NULL, 0, &libusb_shutdown_cfsourcectx);
417 CFRunLoopAddSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
419 /* add the notification port to the run loop */
420 libusb_notification_port = IONotificationPortCreate (kIOMasterPortDefault);
421 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
422 CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
424 /* create notifications for removed devices */
425 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
426 IOServiceMatching(darwin_device_class),
427 darwin_devices_detached,
428 ctx, &libusb_rem_device_iterator);
430 if (kresult != kIOReturnSuccess) {
431 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
436 /* create notifications for attached devices */
437 kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
438 IOServiceMatching(darwin_device_class),
439 darwin_devices_attached,
440 ctx, &libusb_add_device_iterator);
442 if (kresult != kIOReturnSuccess) {
443 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
449 darwin_clear_iterator (libusb_rem_device_iterator);
450 darwin_clear_iterator (libusb_add_device_iterator);
452 usbi_dbg ("darwin event thread ready to receive events");
454 /* signal the main thread that the hotplug runloop has been created. */
455 pthread_mutex_lock (&libusb_darwin_at_mutex);
456 libusb_darwin_acfl = runloop;
457 pthread_cond_signal (&libusb_darwin_at_cond);
458 pthread_mutex_unlock (&libusb_darwin_at_mutex);
460 /* run the runloop */
463 usbi_dbg ("darwin event thread exiting");
465 /* remove the notification cfsource */
466 CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
468 /* remove the shutdown cfsource */
469 CFRunLoopRemoveSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
471 /* delete notification port */
472 IONotificationPortDestroy (libusb_notification_port);
474 /* delete iterators */
475 IOObjectRelease (libusb_rem_device_iterator);
476 IOObjectRelease (libusb_add_device_iterator);
478 CFRelease (libusb_darwin_acfls);
481 libusb_darwin_acfls = NULL;
482 libusb_darwin_acfl = NULL;
487 /* cleanup function to destroy cached devices */
488 static void __attribute__((destructor)) _darwin_finalize(void) {
489 struct darwin_cached_device *dev, *next;
491 usbi_mutex_lock(&darwin_cached_devices_lock);
492 list_for_each_entry_safe(dev, next, &darwin_cached_devices, list, struct darwin_cached_device) {
493 darwin_deref_cached_device(dev);
495 usbi_mutex_unlock(&darwin_cached_devices_lock);
498 static void darwin_check_version (void) {
499 /* adjust for changes in the USB stack in xnu 15 */
500 int sysctl_args[] = {CTL_KERN, KERN_OSRELEASE};
502 char version_string[256] = {'\0',};
505 sysctl(sysctl_args, 2, version_string, &length, NULL, 0);
508 version = strtol (version_string, NULL, 10);
509 if (0 == errno && version >= 15) {
510 darwin_device_class = "IOUSBHostDevice";
514 static int darwin_init(struct libusb_context *ctx) {
515 host_name_port_t host_self;
518 rc = pthread_once (&darwin_init_once, darwin_check_version);
520 return LIBUSB_ERROR_OTHER;
523 rc = darwin_scan_devices (ctx);
524 if (LIBUSB_SUCCESS != rc) {
528 if (libusb_darwin_atomic_fetch_add (&initCount, 1) == 0) {
529 /* create the clocks that will be used */
531 host_self = mach_host_self();
532 host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
533 host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
534 mach_port_deallocate(mach_task_self(), host_self);
536 pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, ctx);
538 pthread_mutex_lock (&libusb_darwin_at_mutex);
539 while (!libusb_darwin_acfl)
540 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
541 pthread_mutex_unlock (&libusb_darwin_at_mutex);
547 static void darwin_exit (void) {
548 if (libusb_darwin_atomic_fetch_add (&initCount, -1) == 1) {
549 mach_port_deallocate(mach_task_self(), clock_realtime);
550 mach_port_deallocate(mach_task_self(), clock_monotonic);
552 /* stop the event runloop and wait for the thread to terminate. */
553 CFRunLoopSourceSignal(libusb_darwin_acfls);
554 CFRunLoopWakeUp (libusb_darwin_acfl);
555 pthread_join (libusb_darwin_at, NULL);
559 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
560 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
562 /* return cached copy */
563 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
570 static int get_configuration_index (struct libusb_device *dev, int config_value) {
571 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
573 IOUSBConfigurationDescriptorPtr desc;
576 /* is there a simpler way to determine the index? */
577 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
578 if (kresult != kIOReturnSuccess)
579 return darwin_to_libusb (kresult);
581 for (i = 0 ; i < numConfig ; i++) {
582 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
584 if (desc->bConfigurationValue == config_value)
588 /* configuration not found */
589 return LIBUSB_ERROR_NOT_FOUND;
592 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
593 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
596 if (0 == priv->active_config)
597 return LIBUSB_ERROR_NOT_FOUND;
599 config_index = get_configuration_index (dev, priv->active_config);
600 if (config_index < 0)
603 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
606 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
607 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
608 IOUSBConfigurationDescriptorPtr desc;
612 if (!priv || !priv->device)
613 return LIBUSB_ERROR_OTHER;
615 kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
616 if (kresult == kIOReturnSuccess) {
617 /* copy descriptor */
618 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
619 len = libusb_le16_to_cpu(desc->wTotalLength);
621 memmove (buffer, desc, len);
623 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
627 ret = darwin_to_libusb (kresult);
628 if (ret != LIBUSB_SUCCESS)
634 /* check whether the os has configured the device */
635 static int darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) {
636 usb_device_t **darwin_device = dev->device;
638 IOUSBConfigurationDescriptorPtr configDesc;
639 IOUSBFindInterfaceRequest request;
640 kern_return_t kresult;
641 io_iterator_t interface_iterator;
642 io_service_t firstInterface;
644 if (dev->dev_descriptor.bNumConfigurations < 1) {
645 usbi_err (ctx, "device has no configurations");
646 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
649 /* checking the configuration of a root hub simulation takes ~1 s in 10.11. the device is
651 if (0x05ac == dev->dev_descriptor.idVendor && 0x8005 == dev->dev_descriptor.idProduct) {
652 usbi_dbg ("ignoring configuration on root hub simulation");
653 dev->active_config = 0;
657 /* find the first configuration */
658 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
659 dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
661 /* check if the device is already configured. there is probably a better way than iterating over the
662 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
663 might lock up on the device request) */
665 /* Setup the Interface Request */
666 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
667 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
668 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
669 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
671 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
673 return darwin_to_libusb (kresult);
676 firstInterface = IOIteratorNext(interface_iterator);
678 /* done with the interface iterator */
679 IOObjectRelease(interface_iterator);
681 if (firstInterface) {
682 IOObjectRelease (firstInterface);
684 /* device is configured */
685 if (dev->dev_descriptor.bNumConfigurations == 1)
686 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
687 dev->active_config = dev->first_config;
689 /* devices with more than one configuration should work with GetConfiguration */
690 (*darwin_device)->GetConfiguration (darwin_device, &dev->active_config);
693 dev->active_config = 0;
695 usbi_dbg ("active config: %u, first config: %u", dev->active_config, dev->first_config);
700 static int darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
701 IOUSBDevRequestTO req;
703 memset (buffer, 0, buffer_size);
705 /* Set up request for descriptor/ */
706 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
707 req.bRequest = kUSBRqGetDescriptor;
708 req.wValue = desc << 8;
709 req.wIndex = desc_index;
710 req.wLength = buffer_size;
712 req.noDataTimeout = 20;
713 req.completionTimeout = 100;
715 return (*device)->DeviceRequestTO (device, &req);
718 static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct darwin_cached_device *dev) {
719 usb_device_t **device = dev->device;
720 int retries = 1, delay = 30000;
721 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
725 UInt16 idProduct, idVendor;
727 dev->can_enumerate = 0;
729 (*device)->GetDeviceClass (device, &bDeviceClass);
730 (*device)->GetDeviceProduct (device, &idProduct);
731 (*device)->GetDeviceVendor (device, &idVendor);
733 /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
734 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
735 * to follow the spec as closely as possible, try opening the device */
736 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
739 /**** retrieve device descriptor ****/
740 ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &dev->dev_descriptor, sizeof(dev->dev_descriptor));
742 if (kIOReturnOverrun == ret && kUSBDeviceDesc == dev->dev_descriptor.bDescriptorType)
743 /* received an overrun error but we still received a device descriptor */
744 ret = kIOReturnSuccess;
746 if (kIOUSBVendorIDAppleComputer == idVendor) {
747 /* NTH: don't bother retrying or unsuspending Apple devices */
751 if (kIOReturnSuccess == ret && (0 == dev->dev_descriptor.bNumConfigurations ||
752 0 == dev->dev_descriptor.bcdUSB)) {
753 /* work around for incorrectly configured devices */
754 if (try_reconfigure && is_open) {
755 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
757 /* set the first configuration */
758 (*device)->SetConfiguration(device, 1);
760 /* don't try to reconfigure again */
764 ret = kIOUSBPipeStalled;
767 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
768 /* device may be suspended. unsuspend it and try again */
769 #if DeviceVersion >= 320
772 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
773 (void)(*device)->GetUSBDeviceInformation (device, &info);
775 /* note that the device was suspended */
776 if (info & (1 << kUSBInformationDeviceIsSuspendedBit) || 0 == info)
781 /* try to unsuspend the device */
782 ret2 = (*device)->USBDeviceSuspend (device, 0);
783 if (kIOReturnSuccess != ret2) {
784 /* prevent log spew from poorly behaving devices. this indicates the
785 os actually had trouble communicating with the device */
786 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
794 if (kIOReturnSuccess != ret) {
795 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
796 /* sleep for a little while before trying again */
797 nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000UL}, NULL);
799 } while (kIOReturnSuccess != ret && retries--);
802 /* resuspend the device */
803 (void)(*device)->USBDeviceSuspend (device, 1);
806 (void) (*device)->USBDeviceClose (device);
808 if (ret != kIOReturnSuccess) {
809 /* a debug message was already printed out for this error */
810 if (LIBUSB_CLASS_HUB == bDeviceClass)
811 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
812 idVendor, idProduct, darwin_error_str (ret), ret);
814 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
815 idVendor, idProduct, darwin_error_str (ret), ret);
816 return darwin_to_libusb (ret);
819 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
820 if (libusb_le16_to_cpu (dev->dev_descriptor.idProduct) != idProduct) {
821 /* not a valid device */
822 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
823 idProduct, libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
824 return LIBUSB_ERROR_NO_DEVICE;
827 usbi_dbg ("cached device descriptor:");
828 usbi_dbg (" bDescriptorType: 0x%02x", dev->dev_descriptor.bDescriptorType);
829 usbi_dbg (" bcdUSB: 0x%04x", dev->dev_descriptor.bcdUSB);
830 usbi_dbg (" bDeviceClass: 0x%02x", dev->dev_descriptor.bDeviceClass);
831 usbi_dbg (" bDeviceSubClass: 0x%02x", dev->dev_descriptor.bDeviceSubClass);
832 usbi_dbg (" bDeviceProtocol: 0x%02x", dev->dev_descriptor.bDeviceProtocol);
833 usbi_dbg (" bMaxPacketSize0: 0x%02x", dev->dev_descriptor.bMaxPacketSize0);
834 usbi_dbg (" idVendor: 0x%04x", dev->dev_descriptor.idVendor);
835 usbi_dbg (" idProduct: 0x%04x", dev->dev_descriptor.idProduct);
836 usbi_dbg (" bcdDevice: 0x%04x", dev->dev_descriptor.bcdDevice);
837 usbi_dbg (" iManufacturer: 0x%02x", dev->dev_descriptor.iManufacturer);
838 usbi_dbg (" iProduct: 0x%02x", dev->dev_descriptor.iProduct);
839 usbi_dbg (" iSerialNumber: 0x%02x", dev->dev_descriptor.iSerialNumber);
840 usbi_dbg (" bNumConfigurations: 0x%02x", dev->dev_descriptor.bNumConfigurations);
842 dev->can_enumerate = 1;
844 return LIBUSB_SUCCESS;
847 static int get_device_port (io_service_t service, UInt8 *port) {
848 kern_return_t result;
852 if (get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, port)) {
856 result = IORegistryEntryGetParentEntry (service, kIOServicePlane, &parent);
857 if (kIOReturnSuccess == result) {
858 ret = get_ioregistry_value_data (parent, CFSTR("port"), 1, port);
859 IOObjectRelease (parent);
865 static int darwin_get_cached_device(struct libusb_context *ctx, io_service_t service,
866 struct darwin_cached_device **cached_out) {
867 struct darwin_cached_device *new_device;
868 UInt64 sessionID = 0, parent_sessionID = 0;
869 int ret = LIBUSB_SUCCESS;
870 usb_device_t **device;
872 kern_return_t result;
875 /* get some info from the io registry */
876 (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
877 if (!get_device_port (service, &port)) {
878 usbi_dbg("could not get connected port number");
881 usbi_dbg("finding cached device for sessionID 0x%" PRIx64, sessionID);
883 result = IORegistryEntryGetParentEntry (service, kIOUSBPlane, &parent);
885 if (kIOReturnSuccess == result) {
886 (void) get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, &parent_sessionID);
887 IOObjectRelease(parent);
890 usbi_mutex_lock(&darwin_cached_devices_lock);
894 list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) {
895 usbi_dbg("matching sessionID 0x%" PRIx64 " against cached device with sessionID 0x%" PRIx64, sessionID, new_device->session);
896 if (new_device->session == sessionID) {
897 usbi_dbg("using cached device for device");
898 *cached_out = new_device;
906 usbi_dbg("caching new device with sessionID 0x%" PRIx64, sessionID);
908 device = darwin_device_from_service (service);
910 ret = LIBUSB_ERROR_NO_DEVICE;
914 new_device = calloc (1, sizeof (*new_device));
916 ret = LIBUSB_ERROR_NO_MEM;
920 /* add this device to the cached device list */
921 list_add(&new_device->list, &darwin_cached_devices);
923 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
925 /* keep a reference to this device */
926 darwin_ref_cached_device(new_device);
928 new_device->device = device;
929 new_device->session = sessionID;
930 (*device)->GetLocationID (device, &new_device->location);
931 new_device->port = port;
932 new_device->parent_session = parent_sessionID;
934 /* cache the device descriptor */
935 ret = darwin_cache_device_descriptor(ctx, new_device);
939 if (new_device->can_enumerate) {
940 snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address,
941 new_device->dev_descriptor.idVendor, new_device->dev_descriptor.idProduct,
942 new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass);
946 usbi_mutex_unlock(&darwin_cached_devices_lock);
948 /* keep track of devices regardless of if we successfully enumerate them to
949 prevent them from being enumerated multiple times */
951 *cached_out = new_device;
956 static int process_new_device (struct libusb_context *ctx, io_service_t service) {
957 struct darwin_device_priv *priv;
958 struct libusb_device *dev = NULL;
959 struct darwin_cached_device *cached_device;
964 ret = darwin_get_cached_device (ctx, service, &cached_device);
966 if (ret < 0 || !cached_device->can_enumerate) {
970 /* check current active configuration (and cache the first configuration value--
971 which may be used by claim_interface) */
972 ret = darwin_check_configuration (ctx, cached_device);
976 usbi_dbg ("allocating new device in context %p for with session 0x%" PRIx64,
977 ctx, cached_device->session);
979 dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
981 return LIBUSB_ERROR_NO_MEM;
984 priv = (struct darwin_device_priv *)dev->os_priv;
986 priv->dev = cached_device;
987 darwin_ref_cached_device (priv->dev);
989 if (cached_device->parent_session > 0) {
990 dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session);
992 dev->parent_dev = NULL;
994 dev->port_number = cached_device->port;
995 dev->bus_number = cached_device->location >> 24;
996 dev->device_address = cached_device->address;
998 (*(priv->dev->device))->GetDeviceSpeed (priv->dev->device, &devSpeed);
1001 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
1002 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
1003 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
1004 #if DeviceVersion >= 500
1005 case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
1008 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
1011 ret = usbi_sanitize_device (dev);
1015 usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
1016 dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
1020 usbi_connect_device (dev);
1022 libusb_unref_device (dev);
1028 static int darwin_scan_devices(struct libusb_context *ctx) {
1029 io_iterator_t deviceIterator;
1030 io_service_t service;
1031 kern_return_t kresult;
1033 kresult = usb_setup_device_iterator (&deviceIterator, 0);
1034 if (kresult != kIOReturnSuccess)
1035 return darwin_to_libusb (kresult);
1037 while ((service = IOIteratorNext (deviceIterator))) {
1038 (void) process_new_device (ctx, service);
1040 IOObjectRelease(service);
1043 IOObjectRelease(deviceIterator);
1048 static int darwin_open (struct libusb_device_handle *dev_handle) {
1049 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1050 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1053 if (0 == dpriv->open_count) {
1054 /* try to open the device */
1055 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
1056 if (kresult != kIOReturnSuccess) {
1057 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
1059 if (kIOReturnExclusiveAccess != kresult) {
1060 return darwin_to_libusb (kresult);
1063 /* it is possible to perform some actions on a device that is not open so do not return an error */
1069 /* create async event source */
1070 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
1071 if (kresult != kIOReturnSuccess) {
1072 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
1074 if (priv->is_open) {
1075 (*(dpriv->device))->USBDeviceClose (dpriv->device);
1080 return darwin_to_libusb (kresult);
1083 CFRetain (libusb_darwin_acfl);
1085 /* add the cfSource to the aync run loop */
1086 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
1089 /* device opened successfully */
1090 dpriv->open_count++;
1092 usbi_dbg ("device open for access");
1097 static void darwin_close (struct libusb_device_handle *dev_handle) {
1098 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1099 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1103 if (dpriv->open_count == 0) {
1104 /* something is probably very wrong if this is the case */
1105 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!");
1109 dpriv->open_count--;
1111 /* make sure all interfaces are released */
1112 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1113 if (dev_handle->claimed_interfaces & (1 << i))
1114 libusb_release_interface (dev_handle, i);
1116 if (0 == dpriv->open_count) {
1117 /* delete the device's async event source */
1118 if (priv->cfSource) {
1119 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
1120 CFRelease (priv->cfSource);
1121 priv->cfSource = NULL;
1122 CFRelease (libusb_darwin_acfl);
1125 if (priv->is_open) {
1126 /* close the device */
1127 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
1129 /* Log the fact that we had a problem closing the file, however failing a
1130 * close isn't really an error, so return success anyway */
1131 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
1137 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
1138 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1140 *config = (int) dpriv->active_config;
1145 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
1146 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1150 /* Setting configuration will invalidate the interface, so we need
1151 to reclaim it. First, dispose of existing interfaces, if any. */
1152 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1153 if (dev_handle->claimed_interfaces & (1 << i))
1154 darwin_release_interface (dev_handle, i);
1156 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
1157 if (kresult != kIOReturnSuccess)
1158 return darwin_to_libusb (kresult);
1160 /* Reclaim any interfaces. */
1161 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1162 if (dev_handle->claimed_interfaces & (1 << i))
1163 darwin_claim_interface (dev_handle, i);
1165 dpriv->active_config = config;
1170 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
1171 IOUSBFindInterfaceRequest request;
1172 kern_return_t kresult;
1173 io_iterator_t interface_iterator;
1174 UInt8 bInterfaceNumber;
1177 *usbInterfacep = IO_OBJECT_NULL;
1179 /* Setup the Interface Request */
1180 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1181 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1182 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1183 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1185 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1189 while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1190 /* find the interface number */
1191 ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
1194 if (ret && bInterfaceNumber == ifc) {
1198 (void) IOObjectRelease (*usbInterfacep);
1201 /* done with the interface iterator */
1202 IOObjectRelease(interface_iterator);
1207 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
1208 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1210 /* current interface */
1211 struct darwin_interface *cInterface = &priv->interfaces[iface];
1213 kern_return_t kresult;
1215 u_int8_t numep, direction, number;
1216 u_int8_t dont_care1, dont_care3;
1217 u_int16_t dont_care2;
1220 usbi_dbg ("building table of endpoints.");
1222 /* retrieve the total number of endpoints on this interface */
1223 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1225 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1226 return darwin_to_libusb (kresult);
1229 /* iterate through pipe references */
1230 for (int i = 1 ; i <= numep ; i++) {
1231 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1232 &dont_care2, &dont_care3);
1234 if (kresult != kIOReturnSuccess) {
1235 /* probably a buggy device. try to get the endpoint address from the descriptors */
1236 struct libusb_config_descriptor *config;
1237 const struct libusb_endpoint_descriptor *endpoint_desc;
1240 kresult = (*(cInterface->interface))->GetAlternateSetting (cInterface->interface, &alt_setting);
1242 usbi_err (HANDLE_CTX (dev_handle), "can't get alternate setting for interface");
1243 return darwin_to_libusb (kresult);
1246 rc = libusb_get_active_config_descriptor (dev_handle->dev, &config);
1247 if (LIBUSB_SUCCESS != rc) {
1251 endpoint_desc = config->interface[iface].altsetting[alt_setting].endpoint + i - 1;
1253 cInterface->endpoint_addrs[i - 1] = endpoint_desc->bEndpointAddress;
1255 cInterface->endpoint_addrs[i - 1] = (((kUSBIn == direction) << kUSBRqDirnShift) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1258 usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, cInterface->endpoint_addrs[i - 1] >> kUSBRqDirnShift,
1259 cInterface->endpoint_addrs[i - 1] & LIBUSB_ENDPOINT_ADDRESS_MASK);
1262 cInterface->num_endpoints = numep;
1267 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1268 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1269 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1270 io_service_t usbInterface = IO_OBJECT_NULL;
1272 IOCFPlugInInterface **plugInInterface = NULL;
1275 /* current interface */
1276 struct darwin_interface *cInterface = &priv->interfaces[iface];
1278 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1279 if (kresult != kIOReturnSuccess)
1280 return darwin_to_libusb (kresult);
1282 /* make sure we have an interface */
1283 if (!usbInterface && dpriv->first_config != 0) {
1284 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1286 /* set the configuration */
1287 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1288 if (kresult != LIBUSB_SUCCESS) {
1289 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1293 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1295 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1296 return darwin_to_libusb (kresult);
1300 if (!usbInterface) {
1301 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1302 return LIBUSB_ERROR_NOT_FOUND;
1305 /* get an interface to the device's interface */
1306 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1307 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1309 /* ignore release error */
1310 (void)IOObjectRelease (usbInterface);
1313 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1314 return darwin_to_libusb (kresult);
1317 if (!plugInInterface) {
1318 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1319 return LIBUSB_ERROR_NOT_FOUND;
1322 /* Do the actual claim */
1323 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1324 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1325 (LPVOID)&cInterface->interface);
1326 /* We no longer need the intermediate plug-in */
1327 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1328 (*plugInInterface)->Release (plugInInterface);
1329 if (kresult || !cInterface->interface) {
1330 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1331 return darwin_to_libusb (kresult);
1334 /* claim the interface */
1335 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1337 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1338 return darwin_to_libusb (kresult);
1341 /* update list of endpoints */
1342 kresult = get_endpoints (dev_handle, iface);
1344 /* this should not happen */
1345 darwin_release_interface (dev_handle, iface);
1346 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1350 cInterface->cfSource = NULL;
1352 /* create async event source */
1353 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1354 if (kresult != kIOReturnSuccess) {
1355 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1357 /* can't continue without an async event source */
1358 (void)darwin_release_interface (dev_handle, iface);
1360 return darwin_to_libusb (kresult);
1363 /* add the cfSource to the async thread's run loop */
1364 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1366 usbi_dbg ("interface opened");
1371 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1372 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1375 /* current interface */
1376 struct darwin_interface *cInterface = &priv->interfaces[iface];
1378 /* Check to see if an interface is open */
1379 if (!cInterface->interface)
1380 return LIBUSB_SUCCESS;
1382 /* clean up endpoint data */
1383 cInterface->num_endpoints = 0;
1385 /* delete the interface's async event source */
1386 if (cInterface->cfSource) {
1387 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1388 CFRelease (cInterface->cfSource);
1391 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1393 usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1395 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1396 if (kresult != kIOReturnSuccess)
1397 usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1399 cInterface->interface = (usb_interface_t **) IO_OBJECT_NULL;
1401 return darwin_to_libusb (kresult);
1404 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1405 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1408 /* current interface */
1409 struct darwin_interface *cInterface = &priv->interfaces[iface];
1411 if (!cInterface->interface)
1412 return LIBUSB_ERROR_NO_DEVICE;
1414 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1415 if (kresult != kIOReturnSuccess)
1416 darwin_reset_device (dev_handle);
1418 /* update list of endpoints */
1419 kresult = get_endpoints (dev_handle, iface);
1421 /* this should not happen */
1422 darwin_release_interface (dev_handle, iface);
1423 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1427 return darwin_to_libusb (kresult);
1430 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1431 /* current interface */
1432 struct darwin_interface *cInterface;
1436 /* determine the interface/endpoint to use */
1437 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, NULL, &cInterface) != 0) {
1438 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1440 return LIBUSB_ERROR_NOT_FOUND;
1443 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1444 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1446 usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1448 return darwin_to_libusb (kresult);
1451 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1452 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1453 IOUSBDeviceDescriptor descriptor;
1454 IOUSBConfigurationDescriptorPtr cached_configuration;
1455 IOUSBConfigurationDescriptor configuration;
1456 bool reenumerate = false;
1460 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1462 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1463 return darwin_to_libusb (kresult);
1467 usbi_dbg ("darwin/reset_device: checking if device descriptor changed");
1469 /* ignore return code. if we can't get a descriptor it might be worthwhile re-enumerating anway */
1470 (void) darwin_request_descriptor (dpriv->device, kUSBDeviceDesc, 0, &descriptor, sizeof (descriptor));
1472 /* check if the device descriptor has changed */
1473 if (0 != memcmp (&dpriv->dev_descriptor, &descriptor, sizeof (descriptor))) {
1478 /* check if any configuration descriptor has changed */
1479 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1480 usbi_dbg ("darwin/reset_device: checking if configuration descriptor %d changed", i);
1482 (void) darwin_request_descriptor (dpriv->device, kUSBConfDesc, i, &configuration, sizeof (configuration));
1483 (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1485 if (!cached_configuration || 0 != memcmp (cached_configuration, &configuration, sizeof (configuration))) {
1493 usbi_dbg ("darwin/reset_device: device requires reenumeration");
1494 (void) (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
1495 return LIBUSB_ERROR_NOT_FOUND;
1498 usbi_dbg ("darwin/reset_device: device reset complete");
1500 return LIBUSB_SUCCESS;
1503 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1504 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1505 io_service_t usbInterface;
1509 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1511 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1513 return darwin_to_libusb (kresult);
1516 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1517 IOObjectRelease (usbInterface);
1529 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1530 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1533 return LIBUSB_ERROR_NOT_SUPPORTED;
1536 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1539 return LIBUSB_ERROR_NOT_SUPPORTED;
1542 static void darwin_destroy_device(struct libusb_device *dev) {
1543 struct darwin_device_priv *dpriv = (struct darwin_device_priv *) dev->os_priv;
1546 /* need to hold the lock in case this is the last reference to the device */
1547 usbi_mutex_lock(&darwin_cached_devices_lock);
1548 darwin_deref_cached_device (dpriv->dev);
1550 usbi_mutex_unlock(&darwin_cached_devices_lock);
1554 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1555 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1558 uint8_t transferType;
1559 /* None of the values below are used in libusbx for bulk transfers */
1560 uint8_t direction, number, interval, pipeRef;
1561 uint16_t maxPacketSize;
1563 struct darwin_interface *cInterface;
1565 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1566 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1568 return LIBUSB_ERROR_NOT_FOUND;
1571 ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1572 &transferType, &maxPacketSize, &interval);
1575 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1576 darwin_error_str(ret), ret);
1577 return darwin_to_libusb (ret);
1580 if (0 != (transfer->length % maxPacketSize)) {
1581 /* do not need a zero packet */
1582 transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1585 /* submit the request */
1586 /* timeouts are unavailable on interrupt endpoints */
1587 if (transferType == kUSBInterrupt) {
1588 if (IS_XFERIN(transfer))
1589 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1590 transfer->length, darwin_async_io_callback, itransfer);
1592 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1593 transfer->length, darwin_async_io_callback, itransfer);
1595 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1597 if (IS_XFERIN(transfer))
1598 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1599 transfer->length, transfer->timeout, transfer->timeout,
1600 darwin_async_io_callback, (void *)itransfer);
1602 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1603 transfer->length, transfer->timeout, transfer->timeout,
1604 darwin_async_io_callback, (void *)itransfer);
1608 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1609 darwin_error_str(ret), ret);
1611 return darwin_to_libusb (ret);
1614 #if InterfaceVersion >= 550
1615 static int submit_stream_transfer(struct usbi_transfer *itransfer) {
1616 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1617 struct darwin_interface *cInterface;
1621 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1622 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1624 return LIBUSB_ERROR_NOT_FOUND;
1627 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1629 if (IS_XFERIN(transfer))
1630 ret = (*(cInterface->interface))->ReadStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1631 transfer->buffer, transfer->length, transfer->timeout,
1632 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1634 ret = (*(cInterface->interface))->WriteStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1635 transfer->buffer, transfer->length, transfer->timeout,
1636 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1639 usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1640 darwin_error_str(ret), ret);
1642 return darwin_to_libusb (ret);
1646 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1647 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1648 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1651 uint8_t direction, number, interval, pipeRef, transferType;
1652 uint16_t maxPacketSize;
1654 AbsoluteTime atTime;
1657 struct darwin_interface *cInterface;
1659 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1660 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1661 free(tpriv->isoc_framelist);
1662 tpriv->isoc_framelist = NULL;
1665 if (!tpriv->isoc_framelist) {
1666 tpriv->num_iso_packets = transfer->num_iso_packets;
1667 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1668 if (!tpriv->isoc_framelist)
1669 return LIBUSB_ERROR_NO_MEM;
1672 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1673 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1674 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1676 /* determine the interface/endpoint to use */
1677 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1678 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1680 return LIBUSB_ERROR_NOT_FOUND;
1683 /* determine the properties of this endpoint and the speed of the device */
1684 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1685 &transferType, &maxPacketSize, &interval);
1687 /* Last but not least we need the bus frame number */
1688 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1690 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1691 free(tpriv->isoc_framelist);
1692 tpriv->isoc_framelist = NULL;
1694 return darwin_to_libusb (kresult);
1697 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1698 &transferType, &maxPacketSize, &interval);
1700 /* schedule for a frame a little in the future */
1703 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1704 frame = cInterface->frames[transfer->endpoint];
1706 /* submit the request */
1707 if (IS_XFERIN(transfer))
1708 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1709 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1712 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1713 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1716 if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
1718 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1));
1720 /* High/super speed */
1721 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1)) / 8;
1723 if (kresult != kIOReturnSuccess) {
1724 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1725 darwin_error_str(kresult));
1726 free (tpriv->isoc_framelist);
1727 tpriv->isoc_framelist = NULL;
1730 return darwin_to_libusb (kresult);
1733 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1734 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1735 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1736 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1737 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1741 bzero(&tpriv->req, sizeof(tpriv->req));
1743 /* IOUSBDeviceInterface expects the request in cpu endianness */
1744 tpriv->req.bmRequestType = setup->bmRequestType;
1745 tpriv->req.bRequest = setup->bRequest;
1746 /* these values should be in bus order from libusb_fill_control_setup */
1747 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1748 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1749 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1750 /* data is stored after the libusb control block */
1751 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1752 tpriv->req.completionTimeout = transfer->timeout;
1753 tpriv->req.noDataTimeout = transfer->timeout;
1755 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1757 /* all transfers in libusb-1.0 are async */
1759 if (transfer->endpoint) {
1760 struct darwin_interface *cInterface;
1763 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1764 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1766 return LIBUSB_ERROR_NOT_FOUND;
1769 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1771 /* control request on endpoint 0 */
1772 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1774 if (kresult != kIOReturnSuccess)
1775 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1777 return darwin_to_libusb (kresult);
1780 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1781 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1783 switch (transfer->type) {
1784 case LIBUSB_TRANSFER_TYPE_CONTROL:
1785 return submit_control_transfer(itransfer);
1786 case LIBUSB_TRANSFER_TYPE_BULK:
1787 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1788 return submit_bulk_transfer(itransfer);
1789 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1790 return submit_iso_transfer(itransfer);
1791 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1792 #if InterfaceVersion >= 550
1793 return submit_stream_transfer(itransfer);
1795 usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers");
1796 return LIBUSB_ERROR_NOT_SUPPORTED;
1799 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1800 return LIBUSB_ERROR_INVALID_PARAM;
1804 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1805 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1806 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1809 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
1812 return LIBUSB_ERROR_NO_DEVICE;
1814 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1816 return darwin_to_libusb (kresult);
1819 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1820 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1821 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1822 struct darwin_interface *cInterface;
1823 uint8_t pipeRef, iface;
1826 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) {
1827 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1829 return LIBUSB_ERROR_NOT_FOUND;
1833 return LIBUSB_ERROR_NO_DEVICE;
1835 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
1837 /* abort transactions */
1838 #if InterfaceVersion >= 550
1839 if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type)
1840 (*(cInterface->interface))->AbortStreamsPipe (cInterface->interface, pipeRef, itransfer->stream_id);
1843 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1845 usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
1847 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1848 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1850 return darwin_to_libusb (kresult);
1853 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1854 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1856 switch (transfer->type) {
1857 case LIBUSB_TRANSFER_TYPE_CONTROL:
1858 return cancel_control_transfer(itransfer);
1859 case LIBUSB_TRANSFER_TYPE_BULK:
1860 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1861 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1862 return darwin_abort_transfers (itransfer);
1864 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1865 return LIBUSB_ERROR_INVALID_PARAM;
1869 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1870 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1871 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1873 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1874 free (tpriv->isoc_framelist);
1875 tpriv->isoc_framelist = NULL;
1879 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1880 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1881 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1882 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1884 usbi_dbg ("an async io operation has completed");
1886 /* if requested write a zero packet */
1887 if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
1888 struct darwin_interface *cInterface;
1891 (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface);
1893 (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
1896 tpriv->result = result;
1897 tpriv->size = (UInt32) (uintptr_t) arg0;
1899 /* signal the core that this transfer is complete */
1900 usbi_signal_transfer_completion(itransfer);
1903 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1904 if (itransfer->timeout_flags & USBI_TRANSFER_TIMED_OUT)
1905 result = kIOUSBTransactionTimeout;
1908 case kIOReturnUnderrun:
1909 case kIOReturnSuccess:
1910 return LIBUSB_TRANSFER_COMPLETED;
1911 case kIOReturnAborted:
1912 return LIBUSB_TRANSFER_CANCELLED;
1913 case kIOUSBPipeStalled:
1914 usbi_dbg ("transfer error: pipe is stalled");
1915 return LIBUSB_TRANSFER_STALL;
1916 case kIOReturnOverrun:
1917 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1918 return LIBUSB_TRANSFER_OVERFLOW;
1919 case kIOUSBTransactionTimeout:
1920 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1921 itransfer->timeout_flags |= USBI_TRANSFER_TIMED_OUT;
1922 return LIBUSB_TRANSFER_TIMED_OUT;
1924 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1925 return LIBUSB_TRANSFER_ERROR;
1929 static int darwin_handle_transfer_completion (struct usbi_transfer *itransfer) {
1930 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1931 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1932 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1933 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1934 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1935 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1938 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1939 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1940 return LIBUSB_ERROR_INVALID_PARAM;
1943 usbi_dbg ("handling %s completion with kernel status %d",
1944 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", tpriv->result);
1946 if (kIOReturnSuccess == tpriv->result || kIOReturnUnderrun == tpriv->result) {
1947 if (isIsoc && tpriv->isoc_framelist) {
1948 /* copy isochronous results back */
1950 for (i = 0; i < transfer->num_iso_packets ; i++) {
1951 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1952 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1953 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1956 itransfer->transferred += tpriv->size;
1959 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1960 return usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, tpriv->result));
1963 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1964 mach_timespec_t sys_time;
1965 clock_serv_t clock_ref;
1968 case USBI_CLOCK_REALTIME:
1969 /* CLOCK_REALTIME represents time since the epoch */
1970 clock_ref = clock_realtime;
1972 case USBI_CLOCK_MONOTONIC:
1973 /* use system boot time as reference for the monotonic clock */
1974 clock_ref = clock_monotonic;
1977 return LIBUSB_ERROR_INVALID_PARAM;
1980 clock_get_time (clock_ref, &sys_time);
1982 tp->tv_sec = sys_time.tv_sec;
1983 tp->tv_nsec = sys_time.tv_nsec;
1988 #if InterfaceVersion >= 550
1989 static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints,
1990 int num_endpoints) {
1991 struct darwin_interface *cInterface;
1992 UInt32 supportsStreams;
1996 /* find the mimimum number of supported streams on the endpoint list */
1997 for (i = 0 ; i < num_endpoints ; ++i) {
1998 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) {
2002 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2003 if (num_streams > supportsStreams)
2004 num_streams = supportsStreams;
2007 /* it is an error if any endpoint in endpoints does not support streams */
2008 if (0 == num_streams)
2009 return LIBUSB_ERROR_INVALID_PARAM;
2011 /* create the streams */
2012 for (i = 0 ; i < num_endpoints ; ++i) {
2013 (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
2015 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, num_streams);
2016 if (kIOReturnSuccess != rc)
2017 return darwin_to_libusb(rc);
2023 static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) {
2024 struct darwin_interface *cInterface;
2025 UInt32 supportsStreams;
2029 for (int i = 0 ; i < num_endpoints ; ++i) {
2030 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface)))
2033 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2034 if (0 == supportsStreams)
2035 return LIBUSB_ERROR_INVALID_PARAM;
2037 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, 0);
2038 if (kIOReturnSuccess != rc)
2039 return darwin_to_libusb(rc);
2042 return LIBUSB_SUCCESS;
2046 const struct usbi_os_backend darwin_backend = {
2049 .init = darwin_init,
2050 .exit = darwin_exit,
2051 .get_device_list = NULL, /* not needed */
2052 .get_device_descriptor = darwin_get_device_descriptor,
2053 .get_active_config_descriptor = darwin_get_active_config_descriptor,
2054 .get_config_descriptor = darwin_get_config_descriptor,
2055 .hotplug_poll = darwin_hotplug_poll,
2057 .open = darwin_open,
2058 .close = darwin_close,
2059 .get_configuration = darwin_get_configuration,
2060 .set_configuration = darwin_set_configuration,
2061 .claim_interface = darwin_claim_interface,
2062 .release_interface = darwin_release_interface,
2064 .set_interface_altsetting = darwin_set_interface_altsetting,
2065 .clear_halt = darwin_clear_halt,
2066 .reset_device = darwin_reset_device,
2068 #if InterfaceVersion >= 550
2069 .alloc_streams = darwin_alloc_streams,
2070 .free_streams = darwin_free_streams,
2073 .kernel_driver_active = darwin_kernel_driver_active,
2074 .detach_kernel_driver = darwin_detach_kernel_driver,
2075 .attach_kernel_driver = darwin_attach_kernel_driver,
2077 .destroy_device = darwin_destroy_device,
2079 .submit_transfer = darwin_submit_transfer,
2080 .cancel_transfer = darwin_cancel_transfer,
2081 .clear_transfer_priv = darwin_clear_transfer_priv,
2083 .handle_transfer_completion = darwin_handle_transfer_completion,
2085 .clock_gettime = darwin_clock_gettime,
2087 .device_priv_size = sizeof(struct darwin_device_priv),
2088 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
2089 .transfer_priv_size = sizeof(struct darwin_transfer_priv),