2 * darwin backend for libusb 1.0
3 * Copyright (C) 2008-2011 Nathan Hjelm <hjelmn@users.sourceforge.net>
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29 #include <sys/ioctl.h>
31 #include <sys/types.h>
34 #include <mach/clock.h>
35 #include <mach/clock_types.h>
36 #include <mach/mach_host.h>
37 #include <mach/mach_port.h>
39 #include <AvailabilityMacros.h>
40 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
41 #include <objc/objc-auto.h>
44 #include <IOKit/IOCFBundle.h>
45 #include <IOKit/usb/IOUSBLib.h>
46 #include <IOKit/IOCFPlugIn.h>
48 #include "darwin_usb.h"
50 static mach_port_t libusb_darwin_mp = 0; /* master port */
51 static CFRunLoopRef libusb_darwin_acfl = NULL; /* async cf loop */
52 static int initCount = 0;
54 /* async event thread */
55 static pthread_t libusb_darwin_at;
57 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
58 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
59 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
60 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
61 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
63 static const char *darwin_error_str (int result) {
65 case kIOReturnSuccess:
67 case kIOReturnNotOpen:
68 return "device not opened for exclusive access";
69 case kIOReturnNoDevice:
70 return "no connection to an IOService";
71 case kIOUSBNoAsyncPortErr:
72 return "no async port has been opened for interface";
73 case kIOReturnExclusiveAccess:
74 return "another process has device opened for exclusive access";
75 case kIOUSBPipeStalled:
76 return "pipe is stalled";
78 return "could not establish a connection to the Darwin kernel";
79 case kIOUSBTransactionTimeout:
80 return "transaction timed out";
81 case kIOReturnBadArgument:
82 return "invalid argument";
83 case kIOReturnAborted:
84 return "transaction aborted";
85 case kIOReturnNotResponding:
86 return "device not responding";
87 case kIOReturnOverrun:
88 return "data overrun";
89 case kIOReturnCannotWire:
90 return "physical memory can not be wired down";
92 return "unknown error";
96 static int darwin_to_libusb (int result) {
98 case kIOReturnUnderrun:
99 case kIOReturnSuccess:
100 return LIBUSB_SUCCESS;
101 case kIOReturnNotOpen:
102 case kIOReturnNoDevice:
103 return LIBUSB_ERROR_NO_DEVICE;
104 case kIOReturnExclusiveAccess:
105 return LIBUSB_ERROR_ACCESS;
106 case kIOUSBPipeStalled:
107 return LIBUSB_ERROR_PIPE;
108 case kIOReturnBadArgument:
109 return LIBUSB_ERROR_INVALID_PARAM;
110 case kIOUSBTransactionTimeout:
111 return LIBUSB_ERROR_TIMEOUT;
112 case kIOReturnNotResponding:
113 case kIOReturnAborted:
115 case kIOUSBNoAsyncPortErr:
117 return LIBUSB_ERROR_OTHER;
122 static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp) {
123 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
125 /* current interface */
126 struct __darwin_interface *cInterface;
130 usbi_info (HANDLE_CTX(dev_handle), "converting ep address 0x%02x to pipeRef and interface", ep);
132 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
133 cInterface = &priv->interfaces[iface];
135 if (dev_handle->claimed_interfaces & (1 << iface)) {
136 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
137 if (cInterface->endpoint_addrs[i] == ep) {
140 usbi_info (HANDLE_CTX(dev_handle), "pipe %d on interface %d matches", *pipep, *ifcp);
147 /* No pipe found with the correct endpoint address */
148 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
153 static int usb_setup_device_iterator (io_iterator_t *deviceIterator, long location) {
154 CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBDeviceClassName);
157 return kIOReturnError;
160 CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
161 &kCFTypeDictionaryKeyCallBacks,
162 &kCFTypeDictionaryValueCallBacks);
164 if (propertyMatchDict) {
165 CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberLongType, &location);
167 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
168 /* release our reference to the CFNumber (CFDictionarySetValue retains it) */
169 CFRelease (locationCF);
171 CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
172 /* release out reference to the CFMutableDictionaryRef (CFDictionarySetValue retains it) */
173 CFRelease (propertyMatchDict);
175 /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
178 return IOServiceGetMatchingServices(libusb_darwin_mp, matchingDict, deviceIterator);
181 static usb_device_t **usb_get_next_device (io_iterator_t deviceIterator, UInt32 *locationp) {
182 io_cf_plugin_ref_t *plugInInterface = NULL;
183 usb_device_t **device;
184 io_service_t usbDevice;
188 if (!IOIteratorIsValid (deviceIterator))
192 while ((usbDevice = IOIteratorNext(deviceIterator))) {
193 result = IOCreatePlugInInterfaceForService(usbDevice, kIOUSBDeviceUserClientTypeID,
194 kIOCFPlugInInterfaceID, &plugInInterface,
196 if (kIOReturnSuccess == result && plugInInterface)
199 usbi_dbg ("libusb/darwin.c usb_get_next_device: could not set up plugin for service: %s\n", darwin_error_str (result));
205 (void)IOObjectRelease(usbDevice);
206 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
209 (*plugInInterface)->Stop(plugInInterface);
210 IODestroyPlugInInterface (plugInInterface);
212 /* get the location from the device */
214 (*(device))->GetLocationID(device, locationp);
219 static kern_return_t darwin_get_device (uint32_t dev_location, usb_device_t ***darwin_device) {
220 kern_return_t kresult;
222 io_iterator_t deviceIterator;
224 kresult = usb_setup_device_iterator (&deviceIterator, dev_location);
228 /* This port of libusb uses locations to keep track of devices. */
229 while ((*darwin_device = usb_get_next_device (deviceIterator, &location)) != NULL) {
230 if (location == dev_location)
233 (**darwin_device)->Release(*darwin_device);
236 IOObjectRelease (deviceIterator);
238 if (!(*darwin_device))
239 return kIOReturnNoDevice;
241 return kIOReturnSuccess;
246 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
247 struct libusb_context *ctx = (struct libusb_context *)ptr;
248 struct libusb_device_handle *handle;
249 struct darwin_device_priv *dpriv;
250 struct darwin_device_handle_priv *priv;
255 CFTypeRef locationCF;
258 usbi_info (ctx, "a device has been detached");
260 while ((device = IOIteratorNext (rem_devices)) != 0) {
261 /* get the location from the i/o registry */
262 locationCF = IORegistryEntryCreateCFProperty (device, CFSTR(kUSBDevicePropertyLocationID), kCFAllocatorDefault, 0);
264 IOObjectRelease (device);
269 locationValid = CFGetTypeID(locationCF) == CFNumberGetTypeID() &&
270 CFNumberGetValue(locationCF, kCFNumberLongType, &location);
272 CFRelease (locationCF);
277 usbi_mutex_lock(&ctx->open_devs_lock);
278 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
279 dpriv = (struct darwin_device_priv *)handle->dev->os_priv;
281 /* the device may have been opened several times. write to each handle's event descriptor */
282 if (dpriv->location == location && handle->os_priv) {
283 priv = (struct darwin_device_handle_priv *)handle->os_priv;
285 message = MESSAGE_DEVICE_GONE;
286 write (priv->fds[1], &message, sizeof (message));
290 usbi_mutex_unlock(&ctx->open_devs_lock);
294 static void darwin_clear_iterator (io_iterator_t iter) {
297 while ((device = IOIteratorNext (iter)) != 0)
298 IOObjectRelease (device);
301 static void *event_thread_main (void *arg0) {
303 struct libusb_context *ctx = (struct libusb_context *)arg0;
304 CFRunLoopRef runloop;
306 /* Tell the Objective-C garbage collector about this thread.
307 This is required because, unlike NSThreads, pthreads are
308 not automatically registered. Although we don't use
309 Objective-C, we use CoreFoundation, which does. */
310 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
311 objc_registerThreadWithCollector();
314 /* hotplug (device removal) source */
315 CFRunLoopSourceRef libusb_notification_cfsource;
316 io_notification_port_t libusb_notification_port;
317 io_iterator_t libusb_rem_device_iterator;
319 usbi_info (ctx, "creating hotplug event source");
321 runloop = CFRunLoopGetCurrent ();
324 /* add the notification port to the run loop */
325 libusb_notification_port = IONotificationPortCreate (libusb_darwin_mp);
326 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
327 CFRunLoopAddSource(CFRunLoopGetCurrent (), libusb_notification_cfsource, kCFRunLoopDefaultMode);
329 /* create notifications for removed devices */
330 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
331 IOServiceMatching(kIOUSBDeviceClassName),
332 (IOServiceMatchingCallback)darwin_devices_detached,
333 (void *)ctx, &libusb_rem_device_iterator);
335 if (kresult != kIOReturnSuccess) {
336 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
342 darwin_clear_iterator (libusb_rem_device_iterator);
344 /* let the main thread know about the async runloop */
345 libusb_darwin_acfl = CFRunLoopGetCurrent ();
347 usbi_info (ctx, "thread ready to receive events");
349 /* run the runloop */
352 usbi_info (ctx, "thread exiting");
354 /* delete notification port */
355 CFRunLoopSourceInvalidate (libusb_notification_cfsource);
356 IONotificationPortDestroy (libusb_notification_port);
360 libusb_darwin_acfl = NULL;
365 static int darwin_init(struct libusb_context *ctx) {
368 if (!(initCount++)) {
369 /* Create the master port for talking to IOKit */
370 if (!libusb_darwin_mp) {
371 kresult = IOMasterPort (MACH_PORT_NULL, &libusb_darwin_mp);
373 if (kresult != kIOReturnSuccess || !libusb_darwin_mp)
374 return darwin_to_libusb (kresult);
377 pthread_create (&libusb_darwin_at, NULL, event_thread_main, (void *)ctx);
379 while (!libusb_darwin_acfl)
386 static void darwin_exit (void) {
387 if (!(--initCount)) {
389 /* stop the async runloop */
390 CFRunLoopStop (libusb_darwin_acfl);
391 pthread_join (libusb_darwin_at, NULL);
393 if (libusb_darwin_mp)
394 mach_port_deallocate(mach_task_self(), libusb_darwin_mp);
396 libusb_darwin_mp = 0;
400 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
401 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
403 /* return cached copy */
404 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
411 static int get_configuration_index (struct libusb_device *dev, int config_value) {
412 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
414 IOUSBConfigurationDescriptorPtr desc;
417 /* is there a simpler way to determine the index? */
418 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
419 if (kresult != kIOReturnSuccess)
420 return darwin_to_libusb (kresult);
422 for (i = 0 ; i < numConfig ; i++) {
423 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
425 if (desc->bConfigurationValue == config_value)
429 /* configuration not found */
430 return LIBUSB_ERROR_OTHER;
433 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
434 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
437 if (0 == priv->active_config)
438 return LIBUSB_ERROR_INVALID_PARAM;
440 config_index = get_configuration_index (dev, priv->active_config);
441 if (config_index < 0)
444 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
447 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
448 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
449 IOUSBConfigurationDescriptorPtr desc;
451 usb_device_t **device = NULL;
454 return LIBUSB_ERROR_OTHER;
457 kresult = darwin_get_device (priv->location, &device);
458 if (kresult || !device) {
459 usbi_err (DEVICE_CTX (dev), "could not find device: %s", darwin_error_str (kresult));
461 return darwin_to_libusb (kresult);
464 /* don't have to open the device to get a config descriptor */
466 device = priv->device;
468 kresult = (*device)->GetConfigurationDescriptorPtr (device, config_index, &desc);
469 if (kresult == kIOReturnSuccess) {
470 /* copy descriptor */
471 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
472 len = libusb_le16_to_cpu(desc->wTotalLength);
474 memmove (buffer, desc, len);
476 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
481 (*device)->Release (device);
483 return darwin_to_libusb (kresult);
486 /* check whether the os has configured the device */
487 static int darwin_check_configuration (struct libusb_context *ctx, struct libusb_device *dev, usb_device_t **darwin_device) {
488 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
490 IOUSBConfigurationDescriptorPtr configDesc;
491 IOUSBFindInterfaceRequest request;
492 kern_return_t kresult;
493 io_iterator_t interface_iterator;
494 io_service_t firstInterface;
496 if (priv->dev_descriptor.bNumConfigurations < 1) {
497 usbi_err (ctx, "device has no configurations");
498 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
501 /* find the first configuration */
502 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
503 priv->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
505 /* check if the device is already configured. there is probably a better way than iterating over the
506 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
507 might lock up on the device request) */
509 /* Setup the Interface Request */
510 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
511 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
512 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
513 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
515 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
517 return darwin_to_libusb (kresult);
520 firstInterface = IOIteratorNext(interface_iterator);
522 /* done with the interface iterator */
523 IOObjectRelease(interface_iterator);
525 if (firstInterface) {
526 IOObjectRelease (firstInterface);
528 /* device is configured */
529 if (priv->dev_descriptor.bNumConfigurations == 1)
530 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
531 priv->active_config = priv->first_config;
533 /* devices with more than one configuration should work with GetConfiguration */
534 (*darwin_device)->GetConfiguration (darwin_device, &priv->active_config);
537 priv->active_config = 0;
539 usbi_info (ctx, "active config: %u, first config: %u", priv->active_config, priv->first_config);
544 static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct libusb_device *dev, usb_device_t **device) {
545 struct darwin_device_priv *priv;
546 int retries = 5, delay = 30000;
547 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
552 UInt16 idProduct, idVendor;
554 (*device)->GetDeviceClass (device, &bDeviceClass);
555 (*device)->GetDeviceProduct (device, &idProduct);
556 (*device)->GetDeviceVendor (device, &idVendor);
558 priv = (struct darwin_device_priv *)dev->os_priv;
560 /* try to open the device (we can usually continue even if this fails) */
561 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
563 /**** retrieve device descriptor ****/
565 /* Set up request for device descriptor */
566 memset (&(priv->dev_descriptor), 0, sizeof(IOUSBDeviceDescriptor));
567 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
568 req.bRequest = kUSBRqGetDescriptor;
569 req.wValue = kUSBDeviceDesc << 8;
571 req.wLength = sizeof(priv->dev_descriptor);
572 req.pData = &(priv->dev_descriptor);
574 /* according to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
575 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
576 * to follow the spec as closely as possible, try opening the device */
578 ret = (*(device))->DeviceRequest (device, &req);
580 if (kIOReturnOverrun == ret && kUSBDeviceDesc == priv->dev_descriptor.bDescriptorType)
581 /* received an overrun error but we still received a device descriptor */
582 ret = kIOReturnSuccess;
584 if (kIOReturnSuccess == ret && (0 == priv->dev_descriptor.idProduct ||
585 0 == priv->dev_descriptor.bNumConfigurations ||
586 0 == priv->dev_descriptor.bcdUSB)) {
587 /* work around for incorrectly configured devices */
588 if (try_reconfigure && is_open) {
589 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
591 /* set the first configuration */
592 (*device)->SetConfiguration(device, 1);
594 /* don't try to reconfigure again */
598 ret = kIOUSBPipeStalled;
601 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
602 /* device may be suspended. unsuspend it and try again */
603 #if DeviceVersion >= 320
606 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
607 (void)(*device)->GetUSBDeviceInformation (device, &info);
609 try_unsuspend = info & (1 << kUSBInformationDeviceIsSuspendedBit);
613 /* resume the device */
614 ret2 = (*device)->USBDeviceSuspend (device, 0);
615 if (kIOReturnSuccess != ret2) {
616 /* prevent log spew from poorly behaving devices. this indicates the
617 os actually had trouble communicating with the device */
618 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
626 if (kIOReturnSuccess != ret) {
627 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
628 /* sleep for a little while before trying again */
631 } while (kIOReturnSuccess != ret && retries--);
634 /* resuspend the device */
635 (void)(*device)->USBDeviceSuspend (device, 1);
638 (void) (*device)->USBDeviceClose (device);
640 if (ret != kIOReturnSuccess) {
641 /* a debug message was already printed out for this error */
642 if (LIBUSB_CLASS_HUB == bDeviceClass)
643 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s. skipping device", idVendor, idProduct, darwin_error_str (ret));
645 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s. skipping device", idVendor, idProduct, darwin_error_str (ret));
650 usbi_dbg ("device descriptor:");
651 usbi_dbg (" bDescriptorType: 0x%02x", priv->dev_descriptor.bDescriptorType);
652 usbi_dbg (" bcdUSB: 0x%04x", priv->dev_descriptor.bcdUSB);
653 usbi_dbg (" bDeviceClass: 0x%02x", priv->dev_descriptor.bDeviceClass);
654 usbi_dbg (" bDeviceSubClass: 0x%02x", priv->dev_descriptor.bDeviceSubClass);
655 usbi_dbg (" bDeviceProtocol: 0x%02x", priv->dev_descriptor.bDeviceProtocol);
656 usbi_dbg (" bMaxPacketSize0: 0x%02x", priv->dev_descriptor.bMaxPacketSize0);
657 usbi_dbg (" idVendor: 0x%04x", priv->dev_descriptor.idVendor);
658 usbi_dbg (" idProduct: 0x%04x", priv->dev_descriptor.idProduct);
659 usbi_dbg (" bcdDevice: 0x%04x", priv->dev_descriptor.bcdDevice);
660 usbi_dbg (" iManufacturer: 0x%02x", priv->dev_descriptor.iManufacturer);
661 usbi_dbg (" iProduct: 0x%02x", priv->dev_descriptor.iProduct);
662 usbi_dbg (" iSerialNumber: 0x%02x", priv->dev_descriptor.iSerialNumber);
663 usbi_dbg (" bNumConfigurations: 0x%02x", priv->dev_descriptor.bNumConfigurations);
665 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
666 if (libusb_le16_to_cpu (priv->dev_descriptor.idProduct) != idProduct) {
667 /* not a valid device */
668 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
669 idProduct, libusb_le16_to_cpu (priv->dev_descriptor.idProduct));
676 static int process_new_device (struct libusb_context *ctx, usb_device_t **device, UInt32 locationID, struct discovered_devs **_discdevs) {
677 struct darwin_device_priv *priv;
678 struct libusb_device *dev;
679 struct discovered_devs *discdevs;
681 int ret = 0, need_unref = 0;
684 dev = usbi_get_device_by_session_id(ctx, locationID);
686 usbi_info (ctx, "allocating new device for location 0x%08x", locationID);
687 dev = usbi_alloc_device(ctx, locationID);
690 usbi_info (ctx, "using existing device for location 0x%08x", locationID);
693 ret = LIBUSB_ERROR_NO_MEM;
697 priv = (struct darwin_device_priv *)dev->os_priv;
699 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&address);
701 ret = darwin_cache_device_descriptor (ctx, dev, device);
705 /* check current active configuration (and cache the first configuration value-- which may be used by claim_interface) */
706 ret = darwin_check_configuration (ctx, dev, device);
710 dev->bus_number = locationID >> 24;
711 dev->device_address = address;
713 /* save our location, we'll need this later */
714 priv->location = locationID;
715 snprintf(priv->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", address, priv->dev_descriptor.idVendor, priv->dev_descriptor.idProduct,
716 priv->dev_descriptor.bDeviceClass, priv->dev_descriptor.bDeviceSubClass);
718 ret = usbi_sanitize_device (dev);
722 /* append the device to the list of discovered devices */
723 discdevs = discovered_devs_append(*_discdevs, dev);
725 ret = LIBUSB_ERROR_NO_MEM;
729 *_discdevs = discdevs;
731 usbi_info (ctx, "found device with address %d at %s", dev->device_address, priv->sys_path);
735 libusb_unref_device(dev);
740 static int darwin_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs) {
741 io_iterator_t deviceIterator;
742 usb_device_t **device;
743 kern_return_t kresult;
746 if (!libusb_darwin_mp)
747 return LIBUSB_ERROR_INVALID_PARAM;
749 kresult = usb_setup_device_iterator (&deviceIterator, 0);
750 if (kresult != kIOReturnSuccess)
751 return darwin_to_libusb (kresult);
753 while ((device = usb_get_next_device (deviceIterator, &location)) != NULL) {
754 (void) process_new_device (ctx, device, location, _discdevs);
756 (*(device))->Release(device);
759 IOObjectRelease(deviceIterator);
764 static int darwin_open (struct libusb_device_handle *dev_handle) {
765 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
766 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
767 usb_device_t **darwin_device;
770 if (0 == dpriv->open_count) {
771 kresult = darwin_get_device (dpriv->location, &darwin_device);
773 usbi_err (HANDLE_CTX (dev_handle), "could not find device: %s", darwin_error_str (kresult));
774 return darwin_to_libusb (kresult);
777 dpriv->device = darwin_device;
779 /* try to open the device */
780 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
782 if (kresult != kIOReturnSuccess) {
783 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
786 case kIOReturnExclusiveAccess:
787 /* it is possible to perform some actions on a device that is not open so do not return an error */
792 (*(dpriv->device))->Release (dpriv->device);
793 dpriv->device = NULL;
794 return darwin_to_libusb (kresult);
797 /* create async event source */
798 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
799 if (kresult != kIOReturnSuccess) {
800 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
802 (*(dpriv->device))->USBDeviceClose (dpriv->device);
803 (*(dpriv->device))->Release (dpriv->device);
805 dpriv->device = NULL;
806 return darwin_to_libusb (kresult);
811 CFRetain (libusb_darwin_acfl);
813 /* add the cfSource to the aync run loop */
814 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
818 /* device opened successfully */
821 /* create a file descriptor for notifications */
824 /* set the pipe to be non-blocking */
825 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
827 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
829 usbi_info (HANDLE_CTX (dev_handle), "device open for access");
834 static void darwin_close (struct libusb_device_handle *dev_handle) {
835 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
836 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
840 if (dpriv->open_count == 0) {
841 /* something is probably very wrong if this is the case */
842 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
848 /* make sure all interfaces are released */
849 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
850 if (dev_handle->claimed_interfaces & (1 << i))
851 libusb_release_interface (dev_handle, i);
853 if (0 == dpriv->open_count) {
855 /* delete the device's async event source */
856 if (priv->cfSource) {
857 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
858 CFRelease (priv->cfSource);
861 /* close the device */
862 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
864 /* Log the fact that we had a problem closing the file, however failing a
865 * close isn't really an error, so return success anyway */
866 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
870 kresult = (*(dpriv->device))->Release(dpriv->device);
872 /* Log the fact that we had a problem closing the file, however failing a
873 * close isn't really an error, so return success anyway */
874 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
877 dpriv->device = NULL;
880 /* file descriptors are maintained per-instance */
881 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
882 close (priv->fds[1]);
883 close (priv->fds[0]);
885 priv->fds[0] = priv->fds[1] = -1;
888 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
889 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
891 *config = (int) dpriv->active_config;
896 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
897 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
901 /* Setting configuration will invalidate the interface, so we need
902 to reclaim it. First, dispose of existing interfaces, if any. */
903 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
904 if (dev_handle->claimed_interfaces & (1 << i))
905 darwin_release_interface (dev_handle, i);
907 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
908 if (kresult != kIOReturnSuccess)
909 return darwin_to_libusb (kresult);
911 /* Reclaim any interfaces. */
912 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
913 if (dev_handle->claimed_interfaces & (1 << i))
914 darwin_claim_interface (dev_handle, i);
916 dpriv->active_config = config;
921 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
922 IOUSBFindInterfaceRequest request;
923 uint8_t current_interface;
924 kern_return_t kresult;
925 io_iterator_t interface_iterator;
927 *usbInterfacep = IO_OBJECT_NULL;
929 /* Setup the Interface Request */
930 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
931 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
932 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
933 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
935 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
939 for ( current_interface = 0 ; current_interface <= ifc ; current_interface++ ) {
940 *usbInterfacep = IOIteratorNext(interface_iterator);
941 if (current_interface != ifc)
942 (void) IOObjectRelease (*usbInterfacep);
945 /* done with the interface iterator */
946 IOObjectRelease(interface_iterator);
951 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
952 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
954 /* current interface */
955 struct __darwin_interface *cInterface = &priv->interfaces[iface];
957 kern_return_t kresult;
959 u_int8_t numep, direction, number;
960 u_int8_t dont_care1, dont_care3;
961 u_int16_t dont_care2;
964 usbi_info (HANDLE_CTX (dev_handle), "building table of endpoints.");
966 /* retrieve the total number of endpoints on this interface */
967 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
969 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
970 return darwin_to_libusb (kresult);
973 /* iterate through pipe references */
974 for (i = 1 ; i <= numep ; i++) {
975 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
976 &dont_care2, &dont_care3);
978 if (kresult != kIOReturnSuccess) {
979 usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
981 return darwin_to_libusb (kresult);
984 usbi_info (HANDLE_CTX (dev_handle), "interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
986 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
989 cInterface->num_endpoints = numep;
994 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
995 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
996 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
997 io_service_t usbInterface = IO_OBJECT_NULL;
999 IOCFPlugInInterface **plugInInterface = NULL;
1002 /* current interface */
1003 struct __darwin_interface *cInterface = &priv->interfaces[iface];
1005 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1006 if (kresult != kIOReturnSuccess)
1007 return darwin_to_libusb (kresult);
1009 /* make sure we have an interface */
1010 if (!usbInterface && dpriv->first_config != 0) {
1011 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1013 /* set the configuration */
1014 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1015 if (kresult != LIBUSB_SUCCESS) {
1016 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1020 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1022 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1023 return darwin_to_libusb (kresult);
1027 if (!usbInterface) {
1028 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1029 return LIBUSB_ERROR_NOT_FOUND;
1032 /* get an interface to the device's interface */
1033 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1034 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1036 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1037 return darwin_to_libusb (kresult);
1040 if (!plugInInterface) {
1041 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1042 return LIBUSB_ERROR_NOT_FOUND;
1045 /* ignore release error */
1046 (void)IOObjectRelease (usbInterface);
1048 /* Do the actual claim */
1049 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1050 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1051 (LPVOID)&cInterface->interface);
1052 if (kresult || !cInterface->interface) {
1053 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1054 return darwin_to_libusb (kresult);
1057 /* We no longer need the intermediate plug-in */
1058 (*plugInInterface)->Release(plugInInterface);
1060 /* claim the interface */
1061 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1063 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1064 return darwin_to_libusb (kresult);
1067 /* update list of endpoints */
1068 kresult = get_endpoints (dev_handle, iface);
1070 /* this should not happen */
1071 darwin_release_interface (dev_handle, iface);
1072 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1076 cInterface->cfSource = NULL;
1078 /* create async event source */
1079 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1080 if (kresult != kIOReturnSuccess) {
1081 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1083 /* can't continue without an async event source */
1084 (void)darwin_release_interface (dev_handle, iface);
1086 return darwin_to_libusb (kresult);
1089 /* add the cfSource to the async thread's run loop */
1090 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1092 usbi_info (HANDLE_CTX (dev_handle), "interface opened");
1097 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1098 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1101 /* current interface */
1102 struct __darwin_interface *cInterface = &priv->interfaces[iface];
1104 /* Check to see if an interface is open */
1105 if (!cInterface->interface)
1106 return LIBUSB_SUCCESS;
1108 /* clean up endpoint data */
1109 cInterface->num_endpoints = 0;
1111 /* delete the interface's async event source */
1112 if (cInterface->cfSource) {
1113 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1114 CFRelease (cInterface->cfSource);
1117 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1119 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1121 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1122 if (kresult != kIOReturnSuccess)
1123 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1125 cInterface->interface = IO_OBJECT_NULL;
1127 return darwin_to_libusb (kresult);
1130 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1131 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1134 /* current interface */
1135 struct __darwin_interface *cInterface = &priv->interfaces[iface];
1137 if (!cInterface->interface)
1138 return LIBUSB_ERROR_NO_DEVICE;
1140 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1141 if (kresult != kIOReturnSuccess)
1142 darwin_reset_device (dev_handle);
1144 /* update list of endpoints */
1145 kresult = get_endpoints (dev_handle, iface);
1147 /* this should not happen */
1148 darwin_release_interface (dev_handle, iface);
1149 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1153 return darwin_to_libusb (kresult);
1156 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1157 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1159 /* current interface */
1160 struct __darwin_interface *cInterface;
1161 uint8_t pipeRef, iface;
1164 /* determine the interface/endpoint to use */
1165 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
1166 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1168 return LIBUSB_ERROR_NOT_FOUND;
1171 cInterface = &priv->interfaces[iface];
1173 #if (InterfaceVersion < 190)
1174 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1176 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1177 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1180 usbi_err (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1182 return darwin_to_libusb (kresult);
1185 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1186 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1189 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1191 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1193 return darwin_to_libusb (kresult);
1196 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1197 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1198 io_service_t usbInterface;
1202 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1204 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1206 return darwin_to_libusb (kresult);
1209 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1210 IOObjectRelease (usbInterface);
1222 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1223 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1224 return LIBUSB_ERROR_NOT_SUPPORTED;
1227 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1228 return LIBUSB_ERROR_NOT_SUPPORTED;
1231 static void darwin_destroy_device(struct libusb_device *dev) {
1234 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1235 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1236 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1239 uint8_t is_read; /* 0 = we're reading, 1 = we're writing */
1240 uint8_t transferType;
1241 /* None of the values below are used in libusb for bulk transfers */
1242 uint8_t direction, number, interval, pipeRef, iface;
1243 uint16_t maxPacketSize;
1245 struct __darwin_interface *cInterface;
1247 /* are we reading or writing? */
1248 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1250 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1251 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1253 return LIBUSB_ERROR_NOT_FOUND;
1256 cInterface = &priv->interfaces[iface];
1258 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1259 &transferType, &maxPacketSize, &interval);
1261 /* submit the request */
1262 /* timeouts are unavailable on interrupt endpoints */
1263 if (transferType == kUSBInterrupt) {
1265 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1266 transfer->length, darwin_async_io_callback, itransfer);
1268 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1269 transfer->length, darwin_async_io_callback, itransfer);
1271 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1274 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1275 transfer->length, transfer->timeout, transfer->timeout,
1276 darwin_async_io_callback, (void *)itransfer);
1278 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1279 transfer->length, transfer->timeout, transfer->timeout,
1280 darwin_async_io_callback, (void *)itransfer);
1284 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", is_read ? "In" : "Out",
1285 darwin_error_str(ret), ret);
1287 return darwin_to_libusb (ret);
1290 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1291 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1292 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1293 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1296 uint8_t is_read; /* 0 = we're writing, 1 = we're reading */
1297 uint8_t pipeRef, iface;
1299 AbsoluteTime atTime;
1302 struct __darwin_interface *cInterface;
1304 /* are we reading or writing? */
1305 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1307 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1308 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1309 free(tpriv->isoc_framelist);
1310 tpriv->isoc_framelist = NULL;
1313 if (!tpriv->isoc_framelist) {
1314 tpriv->num_iso_packets = transfer->num_iso_packets;
1315 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1316 if (!tpriv->isoc_framelist)
1317 return LIBUSB_ERROR_NO_MEM;
1320 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1321 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1322 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1324 /* determine the interface/endpoint to use */
1325 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1326 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1328 return LIBUSB_ERROR_NOT_FOUND;
1331 cInterface = &priv->interfaces[iface];
1333 /* Last but not least we need the bus frame number */
1334 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1336 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1337 free(tpriv->isoc_framelist);
1338 tpriv->isoc_framelist = NULL;
1340 return darwin_to_libusb (kresult);
1343 /* schedule for a frame a little in the future */
1346 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1347 frame = cInterface->frames[transfer->endpoint];
1349 /* submit the request */
1351 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1352 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1355 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1356 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1359 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets / 8;
1361 if (kresult != kIOReturnSuccess) {
1362 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", is_read ? "In" : "Out",
1363 darwin_error_str(kresult));
1364 free (tpriv->isoc_framelist);
1365 tpriv->isoc_framelist = NULL;
1368 return darwin_to_libusb (kresult);
1371 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1372 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1373 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1374 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1375 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1376 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1380 bzero(&tpriv->req, sizeof(tpriv->req));
1382 /* IOUSBDeviceInterface expects the request in cpu endianess */
1383 tpriv->req.bmRequestType = setup->bmRequestType;
1384 tpriv->req.bRequest = setup->bRequest;
1385 /* these values should be in bus order from libusb_fill_control_setup */
1386 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1387 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1388 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1389 /* data is stored after the libusb control block */
1390 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1391 tpriv->req.completionTimeout = transfer->timeout;
1392 tpriv->req.noDataTimeout = transfer->timeout;
1394 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1396 /* all transfers in libusb-1.0 are async */
1398 if (transfer->endpoint) {
1399 struct __darwin_interface *cInterface;
1400 uint8_t pipeRef, iface;
1402 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1403 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1405 return LIBUSB_ERROR_NOT_FOUND;
1408 cInterface = &priv->interfaces[iface];
1410 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1412 /* control request on endpoint 0 */
1413 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1415 if (kresult != kIOReturnSuccess)
1416 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1418 return darwin_to_libusb (kresult);
1421 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1422 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1424 switch (transfer->type) {
1425 case LIBUSB_TRANSFER_TYPE_CONTROL:
1426 return submit_control_transfer(itransfer);
1427 case LIBUSB_TRANSFER_TYPE_BULK:
1428 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1429 return submit_bulk_transfer(itransfer);
1430 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1431 return submit_iso_transfer(itransfer);
1433 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1434 return LIBUSB_ERROR_INVALID_PARAM;
1438 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1439 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1440 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1443 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions control pipe");
1445 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1447 return darwin_to_libusb (kresult);
1450 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1451 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1452 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1453 struct __darwin_interface *cInterface;
1454 uint8_t pipeRef, iface;
1457 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1458 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1460 return LIBUSB_ERROR_NOT_FOUND;
1463 cInterface = &priv->interfaces[iface];
1465 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions on interface %d pipe %d", iface, pipeRef);
1467 /* abort transactions */
1468 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1470 usbi_info (ITRANSFER_CTX (itransfer), "calling clear pipe stall to clear the data toggle bit");
1472 /* clear the data toggle bit */
1473 #if (InterfaceVersion < 190)
1474 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1476 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1477 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1480 return darwin_to_libusb (kresult);
1483 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1484 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1486 switch (transfer->type) {
1487 case LIBUSB_TRANSFER_TYPE_CONTROL:
1488 return cancel_control_transfer(itransfer);
1489 case LIBUSB_TRANSFER_TYPE_BULK:
1490 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1491 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1492 return darwin_abort_transfers (itransfer);
1494 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1495 return LIBUSB_ERROR_INVALID_PARAM;
1499 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1500 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1501 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1503 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1504 free (tpriv->isoc_framelist);
1505 tpriv->isoc_framelist = NULL;
1509 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1510 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1511 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1512 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1515 usbi_info (ITRANSFER_CTX (itransfer), "an async io operation has completed");
1517 /* send a completion message to the device's file descriptor */
1518 message = MESSAGE_ASYNC_IO_COMPLETE;
1519 write (priv->fds[1], &message, sizeof (message));
1520 write (priv->fds[1], &itransfer, sizeof (itransfer));
1521 write (priv->fds[1], &result, sizeof (IOReturn));
1522 write (priv->fds[1], &arg0, sizeof (UInt32));
1525 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1526 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT)
1527 result = kIOUSBTransactionTimeout;
1530 case kIOReturnUnderrun:
1531 case kIOReturnSuccess:
1532 return LIBUSB_TRANSFER_COMPLETED;
1533 case kIOReturnAborted:
1534 return LIBUSB_TRANSFER_CANCELLED;
1535 case kIOUSBPipeStalled:
1536 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: pipe is stalled");
1537 return LIBUSB_TRANSFER_STALL;
1538 case kIOReturnOverrun:
1539 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1540 return LIBUSB_TRANSFER_OVERFLOW;
1541 case kIOUSBTransactionTimeout:
1542 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1543 itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
1544 return LIBUSB_TRANSFER_TIMED_OUT;
1546 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1547 return LIBUSB_TRANSFER_ERROR;
1551 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1552 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1553 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1554 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1555 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1556 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1557 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1560 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1561 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1565 usbi_info (ITRANSFER_CTX (itransfer), "handling %s completion with kernel status %d",
1566 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
1568 if (kIOReturnSuccess == result || kIOReturnUnderrun == result) {
1569 if (isIsoc && tpriv->isoc_framelist) {
1570 /* copy isochronous results back */
1572 for (i = 0; i < transfer->num_iso_packets ; i++) {
1573 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1574 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1575 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1578 itransfer->transferred += io_size;
1581 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1582 usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
1585 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready) {
1586 struct usbi_transfer *itransfer;
1592 usbi_mutex_lock(&ctx->open_devs_lock);
1593 for (i = 0; i < nfds && num_ready > 0; i++) {
1594 struct pollfd *pollfd = &fds[i];
1595 struct libusb_device_handle *handle;
1596 struct darwin_device_handle_priv *hpriv = NULL;
1598 usbi_info (ctx, "checking fd %i with revents = %x", fds[i], pollfd->revents);
1600 if (!pollfd->revents)
1604 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
1605 hpriv = (struct darwin_device_handle_priv *)handle->os_priv;
1606 if (hpriv->fds[0] == pollfd->fd)
1610 if (!(pollfd->revents & POLLERR)) {
1611 ret = read (hpriv->fds[0], &message, sizeof (message));
1612 if (ret < sizeof (message))
1615 /* could not poll the device-- response is to delete the device (this seems a little heavy-handed) */
1616 message = MESSAGE_DEVICE_GONE;
1619 case MESSAGE_DEVICE_GONE:
1620 /* remove the device's async port from the runloop */
1621 if (hpriv->cfSource) {
1622 if (libusb_darwin_acfl)
1623 CFRunLoopRemoveSource (libusb_darwin_acfl, hpriv->cfSource, kCFRunLoopDefaultMode);
1624 CFRelease (hpriv->cfSource);
1625 hpriv->cfSource = NULL;
1628 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1629 usbi_handle_disconnect(handle);
1631 /* done with this device */
1633 case MESSAGE_ASYNC_IO_COMPLETE:
1634 read (hpriv->fds[0], &itransfer, sizeof (itransfer));
1635 read (hpriv->fds[0], &kresult, sizeof (IOReturn));
1636 read (hpriv->fds[0], &io_size, sizeof (UInt32));
1638 darwin_handle_callback (itransfer, kresult, io_size);
1641 usbi_err (ctx, "unknown message received from device pipe");
1645 usbi_mutex_unlock(&ctx->open_devs_lock);
1650 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1651 mach_timespec_t sys_time;
1652 clock_serv_t clock_ref;
1655 case USBI_CLOCK_REALTIME:
1656 /* CLOCK_REALTIME represents time since the epoch */
1657 host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &clock_ref);
1659 case USBI_CLOCK_MONOTONIC:
1660 /* use system boot time as reference for the monotonic clock */
1661 host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &clock_ref);
1664 return LIBUSB_ERROR_INVALID_PARAM;
1667 clock_get_time (clock_ref, &sys_time);
1669 tp->tv_sec = sys_time.tv_sec;
1670 tp->tv_nsec = sys_time.tv_nsec;
1675 const struct usbi_os_backend darwin_backend = {
1677 .init = darwin_init,
1678 .exit = darwin_exit,
1679 .get_device_list = darwin_get_device_list,
1680 .get_device_descriptor = darwin_get_device_descriptor,
1681 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1682 .get_config_descriptor = darwin_get_config_descriptor,
1684 .open = darwin_open,
1685 .close = darwin_close,
1686 .get_configuration = darwin_get_configuration,
1687 .set_configuration = darwin_set_configuration,
1688 .claim_interface = darwin_claim_interface,
1689 .release_interface = darwin_release_interface,
1691 .set_interface_altsetting = darwin_set_interface_altsetting,
1692 .clear_halt = darwin_clear_halt,
1693 .reset_device = darwin_reset_device,
1695 .kernel_driver_active = darwin_kernel_driver_active,
1696 .detach_kernel_driver = darwin_detach_kernel_driver,
1697 .attach_kernel_driver = darwin_attach_kernel_driver,
1699 .destroy_device = darwin_destroy_device,
1701 .submit_transfer = darwin_submit_transfer,
1702 .cancel_transfer = darwin_cancel_transfer,
1703 .clear_transfer_priv = darwin_clear_transfer_priv,
1705 .handle_events = op_handle_events,
1707 .clock_gettime = darwin_clock_gettime,
1709 .device_priv_size = sizeof(struct darwin_device_priv),
1710 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1711 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1712 .add_iso_packet_size = 0,