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);
705 return darwin_to_libusb (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));
713 return LIBUSB_ERROR_NO_DEVICE;
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;
733 return LIBUSB_SUCCESS;
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;
746 /* get some info from the io registry */
747 (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
748 (void) get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, &port);
750 usbi_dbg("finding cached device for sessionID 0x\n" PRIx64, sessionID);
752 result = IORegistryEntryGetParentEntry (service, kIOUSBPlane, &parent);
754 if (kIOReturnSuccess == result) {
755 (void) get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, &parent_sessionID);
756 IOObjectRelease(parent);
759 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 device = darwin_device_from_service (service);
779 ret = LIBUSB_ERROR_NO_DEVICE;
783 new_device = calloc (1, sizeof (*new_device));
785 ret = LIBUSB_ERROR_NO_MEM;
789 /* add this device to the cached device list */
790 list_add(&new_device->list, &darwin_cached_devices);
792 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
794 /* keep a reference to this device */
795 darwin_ref_cached_device(new_device);
797 new_device->device = device;
798 new_device->session = sessionID;
799 (*device)->GetLocationID (device, &new_device->location);
800 new_device->port = port;
801 new_device->parent_session = parent_sessionID;
803 /* cache the device descriptor */
804 ret = darwin_cache_device_descriptor(ctx, new_device);
808 if (new_device->can_enumerate) {
809 snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address,
810 new_device->dev_descriptor.idVendor, new_device->dev_descriptor.idProduct,
811 new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass);
815 usbi_mutex_unlock(&darwin_cached_devices_lock);
817 /* keep track of devices regardless of if we successfully enumerate them to
818 prevent them from being enumerated multiple times */
820 *cached_out = new_device;
825 static int process_new_device (struct libusb_context *ctx, io_service_t service) {
826 struct darwin_device_priv *priv;
827 struct libusb_device *dev = NULL;
828 struct darwin_cached_device *cached_device;
833 ret = darwin_get_cached_device (ctx, service, &cached_device);
835 if (ret < 0 || !cached_device->can_enumerate) {
839 /* check current active configuration (and cache the first configuration value--
840 which may be used by claim_interface) */
841 ret = darwin_check_configuration (ctx, cached_device);
845 usbi_dbg ("allocating new device in context %p for with session 0x%08x",
846 ctx, cached_device->session);
848 dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
850 return LIBUSB_ERROR_NO_MEM;
853 priv = (struct darwin_device_priv *)dev->os_priv;
855 priv->dev = cached_device;
856 darwin_ref_cached_device (priv->dev);
858 if (cached_device->parent_session > 0) {
859 dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session);
861 dev->parent_dev = NULL;
863 dev->port_number = cached_device->port;
864 dev->bus_number = cached_device->location >> 24;
865 dev->device_address = cached_device->address;
867 /* need to add a reference to the parent device */
868 if (dev->parent_dev) {
869 libusb_ref_device(dev->parent_dev);
872 (*(priv->dev->device))->GetDeviceSpeed (priv->dev->device, &devSpeed);
875 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
876 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
877 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
878 #if DeviceVersion >= 500
879 case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
882 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
885 ret = usbi_sanitize_device (dev);
889 usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
890 dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
894 usbi_connect_device (dev);
896 libusb_unref_device (dev);
902 static int darwin_scan_devices(struct libusb_context *ctx) {
903 io_iterator_t deviceIterator;
904 io_service_t service;
905 kern_return_t kresult;
907 kresult = usb_setup_device_iterator (&deviceIterator, 0);
908 if (kresult != kIOReturnSuccess)
909 return darwin_to_libusb (kresult);
911 while ((service = IOIteratorNext (deviceIterator))) {
912 (void) process_new_device (ctx, service);
914 IOObjectRelease(service);
917 IOObjectRelease(deviceIterator);
922 static int darwin_open (struct libusb_device_handle *dev_handle) {
923 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
924 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
927 if (0 == dpriv->open_count) {
928 /* try to open the device */
929 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
930 if (kresult != kIOReturnSuccess) {
931 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
933 if (kIOReturnExclusiveAccess != kresult) {
934 return darwin_to_libusb (kresult);
937 /* it is possible to perform some actions on a device that is not open so do not return an error */
943 /* create async event source */
944 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
945 if (kresult != kIOReturnSuccess) {
946 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
949 (*(dpriv->device))->USBDeviceClose (dpriv->device);
954 return darwin_to_libusb (kresult);
957 CFRetain (libusb_darwin_acfl);
959 /* add the cfSource to the aync run loop */
960 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
963 /* device opened successfully */
966 /* create a file descriptor for notifications */
969 /* set the pipe to be non-blocking */
970 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
972 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
974 usbi_dbg ("device open for access");
979 static void darwin_close (struct libusb_device_handle *dev_handle) {
980 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
981 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
985 if (dpriv->open_count == 0) {
986 /* something is probably very wrong if this is the case */
987 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
993 /* make sure all interfaces are released */
994 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
995 if (dev_handle->claimed_interfaces & (1 << i))
996 libusb_release_interface (dev_handle, i);
998 if (0 == dpriv->open_count) {
999 /* delete the device's async event source */
1000 if (priv->cfSource) {
1001 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
1002 CFRelease (priv->cfSource);
1003 priv->cfSource = NULL;
1004 CFRelease (libusb_darwin_acfl);
1007 if (priv->is_open) {
1008 /* close the device */
1009 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
1011 /* Log the fact that we had a problem closing the file, however failing a
1012 * close isn't really an error, so return success anyway */
1013 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
1018 /* file descriptors are maintained per-instance */
1019 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
1020 close (priv->fds[1]);
1021 close (priv->fds[0]);
1023 priv->fds[0] = priv->fds[1] = -1;
1026 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
1027 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1029 *config = (int) dpriv->active_config;
1034 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
1035 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1039 /* Setting configuration will invalidate the interface, so we need
1040 to reclaim it. First, dispose of existing interfaces, if any. */
1041 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1042 if (dev_handle->claimed_interfaces & (1 << i))
1043 darwin_release_interface (dev_handle, i);
1045 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
1046 if (kresult != kIOReturnSuccess)
1047 return darwin_to_libusb (kresult);
1049 /* Reclaim any interfaces. */
1050 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1051 if (dev_handle->claimed_interfaces & (1 << i))
1052 darwin_claim_interface (dev_handle, i);
1054 dpriv->active_config = config;
1059 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
1060 IOUSBFindInterfaceRequest request;
1061 kern_return_t kresult;
1062 io_iterator_t interface_iterator;
1063 UInt8 bInterfaceNumber;
1066 *usbInterfacep = IO_OBJECT_NULL;
1068 /* Setup the Interface Request */
1069 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1070 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1071 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1072 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1074 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1078 while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1079 /* find the interface number */
1080 ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
1083 if (ret && bInterfaceNumber == ifc) {
1087 (void) IOObjectRelease (*usbInterfacep);
1090 /* done with the interface iterator */
1091 IOObjectRelease(interface_iterator);
1096 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
1097 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1099 /* current interface */
1100 struct darwin_interface *cInterface = &priv->interfaces[iface];
1102 kern_return_t kresult;
1104 u_int8_t numep, direction, number;
1105 u_int8_t dont_care1, dont_care3;
1106 u_int16_t dont_care2;
1109 usbi_dbg ("building table of endpoints.");
1111 /* retrieve the total number of endpoints on this interface */
1112 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1114 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1115 return darwin_to_libusb (kresult);
1118 /* iterate through pipe references */
1119 for (i = 1 ; i <= numep ; i++) {
1120 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1121 &dont_care2, &dont_care3);
1123 if (kresult != kIOReturnSuccess) {
1124 usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
1126 return darwin_to_libusb (kresult);
1129 usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
1131 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1134 cInterface->num_endpoints = numep;
1139 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1140 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1141 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1142 io_service_t usbInterface = IO_OBJECT_NULL;
1144 IOCFPlugInInterface **plugInInterface = NULL;
1147 /* current interface */
1148 struct darwin_interface *cInterface = &priv->interfaces[iface];
1150 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1151 if (kresult != kIOReturnSuccess)
1152 return darwin_to_libusb (kresult);
1154 /* make sure we have an interface */
1155 if (!usbInterface && dpriv->first_config != 0) {
1156 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1158 /* set the configuration */
1159 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1160 if (kresult != LIBUSB_SUCCESS) {
1161 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1165 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1167 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1168 return darwin_to_libusb (kresult);
1172 if (!usbInterface) {
1173 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1174 return LIBUSB_ERROR_NOT_FOUND;
1177 /* get an interface to the device's interface */
1178 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1179 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1181 /* ignore release error */
1182 (void)IOObjectRelease (usbInterface);
1185 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1186 return darwin_to_libusb (kresult);
1189 if (!plugInInterface) {
1190 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1191 return LIBUSB_ERROR_NOT_FOUND;
1194 /* Do the actual claim */
1195 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1196 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1197 (LPVOID)&cInterface->interface);
1198 /* We no longer need the intermediate plug-in */
1199 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1200 (*plugInInterface)->Release (plugInInterface);
1201 if (kresult || !cInterface->interface) {
1202 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1203 return darwin_to_libusb (kresult);
1206 /* claim the interface */
1207 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1209 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1210 return darwin_to_libusb (kresult);
1213 /* update list of endpoints */
1214 kresult = get_endpoints (dev_handle, iface);
1216 /* this should not happen */
1217 darwin_release_interface (dev_handle, iface);
1218 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1222 cInterface->cfSource = NULL;
1224 /* create async event source */
1225 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1226 if (kresult != kIOReturnSuccess) {
1227 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1229 /* can't continue without an async event source */
1230 (void)darwin_release_interface (dev_handle, iface);
1232 return darwin_to_libusb (kresult);
1235 /* add the cfSource to the async thread's run loop */
1236 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1238 usbi_dbg ("interface opened");
1243 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1244 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1247 /* current interface */
1248 struct darwin_interface *cInterface = &priv->interfaces[iface];
1250 /* Check to see if an interface is open */
1251 if (!cInterface->interface)
1252 return LIBUSB_SUCCESS;
1254 /* clean up endpoint data */
1255 cInterface->num_endpoints = 0;
1257 /* delete the interface's async event source */
1258 if (cInterface->cfSource) {
1259 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1260 CFRelease (cInterface->cfSource);
1263 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1265 usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1267 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1268 if (kresult != kIOReturnSuccess)
1269 usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1271 cInterface->interface = IO_OBJECT_NULL;
1273 return darwin_to_libusb (kresult);
1276 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1277 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1280 /* current interface */
1281 struct darwin_interface *cInterface = &priv->interfaces[iface];
1283 if (!cInterface->interface)
1284 return LIBUSB_ERROR_NO_DEVICE;
1286 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1287 if (kresult != kIOReturnSuccess)
1288 darwin_reset_device (dev_handle);
1290 /* update list of endpoints */
1291 kresult = get_endpoints (dev_handle, iface);
1293 /* this should not happen */
1294 darwin_release_interface (dev_handle, iface);
1295 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1299 return darwin_to_libusb (kresult);
1302 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1303 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1305 /* current interface */
1306 struct darwin_interface *cInterface;
1307 uint8_t pipeRef, iface;
1310 /* determine the interface/endpoint to use */
1311 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
1312 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1314 return LIBUSB_ERROR_NOT_FOUND;
1317 cInterface = &priv->interfaces[iface];
1319 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1320 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1322 usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1324 return darwin_to_libusb (kresult);
1327 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1328 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1329 IOUSBDeviceDescriptor descriptor;
1330 IOUSBConfigurationDescriptorPtr cached_configuration;
1331 IOUSBConfigurationDescriptor configuration;
1332 bool reenumerate = false;
1336 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1338 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1339 return darwin_to_libusb (kresult);
1343 usbi_dbg ("darwin/reset_device: checking if device descriptor changed");
1345 /* ignore return code. if we can't get a descriptor it might be worthwhile re-enumerating anway */
1346 (void) darwin_request_descriptor (dpriv->device, kUSBDeviceDesc, 0, &descriptor, sizeof (descriptor));
1348 /* check if the device descriptor has changed */
1349 if (0 != memcmp (&dpriv->dev_descriptor, &descriptor, sizeof (descriptor))) {
1354 /* check if any configuration descriptor has changed */
1355 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1356 usbi_dbg ("darwin/reset_device: checking if configuration descriptor %d changed", i);
1358 (void) darwin_request_descriptor (dpriv->device, kUSBConfDesc, i, &configuration, sizeof (configuration));
1359 (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1361 if (!cached_configuration || 0 != memcmp (cached_configuration, &configuration, sizeof (configuration))) {
1369 usbi_dbg ("darwin/reset_device: device requires reenumeration");
1370 (void) (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
1371 return LIBUSB_ERROR_NOT_FOUND;
1374 usbi_dbg ("darwin/reset_device: device reset complete");
1376 return LIBUSB_SUCCESS;
1379 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1380 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1381 io_service_t usbInterface;
1385 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1387 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1389 return darwin_to_libusb (kresult);
1392 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1393 IOObjectRelease (usbInterface);
1405 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1406 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1409 return LIBUSB_ERROR_NOT_SUPPORTED;
1412 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1415 return LIBUSB_ERROR_NOT_SUPPORTED;
1418 static void darwin_destroy_device(struct libusb_device *dev) {
1419 struct darwin_device_priv *dpriv = (struct darwin_device_priv *) dev->os_priv;
1422 /* need to hold the lock in case this is the last reference to the device */
1423 usbi_mutex_lock(&darwin_cached_devices_lock);
1424 darwin_deref_cached_device (dpriv->dev);
1426 usbi_mutex_unlock(&darwin_cached_devices_lock);
1430 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1431 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1432 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1435 uint8_t transferType;
1436 /* None of the values below are used in libusbx for bulk transfers */
1437 uint8_t direction, number, interval, pipeRef, iface;
1438 uint16_t maxPacketSize;
1440 struct darwin_interface *cInterface;
1442 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1443 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1445 return LIBUSB_ERROR_NOT_FOUND;
1448 cInterface = &priv->interfaces[iface];
1450 ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1451 &transferType, &maxPacketSize, &interval);
1454 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1455 darwin_error_str(ret), ret);
1456 return darwin_to_libusb (ret);
1459 if (0 != (transfer->length % maxPacketSize)) {
1460 /* do not need a zero packet */
1461 transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1464 /* submit the request */
1465 /* timeouts are unavailable on interrupt endpoints */
1466 if (transferType == kUSBInterrupt) {
1467 if (IS_XFERIN(transfer))
1468 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1469 transfer->length, darwin_async_io_callback, itransfer);
1471 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1472 transfer->length, darwin_async_io_callback, itransfer);
1474 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1476 if (IS_XFERIN(transfer))
1477 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1478 transfer->length, transfer->timeout, transfer->timeout,
1479 darwin_async_io_callback, (void *)itransfer);
1481 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1482 transfer->length, transfer->timeout, transfer->timeout,
1483 darwin_async_io_callback, (void *)itransfer);
1487 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1488 darwin_error_str(ret), ret);
1490 return darwin_to_libusb (ret);
1493 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1494 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1495 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1496 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1499 uint8_t direction, number, interval, pipeRef, iface, transferType;
1500 uint16_t maxPacketSize;
1502 AbsoluteTime atTime;
1505 struct darwin_interface *cInterface;
1507 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1508 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1509 free(tpriv->isoc_framelist);
1510 tpriv->isoc_framelist = NULL;
1513 if (!tpriv->isoc_framelist) {
1514 tpriv->num_iso_packets = transfer->num_iso_packets;
1515 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1516 if (!tpriv->isoc_framelist)
1517 return LIBUSB_ERROR_NO_MEM;
1520 /* copy the frame list from the libusbx descriptor (the structures differ only is member order) */
1521 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1522 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1524 /* determine the interface/endpoint to use */
1525 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1526 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1528 return LIBUSB_ERROR_NOT_FOUND;
1531 cInterface = &priv->interfaces[iface];
1533 /* determine the properties of this endpoint and the speed of the device */
1534 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1535 &transferType, &maxPacketSize, &interval);
1537 /* Last but not least we need the bus frame number */
1538 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1540 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1541 free(tpriv->isoc_framelist);
1542 tpriv->isoc_framelist = NULL;
1544 return darwin_to_libusb (kresult);
1547 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1548 &transferType, &maxPacketSize, &interval);
1550 /* schedule for a frame a little in the future */
1553 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1554 frame = cInterface->frames[transfer->endpoint];
1556 /* submit the request */
1557 if (IS_XFERIN(transfer))
1558 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1559 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1562 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1563 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1566 if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
1568 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1));
1570 /* High/super speed */
1571 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1)) / 8;
1573 if (kresult != kIOReturnSuccess) {
1574 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1575 darwin_error_str(kresult));
1576 free (tpriv->isoc_framelist);
1577 tpriv->isoc_framelist = NULL;
1580 return darwin_to_libusb (kresult);
1583 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1584 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1585 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1586 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1587 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1588 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1592 bzero(&tpriv->req, sizeof(tpriv->req));
1594 /* IOUSBDeviceInterface expects the request in cpu endianess */
1595 tpriv->req.bmRequestType = setup->bmRequestType;
1596 tpriv->req.bRequest = setup->bRequest;
1597 /* these values should be in bus order from libusb_fill_control_setup */
1598 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1599 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1600 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1601 /* data is stored after the libusbx control block */
1602 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1603 tpriv->req.completionTimeout = transfer->timeout;
1604 tpriv->req.noDataTimeout = transfer->timeout;
1606 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1608 /* all transfers in libusb-1.0 are async */
1610 if (transfer->endpoint) {
1611 struct darwin_interface *cInterface;
1612 uint8_t pipeRef, iface;
1614 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1615 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1617 return LIBUSB_ERROR_NOT_FOUND;
1620 cInterface = &priv->interfaces[iface];
1622 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1624 /* control request on endpoint 0 */
1625 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1627 if (kresult != kIOReturnSuccess)
1628 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1630 return darwin_to_libusb (kresult);
1633 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1634 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1636 switch (transfer->type) {
1637 case LIBUSB_TRANSFER_TYPE_CONTROL:
1638 return submit_control_transfer(itransfer);
1639 case LIBUSB_TRANSFER_TYPE_BULK:
1640 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1641 return submit_bulk_transfer(itransfer);
1642 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1643 return submit_iso_transfer(itransfer);
1645 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1646 return LIBUSB_ERROR_INVALID_PARAM;
1650 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1651 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1652 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1655 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
1658 return LIBUSB_ERROR_NO_DEVICE;
1660 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1662 return darwin_to_libusb (kresult);
1665 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1666 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1667 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1668 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1669 struct darwin_interface *cInterface;
1670 uint8_t pipeRef, iface;
1673 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1674 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1676 return LIBUSB_ERROR_NOT_FOUND;
1679 cInterface = &priv->interfaces[iface];
1682 return LIBUSB_ERROR_NO_DEVICE;
1684 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
1686 /* abort transactions */
1687 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1689 usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
1691 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1692 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1694 return darwin_to_libusb (kresult);
1697 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1698 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1700 switch (transfer->type) {
1701 case LIBUSB_TRANSFER_TYPE_CONTROL:
1702 return cancel_control_transfer(itransfer);
1703 case LIBUSB_TRANSFER_TYPE_BULK:
1704 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1705 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1706 return darwin_abort_transfers (itransfer);
1708 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1709 return LIBUSB_ERROR_INVALID_PARAM;
1713 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1714 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1715 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1717 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1718 free (tpriv->isoc_framelist);
1719 tpriv->isoc_framelist = NULL;
1723 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1724 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1725 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1726 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1727 struct darwin_msg_async_io_complete message = {.itransfer = itransfer, .result = result,
1728 .size = (UInt32) (uintptr_t) arg0};
1730 usbi_dbg ("an async io operation has completed");
1732 /* if requested write a zero packet */
1733 if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
1734 struct darwin_interface *cInterface;
1735 uint8_t iface, pipeRef;
1737 (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface);
1738 cInterface = &priv->interfaces[iface];
1740 (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
1743 /* send a completion message to the device's file descriptor */
1744 write (priv->fds[1], &message, sizeof (message));
1747 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1748 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT)
1749 result = kIOUSBTransactionTimeout;
1752 case kIOReturnUnderrun:
1753 case kIOReturnSuccess:
1754 return LIBUSB_TRANSFER_COMPLETED;
1755 case kIOReturnAborted:
1756 return LIBUSB_TRANSFER_CANCELLED;
1757 case kIOUSBPipeStalled:
1758 usbi_dbg ("transfer error: pipe is stalled");
1759 return LIBUSB_TRANSFER_STALL;
1760 case kIOReturnOverrun:
1761 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1762 return LIBUSB_TRANSFER_OVERFLOW;
1763 case kIOUSBTransactionTimeout:
1764 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1765 itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
1766 return LIBUSB_TRANSFER_TIMED_OUT;
1768 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1769 return LIBUSB_TRANSFER_ERROR;
1773 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1774 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1775 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1776 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1777 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1778 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1779 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1782 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1783 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1787 usbi_dbg ("handling %s completion with kernel status %d",
1788 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
1790 if (kIOReturnSuccess == result || kIOReturnUnderrun == result) {
1791 if (isIsoc && tpriv->isoc_framelist) {
1792 /* copy isochronous results back */
1794 for (i = 0; i < transfer->num_iso_packets ; i++) {
1795 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1796 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1797 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1800 itransfer->transferred += io_size;
1803 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1804 usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
1807 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready) {
1808 struct darwin_msg_async_io_complete message;
1809 POLL_NFDS_TYPE i = 0;
1812 usbi_mutex_lock(&ctx->open_devs_lock);
1814 for (i = 0; i < nfds && num_ready > 0; i++) {
1815 struct pollfd *pollfd = &fds[i];
1817 usbi_dbg ("checking fd %i with revents = %x", pollfd->fd, pollfd->revents);
1819 if (!pollfd->revents)
1824 if (pollfd->revents & POLLERR) {
1825 /* this probably will never happen so ignore the error an move on. */
1829 /* there is only one type of message */
1830 ret = read (pollfd->fd, &message, sizeof (message));
1831 if (ret < (ssize_t) sizeof (message)) {
1832 usbi_dbg ("WARNING: short read on async io completion pipe\n");
1836 darwin_handle_callback (message.itransfer, message.result, message.size);
1839 usbi_mutex_unlock(&ctx->open_devs_lock);
1844 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1845 mach_timespec_t sys_time;
1846 clock_serv_t clock_ref;
1849 case USBI_CLOCK_REALTIME:
1850 /* CLOCK_REALTIME represents time since the epoch */
1851 clock_ref = clock_realtime;
1853 case USBI_CLOCK_MONOTONIC:
1854 /* use system boot time as reference for the monotonic clock */
1855 clock_ref = clock_monotonic;
1858 return LIBUSB_ERROR_INVALID_PARAM;
1861 clock_get_time (clock_ref, &sys_time);
1863 tp->tv_sec = sys_time.tv_sec;
1864 tp->tv_nsec = sys_time.tv_nsec;
1869 const struct usbi_os_backend darwin_backend = {
1872 .init = darwin_init,
1873 .exit = darwin_exit,
1874 .get_device_list = NULL, /* not needed */
1875 .get_device_descriptor = darwin_get_device_descriptor,
1876 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1877 .get_config_descriptor = darwin_get_config_descriptor,
1879 .open = darwin_open,
1880 .close = darwin_close,
1881 .get_configuration = darwin_get_configuration,
1882 .set_configuration = darwin_set_configuration,
1883 .claim_interface = darwin_claim_interface,
1884 .release_interface = darwin_release_interface,
1886 .set_interface_altsetting = darwin_set_interface_altsetting,
1887 .clear_halt = darwin_clear_halt,
1888 .reset_device = darwin_reset_device,
1890 .kernel_driver_active = darwin_kernel_driver_active,
1891 .detach_kernel_driver = darwin_detach_kernel_driver,
1892 .attach_kernel_driver = darwin_attach_kernel_driver,
1894 .destroy_device = darwin_destroy_device,
1896 .submit_transfer = darwin_submit_transfer,
1897 .cancel_transfer = darwin_cancel_transfer,
1898 .clear_transfer_priv = darwin_clear_transfer_priv,
1900 .handle_events = op_handle_events,
1902 .clock_gettime = darwin_clock_gettime,
1904 .device_priv_size = sizeof(struct darwin_device_priv),
1905 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1906 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1907 .add_iso_packet_size = 0,