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;
230 CFTypeRef locationCF;
233 usbi_info (ctx, "a device has been detached");
235 while ((device = IOIteratorNext (rem_devices)) != 0) {
236 /* get the location from the i/o registry */
237 locationCF = IORegistryEntryCreateCFProperty (device, CFSTR(kUSBDevicePropertyLocationID), kCFAllocatorDefault, 0);
239 CFNumberGetValue(locationCF, kCFNumberLongType, &location);
240 CFRelease (locationCF);
241 IOObjectRelease (device);
243 usbi_mutex_lock(&ctx->open_devs_lock);
244 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
245 dpriv = (struct darwin_device_priv *)handle->dev->os_priv;
247 /* the device may have been opened several times. write to each handle's event descriptor */
248 if (dpriv->location == location && handle->os_priv) {
249 priv = (struct darwin_device_handle_priv *)handle->os_priv;
251 message = MESSAGE_DEVICE_GONE;
252 write (priv->fds[1], &message, sizeof (message));
256 usbi_mutex_unlock(&ctx->open_devs_lock);
260 static void darwin_clear_iterator (io_iterator_t iter) {
263 while ((device = IOIteratorNext (iter)) != 0)
264 IOObjectRelease (device);
267 static void *event_thread_main (void *arg0) {
269 struct libusb_context *ctx = (struct libusb_context *)arg0;
270 CFRunLoopRef runloop;
272 /* Tell the Objective-C garbage collector about this thread.
273 This is required because, unlike NSThreads, pthreads are
274 not automatically registered. Although we don't use
275 Objective-C, we use CoreFoundation, which does. */
276 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
277 objc_registerThreadWithCollector();
280 /* hotplug (device removal) source */
281 CFRunLoopSourceRef libusb_notification_cfsource;
282 io_notification_port_t libusb_notification_port;
283 io_iterator_t libusb_rem_device_iterator;
285 usbi_info (ctx, "creating hotplug event source");
287 runloop = CFRunLoopGetCurrent ();
290 /* add the notification port to the run loop */
291 libusb_notification_port = IONotificationPortCreate (libusb_darwin_mp);
292 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
293 CFRunLoopAddSource(CFRunLoopGetCurrent (), libusb_notification_cfsource, kCFRunLoopDefaultMode);
295 /* create notifications for removed devices */
296 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
297 IOServiceMatching(kIOUSBDeviceClassName),
298 (IOServiceMatchingCallback)darwin_devices_detached,
299 (void *)ctx, &libusb_rem_device_iterator);
301 if (kresult != kIOReturnSuccess) {
302 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
308 darwin_clear_iterator (libusb_rem_device_iterator);
310 /* let the main thread know about the async runloop */
311 libusb_darwin_acfl = CFRunLoopGetCurrent ();
313 usbi_info (ctx, "thread ready to receive events");
315 /* run the runloop */
318 usbi_info (ctx, "thread exiting");
320 /* delete notification port */
321 CFRunLoopSourceInvalidate (libusb_notification_cfsource);
322 IONotificationPortDestroy (libusb_notification_port);
326 libusb_darwin_acfl = NULL;
331 static int darwin_init(struct libusb_context *ctx) {
334 if (!(initCount++)) {
335 /* Create the master port for talking to IOKit */
336 if (!libusb_darwin_mp) {
337 kresult = IOMasterPort (MACH_PORT_NULL, &libusb_darwin_mp);
339 if (kresult != kIOReturnSuccess || !libusb_darwin_mp)
340 return darwin_to_libusb (kresult);
343 pthread_create (&libusb_darwin_at, NULL, event_thread_main, (void *)ctx);
345 while (!libusb_darwin_acfl)
352 static void darwin_exit (void) {
353 if (!(--initCount)) {
355 /* stop the async runloop */
356 CFRunLoopStop (libusb_darwin_acfl);
357 pthread_join (libusb_darwin_at, NULL);
359 if (libusb_darwin_mp)
360 mach_port_deallocate(mach_task_self(), libusb_darwin_mp);
362 libusb_darwin_mp = 0;
366 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
367 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
369 /* return cached copy */
370 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
377 static int get_configuration_index (struct libusb_device *dev, int config_value) {
378 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
380 IOUSBConfigurationDescriptorPtr desc;
383 /* is there a simpler way to determine the index? */
384 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
385 if (kresult != kIOReturnSuccess)
386 return darwin_to_libusb (kresult);
388 for (i = 0 ; i < numConfig ; i++) {
389 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
391 if (desc->bConfigurationValue == config_value)
395 /* configuration not found */
396 return LIBUSB_ERROR_OTHER;
399 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
400 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
403 if (0 == priv->active_config)
404 return LIBUSB_ERROR_INVALID_PARAM;
406 config_index = get_configuration_index (dev, priv->active_config);
407 if (config_index < 0)
410 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
413 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
414 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
415 IOUSBConfigurationDescriptorPtr desc;
417 usb_device_t **device = NULL;
420 return LIBUSB_ERROR_OTHER;
423 kresult = darwin_get_device (priv->location, &device);
424 if (kresult || !device) {
425 usbi_err (DEVICE_CTX (dev), "could not find device: %s", darwin_error_str (kresult));
427 return darwin_to_libusb (kresult);
430 /* don't have to open the device to get a config descriptor */
432 device = priv->device;
434 kresult = (*device)->GetConfigurationDescriptorPtr (device, config_index, &desc);
435 if (kresult == kIOReturnSuccess) {
436 /* copy descriptor */
437 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
438 len = libusb_le16_to_cpu(desc->wTotalLength);
440 memmove (buffer, desc, len);
442 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
447 (*device)->Release (device);
449 return darwin_to_libusb (kresult);
452 /* check whether the os has configured the device */
453 static int darwin_check_configuration (struct libusb_context *ctx, struct libusb_device *dev, usb_device_t **darwin_device) {
454 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
456 IOUSBConfigurationDescriptorPtr configDesc;
457 IOUSBFindInterfaceRequest request;
458 kern_return_t kresult;
459 io_iterator_t interface_iterator;
460 io_service_t firstInterface;
462 if (priv->dev_descriptor.bNumConfigurations < 1) {
463 usbi_err (ctx, "device has no configurations");
464 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
467 /* find the first configuration */
468 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
469 priv->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
471 /* check if the device is already configured. there is probably a better way than iterating over the
472 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
473 might lock up on the device request) */
475 /* Setup the Interface Request */
476 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
477 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
478 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
479 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
481 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
483 return darwin_to_libusb (kresult);
486 firstInterface = IOIteratorNext(interface_iterator);
488 /* done with the interface iterator */
489 IOObjectRelease(interface_iterator);
491 if (firstInterface) {
492 IOObjectRelease (firstInterface);
494 /* device is configured */
495 if (priv->dev_descriptor.bNumConfigurations == 1)
496 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
497 priv->active_config = priv->first_config;
499 /* devices with more than one configuration should work with GetConfiguration */
500 (*darwin_device)->GetConfiguration (darwin_device, &priv->active_config);
503 priv->active_config = 0;
505 usbi_info (ctx, "active config: %u, first config: %u", priv->active_config, priv->first_config);
510 static int process_new_device (struct libusb_context *ctx, usb_device_t **device, UInt32 locationID, struct discovered_devs **_discdevs) {
511 struct darwin_device_priv *priv;
512 struct libusb_device *dev;
513 struct discovered_devs *discdevs;
514 UInt16 address, idVendor, idProduct;
515 UInt8 bDeviceClass, bDeviceSubClass;
517 int ret = 0, need_unref = 0;
520 dev = usbi_get_device_by_session_id(ctx, locationID);
522 usbi_info (ctx, "allocating new device for location 0x%08x", locationID);
523 dev = usbi_alloc_device(ctx, locationID);
526 usbi_info (ctx, "using existing device for location 0x%08x", locationID);
529 ret = LIBUSB_ERROR_NO_MEM;
533 priv = (struct darwin_device_priv *)dev->os_priv;
535 /* Set up request for device descriptor */
536 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
537 req.bRequest = kUSBRqGetDescriptor;
538 req.wValue = kUSBDeviceDesc << 8;
540 req.wLength = sizeof(IOUSBDeviceDescriptor);
541 req.pData = &(priv->dev_descriptor);
543 (*(device))->GetDeviceAddress (device, (USBDeviceAddress *)&address);
544 (*(device))->GetDeviceProduct (device, &idProduct);
545 (*(device))->GetDeviceVendor (device, &idVendor);
546 (*(device))->GetDeviceClass (device, &bDeviceClass);
547 (*(device))->GetDeviceSubClass (device, &bDeviceSubClass);
549 /**** retrieve device descriptors ****/
550 /* according to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
551 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request */
552 ret = (*(device))->DeviceRequest (device, &req);
553 if (ret != kIOReturnSuccess) {
554 int try_unsuspend = 1;
555 #if DeviceVersion >= 320
558 /* device may be suspended. unsuspend it and try again */
559 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
560 (void)(*device)->GetUSBDeviceInformation (device, &info);
562 try_unsuspend = info & (1 << kUSBInformationDeviceIsSuspendedBit);
565 /* the device should be open before to device is unsuspended */
566 (void) (*device)->USBDeviceOpenSeize(device);
569 /* resume the device */
570 (void)(*device)->USBDeviceSuspend (device, 0);
572 ret = (*(device))->DeviceRequest (device, &req);
574 /* resuspend the device */
575 (void)(*device)->USBDeviceSuspend (device, 1);
578 (*device)->USBDeviceClose (device);
581 if (ret != kIOReturnSuccess) {
582 usbi_warn (ctx, "could not retrieve device descriptor: %s. skipping device", darwin_error_str (ret));
587 /**** end: retrieve device descriptors ****/
589 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
590 if (libusb_le16_to_cpu (priv->dev_descriptor.idProduct) != idProduct) {
591 /* not a valid device */
592 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
593 idProduct, libusb_le16_to_cpu (priv->dev_descriptor.idProduct));
598 dev->bus_number = locationID >> 24;
599 dev->device_address = address;
601 /* check current active configuration (and cache the first configuration value-- which may be used by claim_interface) */
602 ret = darwin_check_configuration (ctx, dev, device);
606 /* save our location, we'll need this later */
607 priv->location = locationID;
608 snprintf(priv->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", address, idVendor, idProduct, bDeviceClass, bDeviceSubClass);
610 ret = usbi_sanitize_device (dev);
614 /* append the device to the list of discovered devices */
615 discdevs = discovered_devs_append(*_discdevs, dev);
617 ret = LIBUSB_ERROR_NO_MEM;
621 *_discdevs = discdevs;
623 usbi_info (ctx, "found device with address %d at %s", dev->device_address, priv->sys_path);
627 libusb_unref_device(dev);
632 static int darwin_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs) {
633 io_iterator_t deviceIterator;
634 usb_device_t **device;
635 kern_return_t kresult;
638 if (!libusb_darwin_mp)
639 return LIBUSB_ERROR_INVALID_PARAM;
641 kresult = usb_setup_device_iterator (&deviceIterator);
642 if (kresult != kIOReturnSuccess)
643 return darwin_to_libusb (kresult);
645 while ((device = usb_get_next_device (deviceIterator, &location)) != NULL) {
646 (void) process_new_device (ctx, device, location, _discdevs);
648 (*(device))->Release(device);
651 IOObjectRelease(deviceIterator);
656 static int darwin_open (struct libusb_device_handle *dev_handle) {
657 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
658 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
659 usb_device_t **darwin_device;
662 if (0 == dpriv->open_count) {
663 kresult = darwin_get_device (dpriv->location, &darwin_device);
665 usbi_err (HANDLE_CTX (dev_handle), "could not find device: %s", darwin_error_str (kresult));
666 return darwin_to_libusb (kresult);
669 dpriv->device = darwin_device;
671 /* try to open the device */
672 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
674 if (kresult != kIOReturnSuccess) {
675 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
678 case kIOReturnExclusiveAccess:
679 /* it is possible to perform some actions on a device that is not open so do not return an error */
684 (*(dpriv->device))->Release (dpriv->device);
685 dpriv->device = NULL;
686 return darwin_to_libusb (kresult);
689 /* create async event source */
690 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
691 if (kresult != kIOReturnSuccess) {
692 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
694 (*(dpriv->device))->USBDeviceClose (dpriv->device);
695 (*(dpriv->device))->Release (dpriv->device);
697 dpriv->device = NULL;
698 return darwin_to_libusb (kresult);
703 CFRetain (libusb_darwin_acfl);
705 /* add the cfSource to the aync run loop */
706 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
710 /* device opened successfully */
713 /* create a file descriptor for notifications */
716 /* set the pipe to be non-blocking */
717 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
719 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
721 usbi_info (HANDLE_CTX (dev_handle), "device open for access");
726 static void darwin_close (struct libusb_device_handle *dev_handle) {
727 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
728 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
732 if (dpriv->open_count == 0) {
733 /* something is probably very wrong if this is the case */
734 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
740 /* make sure all interfaces are released */
741 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
742 if (dev_handle->claimed_interfaces & (1 << i))
743 libusb_release_interface (dev_handle, i);
745 if (0 == dpriv->open_count) {
747 /* delete the device's async event source */
748 if (priv->cfSource) {
749 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
750 CFRelease (priv->cfSource);
753 /* close the device */
754 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
756 /* Log the fact that we had a problem closing the file, however failing a
757 * close isn't really an error, so return success anyway */
758 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
762 kresult = (*(dpriv->device))->Release(dpriv->device);
764 /* Log the fact that we had a problem closing the file, however failing a
765 * close isn't really an error, so return success anyway */
766 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
769 dpriv->device = NULL;
772 /* file descriptors are maintained per-instance */
773 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
774 close (priv->fds[1]);
775 close (priv->fds[0]);
777 priv->fds[0] = priv->fds[1] = -1;
780 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
781 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
783 *config = (int) dpriv->active_config;
788 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
789 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
793 /* Setting configuration will invalidate the interface, so we need
794 to reclaim it. First, dispose of existing interfaces, if any. */
795 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
796 if (dev_handle->claimed_interfaces & (1 << i))
797 darwin_release_interface (dev_handle, i);
799 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
800 if (kresult != kIOReturnSuccess)
801 return darwin_to_libusb (kresult);
803 /* Reclaim any interfaces. */
804 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
805 if (dev_handle->claimed_interfaces & (1 << i))
806 darwin_claim_interface (dev_handle, i);
808 dpriv->active_config = config;
813 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
814 IOUSBFindInterfaceRequest request;
815 uint8_t current_interface;
816 kern_return_t kresult;
817 io_iterator_t interface_iterator;
819 *usbInterfacep = IO_OBJECT_NULL;
821 /* Setup the Interface Request */
822 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
823 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
824 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
825 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
827 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
831 for ( current_interface = 0 ; current_interface <= ifc ; current_interface++ ) {
832 *usbInterfacep = IOIteratorNext(interface_iterator);
833 if (current_interface != ifc)
834 (void) IOObjectRelease (*usbInterfacep);
837 /* done with the interface iterator */
838 IOObjectRelease(interface_iterator);
843 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
844 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
846 /* current interface */
847 struct __darwin_interface *cInterface = &priv->interfaces[iface];
849 kern_return_t kresult;
851 u_int8_t numep, direction, number;
852 u_int8_t dont_care1, dont_care3;
853 u_int16_t dont_care2;
856 usbi_info (HANDLE_CTX (dev_handle), "building table of endpoints.");
858 /* retrieve the total number of endpoints on this interface */
859 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
861 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
862 return darwin_to_libusb (kresult);
865 /* iterate through pipe references */
866 for (i = 1 ; i <= numep ; i++) {
867 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
868 &dont_care2, &dont_care3);
870 if (kresult != kIOReturnSuccess) {
871 usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
873 return darwin_to_libusb (kresult);
876 usbi_info (HANDLE_CTX (dev_handle), "interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
878 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
881 cInterface->num_endpoints = numep;
886 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
887 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
888 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
889 io_service_t usbInterface = IO_OBJECT_NULL;
891 IOCFPlugInInterface **plugInInterface = NULL;
894 /* current interface */
895 struct __darwin_interface *cInterface = &priv->interfaces[iface];
897 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
898 if (kresult != kIOReturnSuccess)
899 return darwin_to_libusb (kresult);
901 /* make sure we have an interface */
902 if (!usbInterface && dpriv->first_config != 0) {
903 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
905 /* set the configuration */
906 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
907 if (kresult != LIBUSB_SUCCESS) {
908 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
912 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
914 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
915 return darwin_to_libusb (kresult);
920 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
921 return LIBUSB_ERROR_NOT_FOUND;
924 /* get an interface to the device's interface */
925 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
926 kIOCFPlugInInterfaceID, &plugInInterface, &score);
928 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
929 return darwin_to_libusb (kresult);
932 if (!plugInInterface) {
933 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
934 return LIBUSB_ERROR_NOT_FOUND;
937 /* ignore release error */
938 (void)IOObjectRelease (usbInterface);
940 /* Do the actual claim */
941 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
942 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
943 (LPVOID)&cInterface->interface);
944 if (kresult || !cInterface->interface) {
945 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
946 return darwin_to_libusb (kresult);
949 /* We no longer need the intermediate plug-in */
950 (*plugInInterface)->Release(plugInInterface);
952 /* claim the interface */
953 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
955 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
956 return darwin_to_libusb (kresult);
959 /* update list of endpoints */
960 kresult = get_endpoints (dev_handle, iface);
962 /* this should not happen */
963 darwin_release_interface (dev_handle, iface);
964 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
968 cInterface->cfSource = NULL;
970 /* create async event source */
971 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
972 if (kresult != kIOReturnSuccess) {
973 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
975 /* can't continue without an async event source */
976 (void)darwin_release_interface (dev_handle, iface);
978 return darwin_to_libusb (kresult);
981 /* add the cfSource to the async thread's run loop */
982 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
984 usbi_info (HANDLE_CTX (dev_handle), "interface opened");
989 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
990 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
993 /* current interface */
994 struct __darwin_interface *cInterface = &priv->interfaces[iface];
996 /* Check to see if an interface is open */
997 if (!cInterface->interface)
998 return LIBUSB_SUCCESS;
1000 /* clean up endpoint data */
1001 cInterface->num_endpoints = 0;
1003 /* delete the interface's async event source */
1004 if (cInterface->cfSource) {
1005 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1006 CFRelease (cInterface->cfSource);
1009 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1011 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1013 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1014 if (kresult != kIOReturnSuccess)
1015 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1017 cInterface->interface = IO_OBJECT_NULL;
1019 return darwin_to_libusb (kresult);
1022 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1023 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1026 /* current interface */
1027 struct __darwin_interface *cInterface = &priv->interfaces[iface];
1029 if (!cInterface->interface)
1030 return LIBUSB_ERROR_NO_DEVICE;
1032 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1033 if (kresult != kIOReturnSuccess)
1034 darwin_reset_device (dev_handle);
1036 /* update list of endpoints */
1037 kresult = get_endpoints (dev_handle, iface);
1039 /* this should not happen */
1040 darwin_release_interface (dev_handle, iface);
1041 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1045 return darwin_to_libusb (kresult);
1048 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1049 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1051 /* current interface */
1052 struct __darwin_interface *cInterface;
1053 uint8_t pipeRef, iface;
1056 /* determine the interface/endpoint to use */
1057 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
1058 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1060 return LIBUSB_ERROR_NOT_FOUND;
1063 cInterface = &priv->interfaces[iface];
1065 #if (InterfaceVersion < 190)
1066 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1068 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1069 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1072 usbi_err (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1074 return darwin_to_libusb (kresult);
1077 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1078 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1081 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1083 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1085 return darwin_to_libusb (kresult);
1088 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1089 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1090 io_service_t usbInterface;
1094 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1096 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1098 return darwin_to_libusb (kresult);
1101 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1102 IOObjectRelease (usbInterface);
1114 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1115 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1116 return LIBUSB_ERROR_NOT_SUPPORTED;
1119 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1120 return LIBUSB_ERROR_NOT_SUPPORTED;
1123 static void darwin_destroy_device(struct libusb_device *dev) {
1126 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1127 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1128 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1131 uint8_t is_read; /* 0 = we're reading, 1 = we're writing */
1132 uint8_t transferType;
1133 /* None of the values below are used in libusb for bulk transfers */
1134 uint8_t direction, number, interval, pipeRef, iface;
1135 uint16_t maxPacketSize;
1137 struct __darwin_interface *cInterface;
1139 /* are we reading or writing? */
1140 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1142 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1143 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1145 return LIBUSB_ERROR_NOT_FOUND;
1148 cInterface = &priv->interfaces[iface];
1150 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1151 &transferType, &maxPacketSize, &interval);
1153 /* submit the request */
1154 /* timeouts are unavailable on interrupt endpoints */
1155 if (transferType == kUSBInterrupt) {
1157 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1158 transfer->length, darwin_async_io_callback, itransfer);
1160 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1161 transfer->length, darwin_async_io_callback, itransfer);
1163 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1166 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1167 transfer->length, transfer->timeout, transfer->timeout,
1168 darwin_async_io_callback, (void *)itransfer);
1170 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1171 transfer->length, transfer->timeout, transfer->timeout,
1172 darwin_async_io_callback, (void *)itransfer);
1176 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", is_read ? "In" : "Out",
1177 darwin_error_str(ret), ret);
1179 return darwin_to_libusb (ret);
1182 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1183 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1184 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1185 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1188 uint8_t is_read; /* 0 = we're writing, 1 = we're reading */
1189 uint8_t pipeRef, iface;
1191 AbsoluteTime atTime;
1194 struct __darwin_interface *cInterface;
1196 /* are we reading or writing? */
1197 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1199 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1200 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1201 free(tpriv->isoc_framelist);
1202 tpriv->isoc_framelist = NULL;
1205 if (!tpriv->isoc_framelist) {
1206 tpriv->num_iso_packets = transfer->num_iso_packets;
1207 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1208 if (!tpriv->isoc_framelist)
1209 return LIBUSB_ERROR_NO_MEM;
1212 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1213 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1214 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1216 /* determine the interface/endpoint to use */
1217 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1218 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1220 return LIBUSB_ERROR_NOT_FOUND;
1223 cInterface = &priv->interfaces[iface];
1225 /* Last but not least we need the bus frame number */
1226 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1228 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1229 free(tpriv->isoc_framelist);
1230 tpriv->isoc_framelist = NULL;
1232 return darwin_to_libusb (kresult);
1235 /* schedule for a frame a little in the future */
1238 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1239 frame = cInterface->frames[transfer->endpoint];
1241 /* submit the request */
1243 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1244 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1247 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1248 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1251 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets / 8;
1253 if (kresult != kIOReturnSuccess) {
1254 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", is_read ? "In" : "Out",
1255 darwin_error_str(kresult));
1256 free (tpriv->isoc_framelist);
1257 tpriv->isoc_framelist = NULL;
1260 return darwin_to_libusb (kresult);
1263 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1264 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1265 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1266 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1267 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1268 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1272 bzero(&tpriv->req, sizeof(tpriv->req));
1274 /* IOUSBDeviceInterface expects the request in cpu endianess */
1275 tpriv->req.bmRequestType = setup->bmRequestType;
1276 tpriv->req.bRequest = setup->bRequest;
1277 /* these values should be in bus order from libusb_fill_control_setup */
1278 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1279 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1280 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1281 /* data is stored after the libusb control block */
1282 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1283 tpriv->req.completionTimeout = transfer->timeout;
1284 tpriv->req.noDataTimeout = transfer->timeout;
1286 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1288 /* all transfers in libusb-1.0 are async */
1290 if (transfer->endpoint) {
1291 struct __darwin_interface *cInterface;
1292 uint8_t pipeRef, iface;
1294 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1295 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1297 return LIBUSB_ERROR_NOT_FOUND;
1300 cInterface = &priv->interfaces[iface];
1302 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1304 /* control request on endpoint 0 */
1305 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1307 if (kresult != kIOReturnSuccess)
1308 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1310 return darwin_to_libusb (kresult);
1313 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1314 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1316 switch (transfer->type) {
1317 case LIBUSB_TRANSFER_TYPE_CONTROL:
1318 return submit_control_transfer(itransfer);
1319 case LIBUSB_TRANSFER_TYPE_BULK:
1320 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1321 return submit_bulk_transfer(itransfer);
1322 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1323 return submit_iso_transfer(itransfer);
1325 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1326 return LIBUSB_ERROR_INVALID_PARAM;
1330 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1331 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1332 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1335 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions control pipe");
1337 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1339 return darwin_to_libusb (kresult);
1342 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1343 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1344 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1345 struct __darwin_interface *cInterface;
1346 uint8_t pipeRef, iface;
1349 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1350 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1352 return LIBUSB_ERROR_NOT_FOUND;
1355 cInterface = &priv->interfaces[iface];
1357 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions on interface %d pipe %d", iface, pipeRef);
1359 /* abort transactions */
1360 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1362 usbi_info (ITRANSFER_CTX (itransfer), "calling clear pipe stall to clear the data toggle bit");
1364 /* clear the data toggle bit */
1365 #if (InterfaceVersion < 190)
1366 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1368 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1369 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1372 return darwin_to_libusb (kresult);
1375 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1376 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1378 switch (transfer->type) {
1379 case LIBUSB_TRANSFER_TYPE_CONTROL:
1380 return cancel_control_transfer(itransfer);
1381 case LIBUSB_TRANSFER_TYPE_BULK:
1382 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1383 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1384 return darwin_abort_transfers (itransfer);
1386 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1387 return LIBUSB_ERROR_INVALID_PARAM;
1391 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1392 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1393 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1395 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1396 free (tpriv->isoc_framelist);
1397 tpriv->isoc_framelist = NULL;
1401 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1402 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1403 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1404 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1407 usbi_info (ITRANSFER_CTX (itransfer), "an async io operation has completed");
1409 /* send a completion message to the device's file descriptor */
1410 message = MESSAGE_ASYNC_IO_COMPLETE;
1411 write (priv->fds[1], &message, sizeof (message));
1412 write (priv->fds[1], &itransfer, sizeof (itransfer));
1413 write (priv->fds[1], &result, sizeof (IOReturn));
1414 write (priv->fds[1], &arg0, sizeof (UInt32));
1417 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1418 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT)
1419 result = kIOUSBTransactionTimeout;
1422 case kIOReturnUnderrun:
1423 case kIOReturnSuccess:
1424 return LIBUSB_TRANSFER_COMPLETED;
1425 case kIOReturnAborted:
1426 return LIBUSB_TRANSFER_CANCELLED;
1427 case kIOUSBPipeStalled:
1428 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: pipe is stalled");
1429 return LIBUSB_TRANSFER_STALL;
1430 case kIOReturnOverrun:
1431 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1432 return LIBUSB_TRANSFER_OVERFLOW;
1433 case kIOUSBTransactionTimeout:
1434 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1435 itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
1436 return LIBUSB_TRANSFER_TIMED_OUT;
1438 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1439 return LIBUSB_TRANSFER_ERROR;
1443 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1444 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1445 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1446 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1447 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1448 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1449 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1452 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1453 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1457 usbi_info (ITRANSFER_CTX (itransfer), "handling %s completion with kernel status %d",
1458 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
1460 if (kIOReturnSuccess == result || kIOReturnUnderrun == result) {
1461 if (isIsoc && tpriv->isoc_framelist) {
1462 /* copy isochronous results back */
1464 for (i = 0; i < transfer->num_iso_packets ; i++) {
1465 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1466 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1467 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1470 itransfer->transferred += io_size;
1473 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1474 usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
1477 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready) {
1478 struct usbi_transfer *itransfer;
1484 usbi_mutex_lock(&ctx->open_devs_lock);
1485 for (i = 0; i < nfds && num_ready > 0; i++) {
1486 struct pollfd *pollfd = &fds[i];
1487 struct libusb_device_handle *handle;
1488 struct darwin_device_handle_priv *hpriv = NULL;
1490 usbi_info (ctx, "checking fd %i with revents = %x", fds[i], pollfd->revents);
1492 if (!pollfd->revents)
1496 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
1497 hpriv = (struct darwin_device_handle_priv *)handle->os_priv;
1498 if (hpriv->fds[0] == pollfd->fd)
1502 if (!(pollfd->revents & POLLERR)) {
1503 ret = read (hpriv->fds[0], &message, sizeof (message));
1504 if (ret < sizeof (message))
1507 /* could not poll the device-- response is to delete the device (this seems a little heavy-handed) */
1508 message = MESSAGE_DEVICE_GONE;
1511 case MESSAGE_DEVICE_GONE:
1512 /* remove the device's async port from the runloop */
1513 if (hpriv->cfSource) {
1514 if (libusb_darwin_acfl)
1515 CFRunLoopRemoveSource (libusb_darwin_acfl, hpriv->cfSource, kCFRunLoopDefaultMode);
1516 CFRelease (hpriv->cfSource);
1517 hpriv->cfSource = NULL;
1520 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1521 usbi_handle_disconnect(handle);
1523 /* done with this device */
1525 case MESSAGE_ASYNC_IO_COMPLETE:
1526 read (hpriv->fds[0], &itransfer, sizeof (itransfer));
1527 read (hpriv->fds[0], &kresult, sizeof (IOReturn));
1528 read (hpriv->fds[0], &io_size, sizeof (UInt32));
1530 darwin_handle_callback (itransfer, kresult, io_size);
1533 usbi_err (ctx, "unknown message received from device pipe");
1537 usbi_mutex_unlock(&ctx->open_devs_lock);
1542 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1543 mach_timespec_t sys_time;
1544 clock_serv_t clock_ref;
1547 case USBI_CLOCK_REALTIME:
1548 /* CLOCK_REALTIME represents time since the epoch */
1549 host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &clock_ref);
1551 case USBI_CLOCK_MONOTONIC:
1552 /* use system boot time as reference for the monotonic clock */
1553 host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &clock_ref);
1556 return LIBUSB_ERROR_INVALID_PARAM;
1559 clock_get_time (clock_ref, &sys_time);
1561 tp->tv_sec = sys_time.tv_sec;
1562 tp->tv_nsec = sys_time.tv_nsec;
1567 const struct usbi_os_backend darwin_backend = {
1569 .init = darwin_init,
1570 .exit = darwin_exit,
1571 .get_device_list = darwin_get_device_list,
1572 .get_device_descriptor = darwin_get_device_descriptor,
1573 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1574 .get_config_descriptor = darwin_get_config_descriptor,
1576 .open = darwin_open,
1577 .close = darwin_close,
1578 .get_configuration = darwin_get_configuration,
1579 .set_configuration = darwin_set_configuration,
1580 .claim_interface = darwin_claim_interface,
1581 .release_interface = darwin_release_interface,
1583 .set_interface_altsetting = darwin_set_interface_altsetting,
1584 .clear_halt = darwin_clear_halt,
1585 .reset_device = darwin_reset_device,
1587 .kernel_driver_active = darwin_kernel_driver_active,
1588 .detach_kernel_driver = darwin_detach_kernel_driver,
1589 .attach_kernel_driver = darwin_attach_kernel_driver,
1591 .destroy_device = darwin_destroy_device,
1593 .submit_transfer = darwin_submit_transfer,
1594 .cancel_transfer = darwin_cancel_transfer,
1595 .clear_transfer_priv = darwin_clear_transfer_priv,
1597 .handle_events = op_handle_events,
1599 .clock_gettime = darwin_clock_gettime,
1601 .device_priv_size = sizeof(struct darwin_device_priv),
1602 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1603 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1604 .add_iso_packet_size = 0,