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>
38 #include <mach/mach_port.h>
39 #include <IOKit/IOCFBundle.h>
40 #include <IOKit/usb/IOUSBLib.h>
41 #include <IOKit/IOCFPlugIn.h>
43 #include "darwin_usb.h"
45 static mach_port_t libusb_darwin_mp = 0; /* master port */
46 static CFRunLoopRef libusb_darwin_acfl = NULL; /* async cf loop */
47 static int initCount = 0;
49 /* async event thread */
50 static pthread_t libusb_darwin_at;
52 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
53 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
54 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
55 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
56 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
58 static const char *darwin_error_str (int result) {
60 case kIOReturnSuccess:
62 case kIOReturnNotOpen:
63 return "device not opened for exclusive access";
64 case kIOReturnNoDevice:
65 return "no connection to an IOService";
66 case kIOUSBNoAsyncPortErr:
67 return "no async port has been opened for interface";
68 case kIOReturnExclusiveAccess:
69 return "another process has device opened for exclusive access";
70 case kIOUSBPipeStalled:
71 return "pipe is stalled";
73 return "could not establish a connection to the Darwin kernel";
74 case kIOUSBTransactionTimeout:
75 return "transaction timed out";
76 case kIOReturnBadArgument:
77 return "invalid argument";
78 case kIOReturnAborted:
79 return "transaction aborted";
80 case kIOReturnNotResponding:
81 return "device not responding";
82 case kIOReturnOverrun:
83 return "data overrun";
84 case kIOReturnCannotWire:
85 return "physical memory can not be wired down";
87 return "unknown error";
91 static int darwin_to_libusb (int result) {
93 case kIOReturnUnderrun:
94 case kIOReturnSuccess:
95 return LIBUSB_SUCCESS;
96 case kIOReturnNotOpen:
97 case kIOReturnNoDevice:
98 return LIBUSB_ERROR_NO_DEVICE;
99 case kIOReturnExclusiveAccess:
100 return LIBUSB_ERROR_ACCESS;
101 case kIOUSBPipeStalled:
102 return LIBUSB_ERROR_PIPE;
103 case kIOReturnBadArgument:
104 return LIBUSB_ERROR_INVALID_PARAM;
105 case kIOUSBTransactionTimeout:
106 return LIBUSB_ERROR_TIMEOUT;
107 case kIOReturnNotResponding:
108 case kIOReturnAborted:
110 case kIOUSBNoAsyncPortErr:
112 return LIBUSB_ERROR_OTHER;
117 static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp) {
118 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
120 /* current interface */
121 struct __darwin_interface *cInterface;
125 usbi_info (HANDLE_CTX(dev_handle), "converting ep address 0x%02x to pipeRef and interface", ep);
127 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
128 cInterface = &priv->interfaces[iface];
130 if (dev_handle->claimed_interfaces & (1 << iface)) {
131 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
132 if (cInterface->endpoint_addrs[i] == ep) {
135 usbi_info (HANDLE_CTX(dev_handle), "pipe %d on interface %d matches", *pipep, *ifcp);
142 /* No pipe found with the correct endpoint address */
143 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
148 static int usb_setup_device_iterator (io_iterator_t *deviceIterator) {
149 return IOServiceGetMatchingServices(libusb_darwin_mp, IOServiceMatching(kIOUSBDeviceClassName), deviceIterator);
152 static usb_device_t **usb_get_next_device (io_iterator_t deviceIterator, UInt32 *locationp) {
153 io_cf_plugin_ref_t *plugInInterface = NULL;
154 usb_device_t **device;
155 io_service_t usbDevice;
159 if (!IOIteratorIsValid (deviceIterator))
163 while ((usbDevice = IOIteratorNext(deviceIterator))) {
164 result = IOCreatePlugInInterfaceForService(usbDevice, kIOUSBDeviceUserClientTypeID,
165 kIOCFPlugInInterfaceID, &plugInInterface,
167 if (kIOReturnSuccess == result && plugInInterface)
170 usbi_dbg ("libusb/darwin.c usb_get_next_device: could not set up plugin for service: %s\n", darwin_error_str (result));
176 (void)IOObjectRelease(usbDevice);
177 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
180 (*plugInInterface)->Stop(plugInInterface);
181 IODestroyPlugInInterface (plugInInterface);
183 /* get the location from the device */
185 (*(device))->GetLocationID(device, locationp);
190 static kern_return_t darwin_get_device (uint32_t dev_location, usb_device_t ***darwin_device) {
191 kern_return_t kresult;
193 io_iterator_t deviceIterator;
195 kresult = usb_setup_device_iterator (&deviceIterator);
199 /* This port of libusb uses locations to keep track of devices. */
200 while ((*darwin_device = usb_get_next_device (deviceIterator, &location)) != NULL) {
201 if (location == dev_location)
204 (**darwin_device)->Release(*darwin_device);
207 IOObjectRelease (deviceIterator);
209 if (!(*darwin_device))
210 return kIOReturnNoDevice;
212 return kIOReturnSuccess;
217 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
218 struct libusb_context *ctx = (struct libusb_context *)ptr;
219 struct libusb_device_handle *handle;
220 struct darwin_device_priv *dpriv;
221 struct darwin_device_handle_priv *priv;
225 CFTypeRef locationCF;
228 usbi_info (ctx, "a device has been detached");
230 while ((device = IOIteratorNext (rem_devices)) != 0) {
231 /* get the location from the i/o registry */
232 locationCF = IORegistryEntryCreateCFProperty (device, CFSTR(kUSBDevicePropertyLocationID), kCFAllocatorDefault, 0);
234 CFNumberGetValue(locationCF, kCFNumberLongType, &location);
235 CFRelease (locationCF);
236 IOObjectRelease (device);
238 usbi_mutex_lock(&ctx->open_devs_lock);
239 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
240 dpriv = (struct darwin_device_priv *)handle->dev->os_priv;
242 /* the device may have been opened several times. write to each handle's event descriptor */
243 if (dpriv->location == location && handle->os_priv) {
244 priv = (struct darwin_device_handle_priv *)handle->os_priv;
246 message = MESSAGE_DEVICE_GONE;
247 write (priv->fds[1], &message, sizeof (message));
251 usbi_mutex_unlock(&ctx->open_devs_lock);
255 static void darwin_clear_iterator (io_iterator_t iter) {
258 while ((device = IOIteratorNext (iter)) != 0)
259 IOObjectRelease (device);
262 static void *event_thread_main (void *arg0) {
264 struct libusb_context *ctx = (struct libusb_context *)arg0;
265 CFRunLoopRef runloop;
267 /* hotplug (device removal) source */
268 CFRunLoopSourceRef libusb_notification_cfsource;
269 io_notification_port_t libusb_notification_port;
270 io_iterator_t libusb_rem_device_iterator;
272 usbi_info (ctx, "creating hotplug event source");
274 runloop = CFRunLoopGetCurrent ();
277 /* add the notification port to the run loop */
278 libusb_notification_port = IONotificationPortCreate (libusb_darwin_mp);
279 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
280 CFRunLoopAddSource(CFRunLoopGetCurrent (), libusb_notification_cfsource, kCFRunLoopDefaultMode);
282 /* create notifications for removed devices */
283 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
284 IOServiceMatching(kIOUSBDeviceClassName),
285 (IOServiceMatchingCallback)darwin_devices_detached,
286 (void *)ctx, &libusb_rem_device_iterator);
288 if (kresult != kIOReturnSuccess) {
289 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
291 pthread_exit ((void *)kresult);
295 darwin_clear_iterator (libusb_rem_device_iterator);
297 /* let the main thread know about the async runloop */
298 libusb_darwin_acfl = CFRunLoopGetCurrent ();
300 usbi_info (ctx, "thread ready to receive events");
302 /* run the runloop */
305 usbi_info (ctx, "thread exiting");
307 /* delete notification port */
308 CFRunLoopSourceInvalidate (libusb_notification_cfsource);
309 IONotificationPortDestroy (libusb_notification_port);
313 libusb_darwin_acfl = NULL;
318 static int darwin_init(struct libusb_context *ctx) {
321 if (!(initCount++)) {
322 /* Create the master port for talking to IOKit */
323 if (!libusb_darwin_mp) {
324 kresult = IOMasterPort (MACH_PORT_NULL, &libusb_darwin_mp);
326 if (kresult != kIOReturnSuccess || !libusb_darwin_mp)
327 return darwin_to_libusb (kresult);
330 pthread_create (&libusb_darwin_at, NULL, event_thread_main, (void *)ctx);
332 while (!libusb_darwin_acfl)
339 static void darwin_exit (void) {
340 if (!(--initCount)) {
343 /* stop the async runloop */
344 CFRunLoopStop (libusb_darwin_acfl);
345 pthread_join (libusb_darwin_at, &ret);
347 if (libusb_darwin_mp)
348 mach_port_deallocate(mach_task_self(), libusb_darwin_mp);
350 libusb_darwin_mp = 0;
354 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
355 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
357 /* return cached copy */
358 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
365 static int get_configuration_index (struct libusb_device *dev, int config_value) {
366 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
368 IOUSBConfigurationDescriptorPtr desc;
371 /* is there a simpler way to determine the index? */
372 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
373 if (kresult != kIOReturnSuccess)
374 return darwin_to_libusb (kresult);
376 for (i = 0 ; i < numConfig ; i++) {
377 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
379 if (desc->bConfigurationValue == config_value)
383 /* configuration not found */
384 return LIBUSB_ERROR_OTHER;
387 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
388 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
391 if (0 == priv->active_config)
392 return LIBUSB_ERROR_INVALID_PARAM;
394 config_index = get_configuration_index (dev, priv->active_config);
395 if (config_index < 0)
398 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
401 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
402 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
403 IOUSBConfigurationDescriptorPtr desc;
405 usb_device_t **device = NULL;
408 return LIBUSB_ERROR_OTHER;
411 kresult = darwin_get_device (priv->location, &device);
412 if (kresult || !device) {
413 usbi_err (DEVICE_CTX (dev), "could not find device: %s", darwin_error_str (kresult));
415 return darwin_to_libusb (kresult);
418 /* don't have to open the device to get a config descriptor */
420 device = priv->device;
422 kresult = (*device)->GetConfigurationDescriptorPtr (device, config_index, &desc);
423 if (kresult == kIOReturnSuccess) {
424 /* copy descriptor */
425 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
426 len = libusb_le16_to_cpu(desc->wTotalLength);
428 memmove (buffer, desc, len);
430 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
435 (*device)->Release (device);
437 return darwin_to_libusb (kresult);
440 /* check whether the os has configured the device */
441 static int darwin_check_configuration (struct libusb_context *ctx, struct libusb_device *dev, usb_device_t **darwin_device) {
442 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
444 IOUSBConfigurationDescriptorPtr configDesc;
445 IOUSBFindInterfaceRequest request;
446 kern_return_t kresult;
447 io_iterator_t interface_iterator;
448 io_service_t firstInterface;
450 if (priv->dev_descriptor.bNumConfigurations < 1) {
451 usbi_err (ctx, "device has no configurations");
452 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
455 /* find the first configuration */
456 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
457 priv->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
459 /* check if the device is already configured. there is probably a better way than iterating over the
460 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
461 might lock up on the device request) */
463 /* Setup the Interface Request */
464 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
465 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
466 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
467 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
469 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
471 return darwin_to_libusb (kresult);
474 firstInterface = IOIteratorNext(interface_iterator);
476 /* done with the interface iterator */
477 IOObjectRelease(interface_iterator);
479 if (firstInterface) {
480 IOObjectRelease (firstInterface);
482 /* device is configured */
483 if (priv->dev_descriptor.bNumConfigurations == 1)
484 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
485 priv->active_config = priv->first_config;
487 /* devices with more than one configuration should work with GetConfiguration */
488 (*darwin_device)->GetConfiguration (darwin_device, &priv->active_config);
491 priv->active_config = 0;
493 usbi_info (ctx, "active config: %u, first config: %u", priv->active_config, priv->first_config);
498 static int process_new_device (struct libusb_context *ctx, usb_device_t **device, UInt32 locationID, struct discovered_devs **_discdevs) {
499 struct darwin_device_priv *priv;
500 struct libusb_device *dev;
501 struct discovered_devs *discdevs;
502 UInt16 address, idVendor, idProduct;
503 UInt8 bDeviceClass, bDeviceSubClass;
505 int ret = 0, need_unref = 0;
508 dev = usbi_get_device_by_session_id(ctx, locationID);
510 usbi_info (ctx, "allocating new device for location 0x%08x", locationID);
511 dev = usbi_alloc_device(ctx, locationID);
514 usbi_info (ctx, "using existing device for location 0x%08x", locationID);
517 ret = LIBUSB_ERROR_NO_MEM;
521 priv = (struct darwin_device_priv *)dev->os_priv;
523 /* Set up request for device descriptor */
524 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
525 req.bRequest = kUSBRqGetDescriptor;
526 req.wValue = kUSBDeviceDesc << 8;
528 req.wLength = sizeof(IOUSBDeviceDescriptor);
529 req.pData = &(priv->dev_descriptor);
531 (*(device))->GetDeviceAddress (device, (USBDeviceAddress *)&address);
532 (*(device))->GetDeviceProduct (device, &idProduct);
533 (*(device))->GetDeviceVendor (device, &idVendor);
534 (*(device))->GetDeviceClass (device, &bDeviceClass);
535 (*(device))->GetDeviceSubClass (device, &bDeviceSubClass);
537 /**** retrieve device descriptors ****/
538 /* according to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
539 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request */
540 ret = (*(device))->DeviceRequest (device, &req);
541 if (ret != kIOReturnSuccess) {
542 int try_unsuspend = 1;
543 #if DeviceVersion >= 320
546 /* device may be suspended. unsuspend it and try again */
547 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
548 (void)(*device)->GetUSBDeviceInformation (device, &info);
550 try_unsuspend = info & (1 << kUSBInformationDeviceIsSuspendedBit);
553 /* the device should be open before to device is unsuspended */
554 (void) (*device)->USBDeviceOpenSeize(device);
557 /* resume the device */
558 (void)(*device)->USBDeviceSuspend (device, 0);
560 ret = (*(device))->DeviceRequest (device, &req);
562 /* resuspend the device */
563 (void)(*device)->USBDeviceSuspend (device, 1);
566 (*device)->USBDeviceClose (device);
569 if (ret != kIOReturnSuccess) {
570 usbi_warn (ctx, "could not retrieve device descriptor: %s. skipping device", darwin_error_str (ret));
575 /**** end: retrieve device descriptors ****/
577 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
578 if (libusb_le16_to_cpu (priv->dev_descriptor.idProduct) != idProduct) {
579 /* not a valid device */
580 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
581 idProduct, libusb_le16_to_cpu (priv->dev_descriptor.idProduct));
586 dev->bus_number = locationID >> 24;
587 dev->device_address = address;
589 /* check current active configuration (and cache the first configuration value-- which may be used by claim_interface) */
590 ret = darwin_check_configuration (ctx, dev, device);
594 /* save our location, we'll need this later */
595 priv->location = locationID;
596 snprintf(priv->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", address, idVendor, idProduct, bDeviceClass, bDeviceSubClass);
598 ret = usbi_sanitize_device (dev);
602 /* append the device to the list of discovered devices */
603 discdevs = discovered_devs_append(*_discdevs, dev);
605 ret = LIBUSB_ERROR_NO_MEM;
609 *_discdevs = discdevs;
611 usbi_info (ctx, "found device with address %d at %s", dev->device_address, priv->sys_path);
615 libusb_unref_device(dev);
620 static int darwin_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs) {
621 io_iterator_t deviceIterator;
622 usb_device_t **device;
623 kern_return_t kresult;
626 if (!libusb_darwin_mp)
627 return LIBUSB_ERROR_INVALID_PARAM;
629 kresult = usb_setup_device_iterator (&deviceIterator);
630 if (kresult != kIOReturnSuccess)
631 return darwin_to_libusb (kresult);
633 while ((device = usb_get_next_device (deviceIterator, &location)) != NULL) {
634 (void) process_new_device (ctx, device, location, _discdevs);
636 (*(device))->Release(device);
639 IOObjectRelease(deviceIterator);
644 static int darwin_open (struct libusb_device_handle *dev_handle) {
645 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
646 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
647 usb_device_t **darwin_device;
650 if (0 == dpriv->open_count) {
651 kresult = darwin_get_device (dpriv->location, &darwin_device);
653 usbi_err (HANDLE_CTX (dev_handle), "could not find device: %s", darwin_error_str (kresult));
654 return darwin_to_libusb (kresult);
657 dpriv->device = darwin_device;
659 /* try to open the device */
660 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
662 if (kresult != kIOReturnSuccess) {
663 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
666 case kIOReturnExclusiveAccess:
667 /* it is possible to perform some actions on a device that is not open so do not return an error */
672 (*(dpriv->device))->Release (dpriv->device);
673 dpriv->device = NULL;
674 return darwin_to_libusb (kresult);
677 /* create async event source */
678 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
679 if (kresult != kIOReturnSuccess) {
680 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
682 (*(dpriv->device))->USBDeviceClose (dpriv->device);
683 (*(dpriv->device))->Release (dpriv->device);
685 dpriv->device = NULL;
686 return darwin_to_libusb (kresult);
691 CFRetain (libusb_darwin_acfl);
693 /* add the cfSource to the aync run loop */
694 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
698 /* device opened successfully */
701 /* create a file descriptor for notifications */
704 /* set the pipe to be non-blocking */
705 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
707 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
709 usbi_info (HANDLE_CTX (dev_handle), "device open for access");
714 static void darwin_close (struct libusb_device_handle *dev_handle) {
715 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
716 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
720 if (dpriv->open_count == 0) {
721 /* something is probably very wrong if this is the case */
722 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
728 /* make sure all interfaces are released */
729 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
730 if (dev_handle->claimed_interfaces & (1 << i))
731 libusb_release_interface (dev_handle, i);
733 if (0 == dpriv->open_count) {
735 /* delete the device's async event source */
736 if (priv->cfSource) {
737 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
738 CFRelease (priv->cfSource);
741 /* close the device */
742 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
744 /* Log the fact that we had a problem closing the file, however failing a
745 * close isn't really an error, so return success anyway */
746 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
750 kresult = (*(dpriv->device))->Release(dpriv->device);
752 /* Log the fact that we had a problem closing the file, however failing a
753 * close isn't really an error, so return success anyway */
754 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
757 dpriv->device = NULL;
760 /* file descriptors are maintained per-instance */
761 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
762 close (priv->fds[1]);
763 close (priv->fds[0]);
765 priv->fds[0] = priv->fds[1] = -1;
768 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
769 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
771 *config = (int) dpriv->active_config;
776 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
777 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
781 /* Setting configuration will invalidate the interface, so we need
782 to reclaim it. First, dispose of existing interfaces, if any. */
783 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
784 if (dev_handle->claimed_interfaces & (1 << i))
785 darwin_release_interface (dev_handle, i);
787 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
788 if (kresult != kIOReturnSuccess)
789 return darwin_to_libusb (kresult);
791 /* Reclaim any interfaces. */
792 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
793 if (dev_handle->claimed_interfaces & (1 << i))
794 darwin_claim_interface (dev_handle, i);
796 dpriv->active_config = config;
801 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
802 IOUSBFindInterfaceRequest request;
803 uint8_t current_interface;
804 kern_return_t kresult;
805 io_iterator_t interface_iterator;
807 *usbInterfacep = IO_OBJECT_NULL;
809 /* Setup the Interface Request */
810 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
811 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
812 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
813 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
815 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
819 for ( current_interface = 0 ; current_interface <= ifc ; current_interface++ ) {
820 *usbInterfacep = IOIteratorNext(interface_iterator);
821 if (current_interface != ifc)
822 (void) IOObjectRelease (*usbInterfacep);
825 /* done with the interface iterator */
826 IOObjectRelease(interface_iterator);
831 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
832 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
834 /* current interface */
835 struct __darwin_interface *cInterface = &priv->interfaces[iface];
837 kern_return_t kresult;
839 u_int8_t numep, direction, number;
840 u_int8_t dont_care1, dont_care3;
841 u_int16_t dont_care2;
844 usbi_info (HANDLE_CTX (dev_handle), "building table of endpoints.");
846 /* retrieve the total number of endpoints on this interface */
847 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
849 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
850 return darwin_to_libusb (kresult);
853 /* iterate through pipe references */
854 for (i = 1 ; i <= numep ; i++) {
855 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
856 &dont_care2, &dont_care3);
858 if (kresult != kIOReturnSuccess) {
859 usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
861 return darwin_to_libusb (kresult);
864 usbi_info (HANDLE_CTX (dev_handle), "interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
866 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
869 cInterface->num_endpoints = numep;
874 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
875 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
876 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
877 io_service_t usbInterface = IO_OBJECT_NULL;
879 IOCFPlugInInterface **plugInInterface = NULL;
882 /* current interface */
883 struct __darwin_interface *cInterface = &priv->interfaces[iface];
885 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
886 if (kresult != kIOReturnSuccess)
887 return darwin_to_libusb (kresult);
889 /* make sure we have an interface */
890 if (!usbInterface && dpriv->first_config != 0) {
891 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
893 /* set the configuration */
894 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
895 if (kresult != LIBUSB_SUCCESS) {
896 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
900 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
902 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
903 return darwin_to_libusb (kresult);
908 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
909 return LIBUSB_ERROR_NOT_FOUND;
912 /* get an interface to the device's interface */
913 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
914 kIOCFPlugInInterfaceID, &plugInInterface, &score);
916 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
917 return darwin_to_libusb (kresult);
920 if (!plugInInterface) {
921 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
922 return LIBUSB_ERROR_NOT_FOUND;
925 /* ignore release error */
926 (void)IOObjectRelease (usbInterface);
928 /* Do the actual claim */
929 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
930 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
931 (LPVOID)&cInterface->interface);
932 if (kresult || !cInterface->interface) {
933 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
934 return darwin_to_libusb (kresult);
937 /* We no longer need the intermediate plug-in */
938 (*plugInInterface)->Release(plugInInterface);
940 /* claim the interface */
941 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
943 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
944 return darwin_to_libusb (kresult);
947 /* update list of endpoints */
948 kresult = get_endpoints (dev_handle, iface);
950 /* this should not happen */
951 darwin_release_interface (dev_handle, iface);
952 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
956 cInterface->cfSource = NULL;
958 /* create async event source */
959 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
960 if (kresult != kIOReturnSuccess) {
961 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
963 /* can't continue without an async event source */
964 (void)darwin_release_interface (dev_handle, iface);
966 return darwin_to_libusb (kresult);
969 /* add the cfSource to the async thread's run loop */
970 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
972 usbi_info (HANDLE_CTX (dev_handle), "interface opened");
977 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
978 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
981 /* current interface */
982 struct __darwin_interface *cInterface = &priv->interfaces[iface];
984 /* Check to see if an interface is open */
985 if (!cInterface->interface)
986 return LIBUSB_SUCCESS;
988 /* clean up endpoint data */
989 cInterface->num_endpoints = 0;
991 /* delete the interface's async event source */
992 if (cInterface->cfSource) {
993 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
994 CFRelease (cInterface->cfSource);
997 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
999 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1001 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1002 if (kresult != kIOReturnSuccess)
1003 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1005 cInterface->interface = IO_OBJECT_NULL;
1007 return darwin_to_libusb (kresult);
1010 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1011 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1014 /* current interface */
1015 struct __darwin_interface *cInterface = &priv->interfaces[iface];
1017 if (!cInterface->interface)
1018 return LIBUSB_ERROR_NO_DEVICE;
1020 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1021 if (kresult != kIOReturnSuccess)
1022 darwin_reset_device (dev_handle);
1024 /* update list of endpoints */
1025 kresult = get_endpoints (dev_handle, iface);
1027 /* this should not happen */
1028 darwin_release_interface (dev_handle, iface);
1029 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1033 return darwin_to_libusb (kresult);
1036 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1037 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1039 /* current interface */
1040 struct __darwin_interface *cInterface;
1041 uint8_t pipeRef, iface;
1044 /* determine the interface/endpoint to use */
1045 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
1046 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1048 return LIBUSB_ERROR_NOT_FOUND;
1051 cInterface = &priv->interfaces[iface];
1053 #if (InterfaceVersion < 190)
1054 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1056 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1057 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1060 usbi_err (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1062 return darwin_to_libusb (kresult);
1065 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1066 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1069 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1071 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1073 return darwin_to_libusb (kresult);
1076 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1077 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1078 io_service_t usbInterface;
1082 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1084 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1086 return darwin_to_libusb (kresult);
1089 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1090 IOObjectRelease (usbInterface);
1102 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1103 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1104 return LIBUSB_ERROR_NOT_SUPPORTED;
1107 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1108 return LIBUSB_ERROR_NOT_SUPPORTED;
1111 static void darwin_destroy_device(struct libusb_device *dev) {
1114 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1115 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1116 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1119 uint8_t is_read; /* 0 = we're reading, 1 = we're writing */
1120 uint8_t transferType;
1121 /* None of the values below are used in libusb for bulk transfers */
1122 uint8_t direction, number, interval, pipeRef, iface;
1123 uint16_t maxPacketSize;
1125 struct __darwin_interface *cInterface;
1127 /* are we reading or writing? */
1128 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1130 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1131 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1133 return LIBUSB_ERROR_NOT_FOUND;
1136 cInterface = &priv->interfaces[iface];
1138 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1139 &transferType, &maxPacketSize, &interval);
1141 /* submit the request */
1142 /* timeouts are unavailable on interrupt endpoints */
1143 if (transferType == kUSBInterrupt) {
1145 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1146 transfer->length, darwin_async_io_callback, itransfer);
1148 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1149 transfer->length, darwin_async_io_callback, itransfer);
1151 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1154 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1155 transfer->length, transfer->timeout, transfer->timeout,
1156 darwin_async_io_callback, (void *)itransfer);
1158 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1159 transfer->length, transfer->timeout, transfer->timeout,
1160 darwin_async_io_callback, (void *)itransfer);
1164 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", is_read ? "In" : "Out",
1165 darwin_error_str(ret), ret);
1167 return darwin_to_libusb (ret);
1170 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1171 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1172 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1173 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1176 uint8_t is_read; /* 0 = we're writing, 1 = we're reading */
1177 uint8_t pipeRef, iface;
1179 AbsoluteTime atTime;
1182 struct __darwin_interface *cInterface;
1184 /* are we reading or writing? */
1185 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1187 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1188 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1189 free(tpriv->isoc_framelist);
1190 tpriv->isoc_framelist = NULL;
1193 if (!tpriv->isoc_framelist) {
1194 tpriv->num_iso_packets = transfer->num_iso_packets;
1195 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1196 if (!tpriv->isoc_framelist)
1197 return LIBUSB_ERROR_NO_MEM;
1200 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1201 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1202 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1204 /* determine the interface/endpoint to use */
1205 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1206 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1208 return LIBUSB_ERROR_NOT_FOUND;
1211 cInterface = &priv->interfaces[iface];
1213 /* Last but not least we need the bus frame number */
1214 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1216 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1217 free(tpriv->isoc_framelist);
1218 tpriv->isoc_framelist = NULL;
1220 return darwin_to_libusb (kresult);
1223 /* schedule for a frame a little in the future */
1226 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1227 frame = cInterface->frames[transfer->endpoint];
1229 /* submit the request */
1231 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1232 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1235 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1236 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1239 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets / 8;
1241 if (kresult != kIOReturnSuccess) {
1242 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", is_read ? "In" : "Out",
1243 darwin_error_str(kresult));
1244 free (tpriv->isoc_framelist);
1245 tpriv->isoc_framelist = NULL;
1248 return darwin_to_libusb (kresult);
1251 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1252 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1253 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1254 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1255 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1256 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1260 bzero(&tpriv->req, sizeof(tpriv->req));
1262 /* IOUSBDeviceInterface expects the request in cpu endianess */
1263 tpriv->req.bmRequestType = setup->bmRequestType;
1264 tpriv->req.bRequest = setup->bRequest;
1265 /* these values should be in bus order from libusb_fill_control_setup */
1266 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1267 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1268 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1269 /* data is stored after the libusb control block */
1270 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1271 tpriv->req.completionTimeout = transfer->timeout;
1272 tpriv->req.noDataTimeout = transfer->timeout;
1274 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1276 /* all transfers in libusb-1.0 are async */
1278 if (transfer->endpoint) {
1279 struct __darwin_interface *cInterface;
1280 uint8_t pipeRef, iface;
1282 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1283 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1285 return LIBUSB_ERROR_NOT_FOUND;
1288 cInterface = &priv->interfaces[iface];
1290 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1292 /* control request on endpoint 0 */
1293 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1295 if (kresult != kIOReturnSuccess)
1296 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1298 return darwin_to_libusb (kresult);
1301 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1302 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1304 switch (transfer->type) {
1305 case LIBUSB_TRANSFER_TYPE_CONTROL:
1306 return submit_control_transfer(itransfer);
1307 case LIBUSB_TRANSFER_TYPE_BULK:
1308 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1309 return submit_bulk_transfer(itransfer);
1310 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1311 return submit_iso_transfer(itransfer);
1313 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1314 return LIBUSB_ERROR_INVALID_PARAM;
1318 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1319 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1320 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1323 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions control pipe");
1325 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1327 return darwin_to_libusb (kresult);
1330 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1331 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1332 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1333 struct __darwin_interface *cInterface;
1334 uint8_t pipeRef, iface;
1337 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1338 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1340 return LIBUSB_ERROR_NOT_FOUND;
1343 cInterface = &priv->interfaces[iface];
1345 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions on interface %d pipe %d", iface, pipeRef);
1347 /* abort transactions */
1348 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1350 usbi_info (ITRANSFER_CTX (itransfer), "calling clear pipe stall to clear the data toggle bit");
1352 /* clear the data toggle bit */
1353 #if (InterfaceVersion < 190)
1354 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1356 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1357 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1360 return darwin_to_libusb (kresult);
1363 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1364 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1366 switch (transfer->type) {
1367 case LIBUSB_TRANSFER_TYPE_CONTROL:
1368 return cancel_control_transfer(itransfer);
1369 case LIBUSB_TRANSFER_TYPE_BULK:
1370 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1371 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1372 return darwin_abort_transfers (itransfer);
1374 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1375 return LIBUSB_ERROR_INVALID_PARAM;
1379 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1380 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1381 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1383 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1384 free (tpriv->isoc_framelist);
1385 tpriv->isoc_framelist = NULL;
1389 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1390 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1391 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1392 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1395 usbi_info (ITRANSFER_CTX (itransfer), "an async io operation has completed");
1397 /* send a completion message to the device's file descriptor */
1398 message = MESSAGE_ASYNC_IO_COMPLETE;
1399 write (priv->fds[1], &message, sizeof (message));
1400 write (priv->fds[1], &itransfer, sizeof (itransfer));
1401 write (priv->fds[1], &result, sizeof (IOReturn));
1402 write (priv->fds[1], &arg0, sizeof (UInt32));
1405 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1406 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT)
1407 result = kIOUSBTransactionTimeout;
1410 case kIOReturnUnderrun:
1411 case kIOReturnSuccess:
1412 return LIBUSB_TRANSFER_COMPLETED;
1413 case kIOReturnAborted:
1414 return LIBUSB_TRANSFER_CANCELLED;
1415 case kIOUSBPipeStalled:
1416 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: pipe is stalled");
1417 return LIBUSB_TRANSFER_STALL;
1418 case kIOReturnOverrun:
1419 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1420 return LIBUSB_TRANSFER_OVERFLOW;
1421 case kIOUSBTransactionTimeout:
1422 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1423 itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
1424 return LIBUSB_TRANSFER_TIMED_OUT;
1426 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1427 return LIBUSB_TRANSFER_ERROR;
1431 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1432 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1433 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1434 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1435 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1436 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1437 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1440 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1441 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1445 usbi_info (ITRANSFER_CTX (itransfer), "handling %s completion with kernel status %d",
1446 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
1448 if (kIOReturnSuccess == result || kIOReturnUnderrun == result) {
1449 if (isIsoc && tpriv->isoc_framelist) {
1450 /* copy isochronous results back */
1452 for (i = 0; i < transfer->num_iso_packets ; i++) {
1453 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1454 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1455 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1458 itransfer->transferred += io_size;
1461 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1462 usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
1465 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready) {
1466 struct usbi_transfer *itransfer;
1472 usbi_mutex_lock(&ctx->open_devs_lock);
1473 for (i = 0; i < nfds && num_ready > 0; i++) {
1474 struct pollfd *pollfd = &fds[i];
1475 struct libusb_device_handle *handle;
1476 struct darwin_device_handle_priv *hpriv = NULL;
1478 usbi_info (ctx, "checking fd %i with revents = %x", fds[i], pollfd->revents);
1480 if (!pollfd->revents)
1484 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
1485 hpriv = (struct darwin_device_handle_priv *)handle->os_priv;
1486 if (hpriv->fds[0] == pollfd->fd)
1490 if (!(pollfd->revents & POLLERR)) {
1491 ret = read (hpriv->fds[0], &message, sizeof (message));
1492 if (ret < sizeof (message))
1495 /* could not poll the device-- response is to delete the device (this seems a little heavy-handed) */
1496 message = MESSAGE_DEVICE_GONE;
1499 case MESSAGE_DEVICE_GONE:
1500 /* remove the device's async port from the runloop */
1501 if (hpriv->cfSource) {
1502 if (libusb_darwin_acfl)
1503 CFRunLoopRemoveSource (libusb_darwin_acfl, hpriv->cfSource, kCFRunLoopDefaultMode);
1504 CFRelease (hpriv->cfSource);
1505 hpriv->cfSource = NULL;
1508 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1509 usbi_handle_disconnect(handle);
1511 /* done with this device */
1513 case MESSAGE_ASYNC_IO_COMPLETE:
1514 read (hpriv->fds[0], &itransfer, sizeof (itransfer));
1515 read (hpriv->fds[0], &kresult, sizeof (IOReturn));
1516 read (hpriv->fds[0], &io_size, sizeof (UInt32));
1518 darwin_handle_callback (itransfer, kresult, io_size);
1521 usbi_err (ctx, "unknown message received from device pipe");
1525 usbi_mutex_unlock(&ctx->open_devs_lock);
1530 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1531 mach_timespec_t sys_time;
1532 clock_serv_t clock_ref;
1535 case USBI_CLOCK_REALTIME:
1536 /* CLOCK_REALTIME represents time since the epoch */
1537 host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &clock_ref);
1539 case USBI_CLOCK_MONOTONIC:
1540 /* use system boot time as reference for the monotonic clock */
1541 host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &clock_ref);
1544 return LIBUSB_ERROR_INVALID_PARAM;
1547 clock_get_time (clock_ref, &sys_time);
1549 tp->tv_sec = sys_time.tv_sec;
1550 tp->tv_nsec = sys_time.tv_nsec;
1555 const struct usbi_os_backend darwin_backend = {
1557 .init = darwin_init,
1558 .exit = darwin_exit,
1559 .get_device_list = darwin_get_device_list,
1560 .get_device_descriptor = darwin_get_device_descriptor,
1561 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1562 .get_config_descriptor = darwin_get_config_descriptor,
1564 .open = darwin_open,
1565 .close = darwin_close,
1566 .get_configuration = darwin_get_configuration,
1567 .set_configuration = darwin_set_configuration,
1568 .claim_interface = darwin_claim_interface,
1569 .release_interface = darwin_release_interface,
1571 .set_interface_altsetting = darwin_set_interface_altsetting,
1572 .clear_halt = darwin_clear_halt,
1573 .reset_device = darwin_reset_device,
1575 .kernel_driver_active = darwin_kernel_driver_active,
1576 .detach_kernel_driver = darwin_detach_kernel_driver,
1577 .attach_kernel_driver = darwin_attach_kernel_driver,
1579 .destroy_device = darwin_destroy_device,
1581 .submit_transfer = darwin_submit_transfer,
1582 .cancel_transfer = darwin_cancel_transfer,
1583 .clear_transfer_priv = darwin_clear_transfer_priv,
1585 .handle_events = op_handle_events,
1587 .clock_gettime = darwin_clock_gettime,
1589 .device_priv_size = sizeof(struct darwin_device_priv),
1590 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1591 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1592 .add_iso_packet_size = 0,