1 /* -*- Mode: C; indent-tabs-mode:nil -*- */
3 * darwin backend for libusb 1.0
4 * Copyright © 2008-2018 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 #if !OSX_USE_CLOCK_GETTIME
79 static clock_serv_t clock_realtime;
80 static clock_serv_t clock_monotonic;
83 static CFRunLoopRef libusb_darwin_acfl = NULL; /* event cf loop */
84 static CFRunLoopSourceRef libusb_darwin_acfls = NULL; /* shutdown signal for event cf loop */
86 static usbi_mutex_t darwin_cached_devices_lock = PTHREAD_MUTEX_INITIALIZER;
87 static struct list_head darwin_cached_devices = {&darwin_cached_devices, &darwin_cached_devices};
88 static const char *darwin_device_class = kIOUSBDeviceClassName;
90 #define DARWIN_CACHED_DEVICE(a) ((struct darwin_cached_device *) (((struct darwin_device_priv *)((a)->os_priv))->dev))
92 /* async event thread */
93 static pthread_t libusb_darwin_at;
95 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
96 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
97 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
98 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
99 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
101 static int darwin_scan_devices(struct libusb_context *ctx);
102 static int process_new_device (struct libusb_context *ctx, io_service_t service);
104 #if defined(ENABLE_LOGGING)
105 static const char *darwin_error_str (int result) {
106 static char string_buffer[50];
108 case kIOReturnSuccess:
110 case kIOReturnNotOpen:
111 return "device not opened for exclusive access";
112 case kIOReturnNoDevice:
113 return "no connection to an IOService";
114 case kIOUSBNoAsyncPortErr:
115 return "no async port has been opened for interface";
116 case kIOReturnExclusiveAccess:
117 return "another process has device opened for exclusive access";
118 case kIOUSBPipeStalled:
119 return "pipe is stalled";
121 return "could not establish a connection to the Darwin kernel";
122 case kIOUSBTransactionTimeout:
123 return "transaction timed out";
124 case kIOReturnBadArgument:
125 return "invalid argument";
126 case kIOReturnAborted:
127 return "transaction aborted";
128 case kIOReturnNotResponding:
129 return "device not responding";
130 case kIOReturnOverrun:
131 return "data overrun";
132 case kIOReturnCannotWire:
133 return "physical memory can not be wired down";
134 case kIOReturnNoResources:
135 return "out of resources";
136 case kIOUSBHighSpeedSplitError:
137 return "high speed split error";
139 snprintf(string_buffer, sizeof(string_buffer), "unknown error (0x%x)", result);
140 return string_buffer;
145 static int darwin_to_libusb (int result) {
147 case kIOReturnUnderrun:
148 case kIOReturnSuccess:
149 return LIBUSB_SUCCESS;
150 case kIOReturnNotOpen:
151 case kIOReturnNoDevice:
152 return LIBUSB_ERROR_NO_DEVICE;
153 case kIOReturnExclusiveAccess:
154 return LIBUSB_ERROR_ACCESS;
155 case kIOUSBPipeStalled:
156 return LIBUSB_ERROR_PIPE;
157 case kIOReturnBadArgument:
158 return LIBUSB_ERROR_INVALID_PARAM;
159 case kIOUSBTransactionTimeout:
160 return LIBUSB_ERROR_TIMEOUT;
161 case kIOReturnNotResponding:
162 case kIOReturnAborted:
164 case kIOUSBNoAsyncPortErr:
166 return LIBUSB_ERROR_OTHER;
170 /* this function must be called with the darwin_cached_devices_lock held */
171 static void darwin_deref_cached_device(struct darwin_cached_device *cached_dev) {
172 cached_dev->refcount--;
173 /* free the device and remove it from the cache */
174 if (0 == cached_dev->refcount) {
175 list_del(&cached_dev->list);
177 (*(cached_dev->device))->Release(cached_dev->device);
182 static void darwin_ref_cached_device(struct darwin_cached_device *cached_dev) {
183 cached_dev->refcount++;
186 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) {
187 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
189 /* current interface */
190 struct darwin_interface *cInterface;
194 usbi_dbg ("converting ep address 0x%02x to pipeRef and interface", ep);
196 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
197 cInterface = &priv->interfaces[iface];
199 if (dev_handle->claimed_interfaces & (1 << iface)) {
200 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
201 if (cInterface->endpoint_addrs[i] == ep) {
208 *interface_out = cInterface;
210 usbi_dbg ("pipe %d on interface %d matches", *pipep, iface);
217 /* No pipe found with the correct endpoint address */
218 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
220 return LIBUSB_ERROR_NOT_FOUND;
223 static int usb_setup_device_iterator (io_iterator_t *deviceIterator, UInt32 location) {
224 CFMutableDictionaryRef matchingDict = IOServiceMatching(darwin_device_class);
227 return kIOReturnError;
230 CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
231 &kCFTypeDictionaryKeyCallBacks,
232 &kCFTypeDictionaryValueCallBacks);
234 /* there are no unsigned CFNumber types so treat the value as signed. the OS seems to do this
235 internally (CFNumberType of locationID is kCFNumberSInt32Type) */
236 CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberSInt32Type, &location);
238 if (propertyMatchDict && locationCF) {
239 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
240 CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
242 /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
244 /* release our references as per the Create Rule */
245 if (propertyMatchDict)
246 CFRelease (propertyMatchDict);
248 CFRelease (locationCF);
251 return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator);
254 /* Returns 1 on success, 0 on failure. */
255 static int get_ioregistry_value_number (io_service_t service, CFStringRef property, CFNumberType type, void *p) {
256 CFTypeRef cfNumber = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
260 if (CFGetTypeID(cfNumber) == CFNumberGetTypeID()) {
261 ret = CFNumberGetValue(cfNumber, type, p);
264 CFRelease (cfNumber);
270 static int get_ioregistry_value_data (io_service_t service, CFStringRef property, ssize_t size, void *p) {
271 CFTypeRef cfData = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
275 if (CFGetTypeID (cfData) == CFDataGetTypeID ()) {
276 CFIndex length = CFDataGetLength (cfData);
281 CFDataGetBytes (cfData, CFRangeMake(0, size), p);
291 static usb_device_t **darwin_device_from_service (io_service_t service)
293 io_cf_plugin_ref_t *plugInInterface = NULL;
294 usb_device_t **device;
295 kern_return_t result;
298 result = IOCreatePlugInInterfaceForService(service, kIOUSBDeviceUserClientTypeID,
299 kIOCFPlugInInterfaceID, &plugInInterface,
302 if (kIOReturnSuccess != result || !plugInInterface) {
303 usbi_dbg ("could not set up plugin for service: %s", darwin_error_str (result));
307 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
309 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
310 (*plugInInterface)->Release (plugInInterface);
315 static void darwin_devices_attached (void *ptr, io_iterator_t add_devices) {
317 struct libusb_context *ctx;
318 io_service_t service;
320 usbi_mutex_lock(&active_contexts_lock);
322 while ((service = IOIteratorNext(add_devices))) {
323 /* add this device to each active context's device list */
324 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
325 process_new_device (ctx, service);
328 IOObjectRelease(service);
331 usbi_mutex_unlock(&active_contexts_lock);
334 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
336 struct libusb_device *dev = NULL;
337 struct libusb_context *ctx;
338 struct darwin_cached_device *old_device;
344 usbi_mutex_lock(&active_contexts_lock);
346 while ((device = IOIteratorNext (rem_devices)) != 0) {
347 /* get the location from the i/o registry */
348 ret = get_ioregistry_value_number (device, CFSTR("sessionID"), kCFNumberSInt64Type, &session);
349 IOObjectRelease (device);
353 /* we need to match darwin_ref_cached_device call made in darwin_get_cached_device function
354 otherwise no cached device will ever get freed */
355 usbi_mutex_lock(&darwin_cached_devices_lock);
356 list_for_each_entry(old_device, &darwin_cached_devices, list, struct darwin_cached_device) {
357 if (old_device->session == session) {
358 darwin_deref_cached_device (old_device);
362 usbi_mutex_unlock(&darwin_cached_devices_lock);
364 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
365 usbi_dbg ("notifying context %p of device disconnect", ctx);
367 dev = usbi_get_device_by_session_id(ctx, (unsigned long) session);
369 /* signal the core that this device has been disconnected. the core will tear down this device
370 when the reference count reaches 0 */
371 usbi_disconnect_device(dev);
372 libusb_unref_device(dev);
377 usbi_mutex_unlock(&active_contexts_lock);
380 static void darwin_hotplug_poll (void)
382 /* not sure if 5 seconds will be too long/short but it should work ok */
383 mach_timespec_t timeout = {.tv_sec = 5, .tv_nsec = 0};
385 /* since a kernel thread may nodify the IOInterators used for
386 * hotplug notidication we can't just clear the iterators.
387 * instead just wait until all IOService providers are quiet */
388 (void) IOKitWaitQuiet (kIOMasterPortDefault, &timeout);
391 static void darwin_clear_iterator (io_iterator_t iter) {
394 while ((device = IOIteratorNext (iter)) != 0)
395 IOObjectRelease (device);
398 static void *darwin_event_thread_main (void *arg0) {
400 struct libusb_context *ctx = (struct libusb_context *)arg0;
401 CFRunLoopRef runloop;
403 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
404 /* Set this thread's name, so it can be seen in the debugger
405 and crash reports. */
406 pthread_setname_np ("org.libusb.device-hotplug");
409 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
410 /* Tell the Objective-C garbage collector about this thread.
411 This is required because, unlike NSThreads, pthreads are
412 not automatically registered. Although we don't use
413 Objective-C, we use CoreFoundation, which does.
414 Garbage collection support was entirely removed in 10.12,
415 so don't bother there. */
416 objc_registerThreadWithCollector();
419 /* hotplug (device arrival/removal) sources */
420 CFRunLoopSourceContext libusb_shutdown_cfsourcectx;
421 CFRunLoopSourceRef libusb_notification_cfsource;
422 io_notification_port_t libusb_notification_port;
423 io_iterator_t libusb_rem_device_iterator;
424 io_iterator_t libusb_add_device_iterator;
426 usbi_dbg ("creating hotplug event source");
428 runloop = CFRunLoopGetCurrent ();
431 /* add the shutdown cfsource to the run loop */
432 memset(&libusb_shutdown_cfsourcectx, 0, sizeof(libusb_shutdown_cfsourcectx));
433 libusb_shutdown_cfsourcectx.info = runloop;
434 libusb_shutdown_cfsourcectx.perform = (void (*)(void *))CFRunLoopStop;
435 libusb_darwin_acfls = CFRunLoopSourceCreate(NULL, 0, &libusb_shutdown_cfsourcectx);
436 CFRunLoopAddSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
438 /* add the notification port to the run loop */
439 libusb_notification_port = IONotificationPortCreate (kIOMasterPortDefault);
440 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
441 CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
443 /* create notifications for removed devices */
444 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
445 IOServiceMatching(darwin_device_class),
446 darwin_devices_detached,
447 ctx, &libusb_rem_device_iterator);
449 if (kresult != kIOReturnSuccess) {
450 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
455 /* create notifications for attached devices */
456 kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
457 IOServiceMatching(darwin_device_class),
458 darwin_devices_attached,
459 ctx, &libusb_add_device_iterator);
461 if (kresult != kIOReturnSuccess) {
462 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
468 darwin_clear_iterator (libusb_rem_device_iterator);
469 darwin_clear_iterator (libusb_add_device_iterator);
471 usbi_dbg ("darwin event thread ready to receive events");
473 /* signal the main thread that the hotplug runloop has been created. */
474 pthread_mutex_lock (&libusb_darwin_at_mutex);
475 libusb_darwin_acfl = runloop;
476 pthread_cond_signal (&libusb_darwin_at_cond);
477 pthread_mutex_unlock (&libusb_darwin_at_mutex);
479 /* run the runloop */
482 usbi_dbg ("darwin event thread exiting");
484 /* remove the notification cfsource */
485 CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
487 /* remove the shutdown cfsource */
488 CFRunLoopRemoveSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
490 /* delete notification port */
491 IONotificationPortDestroy (libusb_notification_port);
493 /* delete iterators */
494 IOObjectRelease (libusb_rem_device_iterator);
495 IOObjectRelease (libusb_add_device_iterator);
497 CFRelease (libusb_darwin_acfls);
500 libusb_darwin_acfls = NULL;
501 libusb_darwin_acfl = NULL;
506 /* cleanup function to destroy cached devices */
507 static void __attribute__((destructor)) _darwin_finalize(void) {
508 struct darwin_cached_device *dev, *next;
510 usbi_mutex_lock(&darwin_cached_devices_lock);
511 list_for_each_entry_safe(dev, next, &darwin_cached_devices, list, struct darwin_cached_device) {
512 darwin_deref_cached_device(dev);
514 usbi_mutex_unlock(&darwin_cached_devices_lock);
517 static int darwin_init(struct libusb_context *ctx) {
520 rc = darwin_scan_devices (ctx);
521 if (LIBUSB_SUCCESS != rc) {
525 if (libusb_darwin_atomic_fetch_add (&initCount, 1) == 0) {
526 #if !OSX_USE_CLOCK_GETTIME
527 /* create the clocks that will be used if clock_gettime() is not available */
528 host_name_port_t host_self;
530 host_self = mach_host_self();
531 host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
532 host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
533 mach_port_deallocate(mach_task_self(), host_self);
536 pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, ctx);
538 pthread_mutex_lock (&libusb_darwin_at_mutex);
539 while (!libusb_darwin_acfl)
540 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
541 pthread_mutex_unlock (&libusb_darwin_at_mutex);
547 static void darwin_exit (struct libusb_context *ctx) {
549 if (libusb_darwin_atomic_fetch_add (&initCount, -1) == 1) {
550 #if !OSX_USE_CLOCK_GETTIME
551 mach_port_deallocate(mach_task_self(), clock_realtime);
552 mach_port_deallocate(mach_task_self(), clock_monotonic);
555 /* stop the event runloop and wait for the thread to terminate. */
556 CFRunLoopSourceSignal(libusb_darwin_acfls);
557 CFRunLoopWakeUp (libusb_darwin_acfl);
558 pthread_join (libusb_darwin_at, NULL);
562 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
563 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
565 /* return cached copy */
566 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
573 static int get_configuration_index (struct libusb_device *dev, int config_value) {
574 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
576 IOUSBConfigurationDescriptorPtr desc;
579 /* is there a simpler way to determine the index? */
580 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
581 if (kresult != kIOReturnSuccess)
582 return darwin_to_libusb (kresult);
584 for (i = 0 ; i < numConfig ; i++) {
585 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
587 if (desc->bConfigurationValue == config_value)
591 /* configuration not found */
592 return LIBUSB_ERROR_NOT_FOUND;
595 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
596 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
599 if (0 == priv->active_config)
600 return LIBUSB_ERROR_NOT_FOUND;
602 config_index = get_configuration_index (dev, priv->active_config);
603 if (config_index < 0)
606 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
609 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
610 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
611 IOUSBConfigurationDescriptorPtr desc;
615 if (!priv || !priv->device)
616 return LIBUSB_ERROR_OTHER;
618 kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
619 if (kresult == kIOReturnSuccess) {
620 /* copy descriptor */
621 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
622 len = libusb_le16_to_cpu(desc->wTotalLength);
624 memmove (buffer, desc, len);
626 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
630 ret = darwin_to_libusb (kresult);
631 if (ret != LIBUSB_SUCCESS)
637 /* check whether the os has configured the device */
638 static int darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) {
639 usb_device_t **darwin_device = dev->device;
641 IOUSBConfigurationDescriptorPtr configDesc;
642 IOUSBFindInterfaceRequest request;
643 kern_return_t kresult;
644 io_iterator_t interface_iterator;
645 io_service_t firstInterface;
647 if (dev->dev_descriptor.bNumConfigurations < 1) {
648 usbi_err (ctx, "device has no configurations");
649 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
652 /* checking the configuration of a root hub simulation takes ~1 s in 10.11. the device is
654 if (0x05ac == dev->dev_descriptor.idVendor && 0x8005 == dev->dev_descriptor.idProduct) {
655 usbi_dbg ("ignoring configuration on root hub simulation");
656 dev->active_config = 0;
660 /* find the first configuration */
661 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
662 dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
664 /* check if the device is already configured. there is probably a better way than iterating over the
665 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
666 might lock up on the device request) */
668 /* Setup the Interface Request */
669 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
670 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
671 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
672 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
674 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
676 return darwin_to_libusb (kresult);
679 firstInterface = IOIteratorNext(interface_iterator);
681 /* done with the interface iterator */
682 IOObjectRelease(interface_iterator);
684 if (firstInterface) {
685 IOObjectRelease (firstInterface);
687 /* device is configured */
688 if (dev->dev_descriptor.bNumConfigurations == 1)
689 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
690 dev->active_config = dev->first_config;
692 /* devices with more than one configuration should work with GetConfiguration */
693 (*darwin_device)->GetConfiguration (darwin_device, &dev->active_config);
696 dev->active_config = 0;
698 usbi_dbg ("active config: %u, first config: %u", dev->active_config, dev->first_config);
703 static int darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
704 IOUSBDevRequestTO req;
706 memset (buffer, 0, buffer_size);
708 /* Set up request for descriptor/ */
709 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
710 req.bRequest = kUSBRqGetDescriptor;
711 req.wValue = desc << 8;
712 req.wIndex = desc_index;
713 req.wLength = buffer_size;
715 req.noDataTimeout = 20;
716 req.completionTimeout = 100;
718 return (*device)->DeviceRequestTO (device, &req);
721 static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct darwin_cached_device *dev) {
722 usb_device_t **device = dev->device;
723 int retries = 1, delay = 30000;
724 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
728 UInt16 idProduct, idVendor;
730 dev->can_enumerate = 0;
732 (*device)->GetDeviceClass (device, &bDeviceClass);
733 (*device)->GetDeviceProduct (device, &idProduct);
734 (*device)->GetDeviceVendor (device, &idVendor);
736 /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
737 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
738 * to follow the spec as closely as possible, try opening the device */
739 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
742 /**** retrieve device descriptor ****/
743 ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &dev->dev_descriptor, sizeof(dev->dev_descriptor));
745 if (kIOReturnOverrun == ret && kUSBDeviceDesc == dev->dev_descriptor.bDescriptorType)
746 /* received an overrun error but we still received a device descriptor */
747 ret = kIOReturnSuccess;
749 if (kIOUSBVendorIDAppleComputer == idVendor) {
750 /* NTH: don't bother retrying or unsuspending Apple devices */
754 if (kIOReturnSuccess == ret && (0 == dev->dev_descriptor.bNumConfigurations ||
755 0 == dev->dev_descriptor.bcdUSB)) {
756 /* work around for incorrectly configured devices */
757 if (try_reconfigure && is_open) {
758 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
760 /* set the first configuration */
761 (*device)->SetConfiguration(device, 1);
763 /* don't try to reconfigure again */
767 ret = kIOUSBPipeStalled;
770 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
771 /* device may be suspended. unsuspend it and try again */
772 #if DeviceVersion >= 320
775 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
776 (void)(*device)->GetUSBDeviceInformation (device, &info);
778 /* note that the device was suspended */
779 if (info & (1 << kUSBInformationDeviceIsSuspendedBit) || 0 == info)
784 /* try to unsuspend the device */
785 ret2 = (*device)->USBDeviceSuspend (device, 0);
786 if (kIOReturnSuccess != ret2) {
787 /* prevent log spew from poorly behaving devices. this indicates the
788 os actually had trouble communicating with the device */
789 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
797 if (kIOReturnSuccess != ret) {
798 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
799 /* sleep for a little while before trying again */
800 nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000UL}, NULL);
802 } while (kIOReturnSuccess != ret && retries--);
805 /* resuspend the device */
806 (void)(*device)->USBDeviceSuspend (device, 1);
809 (void) (*device)->USBDeviceClose (device);
811 if (ret != kIOReturnSuccess) {
812 /* a debug message was already printed out for this error */
813 if (LIBUSB_CLASS_HUB == bDeviceClass)
814 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
815 idVendor, idProduct, darwin_error_str (ret), ret);
817 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
818 idVendor, idProduct, darwin_error_str (ret), ret);
819 return darwin_to_libusb (ret);
822 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
823 if (libusb_le16_to_cpu (dev->dev_descriptor.idProduct) != idProduct) {
824 /* not a valid device */
825 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
826 idProduct, libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
827 return LIBUSB_ERROR_NO_DEVICE;
830 usbi_dbg ("cached device descriptor:");
831 usbi_dbg (" bDescriptorType: 0x%02x", dev->dev_descriptor.bDescriptorType);
832 usbi_dbg (" bcdUSB: 0x%04x", dev->dev_descriptor.bcdUSB);
833 usbi_dbg (" bDeviceClass: 0x%02x", dev->dev_descriptor.bDeviceClass);
834 usbi_dbg (" bDeviceSubClass: 0x%02x", dev->dev_descriptor.bDeviceSubClass);
835 usbi_dbg (" bDeviceProtocol: 0x%02x", dev->dev_descriptor.bDeviceProtocol);
836 usbi_dbg (" bMaxPacketSize0: 0x%02x", dev->dev_descriptor.bMaxPacketSize0);
837 usbi_dbg (" idVendor: 0x%04x", dev->dev_descriptor.idVendor);
838 usbi_dbg (" idProduct: 0x%04x", dev->dev_descriptor.idProduct);
839 usbi_dbg (" bcdDevice: 0x%04x", dev->dev_descriptor.bcdDevice);
840 usbi_dbg (" iManufacturer: 0x%02x", dev->dev_descriptor.iManufacturer);
841 usbi_dbg (" iProduct: 0x%02x", dev->dev_descriptor.iProduct);
842 usbi_dbg (" iSerialNumber: 0x%02x", dev->dev_descriptor.iSerialNumber);
843 usbi_dbg (" bNumConfigurations: 0x%02x", dev->dev_descriptor.bNumConfigurations);
845 dev->can_enumerate = 1;
847 return LIBUSB_SUCCESS;
850 static int get_device_port (io_service_t service, UInt8 *port) {
851 kern_return_t result;
855 if (get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, port)) {
859 result = IORegistryEntryGetParentEntry (service, kIOServicePlane, &parent);
860 if (kIOReturnSuccess == result) {
861 ret = get_ioregistry_value_data (parent, CFSTR("port"), 1, port);
862 IOObjectRelease (parent);
868 static int get_device_parent_sessionID(io_service_t service, UInt64 *parent_sessionID) {
869 kern_return_t result;
872 /* Walk up the tree in the IOService plane until we find a parent that has a sessionID */
874 while((result = IORegistryEntryGetParentEntry (parent, kIOUSBPlane, &parent)) == kIOReturnSuccess) {
875 if (get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, parent_sessionID)) {
881 /* We ran out of parents */
885 static int darwin_get_cached_device(struct libusb_context *ctx, io_service_t service,
886 struct darwin_cached_device **cached_out) {
887 struct darwin_cached_device *new_device;
888 UInt64 sessionID = 0, parent_sessionID = 0;
889 int ret = LIBUSB_SUCCESS;
890 usb_device_t **device;
893 /* get some info from the io registry */
894 (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
895 if (!get_device_port (service, &port)) {
896 usbi_dbg("could not get connected port number");
899 usbi_dbg("finding cached device for sessionID 0x%" PRIx64, sessionID);
901 if (get_device_parent_sessionID(service, &parent_sessionID)) {
902 usbi_dbg("parent sessionID: 0x%" PRIx64, parent_sessionID);
905 usbi_mutex_lock(&darwin_cached_devices_lock);
909 list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) {
910 usbi_dbg("matching sessionID 0x%" PRIx64 " against cached device with sessionID 0x%" PRIx64, sessionID, new_device->session);
911 if (new_device->session == sessionID) {
912 usbi_dbg("using cached device for device");
913 *cached_out = new_device;
921 usbi_dbg("caching new device with sessionID 0x%" PRIx64, sessionID);
923 device = darwin_device_from_service (service);
925 ret = LIBUSB_ERROR_NO_DEVICE;
929 new_device = calloc (1, sizeof (*new_device));
931 ret = LIBUSB_ERROR_NO_MEM;
935 /* add this device to the cached device list */
936 list_add(&new_device->list, &darwin_cached_devices);
938 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
940 /* keep a reference to this device */
941 darwin_ref_cached_device(new_device);
943 new_device->device = device;
944 new_device->session = sessionID;
945 (*device)->GetLocationID (device, &new_device->location);
946 new_device->port = port;
947 new_device->parent_session = parent_sessionID;
949 /* cache the device descriptor */
950 ret = darwin_cache_device_descriptor(ctx, new_device);
954 if (new_device->can_enumerate) {
955 snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address,
956 new_device->dev_descriptor.idVendor, new_device->dev_descriptor.idProduct,
957 new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass);
961 usbi_mutex_unlock(&darwin_cached_devices_lock);
963 /* keep track of devices regardless of if we successfully enumerate them to
964 prevent them from being enumerated multiple times */
966 *cached_out = new_device;
971 static int process_new_device (struct libusb_context *ctx, io_service_t service) {
972 struct darwin_device_priv *priv;
973 struct libusb_device *dev = NULL;
974 struct darwin_cached_device *cached_device;
979 ret = darwin_get_cached_device (ctx, service, &cached_device);
981 if (ret < 0 || !cached_device->can_enumerate) {
985 /* check current active configuration (and cache the first configuration value--
986 which may be used by claim_interface) */
987 ret = darwin_check_configuration (ctx, cached_device);
991 usbi_dbg ("allocating new device in context %p for with session 0x%" PRIx64,
992 ctx, cached_device->session);
994 dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
996 return LIBUSB_ERROR_NO_MEM;
999 priv = (struct darwin_device_priv *)dev->os_priv;
1001 priv->dev = cached_device;
1002 darwin_ref_cached_device (priv->dev);
1004 if (cached_device->parent_session > 0) {
1005 dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session);
1007 dev->parent_dev = NULL;
1009 dev->port_number = cached_device->port;
1010 dev->bus_number = cached_device->location >> 24;
1011 dev->device_address = cached_device->address;
1013 (*(priv->dev->device))->GetDeviceSpeed (priv->dev->device, &devSpeed);
1016 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
1017 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
1018 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
1019 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
1020 case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
1022 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101200
1023 case kUSBDeviceSpeedSuperPlus: dev->speed = LIBUSB_SPEED_SUPER_PLUS; break;
1026 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
1029 ret = usbi_sanitize_device (dev);
1033 usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
1034 dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
1038 usbi_connect_device (dev);
1040 libusb_unref_device (dev);
1046 static int darwin_scan_devices(struct libusb_context *ctx) {
1047 io_iterator_t deviceIterator;
1048 io_service_t service;
1049 kern_return_t kresult;
1051 kresult = usb_setup_device_iterator (&deviceIterator, 0);
1052 if (kresult != kIOReturnSuccess)
1053 return darwin_to_libusb (kresult);
1055 while ((service = IOIteratorNext (deviceIterator))) {
1056 (void) process_new_device (ctx, service);
1058 IOObjectRelease(service);
1061 IOObjectRelease(deviceIterator);
1066 static int darwin_open (struct libusb_device_handle *dev_handle) {
1067 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1068 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1071 if (0 == dpriv->open_count) {
1072 /* try to open the device */
1073 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
1074 if (kresult != kIOReturnSuccess) {
1075 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
1077 if (kIOReturnExclusiveAccess != kresult) {
1078 return darwin_to_libusb (kresult);
1081 /* it is possible to perform some actions on a device that is not open so do not return an error */
1087 /* create async event source */
1088 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
1089 if (kresult != kIOReturnSuccess) {
1090 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
1092 if (priv->is_open) {
1093 (*(dpriv->device))->USBDeviceClose (dpriv->device);
1098 return darwin_to_libusb (kresult);
1101 CFRetain (libusb_darwin_acfl);
1103 /* add the cfSource to the aync run loop */
1104 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
1107 /* device opened successfully */
1108 dpriv->open_count++;
1110 usbi_dbg ("device open for access");
1115 static void darwin_close (struct libusb_device_handle *dev_handle) {
1116 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1117 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1121 if (dpriv->open_count == 0) {
1122 /* something is probably very wrong if this is the case */
1123 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!");
1127 dpriv->open_count--;
1129 /* make sure all interfaces are released */
1130 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1131 if (dev_handle->claimed_interfaces & (1 << i))
1132 libusb_release_interface (dev_handle, i);
1134 if (0 == dpriv->open_count) {
1135 /* delete the device's async event source */
1136 if (priv->cfSource) {
1137 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
1138 CFRelease (priv->cfSource);
1139 priv->cfSource = NULL;
1140 CFRelease (libusb_darwin_acfl);
1143 if (priv->is_open) {
1144 /* close the device */
1145 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
1147 /* Log the fact that we had a problem closing the file, however failing a
1148 * close isn't really an error, so return success anyway */
1149 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
1155 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
1156 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1158 *config = (int) dpriv->active_config;
1163 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
1164 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1168 /* Setting configuration will invalidate the interface, so we need
1169 to reclaim it. First, dispose of existing interfaces, if any. */
1170 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1171 if (dev_handle->claimed_interfaces & (1 << i))
1172 darwin_release_interface (dev_handle, i);
1174 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
1175 if (kresult != kIOReturnSuccess)
1176 return darwin_to_libusb (kresult);
1178 /* Reclaim any interfaces. */
1179 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1180 if (dev_handle->claimed_interfaces & (1 << i))
1181 darwin_claim_interface (dev_handle, i);
1183 dpriv->active_config = config;
1188 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
1189 IOUSBFindInterfaceRequest request;
1190 kern_return_t kresult;
1191 io_iterator_t interface_iterator;
1192 UInt8 bInterfaceNumber;
1195 *usbInterfacep = IO_OBJECT_NULL;
1197 /* Setup the Interface Request */
1198 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1199 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1200 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1201 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1203 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1207 while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1208 /* find the interface number */
1209 ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
1212 if (ret && bInterfaceNumber == ifc) {
1216 (void) IOObjectRelease (*usbInterfacep);
1219 /* done with the interface iterator */
1220 IOObjectRelease(interface_iterator);
1225 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
1226 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1228 /* current interface */
1229 struct darwin_interface *cInterface = &priv->interfaces[iface];
1231 kern_return_t kresult;
1233 UInt8 numep, direction, number;
1234 UInt8 dont_care1, dont_care3;
1238 usbi_dbg ("building table of endpoints.");
1240 /* retrieve the total number of endpoints on this interface */
1241 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1243 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1244 return darwin_to_libusb (kresult);
1247 /* iterate through pipe references */
1248 for (int i = 1 ; i <= numep ; i++) {
1249 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1250 &dont_care2, &dont_care3);
1252 if (kresult != kIOReturnSuccess) {
1253 /* probably a buggy device. try to get the endpoint address from the descriptors */
1254 struct libusb_config_descriptor *config;
1255 const struct libusb_endpoint_descriptor *endpoint_desc;
1258 kresult = (*(cInterface->interface))->GetAlternateSetting (cInterface->interface, &alt_setting);
1260 usbi_err (HANDLE_CTX (dev_handle), "can't get alternate setting for interface");
1261 return darwin_to_libusb (kresult);
1264 rc = libusb_get_active_config_descriptor (dev_handle->dev, &config);
1265 if (LIBUSB_SUCCESS != rc) {
1269 endpoint_desc = config->interface[iface].altsetting[alt_setting].endpoint + i - 1;
1271 cInterface->endpoint_addrs[i - 1] = endpoint_desc->bEndpointAddress;
1273 cInterface->endpoint_addrs[i - 1] = (((kUSBIn == direction) << kUSBRqDirnShift) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1276 usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, cInterface->endpoint_addrs[i - 1] >> kUSBRqDirnShift,
1277 cInterface->endpoint_addrs[i - 1] & LIBUSB_ENDPOINT_ADDRESS_MASK);
1280 cInterface->num_endpoints = numep;
1285 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1286 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1287 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1288 io_service_t usbInterface = IO_OBJECT_NULL;
1290 IOCFPlugInInterface **plugInInterface = NULL;
1293 /* current interface */
1294 struct darwin_interface *cInterface = &priv->interfaces[iface];
1296 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1297 if (kresult != kIOReturnSuccess)
1298 return darwin_to_libusb (kresult);
1300 /* make sure we have an interface */
1301 if (!usbInterface && dpriv->first_config != 0) {
1302 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1304 /* set the configuration */
1305 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1306 if (kresult != LIBUSB_SUCCESS) {
1307 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1311 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1313 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1314 return darwin_to_libusb (kresult);
1318 if (!usbInterface) {
1319 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1320 return LIBUSB_ERROR_NOT_FOUND;
1323 /* get an interface to the device's interface */
1324 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1325 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1327 /* ignore release error */
1328 (void)IOObjectRelease (usbInterface);
1331 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1332 return darwin_to_libusb (kresult);
1335 if (!plugInInterface) {
1336 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1337 return LIBUSB_ERROR_NOT_FOUND;
1340 /* Do the actual claim */
1341 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1342 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1343 (LPVOID)&cInterface->interface);
1344 /* We no longer need the intermediate plug-in */
1345 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1346 (*plugInInterface)->Release (plugInInterface);
1347 if (kresult || !cInterface->interface) {
1348 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1349 return darwin_to_libusb (kresult);
1352 /* claim the interface */
1353 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1355 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1356 return darwin_to_libusb (kresult);
1359 /* update list of endpoints */
1360 kresult = get_endpoints (dev_handle, iface);
1362 /* this should not happen */
1363 darwin_release_interface (dev_handle, iface);
1364 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1368 cInterface->cfSource = NULL;
1370 /* create async event source */
1371 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1372 if (kresult != kIOReturnSuccess) {
1373 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1375 /* can't continue without an async event source */
1376 (void)darwin_release_interface (dev_handle, iface);
1378 return darwin_to_libusb (kresult);
1381 /* add the cfSource to the async thread's run loop */
1382 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1384 usbi_dbg ("interface opened");
1389 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1390 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1393 /* current interface */
1394 struct darwin_interface *cInterface = &priv->interfaces[iface];
1396 /* Check to see if an interface is open */
1397 if (!cInterface->interface)
1398 return LIBUSB_SUCCESS;
1400 /* clean up endpoint data */
1401 cInterface->num_endpoints = 0;
1403 /* delete the interface's async event source */
1404 if (cInterface->cfSource) {
1405 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1406 CFRelease (cInterface->cfSource);
1409 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1411 usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1413 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1414 if (kresult != kIOReturnSuccess)
1415 usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1417 cInterface->interface = (usb_interface_t **) IO_OBJECT_NULL;
1419 return darwin_to_libusb (kresult);
1422 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1423 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1426 /* current interface */
1427 struct darwin_interface *cInterface = &priv->interfaces[iface];
1429 if (!cInterface->interface)
1430 return LIBUSB_ERROR_NO_DEVICE;
1432 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1433 if (kresult != kIOReturnSuccess)
1434 darwin_reset_device (dev_handle);
1436 /* update list of endpoints */
1437 kresult = get_endpoints (dev_handle, iface);
1439 /* this should not happen */
1440 darwin_release_interface (dev_handle, iface);
1441 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1445 return darwin_to_libusb (kresult);
1448 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1449 /* current interface */
1450 struct darwin_interface *cInterface;
1454 /* determine the interface/endpoint to use */
1455 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, NULL, &cInterface) != 0) {
1456 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1458 return LIBUSB_ERROR_NOT_FOUND;
1461 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1462 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1464 usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1466 return darwin_to_libusb (kresult);
1469 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1470 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1471 IOUSBDeviceDescriptor descriptor;
1472 IOUSBConfigurationDescriptorPtr cached_configuration;
1473 IOUSBConfigurationDescriptor configuration;
1474 bool reenumerate = false;
1478 /* from macOS 10.11 ResetDevice no longer does anything so just use USBDeviceReEnumerate */
1479 kresult = (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
1481 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceReEnumerate: %s", darwin_error_str (kresult));
1482 return darwin_to_libusb (kresult);
1486 usbi_dbg ("darwin/reset_device: checking if device descriptor changed");
1488 /* ignore return code. if we can't get a descriptor it might be worthwhile re-enumerating anway */
1489 (void) darwin_request_descriptor (dpriv->device, kUSBDeviceDesc, 0, &descriptor, sizeof (descriptor));
1491 /* check if the device descriptor has changed */
1492 if (0 != memcmp (&dpriv->dev_descriptor, &descriptor, sizeof (descriptor))) {
1497 /* check if any configuration descriptor has changed */
1498 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1499 usbi_dbg ("darwin/reset_device: checking if configuration descriptor %d changed", i);
1501 (void) darwin_request_descriptor (dpriv->device, kUSBConfDesc, i, &configuration, sizeof (configuration));
1502 (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1504 if (!cached_configuration || 0 != memcmp (cached_configuration, &configuration, sizeof (configuration))) {
1512 usbi_dbg ("darwin/reset_device: device requires reenumeration");
1513 (void) (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
1514 return LIBUSB_ERROR_NOT_FOUND;
1517 usbi_dbg ("darwin/reset_device: device reset complete");
1519 return LIBUSB_SUCCESS;
1522 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1523 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1524 io_service_t usbInterface;
1528 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1530 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1532 return darwin_to_libusb (kresult);
1535 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1536 IOObjectRelease (usbInterface);
1548 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1549 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1552 return LIBUSB_ERROR_NOT_SUPPORTED;
1555 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1558 return LIBUSB_ERROR_NOT_SUPPORTED;
1561 static void darwin_destroy_device(struct libusb_device *dev) {
1562 struct darwin_device_priv *dpriv = (struct darwin_device_priv *) dev->os_priv;
1565 /* need to hold the lock in case this is the last reference to the device */
1566 usbi_mutex_lock(&darwin_cached_devices_lock);
1567 darwin_deref_cached_device (dpriv->dev);
1569 usbi_mutex_unlock(&darwin_cached_devices_lock);
1573 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1574 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1577 uint8_t transferType;
1578 /* None of the values below are used in libusbx for bulk transfers */
1579 uint8_t direction, number, interval, pipeRef;
1580 uint16_t maxPacketSize;
1582 struct darwin_interface *cInterface;
1584 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1585 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1587 return LIBUSB_ERROR_NOT_FOUND;
1590 ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1591 &transferType, &maxPacketSize, &interval);
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);
1596 return darwin_to_libusb (ret);
1599 if (0 != (transfer->length % maxPacketSize)) {
1600 /* do not need a zero packet */
1601 transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1604 /* submit the request */
1605 /* timeouts are unavailable on interrupt endpoints */
1606 if (transferType == kUSBInterrupt) {
1607 if (IS_XFERIN(transfer))
1608 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1609 transfer->length, darwin_async_io_callback, itransfer);
1611 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1612 transfer->length, darwin_async_io_callback, itransfer);
1614 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1616 if (IS_XFERIN(transfer))
1617 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1618 transfer->length, transfer->timeout, transfer->timeout,
1619 darwin_async_io_callback, (void *)itransfer);
1621 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1622 transfer->length, transfer->timeout, transfer->timeout,
1623 darwin_async_io_callback, (void *)itransfer);
1627 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1628 darwin_error_str(ret), ret);
1630 return darwin_to_libusb (ret);
1633 #if InterfaceVersion >= 550
1634 static int submit_stream_transfer(struct usbi_transfer *itransfer) {
1635 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1636 struct darwin_interface *cInterface;
1640 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1641 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1643 return LIBUSB_ERROR_NOT_FOUND;
1646 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1648 if (IS_XFERIN(transfer))
1649 ret = (*(cInterface->interface))->ReadStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1650 transfer->buffer, transfer->length, transfer->timeout,
1651 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1653 ret = (*(cInterface->interface))->WriteStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1654 transfer->buffer, transfer->length, transfer->timeout,
1655 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1658 usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1659 darwin_error_str(ret), ret);
1661 return darwin_to_libusb (ret);
1665 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1666 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1667 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1670 uint8_t direction, number, interval, pipeRef, transferType;
1671 uint16_t maxPacketSize;
1673 AbsoluteTime atTime;
1676 struct darwin_interface *cInterface;
1678 /* construct an array of IOUSBIsocFrames, reuse the old one if the sizes are the same */
1679 if (tpriv->num_iso_packets != transfer->num_iso_packets) {
1680 free(tpriv->isoc_framelist);
1681 tpriv->isoc_framelist = NULL;
1684 if (!tpriv->isoc_framelist) {
1685 tpriv->num_iso_packets = transfer->num_iso_packets;
1686 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1687 if (!tpriv->isoc_framelist)
1688 return LIBUSB_ERROR_NO_MEM;
1691 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1692 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1693 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1695 /* determine the interface/endpoint to use */
1696 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1697 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1699 return LIBUSB_ERROR_NOT_FOUND;
1702 /* determine the properties of this endpoint and the speed of the device */
1703 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1704 &transferType, &maxPacketSize, &interval);
1706 /* Last but not least we need the bus frame number */
1707 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1709 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1710 free(tpriv->isoc_framelist);
1711 tpriv->isoc_framelist = NULL;
1713 return darwin_to_libusb (kresult);
1716 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1717 &transferType, &maxPacketSize, &interval);
1719 /* schedule for a frame a little in the future */
1722 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1723 frame = cInterface->frames[transfer->endpoint];
1725 /* submit the request */
1726 if (IS_XFERIN(transfer))
1727 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1728 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1731 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1732 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1735 if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
1737 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1));
1739 /* High/super speed */
1740 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1)) / 8;
1742 if (kresult != kIOReturnSuccess) {
1743 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1744 darwin_error_str(kresult));
1745 free (tpriv->isoc_framelist);
1746 tpriv->isoc_framelist = NULL;
1749 return darwin_to_libusb (kresult);
1752 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1753 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1754 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1755 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1756 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1760 memset(&tpriv->req, 0, sizeof(tpriv->req));
1762 /* IOUSBDeviceInterface expects the request in cpu endianness */
1763 tpriv->req.bmRequestType = setup->bmRequestType;
1764 tpriv->req.bRequest = setup->bRequest;
1765 /* these values should be in bus order from libusb_fill_control_setup */
1766 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1767 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1768 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1769 /* data is stored after the libusb control block */
1770 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1771 tpriv->req.completionTimeout = transfer->timeout;
1772 tpriv->req.noDataTimeout = transfer->timeout;
1774 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1776 /* all transfers in libusb-1.0 are async */
1778 if (transfer->endpoint) {
1779 struct darwin_interface *cInterface;
1782 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1783 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1785 return LIBUSB_ERROR_NOT_FOUND;
1788 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1790 /* control request on endpoint 0 */
1791 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1793 if (kresult != kIOReturnSuccess)
1794 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1796 return darwin_to_libusb (kresult);
1799 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1800 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1802 switch (transfer->type) {
1803 case LIBUSB_TRANSFER_TYPE_CONTROL:
1804 return submit_control_transfer(itransfer);
1805 case LIBUSB_TRANSFER_TYPE_BULK:
1806 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1807 return submit_bulk_transfer(itransfer);
1808 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1809 return submit_iso_transfer(itransfer);
1810 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1811 #if InterfaceVersion >= 550
1812 return submit_stream_transfer(itransfer);
1814 usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers");
1815 return LIBUSB_ERROR_NOT_SUPPORTED;
1818 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1819 return LIBUSB_ERROR_INVALID_PARAM;
1823 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1824 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1825 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1828 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
1831 return LIBUSB_ERROR_NO_DEVICE;
1833 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1835 return darwin_to_libusb (kresult);
1838 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1839 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1840 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1841 struct darwin_interface *cInterface;
1842 uint8_t pipeRef, iface;
1845 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) {
1846 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1848 return LIBUSB_ERROR_NOT_FOUND;
1852 return LIBUSB_ERROR_NO_DEVICE;
1854 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
1856 /* abort transactions */
1857 #if InterfaceVersion >= 550
1858 if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type)
1859 (*(cInterface->interface))->AbortStreamsPipe (cInterface->interface, pipeRef, itransfer->stream_id);
1862 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1864 usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
1866 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1867 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1869 return darwin_to_libusb (kresult);
1872 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1873 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1875 switch (transfer->type) {
1876 case LIBUSB_TRANSFER_TYPE_CONTROL:
1877 return cancel_control_transfer(itransfer);
1878 case LIBUSB_TRANSFER_TYPE_BULK:
1879 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1880 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1881 return darwin_abort_transfers (itransfer);
1883 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1884 return LIBUSB_ERROR_INVALID_PARAM;
1888 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1889 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1890 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1892 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1893 free (tpriv->isoc_framelist);
1894 tpriv->isoc_framelist = NULL;
1898 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1899 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1900 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1901 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1903 usbi_dbg ("an async io operation has completed");
1905 /* if requested write a zero packet */
1906 if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
1907 struct darwin_interface *cInterface;
1910 (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface);
1912 (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
1915 tpriv->result = result;
1916 tpriv->size = (UInt32) (uintptr_t) arg0;
1918 /* signal the core that this transfer is complete */
1919 usbi_signal_transfer_completion(itransfer);
1922 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1923 if (itransfer->timeout_flags & USBI_TRANSFER_TIMED_OUT)
1924 result = kIOUSBTransactionTimeout;
1927 case kIOReturnUnderrun:
1928 case kIOReturnSuccess:
1929 return LIBUSB_TRANSFER_COMPLETED;
1930 case kIOReturnAborted:
1931 return LIBUSB_TRANSFER_CANCELLED;
1932 case kIOUSBPipeStalled:
1933 usbi_dbg ("transfer error: pipe is stalled");
1934 return LIBUSB_TRANSFER_STALL;
1935 case kIOReturnOverrun:
1936 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1937 return LIBUSB_TRANSFER_OVERFLOW;
1938 case kIOUSBTransactionTimeout:
1939 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1940 itransfer->timeout_flags |= USBI_TRANSFER_TIMED_OUT;
1941 return LIBUSB_TRANSFER_TIMED_OUT;
1943 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1944 return LIBUSB_TRANSFER_ERROR;
1948 static int darwin_handle_transfer_completion (struct usbi_transfer *itransfer) {
1949 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1950 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1951 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1952 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1953 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1954 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1957 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1958 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1959 return LIBUSB_ERROR_INVALID_PARAM;
1962 usbi_dbg ("handling %s completion with kernel status %d",
1963 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", tpriv->result);
1965 if (kIOReturnSuccess == tpriv->result || kIOReturnUnderrun == tpriv->result) {
1966 if (isIsoc && tpriv->isoc_framelist) {
1967 /* copy isochronous results back */
1969 for (i = 0; i < transfer->num_iso_packets ; i++) {
1970 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1971 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1972 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1975 itransfer->transferred += tpriv->size;
1978 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1979 return usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, tpriv->result));
1982 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1983 #if !OSX_USE_CLOCK_GETTIME
1984 mach_timespec_t sys_time;
1985 clock_serv_t clock_ref;
1988 case USBI_CLOCK_REALTIME:
1989 /* CLOCK_REALTIME represents time since the epoch */
1990 clock_ref = clock_realtime;
1992 case USBI_CLOCK_MONOTONIC:
1993 /* use system boot time as reference for the monotonic clock */
1994 clock_ref = clock_monotonic;
1997 return LIBUSB_ERROR_INVALID_PARAM;
2000 clock_get_time (clock_ref, &sys_time);
2002 tp->tv_sec = sys_time.tv_sec;
2003 tp->tv_nsec = sys_time.tv_nsec;
2008 case USBI_CLOCK_MONOTONIC:
2009 return clock_gettime(CLOCK_MONOTONIC, tp);
2010 case USBI_CLOCK_REALTIME:
2011 return clock_gettime(CLOCK_REALTIME, tp);
2013 return LIBUSB_ERROR_INVALID_PARAM;
2018 #if InterfaceVersion >= 550
2019 static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints,
2020 int num_endpoints) {
2021 struct darwin_interface *cInterface;
2022 UInt32 supportsStreams;
2026 /* find the mimimum number of supported streams on the endpoint list */
2027 for (i = 0 ; i < num_endpoints ; ++i) {
2028 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) {
2032 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2033 if (num_streams > supportsStreams)
2034 num_streams = supportsStreams;
2037 /* it is an error if any endpoint in endpoints does not support streams */
2038 if (0 == num_streams)
2039 return LIBUSB_ERROR_INVALID_PARAM;
2041 /* create the streams */
2042 for (i = 0 ; i < num_endpoints ; ++i) {
2043 (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
2045 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, num_streams);
2046 if (kIOReturnSuccess != rc)
2047 return darwin_to_libusb(rc);
2053 static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) {
2054 struct darwin_interface *cInterface;
2055 UInt32 supportsStreams;
2059 for (int i = 0 ; i < num_endpoints ; ++i) {
2060 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface)))
2063 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2064 if (0 == supportsStreams)
2065 return LIBUSB_ERROR_INVALID_PARAM;
2067 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, 0);
2068 if (kIOReturnSuccess != rc)
2069 return darwin_to_libusb(rc);
2072 return LIBUSB_SUCCESS;
2076 const struct usbi_os_backend usbi_backend = {
2079 .init = darwin_init,
2080 .exit = darwin_exit,
2081 .get_device_list = NULL, /* not needed */
2082 .get_device_descriptor = darwin_get_device_descriptor,
2083 .get_active_config_descriptor = darwin_get_active_config_descriptor,
2084 .get_config_descriptor = darwin_get_config_descriptor,
2085 .hotplug_poll = darwin_hotplug_poll,
2087 .open = darwin_open,
2088 .close = darwin_close,
2089 .get_configuration = darwin_get_configuration,
2090 .set_configuration = darwin_set_configuration,
2091 .claim_interface = darwin_claim_interface,
2092 .release_interface = darwin_release_interface,
2094 .set_interface_altsetting = darwin_set_interface_altsetting,
2095 .clear_halt = darwin_clear_halt,
2096 .reset_device = darwin_reset_device,
2098 #if InterfaceVersion >= 550
2099 .alloc_streams = darwin_alloc_streams,
2100 .free_streams = darwin_free_streams,
2103 .kernel_driver_active = darwin_kernel_driver_active,
2104 .detach_kernel_driver = darwin_detach_kernel_driver,
2105 .attach_kernel_driver = darwin_attach_kernel_driver,
2107 .destroy_device = darwin_destroy_device,
2109 .submit_transfer = darwin_submit_transfer,
2110 .cancel_transfer = darwin_cancel_transfer,
2111 .clear_transfer_priv = darwin_clear_transfer_priv,
2113 .handle_transfer_completion = darwin_handle_transfer_completion,
2115 .clock_gettime = darwin_clock_gettime,
2117 .device_priv_size = sizeof(struct darwin_device_priv),
2118 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
2119 .transfer_priv_size = sizeof(struct darwin_transfer_priv),