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 /* let the main thread know about the async runloop */
362 libusb_darwin_acfl = runloop;
364 /* signal the main thread */
365 pthread_mutex_lock (&libusb_darwin_at_mutex);
366 pthread_cond_signal (&libusb_darwin_at_cond);
367 pthread_mutex_unlock (&libusb_darwin_at_mutex);
369 /* run the runloop */
372 usbi_info (ctx, "thread exiting");
374 /* delete notification port */
375 IONotificationPortDestroy (libusb_notification_port);
376 IOObjectRelease (libusb_rem_device_iterator);
380 libusb_darwin_acfl = NULL;
385 static int darwin_init(struct libusb_context *ctx) {
386 host_name_port_t host_self;
388 if (OSAtomicIncrement32Barrier(&initCount) == 1) {
389 /* create the clocks that will be used */
391 host_self = mach_host_self();
392 host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
393 host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
394 mach_port_deallocate(mach_task_self(), host_self);
396 pthread_mutex_init (&libusb_darwin_at_mutex, NULL);
397 pthread_cond_init (&libusb_darwin_at_cond, NULL);
399 pthread_create (&libusb_darwin_at, NULL, event_thread_main, (void *)ctx);
401 pthread_mutex_lock (&libusb_darwin_at_mutex);
402 while (!libusb_darwin_acfl)
403 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
404 pthread_mutex_unlock (&libusb_darwin_at_mutex);
410 static void darwin_exit (void) {
411 if (OSAtomicDecrement32Barrier(&initCount) == 0) {
412 mach_port_deallocate(mach_task_self(), clock_realtime);
413 mach_port_deallocate(mach_task_self(), clock_monotonic);
415 /* stop the async runloop */
416 CFRunLoopStop (libusb_darwin_acfl);
417 pthread_join (libusb_darwin_at, NULL);
421 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
422 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
424 /* return cached copy */
425 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
432 static int get_configuration_index (struct libusb_device *dev, int config_value) {
433 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
435 IOUSBConfigurationDescriptorPtr desc;
438 /* is there a simpler way to determine the index? */
439 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
440 if (kresult != kIOReturnSuccess)
441 return darwin_to_libusb (kresult);
443 for (i = 0 ; i < numConfig ; i++) {
444 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
446 if (desc->bConfigurationValue == config_value)
450 /* configuration not found */
451 return LIBUSB_ERROR_OTHER;
454 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
455 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
458 if (0 == priv->active_config)
459 return LIBUSB_ERROR_INVALID_PARAM;
461 config_index = get_configuration_index (dev, priv->active_config);
462 if (config_index < 0)
465 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
468 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
469 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
470 IOUSBConfigurationDescriptorPtr desc;
472 usb_device_t **device = NULL;
475 return LIBUSB_ERROR_OTHER;
478 kresult = darwin_get_device (priv->location, &device);
479 if (kresult || !device) {
480 usbi_err (DEVICE_CTX (dev), "could not find device: %s", darwin_error_str (kresult));
482 return darwin_to_libusb (kresult);
485 /* don't have to open the device to get a config descriptor */
487 device = priv->device;
489 kresult = (*device)->GetConfigurationDescriptorPtr (device, config_index, &desc);
490 if (kresult == kIOReturnSuccess) {
491 /* copy descriptor */
492 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
493 len = libusb_le16_to_cpu(desc->wTotalLength);
495 memmove (buffer, desc, len);
497 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
502 (*device)->Release (device);
504 return darwin_to_libusb (kresult);
507 /* check whether the os has configured the device */
508 static int darwin_check_configuration (struct libusb_context *ctx, struct libusb_device *dev, usb_device_t **darwin_device) {
509 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
511 IOUSBConfigurationDescriptorPtr configDesc;
512 IOUSBFindInterfaceRequest request;
513 kern_return_t kresult;
514 io_iterator_t interface_iterator;
515 io_service_t firstInterface;
517 if (priv->dev_descriptor.bNumConfigurations < 1) {
518 usbi_err (ctx, "device has no configurations");
519 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
522 /* find the first configuration */
523 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
524 priv->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
526 /* check if the device is already configured. there is probably a better way than iterating over the
527 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
528 might lock up on the device request) */
530 /* Setup the Interface Request */
531 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
532 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
533 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
534 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
536 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
538 return darwin_to_libusb (kresult);
541 firstInterface = IOIteratorNext(interface_iterator);
543 /* done with the interface iterator */
544 IOObjectRelease(interface_iterator);
546 if (firstInterface) {
547 IOObjectRelease (firstInterface);
549 /* device is configured */
550 if (priv->dev_descriptor.bNumConfigurations == 1)
551 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
552 priv->active_config = priv->first_config;
554 /* devices with more than one configuration should work with GetConfiguration */
555 (*darwin_device)->GetConfiguration (darwin_device, &priv->active_config);
558 priv->active_config = 0;
560 usbi_info (ctx, "active config: %u, first config: %u", priv->active_config, priv->first_config);
565 static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct libusb_device *dev, usb_device_t **device) {
566 struct darwin_device_priv *priv;
567 int retries = 5, delay = 30000;
568 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
573 UInt16 idProduct, idVendor;
575 (*device)->GetDeviceClass (device, &bDeviceClass);
576 (*device)->GetDeviceProduct (device, &idProduct);
577 (*device)->GetDeviceVendor (device, &idVendor);
579 priv = (struct darwin_device_priv *)dev->os_priv;
581 /* try to open the device (we can usually continue even if this fails) */
582 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
584 /**** retrieve device descriptor ****/
586 /* Set up request for device descriptor */
587 memset (&(priv->dev_descriptor), 0, sizeof(IOUSBDeviceDescriptor));
588 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
589 req.bRequest = kUSBRqGetDescriptor;
590 req.wValue = kUSBDeviceDesc << 8;
592 req.wLength = sizeof(priv->dev_descriptor);
593 req.pData = &(priv->dev_descriptor);
595 /* according to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
596 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
597 * to follow the spec as closely as possible, try opening the device */
599 ret = (*(device))->DeviceRequest (device, &req);
601 if (kIOReturnOverrun == ret && kUSBDeviceDesc == priv->dev_descriptor.bDescriptorType)
602 /* received an overrun error but we still received a device descriptor */
603 ret = kIOReturnSuccess;
605 if (kIOReturnSuccess == ret && (0 == priv->dev_descriptor.idProduct ||
606 0 == priv->dev_descriptor.bNumConfigurations ||
607 0 == priv->dev_descriptor.bcdUSB)) {
608 /* work around for incorrectly configured devices */
609 if (try_reconfigure && is_open) {
610 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
612 /* set the first configuration */
613 (*device)->SetConfiguration(device, 1);
615 /* don't try to reconfigure again */
619 ret = kIOUSBPipeStalled;
622 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
623 /* device may be suspended. unsuspend it and try again */
624 #if DeviceVersion >= 320
627 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
628 (void)(*device)->GetUSBDeviceInformation (device, &info);
630 try_unsuspend = info & (1 << kUSBInformationDeviceIsSuspendedBit);
634 /* resume the device */
635 ret2 = (*device)->USBDeviceSuspend (device, 0);
636 if (kIOReturnSuccess != ret2) {
637 /* prevent log spew from poorly behaving devices. this indicates the
638 os actually had trouble communicating with the device */
639 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
647 if (kIOReturnSuccess != ret) {
648 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
649 /* sleep for a little while before trying again */
652 } while (kIOReturnSuccess != ret && retries--);
655 /* resuspend the device */
656 (void)(*device)->USBDeviceSuspend (device, 1);
659 (void) (*device)->USBDeviceClose (device);
661 if (ret != kIOReturnSuccess) {
662 /* a debug message was already printed out for this error */
663 if (LIBUSB_CLASS_HUB == bDeviceClass)
664 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s. skipping device", idVendor, idProduct, darwin_error_str (ret));
666 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s. skipping device", idVendor, idProduct, darwin_error_str (ret));
671 usbi_dbg ("device descriptor:");
672 usbi_dbg (" bDescriptorType: 0x%02x", priv->dev_descriptor.bDescriptorType);
673 usbi_dbg (" bcdUSB: 0x%04x", priv->dev_descriptor.bcdUSB);
674 usbi_dbg (" bDeviceClass: 0x%02x", priv->dev_descriptor.bDeviceClass);
675 usbi_dbg (" bDeviceSubClass: 0x%02x", priv->dev_descriptor.bDeviceSubClass);
676 usbi_dbg (" bDeviceProtocol: 0x%02x", priv->dev_descriptor.bDeviceProtocol);
677 usbi_dbg (" bMaxPacketSize0: 0x%02x", priv->dev_descriptor.bMaxPacketSize0);
678 usbi_dbg (" idVendor: 0x%04x", priv->dev_descriptor.idVendor);
679 usbi_dbg (" idProduct: 0x%04x", priv->dev_descriptor.idProduct);
680 usbi_dbg (" bcdDevice: 0x%04x", priv->dev_descriptor.bcdDevice);
681 usbi_dbg (" iManufacturer: 0x%02x", priv->dev_descriptor.iManufacturer);
682 usbi_dbg (" iProduct: 0x%02x", priv->dev_descriptor.iProduct);
683 usbi_dbg (" iSerialNumber: 0x%02x", priv->dev_descriptor.iSerialNumber);
684 usbi_dbg (" bNumConfigurations: 0x%02x", priv->dev_descriptor.bNumConfigurations);
686 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
687 if (libusb_le16_to_cpu (priv->dev_descriptor.idProduct) != idProduct) {
688 /* not a valid device */
689 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
690 idProduct, libusb_le16_to_cpu (priv->dev_descriptor.idProduct));
697 static int process_new_device (struct libusb_context *ctx, usb_device_t **device, UInt32 locationID, struct discovered_devs **_discdevs) {
698 struct darwin_device_priv *priv;
699 struct libusb_device *dev;
700 struct discovered_devs *discdevs;
703 int ret = 0, need_unref = 0;
706 dev = usbi_get_device_by_session_id(ctx, locationID);
708 usbi_info (ctx, "allocating new device for location 0x%08x", locationID);
709 dev = usbi_alloc_device(ctx, locationID);
712 usbi_info (ctx, "using existing device for location 0x%08x", locationID);
715 ret = LIBUSB_ERROR_NO_MEM;
719 priv = (struct darwin_device_priv *)dev->os_priv;
721 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&address);
723 ret = darwin_cache_device_descriptor (ctx, dev, device);
727 /* check current active configuration (and cache the first configuration value-- which may be used by claim_interface) */
728 ret = darwin_check_configuration (ctx, dev, device);
732 dev->bus_number = locationID >> 24;
733 dev->device_address = address;
735 (*device)->GetDeviceSpeed (device, &devSpeed);
738 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
739 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
740 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
742 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
745 /* save our location, we'll need this later */
746 priv->location = locationID;
747 snprintf(priv->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", address, priv->dev_descriptor.idVendor, priv->dev_descriptor.idProduct,
748 priv->dev_descriptor.bDeviceClass, priv->dev_descriptor.bDeviceSubClass);
750 ret = usbi_sanitize_device (dev);
754 /* append the device to the list of discovered devices */
755 discdevs = discovered_devs_append(*_discdevs, dev);
757 ret = LIBUSB_ERROR_NO_MEM;
761 *_discdevs = discdevs;
763 usbi_info (ctx, "found device with address %d at %s", dev->device_address, priv->sys_path);
767 libusb_unref_device(dev);
772 static int darwin_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs) {
773 io_iterator_t deviceIterator;
774 usb_device_t **device;
775 kern_return_t kresult;
778 kresult = usb_setup_device_iterator (&deviceIterator, 0);
779 if (kresult != kIOReturnSuccess)
780 return darwin_to_libusb (kresult);
782 while ((device = usb_get_next_device (deviceIterator, &location)) != NULL) {
783 (void) process_new_device (ctx, device, location, _discdevs);
785 (*(device))->Release(device);
788 IOObjectRelease(deviceIterator);
793 static int darwin_open (struct libusb_device_handle *dev_handle) {
794 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
795 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
796 usb_device_t **darwin_device;
799 if (0 == dpriv->open_count) {
800 kresult = darwin_get_device (dpriv->location, &darwin_device);
802 usbi_err (HANDLE_CTX (dev_handle), "could not find device: %s", darwin_error_str (kresult));
803 return darwin_to_libusb (kresult);
806 dpriv->device = darwin_device;
808 /* try to open the device */
809 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
811 if (kresult != kIOReturnSuccess) {
812 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
815 case kIOReturnExclusiveAccess:
816 /* it is possible to perform some actions on a device that is not open so do not return an error */
821 (*(dpriv->device))->Release (dpriv->device);
822 dpriv->device = NULL;
823 return darwin_to_libusb (kresult);
826 /* create async event source */
827 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
828 if (kresult != kIOReturnSuccess) {
829 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
831 (*(dpriv->device))->USBDeviceClose (dpriv->device);
832 (*(dpriv->device))->Release (dpriv->device);
834 dpriv->device = NULL;
835 return darwin_to_libusb (kresult);
840 CFRetain (libusb_darwin_acfl);
842 /* add the cfSource to the aync run loop */
843 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
847 /* device opened successfully */
850 /* create a file descriptor for notifications */
853 /* set the pipe to be non-blocking */
854 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
856 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
858 usbi_info (HANDLE_CTX (dev_handle), "device open for access");
863 static void darwin_close (struct libusb_device_handle *dev_handle) {
864 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
865 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
869 if (dpriv->open_count == 0) {
870 /* something is probably very wrong if this is the case */
871 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
877 /* make sure all interfaces are released */
878 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
879 if (dev_handle->claimed_interfaces & (1 << i))
880 libusb_release_interface (dev_handle, i);
882 if (0 == dpriv->open_count) {
884 /* delete the device's async event source */
885 if (priv->cfSource) {
886 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
887 CFRelease (priv->cfSource);
890 /* close the device */
891 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
893 /* Log the fact that we had a problem closing the file, however failing a
894 * close isn't really an error, so return success anyway */
895 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
899 kresult = (*(dpriv->device))->Release(dpriv->device);
901 /* Log the fact that we had a problem closing the file, however failing a
902 * close isn't really an error, so return success anyway */
903 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
906 dpriv->device = NULL;
909 /* file descriptors are maintained per-instance */
910 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
911 close (priv->fds[1]);
912 close (priv->fds[0]);
914 priv->fds[0] = priv->fds[1] = -1;
917 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
918 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
920 *config = (int) dpriv->active_config;
925 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
926 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
930 /* Setting configuration will invalidate the interface, so we need
931 to reclaim it. First, dispose of existing interfaces, if any. */
932 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
933 if (dev_handle->claimed_interfaces & (1 << i))
934 darwin_release_interface (dev_handle, i);
936 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
937 if (kresult != kIOReturnSuccess)
938 return darwin_to_libusb (kresult);
940 /* Reclaim any interfaces. */
941 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
942 if (dev_handle->claimed_interfaces & (1 << i))
943 darwin_claim_interface (dev_handle, i);
945 dpriv->active_config = config;
950 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
951 IOUSBFindInterfaceRequest request;
952 uint8_t current_interface;
953 kern_return_t kresult;
954 io_iterator_t interface_iterator;
956 *usbInterfacep = IO_OBJECT_NULL;
958 /* Setup the Interface Request */
959 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
960 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
961 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
962 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
964 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
968 for ( current_interface = 0 ; current_interface <= ifc ; current_interface++ ) {
969 *usbInterfacep = IOIteratorNext(interface_iterator);
970 if (current_interface != ifc)
971 (void) IOObjectRelease (*usbInterfacep);
974 /* done with the interface iterator */
975 IOObjectRelease(interface_iterator);
980 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
981 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
983 /* current interface */
984 struct darwin_interface *cInterface = &priv->interfaces[iface];
986 kern_return_t kresult;
988 u_int8_t numep, direction, number;
989 u_int8_t dont_care1, dont_care3;
990 u_int16_t dont_care2;
993 usbi_info (HANDLE_CTX (dev_handle), "building table of endpoints.");
995 /* retrieve the total number of endpoints on this interface */
996 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
998 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
999 return darwin_to_libusb (kresult);
1002 /* iterate through pipe references */
1003 for (i = 1 ; i <= numep ; i++) {
1004 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1005 &dont_care2, &dont_care3);
1007 if (kresult != kIOReturnSuccess) {
1008 usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
1010 return darwin_to_libusb (kresult);
1013 usbi_info (HANDLE_CTX (dev_handle), "interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
1015 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1018 cInterface->num_endpoints = numep;
1023 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1024 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1025 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1026 io_service_t usbInterface = IO_OBJECT_NULL;
1028 IOCFPlugInInterface **plugInInterface = NULL;
1031 /* current interface */
1032 struct darwin_interface *cInterface = &priv->interfaces[iface];
1034 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1035 if (kresult != kIOReturnSuccess)
1036 return darwin_to_libusb (kresult);
1038 /* make sure we have an interface */
1039 if (!usbInterface && dpriv->first_config != 0) {
1040 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1042 /* set the configuration */
1043 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1044 if (kresult != LIBUSB_SUCCESS) {
1045 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1049 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1051 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1052 return darwin_to_libusb (kresult);
1056 if (!usbInterface) {
1057 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1058 return LIBUSB_ERROR_NOT_FOUND;
1061 /* get an interface to the device's interface */
1062 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1063 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1065 /* ignore release error */
1066 (void)IOObjectRelease (usbInterface);
1069 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1070 return darwin_to_libusb (kresult);
1073 if (!plugInInterface) {
1074 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1075 return LIBUSB_ERROR_NOT_FOUND;
1078 /* Do the actual claim */
1079 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1080 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1081 (LPVOID)&cInterface->interface);
1082 /* We no longer need the intermediate plug-in */
1083 IODestroyPlugInInterface (plugInInterface);
1084 if (kresult || !cInterface->interface) {
1085 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1086 return darwin_to_libusb (kresult);
1089 /* claim the interface */
1090 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1092 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1093 return darwin_to_libusb (kresult);
1096 /* update list of endpoints */
1097 kresult = get_endpoints (dev_handle, iface);
1099 /* this should not happen */
1100 darwin_release_interface (dev_handle, iface);
1101 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1105 cInterface->cfSource = NULL;
1107 /* create async event source */
1108 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1109 if (kresult != kIOReturnSuccess) {
1110 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1112 /* can't continue without an async event source */
1113 (void)darwin_release_interface (dev_handle, iface);
1115 return darwin_to_libusb (kresult);
1118 /* add the cfSource to the async thread's run loop */
1119 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1121 usbi_info (HANDLE_CTX (dev_handle), "interface opened");
1126 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1127 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1130 /* current interface */
1131 struct darwin_interface *cInterface = &priv->interfaces[iface];
1133 /* Check to see if an interface is open */
1134 if (!cInterface->interface)
1135 return LIBUSB_SUCCESS;
1137 /* clean up endpoint data */
1138 cInterface->num_endpoints = 0;
1140 /* delete the interface's async event source */
1141 if (cInterface->cfSource) {
1142 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1143 CFRelease (cInterface->cfSource);
1146 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1148 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1150 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1151 if (kresult != kIOReturnSuccess)
1152 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1154 cInterface->interface = IO_OBJECT_NULL;
1156 return darwin_to_libusb (kresult);
1159 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1160 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1163 /* current interface */
1164 struct darwin_interface *cInterface = &priv->interfaces[iface];
1166 if (!cInterface->interface)
1167 return LIBUSB_ERROR_NO_DEVICE;
1169 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1170 if (kresult != kIOReturnSuccess)
1171 darwin_reset_device (dev_handle);
1173 /* update list of endpoints */
1174 kresult = get_endpoints (dev_handle, iface);
1176 /* this should not happen */
1177 darwin_release_interface (dev_handle, iface);
1178 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1182 return darwin_to_libusb (kresult);
1185 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1186 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1188 /* current interface */
1189 struct darwin_interface *cInterface;
1190 uint8_t pipeRef, iface;
1193 /* determine the interface/endpoint to use */
1194 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
1195 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1197 return LIBUSB_ERROR_NOT_FOUND;
1200 cInterface = &priv->interfaces[iface];
1202 #if (InterfaceVersion < 190)
1203 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1205 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1206 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1209 usbi_err (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1211 return darwin_to_libusb (kresult);
1214 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1215 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1218 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1220 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1222 return darwin_to_libusb (kresult);
1225 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1226 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1227 io_service_t usbInterface;
1231 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1233 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1235 return darwin_to_libusb (kresult);
1238 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1239 IOObjectRelease (usbInterface);
1251 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1252 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1255 return LIBUSB_ERROR_NOT_SUPPORTED;
1258 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1261 return LIBUSB_ERROR_NOT_SUPPORTED;
1264 static void darwin_destroy_device(struct libusb_device *dev) {
1268 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1269 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1270 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1273 uint8_t is_read; /* 0 = we're reading, 1 = we're writing */
1274 uint8_t transferType;
1275 /* None of the values below are used in libusb for bulk transfers */
1276 uint8_t direction, number, interval, pipeRef, iface;
1277 uint16_t maxPacketSize;
1279 struct darwin_interface *cInterface;
1281 /* are we reading or writing? */
1282 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1284 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1285 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1287 return LIBUSB_ERROR_NOT_FOUND;
1290 cInterface = &priv->interfaces[iface];
1292 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1293 &transferType, &maxPacketSize, &interval);
1295 /* submit the request */
1296 /* timeouts are unavailable on interrupt endpoints */
1297 if (transferType == kUSBInterrupt) {
1299 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1300 transfer->length, darwin_async_io_callback, itransfer);
1302 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1303 transfer->length, darwin_async_io_callback, itransfer);
1305 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1308 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1309 transfer->length, transfer->timeout, transfer->timeout,
1310 darwin_async_io_callback, (void *)itransfer);
1312 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1313 transfer->length, transfer->timeout, transfer->timeout,
1314 darwin_async_io_callback, (void *)itransfer);
1318 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", is_read ? "In" : "Out",
1319 darwin_error_str(ret), ret);
1321 return darwin_to_libusb (ret);
1324 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1325 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1326 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1327 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1330 uint8_t is_read; /* 0 = we're writing, 1 = we're reading */
1331 uint8_t pipeRef, iface;
1333 AbsoluteTime atTime;
1336 struct darwin_interface *cInterface;
1338 /* are we reading or writing? */
1339 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1341 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1342 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1343 free(tpriv->isoc_framelist);
1344 tpriv->isoc_framelist = NULL;
1347 if (!tpriv->isoc_framelist) {
1348 tpriv->num_iso_packets = transfer->num_iso_packets;
1349 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1350 if (!tpriv->isoc_framelist)
1351 return LIBUSB_ERROR_NO_MEM;
1354 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1355 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1356 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1358 /* determine the interface/endpoint to use */
1359 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1360 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1362 return LIBUSB_ERROR_NOT_FOUND;
1365 cInterface = &priv->interfaces[iface];
1367 /* Last but not least we need the bus frame number */
1368 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1370 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1371 free(tpriv->isoc_framelist);
1372 tpriv->isoc_framelist = NULL;
1374 return darwin_to_libusb (kresult);
1377 /* schedule for a frame a little in the future */
1380 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1381 frame = cInterface->frames[transfer->endpoint];
1383 /* submit the request */
1385 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1386 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1389 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1390 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1393 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets / 8;
1395 if (kresult != kIOReturnSuccess) {
1396 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", is_read ? "In" : "Out",
1397 darwin_error_str(kresult));
1398 free (tpriv->isoc_framelist);
1399 tpriv->isoc_framelist = NULL;
1402 return darwin_to_libusb (kresult);
1405 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1406 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1407 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1408 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1409 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1410 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1414 bzero(&tpriv->req, sizeof(tpriv->req));
1416 /* IOUSBDeviceInterface expects the request in cpu endianess */
1417 tpriv->req.bmRequestType = setup->bmRequestType;
1418 tpriv->req.bRequest = setup->bRequest;
1419 /* these values should be in bus order from libusb_fill_control_setup */
1420 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1421 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1422 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1423 /* data is stored after the libusb control block */
1424 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1425 tpriv->req.completionTimeout = transfer->timeout;
1426 tpriv->req.noDataTimeout = transfer->timeout;
1428 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1430 /* all transfers in libusb-1.0 are async */
1432 if (transfer->endpoint) {
1433 struct darwin_interface *cInterface;
1434 uint8_t pipeRef, iface;
1436 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1437 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1439 return LIBUSB_ERROR_NOT_FOUND;
1442 cInterface = &priv->interfaces[iface];
1444 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1446 /* control request on endpoint 0 */
1447 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1449 if (kresult != kIOReturnSuccess)
1450 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1452 return darwin_to_libusb (kresult);
1455 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1456 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1458 switch (transfer->type) {
1459 case LIBUSB_TRANSFER_TYPE_CONTROL:
1460 return submit_control_transfer(itransfer);
1461 case LIBUSB_TRANSFER_TYPE_BULK:
1462 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1463 return submit_bulk_transfer(itransfer);
1464 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1465 return submit_iso_transfer(itransfer);
1467 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1468 return LIBUSB_ERROR_INVALID_PARAM;
1472 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1473 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1474 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1477 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions control pipe");
1480 return LIBUSB_ERROR_NO_DEVICE;
1482 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1484 return darwin_to_libusb (kresult);
1487 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1488 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1489 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1490 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1491 struct darwin_interface *cInterface;
1492 uint8_t pipeRef, iface;
1495 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1496 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1498 return LIBUSB_ERROR_NOT_FOUND;
1501 cInterface = &priv->interfaces[iface];
1504 return LIBUSB_ERROR_NO_DEVICE;
1506 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions on interface %d pipe %d", iface, pipeRef);
1508 /* abort transactions */
1509 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1511 usbi_info (ITRANSFER_CTX (itransfer), "calling clear pipe stall to clear the data toggle bit");
1513 /* clear the data toggle bit */
1514 #if (InterfaceVersion < 190)
1515 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1517 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1518 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1521 return darwin_to_libusb (kresult);
1524 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1525 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1527 switch (transfer->type) {
1528 case LIBUSB_TRANSFER_TYPE_CONTROL:
1529 return cancel_control_transfer(itransfer);
1530 case LIBUSB_TRANSFER_TYPE_BULK:
1531 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1532 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1533 return darwin_abort_transfers (itransfer);
1535 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1536 return LIBUSB_ERROR_INVALID_PARAM;
1540 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1541 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1542 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1544 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1545 free (tpriv->isoc_framelist);
1546 tpriv->isoc_framelist = NULL;
1550 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1551 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1552 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1553 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1554 UInt32 message, size;
1556 usbi_info (ITRANSFER_CTX (itransfer), "an async io operation has completed");
1558 size = (UInt32) arg0;
1560 /* send a completion message to the device's file descriptor */
1561 message = MESSAGE_ASYNC_IO_COMPLETE;
1562 write (priv->fds[1], &message, sizeof (message));
1563 write (priv->fds[1], &itransfer, sizeof (itransfer));
1564 write (priv->fds[1], &result, sizeof (IOReturn));
1565 write (priv->fds[1], &size, sizeof (size));
1568 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1569 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT)
1570 result = kIOUSBTransactionTimeout;
1573 case kIOReturnUnderrun:
1574 case kIOReturnSuccess:
1575 return LIBUSB_TRANSFER_COMPLETED;
1576 case kIOReturnAborted:
1577 return LIBUSB_TRANSFER_CANCELLED;
1578 case kIOUSBPipeStalled:
1579 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: pipe is stalled");
1580 return LIBUSB_TRANSFER_STALL;
1581 case kIOReturnOverrun:
1582 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1583 return LIBUSB_TRANSFER_OVERFLOW;
1584 case kIOUSBTransactionTimeout:
1585 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1586 itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
1587 return LIBUSB_TRANSFER_TIMED_OUT;
1589 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1590 return LIBUSB_TRANSFER_ERROR;
1594 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1595 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1596 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1597 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1598 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1599 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1600 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1603 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1604 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1608 usbi_info (ITRANSFER_CTX (itransfer), "handling %s completion with kernel status %d",
1609 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
1611 if (kIOReturnSuccess == result || kIOReturnUnderrun == result) {
1612 if (isIsoc && tpriv->isoc_framelist) {
1613 /* copy isochronous results back */
1615 for (i = 0; i < transfer->num_iso_packets ; i++) {
1616 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1617 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1618 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1621 itransfer->transferred += io_size;
1624 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1625 usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
1628 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready) {
1629 struct usbi_transfer *itransfer;
1632 POLL_NFDS_TYPE i = 0;
1636 usbi_mutex_lock(&ctx->open_devs_lock);
1637 for (i = 0; i < nfds && num_ready > 0; i++) {
1638 struct pollfd *pollfd = &fds[i];
1639 struct libusb_device_handle *handle;
1640 struct darwin_device_handle_priv *hpriv = NULL;
1642 usbi_info (ctx, "checking fd %i with revents = %x", fds[i], pollfd->revents);
1644 if (!pollfd->revents)
1648 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
1649 hpriv = (struct darwin_device_handle_priv *)handle->os_priv;
1650 if (hpriv->fds[0] == pollfd->fd)
1654 if (!(pollfd->revents & POLLERR)) {
1655 ret = read (hpriv->fds[0], &message, sizeof (message));
1656 if (ret < (ssize_t)sizeof (message))
1659 /* could not poll the device-- response is to delete the device (this seems a little heavy-handed) */
1660 message = MESSAGE_DEVICE_GONE;
1663 case MESSAGE_DEVICE_GONE:
1664 /* remove the device's async port from the runloop */
1665 if (hpriv->cfSource) {
1666 if (libusb_darwin_acfl)
1667 CFRunLoopRemoveSource (libusb_darwin_acfl, hpriv->cfSource, kCFRunLoopDefaultMode);
1668 CFRelease (hpriv->cfSource);
1669 hpriv->cfSource = NULL;
1672 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1673 usbi_handle_disconnect(handle);
1675 /* done with this device */
1677 case MESSAGE_ASYNC_IO_COMPLETE:
1678 read (hpriv->fds[0], &itransfer, sizeof (itransfer));
1679 read (hpriv->fds[0], &kresult, sizeof (IOReturn));
1680 read (hpriv->fds[0], &io_size, sizeof (UInt32));
1682 darwin_handle_callback (itransfer, kresult, io_size);
1685 usbi_err (ctx, "unknown message received from device pipe");
1689 usbi_mutex_unlock(&ctx->open_devs_lock);
1694 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1695 mach_timespec_t sys_time;
1696 clock_serv_t clock_ref;
1699 case USBI_CLOCK_REALTIME:
1700 /* CLOCK_REALTIME represents time since the epoch */
1701 clock_ref = clock_realtime;
1703 case USBI_CLOCK_MONOTONIC:
1704 /* use system boot time as reference for the monotonic clock */
1705 clock_ref = clock_monotonic;
1708 return LIBUSB_ERROR_INVALID_PARAM;
1711 clock_get_time (clock_ref, &sys_time);
1713 tp->tv_sec = sys_time.tv_sec;
1714 tp->tv_nsec = sys_time.tv_nsec;
1719 const struct usbi_os_backend darwin_backend = {
1721 .init = darwin_init,
1722 .exit = darwin_exit,
1723 .get_device_list = darwin_get_device_list,
1724 .get_device_descriptor = darwin_get_device_descriptor,
1725 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1726 .get_config_descriptor = darwin_get_config_descriptor,
1728 .open = darwin_open,
1729 .close = darwin_close,
1730 .get_configuration = darwin_get_configuration,
1731 .set_configuration = darwin_set_configuration,
1732 .claim_interface = darwin_claim_interface,
1733 .release_interface = darwin_release_interface,
1735 .set_interface_altsetting = darwin_set_interface_altsetting,
1736 .clear_halt = darwin_clear_halt,
1737 .reset_device = darwin_reset_device,
1739 .kernel_driver_active = darwin_kernel_driver_active,
1740 .detach_kernel_driver = darwin_detach_kernel_driver,
1741 .attach_kernel_driver = darwin_attach_kernel_driver,
1743 .destroy_device = darwin_destroy_device,
1745 .submit_transfer = darwin_submit_transfer,
1746 .cancel_transfer = darwin_cancel_transfer,
1747 .clear_transfer_priv = darwin_clear_transfer_priv,
1749 .handle_events = op_handle_events,
1751 .clock_gettime = darwin_clock_gettime,
1753 .device_priv_size = sizeof(struct darwin_device_priv),
1754 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1755 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1756 .add_iso_packet_size = 0,