1 /* -*- Mode: C; indent-tabs-mode:nil -*- */
3 * darwin backend for libusbx 1.0
4 * Copyright © 2008-2013 Nathan Hjelm <hjelmn@users.sourceforge.net>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
28 #include <sys/types.h>
31 #include <libkern/OSAtomic.h>
33 #include <mach/clock.h>
34 #include <mach/clock_types.h>
35 #include <mach/mach_host.h>
36 #include <mach/mach_port.h>
38 #include <AvailabilityMacros.h>
39 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
40 #include <objc/objc-auto.h>
43 #include "darwin_usb.h"
45 /* async event thread */
46 static pthread_mutex_t libusb_darwin_at_mutex = PTHREAD_MUTEX_INITIALIZER;
47 static pthread_cond_t libusb_darwin_at_cond = PTHREAD_COND_INITIALIZER;
49 static clock_serv_t clock_realtime;
50 static clock_serv_t clock_monotonic;
52 static CFRunLoopRef libusb_darwin_acfl = NULL; /* event cf loop */
53 static volatile int32_t initCount = 0;
55 static usbi_mutex_t darwin_cached_devices_lock = PTHREAD_MUTEX_INITIALIZER;
56 static struct list_head darwin_cached_devices = {&darwin_cached_devices, &darwin_cached_devices};
58 #define DARWIN_CACHED_DEVICE(a) ((struct darwin_cached_device *) (((struct darwin_device_priv *)((a)->os_priv))->dev))
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 int darwin_scan_devices(struct libusb_context *ctx);
70 static int process_new_device (struct libusb_context *ctx, io_service_t service);
72 #if defined(ENABLE_LOGGING)
73 static const char *darwin_error_str (int result) {
75 case kIOReturnSuccess:
77 case kIOReturnNotOpen:
78 return "device not opened for exclusive access";
79 case kIOReturnNoDevice:
80 return "no connection to an IOService";
81 case kIOUSBNoAsyncPortErr:
82 return "no async port has been opened for interface";
83 case kIOReturnExclusiveAccess:
84 return "another process has device opened for exclusive access";
85 case kIOUSBPipeStalled:
86 return "pipe is stalled";
88 return "could not establish a connection to the Darwin kernel";
89 case kIOUSBTransactionTimeout:
90 return "transaction timed out";
91 case kIOReturnBadArgument:
92 return "invalid argument";
93 case kIOReturnAborted:
94 return "transaction aborted";
95 case kIOReturnNotResponding:
96 return "device not responding";
97 case kIOReturnOverrun:
98 return "data overrun";
99 case kIOReturnCannotWire:
100 return "physical memory can not be wired down";
101 case kIOReturnNoResources:
102 return "out of resources";
103 case kIOUSBHighSpeedSplitError:
104 return "high speed split error";
106 return "unknown error";
111 static int darwin_to_libusb (int result) {
113 case kIOReturnUnderrun:
114 case kIOReturnSuccess:
115 return LIBUSB_SUCCESS;
116 case kIOReturnNotOpen:
117 case kIOReturnNoDevice:
118 return LIBUSB_ERROR_NO_DEVICE;
119 case kIOReturnExclusiveAccess:
120 return LIBUSB_ERROR_ACCESS;
121 case kIOUSBPipeStalled:
122 return LIBUSB_ERROR_PIPE;
123 case kIOReturnBadArgument:
124 return LIBUSB_ERROR_INVALID_PARAM;
125 case kIOUSBTransactionTimeout:
126 return LIBUSB_ERROR_TIMEOUT;
127 case kIOReturnNotResponding:
128 case kIOReturnAborted:
130 case kIOUSBNoAsyncPortErr:
132 return LIBUSB_ERROR_OTHER;
136 /* this function must be called with the darwin_cached_devices_lock held */
137 static void darwin_deref_cached_device(struct darwin_cached_device *cached_dev) {
138 cached_dev->refcount--;
139 /* free the device and remove it from the cache */
140 if (0 == cached_dev->refcount) {
141 list_del(&cached_dev->list);
143 (*(cached_dev->device))->Release(cached_dev->device);
148 static void darwin_ref_cached_device(struct darwin_cached_device *cached_dev) {
149 cached_dev->refcount++;
152 static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp) {
153 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
155 /* current interface */
156 struct darwin_interface *cInterface;
160 usbi_dbg ("converting ep address 0x%02x to pipeRef and interface", ep);
162 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
163 cInterface = &priv->interfaces[iface];
165 if (dev_handle->claimed_interfaces & (1 << iface)) {
166 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
167 if (cInterface->endpoint_addrs[i] == ep) {
170 usbi_dbg ("pipe %d on interface %d matches", *pipep, *ifcp);
177 /* No pipe found with the correct endpoint address */
178 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
183 static int usb_setup_device_iterator (io_iterator_t *deviceIterator, UInt32 location) {
184 CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBDeviceClassName);
187 return kIOReturnError;
190 CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
191 &kCFTypeDictionaryKeyCallBacks,
192 &kCFTypeDictionaryValueCallBacks);
194 if (propertyMatchDict) {
195 /* there are no unsigned CFNumber types so treat the value as signed. the os seems to do this
196 internally (CFNumberType of locationID is 3) */
197 CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberSInt32Type, &location);
199 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
200 /* release our reference to the CFNumber (CFDictionarySetValue retains it) */
201 CFRelease (locationCF);
203 CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
204 /* release out reference to the CFMutableDictionaryRef (CFDictionarySetValue retains it) */
205 CFRelease (propertyMatchDict);
207 /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
210 return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator);
213 /* Returns 1 on success, 0 on failure. */
214 static int get_ioregistry_value_number (io_service_t service, CFStringRef property, CFNumberType type, void *p) {
215 CFTypeRef cfNumber = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
219 if (CFGetTypeID(cfNumber) == CFNumberGetTypeID()) {
220 ret = CFNumberGetValue(cfNumber, type, p);
223 CFRelease (cfNumber);
229 static usb_device_t **darwin_device_from_service (io_service_t service)
231 io_cf_plugin_ref_t *plugInInterface = NULL;
232 usb_device_t **device;
233 kern_return_t result;
236 result = IOCreatePlugInInterfaceForService(service, kIOUSBDeviceUserClientTypeID,
237 kIOCFPlugInInterfaceID, &plugInInterface,
240 if (kIOReturnSuccess != result || !plugInInterface) {
241 usbi_dbg ("could not set up plugin for service: %s\n", darwin_error_str (result));
245 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
247 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
248 (*plugInInterface)->Release (plugInInterface);
253 static void darwin_devices_attached (void *ptr, io_iterator_t add_devices) {
254 struct libusb_context *ctx;
255 io_service_t service;
257 usbi_mutex_lock(&active_contexts_lock);
259 while ((service = IOIteratorNext(add_devices))) {
260 /* add this device to each active context's device list */
261 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
262 process_new_device (ctx, service);;
265 IOObjectRelease(service);
268 usbi_mutex_unlock(&active_contexts_lock);
271 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
272 struct libusb_device *dev = NULL;
273 struct libusb_context *ctx;
279 while ((device = IOIteratorNext (rem_devices)) != 0) {
280 /* get the location from the i/o registry */
281 ret = get_ioregistry_value_number (device, CFSTR("sessionID"), kCFNumberSInt64Type, &session);
282 IOObjectRelease (device);
286 usbi_mutex_lock(&active_contexts_lock);
288 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
289 usbi_dbg ("notifying context %p of device disconnect", ctx);
291 dev = usbi_get_device_by_session_id(ctx, (unsigned long) session);
293 /* signal the core that this device has been disconnected. the core will tear down this device
294 when the reference count reaches 0 */
295 usbi_disconnect_device(dev);
296 usb_unref_device(dev);
300 usbi_mutex_unlock(&active_contexts_lock);
304 static void darwin_clear_iterator (io_iterator_t iter) {
307 while ((device = IOIteratorNext (iter)) != 0)
308 IOObjectRelease (device);
311 static void *darwin_event_thread_main (void *arg0) {
313 struct libusb_context *ctx = (struct libusb_context *)arg0;
314 CFRunLoopRef runloop;
316 /* Set this thread's name, so it can be seen in the debugger
317 and crash reports. */
318 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
319 pthread_setname_np ("org.libusb.device-hotplug");
321 /* Tell the Objective-C garbage collector about this thread.
322 This is required because, unlike NSThreads, pthreads are
323 not automatically registered. Although we don't use
324 Objective-C, we use CoreFoundation, which does. */
325 objc_registerThreadWithCollector();
328 /* hotplug (device arrival/removal) sources */
329 CFRunLoopSourceRef libusb_notification_cfsource;
330 io_notification_port_t libusb_notification_port;
331 io_iterator_t libusb_rem_device_iterator;
332 io_iterator_t libusb_add_device_iterator;
334 usbi_dbg ("creating hotplug event source");
336 runloop = CFRunLoopGetCurrent ();
339 /* add the notification port to the run loop */
340 libusb_notification_port = IONotificationPortCreate (kIOMasterPortDefault);
341 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
342 CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
344 /* create notifications for removed devices */
345 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
346 IOServiceMatching(kIOUSBDeviceClassName),
347 (IOServiceMatchingCallback)darwin_devices_detached,
348 (void *)ctx, &libusb_rem_device_iterator);
350 if (kresult != kIOReturnSuccess) {
351 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
356 /* create notifications for attached devices */
357 kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
358 IOServiceMatching(kIOUSBDeviceClassName),
359 (IOServiceMatchingCallback)darwin_devices_attached,
360 (void *)ctx, &libusb_add_device_iterator);
362 if (kresult != kIOReturnSuccess) {
363 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
369 darwin_clear_iterator (libusb_rem_device_iterator);
370 darwin_clear_iterator (libusb_add_device_iterator);
372 usbi_dbg ("darwin event thread ready to receive events");
374 /* signal the main thread that the hotplug runloop has been created. */
375 pthread_mutex_lock (&libusb_darwin_at_mutex);
376 libusb_darwin_acfl = runloop;
377 pthread_cond_signal (&libusb_darwin_at_cond);
378 pthread_mutex_unlock (&libusb_darwin_at_mutex);
380 /* run the runloop */
383 usbi_dbg ("darwin event thread exiting");
385 /* remove the notification cfsource */
386 CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
388 /* delete notification port */
389 IONotificationPortDestroy (libusb_notification_port);
391 /* delete iterators */
392 IOObjectRelease (libusb_rem_device_iterator);
393 IOObjectRelease (libusb_add_device_iterator);
397 libusb_darwin_acfl = NULL;
402 static void _darwin_finalize(void) {
403 struct darwin_cached_device *dev, *next;
405 usbi_mutex_lock(&darwin_cached_devices_lock);
406 list_for_each_entry_safe(dev, next, &darwin_cached_devices, list, struct darwin_cached_device) {
407 darwin_deref_cached_device(dev);
409 usbi_mutex_unlock(&darwin_cached_devices_lock);
412 static int darwin_init(struct libusb_context *ctx) {
413 host_name_port_t host_self;
414 static int initted = 0;
417 rc = darwin_scan_devices (ctx);
418 if (LIBUSB_SUCCESS != rc) {
422 if (OSAtomicIncrement32Barrier(&initCount) == 1) {
423 /* create the clocks that will be used */
427 atexit(_darwin_finalize);
430 host_self = mach_host_self();
431 host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
432 host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
433 mach_port_deallocate(mach_task_self(), host_self);
435 pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, (void *)ctx);
437 pthread_mutex_lock (&libusb_darwin_at_mutex);
438 while (!libusb_darwin_acfl)
439 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
440 pthread_mutex_unlock (&libusb_darwin_at_mutex);
446 static void darwin_exit (void) {
447 if (OSAtomicDecrement32Barrier(&initCount) == 0) {
448 mach_port_deallocate(mach_task_self(), clock_realtime);
449 mach_port_deallocate(mach_task_self(), clock_monotonic);
451 /* stop the event runloop and wait for the thread to terminate. */
452 CFRunLoopStop (libusb_darwin_acfl);
453 pthread_join (libusb_darwin_at, NULL);
457 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
458 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
460 /* return cached copy */
461 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
468 static int get_configuration_index (struct libusb_device *dev, int config_value) {
469 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
471 IOUSBConfigurationDescriptorPtr desc;
474 /* is there a simpler way to determine the index? */
475 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
476 if (kresult != kIOReturnSuccess)
477 return darwin_to_libusb (kresult);
479 for (i = 0 ; i < numConfig ; i++) {
480 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
482 if (desc->bConfigurationValue == config_value)
486 /* configuration not found */
487 return LIBUSB_ERROR_NOT_FOUND;
490 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
491 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
494 if (0 == priv->active_config)
495 return LIBUSB_ERROR_NOT_FOUND;
497 config_index = get_configuration_index (dev, priv->active_config);
498 if (config_index < 0)
501 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
504 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
505 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
506 IOUSBConfigurationDescriptorPtr desc;
510 if (!priv || !priv->device)
511 return LIBUSB_ERROR_OTHER;
513 kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
514 if (kresult == kIOReturnSuccess) {
515 /* copy descriptor */
516 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
517 len = libusb_le16_to_cpu(desc->wTotalLength);
519 memmove (buffer, desc, len);
521 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
525 ret = darwin_to_libusb (kresult);
526 if (ret != LIBUSB_SUCCESS)
532 /* check whether the os has configured the device */
533 static int darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) {
534 usb_device_t **darwin_device = dev->device;
536 IOUSBConfigurationDescriptorPtr configDesc;
537 IOUSBFindInterfaceRequest request;
538 kern_return_t kresult;
539 io_iterator_t interface_iterator;
540 io_service_t firstInterface;
542 if (dev->dev_descriptor.bNumConfigurations < 1) {
543 usbi_err (ctx, "device has no configurations");
544 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
547 /* find the first configuration */
548 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
549 dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
551 /* check if the device is already configured. there is probably a better way than iterating over the
552 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
553 might lock up on the device request) */
555 /* Setup the Interface Request */
556 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
557 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
558 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
559 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
561 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
563 return darwin_to_libusb (kresult);
566 firstInterface = IOIteratorNext(interface_iterator);
568 /* done with the interface iterator */
569 IOObjectRelease(interface_iterator);
571 if (firstInterface) {
572 IOObjectRelease (firstInterface);
574 /* device is configured */
575 if (dev->dev_descriptor.bNumConfigurations == 1)
576 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
577 dev->active_config = dev->first_config;
579 /* devices with more than one configuration should work with GetConfiguration */
580 (*darwin_device)->GetConfiguration (darwin_device, &dev->active_config);
583 dev->active_config = 0;
585 usbi_dbg ("active config: %u, first config: %u", dev->active_config, dev->first_config);
590 static int darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
591 IOUSBDevRequestTO req;
593 memset (buffer, 0, buffer_size);
595 /* Set up request for descriptor/ */
596 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
597 req.bRequest = kUSBRqGetDescriptor;
598 req.wValue = desc << 8;
599 req.wIndex = desc_index;
600 req.wLength = buffer_size;
602 req.noDataTimeout = 20;
603 req.completionTimeout = 100;
605 return (*device)->DeviceRequestTO (device, &req);
608 static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct darwin_cached_device *dev) {
609 usb_device_t **device = dev->device;
610 int retries = 1, delay = 30000;
611 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
615 UInt16 idProduct, idVendor;
617 dev->can_enumerate = 0;
619 (*device)->GetDeviceClass (device, &bDeviceClass);
620 (*device)->GetDeviceProduct (device, &idProduct);
621 (*device)->GetDeviceVendor (device, &idVendor);
623 /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
624 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
625 * to follow the spec as closely as possible, try opening the device */
626 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
629 /**** retrieve device descriptor ****/
630 ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &dev->dev_descriptor, sizeof(dev->dev_descriptor));
632 if (kIOReturnOverrun == ret && kUSBDeviceDesc == dev->dev_descriptor.bDescriptorType)
633 /* received an overrun error but we still received a device descriptor */
634 ret = kIOReturnSuccess;
636 if (kIOUSBVendorIDAppleComputer == idVendor) {
637 /* NTH: don't bother retrying or unsuspending Apple devices */
641 if (kIOReturnSuccess == ret && (0 == dev->dev_descriptor.bNumConfigurations ||
642 0 == dev->dev_descriptor.bcdUSB)) {
643 /* work around for incorrectly configured devices */
644 if (try_reconfigure && is_open) {
645 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
647 /* set the first configuration */
648 (*device)->SetConfiguration(device, 1);
650 /* don't try to reconfigure again */
654 ret = kIOUSBPipeStalled;
657 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
658 /* device may be suspended. unsuspend it and try again */
659 #if DeviceVersion >= 320
662 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
663 (void)(*device)->GetUSBDeviceInformation (device, &info);
665 /* note that the device was suspended */
666 if (info & (1 << kUSBInformationDeviceIsSuspendedBit) || 0 == info)
671 /* try to unsuspend the device */
672 ret2 = (*device)->USBDeviceSuspend (device, 0);
673 if (kIOReturnSuccess != ret2) {
674 /* prevent log spew from poorly behaving devices. this indicates the
675 os actually had trouble communicating with the device */
676 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
684 if (kIOReturnSuccess != ret) {
685 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
686 /* sleep for a little while before trying again */
689 } while (kIOReturnSuccess != ret && retries--);
692 /* resuspend the device */
693 (void)(*device)->USBDeviceSuspend (device, 1);
696 (void) (*device)->USBDeviceClose (device);
698 if (ret != kIOReturnSuccess) {
699 /* a debug message was already printed out for this error */
700 if (LIBUSB_CLASS_HUB == bDeviceClass)
701 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
702 idVendor, idProduct, darwin_error_str (ret), ret);
704 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
705 idVendor, idProduct, darwin_error_str (ret), ret);
706 return darwin_to_libusb (ret);
709 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
710 if (libusb_le16_to_cpu (dev->dev_descriptor.idProduct) != idProduct) {
711 /* not a valid device */
712 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
713 idProduct, libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
714 return LIBUSB_ERROR_NO_DEVICE;
717 usbi_dbg ("cached device descriptor:");
718 usbi_dbg (" bDescriptorType: 0x%02x", dev->dev_descriptor.bDescriptorType);
719 usbi_dbg (" bcdUSB: 0x%04x", dev->dev_descriptor.bcdUSB);
720 usbi_dbg (" bDeviceClass: 0x%02x", dev->dev_descriptor.bDeviceClass);
721 usbi_dbg (" bDeviceSubClass: 0x%02x", dev->dev_descriptor.bDeviceSubClass);
722 usbi_dbg (" bDeviceProtocol: 0x%02x", dev->dev_descriptor.bDeviceProtocol);
723 usbi_dbg (" bMaxPacketSize0: 0x%02x", dev->dev_descriptor.bMaxPacketSize0);
724 usbi_dbg (" idVendor: 0x%04x", dev->dev_descriptor.idVendor);
725 usbi_dbg (" idProduct: 0x%04x", dev->dev_descriptor.idProduct);
726 usbi_dbg (" bcdDevice: 0x%04x", dev->dev_descriptor.bcdDevice);
727 usbi_dbg (" iManufacturer: 0x%02x", dev->dev_descriptor.iManufacturer);
728 usbi_dbg (" iProduct: 0x%02x", dev->dev_descriptor.iProduct);
729 usbi_dbg (" iSerialNumber: 0x%02x", dev->dev_descriptor.iSerialNumber);
730 usbi_dbg (" bNumConfigurations: 0x%02x", dev->dev_descriptor.bNumConfigurations);
732 dev->can_enumerate = 1;
734 return LIBUSB_SUCCESS;
737 static int darwin_get_cached_device(struct libusb_context *ctx, io_service_t service,
738 struct darwin_cached_device **cached_out) {
739 struct darwin_cached_device *new_device;
740 UInt64 sessionID = 0, parent_sessionID = 0;
741 int ret = LIBUSB_SUCCESS;
742 usb_device_t **device;
744 kern_return_t result;
747 /* get some info from the io registry */
748 (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
749 (void) get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, &port);
751 usbi_dbg("finding cached device for sessionID 0x\n" PRIx64, sessionID);
753 result = IORegistryEntryGetParentEntry (service, kIOUSBPlane, &parent);
755 if (kIOReturnSuccess == result) {
756 (void) get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, &parent_sessionID);
757 IOObjectRelease(parent);
760 usbi_mutex_lock(&darwin_cached_devices_lock);
764 list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) {
765 usbi_dbg("matching sessionID 0x%x against cached device with sessionID 0x%x", sessionID, new_device->session);
766 if (new_device->session == sessionID) {
767 usbi_dbg("using cached device for device");
768 *cached_out = new_device;
776 usbi_dbg("caching new device with sessionID 0x%x\n", sessionID);
778 device = darwin_device_from_service (service);
780 ret = LIBUSB_ERROR_NO_DEVICE;
784 new_device = calloc (1, sizeof (*new_device));
786 ret = LIBUSB_ERROR_NO_MEM;
790 /* add this device to the cached device list */
791 list_add(&new_device->list, &darwin_cached_devices);
793 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
795 /* keep a reference to this device */
796 darwin_ref_cached_device(new_device);
798 new_device->device = device;
799 new_device->session = sessionID;
800 (*device)->GetLocationID (device, &new_device->location);
801 new_device->port = port;
802 new_device->parent_session = parent_sessionID;
804 /* cache the device descriptor */
805 ret = darwin_cache_device_descriptor(ctx, new_device);
809 if (new_device->can_enumerate) {
810 snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address,
811 new_device->dev_descriptor.idVendor, new_device->dev_descriptor.idProduct,
812 new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass);
816 usbi_mutex_unlock(&darwin_cached_devices_lock);
818 /* keep track of devices regardless of if we successfully enumerate them to
819 prevent them from being enumerated multiple times */
821 *cached_out = new_device;
826 static int process_new_device (struct libusb_context *ctx, io_service_t service) {
827 struct darwin_device_priv *priv;
828 struct libusb_device *dev = NULL;
829 struct darwin_cached_device *cached_device;
834 ret = darwin_get_cached_device (ctx, service, &cached_device);
836 if (ret < 0 || !cached_device->can_enumerate) {
840 /* check current active configuration (and cache the first configuration value--
841 which may be used by claim_interface) */
842 ret = darwin_check_configuration (ctx, cached_device);
846 usbi_dbg ("allocating new device in context %p for with session 0x%08x",
847 ctx, cached_device->session);
849 dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
851 return LIBUSB_ERROR_NO_MEM;
854 priv = (struct darwin_device_priv *)dev->os_priv;
856 priv->dev = cached_device;
857 darwin_ref_cached_device (priv->dev);
859 if (cached_device->parent_session > 0) {
860 dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session);
862 dev->parent_dev = NULL;
864 dev->port_number = cached_device->port;
865 dev->bus_number = cached_device->location >> 24;
866 dev->device_address = cached_device->address;
868 (*(priv->dev->device))->GetDeviceSpeed (priv->dev->device, &devSpeed);
871 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
872 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
873 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
874 #if DeviceVersion >= 500
875 case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
878 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
881 ret = usbi_sanitize_device (dev);
885 usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
886 dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
890 usbi_connect_device (dev);
892 libusb_unref_device (dev);
898 static int darwin_scan_devices(struct libusb_context *ctx) {
899 io_iterator_t deviceIterator;
900 io_service_t service;
901 kern_return_t kresult;
903 kresult = usb_setup_device_iterator (&deviceIterator, 0);
904 if (kresult != kIOReturnSuccess)
905 return darwin_to_libusb (kresult);
907 while ((service = IOIteratorNext (deviceIterator))) {
908 (void) process_new_device (ctx, service);
910 IOObjectRelease(service);
913 IOObjectRelease(deviceIterator);
918 static int darwin_open (struct libusb_device_handle *dev_handle) {
919 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
920 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
923 if (0 == dpriv->open_count) {
924 /* try to open the device */
925 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
926 if (kresult != kIOReturnSuccess) {
927 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
929 if (kIOReturnExclusiveAccess != kresult) {
930 return darwin_to_libusb (kresult);
933 /* it is possible to perform some actions on a device that is not open so do not return an error */
939 /* create async event source */
940 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
941 if (kresult != kIOReturnSuccess) {
942 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
945 (*(dpriv->device))->USBDeviceClose (dpriv->device);
950 return darwin_to_libusb (kresult);
953 CFRetain (libusb_darwin_acfl);
955 /* add the cfSource to the aync run loop */
956 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
959 /* device opened successfully */
962 /* create a file descriptor for notifications */
965 /* set the pipe to be non-blocking */
966 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
968 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
970 usbi_dbg ("device open for access");
975 static void darwin_close (struct libusb_device_handle *dev_handle) {
976 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
977 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
981 if (dpriv->open_count == 0) {
982 /* something is probably very wrong if this is the case */
983 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
989 /* make sure all interfaces are released */
990 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
991 if (dev_handle->claimed_interfaces & (1 << i))
992 libusb_release_interface (dev_handle, i);
994 if (0 == dpriv->open_count) {
995 /* delete the device's async event source */
996 if (priv->cfSource) {
997 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
998 CFRelease (priv->cfSource);
999 priv->cfSource = NULL;
1000 CFRelease (libusb_darwin_acfl);
1003 if (priv->is_open) {
1004 /* close the device */
1005 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
1007 /* Log the fact that we had a problem closing the file, however failing a
1008 * close isn't really an error, so return success anyway */
1009 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
1014 /* file descriptors are maintained per-instance */
1015 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
1016 close (priv->fds[1]);
1017 close (priv->fds[0]);
1019 priv->fds[0] = priv->fds[1] = -1;
1022 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
1023 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1025 *config = (int) dpriv->active_config;
1030 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
1031 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1035 /* Setting configuration will invalidate the interface, so we need
1036 to reclaim it. First, dispose of existing interfaces, if any. */
1037 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1038 if (dev_handle->claimed_interfaces & (1 << i))
1039 darwin_release_interface (dev_handle, i);
1041 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
1042 if (kresult != kIOReturnSuccess)
1043 return darwin_to_libusb (kresult);
1045 /* Reclaim any interfaces. */
1046 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1047 if (dev_handle->claimed_interfaces & (1 << i))
1048 darwin_claim_interface (dev_handle, i);
1050 dpriv->active_config = config;
1055 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
1056 IOUSBFindInterfaceRequest request;
1057 kern_return_t kresult;
1058 io_iterator_t interface_iterator;
1059 UInt8 bInterfaceNumber;
1062 *usbInterfacep = IO_OBJECT_NULL;
1064 /* Setup the Interface Request */
1065 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1066 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1067 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1068 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1070 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1074 while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1075 /* find the interface number */
1076 ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
1079 if (ret && bInterfaceNumber == ifc) {
1083 (void) IOObjectRelease (*usbInterfacep);
1086 /* done with the interface iterator */
1087 IOObjectRelease(interface_iterator);
1092 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
1093 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1095 /* current interface */
1096 struct darwin_interface *cInterface = &priv->interfaces[iface];
1098 kern_return_t kresult;
1100 u_int8_t numep, direction, number;
1101 u_int8_t dont_care1, dont_care3;
1102 u_int16_t dont_care2;
1105 usbi_dbg ("building table of endpoints.");
1107 /* retrieve the total number of endpoints on this interface */
1108 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1110 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1111 return darwin_to_libusb (kresult);
1114 /* iterate through pipe references */
1115 for (i = 1 ; i <= numep ; i++) {
1116 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1117 &dont_care2, &dont_care3);
1119 if (kresult != kIOReturnSuccess) {
1120 usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
1122 return darwin_to_libusb (kresult);
1125 usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
1127 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1130 cInterface->num_endpoints = numep;
1135 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1136 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1137 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1138 io_service_t usbInterface = IO_OBJECT_NULL;
1140 IOCFPlugInInterface **plugInInterface = NULL;
1143 /* current interface */
1144 struct darwin_interface *cInterface = &priv->interfaces[iface];
1146 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1147 if (kresult != kIOReturnSuccess)
1148 return darwin_to_libusb (kresult);
1150 /* make sure we have an interface */
1151 if (!usbInterface && dpriv->first_config != 0) {
1152 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1154 /* set the configuration */
1155 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1156 if (kresult != LIBUSB_SUCCESS) {
1157 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1161 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1163 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1164 return darwin_to_libusb (kresult);
1168 if (!usbInterface) {
1169 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1170 return LIBUSB_ERROR_NOT_FOUND;
1173 /* get an interface to the device's interface */
1174 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1175 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1177 /* ignore release error */
1178 (void)IOObjectRelease (usbInterface);
1181 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1182 return darwin_to_libusb (kresult);
1185 if (!plugInInterface) {
1186 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1187 return LIBUSB_ERROR_NOT_FOUND;
1190 /* Do the actual claim */
1191 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1192 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1193 (LPVOID)&cInterface->interface);
1194 /* We no longer need the intermediate plug-in */
1195 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1196 (*plugInInterface)->Release (plugInInterface);
1197 if (kresult || !cInterface->interface) {
1198 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1199 return darwin_to_libusb (kresult);
1202 /* claim the interface */
1203 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1205 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1206 return darwin_to_libusb (kresult);
1209 /* update list of endpoints */
1210 kresult = get_endpoints (dev_handle, iface);
1212 /* this should not happen */
1213 darwin_release_interface (dev_handle, iface);
1214 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1218 cInterface->cfSource = NULL;
1220 /* create async event source */
1221 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1222 if (kresult != kIOReturnSuccess) {
1223 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1225 /* can't continue without an async event source */
1226 (void)darwin_release_interface (dev_handle, iface);
1228 return darwin_to_libusb (kresult);
1231 /* add the cfSource to the async thread's run loop */
1232 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1234 usbi_dbg ("interface opened");
1239 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1240 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1243 /* current interface */
1244 struct darwin_interface *cInterface = &priv->interfaces[iface];
1246 /* Check to see if an interface is open */
1247 if (!cInterface->interface)
1248 return LIBUSB_SUCCESS;
1250 /* clean up endpoint data */
1251 cInterface->num_endpoints = 0;
1253 /* delete the interface's async event source */
1254 if (cInterface->cfSource) {
1255 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1256 CFRelease (cInterface->cfSource);
1259 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1261 usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1263 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1264 if (kresult != kIOReturnSuccess)
1265 usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1267 cInterface->interface = IO_OBJECT_NULL;
1269 return darwin_to_libusb (kresult);
1272 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1273 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1276 /* current interface */
1277 struct darwin_interface *cInterface = &priv->interfaces[iface];
1279 if (!cInterface->interface)
1280 return LIBUSB_ERROR_NO_DEVICE;
1282 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1283 if (kresult != kIOReturnSuccess)
1284 darwin_reset_device (dev_handle);
1286 /* update list of endpoints */
1287 kresult = get_endpoints (dev_handle, iface);
1289 /* this should not happen */
1290 darwin_release_interface (dev_handle, iface);
1291 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1295 return darwin_to_libusb (kresult);
1298 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1299 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1301 /* current interface */
1302 struct darwin_interface *cInterface;
1303 uint8_t pipeRef, iface;
1306 /* determine the interface/endpoint to use */
1307 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
1308 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1310 return LIBUSB_ERROR_NOT_FOUND;
1313 cInterface = &priv->interfaces[iface];
1315 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1316 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1318 usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1320 return darwin_to_libusb (kresult);
1323 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1324 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1325 IOUSBDeviceDescriptor descriptor;
1326 IOUSBConfigurationDescriptorPtr cached_configuration;
1327 IOUSBConfigurationDescriptor configuration;
1328 bool reenumerate = false;
1332 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1334 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1335 return darwin_to_libusb (kresult);
1339 usbi_dbg ("darwin/reset_device: checking if device descriptor changed");
1341 /* ignore return code. if we can't get a descriptor it might be worthwhile re-enumerating anway */
1342 (void) darwin_request_descriptor (dpriv->device, kUSBDeviceDesc, 0, &descriptor, sizeof (descriptor));
1344 /* check if the device descriptor has changed */
1345 if (0 != memcmp (&dpriv->dev_descriptor, &descriptor, sizeof (descriptor))) {
1350 /* check if any configuration descriptor has changed */
1351 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1352 usbi_dbg ("darwin/reset_device: checking if configuration descriptor %d changed", i);
1354 (void) darwin_request_descriptor (dpriv->device, kUSBConfDesc, i, &configuration, sizeof (configuration));
1355 (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1357 if (!cached_configuration || 0 != memcmp (cached_configuration, &configuration, sizeof (configuration))) {
1365 usbi_dbg ("darwin/reset_device: device requires reenumeration");
1366 (void) (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
1367 return LIBUSB_ERROR_NOT_FOUND;
1370 usbi_dbg ("darwin/reset_device: device reset complete");
1372 return LIBUSB_SUCCESS;
1375 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1376 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1377 io_service_t usbInterface;
1381 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1383 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1385 return darwin_to_libusb (kresult);
1388 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1389 IOObjectRelease (usbInterface);
1401 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1402 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1405 return LIBUSB_ERROR_NOT_SUPPORTED;
1408 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1411 return LIBUSB_ERROR_NOT_SUPPORTED;
1414 static void darwin_destroy_device(struct libusb_device *dev) {
1415 struct darwin_device_priv *dpriv = (struct darwin_device_priv *) dev->os_priv;
1418 /* need to hold the lock in case this is the last reference to the device */
1419 usbi_mutex_lock(&darwin_cached_devices_lock);
1420 darwin_deref_cached_device (dpriv->dev);
1422 usbi_mutex_unlock(&darwin_cached_devices_lock);
1426 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1427 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1428 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1431 uint8_t transferType;
1432 /* None of the values below are used in libusbx for bulk transfers */
1433 uint8_t direction, number, interval, pipeRef, iface;
1434 uint16_t maxPacketSize;
1436 struct darwin_interface *cInterface;
1438 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1439 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1441 return LIBUSB_ERROR_NOT_FOUND;
1444 cInterface = &priv->interfaces[iface];
1446 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1447 &transferType, &maxPacketSize, &interval);
1449 if (0 != (transfer->length % maxPacketSize)) {
1450 /* do not need a zero packet */
1451 transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1454 /* submit the request */
1455 /* timeouts are unavailable on interrupt endpoints */
1456 if (transferType == kUSBInterrupt) {
1457 if (IS_XFERIN(transfer))
1458 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1459 transfer->length, darwin_async_io_callback, itransfer);
1461 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1462 transfer->length, darwin_async_io_callback, itransfer);
1464 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1466 if (IS_XFERIN(transfer))
1467 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1468 transfer->length, transfer->timeout, transfer->timeout,
1469 darwin_async_io_callback, (void *)itransfer);
1471 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1472 transfer->length, transfer->timeout, transfer->timeout,
1473 darwin_async_io_callback, (void *)itransfer);
1477 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1478 darwin_error_str(ret), ret);
1480 return darwin_to_libusb (ret);
1483 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1484 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1485 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1486 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1489 uint8_t direction, number, interval, pipeRef, iface, transferType;
1490 uint16_t maxPacketSize;
1492 AbsoluteTime atTime;
1495 struct darwin_interface *cInterface;
1497 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1498 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1499 free(tpriv->isoc_framelist);
1500 tpriv->isoc_framelist = NULL;
1503 if (!tpriv->isoc_framelist) {
1504 tpriv->num_iso_packets = transfer->num_iso_packets;
1505 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1506 if (!tpriv->isoc_framelist)
1507 return LIBUSB_ERROR_NO_MEM;
1510 /* copy the frame list from the libusbx descriptor (the structures differ only is member order) */
1511 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1512 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1514 /* determine the interface/endpoint to use */
1515 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1516 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1518 return LIBUSB_ERROR_NOT_FOUND;
1521 cInterface = &priv->interfaces[iface];
1523 /* determine the properties of this endpoint and the speed of the device */
1524 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1525 &transferType, &maxPacketSize, &interval);
1527 /* Last but not least we need the bus frame number */
1528 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1530 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1531 free(tpriv->isoc_framelist);
1532 tpriv->isoc_framelist = NULL;
1534 return darwin_to_libusb (kresult);
1537 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1538 &transferType, &maxPacketSize, &interval);
1540 /* schedule for a frame a little in the future */
1543 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1544 frame = cInterface->frames[transfer->endpoint];
1546 /* submit the request */
1547 if (IS_XFERIN(transfer))
1548 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1549 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1552 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1553 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1556 if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
1558 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1));
1560 /* High/super speed */
1561 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1)) / 8;
1563 if (kresult != kIOReturnSuccess) {
1564 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1565 darwin_error_str(kresult));
1566 free (tpriv->isoc_framelist);
1567 tpriv->isoc_framelist = NULL;
1570 return darwin_to_libusb (kresult);
1573 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1574 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1575 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1576 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1577 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1578 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1582 bzero(&tpriv->req, sizeof(tpriv->req));
1584 /* IOUSBDeviceInterface expects the request in cpu endianess */
1585 tpriv->req.bmRequestType = setup->bmRequestType;
1586 tpriv->req.bRequest = setup->bRequest;
1587 /* these values should be in bus order from libusb_fill_control_setup */
1588 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1589 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1590 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1591 /* data is stored after the libusbx control block */
1592 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1593 tpriv->req.completionTimeout = transfer->timeout;
1594 tpriv->req.noDataTimeout = transfer->timeout;
1596 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1598 /* all transfers in libusb-1.0 are async */
1600 if (transfer->endpoint) {
1601 struct darwin_interface *cInterface;
1602 uint8_t pipeRef, iface;
1604 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1605 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1607 return LIBUSB_ERROR_NOT_FOUND;
1610 cInterface = &priv->interfaces[iface];
1612 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1614 /* control request on endpoint 0 */
1615 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1617 if (kresult != kIOReturnSuccess)
1618 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1620 return darwin_to_libusb (kresult);
1623 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1624 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1626 switch (transfer->type) {
1627 case LIBUSB_TRANSFER_TYPE_CONTROL:
1628 return submit_control_transfer(itransfer);
1629 case LIBUSB_TRANSFER_TYPE_BULK:
1630 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1631 return submit_bulk_transfer(itransfer);
1632 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1633 return submit_iso_transfer(itransfer);
1635 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1636 return LIBUSB_ERROR_INVALID_PARAM;
1640 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1641 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1642 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1645 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
1648 return LIBUSB_ERROR_NO_DEVICE;
1650 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1652 return darwin_to_libusb (kresult);
1655 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1656 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1657 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1658 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1659 struct darwin_interface *cInterface;
1660 uint8_t pipeRef, iface;
1663 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1664 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1666 return LIBUSB_ERROR_NOT_FOUND;
1669 cInterface = &priv->interfaces[iface];
1672 return LIBUSB_ERROR_NO_DEVICE;
1674 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
1676 /* abort transactions */
1677 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1679 usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
1681 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1682 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1684 return darwin_to_libusb (kresult);
1687 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1688 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1690 switch (transfer->type) {
1691 case LIBUSB_TRANSFER_TYPE_CONTROL:
1692 return cancel_control_transfer(itransfer);
1693 case LIBUSB_TRANSFER_TYPE_BULK:
1694 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1695 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1696 return darwin_abort_transfers (itransfer);
1698 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1699 return LIBUSB_ERROR_INVALID_PARAM;
1703 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1704 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1705 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1707 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1708 free (tpriv->isoc_framelist);
1709 tpriv->isoc_framelist = NULL;
1713 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1714 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1715 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1716 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1717 struct darwin_msg_async_io_complete message = {.itransfer = itransfer, .result = result,
1718 .size = (UInt32) (uintptr_t) arg0};
1720 usbi_dbg ("an async io operation has completed");
1722 /* if requested write a zero packet */
1723 if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
1724 struct darwin_interface *cInterface;
1725 uint8_t iface, pipeRef;
1727 (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface);
1728 cInterface = &priv->interfaces[iface];
1730 (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
1733 /* send a completion message to the device's file descriptor */
1734 write (priv->fds[1], &message, sizeof (message));
1737 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1738 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT)
1739 result = kIOUSBTransactionTimeout;
1742 case kIOReturnUnderrun:
1743 case kIOReturnSuccess:
1744 return LIBUSB_TRANSFER_COMPLETED;
1745 case kIOReturnAborted:
1746 return LIBUSB_TRANSFER_CANCELLED;
1747 case kIOUSBPipeStalled:
1748 usbi_dbg ("transfer error: pipe is stalled");
1749 return LIBUSB_TRANSFER_STALL;
1750 case kIOReturnOverrun:
1751 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1752 return LIBUSB_TRANSFER_OVERFLOW;
1753 case kIOUSBTransactionTimeout:
1754 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1755 itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
1756 return LIBUSB_TRANSFER_TIMED_OUT;
1758 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1759 return LIBUSB_TRANSFER_ERROR;
1763 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1764 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1765 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1766 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1767 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1768 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1769 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1772 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1773 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1777 usbi_dbg ("handling %s completion with kernel status %d",
1778 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
1780 if (kIOReturnSuccess == result || kIOReturnUnderrun == result) {
1781 if (isIsoc && tpriv->isoc_framelist) {
1782 /* copy isochronous results back */
1784 for (i = 0; i < transfer->num_iso_packets ; i++) {
1785 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1786 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1787 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1790 itransfer->transferred += io_size;
1793 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1794 usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
1797 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready) {
1798 struct darwin_msg_async_io_complete message;
1799 POLL_NFDS_TYPE i = 0;
1802 usbi_mutex_lock(&ctx->open_devs_lock);
1804 for (i = 0; i < nfds && num_ready > 0; i++) {
1805 struct pollfd *pollfd = &fds[i];
1807 usbi_dbg ("checking fd %i with revents = %x", pollfd->fd, pollfd->revents);
1809 if (!pollfd->revents)
1814 if (pollfd->revents & POLLERR) {
1815 /* this probably will never happen so ignore the error an move on. */
1819 /* there is only one type of message */
1820 ret = read (pollfd->fd, &message, sizeof (message));
1821 if (ret < (ssize_t) sizeof (message)) {
1822 usbi_dbg ("WARNING: short read on async io completion pipe\n");
1826 darwin_handle_callback (message.itransfer, message.result, message.size);
1829 usbi_mutex_unlock(&ctx->open_devs_lock);
1834 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1835 mach_timespec_t sys_time;
1836 clock_serv_t clock_ref;
1839 case USBI_CLOCK_REALTIME:
1840 /* CLOCK_REALTIME represents time since the epoch */
1841 clock_ref = clock_realtime;
1843 case USBI_CLOCK_MONOTONIC:
1844 /* use system boot time as reference for the monotonic clock */
1845 clock_ref = clock_monotonic;
1848 return LIBUSB_ERROR_INVALID_PARAM;
1851 clock_get_time (clock_ref, &sys_time);
1853 tp->tv_sec = sys_time.tv_sec;
1854 tp->tv_nsec = sys_time.tv_nsec;
1859 const struct usbi_os_backend darwin_backend = {
1862 .init = darwin_init,
1863 .exit = darwin_exit,
1864 .get_device_list = NULL, /* not needed */
1865 .get_device_descriptor = darwin_get_device_descriptor,
1866 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1867 .get_config_descriptor = darwin_get_config_descriptor,
1869 .open = darwin_open,
1870 .close = darwin_close,
1871 .get_configuration = darwin_get_configuration,
1872 .set_configuration = darwin_set_configuration,
1873 .claim_interface = darwin_claim_interface,
1874 .release_interface = darwin_release_interface,
1876 .set_interface_altsetting = darwin_set_interface_altsetting,
1877 .clear_halt = darwin_clear_halt,
1878 .reset_device = darwin_reset_device,
1880 .kernel_driver_active = darwin_kernel_driver_active,
1881 .detach_kernel_driver = darwin_detach_kernel_driver,
1882 .attach_kernel_driver = darwin_attach_kernel_driver,
1884 .destroy_device = darwin_destroy_device,
1886 .submit_transfer = darwin_submit_transfer,
1887 .cancel_transfer = darwin_cancel_transfer,
1888 .clear_transfer_priv = darwin_clear_transfer_priv,
1890 .handle_events = op_handle_events,
1892 .clock_gettime = darwin_clock_gettime,
1894 .device_priv_size = sizeof(struct darwin_device_priv),
1895 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1896 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1897 .add_iso_packet_size = 0,