1 /* -*- Mode: C; indent-tabs-mode:nil -*- */
3 * darwin backend for libusbx 1.0
4 * Copyright © 2008-2012 Nathan Hjelm <hjelmn@users.sourceforge.net>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30 #include <sys/ioctl.h>
32 #include <sys/types.h>
34 #include <libkern/OSAtomic.h>
36 #include <mach/clock.h>
37 #include <mach/clock_types.h>
38 #include <mach/mach_host.h>
39 #include <mach/mach_port.h>
41 #include <AvailabilityMacros.h>
42 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
43 #include <objc/objc-auto.h>
46 #include <IOKit/IOCFBundle.h>
47 #include <IOKit/usb/IOUSBLib.h>
48 #include <IOKit/IOCFPlugIn.h>
50 #include "darwin_usb.h"
52 /* async event thread */
53 static pthread_mutex_t libusb_darwin_at_mutex;
54 static pthread_cond_t libusb_darwin_at_cond;
56 static clock_serv_t clock_realtime;
57 static clock_serv_t clock_monotonic;
59 static CFRunLoopRef libusb_darwin_acfl = NULL; /* async cf loop */
60 static volatile int32_t initCount = 0;
62 /* async event thread */
63 static pthread_t libusb_darwin_at;
65 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
66 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
67 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
68 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
69 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
72 static const char *darwin_error_str (int result) {
74 case kIOReturnSuccess:
76 case kIOReturnNotOpen:
77 return "device not opened for exclusive access";
78 case kIOReturnNoDevice:
79 return "no connection to an IOService";
80 case kIOUSBNoAsyncPortErr:
81 return "no async port has been opened for interface";
82 case kIOReturnExclusiveAccess:
83 return "another process has device opened for exclusive access";
84 case kIOUSBPipeStalled:
85 return "pipe is stalled";
87 return "could not establish a connection to the Darwin kernel";
88 case kIOUSBTransactionTimeout:
89 return "transaction timed out";
90 case kIOReturnBadArgument:
91 return "invalid argument";
92 case kIOReturnAborted:
93 return "transaction aborted";
94 case kIOReturnNotResponding:
95 return "device not responding";
96 case kIOReturnOverrun:
97 return "data overrun";
98 case kIOReturnCannotWire:
99 return "physical memory can not be wired down";
101 return "unknown error";
106 static int darwin_to_libusb (int result) {
108 case kIOReturnUnderrun:
109 case kIOReturnSuccess:
110 return LIBUSB_SUCCESS;
111 case kIOReturnNotOpen:
112 case kIOReturnNoDevice:
113 return LIBUSB_ERROR_NO_DEVICE;
114 case kIOReturnExclusiveAccess:
115 return LIBUSB_ERROR_ACCESS;
116 case kIOUSBPipeStalled:
117 return LIBUSB_ERROR_PIPE;
118 case kIOReturnBadArgument:
119 return LIBUSB_ERROR_INVALID_PARAM;
120 case kIOUSBTransactionTimeout:
121 return LIBUSB_ERROR_TIMEOUT;
122 case kIOReturnNotResponding:
123 case kIOReturnAborted:
125 case kIOUSBNoAsyncPortErr:
127 return LIBUSB_ERROR_OTHER;
132 static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp) {
133 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
135 /* current interface */
136 struct darwin_interface *cInterface;
140 usbi_dbg ("converting ep address 0x%02x to pipeRef and interface", ep);
142 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
143 cInterface = &priv->interfaces[iface];
145 if (dev_handle->claimed_interfaces & (1 << iface)) {
146 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
147 if (cInterface->endpoint_addrs[i] == ep) {
150 usbi_dbg ("pipe %d on interface %d matches", *pipep, *ifcp);
157 /* No pipe found with the correct endpoint address */
158 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
163 static int usb_setup_device_iterator (io_iterator_t *deviceIterator, long location) {
164 CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBDeviceClassName);
167 return kIOReturnError;
170 CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
171 &kCFTypeDictionaryKeyCallBacks,
172 &kCFTypeDictionaryValueCallBacks);
174 if (propertyMatchDict) {
175 CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberLongType, &location);
177 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
178 /* release our reference to the CFNumber (CFDictionarySetValue retains it) */
179 CFRelease (locationCF);
181 CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
182 /* release out reference to the CFMutableDictionaryRef (CFDictionarySetValue retains it) */
183 CFRelease (propertyMatchDict);
185 /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
188 return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator);
191 static int get_ioregistry_value_number (io_service_t service, CFStringRef property, CFNumberType type, void *p) {
192 CFTypeRef cfNumber = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
196 if (CFGetTypeID(cfNumber) == CFNumberGetTypeID()) {
197 ret = CFNumberGetValue(cfNumber, type, p);
200 CFRelease (cfNumber);
206 static usb_device_t **usb_get_next_device (io_iterator_t deviceIterator, UInt32 *locationp, UInt8 *portp, UInt32 *parent_locationp) {
207 io_cf_plugin_ref_t *plugInInterface = NULL;
208 usb_device_t **device;
209 io_service_t usbDevice, parent;
210 kern_return_t result;
213 if (!IOIteratorIsValid (deviceIterator))
217 while ((usbDevice = IOIteratorNext(deviceIterator))) {
218 result = IOCreatePlugInInterfaceForService(usbDevice, kIOUSBDeviceUserClientTypeID,
219 kIOCFPlugInInterfaceID, &plugInInterface,
222 /* we are done with the usb_device_t */
223 (void)IOObjectRelease(usbDevice);
227 (void) get_ioregistry_value_number (usbDevice, CFSTR("PortNum"), kCFNumberSInt8Type, portp);
230 if (parent_locationp) {
231 *parent_locationp = 0;
233 result = IORegistryEntryGetParentEntry (usbDevice, kIOUSBPlane, &parent);
235 if (kIOReturnSuccess == result) {
236 (void) get_ioregistry_value_number (parent, CFSTR("locationID"), kCFNumberLongType, parent_locationp);
240 if (kIOReturnSuccess == result && plugInInterface)
243 usbi_dbg ("libusb/darwin.c usb_get_next_device: could not set up plugin for service: %s\n", darwin_error_str (result));
249 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
251 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
252 (*plugInInterface)->Release (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 = 2, 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 (kAppleVendorID == idVendor) {
637 /* NTH: don't bother retrying or unsuspending Apple devices */
641 if (kIOReturnSuccess == ret && (0 == priv->dev_descriptor.bNumConfigurations ||
642 0 == priv->dev_descriptor.bcdUSB)) {
643 /* work around for incorrectly configured devices */
644 if (try_reconfigure && is_open) {
645 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
647 /* set the first configuration */
648 (*device)->SetConfiguration(device, 1);
650 /* don't try to reconfigure again */
654 ret = kIOUSBPipeStalled;
657 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
658 /* device may be suspended. unsuspend it and try again */
659 #if DeviceVersion >= 320
662 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
663 (void)(*device)->GetUSBDeviceInformation (device, &info);
665 try_unsuspend = info & (1 << kUSBInformationDeviceIsSuspendedBit);
669 /* resume the device */
670 ret2 = (*device)->USBDeviceSuspend (device, 0);
671 if (kIOReturnSuccess != ret2) {
672 /* prevent log spew from poorly behaving devices. this indicates the
673 os actually had trouble communicating with the device */
674 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
682 if (kIOReturnSuccess != ret) {
683 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
684 /* sleep for a little while before trying again */
687 } while (kIOReturnSuccess != ret && retries--);
690 /* resuspend the device */
691 (void)(*device)->USBDeviceSuspend (device, 1);
694 (void) (*device)->USBDeviceClose (device);
696 if (ret != kIOReturnSuccess) {
697 /* a debug message was already printed out for this error */
698 if (LIBUSB_CLASS_HUB == bDeviceClass)
699 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s. skipping device", idVendor, idProduct, darwin_error_str (ret));
701 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s. skipping device", idVendor, idProduct, darwin_error_str (ret));
706 usbi_dbg ("device descriptor:");
707 usbi_dbg (" bDescriptorType: 0x%02x", priv->dev_descriptor.bDescriptorType);
708 usbi_dbg (" bcdUSB: 0x%04x", priv->dev_descriptor.bcdUSB);
709 usbi_dbg (" bDeviceClass: 0x%02x", priv->dev_descriptor.bDeviceClass);
710 usbi_dbg (" bDeviceSubClass: 0x%02x", priv->dev_descriptor.bDeviceSubClass);
711 usbi_dbg (" bDeviceProtocol: 0x%02x", priv->dev_descriptor.bDeviceProtocol);
712 usbi_dbg (" bMaxPacketSize0: 0x%02x", priv->dev_descriptor.bMaxPacketSize0);
713 usbi_dbg (" idVendor: 0x%04x", priv->dev_descriptor.idVendor);
714 usbi_dbg (" idProduct: 0x%04x", priv->dev_descriptor.idProduct);
715 usbi_dbg (" bcdDevice: 0x%04x", priv->dev_descriptor.bcdDevice);
716 usbi_dbg (" iManufacturer: 0x%02x", priv->dev_descriptor.iManufacturer);
717 usbi_dbg (" iProduct: 0x%02x", priv->dev_descriptor.iProduct);
718 usbi_dbg (" iSerialNumber: 0x%02x", priv->dev_descriptor.iSerialNumber);
719 usbi_dbg (" bNumConfigurations: 0x%02x", priv->dev_descriptor.bNumConfigurations);
721 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
722 if (libusb_le16_to_cpu (priv->dev_descriptor.idProduct) != idProduct) {
723 /* not a valid device */
724 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
725 idProduct, libusb_le16_to_cpu (priv->dev_descriptor.idProduct));
732 static int process_new_device (struct libusb_context *ctx, usb_device_t **device, UInt32 locationID,
733 UInt32 parent_location, UInt8 port, struct discovered_devs **_discdevs,
734 struct libusb_device **last_dev) {
735 struct darwin_device_priv *priv;
736 struct libusb_device *dev, *parent = NULL;
737 struct discovered_devs *discdevs;
740 int ret = 0, need_unref = 0;
743 dev = usbi_get_device_by_session_id(ctx, locationID);
745 usbi_dbg ("allocating new device for location 0x%08x", locationID);
746 dev = usbi_alloc_device(ctx, locationID);
749 usbi_dbg ("using existing device for location 0x%08x", locationID);
752 ret = LIBUSB_ERROR_NO_MEM;
756 priv = (struct darwin_device_priv *)dev->os_priv;
758 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&address);
760 ret = darwin_cache_device_descriptor (ctx, dev, device);
764 /* check current active configuration (and cache the first configuration value-- which may be used by claim_interface) */
765 ret = darwin_check_configuration (ctx, dev, device);
769 /* the device iterator provides devices in increasing order of location. given this property
770 * we can use the last device to find the parent. */
771 for (parent = *last_dev ; parent ; parent = parent->parent_dev) {
772 struct darwin_device_priv *parent_priv = (struct darwin_device_priv *) parent->os_priv;
774 if (parent_priv->location == parent_location) {
779 dev->parent_dev = parent;
781 dev->port_number = port;
782 dev->bus_number = locationID >> 24;
783 dev->device_address = address;
785 (*device)->GetDeviceSpeed (device, &devSpeed);
788 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
789 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
790 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
791 #if DeviceVersion >= 500
792 case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
795 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
798 /* save our location, we'll need this later */
799 priv->location = locationID;
800 snprintf(priv->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", address, priv->dev_descriptor.idVendor, priv->dev_descriptor.idProduct,
801 priv->dev_descriptor.bDeviceClass, priv->dev_descriptor.bDeviceSubClass);
803 ret = usbi_sanitize_device (dev);
807 /* append the device to the list of discovered devices */
808 discdevs = discovered_devs_append(*_discdevs, dev);
810 ret = LIBUSB_ERROR_NO_MEM;
814 *_discdevs = discdevs;
817 usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
818 dev->port_number, priv->sys_path, (void *) parent);
822 libusb_unref_device(dev);
827 static int darwin_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs) {
828 io_iterator_t deviceIterator;
829 usb_device_t **device;
830 kern_return_t kresult;
831 UInt32 location, parent_location;
833 struct libusb_device *last_dev = NULL;
835 kresult = usb_setup_device_iterator (&deviceIterator, 0);
836 if (kresult != kIOReturnSuccess)
837 return darwin_to_libusb (kresult);
839 while ((device = usb_get_next_device (deviceIterator, &location, &port, &parent_location)) != NULL) {
840 (void) process_new_device (ctx, device, location, parent_location, port, _discdevs, &last_dev);
842 (*(device))->Release(device);
845 IOObjectRelease(deviceIterator);
850 static int darwin_open (struct libusb_device_handle *dev_handle) {
851 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
852 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
853 usb_device_t **darwin_device;
856 if (0 == dpriv->open_count) {
857 kresult = darwin_get_device (dpriv->location, &darwin_device);
859 usbi_err (HANDLE_CTX (dev_handle), "could not find device: %s", darwin_error_str (kresult));
860 return darwin_to_libusb (kresult);
863 dpriv->device = darwin_device;
865 /* try to open the device */
866 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
868 if (kresult != kIOReturnSuccess) {
869 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
872 case kIOReturnExclusiveAccess:
873 /* it is possible to perform some actions on a device that is not open so do not return an error */
878 (*(dpriv->device))->Release (dpriv->device);
879 dpriv->device = NULL;
880 return darwin_to_libusb (kresult);
883 /* create async event source */
884 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
885 if (kresult != kIOReturnSuccess) {
886 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
888 (*(dpriv->device))->USBDeviceClose (dpriv->device);
889 (*(dpriv->device))->Release (dpriv->device);
891 dpriv->device = NULL;
892 return darwin_to_libusb (kresult);
897 CFRetain (libusb_darwin_acfl);
899 /* add the cfSource to the aync run loop */
900 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
904 /* device opened successfully */
907 /* create a file descriptor for notifications */
910 /* set the pipe to be non-blocking */
911 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
913 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
915 usbi_dbg ("device open for access");
920 static void darwin_close (struct libusb_device_handle *dev_handle) {
921 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
922 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
926 if (dpriv->open_count == 0) {
927 /* something is probably very wrong if this is the case */
928 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
934 /* make sure all interfaces are released */
935 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
936 if (dev_handle->claimed_interfaces & (1 << i))
937 libusb_release_interface (dev_handle, i);
939 if (0 == dpriv->open_count) {
941 /* delete the device's async event source */
942 if (priv->cfSource) {
943 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
944 CFRelease (priv->cfSource);
947 /* close the device */
948 kresult = (*(dpriv->device))->USBDeviceClose(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), "USBDeviceClose: %s", darwin_error_str(kresult));
956 kresult = (*(dpriv->device))->Release(dpriv->device);
958 /* Log the fact that we had a problem closing the file, however failing a
959 * close isn't really an error, so return success anyway */
960 usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
963 dpriv->device = NULL;
966 /* file descriptors are maintained per-instance */
967 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
968 close (priv->fds[1]);
969 close (priv->fds[0]);
971 priv->fds[0] = priv->fds[1] = -1;
974 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
975 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
977 *config = (int) dpriv->active_config;
982 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
983 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
987 /* Setting configuration will invalidate the interface, so we need
988 to reclaim it. First, dispose of existing interfaces, if any. */
989 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
990 if (dev_handle->claimed_interfaces & (1 << i))
991 darwin_release_interface (dev_handle, i);
993 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
994 if (kresult != kIOReturnSuccess)
995 return darwin_to_libusb (kresult);
997 /* Reclaim any interfaces. */
998 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
999 if (dev_handle->claimed_interfaces & (1 << i))
1000 darwin_claim_interface (dev_handle, i);
1002 dpriv->active_config = config;
1007 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
1008 IOUSBFindInterfaceRequest request;
1009 uint8_t current_interface;
1010 kern_return_t kresult;
1011 io_iterator_t interface_iterator;
1013 *usbInterfacep = IO_OBJECT_NULL;
1015 /* Setup the Interface Request */
1016 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1017 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1018 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1019 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1021 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1025 for ( current_interface = 0 ; current_interface <= ifc ; current_interface++ ) {
1026 *usbInterfacep = IOIteratorNext(interface_iterator);
1027 if (current_interface != ifc)
1028 (void) IOObjectRelease (*usbInterfacep);
1031 /* done with the interface iterator */
1032 IOObjectRelease(interface_iterator);
1037 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
1038 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1040 /* current interface */
1041 struct darwin_interface *cInterface = &priv->interfaces[iface];
1043 kern_return_t kresult;
1045 u_int8_t numep, direction, number;
1046 u_int8_t dont_care1, dont_care3;
1047 u_int16_t dont_care2;
1050 usbi_dbg ("building table of endpoints.");
1052 /* retrieve the total number of endpoints on this interface */
1053 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1055 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1056 return darwin_to_libusb (kresult);
1059 /* iterate through pipe references */
1060 for (i = 1 ; i <= numep ; i++) {
1061 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1062 &dont_care2, &dont_care3);
1064 if (kresult != kIOReturnSuccess) {
1065 usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
1067 return darwin_to_libusb (kresult);
1070 usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
1072 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1075 cInterface->num_endpoints = numep;
1080 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1081 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1082 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1083 io_service_t usbInterface = IO_OBJECT_NULL;
1085 IOCFPlugInInterface **plugInInterface = NULL;
1088 /* current interface */
1089 struct darwin_interface *cInterface = &priv->interfaces[iface];
1091 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1092 if (kresult != kIOReturnSuccess)
1093 return darwin_to_libusb (kresult);
1095 /* make sure we have an interface */
1096 if (!usbInterface && dpriv->first_config != 0) {
1097 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1099 /* set the configuration */
1100 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1101 if (kresult != LIBUSB_SUCCESS) {
1102 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1106 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1108 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1109 return darwin_to_libusb (kresult);
1113 if (!usbInterface) {
1114 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1115 return LIBUSB_ERROR_NOT_FOUND;
1118 /* get an interface to the device's interface */
1119 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1120 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1122 /* ignore release error */
1123 (void)IOObjectRelease (usbInterface);
1126 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1127 return darwin_to_libusb (kresult);
1130 if (!plugInInterface) {
1131 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1132 return LIBUSB_ERROR_NOT_FOUND;
1135 /* Do the actual claim */
1136 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1137 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1138 (LPVOID)&cInterface->interface);
1139 /* We no longer need the intermediate plug-in */
1140 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1141 (*plugInInterface)->Release (plugInInterface);
1142 if (kresult || !cInterface->interface) {
1143 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1144 return darwin_to_libusb (kresult);
1147 /* claim the interface */
1148 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1150 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1151 return darwin_to_libusb (kresult);
1154 /* update list of endpoints */
1155 kresult = get_endpoints (dev_handle, iface);
1157 /* this should not happen */
1158 darwin_release_interface (dev_handle, iface);
1159 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1163 cInterface->cfSource = NULL;
1165 /* create async event source */
1166 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1167 if (kresult != kIOReturnSuccess) {
1168 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1170 /* can't continue without an async event source */
1171 (void)darwin_release_interface (dev_handle, iface);
1173 return darwin_to_libusb (kresult);
1176 /* add the cfSource to the async thread's run loop */
1177 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1179 usbi_dbg ("interface opened");
1184 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1185 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1188 /* current interface */
1189 struct darwin_interface *cInterface = &priv->interfaces[iface];
1191 /* Check to see if an interface is open */
1192 if (!cInterface->interface)
1193 return LIBUSB_SUCCESS;
1195 /* clean up endpoint data */
1196 cInterface->num_endpoints = 0;
1198 /* delete the interface's async event source */
1199 if (cInterface->cfSource) {
1200 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1201 CFRelease (cInterface->cfSource);
1204 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1206 usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1208 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1209 if (kresult != kIOReturnSuccess)
1210 usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1212 cInterface->interface = IO_OBJECT_NULL;
1214 return darwin_to_libusb (kresult);
1217 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1218 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1221 /* current interface */
1222 struct darwin_interface *cInterface = &priv->interfaces[iface];
1224 if (!cInterface->interface)
1225 return LIBUSB_ERROR_NO_DEVICE;
1227 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1228 if (kresult != kIOReturnSuccess)
1229 darwin_reset_device (dev_handle);
1231 /* update list of endpoints */
1232 kresult = get_endpoints (dev_handle, iface);
1234 /* this should not happen */
1235 darwin_release_interface (dev_handle, iface);
1236 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1240 return darwin_to_libusb (kresult);
1243 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1244 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1246 /* current interface */
1247 struct darwin_interface *cInterface;
1248 uint8_t pipeRef, iface;
1251 /* determine the interface/endpoint to use */
1252 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
1253 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1255 return LIBUSB_ERROR_NOT_FOUND;
1258 cInterface = &priv->interfaces[iface];
1260 #if (InterfaceVersion < 190)
1261 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1263 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1264 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1267 usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1269 return darwin_to_libusb (kresult);
1272 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1273 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1276 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1278 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1280 return darwin_to_libusb (kresult);
1283 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1284 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1285 io_service_t usbInterface;
1289 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1291 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1293 return darwin_to_libusb (kresult);
1296 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1297 IOObjectRelease (usbInterface);
1309 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1310 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1313 return LIBUSB_ERROR_NOT_SUPPORTED;
1316 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1319 return LIBUSB_ERROR_NOT_SUPPORTED;
1322 static void darwin_destroy_device(struct libusb_device *dev) {
1326 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1327 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1328 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1331 uint8_t transferType;
1332 /* None of the values below are used in libusbx for bulk transfers */
1333 uint8_t direction, number, interval, pipeRef, iface;
1334 uint16_t maxPacketSize;
1336 struct darwin_interface *cInterface;
1338 if (IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
1339 return LIBUSB_ERROR_NOT_SUPPORTED;
1341 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1342 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1344 return LIBUSB_ERROR_NOT_FOUND;
1347 cInterface = &priv->interfaces[iface];
1349 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1350 &transferType, &maxPacketSize, &interval);
1352 /* submit the request */
1353 /* timeouts are unavailable on interrupt endpoints */
1354 if (transferType == kUSBInterrupt) {
1355 if (IS_XFERIN(transfer))
1356 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1357 transfer->length, darwin_async_io_callback, itransfer);
1359 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1360 transfer->length, darwin_async_io_callback, itransfer);
1362 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1364 if (IS_XFERIN(transfer))
1365 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1366 transfer->length, transfer->timeout, transfer->timeout,
1367 darwin_async_io_callback, (void *)itransfer);
1369 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1370 transfer->length, transfer->timeout, transfer->timeout,
1371 darwin_async_io_callback, (void *)itransfer);
1375 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1376 darwin_error_str(ret), ret);
1378 return darwin_to_libusb (ret);
1381 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1382 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1383 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1384 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1387 uint8_t pipeRef, iface;
1389 AbsoluteTime atTime;
1392 struct darwin_interface *cInterface;
1394 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1395 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1396 free(tpriv->isoc_framelist);
1397 tpriv->isoc_framelist = NULL;
1400 if (!tpriv->isoc_framelist) {
1401 tpriv->num_iso_packets = transfer->num_iso_packets;
1402 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1403 if (!tpriv->isoc_framelist)
1404 return LIBUSB_ERROR_NO_MEM;
1407 /* copy the frame list from the libusbx descriptor (the structures differ only is member order) */
1408 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1409 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1411 /* determine the interface/endpoint to use */
1412 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1413 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1415 return LIBUSB_ERROR_NOT_FOUND;
1418 cInterface = &priv->interfaces[iface];
1420 /* Last but not least we need the bus frame number */
1421 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1423 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1424 free(tpriv->isoc_framelist);
1425 tpriv->isoc_framelist = NULL;
1427 return darwin_to_libusb (kresult);
1430 /* schedule for a frame a little in the future */
1433 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1434 frame = cInterface->frames[transfer->endpoint];
1436 /* submit the request */
1437 if (IS_XFERIN(transfer))
1438 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1439 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1442 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1443 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1446 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets / 8;
1448 if (kresult != kIOReturnSuccess) {
1449 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1450 darwin_error_str(kresult));
1451 free (tpriv->isoc_framelist);
1452 tpriv->isoc_framelist = NULL;
1455 return darwin_to_libusb (kresult);
1458 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1459 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1460 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1461 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1462 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1463 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1467 bzero(&tpriv->req, sizeof(tpriv->req));
1469 /* IOUSBDeviceInterface expects the request in cpu endianess */
1470 tpriv->req.bmRequestType = setup->bmRequestType;
1471 tpriv->req.bRequest = setup->bRequest;
1472 /* these values should be in bus order from libusb_fill_control_setup */
1473 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1474 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1475 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1476 /* data is stored after the libusbx control block */
1477 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1478 tpriv->req.completionTimeout = transfer->timeout;
1479 tpriv->req.noDataTimeout = transfer->timeout;
1481 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1483 /* all transfers in libusb-1.0 are async */
1485 if (transfer->endpoint) {
1486 struct darwin_interface *cInterface;
1487 uint8_t pipeRef, iface;
1489 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1490 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1492 return LIBUSB_ERROR_NOT_FOUND;
1495 cInterface = &priv->interfaces[iface];
1497 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1499 /* control request on endpoint 0 */
1500 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1502 if (kresult != kIOReturnSuccess)
1503 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1505 return darwin_to_libusb (kresult);
1508 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1509 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1511 switch (transfer->type) {
1512 case LIBUSB_TRANSFER_TYPE_CONTROL:
1513 return submit_control_transfer(itransfer);
1514 case LIBUSB_TRANSFER_TYPE_BULK:
1515 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1516 return submit_bulk_transfer(itransfer);
1517 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1518 return submit_iso_transfer(itransfer);
1520 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1521 return LIBUSB_ERROR_INVALID_PARAM;
1525 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1526 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1527 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1530 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
1533 return LIBUSB_ERROR_NO_DEVICE;
1535 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1537 return darwin_to_libusb (kresult);
1540 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1541 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1542 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1543 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1544 struct darwin_interface *cInterface;
1545 uint8_t pipeRef, iface;
1548 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1549 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1551 return LIBUSB_ERROR_NOT_FOUND;
1554 cInterface = &priv->interfaces[iface];
1557 return LIBUSB_ERROR_NO_DEVICE;
1559 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
1561 /* abort transactions */
1562 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1564 usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
1566 /* clear the data toggle bit */
1567 #if (InterfaceVersion < 190)
1568 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1570 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1571 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1574 return darwin_to_libusb (kresult);
1577 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1578 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1580 switch (transfer->type) {
1581 case LIBUSB_TRANSFER_TYPE_CONTROL:
1582 return cancel_control_transfer(itransfer);
1583 case LIBUSB_TRANSFER_TYPE_BULK:
1584 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1585 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1586 return darwin_abort_transfers (itransfer);
1588 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1589 return LIBUSB_ERROR_INVALID_PARAM;
1593 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1594 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1595 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1597 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1598 free (tpriv->isoc_framelist);
1599 tpriv->isoc_framelist = NULL;
1603 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1604 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1605 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1606 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1607 UInt32 message, size;
1609 usbi_dbg ("an async io operation has completed");
1611 /* The size should never be larger than 4 GB - Also see libusb bug #117 */
1612 if ((intptr_t) arg0 > UINT32_MAX)
1613 usbi_err (ITRANSFER_CTX (itransfer),
1614 "async size truncation detected - please report this error");
1615 size = (UInt32) (intptr_t) arg0;
1617 /* send a completion message to the device's file descriptor */
1618 message = MESSAGE_ASYNC_IO_COMPLETE;
1619 write (priv->fds[1], &message, sizeof (message));
1620 write (priv->fds[1], &itransfer, sizeof (itransfer));
1621 write (priv->fds[1], &result, sizeof (IOReturn));
1622 write (priv->fds[1], &size, sizeof (size));
1625 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1626 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT)
1627 result = kIOUSBTransactionTimeout;
1630 case kIOReturnUnderrun:
1631 case kIOReturnSuccess:
1632 return LIBUSB_TRANSFER_COMPLETED;
1633 case kIOReturnAborted:
1634 return LIBUSB_TRANSFER_CANCELLED;
1635 case kIOUSBPipeStalled:
1636 usbi_dbg ("transfer error: pipe is stalled");
1637 return LIBUSB_TRANSFER_STALL;
1638 case kIOReturnOverrun:
1639 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1640 return LIBUSB_TRANSFER_OVERFLOW;
1641 case kIOUSBTransactionTimeout:
1642 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1643 itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
1644 return LIBUSB_TRANSFER_TIMED_OUT;
1646 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1647 return LIBUSB_TRANSFER_ERROR;
1651 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1652 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1653 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1654 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1655 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1656 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1657 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1660 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1661 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1665 usbi_dbg ("handling %s completion with kernel status %d",
1666 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
1668 if (kIOReturnSuccess == result || kIOReturnUnderrun == result) {
1669 if (isIsoc && tpriv->isoc_framelist) {
1670 /* copy isochronous results back */
1672 for (i = 0; i < transfer->num_iso_packets ; i++) {
1673 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1674 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1675 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1678 itransfer->transferred += io_size;
1681 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1682 usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
1685 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready) {
1686 struct usbi_transfer *itransfer;
1689 POLL_NFDS_TYPE i = 0;
1693 usbi_mutex_lock(&ctx->open_devs_lock);
1694 for (i = 0; i < nfds && num_ready > 0; i++) {
1695 struct pollfd *pollfd = &fds[i];
1696 struct libusb_device_handle *handle;
1697 struct darwin_device_handle_priv *hpriv = NULL;
1699 usbi_dbg ("checking fd %i with revents = %x", fds[i], pollfd->revents);
1701 if (!pollfd->revents)
1705 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
1706 hpriv = (struct darwin_device_handle_priv *)handle->os_priv;
1707 if (hpriv->fds[0] == pollfd->fd)
1713 if (!(pollfd->revents & POLLERR)) {
1714 ret = read (hpriv->fds[0], &message, sizeof (message));
1715 if (ret < (ssize_t)sizeof (message))
1718 /* could not poll the device-- response is to delete the device (this seems a little heavy-handed) */
1719 message = MESSAGE_DEVICE_GONE;
1722 case MESSAGE_DEVICE_GONE:
1723 /* remove the device's async port from the runloop */
1724 if (hpriv->cfSource) {
1725 if (libusb_darwin_acfl)
1726 CFRunLoopRemoveSource (libusb_darwin_acfl, hpriv->cfSource, kCFRunLoopDefaultMode);
1727 CFRelease (hpriv->cfSource);
1728 hpriv->cfSource = NULL;
1731 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1732 usbi_handle_disconnect(handle);
1734 /* done with this device */
1736 case MESSAGE_ASYNC_IO_COMPLETE:
1737 read (hpriv->fds[0], &itransfer, sizeof (itransfer));
1738 read (hpriv->fds[0], &kresult, sizeof (IOReturn));
1739 read (hpriv->fds[0], &io_size, sizeof (UInt32));
1741 darwin_handle_callback (itransfer, kresult, io_size);
1744 usbi_warn (ctx, "unknown message received from device pipe");
1748 usbi_mutex_unlock(&ctx->open_devs_lock);
1753 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1754 mach_timespec_t sys_time;
1755 clock_serv_t clock_ref;
1758 case USBI_CLOCK_REALTIME:
1759 /* CLOCK_REALTIME represents time since the epoch */
1760 clock_ref = clock_realtime;
1762 case USBI_CLOCK_MONOTONIC:
1763 /* use system boot time as reference for the monotonic clock */
1764 clock_ref = clock_monotonic;
1767 return LIBUSB_ERROR_INVALID_PARAM;
1770 clock_get_time (clock_ref, &sys_time);
1772 tp->tv_sec = sys_time.tv_sec;
1773 tp->tv_nsec = sys_time.tv_nsec;
1778 const struct usbi_os_backend darwin_backend = {
1780 .init = darwin_init,
1781 .exit = darwin_exit,
1782 .get_device_list = darwin_get_device_list,
1783 .get_device_descriptor = darwin_get_device_descriptor,
1784 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1785 .get_config_descriptor = darwin_get_config_descriptor,
1787 .open = darwin_open,
1788 .close = darwin_close,
1789 .get_configuration = darwin_get_configuration,
1790 .set_configuration = darwin_set_configuration,
1791 .claim_interface = darwin_claim_interface,
1792 .release_interface = darwin_release_interface,
1794 .set_interface_altsetting = darwin_set_interface_altsetting,
1795 .clear_halt = darwin_clear_halt,
1796 .reset_device = darwin_reset_device,
1798 .kernel_driver_active = darwin_kernel_driver_active,
1799 .detach_kernel_driver = darwin_detach_kernel_driver,
1800 .attach_kernel_driver = darwin_attach_kernel_driver,
1802 .destroy_device = darwin_destroy_device,
1804 .submit_transfer = darwin_submit_transfer,
1805 .cancel_transfer = darwin_cancel_transfer,
1806 .clear_transfer_priv = darwin_clear_transfer_priv,
1808 .handle_events = op_handle_events,
1810 .clock_gettime = darwin_clock_gettime,
1812 .device_priv_size = sizeof(struct darwin_device_priv),
1813 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1814 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1815 .add_iso_packet_size = 0,