1 /* -*- Mode: C; indent-tabs-mode:nil -*- */
3 * darwin backend for libusb 1.0
4 * Copyright © 2008-2013 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
28 #include <sys/types.h>
31 #include <libkern/OSAtomic.h>
33 #include <mach/clock.h>
34 #include <mach/clock_types.h>
35 #include <mach/mach_host.h>
36 #include <mach/mach_port.h>
38 #include <AvailabilityMacros.h>
39 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
40 #include <objc/objc-auto.h>
43 #include "darwin_usb.h"
45 /* async event thread */
46 static pthread_mutex_t libusb_darwin_at_mutex = PTHREAD_MUTEX_INITIALIZER;
47 static pthread_cond_t libusb_darwin_at_cond = PTHREAD_COND_INITIALIZER;
49 static clock_serv_t clock_realtime;
50 static clock_serv_t clock_monotonic;
52 static CFRunLoopRef libusb_darwin_acfl = NULL; /* event cf loop */
53 static volatile int32_t initCount = 0;
55 static usbi_mutex_t darwin_cached_devices_lock = PTHREAD_MUTEX_INITIALIZER;
56 static struct list_head darwin_cached_devices = {&darwin_cached_devices, &darwin_cached_devices};
58 #define DARWIN_CACHED_DEVICE(a) ((struct darwin_cached_device *) (((struct darwin_device_priv *)((a)->os_priv))->dev))
60 /* async event thread */
61 static pthread_t libusb_darwin_at;
63 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
64 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
65 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
66 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
67 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
69 static int darwin_scan_devices(struct libusb_context *ctx);
70 static int process_new_device (struct libusb_context *ctx, io_service_t service);
72 #if defined(ENABLE_LOGGING)
73 static const char *darwin_error_str (int result) {
74 static char string_buffer[50];
76 case kIOReturnSuccess:
78 case kIOReturnNotOpen:
79 return "device not opened for exclusive access";
80 case kIOReturnNoDevice:
81 return "no connection to an IOService";
82 case kIOUSBNoAsyncPortErr:
83 return "no async port has been opened for interface";
84 case kIOReturnExclusiveAccess:
85 return "another process has device opened for exclusive access";
86 case kIOUSBPipeStalled:
87 return "pipe is stalled";
89 return "could not establish a connection to the Darwin kernel";
90 case kIOUSBTransactionTimeout:
91 return "transaction timed out";
92 case kIOReturnBadArgument:
93 return "invalid argument";
94 case kIOReturnAborted:
95 return "transaction aborted";
96 case kIOReturnNotResponding:
97 return "device not responding";
98 case kIOReturnOverrun:
99 return "data overrun";
100 case kIOReturnCannotWire:
101 return "physical memory can not be wired down";
102 case kIOReturnNoResources:
103 return "out of resources";
104 case kIOUSBHighSpeedSplitError:
105 return "high speed split error";
107 snprintf(string_buffer, sizeof(string_buffer), "unknown error (0x%x)", result);
108 return string_buffer;
113 static int darwin_to_libusb (int result) {
115 case kIOReturnUnderrun:
116 case kIOReturnSuccess:
117 return LIBUSB_SUCCESS;
118 case kIOReturnNotOpen:
119 case kIOReturnNoDevice:
120 return LIBUSB_ERROR_NO_DEVICE;
121 case kIOReturnExclusiveAccess:
122 return LIBUSB_ERROR_ACCESS;
123 case kIOUSBPipeStalled:
124 return LIBUSB_ERROR_PIPE;
125 case kIOReturnBadArgument:
126 return LIBUSB_ERROR_INVALID_PARAM;
127 case kIOUSBTransactionTimeout:
128 return LIBUSB_ERROR_TIMEOUT;
129 case kIOReturnNotResponding:
130 case kIOReturnAborted:
132 case kIOUSBNoAsyncPortErr:
134 return LIBUSB_ERROR_OTHER;
138 /* this function must be called with the darwin_cached_devices_lock held */
139 static void darwin_deref_cached_device(struct darwin_cached_device *cached_dev) {
140 cached_dev->refcount--;
141 /* free the device and remove it from the cache */
142 if (0 == cached_dev->refcount) {
143 list_del(&cached_dev->list);
145 (*(cached_dev->device))->Release(cached_dev->device);
150 static void darwin_ref_cached_device(struct darwin_cached_device *cached_dev) {
151 cached_dev->refcount++;
154 static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp) {
155 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
157 /* current interface */
158 struct darwin_interface *cInterface;
162 usbi_dbg ("converting ep address 0x%02x to pipeRef and interface", ep);
164 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
165 cInterface = &priv->interfaces[iface];
167 if (dev_handle->claimed_interfaces & (1 << iface)) {
168 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
169 if (cInterface->endpoint_addrs[i] == ep) {
172 usbi_dbg ("pipe %d on interface %d matches", *pipep, *ifcp);
179 /* No pipe found with the correct endpoint address */
180 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
185 static int usb_setup_device_iterator (io_iterator_t *deviceIterator, UInt32 location) {
186 CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBDeviceClassName);
189 return kIOReturnError;
192 CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
193 &kCFTypeDictionaryKeyCallBacks,
194 &kCFTypeDictionaryValueCallBacks);
196 if (propertyMatchDict) {
197 /* there are no unsigned CFNumber types so treat the value as signed. the os seems to do this
198 internally (CFNumberType of locationID is 3) */
199 CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberSInt32Type, &location);
201 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
202 /* release our reference to the CFNumber (CFDictionarySetValue retains it) */
203 CFRelease (locationCF);
205 CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
206 /* release out reference to the CFMutableDictionaryRef (CFDictionarySetValue retains it) */
207 CFRelease (propertyMatchDict);
209 /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
212 return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator);
215 /* Returns 1 on success, 0 on failure. */
216 static int get_ioregistry_value_number (io_service_t service, CFStringRef property, CFNumberType type, void *p) {
217 CFTypeRef cfNumber = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
221 if (CFGetTypeID(cfNumber) == CFNumberGetTypeID()) {
222 ret = CFNumberGetValue(cfNumber, type, p);
225 CFRelease (cfNumber);
231 static usb_device_t **darwin_device_from_service (io_service_t service)
233 io_cf_plugin_ref_t *plugInInterface = NULL;
234 usb_device_t **device;
235 kern_return_t result;
238 result = IOCreatePlugInInterfaceForService(service, kIOUSBDeviceUserClientTypeID,
239 kIOCFPlugInInterfaceID, &plugInInterface,
242 if (kIOReturnSuccess != result || !plugInInterface) {
243 usbi_dbg ("could not set up plugin for service: %s\n", darwin_error_str (result));
247 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
249 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
250 (*plugInInterface)->Release (plugInInterface);
255 static void darwin_devices_attached (void *ptr, io_iterator_t add_devices) {
256 struct libusb_context *ctx;
257 io_service_t service;
259 usbi_mutex_lock(&active_contexts_lock);
261 while ((service = IOIteratorNext(add_devices))) {
262 /* add this device to each active context's device list */
263 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
264 process_new_device (ctx, service);;
267 IOObjectRelease(service);
270 usbi_mutex_unlock(&active_contexts_lock);
273 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
274 struct libusb_device *dev = NULL;
275 struct libusb_context *ctx;
281 while ((device = IOIteratorNext (rem_devices)) != 0) {
282 /* get the location from the i/o registry */
283 ret = get_ioregistry_value_number (device, CFSTR("sessionID"), kCFNumberSInt64Type, &session);
284 IOObjectRelease (device);
288 usbi_mutex_lock(&active_contexts_lock);
290 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
291 usbi_dbg ("notifying context %p of device disconnect", ctx);
293 dev = usbi_get_device_by_session_id(ctx, (unsigned long) session);
295 /* signal the core that this device has been disconnected. the core will tear down this device
296 when the reference count reaches 0 */
297 usbi_disconnect_device(dev);
298 libusb_unref_device(dev);
302 usbi_mutex_unlock(&active_contexts_lock);
306 static void darwin_clear_iterator (io_iterator_t iter) {
309 while ((device = IOIteratorNext (iter)) != 0)
310 IOObjectRelease (device);
313 static void *darwin_event_thread_main (void *arg0) {
315 struct libusb_context *ctx = (struct libusb_context *)arg0;
316 CFRunLoopRef runloop;
318 /* Set this thread's name, so it can be seen in the debugger
319 and crash reports. */
320 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
321 pthread_setname_np ("org.libusb.device-hotplug");
323 /* Tell the Objective-C garbage collector about this thread.
324 This is required because, unlike NSThreads, pthreads are
325 not automatically registered. Although we don't use
326 Objective-C, we use CoreFoundation, which does. */
327 objc_registerThreadWithCollector();
330 /* hotplug (device arrival/removal) sources */
331 CFRunLoopSourceRef libusb_notification_cfsource;
332 io_notification_port_t libusb_notification_port;
333 io_iterator_t libusb_rem_device_iterator;
334 io_iterator_t libusb_add_device_iterator;
336 usbi_dbg ("creating hotplug event source");
338 runloop = CFRunLoopGetCurrent ();
341 /* add the notification port to the run loop */
342 libusb_notification_port = IONotificationPortCreate (kIOMasterPortDefault);
343 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
344 CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
346 /* create notifications for removed devices */
347 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
348 IOServiceMatching(kIOUSBDeviceClassName),
349 darwin_devices_detached,
350 ctx, &libusb_rem_device_iterator);
352 if (kresult != kIOReturnSuccess) {
353 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
358 /* create notifications for attached devices */
359 kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
360 IOServiceMatching(kIOUSBDeviceClassName),
361 darwin_devices_attached,
362 ctx, &libusb_add_device_iterator);
364 if (kresult != kIOReturnSuccess) {
365 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
371 darwin_clear_iterator (libusb_rem_device_iterator);
372 darwin_clear_iterator (libusb_add_device_iterator);
374 usbi_dbg ("darwin event thread ready to receive events");
376 /* signal the main thread that the hotplug runloop has been created. */
377 pthread_mutex_lock (&libusb_darwin_at_mutex);
378 libusb_darwin_acfl = runloop;
379 pthread_cond_signal (&libusb_darwin_at_cond);
380 pthread_mutex_unlock (&libusb_darwin_at_mutex);
382 /* run the runloop */
385 usbi_dbg ("darwin event thread exiting");
387 /* remove the notification cfsource */
388 CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
390 /* delete notification port */
391 IONotificationPortDestroy (libusb_notification_port);
393 /* delete iterators */
394 IOObjectRelease (libusb_rem_device_iterator);
395 IOObjectRelease (libusb_add_device_iterator);
399 libusb_darwin_acfl = NULL;
404 /* cleanup function to destroy cached devices */
405 static void __attribute__((destructor)) _darwin_finalize(void) {
406 struct darwin_cached_device *dev, *next;
408 usbi_mutex_lock(&darwin_cached_devices_lock);
409 list_for_each_entry_safe(dev, next, &darwin_cached_devices, list, struct darwin_cached_device) {
410 darwin_deref_cached_device(dev);
412 usbi_mutex_unlock(&darwin_cached_devices_lock);
415 static int darwin_init(struct libusb_context *ctx) {
416 host_name_port_t host_self;
419 rc = darwin_scan_devices (ctx);
420 if (LIBUSB_SUCCESS != rc) {
424 if (OSAtomicIncrement32Barrier(&initCount) == 1) {
425 /* create the clocks that will be used */
427 host_self = mach_host_self();
428 host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
429 host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
430 mach_port_deallocate(mach_task_self(), host_self);
432 pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, ctx);
434 pthread_mutex_lock (&libusb_darwin_at_mutex);
435 while (!libusb_darwin_acfl)
436 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
437 pthread_mutex_unlock (&libusb_darwin_at_mutex);
443 static void darwin_exit (void) {
444 if (OSAtomicDecrement32Barrier(&initCount) == 0) {
445 mach_port_deallocate(mach_task_self(), clock_realtime);
446 mach_port_deallocate(mach_task_self(), clock_monotonic);
448 /* stop the event runloop and wait for the thread to terminate. */
449 CFRunLoopStop (libusb_darwin_acfl);
450 pthread_join (libusb_darwin_at, NULL);
454 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
455 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
457 /* return cached copy */
458 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
465 static int get_configuration_index (struct libusb_device *dev, int config_value) {
466 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
468 IOUSBConfigurationDescriptorPtr desc;
471 /* is there a simpler way to determine the index? */
472 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
473 if (kresult != kIOReturnSuccess)
474 return darwin_to_libusb (kresult);
476 for (i = 0 ; i < numConfig ; i++) {
477 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
479 if (desc->bConfigurationValue == config_value)
483 /* configuration not found */
484 return LIBUSB_ERROR_NOT_FOUND;
487 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
488 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
491 if (0 == priv->active_config)
492 return LIBUSB_ERROR_NOT_FOUND;
494 config_index = get_configuration_index (dev, priv->active_config);
495 if (config_index < 0)
498 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
501 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
502 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
503 IOUSBConfigurationDescriptorPtr desc;
507 if (!priv || !priv->device)
508 return LIBUSB_ERROR_OTHER;
510 kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
511 if (kresult == kIOReturnSuccess) {
512 /* copy descriptor */
513 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
514 len = libusb_le16_to_cpu(desc->wTotalLength);
516 memmove (buffer, desc, len);
518 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
522 ret = darwin_to_libusb (kresult);
523 if (ret != LIBUSB_SUCCESS)
529 /* check whether the os has configured the device */
530 static int darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) {
531 usb_device_t **darwin_device = dev->device;
533 IOUSBConfigurationDescriptorPtr configDesc;
534 IOUSBFindInterfaceRequest request;
535 kern_return_t kresult;
536 io_iterator_t interface_iterator;
537 io_service_t firstInterface;
539 if (dev->dev_descriptor.bNumConfigurations < 1) {
540 usbi_err (ctx, "device has no configurations");
541 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
544 /* find the first configuration */
545 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
546 dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
548 /* check if the device is already configured. there is probably a better way than iterating over the
549 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
550 might lock up on the device request) */
552 /* Setup the Interface Request */
553 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
554 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
555 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
556 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
558 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
560 return darwin_to_libusb (kresult);
563 firstInterface = IOIteratorNext(interface_iterator);
565 /* done with the interface iterator */
566 IOObjectRelease(interface_iterator);
568 if (firstInterface) {
569 IOObjectRelease (firstInterface);
571 /* device is configured */
572 if (dev->dev_descriptor.bNumConfigurations == 1)
573 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
574 dev->active_config = dev->first_config;
576 /* devices with more than one configuration should work with GetConfiguration */
577 (*darwin_device)->GetConfiguration (darwin_device, &dev->active_config);
580 dev->active_config = 0;
582 usbi_dbg ("active config: %u, first config: %u", dev->active_config, dev->first_config);
587 static int darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
588 IOUSBDevRequestTO req;
590 memset (buffer, 0, buffer_size);
592 /* Set up request for descriptor/ */
593 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
594 req.bRequest = kUSBRqGetDescriptor;
595 req.wValue = desc << 8;
596 req.wIndex = desc_index;
597 req.wLength = buffer_size;
599 req.noDataTimeout = 20;
600 req.completionTimeout = 100;
602 return (*device)->DeviceRequestTO (device, &req);
605 static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct darwin_cached_device *dev) {
606 usb_device_t **device = dev->device;
607 int retries = 1, delay = 30000;
608 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
612 UInt16 idProduct, idVendor;
614 dev->can_enumerate = 0;
616 (*device)->GetDeviceClass (device, &bDeviceClass);
617 (*device)->GetDeviceProduct (device, &idProduct);
618 (*device)->GetDeviceVendor (device, &idVendor);
620 /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
621 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
622 * to follow the spec as closely as possible, try opening the device */
623 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
626 /**** retrieve device descriptor ****/
627 ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &dev->dev_descriptor, sizeof(dev->dev_descriptor));
629 if (kIOReturnOverrun == ret && kUSBDeviceDesc == dev->dev_descriptor.bDescriptorType)
630 /* received an overrun error but we still received a device descriptor */
631 ret = kIOReturnSuccess;
633 if (kIOUSBVendorIDAppleComputer == idVendor) {
634 /* NTH: don't bother retrying or unsuspending Apple devices */
638 if (kIOReturnSuccess == ret && (0 == dev->dev_descriptor.bNumConfigurations ||
639 0 == dev->dev_descriptor.bcdUSB)) {
640 /* work around for incorrectly configured devices */
641 if (try_reconfigure && is_open) {
642 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
644 /* set the first configuration */
645 (*device)->SetConfiguration(device, 1);
647 /* don't try to reconfigure again */
651 ret = kIOUSBPipeStalled;
654 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
655 /* device may be suspended. unsuspend it and try again */
656 #if DeviceVersion >= 320
659 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
660 (void)(*device)->GetUSBDeviceInformation (device, &info);
662 /* note that the device was suspended */
663 if (info & (1 << kUSBInformationDeviceIsSuspendedBit) || 0 == info)
668 /* try to unsuspend the device */
669 ret2 = (*device)->USBDeviceSuspend (device, 0);
670 if (kIOReturnSuccess != ret2) {
671 /* prevent log spew from poorly behaving devices. this indicates the
672 os actually had trouble communicating with the device */
673 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
681 if (kIOReturnSuccess != ret) {
682 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
683 /* sleep for a little while before trying again */
686 } while (kIOReturnSuccess != ret && retries--);
689 /* resuspend the device */
690 (void)(*device)->USBDeviceSuspend (device, 1);
693 (void) (*device)->USBDeviceClose (device);
695 if (ret != kIOReturnSuccess) {
696 /* a debug message was already printed out for this error */
697 if (LIBUSB_CLASS_HUB == bDeviceClass)
698 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
699 idVendor, idProduct, darwin_error_str (ret), ret);
701 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
702 idVendor, idProduct, darwin_error_str (ret), ret);
703 return darwin_to_libusb (ret);
706 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
707 if (libusb_le16_to_cpu (dev->dev_descriptor.idProduct) != idProduct) {
708 /* not a valid device */
709 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
710 idProduct, libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
711 return LIBUSB_ERROR_NO_DEVICE;
714 usbi_dbg ("cached device descriptor:");
715 usbi_dbg (" bDescriptorType: 0x%02x", dev->dev_descriptor.bDescriptorType);
716 usbi_dbg (" bcdUSB: 0x%04x", dev->dev_descriptor.bcdUSB);
717 usbi_dbg (" bDeviceClass: 0x%02x", dev->dev_descriptor.bDeviceClass);
718 usbi_dbg (" bDeviceSubClass: 0x%02x", dev->dev_descriptor.bDeviceSubClass);
719 usbi_dbg (" bDeviceProtocol: 0x%02x", dev->dev_descriptor.bDeviceProtocol);
720 usbi_dbg (" bMaxPacketSize0: 0x%02x", dev->dev_descriptor.bMaxPacketSize0);
721 usbi_dbg (" idVendor: 0x%04x", dev->dev_descriptor.idVendor);
722 usbi_dbg (" idProduct: 0x%04x", dev->dev_descriptor.idProduct);
723 usbi_dbg (" bcdDevice: 0x%04x", dev->dev_descriptor.bcdDevice);
724 usbi_dbg (" iManufacturer: 0x%02x", dev->dev_descriptor.iManufacturer);
725 usbi_dbg (" iProduct: 0x%02x", dev->dev_descriptor.iProduct);
726 usbi_dbg (" iSerialNumber: 0x%02x", dev->dev_descriptor.iSerialNumber);
727 usbi_dbg (" bNumConfigurations: 0x%02x", dev->dev_descriptor.bNumConfigurations);
729 dev->can_enumerate = 1;
731 return LIBUSB_SUCCESS;
734 static int darwin_get_cached_device(struct libusb_context *ctx, io_service_t service,
735 struct darwin_cached_device **cached_out) {
736 struct darwin_cached_device *new_device;
737 UInt64 sessionID = 0, parent_sessionID = 0;
738 int ret = LIBUSB_SUCCESS;
739 usb_device_t **device;
741 kern_return_t result;
744 /* get some info from the io registry */
745 (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
746 (void) get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, &port);
748 usbi_dbg("finding cached device for sessionID 0x%" PRIx64, sessionID);
750 result = IORegistryEntryGetParentEntry (service, kIOUSBPlane, &parent);
752 if (kIOReturnSuccess == result) {
753 (void) get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, &parent_sessionID);
754 IOObjectRelease(parent);
757 usbi_mutex_lock(&darwin_cached_devices_lock);
761 list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) {
762 usbi_dbg("matching sessionID 0x%" PRIx64 " against cached device with sessionID 0x%" PRIx64, sessionID, new_device->session);
763 if (new_device->session == sessionID) {
764 usbi_dbg("using cached device for device");
765 *cached_out = new_device;
773 usbi_dbg("caching new device with sessionID 0x%" PRIx64, sessionID);
775 device = darwin_device_from_service (service);
777 ret = LIBUSB_ERROR_NO_DEVICE;
781 new_device = calloc (1, sizeof (*new_device));
783 ret = LIBUSB_ERROR_NO_MEM;
787 /* add this device to the cached device list */
788 list_add(&new_device->list, &darwin_cached_devices);
790 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
792 /* keep a reference to this device */
793 darwin_ref_cached_device(new_device);
795 new_device->device = device;
796 new_device->session = sessionID;
797 (*device)->GetLocationID (device, &new_device->location);
798 new_device->port = port;
799 new_device->parent_session = parent_sessionID;
801 /* cache the device descriptor */
802 ret = darwin_cache_device_descriptor(ctx, new_device);
806 if (new_device->can_enumerate) {
807 snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address,
808 new_device->dev_descriptor.idVendor, new_device->dev_descriptor.idProduct,
809 new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass);
813 usbi_mutex_unlock(&darwin_cached_devices_lock);
815 /* keep track of devices regardless of if we successfully enumerate them to
816 prevent them from being enumerated multiple times */
818 *cached_out = new_device;
823 static int process_new_device (struct libusb_context *ctx, io_service_t service) {
824 struct darwin_device_priv *priv;
825 struct libusb_device *dev = NULL;
826 struct darwin_cached_device *cached_device;
831 ret = darwin_get_cached_device (ctx, service, &cached_device);
833 if (ret < 0 || !cached_device->can_enumerate) {
837 /* check current active configuration (and cache the first configuration value--
838 which may be used by claim_interface) */
839 ret = darwin_check_configuration (ctx, cached_device);
843 usbi_dbg ("allocating new device in context %p for with session 0x%" PRIx64,
844 ctx, cached_device->session);
846 dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
848 return LIBUSB_ERROR_NO_MEM;
851 priv = (struct darwin_device_priv *)dev->os_priv;
853 priv->dev = cached_device;
854 darwin_ref_cached_device (priv->dev);
856 if (cached_device->parent_session > 0) {
857 dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session);
859 dev->parent_dev = NULL;
861 dev->port_number = cached_device->port;
862 dev->bus_number = cached_device->location >> 24;
863 dev->device_address = cached_device->address;
865 (*(priv->dev->device))->GetDeviceSpeed (priv->dev->device, &devSpeed);
868 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
869 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
870 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
871 #if DeviceVersion >= 500
872 case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
875 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
878 ret = usbi_sanitize_device (dev);
882 usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
883 dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
887 usbi_connect_device (dev);
889 libusb_unref_device (dev);
895 static int darwin_scan_devices(struct libusb_context *ctx) {
896 io_iterator_t deviceIterator;
897 io_service_t service;
898 kern_return_t kresult;
900 kresult = usb_setup_device_iterator (&deviceIterator, 0);
901 if (kresult != kIOReturnSuccess)
902 return darwin_to_libusb (kresult);
904 while ((service = IOIteratorNext (deviceIterator))) {
905 (void) process_new_device (ctx, service);
907 IOObjectRelease(service);
910 IOObjectRelease(deviceIterator);
915 static int darwin_open (struct libusb_device_handle *dev_handle) {
916 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
917 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
920 if (0 == dpriv->open_count) {
921 /* try to open the device */
922 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
923 if (kresult != kIOReturnSuccess) {
924 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
926 if (kIOReturnExclusiveAccess != kresult) {
927 return darwin_to_libusb (kresult);
930 /* it is possible to perform some actions on a device that is not open so do not return an error */
936 /* create async event source */
937 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
938 if (kresult != kIOReturnSuccess) {
939 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
942 (*(dpriv->device))->USBDeviceClose (dpriv->device);
947 return darwin_to_libusb (kresult);
950 CFRetain (libusb_darwin_acfl);
952 /* add the cfSource to the aync run loop */
953 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
956 /* device opened successfully */
959 /* create a file descriptor for notifications */
962 /* set the pipe to be non-blocking */
963 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
965 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
967 usbi_dbg ("device open for access");
972 static void darwin_close (struct libusb_device_handle *dev_handle) {
973 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
974 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
978 if (dpriv->open_count == 0) {
979 /* something is probably very wrong if this is the case */
980 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
986 /* make sure all interfaces are released */
987 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
988 if (dev_handle->claimed_interfaces & (1 << i))
989 libusb_release_interface (dev_handle, i);
991 if (0 == dpriv->open_count) {
992 /* delete the device's async event source */
993 if (priv->cfSource) {
994 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
995 CFRelease (priv->cfSource);
996 priv->cfSource = NULL;
997 CFRelease (libusb_darwin_acfl);
1000 if (priv->is_open) {
1001 /* close the device */
1002 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
1004 /* Log the fact that we had a problem closing the file, however failing a
1005 * close isn't really an error, so return success anyway */
1006 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
1011 /* file descriptors are maintained per-instance */
1012 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
1013 close (priv->fds[1]);
1014 close (priv->fds[0]);
1016 priv->fds[0] = priv->fds[1] = -1;
1019 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
1020 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1022 *config = (int) dpriv->active_config;
1027 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
1028 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1032 /* Setting configuration will invalidate the interface, so we need
1033 to reclaim it. First, dispose of existing interfaces, if any. */
1034 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1035 if (dev_handle->claimed_interfaces & (1 << i))
1036 darwin_release_interface (dev_handle, i);
1038 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
1039 if (kresult != kIOReturnSuccess)
1040 return darwin_to_libusb (kresult);
1042 /* Reclaim any interfaces. */
1043 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1044 if (dev_handle->claimed_interfaces & (1 << i))
1045 darwin_claim_interface (dev_handle, i);
1047 dpriv->active_config = config;
1052 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
1053 IOUSBFindInterfaceRequest request;
1054 kern_return_t kresult;
1055 io_iterator_t interface_iterator;
1056 UInt8 bInterfaceNumber;
1059 *usbInterfacep = IO_OBJECT_NULL;
1061 /* Setup the Interface Request */
1062 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1063 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1064 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1065 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1067 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1071 while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1072 /* find the interface number */
1073 ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
1076 if (ret && bInterfaceNumber == ifc) {
1080 (void) IOObjectRelease (*usbInterfacep);
1083 /* done with the interface iterator */
1084 IOObjectRelease(interface_iterator);
1089 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
1090 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1092 /* current interface */
1093 struct darwin_interface *cInterface = &priv->interfaces[iface];
1095 kern_return_t kresult;
1097 u_int8_t numep, direction, number;
1098 u_int8_t dont_care1, dont_care3;
1099 u_int16_t dont_care2;
1102 usbi_dbg ("building table of endpoints.");
1104 /* retrieve the total number of endpoints on this interface */
1105 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1107 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1108 return darwin_to_libusb (kresult);
1111 /* iterate through pipe references */
1112 for (i = 1 ; i <= numep ; i++) {
1113 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1114 &dont_care2, &dont_care3);
1116 if (kresult != kIOReturnSuccess) {
1117 usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
1119 return darwin_to_libusb (kresult);
1122 usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
1124 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1127 cInterface->num_endpoints = numep;
1132 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1133 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1134 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1135 io_service_t usbInterface = IO_OBJECT_NULL;
1137 IOCFPlugInInterface **plugInInterface = NULL;
1140 /* current interface */
1141 struct darwin_interface *cInterface = &priv->interfaces[iface];
1143 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1144 if (kresult != kIOReturnSuccess)
1145 return darwin_to_libusb (kresult);
1147 /* make sure we have an interface */
1148 if (!usbInterface && dpriv->first_config != 0) {
1149 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1151 /* set the configuration */
1152 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1153 if (kresult != LIBUSB_SUCCESS) {
1154 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1158 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1160 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1161 return darwin_to_libusb (kresult);
1165 if (!usbInterface) {
1166 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1167 return LIBUSB_ERROR_NOT_FOUND;
1170 /* get an interface to the device's interface */
1171 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1172 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1174 /* ignore release error */
1175 (void)IOObjectRelease (usbInterface);
1178 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1179 return darwin_to_libusb (kresult);
1182 if (!plugInInterface) {
1183 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1184 return LIBUSB_ERROR_NOT_FOUND;
1187 /* Do the actual claim */
1188 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1189 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1190 (LPVOID)&cInterface->interface);
1191 /* We no longer need the intermediate plug-in */
1192 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1193 (*plugInInterface)->Release (plugInInterface);
1194 if (kresult || !cInterface->interface) {
1195 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1196 return darwin_to_libusb (kresult);
1199 /* claim the interface */
1200 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1202 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1203 return darwin_to_libusb (kresult);
1206 /* update list of endpoints */
1207 kresult = get_endpoints (dev_handle, iface);
1209 /* this should not happen */
1210 darwin_release_interface (dev_handle, iface);
1211 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1215 cInterface->cfSource = NULL;
1217 /* create async event source */
1218 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1219 if (kresult != kIOReturnSuccess) {
1220 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1222 /* can't continue without an async event source */
1223 (void)darwin_release_interface (dev_handle, iface);
1225 return darwin_to_libusb (kresult);
1228 /* add the cfSource to the async thread's run loop */
1229 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1231 usbi_dbg ("interface opened");
1236 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1237 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1240 /* current interface */
1241 struct darwin_interface *cInterface = &priv->interfaces[iface];
1243 /* Check to see if an interface is open */
1244 if (!cInterface->interface)
1245 return LIBUSB_SUCCESS;
1247 /* clean up endpoint data */
1248 cInterface->num_endpoints = 0;
1250 /* delete the interface's async event source */
1251 if (cInterface->cfSource) {
1252 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1253 CFRelease (cInterface->cfSource);
1256 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1258 usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1260 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1261 if (kresult != kIOReturnSuccess)
1262 usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1264 cInterface->interface = IO_OBJECT_NULL;
1266 return darwin_to_libusb (kresult);
1269 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1270 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1273 /* current interface */
1274 struct darwin_interface *cInterface = &priv->interfaces[iface];
1276 if (!cInterface->interface)
1277 return LIBUSB_ERROR_NO_DEVICE;
1279 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1280 if (kresult != kIOReturnSuccess)
1281 darwin_reset_device (dev_handle);
1283 /* update list of endpoints */
1284 kresult = get_endpoints (dev_handle, iface);
1286 /* this should not happen */
1287 darwin_release_interface (dev_handle, iface);
1288 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1292 return darwin_to_libusb (kresult);
1295 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1296 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1298 /* current interface */
1299 struct darwin_interface *cInterface;
1300 uint8_t pipeRef, iface;
1303 /* determine the interface/endpoint to use */
1304 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
1305 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1307 return LIBUSB_ERROR_NOT_FOUND;
1310 cInterface = &priv->interfaces[iface];
1312 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1313 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1315 usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1317 return darwin_to_libusb (kresult);
1320 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1321 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1322 IOUSBDeviceDescriptor descriptor;
1323 IOUSBConfigurationDescriptorPtr cached_configuration;
1324 IOUSBConfigurationDescriptor configuration;
1325 bool reenumerate = false;
1329 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1331 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1332 return darwin_to_libusb (kresult);
1336 usbi_dbg ("darwin/reset_device: checking if device descriptor changed");
1338 /* ignore return code. if we can't get a descriptor it might be worthwhile re-enumerating anway */
1339 (void) darwin_request_descriptor (dpriv->device, kUSBDeviceDesc, 0, &descriptor, sizeof (descriptor));
1341 /* check if the device descriptor has changed */
1342 if (0 != memcmp (&dpriv->dev_descriptor, &descriptor, sizeof (descriptor))) {
1347 /* check if any configuration descriptor has changed */
1348 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1349 usbi_dbg ("darwin/reset_device: checking if configuration descriptor %d changed", i);
1351 (void) darwin_request_descriptor (dpriv->device, kUSBConfDesc, i, &configuration, sizeof (configuration));
1352 (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1354 if (!cached_configuration || 0 != memcmp (cached_configuration, &configuration, sizeof (configuration))) {
1362 usbi_dbg ("darwin/reset_device: device requires reenumeration");
1363 (void) (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
1364 return LIBUSB_ERROR_NOT_FOUND;
1367 usbi_dbg ("darwin/reset_device: device reset complete");
1369 return LIBUSB_SUCCESS;
1372 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1373 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1374 io_service_t usbInterface;
1378 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1380 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1382 return darwin_to_libusb (kresult);
1385 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1386 IOObjectRelease (usbInterface);
1398 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1399 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1402 return LIBUSB_ERROR_NOT_SUPPORTED;
1405 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1408 return LIBUSB_ERROR_NOT_SUPPORTED;
1411 static void darwin_destroy_device(struct libusb_device *dev) {
1412 struct darwin_device_priv *dpriv = (struct darwin_device_priv *) dev->os_priv;
1415 /* need to hold the lock in case this is the last reference to the device */
1416 usbi_mutex_lock(&darwin_cached_devices_lock);
1417 darwin_deref_cached_device (dpriv->dev);
1419 usbi_mutex_unlock(&darwin_cached_devices_lock);
1423 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1424 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1425 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1428 uint8_t transferType;
1429 /* None of the values below are used in libusb for bulk transfers */
1430 uint8_t direction, number, interval, pipeRef, iface;
1431 uint16_t maxPacketSize;
1433 struct darwin_interface *cInterface;
1435 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1436 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1438 return LIBUSB_ERROR_NOT_FOUND;
1441 cInterface = &priv->interfaces[iface];
1443 ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1444 &transferType, &maxPacketSize, &interval);
1447 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1448 darwin_error_str(ret), ret);
1449 return darwin_to_libusb (ret);
1452 if (0 != (transfer->length % maxPacketSize)) {
1453 /* do not need a zero packet */
1454 transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1457 /* submit the request */
1458 /* timeouts are unavailable on interrupt endpoints */
1459 if (transferType == kUSBInterrupt) {
1460 if (IS_XFERIN(transfer))
1461 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1462 transfer->length, darwin_async_io_callback, itransfer);
1464 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1465 transfer->length, darwin_async_io_callback, itransfer);
1467 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1469 if (IS_XFERIN(transfer))
1470 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1471 transfer->length, transfer->timeout, transfer->timeout,
1472 darwin_async_io_callback, (void *)itransfer);
1474 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1475 transfer->length, transfer->timeout, transfer->timeout,
1476 darwin_async_io_callback, (void *)itransfer);
1480 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1481 darwin_error_str(ret), ret);
1483 return darwin_to_libusb (ret);
1486 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1487 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1488 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1489 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1492 uint8_t direction, number, interval, pipeRef, iface, transferType;
1493 uint16_t maxPacketSize;
1495 AbsoluteTime atTime;
1498 struct darwin_interface *cInterface;
1500 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1501 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1502 free(tpriv->isoc_framelist);
1503 tpriv->isoc_framelist = NULL;
1506 if (!tpriv->isoc_framelist) {
1507 tpriv->num_iso_packets = transfer->num_iso_packets;
1508 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1509 if (!tpriv->isoc_framelist)
1510 return LIBUSB_ERROR_NO_MEM;
1513 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1514 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1515 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1517 /* determine the interface/endpoint to use */
1518 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1519 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1521 return LIBUSB_ERROR_NOT_FOUND;
1524 cInterface = &priv->interfaces[iface];
1526 /* determine the properties of this endpoint and the speed of the device */
1527 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1528 &transferType, &maxPacketSize, &interval);
1530 /* Last but not least we need the bus frame number */
1531 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1533 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1534 free(tpriv->isoc_framelist);
1535 tpriv->isoc_framelist = NULL;
1537 return darwin_to_libusb (kresult);
1540 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1541 &transferType, &maxPacketSize, &interval);
1543 /* schedule for a frame a little in the future */
1546 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1547 frame = cInterface->frames[transfer->endpoint];
1549 /* submit the request */
1550 if (IS_XFERIN(transfer))
1551 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1552 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1555 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1556 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1559 if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
1561 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1));
1563 /* High/super speed */
1564 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1)) / 8;
1566 if (kresult != kIOReturnSuccess) {
1567 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1568 darwin_error_str(kresult));
1569 free (tpriv->isoc_framelist);
1570 tpriv->isoc_framelist = NULL;
1573 return darwin_to_libusb (kresult);
1576 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1577 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1578 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1579 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1580 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1581 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1585 bzero(&tpriv->req, sizeof(tpriv->req));
1587 /* IOUSBDeviceInterface expects the request in cpu endianess */
1588 tpriv->req.bmRequestType = setup->bmRequestType;
1589 tpriv->req.bRequest = setup->bRequest;
1590 /* these values should be in bus order from libusb_fill_control_setup */
1591 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1592 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1593 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1594 /* data is stored after the libusb control block */
1595 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1596 tpriv->req.completionTimeout = transfer->timeout;
1597 tpriv->req.noDataTimeout = transfer->timeout;
1599 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1601 /* all transfers in libusb-1.0 are async */
1603 if (transfer->endpoint) {
1604 struct darwin_interface *cInterface;
1605 uint8_t pipeRef, iface;
1607 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1608 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1610 return LIBUSB_ERROR_NOT_FOUND;
1613 cInterface = &priv->interfaces[iface];
1615 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1617 /* control request on endpoint 0 */
1618 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1620 if (kresult != kIOReturnSuccess)
1621 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1623 return darwin_to_libusb (kresult);
1626 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1627 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1629 switch (transfer->type) {
1630 case LIBUSB_TRANSFER_TYPE_CONTROL:
1631 return submit_control_transfer(itransfer);
1632 case LIBUSB_TRANSFER_TYPE_BULK:
1633 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1634 return submit_bulk_transfer(itransfer);
1635 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1636 return submit_iso_transfer(itransfer);
1638 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1639 return LIBUSB_ERROR_INVALID_PARAM;
1643 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1644 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1645 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1648 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
1651 return LIBUSB_ERROR_NO_DEVICE;
1653 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1655 return darwin_to_libusb (kresult);
1658 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1659 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1660 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1661 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1662 struct darwin_interface *cInterface;
1663 uint8_t pipeRef, iface;
1666 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1667 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1669 return LIBUSB_ERROR_NOT_FOUND;
1672 cInterface = &priv->interfaces[iface];
1675 return LIBUSB_ERROR_NO_DEVICE;
1677 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
1679 /* abort transactions */
1680 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1682 usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
1684 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1685 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1687 return darwin_to_libusb (kresult);
1690 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1691 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1693 switch (transfer->type) {
1694 case LIBUSB_TRANSFER_TYPE_CONTROL:
1695 return cancel_control_transfer(itransfer);
1696 case LIBUSB_TRANSFER_TYPE_BULK:
1697 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1698 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1699 return darwin_abort_transfers (itransfer);
1701 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1702 return LIBUSB_ERROR_INVALID_PARAM;
1706 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1707 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1708 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1710 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1711 free (tpriv->isoc_framelist);
1712 tpriv->isoc_framelist = NULL;
1716 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1717 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1718 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1719 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1720 struct darwin_msg_async_io_complete message = {.itransfer = itransfer, .result = result,
1721 .size = (UInt32) (uintptr_t) arg0};
1723 usbi_dbg ("an async io operation has completed");
1725 /* if requested write a zero packet */
1726 if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
1727 struct darwin_interface *cInterface;
1728 uint8_t iface, pipeRef;
1730 (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface);
1731 cInterface = &priv->interfaces[iface];
1733 (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
1736 /* send a completion message to the device's file descriptor */
1737 write (priv->fds[1], &message, sizeof (message));
1740 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1741 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT)
1742 result = kIOUSBTransactionTimeout;
1745 case kIOReturnUnderrun:
1746 case kIOReturnSuccess:
1747 return LIBUSB_TRANSFER_COMPLETED;
1748 case kIOReturnAborted:
1749 return LIBUSB_TRANSFER_CANCELLED;
1750 case kIOUSBPipeStalled:
1751 usbi_dbg ("transfer error: pipe is stalled");
1752 return LIBUSB_TRANSFER_STALL;
1753 case kIOReturnOverrun:
1754 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1755 return LIBUSB_TRANSFER_OVERFLOW;
1756 case kIOUSBTransactionTimeout:
1757 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1758 itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
1759 return LIBUSB_TRANSFER_TIMED_OUT;
1761 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1762 return LIBUSB_TRANSFER_ERROR;
1766 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1767 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1768 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1769 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1770 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1771 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1772 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1775 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1776 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1780 usbi_dbg ("handling %s completion with kernel status %d",
1781 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
1783 if (kIOReturnSuccess == result || kIOReturnUnderrun == result) {
1784 if (isIsoc && tpriv->isoc_framelist) {
1785 /* copy isochronous results back */
1787 for (i = 0; i < transfer->num_iso_packets ; i++) {
1788 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1789 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1790 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1793 itransfer->transferred += io_size;
1796 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1797 usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
1800 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready) {
1801 struct darwin_msg_async_io_complete message;
1802 POLL_NFDS_TYPE i = 0;
1805 usbi_mutex_lock(&ctx->open_devs_lock);
1807 for (i = 0; i < nfds && num_ready > 0; i++) {
1808 struct pollfd *pollfd = &fds[i];
1810 usbi_dbg ("checking fd %i with revents = %x", pollfd->fd, pollfd->revents);
1812 if (!pollfd->revents)
1817 if (pollfd->revents & POLLERR) {
1818 /* this probably will never happen so ignore the error an move on. */
1822 /* there is only one type of message */
1823 ret = read (pollfd->fd, &message, sizeof (message));
1824 if (ret < (ssize_t) sizeof (message)) {
1825 usbi_dbg ("WARNING: short read on async io completion pipe\n");
1829 darwin_handle_callback (message.itransfer, message.result, message.size);
1832 usbi_mutex_unlock(&ctx->open_devs_lock);
1837 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1838 mach_timespec_t sys_time;
1839 clock_serv_t clock_ref;
1842 case USBI_CLOCK_REALTIME:
1843 /* CLOCK_REALTIME represents time since the epoch */
1844 clock_ref = clock_realtime;
1846 case USBI_CLOCK_MONOTONIC:
1847 /* use system boot time as reference for the monotonic clock */
1848 clock_ref = clock_monotonic;
1851 return LIBUSB_ERROR_INVALID_PARAM;
1854 clock_get_time (clock_ref, &sys_time);
1856 tp->tv_sec = sys_time.tv_sec;
1857 tp->tv_nsec = sys_time.tv_nsec;
1862 const struct usbi_os_backend darwin_backend = {
1865 .init = darwin_init,
1866 .exit = darwin_exit,
1867 .get_device_list = NULL, /* not needed */
1868 .get_device_descriptor = darwin_get_device_descriptor,
1869 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1870 .get_config_descriptor = darwin_get_config_descriptor,
1872 .open = darwin_open,
1873 .close = darwin_close,
1874 .get_configuration = darwin_get_configuration,
1875 .set_configuration = darwin_set_configuration,
1876 .claim_interface = darwin_claim_interface,
1877 .release_interface = darwin_release_interface,
1879 .set_interface_altsetting = darwin_set_interface_altsetting,
1880 .clear_halt = darwin_clear_halt,
1881 .reset_device = darwin_reset_device,
1883 .kernel_driver_active = darwin_kernel_driver_active,
1884 .detach_kernel_driver = darwin_detach_kernel_driver,
1885 .attach_kernel_driver = darwin_attach_kernel_driver,
1887 .destroy_device = darwin_destroy_device,
1889 .submit_transfer = darwin_submit_transfer,
1890 .cancel_transfer = darwin_cancel_transfer,
1891 .clear_transfer_priv = darwin_clear_transfer_priv,
1893 .handle_events = op_handle_events,
1895 .clock_gettime = darwin_clock_gettime,
1897 .device_priv_size = sizeof(struct darwin_device_priv),
1898 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1899 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1900 .add_iso_packet_size = 0,