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,
195 if (kIOReturnSuccess == result && plugInInterface)
198 usbi_dbg ("libusb/darwin.c usb_get_next_device: could not set up plugin for service: %s\n", darwin_error_str (result));
204 (void)IOObjectRelease(usbDevice);
205 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
208 (*plugInInterface)->Stop(plugInInterface);
209 IODestroyPlugInInterface (plugInInterface);
211 /* get the location from the device */
213 (*(device))->GetLocationID(device, locationp);
218 static kern_return_t darwin_get_device (uint32_t dev_location, usb_device_t ***darwin_device) {
219 kern_return_t kresult;
221 io_iterator_t deviceIterator;
223 kresult = usb_setup_device_iterator (&deviceIterator, dev_location);
227 /* This port of libusb uses locations to keep track of devices. */
228 while ((*darwin_device = usb_get_next_device (deviceIterator, &location)) != NULL) {
229 if (location == dev_location)
232 (**darwin_device)->Release(*darwin_device);
235 IOObjectRelease (deviceIterator);
237 if (!(*darwin_device))
238 return kIOReturnNoDevice;
240 return kIOReturnSuccess;
245 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
246 struct libusb_context *ctx = (struct libusb_context *)ptr;
247 struct libusb_device_handle *handle;
248 struct darwin_device_priv *dpriv;
249 struct darwin_device_handle_priv *priv;
254 CFTypeRef locationCF;
257 usbi_info (ctx, "a device has been detached");
259 while ((device = IOIteratorNext (rem_devices)) != 0) {
260 /* get the location from the i/o registry */
261 locationCF = IORegistryEntryCreateCFProperty (device, CFSTR(kUSBDevicePropertyLocationID), kCFAllocatorDefault, 0);
263 IOObjectRelease (device);
268 locationValid = CFGetTypeID(locationCF) == CFNumberGetTypeID() &&
269 CFNumberGetValue(locationCF, kCFNumberLongType, &location);
271 CFRelease (locationCF);
276 usbi_mutex_lock(&ctx->open_devs_lock);
277 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
278 dpriv = (struct darwin_device_priv *)handle->dev->os_priv;
280 /* the device may have been opened several times. write to each handle's event descriptor */
281 if (dpriv->location == location && handle->os_priv) {
282 priv = (struct darwin_device_handle_priv *)handle->os_priv;
284 message = MESSAGE_DEVICE_GONE;
285 write (priv->fds[1], &message, sizeof (message));
289 usbi_mutex_unlock(&ctx->open_devs_lock);
293 static void darwin_clear_iterator (io_iterator_t iter) {
296 while ((device = IOIteratorNext (iter)) != 0)
297 IOObjectRelease (device);
300 static void *event_thread_main (void *arg0) {
302 struct libusb_context *ctx = (struct libusb_context *)arg0;
303 CFRunLoopRef runloop;
305 /* Tell the Objective-C garbage collector about this thread.
306 This is required because, unlike NSThreads, pthreads are
307 not automatically registered. Although we don't use
308 Objective-C, we use CoreFoundation, which does. */
309 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
310 objc_registerThreadWithCollector();
313 /* hotplug (device removal) source */
314 CFRunLoopSourceRef libusb_notification_cfsource;
315 io_notification_port_t libusb_notification_port;
316 io_iterator_t libusb_rem_device_iterator;
318 usbi_info (ctx, "creating hotplug event source");
320 runloop = CFRunLoopGetCurrent ();
323 /* add the notification port to the run loop */
324 libusb_notification_port = IONotificationPortCreate (kIOMasterPortDefault);
325 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
326 CFRunLoopAddSource(CFRunLoopGetCurrent (), libusb_notification_cfsource, kCFRunLoopDefaultMode);
328 /* create notifications for removed devices */
329 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
330 IOServiceMatching(kIOUSBDeviceClassName),
331 (IOServiceMatchingCallback)darwin_devices_detached,
332 (void *)ctx, &libusb_rem_device_iterator);
334 if (kresult != kIOReturnSuccess) {
335 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
341 darwin_clear_iterator (libusb_rem_device_iterator);
343 /* let the main thread know about the async runloop */
344 libusb_darwin_acfl = CFRunLoopGetCurrent ();
346 usbi_info (ctx, "thread ready to receive events");
348 /* run the runloop */
351 usbi_info (ctx, "thread exiting");
353 /* delete notification port */
354 CFRunLoopSourceInvalidate (libusb_notification_cfsource);
355 IONotificationPortDestroy (libusb_notification_port);
359 libusb_darwin_acfl = NULL;
364 static int darwin_init(struct libusb_context *ctx) {
367 if (!(initCount++)) {
368 pthread_create (&libusb_darwin_at, NULL, event_thread_main, (void *)ctx);
370 while (!libusb_darwin_acfl)
377 static void darwin_exit (void) {
378 if (!(--initCount)) {
380 /* stop the async runloop */
381 CFRunLoopStop (libusb_darwin_acfl);
382 pthread_join (libusb_darwin_at, NULL);
386 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
387 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
389 /* return cached copy */
390 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
397 static int get_configuration_index (struct libusb_device *dev, int config_value) {
398 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
400 IOUSBConfigurationDescriptorPtr desc;
403 /* is there a simpler way to determine the index? */
404 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
405 if (kresult != kIOReturnSuccess)
406 return darwin_to_libusb (kresult);
408 for (i = 0 ; i < numConfig ; i++) {
409 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
411 if (desc->bConfigurationValue == config_value)
415 /* configuration not found */
416 return LIBUSB_ERROR_OTHER;
419 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
420 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
423 if (0 == priv->active_config)
424 return LIBUSB_ERROR_INVALID_PARAM;
426 config_index = get_configuration_index (dev, priv->active_config);
427 if (config_index < 0)
430 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
433 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
434 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
435 IOUSBConfigurationDescriptorPtr desc;
437 usb_device_t **device = NULL;
440 return LIBUSB_ERROR_OTHER;
443 kresult = darwin_get_device (priv->location, &device);
444 if (kresult || !device) {
445 usbi_err (DEVICE_CTX (dev), "could not find device: %s", darwin_error_str (kresult));
447 return darwin_to_libusb (kresult);
450 /* don't have to open the device to get a config descriptor */
452 device = priv->device;
454 kresult = (*device)->GetConfigurationDescriptorPtr (device, config_index, &desc);
455 if (kresult == kIOReturnSuccess) {
456 /* copy descriptor */
457 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
458 len = libusb_le16_to_cpu(desc->wTotalLength);
460 memmove (buffer, desc, len);
462 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
467 (*device)->Release (device);
469 return darwin_to_libusb (kresult);
472 /* check whether the os has configured the device */
473 static int darwin_check_configuration (struct libusb_context *ctx, struct libusb_device *dev, usb_device_t **darwin_device) {
474 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
476 IOUSBConfigurationDescriptorPtr configDesc;
477 IOUSBFindInterfaceRequest request;
478 kern_return_t kresult;
479 io_iterator_t interface_iterator;
480 io_service_t firstInterface;
482 if (priv->dev_descriptor.bNumConfigurations < 1) {
483 usbi_err (ctx, "device has no configurations");
484 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
487 /* find the first configuration */
488 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
489 priv->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
491 /* check if the device is already configured. there is probably a better way than iterating over the
492 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
493 might lock up on the device request) */
495 /* Setup the Interface Request */
496 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
497 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
498 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
499 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
501 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
503 return darwin_to_libusb (kresult);
506 firstInterface = IOIteratorNext(interface_iterator);
508 /* done with the interface iterator */
509 IOObjectRelease(interface_iterator);
511 if (firstInterface) {
512 IOObjectRelease (firstInterface);
514 /* device is configured */
515 if (priv->dev_descriptor.bNumConfigurations == 1)
516 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
517 priv->active_config = priv->first_config;
519 /* devices with more than one configuration should work with GetConfiguration */
520 (*darwin_device)->GetConfiguration (darwin_device, &priv->active_config);
523 priv->active_config = 0;
525 usbi_info (ctx, "active config: %u, first config: %u", priv->active_config, priv->first_config);
530 static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct libusb_device *dev, usb_device_t **device) {
531 struct darwin_device_priv *priv;
532 int retries = 5, delay = 30000;
533 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
538 UInt16 idProduct, idVendor;
540 (*device)->GetDeviceClass (device, &bDeviceClass);
541 (*device)->GetDeviceProduct (device, &idProduct);
542 (*device)->GetDeviceVendor (device, &idVendor);
544 priv = (struct darwin_device_priv *)dev->os_priv;
546 /* try to open the device (we can usually continue even if this fails) */
547 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
549 /**** retrieve device descriptor ****/
551 /* Set up request for device descriptor */
552 memset (&(priv->dev_descriptor), 0, sizeof(IOUSBDeviceDescriptor));
553 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
554 req.bRequest = kUSBRqGetDescriptor;
555 req.wValue = kUSBDeviceDesc << 8;
557 req.wLength = sizeof(priv->dev_descriptor);
558 req.pData = &(priv->dev_descriptor);
560 /* according to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
561 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
562 * to follow the spec as closely as possible, try opening the device */
564 ret = (*(device))->DeviceRequest (device, &req);
566 if (kIOReturnOverrun == ret && kUSBDeviceDesc == priv->dev_descriptor.bDescriptorType)
567 /* received an overrun error but we still received a device descriptor */
568 ret = kIOReturnSuccess;
570 if (kIOReturnSuccess == ret && (0 == priv->dev_descriptor.idProduct ||
571 0 == priv->dev_descriptor.bNumConfigurations ||
572 0 == priv->dev_descriptor.bcdUSB)) {
573 /* work around for incorrectly configured devices */
574 if (try_reconfigure && is_open) {
575 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
577 /* set the first configuration */
578 (*device)->SetConfiguration(device, 1);
580 /* don't try to reconfigure again */
584 ret = kIOUSBPipeStalled;
587 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
588 /* device may be suspended. unsuspend it and try again */
589 #if DeviceVersion >= 320
592 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
593 (void)(*device)->GetUSBDeviceInformation (device, &info);
595 try_unsuspend = info & (1 << kUSBInformationDeviceIsSuspendedBit);
599 /* resume the device */
600 ret2 = (*device)->USBDeviceSuspend (device, 0);
601 if (kIOReturnSuccess != ret2) {
602 /* prevent log spew from poorly behaving devices. this indicates the
603 os actually had trouble communicating with the device */
604 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
612 if (kIOReturnSuccess != ret) {
613 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
614 /* sleep for a little while before trying again */
617 } while (kIOReturnSuccess != ret && retries--);
620 /* resuspend the device */
621 (void)(*device)->USBDeviceSuspend (device, 1);
624 (void) (*device)->USBDeviceClose (device);
626 if (ret != kIOReturnSuccess) {
627 /* a debug message was already printed out for this error */
628 if (LIBUSB_CLASS_HUB == bDeviceClass)
629 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s. skipping device", idVendor, idProduct, darwin_error_str (ret));
631 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s. skipping device", idVendor, idProduct, darwin_error_str (ret));
636 usbi_dbg ("device descriptor:");
637 usbi_dbg (" bDescriptorType: 0x%02x", priv->dev_descriptor.bDescriptorType);
638 usbi_dbg (" bcdUSB: 0x%04x", priv->dev_descriptor.bcdUSB);
639 usbi_dbg (" bDeviceClass: 0x%02x", priv->dev_descriptor.bDeviceClass);
640 usbi_dbg (" bDeviceSubClass: 0x%02x", priv->dev_descriptor.bDeviceSubClass);
641 usbi_dbg (" bDeviceProtocol: 0x%02x", priv->dev_descriptor.bDeviceProtocol);
642 usbi_dbg (" bMaxPacketSize0: 0x%02x", priv->dev_descriptor.bMaxPacketSize0);
643 usbi_dbg (" idVendor: 0x%04x", priv->dev_descriptor.idVendor);
644 usbi_dbg (" idProduct: 0x%04x", priv->dev_descriptor.idProduct);
645 usbi_dbg (" bcdDevice: 0x%04x", priv->dev_descriptor.bcdDevice);
646 usbi_dbg (" iManufacturer: 0x%02x", priv->dev_descriptor.iManufacturer);
647 usbi_dbg (" iProduct: 0x%02x", priv->dev_descriptor.iProduct);
648 usbi_dbg (" iSerialNumber: 0x%02x", priv->dev_descriptor.iSerialNumber);
649 usbi_dbg (" bNumConfigurations: 0x%02x", priv->dev_descriptor.bNumConfigurations);
651 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
652 if (libusb_le16_to_cpu (priv->dev_descriptor.idProduct) != idProduct) {
653 /* not a valid device */
654 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
655 idProduct, libusb_le16_to_cpu (priv->dev_descriptor.idProduct));
662 static int process_new_device (struct libusb_context *ctx, usb_device_t **device, UInt32 locationID, struct discovered_devs **_discdevs) {
663 struct darwin_device_priv *priv;
664 struct libusb_device *dev;
665 struct discovered_devs *discdevs;
668 int ret = 0, need_unref = 0;
671 dev = usbi_get_device_by_session_id(ctx, locationID);
673 usbi_info (ctx, "allocating new device for location 0x%08x", locationID);
674 dev = usbi_alloc_device(ctx, locationID);
677 usbi_info (ctx, "using existing device for location 0x%08x", locationID);
680 ret = LIBUSB_ERROR_NO_MEM;
684 priv = (struct darwin_device_priv *)dev->os_priv;
686 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&address);
688 ret = darwin_cache_device_descriptor (ctx, dev, device);
692 /* check current active configuration (and cache the first configuration value-- which may be used by claim_interface) */
693 ret = darwin_check_configuration (ctx, dev, device);
697 dev->bus_number = locationID >> 24;
698 dev->device_address = address;
700 (*device)->GetDeviceSpeed (device, &devSpeed);
703 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
704 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
705 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
707 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
710 /* save our location, we'll need this later */
711 priv->location = locationID;
712 snprintf(priv->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", address, priv->dev_descriptor.idVendor, priv->dev_descriptor.idProduct,
713 priv->dev_descriptor.bDeviceClass, priv->dev_descriptor.bDeviceSubClass);
715 ret = usbi_sanitize_device (dev);
719 /* append the device to the list of discovered devices */
720 discdevs = discovered_devs_append(*_discdevs, dev);
722 ret = LIBUSB_ERROR_NO_MEM;
726 *_discdevs = discdevs;
728 usbi_info (ctx, "found device with address %d at %s", dev->device_address, priv->sys_path);
732 libusb_unref_device(dev);
737 static int darwin_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs) {
738 io_iterator_t deviceIterator;
739 usb_device_t **device;
740 kern_return_t kresult;
743 kresult = usb_setup_device_iterator (&deviceIterator, 0);
744 if (kresult != kIOReturnSuccess)
745 return darwin_to_libusb (kresult);
747 while ((device = usb_get_next_device (deviceIterator, &location)) != NULL) {
748 (void) process_new_device (ctx, device, location, _discdevs);
750 (*(device))->Release(device);
753 IOObjectRelease(deviceIterator);
758 static int darwin_open (struct libusb_device_handle *dev_handle) {
759 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
760 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
761 usb_device_t **darwin_device;
764 if (0 == dpriv->open_count) {
765 kresult = darwin_get_device (dpriv->location, &darwin_device);
767 usbi_err (HANDLE_CTX (dev_handle), "could not find device: %s", darwin_error_str (kresult));
768 return darwin_to_libusb (kresult);
771 dpriv->device = darwin_device;
773 /* try to open the device */
774 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
776 if (kresult != kIOReturnSuccess) {
777 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
780 case kIOReturnExclusiveAccess:
781 /* it is possible to perform some actions on a device that is not open so do not return an error */
786 (*(dpriv->device))->Release (dpriv->device);
787 dpriv->device = NULL;
788 return darwin_to_libusb (kresult);
791 /* create async event source */
792 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
793 if (kresult != kIOReturnSuccess) {
794 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
796 (*(dpriv->device))->USBDeviceClose (dpriv->device);
797 (*(dpriv->device))->Release (dpriv->device);
799 dpriv->device = NULL;
800 return darwin_to_libusb (kresult);
805 CFRetain (libusb_darwin_acfl);
807 /* add the cfSource to the aync run loop */
808 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
812 /* device opened successfully */
815 /* create a file descriptor for notifications */
818 /* set the pipe to be non-blocking */
819 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
821 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
823 usbi_info (HANDLE_CTX (dev_handle), "device open for access");
828 static void darwin_close (struct libusb_device_handle *dev_handle) {
829 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
830 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
834 if (dpriv->open_count == 0) {
835 /* something is probably very wrong if this is the case */
836 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
842 /* make sure all interfaces are released */
843 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
844 if (dev_handle->claimed_interfaces & (1 << i))
845 libusb_release_interface (dev_handle, i);
847 if (0 == dpriv->open_count) {
849 /* delete the device's async event source */
850 if (priv->cfSource) {
851 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
852 CFRelease (priv->cfSource);
855 /* close the device */
856 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
858 /* Log the fact that we had a problem closing the file, however failing a
859 * close isn't really an error, so return success anyway */
860 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
864 kresult = (*(dpriv->device))->Release(dpriv->device);
866 /* Log the fact that we had a problem closing the file, however failing a
867 * close isn't really an error, so return success anyway */
868 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
871 dpriv->device = NULL;
874 /* file descriptors are maintained per-instance */
875 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
876 close (priv->fds[1]);
877 close (priv->fds[0]);
879 priv->fds[0] = priv->fds[1] = -1;
882 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
883 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
885 *config = (int) dpriv->active_config;
890 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
891 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
895 /* Setting configuration will invalidate the interface, so we need
896 to reclaim it. First, dispose of existing interfaces, if any. */
897 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
898 if (dev_handle->claimed_interfaces & (1 << i))
899 darwin_release_interface (dev_handle, i);
901 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
902 if (kresult != kIOReturnSuccess)
903 return darwin_to_libusb (kresult);
905 /* Reclaim any interfaces. */
906 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
907 if (dev_handle->claimed_interfaces & (1 << i))
908 darwin_claim_interface (dev_handle, i);
910 dpriv->active_config = config;
915 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
916 IOUSBFindInterfaceRequest request;
917 uint8_t current_interface;
918 kern_return_t kresult;
919 io_iterator_t interface_iterator;
921 *usbInterfacep = IO_OBJECT_NULL;
923 /* Setup the Interface Request */
924 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
925 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
926 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
927 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
929 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
933 for ( current_interface = 0 ; current_interface <= ifc ; current_interface++ ) {
934 *usbInterfacep = IOIteratorNext(interface_iterator);
935 if (current_interface != ifc)
936 (void) IOObjectRelease (*usbInterfacep);
939 /* done with the interface iterator */
940 IOObjectRelease(interface_iterator);
945 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
946 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
948 /* current interface */
949 struct __darwin_interface *cInterface = &priv->interfaces[iface];
951 kern_return_t kresult;
953 u_int8_t numep, direction, number;
954 u_int8_t dont_care1, dont_care3;
955 u_int16_t dont_care2;
958 usbi_info (HANDLE_CTX (dev_handle), "building table of endpoints.");
960 /* retrieve the total number of endpoints on this interface */
961 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
963 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
964 return darwin_to_libusb (kresult);
967 /* iterate through pipe references */
968 for (i = 1 ; i <= numep ; i++) {
969 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
970 &dont_care2, &dont_care3);
972 if (kresult != kIOReturnSuccess) {
973 usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
975 return darwin_to_libusb (kresult);
978 usbi_info (HANDLE_CTX (dev_handle), "interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
980 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
983 cInterface->num_endpoints = numep;
988 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
989 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
990 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
991 io_service_t usbInterface = IO_OBJECT_NULL;
993 IOCFPlugInInterface **plugInInterface = NULL;
996 /* current interface */
997 struct __darwin_interface *cInterface = &priv->interfaces[iface];
999 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1000 if (kresult != kIOReturnSuccess)
1001 return darwin_to_libusb (kresult);
1003 /* make sure we have an interface */
1004 if (!usbInterface && dpriv->first_config != 0) {
1005 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1007 /* set the configuration */
1008 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1009 if (kresult != LIBUSB_SUCCESS) {
1010 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1014 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1016 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1017 return darwin_to_libusb (kresult);
1021 if (!usbInterface) {
1022 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1023 return LIBUSB_ERROR_NOT_FOUND;
1026 /* get an interface to the device's interface */
1027 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1028 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1030 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1031 return darwin_to_libusb (kresult);
1034 if (!plugInInterface) {
1035 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1036 return LIBUSB_ERROR_NOT_FOUND;
1039 /* ignore release error */
1040 (void)IOObjectRelease (usbInterface);
1042 /* Do the actual claim */
1043 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1044 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1045 (LPVOID)&cInterface->interface);
1046 if (kresult || !cInterface->interface) {
1047 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1048 return darwin_to_libusb (kresult);
1051 /* We no longer need the intermediate plug-in */
1052 (*plugInInterface)->Release(plugInInterface);
1054 /* claim the interface */
1055 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1057 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1058 return darwin_to_libusb (kresult);
1061 /* update list of endpoints */
1062 kresult = get_endpoints (dev_handle, iface);
1064 /* this should not happen */
1065 darwin_release_interface (dev_handle, iface);
1066 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1070 cInterface->cfSource = NULL;
1072 /* create async event source */
1073 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1074 if (kresult != kIOReturnSuccess) {
1075 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1077 /* can't continue without an async event source */
1078 (void)darwin_release_interface (dev_handle, iface);
1080 return darwin_to_libusb (kresult);
1083 /* add the cfSource to the async thread's run loop */
1084 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1086 usbi_info (HANDLE_CTX (dev_handle), "interface opened");
1091 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1092 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1095 /* current interface */
1096 struct __darwin_interface *cInterface = &priv->interfaces[iface];
1098 /* Check to see if an interface is open */
1099 if (!cInterface->interface)
1100 return LIBUSB_SUCCESS;
1102 /* clean up endpoint data */
1103 cInterface->num_endpoints = 0;
1105 /* delete the interface's async event source */
1106 if (cInterface->cfSource) {
1107 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1108 CFRelease (cInterface->cfSource);
1111 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1113 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1115 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1116 if (kresult != kIOReturnSuccess)
1117 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1119 cInterface->interface = IO_OBJECT_NULL;
1121 return darwin_to_libusb (kresult);
1124 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1125 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1128 /* current interface */
1129 struct __darwin_interface *cInterface = &priv->interfaces[iface];
1131 if (!cInterface->interface)
1132 return LIBUSB_ERROR_NO_DEVICE;
1134 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1135 if (kresult != kIOReturnSuccess)
1136 darwin_reset_device (dev_handle);
1138 /* update list of endpoints */
1139 kresult = get_endpoints (dev_handle, iface);
1141 /* this should not happen */
1142 darwin_release_interface (dev_handle, iface);
1143 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1147 return darwin_to_libusb (kresult);
1150 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1151 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1153 /* current interface */
1154 struct __darwin_interface *cInterface;
1155 uint8_t pipeRef, iface;
1158 /* determine the interface/endpoint to use */
1159 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
1160 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1162 return LIBUSB_ERROR_NOT_FOUND;
1165 cInterface = &priv->interfaces[iface];
1167 #if (InterfaceVersion < 190)
1168 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1170 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1171 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1174 usbi_err (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1176 return darwin_to_libusb (kresult);
1179 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1180 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1183 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1185 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1187 return darwin_to_libusb (kresult);
1190 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1191 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1192 io_service_t usbInterface;
1196 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1198 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1200 return darwin_to_libusb (kresult);
1203 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1204 IOObjectRelease (usbInterface);
1216 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1217 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1218 return LIBUSB_ERROR_NOT_SUPPORTED;
1221 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1222 return LIBUSB_ERROR_NOT_SUPPORTED;
1225 static void darwin_destroy_device(struct libusb_device *dev) {
1228 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1229 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1230 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1233 uint8_t is_read; /* 0 = we're reading, 1 = we're writing */
1234 uint8_t transferType;
1235 /* None of the values below are used in libusb for bulk transfers */
1236 uint8_t direction, number, interval, pipeRef, iface;
1237 uint16_t maxPacketSize;
1239 struct __darwin_interface *cInterface;
1241 /* are we reading or writing? */
1242 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1244 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1245 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1247 return LIBUSB_ERROR_NOT_FOUND;
1250 cInterface = &priv->interfaces[iface];
1252 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1253 &transferType, &maxPacketSize, &interval);
1255 /* submit the request */
1256 /* timeouts are unavailable on interrupt endpoints */
1257 if (transferType == kUSBInterrupt) {
1259 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1260 transfer->length, darwin_async_io_callback, itransfer);
1262 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1263 transfer->length, darwin_async_io_callback, itransfer);
1265 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1268 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1269 transfer->length, transfer->timeout, transfer->timeout,
1270 darwin_async_io_callback, (void *)itransfer);
1272 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1273 transfer->length, transfer->timeout, transfer->timeout,
1274 darwin_async_io_callback, (void *)itransfer);
1278 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", is_read ? "In" : "Out",
1279 darwin_error_str(ret), ret);
1281 return darwin_to_libusb (ret);
1284 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1285 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1286 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1287 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1290 uint8_t is_read; /* 0 = we're writing, 1 = we're reading */
1291 uint8_t pipeRef, iface;
1293 AbsoluteTime atTime;
1296 struct __darwin_interface *cInterface;
1298 /* are we reading or writing? */
1299 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1301 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1302 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1303 free(tpriv->isoc_framelist);
1304 tpriv->isoc_framelist = NULL;
1307 if (!tpriv->isoc_framelist) {
1308 tpriv->num_iso_packets = transfer->num_iso_packets;
1309 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1310 if (!tpriv->isoc_framelist)
1311 return LIBUSB_ERROR_NO_MEM;
1314 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1315 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1316 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1318 /* determine the interface/endpoint to use */
1319 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1320 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1322 return LIBUSB_ERROR_NOT_FOUND;
1325 cInterface = &priv->interfaces[iface];
1327 /* Last but not least we need the bus frame number */
1328 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1330 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1331 free(tpriv->isoc_framelist);
1332 tpriv->isoc_framelist = NULL;
1334 return darwin_to_libusb (kresult);
1337 /* schedule for a frame a little in the future */
1340 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1341 frame = cInterface->frames[transfer->endpoint];
1343 /* submit the request */
1345 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1346 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1349 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1350 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1353 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets / 8;
1355 if (kresult != kIOReturnSuccess) {
1356 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", is_read ? "In" : "Out",
1357 darwin_error_str(kresult));
1358 free (tpriv->isoc_framelist);
1359 tpriv->isoc_framelist = NULL;
1362 return darwin_to_libusb (kresult);
1365 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1366 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1367 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1368 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1369 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1370 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1374 bzero(&tpriv->req, sizeof(tpriv->req));
1376 /* IOUSBDeviceInterface expects the request in cpu endianess */
1377 tpriv->req.bmRequestType = setup->bmRequestType;
1378 tpriv->req.bRequest = setup->bRequest;
1379 /* these values should be in bus order from libusb_fill_control_setup */
1380 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1381 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1382 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1383 /* data is stored after the libusb control block */
1384 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1385 tpriv->req.completionTimeout = transfer->timeout;
1386 tpriv->req.noDataTimeout = transfer->timeout;
1388 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1390 /* all transfers in libusb-1.0 are async */
1392 if (transfer->endpoint) {
1393 struct __darwin_interface *cInterface;
1394 uint8_t pipeRef, iface;
1396 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1397 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1399 return LIBUSB_ERROR_NOT_FOUND;
1402 cInterface = &priv->interfaces[iface];
1404 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1406 /* control request on endpoint 0 */
1407 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1409 if (kresult != kIOReturnSuccess)
1410 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1412 return darwin_to_libusb (kresult);
1415 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1416 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1418 switch (transfer->type) {
1419 case LIBUSB_TRANSFER_TYPE_CONTROL:
1420 return submit_control_transfer(itransfer);
1421 case LIBUSB_TRANSFER_TYPE_BULK:
1422 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1423 return submit_bulk_transfer(itransfer);
1424 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1425 return submit_iso_transfer(itransfer);
1427 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1428 return LIBUSB_ERROR_INVALID_PARAM;
1432 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1433 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1434 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1437 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions control pipe");
1439 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1441 return darwin_to_libusb (kresult);
1444 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1445 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1446 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1447 struct __darwin_interface *cInterface;
1448 uint8_t pipeRef, iface;
1451 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1452 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1454 return LIBUSB_ERROR_NOT_FOUND;
1457 cInterface = &priv->interfaces[iface];
1459 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions on interface %d pipe %d", iface, pipeRef);
1461 /* abort transactions */
1462 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1464 usbi_info (ITRANSFER_CTX (itransfer), "calling clear pipe stall to clear the data toggle bit");
1466 /* clear the data toggle bit */
1467 #if (InterfaceVersion < 190)
1468 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1470 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1471 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1474 return darwin_to_libusb (kresult);
1477 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1478 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1480 switch (transfer->type) {
1481 case LIBUSB_TRANSFER_TYPE_CONTROL:
1482 return cancel_control_transfer(itransfer);
1483 case LIBUSB_TRANSFER_TYPE_BULK:
1484 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1485 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1486 return darwin_abort_transfers (itransfer);
1488 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1489 return LIBUSB_ERROR_INVALID_PARAM;
1493 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1494 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1495 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1497 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1498 free (tpriv->isoc_framelist);
1499 tpriv->isoc_framelist = NULL;
1503 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1504 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1505 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1506 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1509 usbi_info (ITRANSFER_CTX (itransfer), "an async io operation has completed");
1511 /* send a completion message to the device's file descriptor */
1512 message = MESSAGE_ASYNC_IO_COMPLETE;
1513 write (priv->fds[1], &message, sizeof (message));
1514 write (priv->fds[1], &itransfer, sizeof (itransfer));
1515 write (priv->fds[1], &result, sizeof (IOReturn));
1516 write (priv->fds[1], &arg0, sizeof (UInt32));
1519 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1520 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT)
1521 result = kIOUSBTransactionTimeout;
1524 case kIOReturnUnderrun:
1525 case kIOReturnSuccess:
1526 return LIBUSB_TRANSFER_COMPLETED;
1527 case kIOReturnAborted:
1528 return LIBUSB_TRANSFER_CANCELLED;
1529 case kIOUSBPipeStalled:
1530 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: pipe is stalled");
1531 return LIBUSB_TRANSFER_STALL;
1532 case kIOReturnOverrun:
1533 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1534 return LIBUSB_TRANSFER_OVERFLOW;
1535 case kIOUSBTransactionTimeout:
1536 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1537 itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
1538 return LIBUSB_TRANSFER_TIMED_OUT;
1540 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1541 return LIBUSB_TRANSFER_ERROR;
1545 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1546 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1547 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1548 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1549 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1550 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1551 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1554 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1555 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1559 usbi_info (ITRANSFER_CTX (itransfer), "handling %s completion with kernel status %d",
1560 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
1562 if (kIOReturnSuccess == result || kIOReturnUnderrun == result) {
1563 if (isIsoc && tpriv->isoc_framelist) {
1564 /* copy isochronous results back */
1566 for (i = 0; i < transfer->num_iso_packets ; i++) {
1567 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1568 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1569 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1572 itransfer->transferred += io_size;
1575 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1576 usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
1579 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready) {
1580 struct usbi_transfer *itransfer;
1586 usbi_mutex_lock(&ctx->open_devs_lock);
1587 for (i = 0; i < nfds && num_ready > 0; i++) {
1588 struct pollfd *pollfd = &fds[i];
1589 struct libusb_device_handle *handle;
1590 struct darwin_device_handle_priv *hpriv = NULL;
1592 usbi_info (ctx, "checking fd %i with revents = %x", fds[i], pollfd->revents);
1594 if (!pollfd->revents)
1598 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
1599 hpriv = (struct darwin_device_handle_priv *)handle->os_priv;
1600 if (hpriv->fds[0] == pollfd->fd)
1604 if (!(pollfd->revents & POLLERR)) {
1605 ret = read (hpriv->fds[0], &message, sizeof (message));
1606 if (ret < sizeof (message))
1609 /* could not poll the device-- response is to delete the device (this seems a little heavy-handed) */
1610 message = MESSAGE_DEVICE_GONE;
1613 case MESSAGE_DEVICE_GONE:
1614 /* remove the device's async port from the runloop */
1615 if (hpriv->cfSource) {
1616 if (libusb_darwin_acfl)
1617 CFRunLoopRemoveSource (libusb_darwin_acfl, hpriv->cfSource, kCFRunLoopDefaultMode);
1618 CFRelease (hpriv->cfSource);
1619 hpriv->cfSource = NULL;
1622 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1623 usbi_handle_disconnect(handle);
1625 /* done with this device */
1627 case MESSAGE_ASYNC_IO_COMPLETE:
1628 read (hpriv->fds[0], &itransfer, sizeof (itransfer));
1629 read (hpriv->fds[0], &kresult, sizeof (IOReturn));
1630 read (hpriv->fds[0], &io_size, sizeof (UInt32));
1632 darwin_handle_callback (itransfer, kresult, io_size);
1635 usbi_err (ctx, "unknown message received from device pipe");
1639 usbi_mutex_unlock(&ctx->open_devs_lock);
1644 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1645 mach_timespec_t sys_time;
1646 clock_serv_t clock_ref;
1649 case USBI_CLOCK_REALTIME:
1650 /* CLOCK_REALTIME represents time since the epoch */
1651 host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &clock_ref);
1653 case USBI_CLOCK_MONOTONIC:
1654 /* use system boot time as reference for the monotonic clock */
1655 host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &clock_ref);
1658 return LIBUSB_ERROR_INVALID_PARAM;
1661 clock_get_time (clock_ref, &sys_time);
1663 tp->tv_sec = sys_time.tv_sec;
1664 tp->tv_nsec = sys_time.tv_nsec;
1669 const struct usbi_os_backend darwin_backend = {
1671 .init = darwin_init,
1672 .exit = darwin_exit,
1673 .get_device_list = darwin_get_device_list,
1674 .get_device_descriptor = darwin_get_device_descriptor,
1675 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1676 .get_config_descriptor = darwin_get_config_descriptor,
1678 .open = darwin_open,
1679 .close = darwin_close,
1680 .get_configuration = darwin_get_configuration,
1681 .set_configuration = darwin_set_configuration,
1682 .claim_interface = darwin_claim_interface,
1683 .release_interface = darwin_release_interface,
1685 .set_interface_altsetting = darwin_set_interface_altsetting,
1686 .clear_halt = darwin_clear_halt,
1687 .reset_device = darwin_reset_device,
1689 .kernel_driver_active = darwin_kernel_driver_active,
1690 .detach_kernel_driver = darwin_detach_kernel_driver,
1691 .attach_kernel_driver = darwin_attach_kernel_driver,
1693 .destroy_device = darwin_destroy_device,
1695 .submit_transfer = darwin_submit_transfer,
1696 .cancel_transfer = darwin_cancel_transfer,
1697 .clear_transfer_priv = darwin_clear_transfer_priv,
1699 .handle_events = op_handle_events,
1701 .clock_gettime = darwin_clock_gettime,
1703 .device_priv_size = sizeof(struct darwin_device_priv),
1704 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1705 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1706 .add_iso_packet_size = 0,