2 * darwin backend for libusb 1.0
3 * Copyright (C) 2008-2011 Nathan Hjelm <hjelmn@users.sourceforge.net>
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29 #include <sys/ioctl.h>
31 #include <sys/types.h>
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);
70 static const char *darwin_error_str (int result) {
72 case kIOReturnSuccess:
74 case kIOReturnNotOpen:
75 return "device not opened for exclusive access";
76 case kIOReturnNoDevice:
77 return "no connection to an IOService";
78 case kIOUSBNoAsyncPortErr:
79 return "no async port has been opened for interface";
80 case kIOReturnExclusiveAccess:
81 return "another process has device opened for exclusive access";
82 case kIOUSBPipeStalled:
83 return "pipe is stalled";
85 return "could not establish a connection to the Darwin kernel";
86 case kIOUSBTransactionTimeout:
87 return "transaction timed out";
88 case kIOReturnBadArgument:
89 return "invalid argument";
90 case kIOReturnAborted:
91 return "transaction aborted";
92 case kIOReturnNotResponding:
93 return "device not responding";
94 case kIOReturnOverrun:
95 return "data overrun";
96 case kIOReturnCannotWire:
97 return "physical memory can not be wired down";
99 return "unknown error";
103 static int darwin_to_libusb (int result) {
105 case kIOReturnUnderrun:
106 case kIOReturnSuccess:
107 return LIBUSB_SUCCESS;
108 case kIOReturnNotOpen:
109 case kIOReturnNoDevice:
110 return LIBUSB_ERROR_NO_DEVICE;
111 case kIOReturnExclusiveAccess:
112 return LIBUSB_ERROR_ACCESS;
113 case kIOUSBPipeStalled:
114 return LIBUSB_ERROR_PIPE;
115 case kIOReturnBadArgument:
116 return LIBUSB_ERROR_INVALID_PARAM;
117 case kIOUSBTransactionTimeout:
118 return LIBUSB_ERROR_TIMEOUT;
119 case kIOReturnNotResponding:
120 case kIOReturnAborted:
122 case kIOUSBNoAsyncPortErr:
124 return LIBUSB_ERROR_OTHER;
129 static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp) {
130 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
132 /* current interface */
133 struct darwin_interface *cInterface;
137 usbi_info (HANDLE_CTX(dev_handle), "converting ep address 0x%02x to pipeRef and interface", ep);
139 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
140 cInterface = &priv->interfaces[iface];
142 if (dev_handle->claimed_interfaces & (1 << iface)) {
143 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
144 if (cInterface->endpoint_addrs[i] == ep) {
147 usbi_info (HANDLE_CTX(dev_handle), "pipe %d on interface %d matches", *pipep, *ifcp);
154 /* No pipe found with the correct endpoint address */
155 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
160 static int usb_setup_device_iterator (io_iterator_t *deviceIterator, long location) {
161 CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBDeviceClassName);
164 return kIOReturnError;
167 CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
168 &kCFTypeDictionaryKeyCallBacks,
169 &kCFTypeDictionaryValueCallBacks);
171 if (propertyMatchDict) {
172 CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberLongType, &location);
174 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
175 /* release our reference to the CFNumber (CFDictionarySetValue retains it) */
176 CFRelease (locationCF);
178 CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
179 /* release out reference to the CFMutableDictionaryRef (CFDictionarySetValue retains it) */
180 CFRelease (propertyMatchDict);
182 /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
185 return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator);
188 static usb_device_t **usb_get_next_device (io_iterator_t deviceIterator, UInt32 *locationp) {
189 io_cf_plugin_ref_t *plugInInterface = NULL;
190 usb_device_t **device;
191 io_service_t usbDevice;
195 if (!IOIteratorIsValid (deviceIterator))
199 while ((usbDevice = IOIteratorNext(deviceIterator))) {
200 result = IOCreatePlugInInterfaceForService(usbDevice, kIOUSBDeviceUserClientTypeID,
201 kIOCFPlugInInterfaceID, &plugInInterface,
204 /* we are done with the usb_device_t */
205 (void)IOObjectRelease(usbDevice);
206 if (kIOReturnSuccess == result && plugInInterface)
209 usbi_dbg ("libusb/darwin.c usb_get_next_device: could not set up plugin for service: %s\n", darwin_error_str (result));
215 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
218 (*plugInInterface)->Stop(plugInInterface);
219 IODestroyPlugInInterface (plugInInterface);
221 /* get the location from the device */
223 (*(device))->GetLocationID(device, locationp);
228 static kern_return_t darwin_get_device (uint32_t dev_location, usb_device_t ***darwin_device) {
229 kern_return_t kresult;
231 io_iterator_t deviceIterator;
233 kresult = usb_setup_device_iterator (&deviceIterator, dev_location);
237 /* This port of libusb uses locations to keep track of devices. */
238 while ((*darwin_device = usb_get_next_device (deviceIterator, &location)) != NULL) {
239 if (location == dev_location)
242 (**darwin_device)->Release(*darwin_device);
245 IOObjectRelease (deviceIterator);
247 if (!(*darwin_device))
248 return kIOReturnNoDevice;
250 return kIOReturnSuccess;
255 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
256 struct libusb_context *ctx = (struct libusb_context *)ptr;
257 struct libusb_device_handle *handle;
258 struct darwin_device_priv *dpriv;
259 struct darwin_device_handle_priv *priv;
264 CFTypeRef locationCF;
267 usbi_info (ctx, "a device has been detached");
269 while ((device = IOIteratorNext (rem_devices)) != 0) {
270 /* get the location from the i/o registry */
271 locationCF = IORegistryEntryCreateCFProperty (device, CFSTR(kUSBDevicePropertyLocationID), kCFAllocatorDefault, 0);
273 IOObjectRelease (device);
278 locationValid = CFGetTypeID(locationCF) == CFNumberGetTypeID() &&
279 CFNumberGetValue(locationCF, kCFNumberLongType, &location);
281 CFRelease (locationCF);
286 usbi_mutex_lock(&ctx->open_devs_lock);
287 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
288 dpriv = (struct darwin_device_priv *)handle->dev->os_priv;
290 /* the device may have been opened several times. write to each handle's event descriptor */
291 if (dpriv->location == location && handle->os_priv) {
292 priv = (struct darwin_device_handle_priv *)handle->os_priv;
294 message = MESSAGE_DEVICE_GONE;
295 write (priv->fds[1], &message, sizeof (message));
299 usbi_mutex_unlock(&ctx->open_devs_lock);
303 static void darwin_clear_iterator (io_iterator_t iter) {
306 while ((device = IOIteratorNext (iter)) != 0)
307 IOObjectRelease (device);
310 static void *event_thread_main (void *arg0) {
312 struct libusb_context *ctx = (struct libusb_context *)arg0;
313 CFRunLoopRef runloop;
315 /* Set this thread's name, so it can be seen in the debugger
316 and crash reports. */
317 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
318 pthread_setname_np ("org.libusb.device-detach");
321 /* Tell the Objective-C garbage collector about this thread.
322 This is required because, unlike NSThreads, pthreads are
323 not automatically registered. Although we don't use
324 Objective-C, we use CoreFoundation, which does. */
325 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
326 objc_registerThreadWithCollector();
329 /* hotplug (device removal) source */
330 CFRunLoopSourceRef libusb_notification_cfsource;
331 io_notification_port_t libusb_notification_port;
332 io_iterator_t libusb_rem_device_iterator;
334 usbi_info (ctx, "creating hotplug event source");
336 runloop = CFRunLoopGetCurrent ();
339 /* add the notification port to the run loop */
340 libusb_notification_port = IONotificationPortCreate (kIOMasterPortDefault);
341 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
342 CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
344 /* create notifications for removed devices */
345 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
346 IOServiceMatching(kIOUSBDeviceClassName),
347 (IOServiceMatchingCallback)darwin_devices_detached,
348 (void *)ctx, &libusb_rem_device_iterator);
350 if (kresult != kIOReturnSuccess) {
351 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
357 darwin_clear_iterator (libusb_rem_device_iterator);
359 usbi_info (ctx, "thread ready to receive events");
361 /* signal the main thread that the async runloop has been created. */
362 pthread_mutex_lock (&libusb_darwin_at_mutex);
363 libusb_darwin_acfl = runloop;
364 pthread_cond_signal (&libusb_darwin_at_cond);
365 pthread_mutex_unlock (&libusb_darwin_at_mutex);
367 /* run the runloop */
370 usbi_info (ctx, "thread exiting");
372 /* delete notification port */
373 IONotificationPortDestroy (libusb_notification_port);
374 IOObjectRelease (libusb_rem_device_iterator);
378 libusb_darwin_acfl = NULL;
383 static int darwin_init(struct libusb_context *ctx) {
384 host_name_port_t host_self;
386 if (OSAtomicIncrement32Barrier(&initCount) == 1) {
387 /* create the clocks that will be used */
389 host_self = mach_host_self();
390 host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
391 host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
392 mach_port_deallocate(mach_task_self(), host_self);
394 pthread_mutex_init (&libusb_darwin_at_mutex, NULL);
395 pthread_cond_init (&libusb_darwin_at_cond, NULL);
397 pthread_create (&libusb_darwin_at, NULL, event_thread_main, (void *)ctx);
399 pthread_mutex_lock (&libusb_darwin_at_mutex);
400 while (!libusb_darwin_acfl)
401 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
402 pthread_mutex_unlock (&libusb_darwin_at_mutex);
408 static void darwin_exit (void) {
409 if (OSAtomicDecrement32Barrier(&initCount) == 0) {
410 mach_port_deallocate(mach_task_self(), clock_realtime);
411 mach_port_deallocate(mach_task_self(), clock_monotonic);
413 /* stop the async runloop and wait for the thread to terminate. */
414 CFRunLoopStop (libusb_darwin_acfl);
415 pthread_join (libusb_darwin_at, NULL);
419 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
420 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
422 /* return cached copy */
423 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
430 static int get_configuration_index (struct libusb_device *dev, int config_value) {
431 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
433 IOUSBConfigurationDescriptorPtr desc;
436 /* is there a simpler way to determine the index? */
437 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
438 if (kresult != kIOReturnSuccess)
439 return darwin_to_libusb (kresult);
441 for (i = 0 ; i < numConfig ; i++) {
442 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
444 if (desc->bConfigurationValue == config_value)
448 /* configuration not found */
449 return LIBUSB_ERROR_OTHER;
452 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
453 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
456 if (0 == priv->active_config)
457 return LIBUSB_ERROR_INVALID_PARAM;
459 config_index = get_configuration_index (dev, priv->active_config);
460 if (config_index < 0)
463 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
466 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
467 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
468 IOUSBConfigurationDescriptorPtr desc;
470 usb_device_t **device = NULL;
473 return LIBUSB_ERROR_OTHER;
476 kresult = darwin_get_device (priv->location, &device);
477 if (kresult || !device) {
478 usbi_err (DEVICE_CTX (dev), "could not find device: %s", darwin_error_str (kresult));
480 return darwin_to_libusb (kresult);
483 /* don't have to open the device to get a config descriptor */
485 device = priv->device;
487 kresult = (*device)->GetConfigurationDescriptorPtr (device, config_index, &desc);
488 if (kresult == kIOReturnSuccess) {
489 /* copy descriptor */
490 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
491 len = libusb_le16_to_cpu(desc->wTotalLength);
493 memmove (buffer, desc, len);
495 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
500 (*device)->Release (device);
502 return darwin_to_libusb (kresult);
505 /* check whether the os has configured the device */
506 static int darwin_check_configuration (struct libusb_context *ctx, struct libusb_device *dev, usb_device_t **darwin_device) {
507 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
509 IOUSBConfigurationDescriptorPtr configDesc;
510 IOUSBFindInterfaceRequest request;
511 kern_return_t kresult;
512 io_iterator_t interface_iterator;
513 io_service_t firstInterface;
515 if (priv->dev_descriptor.bNumConfigurations < 1) {
516 usbi_err (ctx, "device has no configurations");
517 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
520 /* find the first configuration */
521 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
522 priv->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
524 /* check if the device is already configured. there is probably a better way than iterating over the
525 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
526 might lock up on the device request) */
528 /* Setup the Interface Request */
529 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
530 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
531 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
532 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
534 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
536 return darwin_to_libusb (kresult);
539 firstInterface = IOIteratorNext(interface_iterator);
541 /* done with the interface iterator */
542 IOObjectRelease(interface_iterator);
544 if (firstInterface) {
545 IOObjectRelease (firstInterface);
547 /* device is configured */
548 if (priv->dev_descriptor.bNumConfigurations == 1)
549 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
550 priv->active_config = priv->first_config;
552 /* devices with more than one configuration should work with GetConfiguration */
553 (*darwin_device)->GetConfiguration (darwin_device, &priv->active_config);
556 priv->active_config = 0;
558 usbi_info (ctx, "active config: %u, first config: %u", priv->active_config, priv->first_config);
563 static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct libusb_device *dev, usb_device_t **device) {
564 struct darwin_device_priv *priv;
565 int retries = 5, delay = 30000;
566 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
571 UInt16 idProduct, idVendor;
573 (*device)->GetDeviceClass (device, &bDeviceClass);
574 (*device)->GetDeviceProduct (device, &idProduct);
575 (*device)->GetDeviceVendor (device, &idVendor);
577 priv = (struct darwin_device_priv *)dev->os_priv;
579 /* try to open the device (we can usually continue even if this fails) */
580 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
582 /**** retrieve device descriptor ****/
584 /* Set up request for device descriptor */
585 memset (&(priv->dev_descriptor), 0, sizeof(IOUSBDeviceDescriptor));
586 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
587 req.bRequest = kUSBRqGetDescriptor;
588 req.wValue = kUSBDeviceDesc << 8;
590 req.wLength = sizeof(priv->dev_descriptor);
591 req.pData = &(priv->dev_descriptor);
593 /* according to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
594 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
595 * to follow the spec as closely as possible, try opening the device */
597 ret = (*(device))->DeviceRequest (device, &req);
599 if (kIOReturnOverrun == ret && kUSBDeviceDesc == priv->dev_descriptor.bDescriptorType)
600 /* received an overrun error but we still received a device descriptor */
601 ret = kIOReturnSuccess;
603 if (kIOReturnSuccess == ret && (0 == priv->dev_descriptor.idProduct ||
604 0 == priv->dev_descriptor.bNumConfigurations ||
605 0 == priv->dev_descriptor.bcdUSB)) {
606 /* work around for incorrectly configured devices */
607 if (try_reconfigure && is_open) {
608 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
610 /* set the first configuration */
611 (*device)->SetConfiguration(device, 1);
613 /* don't try to reconfigure again */
617 ret = kIOUSBPipeStalled;
620 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
621 /* device may be suspended. unsuspend it and try again */
622 #if DeviceVersion >= 320
625 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
626 (void)(*device)->GetUSBDeviceInformation (device, &info);
628 try_unsuspend = info & (1 << kUSBInformationDeviceIsSuspendedBit);
632 /* resume the device */
633 ret2 = (*device)->USBDeviceSuspend (device, 0);
634 if (kIOReturnSuccess != ret2) {
635 /* prevent log spew from poorly behaving devices. this indicates the
636 os actually had trouble communicating with the device */
637 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
645 if (kIOReturnSuccess != ret) {
646 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
647 /* sleep for a little while before trying again */
650 } while (kIOReturnSuccess != ret && retries--);
653 /* resuspend the device */
654 (void)(*device)->USBDeviceSuspend (device, 1);
657 (void) (*device)->USBDeviceClose (device);
659 if (ret != kIOReturnSuccess) {
660 /* a debug message was already printed out for this error */
661 if (LIBUSB_CLASS_HUB == bDeviceClass)
662 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s. skipping device", idVendor, idProduct, darwin_error_str (ret));
664 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s. skipping device", idVendor, idProduct, darwin_error_str (ret));
669 usbi_dbg ("device descriptor:");
670 usbi_dbg (" bDescriptorType: 0x%02x", priv->dev_descriptor.bDescriptorType);
671 usbi_dbg (" bcdUSB: 0x%04x", priv->dev_descriptor.bcdUSB);
672 usbi_dbg (" bDeviceClass: 0x%02x", priv->dev_descriptor.bDeviceClass);
673 usbi_dbg (" bDeviceSubClass: 0x%02x", priv->dev_descriptor.bDeviceSubClass);
674 usbi_dbg (" bDeviceProtocol: 0x%02x", priv->dev_descriptor.bDeviceProtocol);
675 usbi_dbg (" bMaxPacketSize0: 0x%02x", priv->dev_descriptor.bMaxPacketSize0);
676 usbi_dbg (" idVendor: 0x%04x", priv->dev_descriptor.idVendor);
677 usbi_dbg (" idProduct: 0x%04x", priv->dev_descriptor.idProduct);
678 usbi_dbg (" bcdDevice: 0x%04x", priv->dev_descriptor.bcdDevice);
679 usbi_dbg (" iManufacturer: 0x%02x", priv->dev_descriptor.iManufacturer);
680 usbi_dbg (" iProduct: 0x%02x", priv->dev_descriptor.iProduct);
681 usbi_dbg (" iSerialNumber: 0x%02x", priv->dev_descriptor.iSerialNumber);
682 usbi_dbg (" bNumConfigurations: 0x%02x", priv->dev_descriptor.bNumConfigurations);
684 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
685 if (libusb_le16_to_cpu (priv->dev_descriptor.idProduct) != idProduct) {
686 /* not a valid device */
687 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
688 idProduct, libusb_le16_to_cpu (priv->dev_descriptor.idProduct));
695 static int process_new_device (struct libusb_context *ctx, usb_device_t **device, UInt32 locationID, struct discovered_devs **_discdevs) {
696 struct darwin_device_priv *priv;
697 struct libusb_device *dev;
698 struct discovered_devs *discdevs;
701 int ret = 0, need_unref = 0;
704 dev = usbi_get_device_by_session_id(ctx, locationID);
706 usbi_info (ctx, "allocating new device for location 0x%08x", locationID);
707 dev = usbi_alloc_device(ctx, locationID);
710 usbi_info (ctx, "using existing device for location 0x%08x", locationID);
713 ret = LIBUSB_ERROR_NO_MEM;
717 priv = (struct darwin_device_priv *)dev->os_priv;
719 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&address);
721 ret = darwin_cache_device_descriptor (ctx, dev, device);
725 /* check current active configuration (and cache the first configuration value-- which may be used by claim_interface) */
726 ret = darwin_check_configuration (ctx, dev, device);
730 dev->bus_number = locationID >> 24;
731 dev->device_address = address;
733 (*device)->GetDeviceSpeed (device, &devSpeed);
736 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
737 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
738 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
740 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
743 /* save our location, we'll need this later */
744 priv->location = locationID;
745 snprintf(priv->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", address, priv->dev_descriptor.idVendor, priv->dev_descriptor.idProduct,
746 priv->dev_descriptor.bDeviceClass, priv->dev_descriptor.bDeviceSubClass);
748 ret = usbi_sanitize_device (dev);
752 /* append the device to the list of discovered devices */
753 discdevs = discovered_devs_append(*_discdevs, dev);
755 ret = LIBUSB_ERROR_NO_MEM;
759 *_discdevs = discdevs;
761 usbi_info (ctx, "found device with address %d at %s", dev->device_address, priv->sys_path);
765 libusb_unref_device(dev);
770 static int darwin_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs) {
771 io_iterator_t deviceIterator;
772 usb_device_t **device;
773 kern_return_t kresult;
776 kresult = usb_setup_device_iterator (&deviceIterator, 0);
777 if (kresult != kIOReturnSuccess)
778 return darwin_to_libusb (kresult);
780 while ((device = usb_get_next_device (deviceIterator, &location)) != NULL) {
781 (void) process_new_device (ctx, device, location, _discdevs);
783 (*(device))->Release(device);
786 IOObjectRelease(deviceIterator);
791 static int darwin_open (struct libusb_device_handle *dev_handle) {
792 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
793 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
794 usb_device_t **darwin_device;
797 if (0 == dpriv->open_count) {
798 kresult = darwin_get_device (dpriv->location, &darwin_device);
800 usbi_err (HANDLE_CTX (dev_handle), "could not find device: %s", darwin_error_str (kresult));
801 return darwin_to_libusb (kresult);
804 dpriv->device = darwin_device;
806 /* try to open the device */
807 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
809 if (kresult != kIOReturnSuccess) {
810 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
813 case kIOReturnExclusiveAccess:
814 /* it is possible to perform some actions on a device that is not open so do not return an error */
819 (*(dpriv->device))->Release (dpriv->device);
820 dpriv->device = NULL;
821 return darwin_to_libusb (kresult);
824 /* create async event source */
825 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
826 if (kresult != kIOReturnSuccess) {
827 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
829 (*(dpriv->device))->USBDeviceClose (dpriv->device);
830 (*(dpriv->device))->Release (dpriv->device);
832 dpriv->device = NULL;
833 return darwin_to_libusb (kresult);
838 CFRetain (libusb_darwin_acfl);
840 /* add the cfSource to the aync run loop */
841 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
845 /* device opened successfully */
848 /* create a file descriptor for notifications */
851 /* set the pipe to be non-blocking */
852 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
854 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
856 usbi_info (HANDLE_CTX (dev_handle), "device open for access");
861 static void darwin_close (struct libusb_device_handle *dev_handle) {
862 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
863 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
867 if (dpriv->open_count == 0) {
868 /* something is probably very wrong if this is the case */
869 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
875 /* make sure all interfaces are released */
876 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
877 if (dev_handle->claimed_interfaces & (1 << i))
878 libusb_release_interface (dev_handle, i);
880 if (0 == dpriv->open_count) {
882 /* delete the device's async event source */
883 if (priv->cfSource) {
884 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
885 CFRelease (priv->cfSource);
888 /* close the device */
889 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
891 /* Log the fact that we had a problem closing the file, however failing a
892 * close isn't really an error, so return success anyway */
893 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
897 kresult = (*(dpriv->device))->Release(dpriv->device);
899 /* Log the fact that we had a problem closing the file, however failing a
900 * close isn't really an error, so return success anyway */
901 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
904 dpriv->device = NULL;
907 /* file descriptors are maintained per-instance */
908 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
909 close (priv->fds[1]);
910 close (priv->fds[0]);
912 priv->fds[0] = priv->fds[1] = -1;
915 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
916 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
918 *config = (int) dpriv->active_config;
923 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
924 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
928 /* Setting configuration will invalidate the interface, so we need
929 to reclaim it. First, dispose of existing interfaces, if any. */
930 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
931 if (dev_handle->claimed_interfaces & (1 << i))
932 darwin_release_interface (dev_handle, i);
934 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
935 if (kresult != kIOReturnSuccess)
936 return darwin_to_libusb (kresult);
938 /* Reclaim any interfaces. */
939 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
940 if (dev_handle->claimed_interfaces & (1 << i))
941 darwin_claim_interface (dev_handle, i);
943 dpriv->active_config = config;
948 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
949 IOUSBFindInterfaceRequest request;
950 uint8_t current_interface;
951 kern_return_t kresult;
952 io_iterator_t interface_iterator;
954 *usbInterfacep = IO_OBJECT_NULL;
956 /* Setup the Interface Request */
957 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
958 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
959 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
960 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
962 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
966 for ( current_interface = 0 ; current_interface <= ifc ; current_interface++ ) {
967 *usbInterfacep = IOIteratorNext(interface_iterator);
968 if (current_interface != ifc)
969 (void) IOObjectRelease (*usbInterfacep);
972 /* done with the interface iterator */
973 IOObjectRelease(interface_iterator);
978 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
979 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
981 /* current interface */
982 struct darwin_interface *cInterface = &priv->interfaces[iface];
984 kern_return_t kresult;
986 u_int8_t numep, direction, number;
987 u_int8_t dont_care1, dont_care3;
988 u_int16_t dont_care2;
991 usbi_info (HANDLE_CTX (dev_handle), "building table of endpoints.");
993 /* retrieve the total number of endpoints on this interface */
994 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
996 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
997 return darwin_to_libusb (kresult);
1000 /* iterate through pipe references */
1001 for (i = 1 ; i <= numep ; i++) {
1002 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1003 &dont_care2, &dont_care3);
1005 if (kresult != kIOReturnSuccess) {
1006 usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
1008 return darwin_to_libusb (kresult);
1011 usbi_info (HANDLE_CTX (dev_handle), "interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
1013 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1016 cInterface->num_endpoints = numep;
1021 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1022 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1023 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1024 io_service_t usbInterface = IO_OBJECT_NULL;
1026 IOCFPlugInInterface **plugInInterface = NULL;
1029 /* current interface */
1030 struct darwin_interface *cInterface = &priv->interfaces[iface];
1032 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1033 if (kresult != kIOReturnSuccess)
1034 return darwin_to_libusb (kresult);
1036 /* make sure we have an interface */
1037 if (!usbInterface && dpriv->first_config != 0) {
1038 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1040 /* set the configuration */
1041 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1042 if (kresult != LIBUSB_SUCCESS) {
1043 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1047 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1049 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1050 return darwin_to_libusb (kresult);
1054 if (!usbInterface) {
1055 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1056 return LIBUSB_ERROR_NOT_FOUND;
1059 /* get an interface to the device's interface */
1060 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1061 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1063 /* ignore release error */
1064 (void)IOObjectRelease (usbInterface);
1067 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1068 return darwin_to_libusb (kresult);
1071 if (!plugInInterface) {
1072 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1073 return LIBUSB_ERROR_NOT_FOUND;
1076 /* Do the actual claim */
1077 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1078 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1079 (LPVOID)&cInterface->interface);
1080 /* We no longer need the intermediate plug-in */
1081 IODestroyPlugInInterface (plugInInterface);
1082 if (kresult || !cInterface->interface) {
1083 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1084 return darwin_to_libusb (kresult);
1087 /* claim the interface */
1088 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1090 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1091 return darwin_to_libusb (kresult);
1094 /* update list of endpoints */
1095 kresult = get_endpoints (dev_handle, iface);
1097 /* this should not happen */
1098 darwin_release_interface (dev_handle, iface);
1099 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1103 cInterface->cfSource = NULL;
1105 /* create async event source */
1106 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1107 if (kresult != kIOReturnSuccess) {
1108 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1110 /* can't continue without an async event source */
1111 (void)darwin_release_interface (dev_handle, iface);
1113 return darwin_to_libusb (kresult);
1116 /* add the cfSource to the async thread's run loop */
1117 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1119 usbi_info (HANDLE_CTX (dev_handle), "interface opened");
1124 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1125 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1128 /* current interface */
1129 struct darwin_interface *cInterface = &priv->interfaces[iface];
1131 /* Check to see if an interface is open */
1132 if (!cInterface->interface)
1133 return LIBUSB_SUCCESS;
1135 /* clean up endpoint data */
1136 cInterface->num_endpoints = 0;
1138 /* delete the interface's async event source */
1139 if (cInterface->cfSource) {
1140 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1141 CFRelease (cInterface->cfSource);
1144 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1146 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1148 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1149 if (kresult != kIOReturnSuccess)
1150 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1152 cInterface->interface = IO_OBJECT_NULL;
1154 return darwin_to_libusb (kresult);
1157 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1158 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1161 /* current interface */
1162 struct darwin_interface *cInterface = &priv->interfaces[iface];
1164 if (!cInterface->interface)
1165 return LIBUSB_ERROR_NO_DEVICE;
1167 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1168 if (kresult != kIOReturnSuccess)
1169 darwin_reset_device (dev_handle);
1171 /* update list of endpoints */
1172 kresult = get_endpoints (dev_handle, iface);
1174 /* this should not happen */
1175 darwin_release_interface (dev_handle, iface);
1176 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1180 return darwin_to_libusb (kresult);
1183 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1184 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1186 /* current interface */
1187 struct darwin_interface *cInterface;
1188 uint8_t pipeRef, iface;
1191 /* determine the interface/endpoint to use */
1192 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
1193 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1195 return LIBUSB_ERROR_NOT_FOUND;
1198 cInterface = &priv->interfaces[iface];
1200 #if (InterfaceVersion < 190)
1201 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1203 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1204 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1207 usbi_err (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1209 return darwin_to_libusb (kresult);
1212 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1213 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1216 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1218 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1220 return darwin_to_libusb (kresult);
1223 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1224 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1225 io_service_t usbInterface;
1229 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1231 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1233 return darwin_to_libusb (kresult);
1236 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1237 IOObjectRelease (usbInterface);
1249 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1250 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1253 return LIBUSB_ERROR_NOT_SUPPORTED;
1256 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1259 return LIBUSB_ERROR_NOT_SUPPORTED;
1262 static void darwin_destroy_device(struct libusb_device *dev) {
1266 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1267 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1268 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1271 uint8_t is_read; /* 0 = we're reading, 1 = we're writing */
1272 uint8_t transferType;
1273 /* None of the values below are used in libusb for bulk transfers */
1274 uint8_t direction, number, interval, pipeRef, iface;
1275 uint16_t maxPacketSize;
1277 struct darwin_interface *cInterface;
1279 /* are we reading or writing? */
1280 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1282 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1283 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1285 return LIBUSB_ERROR_NOT_FOUND;
1288 cInterface = &priv->interfaces[iface];
1290 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1291 &transferType, &maxPacketSize, &interval);
1293 /* submit the request */
1294 /* timeouts are unavailable on interrupt endpoints */
1295 if (transferType == kUSBInterrupt) {
1297 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1298 transfer->length, darwin_async_io_callback, itransfer);
1300 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1301 transfer->length, darwin_async_io_callback, itransfer);
1303 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1306 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1307 transfer->length, transfer->timeout, transfer->timeout,
1308 darwin_async_io_callback, (void *)itransfer);
1310 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1311 transfer->length, transfer->timeout, transfer->timeout,
1312 darwin_async_io_callback, (void *)itransfer);
1316 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", is_read ? "In" : "Out",
1317 darwin_error_str(ret), ret);
1319 return darwin_to_libusb (ret);
1322 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1323 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1324 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1325 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1328 uint8_t is_read; /* 0 = we're writing, 1 = we're reading */
1329 uint8_t pipeRef, iface;
1331 AbsoluteTime atTime;
1334 struct darwin_interface *cInterface;
1336 /* are we reading or writing? */
1337 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1339 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1340 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1341 free(tpriv->isoc_framelist);
1342 tpriv->isoc_framelist = NULL;
1345 if (!tpriv->isoc_framelist) {
1346 tpriv->num_iso_packets = transfer->num_iso_packets;
1347 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1348 if (!tpriv->isoc_framelist)
1349 return LIBUSB_ERROR_NO_MEM;
1352 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1353 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1354 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1356 /* determine the interface/endpoint to use */
1357 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1358 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1360 return LIBUSB_ERROR_NOT_FOUND;
1363 cInterface = &priv->interfaces[iface];
1365 /* Last but not least we need the bus frame number */
1366 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1368 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1369 free(tpriv->isoc_framelist);
1370 tpriv->isoc_framelist = NULL;
1372 return darwin_to_libusb (kresult);
1375 /* schedule for a frame a little in the future */
1378 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1379 frame = cInterface->frames[transfer->endpoint];
1381 /* submit the request */
1383 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1384 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1387 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1388 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1391 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets / 8;
1393 if (kresult != kIOReturnSuccess) {
1394 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", is_read ? "In" : "Out",
1395 darwin_error_str(kresult));
1396 free (tpriv->isoc_framelist);
1397 tpriv->isoc_framelist = NULL;
1400 return darwin_to_libusb (kresult);
1403 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1404 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1405 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1406 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1407 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1408 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1412 bzero(&tpriv->req, sizeof(tpriv->req));
1414 /* IOUSBDeviceInterface expects the request in cpu endianess */
1415 tpriv->req.bmRequestType = setup->bmRequestType;
1416 tpriv->req.bRequest = setup->bRequest;
1417 /* these values should be in bus order from libusb_fill_control_setup */
1418 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1419 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1420 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1421 /* data is stored after the libusb control block */
1422 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1423 tpriv->req.completionTimeout = transfer->timeout;
1424 tpriv->req.noDataTimeout = transfer->timeout;
1426 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1428 /* all transfers in libusb-1.0 are async */
1430 if (transfer->endpoint) {
1431 struct darwin_interface *cInterface;
1432 uint8_t pipeRef, iface;
1434 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1435 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1437 return LIBUSB_ERROR_NOT_FOUND;
1440 cInterface = &priv->interfaces[iface];
1442 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1444 /* control request on endpoint 0 */
1445 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1447 if (kresult != kIOReturnSuccess)
1448 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1450 return darwin_to_libusb (kresult);
1453 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1454 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1456 switch (transfer->type) {
1457 case LIBUSB_TRANSFER_TYPE_CONTROL:
1458 return submit_control_transfer(itransfer);
1459 case LIBUSB_TRANSFER_TYPE_BULK:
1460 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1461 return submit_bulk_transfer(itransfer);
1462 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1463 return submit_iso_transfer(itransfer);
1465 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1466 return LIBUSB_ERROR_INVALID_PARAM;
1470 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1471 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1472 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1475 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions control pipe");
1478 return LIBUSB_ERROR_NO_DEVICE;
1480 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1482 return darwin_to_libusb (kresult);
1485 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1486 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1487 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1488 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1489 struct darwin_interface *cInterface;
1490 uint8_t pipeRef, iface;
1493 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1494 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1496 return LIBUSB_ERROR_NOT_FOUND;
1499 cInterface = &priv->interfaces[iface];
1502 return LIBUSB_ERROR_NO_DEVICE;
1504 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions on interface %d pipe %d", iface, pipeRef);
1506 /* abort transactions */
1507 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1509 usbi_info (ITRANSFER_CTX (itransfer), "calling clear pipe stall to clear the data toggle bit");
1511 /* clear the data toggle bit */
1512 #if (InterfaceVersion < 190)
1513 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1515 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1516 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1519 return darwin_to_libusb (kresult);
1522 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1523 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1525 switch (transfer->type) {
1526 case LIBUSB_TRANSFER_TYPE_CONTROL:
1527 return cancel_control_transfer(itransfer);
1528 case LIBUSB_TRANSFER_TYPE_BULK:
1529 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1530 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1531 return darwin_abort_transfers (itransfer);
1533 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1534 return LIBUSB_ERROR_INVALID_PARAM;
1538 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1539 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1540 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1542 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1543 free (tpriv->isoc_framelist);
1544 tpriv->isoc_framelist = NULL;
1548 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1549 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1550 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1551 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1552 UInt32 message, size;
1554 usbi_info (ITRANSFER_CTX (itransfer), "an async io operation has completed");
1556 size = (UInt32) arg0;
1558 /* send a completion message to the device's file descriptor */
1559 message = MESSAGE_ASYNC_IO_COMPLETE;
1560 write (priv->fds[1], &message, sizeof (message));
1561 write (priv->fds[1], &itransfer, sizeof (itransfer));
1562 write (priv->fds[1], &result, sizeof (IOReturn));
1563 write (priv->fds[1], &size, sizeof (size));
1566 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1567 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT)
1568 result = kIOUSBTransactionTimeout;
1571 case kIOReturnUnderrun:
1572 case kIOReturnSuccess:
1573 return LIBUSB_TRANSFER_COMPLETED;
1574 case kIOReturnAborted:
1575 return LIBUSB_TRANSFER_CANCELLED;
1576 case kIOUSBPipeStalled:
1577 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: pipe is stalled");
1578 return LIBUSB_TRANSFER_STALL;
1579 case kIOReturnOverrun:
1580 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1581 return LIBUSB_TRANSFER_OVERFLOW;
1582 case kIOUSBTransactionTimeout:
1583 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1584 itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
1585 return LIBUSB_TRANSFER_TIMED_OUT;
1587 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1588 return LIBUSB_TRANSFER_ERROR;
1592 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1593 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1594 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1595 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1596 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1597 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1598 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1601 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1602 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1606 usbi_info (ITRANSFER_CTX (itransfer), "handling %s completion with kernel status %d",
1607 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
1609 if (kIOReturnSuccess == result || kIOReturnUnderrun == result) {
1610 if (isIsoc && tpriv->isoc_framelist) {
1611 /* copy isochronous results back */
1613 for (i = 0; i < transfer->num_iso_packets ; i++) {
1614 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1615 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1616 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1619 itransfer->transferred += io_size;
1622 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1623 usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
1626 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready) {
1627 struct usbi_transfer *itransfer;
1630 POLL_NFDS_TYPE i = 0;
1634 usbi_mutex_lock(&ctx->open_devs_lock);
1635 for (i = 0; i < nfds && num_ready > 0; i++) {
1636 struct pollfd *pollfd = &fds[i];
1637 struct libusb_device_handle *handle;
1638 struct darwin_device_handle_priv *hpriv = NULL;
1640 usbi_info (ctx, "checking fd %i with revents = %x", fds[i], pollfd->revents);
1642 if (!pollfd->revents)
1646 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
1647 hpriv = (struct darwin_device_handle_priv *)handle->os_priv;
1648 if (hpriv->fds[0] == pollfd->fd)
1652 if (!(pollfd->revents & POLLERR)) {
1653 ret = read (hpriv->fds[0], &message, sizeof (message));
1654 if (ret < (ssize_t)sizeof (message))
1657 /* could not poll the device-- response is to delete the device (this seems a little heavy-handed) */
1658 message = MESSAGE_DEVICE_GONE;
1661 case MESSAGE_DEVICE_GONE:
1662 /* remove the device's async port from the runloop */
1663 if (hpriv->cfSource) {
1664 if (libusb_darwin_acfl)
1665 CFRunLoopRemoveSource (libusb_darwin_acfl, hpriv->cfSource, kCFRunLoopDefaultMode);
1666 CFRelease (hpriv->cfSource);
1667 hpriv->cfSource = NULL;
1670 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1671 usbi_handle_disconnect(handle);
1673 /* done with this device */
1675 case MESSAGE_ASYNC_IO_COMPLETE:
1676 read (hpriv->fds[0], &itransfer, sizeof (itransfer));
1677 read (hpriv->fds[0], &kresult, sizeof (IOReturn));
1678 read (hpriv->fds[0], &io_size, sizeof (UInt32));
1680 darwin_handle_callback (itransfer, kresult, io_size);
1683 usbi_err (ctx, "unknown message received from device pipe");
1687 usbi_mutex_unlock(&ctx->open_devs_lock);
1692 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1693 mach_timespec_t sys_time;
1694 clock_serv_t clock_ref;
1697 case USBI_CLOCK_REALTIME:
1698 /* CLOCK_REALTIME represents time since the epoch */
1699 clock_ref = clock_realtime;
1701 case USBI_CLOCK_MONOTONIC:
1702 /* use system boot time as reference for the monotonic clock */
1703 clock_ref = clock_monotonic;
1706 return LIBUSB_ERROR_INVALID_PARAM;
1709 clock_get_time (clock_ref, &sys_time);
1711 tp->tv_sec = sys_time.tv_sec;
1712 tp->tv_nsec = sys_time.tv_nsec;
1717 const struct usbi_os_backend darwin_backend = {
1719 .init = darwin_init,
1720 .exit = darwin_exit,
1721 .get_device_list = darwin_get_device_list,
1722 .get_device_descriptor = darwin_get_device_descriptor,
1723 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1724 .get_config_descriptor = darwin_get_config_descriptor,
1726 .open = darwin_open,
1727 .close = darwin_close,
1728 .get_configuration = darwin_get_configuration,
1729 .set_configuration = darwin_set_configuration,
1730 .claim_interface = darwin_claim_interface,
1731 .release_interface = darwin_release_interface,
1733 .set_interface_altsetting = darwin_set_interface_altsetting,
1734 .clear_halt = darwin_clear_halt,
1735 .reset_device = darwin_reset_device,
1737 .kernel_driver_active = darwin_kernel_driver_active,
1738 .detach_kernel_driver = darwin_detach_kernel_driver,
1739 .attach_kernel_driver = darwin_attach_kernel_driver,
1741 .destroy_device = darwin_destroy_device,
1743 .submit_transfer = darwin_submit_transfer,
1744 .cancel_transfer = darwin_cancel_transfer,
1745 .clear_transfer_priv = darwin_clear_transfer_priv,
1747 .handle_events = op_handle_events,
1749 .clock_gettime = darwin_clock_gettime,
1751 .device_priv_size = sizeof(struct darwin_device_priv),
1752 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1753 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1754 .add_iso_packet_size = 0,