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 /* async event thread */
51 static pthread_mutex_t libusb_darwin_at_mutex;
52 static pthread_cond_t libusb_darwin_at_cond;
54 static clock_serv_t clock_realtime;
55 static clock_serv_t clock_monotonic;
57 static CFRunLoopRef libusb_darwin_acfl = NULL; /* async cf loop */
58 static int initCount = 0;
60 /* async event thread */
61 static pthread_t libusb_darwin_at;
63 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
64 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
65 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
66 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
67 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
69 static const char *darwin_error_str (int result) {
71 case kIOReturnSuccess:
73 case kIOReturnNotOpen:
74 return "device not opened for exclusive access";
75 case kIOReturnNoDevice:
76 return "no connection to an IOService";
77 case kIOUSBNoAsyncPortErr:
78 return "no async port has been opened for interface";
79 case kIOReturnExclusiveAccess:
80 return "another process has device opened for exclusive access";
81 case kIOUSBPipeStalled:
82 return "pipe is stalled";
84 return "could not establish a connection to the Darwin kernel";
85 case kIOUSBTransactionTimeout:
86 return "transaction timed out";
87 case kIOReturnBadArgument:
88 return "invalid argument";
89 case kIOReturnAborted:
90 return "transaction aborted";
91 case kIOReturnNotResponding:
92 return "device not responding";
93 case kIOReturnOverrun:
94 return "data overrun";
95 case kIOReturnCannotWire:
96 return "physical memory can not be wired down";
98 return "unknown error";
102 static int darwin_to_libusb (int result) {
104 case kIOReturnUnderrun:
105 case kIOReturnSuccess:
106 return LIBUSB_SUCCESS;
107 case kIOReturnNotOpen:
108 case kIOReturnNoDevice:
109 return LIBUSB_ERROR_NO_DEVICE;
110 case kIOReturnExclusiveAccess:
111 return LIBUSB_ERROR_ACCESS;
112 case kIOUSBPipeStalled:
113 return LIBUSB_ERROR_PIPE;
114 case kIOReturnBadArgument:
115 return LIBUSB_ERROR_INVALID_PARAM;
116 case kIOUSBTransactionTimeout:
117 return LIBUSB_ERROR_TIMEOUT;
118 case kIOReturnNotResponding:
119 case kIOReturnAborted:
121 case kIOUSBNoAsyncPortErr:
123 return LIBUSB_ERROR_OTHER;
128 static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp) {
129 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
131 /* current interface */
132 struct darwin_interface *cInterface;
136 usbi_info (HANDLE_CTX(dev_handle), "converting ep address 0x%02x to pipeRef and interface", ep);
138 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
139 cInterface = &priv->interfaces[iface];
141 if (dev_handle->claimed_interfaces & (1 << iface)) {
142 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
143 if (cInterface->endpoint_addrs[i] == ep) {
146 usbi_info (HANDLE_CTX(dev_handle), "pipe %d on interface %d matches", *pipep, *ifcp);
153 /* No pipe found with the correct endpoint address */
154 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
159 static int usb_setup_device_iterator (io_iterator_t *deviceIterator, long location) {
160 CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBDeviceClassName);
163 return kIOReturnError;
166 CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
167 &kCFTypeDictionaryKeyCallBacks,
168 &kCFTypeDictionaryValueCallBacks);
170 if (propertyMatchDict) {
171 CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberLongType, &location);
173 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
174 /* release our reference to the CFNumber (CFDictionarySetValue retains it) */
175 CFRelease (locationCF);
177 CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
178 /* release out reference to the CFMutableDictionaryRef (CFDictionarySetValue retains it) */
179 CFRelease (propertyMatchDict);
181 /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
184 return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator);
187 static usb_device_t **usb_get_next_device (io_iterator_t deviceIterator, UInt32 *locationp) {
188 io_cf_plugin_ref_t *plugInInterface = NULL;
189 usb_device_t **device;
190 io_service_t usbDevice;
194 if (!IOIteratorIsValid (deviceIterator))
198 while ((usbDevice = IOIteratorNext(deviceIterator))) {
199 result = IOCreatePlugInInterfaceForService(usbDevice, kIOUSBDeviceUserClientTypeID,
200 kIOCFPlugInInterfaceID, &plugInInterface,
203 /* we are done with the usb_device_t */
204 (void)IOObjectRelease(usbDevice);
205 if (kIOReturnSuccess == result && plugInInterface)
208 usbi_dbg ("libusb/darwin.c usb_get_next_device: could not set up plugin for service: %s\n", darwin_error_str (result));
214 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
217 (*plugInInterface)->Stop(plugInInterface);
218 IODestroyPlugInInterface (plugInInterface);
220 /* get the location from the device */
222 (*(device))->GetLocationID(device, locationp);
227 static kern_return_t darwin_get_device (uint32_t dev_location, usb_device_t ***darwin_device) {
228 kern_return_t kresult;
230 io_iterator_t deviceIterator;
232 kresult = usb_setup_device_iterator (&deviceIterator, dev_location);
236 /* This port of libusb uses locations to keep track of devices. */
237 while ((*darwin_device = usb_get_next_device (deviceIterator, &location)) != NULL) {
238 if (location == dev_location)
241 (**darwin_device)->Release(*darwin_device);
244 IOObjectRelease (deviceIterator);
246 if (!(*darwin_device))
247 return kIOReturnNoDevice;
249 return kIOReturnSuccess;
254 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
255 struct libusb_context *ctx = (struct libusb_context *)ptr;
256 struct libusb_device_handle *handle;
257 struct darwin_device_priv *dpriv;
258 struct darwin_device_handle_priv *priv;
263 CFTypeRef locationCF;
266 usbi_info (ctx, "a device has been detached");
268 while ((device = IOIteratorNext (rem_devices)) != 0) {
269 /* get the location from the i/o registry */
270 locationCF = IORegistryEntryCreateCFProperty (device, CFSTR(kUSBDevicePropertyLocationID), kCFAllocatorDefault, 0);
272 IOObjectRelease (device);
277 locationValid = CFGetTypeID(locationCF) == CFNumberGetTypeID() &&
278 CFNumberGetValue(locationCF, kCFNumberLongType, &location);
280 CFRelease (locationCF);
285 usbi_mutex_lock(&ctx->open_devs_lock);
286 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
287 dpriv = (struct darwin_device_priv *)handle->dev->os_priv;
289 /* the device may have been opened several times. write to each handle's event descriptor */
290 if (dpriv->location == location && handle->os_priv) {
291 priv = (struct darwin_device_handle_priv *)handle->os_priv;
293 message = MESSAGE_DEVICE_GONE;
294 write (priv->fds[1], &message, sizeof (message));
298 usbi_mutex_unlock(&ctx->open_devs_lock);
302 static void darwin_clear_iterator (io_iterator_t iter) {
305 while ((device = IOIteratorNext (iter)) != 0)
306 IOObjectRelease (device);
309 static void *event_thread_main (void *arg0) {
311 struct libusb_context *ctx = (struct libusb_context *)arg0;
312 CFRunLoopRef runloop;
314 /* Tell the Objective-C garbage collector about this thread.
315 This is required because, unlike NSThreads, pthreads are
316 not automatically registered. Although we don't use
317 Objective-C, we use CoreFoundation, which does. */
318 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
319 objc_registerThreadWithCollector();
322 /* hotplug (device removal) source */
323 CFRunLoopSourceRef libusb_notification_cfsource;
324 io_notification_port_t libusb_notification_port;
325 io_iterator_t libusb_rem_device_iterator;
327 usbi_info (ctx, "creating hotplug event source");
329 runloop = CFRunLoopGetCurrent ();
332 /* add the notification port to the run loop */
333 libusb_notification_port = IONotificationPortCreate (kIOMasterPortDefault);
334 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
335 CFRunLoopAddSource(CFRunLoopGetCurrent (), libusb_notification_cfsource, kCFRunLoopDefaultMode);
337 /* create notifications for removed devices */
338 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
339 IOServiceMatching(kIOUSBDeviceClassName),
340 (IOServiceMatchingCallback)darwin_devices_detached,
341 (void *)ctx, &libusb_rem_device_iterator);
343 if (kresult != kIOReturnSuccess) {
344 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
350 darwin_clear_iterator (libusb_rem_device_iterator);
352 usbi_info (ctx, "thread ready to receive events");
354 /* let the main thread know about the async runloop */
355 libusb_darwin_acfl = CFRunLoopGetCurrent ();
357 /* signal the main thread */
358 pthread_mutex_lock (&libusb_darwin_at_mutex);
359 pthread_cond_signal (&libusb_darwin_at_cond);
360 pthread_mutex_unlock (&libusb_darwin_at_mutex);
362 /* run the runloop */
365 usbi_info (ctx, "thread exiting");
367 /* delete notification port */
368 IONotificationPortDestroy (libusb_notification_port);
369 IOObjectRelease (libusb_rem_device_iterator);
373 libusb_darwin_acfl = NULL;
378 static int darwin_init(struct libusb_context *ctx) {
379 host_name_port_t host_self;
381 if (!(initCount++)) {
382 /* create the clocks that will be used */
384 host_self = mach_host_self();
385 host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
386 host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
387 mach_port_deallocate(mach_task_self(), host_self);
389 pthread_mutex_init (&libusb_darwin_at_mutex, NULL);
390 pthread_cond_init (&libusb_darwin_at_cond, NULL);
392 pthread_create (&libusb_darwin_at, NULL, event_thread_main, (void *)ctx);
394 pthread_mutex_lock (&libusb_darwin_at_mutex);
395 while (!libusb_darwin_acfl)
396 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
397 pthread_mutex_unlock (&libusb_darwin_at_mutex);
403 static void darwin_exit (void) {
404 if (!(--initCount)) {
405 mach_port_deallocate(mach_task_self(), clock_realtime);
406 mach_port_deallocate(mach_task_self(), clock_monotonic);
408 /* stop the async runloop */
409 CFRunLoopStop (libusb_darwin_acfl);
410 pthread_join (libusb_darwin_at, NULL);
414 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
415 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
417 /* return cached copy */
418 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
425 static int get_configuration_index (struct libusb_device *dev, int config_value) {
426 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
428 IOUSBConfigurationDescriptorPtr desc;
431 /* is there a simpler way to determine the index? */
432 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
433 if (kresult != kIOReturnSuccess)
434 return darwin_to_libusb (kresult);
436 for (i = 0 ; i < numConfig ; i++) {
437 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
439 if (desc->bConfigurationValue == config_value)
443 /* configuration not found */
444 return LIBUSB_ERROR_OTHER;
447 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
448 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
451 if (0 == priv->active_config)
452 return LIBUSB_ERROR_INVALID_PARAM;
454 config_index = get_configuration_index (dev, priv->active_config);
455 if (config_index < 0)
458 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
461 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
462 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
463 IOUSBConfigurationDescriptorPtr desc;
465 usb_device_t **device = NULL;
468 return LIBUSB_ERROR_OTHER;
471 kresult = darwin_get_device (priv->location, &device);
472 if (kresult || !device) {
473 usbi_err (DEVICE_CTX (dev), "could not find device: %s", darwin_error_str (kresult));
475 return darwin_to_libusb (kresult);
478 /* don't have to open the device to get a config descriptor */
480 device = priv->device;
482 kresult = (*device)->GetConfigurationDescriptorPtr (device, config_index, &desc);
483 if (kresult == kIOReturnSuccess) {
484 /* copy descriptor */
485 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
486 len = libusb_le16_to_cpu(desc->wTotalLength);
488 memmove (buffer, desc, len);
490 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
495 (*device)->Release (device);
497 return darwin_to_libusb (kresult);
500 /* check whether the os has configured the device */
501 static int darwin_check_configuration (struct libusb_context *ctx, struct libusb_device *dev, usb_device_t **darwin_device) {
502 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
504 IOUSBConfigurationDescriptorPtr configDesc;
505 IOUSBFindInterfaceRequest request;
506 kern_return_t kresult;
507 io_iterator_t interface_iterator;
508 io_service_t firstInterface;
510 if (priv->dev_descriptor.bNumConfigurations < 1) {
511 usbi_err (ctx, "device has no configurations");
512 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
515 /* find the first configuration */
516 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
517 priv->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
519 /* check if the device is already configured. there is probably a better way than iterating over the
520 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
521 might lock up on the device request) */
523 /* Setup the Interface Request */
524 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
525 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
526 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
527 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
529 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
531 return darwin_to_libusb (kresult);
534 firstInterface = IOIteratorNext(interface_iterator);
536 /* done with the interface iterator */
537 IOObjectRelease(interface_iterator);
539 if (firstInterface) {
540 IOObjectRelease (firstInterface);
542 /* device is configured */
543 if (priv->dev_descriptor.bNumConfigurations == 1)
544 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
545 priv->active_config = priv->first_config;
547 /* devices with more than one configuration should work with GetConfiguration */
548 (*darwin_device)->GetConfiguration (darwin_device, &priv->active_config);
551 priv->active_config = 0;
553 usbi_info (ctx, "active config: %u, first config: %u", priv->active_config, priv->first_config);
558 static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct libusb_device *dev, usb_device_t **device) {
559 struct darwin_device_priv *priv;
560 int retries = 5, delay = 30000;
561 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
566 UInt16 idProduct, idVendor;
568 (*device)->GetDeviceClass (device, &bDeviceClass);
569 (*device)->GetDeviceProduct (device, &idProduct);
570 (*device)->GetDeviceVendor (device, &idVendor);
572 priv = (struct darwin_device_priv *)dev->os_priv;
574 /* try to open the device (we can usually continue even if this fails) */
575 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
577 /**** retrieve device descriptor ****/
579 /* Set up request for device descriptor */
580 memset (&(priv->dev_descriptor), 0, sizeof(IOUSBDeviceDescriptor));
581 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
582 req.bRequest = kUSBRqGetDescriptor;
583 req.wValue = kUSBDeviceDesc << 8;
585 req.wLength = sizeof(priv->dev_descriptor);
586 req.pData = &(priv->dev_descriptor);
588 /* according to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
589 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
590 * to follow the spec as closely as possible, try opening the device */
592 ret = (*(device))->DeviceRequest (device, &req);
594 if (kIOReturnOverrun == ret && kUSBDeviceDesc == priv->dev_descriptor.bDescriptorType)
595 /* received an overrun error but we still received a device descriptor */
596 ret = kIOReturnSuccess;
598 if (kIOReturnSuccess == ret && (0 == priv->dev_descriptor.idProduct ||
599 0 == priv->dev_descriptor.bNumConfigurations ||
600 0 == priv->dev_descriptor.bcdUSB)) {
601 /* work around for incorrectly configured devices */
602 if (try_reconfigure && is_open) {
603 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
605 /* set the first configuration */
606 (*device)->SetConfiguration(device, 1);
608 /* don't try to reconfigure again */
612 ret = kIOUSBPipeStalled;
615 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
616 /* device may be suspended. unsuspend it and try again */
617 #if DeviceVersion >= 320
620 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
621 (void)(*device)->GetUSBDeviceInformation (device, &info);
623 try_unsuspend = info & (1 << kUSBInformationDeviceIsSuspendedBit);
627 /* resume the device */
628 ret2 = (*device)->USBDeviceSuspend (device, 0);
629 if (kIOReturnSuccess != ret2) {
630 /* prevent log spew from poorly behaving devices. this indicates the
631 os actually had trouble communicating with the device */
632 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
640 if (kIOReturnSuccess != ret) {
641 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
642 /* sleep for a little while before trying again */
645 } while (kIOReturnSuccess != ret && retries--);
648 /* resuspend the device */
649 (void)(*device)->USBDeviceSuspend (device, 1);
652 (void) (*device)->USBDeviceClose (device);
654 if (ret != kIOReturnSuccess) {
655 /* a debug message was already printed out for this error */
656 if (LIBUSB_CLASS_HUB == bDeviceClass)
657 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s. skipping device", idVendor, idProduct, darwin_error_str (ret));
659 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s. skipping device", idVendor, idProduct, darwin_error_str (ret));
664 usbi_dbg ("device descriptor:");
665 usbi_dbg (" bDescriptorType: 0x%02x", priv->dev_descriptor.bDescriptorType);
666 usbi_dbg (" bcdUSB: 0x%04x", priv->dev_descriptor.bcdUSB);
667 usbi_dbg (" bDeviceClass: 0x%02x", priv->dev_descriptor.bDeviceClass);
668 usbi_dbg (" bDeviceSubClass: 0x%02x", priv->dev_descriptor.bDeviceSubClass);
669 usbi_dbg (" bDeviceProtocol: 0x%02x", priv->dev_descriptor.bDeviceProtocol);
670 usbi_dbg (" bMaxPacketSize0: 0x%02x", priv->dev_descriptor.bMaxPacketSize0);
671 usbi_dbg (" idVendor: 0x%04x", priv->dev_descriptor.idVendor);
672 usbi_dbg (" idProduct: 0x%04x", priv->dev_descriptor.idProduct);
673 usbi_dbg (" bcdDevice: 0x%04x", priv->dev_descriptor.bcdDevice);
674 usbi_dbg (" iManufacturer: 0x%02x", priv->dev_descriptor.iManufacturer);
675 usbi_dbg (" iProduct: 0x%02x", priv->dev_descriptor.iProduct);
676 usbi_dbg (" iSerialNumber: 0x%02x", priv->dev_descriptor.iSerialNumber);
677 usbi_dbg (" bNumConfigurations: 0x%02x", priv->dev_descriptor.bNumConfigurations);
679 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
680 if (libusb_le16_to_cpu (priv->dev_descriptor.idProduct) != idProduct) {
681 /* not a valid device */
682 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
683 idProduct, libusb_le16_to_cpu (priv->dev_descriptor.idProduct));
690 static int process_new_device (struct libusb_context *ctx, usb_device_t **device, UInt32 locationID, struct discovered_devs **_discdevs) {
691 struct darwin_device_priv *priv;
692 struct libusb_device *dev;
693 struct discovered_devs *discdevs;
696 int ret = 0, need_unref = 0;
699 dev = usbi_get_device_by_session_id(ctx, locationID);
701 usbi_info (ctx, "allocating new device for location 0x%08x", locationID);
702 dev = usbi_alloc_device(ctx, locationID);
705 usbi_info (ctx, "using existing device for location 0x%08x", locationID);
708 ret = LIBUSB_ERROR_NO_MEM;
712 priv = (struct darwin_device_priv *)dev->os_priv;
714 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&address);
716 ret = darwin_cache_device_descriptor (ctx, dev, device);
720 /* check current active configuration (and cache the first configuration value-- which may be used by claim_interface) */
721 ret = darwin_check_configuration (ctx, dev, device);
725 dev->bus_number = locationID >> 24;
726 dev->device_address = address;
728 (*device)->GetDeviceSpeed (device, &devSpeed);
731 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
732 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
733 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
735 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
738 /* save our location, we'll need this later */
739 priv->location = locationID;
740 snprintf(priv->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", address, priv->dev_descriptor.idVendor, priv->dev_descriptor.idProduct,
741 priv->dev_descriptor.bDeviceClass, priv->dev_descriptor.bDeviceSubClass);
743 ret = usbi_sanitize_device (dev);
747 /* append the device to the list of discovered devices */
748 discdevs = discovered_devs_append(*_discdevs, dev);
750 ret = LIBUSB_ERROR_NO_MEM;
754 *_discdevs = discdevs;
756 usbi_info (ctx, "found device with address %d at %s", dev->device_address, priv->sys_path);
760 libusb_unref_device(dev);
765 static int darwin_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs) {
766 io_iterator_t deviceIterator;
767 usb_device_t **device;
768 kern_return_t kresult;
771 kresult = usb_setup_device_iterator (&deviceIterator, 0);
772 if (kresult != kIOReturnSuccess)
773 return darwin_to_libusb (kresult);
775 while ((device = usb_get_next_device (deviceIterator, &location)) != NULL) {
776 (void) process_new_device (ctx, device, location, _discdevs);
778 (*(device))->Release(device);
781 IOObjectRelease(deviceIterator);
786 static int darwin_open (struct libusb_device_handle *dev_handle) {
787 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
788 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
789 usb_device_t **darwin_device;
792 if (0 == dpriv->open_count) {
793 kresult = darwin_get_device (dpriv->location, &darwin_device);
795 usbi_err (HANDLE_CTX (dev_handle), "could not find device: %s", darwin_error_str (kresult));
796 return darwin_to_libusb (kresult);
799 dpriv->device = darwin_device;
801 /* try to open the device */
802 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
804 if (kresult != kIOReturnSuccess) {
805 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
808 case kIOReturnExclusiveAccess:
809 /* it is possible to perform some actions on a device that is not open so do not return an error */
814 (*(dpriv->device))->Release (dpriv->device);
815 dpriv->device = NULL;
816 return darwin_to_libusb (kresult);
819 /* create async event source */
820 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
821 if (kresult != kIOReturnSuccess) {
822 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
824 (*(dpriv->device))->USBDeviceClose (dpriv->device);
825 (*(dpriv->device))->Release (dpriv->device);
827 dpriv->device = NULL;
828 return darwin_to_libusb (kresult);
833 CFRetain (libusb_darwin_acfl);
835 /* add the cfSource to the aync run loop */
836 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
840 /* device opened successfully */
843 /* create a file descriptor for notifications */
846 /* set the pipe to be non-blocking */
847 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
849 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
851 usbi_info (HANDLE_CTX (dev_handle), "device open for access");
856 static void darwin_close (struct libusb_device_handle *dev_handle) {
857 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
858 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
862 if (dpriv->open_count == 0) {
863 /* something is probably very wrong if this is the case */
864 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
870 /* make sure all interfaces are released */
871 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
872 if (dev_handle->claimed_interfaces & (1 << i))
873 libusb_release_interface (dev_handle, i);
875 if (0 == dpriv->open_count) {
877 /* delete the device's async event source */
878 if (priv->cfSource) {
879 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
880 CFRelease (priv->cfSource);
883 /* close the device */
884 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
886 /* Log the fact that we had a problem closing the file, however failing a
887 * close isn't really an error, so return success anyway */
888 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
892 kresult = (*(dpriv->device))->Release(dpriv->device);
894 /* Log the fact that we had a problem closing the file, however failing a
895 * close isn't really an error, so return success anyway */
896 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
899 dpriv->device = NULL;
902 /* file descriptors are maintained per-instance */
903 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
904 close (priv->fds[1]);
905 close (priv->fds[0]);
907 priv->fds[0] = priv->fds[1] = -1;
910 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
911 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
913 *config = (int) dpriv->active_config;
918 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
919 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
923 /* Setting configuration will invalidate the interface, so we need
924 to reclaim it. First, dispose of existing interfaces, if any. */
925 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
926 if (dev_handle->claimed_interfaces & (1 << i))
927 darwin_release_interface (dev_handle, i);
929 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
930 if (kresult != kIOReturnSuccess)
931 return darwin_to_libusb (kresult);
933 /* Reclaim any interfaces. */
934 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
935 if (dev_handle->claimed_interfaces & (1 << i))
936 darwin_claim_interface (dev_handle, i);
938 dpriv->active_config = config;
943 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
944 IOUSBFindInterfaceRequest request;
945 uint8_t current_interface;
946 kern_return_t kresult;
947 io_iterator_t interface_iterator;
949 *usbInterfacep = IO_OBJECT_NULL;
951 /* Setup the Interface Request */
952 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
953 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
954 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
955 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
957 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
961 for ( current_interface = 0 ; current_interface <= ifc ; current_interface++ ) {
962 *usbInterfacep = IOIteratorNext(interface_iterator);
963 if (current_interface != ifc)
964 (void) IOObjectRelease (*usbInterfacep);
967 /* done with the interface iterator */
968 IOObjectRelease(interface_iterator);
973 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
974 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
976 /* current interface */
977 struct darwin_interface *cInterface = &priv->interfaces[iface];
979 kern_return_t kresult;
981 u_int8_t numep, direction, number;
982 u_int8_t dont_care1, dont_care3;
983 u_int16_t dont_care2;
986 usbi_info (HANDLE_CTX (dev_handle), "building table of endpoints.");
988 /* retrieve the total number of endpoints on this interface */
989 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
991 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
992 return darwin_to_libusb (kresult);
995 /* iterate through pipe references */
996 for (i = 1 ; i <= numep ; i++) {
997 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
998 &dont_care2, &dont_care3);
1000 if (kresult != kIOReturnSuccess) {
1001 usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
1003 return darwin_to_libusb (kresult);
1006 usbi_info (HANDLE_CTX (dev_handle), "interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
1008 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1011 cInterface->num_endpoints = numep;
1016 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1017 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1018 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1019 io_service_t usbInterface = IO_OBJECT_NULL;
1021 IOCFPlugInInterface **plugInInterface = NULL;
1024 /* current interface */
1025 struct darwin_interface *cInterface = &priv->interfaces[iface];
1027 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1028 if (kresult != kIOReturnSuccess)
1029 return darwin_to_libusb (kresult);
1031 /* make sure we have an interface */
1032 if (!usbInterface && dpriv->first_config != 0) {
1033 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1035 /* set the configuration */
1036 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1037 if (kresult != LIBUSB_SUCCESS) {
1038 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1042 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1044 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1045 return darwin_to_libusb (kresult);
1049 if (!usbInterface) {
1050 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1051 return LIBUSB_ERROR_NOT_FOUND;
1054 /* get an interface to the device's interface */
1055 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1056 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1058 /* ignore release error */
1059 (void)IOObjectRelease (usbInterface);
1062 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1063 return darwin_to_libusb (kresult);
1066 if (!plugInInterface) {
1067 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1068 return LIBUSB_ERROR_NOT_FOUND;
1071 /* Do the actual claim */
1072 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1073 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1074 (LPVOID)&cInterface->interface);
1075 /* We no longer need the intermediate plug-in */
1076 IODestroyPlugInInterface (plugInInterface);
1077 if (kresult || !cInterface->interface) {
1078 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1079 return darwin_to_libusb (kresult);
1082 /* claim the interface */
1083 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1085 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1086 return darwin_to_libusb (kresult);
1089 /* update list of endpoints */
1090 kresult = get_endpoints (dev_handle, iface);
1092 /* this should not happen */
1093 darwin_release_interface (dev_handle, iface);
1094 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1098 cInterface->cfSource = NULL;
1100 /* create async event source */
1101 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1102 if (kresult != kIOReturnSuccess) {
1103 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1105 /* can't continue without an async event source */
1106 (void)darwin_release_interface (dev_handle, iface);
1108 return darwin_to_libusb (kresult);
1111 /* add the cfSource to the async thread's run loop */
1112 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1114 usbi_info (HANDLE_CTX (dev_handle), "interface opened");
1119 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1120 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1123 /* current interface */
1124 struct darwin_interface *cInterface = &priv->interfaces[iface];
1126 /* Check to see if an interface is open */
1127 if (!cInterface->interface)
1128 return LIBUSB_SUCCESS;
1130 /* clean up endpoint data */
1131 cInterface->num_endpoints = 0;
1133 /* delete the interface's async event source */
1134 if (cInterface->cfSource) {
1135 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1136 CFRelease (cInterface->cfSource);
1139 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1141 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1143 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1144 if (kresult != kIOReturnSuccess)
1145 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1147 cInterface->interface = IO_OBJECT_NULL;
1149 return darwin_to_libusb (kresult);
1152 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1153 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1156 /* current interface */
1157 struct darwin_interface *cInterface = &priv->interfaces[iface];
1159 if (!cInterface->interface)
1160 return LIBUSB_ERROR_NO_DEVICE;
1162 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1163 if (kresult != kIOReturnSuccess)
1164 darwin_reset_device (dev_handle);
1166 /* update list of endpoints */
1167 kresult = get_endpoints (dev_handle, iface);
1169 /* this should not happen */
1170 darwin_release_interface (dev_handle, iface);
1171 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1175 return darwin_to_libusb (kresult);
1178 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1179 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1181 /* current interface */
1182 struct darwin_interface *cInterface;
1183 uint8_t pipeRef, iface;
1186 /* determine the interface/endpoint to use */
1187 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
1188 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1190 return LIBUSB_ERROR_NOT_FOUND;
1193 cInterface = &priv->interfaces[iface];
1195 #if (InterfaceVersion < 190)
1196 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1198 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1199 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1202 usbi_err (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1204 return darwin_to_libusb (kresult);
1207 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1208 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1211 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1213 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1215 return darwin_to_libusb (kresult);
1218 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1219 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1220 io_service_t usbInterface;
1224 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1226 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1228 return darwin_to_libusb (kresult);
1231 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1232 IOObjectRelease (usbInterface);
1244 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1245 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1246 return LIBUSB_ERROR_NOT_SUPPORTED;
1249 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1250 return LIBUSB_ERROR_NOT_SUPPORTED;
1253 static void darwin_destroy_device(struct libusb_device *dev) {
1256 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1257 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1258 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1261 uint8_t is_read; /* 0 = we're reading, 1 = we're writing */
1262 uint8_t transferType;
1263 /* None of the values below are used in libusb for bulk transfers */
1264 uint8_t direction, number, interval, pipeRef, iface;
1265 uint16_t maxPacketSize;
1267 struct darwin_interface *cInterface;
1269 /* are we reading or writing? */
1270 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1272 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1273 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1275 return LIBUSB_ERROR_NOT_FOUND;
1278 cInterface = &priv->interfaces[iface];
1280 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1281 &transferType, &maxPacketSize, &interval);
1283 /* submit the request */
1284 /* timeouts are unavailable on interrupt endpoints */
1285 if (transferType == kUSBInterrupt) {
1287 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1288 transfer->length, darwin_async_io_callback, itransfer);
1290 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1291 transfer->length, darwin_async_io_callback, itransfer);
1293 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1296 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1297 transfer->length, transfer->timeout, transfer->timeout,
1298 darwin_async_io_callback, (void *)itransfer);
1300 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1301 transfer->length, transfer->timeout, transfer->timeout,
1302 darwin_async_io_callback, (void *)itransfer);
1306 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", is_read ? "In" : "Out",
1307 darwin_error_str(ret), ret);
1309 return darwin_to_libusb (ret);
1312 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1313 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1314 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1315 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1318 uint8_t is_read; /* 0 = we're writing, 1 = we're reading */
1319 uint8_t pipeRef, iface;
1321 AbsoluteTime atTime;
1324 struct darwin_interface *cInterface;
1326 /* are we reading or writing? */
1327 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1329 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1330 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1331 free(tpriv->isoc_framelist);
1332 tpriv->isoc_framelist = NULL;
1335 if (!tpriv->isoc_framelist) {
1336 tpriv->num_iso_packets = transfer->num_iso_packets;
1337 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1338 if (!tpriv->isoc_framelist)
1339 return LIBUSB_ERROR_NO_MEM;
1342 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1343 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1344 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1346 /* determine the interface/endpoint to use */
1347 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1348 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1350 return LIBUSB_ERROR_NOT_FOUND;
1353 cInterface = &priv->interfaces[iface];
1355 /* Last but not least we need the bus frame number */
1356 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1358 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1359 free(tpriv->isoc_framelist);
1360 tpriv->isoc_framelist = NULL;
1362 return darwin_to_libusb (kresult);
1365 /* schedule for a frame a little in the future */
1368 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1369 frame = cInterface->frames[transfer->endpoint];
1371 /* submit the request */
1373 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1374 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1377 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1378 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1381 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets / 8;
1383 if (kresult != kIOReturnSuccess) {
1384 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", is_read ? "In" : "Out",
1385 darwin_error_str(kresult));
1386 free (tpriv->isoc_framelist);
1387 tpriv->isoc_framelist = NULL;
1390 return darwin_to_libusb (kresult);
1393 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1394 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1395 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1396 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1397 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1398 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1402 bzero(&tpriv->req, sizeof(tpriv->req));
1404 /* IOUSBDeviceInterface expects the request in cpu endianess */
1405 tpriv->req.bmRequestType = setup->bmRequestType;
1406 tpriv->req.bRequest = setup->bRequest;
1407 /* these values should be in bus order from libusb_fill_control_setup */
1408 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1409 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1410 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1411 /* data is stored after the libusb control block */
1412 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1413 tpriv->req.completionTimeout = transfer->timeout;
1414 tpriv->req.noDataTimeout = transfer->timeout;
1416 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1418 /* all transfers in libusb-1.0 are async */
1420 if (transfer->endpoint) {
1421 struct darwin_interface *cInterface;
1422 uint8_t pipeRef, iface;
1424 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1425 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1427 return LIBUSB_ERROR_NOT_FOUND;
1430 cInterface = &priv->interfaces[iface];
1432 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1434 /* control request on endpoint 0 */
1435 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1437 if (kresult != kIOReturnSuccess)
1438 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1440 return darwin_to_libusb (kresult);
1443 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1444 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1446 switch (transfer->type) {
1447 case LIBUSB_TRANSFER_TYPE_CONTROL:
1448 return submit_control_transfer(itransfer);
1449 case LIBUSB_TRANSFER_TYPE_BULK:
1450 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1451 return submit_bulk_transfer(itransfer);
1452 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1453 return submit_iso_transfer(itransfer);
1455 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1456 return LIBUSB_ERROR_INVALID_PARAM;
1460 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1461 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1462 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1465 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions control pipe");
1468 return LIBUSB_ERROR_NO_DEVICE;
1470 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1472 return darwin_to_libusb (kresult);
1475 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1476 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1477 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1478 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1479 struct darwin_interface *cInterface;
1480 uint8_t pipeRef, iface;
1483 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1484 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1486 return LIBUSB_ERROR_NOT_FOUND;
1489 cInterface = &priv->interfaces[iface];
1492 return LIBUSB_ERROR_NO_DEVICE;
1494 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions on interface %d pipe %d", iface, pipeRef);
1496 /* abort transactions */
1497 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1499 usbi_info (ITRANSFER_CTX (itransfer), "calling clear pipe stall to clear the data toggle bit");
1501 /* clear the data toggle bit */
1502 #if (InterfaceVersion < 190)
1503 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1505 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1506 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1509 return darwin_to_libusb (kresult);
1512 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1513 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1515 switch (transfer->type) {
1516 case LIBUSB_TRANSFER_TYPE_CONTROL:
1517 return cancel_control_transfer(itransfer);
1518 case LIBUSB_TRANSFER_TYPE_BULK:
1519 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1520 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1521 return darwin_abort_transfers (itransfer);
1523 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1524 return LIBUSB_ERROR_INVALID_PARAM;
1528 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1529 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1530 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1532 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1533 free (tpriv->isoc_framelist);
1534 tpriv->isoc_framelist = NULL;
1538 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1539 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1540 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1541 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1542 UInt32 message, size;
1544 usbi_info (ITRANSFER_CTX (itransfer), "an async io operation has completed");
1546 size = (UInt32) arg0;
1548 /* send a completion message to the device's file descriptor */
1549 message = MESSAGE_ASYNC_IO_COMPLETE;
1550 write (priv->fds[1], &message, sizeof (message));
1551 write (priv->fds[1], &itransfer, sizeof (itransfer));
1552 write (priv->fds[1], &result, sizeof (IOReturn));
1553 write (priv->fds[1], &size, sizeof (size));
1556 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1557 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT)
1558 result = kIOUSBTransactionTimeout;
1561 case kIOReturnUnderrun:
1562 case kIOReturnSuccess:
1563 return LIBUSB_TRANSFER_COMPLETED;
1564 case kIOReturnAborted:
1565 return LIBUSB_TRANSFER_CANCELLED;
1566 case kIOUSBPipeStalled:
1567 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: pipe is stalled");
1568 return LIBUSB_TRANSFER_STALL;
1569 case kIOReturnOverrun:
1570 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1571 return LIBUSB_TRANSFER_OVERFLOW;
1572 case kIOUSBTransactionTimeout:
1573 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1574 itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
1575 return LIBUSB_TRANSFER_TIMED_OUT;
1577 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1578 return LIBUSB_TRANSFER_ERROR;
1582 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1583 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1584 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1585 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1586 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1587 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1588 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1591 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1592 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1596 usbi_info (ITRANSFER_CTX (itransfer), "handling %s completion with kernel status %d",
1597 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
1599 if (kIOReturnSuccess == result || kIOReturnUnderrun == result) {
1600 if (isIsoc && tpriv->isoc_framelist) {
1601 /* copy isochronous results back */
1603 for (i = 0; i < transfer->num_iso_packets ; i++) {
1604 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1605 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1606 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1609 itransfer->transferred += io_size;
1612 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1613 usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
1616 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready) {
1617 struct usbi_transfer *itransfer;
1623 usbi_mutex_lock(&ctx->open_devs_lock);
1624 for (i = 0; i < nfds && num_ready > 0; i++) {
1625 struct pollfd *pollfd = &fds[i];
1626 struct libusb_device_handle *handle;
1627 struct darwin_device_handle_priv *hpriv = NULL;
1629 usbi_info (ctx, "checking fd %i with revents = %x", fds[i], pollfd->revents);
1631 if (!pollfd->revents)
1635 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
1636 hpriv = (struct darwin_device_handle_priv *)handle->os_priv;
1637 if (hpriv->fds[0] == pollfd->fd)
1641 if (!(pollfd->revents & POLLERR)) {
1642 ret = read (hpriv->fds[0], &message, sizeof (message));
1643 if (ret < sizeof (message))
1646 /* could not poll the device-- response is to delete the device (this seems a little heavy-handed) */
1647 message = MESSAGE_DEVICE_GONE;
1650 case MESSAGE_DEVICE_GONE:
1651 /* remove the device's async port from the runloop */
1652 if (hpriv->cfSource) {
1653 if (libusb_darwin_acfl)
1654 CFRunLoopRemoveSource (libusb_darwin_acfl, hpriv->cfSource, kCFRunLoopDefaultMode);
1655 CFRelease (hpriv->cfSource);
1656 hpriv->cfSource = NULL;
1659 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1660 usbi_handle_disconnect(handle);
1662 /* done with this device */
1664 case MESSAGE_ASYNC_IO_COMPLETE:
1665 read (hpriv->fds[0], &itransfer, sizeof (itransfer));
1666 read (hpriv->fds[0], &kresult, sizeof (IOReturn));
1667 read (hpriv->fds[0], &io_size, sizeof (UInt32));
1669 darwin_handle_callback (itransfer, kresult, io_size);
1672 usbi_err (ctx, "unknown message received from device pipe");
1676 usbi_mutex_unlock(&ctx->open_devs_lock);
1681 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1682 mach_timespec_t sys_time;
1683 clock_serv_t clock_ref;
1686 case USBI_CLOCK_REALTIME:
1687 /* CLOCK_REALTIME represents time since the epoch */
1688 clock_ref = clock_realtime;
1690 case USBI_CLOCK_MONOTONIC:
1691 /* use system boot time as reference for the monotonic clock */
1692 clock_ref = clock_monotonic;
1695 return LIBUSB_ERROR_INVALID_PARAM;
1698 clock_get_time (clock_ref, &sys_time);
1700 tp->tv_sec = sys_time.tv_sec;
1701 tp->tv_nsec = sys_time.tv_nsec;
1706 const struct usbi_os_backend darwin_backend = {
1708 .init = darwin_init,
1709 .exit = darwin_exit,
1710 .get_device_list = darwin_get_device_list,
1711 .get_device_descriptor = darwin_get_device_descriptor,
1712 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1713 .get_config_descriptor = darwin_get_config_descriptor,
1715 .open = darwin_open,
1716 .close = darwin_close,
1717 .get_configuration = darwin_get_configuration,
1718 .set_configuration = darwin_set_configuration,
1719 .claim_interface = darwin_claim_interface,
1720 .release_interface = darwin_release_interface,
1722 .set_interface_altsetting = darwin_set_interface_altsetting,
1723 .clear_halt = darwin_clear_halt,
1724 .reset_device = darwin_reset_device,
1726 .kernel_driver_active = darwin_kernel_driver_active,
1727 .detach_kernel_driver = darwin_detach_kernel_driver,
1728 .attach_kernel_driver = darwin_attach_kernel_driver,
1730 .destroy_device = darwin_destroy_device,
1732 .submit_transfer = darwin_submit_transfer,
1733 .cancel_transfer = darwin_cancel_transfer,
1734 .clear_transfer_priv = darwin_clear_transfer_priv,
1736 .handle_events = op_handle_events,
1738 .clock_gettime = darwin_clock_gettime,
1740 .device_priv_size = sizeof(struct darwin_device_priv),
1741 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1742 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1743 .add_iso_packet_size = 0,