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 /* async event thread */
51 static pthread_mutex_t libusb_darwin_at_mutex;
52 static pthread_cond_t libusb_darwin_at_cond;
54 static clock_serv_t clock_realtime;
55 static clock_serv_t clock_monotonic;
57 static CFRunLoopRef libusb_darwin_acfl = NULL; /* async cf loop */
58 static int initCount = 0;
60 /* async event thread */
61 static pthread_t libusb_darwin_at;
63 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
64 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
65 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
66 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
67 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
69 static const char *darwin_error_str (int result) {
71 case kIOReturnSuccess:
73 case kIOReturnNotOpen:
74 return "device not opened for exclusive access";
75 case kIOReturnNoDevice:
76 return "no connection to an IOService";
77 case kIOUSBNoAsyncPortErr:
78 return "no async port has been opened for interface";
79 case kIOReturnExclusiveAccess:
80 return "another process has device opened for exclusive access";
81 case kIOUSBPipeStalled:
82 return "pipe is stalled";
84 return "could not establish a connection to the Darwin kernel";
85 case kIOUSBTransactionTimeout:
86 return "transaction timed out";
87 case kIOReturnBadArgument:
88 return "invalid argument";
89 case kIOReturnAborted:
90 return "transaction aborted";
91 case kIOReturnNotResponding:
92 return "device not responding";
93 case kIOReturnOverrun:
94 return "data overrun";
95 case kIOReturnCannotWire:
96 return "physical memory can not be wired down";
98 return "unknown error";
102 static int darwin_to_libusb (int result) {
104 case kIOReturnUnderrun:
105 case kIOReturnSuccess:
106 return LIBUSB_SUCCESS;
107 case kIOReturnNotOpen:
108 case kIOReturnNoDevice:
109 return LIBUSB_ERROR_NO_DEVICE;
110 case kIOReturnExclusiveAccess:
111 return LIBUSB_ERROR_ACCESS;
112 case kIOUSBPipeStalled:
113 return LIBUSB_ERROR_PIPE;
114 case kIOReturnBadArgument:
115 return LIBUSB_ERROR_INVALID_PARAM;
116 case kIOUSBTransactionTimeout:
117 return LIBUSB_ERROR_TIMEOUT;
118 case kIOReturnNotResponding:
119 case kIOReturnAborted:
121 case kIOUSBNoAsyncPortErr:
123 return LIBUSB_ERROR_OTHER;
128 static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp) {
129 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
131 /* current interface */
132 struct darwin_interface *cInterface;
136 usbi_info (HANDLE_CTX(dev_handle), "converting ep address 0x%02x to pipeRef and interface", ep);
138 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
139 cInterface = &priv->interfaces[iface];
141 if (dev_handle->claimed_interfaces & (1 << iface)) {
142 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
143 if (cInterface->endpoint_addrs[i] == ep) {
146 usbi_info (HANDLE_CTX(dev_handle), "pipe %d on interface %d matches", *pipep, *ifcp);
153 /* No pipe found with the correct endpoint address */
154 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
159 static int usb_setup_device_iterator (io_iterator_t *deviceIterator, long location) {
160 CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBDeviceClassName);
163 return kIOReturnError;
166 CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
167 &kCFTypeDictionaryKeyCallBacks,
168 &kCFTypeDictionaryValueCallBacks);
170 if (propertyMatchDict) {
171 CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberLongType, &location);
173 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
174 /* release our reference to the CFNumber (CFDictionarySetValue retains it) */
175 CFRelease (locationCF);
177 CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
178 /* release out reference to the CFMutableDictionaryRef (CFDictionarySetValue retains it) */
179 CFRelease (propertyMatchDict);
181 /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
184 return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator);
187 static usb_device_t **usb_get_next_device (io_iterator_t deviceIterator, UInt32 *locationp) {
188 io_cf_plugin_ref_t *plugInInterface = NULL;
189 usb_device_t **device;
190 io_service_t usbDevice;
194 if (!IOIteratorIsValid (deviceIterator))
198 while ((usbDevice = IOIteratorNext(deviceIterator))) {
199 result = IOCreatePlugInInterfaceForService(usbDevice, kIOUSBDeviceUserClientTypeID,
200 kIOCFPlugInInterfaceID, &plugInInterface,
203 /* we are done with the usb_device_t */
204 (void)IOObjectRelease(usbDevice);
205 if (kIOReturnSuccess == result && plugInInterface)
208 usbi_dbg ("libusb/darwin.c usb_get_next_device: could not set up plugin for service: %s\n", darwin_error_str (result));
214 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
217 (*plugInInterface)->Stop(plugInInterface);
218 IODestroyPlugInInterface (plugInInterface);
220 /* get the location from the device */
222 (*(device))->GetLocationID(device, locationp);
227 static kern_return_t darwin_get_device (uint32_t dev_location, usb_device_t ***darwin_device) {
228 kern_return_t kresult;
230 io_iterator_t deviceIterator;
232 kresult = usb_setup_device_iterator (&deviceIterator, dev_location);
236 /* This port of libusb uses locations to keep track of devices. */
237 while ((*darwin_device = usb_get_next_device (deviceIterator, &location)) != NULL) {
238 if (location == dev_location)
241 (**darwin_device)->Release(*darwin_device);
244 IOObjectRelease (deviceIterator);
246 if (!(*darwin_device))
247 return kIOReturnNoDevice;
249 return kIOReturnSuccess;
254 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
255 struct libusb_context *ctx = (struct libusb_context *)ptr;
256 struct libusb_device_handle *handle;
257 struct darwin_device_priv *dpriv;
258 struct darwin_device_handle_priv *priv;
263 CFTypeRef locationCF;
266 usbi_info (ctx, "a device has been detached");
268 while ((device = IOIteratorNext (rem_devices)) != 0) {
269 /* get the location from the i/o registry */
270 locationCF = IORegistryEntryCreateCFProperty (device, CFSTR(kUSBDevicePropertyLocationID), kCFAllocatorDefault, 0);
272 IOObjectRelease (device);
277 locationValid = CFGetTypeID(locationCF) == CFNumberGetTypeID() &&
278 CFNumberGetValue(locationCF, kCFNumberLongType, &location);
280 CFRelease (locationCF);
285 usbi_mutex_lock(&ctx->open_devs_lock);
286 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
287 dpriv = (struct darwin_device_priv *)handle->dev->os_priv;
289 /* the device may have been opened several times. write to each handle's event descriptor */
290 if (dpriv->location == location && handle->os_priv) {
291 priv = (struct darwin_device_handle_priv *)handle->os_priv;
293 message = MESSAGE_DEVICE_GONE;
294 write (priv->fds[1], &message, sizeof (message));
298 usbi_mutex_unlock(&ctx->open_devs_lock);
302 static void darwin_clear_iterator (io_iterator_t iter) {
305 while ((device = IOIteratorNext (iter)) != 0)
306 IOObjectRelease (device);
309 static void *event_thread_main (void *arg0) {
311 struct libusb_context *ctx = (struct libusb_context *)arg0;
312 CFRunLoopRef runloop;
314 /* Set this thread's name, so it can be seen in the debugger
315 and crash reports. */
316 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
317 pthread_setname_np ("org.libusb.device-detach");
320 /* Tell the Objective-C garbage collector about this thread.
321 This is required because, unlike NSThreads, pthreads are
322 not automatically registered. Although we don't use
323 Objective-C, we use CoreFoundation, which does. */
324 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
325 objc_registerThreadWithCollector();
328 /* hotplug (device removal) source */
329 CFRunLoopSourceRef libusb_notification_cfsource;
330 io_notification_port_t libusb_notification_port;
331 io_iterator_t libusb_rem_device_iterator;
333 usbi_info (ctx, "creating hotplug event source");
335 runloop = CFRunLoopGetCurrent ();
338 /* add the notification port to the run loop */
339 libusb_notification_port = IONotificationPortCreate (kIOMasterPortDefault);
340 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
341 CFRunLoopAddSource(CFRunLoopGetCurrent (), libusb_notification_cfsource, kCFRunLoopDefaultMode);
343 /* create notifications for removed devices */
344 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
345 IOServiceMatching(kIOUSBDeviceClassName),
346 (IOServiceMatchingCallback)darwin_devices_detached,
347 (void *)ctx, &libusb_rem_device_iterator);
349 if (kresult != kIOReturnSuccess) {
350 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
356 darwin_clear_iterator (libusb_rem_device_iterator);
358 usbi_info (ctx, "thread ready to receive events");
360 /* let the main thread know about the async runloop */
361 libusb_darwin_acfl = CFRunLoopGetCurrent ();
363 /* signal the main thread */
364 pthread_mutex_lock (&libusb_darwin_at_mutex);
365 pthread_cond_signal (&libusb_darwin_at_cond);
366 pthread_mutex_unlock (&libusb_darwin_at_mutex);
368 /* run the runloop */
371 usbi_info (ctx, "thread exiting");
373 /* delete notification port */
374 IONotificationPortDestroy (libusb_notification_port);
375 IOObjectRelease (libusb_rem_device_iterator);
379 libusb_darwin_acfl = NULL;
384 static int darwin_init(struct libusb_context *ctx) {
385 host_name_port_t host_self;
387 if (!(initCount++)) {
388 /* create the clocks that will be used */
390 host_self = mach_host_self();
391 host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
392 host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
393 mach_port_deallocate(mach_task_self(), host_self);
395 pthread_mutex_init (&libusb_darwin_at_mutex, NULL);
396 pthread_cond_init (&libusb_darwin_at_cond, NULL);
398 pthread_create (&libusb_darwin_at, NULL, event_thread_main, (void *)ctx);
400 pthread_mutex_lock (&libusb_darwin_at_mutex);
401 while (!libusb_darwin_acfl)
402 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
403 pthread_mutex_unlock (&libusb_darwin_at_mutex);
409 static void darwin_exit (void) {
410 if (!(--initCount)) {
411 mach_port_deallocate(mach_task_self(), clock_realtime);
412 mach_port_deallocate(mach_task_self(), clock_monotonic);
414 /* stop the async runloop */
415 CFRunLoopStop (libusb_darwin_acfl);
416 pthread_join (libusb_darwin_at, NULL);
420 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
421 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
423 /* return cached copy */
424 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
431 static int get_configuration_index (struct libusb_device *dev, int config_value) {
432 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
434 IOUSBConfigurationDescriptorPtr desc;
437 /* is there a simpler way to determine the index? */
438 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
439 if (kresult != kIOReturnSuccess)
440 return darwin_to_libusb (kresult);
442 for (i = 0 ; i < numConfig ; i++) {
443 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
445 if (desc->bConfigurationValue == config_value)
449 /* configuration not found */
450 return LIBUSB_ERROR_OTHER;
453 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
454 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
457 if (0 == priv->active_config)
458 return LIBUSB_ERROR_INVALID_PARAM;
460 config_index = get_configuration_index (dev, priv->active_config);
461 if (config_index < 0)
464 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
467 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
468 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
469 IOUSBConfigurationDescriptorPtr desc;
471 usb_device_t **device = NULL;
474 return LIBUSB_ERROR_OTHER;
477 kresult = darwin_get_device (priv->location, &device);
478 if (kresult || !device) {
479 usbi_err (DEVICE_CTX (dev), "could not find device: %s", darwin_error_str (kresult));
481 return darwin_to_libusb (kresult);
484 /* don't have to open the device to get a config descriptor */
486 device = priv->device;
488 kresult = (*device)->GetConfigurationDescriptorPtr (device, config_index, &desc);
489 if (kresult == kIOReturnSuccess) {
490 /* copy descriptor */
491 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
492 len = libusb_le16_to_cpu(desc->wTotalLength);
494 memmove (buffer, desc, len);
496 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
501 (*device)->Release (device);
503 return darwin_to_libusb (kresult);
506 /* check whether the os has configured the device */
507 static int darwin_check_configuration (struct libusb_context *ctx, struct libusb_device *dev, usb_device_t **darwin_device) {
508 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
510 IOUSBConfigurationDescriptorPtr configDesc;
511 IOUSBFindInterfaceRequest request;
512 kern_return_t kresult;
513 io_iterator_t interface_iterator;
514 io_service_t firstInterface;
516 if (priv->dev_descriptor.bNumConfigurations < 1) {
517 usbi_err (ctx, "device has no configurations");
518 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
521 /* find the first configuration */
522 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
523 priv->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
525 /* check if the device is already configured. there is probably a better way than iterating over the
526 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
527 might lock up on the device request) */
529 /* Setup the Interface Request */
530 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
531 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
532 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
533 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
535 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
537 return darwin_to_libusb (kresult);
540 firstInterface = IOIteratorNext(interface_iterator);
542 /* done with the interface iterator */
543 IOObjectRelease(interface_iterator);
545 if (firstInterface) {
546 IOObjectRelease (firstInterface);
548 /* device is configured */
549 if (priv->dev_descriptor.bNumConfigurations == 1)
550 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
551 priv->active_config = priv->first_config;
553 /* devices with more than one configuration should work with GetConfiguration */
554 (*darwin_device)->GetConfiguration (darwin_device, &priv->active_config);
557 priv->active_config = 0;
559 usbi_info (ctx, "active config: %u, first config: %u", priv->active_config, priv->first_config);
564 static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct libusb_device *dev, usb_device_t **device) {
565 struct darwin_device_priv *priv;
566 int retries = 5, delay = 30000;
567 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
572 UInt16 idProduct, idVendor;
574 (*device)->GetDeviceClass (device, &bDeviceClass);
575 (*device)->GetDeviceProduct (device, &idProduct);
576 (*device)->GetDeviceVendor (device, &idVendor);
578 priv = (struct darwin_device_priv *)dev->os_priv;
580 /* try to open the device (we can usually continue even if this fails) */
581 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
583 /**** retrieve device descriptor ****/
585 /* Set up request for device descriptor */
586 memset (&(priv->dev_descriptor), 0, sizeof(IOUSBDeviceDescriptor));
587 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
588 req.bRequest = kUSBRqGetDescriptor;
589 req.wValue = kUSBDeviceDesc << 8;
591 req.wLength = sizeof(priv->dev_descriptor);
592 req.pData = &(priv->dev_descriptor);
594 /* according to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
595 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
596 * to follow the spec as closely as possible, try opening the device */
598 ret = (*(device))->DeviceRequest (device, &req);
600 if (kIOReturnOverrun == ret && kUSBDeviceDesc == priv->dev_descriptor.bDescriptorType)
601 /* received an overrun error but we still received a device descriptor */
602 ret = kIOReturnSuccess;
604 if (kIOReturnSuccess == ret && (0 == priv->dev_descriptor.idProduct ||
605 0 == priv->dev_descriptor.bNumConfigurations ||
606 0 == priv->dev_descriptor.bcdUSB)) {
607 /* work around for incorrectly configured devices */
608 if (try_reconfigure && is_open) {
609 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
611 /* set the first configuration */
612 (*device)->SetConfiguration(device, 1);
614 /* don't try to reconfigure again */
618 ret = kIOUSBPipeStalled;
621 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
622 /* device may be suspended. unsuspend it and try again */
623 #if DeviceVersion >= 320
626 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
627 (void)(*device)->GetUSBDeviceInformation (device, &info);
629 try_unsuspend = info & (1 << kUSBInformationDeviceIsSuspendedBit);
633 /* resume the device */
634 ret2 = (*device)->USBDeviceSuspend (device, 0);
635 if (kIOReturnSuccess != ret2) {
636 /* prevent log spew from poorly behaving devices. this indicates the
637 os actually had trouble communicating with the device */
638 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
646 if (kIOReturnSuccess != ret) {
647 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
648 /* sleep for a little while before trying again */
651 } while (kIOReturnSuccess != ret && retries--);
654 /* resuspend the device */
655 (void)(*device)->USBDeviceSuspend (device, 1);
658 (void) (*device)->USBDeviceClose (device);
660 if (ret != kIOReturnSuccess) {
661 /* a debug message was already printed out for this error */
662 if (LIBUSB_CLASS_HUB == bDeviceClass)
663 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s. skipping device", idVendor, idProduct, darwin_error_str (ret));
665 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s. skipping device", idVendor, idProduct, darwin_error_str (ret));
670 usbi_dbg ("device descriptor:");
671 usbi_dbg (" bDescriptorType: 0x%02x", priv->dev_descriptor.bDescriptorType);
672 usbi_dbg (" bcdUSB: 0x%04x", priv->dev_descriptor.bcdUSB);
673 usbi_dbg (" bDeviceClass: 0x%02x", priv->dev_descriptor.bDeviceClass);
674 usbi_dbg (" bDeviceSubClass: 0x%02x", priv->dev_descriptor.bDeviceSubClass);
675 usbi_dbg (" bDeviceProtocol: 0x%02x", priv->dev_descriptor.bDeviceProtocol);
676 usbi_dbg (" bMaxPacketSize0: 0x%02x", priv->dev_descriptor.bMaxPacketSize0);
677 usbi_dbg (" idVendor: 0x%04x", priv->dev_descriptor.idVendor);
678 usbi_dbg (" idProduct: 0x%04x", priv->dev_descriptor.idProduct);
679 usbi_dbg (" bcdDevice: 0x%04x", priv->dev_descriptor.bcdDevice);
680 usbi_dbg (" iManufacturer: 0x%02x", priv->dev_descriptor.iManufacturer);
681 usbi_dbg (" iProduct: 0x%02x", priv->dev_descriptor.iProduct);
682 usbi_dbg (" iSerialNumber: 0x%02x", priv->dev_descriptor.iSerialNumber);
683 usbi_dbg (" bNumConfigurations: 0x%02x", priv->dev_descriptor.bNumConfigurations);
685 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
686 if (libusb_le16_to_cpu (priv->dev_descriptor.idProduct) != idProduct) {
687 /* not a valid device */
688 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
689 idProduct, libusb_le16_to_cpu (priv->dev_descriptor.idProduct));
696 static int process_new_device (struct libusb_context *ctx, usb_device_t **device, UInt32 locationID, struct discovered_devs **_discdevs) {
697 struct darwin_device_priv *priv;
698 struct libusb_device *dev;
699 struct discovered_devs *discdevs;
702 int ret = 0, need_unref = 0;
705 dev = usbi_get_device_by_session_id(ctx, locationID);
707 usbi_info (ctx, "allocating new device for location 0x%08x", locationID);
708 dev = usbi_alloc_device(ctx, locationID);
711 usbi_info (ctx, "using existing device for location 0x%08x", locationID);
714 ret = LIBUSB_ERROR_NO_MEM;
718 priv = (struct darwin_device_priv *)dev->os_priv;
720 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&address);
722 ret = darwin_cache_device_descriptor (ctx, dev, device);
726 /* check current active configuration (and cache the first configuration value-- which may be used by claim_interface) */
727 ret = darwin_check_configuration (ctx, dev, device);
731 dev->bus_number = locationID >> 24;
732 dev->device_address = address;
734 (*device)->GetDeviceSpeed (device, &devSpeed);
737 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
738 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
739 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
741 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
744 /* save our location, we'll need this later */
745 priv->location = locationID;
746 snprintf(priv->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", address, priv->dev_descriptor.idVendor, priv->dev_descriptor.idProduct,
747 priv->dev_descriptor.bDeviceClass, priv->dev_descriptor.bDeviceSubClass);
749 ret = usbi_sanitize_device (dev);
753 /* append the device to the list of discovered devices */
754 discdevs = discovered_devs_append(*_discdevs, dev);
756 ret = LIBUSB_ERROR_NO_MEM;
760 *_discdevs = discdevs;
762 usbi_info (ctx, "found device with address %d at %s", dev->device_address, priv->sys_path);
766 libusb_unref_device(dev);
771 static int darwin_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs) {
772 io_iterator_t deviceIterator;
773 usb_device_t **device;
774 kern_return_t kresult;
777 kresult = usb_setup_device_iterator (&deviceIterator, 0);
778 if (kresult != kIOReturnSuccess)
779 return darwin_to_libusb (kresult);
781 while ((device = usb_get_next_device (deviceIterator, &location)) != NULL) {
782 (void) process_new_device (ctx, device, location, _discdevs);
784 (*(device))->Release(device);
787 IOObjectRelease(deviceIterator);
792 static int darwin_open (struct libusb_device_handle *dev_handle) {
793 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
794 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
795 usb_device_t **darwin_device;
798 if (0 == dpriv->open_count) {
799 kresult = darwin_get_device (dpriv->location, &darwin_device);
801 usbi_err (HANDLE_CTX (dev_handle), "could not find device: %s", darwin_error_str (kresult));
802 return darwin_to_libusb (kresult);
805 dpriv->device = darwin_device;
807 /* try to open the device */
808 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
810 if (kresult != kIOReturnSuccess) {
811 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
814 case kIOReturnExclusiveAccess:
815 /* it is possible to perform some actions on a device that is not open so do not return an error */
820 (*(dpriv->device))->Release (dpriv->device);
821 dpriv->device = NULL;
822 return darwin_to_libusb (kresult);
825 /* create async event source */
826 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
827 if (kresult != kIOReturnSuccess) {
828 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
830 (*(dpriv->device))->USBDeviceClose (dpriv->device);
831 (*(dpriv->device))->Release (dpriv->device);
833 dpriv->device = NULL;
834 return darwin_to_libusb (kresult);
839 CFRetain (libusb_darwin_acfl);
841 /* add the cfSource to the aync run loop */
842 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
846 /* device opened successfully */
849 /* create a file descriptor for notifications */
852 /* set the pipe to be non-blocking */
853 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
855 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
857 usbi_info (HANDLE_CTX (dev_handle), "device open for access");
862 static void darwin_close (struct libusb_device_handle *dev_handle) {
863 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
864 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
868 if (dpriv->open_count == 0) {
869 /* something is probably very wrong if this is the case */
870 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
876 /* make sure all interfaces are released */
877 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
878 if (dev_handle->claimed_interfaces & (1 << i))
879 libusb_release_interface (dev_handle, i);
881 if (0 == dpriv->open_count) {
883 /* delete the device's async event source */
884 if (priv->cfSource) {
885 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
886 CFRelease (priv->cfSource);
889 /* close the device */
890 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
892 /* Log the fact that we had a problem closing the file, however failing a
893 * close isn't really an error, so return success anyway */
894 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
898 kresult = (*(dpriv->device))->Release(dpriv->device);
900 /* Log the fact that we had a problem closing the file, however failing a
901 * close isn't really an error, so return success anyway */
902 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
905 dpriv->device = NULL;
908 /* file descriptors are maintained per-instance */
909 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
910 close (priv->fds[1]);
911 close (priv->fds[0]);
913 priv->fds[0] = priv->fds[1] = -1;
916 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
917 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
919 *config = (int) dpriv->active_config;
924 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
925 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
929 /* Setting configuration will invalidate the interface, so we need
930 to reclaim it. First, dispose of existing interfaces, if any. */
931 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
932 if (dev_handle->claimed_interfaces & (1 << i))
933 darwin_release_interface (dev_handle, i);
935 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
936 if (kresult != kIOReturnSuccess)
937 return darwin_to_libusb (kresult);
939 /* Reclaim any interfaces. */
940 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
941 if (dev_handle->claimed_interfaces & (1 << i))
942 darwin_claim_interface (dev_handle, i);
944 dpriv->active_config = config;
949 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
950 IOUSBFindInterfaceRequest request;
951 uint8_t current_interface;
952 kern_return_t kresult;
953 io_iterator_t interface_iterator;
955 *usbInterfacep = IO_OBJECT_NULL;
957 /* Setup the Interface Request */
958 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
959 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
960 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
961 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
963 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
967 for ( current_interface = 0 ; current_interface <= ifc ; current_interface++ ) {
968 *usbInterfacep = IOIteratorNext(interface_iterator);
969 if (current_interface != ifc)
970 (void) IOObjectRelease (*usbInterfacep);
973 /* done with the interface iterator */
974 IOObjectRelease(interface_iterator);
979 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
980 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
982 /* current interface */
983 struct darwin_interface *cInterface = &priv->interfaces[iface];
985 kern_return_t kresult;
987 u_int8_t numep, direction, number;
988 u_int8_t dont_care1, dont_care3;
989 u_int16_t dont_care2;
992 usbi_info (HANDLE_CTX (dev_handle), "building table of endpoints.");
994 /* retrieve the total number of endpoints on this interface */
995 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
997 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
998 return darwin_to_libusb (kresult);
1001 /* iterate through pipe references */
1002 for (i = 1 ; i <= numep ; i++) {
1003 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1004 &dont_care2, &dont_care3);
1006 if (kresult != kIOReturnSuccess) {
1007 usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
1009 return darwin_to_libusb (kresult);
1012 usbi_info (HANDLE_CTX (dev_handle), "interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
1014 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1017 cInterface->num_endpoints = numep;
1022 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1023 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1024 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1025 io_service_t usbInterface = IO_OBJECT_NULL;
1027 IOCFPlugInInterface **plugInInterface = NULL;
1030 /* current interface */
1031 struct darwin_interface *cInterface = &priv->interfaces[iface];
1033 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1034 if (kresult != kIOReturnSuccess)
1035 return darwin_to_libusb (kresult);
1037 /* make sure we have an interface */
1038 if (!usbInterface && dpriv->first_config != 0) {
1039 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1041 /* set the configuration */
1042 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1043 if (kresult != LIBUSB_SUCCESS) {
1044 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1048 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1050 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1051 return darwin_to_libusb (kresult);
1055 if (!usbInterface) {
1056 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1057 return LIBUSB_ERROR_NOT_FOUND;
1060 /* get an interface to the device's interface */
1061 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1062 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1064 /* ignore release error */
1065 (void)IOObjectRelease (usbInterface);
1068 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1069 return darwin_to_libusb (kresult);
1072 if (!plugInInterface) {
1073 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1074 return LIBUSB_ERROR_NOT_FOUND;
1077 /* Do the actual claim */
1078 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1079 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1080 (LPVOID)&cInterface->interface);
1081 /* We no longer need the intermediate plug-in */
1082 IODestroyPlugInInterface (plugInInterface);
1083 if (kresult || !cInterface->interface) {
1084 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1085 return darwin_to_libusb (kresult);
1088 /* claim the interface */
1089 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1091 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1092 return darwin_to_libusb (kresult);
1095 /* update list of endpoints */
1096 kresult = get_endpoints (dev_handle, iface);
1098 /* this should not happen */
1099 darwin_release_interface (dev_handle, iface);
1100 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1104 cInterface->cfSource = NULL;
1106 /* create async event source */
1107 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1108 if (kresult != kIOReturnSuccess) {
1109 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1111 /* can't continue without an async event source */
1112 (void)darwin_release_interface (dev_handle, iface);
1114 return darwin_to_libusb (kresult);
1117 /* add the cfSource to the async thread's run loop */
1118 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1120 usbi_info (HANDLE_CTX (dev_handle), "interface opened");
1125 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1126 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1129 /* current interface */
1130 struct darwin_interface *cInterface = &priv->interfaces[iface];
1132 /* Check to see if an interface is open */
1133 if (!cInterface->interface)
1134 return LIBUSB_SUCCESS;
1136 /* clean up endpoint data */
1137 cInterface->num_endpoints = 0;
1139 /* delete the interface's async event source */
1140 if (cInterface->cfSource) {
1141 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1142 CFRelease (cInterface->cfSource);
1145 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1147 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1149 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1150 if (kresult != kIOReturnSuccess)
1151 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1153 cInterface->interface = IO_OBJECT_NULL;
1155 return darwin_to_libusb (kresult);
1158 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1159 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1162 /* current interface */
1163 struct darwin_interface *cInterface = &priv->interfaces[iface];
1165 if (!cInterface->interface)
1166 return LIBUSB_ERROR_NO_DEVICE;
1168 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1169 if (kresult != kIOReturnSuccess)
1170 darwin_reset_device (dev_handle);
1172 /* update list of endpoints */
1173 kresult = get_endpoints (dev_handle, iface);
1175 /* this should not happen */
1176 darwin_release_interface (dev_handle, iface);
1177 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1181 return darwin_to_libusb (kresult);
1184 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1185 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1187 /* current interface */
1188 struct darwin_interface *cInterface;
1189 uint8_t pipeRef, iface;
1192 /* determine the interface/endpoint to use */
1193 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
1194 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1196 return LIBUSB_ERROR_NOT_FOUND;
1199 cInterface = &priv->interfaces[iface];
1201 #if (InterfaceVersion < 190)
1202 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1204 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1205 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1208 usbi_err (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1210 return darwin_to_libusb (kresult);
1213 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1214 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1217 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1219 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1221 return darwin_to_libusb (kresult);
1224 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1225 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1226 io_service_t usbInterface;
1230 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1232 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1234 return darwin_to_libusb (kresult);
1237 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1238 IOObjectRelease (usbInterface);
1250 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1251 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1254 return LIBUSB_ERROR_NOT_SUPPORTED;
1257 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1260 return LIBUSB_ERROR_NOT_SUPPORTED;
1263 static void darwin_destroy_device(struct libusb_device *dev) {
1267 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1268 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1269 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1272 uint8_t is_read; /* 0 = we're reading, 1 = we're writing */
1273 uint8_t transferType;
1274 /* None of the values below are used in libusb for bulk transfers */
1275 uint8_t direction, number, interval, pipeRef, iface;
1276 uint16_t maxPacketSize;
1278 struct darwin_interface *cInterface;
1280 /* are we reading or writing? */
1281 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1283 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1284 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1286 return LIBUSB_ERROR_NOT_FOUND;
1289 cInterface = &priv->interfaces[iface];
1291 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1292 &transferType, &maxPacketSize, &interval);
1294 /* submit the request */
1295 /* timeouts are unavailable on interrupt endpoints */
1296 if (transferType == kUSBInterrupt) {
1298 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1299 transfer->length, darwin_async_io_callback, itransfer);
1301 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1302 transfer->length, darwin_async_io_callback, itransfer);
1304 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1307 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1308 transfer->length, transfer->timeout, transfer->timeout,
1309 darwin_async_io_callback, (void *)itransfer);
1311 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1312 transfer->length, transfer->timeout, transfer->timeout,
1313 darwin_async_io_callback, (void *)itransfer);
1317 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", is_read ? "In" : "Out",
1318 darwin_error_str(ret), ret);
1320 return darwin_to_libusb (ret);
1323 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1324 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1325 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1326 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1329 uint8_t is_read; /* 0 = we're writing, 1 = we're reading */
1330 uint8_t pipeRef, iface;
1332 AbsoluteTime atTime;
1335 struct darwin_interface *cInterface;
1337 /* are we reading or writing? */
1338 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1340 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1341 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1342 free(tpriv->isoc_framelist);
1343 tpriv->isoc_framelist = NULL;
1346 if (!tpriv->isoc_framelist) {
1347 tpriv->num_iso_packets = transfer->num_iso_packets;
1348 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1349 if (!tpriv->isoc_framelist)
1350 return LIBUSB_ERROR_NO_MEM;
1353 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1354 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1355 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1357 /* determine the interface/endpoint to use */
1358 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1359 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1361 return LIBUSB_ERROR_NOT_FOUND;
1364 cInterface = &priv->interfaces[iface];
1366 /* Last but not least we need the bus frame number */
1367 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1369 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1370 free(tpriv->isoc_framelist);
1371 tpriv->isoc_framelist = NULL;
1373 return darwin_to_libusb (kresult);
1376 /* schedule for a frame a little in the future */
1379 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1380 frame = cInterface->frames[transfer->endpoint];
1382 /* submit the request */
1384 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1385 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1388 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1389 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1392 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets / 8;
1394 if (kresult != kIOReturnSuccess) {
1395 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", is_read ? "In" : "Out",
1396 darwin_error_str(kresult));
1397 free (tpriv->isoc_framelist);
1398 tpriv->isoc_framelist = NULL;
1401 return darwin_to_libusb (kresult);
1404 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1405 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1406 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1407 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1408 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1409 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1413 bzero(&tpriv->req, sizeof(tpriv->req));
1415 /* IOUSBDeviceInterface expects the request in cpu endianess */
1416 tpriv->req.bmRequestType = setup->bmRequestType;
1417 tpriv->req.bRequest = setup->bRequest;
1418 /* these values should be in bus order from libusb_fill_control_setup */
1419 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1420 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1421 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1422 /* data is stored after the libusb control block */
1423 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1424 tpriv->req.completionTimeout = transfer->timeout;
1425 tpriv->req.noDataTimeout = transfer->timeout;
1427 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1429 /* all transfers in libusb-1.0 are async */
1431 if (transfer->endpoint) {
1432 struct darwin_interface *cInterface;
1433 uint8_t pipeRef, iface;
1435 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1436 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1438 return LIBUSB_ERROR_NOT_FOUND;
1441 cInterface = &priv->interfaces[iface];
1443 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1445 /* control request on endpoint 0 */
1446 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1448 if (kresult != kIOReturnSuccess)
1449 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1451 return darwin_to_libusb (kresult);
1454 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1455 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1457 switch (transfer->type) {
1458 case LIBUSB_TRANSFER_TYPE_CONTROL:
1459 return submit_control_transfer(itransfer);
1460 case LIBUSB_TRANSFER_TYPE_BULK:
1461 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1462 return submit_bulk_transfer(itransfer);
1463 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1464 return submit_iso_transfer(itransfer);
1466 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1467 return LIBUSB_ERROR_INVALID_PARAM;
1471 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1472 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1473 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1476 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions control pipe");
1479 return LIBUSB_ERROR_NO_DEVICE;
1481 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1483 return darwin_to_libusb (kresult);
1486 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1487 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1488 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1489 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1490 struct darwin_interface *cInterface;
1491 uint8_t pipeRef, iface;
1494 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1495 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1497 return LIBUSB_ERROR_NOT_FOUND;
1500 cInterface = &priv->interfaces[iface];
1503 return LIBUSB_ERROR_NO_DEVICE;
1505 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions on interface %d pipe %d", iface, pipeRef);
1507 /* abort transactions */
1508 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1510 usbi_info (ITRANSFER_CTX (itransfer), "calling clear pipe stall to clear the data toggle bit");
1512 /* clear the data toggle bit */
1513 #if (InterfaceVersion < 190)
1514 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1516 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1517 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1520 return darwin_to_libusb (kresult);
1523 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1524 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1526 switch (transfer->type) {
1527 case LIBUSB_TRANSFER_TYPE_CONTROL:
1528 return cancel_control_transfer(itransfer);
1529 case LIBUSB_TRANSFER_TYPE_BULK:
1530 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1531 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1532 return darwin_abort_transfers (itransfer);
1534 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1535 return LIBUSB_ERROR_INVALID_PARAM;
1539 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1540 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1541 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1543 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1544 free (tpriv->isoc_framelist);
1545 tpriv->isoc_framelist = NULL;
1549 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1550 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1551 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1552 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1553 UInt32 message, size;
1555 usbi_info (ITRANSFER_CTX (itransfer), "an async io operation has completed");
1557 size = (UInt32) arg0;
1559 /* send a completion message to the device's file descriptor */
1560 message = MESSAGE_ASYNC_IO_COMPLETE;
1561 write (priv->fds[1], &message, sizeof (message));
1562 write (priv->fds[1], &itransfer, sizeof (itransfer));
1563 write (priv->fds[1], &result, sizeof (IOReturn));
1564 write (priv->fds[1], &size, sizeof (size));
1567 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1568 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT)
1569 result = kIOUSBTransactionTimeout;
1572 case kIOReturnUnderrun:
1573 case kIOReturnSuccess:
1574 return LIBUSB_TRANSFER_COMPLETED;
1575 case kIOReturnAborted:
1576 return LIBUSB_TRANSFER_CANCELLED;
1577 case kIOUSBPipeStalled:
1578 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: pipe is stalled");
1579 return LIBUSB_TRANSFER_STALL;
1580 case kIOReturnOverrun:
1581 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1582 return LIBUSB_TRANSFER_OVERFLOW;
1583 case kIOUSBTransactionTimeout:
1584 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1585 itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
1586 return LIBUSB_TRANSFER_TIMED_OUT;
1588 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1589 return LIBUSB_TRANSFER_ERROR;
1593 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1594 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1595 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1596 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1597 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1598 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1599 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1602 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1603 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1607 usbi_info (ITRANSFER_CTX (itransfer), "handling %s completion with kernel status %d",
1608 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
1610 if (kIOReturnSuccess == result || kIOReturnUnderrun == result) {
1611 if (isIsoc && tpriv->isoc_framelist) {
1612 /* copy isochronous results back */
1614 for (i = 0; i < transfer->num_iso_packets ; i++) {
1615 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1616 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1617 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1620 itransfer->transferred += io_size;
1623 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1624 usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
1627 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready) {
1628 struct usbi_transfer *itransfer;
1631 POLL_NFDS_TYPE i = 0;
1635 usbi_mutex_lock(&ctx->open_devs_lock);
1636 for (i = 0; i < nfds && num_ready > 0; i++) {
1637 struct pollfd *pollfd = &fds[i];
1638 struct libusb_device_handle *handle;
1639 struct darwin_device_handle_priv *hpriv = NULL;
1641 usbi_info (ctx, "checking fd %i with revents = %x", fds[i], pollfd->revents);
1643 if (!pollfd->revents)
1647 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
1648 hpriv = (struct darwin_device_handle_priv *)handle->os_priv;
1649 if (hpriv->fds[0] == pollfd->fd)
1653 if (!(pollfd->revents & POLLERR)) {
1654 ret = read (hpriv->fds[0], &message, sizeof (message));
1655 if (ret < (ssize_t)sizeof (message))
1658 /* could not poll the device-- response is to delete the device (this seems a little heavy-handed) */
1659 message = MESSAGE_DEVICE_GONE;
1662 case MESSAGE_DEVICE_GONE:
1663 /* remove the device's async port from the runloop */
1664 if (hpriv->cfSource) {
1665 if (libusb_darwin_acfl)
1666 CFRunLoopRemoveSource (libusb_darwin_acfl, hpriv->cfSource, kCFRunLoopDefaultMode);
1667 CFRelease (hpriv->cfSource);
1668 hpriv->cfSource = NULL;
1671 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1672 usbi_handle_disconnect(handle);
1674 /* done with this device */
1676 case MESSAGE_ASYNC_IO_COMPLETE:
1677 read (hpriv->fds[0], &itransfer, sizeof (itransfer));
1678 read (hpriv->fds[0], &kresult, sizeof (IOReturn));
1679 read (hpriv->fds[0], &io_size, sizeof (UInt32));
1681 darwin_handle_callback (itransfer, kresult, io_size);
1684 usbi_err (ctx, "unknown message received from device pipe");
1688 usbi_mutex_unlock(&ctx->open_devs_lock);
1693 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1694 mach_timespec_t sys_time;
1695 clock_serv_t clock_ref;
1698 case USBI_CLOCK_REALTIME:
1699 /* CLOCK_REALTIME represents time since the epoch */
1700 clock_ref = clock_realtime;
1702 case USBI_CLOCK_MONOTONIC:
1703 /* use system boot time as reference for the monotonic clock */
1704 clock_ref = clock_monotonic;
1707 return LIBUSB_ERROR_INVALID_PARAM;
1710 clock_get_time (clock_ref, &sys_time);
1712 tp->tv_sec = sys_time.tv_sec;
1713 tp->tv_nsec = sys_time.tv_nsec;
1718 const struct usbi_os_backend darwin_backend = {
1720 .init = darwin_init,
1721 .exit = darwin_exit,
1722 .get_device_list = darwin_get_device_list,
1723 .get_device_descriptor = darwin_get_device_descriptor,
1724 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1725 .get_config_descriptor = darwin_get_config_descriptor,
1727 .open = darwin_open,
1728 .close = darwin_close,
1729 .get_configuration = darwin_get_configuration,
1730 .set_configuration = darwin_set_configuration,
1731 .claim_interface = darwin_claim_interface,
1732 .release_interface = darwin_release_interface,
1734 .set_interface_altsetting = darwin_set_interface_altsetting,
1735 .clear_halt = darwin_clear_halt,
1736 .reset_device = darwin_reset_device,
1738 .kernel_driver_active = darwin_kernel_driver_active,
1739 .detach_kernel_driver = darwin_detach_kernel_driver,
1740 .attach_kernel_driver = darwin_attach_kernel_driver,
1742 .destroy_device = darwin_destroy_device,
1744 .submit_transfer = darwin_submit_transfer,
1745 .cancel_transfer = darwin_cancel_transfer,
1746 .clear_transfer_priv = darwin_clear_transfer_priv,
1748 .handle_events = op_handle_events,
1750 .clock_gettime = darwin_clock_gettime,
1752 .device_priv_size = sizeof(struct darwin_device_priv),
1753 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1754 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1755 .add_iso_packet_size = 0,