2 * darwin backend for libusbx 1.0
3 * Copyright © 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>
33 #include <libkern/OSAtomic.h>
35 #include <mach/clock.h>
36 #include <mach/clock_types.h>
37 #include <mach/mach_host.h>
38 #include <mach/mach_port.h>
40 #include <AvailabilityMacros.h>
41 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
42 #include <objc/objc-auto.h>
45 #include <IOKit/IOCFBundle.h>
46 #include <IOKit/usb/IOUSBLib.h>
47 #include <IOKit/IOCFPlugIn.h>
49 #include "darwin_usb.h"
51 /* async event thread */
52 static pthread_mutex_t libusb_darwin_at_mutex;
53 static pthread_cond_t libusb_darwin_at_cond;
55 static clock_serv_t clock_realtime;
56 static clock_serv_t clock_monotonic;
58 static CFRunLoopRef libusb_darwin_acfl = NULL; /* async cf loop */
59 static volatile int32_t initCount = 0;
61 /* async event thread */
62 static pthread_t libusb_darwin_at;
64 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
65 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
66 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
67 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
68 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
71 static const char *darwin_error_str (int result) {
73 case kIOReturnSuccess:
75 case kIOReturnNotOpen:
76 return "device not opened for exclusive access";
77 case kIOReturnNoDevice:
78 return "no connection to an IOService";
79 case kIOUSBNoAsyncPortErr:
80 return "no async port has been opened for interface";
81 case kIOReturnExclusiveAccess:
82 return "another process has device opened for exclusive access";
83 case kIOUSBPipeStalled:
84 return "pipe is stalled";
86 return "could not establish a connection to the Darwin kernel";
87 case kIOUSBTransactionTimeout:
88 return "transaction timed out";
89 case kIOReturnBadArgument:
90 return "invalid argument";
91 case kIOReturnAborted:
92 return "transaction aborted";
93 case kIOReturnNotResponding:
94 return "device not responding";
95 case kIOReturnOverrun:
96 return "data overrun";
97 case kIOReturnCannotWire:
98 return "physical memory can not be wired down";
100 return "unknown error";
105 static int darwin_to_libusb (int result) {
107 case kIOReturnUnderrun:
108 case kIOReturnSuccess:
109 return LIBUSB_SUCCESS;
110 case kIOReturnNotOpen:
111 case kIOReturnNoDevice:
112 return LIBUSB_ERROR_NO_DEVICE;
113 case kIOReturnExclusiveAccess:
114 return LIBUSB_ERROR_ACCESS;
115 case kIOUSBPipeStalled:
116 return LIBUSB_ERROR_PIPE;
117 case kIOReturnBadArgument:
118 return LIBUSB_ERROR_INVALID_PARAM;
119 case kIOUSBTransactionTimeout:
120 return LIBUSB_ERROR_TIMEOUT;
121 case kIOReturnNotResponding:
122 case kIOReturnAborted:
124 case kIOUSBNoAsyncPortErr:
126 return LIBUSB_ERROR_OTHER;
131 static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp) {
132 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
134 /* current interface */
135 struct darwin_interface *cInterface;
139 usbi_dbg ("converting ep address 0x%02x to pipeRef and interface", ep);
141 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
142 cInterface = &priv->interfaces[iface];
144 if (dev_handle->claimed_interfaces & (1 << iface)) {
145 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
146 if (cInterface->endpoint_addrs[i] == ep) {
149 usbi_dbg ("pipe %d on interface %d matches", *pipep, *ifcp);
156 /* No pipe found with the correct endpoint address */
157 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
162 static int usb_setup_device_iterator (io_iterator_t *deviceIterator, long location) {
163 CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBDeviceClassName);
166 return kIOReturnError;
169 CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
170 &kCFTypeDictionaryKeyCallBacks,
171 &kCFTypeDictionaryValueCallBacks);
173 if (propertyMatchDict) {
174 CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberLongType, &location);
176 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
177 /* release our reference to the CFNumber (CFDictionarySetValue retains it) */
178 CFRelease (locationCF);
180 CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
181 /* release out reference to the CFMutableDictionaryRef (CFDictionarySetValue retains it) */
182 CFRelease (propertyMatchDict);
184 /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
187 return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator);
190 static int get_ioregistry_value_number (io_service_t service, CFStringRef property, CFNumberType type, void *p) {
191 CFTypeRef cfNumber = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
195 if (CFGetTypeID(cfNumber) == CFNumberGetTypeID()) {
196 ret = CFNumberGetValue(cfNumber, type, p);
199 CFRelease (cfNumber);
205 static usb_device_t **usb_get_next_device (io_iterator_t deviceIterator, UInt32 *locationp, UInt8 *portp, UInt32 *parent_locationp) {
206 io_cf_plugin_ref_t *plugInInterface = NULL;
207 usb_device_t **device;
208 io_service_t usbDevice, parent;
209 kern_return_t result;
212 if (!IOIteratorIsValid (deviceIterator))
216 while ((usbDevice = IOIteratorNext(deviceIterator))) {
217 result = IOCreatePlugInInterfaceForService(usbDevice, kIOUSBDeviceUserClientTypeID,
218 kIOCFPlugInInterfaceID, &plugInInterface,
221 /* we are done with the usb_device_t */
222 (void)IOObjectRelease(usbDevice);
226 (void) get_ioregistry_value_number (usbDevice, CFSTR("PortNum"), kCFNumberSInt8Type, portp);
229 if (parent_locationp) {
230 *parent_locationp = 0;
232 result = IORegistryEntryGetParentEntry (usbDevice, kIOUSBPlane, &parent);
234 if (kIOReturnSuccess == result) {
235 (void) get_ioregistry_value_number (parent, CFSTR("locationID"), kCFNumberLongType, parent_locationp);
239 if (kIOReturnSuccess == result && plugInInterface)
242 usbi_dbg ("libusb/darwin.c usb_get_next_device: could not set up plugin for service: %s\n", darwin_error_str (result));
248 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
251 (*plugInInterface)->Stop(plugInInterface);
252 IODestroyPlugInInterface (plugInInterface);
254 /* get the location from the device */
256 (*(device))->GetLocationID(device, locationp);
261 static kern_return_t darwin_get_device (uint32_t dev_location, usb_device_t ***darwin_device) {
262 kern_return_t kresult;
264 io_iterator_t deviceIterator;
266 kresult = usb_setup_device_iterator (&deviceIterator, dev_location);
270 /* This port of libusb uses locations to keep track of devices. */
271 while ((*darwin_device = usb_get_next_device (deviceIterator, &location, NULL, NULL)) != NULL) {
272 if (location == dev_location)
275 (**darwin_device)->Release(*darwin_device);
278 IOObjectRelease (deviceIterator);
280 if (!(*darwin_device))
281 return kIOReturnNoDevice;
283 return kIOReturnSuccess;
288 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
289 struct libusb_context *ctx = (struct libusb_context *)ptr;
290 struct libusb_device_handle *handle;
291 struct darwin_device_priv *dpriv;
292 struct darwin_device_handle_priv *priv;
297 CFTypeRef locationCF;
300 usbi_dbg ("a device has been detached");
302 while ((device = IOIteratorNext (rem_devices)) != 0) {
303 /* get the location from the i/o registry */
304 locationCF = IORegistryEntryCreateCFProperty (device, CFSTR(kUSBDevicePropertyLocationID), kCFAllocatorDefault, 0);
306 IOObjectRelease (device);
311 locationValid = CFGetTypeID(locationCF) == CFNumberGetTypeID() &&
312 CFNumberGetValue(locationCF, kCFNumberLongType, &location);
314 CFRelease (locationCF);
319 usbi_mutex_lock(&ctx->open_devs_lock);
320 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
321 dpriv = (struct darwin_device_priv *)handle->dev->os_priv;
323 /* the device may have been opened several times. write to each handle's event descriptor */
324 if (dpriv->location == location && handle->os_priv) {
325 priv = (struct darwin_device_handle_priv *)handle->os_priv;
327 message = MESSAGE_DEVICE_GONE;
328 write (priv->fds[1], &message, sizeof (message));
332 usbi_mutex_unlock(&ctx->open_devs_lock);
336 static void darwin_clear_iterator (io_iterator_t iter) {
339 while ((device = IOIteratorNext (iter)) != 0)
340 IOObjectRelease (device);
343 static void *event_thread_main (void *arg0) {
345 struct libusb_context *ctx = (struct libusb_context *)arg0;
346 CFRunLoopRef runloop;
348 /* Set this thread's name, so it can be seen in the debugger
349 and crash reports. */
350 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
351 pthread_setname_np ("org.libusb.device-detach");
354 /* Tell the Objective-C garbage collector about this thread.
355 This is required because, unlike NSThreads, pthreads are
356 not automatically registered. Although we don't use
357 Objective-C, we use CoreFoundation, which does. */
358 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
359 objc_registerThreadWithCollector();
362 /* hotplug (device removal) source */
363 CFRunLoopSourceRef libusb_notification_cfsource;
364 io_notification_port_t libusb_notification_port;
365 io_iterator_t libusb_rem_device_iterator;
367 usbi_dbg ("creating hotplug event source");
369 runloop = CFRunLoopGetCurrent ();
372 /* add the notification port to the run loop */
373 libusb_notification_port = IONotificationPortCreate (kIOMasterPortDefault);
374 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
375 CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
377 /* create notifications for removed devices */
378 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
379 IOServiceMatching(kIOUSBDeviceClassName),
380 (IOServiceMatchingCallback)darwin_devices_detached,
381 (void *)ctx, &libusb_rem_device_iterator);
383 if (kresult != kIOReturnSuccess) {
384 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
390 darwin_clear_iterator (libusb_rem_device_iterator);
392 usbi_dbg ("thread ready to receive events");
394 /* signal the main thread that the async runloop has been created. */
395 pthread_mutex_lock (&libusb_darwin_at_mutex);
396 libusb_darwin_acfl = runloop;
397 pthread_cond_signal (&libusb_darwin_at_cond);
398 pthread_mutex_unlock (&libusb_darwin_at_mutex);
400 /* run the runloop */
403 usbi_dbg ("thread exiting");
405 /* delete notification port */
406 IONotificationPortDestroy (libusb_notification_port);
407 IOObjectRelease (libusb_rem_device_iterator);
411 libusb_darwin_acfl = NULL;
416 static int darwin_init(struct libusb_context *ctx) {
417 host_name_port_t host_self;
419 if (OSAtomicIncrement32Barrier(&initCount) == 1) {
420 /* create the clocks that will be used */
422 host_self = mach_host_self();
423 host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
424 host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
425 mach_port_deallocate(mach_task_self(), host_self);
427 pthread_mutex_init (&libusb_darwin_at_mutex, NULL);
428 pthread_cond_init (&libusb_darwin_at_cond, NULL);
430 pthread_create (&libusb_darwin_at, NULL, event_thread_main, (void *)ctx);
432 pthread_mutex_lock (&libusb_darwin_at_mutex);
433 while (!libusb_darwin_acfl)
434 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
435 pthread_mutex_unlock (&libusb_darwin_at_mutex);
441 static void darwin_exit (void) {
442 if (OSAtomicDecrement32Barrier(&initCount) == 0) {
443 mach_port_deallocate(mach_task_self(), clock_realtime);
444 mach_port_deallocate(mach_task_self(), clock_monotonic);
446 /* stop the async runloop and wait for the thread to terminate. */
447 CFRunLoopStop (libusb_darwin_acfl);
448 pthread_join (libusb_darwin_at, NULL);
452 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
453 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
455 /* return cached copy */
456 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
463 static int get_configuration_index (struct libusb_device *dev, int config_value) {
464 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
466 IOUSBConfigurationDescriptorPtr desc;
469 /* is there a simpler way to determine the index? */
470 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
471 if (kresult != kIOReturnSuccess)
472 return darwin_to_libusb (kresult);
474 for (i = 0 ; i < numConfig ; i++) {
475 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
477 if (desc->bConfigurationValue == config_value)
481 /* configuration not found */
482 return LIBUSB_ERROR_OTHER;
485 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
486 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
489 if (0 == priv->active_config)
490 return LIBUSB_ERROR_INVALID_PARAM;
492 config_index = get_configuration_index (dev, priv->active_config);
493 if (config_index < 0)
496 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
499 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
500 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
501 IOUSBConfigurationDescriptorPtr desc;
503 usb_device_t **device = NULL;
506 return LIBUSB_ERROR_OTHER;
509 kresult = darwin_get_device (priv->location, &device);
510 if (kresult || !device) {
511 usbi_err (DEVICE_CTX (dev), "could not find device: %s", darwin_error_str (kresult));
513 return darwin_to_libusb (kresult);
516 /* don't have to open the device to get a config descriptor */
518 device = priv->device;
520 kresult = (*device)->GetConfigurationDescriptorPtr (device, config_index, &desc);
521 if (kresult == kIOReturnSuccess) {
522 /* copy descriptor */
523 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
524 len = libusb_le16_to_cpu(desc->wTotalLength);
526 memmove (buffer, desc, len);
528 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
533 (*device)->Release (device);
535 return darwin_to_libusb (kresult);
538 /* check whether the os has configured the device */
539 static int darwin_check_configuration (struct libusb_context *ctx, struct libusb_device *dev, usb_device_t **darwin_device) {
540 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
542 IOUSBConfigurationDescriptorPtr configDesc;
543 IOUSBFindInterfaceRequest request;
544 kern_return_t kresult;
545 io_iterator_t interface_iterator;
546 io_service_t firstInterface;
548 if (priv->dev_descriptor.bNumConfigurations < 1) {
549 usbi_err (ctx, "device has no configurations");
550 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
553 /* find the first configuration */
554 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
555 priv->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
557 /* check if the device is already configured. there is probably a better way than iterating over the
558 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
559 might lock up on the device request) */
561 /* Setup the Interface Request */
562 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
563 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
564 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
565 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
567 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
569 return darwin_to_libusb (kresult);
572 firstInterface = IOIteratorNext(interface_iterator);
574 /* done with the interface iterator */
575 IOObjectRelease(interface_iterator);
577 if (firstInterface) {
578 IOObjectRelease (firstInterface);
580 /* device is configured */
581 if (priv->dev_descriptor.bNumConfigurations == 1)
582 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
583 priv->active_config = priv->first_config;
585 /* devices with more than one configuration should work with GetConfiguration */
586 (*darwin_device)->GetConfiguration (darwin_device, &priv->active_config);
589 priv->active_config = 0;
591 usbi_dbg ("active config: %u, first config: %u", priv->active_config, priv->first_config);
596 static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct libusb_device *dev, usb_device_t **device) {
597 struct darwin_device_priv *priv;
598 int retries = 5, delay = 30000;
599 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
604 UInt16 idProduct, idVendor;
606 (*device)->GetDeviceClass (device, &bDeviceClass);
607 (*device)->GetDeviceProduct (device, &idProduct);
608 (*device)->GetDeviceVendor (device, &idVendor);
610 priv = (struct darwin_device_priv *)dev->os_priv;
612 /* try to open the device (we can usually continue even if this fails) */
613 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
615 /**** retrieve device descriptor ****/
617 /* Set up request for device descriptor */
618 memset (&(priv->dev_descriptor), 0, sizeof(IOUSBDeviceDescriptor));
619 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
620 req.bRequest = kUSBRqGetDescriptor;
621 req.wValue = kUSBDeviceDesc << 8;
623 req.wLength = sizeof(priv->dev_descriptor);
624 req.pData = &(priv->dev_descriptor);
626 /* according to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
627 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
628 * to follow the spec as closely as possible, try opening the device */
630 ret = (*(device))->DeviceRequest (device, &req);
632 if (kIOReturnOverrun == ret && kUSBDeviceDesc == priv->dev_descriptor.bDescriptorType)
633 /* received an overrun error but we still received a device descriptor */
634 ret = kIOReturnSuccess;
636 if (kIOReturnSuccess == ret && (0 == priv->dev_descriptor.bNumConfigurations ||
637 0 == priv->dev_descriptor.bcdUSB)) {
638 /* work around for incorrectly configured devices */
639 if (try_reconfigure && is_open) {
640 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
642 /* set the first configuration */
643 (*device)->SetConfiguration(device, 1);
645 /* don't try to reconfigure again */
649 ret = kIOUSBPipeStalled;
652 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
653 /* device may be suspended. unsuspend it and try again */
654 #if DeviceVersion >= 320
657 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
658 (void)(*device)->GetUSBDeviceInformation (device, &info);
660 try_unsuspend = info & (1 << kUSBInformationDeviceIsSuspendedBit);
664 /* resume the device */
665 ret2 = (*device)->USBDeviceSuspend (device, 0);
666 if (kIOReturnSuccess != ret2) {
667 /* prevent log spew from poorly behaving devices. this indicates the
668 os actually had trouble communicating with the device */
669 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
677 if (kIOReturnSuccess != ret) {
678 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
679 /* sleep for a little while before trying again */
682 } while (kIOReturnSuccess != ret && retries--);
685 /* resuspend the device */
686 (void)(*device)->USBDeviceSuspend (device, 1);
689 (void) (*device)->USBDeviceClose (device);
691 if (ret != kIOReturnSuccess) {
692 /* a debug message was already printed out for this error */
693 if (LIBUSB_CLASS_HUB == bDeviceClass)
694 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s. skipping device", idVendor, idProduct, darwin_error_str (ret));
696 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s. skipping device", idVendor, idProduct, darwin_error_str (ret));
701 usbi_dbg ("device descriptor:");
702 usbi_dbg (" bDescriptorType: 0x%02x", priv->dev_descriptor.bDescriptorType);
703 usbi_dbg (" bcdUSB: 0x%04x", priv->dev_descriptor.bcdUSB);
704 usbi_dbg (" bDeviceClass: 0x%02x", priv->dev_descriptor.bDeviceClass);
705 usbi_dbg (" bDeviceSubClass: 0x%02x", priv->dev_descriptor.bDeviceSubClass);
706 usbi_dbg (" bDeviceProtocol: 0x%02x", priv->dev_descriptor.bDeviceProtocol);
707 usbi_dbg (" bMaxPacketSize0: 0x%02x", priv->dev_descriptor.bMaxPacketSize0);
708 usbi_dbg (" idVendor: 0x%04x", priv->dev_descriptor.idVendor);
709 usbi_dbg (" idProduct: 0x%04x", priv->dev_descriptor.idProduct);
710 usbi_dbg (" bcdDevice: 0x%04x", priv->dev_descriptor.bcdDevice);
711 usbi_dbg (" iManufacturer: 0x%02x", priv->dev_descriptor.iManufacturer);
712 usbi_dbg (" iProduct: 0x%02x", priv->dev_descriptor.iProduct);
713 usbi_dbg (" iSerialNumber: 0x%02x", priv->dev_descriptor.iSerialNumber);
714 usbi_dbg (" bNumConfigurations: 0x%02x", priv->dev_descriptor.bNumConfigurations);
716 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
717 if (libusb_le16_to_cpu (priv->dev_descriptor.idProduct) != idProduct) {
718 /* not a valid device */
719 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
720 idProduct, libusb_le16_to_cpu (priv->dev_descriptor.idProduct));
727 static int process_new_device (struct libusb_context *ctx, usb_device_t **device, UInt32 locationID,
728 UInt32 parent_location, UInt8 port, struct discovered_devs **_discdevs,
729 struct libusb_device **last_dev) {
730 struct darwin_device_priv *priv;
731 struct libusb_device *dev, *parent = NULL;
732 struct discovered_devs *discdevs;
735 int ret = 0, need_unref = 0;
738 dev = usbi_get_device_by_session_id(ctx, locationID);
740 usbi_dbg ("allocating new device for location 0x%08x", locationID);
741 dev = usbi_alloc_device(ctx, locationID);
744 usbi_dbg ("using existing device for location 0x%08x", locationID);
747 ret = LIBUSB_ERROR_NO_MEM;
751 priv = (struct darwin_device_priv *)dev->os_priv;
753 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&address);
755 ret = darwin_cache_device_descriptor (ctx, dev, device);
759 /* check current active configuration (and cache the first configuration value-- which may be used by claim_interface) */
760 ret = darwin_check_configuration (ctx, dev, device);
764 /* the device iterator provides devices in increasing order of location. given this property
765 * we can use the last device to find the parent. */
766 for (parent = *last_dev ; parent ; parent = parent->parent_dev) {
767 struct darwin_device_priv *parent_priv = (struct darwin_device_priv *) parent->os_priv;
769 if (parent_priv->location == parent_location) {
774 dev->parent_dev = parent;
776 dev->port_number = port;
777 dev->bus_number = locationID >> 24;
778 dev->device_address = address;
780 (*device)->GetDeviceSpeed (device, &devSpeed);
783 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
784 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
785 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
787 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
790 /* save our location, we'll need this later */
791 priv->location = locationID;
792 snprintf(priv->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", address, priv->dev_descriptor.idVendor, priv->dev_descriptor.idProduct,
793 priv->dev_descriptor.bDeviceClass, priv->dev_descriptor.bDeviceSubClass);
795 ret = usbi_sanitize_device (dev);
799 /* append the device to the list of discovered devices */
800 discdevs = discovered_devs_append(*_discdevs, dev);
802 ret = LIBUSB_ERROR_NO_MEM;
806 *_discdevs = discdevs;
809 usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
810 dev->port_number, priv->sys_path, (void *) parent);
814 libusb_unref_device(dev);
819 static int darwin_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs) {
820 io_iterator_t deviceIterator;
821 usb_device_t **device;
822 kern_return_t kresult;
823 UInt32 location, parent_location;
825 struct libusb_device *last_dev = NULL;
827 kresult = usb_setup_device_iterator (&deviceIterator, 0);
828 if (kresult != kIOReturnSuccess)
829 return darwin_to_libusb (kresult);
831 while ((device = usb_get_next_device (deviceIterator, &location, &port, &parent_location)) != NULL) {
832 (void) process_new_device (ctx, device, location, parent_location, port, _discdevs, &last_dev);
834 (*(device))->Release(device);
837 IOObjectRelease(deviceIterator);
842 static int darwin_open (struct libusb_device_handle *dev_handle) {
843 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
844 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
845 usb_device_t **darwin_device;
848 if (0 == dpriv->open_count) {
849 kresult = darwin_get_device (dpriv->location, &darwin_device);
851 usbi_err (HANDLE_CTX (dev_handle), "could not find device: %s", darwin_error_str (kresult));
852 return darwin_to_libusb (kresult);
855 dpriv->device = darwin_device;
857 /* try to open the device */
858 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
860 if (kresult != kIOReturnSuccess) {
861 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
864 case kIOReturnExclusiveAccess:
865 /* it is possible to perform some actions on a device that is not open so do not return an error */
870 (*(dpriv->device))->Release (dpriv->device);
871 dpriv->device = NULL;
872 return darwin_to_libusb (kresult);
875 /* create async event source */
876 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
877 if (kresult != kIOReturnSuccess) {
878 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
880 (*(dpriv->device))->USBDeviceClose (dpriv->device);
881 (*(dpriv->device))->Release (dpriv->device);
883 dpriv->device = NULL;
884 return darwin_to_libusb (kresult);
889 CFRetain (libusb_darwin_acfl);
891 /* add the cfSource to the aync run loop */
892 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
896 /* device opened successfully */
899 /* create a file descriptor for notifications */
902 /* set the pipe to be non-blocking */
903 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
905 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
907 usbi_dbg ("device open for access");
912 static void darwin_close (struct libusb_device_handle *dev_handle) {
913 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
914 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
918 if (dpriv->open_count == 0) {
919 /* something is probably very wrong if this is the case */
920 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
926 /* make sure all interfaces are released */
927 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
928 if (dev_handle->claimed_interfaces & (1 << i))
929 libusb_release_interface (dev_handle, i);
931 if (0 == dpriv->open_count) {
933 /* delete the device's async event source */
934 if (priv->cfSource) {
935 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
936 CFRelease (priv->cfSource);
939 /* close the device */
940 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
942 /* Log the fact that we had a problem closing the file, however failing a
943 * close isn't really an error, so return success anyway */
944 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
948 kresult = (*(dpriv->device))->Release(dpriv->device);
950 /* Log the fact that we had a problem closing the file, however failing a
951 * close isn't really an error, so return success anyway */
952 usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
955 dpriv->device = NULL;
958 /* file descriptors are maintained per-instance */
959 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
960 close (priv->fds[1]);
961 close (priv->fds[0]);
963 priv->fds[0] = priv->fds[1] = -1;
966 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
967 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
969 *config = (int) dpriv->active_config;
974 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
975 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
979 /* Setting configuration will invalidate the interface, so we need
980 to reclaim it. First, dispose of existing interfaces, if any. */
981 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
982 if (dev_handle->claimed_interfaces & (1 << i))
983 darwin_release_interface (dev_handle, i);
985 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
986 if (kresult != kIOReturnSuccess)
987 return darwin_to_libusb (kresult);
989 /* Reclaim any interfaces. */
990 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
991 if (dev_handle->claimed_interfaces & (1 << i))
992 darwin_claim_interface (dev_handle, i);
994 dpriv->active_config = config;
999 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
1000 IOUSBFindInterfaceRequest request;
1001 uint8_t current_interface;
1002 kern_return_t kresult;
1003 io_iterator_t interface_iterator;
1005 *usbInterfacep = IO_OBJECT_NULL;
1007 /* Setup the Interface Request */
1008 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1009 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1010 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1011 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1013 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1017 for ( current_interface = 0 ; current_interface <= ifc ; current_interface++ ) {
1018 *usbInterfacep = IOIteratorNext(interface_iterator);
1019 if (current_interface != ifc)
1020 (void) IOObjectRelease (*usbInterfacep);
1023 /* done with the interface iterator */
1024 IOObjectRelease(interface_iterator);
1029 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
1030 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1032 /* current interface */
1033 struct darwin_interface *cInterface = &priv->interfaces[iface];
1035 kern_return_t kresult;
1037 u_int8_t numep, direction, number;
1038 u_int8_t dont_care1, dont_care3;
1039 u_int16_t dont_care2;
1042 usbi_dbg ("building table of endpoints.");
1044 /* retrieve the total number of endpoints on this interface */
1045 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1047 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1048 return darwin_to_libusb (kresult);
1051 /* iterate through pipe references */
1052 for (i = 1 ; i <= numep ; i++) {
1053 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1054 &dont_care2, &dont_care3);
1056 if (kresult != kIOReturnSuccess) {
1057 usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
1059 return darwin_to_libusb (kresult);
1062 usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
1064 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1067 cInterface->num_endpoints = numep;
1072 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1073 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1074 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1075 io_service_t usbInterface = IO_OBJECT_NULL;
1077 IOCFPlugInInterface **plugInInterface = NULL;
1080 /* current interface */
1081 struct darwin_interface *cInterface = &priv->interfaces[iface];
1083 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1084 if (kresult != kIOReturnSuccess)
1085 return darwin_to_libusb (kresult);
1087 /* make sure we have an interface */
1088 if (!usbInterface && dpriv->first_config != 0) {
1089 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1091 /* set the configuration */
1092 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1093 if (kresult != LIBUSB_SUCCESS) {
1094 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1098 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1100 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1101 return darwin_to_libusb (kresult);
1105 if (!usbInterface) {
1106 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1107 return LIBUSB_ERROR_NOT_FOUND;
1110 /* get an interface to the device's interface */
1111 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1112 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1114 /* ignore release error */
1115 (void)IOObjectRelease (usbInterface);
1118 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1119 return darwin_to_libusb (kresult);
1122 if (!plugInInterface) {
1123 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1124 return LIBUSB_ERROR_NOT_FOUND;
1127 /* Do the actual claim */
1128 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1129 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1130 (LPVOID)&cInterface->interface);
1131 /* We no longer need the intermediate plug-in */
1132 IODestroyPlugInInterface (plugInInterface);
1133 if (kresult || !cInterface->interface) {
1134 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1135 return darwin_to_libusb (kresult);
1138 /* claim the interface */
1139 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1141 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1142 return darwin_to_libusb (kresult);
1145 /* update list of endpoints */
1146 kresult = get_endpoints (dev_handle, iface);
1148 /* this should not happen */
1149 darwin_release_interface (dev_handle, iface);
1150 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1154 cInterface->cfSource = NULL;
1156 /* create async event source */
1157 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1158 if (kresult != kIOReturnSuccess) {
1159 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1161 /* can't continue without an async event source */
1162 (void)darwin_release_interface (dev_handle, iface);
1164 return darwin_to_libusb (kresult);
1167 /* add the cfSource to the async thread's run loop */
1168 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1170 usbi_dbg ("interface opened");
1175 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1176 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1179 /* current interface */
1180 struct darwin_interface *cInterface = &priv->interfaces[iface];
1182 /* Check to see if an interface is open */
1183 if (!cInterface->interface)
1184 return LIBUSB_SUCCESS;
1186 /* clean up endpoint data */
1187 cInterface->num_endpoints = 0;
1189 /* delete the interface's async event source */
1190 if (cInterface->cfSource) {
1191 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1192 CFRelease (cInterface->cfSource);
1195 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1197 usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1199 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1200 if (kresult != kIOReturnSuccess)
1201 usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1203 cInterface->interface = IO_OBJECT_NULL;
1205 return darwin_to_libusb (kresult);
1208 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1209 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1212 /* current interface */
1213 struct darwin_interface *cInterface = &priv->interfaces[iface];
1215 if (!cInterface->interface)
1216 return LIBUSB_ERROR_NO_DEVICE;
1218 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1219 if (kresult != kIOReturnSuccess)
1220 darwin_reset_device (dev_handle);
1222 /* update list of endpoints */
1223 kresult = get_endpoints (dev_handle, iface);
1225 /* this should not happen */
1226 darwin_release_interface (dev_handle, iface);
1227 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1231 return darwin_to_libusb (kresult);
1234 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1235 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1237 /* current interface */
1238 struct darwin_interface *cInterface;
1239 uint8_t pipeRef, iface;
1242 /* determine the interface/endpoint to use */
1243 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
1244 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1246 return LIBUSB_ERROR_NOT_FOUND;
1249 cInterface = &priv->interfaces[iface];
1251 #if (InterfaceVersion < 190)
1252 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1254 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1255 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1258 usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1260 return darwin_to_libusb (kresult);
1263 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1264 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1267 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1269 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1271 return darwin_to_libusb (kresult);
1274 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1275 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1276 io_service_t usbInterface;
1280 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1282 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1284 return darwin_to_libusb (kresult);
1287 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1288 IOObjectRelease (usbInterface);
1300 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1301 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1304 return LIBUSB_ERROR_NOT_SUPPORTED;
1307 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1310 return LIBUSB_ERROR_NOT_SUPPORTED;
1313 static void darwin_destroy_device(struct libusb_device *dev) {
1317 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1318 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1319 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1322 uint8_t transferType;
1323 /* None of the values below are used in libusbx for bulk transfers */
1324 uint8_t direction, number, interval, pipeRef, iface;
1325 uint16_t maxPacketSize;
1327 struct darwin_interface *cInterface;
1329 if (IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
1330 return LIBUSB_ERROR_NOT_SUPPORTED;
1332 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1333 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1335 return LIBUSB_ERROR_NOT_FOUND;
1338 cInterface = &priv->interfaces[iface];
1340 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1341 &transferType, &maxPacketSize, &interval);
1343 /* submit the request */
1344 /* timeouts are unavailable on interrupt endpoints */
1345 if (transferType == kUSBInterrupt) {
1346 if (IS_XFERIN(transfer))
1347 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1348 transfer->length, darwin_async_io_callback, itransfer);
1350 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1351 transfer->length, darwin_async_io_callback, itransfer);
1353 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1355 if (IS_XFERIN(transfer))
1356 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1357 transfer->length, transfer->timeout, transfer->timeout,
1358 darwin_async_io_callback, (void *)itransfer);
1360 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1361 transfer->length, transfer->timeout, transfer->timeout,
1362 darwin_async_io_callback, (void *)itransfer);
1366 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1367 darwin_error_str(ret), ret);
1369 return darwin_to_libusb (ret);
1372 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1373 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1374 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1375 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1378 uint8_t pipeRef, iface;
1380 AbsoluteTime atTime;
1383 struct darwin_interface *cInterface;
1385 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1386 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1387 free(tpriv->isoc_framelist);
1388 tpriv->isoc_framelist = NULL;
1391 if (!tpriv->isoc_framelist) {
1392 tpriv->num_iso_packets = transfer->num_iso_packets;
1393 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1394 if (!tpriv->isoc_framelist)
1395 return LIBUSB_ERROR_NO_MEM;
1398 /* copy the frame list from the libusbx descriptor (the structures differ only is member order) */
1399 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1400 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1402 /* determine the interface/endpoint to use */
1403 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1404 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1406 return LIBUSB_ERROR_NOT_FOUND;
1409 cInterface = &priv->interfaces[iface];
1411 /* Last but not least we need the bus frame number */
1412 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1414 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1415 free(tpriv->isoc_framelist);
1416 tpriv->isoc_framelist = NULL;
1418 return darwin_to_libusb (kresult);
1421 /* schedule for a frame a little in the future */
1424 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1425 frame = cInterface->frames[transfer->endpoint];
1427 /* submit the request */
1428 if (IS_XFERIN(transfer))
1429 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1430 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1433 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1434 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1437 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets / 8;
1439 if (kresult != kIOReturnSuccess) {
1440 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1441 darwin_error_str(kresult));
1442 free (tpriv->isoc_framelist);
1443 tpriv->isoc_framelist = NULL;
1446 return darwin_to_libusb (kresult);
1449 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1450 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1451 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1452 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1453 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1454 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1458 bzero(&tpriv->req, sizeof(tpriv->req));
1460 /* IOUSBDeviceInterface expects the request in cpu endianess */
1461 tpriv->req.bmRequestType = setup->bmRequestType;
1462 tpriv->req.bRequest = setup->bRequest;
1463 /* these values should be in bus order from libusb_fill_control_setup */
1464 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1465 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1466 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1467 /* data is stored after the libusbx control block */
1468 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1469 tpriv->req.completionTimeout = transfer->timeout;
1470 tpriv->req.noDataTimeout = transfer->timeout;
1472 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1474 /* all transfers in libusb-1.0 are async */
1476 if (transfer->endpoint) {
1477 struct darwin_interface *cInterface;
1478 uint8_t pipeRef, iface;
1480 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1481 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1483 return LIBUSB_ERROR_NOT_FOUND;
1486 cInterface = &priv->interfaces[iface];
1488 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1490 /* control request on endpoint 0 */
1491 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1493 if (kresult != kIOReturnSuccess)
1494 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1496 return darwin_to_libusb (kresult);
1499 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1500 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1502 switch (transfer->type) {
1503 case LIBUSB_TRANSFER_TYPE_CONTROL:
1504 return submit_control_transfer(itransfer);
1505 case LIBUSB_TRANSFER_TYPE_BULK:
1506 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1507 return submit_bulk_transfer(itransfer);
1508 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1509 return submit_iso_transfer(itransfer);
1511 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1512 return LIBUSB_ERROR_INVALID_PARAM;
1516 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1517 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1518 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1521 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
1524 return LIBUSB_ERROR_NO_DEVICE;
1526 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1528 return darwin_to_libusb (kresult);
1531 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1532 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1533 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1534 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1535 struct darwin_interface *cInterface;
1536 uint8_t pipeRef, iface;
1539 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1540 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1542 return LIBUSB_ERROR_NOT_FOUND;
1545 cInterface = &priv->interfaces[iface];
1548 return LIBUSB_ERROR_NO_DEVICE;
1550 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
1552 /* abort transactions */
1553 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1555 usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
1557 /* clear the data toggle bit */
1558 #if (InterfaceVersion < 190)
1559 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1561 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1562 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1565 return darwin_to_libusb (kresult);
1568 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1569 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1571 switch (transfer->type) {
1572 case LIBUSB_TRANSFER_TYPE_CONTROL:
1573 return cancel_control_transfer(itransfer);
1574 case LIBUSB_TRANSFER_TYPE_BULK:
1575 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1576 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1577 return darwin_abort_transfers (itransfer);
1579 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1580 return LIBUSB_ERROR_INVALID_PARAM;
1584 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1585 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1586 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1588 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1589 free (tpriv->isoc_framelist);
1590 tpriv->isoc_framelist = NULL;
1594 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1595 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1596 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1597 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1598 UInt32 message, size;
1600 usbi_dbg ("an async io operation has completed");
1602 /* The size should never be larger than 4 GB - Also see libusb bug #117 */
1603 if ((intptr_t) arg0 > UINT32_MAX)
1604 usbi_err (ITRANSFER_CTX (itransfer),
1605 "async size truncation detected - please report this error");
1606 size = (UInt32) (intptr_t) arg0;
1608 /* send a completion message to the device's file descriptor */
1609 message = MESSAGE_ASYNC_IO_COMPLETE;
1610 write (priv->fds[1], &message, sizeof (message));
1611 write (priv->fds[1], &itransfer, sizeof (itransfer));
1612 write (priv->fds[1], &result, sizeof (IOReturn));
1613 write (priv->fds[1], &size, sizeof (size));
1616 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1617 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT)
1618 result = kIOUSBTransactionTimeout;
1621 case kIOReturnUnderrun:
1622 case kIOReturnSuccess:
1623 return LIBUSB_TRANSFER_COMPLETED;
1624 case kIOReturnAborted:
1625 return LIBUSB_TRANSFER_CANCELLED;
1626 case kIOUSBPipeStalled:
1627 usbi_dbg ("transfer error: pipe is stalled");
1628 return LIBUSB_TRANSFER_STALL;
1629 case kIOReturnOverrun:
1630 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1631 return LIBUSB_TRANSFER_OVERFLOW;
1632 case kIOUSBTransactionTimeout:
1633 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1634 itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
1635 return LIBUSB_TRANSFER_TIMED_OUT;
1637 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1638 return LIBUSB_TRANSFER_ERROR;
1642 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1643 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1644 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1645 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1646 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1647 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1648 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1651 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1652 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1656 usbi_dbg ("handling %s completion with kernel status %d",
1657 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
1659 if (kIOReturnSuccess == result || kIOReturnUnderrun == result) {
1660 if (isIsoc && tpriv->isoc_framelist) {
1661 /* copy isochronous results back */
1663 for (i = 0; i < transfer->num_iso_packets ; i++) {
1664 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1665 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1666 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1669 itransfer->transferred += io_size;
1672 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1673 usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
1676 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready) {
1677 struct usbi_transfer *itransfer;
1680 POLL_NFDS_TYPE i = 0;
1684 usbi_mutex_lock(&ctx->open_devs_lock);
1685 for (i = 0; i < nfds && num_ready > 0; i++) {
1686 struct pollfd *pollfd = &fds[i];
1687 struct libusb_device_handle *handle;
1688 struct darwin_device_handle_priv *hpriv = NULL;
1690 usbi_dbg ("checking fd %i with revents = %x", fds[i], pollfd->revents);
1692 if (!pollfd->revents)
1696 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
1697 hpriv = (struct darwin_device_handle_priv *)handle->os_priv;
1698 if (hpriv->fds[0] == pollfd->fd)
1704 if (!(pollfd->revents & POLLERR)) {
1705 ret = read (hpriv->fds[0], &message, sizeof (message));
1706 if (ret < (ssize_t)sizeof (message))
1709 /* could not poll the device-- response is to delete the device (this seems a little heavy-handed) */
1710 message = MESSAGE_DEVICE_GONE;
1713 case MESSAGE_DEVICE_GONE:
1714 /* remove the device's async port from the runloop */
1715 if (hpriv->cfSource) {
1716 if (libusb_darwin_acfl)
1717 CFRunLoopRemoveSource (libusb_darwin_acfl, hpriv->cfSource, kCFRunLoopDefaultMode);
1718 CFRelease (hpriv->cfSource);
1719 hpriv->cfSource = NULL;
1722 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1723 usbi_handle_disconnect(handle);
1725 /* done with this device */
1727 case MESSAGE_ASYNC_IO_COMPLETE:
1728 read (hpriv->fds[0], &itransfer, sizeof (itransfer));
1729 read (hpriv->fds[0], &kresult, sizeof (IOReturn));
1730 read (hpriv->fds[0], &io_size, sizeof (UInt32));
1732 darwin_handle_callback (itransfer, kresult, io_size);
1735 usbi_warn (ctx, "unknown message received from device pipe");
1739 usbi_mutex_unlock(&ctx->open_devs_lock);
1744 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1745 mach_timespec_t sys_time;
1746 clock_serv_t clock_ref;
1749 case USBI_CLOCK_REALTIME:
1750 /* CLOCK_REALTIME represents time since the epoch */
1751 clock_ref = clock_realtime;
1753 case USBI_CLOCK_MONOTONIC:
1754 /* use system boot time as reference for the monotonic clock */
1755 clock_ref = clock_monotonic;
1758 return LIBUSB_ERROR_INVALID_PARAM;
1761 clock_get_time (clock_ref, &sys_time);
1763 tp->tv_sec = sys_time.tv_sec;
1764 tp->tv_nsec = sys_time.tv_nsec;
1769 const struct usbi_os_backend darwin_backend = {
1771 .init = darwin_init,
1772 .exit = darwin_exit,
1773 .get_device_list = darwin_get_device_list,
1774 .get_device_descriptor = darwin_get_device_descriptor,
1775 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1776 .get_config_descriptor = darwin_get_config_descriptor,
1778 .open = darwin_open,
1779 .close = darwin_close,
1780 .get_configuration = darwin_get_configuration,
1781 .set_configuration = darwin_set_configuration,
1782 .claim_interface = darwin_claim_interface,
1783 .release_interface = darwin_release_interface,
1785 .set_interface_altsetting = darwin_set_interface_altsetting,
1786 .clear_halt = darwin_clear_halt,
1787 .reset_device = darwin_reset_device,
1789 .kernel_driver_active = darwin_kernel_driver_active,
1790 .detach_kernel_driver = darwin_detach_kernel_driver,
1791 .attach_kernel_driver = darwin_attach_kernel_driver,
1793 .destroy_device = darwin_destroy_device,
1795 .submit_transfer = darwin_submit_transfer,
1796 .cancel_transfer = darwin_cancel_transfer,
1797 .clear_transfer_priv = darwin_clear_transfer_priv,
1799 .handle_events = op_handle_events,
1801 .clock_gettime = darwin_clock_gettime,
1803 .device_priv_size = sizeof(struct darwin_device_priv),
1804 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1805 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1806 .add_iso_packet_size = 0,