1 /* -*- Mode: C; indent-tabs-mode:nil -*- */
3 * darwin backend for libusbx 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
29 #include <sys/ioctl.h>
31 #include <sys/types.h>
33 #include <libkern/OSAtomic.h>
35 #include <mach/clock.h>
36 #include <mach/clock_types.h>
37 #include <mach/mach_host.h>
38 #include <mach/mach_port.h>
40 #include <AvailabilityMacros.h>
41 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
42 #include <objc/objc-auto.h>
45 #include <IOKit/IOCFBundle.h>
46 #include <IOKit/usb/IOUSBLib.h>
47 #include <IOKit/IOCFPlugIn.h>
49 #include "darwin_usb.h"
51 /* async event thread */
52 static pthread_mutex_t libusb_darwin_at_mutex = PTHREAD_MUTEX_INITIALIZER;
53 static pthread_cond_t libusb_darwin_at_cond = PTHREAD_COND_INITIALIZER;
55 static clock_serv_t clock_realtime;
56 static clock_serv_t clock_monotonic;
58 static CFRunLoopRef libusb_darwin_acfl = NULL; /* event cf loop */
59 static volatile int32_t initCount = 0;
61 /* async event thread */
62 static pthread_t libusb_darwin_at;
64 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
65 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
66 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
67 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
68 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
70 static int darwin_scan_devices(struct libusb_context *ctx);
71 static int process_new_device (struct libusb_context *ctx, usb_device_t **device, UInt32 locationID,
72 UInt32 parent_location, UInt8 port);
74 #if defined(ENABLE_LOGGING)
75 static const char *darwin_error_str (int result) {
77 case kIOReturnSuccess:
79 case kIOReturnNotOpen:
80 return "device not opened for exclusive access";
81 case kIOReturnNoDevice:
82 return "no connection to an IOService";
83 case kIOUSBNoAsyncPortErr:
84 return "no async port has been opened for interface";
85 case kIOReturnExclusiveAccess:
86 return "another process has device opened for exclusive access";
87 case kIOUSBPipeStalled:
88 return "pipe is stalled";
90 return "could not establish a connection to the Darwin kernel";
91 case kIOUSBTransactionTimeout:
92 return "transaction timed out";
93 case kIOReturnBadArgument:
94 return "invalid argument";
95 case kIOReturnAborted:
96 return "transaction aborted";
97 case kIOReturnNotResponding:
98 return "device not responding";
99 case kIOReturnOverrun:
100 return "data overrun";
101 case kIOReturnCannotWire:
102 return "physical memory can not be wired down";
103 case kIOReturnNoResources:
104 return "out of resources";
106 return "unknown error";
111 static int darwin_to_libusb (int result) {
113 case kIOReturnUnderrun:
114 case kIOReturnSuccess:
115 return LIBUSB_SUCCESS;
116 case kIOReturnNotOpen:
117 case kIOReturnNoDevice:
118 return LIBUSB_ERROR_NO_DEVICE;
119 case kIOReturnExclusiveAccess:
120 return LIBUSB_ERROR_ACCESS;
121 case kIOUSBPipeStalled:
122 return LIBUSB_ERROR_PIPE;
123 case kIOReturnBadArgument:
124 return LIBUSB_ERROR_INVALID_PARAM;
125 case kIOUSBTransactionTimeout:
126 return LIBUSB_ERROR_TIMEOUT;
127 case kIOReturnNotResponding:
128 case kIOReturnAborted:
130 case kIOUSBNoAsyncPortErr:
132 return LIBUSB_ERROR_OTHER;
137 static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp) {
138 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
140 /* current interface */
141 struct darwin_interface *cInterface;
145 usbi_dbg ("converting ep address 0x%02x to pipeRef and interface", ep);
147 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
148 cInterface = &priv->interfaces[iface];
150 if (dev_handle->claimed_interfaces & (1 << iface)) {
151 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
152 if (cInterface->endpoint_addrs[i] == ep) {
155 usbi_dbg ("pipe %d on interface %d matches", *pipep, *ifcp);
162 /* No pipe found with the correct endpoint address */
163 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
168 static int usb_setup_device_iterator (io_iterator_t *deviceIterator, UInt32 location) {
169 CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBDeviceClassName);
172 return kIOReturnError;
175 CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
176 &kCFTypeDictionaryKeyCallBacks,
177 &kCFTypeDictionaryValueCallBacks);
179 if (propertyMatchDict) {
180 /* there are no unsigned CFNumber types so treat the value as signed. the os seems to do this
181 internally (CFNumberType of locationID is 3) */
182 CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberSInt32Type, &location);
184 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
185 /* release our reference to the CFNumber (CFDictionarySetValue retains it) */
186 CFRelease (locationCF);
188 CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
189 /* release out reference to the CFMutableDictionaryRef (CFDictionarySetValue retains it) */
190 CFRelease (propertyMatchDict);
192 /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
195 return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator);
198 static int get_ioregistry_value_number (io_service_t service, CFStringRef property, CFNumberType type, void *p) {
199 CFTypeRef cfNumber = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
203 if (CFGetTypeID(cfNumber) == CFNumberGetTypeID()) {
204 ret = CFNumberGetValue(cfNumber, type, p);
207 CFRelease (cfNumber);
213 static usb_device_t **usb_get_next_device (io_iterator_t deviceIterator, UInt32 *locationp, UInt8 *portp, UInt32 *parent_locationp) {
214 io_cf_plugin_ref_t *plugInInterface = NULL;
215 usb_device_t **device;
216 io_service_t usbDevice, parent;
217 kern_return_t result;
220 if (!IOIteratorIsValid (deviceIterator))
224 while ((usbDevice = IOIteratorNext(deviceIterator))) {
225 result = IOCreatePlugInInterfaceForService(usbDevice, kIOUSBDeviceUserClientTypeID,
226 kIOCFPlugInInterfaceID, &plugInInterface,
229 /* we are done with the usb_device_t */
230 (void)IOObjectRelease(usbDevice);
234 (void) get_ioregistry_value_number (usbDevice, CFSTR("PortNum"), kCFNumberSInt8Type, portp);
237 if (parent_locationp) {
238 *parent_locationp = 0;
240 result = IORegistryEntryGetParentEntry (usbDevice, kIOUSBPlane, &parent);
242 if (kIOReturnSuccess == result) {
243 (void) get_ioregistry_value_number (parent, CFSTR("locationID"), kCFNumberLongType, parent_locationp);
247 if (kIOReturnSuccess == result && plugInInterface)
250 usbi_dbg ("libusb/darwin.c usb_get_next_device: could not set up plugin for service: %s\n", darwin_error_str (result));
256 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
258 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
259 (*plugInInterface)->Release (plugInInterface);
261 /* get the location from the device */
263 (*(device))->GetLocationID(device, locationp);
268 static void darwin_devices_attached (void *ptr, io_iterator_t add_devices) {
269 struct libusb_context *ctx;
270 usb_device_t **device;
271 UInt32 location, parent_location;
274 usbi_mutex_lock(&active_contexts_lock);
276 while ((device = usb_get_next_device (add_devices, &location, &port, &parent_location))) {
277 /* add this device to each active context's device list */
278 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
279 process_new_device (ctx, device, location, parent_location, port);
282 /* release extra reference */
283 (*device)->Release (device);
286 usbi_mutex_unlock(&active_contexts_lock);
289 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
290 struct libusb_device *dev = NULL;
291 struct libusb_context *ctx;
296 CFTypeRef locationCF;
298 while ((device = IOIteratorNext (rem_devices)) != 0) {
299 /* get the location from the i/o registry */
300 locationCF = IORegistryEntryCreateCFProperty (device, CFSTR(kUSBDevicePropertyLocationID), kCFAllocatorDefault, 0);
302 IOObjectRelease (device);
307 locationValid = CFGetTypeID(locationCF) == CFNumberGetTypeID() &&
308 CFNumberGetValue(locationCF, kCFNumberSInt32Type, &location);
310 CFRelease (locationCF);
315 usbi_mutex_lock(&active_contexts_lock);
317 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
318 usbi_dbg ("libusb/darwin.c darwin_devices_detached: notifying context %p of device disconnect", ctx);
320 dev = usbi_get_device_by_session_id(ctx, location);
325 /* signal the core that this device has been disconnected. the core will tear down this device
326 when the reference count reaches 0 */
327 usbi_disconnect_device(dev);
330 usbi_mutex_unlock(&active_contexts_lock);
334 static void darwin_clear_iterator (io_iterator_t iter) {
337 while ((device = IOIteratorNext (iter)) != 0)
338 IOObjectRelease (device);
341 static void *darwin_event_thread_main (void *arg0) {
343 struct libusb_context *ctx = (struct libusb_context *)arg0;
344 CFRunLoopRef runloop;
346 /* Set this thread's name, so it can be seen in the debugger
347 and crash reports. */
348 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
349 pthread_setname_np ("org.libusb.device-hotplug");
352 /* Tell the Objective-C garbage collector about this thread.
353 This is required because, unlike NSThreads, pthreads are
354 not automatically registered. Although we don't use
355 Objective-C, we use CoreFoundation, which does. */
356 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
357 objc_registerThreadWithCollector();
360 /* hotplug (device arrival/removal) sources */
361 CFRunLoopSourceRef libusb_notification_cfsource;
362 io_notification_port_t libusb_notification_port;
363 io_iterator_t libusb_rem_device_iterator;
364 io_iterator_t libusb_add_device_iterator;
366 usbi_dbg ("creating hotplug event source");
368 runloop = CFRunLoopGetCurrent ();
371 /* add the notification port to the run loop */
372 libusb_notification_port = IONotificationPortCreate (kIOMasterPortDefault);
373 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
374 CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
376 /* create notifications for removed devices */
377 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
378 IOServiceMatching(kIOUSBDeviceClassName),
379 (IOServiceMatchingCallback)darwin_devices_detached,
380 (void *)ctx, &libusb_rem_device_iterator);
382 if (kresult != kIOReturnSuccess) {
383 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
388 /* create notifications for attached devices */
389 kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
390 IOServiceMatching(kIOUSBDeviceClassName),
391 (IOServiceMatchingCallback)darwin_devices_attached,
392 (void *)ctx, &libusb_add_device_iterator);
394 if (kresult != kIOReturnSuccess) {
395 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
401 darwin_clear_iterator (libusb_rem_device_iterator);
402 darwin_clear_iterator (libusb_add_device_iterator);
404 usbi_dbg ("darwin event thread ready to receive events");
406 /* signal the main thread that the hotplug runloop has been created. */
407 pthread_mutex_lock (&libusb_darwin_at_mutex);
408 libusb_darwin_acfl = runloop;
409 pthread_cond_signal (&libusb_darwin_at_cond);
410 pthread_mutex_unlock (&libusb_darwin_at_mutex);
412 /* run the runloop */
415 usbi_dbg ("darwin event thread exiting");
417 /* remove the notification cfsource */
418 CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
420 /* delete notification port */
421 IONotificationPortDestroy (libusb_notification_port);
423 /* delete iterators */
424 IOObjectRelease (libusb_rem_device_iterator);
425 IOObjectRelease (libusb_add_device_iterator);
429 libusb_darwin_acfl = NULL;
434 static int darwin_init(struct libusb_context *ctx) {
435 host_name_port_t host_self;
438 rc = darwin_scan_devices (ctx);
439 if (LIBUSB_SUCCESS != rc) {
443 if (OSAtomicIncrement32Barrier(&initCount) == 1) {
444 /* create the clocks that will be used */
446 host_self = mach_host_self();
447 host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
448 host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
449 mach_port_deallocate(mach_task_self(), host_self);
451 pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, (void *)ctx);
453 pthread_mutex_lock (&libusb_darwin_at_mutex);
454 while (!libusb_darwin_acfl)
455 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
456 pthread_mutex_unlock (&libusb_darwin_at_mutex);
462 static void darwin_exit (void) {
463 if (OSAtomicDecrement32Barrier(&initCount) == 0) {
464 mach_port_deallocate(mach_task_self(), clock_realtime);
465 mach_port_deallocate(mach_task_self(), clock_monotonic);
467 /* stop the event runloop and wait for the thread to terminate. */
468 CFRunLoopStop (libusb_darwin_acfl);
469 pthread_join (libusb_darwin_at, NULL);
473 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
474 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
476 /* return cached copy */
477 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
484 static int get_configuration_index (struct libusb_device *dev, int config_value) {
485 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
487 IOUSBConfigurationDescriptorPtr desc;
490 /* is there a simpler way to determine the index? */
491 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
492 if (kresult != kIOReturnSuccess)
493 return darwin_to_libusb (kresult);
495 for (i = 0 ; i < numConfig ; i++) {
496 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
498 if (desc->bConfigurationValue == config_value)
502 /* configuration not found */
503 return LIBUSB_ERROR_OTHER;
506 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
507 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
510 if (0 == priv->active_config)
511 return LIBUSB_ERROR_NOT_FOUND;
513 config_index = get_configuration_index (dev, priv->active_config);
514 if (config_index < 0)
517 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
520 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
521 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
522 IOUSBConfigurationDescriptorPtr desc;
525 if (!priv || !priv->device)
526 return LIBUSB_ERROR_OTHER;
528 kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
529 if (kresult == kIOReturnSuccess) {
530 /* copy descriptor */
531 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
532 len = libusb_le16_to_cpu(desc->wTotalLength);
534 memmove (buffer, desc, len);
536 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
540 return darwin_to_libusb (kresult);
543 /* check whether the os has configured the device */
544 static int darwin_check_configuration (struct libusb_context *ctx, struct libusb_device *dev, usb_device_t **darwin_device) {
545 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
547 IOUSBConfigurationDescriptorPtr configDesc;
548 IOUSBFindInterfaceRequest request;
549 kern_return_t kresult;
550 io_iterator_t interface_iterator;
551 io_service_t firstInterface;
553 if (priv->dev_descriptor.bNumConfigurations < 1) {
554 usbi_err (ctx, "device has no configurations");
555 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
558 /* find the first configuration */
559 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
560 priv->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
562 /* check if the device is already configured. there is probably a better way than iterating over the
563 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
564 might lock up on the device request) */
566 /* Setup the Interface Request */
567 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
568 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
569 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
570 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
572 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
574 return darwin_to_libusb (kresult);
577 firstInterface = IOIteratorNext(interface_iterator);
579 /* done with the interface iterator */
580 IOObjectRelease(interface_iterator);
582 if (firstInterface) {
583 IOObjectRelease (firstInterface);
585 /* device is configured */
586 if (priv->dev_descriptor.bNumConfigurations == 1)
587 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
588 priv->active_config = priv->first_config;
590 /* devices with more than one configuration should work with GetConfiguration */
591 (*darwin_device)->GetConfiguration (darwin_device, &priv->active_config);
594 priv->active_config = 0;
596 usbi_dbg ("active config: %u, first config: %u", priv->active_config, priv->first_config);
601 static int darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
604 memset (buffer, 0, buffer_size);
606 /* Set up request for descriptor/ */
607 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
608 req.bRequest = kUSBRqGetDescriptor;
609 req.wValue = desc << 8;
610 req.wIndex = desc_index;
611 req.wLength = buffer_size;
614 return (*device)->DeviceRequest (device, &req);
617 static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct libusb_device *dev, usb_device_t **device) {
618 struct darwin_device_priv *priv;
619 int retries = 2, delay = 30000;
620 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
624 UInt16 idProduct, idVendor;
626 (*device)->GetDeviceClass (device, &bDeviceClass);
627 (*device)->GetDeviceProduct (device, &idProduct);
628 (*device)->GetDeviceVendor (device, &idVendor);
630 priv = (struct darwin_device_priv *)dev->os_priv;
632 /* try to open the device (we can usually continue even if this fails) */
633 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
635 /**** retrieve device descriptor ****/
637 /* according to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
638 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
639 * to follow the spec as closely as possible, try opening the device */
640 ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &priv->dev_descriptor, sizeof(priv->dev_descriptor));
643 if (kIOReturnOverrun == ret && kUSBDeviceDesc == priv->dev_descriptor.bDescriptorType)
644 /* received an overrun error but we still received a device descriptor */
645 ret = kIOReturnSuccess;
647 if (kIOUSBVendorIDAppleComputer == idVendor) {
648 /* NTH: don't bother retrying or unsuspending Apple devices */
652 if (kIOReturnSuccess == ret && (0 == priv->dev_descriptor.bNumConfigurations ||
653 0 == priv->dev_descriptor.bcdUSB)) {
654 /* work around for incorrectly configured devices */
655 if (try_reconfigure && is_open) {
656 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
658 /* set the first configuration */
659 (*device)->SetConfiguration(device, 1);
661 /* don't try to reconfigure again */
665 ret = kIOUSBPipeStalled;
668 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
669 /* device may be suspended. unsuspend it and try again */
670 #if DeviceVersion >= 320
673 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
674 (void)(*device)->GetUSBDeviceInformation (device, &info);
676 try_unsuspend = info & (1 << kUSBInformationDeviceIsSuspendedBit);
680 /* resume the device */
681 ret2 = (*device)->USBDeviceSuspend (device, 0);
682 if (kIOReturnSuccess != ret2) {
683 /* prevent log spew from poorly behaving devices. this indicates the
684 os actually had trouble communicating with the device */
685 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
693 if (kIOReturnSuccess != ret) {
694 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
695 /* sleep for a little while before trying again */
698 } while (kIOReturnSuccess != ret && retries--);
701 /* resuspend the device */
702 (void)(*device)->USBDeviceSuspend (device, 1);
705 (void) (*device)->USBDeviceClose (device);
707 if (ret != kIOReturnSuccess) {
708 /* a debug message was already printed out for this error */
709 if (LIBUSB_CLASS_HUB == bDeviceClass)
710 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s. skipping device", idVendor, idProduct, darwin_error_str (ret));
712 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s. skipping device", idVendor, idProduct, darwin_error_str (ret));
717 usbi_dbg ("device descriptor:");
718 usbi_dbg (" bDescriptorType: 0x%02x", priv->dev_descriptor.bDescriptorType);
719 usbi_dbg (" bcdUSB: 0x%04x", priv->dev_descriptor.bcdUSB);
720 usbi_dbg (" bDeviceClass: 0x%02x", priv->dev_descriptor.bDeviceClass);
721 usbi_dbg (" bDeviceSubClass: 0x%02x", priv->dev_descriptor.bDeviceSubClass);
722 usbi_dbg (" bDeviceProtocol: 0x%02x", priv->dev_descriptor.bDeviceProtocol);
723 usbi_dbg (" bMaxPacketSize0: 0x%02x", priv->dev_descriptor.bMaxPacketSize0);
724 usbi_dbg (" idVendor: 0x%04x", priv->dev_descriptor.idVendor);
725 usbi_dbg (" idProduct: 0x%04x", priv->dev_descriptor.idProduct);
726 usbi_dbg (" bcdDevice: 0x%04x", priv->dev_descriptor.bcdDevice);
727 usbi_dbg (" iManufacturer: 0x%02x", priv->dev_descriptor.iManufacturer);
728 usbi_dbg (" iProduct: 0x%02x", priv->dev_descriptor.iProduct);
729 usbi_dbg (" iSerialNumber: 0x%02x", priv->dev_descriptor.iSerialNumber);
730 usbi_dbg (" bNumConfigurations: 0x%02x", priv->dev_descriptor.bNumConfigurations);
732 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
733 if (libusb_le16_to_cpu (priv->dev_descriptor.idProduct) != idProduct) {
734 /* not a valid device */
735 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
736 idProduct, libusb_le16_to_cpu (priv->dev_descriptor.idProduct));
743 static int process_new_device (struct libusb_context *ctx, usb_device_t **device, UInt32 locationID,
744 UInt32 parent_location, UInt8 port) {
745 struct darwin_device_priv *priv;
746 struct libusb_device *dev, *parent = NULL;
752 usbi_dbg ("allocating new device for location 0x%08x", locationID);
754 dev = usbi_alloc_device(ctx, locationID);
756 return LIBUSB_ERROR_NO_MEM;
759 priv = (struct darwin_device_priv *)dev->os_priv;
760 priv->device = device;
762 /* increment the device's reference count (it is decremented in darwin_destroy_device) */
763 (*device)->AddRef (device);
765 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&address);
767 ret = darwin_cache_device_descriptor (ctx, dev, device);
771 /* check current active configuration (and cache the first configuration value-- which may be used by claim_interface) */
772 ret = darwin_check_configuration (ctx, dev, device);
776 /* the device iterator provides devices in increasing order of location. given this property
777 * we can use the last device to find the parent. */
778 /* TODO: FIX TOPOLOGY!
779 for (parent = *last_dev ; parent ; parent = parent->parent_dev) {
780 struct darwin_device_priv *parent_priv = (struct darwin_device_priv *) parent->os_priv;
782 if (parent_priv->location == parent_location) {
787 dev->parent_dev = parent;
789 dev->port_number = port;
791 dev->bus_number = locationID >> 24;
792 dev->device_address = address;
794 (*device)->GetDeviceSpeed (device, &devSpeed);
797 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
798 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
799 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
800 #if DeviceVersion >= 500
801 case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
804 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
807 /* save our location, we'll need this later */
808 priv->location = locationID;
809 snprintf(priv->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", address, priv->dev_descriptor.idVendor, priv->dev_descriptor.idProduct,
810 priv->dev_descriptor.bDeviceClass, priv->dev_descriptor.bDeviceSubClass);
812 ret = usbi_sanitize_device (dev);
816 usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
817 dev->port_number, (void *) parent, priv->sys_path);
821 usbi_connect_device (dev);
823 libusb_unref_device (dev);
829 static int darwin_scan_devices(struct libusb_context *ctx) {
830 io_iterator_t deviceIterator;
831 usb_device_t **device;
832 kern_return_t kresult;
833 UInt32 location, parent_location;
836 kresult = usb_setup_device_iterator (&deviceIterator, 0);
837 if (kresult != kIOReturnSuccess)
838 return darwin_to_libusb (kresult);
840 while ((device = usb_get_next_device (deviceIterator, &location, &port, &parent_location)) != NULL) {
841 (void) process_new_device (ctx, device, location, parent_location, port);
843 /* process_new_device added a reference so we need to release the one
844 from QueryInterface */
845 (*device)->Release (device);
848 IOObjectRelease(deviceIterator);
853 static int darwin_open (struct libusb_device_handle *dev_handle) {
854 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
855 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
858 if (0 == dpriv->open_count) {
859 /* try to open the device */
860 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
861 if (kresult != kIOReturnSuccess) {
862 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
864 if (kIOReturnExclusiveAccess != kresult) {
865 return darwin_to_libusb (kresult);
868 /* it is possible to perform some actions on a device that is not open so do not return an error */
874 /* create async event source */
875 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
876 if (kresult != kIOReturnSuccess) {
877 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
880 (*(dpriv->device))->USBDeviceClose (dpriv->device);
885 return darwin_to_libusb (kresult);
888 CFRetain (libusb_darwin_acfl);
890 /* add the cfSource to the aync run loop */
891 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
894 /* device opened successfully */
897 /* create a file descriptor for notifications */
900 /* set the pipe to be non-blocking */
901 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
903 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
905 usbi_dbg ("device open for access");
910 static void darwin_close (struct libusb_device_handle *dev_handle) {
911 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
912 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
916 if (dpriv->open_count == 0) {
917 /* something is probably very wrong if this is the case */
918 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
924 /* make sure all interfaces are released */
925 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
926 if (dev_handle->claimed_interfaces & (1 << i))
927 libusb_release_interface (dev_handle, i);
929 if (0 == dpriv->open_count) {
930 /* delete the device's async event source */
931 if (priv->cfSource) {
932 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
933 CFRelease (priv->cfSource);
934 priv->cfSource = NULL;
935 CFRelease (libusb_darwin_acfl);
939 /* close the device */
940 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
942 /* Log the fact that we had a problem closing the file, however failing a
943 * close isn't really an error, so return success anyway */
944 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
949 /* file descriptors are maintained per-instance */
950 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
951 close (priv->fds[1]);
952 close (priv->fds[0]);
954 priv->fds[0] = priv->fds[1] = -1;
957 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
958 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
960 *config = (int) dpriv->active_config;
965 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
966 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
970 /* Setting configuration will invalidate the interface, so we need
971 to reclaim it. First, dispose of existing interfaces, if any. */
972 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
973 if (dev_handle->claimed_interfaces & (1 << i))
974 darwin_release_interface (dev_handle, i);
976 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
977 if (kresult != kIOReturnSuccess)
978 return darwin_to_libusb (kresult);
980 /* Reclaim any interfaces. */
981 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
982 if (dev_handle->claimed_interfaces & (1 << i))
983 darwin_claim_interface (dev_handle, i);
985 dpriv->active_config = config;
990 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
991 IOUSBFindInterfaceRequest request;
992 kern_return_t kresult;
993 io_iterator_t interface_iterator;
994 CFTypeRef bInterfaceNumberCF;
995 int bInterfaceNumber;
997 *usbInterfacep = IO_OBJECT_NULL;
999 /* Setup the Interface Request */
1000 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1001 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1002 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1003 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1005 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1009 while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1010 /* find the interface number */
1011 bInterfaceNumberCF = IORegistryEntryCreateCFProperty (*usbInterfacep, CFSTR("bInterfaceNumber"),
1012 kCFAllocatorDefault, 0);
1013 if (!bInterfaceNumberCF) {
1017 CFNumberGetValue(bInterfaceNumberCF, kCFNumberIntType, &bInterfaceNumber);
1019 CFRelease(bInterfaceNumberCF);
1021 if ((uint8_t) bInterfaceNumber == ifc) {
1025 (void) IOObjectRelease (*usbInterfacep);
1028 /* done with the interface iterator */
1029 IOObjectRelease(interface_iterator);
1034 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
1035 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1037 /* current interface */
1038 struct darwin_interface *cInterface = &priv->interfaces[iface];
1040 kern_return_t kresult;
1042 u_int8_t numep, direction, number;
1043 u_int8_t dont_care1, dont_care3;
1044 u_int16_t dont_care2;
1047 usbi_dbg ("building table of endpoints.");
1049 /* retrieve the total number of endpoints on this interface */
1050 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1052 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1053 return darwin_to_libusb (kresult);
1056 /* iterate through pipe references */
1057 for (i = 1 ; i <= numep ; i++) {
1058 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1059 &dont_care2, &dont_care3);
1061 if (kresult != kIOReturnSuccess) {
1062 usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
1064 return darwin_to_libusb (kresult);
1067 usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
1069 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1072 cInterface->num_endpoints = numep;
1077 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1078 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1079 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1080 io_service_t usbInterface = IO_OBJECT_NULL;
1082 IOCFPlugInInterface **plugInInterface = NULL;
1085 /* current interface */
1086 struct darwin_interface *cInterface = &priv->interfaces[iface];
1088 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1089 if (kresult != kIOReturnSuccess)
1090 return darwin_to_libusb (kresult);
1092 /* make sure we have an interface */
1093 if (!usbInterface && dpriv->first_config != 0) {
1094 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1096 /* set the configuration */
1097 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1098 if (kresult != LIBUSB_SUCCESS) {
1099 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1103 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1105 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1106 return darwin_to_libusb (kresult);
1110 if (!usbInterface) {
1111 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1112 return LIBUSB_ERROR_NOT_FOUND;
1115 /* get an interface to the device's interface */
1116 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1117 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1119 /* ignore release error */
1120 (void)IOObjectRelease (usbInterface);
1123 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1124 return darwin_to_libusb (kresult);
1127 if (!plugInInterface) {
1128 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1129 return LIBUSB_ERROR_NOT_FOUND;
1132 /* Do the actual claim */
1133 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1134 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1135 (LPVOID)&cInterface->interface);
1136 /* We no longer need the intermediate plug-in */
1137 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1138 (*plugInInterface)->Release (plugInInterface);
1139 if (kresult || !cInterface->interface) {
1140 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1141 return darwin_to_libusb (kresult);
1144 /* claim the interface */
1145 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1147 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1148 return darwin_to_libusb (kresult);
1151 /* update list of endpoints */
1152 kresult = get_endpoints (dev_handle, iface);
1154 /* this should not happen */
1155 darwin_release_interface (dev_handle, iface);
1156 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1160 cInterface->cfSource = NULL;
1162 /* create async event source */
1163 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1164 if (kresult != kIOReturnSuccess) {
1165 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1167 /* can't continue without an async event source */
1168 (void)darwin_release_interface (dev_handle, iface);
1170 return darwin_to_libusb (kresult);
1173 /* add the cfSource to the async thread's run loop */
1174 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1176 usbi_dbg ("interface opened");
1181 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1182 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1185 /* current interface */
1186 struct darwin_interface *cInterface = &priv->interfaces[iface];
1188 /* Check to see if an interface is open */
1189 if (!cInterface->interface)
1190 return LIBUSB_SUCCESS;
1192 /* clean up endpoint data */
1193 cInterface->num_endpoints = 0;
1195 /* delete the interface's async event source */
1196 if (cInterface->cfSource) {
1197 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1198 CFRelease (cInterface->cfSource);
1201 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1203 usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1205 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1206 if (kresult != kIOReturnSuccess)
1207 usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1209 cInterface->interface = IO_OBJECT_NULL;
1211 return darwin_to_libusb (kresult);
1214 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1215 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1218 /* current interface */
1219 struct darwin_interface *cInterface = &priv->interfaces[iface];
1221 if (!cInterface->interface)
1222 return LIBUSB_ERROR_NO_DEVICE;
1224 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1225 if (kresult != kIOReturnSuccess)
1226 darwin_reset_device (dev_handle);
1228 /* update list of endpoints */
1229 kresult = get_endpoints (dev_handle, iface);
1231 /* this should not happen */
1232 darwin_release_interface (dev_handle, iface);
1233 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1237 return darwin_to_libusb (kresult);
1240 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1241 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1243 /* current interface */
1244 struct darwin_interface *cInterface;
1245 uint8_t pipeRef, iface;
1248 /* determine the interface/endpoint to use */
1249 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
1250 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1252 return LIBUSB_ERROR_NOT_FOUND;
1255 cInterface = &priv->interfaces[iface];
1257 #if (InterfaceVersion < 190)
1258 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1260 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1261 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1264 usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1266 return darwin_to_libusb (kresult);
1269 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1270 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1271 IOUSBDeviceDescriptor descriptor;
1272 IOUSBConfigurationDescriptorPtr cached_configuration;
1273 IOUSBConfigurationDescriptor configuration;
1274 bool reenumerate = false;
1278 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1280 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1281 return darwin_to_libusb (kresult);
1285 usbi_dbg ("darwin/reset_device: checking if device descriptor changed");
1287 /* ignore return code. if we can't get a descriptor it might be worthwhile re-enumerating anway */
1288 (void) darwin_request_descriptor (dpriv->device, kUSBDeviceDesc, 0, &descriptor, sizeof (descriptor));
1290 /* check if the device descriptor has changed */
1291 if (0 != memcmp (&dpriv->dev_descriptor, &descriptor, sizeof (descriptor))) {
1296 /* check if any configuration descriptor has changed */
1297 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1298 usbi_dbg ("darwin/reset_device: checking if configuration descriptor %d changed", i);
1300 (void) darwin_request_descriptor (dpriv->device, kUSBConfDesc, i, &configuration, sizeof (configuration));
1301 (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1303 if (!cached_configuration || 0 != memcmp (cached_configuration, &configuration, sizeof (configuration))) {
1311 usbi_dbg ("darwin/reset_device: device requires reenumeration");
1312 (void) (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
1313 return LIBUSB_ERROR_NOT_FOUND;
1316 usbi_dbg ("darwin/reset_device: device reset complete");
1318 return LIBUSB_SUCCESS;
1321 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1322 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1323 io_service_t usbInterface;
1327 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1329 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1331 return darwin_to_libusb (kresult);
1334 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1335 IOObjectRelease (usbInterface);
1347 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1348 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1351 return LIBUSB_ERROR_NOT_SUPPORTED;
1354 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1357 return LIBUSB_ERROR_NOT_SUPPORTED;
1360 static void darwin_destroy_device(struct libusb_device *dev) {
1361 struct darwin_device_priv *dpriv = (struct darwin_device_priv *) dev->os_priv;
1363 if (dpriv->device) {
1364 /* it is an internal error if the reference count of a device is < 0 after release */
1365 assert(0 <= (*(dpriv->device))->Release(dpriv->device));
1367 dpriv->device = NULL;
1371 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1372 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1373 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1376 uint8_t transferType;
1377 /* None of the values below are used in libusbx for bulk transfers */
1378 uint8_t direction, number, interval, pipeRef, iface;
1379 uint16_t maxPacketSize;
1381 struct darwin_interface *cInterface;
1383 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1384 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1386 return LIBUSB_ERROR_NOT_FOUND;
1389 cInterface = &priv->interfaces[iface];
1391 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1392 &transferType, &maxPacketSize, &interval);
1394 if (0 != (transfer->length % maxPacketSize)) {
1395 /* do not need a zero packet */
1396 transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1399 /* submit the request */
1400 /* timeouts are unavailable on interrupt endpoints */
1401 if (transferType == kUSBInterrupt) {
1402 if (IS_XFERIN(transfer))
1403 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1404 transfer->length, darwin_async_io_callback, itransfer);
1406 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1407 transfer->length, darwin_async_io_callback, itransfer);
1409 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1411 if (IS_XFERIN(transfer))
1412 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1413 transfer->length, transfer->timeout, transfer->timeout,
1414 darwin_async_io_callback, (void *)itransfer);
1416 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1417 transfer->length, transfer->timeout, transfer->timeout,
1418 darwin_async_io_callback, (void *)itransfer);
1422 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1423 darwin_error_str(ret), ret);
1425 return darwin_to_libusb (ret);
1428 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1429 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1430 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1431 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1434 uint8_t direction, number, interval, pipeRef, iface, transferType;
1435 uint16_t maxPacketSize;
1437 AbsoluteTime atTime;
1440 struct darwin_interface *cInterface;
1442 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1443 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1444 free(tpriv->isoc_framelist);
1445 tpriv->isoc_framelist = NULL;
1448 if (!tpriv->isoc_framelist) {
1449 tpriv->num_iso_packets = transfer->num_iso_packets;
1450 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1451 if (!tpriv->isoc_framelist)
1452 return LIBUSB_ERROR_NO_MEM;
1455 /* copy the frame list from the libusbx descriptor (the structures differ only is member order) */
1456 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1457 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1459 /* determine the interface/endpoint to use */
1460 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1461 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1463 return LIBUSB_ERROR_NOT_FOUND;
1466 cInterface = &priv->interfaces[iface];
1468 /* determine the properties of this endpoint and the speed of the device */
1469 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1470 &transferType, &maxPacketSize, &interval);
1472 /* Last but not least we need the bus frame number */
1473 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1475 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1476 free(tpriv->isoc_framelist);
1477 tpriv->isoc_framelist = NULL;
1479 return darwin_to_libusb (kresult);
1482 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1483 &transferType, &maxPacketSize, &interval);
1485 /* schedule for a frame a little in the future */
1488 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1489 frame = cInterface->frames[transfer->endpoint];
1491 /* submit the request */
1492 if (IS_XFERIN(transfer))
1493 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1494 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1497 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1498 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1501 if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
1503 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1));
1505 /* High/super speed */
1506 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1)) / 8;
1508 if (kresult != kIOReturnSuccess) {
1509 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1510 darwin_error_str(kresult));
1511 free (tpriv->isoc_framelist);
1512 tpriv->isoc_framelist = NULL;
1515 return darwin_to_libusb (kresult);
1518 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1519 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1520 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1521 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1522 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1523 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1527 bzero(&tpriv->req, sizeof(tpriv->req));
1529 /* IOUSBDeviceInterface expects the request in cpu endianess */
1530 tpriv->req.bmRequestType = setup->bmRequestType;
1531 tpriv->req.bRequest = setup->bRequest;
1532 /* these values should be in bus order from libusb_fill_control_setup */
1533 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1534 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1535 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1536 /* data is stored after the libusbx control block */
1537 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1538 tpriv->req.completionTimeout = transfer->timeout;
1539 tpriv->req.noDataTimeout = transfer->timeout;
1541 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1543 /* all transfers in libusb-1.0 are async */
1545 if (transfer->endpoint) {
1546 struct darwin_interface *cInterface;
1547 uint8_t pipeRef, iface;
1549 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1550 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1552 return LIBUSB_ERROR_NOT_FOUND;
1555 cInterface = &priv->interfaces[iface];
1557 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1559 /* control request on endpoint 0 */
1560 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1562 if (kresult != kIOReturnSuccess)
1563 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1565 return darwin_to_libusb (kresult);
1568 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1569 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1571 switch (transfer->type) {
1572 case LIBUSB_TRANSFER_TYPE_CONTROL:
1573 return submit_control_transfer(itransfer);
1574 case LIBUSB_TRANSFER_TYPE_BULK:
1575 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1576 return submit_bulk_transfer(itransfer);
1577 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1578 return submit_iso_transfer(itransfer);
1580 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1581 return LIBUSB_ERROR_INVALID_PARAM;
1585 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1586 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1587 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1590 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
1593 return LIBUSB_ERROR_NO_DEVICE;
1595 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1597 return darwin_to_libusb (kresult);
1600 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1601 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1602 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1603 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1604 struct darwin_interface *cInterface;
1605 uint8_t pipeRef, iface;
1608 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1609 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1611 return LIBUSB_ERROR_NOT_FOUND;
1614 cInterface = &priv->interfaces[iface];
1617 return LIBUSB_ERROR_NO_DEVICE;
1619 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
1621 /* abort transactions */
1622 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1624 usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
1626 /* clear the data toggle bit */
1627 #if (InterfaceVersion < 190)
1628 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1630 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1631 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1634 return darwin_to_libusb (kresult);
1637 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1638 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1640 switch (transfer->type) {
1641 case LIBUSB_TRANSFER_TYPE_CONTROL:
1642 return cancel_control_transfer(itransfer);
1643 case LIBUSB_TRANSFER_TYPE_BULK:
1644 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1645 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1646 return darwin_abort_transfers (itransfer);
1648 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1649 return LIBUSB_ERROR_INVALID_PARAM;
1653 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1654 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1655 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1657 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1658 free (tpriv->isoc_framelist);
1659 tpriv->isoc_framelist = NULL;
1663 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1664 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1665 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1666 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1667 struct darwin_msg_async_io_complete message = {.itransfer = itransfer, .result = result,
1668 .size = (UInt32) (uintptr_t) arg0};
1670 usbi_dbg ("an async io operation has completed");
1672 /* if requested write a zero packet */
1673 if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
1674 struct darwin_interface *cInterface;
1675 uint8_t iface, pipeRef;
1677 (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface);
1678 cInterface = &priv->interfaces[iface];
1680 (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
1683 /* send a completion message to the device's file descriptor */
1684 write (priv->fds[1], &message, sizeof (message));
1687 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1688 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT)
1689 result = kIOUSBTransactionTimeout;
1692 case kIOReturnUnderrun:
1693 case kIOReturnSuccess:
1694 return LIBUSB_TRANSFER_COMPLETED;
1695 case kIOReturnAborted:
1696 return LIBUSB_TRANSFER_CANCELLED;
1697 case kIOUSBPipeStalled:
1698 usbi_dbg ("transfer error: pipe is stalled");
1699 return LIBUSB_TRANSFER_STALL;
1700 case kIOReturnOverrun:
1701 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1702 return LIBUSB_TRANSFER_OVERFLOW;
1703 case kIOUSBTransactionTimeout:
1704 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1705 itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
1706 return LIBUSB_TRANSFER_TIMED_OUT;
1708 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1709 return LIBUSB_TRANSFER_ERROR;
1713 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1714 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1715 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1716 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1717 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1718 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1719 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1722 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1723 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1727 usbi_dbg ("handling %s completion with kernel status %d",
1728 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
1730 if (kIOReturnSuccess == result || kIOReturnUnderrun == result) {
1731 if (isIsoc && tpriv->isoc_framelist) {
1732 /* copy isochronous results back */
1734 for (i = 0; i < transfer->num_iso_packets ; i++) {
1735 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1736 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1737 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1740 itransfer->transferred += io_size;
1743 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1744 usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
1747 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready) {
1748 struct darwin_msg_async_io_complete message;
1749 POLL_NFDS_TYPE i = 0;
1752 usbi_mutex_lock(&ctx->open_devs_lock);
1754 for (i = 0; i < nfds && num_ready > 0; i++) {
1755 struct pollfd *pollfd = &fds[i];
1757 usbi_dbg ("checking fd %i with revents = %x", pollfd->fd, pollfd->revents);
1759 if (!pollfd->revents)
1764 if (pollfd->revents & POLLERR) {
1765 /* this probably will never happen so ignore the error an move on. */
1769 /* there is only one type of message */
1770 ret = read (pollfd->fd, &message, sizeof (message));
1771 if (ret < (ssize_t) sizeof (message)) {
1772 usbi_dbg ("WARNING: short read on async io completion pipe\n");
1776 darwin_handle_callback (message.itransfer, message.result, message.size);
1779 usbi_mutex_unlock(&ctx->open_devs_lock);
1784 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1785 mach_timespec_t sys_time;
1786 clock_serv_t clock_ref;
1789 case USBI_CLOCK_REALTIME:
1790 /* CLOCK_REALTIME represents time since the epoch */
1791 clock_ref = clock_realtime;
1793 case USBI_CLOCK_MONOTONIC:
1794 /* use system boot time as reference for the monotonic clock */
1795 clock_ref = clock_monotonic;
1798 return LIBUSB_ERROR_INVALID_PARAM;
1801 clock_get_time (clock_ref, &sys_time);
1803 tp->tv_sec = sys_time.tv_sec;
1804 tp->tv_nsec = sys_time.tv_nsec;
1809 const struct usbi_os_backend darwin_backend = {
1812 .init = darwin_init,
1813 .exit = darwin_exit,
1814 .get_device_list = NULL, /* not needed */
1815 .get_device_descriptor = darwin_get_device_descriptor,
1816 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1817 .get_config_descriptor = darwin_get_config_descriptor,
1819 .open = darwin_open,
1820 .close = darwin_close,
1821 .get_configuration = darwin_get_configuration,
1822 .set_configuration = darwin_set_configuration,
1823 .claim_interface = darwin_claim_interface,
1824 .release_interface = darwin_release_interface,
1826 .set_interface_altsetting = darwin_set_interface_altsetting,
1827 .clear_halt = darwin_clear_halt,
1828 .reset_device = darwin_reset_device,
1830 .kernel_driver_active = darwin_kernel_driver_active,
1831 .detach_kernel_driver = darwin_detach_kernel_driver,
1832 .attach_kernel_driver = darwin_attach_kernel_driver,
1834 .destroy_device = darwin_destroy_device,
1836 .submit_transfer = darwin_submit_transfer,
1837 .cancel_transfer = darwin_cancel_transfer,
1838 .clear_transfer_priv = darwin_clear_transfer_priv,
1840 .handle_events = op_handle_events,
1842 .clock_gettime = darwin_clock_gettime,
1844 .device_priv_size = sizeof(struct darwin_device_priv),
1845 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1846 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1847 .add_iso_packet_size = 0,