2 * darwin backend for libusb 1.0
3 * Copyright (C) 2008-2011 Nathan Hjelm <hjelmn@users.sourceforge.net>
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29 #include <sys/ioctl.h>
31 #include <sys/types.h>
34 #include <mach/clock.h>
35 #include <mach/clock_types.h>
36 #include <mach/mach_host.h>
37 #include <mach/mach_port.h>
39 #include <AvailabilityMacros.h>
40 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
41 #include <objc/objc-auto.h>
44 #include <IOKit/IOCFBundle.h>
45 #include <IOKit/usb/IOUSBLib.h>
46 #include <IOKit/IOCFPlugIn.h>
48 #include "darwin_usb.h"
50 static CFRunLoopRef libusb_darwin_acfl = NULL; /* async cf loop */
51 static int initCount = 0;
53 /* async event thread */
54 static pthread_t libusb_darwin_at;
56 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
57 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
58 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
59 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
60 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
62 static const char *darwin_error_str (int result) {
64 case kIOReturnSuccess:
66 case kIOReturnNotOpen:
67 return "device not opened for exclusive access";
68 case kIOReturnNoDevice:
69 return "no connection to an IOService";
70 case kIOUSBNoAsyncPortErr:
71 return "no async port has been opened for interface";
72 case kIOReturnExclusiveAccess:
73 return "another process has device opened for exclusive access";
74 case kIOUSBPipeStalled:
75 return "pipe is stalled";
77 return "could not establish a connection to the Darwin kernel";
78 case kIOUSBTransactionTimeout:
79 return "transaction timed out";
80 case kIOReturnBadArgument:
81 return "invalid argument";
82 case kIOReturnAborted:
83 return "transaction aborted";
84 case kIOReturnNotResponding:
85 return "device not responding";
86 case kIOReturnOverrun:
87 return "data overrun";
88 case kIOReturnCannotWire:
89 return "physical memory can not be wired down";
91 return "unknown error";
95 static int darwin_to_libusb (int result) {
97 case kIOReturnUnderrun:
98 case kIOReturnSuccess:
99 return LIBUSB_SUCCESS;
100 case kIOReturnNotOpen:
101 case kIOReturnNoDevice:
102 return LIBUSB_ERROR_NO_DEVICE;
103 case kIOReturnExclusiveAccess:
104 return LIBUSB_ERROR_ACCESS;
105 case kIOUSBPipeStalled:
106 return LIBUSB_ERROR_PIPE;
107 case kIOReturnBadArgument:
108 return LIBUSB_ERROR_INVALID_PARAM;
109 case kIOUSBTransactionTimeout:
110 return LIBUSB_ERROR_TIMEOUT;
111 case kIOReturnNotResponding:
112 case kIOReturnAborted:
114 case kIOUSBNoAsyncPortErr:
116 return LIBUSB_ERROR_OTHER;
121 static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp) {
122 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
124 /* current interface */
125 struct darwin_interface *cInterface;
129 usbi_info (HANDLE_CTX(dev_handle), "converting ep address 0x%02x to pipeRef and interface", ep);
131 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
132 cInterface = &priv->interfaces[iface];
134 if (dev_handle->claimed_interfaces & (1 << iface)) {
135 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
136 if (cInterface->endpoint_addrs[i] == ep) {
139 usbi_info (HANDLE_CTX(dev_handle), "pipe %d on interface %d matches", *pipep, *ifcp);
146 /* No pipe found with the correct endpoint address */
147 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
152 static int usb_setup_device_iterator (io_iterator_t *deviceIterator, long location) {
153 CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBDeviceClassName);
156 return kIOReturnError;
159 CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
160 &kCFTypeDictionaryKeyCallBacks,
161 &kCFTypeDictionaryValueCallBacks);
163 if (propertyMatchDict) {
164 CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberLongType, &location);
166 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
167 /* release our reference to the CFNumber (CFDictionarySetValue retains it) */
168 CFRelease (locationCF);
170 CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
171 /* release out reference to the CFMutableDictionaryRef (CFDictionarySetValue retains it) */
172 CFRelease (propertyMatchDict);
174 /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
177 return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator);
180 static usb_device_t **usb_get_next_device (io_iterator_t deviceIterator, UInt32 *locationp) {
181 io_cf_plugin_ref_t *plugInInterface = NULL;
182 usb_device_t **device;
183 io_service_t usbDevice;
187 if (!IOIteratorIsValid (deviceIterator))
191 while ((usbDevice = IOIteratorNext(deviceIterator))) {
192 result = IOCreatePlugInInterfaceForService(usbDevice, kIOUSBDeviceUserClientTypeID,
193 kIOCFPlugInInterfaceID, &plugInInterface,
196 /* we are done with the usb_device_t */
197 (void)IOObjectRelease(usbDevice);
198 if (kIOReturnSuccess == result && plugInInterface)
201 usbi_dbg ("libusb/darwin.c usb_get_next_device: could not set up plugin for service: %s\n", darwin_error_str (result));
207 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
210 (*plugInInterface)->Stop(plugInInterface);
211 IODestroyPlugInInterface (plugInInterface);
213 /* get the location from the device */
215 (*(device))->GetLocationID(device, locationp);
220 static kern_return_t darwin_get_device (uint32_t dev_location, usb_device_t ***darwin_device) {
221 kern_return_t kresult;
223 io_iterator_t deviceIterator;
225 kresult = usb_setup_device_iterator (&deviceIterator, dev_location);
229 /* This port of libusb uses locations to keep track of devices. */
230 while ((*darwin_device = usb_get_next_device (deviceIterator, &location)) != NULL) {
231 if (location == dev_location)
234 (**darwin_device)->Release(*darwin_device);
237 IOObjectRelease (deviceIterator);
239 if (!(*darwin_device))
240 return kIOReturnNoDevice;
242 return kIOReturnSuccess;
247 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
248 struct libusb_context *ctx = (struct libusb_context *)ptr;
249 struct libusb_device_handle *handle;
250 struct darwin_device_priv *dpriv;
251 struct darwin_device_handle_priv *priv;
256 CFTypeRef locationCF;
259 usbi_info (ctx, "a device has been detached");
261 while ((device = IOIteratorNext (rem_devices)) != 0) {
262 /* get the location from the i/o registry */
263 locationCF = IORegistryEntryCreateCFProperty (device, CFSTR(kUSBDevicePropertyLocationID), kCFAllocatorDefault, 0);
265 IOObjectRelease (device);
270 locationValid = CFGetTypeID(locationCF) == CFNumberGetTypeID() &&
271 CFNumberGetValue(locationCF, kCFNumberLongType, &location);
273 CFRelease (locationCF);
278 usbi_mutex_lock(&ctx->open_devs_lock);
279 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
280 dpriv = (struct darwin_device_priv *)handle->dev->os_priv;
282 /* the device may have been opened several times. write to each handle's event descriptor */
283 if (dpriv->location == location && handle->os_priv) {
284 priv = (struct darwin_device_handle_priv *)handle->os_priv;
286 message = MESSAGE_DEVICE_GONE;
287 write (priv->fds[1], &message, sizeof (message));
291 usbi_mutex_unlock(&ctx->open_devs_lock);
295 static void darwin_clear_iterator (io_iterator_t iter) {
298 while ((device = IOIteratorNext (iter)) != 0)
299 IOObjectRelease (device);
302 static void *event_thread_main (void *arg0) {
304 struct libusb_context *ctx = (struct libusb_context *)arg0;
305 CFRunLoopRef runloop;
307 /* Tell the Objective-C garbage collector about this thread.
308 This is required because, unlike NSThreads, pthreads are
309 not automatically registered. Although we don't use
310 Objective-C, we use CoreFoundation, which does. */
311 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
312 objc_registerThreadWithCollector();
315 /* hotplug (device removal) source */
316 CFRunLoopSourceRef libusb_notification_cfsource;
317 io_notification_port_t libusb_notification_port;
318 io_iterator_t libusb_rem_device_iterator;
320 usbi_info (ctx, "creating hotplug event source");
322 runloop = CFRunLoopGetCurrent ();
325 /* add the notification port to the run loop */
326 libusb_notification_port = IONotificationPortCreate (kIOMasterPortDefault);
327 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
328 CFRunLoopAddSource(CFRunLoopGetCurrent (), libusb_notification_cfsource, kCFRunLoopDefaultMode);
330 /* create notifications for removed devices */
331 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
332 IOServiceMatching(kIOUSBDeviceClassName),
333 (IOServiceMatchingCallback)darwin_devices_detached,
334 (void *)ctx, &libusb_rem_device_iterator);
336 if (kresult != kIOReturnSuccess) {
337 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
343 darwin_clear_iterator (libusb_rem_device_iterator);
345 /* let the main thread know about the async runloop */
346 libusb_darwin_acfl = CFRunLoopGetCurrent ();
348 usbi_info (ctx, "thread ready to receive events");
350 /* run the runloop */
353 usbi_info (ctx, "thread exiting");
355 /* delete notification port */
356 CFRunLoopSourceInvalidate (libusb_notification_cfsource);
357 IONotificationPortDestroy (libusb_notification_port);
361 libusb_darwin_acfl = NULL;
366 static int darwin_init(struct libusb_context *ctx) {
369 if (!(initCount++)) {
370 pthread_create (&libusb_darwin_at, NULL, event_thread_main, (void *)ctx);
372 while (!libusb_darwin_acfl)
379 static void darwin_exit (void) {
380 if (!(--initCount)) {
382 /* stop the async runloop */
383 CFRunLoopStop (libusb_darwin_acfl);
384 pthread_join (libusb_darwin_at, NULL);
388 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
389 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
391 /* return cached copy */
392 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
399 static int get_configuration_index (struct libusb_device *dev, int config_value) {
400 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
402 IOUSBConfigurationDescriptorPtr desc;
405 /* is there a simpler way to determine the index? */
406 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
407 if (kresult != kIOReturnSuccess)
408 return darwin_to_libusb (kresult);
410 for (i = 0 ; i < numConfig ; i++) {
411 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
413 if (desc->bConfigurationValue == config_value)
417 /* configuration not found */
418 return LIBUSB_ERROR_OTHER;
421 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
422 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
425 if (0 == priv->active_config)
426 return LIBUSB_ERROR_INVALID_PARAM;
428 config_index = get_configuration_index (dev, priv->active_config);
429 if (config_index < 0)
432 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
435 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
436 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
437 IOUSBConfigurationDescriptorPtr desc;
439 usb_device_t **device = NULL;
442 return LIBUSB_ERROR_OTHER;
445 kresult = darwin_get_device (priv->location, &device);
446 if (kresult || !device) {
447 usbi_err (DEVICE_CTX (dev), "could not find device: %s", darwin_error_str (kresult));
449 return darwin_to_libusb (kresult);
452 /* don't have to open the device to get a config descriptor */
454 device = priv->device;
456 kresult = (*device)->GetConfigurationDescriptorPtr (device, config_index, &desc);
457 if (kresult == kIOReturnSuccess) {
458 /* copy descriptor */
459 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
460 len = libusb_le16_to_cpu(desc->wTotalLength);
462 memmove (buffer, desc, len);
464 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
469 (*device)->Release (device);
471 return darwin_to_libusb (kresult);
474 /* check whether the os has configured the device */
475 static int darwin_check_configuration (struct libusb_context *ctx, struct libusb_device *dev, usb_device_t **darwin_device) {
476 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
478 IOUSBConfigurationDescriptorPtr configDesc;
479 IOUSBFindInterfaceRequest request;
480 kern_return_t kresult;
481 io_iterator_t interface_iterator;
482 io_service_t firstInterface;
484 if (priv->dev_descriptor.bNumConfigurations < 1) {
485 usbi_err (ctx, "device has no configurations");
486 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
489 /* find the first configuration */
490 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
491 priv->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
493 /* check if the device is already configured. there is probably a better way than iterating over the
494 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
495 might lock up on the device request) */
497 /* Setup the Interface Request */
498 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
499 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
500 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
501 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
503 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
505 return darwin_to_libusb (kresult);
508 firstInterface = IOIteratorNext(interface_iterator);
510 /* done with the interface iterator */
511 IOObjectRelease(interface_iterator);
513 if (firstInterface) {
514 IOObjectRelease (firstInterface);
516 /* device is configured */
517 if (priv->dev_descriptor.bNumConfigurations == 1)
518 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
519 priv->active_config = priv->first_config;
521 /* devices with more than one configuration should work with GetConfiguration */
522 (*darwin_device)->GetConfiguration (darwin_device, &priv->active_config);
525 priv->active_config = 0;
527 usbi_info (ctx, "active config: %u, first config: %u", priv->active_config, priv->first_config);
532 static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct libusb_device *dev, usb_device_t **device) {
533 struct darwin_device_priv *priv;
534 int retries = 5, delay = 30000;
535 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
540 UInt16 idProduct, idVendor;
542 (*device)->GetDeviceClass (device, &bDeviceClass);
543 (*device)->GetDeviceProduct (device, &idProduct);
544 (*device)->GetDeviceVendor (device, &idVendor);
546 priv = (struct darwin_device_priv *)dev->os_priv;
548 /* try to open the device (we can usually continue even if this fails) */
549 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
551 /**** retrieve device descriptor ****/
553 /* Set up request for device descriptor */
554 memset (&(priv->dev_descriptor), 0, sizeof(IOUSBDeviceDescriptor));
555 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
556 req.bRequest = kUSBRqGetDescriptor;
557 req.wValue = kUSBDeviceDesc << 8;
559 req.wLength = sizeof(priv->dev_descriptor);
560 req.pData = &(priv->dev_descriptor);
562 /* according to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
563 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
564 * to follow the spec as closely as possible, try opening the device */
566 ret = (*(device))->DeviceRequest (device, &req);
568 if (kIOReturnOverrun == ret && kUSBDeviceDesc == priv->dev_descriptor.bDescriptorType)
569 /* received an overrun error but we still received a device descriptor */
570 ret = kIOReturnSuccess;
572 if (kIOReturnSuccess == ret && (0 == priv->dev_descriptor.idProduct ||
573 0 == priv->dev_descriptor.bNumConfigurations ||
574 0 == priv->dev_descriptor.bcdUSB)) {
575 /* work around for incorrectly configured devices */
576 if (try_reconfigure && is_open) {
577 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
579 /* set the first configuration */
580 (*device)->SetConfiguration(device, 1);
582 /* don't try to reconfigure again */
586 ret = kIOUSBPipeStalled;
589 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
590 /* device may be suspended. unsuspend it and try again */
591 #if DeviceVersion >= 320
594 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
595 (void)(*device)->GetUSBDeviceInformation (device, &info);
597 try_unsuspend = info & (1 << kUSBInformationDeviceIsSuspendedBit);
601 /* resume the device */
602 ret2 = (*device)->USBDeviceSuspend (device, 0);
603 if (kIOReturnSuccess != ret2) {
604 /* prevent log spew from poorly behaving devices. this indicates the
605 os actually had trouble communicating with the device */
606 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
614 if (kIOReturnSuccess != ret) {
615 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
616 /* sleep for a little while before trying again */
619 } while (kIOReturnSuccess != ret && retries--);
622 /* resuspend the device */
623 (void)(*device)->USBDeviceSuspend (device, 1);
626 (void) (*device)->USBDeviceClose (device);
628 if (ret != kIOReturnSuccess) {
629 /* a debug message was already printed out for this error */
630 if (LIBUSB_CLASS_HUB == bDeviceClass)
631 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s. skipping device", idVendor, idProduct, darwin_error_str (ret));
633 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s. skipping device", idVendor, idProduct, darwin_error_str (ret));
638 usbi_dbg ("device descriptor:");
639 usbi_dbg (" bDescriptorType: 0x%02x", priv->dev_descriptor.bDescriptorType);
640 usbi_dbg (" bcdUSB: 0x%04x", priv->dev_descriptor.bcdUSB);
641 usbi_dbg (" bDeviceClass: 0x%02x", priv->dev_descriptor.bDeviceClass);
642 usbi_dbg (" bDeviceSubClass: 0x%02x", priv->dev_descriptor.bDeviceSubClass);
643 usbi_dbg (" bDeviceProtocol: 0x%02x", priv->dev_descriptor.bDeviceProtocol);
644 usbi_dbg (" bMaxPacketSize0: 0x%02x", priv->dev_descriptor.bMaxPacketSize0);
645 usbi_dbg (" idVendor: 0x%04x", priv->dev_descriptor.idVendor);
646 usbi_dbg (" idProduct: 0x%04x", priv->dev_descriptor.idProduct);
647 usbi_dbg (" bcdDevice: 0x%04x", priv->dev_descriptor.bcdDevice);
648 usbi_dbg (" iManufacturer: 0x%02x", priv->dev_descriptor.iManufacturer);
649 usbi_dbg (" iProduct: 0x%02x", priv->dev_descriptor.iProduct);
650 usbi_dbg (" iSerialNumber: 0x%02x", priv->dev_descriptor.iSerialNumber);
651 usbi_dbg (" bNumConfigurations: 0x%02x", priv->dev_descriptor.bNumConfigurations);
653 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
654 if (libusb_le16_to_cpu (priv->dev_descriptor.idProduct) != idProduct) {
655 /* not a valid device */
656 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
657 idProduct, libusb_le16_to_cpu (priv->dev_descriptor.idProduct));
664 static int process_new_device (struct libusb_context *ctx, usb_device_t **device, UInt32 locationID, struct discovered_devs **_discdevs) {
665 struct darwin_device_priv *priv;
666 struct libusb_device *dev;
667 struct discovered_devs *discdevs;
670 int ret = 0, need_unref = 0;
673 dev = usbi_get_device_by_session_id(ctx, locationID);
675 usbi_info (ctx, "allocating new device for location 0x%08x", locationID);
676 dev = usbi_alloc_device(ctx, locationID);
679 usbi_info (ctx, "using existing device for location 0x%08x", locationID);
682 ret = LIBUSB_ERROR_NO_MEM;
686 priv = (struct darwin_device_priv *)dev->os_priv;
688 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&address);
690 ret = darwin_cache_device_descriptor (ctx, dev, device);
694 /* check current active configuration (and cache the first configuration value-- which may be used by claim_interface) */
695 ret = darwin_check_configuration (ctx, dev, device);
699 dev->bus_number = locationID >> 24;
700 dev->device_address = address;
702 (*device)->GetDeviceSpeed (device, &devSpeed);
705 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
706 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
707 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
709 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
712 /* save our location, we'll need this later */
713 priv->location = locationID;
714 snprintf(priv->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", address, priv->dev_descriptor.idVendor, priv->dev_descriptor.idProduct,
715 priv->dev_descriptor.bDeviceClass, priv->dev_descriptor.bDeviceSubClass);
717 ret = usbi_sanitize_device (dev);
721 /* append the device to the list of discovered devices */
722 discdevs = discovered_devs_append(*_discdevs, dev);
724 ret = LIBUSB_ERROR_NO_MEM;
728 *_discdevs = discdevs;
730 usbi_info (ctx, "found device with address %d at %s", dev->device_address, priv->sys_path);
734 libusb_unref_device(dev);
739 static int darwin_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs) {
740 io_iterator_t deviceIterator;
741 usb_device_t **device;
742 kern_return_t kresult;
745 kresult = usb_setup_device_iterator (&deviceIterator, 0);
746 if (kresult != kIOReturnSuccess)
747 return darwin_to_libusb (kresult);
749 while ((device = usb_get_next_device (deviceIterator, &location)) != NULL) {
750 (void) process_new_device (ctx, device, location, _discdevs);
752 (*(device))->Release(device);
755 IOObjectRelease(deviceIterator);
760 static int darwin_open (struct libusb_device_handle *dev_handle) {
761 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
762 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
763 usb_device_t **darwin_device;
766 if (0 == dpriv->open_count) {
767 kresult = darwin_get_device (dpriv->location, &darwin_device);
769 usbi_err (HANDLE_CTX (dev_handle), "could not find device: %s", darwin_error_str (kresult));
770 return darwin_to_libusb (kresult);
773 dpriv->device = darwin_device;
775 /* try to open the device */
776 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
778 if (kresult != kIOReturnSuccess) {
779 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
782 case kIOReturnExclusiveAccess:
783 /* it is possible to perform some actions on a device that is not open so do not return an error */
788 (*(dpriv->device))->Release (dpriv->device);
789 dpriv->device = NULL;
790 return darwin_to_libusb (kresult);
793 /* create async event source */
794 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
795 if (kresult != kIOReturnSuccess) {
796 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
798 (*(dpriv->device))->USBDeviceClose (dpriv->device);
799 (*(dpriv->device))->Release (dpriv->device);
801 dpriv->device = NULL;
802 return darwin_to_libusb (kresult);
807 CFRetain (libusb_darwin_acfl);
809 /* add the cfSource to the aync run loop */
810 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
814 /* device opened successfully */
817 /* create a file descriptor for notifications */
820 /* set the pipe to be non-blocking */
821 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
823 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
825 usbi_info (HANDLE_CTX (dev_handle), "device open for access");
830 static void darwin_close (struct libusb_device_handle *dev_handle) {
831 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
832 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
836 if (dpriv->open_count == 0) {
837 /* something is probably very wrong if this is the case */
838 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
844 /* make sure all interfaces are released */
845 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
846 if (dev_handle->claimed_interfaces & (1 << i))
847 libusb_release_interface (dev_handle, i);
849 if (0 == dpriv->open_count) {
851 /* delete the device's async event source */
852 if (priv->cfSource) {
853 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
854 CFRelease (priv->cfSource);
857 /* close the device */
858 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
860 /* Log the fact that we had a problem closing the file, however failing a
861 * close isn't really an error, so return success anyway */
862 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
866 kresult = (*(dpriv->device))->Release(dpriv->device);
868 /* Log the fact that we had a problem closing the file, however failing a
869 * close isn't really an error, so return success anyway */
870 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
873 dpriv->device = NULL;
876 /* file descriptors are maintained per-instance */
877 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
878 close (priv->fds[1]);
879 close (priv->fds[0]);
881 priv->fds[0] = priv->fds[1] = -1;
884 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
885 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
887 *config = (int) dpriv->active_config;
892 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
893 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
897 /* Setting configuration will invalidate the interface, so we need
898 to reclaim it. First, dispose of existing interfaces, if any. */
899 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
900 if (dev_handle->claimed_interfaces & (1 << i))
901 darwin_release_interface (dev_handle, i);
903 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
904 if (kresult != kIOReturnSuccess)
905 return darwin_to_libusb (kresult);
907 /* Reclaim any interfaces. */
908 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
909 if (dev_handle->claimed_interfaces & (1 << i))
910 darwin_claim_interface (dev_handle, i);
912 dpriv->active_config = config;
917 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
918 IOUSBFindInterfaceRequest request;
919 uint8_t current_interface;
920 kern_return_t kresult;
921 io_iterator_t interface_iterator;
923 *usbInterfacep = IO_OBJECT_NULL;
925 /* Setup the Interface Request */
926 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
927 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
928 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
929 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
931 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
935 for ( current_interface = 0 ; current_interface <= ifc ; current_interface++ ) {
936 *usbInterfacep = IOIteratorNext(interface_iterator);
937 if (current_interface != ifc)
938 (void) IOObjectRelease (*usbInterfacep);
941 /* done with the interface iterator */
942 IOObjectRelease(interface_iterator);
947 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
948 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
950 /* current interface */
951 struct darwin_interface *cInterface = &priv->interfaces[iface];
953 kern_return_t kresult;
955 u_int8_t numep, direction, number;
956 u_int8_t dont_care1, dont_care3;
957 u_int16_t dont_care2;
960 usbi_info (HANDLE_CTX (dev_handle), "building table of endpoints.");
962 /* retrieve the total number of endpoints on this interface */
963 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
965 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
966 return darwin_to_libusb (kresult);
969 /* iterate through pipe references */
970 for (i = 1 ; i <= numep ; i++) {
971 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
972 &dont_care2, &dont_care3);
974 if (kresult != kIOReturnSuccess) {
975 usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
977 return darwin_to_libusb (kresult);
980 usbi_info (HANDLE_CTX (dev_handle), "interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
982 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
985 cInterface->num_endpoints = numep;
990 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
991 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
992 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
993 io_service_t usbInterface = IO_OBJECT_NULL;
995 IOCFPlugInInterface **plugInInterface = NULL;
998 /* current interface */
999 struct darwin_interface *cInterface = &priv->interfaces[iface];
1001 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1002 if (kresult != kIOReturnSuccess)
1003 return darwin_to_libusb (kresult);
1005 /* make sure we have an interface */
1006 if (!usbInterface && dpriv->first_config != 0) {
1007 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1009 /* set the configuration */
1010 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1011 if (kresult != LIBUSB_SUCCESS) {
1012 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1016 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1018 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1019 return darwin_to_libusb (kresult);
1023 if (!usbInterface) {
1024 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1025 return LIBUSB_ERROR_NOT_FOUND;
1028 /* get an interface to the device's interface */
1029 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1030 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1032 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1033 return darwin_to_libusb (kresult);
1036 if (!plugInInterface) {
1037 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1038 return LIBUSB_ERROR_NOT_FOUND;
1041 /* ignore release error */
1042 (void)IOObjectRelease (usbInterface);
1044 /* Do the actual claim */
1045 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1046 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1047 (LPVOID)&cInterface->interface);
1048 /* We no longer need the intermediate plug-in */
1049 IODestroyPlugInInterface (plugInInterface);
1050 if (kresult || !cInterface->interface) {
1051 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1052 return darwin_to_libusb (kresult);
1055 /* claim the interface */
1056 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1058 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1059 return darwin_to_libusb (kresult);
1062 /* update list of endpoints */
1063 kresult = get_endpoints (dev_handle, iface);
1065 /* this should not happen */
1066 darwin_release_interface (dev_handle, iface);
1067 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1071 cInterface->cfSource = NULL;
1073 /* create async event source */
1074 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1075 if (kresult != kIOReturnSuccess) {
1076 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1078 /* can't continue without an async event source */
1079 (void)darwin_release_interface (dev_handle, iface);
1081 return darwin_to_libusb (kresult);
1084 /* add the cfSource to the async thread's run loop */
1085 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1087 usbi_info (HANDLE_CTX (dev_handle), "interface opened");
1092 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1093 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1096 /* current interface */
1097 struct darwin_interface *cInterface = &priv->interfaces[iface];
1099 /* Check to see if an interface is open */
1100 if (!cInterface->interface)
1101 return LIBUSB_SUCCESS;
1103 /* clean up endpoint data */
1104 cInterface->num_endpoints = 0;
1106 /* delete the interface's async event source */
1107 if (cInterface->cfSource) {
1108 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1109 CFRelease (cInterface->cfSource);
1112 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1114 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1116 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1117 if (kresult != kIOReturnSuccess)
1118 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1120 cInterface->interface = IO_OBJECT_NULL;
1122 return darwin_to_libusb (kresult);
1125 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1126 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1129 /* current interface */
1130 struct darwin_interface *cInterface = &priv->interfaces[iface];
1132 if (!cInterface->interface)
1133 return LIBUSB_ERROR_NO_DEVICE;
1135 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1136 if (kresult != kIOReturnSuccess)
1137 darwin_reset_device (dev_handle);
1139 /* update list of endpoints */
1140 kresult = get_endpoints (dev_handle, iface);
1142 /* this should not happen */
1143 darwin_release_interface (dev_handle, iface);
1144 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1148 return darwin_to_libusb (kresult);
1151 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1152 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1154 /* current interface */
1155 struct darwin_interface *cInterface;
1156 uint8_t pipeRef, iface;
1159 /* determine the interface/endpoint to use */
1160 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
1161 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1163 return LIBUSB_ERROR_NOT_FOUND;
1166 cInterface = &priv->interfaces[iface];
1168 #if (InterfaceVersion < 190)
1169 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1171 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1172 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1175 usbi_err (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1177 return darwin_to_libusb (kresult);
1180 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1181 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1184 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1186 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1188 return darwin_to_libusb (kresult);
1191 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1192 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1193 io_service_t usbInterface;
1197 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1199 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1201 return darwin_to_libusb (kresult);
1204 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1205 IOObjectRelease (usbInterface);
1217 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1218 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1219 return LIBUSB_ERROR_NOT_SUPPORTED;
1222 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1223 return LIBUSB_ERROR_NOT_SUPPORTED;
1226 static void darwin_destroy_device(struct libusb_device *dev) {
1229 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1230 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1231 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1234 uint8_t is_read; /* 0 = we're reading, 1 = we're writing */
1235 uint8_t transferType;
1236 /* None of the values below are used in libusb for bulk transfers */
1237 uint8_t direction, number, interval, pipeRef, iface;
1238 uint16_t maxPacketSize;
1240 struct darwin_interface *cInterface;
1242 /* are we reading or writing? */
1243 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1245 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1246 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1248 return LIBUSB_ERROR_NOT_FOUND;
1251 cInterface = &priv->interfaces[iface];
1253 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1254 &transferType, &maxPacketSize, &interval);
1256 /* submit the request */
1257 /* timeouts are unavailable on interrupt endpoints */
1258 if (transferType == kUSBInterrupt) {
1260 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1261 transfer->length, darwin_async_io_callback, itransfer);
1263 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1264 transfer->length, darwin_async_io_callback, itransfer);
1266 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1269 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1270 transfer->length, transfer->timeout, transfer->timeout,
1271 darwin_async_io_callback, (void *)itransfer);
1273 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1274 transfer->length, transfer->timeout, transfer->timeout,
1275 darwin_async_io_callback, (void *)itransfer);
1279 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", is_read ? "In" : "Out",
1280 darwin_error_str(ret), ret);
1282 return darwin_to_libusb (ret);
1285 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1286 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1287 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1288 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1291 uint8_t is_read; /* 0 = we're writing, 1 = we're reading */
1292 uint8_t pipeRef, iface;
1294 AbsoluteTime atTime;
1297 struct darwin_interface *cInterface;
1299 /* are we reading or writing? */
1300 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1302 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1303 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1304 free(tpriv->isoc_framelist);
1305 tpriv->isoc_framelist = NULL;
1308 if (!tpriv->isoc_framelist) {
1309 tpriv->num_iso_packets = transfer->num_iso_packets;
1310 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1311 if (!tpriv->isoc_framelist)
1312 return LIBUSB_ERROR_NO_MEM;
1315 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1316 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1317 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1319 /* determine the interface/endpoint to use */
1320 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1321 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1323 return LIBUSB_ERROR_NOT_FOUND;
1326 cInterface = &priv->interfaces[iface];
1328 /* Last but not least we need the bus frame number */
1329 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1331 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1332 free(tpriv->isoc_framelist);
1333 tpriv->isoc_framelist = NULL;
1335 return darwin_to_libusb (kresult);
1338 /* schedule for a frame a little in the future */
1341 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1342 frame = cInterface->frames[transfer->endpoint];
1344 /* submit the request */
1346 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1347 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1350 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1351 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1354 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets / 8;
1356 if (kresult != kIOReturnSuccess) {
1357 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", is_read ? "In" : "Out",
1358 darwin_error_str(kresult));
1359 free (tpriv->isoc_framelist);
1360 tpriv->isoc_framelist = NULL;
1363 return darwin_to_libusb (kresult);
1366 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1367 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1368 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1369 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1370 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1371 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1375 bzero(&tpriv->req, sizeof(tpriv->req));
1377 /* IOUSBDeviceInterface expects the request in cpu endianess */
1378 tpriv->req.bmRequestType = setup->bmRequestType;
1379 tpriv->req.bRequest = setup->bRequest;
1380 /* these values should be in bus order from libusb_fill_control_setup */
1381 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1382 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1383 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1384 /* data is stored after the libusb control block */
1385 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1386 tpriv->req.completionTimeout = transfer->timeout;
1387 tpriv->req.noDataTimeout = transfer->timeout;
1389 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1391 /* all transfers in libusb-1.0 are async */
1393 if (transfer->endpoint) {
1394 struct darwin_interface *cInterface;
1395 uint8_t pipeRef, iface;
1397 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1398 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1400 return LIBUSB_ERROR_NOT_FOUND;
1403 cInterface = &priv->interfaces[iface];
1405 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1407 /* control request on endpoint 0 */
1408 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1410 if (kresult != kIOReturnSuccess)
1411 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1413 return darwin_to_libusb (kresult);
1416 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1417 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1419 switch (transfer->type) {
1420 case LIBUSB_TRANSFER_TYPE_CONTROL:
1421 return submit_control_transfer(itransfer);
1422 case LIBUSB_TRANSFER_TYPE_BULK:
1423 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1424 return submit_bulk_transfer(itransfer);
1425 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1426 return submit_iso_transfer(itransfer);
1428 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1429 return LIBUSB_ERROR_INVALID_PARAM;
1433 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1434 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1435 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1438 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions control pipe");
1440 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1442 return darwin_to_libusb (kresult);
1445 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1446 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1447 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1448 struct darwin_interface *cInterface;
1449 uint8_t pipeRef, iface;
1452 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1453 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1455 return LIBUSB_ERROR_NOT_FOUND;
1458 cInterface = &priv->interfaces[iface];
1460 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions on interface %d pipe %d", iface, pipeRef);
1462 /* abort transactions */
1463 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1465 usbi_info (ITRANSFER_CTX (itransfer), "calling clear pipe stall to clear the data toggle bit");
1467 /* clear the data toggle bit */
1468 #if (InterfaceVersion < 190)
1469 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1471 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1472 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1475 return darwin_to_libusb (kresult);
1478 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1479 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1481 switch (transfer->type) {
1482 case LIBUSB_TRANSFER_TYPE_CONTROL:
1483 return cancel_control_transfer(itransfer);
1484 case LIBUSB_TRANSFER_TYPE_BULK:
1485 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1486 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1487 return darwin_abort_transfers (itransfer);
1489 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1490 return LIBUSB_ERROR_INVALID_PARAM;
1494 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1495 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1496 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1498 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1499 free (tpriv->isoc_framelist);
1500 tpriv->isoc_framelist = NULL;
1504 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1505 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1506 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1507 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1510 usbi_info (ITRANSFER_CTX (itransfer), "an async io operation has completed");
1512 /* send a completion message to the device's file descriptor */
1513 message = MESSAGE_ASYNC_IO_COMPLETE;
1514 write (priv->fds[1], &message, sizeof (message));
1515 write (priv->fds[1], &itransfer, sizeof (itransfer));
1516 write (priv->fds[1], &result, sizeof (IOReturn));
1517 write (priv->fds[1], &arg0, sizeof (UInt32));
1520 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1521 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT)
1522 result = kIOUSBTransactionTimeout;
1525 case kIOReturnUnderrun:
1526 case kIOReturnSuccess:
1527 return LIBUSB_TRANSFER_COMPLETED;
1528 case kIOReturnAborted:
1529 return LIBUSB_TRANSFER_CANCELLED;
1530 case kIOUSBPipeStalled:
1531 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: pipe is stalled");
1532 return LIBUSB_TRANSFER_STALL;
1533 case kIOReturnOverrun:
1534 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1535 return LIBUSB_TRANSFER_OVERFLOW;
1536 case kIOUSBTransactionTimeout:
1537 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1538 itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
1539 return LIBUSB_TRANSFER_TIMED_OUT;
1541 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1542 return LIBUSB_TRANSFER_ERROR;
1546 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1547 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1548 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1549 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1550 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1551 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1552 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1555 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1556 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1560 usbi_info (ITRANSFER_CTX (itransfer), "handling %s completion with kernel status %d",
1561 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
1563 if (kIOReturnSuccess == result || kIOReturnUnderrun == result) {
1564 if (isIsoc && tpriv->isoc_framelist) {
1565 /* copy isochronous results back */
1567 for (i = 0; i < transfer->num_iso_packets ; i++) {
1568 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1569 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1570 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1573 itransfer->transferred += io_size;
1576 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1577 usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
1580 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready) {
1581 struct usbi_transfer *itransfer;
1587 usbi_mutex_lock(&ctx->open_devs_lock);
1588 for (i = 0; i < nfds && num_ready > 0; i++) {
1589 struct pollfd *pollfd = &fds[i];
1590 struct libusb_device_handle *handle;
1591 struct darwin_device_handle_priv *hpriv = NULL;
1593 usbi_info (ctx, "checking fd %i with revents = %x", fds[i], pollfd->revents);
1595 if (!pollfd->revents)
1599 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
1600 hpriv = (struct darwin_device_handle_priv *)handle->os_priv;
1601 if (hpriv->fds[0] == pollfd->fd)
1605 if (!(pollfd->revents & POLLERR)) {
1606 ret = read (hpriv->fds[0], &message, sizeof (message));
1607 if (ret < sizeof (message))
1610 /* could not poll the device-- response is to delete the device (this seems a little heavy-handed) */
1611 message = MESSAGE_DEVICE_GONE;
1614 case MESSAGE_DEVICE_GONE:
1615 /* remove the device's async port from the runloop */
1616 if (hpriv->cfSource) {
1617 if (libusb_darwin_acfl)
1618 CFRunLoopRemoveSource (libusb_darwin_acfl, hpriv->cfSource, kCFRunLoopDefaultMode);
1619 CFRelease (hpriv->cfSource);
1620 hpriv->cfSource = NULL;
1623 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1624 usbi_handle_disconnect(handle);
1626 /* done with this device */
1628 case MESSAGE_ASYNC_IO_COMPLETE:
1629 read (hpriv->fds[0], &itransfer, sizeof (itransfer));
1630 read (hpriv->fds[0], &kresult, sizeof (IOReturn));
1631 read (hpriv->fds[0], &io_size, sizeof (UInt32));
1633 darwin_handle_callback (itransfer, kresult, io_size);
1636 usbi_err (ctx, "unknown message received from device pipe");
1640 usbi_mutex_unlock(&ctx->open_devs_lock);
1645 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1646 mach_timespec_t sys_time;
1647 clock_serv_t clock_ref;
1650 case USBI_CLOCK_REALTIME:
1651 /* CLOCK_REALTIME represents time since the epoch */
1652 host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &clock_ref);
1654 case USBI_CLOCK_MONOTONIC:
1655 /* use system boot time as reference for the monotonic clock */
1656 host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &clock_ref);
1659 return LIBUSB_ERROR_INVALID_PARAM;
1662 clock_get_time (clock_ref, &sys_time);
1664 tp->tv_sec = sys_time.tv_sec;
1665 tp->tv_nsec = sys_time.tv_nsec;
1670 const struct usbi_os_backend darwin_backend = {
1672 .init = darwin_init,
1673 .exit = darwin_exit,
1674 .get_device_list = darwin_get_device_list,
1675 .get_device_descriptor = darwin_get_device_descriptor,
1676 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1677 .get_config_descriptor = darwin_get_config_descriptor,
1679 .open = darwin_open,
1680 .close = darwin_close,
1681 .get_configuration = darwin_get_configuration,
1682 .set_configuration = darwin_set_configuration,
1683 .claim_interface = darwin_claim_interface,
1684 .release_interface = darwin_release_interface,
1686 .set_interface_altsetting = darwin_set_interface_altsetting,
1687 .clear_halt = darwin_clear_halt,
1688 .reset_device = darwin_reset_device,
1690 .kernel_driver_active = darwin_kernel_driver_active,
1691 .detach_kernel_driver = darwin_detach_kernel_driver,
1692 .attach_kernel_driver = darwin_attach_kernel_driver,
1694 .destroy_device = darwin_destroy_device,
1696 .submit_transfer = darwin_submit_transfer,
1697 .cancel_transfer = darwin_cancel_transfer,
1698 .clear_transfer_priv = darwin_clear_transfer_priv,
1700 .handle_events = op_handle_events,
1702 .clock_gettime = darwin_clock_gettime,
1704 .device_priv_size = sizeof(struct darwin_device_priv),
1705 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1706 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1707 .add_iso_packet_size = 0,