1 /* -*- Mode: C; indent-tabs-mode:nil -*- */
3 * darwin backend for libusb 1.0
4 * Copyright © 2008-2014 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 <libkern/OSAtomic.h>
33 #include <sys/sysctl.h>
35 #include <mach/clock.h>
36 #include <mach/clock_types.h>
37 #include <mach/mach_host.h>
38 #include <mach/mach_port.h>
40 #include <AvailabilityMacros.h>
41 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
42 #include <objc/objc-auto.h>
45 #include "darwin_usb.h"
47 /* async event thread */
48 static pthread_mutex_t libusb_darwin_at_mutex = PTHREAD_MUTEX_INITIALIZER;
49 static pthread_cond_t libusb_darwin_at_cond = PTHREAD_COND_INITIALIZER;
51 static pthread_once_t darwin_init_once = PTHREAD_ONCE_INIT;
53 static clock_serv_t clock_realtime;
54 static clock_serv_t clock_monotonic;
56 static CFRunLoopRef libusb_darwin_acfl = NULL; /* event cf loop */
57 static CFRunLoopSourceRef libusb_darwin_acfls = NULL; /* shutdown signal for event cf loop */
58 static volatile int32_t initCount = 0;
60 static usbi_mutex_t darwin_cached_devices_lock = PTHREAD_MUTEX_INITIALIZER;
61 static struct list_head darwin_cached_devices = {&darwin_cached_devices, &darwin_cached_devices};
62 static char *darwin_device_class = kIOUSBDeviceClassName;
64 #define DARWIN_CACHED_DEVICE(a) ((struct darwin_cached_device *) (((struct darwin_device_priv *)((a)->os_priv))->dev))
66 /* async event thread */
67 static pthread_t libusb_darwin_at;
69 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
70 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
71 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
72 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
73 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
75 static int darwin_scan_devices(struct libusb_context *ctx);
76 static int process_new_device (struct libusb_context *ctx, io_service_t service);
78 #if defined(ENABLE_LOGGING)
79 static const char *darwin_error_str (int result) {
80 static char string_buffer[50];
82 case kIOReturnSuccess:
84 case kIOReturnNotOpen:
85 return "device not opened for exclusive access";
86 case kIOReturnNoDevice:
87 return "no connection to an IOService";
88 case kIOUSBNoAsyncPortErr:
89 return "no async port has been opened for interface";
90 case kIOReturnExclusiveAccess:
91 return "another process has device opened for exclusive access";
92 case kIOUSBPipeStalled:
93 return "pipe is stalled";
95 return "could not establish a connection to the Darwin kernel";
96 case kIOUSBTransactionTimeout:
97 return "transaction timed out";
98 case kIOReturnBadArgument:
99 return "invalid argument";
100 case kIOReturnAborted:
101 return "transaction aborted";
102 case kIOReturnNotResponding:
103 return "device not responding";
104 case kIOReturnOverrun:
105 return "data overrun";
106 case kIOReturnCannotWire:
107 return "physical memory can not be wired down";
108 case kIOReturnNoResources:
109 return "out of resources";
110 case kIOUSBHighSpeedSplitError:
111 return "high speed split error";
113 snprintf(string_buffer, sizeof(string_buffer), "unknown error (0x%x)", result);
114 return string_buffer;
119 static int darwin_to_libusb (int result) {
121 case kIOReturnUnderrun:
122 case kIOReturnSuccess:
123 return LIBUSB_SUCCESS;
124 case kIOReturnNotOpen:
125 case kIOReturnNoDevice:
126 return LIBUSB_ERROR_NO_DEVICE;
127 case kIOReturnExclusiveAccess:
128 return LIBUSB_ERROR_ACCESS;
129 case kIOUSBPipeStalled:
130 return LIBUSB_ERROR_PIPE;
131 case kIOReturnBadArgument:
132 return LIBUSB_ERROR_INVALID_PARAM;
133 case kIOUSBTransactionTimeout:
134 return LIBUSB_ERROR_TIMEOUT;
135 case kIOReturnNotResponding:
136 case kIOReturnAborted:
138 case kIOUSBNoAsyncPortErr:
140 return LIBUSB_ERROR_OTHER;
144 /* this function must be called with the darwin_cached_devices_lock held */
145 static void darwin_deref_cached_device(struct darwin_cached_device *cached_dev) {
146 cached_dev->refcount--;
147 /* free the device and remove it from the cache */
148 if (0 == cached_dev->refcount) {
149 list_del(&cached_dev->list);
151 (*(cached_dev->device))->Release(cached_dev->device);
156 static void darwin_ref_cached_device(struct darwin_cached_device *cached_dev) {
157 cached_dev->refcount++;
160 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) {
161 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
163 /* current interface */
164 struct darwin_interface *cInterface;
168 usbi_dbg ("converting ep address 0x%02x to pipeRef and interface", ep);
170 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
171 cInterface = &priv->interfaces[iface];
173 if (dev_handle->claimed_interfaces & (1 << iface)) {
174 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
175 if (cInterface->endpoint_addrs[i] == ep) {
182 *interface_out = cInterface;
184 usbi_dbg ("pipe %d on interface %d matches", *pipep, iface);
191 /* No pipe found with the correct endpoint address */
192 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
194 return LIBUSB_ERROR_NOT_FOUND;
197 static int usb_setup_device_iterator (io_iterator_t *deviceIterator, UInt32 location) {
198 CFMutableDictionaryRef matchingDict = IOServiceMatching(darwin_device_class);
201 return kIOReturnError;
204 CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
205 &kCFTypeDictionaryKeyCallBacks,
206 &kCFTypeDictionaryValueCallBacks);
208 if (propertyMatchDict) {
209 /* there are no unsigned CFNumber types so treat the value as signed. the os seems to do this
210 internally (CFNumberType of locationID is 3) */
211 CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberSInt32Type, &location);
213 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
214 /* release our reference to the CFNumber (CFDictionarySetValue retains it) */
215 CFRelease (locationCF);
217 CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
218 /* release out reference to the CFMutableDictionaryRef (CFDictionarySetValue retains it) */
219 CFRelease (propertyMatchDict);
221 /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
224 return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator);
227 /* Returns 1 on success, 0 on failure. */
228 static int get_ioregistry_value_number (io_service_t service, CFStringRef property, CFNumberType type, void *p) {
229 CFTypeRef cfNumber = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
233 if (CFGetTypeID(cfNumber) == CFNumberGetTypeID()) {
234 ret = CFNumberGetValue(cfNumber, type, p);
237 CFRelease (cfNumber);
243 static int get_ioregistry_value_data (io_service_t service, CFStringRef property, ssize_t size, void *p) {
244 CFTypeRef cfData = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
248 if (CFGetTypeID (cfData) == CFDataGetTypeID ()) {
249 CFIndex length = CFDataGetLength (cfData);
254 CFDataGetBytes (cfData, CFRangeMake(0, size), p);
264 static usb_device_t **darwin_device_from_service (io_service_t service)
266 io_cf_plugin_ref_t *plugInInterface = NULL;
267 usb_device_t **device;
268 kern_return_t result;
271 result = IOCreatePlugInInterfaceForService(service, kIOUSBDeviceUserClientTypeID,
272 kIOCFPlugInInterfaceID, &plugInInterface,
275 if (kIOReturnSuccess != result || !plugInInterface) {
276 usbi_dbg ("could not set up plugin for service: %s", darwin_error_str (result));
280 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
282 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
283 (*plugInInterface)->Release (plugInInterface);
288 static void darwin_devices_attached (void *ptr, io_iterator_t add_devices) {
289 struct libusb_context *ctx;
290 io_service_t service;
292 usbi_mutex_lock(&active_contexts_lock);
294 while ((service = IOIteratorNext(add_devices))) {
295 /* add this device to each active context's device list */
296 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
297 process_new_device (ctx, service);;
300 IOObjectRelease(service);
303 usbi_mutex_unlock(&active_contexts_lock);
306 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
307 struct libusb_device *dev = NULL;
308 struct libusb_context *ctx;
309 struct darwin_cached_device *old_device;
315 usbi_mutex_lock(&active_contexts_lock);
317 while ((device = IOIteratorNext (rem_devices)) != 0) {
318 /* get the location from the i/o registry */
319 ret = get_ioregistry_value_number (device, CFSTR("sessionID"), kCFNumberSInt64Type, &session);
320 IOObjectRelease (device);
324 /* we need to match darwin_ref_cached_device call made in darwin_get_cached_device function
325 otherwise no cached device will ever get freed */
326 usbi_mutex_lock(&darwin_cached_devices_lock);
327 list_for_each_entry(old_device, &darwin_cached_devices, list, struct darwin_cached_device) {
328 if (old_device->session == session) {
329 darwin_deref_cached_device (old_device);
333 usbi_mutex_unlock(&darwin_cached_devices_lock);
335 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
336 usbi_dbg ("notifying context %p of device disconnect", ctx);
338 dev = usbi_get_device_by_session_id(ctx, (unsigned long) session);
340 /* signal the core that this device has been disconnected. the core will tear down this device
341 when the reference count reaches 0 */
342 usbi_disconnect_device(dev);
343 libusb_unref_device(dev);
348 usbi_mutex_unlock(&active_contexts_lock);
351 static void darwin_hotplug_poll (void)
353 /* not sure if 5 seconds will be too long/short but it should work ok */
354 mach_timespec_t timeout = {.tv_sec = 5, .tv_nsec = 0};
356 /* since a kernel thread may nodify the IOInterators used for
357 * hotplug notidication we can't just clear the iterators.
358 * instead just wait until all IOService providers are quiet */
359 (void) IOKitWaitQuiet (kIOMasterPortDefault, &timeout);
362 static void darwin_clear_iterator (io_iterator_t iter) {
365 while ((device = IOIteratorNext (iter)) != 0)
366 IOObjectRelease (device);
369 static void *darwin_event_thread_main (void *arg0) {
371 struct libusb_context *ctx = (struct libusb_context *)arg0;
372 CFRunLoopRef runloop;
374 /* Set this thread's name, so it can be seen in the debugger
375 and crash reports. */
376 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED <= 1080
377 pthread_setname_np ("org.libusb.device-hotplug");
379 /* Tell the Objective-C garbage collector about this thread.
380 This is required because, unlike NSThreads, pthreads are
381 not automatically registered. Although we don't use
382 Objective-C, we use CoreFoundation, which does. */
383 objc_registerThreadWithCollector();
386 /* hotplug (device arrival/removal) sources */
387 CFRunLoopSourceContext libusb_shutdown_cfsourcectx;
388 CFRunLoopSourceRef libusb_notification_cfsource;
389 io_notification_port_t libusb_notification_port;
390 io_iterator_t libusb_rem_device_iterator;
391 io_iterator_t libusb_add_device_iterator;
393 usbi_dbg ("creating hotplug event source");
395 runloop = CFRunLoopGetCurrent ();
398 /* add the shutdown cfsource to the run loop */
399 memset(&libusb_shutdown_cfsourcectx, 0, sizeof(libusb_shutdown_cfsourcectx));
400 libusb_shutdown_cfsourcectx.info = runloop;
401 libusb_shutdown_cfsourcectx.perform = (void (*)(void *))CFRunLoopStop;
402 libusb_darwin_acfls = CFRunLoopSourceCreate(NULL, 0, &libusb_shutdown_cfsourcectx);
403 CFRunLoopAddSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
405 /* add the notification port to the run loop */
406 libusb_notification_port = IONotificationPortCreate (kIOMasterPortDefault);
407 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
408 CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
410 /* create notifications for removed devices */
411 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
412 IOServiceMatching(darwin_device_class),
413 darwin_devices_detached,
414 ctx, &libusb_rem_device_iterator);
416 if (kresult != kIOReturnSuccess) {
417 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
422 /* create notifications for attached devices */
423 kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
424 IOServiceMatching(darwin_device_class),
425 darwin_devices_attached,
426 ctx, &libusb_add_device_iterator);
428 if (kresult != kIOReturnSuccess) {
429 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
435 darwin_clear_iterator (libusb_rem_device_iterator);
436 darwin_clear_iterator (libusb_add_device_iterator);
438 usbi_dbg ("darwin event thread ready to receive events");
440 /* signal the main thread that the hotplug runloop has been created. */
441 pthread_mutex_lock (&libusb_darwin_at_mutex);
442 libusb_darwin_acfl = runloop;
443 pthread_cond_signal (&libusb_darwin_at_cond);
444 pthread_mutex_unlock (&libusb_darwin_at_mutex);
446 /* run the runloop */
449 usbi_dbg ("darwin event thread exiting");
451 /* remove the notification cfsource */
452 CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
454 /* remove the shutdown cfsource */
455 CFRunLoopRemoveSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
457 /* delete notification port */
458 IONotificationPortDestroy (libusb_notification_port);
460 /* delete iterators */
461 IOObjectRelease (libusb_rem_device_iterator);
462 IOObjectRelease (libusb_add_device_iterator);
464 CFRelease (libusb_darwin_acfls);
467 libusb_darwin_acfls = NULL;
468 libusb_darwin_acfl = NULL;
473 /* cleanup function to destroy cached devices */
474 static void __attribute__((destructor)) _darwin_finalize(void) {
475 struct darwin_cached_device *dev, *next;
477 usbi_mutex_lock(&darwin_cached_devices_lock);
478 list_for_each_entry_safe(dev, next, &darwin_cached_devices, list, struct darwin_cached_device) {
479 darwin_deref_cached_device(dev);
481 usbi_mutex_unlock(&darwin_cached_devices_lock);
484 static void darwin_check_version (void) {
485 /* adjust for changes in the USB stack in xnu 15 */
486 int sysctl_args[] = {CTL_KERN, KERN_OSRELEASE};
488 char version_string[256] = {'\0',};
491 sysctl(sysctl_args, 2, version_string, &length, NULL, 0);
494 version = strtol (version_string, NULL, 10);
495 if (0 == errno && version >= 15) {
496 darwin_device_class = "IOUSBHostDevice";
500 static int darwin_init(struct libusb_context *ctx) {
501 host_name_port_t host_self;
504 rc = pthread_once (&darwin_init_once, darwin_check_version);
506 return LIBUSB_ERROR_OTHER;
509 rc = darwin_scan_devices (ctx);
510 if (LIBUSB_SUCCESS != rc) {
514 if (OSAtomicIncrement32Barrier(&initCount) == 1) {
515 /* create the clocks that will be used */
517 host_self = mach_host_self();
518 host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
519 host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
520 mach_port_deallocate(mach_task_self(), host_self);
522 pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, ctx);
524 pthread_mutex_lock (&libusb_darwin_at_mutex);
525 while (!libusb_darwin_acfl)
526 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
527 pthread_mutex_unlock (&libusb_darwin_at_mutex);
533 static void darwin_exit (void) {
534 if (OSAtomicDecrement32Barrier(&initCount) == 0) {
535 mach_port_deallocate(mach_task_self(), clock_realtime);
536 mach_port_deallocate(mach_task_self(), clock_monotonic);
538 /* stop the event runloop and wait for the thread to terminate. */
539 CFRunLoopSourceSignal(libusb_darwin_acfls);
540 CFRunLoopWakeUp (libusb_darwin_acfl);
541 pthread_join (libusb_darwin_at, NULL);
545 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
546 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
548 /* return cached copy */
549 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
556 static int get_configuration_index (struct libusb_device *dev, int config_value) {
557 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
559 IOUSBConfigurationDescriptorPtr desc;
562 /* is there a simpler way to determine the index? */
563 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
564 if (kresult != kIOReturnSuccess)
565 return darwin_to_libusb (kresult);
567 for (i = 0 ; i < numConfig ; i++) {
568 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
570 if (desc->bConfigurationValue == config_value)
574 /* configuration not found */
575 return LIBUSB_ERROR_NOT_FOUND;
578 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
579 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
582 if (0 == priv->active_config)
583 return LIBUSB_ERROR_NOT_FOUND;
585 config_index = get_configuration_index (dev, priv->active_config);
586 if (config_index < 0)
589 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
592 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
593 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
594 IOUSBConfigurationDescriptorPtr desc;
598 if (!priv || !priv->device)
599 return LIBUSB_ERROR_OTHER;
601 kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
602 if (kresult == kIOReturnSuccess) {
603 /* copy descriptor */
604 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
605 len = libusb_le16_to_cpu(desc->wTotalLength);
607 memmove (buffer, desc, len);
609 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
613 ret = darwin_to_libusb (kresult);
614 if (ret != LIBUSB_SUCCESS)
620 /* check whether the os has configured the device */
621 static int darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) {
622 usb_device_t **darwin_device = dev->device;
624 IOUSBConfigurationDescriptorPtr configDesc;
625 IOUSBFindInterfaceRequest request;
626 kern_return_t kresult;
627 io_iterator_t interface_iterator;
628 io_service_t firstInterface;
630 if (dev->dev_descriptor.bNumConfigurations < 1) {
631 usbi_err (ctx, "device has no configurations");
632 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
635 /* checking the configuration of a root hub simulation takes ~1 s in 10.11. the device is
637 if (0x05ac == dev->dev_descriptor.idVendor && 0x8005 == dev->dev_descriptor.idProduct) {
638 usbi_dbg ("ignoring configuration on root hub simulation");
639 dev->active_config = 0;
643 /* find the first configuration */
644 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
645 dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
647 /* check if the device is already configured. there is probably a better way than iterating over the
648 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
649 might lock up on the device request) */
651 /* Setup the Interface Request */
652 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
653 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
654 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
655 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
657 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
659 return darwin_to_libusb (kresult);
662 firstInterface = IOIteratorNext(interface_iterator);
664 /* done with the interface iterator */
665 IOObjectRelease(interface_iterator);
667 if (firstInterface) {
668 IOObjectRelease (firstInterface);
670 /* device is configured */
671 if (dev->dev_descriptor.bNumConfigurations == 1)
672 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
673 dev->active_config = dev->first_config;
675 /* devices with more than one configuration should work with GetConfiguration */
676 (*darwin_device)->GetConfiguration (darwin_device, &dev->active_config);
679 dev->active_config = 0;
681 usbi_dbg ("active config: %u, first config: %u", dev->active_config, dev->first_config);
686 static int darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
687 IOUSBDevRequestTO req;
689 memset (buffer, 0, buffer_size);
691 /* Set up request for descriptor/ */
692 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
693 req.bRequest = kUSBRqGetDescriptor;
694 req.wValue = desc << 8;
695 req.wIndex = desc_index;
696 req.wLength = buffer_size;
698 req.noDataTimeout = 20;
699 req.completionTimeout = 100;
701 return (*device)->DeviceRequestTO (device, &req);
704 static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct darwin_cached_device *dev) {
705 usb_device_t **device = dev->device;
706 int retries = 1, delay = 30000;
707 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
711 UInt16 idProduct, idVendor;
713 dev->can_enumerate = 0;
715 (*device)->GetDeviceClass (device, &bDeviceClass);
716 (*device)->GetDeviceProduct (device, &idProduct);
717 (*device)->GetDeviceVendor (device, &idVendor);
719 /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
720 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
721 * to follow the spec as closely as possible, try opening the device */
722 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
725 /**** retrieve device descriptor ****/
726 ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &dev->dev_descriptor, sizeof(dev->dev_descriptor));
728 if (kIOReturnOverrun == ret && kUSBDeviceDesc == dev->dev_descriptor.bDescriptorType)
729 /* received an overrun error but we still received a device descriptor */
730 ret = kIOReturnSuccess;
732 if (kIOUSBVendorIDAppleComputer == idVendor) {
733 /* NTH: don't bother retrying or unsuspending Apple devices */
737 if (kIOReturnSuccess == ret && (0 == dev->dev_descriptor.bNumConfigurations ||
738 0 == dev->dev_descriptor.bcdUSB)) {
739 /* work around for incorrectly configured devices */
740 if (try_reconfigure && is_open) {
741 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
743 /* set the first configuration */
744 (*device)->SetConfiguration(device, 1);
746 /* don't try to reconfigure again */
750 ret = kIOUSBPipeStalled;
753 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
754 /* device may be suspended. unsuspend it and try again */
755 #if DeviceVersion >= 320
758 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
759 (void)(*device)->GetUSBDeviceInformation (device, &info);
761 /* note that the device was suspended */
762 if (info & (1 << kUSBInformationDeviceIsSuspendedBit) || 0 == info)
767 /* try to unsuspend the device */
768 ret2 = (*device)->USBDeviceSuspend (device, 0);
769 if (kIOReturnSuccess != ret2) {
770 /* prevent log spew from poorly behaving devices. this indicates the
771 os actually had trouble communicating with the device */
772 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
780 if (kIOReturnSuccess != ret) {
781 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
782 /* sleep for a little while before trying again */
783 nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000UL}, NULL);
785 } while (kIOReturnSuccess != ret && retries--);
788 /* resuspend the device */
789 (void)(*device)->USBDeviceSuspend (device, 1);
792 (void) (*device)->USBDeviceClose (device);
794 if (ret != kIOReturnSuccess) {
795 /* a debug message was already printed out for this error */
796 if (LIBUSB_CLASS_HUB == bDeviceClass)
797 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
798 idVendor, idProduct, darwin_error_str (ret), ret);
800 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
801 idVendor, idProduct, darwin_error_str (ret), ret);
802 return darwin_to_libusb (ret);
805 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
806 if (libusb_le16_to_cpu (dev->dev_descriptor.idProduct) != idProduct) {
807 /* not a valid device */
808 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
809 idProduct, libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
810 return LIBUSB_ERROR_NO_DEVICE;
813 usbi_dbg ("cached device descriptor:");
814 usbi_dbg (" bDescriptorType: 0x%02x", dev->dev_descriptor.bDescriptorType);
815 usbi_dbg (" bcdUSB: 0x%04x", dev->dev_descriptor.bcdUSB);
816 usbi_dbg (" bDeviceClass: 0x%02x", dev->dev_descriptor.bDeviceClass);
817 usbi_dbg (" bDeviceSubClass: 0x%02x", dev->dev_descriptor.bDeviceSubClass);
818 usbi_dbg (" bDeviceProtocol: 0x%02x", dev->dev_descriptor.bDeviceProtocol);
819 usbi_dbg (" bMaxPacketSize0: 0x%02x", dev->dev_descriptor.bMaxPacketSize0);
820 usbi_dbg (" idVendor: 0x%04x", dev->dev_descriptor.idVendor);
821 usbi_dbg (" idProduct: 0x%04x", dev->dev_descriptor.idProduct);
822 usbi_dbg (" bcdDevice: 0x%04x", dev->dev_descriptor.bcdDevice);
823 usbi_dbg (" iManufacturer: 0x%02x", dev->dev_descriptor.iManufacturer);
824 usbi_dbg (" iProduct: 0x%02x", dev->dev_descriptor.iProduct);
825 usbi_dbg (" iSerialNumber: 0x%02x", dev->dev_descriptor.iSerialNumber);
826 usbi_dbg (" bNumConfigurations: 0x%02x", dev->dev_descriptor.bNumConfigurations);
828 dev->can_enumerate = 1;
830 return LIBUSB_SUCCESS;
833 static int get_device_port (io_service_t service, UInt8 *port) {
834 kern_return_t result;
838 if (get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, port)) {
842 result = IORegistryEntryGetParentEntry (service, kIOServicePlane, &parent);
843 if (kIOReturnSuccess == result) {
844 ret = get_ioregistry_value_data (parent, CFSTR("port"), 1, port);
845 IOObjectRelease (parent);
851 static int darwin_get_cached_device(struct libusb_context *ctx, io_service_t service,
852 struct darwin_cached_device **cached_out) {
853 struct darwin_cached_device *new_device;
854 UInt64 sessionID = 0, parent_sessionID = 0;
855 int ret = LIBUSB_SUCCESS;
856 usb_device_t **device;
858 kern_return_t result;
861 /* get some info from the io registry */
862 (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
863 if (!get_device_port (service, &port)) {
864 usbi_dbg("could not get connected port number");
867 usbi_dbg("finding cached device for sessionID 0x%" PRIx64, sessionID);
869 result = IORegistryEntryGetParentEntry (service, kIOUSBPlane, &parent);
871 if (kIOReturnSuccess == result) {
872 (void) get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, &parent_sessionID);
873 IOObjectRelease(parent);
876 usbi_mutex_lock(&darwin_cached_devices_lock);
880 list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) {
881 usbi_dbg("matching sessionID 0x%" PRIx64 " against cached device with sessionID 0x%" PRIx64, sessionID, new_device->session);
882 if (new_device->session == sessionID) {
883 usbi_dbg("using cached device for device");
884 *cached_out = new_device;
892 usbi_dbg("caching new device with sessionID 0x%" PRIx64, sessionID);
894 device = darwin_device_from_service (service);
896 ret = LIBUSB_ERROR_NO_DEVICE;
900 new_device = calloc (1, sizeof (*new_device));
902 ret = LIBUSB_ERROR_NO_MEM;
906 /* add this device to the cached device list */
907 list_add(&new_device->list, &darwin_cached_devices);
909 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
911 /* keep a reference to this device */
912 darwin_ref_cached_device(new_device);
914 new_device->device = device;
915 new_device->session = sessionID;
916 (*device)->GetLocationID (device, &new_device->location);
917 new_device->port = port;
918 new_device->parent_session = parent_sessionID;
920 /* cache the device descriptor */
921 ret = darwin_cache_device_descriptor(ctx, new_device);
925 if (new_device->can_enumerate) {
926 snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address,
927 new_device->dev_descriptor.idVendor, new_device->dev_descriptor.idProduct,
928 new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass);
932 usbi_mutex_unlock(&darwin_cached_devices_lock);
934 /* keep track of devices regardless of if we successfully enumerate them to
935 prevent them from being enumerated multiple times */
937 *cached_out = new_device;
942 static int process_new_device (struct libusb_context *ctx, io_service_t service) {
943 struct darwin_device_priv *priv;
944 struct libusb_device *dev = NULL;
945 struct darwin_cached_device *cached_device;
950 ret = darwin_get_cached_device (ctx, service, &cached_device);
952 if (ret < 0 || !cached_device->can_enumerate) {
956 /* check current active configuration (and cache the first configuration value--
957 which may be used by claim_interface) */
958 ret = darwin_check_configuration (ctx, cached_device);
962 usbi_dbg ("allocating new device in context %p for with session 0x%" PRIx64,
963 ctx, cached_device->session);
965 dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
967 return LIBUSB_ERROR_NO_MEM;
970 priv = (struct darwin_device_priv *)dev->os_priv;
972 priv->dev = cached_device;
973 darwin_ref_cached_device (priv->dev);
975 if (cached_device->parent_session > 0) {
976 dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session);
978 dev->parent_dev = NULL;
980 dev->port_number = cached_device->port;
981 dev->bus_number = cached_device->location >> 24;
982 dev->device_address = cached_device->address;
984 (*(priv->dev->device))->GetDeviceSpeed (priv->dev->device, &devSpeed);
987 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
988 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
989 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
990 #if DeviceVersion >= 500
991 case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
994 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
997 ret = usbi_sanitize_device (dev);
1001 usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
1002 dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
1006 usbi_connect_device (dev);
1008 libusb_unref_device (dev);
1014 static int darwin_scan_devices(struct libusb_context *ctx) {
1015 io_iterator_t deviceIterator;
1016 io_service_t service;
1017 kern_return_t kresult;
1019 kresult = usb_setup_device_iterator (&deviceIterator, 0);
1020 if (kresult != kIOReturnSuccess)
1021 return darwin_to_libusb (kresult);
1023 while ((service = IOIteratorNext (deviceIterator))) {
1024 (void) process_new_device (ctx, service);
1026 IOObjectRelease(service);
1029 IOObjectRelease(deviceIterator);
1034 static int darwin_open (struct libusb_device_handle *dev_handle) {
1035 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1036 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1039 if (0 == dpriv->open_count) {
1040 /* try to open the device */
1041 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
1042 if (kresult != kIOReturnSuccess) {
1043 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
1045 if (kIOReturnExclusiveAccess != kresult) {
1046 return darwin_to_libusb (kresult);
1049 /* it is possible to perform some actions on a device that is not open so do not return an error */
1055 /* create async event source */
1056 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
1057 if (kresult != kIOReturnSuccess) {
1058 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
1060 if (priv->is_open) {
1061 (*(dpriv->device))->USBDeviceClose (dpriv->device);
1066 return darwin_to_libusb (kresult);
1069 CFRetain (libusb_darwin_acfl);
1071 /* add the cfSource to the aync run loop */
1072 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
1075 /* device opened successfully */
1076 dpriv->open_count++;
1078 usbi_dbg ("device open for access");
1083 static void darwin_close (struct libusb_device_handle *dev_handle) {
1084 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1085 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1089 if (dpriv->open_count == 0) {
1090 /* something is probably very wrong if this is the case */
1091 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!");
1095 dpriv->open_count--;
1097 /* make sure all interfaces are released */
1098 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1099 if (dev_handle->claimed_interfaces & (1 << i))
1100 libusb_release_interface (dev_handle, i);
1102 if (0 == dpriv->open_count) {
1103 /* delete the device's async event source */
1104 if (priv->cfSource) {
1105 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
1106 CFRelease (priv->cfSource);
1107 priv->cfSource = NULL;
1108 CFRelease (libusb_darwin_acfl);
1111 if (priv->is_open) {
1112 /* close the device */
1113 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
1115 /* Log the fact that we had a problem closing the file, however failing a
1116 * close isn't really an error, so return success anyway */
1117 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
1123 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
1124 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1126 *config = (int) dpriv->active_config;
1131 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
1132 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1136 /* Setting configuration will invalidate the interface, so we need
1137 to reclaim it. First, dispose of existing interfaces, if any. */
1138 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1139 if (dev_handle->claimed_interfaces & (1 << i))
1140 darwin_release_interface (dev_handle, i);
1142 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
1143 if (kresult != kIOReturnSuccess)
1144 return darwin_to_libusb (kresult);
1146 /* Reclaim any interfaces. */
1147 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1148 if (dev_handle->claimed_interfaces & (1 << i))
1149 darwin_claim_interface (dev_handle, i);
1151 dpriv->active_config = config;
1156 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
1157 IOUSBFindInterfaceRequest request;
1158 kern_return_t kresult;
1159 io_iterator_t interface_iterator;
1160 UInt8 bInterfaceNumber;
1163 *usbInterfacep = IO_OBJECT_NULL;
1165 /* Setup the Interface Request */
1166 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1167 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1168 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1169 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1171 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1175 while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1176 /* find the interface number */
1177 ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
1180 if (ret && bInterfaceNumber == ifc) {
1184 (void) IOObjectRelease (*usbInterfacep);
1187 /* done with the interface iterator */
1188 IOObjectRelease(interface_iterator);
1193 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
1194 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1196 /* current interface */
1197 struct darwin_interface *cInterface = &priv->interfaces[iface];
1199 kern_return_t kresult;
1201 u_int8_t numep, direction, number;
1202 u_int8_t dont_care1, dont_care3;
1203 u_int16_t dont_care2;
1206 usbi_dbg ("building table of endpoints.");
1208 /* retrieve the total number of endpoints on this interface */
1209 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1211 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1212 return darwin_to_libusb (kresult);
1215 /* iterate through pipe references */
1216 for (int i = 1 ; i <= numep ; i++) {
1217 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1218 &dont_care2, &dont_care3);
1220 if (kresult != kIOReturnSuccess) {
1221 /* probably a buggy device. try to get the endpoint address from the descriptors */
1222 struct libusb_config_descriptor *config;
1223 const struct libusb_endpoint_descriptor *endpoint_desc;
1226 kresult = (*(cInterface->interface))->GetAlternateSetting (cInterface->interface, &alt_setting);
1228 usbi_err (HANDLE_CTX (dev_handle), "can't get alternate setting for interface");
1229 return darwin_to_libusb (kresult);
1232 rc = libusb_get_active_config_descriptor (dev_handle->dev, &config);
1233 if (LIBUSB_SUCCESS != rc) {
1237 endpoint_desc = config->interface[iface].altsetting[alt_setting].endpoint + i - 1;
1239 cInterface->endpoint_addrs[i - 1] = endpoint_desc->bEndpointAddress;
1241 cInterface->endpoint_addrs[i - 1] = (((kUSBIn == direction) << kUSBRqDirnShift) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1244 usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, cInterface->endpoint_addrs[i - 1] >> kUSBRqDirnShift,
1245 cInterface->endpoint_addrs[i - 1] & LIBUSB_ENDPOINT_ADDRESS_MASK);
1248 cInterface->num_endpoints = numep;
1253 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1254 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1255 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1256 io_service_t usbInterface = IO_OBJECT_NULL;
1258 IOCFPlugInInterface **plugInInterface = NULL;
1261 /* current interface */
1262 struct darwin_interface *cInterface = &priv->interfaces[iface];
1264 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1265 if (kresult != kIOReturnSuccess)
1266 return darwin_to_libusb (kresult);
1268 /* make sure we have an interface */
1269 if (!usbInterface && dpriv->first_config != 0) {
1270 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1272 /* set the configuration */
1273 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1274 if (kresult != LIBUSB_SUCCESS) {
1275 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1279 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1281 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1282 return darwin_to_libusb (kresult);
1286 if (!usbInterface) {
1287 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1288 return LIBUSB_ERROR_NOT_FOUND;
1291 /* get an interface to the device's interface */
1292 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1293 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1295 /* ignore release error */
1296 (void)IOObjectRelease (usbInterface);
1299 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1300 return darwin_to_libusb (kresult);
1303 if (!plugInInterface) {
1304 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1305 return LIBUSB_ERROR_NOT_FOUND;
1308 /* Do the actual claim */
1309 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1310 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1311 (LPVOID)&cInterface->interface);
1312 /* We no longer need the intermediate plug-in */
1313 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1314 (*plugInInterface)->Release (plugInInterface);
1315 if (kresult || !cInterface->interface) {
1316 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1317 return darwin_to_libusb (kresult);
1320 /* claim the interface */
1321 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1323 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1324 return darwin_to_libusb (kresult);
1327 /* update list of endpoints */
1328 kresult = get_endpoints (dev_handle, iface);
1330 /* this should not happen */
1331 darwin_release_interface (dev_handle, iface);
1332 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1336 cInterface->cfSource = NULL;
1338 /* create async event source */
1339 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1340 if (kresult != kIOReturnSuccess) {
1341 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1343 /* can't continue without an async event source */
1344 (void)darwin_release_interface (dev_handle, iface);
1346 return darwin_to_libusb (kresult);
1349 /* add the cfSource to the async thread's run loop */
1350 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1352 usbi_dbg ("interface opened");
1357 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1358 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1361 /* current interface */
1362 struct darwin_interface *cInterface = &priv->interfaces[iface];
1364 /* Check to see if an interface is open */
1365 if (!cInterface->interface)
1366 return LIBUSB_SUCCESS;
1368 /* clean up endpoint data */
1369 cInterface->num_endpoints = 0;
1371 /* delete the interface's async event source */
1372 if (cInterface->cfSource) {
1373 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1374 CFRelease (cInterface->cfSource);
1377 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1379 usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1381 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1382 if (kresult != kIOReturnSuccess)
1383 usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1385 cInterface->interface = (usb_interface_t **) IO_OBJECT_NULL;
1387 return darwin_to_libusb (kresult);
1390 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1391 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1394 /* current interface */
1395 struct darwin_interface *cInterface = &priv->interfaces[iface];
1397 if (!cInterface->interface)
1398 return LIBUSB_ERROR_NO_DEVICE;
1400 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1401 if (kresult != kIOReturnSuccess)
1402 darwin_reset_device (dev_handle);
1404 /* update list of endpoints */
1405 kresult = get_endpoints (dev_handle, iface);
1407 /* this should not happen */
1408 darwin_release_interface (dev_handle, iface);
1409 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1413 return darwin_to_libusb (kresult);
1416 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1417 /* current interface */
1418 struct darwin_interface *cInterface;
1422 /* determine the interface/endpoint to use */
1423 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, NULL, &cInterface) != 0) {
1424 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1426 return LIBUSB_ERROR_NOT_FOUND;
1429 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1430 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1432 usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1434 return darwin_to_libusb (kresult);
1437 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1438 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1439 IOUSBDeviceDescriptor descriptor;
1440 IOUSBConfigurationDescriptorPtr cached_configuration;
1441 IOUSBConfigurationDescriptor configuration;
1442 bool reenumerate = false;
1446 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1448 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1449 return darwin_to_libusb (kresult);
1453 usbi_dbg ("darwin/reset_device: checking if device descriptor changed");
1455 /* ignore return code. if we can't get a descriptor it might be worthwhile re-enumerating anway */
1456 (void) darwin_request_descriptor (dpriv->device, kUSBDeviceDesc, 0, &descriptor, sizeof (descriptor));
1458 /* check if the device descriptor has changed */
1459 if (0 != memcmp (&dpriv->dev_descriptor, &descriptor, sizeof (descriptor))) {
1464 /* check if any configuration descriptor has changed */
1465 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1466 usbi_dbg ("darwin/reset_device: checking if configuration descriptor %d changed", i);
1468 (void) darwin_request_descriptor (dpriv->device, kUSBConfDesc, i, &configuration, sizeof (configuration));
1469 (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1471 if (!cached_configuration || 0 != memcmp (cached_configuration, &configuration, sizeof (configuration))) {
1479 usbi_dbg ("darwin/reset_device: device requires reenumeration");
1480 (void) (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
1481 return LIBUSB_ERROR_NOT_FOUND;
1484 usbi_dbg ("darwin/reset_device: device reset complete");
1486 return LIBUSB_SUCCESS;
1489 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1490 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1491 io_service_t usbInterface;
1495 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1497 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1499 return darwin_to_libusb (kresult);
1502 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1503 IOObjectRelease (usbInterface);
1515 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1516 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1519 return LIBUSB_ERROR_NOT_SUPPORTED;
1522 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1525 return LIBUSB_ERROR_NOT_SUPPORTED;
1528 static void darwin_destroy_device(struct libusb_device *dev) {
1529 struct darwin_device_priv *dpriv = (struct darwin_device_priv *) dev->os_priv;
1532 /* need to hold the lock in case this is the last reference to the device */
1533 usbi_mutex_lock(&darwin_cached_devices_lock);
1534 darwin_deref_cached_device (dpriv->dev);
1536 usbi_mutex_unlock(&darwin_cached_devices_lock);
1540 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1541 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1544 uint8_t transferType;
1545 /* None of the values below are used in libusbx for bulk transfers */
1546 uint8_t direction, number, interval, pipeRef;
1547 uint16_t maxPacketSize;
1549 struct darwin_interface *cInterface;
1551 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1552 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1554 return LIBUSB_ERROR_NOT_FOUND;
1557 ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1558 &transferType, &maxPacketSize, &interval);
1561 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1562 darwin_error_str(ret), ret);
1563 return darwin_to_libusb (ret);
1566 if (0 != (transfer->length % maxPacketSize)) {
1567 /* do not need a zero packet */
1568 transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1571 /* submit the request */
1572 /* timeouts are unavailable on interrupt endpoints */
1573 if (transferType == kUSBInterrupt) {
1574 if (IS_XFERIN(transfer))
1575 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1576 transfer->length, darwin_async_io_callback, itransfer);
1578 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1579 transfer->length, darwin_async_io_callback, itransfer);
1581 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1583 if (IS_XFERIN(transfer))
1584 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1585 transfer->length, transfer->timeout, transfer->timeout,
1586 darwin_async_io_callback, (void *)itransfer);
1588 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1589 transfer->length, transfer->timeout, transfer->timeout,
1590 darwin_async_io_callback, (void *)itransfer);
1594 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1595 darwin_error_str(ret), ret);
1597 return darwin_to_libusb (ret);
1600 #if InterfaceVersion >= 550
1601 static int submit_stream_transfer(struct usbi_transfer *itransfer) {
1602 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1603 struct darwin_interface *cInterface;
1607 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1608 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1610 return LIBUSB_ERROR_NOT_FOUND;
1613 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1615 if (IS_XFERIN(transfer))
1616 ret = (*(cInterface->interface))->ReadStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1617 transfer->buffer, transfer->length, transfer->timeout,
1618 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1620 ret = (*(cInterface->interface))->WriteStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1621 transfer->buffer, transfer->length, transfer->timeout,
1622 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1625 usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1626 darwin_error_str(ret), ret);
1628 return darwin_to_libusb (ret);
1632 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1633 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1634 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1637 uint8_t direction, number, interval, pipeRef, transferType;
1638 uint16_t maxPacketSize;
1640 AbsoluteTime atTime;
1643 struct darwin_interface *cInterface;
1645 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1646 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1647 free(tpriv->isoc_framelist);
1648 tpriv->isoc_framelist = NULL;
1651 if (!tpriv->isoc_framelist) {
1652 tpriv->num_iso_packets = transfer->num_iso_packets;
1653 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1654 if (!tpriv->isoc_framelist)
1655 return LIBUSB_ERROR_NO_MEM;
1658 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1659 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1660 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1662 /* determine the interface/endpoint to use */
1663 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1664 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1666 return LIBUSB_ERROR_NOT_FOUND;
1669 /* determine the properties of this endpoint and the speed of the device */
1670 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1671 &transferType, &maxPacketSize, &interval);
1673 /* Last but not least we need the bus frame number */
1674 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1676 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1677 free(tpriv->isoc_framelist);
1678 tpriv->isoc_framelist = NULL;
1680 return darwin_to_libusb (kresult);
1683 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1684 &transferType, &maxPacketSize, &interval);
1686 /* schedule for a frame a little in the future */
1689 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1690 frame = cInterface->frames[transfer->endpoint];
1692 /* submit the request */
1693 if (IS_XFERIN(transfer))
1694 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1695 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1698 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1699 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1702 if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
1704 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1));
1706 /* High/super speed */
1707 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1)) / 8;
1709 if (kresult != kIOReturnSuccess) {
1710 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1711 darwin_error_str(kresult));
1712 free (tpriv->isoc_framelist);
1713 tpriv->isoc_framelist = NULL;
1716 return darwin_to_libusb (kresult);
1719 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1720 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1721 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1722 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1723 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1727 bzero(&tpriv->req, sizeof(tpriv->req));
1729 /* IOUSBDeviceInterface expects the request in cpu endianness */
1730 tpriv->req.bmRequestType = setup->bmRequestType;
1731 tpriv->req.bRequest = setup->bRequest;
1732 /* these values should be in bus order from libusb_fill_control_setup */
1733 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1734 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1735 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1736 /* data is stored after the libusb control block */
1737 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1738 tpriv->req.completionTimeout = transfer->timeout;
1739 tpriv->req.noDataTimeout = transfer->timeout;
1741 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1743 /* all transfers in libusb-1.0 are async */
1745 if (transfer->endpoint) {
1746 struct darwin_interface *cInterface;
1749 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1750 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1752 return LIBUSB_ERROR_NOT_FOUND;
1755 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1757 /* control request on endpoint 0 */
1758 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1760 if (kresult != kIOReturnSuccess)
1761 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1763 return darwin_to_libusb (kresult);
1766 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1767 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1769 switch (transfer->type) {
1770 case LIBUSB_TRANSFER_TYPE_CONTROL:
1771 return submit_control_transfer(itransfer);
1772 case LIBUSB_TRANSFER_TYPE_BULK:
1773 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1774 return submit_bulk_transfer(itransfer);
1775 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1776 return submit_iso_transfer(itransfer);
1777 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1778 #if InterfaceVersion >= 550
1779 return submit_stream_transfer(itransfer);
1781 usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers");
1782 return LIBUSB_ERROR_NOT_SUPPORTED;
1785 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1786 return LIBUSB_ERROR_INVALID_PARAM;
1790 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1791 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1792 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1795 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
1798 return LIBUSB_ERROR_NO_DEVICE;
1800 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1802 return darwin_to_libusb (kresult);
1805 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1806 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1807 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1808 struct darwin_interface *cInterface;
1809 uint8_t pipeRef, iface;
1812 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) {
1813 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1815 return LIBUSB_ERROR_NOT_FOUND;
1819 return LIBUSB_ERROR_NO_DEVICE;
1821 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
1823 /* abort transactions */
1824 #if InterfaceVersion >= 550
1825 if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type)
1826 (*(cInterface->interface))->AbortStreamsPipe (cInterface->interface, pipeRef, itransfer->stream_id);
1829 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1831 usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
1833 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1834 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1836 return darwin_to_libusb (kresult);
1839 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1840 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1842 switch (transfer->type) {
1843 case LIBUSB_TRANSFER_TYPE_CONTROL:
1844 return cancel_control_transfer(itransfer);
1845 case LIBUSB_TRANSFER_TYPE_BULK:
1846 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1847 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1848 return darwin_abort_transfers (itransfer);
1850 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1851 return LIBUSB_ERROR_INVALID_PARAM;
1855 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1856 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1857 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1859 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1860 free (tpriv->isoc_framelist);
1861 tpriv->isoc_framelist = NULL;
1865 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1866 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1867 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1868 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1870 usbi_dbg ("an async io operation has completed");
1872 /* if requested write a zero packet */
1873 if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
1874 struct darwin_interface *cInterface;
1877 (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface);
1879 (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
1882 tpriv->result = result;
1883 tpriv->size = (UInt32) (uintptr_t) arg0;
1885 /* signal the core that this transfer is complete */
1886 usbi_signal_transfer_completion(itransfer);
1889 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1890 if (itransfer->timeout_flags & USBI_TRANSFER_TIMED_OUT)
1891 result = kIOUSBTransactionTimeout;
1894 case kIOReturnUnderrun:
1895 case kIOReturnSuccess:
1896 return LIBUSB_TRANSFER_COMPLETED;
1897 case kIOReturnAborted:
1898 return LIBUSB_TRANSFER_CANCELLED;
1899 case kIOUSBPipeStalled:
1900 usbi_dbg ("transfer error: pipe is stalled");
1901 return LIBUSB_TRANSFER_STALL;
1902 case kIOReturnOverrun:
1903 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1904 return LIBUSB_TRANSFER_OVERFLOW;
1905 case kIOUSBTransactionTimeout:
1906 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1907 itransfer->timeout_flags |= USBI_TRANSFER_TIMED_OUT;
1908 return LIBUSB_TRANSFER_TIMED_OUT;
1910 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1911 return LIBUSB_TRANSFER_ERROR;
1915 static int darwin_handle_transfer_completion (struct usbi_transfer *itransfer) {
1916 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1917 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1918 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1919 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1920 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1921 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1924 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1925 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1926 return LIBUSB_ERROR_INVALID_PARAM;
1929 usbi_dbg ("handling %s completion with kernel status %d",
1930 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", tpriv->result);
1932 if (kIOReturnSuccess == tpriv->result || kIOReturnUnderrun == tpriv->result) {
1933 if (isIsoc && tpriv->isoc_framelist) {
1934 /* copy isochronous results back */
1936 for (i = 0; i < transfer->num_iso_packets ; i++) {
1937 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1938 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1939 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1942 itransfer->transferred += tpriv->size;
1945 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1946 return usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, tpriv->result));
1949 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1950 mach_timespec_t sys_time;
1951 clock_serv_t clock_ref;
1954 case USBI_CLOCK_REALTIME:
1955 /* CLOCK_REALTIME represents time since the epoch */
1956 clock_ref = clock_realtime;
1958 case USBI_CLOCK_MONOTONIC:
1959 /* use system boot time as reference for the monotonic clock */
1960 clock_ref = clock_monotonic;
1963 return LIBUSB_ERROR_INVALID_PARAM;
1966 clock_get_time (clock_ref, &sys_time);
1968 tp->tv_sec = sys_time.tv_sec;
1969 tp->tv_nsec = sys_time.tv_nsec;
1974 #if InterfaceVersion >= 550
1975 static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints,
1976 int num_endpoints) {
1977 struct darwin_interface *cInterface;
1978 UInt32 supportsStreams;
1982 /* find the mimimum number of supported streams on the endpoint list */
1983 for (i = 0 ; i < num_endpoints ; ++i) {
1984 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) {
1988 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
1989 if (num_streams > supportsStreams)
1990 num_streams = supportsStreams;
1993 /* it is an error if any endpoint in endpoints does not support streams */
1994 if (0 == num_streams)
1995 return LIBUSB_ERROR_INVALID_PARAM;
1997 /* create the streams */
1998 for (i = 0 ; i < num_endpoints ; ++i) {
1999 (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
2001 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, num_streams);
2002 if (kIOReturnSuccess != rc)
2003 return darwin_to_libusb(rc);
2009 static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) {
2010 struct darwin_interface *cInterface;
2011 UInt32 supportsStreams;
2015 for (int i = 0 ; i < num_endpoints ; ++i) {
2016 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface)))
2019 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2020 if (0 == supportsStreams)
2021 return LIBUSB_ERROR_INVALID_PARAM;
2023 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, 0);
2024 if (kIOReturnSuccess != rc)
2025 return darwin_to_libusb(rc);
2028 return LIBUSB_SUCCESS;
2032 const struct usbi_os_backend darwin_backend = {
2035 .init = darwin_init,
2036 .exit = darwin_exit,
2037 .get_device_list = NULL, /* not needed */
2038 .get_device_descriptor = darwin_get_device_descriptor,
2039 .get_active_config_descriptor = darwin_get_active_config_descriptor,
2040 .get_config_descriptor = darwin_get_config_descriptor,
2041 .hotplug_poll = darwin_hotplug_poll,
2043 .open = darwin_open,
2044 .close = darwin_close,
2045 .get_configuration = darwin_get_configuration,
2046 .set_configuration = darwin_set_configuration,
2047 .claim_interface = darwin_claim_interface,
2048 .release_interface = darwin_release_interface,
2050 .set_interface_altsetting = darwin_set_interface_altsetting,
2051 .clear_halt = darwin_clear_halt,
2052 .reset_device = darwin_reset_device,
2054 #if InterfaceVersion >= 550
2055 .alloc_streams = darwin_alloc_streams,
2056 .free_streams = darwin_free_streams,
2059 .kernel_driver_active = darwin_kernel_driver_active,
2060 .detach_kernel_driver = darwin_detach_kernel_driver,
2061 .attach_kernel_driver = darwin_attach_kernel_driver,
2063 .destroy_device = darwin_destroy_device,
2065 .submit_transfer = darwin_submit_transfer,
2066 .cancel_transfer = darwin_cancel_transfer,
2067 .clear_transfer_priv = darwin_clear_transfer_priv,
2069 .handle_transfer_completion = darwin_handle_transfer_completion,
2071 .clock_gettime = darwin_clock_gettime,
2073 .device_priv_size = sizeof(struct darwin_device_priv),
2074 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
2075 .transfer_priv_size = sizeof(struct darwin_transfer_priv),