2 * darwin backend for libusb 1.0
3 * Copyright (C) 2008-2010 Nathan Hjelm <hjelmn@users.sourceforge.net>
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29 #include <sys/ioctl.h>
31 #include <sys/types.h>
34 #include <mach/clock.h>
35 #include <mach/clock_types.h>
36 #include <mach/mach_host.h>
37 #include <mach/mach_port.h>
39 #include <AvailabilityMacros.h>
40 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
41 #include <objc/objc-auto.h>
44 #include <IOKit/IOCFBundle.h>
45 #include <IOKit/usb/IOUSBLib.h>
46 #include <IOKit/IOCFPlugIn.h>
48 #include "darwin_usb.h"
50 static mach_port_t libusb_darwin_mp = 0; /* master port */
51 static CFRunLoopRef libusb_darwin_acfl = NULL; /* async cf loop */
52 static int initCount = 0;
54 /* async event thread */
55 static pthread_t libusb_darwin_at;
57 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
58 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
59 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
60 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
61 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
63 static const char *darwin_error_str (int result) {
65 case kIOReturnSuccess:
67 case kIOReturnNotOpen:
68 return "device not opened for exclusive access";
69 case kIOReturnNoDevice:
70 return "no connection to an IOService";
71 case kIOUSBNoAsyncPortErr:
72 return "no async port has been opened for interface";
73 case kIOReturnExclusiveAccess:
74 return "another process has device opened for exclusive access";
75 case kIOUSBPipeStalled:
76 return "pipe is stalled";
78 return "could not establish a connection to the Darwin kernel";
79 case kIOUSBTransactionTimeout:
80 return "transaction timed out";
81 case kIOReturnBadArgument:
82 return "invalid argument";
83 case kIOReturnAborted:
84 return "transaction aborted";
85 case kIOReturnNotResponding:
86 return "device not responding";
87 case kIOReturnOverrun:
88 return "data overrun";
89 case kIOReturnCannotWire:
90 return "physical memory can not be wired down";
92 return "unknown error";
96 static int darwin_to_libusb (int result) {
98 case kIOReturnUnderrun:
99 case kIOReturnSuccess:
100 return LIBUSB_SUCCESS;
101 case kIOReturnNotOpen:
102 case kIOReturnNoDevice:
103 return LIBUSB_ERROR_NO_DEVICE;
104 case kIOReturnExclusiveAccess:
105 return LIBUSB_ERROR_ACCESS;
106 case kIOUSBPipeStalled:
107 return LIBUSB_ERROR_PIPE;
108 case kIOReturnBadArgument:
109 return LIBUSB_ERROR_INVALID_PARAM;
110 case kIOUSBTransactionTimeout:
111 return LIBUSB_ERROR_TIMEOUT;
112 case kIOReturnNotResponding:
113 case kIOReturnAborted:
115 case kIOUSBNoAsyncPortErr:
117 return LIBUSB_ERROR_OTHER;
122 static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp) {
123 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
125 /* current interface */
126 struct __darwin_interface *cInterface;
130 usbi_info (HANDLE_CTX(dev_handle), "converting ep address 0x%02x to pipeRef and interface", ep);
132 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
133 cInterface = &priv->interfaces[iface];
135 if (dev_handle->claimed_interfaces & (1 << iface)) {
136 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
137 if (cInterface->endpoint_addrs[i] == ep) {
140 usbi_info (HANDLE_CTX(dev_handle), "pipe %d on interface %d matches", *pipep, *ifcp);
147 /* No pipe found with the correct endpoint address */
148 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
153 static int usb_setup_device_iterator (io_iterator_t *deviceIterator) {
154 return IOServiceGetMatchingServices(libusb_darwin_mp, IOServiceMatching(kIOUSBDeviceClassName), deviceIterator);
157 static usb_device_t **usb_get_next_device (io_iterator_t deviceIterator, UInt32 *locationp) {
158 io_cf_plugin_ref_t *plugInInterface = NULL;
159 usb_device_t **device;
160 io_service_t usbDevice;
164 if (!IOIteratorIsValid (deviceIterator))
168 while ((usbDevice = IOIteratorNext(deviceIterator))) {
169 result = IOCreatePlugInInterfaceForService(usbDevice, kIOUSBDeviceUserClientTypeID,
170 kIOCFPlugInInterfaceID, &plugInInterface,
172 if (kIOReturnSuccess == result && plugInInterface)
175 usbi_dbg ("libusb/darwin.c usb_get_next_device: could not set up plugin for service: %s\n", darwin_error_str (result));
181 (void)IOObjectRelease(usbDevice);
182 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
185 (*plugInInterface)->Stop(plugInInterface);
186 IODestroyPlugInInterface (plugInInterface);
188 /* get the location from the device */
190 (*(device))->GetLocationID(device, locationp);
195 static kern_return_t darwin_get_device (uint32_t dev_location, usb_device_t ***darwin_device) {
196 kern_return_t kresult;
198 io_iterator_t deviceIterator;
200 kresult = usb_setup_device_iterator (&deviceIterator);
204 /* This port of libusb uses locations to keep track of devices. */
205 while ((*darwin_device = usb_get_next_device (deviceIterator, &location)) != NULL) {
206 if (location == dev_location)
209 (**darwin_device)->Release(*darwin_device);
212 IOObjectRelease (deviceIterator);
214 if (!(*darwin_device))
215 return kIOReturnNoDevice;
217 return kIOReturnSuccess;
222 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
223 struct libusb_context *ctx = (struct libusb_context *)ptr;
224 struct libusb_device_handle *handle;
225 struct darwin_device_priv *dpriv;
226 struct darwin_device_handle_priv *priv;
231 CFTypeRef locationCF;
234 usbi_info (ctx, "a device has been detached");
236 while ((device = IOIteratorNext (rem_devices)) != 0) {
237 /* get the location from the i/o registry */
238 locationCF = IORegistryEntryCreateCFProperty (device, CFSTR(kUSBDevicePropertyLocationID), kCFAllocatorDefault, 0);
240 IOObjectRelease (device);
245 locationValid = CFGetTypeID(locationCF) == CFNumberGetTypeID() &&
246 CFNumberGetValue(locationCF, kCFNumberLongType, &location);
248 CFRelease (locationCF);
253 usbi_mutex_lock(&ctx->open_devs_lock);
254 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
255 dpriv = (struct darwin_device_priv *)handle->dev->os_priv;
257 /* the device may have been opened several times. write to each handle's event descriptor */
258 if (dpriv->location == location && handle->os_priv) {
259 priv = (struct darwin_device_handle_priv *)handle->os_priv;
261 message = MESSAGE_DEVICE_GONE;
262 write (priv->fds[1], &message, sizeof (message));
266 usbi_mutex_unlock(&ctx->open_devs_lock);
270 static void darwin_clear_iterator (io_iterator_t iter) {
273 while ((device = IOIteratorNext (iter)) != 0)
274 IOObjectRelease (device);
277 static void *event_thread_main (void *arg0) {
279 struct libusb_context *ctx = (struct libusb_context *)arg0;
280 CFRunLoopRef runloop;
282 /* Tell the Objective-C garbage collector about this thread.
283 This is required because, unlike NSThreads, pthreads are
284 not automatically registered. Although we don't use
285 Objective-C, we use CoreFoundation, which does. */
286 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
287 objc_registerThreadWithCollector();
290 /* hotplug (device removal) source */
291 CFRunLoopSourceRef libusb_notification_cfsource;
292 io_notification_port_t libusb_notification_port;
293 io_iterator_t libusb_rem_device_iterator;
295 usbi_info (ctx, "creating hotplug event source");
297 runloop = CFRunLoopGetCurrent ();
300 /* add the notification port to the run loop */
301 libusb_notification_port = IONotificationPortCreate (libusb_darwin_mp);
302 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
303 CFRunLoopAddSource(CFRunLoopGetCurrent (), libusb_notification_cfsource, kCFRunLoopDefaultMode);
305 /* create notifications for removed devices */
306 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
307 IOServiceMatching(kIOUSBDeviceClassName),
308 (IOServiceMatchingCallback)darwin_devices_detached,
309 (void *)ctx, &libusb_rem_device_iterator);
311 if (kresult != kIOReturnSuccess) {
312 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
318 darwin_clear_iterator (libusb_rem_device_iterator);
320 /* let the main thread know about the async runloop */
321 libusb_darwin_acfl = CFRunLoopGetCurrent ();
323 usbi_info (ctx, "thread ready to receive events");
325 /* run the runloop */
328 usbi_info (ctx, "thread exiting");
330 /* delete notification port */
331 CFRunLoopSourceInvalidate (libusb_notification_cfsource);
332 IONotificationPortDestroy (libusb_notification_port);
336 libusb_darwin_acfl = NULL;
341 static int darwin_init(struct libusb_context *ctx) {
344 if (!(initCount++)) {
345 /* Create the master port for talking to IOKit */
346 if (!libusb_darwin_mp) {
347 kresult = IOMasterPort (MACH_PORT_NULL, &libusb_darwin_mp);
349 if (kresult != kIOReturnSuccess || !libusb_darwin_mp)
350 return darwin_to_libusb (kresult);
353 pthread_create (&libusb_darwin_at, NULL, event_thread_main, (void *)ctx);
355 while (!libusb_darwin_acfl)
362 static void darwin_exit (void) {
363 if (!(--initCount)) {
365 /* stop the async runloop */
366 CFRunLoopStop (libusb_darwin_acfl);
367 pthread_join (libusb_darwin_at, NULL);
369 if (libusb_darwin_mp)
370 mach_port_deallocate(mach_task_self(), libusb_darwin_mp);
372 libusb_darwin_mp = 0;
376 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
377 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
379 /* return cached copy */
380 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
387 static int get_configuration_index (struct libusb_device *dev, int config_value) {
388 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
390 IOUSBConfigurationDescriptorPtr desc;
393 /* is there a simpler way to determine the index? */
394 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
395 if (kresult != kIOReturnSuccess)
396 return darwin_to_libusb (kresult);
398 for (i = 0 ; i < numConfig ; i++) {
399 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
401 if (desc->bConfigurationValue == config_value)
405 /* configuration not found */
406 return LIBUSB_ERROR_OTHER;
409 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
410 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
413 if (0 == priv->active_config)
414 return LIBUSB_ERROR_INVALID_PARAM;
416 config_index = get_configuration_index (dev, priv->active_config);
417 if (config_index < 0)
420 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
423 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
424 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
425 IOUSBConfigurationDescriptorPtr desc;
427 usb_device_t **device = NULL;
430 return LIBUSB_ERROR_OTHER;
433 kresult = darwin_get_device (priv->location, &device);
434 if (kresult || !device) {
435 usbi_err (DEVICE_CTX (dev), "could not find device: %s", darwin_error_str (kresult));
437 return darwin_to_libusb (kresult);
440 /* don't have to open the device to get a config descriptor */
442 device = priv->device;
444 kresult = (*device)->GetConfigurationDescriptorPtr (device, config_index, &desc);
445 if (kresult == kIOReturnSuccess) {
446 /* copy descriptor */
447 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
448 len = libusb_le16_to_cpu(desc->wTotalLength);
450 memmove (buffer, desc, len);
452 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
457 (*device)->Release (device);
459 return darwin_to_libusb (kresult);
462 /* check whether the os has configured the device */
463 static int darwin_check_configuration (struct libusb_context *ctx, struct libusb_device *dev, usb_device_t **darwin_device) {
464 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
466 IOUSBConfigurationDescriptorPtr configDesc;
467 IOUSBFindInterfaceRequest request;
468 kern_return_t kresult;
469 io_iterator_t interface_iterator;
470 io_service_t firstInterface;
472 if (priv->dev_descriptor.bNumConfigurations < 1) {
473 usbi_err (ctx, "device has no configurations");
474 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
477 /* find the first configuration */
478 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
479 priv->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
481 /* check if the device is already configured. there is probably a better way than iterating over the
482 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
483 might lock up on the device request) */
485 /* Setup the Interface Request */
486 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
487 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
488 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
489 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
491 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
493 return darwin_to_libusb (kresult);
496 firstInterface = IOIteratorNext(interface_iterator);
498 /* done with the interface iterator */
499 IOObjectRelease(interface_iterator);
501 if (firstInterface) {
502 IOObjectRelease (firstInterface);
504 /* device is configured */
505 if (priv->dev_descriptor.bNumConfigurations == 1)
506 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
507 priv->active_config = priv->first_config;
509 /* devices with more than one configuration should work with GetConfiguration */
510 (*darwin_device)->GetConfiguration (darwin_device, &priv->active_config);
513 priv->active_config = 0;
515 usbi_info (ctx, "active config: %u, first config: %u", priv->active_config, priv->first_config);
520 static int process_new_device (struct libusb_context *ctx, usb_device_t **device, UInt32 locationID, struct discovered_devs **_discdevs) {
521 struct darwin_device_priv *priv;
522 struct libusb_device *dev;
523 struct discovered_devs *discdevs;
524 UInt16 address, idVendor, idProduct;
525 UInt8 bDeviceClass, bDeviceSubClass;
527 int ret = 0, need_unref = 0;
530 dev = usbi_get_device_by_session_id(ctx, locationID);
532 usbi_info (ctx, "allocating new device for location 0x%08x", locationID);
533 dev = usbi_alloc_device(ctx, locationID);
536 usbi_info (ctx, "using existing device for location 0x%08x", locationID);
539 ret = LIBUSB_ERROR_NO_MEM;
543 priv = (struct darwin_device_priv *)dev->os_priv;
545 /* Set up request for device descriptor */
546 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
547 req.bRequest = kUSBRqGetDescriptor;
548 req.wValue = kUSBDeviceDesc << 8;
550 req.wLength = sizeof(IOUSBDeviceDescriptor);
551 req.pData = &(priv->dev_descriptor);
553 (*(device))->GetDeviceAddress (device, (USBDeviceAddress *)&address);
554 (*(device))->GetDeviceProduct (device, &idProduct);
555 (*(device))->GetDeviceVendor (device, &idVendor);
556 (*(device))->GetDeviceClass (device, &bDeviceClass);
557 (*(device))->GetDeviceSubClass (device, &bDeviceSubClass);
559 /**** retrieve device descriptors ****/
560 /* according to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
561 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request */
562 ret = (*(device))->DeviceRequest (device, &req);
563 if (ret != kIOReturnSuccess) {
564 int try_unsuspend = 1;
565 #if DeviceVersion >= 320
568 /* device may be suspended. unsuspend it and try again */
569 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
570 (void)(*device)->GetUSBDeviceInformation (device, &info);
572 try_unsuspend = info & (1 << kUSBInformationDeviceIsSuspendedBit);
575 /* the device should be open before to device is unsuspended */
576 (void) (*device)->USBDeviceOpenSeize(device);
579 /* resume the device */
580 (void)(*device)->USBDeviceSuspend (device, 0);
582 ret = (*(device))->DeviceRequest (device, &req);
584 /* resuspend the device */
585 (void)(*device)->USBDeviceSuspend (device, 1);
588 (*device)->USBDeviceClose (device);
591 if (ret != kIOReturnSuccess) {
592 usbi_warn (ctx, "could not retrieve device descriptor: %s. skipping device", darwin_error_str (ret));
597 /**** end: retrieve device descriptors ****/
599 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
600 if (libusb_le16_to_cpu (priv->dev_descriptor.idProduct) != idProduct) {
601 /* not a valid device */
602 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
603 idProduct, libusb_le16_to_cpu (priv->dev_descriptor.idProduct));
608 dev->bus_number = locationID >> 24;
609 dev->device_address = address;
611 /* check current active configuration (and cache the first configuration value-- which may be used by claim_interface) */
612 ret = darwin_check_configuration (ctx, dev, device);
616 /* save our location, we'll need this later */
617 priv->location = locationID;
618 snprintf(priv->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", address, idVendor, idProduct, bDeviceClass, bDeviceSubClass);
620 ret = usbi_sanitize_device (dev);
624 /* append the device to the list of discovered devices */
625 discdevs = discovered_devs_append(*_discdevs, dev);
627 ret = LIBUSB_ERROR_NO_MEM;
631 *_discdevs = discdevs;
633 usbi_info (ctx, "found device with address %d at %s", dev->device_address, priv->sys_path);
637 libusb_unref_device(dev);
642 static int darwin_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs) {
643 io_iterator_t deviceIterator;
644 usb_device_t **device;
645 kern_return_t kresult;
648 if (!libusb_darwin_mp)
649 return LIBUSB_ERROR_INVALID_PARAM;
651 kresult = usb_setup_device_iterator (&deviceIterator);
652 if (kresult != kIOReturnSuccess)
653 return darwin_to_libusb (kresult);
655 while ((device = usb_get_next_device (deviceIterator, &location)) != NULL) {
656 (void) process_new_device (ctx, device, location, _discdevs);
658 (*(device))->Release(device);
661 IOObjectRelease(deviceIterator);
666 static int darwin_open (struct libusb_device_handle *dev_handle) {
667 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
668 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
669 usb_device_t **darwin_device;
672 if (0 == dpriv->open_count) {
673 kresult = darwin_get_device (dpriv->location, &darwin_device);
675 usbi_err (HANDLE_CTX (dev_handle), "could not find device: %s", darwin_error_str (kresult));
676 return darwin_to_libusb (kresult);
679 dpriv->device = darwin_device;
681 /* try to open the device */
682 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
684 if (kresult != kIOReturnSuccess) {
685 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
688 case kIOReturnExclusiveAccess:
689 /* it is possible to perform some actions on a device that is not open so do not return an error */
694 (*(dpriv->device))->Release (dpriv->device);
695 dpriv->device = NULL;
696 return darwin_to_libusb (kresult);
699 /* create async event source */
700 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
701 if (kresult != kIOReturnSuccess) {
702 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
704 (*(dpriv->device))->USBDeviceClose (dpriv->device);
705 (*(dpriv->device))->Release (dpriv->device);
707 dpriv->device = NULL;
708 return darwin_to_libusb (kresult);
713 CFRetain (libusb_darwin_acfl);
715 /* add the cfSource to the aync run loop */
716 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
720 /* device opened successfully */
723 /* create a file descriptor for notifications */
726 /* set the pipe to be non-blocking */
727 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
729 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
731 usbi_info (HANDLE_CTX (dev_handle), "device open for access");
736 static void darwin_close (struct libusb_device_handle *dev_handle) {
737 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
738 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
742 if (dpriv->open_count == 0) {
743 /* something is probably very wrong if this is the case */
744 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
750 /* make sure all interfaces are released */
751 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
752 if (dev_handle->claimed_interfaces & (1 << i))
753 libusb_release_interface (dev_handle, i);
755 if (0 == dpriv->open_count) {
757 /* delete the device's async event source */
758 if (priv->cfSource) {
759 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
760 CFRelease (priv->cfSource);
763 /* close the device */
764 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
766 /* Log the fact that we had a problem closing the file, however failing a
767 * close isn't really an error, so return success anyway */
768 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
772 kresult = (*(dpriv->device))->Release(dpriv->device);
774 /* Log the fact that we had a problem closing the file, however failing a
775 * close isn't really an error, so return success anyway */
776 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
779 dpriv->device = NULL;
782 /* file descriptors are maintained per-instance */
783 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
784 close (priv->fds[1]);
785 close (priv->fds[0]);
787 priv->fds[0] = priv->fds[1] = -1;
790 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
791 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
793 *config = (int) dpriv->active_config;
798 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
799 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
803 /* Setting configuration will invalidate the interface, so we need
804 to reclaim it. First, dispose of existing interfaces, if any. */
805 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
806 if (dev_handle->claimed_interfaces & (1 << i))
807 darwin_release_interface (dev_handle, i);
809 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
810 if (kresult != kIOReturnSuccess)
811 return darwin_to_libusb (kresult);
813 /* Reclaim any interfaces. */
814 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
815 if (dev_handle->claimed_interfaces & (1 << i))
816 darwin_claim_interface (dev_handle, i);
818 dpriv->active_config = config;
823 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
824 IOUSBFindInterfaceRequest request;
825 uint8_t current_interface;
826 kern_return_t kresult;
827 io_iterator_t interface_iterator;
829 *usbInterfacep = IO_OBJECT_NULL;
831 /* Setup the Interface Request */
832 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
833 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
834 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
835 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
837 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
841 for ( current_interface = 0 ; current_interface <= ifc ; current_interface++ ) {
842 *usbInterfacep = IOIteratorNext(interface_iterator);
843 if (current_interface != ifc)
844 (void) IOObjectRelease (*usbInterfacep);
847 /* done with the interface iterator */
848 IOObjectRelease(interface_iterator);
853 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
854 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
856 /* current interface */
857 struct __darwin_interface *cInterface = &priv->interfaces[iface];
859 kern_return_t kresult;
861 u_int8_t numep, direction, number;
862 u_int8_t dont_care1, dont_care3;
863 u_int16_t dont_care2;
866 usbi_info (HANDLE_CTX (dev_handle), "building table of endpoints.");
868 /* retrieve the total number of endpoints on this interface */
869 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
871 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
872 return darwin_to_libusb (kresult);
875 /* iterate through pipe references */
876 for (i = 1 ; i <= numep ; i++) {
877 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
878 &dont_care2, &dont_care3);
880 if (kresult != kIOReturnSuccess) {
881 usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
883 return darwin_to_libusb (kresult);
886 usbi_info (HANDLE_CTX (dev_handle), "interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
888 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
891 cInterface->num_endpoints = numep;
896 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
897 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
898 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
899 io_service_t usbInterface = IO_OBJECT_NULL;
901 IOCFPlugInInterface **plugInInterface = NULL;
904 /* current interface */
905 struct __darwin_interface *cInterface = &priv->interfaces[iface];
907 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
908 if (kresult != kIOReturnSuccess)
909 return darwin_to_libusb (kresult);
911 /* make sure we have an interface */
912 if (!usbInterface && dpriv->first_config != 0) {
913 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
915 /* set the configuration */
916 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
917 if (kresult != LIBUSB_SUCCESS) {
918 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
922 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
924 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
925 return darwin_to_libusb (kresult);
930 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
931 return LIBUSB_ERROR_NOT_FOUND;
934 /* get an interface to the device's interface */
935 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
936 kIOCFPlugInInterfaceID, &plugInInterface, &score);
938 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
939 return darwin_to_libusb (kresult);
942 if (!plugInInterface) {
943 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
944 return LIBUSB_ERROR_NOT_FOUND;
947 /* ignore release error */
948 (void)IOObjectRelease (usbInterface);
950 /* Do the actual claim */
951 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
952 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
953 (LPVOID)&cInterface->interface);
954 if (kresult || !cInterface->interface) {
955 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
956 return darwin_to_libusb (kresult);
959 /* We no longer need the intermediate plug-in */
960 (*plugInInterface)->Release(plugInInterface);
962 /* claim the interface */
963 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
965 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
966 return darwin_to_libusb (kresult);
969 /* update list of endpoints */
970 kresult = get_endpoints (dev_handle, iface);
972 /* this should not happen */
973 darwin_release_interface (dev_handle, iface);
974 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
978 cInterface->cfSource = NULL;
980 /* create async event source */
981 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
982 if (kresult != kIOReturnSuccess) {
983 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
985 /* can't continue without an async event source */
986 (void)darwin_release_interface (dev_handle, iface);
988 return darwin_to_libusb (kresult);
991 /* add the cfSource to the async thread's run loop */
992 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
994 usbi_info (HANDLE_CTX (dev_handle), "interface opened");
999 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1000 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1003 /* current interface */
1004 struct __darwin_interface *cInterface = &priv->interfaces[iface];
1006 /* Check to see if an interface is open */
1007 if (!cInterface->interface)
1008 return LIBUSB_SUCCESS;
1010 /* clean up endpoint data */
1011 cInterface->num_endpoints = 0;
1013 /* delete the interface's async event source */
1014 if (cInterface->cfSource) {
1015 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1016 CFRelease (cInterface->cfSource);
1019 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1021 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1023 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1024 if (kresult != kIOReturnSuccess)
1025 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1027 cInterface->interface = IO_OBJECT_NULL;
1029 return darwin_to_libusb (kresult);
1032 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1033 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1036 /* current interface */
1037 struct __darwin_interface *cInterface = &priv->interfaces[iface];
1039 if (!cInterface->interface)
1040 return LIBUSB_ERROR_NO_DEVICE;
1042 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1043 if (kresult != kIOReturnSuccess)
1044 darwin_reset_device (dev_handle);
1046 /* update list of endpoints */
1047 kresult = get_endpoints (dev_handle, iface);
1049 /* this should not happen */
1050 darwin_release_interface (dev_handle, iface);
1051 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1055 return darwin_to_libusb (kresult);
1058 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1059 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1061 /* current interface */
1062 struct __darwin_interface *cInterface;
1063 uint8_t pipeRef, iface;
1066 /* determine the interface/endpoint to use */
1067 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
1068 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1070 return LIBUSB_ERROR_NOT_FOUND;
1073 cInterface = &priv->interfaces[iface];
1075 #if (InterfaceVersion < 190)
1076 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1078 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1079 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1082 usbi_err (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1084 return darwin_to_libusb (kresult);
1087 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1088 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1091 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1093 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1095 return darwin_to_libusb (kresult);
1098 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1099 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1100 io_service_t usbInterface;
1104 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1106 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1108 return darwin_to_libusb (kresult);
1111 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1112 IOObjectRelease (usbInterface);
1124 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1125 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1126 return LIBUSB_ERROR_NOT_SUPPORTED;
1129 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1130 return LIBUSB_ERROR_NOT_SUPPORTED;
1133 static void darwin_destroy_device(struct libusb_device *dev) {
1136 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1137 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1138 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1141 uint8_t is_read; /* 0 = we're reading, 1 = we're writing */
1142 uint8_t transferType;
1143 /* None of the values below are used in libusb for bulk transfers */
1144 uint8_t direction, number, interval, pipeRef, iface;
1145 uint16_t maxPacketSize;
1147 struct __darwin_interface *cInterface;
1149 /* are we reading or writing? */
1150 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1152 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1153 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1155 return LIBUSB_ERROR_NOT_FOUND;
1158 cInterface = &priv->interfaces[iface];
1160 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1161 &transferType, &maxPacketSize, &interval);
1163 /* submit the request */
1164 /* timeouts are unavailable on interrupt endpoints */
1165 if (transferType == kUSBInterrupt) {
1167 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1168 transfer->length, darwin_async_io_callback, itransfer);
1170 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1171 transfer->length, darwin_async_io_callback, itransfer);
1173 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1176 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1177 transfer->length, transfer->timeout, transfer->timeout,
1178 darwin_async_io_callback, (void *)itransfer);
1180 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1181 transfer->length, transfer->timeout, transfer->timeout,
1182 darwin_async_io_callback, (void *)itransfer);
1186 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", is_read ? "In" : "Out",
1187 darwin_error_str(ret), ret);
1189 return darwin_to_libusb (ret);
1192 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1193 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1194 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1195 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1198 uint8_t is_read; /* 0 = we're writing, 1 = we're reading */
1199 uint8_t pipeRef, iface;
1201 AbsoluteTime atTime;
1204 struct __darwin_interface *cInterface;
1206 /* are we reading or writing? */
1207 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1209 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1210 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1211 free(tpriv->isoc_framelist);
1212 tpriv->isoc_framelist = NULL;
1215 if (!tpriv->isoc_framelist) {
1216 tpriv->num_iso_packets = transfer->num_iso_packets;
1217 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1218 if (!tpriv->isoc_framelist)
1219 return LIBUSB_ERROR_NO_MEM;
1222 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1223 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1224 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1226 /* determine the interface/endpoint to use */
1227 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1228 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1230 return LIBUSB_ERROR_NOT_FOUND;
1233 cInterface = &priv->interfaces[iface];
1235 /* Last but not least we need the bus frame number */
1236 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1238 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1239 free(tpriv->isoc_framelist);
1240 tpriv->isoc_framelist = NULL;
1242 return darwin_to_libusb (kresult);
1245 /* schedule for a frame a little in the future */
1248 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1249 frame = cInterface->frames[transfer->endpoint];
1251 /* submit the request */
1253 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1254 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1257 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1258 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1261 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets / 8;
1263 if (kresult != kIOReturnSuccess) {
1264 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", is_read ? "In" : "Out",
1265 darwin_error_str(kresult));
1266 free (tpriv->isoc_framelist);
1267 tpriv->isoc_framelist = NULL;
1270 return darwin_to_libusb (kresult);
1273 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1274 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1275 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1276 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1277 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1278 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1282 bzero(&tpriv->req, sizeof(tpriv->req));
1284 /* IOUSBDeviceInterface expects the request in cpu endianess */
1285 tpriv->req.bmRequestType = setup->bmRequestType;
1286 tpriv->req.bRequest = setup->bRequest;
1287 /* these values should be in bus order from libusb_fill_control_setup */
1288 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1289 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1290 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1291 /* data is stored after the libusb control block */
1292 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1293 tpriv->req.completionTimeout = transfer->timeout;
1294 tpriv->req.noDataTimeout = transfer->timeout;
1296 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1298 /* all transfers in libusb-1.0 are async */
1300 if (transfer->endpoint) {
1301 struct __darwin_interface *cInterface;
1302 uint8_t pipeRef, iface;
1304 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1305 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1307 return LIBUSB_ERROR_NOT_FOUND;
1310 cInterface = &priv->interfaces[iface];
1312 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1314 /* control request on endpoint 0 */
1315 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1317 if (kresult != kIOReturnSuccess)
1318 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1320 return darwin_to_libusb (kresult);
1323 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1324 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1326 switch (transfer->type) {
1327 case LIBUSB_TRANSFER_TYPE_CONTROL:
1328 return submit_control_transfer(itransfer);
1329 case LIBUSB_TRANSFER_TYPE_BULK:
1330 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1331 return submit_bulk_transfer(itransfer);
1332 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1333 return submit_iso_transfer(itransfer);
1335 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1336 return LIBUSB_ERROR_INVALID_PARAM;
1340 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1341 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1342 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1345 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions control pipe");
1347 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1349 return darwin_to_libusb (kresult);
1352 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1353 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1354 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1355 struct __darwin_interface *cInterface;
1356 uint8_t pipeRef, iface;
1359 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1360 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1362 return LIBUSB_ERROR_NOT_FOUND;
1365 cInterface = &priv->interfaces[iface];
1367 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions on interface %d pipe %d", iface, pipeRef);
1369 /* abort transactions */
1370 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1372 usbi_info (ITRANSFER_CTX (itransfer), "calling clear pipe stall to clear the data toggle bit");
1374 /* clear the data toggle bit */
1375 #if (InterfaceVersion < 190)
1376 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1378 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1379 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1382 return darwin_to_libusb (kresult);
1385 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1386 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1388 switch (transfer->type) {
1389 case LIBUSB_TRANSFER_TYPE_CONTROL:
1390 return cancel_control_transfer(itransfer);
1391 case LIBUSB_TRANSFER_TYPE_BULK:
1392 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1393 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1394 return darwin_abort_transfers (itransfer);
1396 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1397 return LIBUSB_ERROR_INVALID_PARAM;
1401 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1402 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1403 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1405 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1406 free (tpriv->isoc_framelist);
1407 tpriv->isoc_framelist = NULL;
1411 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1412 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1413 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1414 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1417 usbi_info (ITRANSFER_CTX (itransfer), "an async io operation has completed");
1419 /* send a completion message to the device's file descriptor */
1420 message = MESSAGE_ASYNC_IO_COMPLETE;
1421 write (priv->fds[1], &message, sizeof (message));
1422 write (priv->fds[1], &itransfer, sizeof (itransfer));
1423 write (priv->fds[1], &result, sizeof (IOReturn));
1424 write (priv->fds[1], &arg0, sizeof (UInt32));
1427 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1428 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT)
1429 result = kIOUSBTransactionTimeout;
1432 case kIOReturnUnderrun:
1433 case kIOReturnSuccess:
1434 return LIBUSB_TRANSFER_COMPLETED;
1435 case kIOReturnAborted:
1436 return LIBUSB_TRANSFER_CANCELLED;
1437 case kIOUSBPipeStalled:
1438 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: pipe is stalled");
1439 return LIBUSB_TRANSFER_STALL;
1440 case kIOReturnOverrun:
1441 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1442 return LIBUSB_TRANSFER_OVERFLOW;
1443 case kIOUSBTransactionTimeout:
1444 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1445 itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
1446 return LIBUSB_TRANSFER_TIMED_OUT;
1448 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1449 return LIBUSB_TRANSFER_ERROR;
1453 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1454 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1455 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1456 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1457 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1458 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1459 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1462 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1463 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1467 usbi_info (ITRANSFER_CTX (itransfer), "handling %s completion with kernel status %d",
1468 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
1470 if (kIOReturnSuccess == result || kIOReturnUnderrun == result) {
1471 if (isIsoc && tpriv->isoc_framelist) {
1472 /* copy isochronous results back */
1474 for (i = 0; i < transfer->num_iso_packets ; i++) {
1475 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1476 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1477 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1480 itransfer->transferred += io_size;
1483 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1484 usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
1487 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready) {
1488 struct usbi_transfer *itransfer;
1494 usbi_mutex_lock(&ctx->open_devs_lock);
1495 for (i = 0; i < nfds && num_ready > 0; i++) {
1496 struct pollfd *pollfd = &fds[i];
1497 struct libusb_device_handle *handle;
1498 struct darwin_device_handle_priv *hpriv = NULL;
1500 usbi_info (ctx, "checking fd %i with revents = %x", fds[i], pollfd->revents);
1502 if (!pollfd->revents)
1506 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
1507 hpriv = (struct darwin_device_handle_priv *)handle->os_priv;
1508 if (hpriv->fds[0] == pollfd->fd)
1512 if (!(pollfd->revents & POLLERR)) {
1513 ret = read (hpriv->fds[0], &message, sizeof (message));
1514 if (ret < sizeof (message))
1517 /* could not poll the device-- response is to delete the device (this seems a little heavy-handed) */
1518 message = MESSAGE_DEVICE_GONE;
1521 case MESSAGE_DEVICE_GONE:
1522 /* remove the device's async port from the runloop */
1523 if (hpriv->cfSource) {
1524 if (libusb_darwin_acfl)
1525 CFRunLoopRemoveSource (libusb_darwin_acfl, hpriv->cfSource, kCFRunLoopDefaultMode);
1526 CFRelease (hpriv->cfSource);
1527 hpriv->cfSource = NULL;
1530 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1531 usbi_handle_disconnect(handle);
1533 /* done with this device */
1535 case MESSAGE_ASYNC_IO_COMPLETE:
1536 read (hpriv->fds[0], &itransfer, sizeof (itransfer));
1537 read (hpriv->fds[0], &kresult, sizeof (IOReturn));
1538 read (hpriv->fds[0], &io_size, sizeof (UInt32));
1540 darwin_handle_callback (itransfer, kresult, io_size);
1543 usbi_err (ctx, "unknown message received from device pipe");
1547 usbi_mutex_unlock(&ctx->open_devs_lock);
1552 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1553 mach_timespec_t sys_time;
1554 clock_serv_t clock_ref;
1557 case USBI_CLOCK_REALTIME:
1558 /* CLOCK_REALTIME represents time since the epoch */
1559 host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &clock_ref);
1561 case USBI_CLOCK_MONOTONIC:
1562 /* use system boot time as reference for the monotonic clock */
1563 host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &clock_ref);
1566 return LIBUSB_ERROR_INVALID_PARAM;
1569 clock_get_time (clock_ref, &sys_time);
1571 tp->tv_sec = sys_time.tv_sec;
1572 tp->tv_nsec = sys_time.tv_nsec;
1577 const struct usbi_os_backend darwin_backend = {
1579 .init = darwin_init,
1580 .exit = darwin_exit,
1581 .get_device_list = darwin_get_device_list,
1582 .get_device_descriptor = darwin_get_device_descriptor,
1583 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1584 .get_config_descriptor = darwin_get_config_descriptor,
1586 .open = darwin_open,
1587 .close = darwin_close,
1588 .get_configuration = darwin_get_configuration,
1589 .set_configuration = darwin_set_configuration,
1590 .claim_interface = darwin_claim_interface,
1591 .release_interface = darwin_release_interface,
1593 .set_interface_altsetting = darwin_set_interface_altsetting,
1594 .clear_halt = darwin_clear_halt,
1595 .reset_device = darwin_reset_device,
1597 .kernel_driver_active = darwin_kernel_driver_active,
1598 .detach_kernel_driver = darwin_detach_kernel_driver,
1599 .attach_kernel_driver = darwin_attach_kernel_driver,
1601 .destroy_device = darwin_destroy_device,
1603 .submit_transfer = darwin_submit_transfer,
1604 .cancel_transfer = darwin_cancel_transfer,
1605 .clear_transfer_priv = darwin_clear_transfer_priv,
1607 .handle_events = op_handle_events,
1609 .clock_gettime = darwin_clock_gettime,
1611 .device_priv_size = sizeof(struct darwin_device_priv),
1612 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1613 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1614 .add_iso_packet_size = 0,