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 /* there are no unsigned CFNumber types so treat the value as signed. the OS seems to do this
237 internally (CFNumberType of locationID is kCFNumberSInt32Type) */
238 CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberSInt32Type, &location);
240 if (propertyMatchDict && locationCF) {
241 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
242 CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
244 /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
246 /* release our references as per the Create Rule */
247 if (propertyMatchDict)
248 CFRelease (propertyMatchDict);
250 CFRelease (locationCF);
253 return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator);
256 /* Returns 1 on success, 0 on failure. */
257 static int get_ioregistry_value_number (io_service_t service, CFStringRef property, CFNumberType type, void *p) {
258 CFTypeRef cfNumber = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
262 if (CFGetTypeID(cfNumber) == CFNumberGetTypeID()) {
263 ret = CFNumberGetValue(cfNumber, type, p);
266 CFRelease (cfNumber);
272 static int get_ioregistry_value_data (io_service_t service, CFStringRef property, ssize_t size, void *p) {
273 CFTypeRef cfData = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
277 if (CFGetTypeID (cfData) == CFDataGetTypeID ()) {
278 CFIndex length = CFDataGetLength (cfData);
283 CFDataGetBytes (cfData, CFRangeMake(0, size), p);
293 static usb_device_t **darwin_device_from_service (io_service_t service)
295 io_cf_plugin_ref_t *plugInInterface = NULL;
296 usb_device_t **device;
297 kern_return_t result;
300 result = IOCreatePlugInInterfaceForService(service, kIOUSBDeviceUserClientTypeID,
301 kIOCFPlugInInterfaceID, &plugInInterface,
304 if (kIOReturnSuccess != result || !plugInInterface) {
305 usbi_dbg ("could not set up plugin for service: %s", darwin_error_str (result));
309 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
311 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
312 (*plugInInterface)->Release (plugInInterface);
317 static void darwin_devices_attached (void *ptr, io_iterator_t add_devices) {
319 struct libusb_context *ctx;
320 io_service_t service;
322 usbi_mutex_lock(&active_contexts_lock);
324 while ((service = IOIteratorNext(add_devices))) {
325 /* add this device to each active context's device list */
326 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
327 process_new_device (ctx, service);
330 IOObjectRelease(service);
333 usbi_mutex_unlock(&active_contexts_lock);
336 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
338 struct libusb_device *dev = NULL;
339 struct libusb_context *ctx;
340 struct darwin_cached_device *old_device;
346 usbi_mutex_lock(&active_contexts_lock);
348 while ((device = IOIteratorNext (rem_devices)) != 0) {
349 /* get the location from the i/o registry */
350 ret = get_ioregistry_value_number (device, CFSTR("sessionID"), kCFNumberSInt64Type, &session);
351 IOObjectRelease (device);
355 /* we need to match darwin_ref_cached_device call made in darwin_get_cached_device function
356 otherwise no cached device will ever get freed */
357 usbi_mutex_lock(&darwin_cached_devices_lock);
358 list_for_each_entry(old_device, &darwin_cached_devices, list, struct darwin_cached_device) {
359 if (old_device->session == session) {
360 darwin_deref_cached_device (old_device);
364 usbi_mutex_unlock(&darwin_cached_devices_lock);
366 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
367 usbi_dbg ("notifying context %p of device disconnect", ctx);
369 dev = usbi_get_device_by_session_id(ctx, (unsigned long) session);
371 /* signal the core that this device has been disconnected. the core will tear down this device
372 when the reference count reaches 0 */
373 usbi_disconnect_device(dev);
374 libusb_unref_device(dev);
379 usbi_mutex_unlock(&active_contexts_lock);
382 static void darwin_hotplug_poll (void)
384 /* not sure if 5 seconds will be too long/short but it should work ok */
385 mach_timespec_t timeout = {.tv_sec = 5, .tv_nsec = 0};
387 /* since a kernel thread may nodify the IOInterators used for
388 * hotplug notidication we can't just clear the iterators.
389 * instead just wait until all IOService providers are quiet */
390 (void) IOKitWaitQuiet (kIOMasterPortDefault, &timeout);
393 static void darwin_clear_iterator (io_iterator_t iter) {
396 while ((device = IOIteratorNext (iter)) != 0)
397 IOObjectRelease (device);
400 static void *darwin_event_thread_main (void *arg0) {
402 struct libusb_context *ctx = (struct libusb_context *)arg0;
403 CFRunLoopRef runloop;
405 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
406 /* Set this thread's name, so it can be seen in the debugger
407 and crash reports. */
408 pthread_setname_np ("org.libusb.device-hotplug");
411 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
412 /* Tell the Objective-C garbage collector about this thread.
413 This is required because, unlike NSThreads, pthreads are
414 not automatically registered. Although we don't use
415 Objective-C, we use CoreFoundation, which does.
416 Garbage collection support was entirely removed in 10.12,
417 so don't bother there. */
418 objc_registerThreadWithCollector();
421 /* hotplug (device arrival/removal) sources */
422 CFRunLoopSourceContext libusb_shutdown_cfsourcectx;
423 CFRunLoopSourceRef libusb_notification_cfsource;
424 io_notification_port_t libusb_notification_port;
425 io_iterator_t libusb_rem_device_iterator;
426 io_iterator_t libusb_add_device_iterator;
428 usbi_dbg ("creating hotplug event source");
430 runloop = CFRunLoopGetCurrent ();
433 /* add the shutdown cfsource to the run loop */
434 memset(&libusb_shutdown_cfsourcectx, 0, sizeof(libusb_shutdown_cfsourcectx));
435 libusb_shutdown_cfsourcectx.info = runloop;
436 libusb_shutdown_cfsourcectx.perform = (void (*)(void *))CFRunLoopStop;
437 libusb_darwin_acfls = CFRunLoopSourceCreate(NULL, 0, &libusb_shutdown_cfsourcectx);
438 CFRunLoopAddSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
440 /* add the notification port to the run loop */
441 libusb_notification_port = IONotificationPortCreate (kIOMasterPortDefault);
442 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
443 CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
445 /* create notifications for removed devices */
446 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
447 IOServiceMatching(darwin_device_class),
448 darwin_devices_detached,
449 ctx, &libusb_rem_device_iterator);
451 if (kresult != kIOReturnSuccess) {
452 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
457 /* create notifications for attached devices */
458 kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
459 IOServiceMatching(darwin_device_class),
460 darwin_devices_attached,
461 ctx, &libusb_add_device_iterator);
463 if (kresult != kIOReturnSuccess) {
464 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
470 darwin_clear_iterator (libusb_rem_device_iterator);
471 darwin_clear_iterator (libusb_add_device_iterator);
473 usbi_dbg ("darwin event thread ready to receive events");
475 /* signal the main thread that the hotplug runloop has been created. */
476 pthread_mutex_lock (&libusb_darwin_at_mutex);
477 libusb_darwin_acfl = runloop;
478 pthread_cond_signal (&libusb_darwin_at_cond);
479 pthread_mutex_unlock (&libusb_darwin_at_mutex);
481 /* run the runloop */
484 usbi_dbg ("darwin event thread exiting");
486 /* remove the notification cfsource */
487 CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
489 /* remove the shutdown cfsource */
490 CFRunLoopRemoveSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
492 /* delete notification port */
493 IONotificationPortDestroy (libusb_notification_port);
495 /* delete iterators */
496 IOObjectRelease (libusb_rem_device_iterator);
497 IOObjectRelease (libusb_add_device_iterator);
499 CFRelease (libusb_darwin_acfls);
502 libusb_darwin_acfls = NULL;
503 libusb_darwin_acfl = NULL;
508 /* cleanup function to destroy cached devices */
509 static void __attribute__((destructor)) _darwin_finalize(void) {
510 struct darwin_cached_device *dev, *next;
512 usbi_mutex_lock(&darwin_cached_devices_lock);
513 list_for_each_entry_safe(dev, next, &darwin_cached_devices, list, struct darwin_cached_device) {
514 darwin_deref_cached_device(dev);
516 usbi_mutex_unlock(&darwin_cached_devices_lock);
519 static void darwin_check_version (void) {
520 /* adjust for changes in the USB stack in xnu 15 */
521 int sysctl_args[] = {CTL_KERN, KERN_OSRELEASE};
523 char version_string[256] = {'\0',};
526 sysctl(sysctl_args, 2, version_string, &length, NULL, 0);
529 version = strtol (version_string, NULL, 10);
530 if (0 == errno && version >= 15) {
531 darwin_device_class = "IOUSBHostDevice";
535 static int darwin_init(struct libusb_context *ctx) {
538 rc = pthread_once (&darwin_init_once, darwin_check_version);
540 return LIBUSB_ERROR_OTHER;
543 rc = darwin_scan_devices (ctx);
544 if (LIBUSB_SUCCESS != rc) {
548 if (libusb_darwin_atomic_fetch_add (&initCount, 1) == 0) {
549 #if !OSX_USE_CLOCK_GETTIME
550 /* create the clocks that will be used if clock_gettime() is not available */
551 host_name_port_t host_self;
553 host_self = mach_host_self();
554 host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
555 host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
556 mach_port_deallocate(mach_task_self(), host_self);
559 pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, ctx);
561 pthread_mutex_lock (&libusb_darwin_at_mutex);
562 while (!libusb_darwin_acfl)
563 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
564 pthread_mutex_unlock (&libusb_darwin_at_mutex);
570 static void darwin_exit (struct libusb_context *ctx) {
572 if (libusb_darwin_atomic_fetch_add (&initCount, -1) == 1) {
573 #if !OSX_USE_CLOCK_GETTIME
574 mach_port_deallocate(mach_task_self(), clock_realtime);
575 mach_port_deallocate(mach_task_self(), clock_monotonic);
578 /* stop the event runloop and wait for the thread to terminate. */
579 CFRunLoopSourceSignal(libusb_darwin_acfls);
580 CFRunLoopWakeUp (libusb_darwin_acfl);
581 pthread_join (libusb_darwin_at, NULL);
585 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
586 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
588 /* return cached copy */
589 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
596 static int get_configuration_index (struct libusb_device *dev, int config_value) {
597 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
599 IOUSBConfigurationDescriptorPtr desc;
602 /* is there a simpler way to determine the index? */
603 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
604 if (kresult != kIOReturnSuccess)
605 return darwin_to_libusb (kresult);
607 for (i = 0 ; i < numConfig ; i++) {
608 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
610 if (desc->bConfigurationValue == config_value)
614 /* configuration not found */
615 return LIBUSB_ERROR_NOT_FOUND;
618 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
619 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
622 if (0 == priv->active_config)
623 return LIBUSB_ERROR_NOT_FOUND;
625 config_index = get_configuration_index (dev, priv->active_config);
626 if (config_index < 0)
629 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
632 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
633 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
634 IOUSBConfigurationDescriptorPtr desc;
638 if (!priv || !priv->device)
639 return LIBUSB_ERROR_OTHER;
641 kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
642 if (kresult == kIOReturnSuccess) {
643 /* copy descriptor */
644 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
645 len = libusb_le16_to_cpu(desc->wTotalLength);
647 memmove (buffer, desc, len);
649 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
653 ret = darwin_to_libusb (kresult);
654 if (ret != LIBUSB_SUCCESS)
660 /* check whether the os has configured the device */
661 static int darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) {
662 usb_device_t **darwin_device = dev->device;
664 IOUSBConfigurationDescriptorPtr configDesc;
665 IOUSBFindInterfaceRequest request;
666 kern_return_t kresult;
667 io_iterator_t interface_iterator;
668 io_service_t firstInterface;
670 if (dev->dev_descriptor.bNumConfigurations < 1) {
671 usbi_err (ctx, "device has no configurations");
672 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
675 /* checking the configuration of a root hub simulation takes ~1 s in 10.11. the device is
677 if (0x05ac == dev->dev_descriptor.idVendor && 0x8005 == dev->dev_descriptor.idProduct) {
678 usbi_dbg ("ignoring configuration on root hub simulation");
679 dev->active_config = 0;
683 /* find the first configuration */
684 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
685 dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
687 /* check if the device is already configured. there is probably a better way than iterating over the
688 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
689 might lock up on the device request) */
691 /* Setup the Interface Request */
692 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
693 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
694 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
695 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
697 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
699 return darwin_to_libusb (kresult);
702 firstInterface = IOIteratorNext(interface_iterator);
704 /* done with the interface iterator */
705 IOObjectRelease(interface_iterator);
707 if (firstInterface) {
708 IOObjectRelease (firstInterface);
710 /* device is configured */
711 if (dev->dev_descriptor.bNumConfigurations == 1)
712 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
713 dev->active_config = dev->first_config;
715 /* devices with more than one configuration should work with GetConfiguration */
716 (*darwin_device)->GetConfiguration (darwin_device, &dev->active_config);
719 dev->active_config = 0;
721 usbi_dbg ("active config: %u, first config: %u", dev->active_config, dev->first_config);
726 static int darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
727 IOUSBDevRequestTO req;
729 memset (buffer, 0, buffer_size);
731 /* Set up request for descriptor/ */
732 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
733 req.bRequest = kUSBRqGetDescriptor;
734 req.wValue = desc << 8;
735 req.wIndex = desc_index;
736 req.wLength = buffer_size;
738 req.noDataTimeout = 20;
739 req.completionTimeout = 100;
741 return (*device)->DeviceRequestTO (device, &req);
744 static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct darwin_cached_device *dev) {
745 usb_device_t **device = dev->device;
746 int retries = 1, delay = 30000;
747 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
751 UInt16 idProduct, idVendor;
753 dev->can_enumerate = 0;
755 (*device)->GetDeviceClass (device, &bDeviceClass);
756 (*device)->GetDeviceProduct (device, &idProduct);
757 (*device)->GetDeviceVendor (device, &idVendor);
759 /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
760 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
761 * to follow the spec as closely as possible, try opening the device */
762 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
765 /**** retrieve device descriptor ****/
766 ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &dev->dev_descriptor, sizeof(dev->dev_descriptor));
768 if (kIOReturnOverrun == ret && kUSBDeviceDesc == dev->dev_descriptor.bDescriptorType)
769 /* received an overrun error but we still received a device descriptor */
770 ret = kIOReturnSuccess;
772 if (kIOUSBVendorIDAppleComputer == idVendor) {
773 /* NTH: don't bother retrying or unsuspending Apple devices */
777 if (kIOReturnSuccess == ret && (0 == dev->dev_descriptor.bNumConfigurations ||
778 0 == dev->dev_descriptor.bcdUSB)) {
779 /* work around for incorrectly configured devices */
780 if (try_reconfigure && is_open) {
781 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
783 /* set the first configuration */
784 (*device)->SetConfiguration(device, 1);
786 /* don't try to reconfigure again */
790 ret = kIOUSBPipeStalled;
793 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
794 /* device may be suspended. unsuspend it and try again */
795 #if DeviceVersion >= 320
798 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
799 (void)(*device)->GetUSBDeviceInformation (device, &info);
801 /* note that the device was suspended */
802 if (info & (1 << kUSBInformationDeviceIsSuspendedBit) || 0 == info)
807 /* try to unsuspend the device */
808 ret2 = (*device)->USBDeviceSuspend (device, 0);
809 if (kIOReturnSuccess != ret2) {
810 /* prevent log spew from poorly behaving devices. this indicates the
811 os actually had trouble communicating with the device */
812 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
820 if (kIOReturnSuccess != ret) {
821 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
822 /* sleep for a little while before trying again */
823 nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000UL}, NULL);
825 } while (kIOReturnSuccess != ret && retries--);
828 /* resuspend the device */
829 (void)(*device)->USBDeviceSuspend (device, 1);
832 (void) (*device)->USBDeviceClose (device);
834 if (ret != kIOReturnSuccess) {
835 /* a debug message was already printed out for this error */
836 if (LIBUSB_CLASS_HUB == bDeviceClass)
837 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
838 idVendor, idProduct, darwin_error_str (ret), ret);
840 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
841 idVendor, idProduct, darwin_error_str (ret), ret);
842 return darwin_to_libusb (ret);
845 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
846 if (libusb_le16_to_cpu (dev->dev_descriptor.idProduct) != idProduct) {
847 /* not a valid device */
848 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
849 idProduct, libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
850 return LIBUSB_ERROR_NO_DEVICE;
853 usbi_dbg ("cached device descriptor:");
854 usbi_dbg (" bDescriptorType: 0x%02x", dev->dev_descriptor.bDescriptorType);
855 usbi_dbg (" bcdUSB: 0x%04x", dev->dev_descriptor.bcdUSB);
856 usbi_dbg (" bDeviceClass: 0x%02x", dev->dev_descriptor.bDeviceClass);
857 usbi_dbg (" bDeviceSubClass: 0x%02x", dev->dev_descriptor.bDeviceSubClass);
858 usbi_dbg (" bDeviceProtocol: 0x%02x", dev->dev_descriptor.bDeviceProtocol);
859 usbi_dbg (" bMaxPacketSize0: 0x%02x", dev->dev_descriptor.bMaxPacketSize0);
860 usbi_dbg (" idVendor: 0x%04x", dev->dev_descriptor.idVendor);
861 usbi_dbg (" idProduct: 0x%04x", dev->dev_descriptor.idProduct);
862 usbi_dbg (" bcdDevice: 0x%04x", dev->dev_descriptor.bcdDevice);
863 usbi_dbg (" iManufacturer: 0x%02x", dev->dev_descriptor.iManufacturer);
864 usbi_dbg (" iProduct: 0x%02x", dev->dev_descriptor.iProduct);
865 usbi_dbg (" iSerialNumber: 0x%02x", dev->dev_descriptor.iSerialNumber);
866 usbi_dbg (" bNumConfigurations: 0x%02x", dev->dev_descriptor.bNumConfigurations);
868 dev->can_enumerate = 1;
870 return LIBUSB_SUCCESS;
873 static int get_device_port (io_service_t service, UInt8 *port) {
874 kern_return_t result;
878 if (get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, port)) {
882 result = IORegistryEntryGetParentEntry (service, kIOServicePlane, &parent);
883 if (kIOReturnSuccess == result) {
884 ret = get_ioregistry_value_data (parent, CFSTR("port"), 1, port);
885 IOObjectRelease (parent);
891 static int get_device_parent_sessionID(io_service_t service, UInt64 *parent_sessionID) {
892 kern_return_t result;
895 /* Walk up the tree in the IOService plane until we find a parent that has a sessionID */
897 while((result = IORegistryEntryGetParentEntry (parent, kIOServicePlane, &parent)) == kIOReturnSuccess) {
898 if (get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, parent_sessionID)) {
904 /* We ran out of parents */
908 static int darwin_get_cached_device(struct libusb_context *ctx, io_service_t service,
909 struct darwin_cached_device **cached_out) {
910 struct darwin_cached_device *new_device;
911 UInt64 sessionID = 0, parent_sessionID = 0;
912 int ret = LIBUSB_SUCCESS;
913 usb_device_t **device;
916 /* get some info from the io registry */
917 (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
918 if (!get_device_port (service, &port)) {
919 usbi_dbg("could not get connected port number");
922 usbi_dbg("finding cached device for sessionID 0x%" PRIx64, sessionID);
924 if (get_device_parent_sessionID(service, &parent_sessionID)) {
925 usbi_dbg("parent sessionID: 0x%" PRIx64, parent_sessionID);
928 usbi_mutex_lock(&darwin_cached_devices_lock);
932 list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) {
933 usbi_dbg("matching sessionID 0x%" PRIx64 " against cached device with sessionID 0x%" PRIx64, sessionID, new_device->session);
934 if (new_device->session == sessionID) {
935 usbi_dbg("using cached device for device");
936 *cached_out = new_device;
944 usbi_dbg("caching new device with sessionID 0x%" PRIx64, sessionID);
946 device = darwin_device_from_service (service);
948 ret = LIBUSB_ERROR_NO_DEVICE;
952 new_device = calloc (1, sizeof (*new_device));
954 ret = LIBUSB_ERROR_NO_MEM;
958 /* add this device to the cached device list */
959 list_add(&new_device->list, &darwin_cached_devices);
961 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
963 /* keep a reference to this device */
964 darwin_ref_cached_device(new_device);
966 new_device->device = device;
967 new_device->session = sessionID;
968 (*device)->GetLocationID (device, &new_device->location);
969 new_device->port = port;
970 new_device->parent_session = parent_sessionID;
972 /* cache the device descriptor */
973 ret = darwin_cache_device_descriptor(ctx, new_device);
977 if (new_device->can_enumerate) {
978 snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address,
979 new_device->dev_descriptor.idVendor, new_device->dev_descriptor.idProduct,
980 new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass);
984 usbi_mutex_unlock(&darwin_cached_devices_lock);
986 /* keep track of devices regardless of if we successfully enumerate them to
987 prevent them from being enumerated multiple times */
989 *cached_out = new_device;
994 static int process_new_device (struct libusb_context *ctx, io_service_t service) {
995 struct darwin_device_priv *priv;
996 struct libusb_device *dev = NULL;
997 struct darwin_cached_device *cached_device;
1002 ret = darwin_get_cached_device (ctx, service, &cached_device);
1004 if (ret < 0 || !cached_device->can_enumerate) {
1008 /* check current active configuration (and cache the first configuration value--
1009 which may be used by claim_interface) */
1010 ret = darwin_check_configuration (ctx, cached_device);
1014 usbi_dbg ("allocating new device in context %p for with session 0x%" PRIx64,
1015 ctx, cached_device->session);
1017 dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
1019 return LIBUSB_ERROR_NO_MEM;
1022 priv = (struct darwin_device_priv *)dev->os_priv;
1024 priv->dev = cached_device;
1025 darwin_ref_cached_device (priv->dev);
1027 if (cached_device->parent_session > 0) {
1028 dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session);
1030 dev->parent_dev = NULL;
1032 dev->port_number = cached_device->port;
1033 dev->bus_number = cached_device->location >> 24;
1034 dev->device_address = cached_device->address;
1036 (*(priv->dev->device))->GetDeviceSpeed (priv->dev->device, &devSpeed);
1039 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
1040 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
1041 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
1042 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
1043 case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
1045 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101200
1046 case kUSBDeviceSpeedSuperPlus: dev->speed = LIBUSB_SPEED_SUPER_PLUS; break;
1049 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
1052 ret = usbi_sanitize_device (dev);
1056 usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
1057 dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
1061 usbi_connect_device (dev);
1063 libusb_unref_device (dev);
1069 static int darwin_scan_devices(struct libusb_context *ctx) {
1070 io_iterator_t deviceIterator;
1071 io_service_t service;
1072 kern_return_t kresult;
1074 kresult = usb_setup_device_iterator (&deviceIterator, 0);
1075 if (kresult != kIOReturnSuccess)
1076 return darwin_to_libusb (kresult);
1078 while ((service = IOIteratorNext (deviceIterator))) {
1079 (void) process_new_device (ctx, service);
1081 IOObjectRelease(service);
1084 IOObjectRelease(deviceIterator);
1089 static int darwin_open (struct libusb_device_handle *dev_handle) {
1090 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1091 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1094 if (0 == dpriv->open_count) {
1095 /* try to open the device */
1096 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
1097 if (kresult != kIOReturnSuccess) {
1098 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
1100 if (kIOReturnExclusiveAccess != kresult) {
1101 return darwin_to_libusb (kresult);
1104 /* it is possible to perform some actions on a device that is not open so do not return an error */
1110 /* create async event source */
1111 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
1112 if (kresult != kIOReturnSuccess) {
1113 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
1115 if (priv->is_open) {
1116 (*(dpriv->device))->USBDeviceClose (dpriv->device);
1121 return darwin_to_libusb (kresult);
1124 CFRetain (libusb_darwin_acfl);
1126 /* add the cfSource to the aync run loop */
1127 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
1130 /* device opened successfully */
1131 dpriv->open_count++;
1133 usbi_dbg ("device open for access");
1138 static void darwin_close (struct libusb_device_handle *dev_handle) {
1139 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1140 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1144 if (dpriv->open_count == 0) {
1145 /* something is probably very wrong if this is the case */
1146 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!");
1150 dpriv->open_count--;
1152 /* make sure all interfaces are released */
1153 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1154 if (dev_handle->claimed_interfaces & (1 << i))
1155 libusb_release_interface (dev_handle, i);
1157 if (0 == dpriv->open_count) {
1158 /* delete the device's async event source */
1159 if (priv->cfSource) {
1160 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
1161 CFRelease (priv->cfSource);
1162 priv->cfSource = NULL;
1163 CFRelease (libusb_darwin_acfl);
1166 if (priv->is_open) {
1167 /* close the device */
1168 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
1170 /* Log the fact that we had a problem closing the file, however failing a
1171 * close isn't really an error, so return success anyway */
1172 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
1178 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
1179 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1181 *config = (int) dpriv->active_config;
1186 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
1187 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1191 /* Setting configuration will invalidate the interface, so we need
1192 to reclaim it. First, dispose of existing interfaces, if any. */
1193 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1194 if (dev_handle->claimed_interfaces & (1 << i))
1195 darwin_release_interface (dev_handle, i);
1197 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
1198 if (kresult != kIOReturnSuccess)
1199 return darwin_to_libusb (kresult);
1201 /* Reclaim any interfaces. */
1202 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1203 if (dev_handle->claimed_interfaces & (1 << i))
1204 darwin_claim_interface (dev_handle, i);
1206 dpriv->active_config = config;
1211 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
1212 IOUSBFindInterfaceRequest request;
1213 kern_return_t kresult;
1214 io_iterator_t interface_iterator;
1215 UInt8 bInterfaceNumber;
1218 *usbInterfacep = IO_OBJECT_NULL;
1220 /* Setup the Interface Request */
1221 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1222 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1223 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1224 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1226 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1230 while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1231 /* find the interface number */
1232 ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
1235 if (ret && bInterfaceNumber == ifc) {
1239 (void) IOObjectRelease (*usbInterfacep);
1242 /* done with the interface iterator */
1243 IOObjectRelease(interface_iterator);
1248 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
1249 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1251 /* current interface */
1252 struct darwin_interface *cInterface = &priv->interfaces[iface];
1254 kern_return_t kresult;
1256 UInt8 numep, direction, number;
1257 UInt8 dont_care1, dont_care3;
1261 usbi_dbg ("building table of endpoints.");
1263 /* retrieve the total number of endpoints on this interface */
1264 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1266 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1267 return darwin_to_libusb (kresult);
1270 /* iterate through pipe references */
1271 for (int i = 1 ; i <= numep ; i++) {
1272 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1273 &dont_care2, &dont_care3);
1275 if (kresult != kIOReturnSuccess) {
1276 /* probably a buggy device. try to get the endpoint address from the descriptors */
1277 struct libusb_config_descriptor *config;
1278 const struct libusb_endpoint_descriptor *endpoint_desc;
1281 kresult = (*(cInterface->interface))->GetAlternateSetting (cInterface->interface, &alt_setting);
1283 usbi_err (HANDLE_CTX (dev_handle), "can't get alternate setting for interface");
1284 return darwin_to_libusb (kresult);
1287 rc = libusb_get_active_config_descriptor (dev_handle->dev, &config);
1288 if (LIBUSB_SUCCESS != rc) {
1292 endpoint_desc = config->interface[iface].altsetting[alt_setting].endpoint + i - 1;
1294 cInterface->endpoint_addrs[i - 1] = endpoint_desc->bEndpointAddress;
1296 cInterface->endpoint_addrs[i - 1] = (((kUSBIn == direction) << kUSBRqDirnShift) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1299 usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, cInterface->endpoint_addrs[i - 1] >> kUSBRqDirnShift,
1300 cInterface->endpoint_addrs[i - 1] & LIBUSB_ENDPOINT_ADDRESS_MASK);
1303 cInterface->num_endpoints = numep;
1308 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1309 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1310 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1311 io_service_t usbInterface = IO_OBJECT_NULL;
1313 IOCFPlugInInterface **plugInInterface = NULL;
1316 /* current interface */
1317 struct darwin_interface *cInterface = &priv->interfaces[iface];
1319 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1320 if (kresult != kIOReturnSuccess)
1321 return darwin_to_libusb (kresult);
1323 /* make sure we have an interface */
1324 if (!usbInterface && dpriv->first_config != 0) {
1325 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1327 /* set the configuration */
1328 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1329 if (kresult != LIBUSB_SUCCESS) {
1330 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1334 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1336 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1337 return darwin_to_libusb (kresult);
1341 if (!usbInterface) {
1342 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1343 return LIBUSB_ERROR_NOT_FOUND;
1346 /* get an interface to the device's interface */
1347 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1348 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1350 /* ignore release error */
1351 (void)IOObjectRelease (usbInterface);
1354 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1355 return darwin_to_libusb (kresult);
1358 if (!plugInInterface) {
1359 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1360 return LIBUSB_ERROR_NOT_FOUND;
1363 /* Do the actual claim */
1364 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1365 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1366 (LPVOID)&cInterface->interface);
1367 /* We no longer need the intermediate plug-in */
1368 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1369 (*plugInInterface)->Release (plugInInterface);
1370 if (kresult || !cInterface->interface) {
1371 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1372 return darwin_to_libusb (kresult);
1375 /* claim the interface */
1376 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1378 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1379 return darwin_to_libusb (kresult);
1382 /* update list of endpoints */
1383 kresult = get_endpoints (dev_handle, iface);
1385 /* this should not happen */
1386 darwin_release_interface (dev_handle, iface);
1387 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1391 cInterface->cfSource = NULL;
1393 /* create async event source */
1394 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1395 if (kresult != kIOReturnSuccess) {
1396 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1398 /* can't continue without an async event source */
1399 (void)darwin_release_interface (dev_handle, iface);
1401 return darwin_to_libusb (kresult);
1404 /* add the cfSource to the async thread's run loop */
1405 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1407 usbi_dbg ("interface opened");
1412 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1413 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1416 /* current interface */
1417 struct darwin_interface *cInterface = &priv->interfaces[iface];
1419 /* Check to see if an interface is open */
1420 if (!cInterface->interface)
1421 return LIBUSB_SUCCESS;
1423 /* clean up endpoint data */
1424 cInterface->num_endpoints = 0;
1426 /* delete the interface's async event source */
1427 if (cInterface->cfSource) {
1428 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1429 CFRelease (cInterface->cfSource);
1432 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1434 usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1436 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1437 if (kresult != kIOReturnSuccess)
1438 usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1440 cInterface->interface = (usb_interface_t **) IO_OBJECT_NULL;
1442 return darwin_to_libusb (kresult);
1445 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1446 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1449 /* current interface */
1450 struct darwin_interface *cInterface = &priv->interfaces[iface];
1452 if (!cInterface->interface)
1453 return LIBUSB_ERROR_NO_DEVICE;
1455 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1456 if (kresult != kIOReturnSuccess)
1457 darwin_reset_device (dev_handle);
1459 /* update list of endpoints */
1460 kresult = get_endpoints (dev_handle, iface);
1462 /* this should not happen */
1463 darwin_release_interface (dev_handle, iface);
1464 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1468 return darwin_to_libusb (kresult);
1471 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1472 /* current interface */
1473 struct darwin_interface *cInterface;
1477 /* determine the interface/endpoint to use */
1478 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, NULL, &cInterface) != 0) {
1479 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1481 return LIBUSB_ERROR_NOT_FOUND;
1484 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1485 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1487 usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1489 return darwin_to_libusb (kresult);
1492 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1493 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1494 IOUSBDeviceDescriptor descriptor;
1495 IOUSBConfigurationDescriptorPtr cached_configuration;
1496 IOUSBConfigurationDescriptor configuration;
1497 bool reenumerate = false;
1501 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1503 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1504 return darwin_to_libusb (kresult);
1508 usbi_dbg ("darwin/reset_device: checking if device descriptor changed");
1510 /* ignore return code. if we can't get a descriptor it might be worthwhile re-enumerating anway */
1511 (void) darwin_request_descriptor (dpriv->device, kUSBDeviceDesc, 0, &descriptor, sizeof (descriptor));
1513 /* check if the device descriptor has changed */
1514 if (0 != memcmp (&dpriv->dev_descriptor, &descriptor, sizeof (descriptor))) {
1519 /* check if any configuration descriptor has changed */
1520 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1521 usbi_dbg ("darwin/reset_device: checking if configuration descriptor %d changed", i);
1523 (void) darwin_request_descriptor (dpriv->device, kUSBConfDesc, i, &configuration, sizeof (configuration));
1524 (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1526 if (!cached_configuration || 0 != memcmp (cached_configuration, &configuration, sizeof (configuration))) {
1534 usbi_dbg ("darwin/reset_device: device requires reenumeration");
1535 (void) (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
1536 return LIBUSB_ERROR_NOT_FOUND;
1539 usbi_dbg ("darwin/reset_device: device reset complete");
1541 return LIBUSB_SUCCESS;
1544 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1545 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1546 io_service_t usbInterface;
1550 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1552 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1554 return darwin_to_libusb (kresult);
1557 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1558 IOObjectRelease (usbInterface);
1570 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1571 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1574 return LIBUSB_ERROR_NOT_SUPPORTED;
1577 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1580 return LIBUSB_ERROR_NOT_SUPPORTED;
1583 static void darwin_destroy_device(struct libusb_device *dev) {
1584 struct darwin_device_priv *dpriv = (struct darwin_device_priv *) dev->os_priv;
1587 /* need to hold the lock in case this is the last reference to the device */
1588 usbi_mutex_lock(&darwin_cached_devices_lock);
1589 darwin_deref_cached_device (dpriv->dev);
1591 usbi_mutex_unlock(&darwin_cached_devices_lock);
1595 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1596 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1599 uint8_t transferType;
1600 /* None of the values below are used in libusbx for bulk transfers */
1601 uint8_t direction, number, interval, pipeRef;
1602 uint16_t maxPacketSize;
1604 struct darwin_interface *cInterface;
1606 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1607 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1609 return LIBUSB_ERROR_NOT_FOUND;
1612 ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1613 &transferType, &maxPacketSize, &interval);
1616 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1617 darwin_error_str(ret), ret);
1618 return darwin_to_libusb (ret);
1621 if (0 != (transfer->length % maxPacketSize)) {
1622 /* do not need a zero packet */
1623 transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1626 /* submit the request */
1627 /* timeouts are unavailable on interrupt endpoints */
1628 if (transferType == kUSBInterrupt) {
1629 if (IS_XFERIN(transfer))
1630 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1631 transfer->length, darwin_async_io_callback, itransfer);
1633 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1634 transfer->length, darwin_async_io_callback, itransfer);
1636 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1638 if (IS_XFERIN(transfer))
1639 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1640 transfer->length, transfer->timeout, transfer->timeout,
1641 darwin_async_io_callback, (void *)itransfer);
1643 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1644 transfer->length, transfer->timeout, transfer->timeout,
1645 darwin_async_io_callback, (void *)itransfer);
1649 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1650 darwin_error_str(ret), ret);
1652 return darwin_to_libusb (ret);
1655 #if InterfaceVersion >= 550
1656 static int submit_stream_transfer(struct usbi_transfer *itransfer) {
1657 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1658 struct darwin_interface *cInterface;
1662 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1663 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1665 return LIBUSB_ERROR_NOT_FOUND;
1668 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1670 if (IS_XFERIN(transfer))
1671 ret = (*(cInterface->interface))->ReadStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1672 transfer->buffer, transfer->length, transfer->timeout,
1673 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1675 ret = (*(cInterface->interface))->WriteStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1676 transfer->buffer, transfer->length, transfer->timeout,
1677 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1680 usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1681 darwin_error_str(ret), ret);
1683 return darwin_to_libusb (ret);
1687 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1688 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1689 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1692 uint8_t direction, number, interval, pipeRef, transferType;
1693 uint16_t maxPacketSize;
1695 AbsoluteTime atTime;
1698 struct darwin_interface *cInterface;
1700 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1701 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1702 free(tpriv->isoc_framelist);
1703 tpriv->isoc_framelist = NULL;
1706 if (!tpriv->isoc_framelist) {
1707 tpriv->num_iso_packets = transfer->num_iso_packets;
1708 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1709 if (!tpriv->isoc_framelist)
1710 return LIBUSB_ERROR_NO_MEM;
1713 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1714 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1715 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1717 /* determine the interface/endpoint to use */
1718 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1719 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1721 return LIBUSB_ERROR_NOT_FOUND;
1724 /* determine the properties of this endpoint and the speed of the device */
1725 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1726 &transferType, &maxPacketSize, &interval);
1728 /* Last but not least we need the bus frame number */
1729 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1731 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1732 free(tpriv->isoc_framelist);
1733 tpriv->isoc_framelist = NULL;
1735 return darwin_to_libusb (kresult);
1738 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1739 &transferType, &maxPacketSize, &interval);
1741 /* schedule for a frame a little in the future */
1744 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1745 frame = cInterface->frames[transfer->endpoint];
1747 /* submit the request */
1748 if (IS_XFERIN(transfer))
1749 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1750 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1753 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1754 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1757 if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
1759 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1));
1761 /* High/super speed */
1762 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1)) / 8;
1764 if (kresult != kIOReturnSuccess) {
1765 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1766 darwin_error_str(kresult));
1767 free (tpriv->isoc_framelist);
1768 tpriv->isoc_framelist = NULL;
1771 return darwin_to_libusb (kresult);
1774 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1775 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1776 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1777 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1778 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1782 memset(&tpriv->req, 0, sizeof(tpriv->req));
1784 /* IOUSBDeviceInterface expects the request in cpu endianness */
1785 tpriv->req.bmRequestType = setup->bmRequestType;
1786 tpriv->req.bRequest = setup->bRequest;
1787 /* these values should be in bus order from libusb_fill_control_setup */
1788 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1789 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1790 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1791 /* data is stored after the libusb control block */
1792 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1793 tpriv->req.completionTimeout = transfer->timeout;
1794 tpriv->req.noDataTimeout = transfer->timeout;
1796 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1798 /* all transfers in libusb-1.0 are async */
1800 if (transfer->endpoint) {
1801 struct darwin_interface *cInterface;
1804 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1805 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1807 return LIBUSB_ERROR_NOT_FOUND;
1810 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1812 /* control request on endpoint 0 */
1813 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1815 if (kresult != kIOReturnSuccess)
1816 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1818 return darwin_to_libusb (kresult);
1821 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1822 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1824 switch (transfer->type) {
1825 case LIBUSB_TRANSFER_TYPE_CONTROL:
1826 return submit_control_transfer(itransfer);
1827 case LIBUSB_TRANSFER_TYPE_BULK:
1828 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1829 return submit_bulk_transfer(itransfer);
1830 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1831 return submit_iso_transfer(itransfer);
1832 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1833 #if InterfaceVersion >= 550
1834 return submit_stream_transfer(itransfer);
1836 usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers");
1837 return LIBUSB_ERROR_NOT_SUPPORTED;
1840 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1841 return LIBUSB_ERROR_INVALID_PARAM;
1845 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1846 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1847 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1850 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
1853 return LIBUSB_ERROR_NO_DEVICE;
1855 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1857 return darwin_to_libusb (kresult);
1860 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1861 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1862 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1863 struct darwin_interface *cInterface;
1864 uint8_t pipeRef, iface;
1867 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) {
1868 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1870 return LIBUSB_ERROR_NOT_FOUND;
1874 return LIBUSB_ERROR_NO_DEVICE;
1876 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
1878 /* abort transactions */
1879 #if InterfaceVersion >= 550
1880 if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type)
1881 (*(cInterface->interface))->AbortStreamsPipe (cInterface->interface, pipeRef, itransfer->stream_id);
1884 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1886 usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
1888 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1889 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1891 return darwin_to_libusb (kresult);
1894 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1895 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1897 switch (transfer->type) {
1898 case LIBUSB_TRANSFER_TYPE_CONTROL:
1899 return cancel_control_transfer(itransfer);
1900 case LIBUSB_TRANSFER_TYPE_BULK:
1901 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1902 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1903 return darwin_abort_transfers (itransfer);
1905 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1906 return LIBUSB_ERROR_INVALID_PARAM;
1910 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1911 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1912 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1914 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1915 free (tpriv->isoc_framelist);
1916 tpriv->isoc_framelist = NULL;
1920 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1921 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1922 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1923 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1925 usbi_dbg ("an async io operation has completed");
1927 /* if requested write a zero packet */
1928 if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
1929 struct darwin_interface *cInterface;
1932 (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface);
1934 (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
1937 tpriv->result = result;
1938 tpriv->size = (UInt32) (uintptr_t) arg0;
1940 /* signal the core that this transfer is complete */
1941 usbi_signal_transfer_completion(itransfer);
1944 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1945 if (itransfer->timeout_flags & USBI_TRANSFER_TIMED_OUT)
1946 result = kIOUSBTransactionTimeout;
1949 case kIOReturnUnderrun:
1950 case kIOReturnSuccess:
1951 return LIBUSB_TRANSFER_COMPLETED;
1952 case kIOReturnAborted:
1953 return LIBUSB_TRANSFER_CANCELLED;
1954 case kIOUSBPipeStalled:
1955 usbi_dbg ("transfer error: pipe is stalled");
1956 return LIBUSB_TRANSFER_STALL;
1957 case kIOReturnOverrun:
1958 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1959 return LIBUSB_TRANSFER_OVERFLOW;
1960 case kIOUSBTransactionTimeout:
1961 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1962 itransfer->timeout_flags |= USBI_TRANSFER_TIMED_OUT;
1963 return LIBUSB_TRANSFER_TIMED_OUT;
1965 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1966 return LIBUSB_TRANSFER_ERROR;
1970 static int darwin_handle_transfer_completion (struct usbi_transfer *itransfer) {
1971 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1972 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1973 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1974 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1975 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1976 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1979 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1980 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1981 return LIBUSB_ERROR_INVALID_PARAM;
1984 usbi_dbg ("handling %s completion with kernel status %d",
1985 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", tpriv->result);
1987 if (kIOReturnSuccess == tpriv->result || kIOReturnUnderrun == tpriv->result) {
1988 if (isIsoc && tpriv->isoc_framelist) {
1989 /* copy isochronous results back */
1991 for (i = 0; i < transfer->num_iso_packets ; i++) {
1992 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1993 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1994 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1997 itransfer->transferred += tpriv->size;
2000 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
2001 return usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, tpriv->result));
2004 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
2005 #if !OSX_USE_CLOCK_GETTIME
2006 mach_timespec_t sys_time;
2007 clock_serv_t clock_ref;
2010 case USBI_CLOCK_REALTIME:
2011 /* CLOCK_REALTIME represents time since the epoch */
2012 clock_ref = clock_realtime;
2014 case USBI_CLOCK_MONOTONIC:
2015 /* use system boot time as reference for the monotonic clock */
2016 clock_ref = clock_monotonic;
2019 return LIBUSB_ERROR_INVALID_PARAM;
2022 clock_get_time (clock_ref, &sys_time);
2024 tp->tv_sec = sys_time.tv_sec;
2025 tp->tv_nsec = sys_time.tv_nsec;
2030 case USBI_CLOCK_MONOTONIC:
2031 return clock_gettime(CLOCK_MONOTONIC, tp);
2032 case USBI_CLOCK_REALTIME:
2033 return clock_gettime(CLOCK_REALTIME, tp);
2035 return LIBUSB_ERROR_INVALID_PARAM;
2040 #if InterfaceVersion >= 550
2041 static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints,
2042 int num_endpoints) {
2043 struct darwin_interface *cInterface;
2044 UInt32 supportsStreams;
2048 /* find the mimimum number of supported streams on the endpoint list */
2049 for (i = 0 ; i < num_endpoints ; ++i) {
2050 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) {
2054 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2055 if (num_streams > supportsStreams)
2056 num_streams = supportsStreams;
2059 /* it is an error if any endpoint in endpoints does not support streams */
2060 if (0 == num_streams)
2061 return LIBUSB_ERROR_INVALID_PARAM;
2063 /* create the streams */
2064 for (i = 0 ; i < num_endpoints ; ++i) {
2065 (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
2067 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, num_streams);
2068 if (kIOReturnSuccess != rc)
2069 return darwin_to_libusb(rc);
2075 static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) {
2076 struct darwin_interface *cInterface;
2077 UInt32 supportsStreams;
2081 for (int i = 0 ; i < num_endpoints ; ++i) {
2082 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface)))
2085 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2086 if (0 == supportsStreams)
2087 return LIBUSB_ERROR_INVALID_PARAM;
2089 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, 0);
2090 if (kIOReturnSuccess != rc)
2091 return darwin_to_libusb(rc);
2094 return LIBUSB_SUCCESS;
2098 const struct usbi_os_backend usbi_backend = {
2101 .init = darwin_init,
2102 .exit = darwin_exit,
2103 .get_device_list = NULL, /* not needed */
2104 .get_device_descriptor = darwin_get_device_descriptor,
2105 .get_active_config_descriptor = darwin_get_active_config_descriptor,
2106 .get_config_descriptor = darwin_get_config_descriptor,
2107 .hotplug_poll = darwin_hotplug_poll,
2109 .open = darwin_open,
2110 .close = darwin_close,
2111 .get_configuration = darwin_get_configuration,
2112 .set_configuration = darwin_set_configuration,
2113 .claim_interface = darwin_claim_interface,
2114 .release_interface = darwin_release_interface,
2116 .set_interface_altsetting = darwin_set_interface_altsetting,
2117 .clear_halt = darwin_clear_halt,
2118 .reset_device = darwin_reset_device,
2120 #if InterfaceVersion >= 550
2121 .alloc_streams = darwin_alloc_streams,
2122 .free_streams = darwin_free_streams,
2125 .kernel_driver_active = darwin_kernel_driver_active,
2126 .detach_kernel_driver = darwin_detach_kernel_driver,
2127 .attach_kernel_driver = darwin_attach_kernel_driver,
2129 .destroy_device = darwin_destroy_device,
2131 .submit_transfer = darwin_submit_transfer,
2132 .cancel_transfer = darwin_cancel_transfer,
2133 .clear_transfer_priv = darwin_clear_transfer_priv,
2135 .handle_transfer_completion = darwin_handle_transfer_completion,
2137 .clock_gettime = darwin_clock_gettime,
2139 .device_priv_size = sizeof(struct darwin_device_priv),
2140 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
2141 .transfer_priv_size = sizeof(struct darwin_transfer_priv),