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);
299 usbi_mutex_unlock(&active_contexts_lock);
303 static void darwin_clear_iterator (io_iterator_t iter) {
306 while ((device = IOIteratorNext (iter)) != 0)
307 IOObjectRelease (device);
310 static void *darwin_event_thread_main (void *arg0) {
312 struct libusb_context *ctx = (struct libusb_context *)arg0;
313 CFRunLoopRef runloop;
315 /* Set this thread's name, so it can be seen in the debugger
316 and crash reports. */
317 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
318 pthread_setname_np ("org.libusb.device-hotplug");
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 objc_registerThreadWithCollector();
327 /* hotplug (device arrival/removal) sources */
328 CFRunLoopSourceRef libusb_notification_cfsource;
329 io_notification_port_t libusb_notification_port;
330 io_iterator_t libusb_rem_device_iterator;
331 io_iterator_t libusb_add_device_iterator;
333 usbi_dbg ("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(runloop, 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));
355 /* create notifications for attached devices */
356 kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
357 IOServiceMatching(kIOUSBDeviceClassName),
358 (IOServiceMatchingCallback)darwin_devices_attached,
359 (void *)ctx, &libusb_add_device_iterator);
361 if (kresult != kIOReturnSuccess) {
362 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
368 darwin_clear_iterator (libusb_rem_device_iterator);
369 darwin_clear_iterator (libusb_add_device_iterator);
371 usbi_dbg ("darwin event thread ready to receive events");
373 /* signal the main thread that the hotplug runloop has been created. */
374 pthread_mutex_lock (&libusb_darwin_at_mutex);
375 libusb_darwin_acfl = runloop;
376 pthread_cond_signal (&libusb_darwin_at_cond);
377 pthread_mutex_unlock (&libusb_darwin_at_mutex);
379 /* run the runloop */
382 usbi_dbg ("darwin event thread exiting");
384 /* remove the notification cfsource */
385 CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
387 /* delete notification port */
388 IONotificationPortDestroy (libusb_notification_port);
390 /* delete iterators */
391 IOObjectRelease (libusb_rem_device_iterator);
392 IOObjectRelease (libusb_add_device_iterator);
396 libusb_darwin_acfl = NULL;
401 static void _darwin_finalize(void) {
402 struct darwin_cached_device *dev, *next;
404 usbi_mutex_lock(&darwin_cached_devices_lock);
405 list_for_each_entry_safe(dev, next, &darwin_cached_devices, list, struct darwin_cached_device) {
406 darwin_deref_cached_device(dev);
408 usbi_mutex_unlock(&darwin_cached_devices_lock);
411 static int darwin_init(struct libusb_context *ctx) {
412 host_name_port_t host_self;
413 static int initted = 0;
416 rc = darwin_scan_devices (ctx);
417 if (LIBUSB_SUCCESS != rc) {
421 if (OSAtomicIncrement32Barrier(&initCount) == 1) {
422 /* create the clocks that will be used */
426 atexit(_darwin_finalize);
429 host_self = mach_host_self();
430 host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
431 host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
432 mach_port_deallocate(mach_task_self(), host_self);
434 pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, (void *)ctx);
436 pthread_mutex_lock (&libusb_darwin_at_mutex);
437 while (!libusb_darwin_acfl)
438 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
439 pthread_mutex_unlock (&libusb_darwin_at_mutex);
445 static void darwin_exit (void) {
446 if (OSAtomicDecrement32Barrier(&initCount) == 0) {
447 mach_port_deallocate(mach_task_self(), clock_realtime);
448 mach_port_deallocate(mach_task_self(), clock_monotonic);
450 /* stop the event runloop and wait for the thread to terminate. */
451 CFRunLoopStop (libusb_darwin_acfl);
452 pthread_join (libusb_darwin_at, NULL);
456 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
457 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
459 /* return cached copy */
460 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
467 static int get_configuration_index (struct libusb_device *dev, int config_value) {
468 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
470 IOUSBConfigurationDescriptorPtr desc;
473 /* is there a simpler way to determine the index? */
474 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
475 if (kresult != kIOReturnSuccess)
476 return darwin_to_libusb (kresult);
478 for (i = 0 ; i < numConfig ; i++) {
479 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
481 if (desc->bConfigurationValue == config_value)
485 /* configuration not found */
486 return LIBUSB_ERROR_NOT_FOUND;
489 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
490 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
493 if (0 == priv->active_config)
494 return LIBUSB_ERROR_NOT_FOUND;
496 config_index = get_configuration_index (dev, priv->active_config);
497 if (config_index < 0)
500 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
503 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
504 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
505 IOUSBConfigurationDescriptorPtr desc;
509 if (!priv || !priv->device)
510 return LIBUSB_ERROR_OTHER;
512 kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
513 if (kresult == kIOReturnSuccess) {
514 /* copy descriptor */
515 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
516 len = libusb_le16_to_cpu(desc->wTotalLength);
518 memmove (buffer, desc, len);
520 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
524 ret = darwin_to_libusb (kresult);
525 if (ret != LIBUSB_SUCCESS)
531 /* check whether the os has configured the device */
532 static int darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) {
533 usb_device_t **darwin_device = dev->device;
535 IOUSBConfigurationDescriptorPtr configDesc;
536 IOUSBFindInterfaceRequest request;
537 kern_return_t kresult;
538 io_iterator_t interface_iterator;
539 io_service_t firstInterface;
541 if (dev->dev_descriptor.bNumConfigurations < 1) {
542 usbi_err (ctx, "device has no configurations");
543 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
546 /* find the first configuration */
547 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
548 dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
550 /* check if the device is already configured. there is probably a better way than iterating over the
551 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
552 might lock up on the device request) */
554 /* Setup the Interface Request */
555 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
556 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
557 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
558 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
560 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
562 return darwin_to_libusb (kresult);
565 firstInterface = IOIteratorNext(interface_iterator);
567 /* done with the interface iterator */
568 IOObjectRelease(interface_iterator);
570 if (firstInterface) {
571 IOObjectRelease (firstInterface);
573 /* device is configured */
574 if (dev->dev_descriptor.bNumConfigurations == 1)
575 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
576 dev->active_config = dev->first_config;
578 /* devices with more than one configuration should work with GetConfiguration */
579 (*darwin_device)->GetConfiguration (darwin_device, &dev->active_config);
582 dev->active_config = 0;
584 usbi_dbg ("active config: %u, first config: %u", dev->active_config, dev->first_config);
589 static int darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
590 IOUSBDevRequestTO req;
592 memset (buffer, 0, buffer_size);
594 /* Set up request for descriptor/ */
595 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
596 req.bRequest = kUSBRqGetDescriptor;
597 req.wValue = desc << 8;
598 req.wIndex = desc_index;
599 req.wLength = buffer_size;
601 req.noDataTimeout = 20;
602 req.completionTimeout = 100;
604 return (*device)->DeviceRequestTO (device, &req);
607 static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct darwin_cached_device *dev) {
608 usb_device_t **device = dev->device;
609 int retries = 1, delay = 30000;
610 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
614 UInt16 idProduct, idVendor;
616 dev->can_enumerate = 0;
618 (*device)->GetDeviceClass (device, &bDeviceClass);
619 (*device)->GetDeviceProduct (device, &idProduct);
620 (*device)->GetDeviceVendor (device, &idVendor);
622 /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
623 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
624 * to follow the spec as closely as possible, try opening the device */
625 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
628 /**** retrieve device descriptor ****/
629 ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &dev->dev_descriptor, sizeof(dev->dev_descriptor));
631 if (kIOReturnOverrun == ret && kUSBDeviceDesc == dev->dev_descriptor.bDescriptorType)
632 /* received an overrun error but we still received a device descriptor */
633 ret = kIOReturnSuccess;
635 if (kIOUSBVendorIDAppleComputer == idVendor) {
636 /* NTH: don't bother retrying or unsuspending Apple devices */
640 if (kIOReturnSuccess == ret && (0 == dev->dev_descriptor.bNumConfigurations ||
641 0 == dev->dev_descriptor.bcdUSB)) {
642 /* work around for incorrectly configured devices */
643 if (try_reconfigure && is_open) {
644 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
646 /* set the first configuration */
647 (*device)->SetConfiguration(device, 1);
649 /* don't try to reconfigure again */
653 ret = kIOUSBPipeStalled;
656 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
657 /* device may be suspended. unsuspend it and try again */
658 #if DeviceVersion >= 320
661 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
662 (void)(*device)->GetUSBDeviceInformation (device, &info);
664 /* note that the device was suspended */
665 if (info & (1 << kUSBInformationDeviceIsSuspendedBit) || 0 == info)
670 /* try to unsuspend the device */
671 ret2 = (*device)->USBDeviceSuspend (device, 0);
672 if (kIOReturnSuccess != ret2) {
673 /* prevent log spew from poorly behaving devices. this indicates the
674 os actually had trouble communicating with the device */
675 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
683 if (kIOReturnSuccess != ret) {
684 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
685 /* sleep for a little while before trying again */
688 } while (kIOReturnSuccess != ret && retries--);
691 /* resuspend the device */
692 (void)(*device)->USBDeviceSuspend (device, 1);
695 (void) (*device)->USBDeviceClose (device);
697 if (ret != kIOReturnSuccess) {
698 /* a debug message was already printed out for this error */
699 if (LIBUSB_CLASS_HUB == bDeviceClass)
700 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
701 idVendor, idProduct, darwin_error_str (ret), ret);
703 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
704 idVendor, idProduct, darwin_error_str (ret), ret);
708 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
709 if (libusb_le16_to_cpu (dev->dev_descriptor.idProduct) != idProduct) {
710 /* not a valid device */
711 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
712 idProduct, libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
716 usbi_dbg ("cached device descriptor:");
717 usbi_dbg (" bDescriptorType: 0x%02x", dev->dev_descriptor.bDescriptorType);
718 usbi_dbg (" bcdUSB: 0x%04x", dev->dev_descriptor.bcdUSB);
719 usbi_dbg (" bDeviceClass: 0x%02x", dev->dev_descriptor.bDeviceClass);
720 usbi_dbg (" bDeviceSubClass: 0x%02x", dev->dev_descriptor.bDeviceSubClass);
721 usbi_dbg (" bDeviceProtocol: 0x%02x", dev->dev_descriptor.bDeviceProtocol);
722 usbi_dbg (" bMaxPacketSize0: 0x%02x", dev->dev_descriptor.bMaxPacketSize0);
723 usbi_dbg (" idVendor: 0x%04x", dev->dev_descriptor.idVendor);
724 usbi_dbg (" idProduct: 0x%04x", dev->dev_descriptor.idProduct);
725 usbi_dbg (" bcdDevice: 0x%04x", dev->dev_descriptor.bcdDevice);
726 usbi_dbg (" iManufacturer: 0x%02x", dev->dev_descriptor.iManufacturer);
727 usbi_dbg (" iProduct: 0x%02x", dev->dev_descriptor.iProduct);
728 usbi_dbg (" iSerialNumber: 0x%02x", dev->dev_descriptor.iSerialNumber);
729 usbi_dbg (" bNumConfigurations: 0x%02x", dev->dev_descriptor.bNumConfigurations);
731 dev->can_enumerate = 1;
736 static int darwin_get_cached_device(struct libusb_context *ctx, io_service_t service,
737 struct darwin_cached_device **cached_out) {
738 struct darwin_cached_device *new_device;
739 UInt64 sessionID = 0, parent_sessionID = 0;
740 int ret = LIBUSB_SUCCESS;
741 usb_device_t **device;
743 kern_return_t result;
748 /* get some info from the io registry */
749 (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
750 (void) get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, &port);
752 usbi_dbg("finding cached device for sessionID 0x\n" PRIx64, sessionID);
754 result = IORegistryEntryGetParentEntry (service, kIOUSBPlane, &parent);
756 if (kIOReturnSuccess == result) {
757 (void) get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, &parent_sessionID);
758 IOObjectRelease(parent);
761 usbi_mutex_lock(&darwin_cached_devices_lock);
763 list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) {
764 usbi_dbg("matching sessionID 0x%x against cached device with sessionID 0x%x", sessionID, new_device->session);
765 if (new_device->session == sessionID) {
766 usbi_dbg("using cached device for device");
767 *cached_out = new_device;
775 usbi_dbg("caching new device with sessionID 0x%x\n", sessionID);
777 new_device = calloc (1, sizeof (*new_device));
779 ret = LIBUSB_ERROR_NO_MEM;
783 device = darwin_device_from_service (service);
785 ret = LIBUSB_ERROR_NO_DEVICE;
791 /* add this device to the cached device list */
792 list_add(&new_device->list, &darwin_cached_devices);
794 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
796 /* keep a reference to this device */
797 darwin_ref_cached_device(new_device);
799 new_device->device = device;
800 new_device->session = sessionID;
801 (*device)->GetLocationID (device, &new_device->location);
802 new_device->port = port;
803 new_device->parent_session = parent_sessionID;
805 /* cache the device descriptor */
806 ret = darwin_cache_device_descriptor(ctx, new_device);
810 if (new_device->can_enumerate) {
811 snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address,
812 new_device->dev_descriptor.idVendor, new_device->dev_descriptor.idProduct,
813 new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass);
817 usbi_mutex_unlock(&darwin_cached_devices_lock);
819 /* keep track of devices regardless of if we successfully enumerate them to
820 prevent them from being enumerated multiple times */
822 *cached_out = new_device;
827 static int process_new_device (struct libusb_context *ctx, io_service_t service) {
828 struct darwin_device_priv *priv;
829 struct libusb_device *dev = NULL;
830 struct darwin_cached_device *cached_device;
835 ret = darwin_get_cached_device (ctx, service, &cached_device);
837 if (ret < 0 || (cached_device && !cached_device->can_enumerate)) {
841 /* check current active configuration (and cache the first configuration value--
842 which may be used by claim_interface) */
843 ret = darwin_check_configuration (ctx, cached_device);
847 usbi_dbg ("allocating new device in context %p for with session 0x%08x",
848 ctx, cached_device->session);
850 dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
852 return LIBUSB_ERROR_NO_MEM;
855 priv = (struct darwin_device_priv *)dev->os_priv;
857 priv->dev = cached_device;
858 darwin_ref_cached_device (priv->dev);
860 if (cached_device->parent_session > 0) {
861 dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session);
863 dev->parent_dev = NULL;
865 dev->port_number = cached_device->port;
866 dev->bus_number = cached_device->location >> 24;
867 dev->device_address = cached_device->address;
869 /* need to add a reference to the parent device */
870 if (dev->parent_dev) {
871 libusb_ref_device(dev->parent_dev);
874 (*(priv->dev->device))->GetDeviceSpeed (priv->dev->device, &devSpeed);
877 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
878 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
879 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
880 #if DeviceVersion >= 500
881 case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
884 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
887 ret = usbi_sanitize_device (dev);
891 usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
892 dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
896 usbi_connect_device (dev);
898 libusb_unref_device (dev);
904 static int darwin_scan_devices(struct libusb_context *ctx) {
905 io_iterator_t deviceIterator;
906 io_service_t service;
907 kern_return_t kresult;
909 kresult = usb_setup_device_iterator (&deviceIterator, 0);
910 if (kresult != kIOReturnSuccess)
911 return darwin_to_libusb (kresult);
913 while ((service = IOIteratorNext (deviceIterator))) {
914 (void) process_new_device (ctx, service);
916 IOObjectRelease(service);
919 IOObjectRelease(deviceIterator);
924 static int darwin_open (struct libusb_device_handle *dev_handle) {
925 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
926 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
929 if (0 == dpriv->open_count) {
930 /* try to open the device */
931 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
932 if (kresult != kIOReturnSuccess) {
933 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
935 if (kIOReturnExclusiveAccess != kresult) {
936 return darwin_to_libusb (kresult);
939 /* it is possible to perform some actions on a device that is not open so do not return an error */
945 /* create async event source */
946 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
947 if (kresult != kIOReturnSuccess) {
948 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
951 (*(dpriv->device))->USBDeviceClose (dpriv->device);
956 return darwin_to_libusb (kresult);
959 CFRetain (libusb_darwin_acfl);
961 /* add the cfSource to the aync run loop */
962 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
965 /* device opened successfully */
968 /* create a file descriptor for notifications */
971 /* set the pipe to be non-blocking */
972 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
974 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
976 usbi_dbg ("device open for access");
981 static void darwin_close (struct libusb_device_handle *dev_handle) {
982 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
983 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
987 if (dpriv->open_count == 0) {
988 /* something is probably very wrong if this is the case */
989 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
995 /* make sure all interfaces are released */
996 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
997 if (dev_handle->claimed_interfaces & (1 << i))
998 libusb_release_interface (dev_handle, i);
1000 if (0 == dpriv->open_count) {
1001 /* delete the device's async event source */
1002 if (priv->cfSource) {
1003 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
1004 CFRelease (priv->cfSource);
1005 priv->cfSource = NULL;
1006 CFRelease (libusb_darwin_acfl);
1009 if (priv->is_open) {
1010 /* close the device */
1011 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
1013 /* Log the fact that we had a problem closing the file, however failing a
1014 * close isn't really an error, so return success anyway */
1015 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
1020 /* file descriptors are maintained per-instance */
1021 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
1022 close (priv->fds[1]);
1023 close (priv->fds[0]);
1025 priv->fds[0] = priv->fds[1] = -1;
1028 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
1029 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1031 *config = (int) dpriv->active_config;
1036 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
1037 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1041 /* Setting configuration will invalidate the interface, so we need
1042 to reclaim it. First, dispose of existing interfaces, if any. */
1043 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1044 if (dev_handle->claimed_interfaces & (1 << i))
1045 darwin_release_interface (dev_handle, i);
1047 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
1048 if (kresult != kIOReturnSuccess)
1049 return darwin_to_libusb (kresult);
1051 /* Reclaim any interfaces. */
1052 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1053 if (dev_handle->claimed_interfaces & (1 << i))
1054 darwin_claim_interface (dev_handle, i);
1056 dpriv->active_config = config;
1061 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
1062 IOUSBFindInterfaceRequest request;
1063 kern_return_t kresult;
1064 io_iterator_t interface_iterator;
1065 UInt8 bInterfaceNumber;
1068 *usbInterfacep = IO_OBJECT_NULL;
1070 /* Setup the Interface Request */
1071 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1072 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1073 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1074 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1076 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1080 while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1081 /* find the interface number */
1082 ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
1085 if (ret && bInterfaceNumber == ifc) {
1089 (void) IOObjectRelease (*usbInterfacep);
1092 /* done with the interface iterator */
1093 IOObjectRelease(interface_iterator);
1098 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
1099 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1101 /* current interface */
1102 struct darwin_interface *cInterface = &priv->interfaces[iface];
1104 kern_return_t kresult;
1106 u_int8_t numep, direction, number;
1107 u_int8_t dont_care1, dont_care3;
1108 u_int16_t dont_care2;
1111 usbi_dbg ("building table of endpoints.");
1113 /* retrieve the total number of endpoints on this interface */
1114 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1116 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1117 return darwin_to_libusb (kresult);
1120 /* iterate through pipe references */
1121 for (i = 1 ; i <= numep ; i++) {
1122 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1123 &dont_care2, &dont_care3);
1125 if (kresult != kIOReturnSuccess) {
1126 usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
1128 return darwin_to_libusb (kresult);
1131 usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
1133 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1136 cInterface->num_endpoints = numep;
1141 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1142 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1143 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1144 io_service_t usbInterface = IO_OBJECT_NULL;
1146 IOCFPlugInInterface **plugInInterface = NULL;
1149 /* current interface */
1150 struct darwin_interface *cInterface = &priv->interfaces[iface];
1152 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1153 if (kresult != kIOReturnSuccess)
1154 return darwin_to_libusb (kresult);
1156 /* make sure we have an interface */
1157 if (!usbInterface && dpriv->first_config != 0) {
1158 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1160 /* set the configuration */
1161 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1162 if (kresult != LIBUSB_SUCCESS) {
1163 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1167 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1169 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1170 return darwin_to_libusb (kresult);
1174 if (!usbInterface) {
1175 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1176 return LIBUSB_ERROR_NOT_FOUND;
1179 /* get an interface to the device's interface */
1180 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1181 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1183 /* ignore release error */
1184 (void)IOObjectRelease (usbInterface);
1187 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1188 return darwin_to_libusb (kresult);
1191 if (!plugInInterface) {
1192 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1193 return LIBUSB_ERROR_NOT_FOUND;
1196 /* Do the actual claim */
1197 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1198 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1199 (LPVOID)&cInterface->interface);
1200 /* We no longer need the intermediate plug-in */
1201 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1202 (*plugInInterface)->Release (plugInInterface);
1203 if (kresult || !cInterface->interface) {
1204 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1205 return darwin_to_libusb (kresult);
1208 /* claim the interface */
1209 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1211 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1212 return darwin_to_libusb (kresult);
1215 /* update list of endpoints */
1216 kresult = get_endpoints (dev_handle, iface);
1218 /* this should not happen */
1219 darwin_release_interface (dev_handle, iface);
1220 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1224 cInterface->cfSource = NULL;
1226 /* create async event source */
1227 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1228 if (kresult != kIOReturnSuccess) {
1229 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1231 /* can't continue without an async event source */
1232 (void)darwin_release_interface (dev_handle, iface);
1234 return darwin_to_libusb (kresult);
1237 /* add the cfSource to the async thread's run loop */
1238 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1240 usbi_dbg ("interface opened");
1245 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1246 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1249 /* current interface */
1250 struct darwin_interface *cInterface = &priv->interfaces[iface];
1252 /* Check to see if an interface is open */
1253 if (!cInterface->interface)
1254 return LIBUSB_SUCCESS;
1256 /* clean up endpoint data */
1257 cInterface->num_endpoints = 0;
1259 /* delete the interface's async event source */
1260 if (cInterface->cfSource) {
1261 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1262 CFRelease (cInterface->cfSource);
1265 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1267 usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1269 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1270 if (kresult != kIOReturnSuccess)
1271 usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1273 cInterface->interface = IO_OBJECT_NULL;
1275 return darwin_to_libusb (kresult);
1278 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1279 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1282 /* current interface */
1283 struct darwin_interface *cInterface = &priv->interfaces[iface];
1285 if (!cInterface->interface)
1286 return LIBUSB_ERROR_NO_DEVICE;
1288 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1289 if (kresult != kIOReturnSuccess)
1290 darwin_reset_device (dev_handle);
1292 /* update list of endpoints */
1293 kresult = get_endpoints (dev_handle, iface);
1295 /* this should not happen */
1296 darwin_release_interface (dev_handle, iface);
1297 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1301 return darwin_to_libusb (kresult);
1304 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1305 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1307 /* current interface */
1308 struct darwin_interface *cInterface;
1309 uint8_t pipeRef, iface;
1312 /* determine the interface/endpoint to use */
1313 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
1314 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1316 return LIBUSB_ERROR_NOT_FOUND;
1319 cInterface = &priv->interfaces[iface];
1321 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1322 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1324 usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1326 return darwin_to_libusb (kresult);
1329 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1330 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1331 IOUSBDeviceDescriptor descriptor;
1332 IOUSBConfigurationDescriptorPtr cached_configuration;
1333 IOUSBConfigurationDescriptor configuration;
1334 bool reenumerate = false;
1338 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1340 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1341 return darwin_to_libusb (kresult);
1345 usbi_dbg ("darwin/reset_device: checking if device descriptor changed");
1347 /* ignore return code. if we can't get a descriptor it might be worthwhile re-enumerating anway */
1348 (void) darwin_request_descriptor (dpriv->device, kUSBDeviceDesc, 0, &descriptor, sizeof (descriptor));
1350 /* check if the device descriptor has changed */
1351 if (0 != memcmp (&dpriv->dev_descriptor, &descriptor, sizeof (descriptor))) {
1356 /* check if any configuration descriptor has changed */
1357 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1358 usbi_dbg ("darwin/reset_device: checking if configuration descriptor %d changed", i);
1360 (void) darwin_request_descriptor (dpriv->device, kUSBConfDesc, i, &configuration, sizeof (configuration));
1361 (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1363 if (!cached_configuration || 0 != memcmp (cached_configuration, &configuration, sizeof (configuration))) {
1371 usbi_dbg ("darwin/reset_device: device requires reenumeration");
1372 (void) (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
1373 return LIBUSB_ERROR_NOT_FOUND;
1376 usbi_dbg ("darwin/reset_device: device reset complete");
1378 return LIBUSB_SUCCESS;
1381 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1382 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1383 io_service_t usbInterface;
1387 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1389 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1391 return darwin_to_libusb (kresult);
1394 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1395 IOObjectRelease (usbInterface);
1407 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1408 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1411 return LIBUSB_ERROR_NOT_SUPPORTED;
1414 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1417 return LIBUSB_ERROR_NOT_SUPPORTED;
1420 static void darwin_destroy_device(struct libusb_device *dev) {
1421 struct darwin_device_priv *dpriv = (struct darwin_device_priv *) dev->os_priv;
1424 /* need to hold the lock in case this is the last reference to the device */
1425 usbi_mutex_lock(&darwin_cached_devices_lock);
1426 darwin_deref_cached_device (dpriv->dev);
1428 usbi_mutex_unlock(&darwin_cached_devices_lock);
1432 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1433 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1434 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1437 uint8_t transferType;
1438 /* None of the values below are used in libusbx for bulk transfers */
1439 uint8_t direction, number, interval, pipeRef, iface;
1440 uint16_t maxPacketSize;
1442 struct darwin_interface *cInterface;
1444 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1445 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1447 return LIBUSB_ERROR_NOT_FOUND;
1450 cInterface = &priv->interfaces[iface];
1452 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1453 &transferType, &maxPacketSize, &interval);
1455 if (0 != (transfer->length % maxPacketSize)) {
1456 /* do not need a zero packet */
1457 transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1460 /* submit the request */
1461 /* timeouts are unavailable on interrupt endpoints */
1462 if (transferType == kUSBInterrupt) {
1463 if (IS_XFERIN(transfer))
1464 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1465 transfer->length, darwin_async_io_callback, itransfer);
1467 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1468 transfer->length, darwin_async_io_callback, itransfer);
1470 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1472 if (IS_XFERIN(transfer))
1473 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1474 transfer->length, transfer->timeout, transfer->timeout,
1475 darwin_async_io_callback, (void *)itransfer);
1477 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1478 transfer->length, transfer->timeout, transfer->timeout,
1479 darwin_async_io_callback, (void *)itransfer);
1483 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1484 darwin_error_str(ret), ret);
1486 return darwin_to_libusb (ret);
1489 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1490 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1491 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1492 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1495 uint8_t direction, number, interval, pipeRef, iface, transferType;
1496 uint16_t maxPacketSize;
1498 AbsoluteTime atTime;
1501 struct darwin_interface *cInterface;
1503 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1504 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1505 free(tpriv->isoc_framelist);
1506 tpriv->isoc_framelist = NULL;
1509 if (!tpriv->isoc_framelist) {
1510 tpriv->num_iso_packets = transfer->num_iso_packets;
1511 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1512 if (!tpriv->isoc_framelist)
1513 return LIBUSB_ERROR_NO_MEM;
1516 /* copy the frame list from the libusbx descriptor (the structures differ only is member order) */
1517 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1518 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1520 /* determine the interface/endpoint to use */
1521 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1522 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1524 return LIBUSB_ERROR_NOT_FOUND;
1527 cInterface = &priv->interfaces[iface];
1529 /* determine the properties of this endpoint and the speed of the device */
1530 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1531 &transferType, &maxPacketSize, &interval);
1533 /* Last but not least we need the bus frame number */
1534 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1536 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1537 free(tpriv->isoc_framelist);
1538 tpriv->isoc_framelist = NULL;
1540 return darwin_to_libusb (kresult);
1543 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1544 &transferType, &maxPacketSize, &interval);
1546 /* schedule for a frame a little in the future */
1549 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1550 frame = cInterface->frames[transfer->endpoint];
1552 /* submit the request */
1553 if (IS_XFERIN(transfer))
1554 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1555 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1558 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1559 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1562 if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
1564 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1));
1566 /* High/super speed */
1567 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1)) / 8;
1569 if (kresult != kIOReturnSuccess) {
1570 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1571 darwin_error_str(kresult));
1572 free (tpriv->isoc_framelist);
1573 tpriv->isoc_framelist = NULL;
1576 return darwin_to_libusb (kresult);
1579 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1580 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1581 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1582 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1583 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1584 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1588 bzero(&tpriv->req, sizeof(tpriv->req));
1590 /* IOUSBDeviceInterface expects the request in cpu endianess */
1591 tpriv->req.bmRequestType = setup->bmRequestType;
1592 tpriv->req.bRequest = setup->bRequest;
1593 /* these values should be in bus order from libusb_fill_control_setup */
1594 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1595 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1596 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1597 /* data is stored after the libusbx control block */
1598 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1599 tpriv->req.completionTimeout = transfer->timeout;
1600 tpriv->req.noDataTimeout = transfer->timeout;
1602 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1604 /* all transfers in libusb-1.0 are async */
1606 if (transfer->endpoint) {
1607 struct darwin_interface *cInterface;
1608 uint8_t pipeRef, iface;
1610 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1611 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1613 return LIBUSB_ERROR_NOT_FOUND;
1616 cInterface = &priv->interfaces[iface];
1618 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1620 /* control request on endpoint 0 */
1621 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1623 if (kresult != kIOReturnSuccess)
1624 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1626 return darwin_to_libusb (kresult);
1629 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1630 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1632 switch (transfer->type) {
1633 case LIBUSB_TRANSFER_TYPE_CONTROL:
1634 return submit_control_transfer(itransfer);
1635 case LIBUSB_TRANSFER_TYPE_BULK:
1636 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1637 return submit_bulk_transfer(itransfer);
1638 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1639 return submit_iso_transfer(itransfer);
1641 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1642 return LIBUSB_ERROR_INVALID_PARAM;
1646 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1647 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1648 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1651 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
1654 return LIBUSB_ERROR_NO_DEVICE;
1656 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1658 return darwin_to_libusb (kresult);
1661 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1662 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1663 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1664 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1665 struct darwin_interface *cInterface;
1666 uint8_t pipeRef, iface;
1669 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1670 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1672 return LIBUSB_ERROR_NOT_FOUND;
1675 cInterface = &priv->interfaces[iface];
1678 return LIBUSB_ERROR_NO_DEVICE;
1680 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
1682 /* abort transactions */
1683 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1685 usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
1687 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1688 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1690 return darwin_to_libusb (kresult);
1693 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1694 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1696 switch (transfer->type) {
1697 case LIBUSB_TRANSFER_TYPE_CONTROL:
1698 return cancel_control_transfer(itransfer);
1699 case LIBUSB_TRANSFER_TYPE_BULK:
1700 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1701 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1702 return darwin_abort_transfers (itransfer);
1704 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1705 return LIBUSB_ERROR_INVALID_PARAM;
1709 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1710 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1711 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1713 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1714 free (tpriv->isoc_framelist);
1715 tpriv->isoc_framelist = NULL;
1719 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1720 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1721 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1722 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1723 struct darwin_msg_async_io_complete message = {.itransfer = itransfer, .result = result,
1724 .size = (UInt32) (uintptr_t) arg0};
1726 usbi_dbg ("an async io operation has completed");
1728 /* if requested write a zero packet */
1729 if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
1730 struct darwin_interface *cInterface;
1731 uint8_t iface, pipeRef;
1733 (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface);
1734 cInterface = &priv->interfaces[iface];
1736 (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
1739 /* send a completion message to the device's file descriptor */
1740 write (priv->fds[1], &message, sizeof (message));
1743 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1744 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT)
1745 result = kIOUSBTransactionTimeout;
1748 case kIOReturnUnderrun:
1749 case kIOReturnSuccess:
1750 return LIBUSB_TRANSFER_COMPLETED;
1751 case kIOReturnAborted:
1752 return LIBUSB_TRANSFER_CANCELLED;
1753 case kIOUSBPipeStalled:
1754 usbi_dbg ("transfer error: pipe is stalled");
1755 return LIBUSB_TRANSFER_STALL;
1756 case kIOReturnOverrun:
1757 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1758 return LIBUSB_TRANSFER_OVERFLOW;
1759 case kIOUSBTransactionTimeout:
1760 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1761 itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
1762 return LIBUSB_TRANSFER_TIMED_OUT;
1764 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1765 return LIBUSB_TRANSFER_ERROR;
1769 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1770 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1771 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1772 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1773 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1774 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1775 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1778 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1779 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1783 usbi_dbg ("handling %s completion with kernel status %d",
1784 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
1786 if (kIOReturnSuccess == result || kIOReturnUnderrun == result) {
1787 if (isIsoc && tpriv->isoc_framelist) {
1788 /* copy isochronous results back */
1790 for (i = 0; i < transfer->num_iso_packets ; i++) {
1791 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1792 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1793 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1796 itransfer->transferred += io_size;
1799 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1800 usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
1803 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready) {
1804 struct darwin_msg_async_io_complete message;
1805 POLL_NFDS_TYPE i = 0;
1808 usbi_mutex_lock(&ctx->open_devs_lock);
1810 for (i = 0; i < nfds && num_ready > 0; i++) {
1811 struct pollfd *pollfd = &fds[i];
1813 usbi_dbg ("checking fd %i with revents = %x", pollfd->fd, pollfd->revents);
1815 if (!pollfd->revents)
1820 if (pollfd->revents & POLLERR) {
1821 /* this probably will never happen so ignore the error an move on. */
1825 /* there is only one type of message */
1826 ret = read (pollfd->fd, &message, sizeof (message));
1827 if (ret < (ssize_t) sizeof (message)) {
1828 usbi_dbg ("WARNING: short read on async io completion pipe\n");
1832 darwin_handle_callback (message.itransfer, message.result, message.size);
1835 usbi_mutex_unlock(&ctx->open_devs_lock);
1840 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1841 mach_timespec_t sys_time;
1842 clock_serv_t clock_ref;
1845 case USBI_CLOCK_REALTIME:
1846 /* CLOCK_REALTIME represents time since the epoch */
1847 clock_ref = clock_realtime;
1849 case USBI_CLOCK_MONOTONIC:
1850 /* use system boot time as reference for the monotonic clock */
1851 clock_ref = clock_monotonic;
1854 return LIBUSB_ERROR_INVALID_PARAM;
1857 clock_get_time (clock_ref, &sys_time);
1859 tp->tv_sec = sys_time.tv_sec;
1860 tp->tv_nsec = sys_time.tv_nsec;
1865 const struct usbi_os_backend darwin_backend = {
1868 .init = darwin_init,
1869 .exit = darwin_exit,
1870 .get_device_list = NULL, /* not needed */
1871 .get_device_descriptor = darwin_get_device_descriptor,
1872 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1873 .get_config_descriptor = darwin_get_config_descriptor,
1875 .open = darwin_open,
1876 .close = darwin_close,
1877 .get_configuration = darwin_get_configuration,
1878 .set_configuration = darwin_set_configuration,
1879 .claim_interface = darwin_claim_interface,
1880 .release_interface = darwin_release_interface,
1882 .set_interface_altsetting = darwin_set_interface_altsetting,
1883 .clear_halt = darwin_clear_halt,
1884 .reset_device = darwin_reset_device,
1886 .kernel_driver_active = darwin_kernel_driver_active,
1887 .detach_kernel_driver = darwin_detach_kernel_driver,
1888 .attach_kernel_driver = darwin_attach_kernel_driver,
1890 .destroy_device = darwin_destroy_device,
1892 .submit_transfer = darwin_submit_transfer,
1893 .cancel_transfer = darwin_cancel_transfer,
1894 .clear_transfer_priv = darwin_clear_transfer_priv,
1896 .handle_events = op_handle_events,
1898 .clock_gettime = darwin_clock_gettime,
1900 .device_priv_size = sizeof(struct darwin_device_priv),
1901 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1902 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1903 .add_iso_packet_size = 0,