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));
304 pthread_exit ((void *)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)) {
356 /* stop the async runloop */
357 CFRunLoopStop (libusb_darwin_acfl);
358 pthread_join (libusb_darwin_at, &ret);
360 if (libusb_darwin_mp)
361 mach_port_deallocate(mach_task_self(), libusb_darwin_mp);
363 libusb_darwin_mp = 0;
367 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
368 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
370 /* return cached copy */
371 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
378 static int get_configuration_index (struct libusb_device *dev, int config_value) {
379 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
381 IOUSBConfigurationDescriptorPtr desc;
384 /* is there a simpler way to determine the index? */
385 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
386 if (kresult != kIOReturnSuccess)
387 return darwin_to_libusb (kresult);
389 for (i = 0 ; i < numConfig ; i++) {
390 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
392 if (desc->bConfigurationValue == config_value)
396 /* configuration not found */
397 return LIBUSB_ERROR_OTHER;
400 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
401 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
404 if (0 == priv->active_config)
405 return LIBUSB_ERROR_INVALID_PARAM;
407 config_index = get_configuration_index (dev, priv->active_config);
408 if (config_index < 0)
411 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
414 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
415 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
416 IOUSBConfigurationDescriptorPtr desc;
418 usb_device_t **device = NULL;
421 return LIBUSB_ERROR_OTHER;
424 kresult = darwin_get_device (priv->location, &device);
425 if (kresult || !device) {
426 usbi_err (DEVICE_CTX (dev), "could not find device: %s", darwin_error_str (kresult));
428 return darwin_to_libusb (kresult);
431 /* don't have to open the device to get a config descriptor */
433 device = priv->device;
435 kresult = (*device)->GetConfigurationDescriptorPtr (device, config_index, &desc);
436 if (kresult == kIOReturnSuccess) {
437 /* copy descriptor */
438 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
439 len = libusb_le16_to_cpu(desc->wTotalLength);
441 memmove (buffer, desc, len);
443 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
448 (*device)->Release (device);
450 return darwin_to_libusb (kresult);
453 /* check whether the os has configured the device */
454 static int darwin_check_configuration (struct libusb_context *ctx, struct libusb_device *dev, usb_device_t **darwin_device) {
455 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
457 IOUSBConfigurationDescriptorPtr configDesc;
458 IOUSBFindInterfaceRequest request;
459 kern_return_t kresult;
460 io_iterator_t interface_iterator;
461 io_service_t firstInterface;
463 if (priv->dev_descriptor.bNumConfigurations < 1) {
464 usbi_err (ctx, "device has no configurations");
465 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
468 /* find the first configuration */
469 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
470 priv->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
472 /* check if the device is already configured. there is probably a better way than iterating over the
473 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
474 might lock up on the device request) */
476 /* Setup the Interface Request */
477 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
478 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
479 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
480 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
482 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
484 return darwin_to_libusb (kresult);
487 firstInterface = IOIteratorNext(interface_iterator);
489 /* done with the interface iterator */
490 IOObjectRelease(interface_iterator);
492 if (firstInterface) {
493 IOObjectRelease (firstInterface);
495 /* device is configured */
496 if (priv->dev_descriptor.bNumConfigurations == 1)
497 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
498 priv->active_config = priv->first_config;
500 /* devices with more than one configuration should work with GetConfiguration */
501 (*darwin_device)->GetConfiguration (darwin_device, &priv->active_config);
504 priv->active_config = 0;
506 usbi_info (ctx, "active config: %u, first config: %u", priv->active_config, priv->first_config);
511 static int process_new_device (struct libusb_context *ctx, usb_device_t **device, UInt32 locationID, struct discovered_devs **_discdevs) {
512 struct darwin_device_priv *priv;
513 struct libusb_device *dev;
514 struct discovered_devs *discdevs;
515 UInt16 address, idVendor, idProduct;
516 UInt8 bDeviceClass, bDeviceSubClass;
518 int ret = 0, need_unref = 0;
521 dev = usbi_get_device_by_session_id(ctx, locationID);
523 usbi_info (ctx, "allocating new device for location 0x%08x", locationID);
524 dev = usbi_alloc_device(ctx, locationID);
527 usbi_info (ctx, "using existing device for location 0x%08x", locationID);
530 ret = LIBUSB_ERROR_NO_MEM;
534 priv = (struct darwin_device_priv *)dev->os_priv;
536 /* Set up request for device descriptor */
537 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
538 req.bRequest = kUSBRqGetDescriptor;
539 req.wValue = kUSBDeviceDesc << 8;
541 req.wLength = sizeof(IOUSBDeviceDescriptor);
542 req.pData = &(priv->dev_descriptor);
544 (*(device))->GetDeviceAddress (device, (USBDeviceAddress *)&address);
545 (*(device))->GetDeviceProduct (device, &idProduct);
546 (*(device))->GetDeviceVendor (device, &idVendor);
547 (*(device))->GetDeviceClass (device, &bDeviceClass);
548 (*(device))->GetDeviceSubClass (device, &bDeviceSubClass);
550 /**** retrieve device descriptors ****/
551 /* according to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
552 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request */
553 ret = (*(device))->DeviceRequest (device, &req);
554 if (ret != kIOReturnSuccess) {
555 int try_unsuspend = 1;
556 #if DeviceVersion >= 320
559 /* device may be suspended. unsuspend it and try again */
560 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
561 (void)(*device)->GetUSBDeviceInformation (device, &info);
563 try_unsuspend = info & (1 << kUSBInformationDeviceIsSuspendedBit);
566 /* the device should be open before to device is unsuspended */
567 (void) (*device)->USBDeviceOpenSeize(device);
570 /* resume the device */
571 (void)(*device)->USBDeviceSuspend (device, 0);
573 ret = (*(device))->DeviceRequest (device, &req);
575 /* resuspend the device */
576 (void)(*device)->USBDeviceSuspend (device, 1);
579 (*device)->USBDeviceClose (device);
582 if (ret != kIOReturnSuccess) {
583 usbi_warn (ctx, "could not retrieve device descriptor: %s. skipping device", darwin_error_str (ret));
588 /**** end: retrieve device descriptors ****/
590 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
591 if (libusb_le16_to_cpu (priv->dev_descriptor.idProduct) != idProduct) {
592 /* not a valid device */
593 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
594 idProduct, libusb_le16_to_cpu (priv->dev_descriptor.idProduct));
599 dev->bus_number = locationID >> 24;
600 dev->device_address = address;
602 /* check current active configuration (and cache the first configuration value-- which may be used by claim_interface) */
603 ret = darwin_check_configuration (ctx, dev, device);
607 /* save our location, we'll need this later */
608 priv->location = locationID;
609 snprintf(priv->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", address, idVendor, idProduct, bDeviceClass, bDeviceSubClass);
611 ret = usbi_sanitize_device (dev);
615 /* append the device to the list of discovered devices */
616 discdevs = discovered_devs_append(*_discdevs, dev);
618 ret = LIBUSB_ERROR_NO_MEM;
622 *_discdevs = discdevs;
624 usbi_info (ctx, "found device with address %d at %s", dev->device_address, priv->sys_path);
628 libusb_unref_device(dev);
633 static int darwin_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs) {
634 io_iterator_t deviceIterator;
635 usb_device_t **device;
636 kern_return_t kresult;
639 if (!libusb_darwin_mp)
640 return LIBUSB_ERROR_INVALID_PARAM;
642 kresult = usb_setup_device_iterator (&deviceIterator);
643 if (kresult != kIOReturnSuccess)
644 return darwin_to_libusb (kresult);
646 while ((device = usb_get_next_device (deviceIterator, &location)) != NULL) {
647 (void) process_new_device (ctx, device, location, _discdevs);
649 (*(device))->Release(device);
652 IOObjectRelease(deviceIterator);
657 static int darwin_open (struct libusb_device_handle *dev_handle) {
658 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
659 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
660 usb_device_t **darwin_device;
663 if (0 == dpriv->open_count) {
664 kresult = darwin_get_device (dpriv->location, &darwin_device);
666 usbi_err (HANDLE_CTX (dev_handle), "could not find device: %s", darwin_error_str (kresult));
667 return darwin_to_libusb (kresult);
670 dpriv->device = darwin_device;
672 /* try to open the device */
673 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
675 if (kresult != kIOReturnSuccess) {
676 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
679 case kIOReturnExclusiveAccess:
680 /* it is possible to perform some actions on a device that is not open so do not return an error */
685 (*(dpriv->device))->Release (dpriv->device);
686 dpriv->device = NULL;
687 return darwin_to_libusb (kresult);
690 /* create async event source */
691 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
692 if (kresult != kIOReturnSuccess) {
693 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
695 (*(dpriv->device))->USBDeviceClose (dpriv->device);
696 (*(dpriv->device))->Release (dpriv->device);
698 dpriv->device = NULL;
699 return darwin_to_libusb (kresult);
704 CFRetain (libusb_darwin_acfl);
706 /* add the cfSource to the aync run loop */
707 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
711 /* device opened successfully */
714 /* create a file descriptor for notifications */
717 /* set the pipe to be non-blocking */
718 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
720 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
722 usbi_info (HANDLE_CTX (dev_handle), "device open for access");
727 static void darwin_close (struct libusb_device_handle *dev_handle) {
728 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
729 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
733 if (dpriv->open_count == 0) {
734 /* something is probably very wrong if this is the case */
735 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
741 /* make sure all interfaces are released */
742 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
743 if (dev_handle->claimed_interfaces & (1 << i))
744 libusb_release_interface (dev_handle, i);
746 if (0 == dpriv->open_count) {
748 /* delete the device's async event source */
749 if (priv->cfSource) {
750 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
751 CFRelease (priv->cfSource);
754 /* close the device */
755 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
757 /* Log the fact that we had a problem closing the file, however failing a
758 * close isn't really an error, so return success anyway */
759 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
763 kresult = (*(dpriv->device))->Release(dpriv->device);
765 /* Log the fact that we had a problem closing the file, however failing a
766 * close isn't really an error, so return success anyway */
767 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
770 dpriv->device = NULL;
773 /* file descriptors are maintained per-instance */
774 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
775 close (priv->fds[1]);
776 close (priv->fds[0]);
778 priv->fds[0] = priv->fds[1] = -1;
781 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
782 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
784 *config = (int) dpriv->active_config;
789 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
790 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
794 /* Setting configuration will invalidate the interface, so we need
795 to reclaim it. First, dispose of existing interfaces, if any. */
796 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
797 if (dev_handle->claimed_interfaces & (1 << i))
798 darwin_release_interface (dev_handle, i);
800 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
801 if (kresult != kIOReturnSuccess)
802 return darwin_to_libusb (kresult);
804 /* Reclaim any interfaces. */
805 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
806 if (dev_handle->claimed_interfaces & (1 << i))
807 darwin_claim_interface (dev_handle, i);
809 dpriv->active_config = config;
814 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
815 IOUSBFindInterfaceRequest request;
816 uint8_t current_interface;
817 kern_return_t kresult;
818 io_iterator_t interface_iterator;
820 *usbInterfacep = IO_OBJECT_NULL;
822 /* Setup the Interface Request */
823 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
824 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
825 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
826 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
828 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
832 for ( current_interface = 0 ; current_interface <= ifc ; current_interface++ ) {
833 *usbInterfacep = IOIteratorNext(interface_iterator);
834 if (current_interface != ifc)
835 (void) IOObjectRelease (*usbInterfacep);
838 /* done with the interface iterator */
839 IOObjectRelease(interface_iterator);
844 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
845 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
847 /* current interface */
848 struct __darwin_interface *cInterface = &priv->interfaces[iface];
850 kern_return_t kresult;
852 u_int8_t numep, direction, number;
853 u_int8_t dont_care1, dont_care3;
854 u_int16_t dont_care2;
857 usbi_info (HANDLE_CTX (dev_handle), "building table of endpoints.");
859 /* retrieve the total number of endpoints on this interface */
860 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
862 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
863 return darwin_to_libusb (kresult);
866 /* iterate through pipe references */
867 for (i = 1 ; i <= numep ; i++) {
868 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
869 &dont_care2, &dont_care3);
871 if (kresult != kIOReturnSuccess) {
872 usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
874 return darwin_to_libusb (kresult);
877 usbi_info (HANDLE_CTX (dev_handle), "interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
879 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
882 cInterface->num_endpoints = numep;
887 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
888 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
889 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
890 io_service_t usbInterface = IO_OBJECT_NULL;
892 IOCFPlugInInterface **plugInInterface = NULL;
895 /* current interface */
896 struct __darwin_interface *cInterface = &priv->interfaces[iface];
898 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
899 if (kresult != kIOReturnSuccess)
900 return darwin_to_libusb (kresult);
902 /* make sure we have an interface */
903 if (!usbInterface && dpriv->first_config != 0) {
904 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
906 /* set the configuration */
907 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
908 if (kresult != LIBUSB_SUCCESS) {
909 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
913 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
915 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
916 return darwin_to_libusb (kresult);
921 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
922 return LIBUSB_ERROR_NOT_FOUND;
925 /* get an interface to the device's interface */
926 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
927 kIOCFPlugInInterfaceID, &plugInInterface, &score);
929 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
930 return darwin_to_libusb (kresult);
933 if (!plugInInterface) {
934 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
935 return LIBUSB_ERROR_NOT_FOUND;
938 /* ignore release error */
939 (void)IOObjectRelease (usbInterface);
941 /* Do the actual claim */
942 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
943 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
944 (LPVOID)&cInterface->interface);
945 if (kresult || !cInterface->interface) {
946 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
947 return darwin_to_libusb (kresult);
950 /* We no longer need the intermediate plug-in */
951 (*plugInInterface)->Release(plugInInterface);
953 /* claim the interface */
954 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
956 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
957 return darwin_to_libusb (kresult);
960 /* update list of endpoints */
961 kresult = get_endpoints (dev_handle, iface);
963 /* this should not happen */
964 darwin_release_interface (dev_handle, iface);
965 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
969 cInterface->cfSource = NULL;
971 /* create async event source */
972 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
973 if (kresult != kIOReturnSuccess) {
974 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
976 /* can't continue without an async event source */
977 (void)darwin_release_interface (dev_handle, iface);
979 return darwin_to_libusb (kresult);
982 /* add the cfSource to the async thread's run loop */
983 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
985 usbi_info (HANDLE_CTX (dev_handle), "interface opened");
990 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
991 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
994 /* current interface */
995 struct __darwin_interface *cInterface = &priv->interfaces[iface];
997 /* Check to see if an interface is open */
998 if (!cInterface->interface)
999 return LIBUSB_SUCCESS;
1001 /* clean up endpoint data */
1002 cInterface->num_endpoints = 0;
1004 /* delete the interface's async event source */
1005 if (cInterface->cfSource) {
1006 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1007 CFRelease (cInterface->cfSource);
1010 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1012 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1014 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1015 if (kresult != kIOReturnSuccess)
1016 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1018 cInterface->interface = IO_OBJECT_NULL;
1020 return darwin_to_libusb (kresult);
1023 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1024 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1027 /* current interface */
1028 struct __darwin_interface *cInterface = &priv->interfaces[iface];
1030 if (!cInterface->interface)
1031 return LIBUSB_ERROR_NO_DEVICE;
1033 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1034 if (kresult != kIOReturnSuccess)
1035 darwin_reset_device (dev_handle);
1037 /* update list of endpoints */
1038 kresult = get_endpoints (dev_handle, iface);
1040 /* this should not happen */
1041 darwin_release_interface (dev_handle, iface);
1042 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1046 return darwin_to_libusb (kresult);
1049 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1050 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1052 /* current interface */
1053 struct __darwin_interface *cInterface;
1054 uint8_t pipeRef, iface;
1057 /* determine the interface/endpoint to use */
1058 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
1059 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1061 return LIBUSB_ERROR_NOT_FOUND;
1064 cInterface = &priv->interfaces[iface];
1066 #if (InterfaceVersion < 190)
1067 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1069 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1070 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1073 usbi_err (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1075 return darwin_to_libusb (kresult);
1078 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1079 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1082 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1084 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1086 return darwin_to_libusb (kresult);
1089 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1090 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1091 io_service_t usbInterface;
1095 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1097 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1099 return darwin_to_libusb (kresult);
1102 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1103 IOObjectRelease (usbInterface);
1115 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1116 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1117 return LIBUSB_ERROR_NOT_SUPPORTED;
1120 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1121 return LIBUSB_ERROR_NOT_SUPPORTED;
1124 static void darwin_destroy_device(struct libusb_device *dev) {
1127 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1128 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1129 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1132 uint8_t is_read; /* 0 = we're reading, 1 = we're writing */
1133 uint8_t transferType;
1134 /* None of the values below are used in libusb for bulk transfers */
1135 uint8_t direction, number, interval, pipeRef, iface;
1136 uint16_t maxPacketSize;
1138 struct __darwin_interface *cInterface;
1140 /* are we reading or writing? */
1141 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1143 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1144 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1146 return LIBUSB_ERROR_NOT_FOUND;
1149 cInterface = &priv->interfaces[iface];
1151 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1152 &transferType, &maxPacketSize, &interval);
1154 /* submit the request */
1155 /* timeouts are unavailable on interrupt endpoints */
1156 if (transferType == kUSBInterrupt) {
1158 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1159 transfer->length, darwin_async_io_callback, itransfer);
1161 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1162 transfer->length, darwin_async_io_callback, itransfer);
1164 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1167 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1168 transfer->length, transfer->timeout, transfer->timeout,
1169 darwin_async_io_callback, (void *)itransfer);
1171 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1172 transfer->length, transfer->timeout, transfer->timeout,
1173 darwin_async_io_callback, (void *)itransfer);
1177 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", is_read ? "In" : "Out",
1178 darwin_error_str(ret), ret);
1180 return darwin_to_libusb (ret);
1183 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1184 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1185 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1186 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1189 uint8_t is_read; /* 0 = we're writing, 1 = we're reading */
1190 uint8_t pipeRef, iface;
1192 AbsoluteTime atTime;
1195 struct __darwin_interface *cInterface;
1197 /* are we reading or writing? */
1198 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1200 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1201 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1202 free(tpriv->isoc_framelist);
1203 tpriv->isoc_framelist = NULL;
1206 if (!tpriv->isoc_framelist) {
1207 tpriv->num_iso_packets = transfer->num_iso_packets;
1208 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1209 if (!tpriv->isoc_framelist)
1210 return LIBUSB_ERROR_NO_MEM;
1213 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1214 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1215 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1217 /* determine the interface/endpoint to use */
1218 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1219 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1221 return LIBUSB_ERROR_NOT_FOUND;
1224 cInterface = &priv->interfaces[iface];
1226 /* Last but not least we need the bus frame number */
1227 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1229 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1230 free(tpriv->isoc_framelist);
1231 tpriv->isoc_framelist = NULL;
1233 return darwin_to_libusb (kresult);
1236 /* schedule for a frame a little in the future */
1239 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1240 frame = cInterface->frames[transfer->endpoint];
1242 /* submit the request */
1244 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1245 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1248 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1249 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1252 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets / 8;
1254 if (kresult != kIOReturnSuccess) {
1255 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", is_read ? "In" : "Out",
1256 darwin_error_str(kresult));
1257 free (tpriv->isoc_framelist);
1258 tpriv->isoc_framelist = NULL;
1261 return darwin_to_libusb (kresult);
1264 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1265 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1266 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1267 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1268 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1269 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1273 bzero(&tpriv->req, sizeof(tpriv->req));
1275 /* IOUSBDeviceInterface expects the request in cpu endianess */
1276 tpriv->req.bmRequestType = setup->bmRequestType;
1277 tpriv->req.bRequest = setup->bRequest;
1278 /* these values should be in bus order from libusb_fill_control_setup */
1279 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1280 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1281 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1282 /* data is stored after the libusb control block */
1283 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1284 tpriv->req.completionTimeout = transfer->timeout;
1285 tpriv->req.noDataTimeout = transfer->timeout;
1287 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1289 /* all transfers in libusb-1.0 are async */
1291 if (transfer->endpoint) {
1292 struct __darwin_interface *cInterface;
1293 uint8_t pipeRef, iface;
1295 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1296 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1298 return LIBUSB_ERROR_NOT_FOUND;
1301 cInterface = &priv->interfaces[iface];
1303 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1305 /* control request on endpoint 0 */
1306 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1308 if (kresult != kIOReturnSuccess)
1309 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1311 return darwin_to_libusb (kresult);
1314 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1315 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1317 switch (transfer->type) {
1318 case LIBUSB_TRANSFER_TYPE_CONTROL:
1319 return submit_control_transfer(itransfer);
1320 case LIBUSB_TRANSFER_TYPE_BULK:
1321 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1322 return submit_bulk_transfer(itransfer);
1323 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1324 return submit_iso_transfer(itransfer);
1326 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1327 return LIBUSB_ERROR_INVALID_PARAM;
1331 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1332 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1333 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1336 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions control pipe");
1338 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1340 return darwin_to_libusb (kresult);
1343 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1344 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1345 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1346 struct __darwin_interface *cInterface;
1347 uint8_t pipeRef, iface;
1350 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1351 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1353 return LIBUSB_ERROR_NOT_FOUND;
1356 cInterface = &priv->interfaces[iface];
1358 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions on interface %d pipe %d", iface, pipeRef);
1360 /* abort transactions */
1361 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1363 usbi_info (ITRANSFER_CTX (itransfer), "calling clear pipe stall to clear the data toggle bit");
1365 /* clear the data toggle bit */
1366 #if (InterfaceVersion < 190)
1367 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1369 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1370 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1373 return darwin_to_libusb (kresult);
1376 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1377 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1379 switch (transfer->type) {
1380 case LIBUSB_TRANSFER_TYPE_CONTROL:
1381 return cancel_control_transfer(itransfer);
1382 case LIBUSB_TRANSFER_TYPE_BULK:
1383 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1384 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1385 return darwin_abort_transfers (itransfer);
1387 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1388 return LIBUSB_ERROR_INVALID_PARAM;
1392 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1393 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1394 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1396 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1397 free (tpriv->isoc_framelist);
1398 tpriv->isoc_framelist = NULL;
1402 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1403 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1404 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1405 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1408 usbi_info (ITRANSFER_CTX (itransfer), "an async io operation has completed");
1410 /* send a completion message to the device's file descriptor */
1411 message = MESSAGE_ASYNC_IO_COMPLETE;
1412 write (priv->fds[1], &message, sizeof (message));
1413 write (priv->fds[1], &itransfer, sizeof (itransfer));
1414 write (priv->fds[1], &result, sizeof (IOReturn));
1415 write (priv->fds[1], &arg0, sizeof (UInt32));
1418 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1419 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT)
1420 result = kIOUSBTransactionTimeout;
1423 case kIOReturnUnderrun:
1424 case kIOReturnSuccess:
1425 return LIBUSB_TRANSFER_COMPLETED;
1426 case kIOReturnAborted:
1427 return LIBUSB_TRANSFER_CANCELLED;
1428 case kIOUSBPipeStalled:
1429 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: pipe is stalled");
1430 return LIBUSB_TRANSFER_STALL;
1431 case kIOReturnOverrun:
1432 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1433 return LIBUSB_TRANSFER_OVERFLOW;
1434 case kIOUSBTransactionTimeout:
1435 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1436 itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
1437 return LIBUSB_TRANSFER_TIMED_OUT;
1439 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1440 return LIBUSB_TRANSFER_ERROR;
1444 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1445 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1446 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1447 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1448 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1449 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1450 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1453 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1454 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1458 usbi_info (ITRANSFER_CTX (itransfer), "handling %s completion with kernel status %d",
1459 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
1461 if (kIOReturnSuccess == result || kIOReturnUnderrun == result) {
1462 if (isIsoc && tpriv->isoc_framelist) {
1463 /* copy isochronous results back */
1465 for (i = 0; i < transfer->num_iso_packets ; i++) {
1466 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1467 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1468 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1471 itransfer->transferred += io_size;
1474 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1475 usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
1478 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready) {
1479 struct usbi_transfer *itransfer;
1485 usbi_mutex_lock(&ctx->open_devs_lock);
1486 for (i = 0; i < nfds && num_ready > 0; i++) {
1487 struct pollfd *pollfd = &fds[i];
1488 struct libusb_device_handle *handle;
1489 struct darwin_device_handle_priv *hpriv = NULL;
1491 usbi_info (ctx, "checking fd %i with revents = %x", fds[i], pollfd->revents);
1493 if (!pollfd->revents)
1497 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
1498 hpriv = (struct darwin_device_handle_priv *)handle->os_priv;
1499 if (hpriv->fds[0] == pollfd->fd)
1503 if (!(pollfd->revents & POLLERR)) {
1504 ret = read (hpriv->fds[0], &message, sizeof (message));
1505 if (ret < sizeof (message))
1508 /* could not poll the device-- response is to delete the device (this seems a little heavy-handed) */
1509 message = MESSAGE_DEVICE_GONE;
1512 case MESSAGE_DEVICE_GONE:
1513 /* remove the device's async port from the runloop */
1514 if (hpriv->cfSource) {
1515 if (libusb_darwin_acfl)
1516 CFRunLoopRemoveSource (libusb_darwin_acfl, hpriv->cfSource, kCFRunLoopDefaultMode);
1517 CFRelease (hpriv->cfSource);
1518 hpriv->cfSource = NULL;
1521 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1522 usbi_handle_disconnect(handle);
1524 /* done with this device */
1526 case MESSAGE_ASYNC_IO_COMPLETE:
1527 read (hpriv->fds[0], &itransfer, sizeof (itransfer));
1528 read (hpriv->fds[0], &kresult, sizeof (IOReturn));
1529 read (hpriv->fds[0], &io_size, sizeof (UInt32));
1531 darwin_handle_callback (itransfer, kresult, io_size);
1534 usbi_err (ctx, "unknown message received from device pipe");
1538 usbi_mutex_unlock(&ctx->open_devs_lock);
1543 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1544 mach_timespec_t sys_time;
1545 clock_serv_t clock_ref;
1548 case USBI_CLOCK_REALTIME:
1549 /* CLOCK_REALTIME represents time since the epoch */
1550 host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &clock_ref);
1552 case USBI_CLOCK_MONOTONIC:
1553 /* use system boot time as reference for the monotonic clock */
1554 host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &clock_ref);
1557 return LIBUSB_ERROR_INVALID_PARAM;
1560 clock_get_time (clock_ref, &sys_time);
1562 tp->tv_sec = sys_time.tv_sec;
1563 tp->tv_nsec = sys_time.tv_nsec;
1568 const struct usbi_os_backend darwin_backend = {
1570 .init = darwin_init,
1571 .exit = darwin_exit,
1572 .get_device_list = darwin_get_device_list,
1573 .get_device_descriptor = darwin_get_device_descriptor,
1574 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1575 .get_config_descriptor = darwin_get_config_descriptor,
1577 .open = darwin_open,
1578 .close = darwin_close,
1579 .get_configuration = darwin_get_configuration,
1580 .set_configuration = darwin_set_configuration,
1581 .claim_interface = darwin_claim_interface,
1582 .release_interface = darwin_release_interface,
1584 .set_interface_altsetting = darwin_set_interface_altsetting,
1585 .clear_halt = darwin_clear_halt,
1586 .reset_device = darwin_reset_device,
1588 .kernel_driver_active = darwin_kernel_driver_active,
1589 .detach_kernel_driver = darwin_detach_kernel_driver,
1590 .attach_kernel_driver = darwin_attach_kernel_driver,
1592 .destroy_device = darwin_destroy_device,
1594 .submit_transfer = darwin_submit_transfer,
1595 .cancel_transfer = darwin_cancel_transfer,
1596 .clear_transfer_priv = darwin_clear_transfer_priv,
1598 .handle_events = op_handle_events,
1600 .clock_gettime = darwin_clock_gettime,
1602 .device_priv_size = sizeof(struct darwin_device_priv),
1603 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1604 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1605 .add_iso_packet_size = 0,